code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -0,0 +1,172 @@ +package store.domain; + +import static store.constants.NumberConstants.FREEBIE_QUANTITY; + +import java.util.List; +import store.dto.BuyGetQuantity; +import store.dto.PromotionInfo; +import store.io.InputView; + +public class PromotionManager { + + private final List<PromotionInfo> promotionInfos; + private final StoreHouse storeHouse; + private final InputView inputView; + + public PromotionManager(List<PromotionInfo> promotionInfos, StoreHouse storeHouse, InputView inputView) { + this.promotionInfos = promotionInfos; + this.storeHouse = storeHouse; + this.inputView = inputView; + } + + public void setPromotionInfo() { + promotionInfos.forEach(promotionInfo -> { + Promotion.setQuantity( + promotionInfo.getPromotionName(), promotionInfo.getBuyQuantity(), promotionInfo.getGetQuantity() + ); + Promotion.setPromotionPeriods( + promotionInfo.getPromotionName(), promotionInfo.getStartDateTime(), promotionInfo.getEndDateTime() + ); + }); + } + + public Receipt applyPromotion(Product product, int purchaseQuantity) { + Receipt receipt = new Receipt(); + if (!isValidPromotionApplicable(product, purchaseQuantity)) { + processRegularPricePayment(product, purchaseQuantity); + return receipt; + } + return getReceiptWhenPromotionPayment(product, purchaseQuantity, receipt); + } + + public boolean isValidPromotionApplicable(Product product, int purchaseQuantity) { + return validPromotionPeriod(product.getPromotionName()) && + canApplyPromotion(product, purchaseQuantity) && + validPromotionProductStock(product); + } + + private boolean validPromotionPeriod(Promotion promotionName) { + return Promotion.isPromotionValid(promotionName); + } + + private boolean canApplyPromotion(Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return purchaseQuantity >= buyQuantity; + } + + private boolean validPromotionProductStock(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + return buyQuantity <= product.getQuantity(); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity) { + + Product generalProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(generalProduct, purchaseQuantity); + } + + private Product findProductByPromotionName(Product product, Promotion promotionName) { + List<Product> products = storeHouse.findProductByName(product.getName()); + + return products.stream() + .filter(prdt -> !prdt.getPromotionName().equals(promotionName)) + .findFirst() + .orElse(null); + } + + private Receipt getReceiptWhenPromotionPayment(Product product, int purchaseQuantity, Receipt receipt) { + if (processFullPromotionPayment(receipt, product, purchaseQuantity)) { + return receipt; + } + processPartialPromotionPayment(receipt, product, purchaseQuantity); + return receipt; + } + + private boolean processFullPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + + if (purchaseQuantity <= product.getQuantity()) { + return canAddOneFreebie(receipt, product, purchaseQuantity); + } + return false; + } + + private boolean canAddOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int totalPurchaseQuantity = purchaseQuantity; + if (purchaseQuantity % (buyQuantity + getQuantity) == buyQuantity) { + totalPurchaseQuantity = addOneFreebie(receipt, product, purchaseQuantity); + } + receipt.addFreebieProduct(product, totalPurchaseQuantity / (buyQuantity + getQuantity)); + return true; + } + + private int addOneFreebie(Receipt receipt, Product product, int purchaseQuantity) { + Choice freebieAdditionChoice = inputView.readFreebieAdditionChoice(product.getName()); + int totalPurchaseQuantity = purchaseQuantity; + if (freebieAdditionChoice.equals(Choice.Y)) { + totalPurchaseQuantity += FREEBIE_QUANTITY; + addFreebieFromRegularProduct(receipt, product, purchaseQuantity); + } + storeHouse.buy(product, totalPurchaseQuantity); + return totalPurchaseQuantity; + } + + private void addFreebieFromRegularProduct(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + int remainder = purchaseQuantity % (buyQuantity + getQuantity); + if (purchaseQuantity == (product.getQuantity() - remainder)) { + processRegularPricePayment(product, FREEBIE_QUANTITY); + receipt.addFreebieProduct(product, FREEBIE_QUANTITY); + } + } + + private void processPartialPromotionPayment(Receipt receipt, Product product, int purchaseQuantity) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int buyQuantity = buyAndGetQuantity.getBuyQuantity(); + int getQuantity = buyAndGetQuantity.getGetQuantity(); + + int promotionAppliedQuantity = getPromotionAppliedQuantity(product); + processRegularPricePayment(product, purchaseQuantity, promotionAppliedQuantity); + storeHouse.buy(product, promotionAppliedQuantity); + receipt.addFreebieProduct(product, promotionAppliedQuantity / (buyQuantity + getQuantity)); + } + + private int getPromotionAppliedQuantity(Product product) { + BuyGetQuantity buyAndGetQuantity = getBuyAndGetQuantity(product.getPromotionName()); + int bundle = buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity(); + int promotionStock = product.getQuantity(); + int count = promotionStock / bundle; + + return count * (buyAndGetQuantity.getBuyQuantity() + buyAndGetQuantity.getGetQuantity()); + } + + private void processRegularPricePayment(Product product, int purchaseQuantity, int promotionAppliedQuantity) { + int regularPricePaymentQuantity = purchaseQuantity - promotionAppliedQuantity; + Choice regularPricePaymentChoice = getRegularPriceApplicationChoice(product, + regularPricePaymentQuantity); + if (regularPricePaymentChoice.equals( + Choice.Y)) { + Product regularProduct = findProductByPromotionName(product, Promotion.NULL); + storeHouse.buy(regularProduct, regularPricePaymentQuantity); + } + } + + private Choice getRegularPriceApplicationChoice(Product product, int purchaseQuantity) { + return inputView.readRegularPricePaymentChoice(product.getName(), purchaseQuantity); + } + + + public static BuyGetQuantity getBuyAndGetQuantity(Promotion promotionName) { + return BuyGetQuantity.of(promotionName.getBuyQuantity(), promotionName.getGetQuantity()); + } + + public List<PromotionInfo> getPromotionInfos() { + return promotionInfos; + } +}
Java
๋„ต ํ”ผ๋“œ๋ฐฑ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค :) ์ผ๋‹จ ๋Œ์•„๊ฐ€๊ฒŒ ๋งŒ๋“œ๋Š” ๊ฒŒ ๋ชฉ์ ์ด์—ˆ๊ธฐ์— ์ด๋Ÿฐ ๊ตฌ์กฐ๊ฐ€ ๋‚˜์™€๋ฒ„๋ ธ๋„ค์š”,, ใ…Žใ…Ž ์ž…๋ ฅ ๋ฐ›๋Š” ๋ถ€๋ถ„์€ ์ปจํŠธ๋กค๋Ÿฌ๋กœ ๋นผ์„œ ๋ฆฌํŒฉํ† ๋งํ•  ์˜ˆ์ •์ž…๋‹ˆ๋‹ค!
@@ -0,0 +1,48 @@ +package store.domain; + +import static store.constants.NumberConstants.SINGLE_PRODUCT_QUANTITY; + +import java.util.ArrayList; +import java.util.List; +import store.exception.ProductNotExistException; + +public class StoreHouse { + + private final List<Product> productList = new ArrayList<>(); + + + public void buy(Product product, int quantity) { + product.sell(quantity); + } + + public List<Product> findProductByName(String productName) { + List<Product> filteredProduct = productList.stream() + .filter(product -> product.getName().equals(productName)) + .toList(); + + if (filteredProduct.isEmpty()) { + throw new ProductNotExistException(); + } + + return filteredProduct; + } + + public boolean checkRegularPricePurchase(String productName) { + int count = (int) productList.stream() + .filter(product -> product.getName().equals(productName)) + .count(); + List<Product> products = findProductByName(productName); + Promotion promotionName = products.getFirst().getPromotionName(); + + return count == SINGLE_PRODUCT_QUANTITY && promotionName.equals(Promotion.NULL); + } + + public void addProduct(Product product) { + productList.add(product); + } + + public List<Product> getProductList() { + return productList; + } +} +
Java
์—‡ ๊ทธ ๋ฐฉ๋ฒ•๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์ง€๋งŒ, ๋™์ผํ•œ ์ด๋ฆ„์„ ๊ฐ€์ง„ ์ƒํ’ˆ์„ ๋ชจ๋‘ ๊ฐ€์ ธ์™€์„œ ๊ฐ ์ƒํ™ฉ์— ๋งž๊ฒŒ ์ฒ˜๋ฆฌํ•˜๋Š” ๋กœ์ง์—๋Š” List๊ฐ€ ๋” ์ ์ ˆํ•  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค! ๋‹ค์–‘ํ•œ ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ๊ณ ๋ฏผํ•ด ๋ณผ ์ˆ˜ ์žˆ๊ฒŒ ํ•ด์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค :)
@@ -0,0 +1,115 @@ +package store.io; + +import static store.constants.InputMessages.ADDITIONAL_PURCHASE_MESSAGE; +import static store.constants.InputMessages.FREEBIE_ADDITION_MESSAGE; +import static store.constants.InputMessages.INPUT_PRODUCT_NAME_AND_QUANTITY; +import static store.constants.InputMessages.MEMBERSHIP_DISCOUNT_CHOICE_MESSAGE; +import static store.constants.InputMessages.REGULAR_PRICE_BUY_MESSAGE; +import static store.constants.StringConstants.NEW_LINE; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import store.domain.Choice; +import store.domain.Product; +import store.domain.StoreHouse; +import store.dto.PromotionInfo; +import store.dto.Purchase; +import store.io.parser.InputParser; +import store.io.parser.ProductsFileLineParser; +import store.io.parser.PromotionsFileLineParser; +import store.io.reader.FileReader; +import store.io.reader.Reader; +import store.io.writer.Writer; + +public class InputView { + + private final Reader reader; + private final Writer writer; + private final InputValidator validator; + + public InputView(Reader reader, Writer writer, InputValidator validator) { + this.reader = reader; + this.writer = writer; + this.validator = validator; + } + + public StoreHouse readProductsFileInput(String fileName) { + try { + return readProductsFile(fileName); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private StoreHouse readProductsFile(String fileName) throws IOException { + Reader reader = new FileReader(fileName); + reader.readLine(); + String line; + StoreHouse storeHouse = new StoreHouse(); + while ((line = reader.readLine()) != null) { + Product product = new ProductsFileLineParser(line).parseLine(); + storeHouse.addProduct(product); + } + return storeHouse; + } + + public List<PromotionInfo> readPromotionsFileInput(String fileName) { + try { + return readPromotionsFile(fileName); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private List<PromotionInfo> readPromotionsFile(String fileName) throws IOException { + Reader reader = new FileReader(fileName); + reader.readLine(); + String line; + List<PromotionInfo> promotionInfos = new ArrayList<>(); + while ((line = reader.readLine()) != null) { + promotionInfos.add(new PromotionsFileLineParser(line).parseLine()); + } + return promotionInfos; + } + + public List<Purchase> readProductNameAndQuantity() { + writer.write(INPUT_PRODUCT_NAME_AND_QUANTITY); + String inputProductAndQuantity = reader.readLine(); + writer.write(NEW_LINE); + validator.validateEmptyInput(inputProductAndQuantity); + return new InputParser().parse(inputProductAndQuantity); + } + + public Choice readFreebieAdditionChoice(String productName) { + writer.write(String.format(FREEBIE_ADDITION_MESSAGE, productName)); + String input = reader.readLine(); + writer.write(NEW_LINE); + validator.validateEmptyInput(input); + return Choice.checkYesOrNo(input); + } + + public Choice readRegularPricePaymentChoice(String productName, int quantity) { + writer.write(String.format(REGULAR_PRICE_BUY_MESSAGE, productName, quantity)); + String input = reader.readLine(); + writer.write(NEW_LINE); + validator.validateEmptyInput(input); + return Choice.checkYesOrNo(input); + } + + public Choice readMembershipDiscountApplicationChoice() { + writer.write(MEMBERSHIP_DISCOUNT_CHOICE_MESSAGE); + String input = reader.readLine(); + writer.write(NEW_LINE); + validator.validateEmptyInput(input); + return Choice.checkYesOrNo(input); + } + + public Choice readAdditionalPurchaseChoice() { + writer.write(ADDITIONAL_PURCHASE_MESSAGE); + String input = reader.readLine(); + writer.write(NEW_LINE); + validator.validateEmptyInput(input); + return Choice.checkYesOrNo(input); + } +}
Java
๋‹ค์–‘ํ•œ ์˜๊ฒฌ ์ œ์‹œํ•ด ์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค!! ์ง€๊ธˆ ๋ณด๋‹ˆ ๊ทธ๋ ‡๋„ค์š”,, ํŒŒ์ผ์— ๋Œ€ํ•œ ์ฒ˜๋ฆฌ๋Š” ์—„์—ฐํžˆ ๋ทฐ์™€๋Š” ๋‹ค๋ฅธ ์ฑ…์ž„์ธ๋ฐ (๊ฐ’์„ ์ฝ์–ด๋“ค์ธ๋‹ค๋Š” ๋ถ€๋ถ„์— ๊ฝ‚ํ˜€) ์ด ๋ถ€๋ถ„์„ ๊ฐ„๊ณผํ–ˆ๋˜ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.์„œ๋น„์Šค๋กœ ๋ถ„๋ฆฌํ•˜๋Š” ๋ฐฉ๋ฒ•๋„ ์ข‹์€ ๊ฒƒ ๊ฐ™์•„์š”! ํ•˜๋‚˜ ์˜๊ฒฌ์„ ์—ฌ์ญ™๊ณ  ์‹ถ์€ ๊ฒŒ ์žˆ๋Š”๋ฐ, **๋ทฐ์—์„œ ์ž…๋ ฅ๊ฐ’์— ๋Œ€ํ•œ ํŒŒ์‹ฑ์„ ํ•˜๋Š” ๊ฒƒ์— ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋Š”์ง€** ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค! ํ˜„์žฌ๋Š” ์ž…๋ ฅ ๋ฐ›๊ธฐ+๊ฒ€์ฆ+ํŒŒ์‹ฑ์„ ๋ชจ๋‘ ์ˆ˜ํ–‰ํ•˜๊ณ  ์žˆ์–ด ์ฑ…์ž„ ๋ถ„๋ฆฌ๊ฐ€ ์ž˜ ์ด๋ฃจ์–ด์ง€์ง€ ์•Š์€ ๊ฒƒ ๊ฐ™๋‹ค๊ณ  ๋А๊ปด์ง‘๋‹ˆ๋‹ค... ๋ง์”€ํ•ด ์ฃผ์‹  ๊ฒƒ์ฒ˜๋Ÿผ ๋นˆ ๊ฐ’์„ ๊ฒ€์ฆํ•˜๋Š” ๋กœ์ง์„ parser๋กœ ํฌํ•จ์‹œํ‚จ๋‹ค๊ณ  ํ•˜๋ฉด, ๋ทฐ์—์„œ๋Š” ์ž…๋ ฅ์„ ๋ฐ›๋Š” ๊ธฐ๋Šฅ๋งŒ ์ˆ˜ํ–‰ํ•˜๊ณ  ์ปจํŠธ๋กค๋Ÿฌ๋‚˜ ์„œ๋น„์Šค์—์„œ ๊ฒ€์ฆ+ํŒŒ์‹ฑ์„ ์ง„ํ–‰ํ•˜๋Š” ํŽธ์ด ๋” ์ข‹์„๊นŒ์š”?
@@ -0,0 +1,138 @@ +name: CI + +on: + pull_request: + types: + - closed + +env: + IMAGE: ${{ vars.NCR_REGISTRY }}/follow-app + IMAGE_LATEST: ${{ vars.NCR_REGISTRY }}/follow-app:latest + +jobs: + lint-test: + name: lint and test + uses: ./.github/workflows/DRF-test.yaml + + send-discord-fail-message: + needs: lint-test + if: failure() + runs-on: ubuntu-latest + steps: + - name: Send Message to Discord + uses: "hugoalh/send-discord-webhook-ghaction@v5.0.0" + with: + key: ${{ secrets.DISCORD_WEBHOOK_KEY }} + payload: | + { + "content": "", + "embeds": [ + { + "title": "Test Failed", + "description": "workflow failed at DRF test stage.", + "color": "#b42323", + "footer": { + "text": "${{ github.event_name }}" + } + } + ], + "username": "Project Build Manager", + "avatar_url": "https://file.limeskin.kro.kr/curious_cat-small.png", + } + + build-and-push: + needs: lint-test + name: build and push + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Set up Docker buildx + uses: docker/setup-buildx-action@v2 + + - name: Login to NCR + uses: docker/login-action@v2 + with: + registry: ${{ vars.NCR_REGISTRY }} + username: ${{ secrets.NCR_ACCESS_KEY }} + password: ${{ secrets.NCR_SECRET_KEY }} + + - name: Get current timestamp + id: timestamp + run: echo "timestamp=$(date '+%s')" >> "$GITHUB_OUTPUT" + + - name: Build and Push + uses: docker/build-push-action@v4 + with: + context: follow_app + tags: ${{ env.IMAGE_LATEST }},"${{ env.IMAGE }}:${{ steps.timestamp.outputs.timestamp }}" + push: true + + health-check: + needs: build-and-push + name: health check + runs-on: ubuntu-latest + steps: + - name: Healthcheck Start + uses: appleboy/ssh-action@v1.0.0 + with: + host: ${{ secrets.HOST }} + username: ${{ secrets.USERNAME }} + password: ${{ secrets.PASSWORD }} + script: | + cd follow_app + docker login \ + ${{ vars.NCR_REGISTRY }} \ + -u ${{ secrets.NCR_ACCESS_KEY }} \ + -p ${{ secrets.NCR_SECRET_KEY }} + docker pull ${{ env.IMAGE_LATEST }} + + send-discord-fail-health: + needs: health-check + if: failure() + runs-on: ubuntu-latest + steps: + - name: Send Message to Discord + uses: "hugoalh/send-discord-webhook-ghaction@v5.0.0" + with: + key: ${{ secrets.DISCORD_WEBHOOK_KEY }} + payload: | + { + "content": "", + "embeds": [ + { + "title": "Health Check Failed", + "description": "workflow failed at stage server health check.", + "color": "#b42323", + "footer": { + "text": "${{ github.event_name }}" + } + } + ], + "username": "Project Build Manager", + "avatar_url": "https://file.limeskin.kro.kr/curious_cat-small.png", + } + + deploy: + needs: health-check + name: deploy + runs-on: ubuntu-latest + steps: + - name: pull and run image + uses: appleboy/ssh-action@v1.0.0 + with: + host: ${{ secrets.HOST }} + username: ${{ secrets.USERNAME }} + password: ${{ secrets.PASSWORD }} + script: | + docker login \ + ${{ vars.NCR_REGISTRY }} \ + -u ${{ secrets.NCR_ACCESS_KEY }} \ + -p ${{ secrets.NCR_SECRET_KEY }} + docker pull ${{ env.IMAGE_LATEST }} + docker stop follow-app + docker run -d --rm --name follow-app \ + --env-file .env \ + -p 8000:8000 \ + ${{ env.IMAGE_LATEST }} \ + /start
Unknown
๋‹ค๋ฅธ yaml ํŒŒ์ผ์— ์žˆ๋Š” workflow ๋ฅผ ๊ฐ€์ ธ์™€์„œ ์‚ฌ์šฉํ•˜์‹œ๋Š”๊ฑฐ ๊ฐ™์€๋ฐ, ์ž‘์—… ๋‚ด์— ์žˆ๋Š” ๋ณ€์ˆ˜๋„ ๋”ฐ๋กœ ๊บผ๋‚ด์„œ ์“ธ ์ˆ˜ ์žˆ๋‚˜์š” ??
@@ -0,0 +1,49 @@ +name: DRF Test + +on: + push: + workflow_call: + +jobs: + lint: + name: black check + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-python@v4 + with: + python-version: "3.11" + - name: install black + run: pip install black + - name: check black + run: black --check . + + drf-test: + needs: lint + name: test drf with docker + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: set env file + run: | + cat <<EOF > .env + # DB + POSTGRES_DB=postgres + POSTGRES_USER=postgres + POSTGRES_PASSWORD=postgres + POSTGRES_PORT=5432 + # DRF + DB_HOST=db + DJANGO_SECRET_KEY=just_test_secret_885f6d0c189dd4ccd619820b9f28f56bbe02be48d978f + RUN_MODE=local + DJANGO_ALLOWED_HOST=localhost + # NCP + NCP_ACCESS_KEY=${{ secrets.NCP_ACCESS_KEY }} + NCP_SECRET_KEY=${{ secrets.NCP_SECRET_KEY }} + EOF + + - name: test + run: | + docker compose up --build -d + docker compose run follow-app python manage.py test
Unknown
DB๊ด€๋ จ ๋ณ€์ˆ˜๋“ค๋„ secret์œผ๋กœ ์ถ”๊ฐ€ํ•ด์ฃผ์…”์„œ ์ฒ˜๋ฆฌํ•ด์ฃผ์‹œ๋ฉด ๋” ์ข‹์„๊ฑฐ ๊ฐ™์Šต๋‹ˆ๋‹ค :)
@@ -0,0 +1,138 @@ +name: CI + +on: + pull_request: + types: + - closed + +env: + IMAGE: ${{ vars.NCR_REGISTRY }}/follow-app + IMAGE_LATEST: ${{ vars.NCR_REGISTRY }}/follow-app:latest + +jobs: + lint-test: + name: lint and test + uses: ./.github/workflows/DRF-test.yaml + + send-discord-fail-message: + needs: lint-test + if: failure() + runs-on: ubuntu-latest + steps: + - name: Send Message to Discord + uses: "hugoalh/send-discord-webhook-ghaction@v5.0.0" + with: + key: ${{ secrets.DISCORD_WEBHOOK_KEY }} + payload: | + { + "content": "", + "embeds": [ + { + "title": "Test Failed", + "description": "workflow failed at DRF test stage.", + "color": "#b42323", + "footer": { + "text": "${{ github.event_name }}" + } + } + ], + "username": "Project Build Manager", + "avatar_url": "https://file.limeskin.kro.kr/curious_cat-small.png", + } + + build-and-push: + needs: lint-test + name: build and push + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Set up Docker buildx + uses: docker/setup-buildx-action@v2 + + - name: Login to NCR + uses: docker/login-action@v2 + with: + registry: ${{ vars.NCR_REGISTRY }} + username: ${{ secrets.NCR_ACCESS_KEY }} + password: ${{ secrets.NCR_SECRET_KEY }} + + - name: Get current timestamp + id: timestamp + run: echo "timestamp=$(date '+%s')" >> "$GITHUB_OUTPUT" + + - name: Build and Push + uses: docker/build-push-action@v4 + with: + context: follow_app + tags: ${{ env.IMAGE_LATEST }},"${{ env.IMAGE }}:${{ steps.timestamp.outputs.timestamp }}" + push: true + + health-check: + needs: build-and-push + name: health check + runs-on: ubuntu-latest + steps: + - name: Healthcheck Start + uses: appleboy/ssh-action@v1.0.0 + with: + host: ${{ secrets.HOST }} + username: ${{ secrets.USERNAME }} + password: ${{ secrets.PASSWORD }} + script: | + cd follow_app + docker login \ + ${{ vars.NCR_REGISTRY }} \ + -u ${{ secrets.NCR_ACCESS_KEY }} \ + -p ${{ secrets.NCR_SECRET_KEY }} + docker pull ${{ env.IMAGE_LATEST }} + + send-discord-fail-health: + needs: health-check + if: failure() + runs-on: ubuntu-latest + steps: + - name: Send Message to Discord + uses: "hugoalh/send-discord-webhook-ghaction@v5.0.0" + with: + key: ${{ secrets.DISCORD_WEBHOOK_KEY }} + payload: | + { + "content": "", + "embeds": [ + { + "title": "Health Check Failed", + "description": "workflow failed at stage server health check.", + "color": "#b42323", + "footer": { + "text": "${{ github.event_name }}" + } + } + ], + "username": "Project Build Manager", + "avatar_url": "https://file.limeskin.kro.kr/curious_cat-small.png", + } + + deploy: + needs: health-check + name: deploy + runs-on: ubuntu-latest + steps: + - name: pull and run image + uses: appleboy/ssh-action@v1.0.0 + with: + host: ${{ secrets.HOST }} + username: ${{ secrets.USERNAME }} + password: ${{ secrets.PASSWORD }} + script: | + docker login \ + ${{ vars.NCR_REGISTRY }} \ + -u ${{ secrets.NCR_ACCESS_KEY }} \ + -p ${{ secrets.NCR_SECRET_KEY }} + docker pull ${{ env.IMAGE_LATEST }} + docker stop follow-app + docker run -d --rm --name follow-app \ + --env-file .env \ + -p 8000:8000 \ + ${{ env.IMAGE_LATEST }} \ + /start
Unknown
health-check๋Š” ์–ด๋–ค์‹์œผ๋กœ ํ™•์ธํ•˜๊ฒŒ ๋˜๋Š”๊ฑด์ง€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,33 @@ +from django.core.management.base import BaseCommand +from django.contrib.auth.models import User +from tweet.models import Follow, Post + + +class Command(BaseCommand): + def handle(self, **options): + # if db has user script doesn't work + if User.objects.filter(username="user0").exists(): + print("๋ฐ์ดํ„ฐ๊ฐ€ ์ด๋ฏธ ์กด์žฌํ•ฉ๋‹ˆ๋‹ค.") + exit(0) + + # create user data + for i in range(5): + user = User.objects.create_user(username=f"user{i}", password=f"user{i}") + # create post data + for j in range(3): + Post.objects.create(owner=user, content=f"{j}. post by user{i}") + + # set follow data + for i in range(5): + user = User.objects.get(username=f"user{i}") + a = (i + 1) % 5 + b = (i + 2) % 5 + c = (i + 4) % 5 + usera = User.objects.get(username=f"user{a}") + userb = User.objects.get(username=f"user{b}") + userc = User.objects.get(username=f"user{c}") + Follow.objects.create(user=user, follow=usera) + Follow.objects.create(user=user, follow=userb) + Follow.objects.create(user=user, follow=userc) + + print("๋ฐ์ดํ„ฐ ์ƒ์„ฑ ์™„๋ฃŒ")
Python
์ด๋Ÿฐ๋ฐฉ๋ฒ•์ด ์žˆ๋‹ค๋‹ˆ ๋งŽ์ด ๋ฐฐ์šฐ๊ณ  ๊ฐ‘๋‹ˆ๋‹ค ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค
@@ -0,0 +1,138 @@ +name: CI + +on: + pull_request: + types: + - closed + +env: + IMAGE: ${{ vars.NCR_REGISTRY }}/follow-app + IMAGE_LATEST: ${{ vars.NCR_REGISTRY }}/follow-app:latest + +jobs: + lint-test: + name: lint and test + uses: ./.github/workflows/DRF-test.yaml + + send-discord-fail-message: + needs: lint-test + if: failure() + runs-on: ubuntu-latest + steps: + - name: Send Message to Discord + uses: "hugoalh/send-discord-webhook-ghaction@v5.0.0" + with: + key: ${{ secrets.DISCORD_WEBHOOK_KEY }} + payload: | + { + "content": "", + "embeds": [ + { + "title": "Test Failed", + "description": "workflow failed at DRF test stage.", + "color": "#b42323", + "footer": { + "text": "${{ github.event_name }}" + } + } + ], + "username": "Project Build Manager", + "avatar_url": "https://file.limeskin.kro.kr/curious_cat-small.png", + } + + build-and-push: + needs: lint-test + name: build and push + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Set up Docker buildx + uses: docker/setup-buildx-action@v2 + + - name: Login to NCR + uses: docker/login-action@v2 + with: + registry: ${{ vars.NCR_REGISTRY }} + username: ${{ secrets.NCR_ACCESS_KEY }} + password: ${{ secrets.NCR_SECRET_KEY }} + + - name: Get current timestamp + id: timestamp + run: echo "timestamp=$(date '+%s')" >> "$GITHUB_OUTPUT" + + - name: Build and Push + uses: docker/build-push-action@v4 + with: + context: follow_app + tags: ${{ env.IMAGE_LATEST }},"${{ env.IMAGE }}:${{ steps.timestamp.outputs.timestamp }}" + push: true + + health-check: + needs: build-and-push + name: health check + runs-on: ubuntu-latest + steps: + - name: Healthcheck Start + uses: appleboy/ssh-action@v1.0.0 + with: + host: ${{ secrets.HOST }} + username: ${{ secrets.USERNAME }} + password: ${{ secrets.PASSWORD }} + script: | + cd follow_app + docker login \ + ${{ vars.NCR_REGISTRY }} \ + -u ${{ secrets.NCR_ACCESS_KEY }} \ + -p ${{ secrets.NCR_SECRET_KEY }} + docker pull ${{ env.IMAGE_LATEST }} + + send-discord-fail-health: + needs: health-check + if: failure() + runs-on: ubuntu-latest + steps: + - name: Send Message to Discord + uses: "hugoalh/send-discord-webhook-ghaction@v5.0.0" + with: + key: ${{ secrets.DISCORD_WEBHOOK_KEY }} + payload: | + { + "content": "", + "embeds": [ + { + "title": "Health Check Failed", + "description": "workflow failed at stage server health check.", + "color": "#b42323", + "footer": { + "text": "${{ github.event_name }}" + } + } + ], + "username": "Project Build Manager", + "avatar_url": "https://file.limeskin.kro.kr/curious_cat-small.png", + } + + deploy: + needs: health-check + name: deploy + runs-on: ubuntu-latest + steps: + - name: pull and run image + uses: appleboy/ssh-action@v1.0.0 + with: + host: ${{ secrets.HOST }} + username: ${{ secrets.USERNAME }} + password: ${{ secrets.PASSWORD }} + script: | + docker login \ + ${{ vars.NCR_REGISTRY }} \ + -u ${{ secrets.NCR_ACCESS_KEY }} \ + -p ${{ secrets.NCR_SECRET_KEY }} + docker pull ${{ env.IMAGE_LATEST }} + docker stop follow-app + docker run -d --rm --name follow-app \ + --env-file .env \ + -p 8000:8000 \ + ${{ env.IMAGE_LATEST }} \ + /start
Unknown
test๋งŒ ํ•˜๊ธฐ ์œ„ํ•ด ๋ถˆ๋Ÿฌ์˜ค๋Š” workflow๋ผ ๋ณ€์ˆ˜๋ฅผ ๊ฐ€์ ธ์˜ฌ ์ƒ๊ฐ์€ ๋ชปํ–ˆ๋„ค์š”. job๋ผ๋ฆฌ์˜ ๋ณ€์ˆ˜ ๊ณต์œ  ๋ฐฉ๋ฒ•์œผ๋กœ ๊บผ๋‚ผ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™๊ธด ํ•œ๋ฐ ์‹œ๋„๋Š” ์•ˆํ•ด๋ดค์–ด์š”
@@ -0,0 +1,49 @@ +name: DRF Test + +on: + push: + workflow_call: + +jobs: + lint: + name: black check + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-python@v4 + with: + python-version: "3.11" + - name: install black + run: pip install black + - name: check black + run: black --check . + + drf-test: + needs: lint + name: test drf with docker + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: set env file + run: | + cat <<EOF > .env + # DB + POSTGRES_DB=postgres + POSTGRES_USER=postgres + POSTGRES_PASSWORD=postgres + POSTGRES_PORT=5432 + # DRF + DB_HOST=db + DJANGO_SECRET_KEY=just_test_secret_885f6d0c189dd4ccd619820b9f28f56bbe02be48d978f + RUN_MODE=local + DJANGO_ALLOWED_HOST=localhost + # NCP + NCP_ACCESS_KEY=${{ secrets.NCP_ACCESS_KEY }} + NCP_SECRET_KEY=${{ secrets.NCP_SECRET_KEY }} + EOF + + - name: test + run: | + docker compose up --build -d + docker compose run follow-app python manage.py test
Unknown
๋งž์•„์š” ๋‹ค๋งŒ ์ € ๋ถ€๋ถ„์ด ์ˆœ์ „ํžˆ ํ…Œ์ŠคํŠธ๋งŒ์„ ์œ„ํ•œ ๋ถ€๋ถ„์ด๋ผ ๊ดœ์ฐฎ์„ ๊ฑฐ๋ผ๊ณ  ์ƒ๊ฐํ–ˆ์–ด์š” ์›๋ž˜ test์šฉ envํŒŒ์ผ์„ git์— ๊ทธ๋Œ€๋กœ ์˜ฌ๋ ค์„œ actions์—์„œ ์‚ฌ์šฉํ–ˆ์—ˆ๋Š”๋ฐ ์ œ๊ฐ€ ์‹ค์ˆ˜๋กœ ncp key๋ฅผ ๋„ฃ์–ด์„œ ์˜ฌ๋ฆฌ๋Š” ๋ฐ”๋žŒ์— ๊ธ‰ํ•˜๊ฒŒ ์œ„์™€ ๊ฐ™์ด ๋ณ€๊ฒฝ๋œ ๊ฑฐ์—์š”. ์ €๋„ ์ €๋Ÿฐ์‹์œผ๋กœ ์ž‘์„ฑํ•˜๊ธฐ์—” ๋ณด๊ธฐ ์•Š์ข‹์•„ ๋ณด์—ฌ์„œ ์กฐ๊ธˆ ๋” ์„ธ๋ จ๋œ ๋ฐฉ์‹์œผ๋กœ ๋ณ€๊ฒฝํ•ด ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค
@@ -0,0 +1,138 @@ +name: CI + +on: + pull_request: + types: + - closed + +env: + IMAGE: ${{ vars.NCR_REGISTRY }}/follow-app + IMAGE_LATEST: ${{ vars.NCR_REGISTRY }}/follow-app:latest + +jobs: + lint-test: + name: lint and test + uses: ./.github/workflows/DRF-test.yaml + + send-discord-fail-message: + needs: lint-test + if: failure() + runs-on: ubuntu-latest + steps: + - name: Send Message to Discord + uses: "hugoalh/send-discord-webhook-ghaction@v5.0.0" + with: + key: ${{ secrets.DISCORD_WEBHOOK_KEY }} + payload: | + { + "content": "", + "embeds": [ + { + "title": "Test Failed", + "description": "workflow failed at DRF test stage.", + "color": "#b42323", + "footer": { + "text": "${{ github.event_name }}" + } + } + ], + "username": "Project Build Manager", + "avatar_url": "https://file.limeskin.kro.kr/curious_cat-small.png", + } + + build-and-push: + needs: lint-test + name: build and push + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Set up Docker buildx + uses: docker/setup-buildx-action@v2 + + - name: Login to NCR + uses: docker/login-action@v2 + with: + registry: ${{ vars.NCR_REGISTRY }} + username: ${{ secrets.NCR_ACCESS_KEY }} + password: ${{ secrets.NCR_SECRET_KEY }} + + - name: Get current timestamp + id: timestamp + run: echo "timestamp=$(date '+%s')" >> "$GITHUB_OUTPUT" + + - name: Build and Push + uses: docker/build-push-action@v4 + with: + context: follow_app + tags: ${{ env.IMAGE_LATEST }},"${{ env.IMAGE }}:${{ steps.timestamp.outputs.timestamp }}" + push: true + + health-check: + needs: build-and-push + name: health check + runs-on: ubuntu-latest + steps: + - name: Healthcheck Start + uses: appleboy/ssh-action@v1.0.0 + with: + host: ${{ secrets.HOST }} + username: ${{ secrets.USERNAME }} + password: ${{ secrets.PASSWORD }} + script: | + cd follow_app + docker login \ + ${{ vars.NCR_REGISTRY }} \ + -u ${{ secrets.NCR_ACCESS_KEY }} \ + -p ${{ secrets.NCR_SECRET_KEY }} + docker pull ${{ env.IMAGE_LATEST }} + + send-discord-fail-health: + needs: health-check + if: failure() + runs-on: ubuntu-latest + steps: + - name: Send Message to Discord + uses: "hugoalh/send-discord-webhook-ghaction@v5.0.0" + with: + key: ${{ secrets.DISCORD_WEBHOOK_KEY }} + payload: | + { + "content": "", + "embeds": [ + { + "title": "Health Check Failed", + "description": "workflow failed at stage server health check.", + "color": "#b42323", + "footer": { + "text": "${{ github.event_name }}" + } + } + ], + "username": "Project Build Manager", + "avatar_url": "https://file.limeskin.kro.kr/curious_cat-small.png", + } + + deploy: + needs: health-check + name: deploy + runs-on: ubuntu-latest + steps: + - name: pull and run image + uses: appleboy/ssh-action@v1.0.0 + with: + host: ${{ secrets.HOST }} + username: ${{ secrets.USERNAME }} + password: ${{ secrets.PASSWORD }} + script: | + docker login \ + ${{ vars.NCR_REGISTRY }} \ + -u ${{ secrets.NCR_ACCESS_KEY }} \ + -p ${{ secrets.NCR_SECRET_KEY }} + docker pull ${{ env.IMAGE_LATEST }} + docker stop follow-app + docker run -d --rm --name follow-app \ + --env-file .env \ + -p 8000:8000 \ + ${{ env.IMAGE_LATEST }} \ + /start
Unknown
health-check๋ฅผ ํ™•์ธํ•˜๋Š” ๋ถ€๋ถ„์€ ์•„์ง ๋งŒ๋“ค์ง€ ์•Š์•˜์–ด์š” ๋Œ€์‹ ์— DRF test๋ฅผ ํ†ต๊ณผํ•˜๋ฉด ์ •์ƒ ๋™์ž‘์ธ ๊ฑฐ๋กœ ๊ฐ„์ฃผํ•˜๊ณ  ๋งŒ๋“ค๊ธด ํ–ˆ์–ด์š” ์‚ฌ์‹ค actions์—์„œ health-check๋ฅผ ๊ตฌํ˜„ํ•˜๊ธฐ ์กฐ๊ธˆ ๊นŒ๋‹ค๋กœ์›Œ์„œ k8s ์ ์šฉํ•˜๋ฉด์„œ health-check๋„ ๊ตฌํ˜„ ํ•  ๊ณ„ํš์ž…๋‹ˆ๋‹ค.
@@ -0,0 +1,519 @@ +import React, { Component } from 'react'; +import * as d3 from 'd3'; +import drawData from './Module/loadHandle'; +import FilterContainer from './Components/FilterContainer'; +import LoginModal from './Components/LoginModal'; +import DrawContainer from './Components/DrawContainer'; +import './less/App.less'; +import * as constants from './constants'; +import * as MakeSecret from './Module/simpleEncryption'; +import NearbyFactorDialog from './Components/NearbyFactorDialog'; +import DrawingSetTitleDescription from './Components/drawingSetTitleDescriptionModal'; + +class App extends Component { + constructor(props) { + super(props); + this.bound = undefined; + this.drawList = {}; + this.newToggleBox = constants.newToggleBox; + this.state = { + name: undefined, + drawingData: [], + map: undefined, + showFilter: false, + showModal: false, + activeFilter: 'active', + activeDraw: '', + MyInfoButton: false, + showDraw: false, + factors: [], + NearByFactorItems: [], + showDrawingSetTitleDescriptionModal: false, + drawingSetTitle: null, + drawingSetDescription: null, + descriptionModalState: false, + descriptionValue: '', + descriptionTitle: '', + legendToggle: false + // NearByFilteringItems: [] + }; + } + + componentDidMount = async () => { + const naver = window.naver; + const map = await new naver.maps.Map(d3.select('#map').node(), { + zoomControl: true, + zoomControlOptions: { + style: naver.maps.ZoomControlStyle.SMALL, + position: naver.maps.Position.TOP_RIGHT + }, + logoControl: true, + logoControlOptions: { + position: naver.maps.Position.BOTTOM_RIGHT + }, + scaleControl: true, + scaleControlOptions: { + position: naver.maps.Position.BOTTOM_RIGHT + }, + mapDataControl: true, + mapDataControlOptions: { + position: naver.maps.Position.BOTTOM_LEFT + } + }); + + this.setState({ map }); + this.bound = map.getBounds(); + this.mainPageLoad(map); + naver.maps.Event.addListener(map, 'idle', e => { + const { showDraw } = this.state; + this.bound = map.getBounds(); + // ๊ทธ๋ฆฌ๊ธฐ ๋ชจ๋“œ๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ์—๋งŒ ๋ฐ์ดํ„ฐ๋ฅผ ๋ถˆ๋Ÿฌ์˜ด + if (!showDraw) { + this.mainPageLoad(map); + this.deleteDraw(); + } + }); + const name = JSON.parse(localStorage.getItem('token')); + if (name) { + this.setState({ + name: MakeSecret.Decrypt(name) + }); + } + }; + + isDelete = false; + + handleUserNameOnChange = username => { + this.setState({ name: username }); + }; + + showDrawingSetTitleDescriptionModal = value => { + this.setState({ showDrawingSetTitleDescriptionModal: value }); + }; + + changeDrawingSetTitle = text => { + this.setState({ drawingSetTitle: text }); + }; + + changeDrawingSetDescription = text => { + this.setState({ drawingSetDescription: text }); + }; + + mainPageLoad = map => { + const { name, factors } = this.state; + const bound = this.bound; + const nearbyData = async val => { + await this.setState({ + NearByFactorItems: val + }); + }; + drawData(name, bound, factors, false, this.drawList, map, nearbyData); + }; + + toggleAllDraw = () => { + const { showDraw, map } = this.state; + if (showDraw) { + Object.entries(this.drawList).forEach(([key, value]) => { + value.setMap(null); + delete this.drawList[key]; + }); + this.isDelete = true; + } else { + if (this.isDelete) { + this.mainPageLoad(map); + this.isDelete = false; + } + } + }; + + deleteDraw = () => { + Object.entries(this.drawList).forEach(([key, value]) => { + const startPos = {}; + const endPos = {}; + // reference point + startPos.x = value._lineData[0].coord.x; + startPos.y = value._lineData[0].coord.y; + endPos.x = value._lineData[value._lineData.length - 1].coord.x; + endPos.y = value._lineData[value._lineData.length - 1].coord.y; + + if ( + (startPos.x < this.bound._min._lng - 0.01 + || this.bound._max._lng + 0.01 < startPos.x + || startPos.y < this.bound._min._lat - 0.01 + || this.bound._max._lat + 0.01 < startPos.y) + && (endPos.x < this.bound._min._lng - 0.01 + || this.bound._max._lng + 0.01 < endPos.x + || endPos.y < this.bound._min._lat - 0.01 + || this.bound._max._lat + 0.01 < endPos.y) + ) { + value.setMap(null); + delete this.drawList[key]; + } + }); + }; + + toggleLoginModal = () => { + const { showModal } = this.state; + this.setState({ showModal: !showModal }); + }; + + toggleDraw = () => { + const { showDraw } = this.state; + this.setState({ descriptionModalState: false }); + this.setState({ showDraw: !showDraw }); + }; + + toggleLegend = () => { + const { legendToggle } = this.state; + this.setState({ legendToggle: !legendToggle }); + }; + + showFilter = () => { + const { showFilter, activeFilter } = this.state; + if (activeFilter === 'active') { + this.setState({ + showFilter: !showFilter, + activeFilter: '' + }); + } else { + this.setState({ + showFilter: !showFilter, + activeFilter: 'active' + }); + } + }; + + showDraw = () => { + const { showDraw, drawingData, activeDraw } = this.state; + if (drawingData.length) { + const pressedConfirm = confirm( + '์ €์žฅํ•˜์ง€ ์•Š๊ณ  ๊ทธ๋ฆฌ๊ธฐ ์ฐฝ์„ ๋‹ซ์œผ๋ฉด ๊ทธ๋ฆฐ ์ •๋ณด๋Š” ๋ชจ๋‘ ์‚ฌ๋ผ์ง‘๋‹ˆ๋‹ค!\n๊ทธ๋ž˜๋„ ๊ทธ๋ฆฌ๊ธฐ ์ฐฝ์„ ๋‹ซ์œผ์‹œ๊ฒ ์–ด์š”?' + ); + if (pressedConfirm) { + for (let index = 0; index < drawingData.length; index++) { + drawingData[index].figure.onRemove(); + } + this.setState({ drawingData: [] }); + this.setState({ descriptionModalState: false }); + } else if (!pressedConfirm) { + return; + } + } + + if (activeDraw === 'active') { + this.setState({ + showDraw: !showDraw, + activeDraw: '' + }); + } else { + this.setState({ + showDraw: !showDraw, + activeDraw: 'active' + }); + } + }; + + initDrawingListAfterSave = () => { + this.setState({ drawingData: [] }); + }; + + initUserName = () => { + this.setState({ name: undefined }); + }; + + myInfoToggle = () => { + const { MyInfoButton } = this.state; + this.setState({ MyInfoButton: !MyInfoButton }); + this.factorLoad(null, !MyInfoButton); + }; + + updateDrawingData = (shapeData, order = false, index) => { + const { drawingData } = this.state; + this.setState({ drawingData: [...drawingData, shapeData] }); + if (order) { + const newDrawingData = [...drawingData]; + newDrawingData.splice(index, 1); + this.setState({ drawingData: newDrawingData }); + } + }; + + mainToggle = (stateName, toggle) => { + this.setState({ [stateName]: !toggle }); + }; + + factorLoad = (category, toggle = false) => { + const { name, map } = this.state; + const bound = this.bound; + const factors = []; + let nearbyData; + + // ๊ธฐ์กด ์ง€๋„์— ์žˆ๋˜ ์ •๋ณด๋ฅผ ์ง€์›Œ์คŒ + Object.entries(this.drawList).forEach(([key, value]) => { + value.setMap(null); + delete this.drawList[key]; + }); + // ์œ ์ € ํ˜ธ์žฌ ๋ณด๊ธฐ + if (toggle) { + const toggleObj = {}; + Object.entries(this.newToggleBox).forEach(([key, value]) => { + toggleObj[key] = false; + }); + this.newToggleBox = toggleObj; + } + // ํ•„ํ„ฐ๋ง ํ•˜๊ธฐ + if (category) { + const toggleCategory = { + [category]: !this.newToggleBox[category] + }; + this.newToggleBox = { + ...this.newToggleBox, + ...toggleCategory + }; + Object.entries(this.newToggleBox).forEach(([key, value]) => { + if (value) { + factors.push(key); + } + }); + this.setState({ + factors: factors + }); + nearbyData = async val => { + await this.setState({ + NearByFactorItems: val + }); + }; + } + // TODO: + drawData(name, bound, factors, toggle, this.drawList, map, nearbyData); + }; + + handleChangeDescription = event => { + this.setState({ descriptionValue: event.target.value }); + }; + + handleChangeTitle = event => { + this.setState({ descriptionTitle: event.target.value }); + }; + + descriptionModal = () => { + const { + descriptionModalState, + descriptionValue, + descriptionTitle + } = this.state; + if (descriptionModalState) { + return ( + <div className="descriptionModal"> + <div className="descriptionHeader"> </div> + <textarea + placeholder="์ œ๋ชฉ์„ ์ง€์–ด์ฃผ์„ธ์š”:D" + className="descriptionInputTitle" + type="text" + value={descriptionTitle} + onChange={this.handleChangeTitle} + /> + <textarea + placeholder="ํ˜ธ์žฌ ๋‚ด์šฉ์„ ์ฑ„์›Œ์ฃผ์„ธ์š”:D" + className="descriptionInput" + type="text" + value={descriptionValue} + onChange={this.handleChangeDescription} + /> + <button + className="descriptionCloser" + type="button" + onClick={this.descriptionModalHide} + > + ๋‹ซ๊ธฐ + </button> + <button + className="descriptionSave" + type="button" + onClick={this.descriptionModalSave} + > + ์ €์žฅ + </button> + </div> + ); + } else { + return <div />; + } + }; + + descriptionModalHide = () => { + this.setState({ + descriptionModalState: false, + descriptionValue: '', + descriptionTitle: '' + }); + }; + + descriptionModalSave = () => { + const { descriptionValue, descriptionTitle, drawingData } = this.state; + this.setState({ descriptionModalState: false }); + const arrayOfShapes = drawingData; + arrayOfShapes[arrayOfShapes.length - 1].title = descriptionTitle; + arrayOfShapes[arrayOfShapes.length - 1].value = descriptionValue; + this.setState({ drawingData: arrayOfShapes }); + }; + + descriptionModalShow = () => { + this.setState({ descriptionModalState: true }); + }; + + render() { + const { + map, + name, + drawingData, + showFilter, + showDraw, + showModal, + activeFilter, + activeDraw, + MyInfoButton, + NearByFactorItems, + legendToggle, + showDrawingSetTitleDescriptionModal, + drawingSetTitle, + drawingSetDescription + } = this.state; + + this.toggleAllDraw(); + return ( + <div id="wrapper"> + <div id="map"> + <NearbyFactorDialog + mapLoad={map} + NearByFactorItems={NearByFactorItems} + /> + <div id="loginFavorContainer"> + <div + className="loginFavorBtn" + onClick={this.toggleLoginModal} + onKeyPress={this.toggleLoginModal} + role="button" + tabIndex="0" + > + {`My`} + </div> + <div + className={`loginFavorBtn ${activeFilter}`} + onClick={() => { + if (activeDraw === '') { + this.showFilter(); + } + }} + onKeyPress={() => this.showFilter} + role="button" + tabIndex="0" + > + {`ํ•„ํ„ฐ`} + </div> + <div + className={`loginFavorBtn ${activeDraw}`} + onClick={() => { + if (activeFilter === '') { + this.showDraw(); + this.descriptionModalHide(); + } + }} + onKeyPress={() => this.showDraw} + role="button" + tabIndex="0" + > + {`๊ทธ๋ฆฌ๊ธฐ`} + </div> + </div> + {showModal ? ( + <LoginModal + name={name} + toggleLoginModal={this.toggleLoginModal} + handleUserNameOnChange={this.handleUserNameOnChange} + initUserName={this.initUserName} + /> + ) : null} + <div className={!showFilter ? 'block' : 'none'}> + <FilterContainer + MyInfoButton={MyInfoButton} + myInfoToggle={this.myInfoToggle} + factorLoad={this.factorLoad} + showFilter={this.showFilter} + /> + </div> + <div className={showDraw ? 'block' : 'none'}> + <DrawContainer + handleToggle={this.showDraw} + mapLoad={map} + handleUserNameOnChange={this.handleUserNameOnChange} + drawingData={drawingData} + updateDrawingData={this.updateDrawingData} + toggleLoginModal={this.toggleLoginModal} + NearByFactorItems={NearByFactorItems} + initDrawingListAfterSave={ + this.initDrawingListAfterSave + } + showDraw={this.showDraw} + showDrawingSetTitleDescriptionModal={ + this.showDrawingSetTitleDescriptionModal + } + descriptionModalShow={this.descriptionModalShow} + descriptionModalHide={this.descriptionModalHide} + /> + </div> + {showDrawingSetTitleDescriptionModal ? ( + <DrawingSetTitleDescription + changeDrawingSetTitle={this.changeDrawingSetTitle} + changeDrawingSetDescription={ + this.changeDrawingSetDescription + } + drawingData={drawingData} + toggleLoginModal={this.toggleLoginModal} + initDrawingListAfterSave={ + this.initDrawingListAfterSave + } + showDraw={this.showDraw} + showDrawingSetTitleDescriptionModal={ + this.showDrawingSetTitleDescriptionModal + } + drawingSetTitle={drawingSetTitle} + drawingSetDescription={drawingSetDescription} + /> + ) : null} + <div + className="legend" + onClick={this.toggleLegend} + onKeyPress={this.toggleLegend} + role="button" + tabIndex="0" + /> + <div + className={ + 'colorList ' + (legendToggle ? 'invisible' : '') + } + > + {Object.keys(constants.newToggleBox).map( + (color, index) => { + return ( + <div className="eachColor" key={index}> + <div className="legendColorBox"> + <div className="colorCircle" /> + </div> + <div className="legendTextBox"> + {color} + </div> + </div> + ); + } + )} + </div> + </div> + <div> + <this.descriptionModal /> + </div> + </div> + ); + } +} + +export default App;
JavaScript
์ƒ์ˆ˜๋กœ ๋นผ๋†“๋Š”๊ฒŒ ์ข‹์„๋“ฏ. `server/categories.js`์—๋„ ์ •์˜๋˜์–ด์žˆ๊ณ  server๋‚˜ client๋‚˜ ๊ฐ™์ด ์“ฐ๊ฒŒ ๋ ํ…๋ฐ ์–ด๋–ป๊ฒŒ ์ฒ˜๋ฆฌํ• ์ง€ ์ •ํ•˜๋Š”๊ฒŒ ์ข‹์„๋“ฏ
@@ -0,0 +1,519 @@ +import React, { Component } from 'react'; +import * as d3 from 'd3'; +import drawData from './Module/loadHandle'; +import FilterContainer from './Components/FilterContainer'; +import LoginModal from './Components/LoginModal'; +import DrawContainer from './Components/DrawContainer'; +import './less/App.less'; +import * as constants from './constants'; +import * as MakeSecret from './Module/simpleEncryption'; +import NearbyFactorDialog from './Components/NearbyFactorDialog'; +import DrawingSetTitleDescription from './Components/drawingSetTitleDescriptionModal'; + +class App extends Component { + constructor(props) { + super(props); + this.bound = undefined; + this.drawList = {}; + this.newToggleBox = constants.newToggleBox; + this.state = { + name: undefined, + drawingData: [], + map: undefined, + showFilter: false, + showModal: false, + activeFilter: 'active', + activeDraw: '', + MyInfoButton: false, + showDraw: false, + factors: [], + NearByFactorItems: [], + showDrawingSetTitleDescriptionModal: false, + drawingSetTitle: null, + drawingSetDescription: null, + descriptionModalState: false, + descriptionValue: '', + descriptionTitle: '', + legendToggle: false + // NearByFilteringItems: [] + }; + } + + componentDidMount = async () => { + const naver = window.naver; + const map = await new naver.maps.Map(d3.select('#map').node(), { + zoomControl: true, + zoomControlOptions: { + style: naver.maps.ZoomControlStyle.SMALL, + position: naver.maps.Position.TOP_RIGHT + }, + logoControl: true, + logoControlOptions: { + position: naver.maps.Position.BOTTOM_RIGHT + }, + scaleControl: true, + scaleControlOptions: { + position: naver.maps.Position.BOTTOM_RIGHT + }, + mapDataControl: true, + mapDataControlOptions: { + position: naver.maps.Position.BOTTOM_LEFT + } + }); + + this.setState({ map }); + this.bound = map.getBounds(); + this.mainPageLoad(map); + naver.maps.Event.addListener(map, 'idle', e => { + const { showDraw } = this.state; + this.bound = map.getBounds(); + // ๊ทธ๋ฆฌ๊ธฐ ๋ชจ๋“œ๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ์—๋งŒ ๋ฐ์ดํ„ฐ๋ฅผ ๋ถˆ๋Ÿฌ์˜ด + if (!showDraw) { + this.mainPageLoad(map); + this.deleteDraw(); + } + }); + const name = JSON.parse(localStorage.getItem('token')); + if (name) { + this.setState({ + name: MakeSecret.Decrypt(name) + }); + } + }; + + isDelete = false; + + handleUserNameOnChange = username => { + this.setState({ name: username }); + }; + + showDrawingSetTitleDescriptionModal = value => { + this.setState({ showDrawingSetTitleDescriptionModal: value }); + }; + + changeDrawingSetTitle = text => { + this.setState({ drawingSetTitle: text }); + }; + + changeDrawingSetDescription = text => { + this.setState({ drawingSetDescription: text }); + }; + + mainPageLoad = map => { + const { name, factors } = this.state; + const bound = this.bound; + const nearbyData = async val => { + await this.setState({ + NearByFactorItems: val + }); + }; + drawData(name, bound, factors, false, this.drawList, map, nearbyData); + }; + + toggleAllDraw = () => { + const { showDraw, map } = this.state; + if (showDraw) { + Object.entries(this.drawList).forEach(([key, value]) => { + value.setMap(null); + delete this.drawList[key]; + }); + this.isDelete = true; + } else { + if (this.isDelete) { + this.mainPageLoad(map); + this.isDelete = false; + } + } + }; + + deleteDraw = () => { + Object.entries(this.drawList).forEach(([key, value]) => { + const startPos = {}; + const endPos = {}; + // reference point + startPos.x = value._lineData[0].coord.x; + startPos.y = value._lineData[0].coord.y; + endPos.x = value._lineData[value._lineData.length - 1].coord.x; + endPos.y = value._lineData[value._lineData.length - 1].coord.y; + + if ( + (startPos.x < this.bound._min._lng - 0.01 + || this.bound._max._lng + 0.01 < startPos.x + || startPos.y < this.bound._min._lat - 0.01 + || this.bound._max._lat + 0.01 < startPos.y) + && (endPos.x < this.bound._min._lng - 0.01 + || this.bound._max._lng + 0.01 < endPos.x + || endPos.y < this.bound._min._lat - 0.01 + || this.bound._max._lat + 0.01 < endPos.y) + ) { + value.setMap(null); + delete this.drawList[key]; + } + }); + }; + + toggleLoginModal = () => { + const { showModal } = this.state; + this.setState({ showModal: !showModal }); + }; + + toggleDraw = () => { + const { showDraw } = this.state; + this.setState({ descriptionModalState: false }); + this.setState({ showDraw: !showDraw }); + }; + + toggleLegend = () => { + const { legendToggle } = this.state; + this.setState({ legendToggle: !legendToggle }); + }; + + showFilter = () => { + const { showFilter, activeFilter } = this.state; + if (activeFilter === 'active') { + this.setState({ + showFilter: !showFilter, + activeFilter: '' + }); + } else { + this.setState({ + showFilter: !showFilter, + activeFilter: 'active' + }); + } + }; + + showDraw = () => { + const { showDraw, drawingData, activeDraw } = this.state; + if (drawingData.length) { + const pressedConfirm = confirm( + '์ €์žฅํ•˜์ง€ ์•Š๊ณ  ๊ทธ๋ฆฌ๊ธฐ ์ฐฝ์„ ๋‹ซ์œผ๋ฉด ๊ทธ๋ฆฐ ์ •๋ณด๋Š” ๋ชจ๋‘ ์‚ฌ๋ผ์ง‘๋‹ˆ๋‹ค!\n๊ทธ๋ž˜๋„ ๊ทธ๋ฆฌ๊ธฐ ์ฐฝ์„ ๋‹ซ์œผ์‹œ๊ฒ ์–ด์š”?' + ); + if (pressedConfirm) { + for (let index = 0; index < drawingData.length; index++) { + drawingData[index].figure.onRemove(); + } + this.setState({ drawingData: [] }); + this.setState({ descriptionModalState: false }); + } else if (!pressedConfirm) { + return; + } + } + + if (activeDraw === 'active') { + this.setState({ + showDraw: !showDraw, + activeDraw: '' + }); + } else { + this.setState({ + showDraw: !showDraw, + activeDraw: 'active' + }); + } + }; + + initDrawingListAfterSave = () => { + this.setState({ drawingData: [] }); + }; + + initUserName = () => { + this.setState({ name: undefined }); + }; + + myInfoToggle = () => { + const { MyInfoButton } = this.state; + this.setState({ MyInfoButton: !MyInfoButton }); + this.factorLoad(null, !MyInfoButton); + }; + + updateDrawingData = (shapeData, order = false, index) => { + const { drawingData } = this.state; + this.setState({ drawingData: [...drawingData, shapeData] }); + if (order) { + const newDrawingData = [...drawingData]; + newDrawingData.splice(index, 1); + this.setState({ drawingData: newDrawingData }); + } + }; + + mainToggle = (stateName, toggle) => { + this.setState({ [stateName]: !toggle }); + }; + + factorLoad = (category, toggle = false) => { + const { name, map } = this.state; + const bound = this.bound; + const factors = []; + let nearbyData; + + // ๊ธฐ์กด ์ง€๋„์— ์žˆ๋˜ ์ •๋ณด๋ฅผ ์ง€์›Œ์คŒ + Object.entries(this.drawList).forEach(([key, value]) => { + value.setMap(null); + delete this.drawList[key]; + }); + // ์œ ์ € ํ˜ธ์žฌ ๋ณด๊ธฐ + if (toggle) { + const toggleObj = {}; + Object.entries(this.newToggleBox).forEach(([key, value]) => { + toggleObj[key] = false; + }); + this.newToggleBox = toggleObj; + } + // ํ•„ํ„ฐ๋ง ํ•˜๊ธฐ + if (category) { + const toggleCategory = { + [category]: !this.newToggleBox[category] + }; + this.newToggleBox = { + ...this.newToggleBox, + ...toggleCategory + }; + Object.entries(this.newToggleBox).forEach(([key, value]) => { + if (value) { + factors.push(key); + } + }); + this.setState({ + factors: factors + }); + nearbyData = async val => { + await this.setState({ + NearByFactorItems: val + }); + }; + } + // TODO: + drawData(name, bound, factors, toggle, this.drawList, map, nearbyData); + }; + + handleChangeDescription = event => { + this.setState({ descriptionValue: event.target.value }); + }; + + handleChangeTitle = event => { + this.setState({ descriptionTitle: event.target.value }); + }; + + descriptionModal = () => { + const { + descriptionModalState, + descriptionValue, + descriptionTitle + } = this.state; + if (descriptionModalState) { + return ( + <div className="descriptionModal"> + <div className="descriptionHeader"> </div> + <textarea + placeholder="์ œ๋ชฉ์„ ์ง€์–ด์ฃผ์„ธ์š”:D" + className="descriptionInputTitle" + type="text" + value={descriptionTitle} + onChange={this.handleChangeTitle} + /> + <textarea + placeholder="ํ˜ธ์žฌ ๋‚ด์šฉ์„ ์ฑ„์›Œ์ฃผ์„ธ์š”:D" + className="descriptionInput" + type="text" + value={descriptionValue} + onChange={this.handleChangeDescription} + /> + <button + className="descriptionCloser" + type="button" + onClick={this.descriptionModalHide} + > + ๋‹ซ๊ธฐ + </button> + <button + className="descriptionSave" + type="button" + onClick={this.descriptionModalSave} + > + ์ €์žฅ + </button> + </div> + ); + } else { + return <div />; + } + }; + + descriptionModalHide = () => { + this.setState({ + descriptionModalState: false, + descriptionValue: '', + descriptionTitle: '' + }); + }; + + descriptionModalSave = () => { + const { descriptionValue, descriptionTitle, drawingData } = this.state; + this.setState({ descriptionModalState: false }); + const arrayOfShapes = drawingData; + arrayOfShapes[arrayOfShapes.length - 1].title = descriptionTitle; + arrayOfShapes[arrayOfShapes.length - 1].value = descriptionValue; + this.setState({ drawingData: arrayOfShapes }); + }; + + descriptionModalShow = () => { + this.setState({ descriptionModalState: true }); + }; + + render() { + const { + map, + name, + drawingData, + showFilter, + showDraw, + showModal, + activeFilter, + activeDraw, + MyInfoButton, + NearByFactorItems, + legendToggle, + showDrawingSetTitleDescriptionModal, + drawingSetTitle, + drawingSetDescription + } = this.state; + + this.toggleAllDraw(); + return ( + <div id="wrapper"> + <div id="map"> + <NearbyFactorDialog + mapLoad={map} + NearByFactorItems={NearByFactorItems} + /> + <div id="loginFavorContainer"> + <div + className="loginFavorBtn" + onClick={this.toggleLoginModal} + onKeyPress={this.toggleLoginModal} + role="button" + tabIndex="0" + > + {`My`} + </div> + <div + className={`loginFavorBtn ${activeFilter}`} + onClick={() => { + if (activeDraw === '') { + this.showFilter(); + } + }} + onKeyPress={() => this.showFilter} + role="button" + tabIndex="0" + > + {`ํ•„ํ„ฐ`} + </div> + <div + className={`loginFavorBtn ${activeDraw}`} + onClick={() => { + if (activeFilter === '') { + this.showDraw(); + this.descriptionModalHide(); + } + }} + onKeyPress={() => this.showDraw} + role="button" + tabIndex="0" + > + {`๊ทธ๋ฆฌ๊ธฐ`} + </div> + </div> + {showModal ? ( + <LoginModal + name={name} + toggleLoginModal={this.toggleLoginModal} + handleUserNameOnChange={this.handleUserNameOnChange} + initUserName={this.initUserName} + /> + ) : null} + <div className={!showFilter ? 'block' : 'none'}> + <FilterContainer + MyInfoButton={MyInfoButton} + myInfoToggle={this.myInfoToggle} + factorLoad={this.factorLoad} + showFilter={this.showFilter} + /> + </div> + <div className={showDraw ? 'block' : 'none'}> + <DrawContainer + handleToggle={this.showDraw} + mapLoad={map} + handleUserNameOnChange={this.handleUserNameOnChange} + drawingData={drawingData} + updateDrawingData={this.updateDrawingData} + toggleLoginModal={this.toggleLoginModal} + NearByFactorItems={NearByFactorItems} + initDrawingListAfterSave={ + this.initDrawingListAfterSave + } + showDraw={this.showDraw} + showDrawingSetTitleDescriptionModal={ + this.showDrawingSetTitleDescriptionModal + } + descriptionModalShow={this.descriptionModalShow} + descriptionModalHide={this.descriptionModalHide} + /> + </div> + {showDrawingSetTitleDescriptionModal ? ( + <DrawingSetTitleDescription + changeDrawingSetTitle={this.changeDrawingSetTitle} + changeDrawingSetDescription={ + this.changeDrawingSetDescription + } + drawingData={drawingData} + toggleLoginModal={this.toggleLoginModal} + initDrawingListAfterSave={ + this.initDrawingListAfterSave + } + showDraw={this.showDraw} + showDrawingSetTitleDescriptionModal={ + this.showDrawingSetTitleDescriptionModal + } + drawingSetTitle={drawingSetTitle} + drawingSetDescription={drawingSetDescription} + /> + ) : null} + <div + className="legend" + onClick={this.toggleLegend} + onKeyPress={this.toggleLegend} + role="button" + tabIndex="0" + /> + <div + className={ + 'colorList ' + (legendToggle ? 'invisible' : '') + } + > + {Object.keys(constants.newToggleBox).map( + (color, index) => { + return ( + <div className="eachColor" key={index}> + <div className="legendColorBox"> + <div className="colorCircle" /> + </div> + <div className="legendTextBox"> + {color} + </div> + </div> + ); + } + )} + </div> + </div> + <div> + <this.descriptionModal /> + </div> + </div> + ); + } +} + +export default App;
JavaScript
`idle` ์ด๋ฒคํŠธ๊ฐ€ ๋ธŒ๋ผ์šฐ์ € ์ฐฝ ํฌ๊ธฐ๋ฅผ ๋ณ€๊ฒฝํ• ๋•Œ ๋„ˆ๋ฌด ์ž์ฃผ ๋ฐœ์ƒํ•˜๋ฏ€๋กœ debounce ์ฒ˜๋ฆฌํ•˜๋Š”๊ฒŒ ์ข‹๊ฒ ์Œ
@@ -0,0 +1,519 @@ +import React, { Component } from 'react'; +import * as d3 from 'd3'; +import drawData from './Module/loadHandle'; +import FilterContainer from './Components/FilterContainer'; +import LoginModal from './Components/LoginModal'; +import DrawContainer from './Components/DrawContainer'; +import './less/App.less'; +import * as constants from './constants'; +import * as MakeSecret from './Module/simpleEncryption'; +import NearbyFactorDialog from './Components/NearbyFactorDialog'; +import DrawingSetTitleDescription from './Components/drawingSetTitleDescriptionModal'; + +class App extends Component { + constructor(props) { + super(props); + this.bound = undefined; + this.drawList = {}; + this.newToggleBox = constants.newToggleBox; + this.state = { + name: undefined, + drawingData: [], + map: undefined, + showFilter: false, + showModal: false, + activeFilter: 'active', + activeDraw: '', + MyInfoButton: false, + showDraw: false, + factors: [], + NearByFactorItems: [], + showDrawingSetTitleDescriptionModal: false, + drawingSetTitle: null, + drawingSetDescription: null, + descriptionModalState: false, + descriptionValue: '', + descriptionTitle: '', + legendToggle: false + // NearByFilteringItems: [] + }; + } + + componentDidMount = async () => { + const naver = window.naver; + const map = await new naver.maps.Map(d3.select('#map').node(), { + zoomControl: true, + zoomControlOptions: { + style: naver.maps.ZoomControlStyle.SMALL, + position: naver.maps.Position.TOP_RIGHT + }, + logoControl: true, + logoControlOptions: { + position: naver.maps.Position.BOTTOM_RIGHT + }, + scaleControl: true, + scaleControlOptions: { + position: naver.maps.Position.BOTTOM_RIGHT + }, + mapDataControl: true, + mapDataControlOptions: { + position: naver.maps.Position.BOTTOM_LEFT + } + }); + + this.setState({ map }); + this.bound = map.getBounds(); + this.mainPageLoad(map); + naver.maps.Event.addListener(map, 'idle', e => { + const { showDraw } = this.state; + this.bound = map.getBounds(); + // ๊ทธ๋ฆฌ๊ธฐ ๋ชจ๋“œ๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ์—๋งŒ ๋ฐ์ดํ„ฐ๋ฅผ ๋ถˆ๋Ÿฌ์˜ด + if (!showDraw) { + this.mainPageLoad(map); + this.deleteDraw(); + } + }); + const name = JSON.parse(localStorage.getItem('token')); + if (name) { + this.setState({ + name: MakeSecret.Decrypt(name) + }); + } + }; + + isDelete = false; + + handleUserNameOnChange = username => { + this.setState({ name: username }); + }; + + showDrawingSetTitleDescriptionModal = value => { + this.setState({ showDrawingSetTitleDescriptionModal: value }); + }; + + changeDrawingSetTitle = text => { + this.setState({ drawingSetTitle: text }); + }; + + changeDrawingSetDescription = text => { + this.setState({ drawingSetDescription: text }); + }; + + mainPageLoad = map => { + const { name, factors } = this.state; + const bound = this.bound; + const nearbyData = async val => { + await this.setState({ + NearByFactorItems: val + }); + }; + drawData(name, bound, factors, false, this.drawList, map, nearbyData); + }; + + toggleAllDraw = () => { + const { showDraw, map } = this.state; + if (showDraw) { + Object.entries(this.drawList).forEach(([key, value]) => { + value.setMap(null); + delete this.drawList[key]; + }); + this.isDelete = true; + } else { + if (this.isDelete) { + this.mainPageLoad(map); + this.isDelete = false; + } + } + }; + + deleteDraw = () => { + Object.entries(this.drawList).forEach(([key, value]) => { + const startPos = {}; + const endPos = {}; + // reference point + startPos.x = value._lineData[0].coord.x; + startPos.y = value._lineData[0].coord.y; + endPos.x = value._lineData[value._lineData.length - 1].coord.x; + endPos.y = value._lineData[value._lineData.length - 1].coord.y; + + if ( + (startPos.x < this.bound._min._lng - 0.01 + || this.bound._max._lng + 0.01 < startPos.x + || startPos.y < this.bound._min._lat - 0.01 + || this.bound._max._lat + 0.01 < startPos.y) + && (endPos.x < this.bound._min._lng - 0.01 + || this.bound._max._lng + 0.01 < endPos.x + || endPos.y < this.bound._min._lat - 0.01 + || this.bound._max._lat + 0.01 < endPos.y) + ) { + value.setMap(null); + delete this.drawList[key]; + } + }); + }; + + toggleLoginModal = () => { + const { showModal } = this.state; + this.setState({ showModal: !showModal }); + }; + + toggleDraw = () => { + const { showDraw } = this.state; + this.setState({ descriptionModalState: false }); + this.setState({ showDraw: !showDraw }); + }; + + toggleLegend = () => { + const { legendToggle } = this.state; + this.setState({ legendToggle: !legendToggle }); + }; + + showFilter = () => { + const { showFilter, activeFilter } = this.state; + if (activeFilter === 'active') { + this.setState({ + showFilter: !showFilter, + activeFilter: '' + }); + } else { + this.setState({ + showFilter: !showFilter, + activeFilter: 'active' + }); + } + }; + + showDraw = () => { + const { showDraw, drawingData, activeDraw } = this.state; + if (drawingData.length) { + const pressedConfirm = confirm( + '์ €์žฅํ•˜์ง€ ์•Š๊ณ  ๊ทธ๋ฆฌ๊ธฐ ์ฐฝ์„ ๋‹ซ์œผ๋ฉด ๊ทธ๋ฆฐ ์ •๋ณด๋Š” ๋ชจ๋‘ ์‚ฌ๋ผ์ง‘๋‹ˆ๋‹ค!\n๊ทธ๋ž˜๋„ ๊ทธ๋ฆฌ๊ธฐ ์ฐฝ์„ ๋‹ซ์œผ์‹œ๊ฒ ์–ด์š”?' + ); + if (pressedConfirm) { + for (let index = 0; index < drawingData.length; index++) { + drawingData[index].figure.onRemove(); + } + this.setState({ drawingData: [] }); + this.setState({ descriptionModalState: false }); + } else if (!pressedConfirm) { + return; + } + } + + if (activeDraw === 'active') { + this.setState({ + showDraw: !showDraw, + activeDraw: '' + }); + } else { + this.setState({ + showDraw: !showDraw, + activeDraw: 'active' + }); + } + }; + + initDrawingListAfterSave = () => { + this.setState({ drawingData: [] }); + }; + + initUserName = () => { + this.setState({ name: undefined }); + }; + + myInfoToggle = () => { + const { MyInfoButton } = this.state; + this.setState({ MyInfoButton: !MyInfoButton }); + this.factorLoad(null, !MyInfoButton); + }; + + updateDrawingData = (shapeData, order = false, index) => { + const { drawingData } = this.state; + this.setState({ drawingData: [...drawingData, shapeData] }); + if (order) { + const newDrawingData = [...drawingData]; + newDrawingData.splice(index, 1); + this.setState({ drawingData: newDrawingData }); + } + }; + + mainToggle = (stateName, toggle) => { + this.setState({ [stateName]: !toggle }); + }; + + factorLoad = (category, toggle = false) => { + const { name, map } = this.state; + const bound = this.bound; + const factors = []; + let nearbyData; + + // ๊ธฐ์กด ์ง€๋„์— ์žˆ๋˜ ์ •๋ณด๋ฅผ ์ง€์›Œ์คŒ + Object.entries(this.drawList).forEach(([key, value]) => { + value.setMap(null); + delete this.drawList[key]; + }); + // ์œ ์ € ํ˜ธ์žฌ ๋ณด๊ธฐ + if (toggle) { + const toggleObj = {}; + Object.entries(this.newToggleBox).forEach(([key, value]) => { + toggleObj[key] = false; + }); + this.newToggleBox = toggleObj; + } + // ํ•„ํ„ฐ๋ง ํ•˜๊ธฐ + if (category) { + const toggleCategory = { + [category]: !this.newToggleBox[category] + }; + this.newToggleBox = { + ...this.newToggleBox, + ...toggleCategory + }; + Object.entries(this.newToggleBox).forEach(([key, value]) => { + if (value) { + factors.push(key); + } + }); + this.setState({ + factors: factors + }); + nearbyData = async val => { + await this.setState({ + NearByFactorItems: val + }); + }; + } + // TODO: + drawData(name, bound, factors, toggle, this.drawList, map, nearbyData); + }; + + handleChangeDescription = event => { + this.setState({ descriptionValue: event.target.value }); + }; + + handleChangeTitle = event => { + this.setState({ descriptionTitle: event.target.value }); + }; + + descriptionModal = () => { + const { + descriptionModalState, + descriptionValue, + descriptionTitle + } = this.state; + if (descriptionModalState) { + return ( + <div className="descriptionModal"> + <div className="descriptionHeader"> </div> + <textarea + placeholder="์ œ๋ชฉ์„ ์ง€์–ด์ฃผ์„ธ์š”:D" + className="descriptionInputTitle" + type="text" + value={descriptionTitle} + onChange={this.handleChangeTitle} + /> + <textarea + placeholder="ํ˜ธ์žฌ ๋‚ด์šฉ์„ ์ฑ„์›Œ์ฃผ์„ธ์š”:D" + className="descriptionInput" + type="text" + value={descriptionValue} + onChange={this.handleChangeDescription} + /> + <button + className="descriptionCloser" + type="button" + onClick={this.descriptionModalHide} + > + ๋‹ซ๊ธฐ + </button> + <button + className="descriptionSave" + type="button" + onClick={this.descriptionModalSave} + > + ์ €์žฅ + </button> + </div> + ); + } else { + return <div />; + } + }; + + descriptionModalHide = () => { + this.setState({ + descriptionModalState: false, + descriptionValue: '', + descriptionTitle: '' + }); + }; + + descriptionModalSave = () => { + const { descriptionValue, descriptionTitle, drawingData } = this.state; + this.setState({ descriptionModalState: false }); + const arrayOfShapes = drawingData; + arrayOfShapes[arrayOfShapes.length - 1].title = descriptionTitle; + arrayOfShapes[arrayOfShapes.length - 1].value = descriptionValue; + this.setState({ drawingData: arrayOfShapes }); + }; + + descriptionModalShow = () => { + this.setState({ descriptionModalState: true }); + }; + + render() { + const { + map, + name, + drawingData, + showFilter, + showDraw, + showModal, + activeFilter, + activeDraw, + MyInfoButton, + NearByFactorItems, + legendToggle, + showDrawingSetTitleDescriptionModal, + drawingSetTitle, + drawingSetDescription + } = this.state; + + this.toggleAllDraw(); + return ( + <div id="wrapper"> + <div id="map"> + <NearbyFactorDialog + mapLoad={map} + NearByFactorItems={NearByFactorItems} + /> + <div id="loginFavorContainer"> + <div + className="loginFavorBtn" + onClick={this.toggleLoginModal} + onKeyPress={this.toggleLoginModal} + role="button" + tabIndex="0" + > + {`My`} + </div> + <div + className={`loginFavorBtn ${activeFilter}`} + onClick={() => { + if (activeDraw === '') { + this.showFilter(); + } + }} + onKeyPress={() => this.showFilter} + role="button" + tabIndex="0" + > + {`ํ•„ํ„ฐ`} + </div> + <div + className={`loginFavorBtn ${activeDraw}`} + onClick={() => { + if (activeFilter === '') { + this.showDraw(); + this.descriptionModalHide(); + } + }} + onKeyPress={() => this.showDraw} + role="button" + tabIndex="0" + > + {`๊ทธ๋ฆฌ๊ธฐ`} + </div> + </div> + {showModal ? ( + <LoginModal + name={name} + toggleLoginModal={this.toggleLoginModal} + handleUserNameOnChange={this.handleUserNameOnChange} + initUserName={this.initUserName} + /> + ) : null} + <div className={!showFilter ? 'block' : 'none'}> + <FilterContainer + MyInfoButton={MyInfoButton} + myInfoToggle={this.myInfoToggle} + factorLoad={this.factorLoad} + showFilter={this.showFilter} + /> + </div> + <div className={showDraw ? 'block' : 'none'}> + <DrawContainer + handleToggle={this.showDraw} + mapLoad={map} + handleUserNameOnChange={this.handleUserNameOnChange} + drawingData={drawingData} + updateDrawingData={this.updateDrawingData} + toggleLoginModal={this.toggleLoginModal} + NearByFactorItems={NearByFactorItems} + initDrawingListAfterSave={ + this.initDrawingListAfterSave + } + showDraw={this.showDraw} + showDrawingSetTitleDescriptionModal={ + this.showDrawingSetTitleDescriptionModal + } + descriptionModalShow={this.descriptionModalShow} + descriptionModalHide={this.descriptionModalHide} + /> + </div> + {showDrawingSetTitleDescriptionModal ? ( + <DrawingSetTitleDescription + changeDrawingSetTitle={this.changeDrawingSetTitle} + changeDrawingSetDescription={ + this.changeDrawingSetDescription + } + drawingData={drawingData} + toggleLoginModal={this.toggleLoginModal} + initDrawingListAfterSave={ + this.initDrawingListAfterSave + } + showDraw={this.showDraw} + showDrawingSetTitleDescriptionModal={ + this.showDrawingSetTitleDescriptionModal + } + drawingSetTitle={drawingSetTitle} + drawingSetDescription={drawingSetDescription} + /> + ) : null} + <div + className="legend" + onClick={this.toggleLegend} + onKeyPress={this.toggleLegend} + role="button" + tabIndex="0" + /> + <div + className={ + 'colorList ' + (legendToggle ? 'invisible' : '') + } + > + {Object.keys(constants.newToggleBox).map( + (color, index) => { + return ( + <div className="eachColor" key={index}> + <div className="legendColorBox"> + <div className="colorCircle" /> + </div> + <div className="legendTextBox"> + {color} + </div> + </div> + ); + } + )} + </div> + </div> + <div> + <this.descriptionModal /> + </div> + </div> + ); + } +} + +export default App;
JavaScript
์ž…๋ ฅ๊ฐ’๋„ ์—†๊ณ , ๋ฆฌํ„ด๊ฐ’๋„ ๊ณ ์ •๊ฐ’์ธ๋ฐ ํ•จ์ˆ˜๋กœ ๋งŒ๋“ค์–ด์„œ ๋ฐ˜ํ™˜ํ•  ์ด์œ ๊ฐ€ ์—†์–ด๋ณด์ž„.
@@ -0,0 +1,519 @@ +import React, { Component } from 'react'; +import * as d3 from 'd3'; +import drawData from './Module/loadHandle'; +import FilterContainer from './Components/FilterContainer'; +import LoginModal from './Components/LoginModal'; +import DrawContainer from './Components/DrawContainer'; +import './less/App.less'; +import * as constants from './constants'; +import * as MakeSecret from './Module/simpleEncryption'; +import NearbyFactorDialog from './Components/NearbyFactorDialog'; +import DrawingSetTitleDescription from './Components/drawingSetTitleDescriptionModal'; + +class App extends Component { + constructor(props) { + super(props); + this.bound = undefined; + this.drawList = {}; + this.newToggleBox = constants.newToggleBox; + this.state = { + name: undefined, + drawingData: [], + map: undefined, + showFilter: false, + showModal: false, + activeFilter: 'active', + activeDraw: '', + MyInfoButton: false, + showDraw: false, + factors: [], + NearByFactorItems: [], + showDrawingSetTitleDescriptionModal: false, + drawingSetTitle: null, + drawingSetDescription: null, + descriptionModalState: false, + descriptionValue: '', + descriptionTitle: '', + legendToggle: false + // NearByFilteringItems: [] + }; + } + + componentDidMount = async () => { + const naver = window.naver; + const map = await new naver.maps.Map(d3.select('#map').node(), { + zoomControl: true, + zoomControlOptions: { + style: naver.maps.ZoomControlStyle.SMALL, + position: naver.maps.Position.TOP_RIGHT + }, + logoControl: true, + logoControlOptions: { + position: naver.maps.Position.BOTTOM_RIGHT + }, + scaleControl: true, + scaleControlOptions: { + position: naver.maps.Position.BOTTOM_RIGHT + }, + mapDataControl: true, + mapDataControlOptions: { + position: naver.maps.Position.BOTTOM_LEFT + } + }); + + this.setState({ map }); + this.bound = map.getBounds(); + this.mainPageLoad(map); + naver.maps.Event.addListener(map, 'idle', e => { + const { showDraw } = this.state; + this.bound = map.getBounds(); + // ๊ทธ๋ฆฌ๊ธฐ ๋ชจ๋“œ๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ์—๋งŒ ๋ฐ์ดํ„ฐ๋ฅผ ๋ถˆ๋Ÿฌ์˜ด + if (!showDraw) { + this.mainPageLoad(map); + this.deleteDraw(); + } + }); + const name = JSON.parse(localStorage.getItem('token')); + if (name) { + this.setState({ + name: MakeSecret.Decrypt(name) + }); + } + }; + + isDelete = false; + + handleUserNameOnChange = username => { + this.setState({ name: username }); + }; + + showDrawingSetTitleDescriptionModal = value => { + this.setState({ showDrawingSetTitleDescriptionModal: value }); + }; + + changeDrawingSetTitle = text => { + this.setState({ drawingSetTitle: text }); + }; + + changeDrawingSetDescription = text => { + this.setState({ drawingSetDescription: text }); + }; + + mainPageLoad = map => { + const { name, factors } = this.state; + const bound = this.bound; + const nearbyData = async val => { + await this.setState({ + NearByFactorItems: val + }); + }; + drawData(name, bound, factors, false, this.drawList, map, nearbyData); + }; + + toggleAllDraw = () => { + const { showDraw, map } = this.state; + if (showDraw) { + Object.entries(this.drawList).forEach(([key, value]) => { + value.setMap(null); + delete this.drawList[key]; + }); + this.isDelete = true; + } else { + if (this.isDelete) { + this.mainPageLoad(map); + this.isDelete = false; + } + } + }; + + deleteDraw = () => { + Object.entries(this.drawList).forEach(([key, value]) => { + const startPos = {}; + const endPos = {}; + // reference point + startPos.x = value._lineData[0].coord.x; + startPos.y = value._lineData[0].coord.y; + endPos.x = value._lineData[value._lineData.length - 1].coord.x; + endPos.y = value._lineData[value._lineData.length - 1].coord.y; + + if ( + (startPos.x < this.bound._min._lng - 0.01 + || this.bound._max._lng + 0.01 < startPos.x + || startPos.y < this.bound._min._lat - 0.01 + || this.bound._max._lat + 0.01 < startPos.y) + && (endPos.x < this.bound._min._lng - 0.01 + || this.bound._max._lng + 0.01 < endPos.x + || endPos.y < this.bound._min._lat - 0.01 + || this.bound._max._lat + 0.01 < endPos.y) + ) { + value.setMap(null); + delete this.drawList[key]; + } + }); + }; + + toggleLoginModal = () => { + const { showModal } = this.state; + this.setState({ showModal: !showModal }); + }; + + toggleDraw = () => { + const { showDraw } = this.state; + this.setState({ descriptionModalState: false }); + this.setState({ showDraw: !showDraw }); + }; + + toggleLegend = () => { + const { legendToggle } = this.state; + this.setState({ legendToggle: !legendToggle }); + }; + + showFilter = () => { + const { showFilter, activeFilter } = this.state; + if (activeFilter === 'active') { + this.setState({ + showFilter: !showFilter, + activeFilter: '' + }); + } else { + this.setState({ + showFilter: !showFilter, + activeFilter: 'active' + }); + } + }; + + showDraw = () => { + const { showDraw, drawingData, activeDraw } = this.state; + if (drawingData.length) { + const pressedConfirm = confirm( + '์ €์žฅํ•˜์ง€ ์•Š๊ณ  ๊ทธ๋ฆฌ๊ธฐ ์ฐฝ์„ ๋‹ซ์œผ๋ฉด ๊ทธ๋ฆฐ ์ •๋ณด๋Š” ๋ชจ๋‘ ์‚ฌ๋ผ์ง‘๋‹ˆ๋‹ค!\n๊ทธ๋ž˜๋„ ๊ทธ๋ฆฌ๊ธฐ ์ฐฝ์„ ๋‹ซ์œผ์‹œ๊ฒ ์–ด์š”?' + ); + if (pressedConfirm) { + for (let index = 0; index < drawingData.length; index++) { + drawingData[index].figure.onRemove(); + } + this.setState({ drawingData: [] }); + this.setState({ descriptionModalState: false }); + } else if (!pressedConfirm) { + return; + } + } + + if (activeDraw === 'active') { + this.setState({ + showDraw: !showDraw, + activeDraw: '' + }); + } else { + this.setState({ + showDraw: !showDraw, + activeDraw: 'active' + }); + } + }; + + initDrawingListAfterSave = () => { + this.setState({ drawingData: [] }); + }; + + initUserName = () => { + this.setState({ name: undefined }); + }; + + myInfoToggle = () => { + const { MyInfoButton } = this.state; + this.setState({ MyInfoButton: !MyInfoButton }); + this.factorLoad(null, !MyInfoButton); + }; + + updateDrawingData = (shapeData, order = false, index) => { + const { drawingData } = this.state; + this.setState({ drawingData: [...drawingData, shapeData] }); + if (order) { + const newDrawingData = [...drawingData]; + newDrawingData.splice(index, 1); + this.setState({ drawingData: newDrawingData }); + } + }; + + mainToggle = (stateName, toggle) => { + this.setState({ [stateName]: !toggle }); + }; + + factorLoad = (category, toggle = false) => { + const { name, map } = this.state; + const bound = this.bound; + const factors = []; + let nearbyData; + + // ๊ธฐ์กด ์ง€๋„์— ์žˆ๋˜ ์ •๋ณด๋ฅผ ์ง€์›Œ์คŒ + Object.entries(this.drawList).forEach(([key, value]) => { + value.setMap(null); + delete this.drawList[key]; + }); + // ์œ ์ € ํ˜ธ์žฌ ๋ณด๊ธฐ + if (toggle) { + const toggleObj = {}; + Object.entries(this.newToggleBox).forEach(([key, value]) => { + toggleObj[key] = false; + }); + this.newToggleBox = toggleObj; + } + // ํ•„ํ„ฐ๋ง ํ•˜๊ธฐ + if (category) { + const toggleCategory = { + [category]: !this.newToggleBox[category] + }; + this.newToggleBox = { + ...this.newToggleBox, + ...toggleCategory + }; + Object.entries(this.newToggleBox).forEach(([key, value]) => { + if (value) { + factors.push(key); + } + }); + this.setState({ + factors: factors + }); + nearbyData = async val => { + await this.setState({ + NearByFactorItems: val + }); + }; + } + // TODO: + drawData(name, bound, factors, toggle, this.drawList, map, nearbyData); + }; + + handleChangeDescription = event => { + this.setState({ descriptionValue: event.target.value }); + }; + + handleChangeTitle = event => { + this.setState({ descriptionTitle: event.target.value }); + }; + + descriptionModal = () => { + const { + descriptionModalState, + descriptionValue, + descriptionTitle + } = this.state; + if (descriptionModalState) { + return ( + <div className="descriptionModal"> + <div className="descriptionHeader"> </div> + <textarea + placeholder="์ œ๋ชฉ์„ ์ง€์–ด์ฃผ์„ธ์š”:D" + className="descriptionInputTitle" + type="text" + value={descriptionTitle} + onChange={this.handleChangeTitle} + /> + <textarea + placeholder="ํ˜ธ์žฌ ๋‚ด์šฉ์„ ์ฑ„์›Œ์ฃผ์„ธ์š”:D" + className="descriptionInput" + type="text" + value={descriptionValue} + onChange={this.handleChangeDescription} + /> + <button + className="descriptionCloser" + type="button" + onClick={this.descriptionModalHide} + > + ๋‹ซ๊ธฐ + </button> + <button + className="descriptionSave" + type="button" + onClick={this.descriptionModalSave} + > + ์ €์žฅ + </button> + </div> + ); + } else { + return <div />; + } + }; + + descriptionModalHide = () => { + this.setState({ + descriptionModalState: false, + descriptionValue: '', + descriptionTitle: '' + }); + }; + + descriptionModalSave = () => { + const { descriptionValue, descriptionTitle, drawingData } = this.state; + this.setState({ descriptionModalState: false }); + const arrayOfShapes = drawingData; + arrayOfShapes[arrayOfShapes.length - 1].title = descriptionTitle; + arrayOfShapes[arrayOfShapes.length - 1].value = descriptionValue; + this.setState({ drawingData: arrayOfShapes }); + }; + + descriptionModalShow = () => { + this.setState({ descriptionModalState: true }); + }; + + render() { + const { + map, + name, + drawingData, + showFilter, + showDraw, + showModal, + activeFilter, + activeDraw, + MyInfoButton, + NearByFactorItems, + legendToggle, + showDrawingSetTitleDescriptionModal, + drawingSetTitle, + drawingSetDescription + } = this.state; + + this.toggleAllDraw(); + return ( + <div id="wrapper"> + <div id="map"> + <NearbyFactorDialog + mapLoad={map} + NearByFactorItems={NearByFactorItems} + /> + <div id="loginFavorContainer"> + <div + className="loginFavorBtn" + onClick={this.toggleLoginModal} + onKeyPress={this.toggleLoginModal} + role="button" + tabIndex="0" + > + {`My`} + </div> + <div + className={`loginFavorBtn ${activeFilter}`} + onClick={() => { + if (activeDraw === '') { + this.showFilter(); + } + }} + onKeyPress={() => this.showFilter} + role="button" + tabIndex="0" + > + {`ํ•„ํ„ฐ`} + </div> + <div + className={`loginFavorBtn ${activeDraw}`} + onClick={() => { + if (activeFilter === '') { + this.showDraw(); + this.descriptionModalHide(); + } + }} + onKeyPress={() => this.showDraw} + role="button" + tabIndex="0" + > + {`๊ทธ๋ฆฌ๊ธฐ`} + </div> + </div> + {showModal ? ( + <LoginModal + name={name} + toggleLoginModal={this.toggleLoginModal} + handleUserNameOnChange={this.handleUserNameOnChange} + initUserName={this.initUserName} + /> + ) : null} + <div className={!showFilter ? 'block' : 'none'}> + <FilterContainer + MyInfoButton={MyInfoButton} + myInfoToggle={this.myInfoToggle} + factorLoad={this.factorLoad} + showFilter={this.showFilter} + /> + </div> + <div className={showDraw ? 'block' : 'none'}> + <DrawContainer + handleToggle={this.showDraw} + mapLoad={map} + handleUserNameOnChange={this.handleUserNameOnChange} + drawingData={drawingData} + updateDrawingData={this.updateDrawingData} + toggleLoginModal={this.toggleLoginModal} + NearByFactorItems={NearByFactorItems} + initDrawingListAfterSave={ + this.initDrawingListAfterSave + } + showDraw={this.showDraw} + showDrawingSetTitleDescriptionModal={ + this.showDrawingSetTitleDescriptionModal + } + descriptionModalShow={this.descriptionModalShow} + descriptionModalHide={this.descriptionModalHide} + /> + </div> + {showDrawingSetTitleDescriptionModal ? ( + <DrawingSetTitleDescription + changeDrawingSetTitle={this.changeDrawingSetTitle} + changeDrawingSetDescription={ + this.changeDrawingSetDescription + } + drawingData={drawingData} + toggleLoginModal={this.toggleLoginModal} + initDrawingListAfterSave={ + this.initDrawingListAfterSave + } + showDraw={this.showDraw} + showDrawingSetTitleDescriptionModal={ + this.showDrawingSetTitleDescriptionModal + } + drawingSetTitle={drawingSetTitle} + drawingSetDescription={drawingSetDescription} + /> + ) : null} + <div + className="legend" + onClick={this.toggleLegend} + onKeyPress={this.toggleLegend} + role="button" + tabIndex="0" + /> + <div + className={ + 'colorList ' + (legendToggle ? 'invisible' : '') + } + > + {Object.keys(constants.newToggleBox).map( + (color, index) => { + return ( + <div className="eachColor" key={index}> + <div className="legendColorBox"> + <div className="colorCircle" /> + </div> + <div className="legendTextBox"> + {color} + </div> + </div> + ); + } + )} + </div> + </div> + <div> + <this.descriptionModal /> + </div> + </div> + ); + } +} + +export default App;
JavaScript
`mainPageLoad`์—์„œ ๋ฐ์ดํ„ฐ ๋กœ๋”ฉ์ด ๋๋‚˜๋Š” ์‹œ์ ์— ๋งž๊ฒŒ ๊ธฐ์กดํ•€์„ ์ œ๊ฑฐํ•˜๋Š” `DataDelete`๋ฅผ ์ฒ˜๋ฆฌํ•ด์•ผํ• ๋“ฏ ํ•จ.
@@ -0,0 +1,519 @@ +import React, { Component } from 'react'; +import * as d3 from 'd3'; +import drawData from './Module/loadHandle'; +import FilterContainer from './Components/FilterContainer'; +import LoginModal from './Components/LoginModal'; +import DrawContainer from './Components/DrawContainer'; +import './less/App.less'; +import * as constants from './constants'; +import * as MakeSecret from './Module/simpleEncryption'; +import NearbyFactorDialog from './Components/NearbyFactorDialog'; +import DrawingSetTitleDescription from './Components/drawingSetTitleDescriptionModal'; + +class App extends Component { + constructor(props) { + super(props); + this.bound = undefined; + this.drawList = {}; + this.newToggleBox = constants.newToggleBox; + this.state = { + name: undefined, + drawingData: [], + map: undefined, + showFilter: false, + showModal: false, + activeFilter: 'active', + activeDraw: '', + MyInfoButton: false, + showDraw: false, + factors: [], + NearByFactorItems: [], + showDrawingSetTitleDescriptionModal: false, + drawingSetTitle: null, + drawingSetDescription: null, + descriptionModalState: false, + descriptionValue: '', + descriptionTitle: '', + legendToggle: false + // NearByFilteringItems: [] + }; + } + + componentDidMount = async () => { + const naver = window.naver; + const map = await new naver.maps.Map(d3.select('#map').node(), { + zoomControl: true, + zoomControlOptions: { + style: naver.maps.ZoomControlStyle.SMALL, + position: naver.maps.Position.TOP_RIGHT + }, + logoControl: true, + logoControlOptions: { + position: naver.maps.Position.BOTTOM_RIGHT + }, + scaleControl: true, + scaleControlOptions: { + position: naver.maps.Position.BOTTOM_RIGHT + }, + mapDataControl: true, + mapDataControlOptions: { + position: naver.maps.Position.BOTTOM_LEFT + } + }); + + this.setState({ map }); + this.bound = map.getBounds(); + this.mainPageLoad(map); + naver.maps.Event.addListener(map, 'idle', e => { + const { showDraw } = this.state; + this.bound = map.getBounds(); + // ๊ทธ๋ฆฌ๊ธฐ ๋ชจ๋“œ๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ์—๋งŒ ๋ฐ์ดํ„ฐ๋ฅผ ๋ถˆ๋Ÿฌ์˜ด + if (!showDraw) { + this.mainPageLoad(map); + this.deleteDraw(); + } + }); + const name = JSON.parse(localStorage.getItem('token')); + if (name) { + this.setState({ + name: MakeSecret.Decrypt(name) + }); + } + }; + + isDelete = false; + + handleUserNameOnChange = username => { + this.setState({ name: username }); + }; + + showDrawingSetTitleDescriptionModal = value => { + this.setState({ showDrawingSetTitleDescriptionModal: value }); + }; + + changeDrawingSetTitle = text => { + this.setState({ drawingSetTitle: text }); + }; + + changeDrawingSetDescription = text => { + this.setState({ drawingSetDescription: text }); + }; + + mainPageLoad = map => { + const { name, factors } = this.state; + const bound = this.bound; + const nearbyData = async val => { + await this.setState({ + NearByFactorItems: val + }); + }; + drawData(name, bound, factors, false, this.drawList, map, nearbyData); + }; + + toggleAllDraw = () => { + const { showDraw, map } = this.state; + if (showDraw) { + Object.entries(this.drawList).forEach(([key, value]) => { + value.setMap(null); + delete this.drawList[key]; + }); + this.isDelete = true; + } else { + if (this.isDelete) { + this.mainPageLoad(map); + this.isDelete = false; + } + } + }; + + deleteDraw = () => { + Object.entries(this.drawList).forEach(([key, value]) => { + const startPos = {}; + const endPos = {}; + // reference point + startPos.x = value._lineData[0].coord.x; + startPos.y = value._lineData[0].coord.y; + endPos.x = value._lineData[value._lineData.length - 1].coord.x; + endPos.y = value._lineData[value._lineData.length - 1].coord.y; + + if ( + (startPos.x < this.bound._min._lng - 0.01 + || this.bound._max._lng + 0.01 < startPos.x + || startPos.y < this.bound._min._lat - 0.01 + || this.bound._max._lat + 0.01 < startPos.y) + && (endPos.x < this.bound._min._lng - 0.01 + || this.bound._max._lng + 0.01 < endPos.x + || endPos.y < this.bound._min._lat - 0.01 + || this.bound._max._lat + 0.01 < endPos.y) + ) { + value.setMap(null); + delete this.drawList[key]; + } + }); + }; + + toggleLoginModal = () => { + const { showModal } = this.state; + this.setState({ showModal: !showModal }); + }; + + toggleDraw = () => { + const { showDraw } = this.state; + this.setState({ descriptionModalState: false }); + this.setState({ showDraw: !showDraw }); + }; + + toggleLegend = () => { + const { legendToggle } = this.state; + this.setState({ legendToggle: !legendToggle }); + }; + + showFilter = () => { + const { showFilter, activeFilter } = this.state; + if (activeFilter === 'active') { + this.setState({ + showFilter: !showFilter, + activeFilter: '' + }); + } else { + this.setState({ + showFilter: !showFilter, + activeFilter: 'active' + }); + } + }; + + showDraw = () => { + const { showDraw, drawingData, activeDraw } = this.state; + if (drawingData.length) { + const pressedConfirm = confirm( + '์ €์žฅํ•˜์ง€ ์•Š๊ณ  ๊ทธ๋ฆฌ๊ธฐ ์ฐฝ์„ ๋‹ซ์œผ๋ฉด ๊ทธ๋ฆฐ ์ •๋ณด๋Š” ๋ชจ๋‘ ์‚ฌ๋ผ์ง‘๋‹ˆ๋‹ค!\n๊ทธ๋ž˜๋„ ๊ทธ๋ฆฌ๊ธฐ ์ฐฝ์„ ๋‹ซ์œผ์‹œ๊ฒ ์–ด์š”?' + ); + if (pressedConfirm) { + for (let index = 0; index < drawingData.length; index++) { + drawingData[index].figure.onRemove(); + } + this.setState({ drawingData: [] }); + this.setState({ descriptionModalState: false }); + } else if (!pressedConfirm) { + return; + } + } + + if (activeDraw === 'active') { + this.setState({ + showDraw: !showDraw, + activeDraw: '' + }); + } else { + this.setState({ + showDraw: !showDraw, + activeDraw: 'active' + }); + } + }; + + initDrawingListAfterSave = () => { + this.setState({ drawingData: [] }); + }; + + initUserName = () => { + this.setState({ name: undefined }); + }; + + myInfoToggle = () => { + const { MyInfoButton } = this.state; + this.setState({ MyInfoButton: !MyInfoButton }); + this.factorLoad(null, !MyInfoButton); + }; + + updateDrawingData = (shapeData, order = false, index) => { + const { drawingData } = this.state; + this.setState({ drawingData: [...drawingData, shapeData] }); + if (order) { + const newDrawingData = [...drawingData]; + newDrawingData.splice(index, 1); + this.setState({ drawingData: newDrawingData }); + } + }; + + mainToggle = (stateName, toggle) => { + this.setState({ [stateName]: !toggle }); + }; + + factorLoad = (category, toggle = false) => { + const { name, map } = this.state; + const bound = this.bound; + const factors = []; + let nearbyData; + + // ๊ธฐ์กด ์ง€๋„์— ์žˆ๋˜ ์ •๋ณด๋ฅผ ์ง€์›Œ์คŒ + Object.entries(this.drawList).forEach(([key, value]) => { + value.setMap(null); + delete this.drawList[key]; + }); + // ์œ ์ € ํ˜ธ์žฌ ๋ณด๊ธฐ + if (toggle) { + const toggleObj = {}; + Object.entries(this.newToggleBox).forEach(([key, value]) => { + toggleObj[key] = false; + }); + this.newToggleBox = toggleObj; + } + // ํ•„ํ„ฐ๋ง ํ•˜๊ธฐ + if (category) { + const toggleCategory = { + [category]: !this.newToggleBox[category] + }; + this.newToggleBox = { + ...this.newToggleBox, + ...toggleCategory + }; + Object.entries(this.newToggleBox).forEach(([key, value]) => { + if (value) { + factors.push(key); + } + }); + this.setState({ + factors: factors + }); + nearbyData = async val => { + await this.setState({ + NearByFactorItems: val + }); + }; + } + // TODO: + drawData(name, bound, factors, toggle, this.drawList, map, nearbyData); + }; + + handleChangeDescription = event => { + this.setState({ descriptionValue: event.target.value }); + }; + + handleChangeTitle = event => { + this.setState({ descriptionTitle: event.target.value }); + }; + + descriptionModal = () => { + const { + descriptionModalState, + descriptionValue, + descriptionTitle + } = this.state; + if (descriptionModalState) { + return ( + <div className="descriptionModal"> + <div className="descriptionHeader"> </div> + <textarea + placeholder="์ œ๋ชฉ์„ ์ง€์–ด์ฃผ์„ธ์š”:D" + className="descriptionInputTitle" + type="text" + value={descriptionTitle} + onChange={this.handleChangeTitle} + /> + <textarea + placeholder="ํ˜ธ์žฌ ๋‚ด์šฉ์„ ์ฑ„์›Œ์ฃผ์„ธ์š”:D" + className="descriptionInput" + type="text" + value={descriptionValue} + onChange={this.handleChangeDescription} + /> + <button + className="descriptionCloser" + type="button" + onClick={this.descriptionModalHide} + > + ๋‹ซ๊ธฐ + </button> + <button + className="descriptionSave" + type="button" + onClick={this.descriptionModalSave} + > + ์ €์žฅ + </button> + </div> + ); + } else { + return <div />; + } + }; + + descriptionModalHide = () => { + this.setState({ + descriptionModalState: false, + descriptionValue: '', + descriptionTitle: '' + }); + }; + + descriptionModalSave = () => { + const { descriptionValue, descriptionTitle, drawingData } = this.state; + this.setState({ descriptionModalState: false }); + const arrayOfShapes = drawingData; + arrayOfShapes[arrayOfShapes.length - 1].title = descriptionTitle; + arrayOfShapes[arrayOfShapes.length - 1].value = descriptionValue; + this.setState({ drawingData: arrayOfShapes }); + }; + + descriptionModalShow = () => { + this.setState({ descriptionModalState: true }); + }; + + render() { + const { + map, + name, + drawingData, + showFilter, + showDraw, + showModal, + activeFilter, + activeDraw, + MyInfoButton, + NearByFactorItems, + legendToggle, + showDrawingSetTitleDescriptionModal, + drawingSetTitle, + drawingSetDescription + } = this.state; + + this.toggleAllDraw(); + return ( + <div id="wrapper"> + <div id="map"> + <NearbyFactorDialog + mapLoad={map} + NearByFactorItems={NearByFactorItems} + /> + <div id="loginFavorContainer"> + <div + className="loginFavorBtn" + onClick={this.toggleLoginModal} + onKeyPress={this.toggleLoginModal} + role="button" + tabIndex="0" + > + {`My`} + </div> + <div + className={`loginFavorBtn ${activeFilter}`} + onClick={() => { + if (activeDraw === '') { + this.showFilter(); + } + }} + onKeyPress={() => this.showFilter} + role="button" + tabIndex="0" + > + {`ํ•„ํ„ฐ`} + </div> + <div + className={`loginFavorBtn ${activeDraw}`} + onClick={() => { + if (activeFilter === '') { + this.showDraw(); + this.descriptionModalHide(); + } + }} + onKeyPress={() => this.showDraw} + role="button" + tabIndex="0" + > + {`๊ทธ๋ฆฌ๊ธฐ`} + </div> + </div> + {showModal ? ( + <LoginModal + name={name} + toggleLoginModal={this.toggleLoginModal} + handleUserNameOnChange={this.handleUserNameOnChange} + initUserName={this.initUserName} + /> + ) : null} + <div className={!showFilter ? 'block' : 'none'}> + <FilterContainer + MyInfoButton={MyInfoButton} + myInfoToggle={this.myInfoToggle} + factorLoad={this.factorLoad} + showFilter={this.showFilter} + /> + </div> + <div className={showDraw ? 'block' : 'none'}> + <DrawContainer + handleToggle={this.showDraw} + mapLoad={map} + handleUserNameOnChange={this.handleUserNameOnChange} + drawingData={drawingData} + updateDrawingData={this.updateDrawingData} + toggleLoginModal={this.toggleLoginModal} + NearByFactorItems={NearByFactorItems} + initDrawingListAfterSave={ + this.initDrawingListAfterSave + } + showDraw={this.showDraw} + showDrawingSetTitleDescriptionModal={ + this.showDrawingSetTitleDescriptionModal + } + descriptionModalShow={this.descriptionModalShow} + descriptionModalHide={this.descriptionModalHide} + /> + </div> + {showDrawingSetTitleDescriptionModal ? ( + <DrawingSetTitleDescription + changeDrawingSetTitle={this.changeDrawingSetTitle} + changeDrawingSetDescription={ + this.changeDrawingSetDescription + } + drawingData={drawingData} + toggleLoginModal={this.toggleLoginModal} + initDrawingListAfterSave={ + this.initDrawingListAfterSave + } + showDraw={this.showDraw} + showDrawingSetTitleDescriptionModal={ + this.showDrawingSetTitleDescriptionModal + } + drawingSetTitle={drawingSetTitle} + drawingSetDescription={drawingSetDescription} + /> + ) : null} + <div + className="legend" + onClick={this.toggleLegend} + onKeyPress={this.toggleLegend} + role="button" + tabIndex="0" + /> + <div + className={ + 'colorList ' + (legendToggle ? 'invisible' : '') + } + > + {Object.keys(constants.newToggleBox).map( + (color, index) => { + return ( + <div className="eachColor" key={index}> + <div className="legendColorBox"> + <div className="colorCircle" /> + </div> + <div className="legendTextBox"> + {color} + </div> + </div> + ); + } + )} + </div> + </div> + <div> + <this.descriptionModal /> + </div> + </div> + ); + } +} + +export default App;
JavaScript
์ดํ›„์— ```suggestion } else { this.drawList[el.id].setMap(null); delete this.drawList[el.id]; } ``` ์ด๋ ‡๊ฒŒ ํ•ด์•ผํ•˜์ง€ ์•Š์„๊นŒ?
@@ -0,0 +1,519 @@ +import React, { Component } from 'react'; +import * as d3 from 'd3'; +import drawData from './Module/loadHandle'; +import FilterContainer from './Components/FilterContainer'; +import LoginModal from './Components/LoginModal'; +import DrawContainer from './Components/DrawContainer'; +import './less/App.less'; +import * as constants from './constants'; +import * as MakeSecret from './Module/simpleEncryption'; +import NearbyFactorDialog from './Components/NearbyFactorDialog'; +import DrawingSetTitleDescription from './Components/drawingSetTitleDescriptionModal'; + +class App extends Component { + constructor(props) { + super(props); + this.bound = undefined; + this.drawList = {}; + this.newToggleBox = constants.newToggleBox; + this.state = { + name: undefined, + drawingData: [], + map: undefined, + showFilter: false, + showModal: false, + activeFilter: 'active', + activeDraw: '', + MyInfoButton: false, + showDraw: false, + factors: [], + NearByFactorItems: [], + showDrawingSetTitleDescriptionModal: false, + drawingSetTitle: null, + drawingSetDescription: null, + descriptionModalState: false, + descriptionValue: '', + descriptionTitle: '', + legendToggle: false + // NearByFilteringItems: [] + }; + } + + componentDidMount = async () => { + const naver = window.naver; + const map = await new naver.maps.Map(d3.select('#map').node(), { + zoomControl: true, + zoomControlOptions: { + style: naver.maps.ZoomControlStyle.SMALL, + position: naver.maps.Position.TOP_RIGHT + }, + logoControl: true, + logoControlOptions: { + position: naver.maps.Position.BOTTOM_RIGHT + }, + scaleControl: true, + scaleControlOptions: { + position: naver.maps.Position.BOTTOM_RIGHT + }, + mapDataControl: true, + mapDataControlOptions: { + position: naver.maps.Position.BOTTOM_LEFT + } + }); + + this.setState({ map }); + this.bound = map.getBounds(); + this.mainPageLoad(map); + naver.maps.Event.addListener(map, 'idle', e => { + const { showDraw } = this.state; + this.bound = map.getBounds(); + // ๊ทธ๋ฆฌ๊ธฐ ๋ชจ๋“œ๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ์—๋งŒ ๋ฐ์ดํ„ฐ๋ฅผ ๋ถˆ๋Ÿฌ์˜ด + if (!showDraw) { + this.mainPageLoad(map); + this.deleteDraw(); + } + }); + const name = JSON.parse(localStorage.getItem('token')); + if (name) { + this.setState({ + name: MakeSecret.Decrypt(name) + }); + } + }; + + isDelete = false; + + handleUserNameOnChange = username => { + this.setState({ name: username }); + }; + + showDrawingSetTitleDescriptionModal = value => { + this.setState({ showDrawingSetTitleDescriptionModal: value }); + }; + + changeDrawingSetTitle = text => { + this.setState({ drawingSetTitle: text }); + }; + + changeDrawingSetDescription = text => { + this.setState({ drawingSetDescription: text }); + }; + + mainPageLoad = map => { + const { name, factors } = this.state; + const bound = this.bound; + const nearbyData = async val => { + await this.setState({ + NearByFactorItems: val + }); + }; + drawData(name, bound, factors, false, this.drawList, map, nearbyData); + }; + + toggleAllDraw = () => { + const { showDraw, map } = this.state; + if (showDraw) { + Object.entries(this.drawList).forEach(([key, value]) => { + value.setMap(null); + delete this.drawList[key]; + }); + this.isDelete = true; + } else { + if (this.isDelete) { + this.mainPageLoad(map); + this.isDelete = false; + } + } + }; + + deleteDraw = () => { + Object.entries(this.drawList).forEach(([key, value]) => { + const startPos = {}; + const endPos = {}; + // reference point + startPos.x = value._lineData[0].coord.x; + startPos.y = value._lineData[0].coord.y; + endPos.x = value._lineData[value._lineData.length - 1].coord.x; + endPos.y = value._lineData[value._lineData.length - 1].coord.y; + + if ( + (startPos.x < this.bound._min._lng - 0.01 + || this.bound._max._lng + 0.01 < startPos.x + || startPos.y < this.bound._min._lat - 0.01 + || this.bound._max._lat + 0.01 < startPos.y) + && (endPos.x < this.bound._min._lng - 0.01 + || this.bound._max._lng + 0.01 < endPos.x + || endPos.y < this.bound._min._lat - 0.01 + || this.bound._max._lat + 0.01 < endPos.y) + ) { + value.setMap(null); + delete this.drawList[key]; + } + }); + }; + + toggleLoginModal = () => { + const { showModal } = this.state; + this.setState({ showModal: !showModal }); + }; + + toggleDraw = () => { + const { showDraw } = this.state; + this.setState({ descriptionModalState: false }); + this.setState({ showDraw: !showDraw }); + }; + + toggleLegend = () => { + const { legendToggle } = this.state; + this.setState({ legendToggle: !legendToggle }); + }; + + showFilter = () => { + const { showFilter, activeFilter } = this.state; + if (activeFilter === 'active') { + this.setState({ + showFilter: !showFilter, + activeFilter: '' + }); + } else { + this.setState({ + showFilter: !showFilter, + activeFilter: 'active' + }); + } + }; + + showDraw = () => { + const { showDraw, drawingData, activeDraw } = this.state; + if (drawingData.length) { + const pressedConfirm = confirm( + '์ €์žฅํ•˜์ง€ ์•Š๊ณ  ๊ทธ๋ฆฌ๊ธฐ ์ฐฝ์„ ๋‹ซ์œผ๋ฉด ๊ทธ๋ฆฐ ์ •๋ณด๋Š” ๋ชจ๋‘ ์‚ฌ๋ผ์ง‘๋‹ˆ๋‹ค!\n๊ทธ๋ž˜๋„ ๊ทธ๋ฆฌ๊ธฐ ์ฐฝ์„ ๋‹ซ์œผ์‹œ๊ฒ ์–ด์š”?' + ); + if (pressedConfirm) { + for (let index = 0; index < drawingData.length; index++) { + drawingData[index].figure.onRemove(); + } + this.setState({ drawingData: [] }); + this.setState({ descriptionModalState: false }); + } else if (!pressedConfirm) { + return; + } + } + + if (activeDraw === 'active') { + this.setState({ + showDraw: !showDraw, + activeDraw: '' + }); + } else { + this.setState({ + showDraw: !showDraw, + activeDraw: 'active' + }); + } + }; + + initDrawingListAfterSave = () => { + this.setState({ drawingData: [] }); + }; + + initUserName = () => { + this.setState({ name: undefined }); + }; + + myInfoToggle = () => { + const { MyInfoButton } = this.state; + this.setState({ MyInfoButton: !MyInfoButton }); + this.factorLoad(null, !MyInfoButton); + }; + + updateDrawingData = (shapeData, order = false, index) => { + const { drawingData } = this.state; + this.setState({ drawingData: [...drawingData, shapeData] }); + if (order) { + const newDrawingData = [...drawingData]; + newDrawingData.splice(index, 1); + this.setState({ drawingData: newDrawingData }); + } + }; + + mainToggle = (stateName, toggle) => { + this.setState({ [stateName]: !toggle }); + }; + + factorLoad = (category, toggle = false) => { + const { name, map } = this.state; + const bound = this.bound; + const factors = []; + let nearbyData; + + // ๊ธฐ์กด ์ง€๋„์— ์žˆ๋˜ ์ •๋ณด๋ฅผ ์ง€์›Œ์คŒ + Object.entries(this.drawList).forEach(([key, value]) => { + value.setMap(null); + delete this.drawList[key]; + }); + // ์œ ์ € ํ˜ธ์žฌ ๋ณด๊ธฐ + if (toggle) { + const toggleObj = {}; + Object.entries(this.newToggleBox).forEach(([key, value]) => { + toggleObj[key] = false; + }); + this.newToggleBox = toggleObj; + } + // ํ•„ํ„ฐ๋ง ํ•˜๊ธฐ + if (category) { + const toggleCategory = { + [category]: !this.newToggleBox[category] + }; + this.newToggleBox = { + ...this.newToggleBox, + ...toggleCategory + }; + Object.entries(this.newToggleBox).forEach(([key, value]) => { + if (value) { + factors.push(key); + } + }); + this.setState({ + factors: factors + }); + nearbyData = async val => { + await this.setState({ + NearByFactorItems: val + }); + }; + } + // TODO: + drawData(name, bound, factors, toggle, this.drawList, map, nearbyData); + }; + + handleChangeDescription = event => { + this.setState({ descriptionValue: event.target.value }); + }; + + handleChangeTitle = event => { + this.setState({ descriptionTitle: event.target.value }); + }; + + descriptionModal = () => { + const { + descriptionModalState, + descriptionValue, + descriptionTitle + } = this.state; + if (descriptionModalState) { + return ( + <div className="descriptionModal"> + <div className="descriptionHeader"> </div> + <textarea + placeholder="์ œ๋ชฉ์„ ์ง€์–ด์ฃผ์„ธ์š”:D" + className="descriptionInputTitle" + type="text" + value={descriptionTitle} + onChange={this.handleChangeTitle} + /> + <textarea + placeholder="ํ˜ธ์žฌ ๋‚ด์šฉ์„ ์ฑ„์›Œ์ฃผ์„ธ์š”:D" + className="descriptionInput" + type="text" + value={descriptionValue} + onChange={this.handleChangeDescription} + /> + <button + className="descriptionCloser" + type="button" + onClick={this.descriptionModalHide} + > + ๋‹ซ๊ธฐ + </button> + <button + className="descriptionSave" + type="button" + onClick={this.descriptionModalSave} + > + ์ €์žฅ + </button> + </div> + ); + } else { + return <div />; + } + }; + + descriptionModalHide = () => { + this.setState({ + descriptionModalState: false, + descriptionValue: '', + descriptionTitle: '' + }); + }; + + descriptionModalSave = () => { + const { descriptionValue, descriptionTitle, drawingData } = this.state; + this.setState({ descriptionModalState: false }); + const arrayOfShapes = drawingData; + arrayOfShapes[arrayOfShapes.length - 1].title = descriptionTitle; + arrayOfShapes[arrayOfShapes.length - 1].value = descriptionValue; + this.setState({ drawingData: arrayOfShapes }); + }; + + descriptionModalShow = () => { + this.setState({ descriptionModalState: true }); + }; + + render() { + const { + map, + name, + drawingData, + showFilter, + showDraw, + showModal, + activeFilter, + activeDraw, + MyInfoButton, + NearByFactorItems, + legendToggle, + showDrawingSetTitleDescriptionModal, + drawingSetTitle, + drawingSetDescription + } = this.state; + + this.toggleAllDraw(); + return ( + <div id="wrapper"> + <div id="map"> + <NearbyFactorDialog + mapLoad={map} + NearByFactorItems={NearByFactorItems} + /> + <div id="loginFavorContainer"> + <div + className="loginFavorBtn" + onClick={this.toggleLoginModal} + onKeyPress={this.toggleLoginModal} + role="button" + tabIndex="0" + > + {`My`} + </div> + <div + className={`loginFavorBtn ${activeFilter}`} + onClick={() => { + if (activeDraw === '') { + this.showFilter(); + } + }} + onKeyPress={() => this.showFilter} + role="button" + tabIndex="0" + > + {`ํ•„ํ„ฐ`} + </div> + <div + className={`loginFavorBtn ${activeDraw}`} + onClick={() => { + if (activeFilter === '') { + this.showDraw(); + this.descriptionModalHide(); + } + }} + onKeyPress={() => this.showDraw} + role="button" + tabIndex="0" + > + {`๊ทธ๋ฆฌ๊ธฐ`} + </div> + </div> + {showModal ? ( + <LoginModal + name={name} + toggleLoginModal={this.toggleLoginModal} + handleUserNameOnChange={this.handleUserNameOnChange} + initUserName={this.initUserName} + /> + ) : null} + <div className={!showFilter ? 'block' : 'none'}> + <FilterContainer + MyInfoButton={MyInfoButton} + myInfoToggle={this.myInfoToggle} + factorLoad={this.factorLoad} + showFilter={this.showFilter} + /> + </div> + <div className={showDraw ? 'block' : 'none'}> + <DrawContainer + handleToggle={this.showDraw} + mapLoad={map} + handleUserNameOnChange={this.handleUserNameOnChange} + drawingData={drawingData} + updateDrawingData={this.updateDrawingData} + toggleLoginModal={this.toggleLoginModal} + NearByFactorItems={NearByFactorItems} + initDrawingListAfterSave={ + this.initDrawingListAfterSave + } + showDraw={this.showDraw} + showDrawingSetTitleDescriptionModal={ + this.showDrawingSetTitleDescriptionModal + } + descriptionModalShow={this.descriptionModalShow} + descriptionModalHide={this.descriptionModalHide} + /> + </div> + {showDrawingSetTitleDescriptionModal ? ( + <DrawingSetTitleDescription + changeDrawingSetTitle={this.changeDrawingSetTitle} + changeDrawingSetDescription={ + this.changeDrawingSetDescription + } + drawingData={drawingData} + toggleLoginModal={this.toggleLoginModal} + initDrawingListAfterSave={ + this.initDrawingListAfterSave + } + showDraw={this.showDraw} + showDrawingSetTitleDescriptionModal={ + this.showDrawingSetTitleDescriptionModal + } + drawingSetTitle={drawingSetTitle} + drawingSetDescription={drawingSetDescription} + /> + ) : null} + <div + className="legend" + onClick={this.toggleLegend} + onKeyPress={this.toggleLegend} + role="button" + tabIndex="0" + /> + <div + className={ + 'colorList ' + (legendToggle ? 'invisible' : '') + } + > + {Object.keys(constants.newToggleBox).map( + (color, index) => { + return ( + <div className="eachColor" key={index}> + <div className="legendColorBox"> + <div className="colorCircle" /> + </div> + <div className="legendTextBox"> + {color} + </div> + </div> + ); + } + )} + </div> + </div> + <div> + <this.descriptionModal /> + </div> + </div> + ); + } +} + +export default App;
JavaScript
ํ•„์š”์—†์Œ ์ œ๊ฑฐ
@@ -0,0 +1,519 @@ +import React, { Component } from 'react'; +import * as d3 from 'd3'; +import drawData from './Module/loadHandle'; +import FilterContainer from './Components/FilterContainer'; +import LoginModal from './Components/LoginModal'; +import DrawContainer from './Components/DrawContainer'; +import './less/App.less'; +import * as constants from './constants'; +import * as MakeSecret from './Module/simpleEncryption'; +import NearbyFactorDialog from './Components/NearbyFactorDialog'; +import DrawingSetTitleDescription from './Components/drawingSetTitleDescriptionModal'; + +class App extends Component { + constructor(props) { + super(props); + this.bound = undefined; + this.drawList = {}; + this.newToggleBox = constants.newToggleBox; + this.state = { + name: undefined, + drawingData: [], + map: undefined, + showFilter: false, + showModal: false, + activeFilter: 'active', + activeDraw: '', + MyInfoButton: false, + showDraw: false, + factors: [], + NearByFactorItems: [], + showDrawingSetTitleDescriptionModal: false, + drawingSetTitle: null, + drawingSetDescription: null, + descriptionModalState: false, + descriptionValue: '', + descriptionTitle: '', + legendToggle: false + // NearByFilteringItems: [] + }; + } + + componentDidMount = async () => { + const naver = window.naver; + const map = await new naver.maps.Map(d3.select('#map').node(), { + zoomControl: true, + zoomControlOptions: { + style: naver.maps.ZoomControlStyle.SMALL, + position: naver.maps.Position.TOP_RIGHT + }, + logoControl: true, + logoControlOptions: { + position: naver.maps.Position.BOTTOM_RIGHT + }, + scaleControl: true, + scaleControlOptions: { + position: naver.maps.Position.BOTTOM_RIGHT + }, + mapDataControl: true, + mapDataControlOptions: { + position: naver.maps.Position.BOTTOM_LEFT + } + }); + + this.setState({ map }); + this.bound = map.getBounds(); + this.mainPageLoad(map); + naver.maps.Event.addListener(map, 'idle', e => { + const { showDraw } = this.state; + this.bound = map.getBounds(); + // ๊ทธ๋ฆฌ๊ธฐ ๋ชจ๋“œ๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ์—๋งŒ ๋ฐ์ดํ„ฐ๋ฅผ ๋ถˆ๋Ÿฌ์˜ด + if (!showDraw) { + this.mainPageLoad(map); + this.deleteDraw(); + } + }); + const name = JSON.parse(localStorage.getItem('token')); + if (name) { + this.setState({ + name: MakeSecret.Decrypt(name) + }); + } + }; + + isDelete = false; + + handleUserNameOnChange = username => { + this.setState({ name: username }); + }; + + showDrawingSetTitleDescriptionModal = value => { + this.setState({ showDrawingSetTitleDescriptionModal: value }); + }; + + changeDrawingSetTitle = text => { + this.setState({ drawingSetTitle: text }); + }; + + changeDrawingSetDescription = text => { + this.setState({ drawingSetDescription: text }); + }; + + mainPageLoad = map => { + const { name, factors } = this.state; + const bound = this.bound; + const nearbyData = async val => { + await this.setState({ + NearByFactorItems: val + }); + }; + drawData(name, bound, factors, false, this.drawList, map, nearbyData); + }; + + toggleAllDraw = () => { + const { showDraw, map } = this.state; + if (showDraw) { + Object.entries(this.drawList).forEach(([key, value]) => { + value.setMap(null); + delete this.drawList[key]; + }); + this.isDelete = true; + } else { + if (this.isDelete) { + this.mainPageLoad(map); + this.isDelete = false; + } + } + }; + + deleteDraw = () => { + Object.entries(this.drawList).forEach(([key, value]) => { + const startPos = {}; + const endPos = {}; + // reference point + startPos.x = value._lineData[0].coord.x; + startPos.y = value._lineData[0].coord.y; + endPos.x = value._lineData[value._lineData.length - 1].coord.x; + endPos.y = value._lineData[value._lineData.length - 1].coord.y; + + if ( + (startPos.x < this.bound._min._lng - 0.01 + || this.bound._max._lng + 0.01 < startPos.x + || startPos.y < this.bound._min._lat - 0.01 + || this.bound._max._lat + 0.01 < startPos.y) + && (endPos.x < this.bound._min._lng - 0.01 + || this.bound._max._lng + 0.01 < endPos.x + || endPos.y < this.bound._min._lat - 0.01 + || this.bound._max._lat + 0.01 < endPos.y) + ) { + value.setMap(null); + delete this.drawList[key]; + } + }); + }; + + toggleLoginModal = () => { + const { showModal } = this.state; + this.setState({ showModal: !showModal }); + }; + + toggleDraw = () => { + const { showDraw } = this.state; + this.setState({ descriptionModalState: false }); + this.setState({ showDraw: !showDraw }); + }; + + toggleLegend = () => { + const { legendToggle } = this.state; + this.setState({ legendToggle: !legendToggle }); + }; + + showFilter = () => { + const { showFilter, activeFilter } = this.state; + if (activeFilter === 'active') { + this.setState({ + showFilter: !showFilter, + activeFilter: '' + }); + } else { + this.setState({ + showFilter: !showFilter, + activeFilter: 'active' + }); + } + }; + + showDraw = () => { + const { showDraw, drawingData, activeDraw } = this.state; + if (drawingData.length) { + const pressedConfirm = confirm( + '์ €์žฅํ•˜์ง€ ์•Š๊ณ  ๊ทธ๋ฆฌ๊ธฐ ์ฐฝ์„ ๋‹ซ์œผ๋ฉด ๊ทธ๋ฆฐ ์ •๋ณด๋Š” ๋ชจ๋‘ ์‚ฌ๋ผ์ง‘๋‹ˆ๋‹ค!\n๊ทธ๋ž˜๋„ ๊ทธ๋ฆฌ๊ธฐ ์ฐฝ์„ ๋‹ซ์œผ์‹œ๊ฒ ์–ด์š”?' + ); + if (pressedConfirm) { + for (let index = 0; index < drawingData.length; index++) { + drawingData[index].figure.onRemove(); + } + this.setState({ drawingData: [] }); + this.setState({ descriptionModalState: false }); + } else if (!pressedConfirm) { + return; + } + } + + if (activeDraw === 'active') { + this.setState({ + showDraw: !showDraw, + activeDraw: '' + }); + } else { + this.setState({ + showDraw: !showDraw, + activeDraw: 'active' + }); + } + }; + + initDrawingListAfterSave = () => { + this.setState({ drawingData: [] }); + }; + + initUserName = () => { + this.setState({ name: undefined }); + }; + + myInfoToggle = () => { + const { MyInfoButton } = this.state; + this.setState({ MyInfoButton: !MyInfoButton }); + this.factorLoad(null, !MyInfoButton); + }; + + updateDrawingData = (shapeData, order = false, index) => { + const { drawingData } = this.state; + this.setState({ drawingData: [...drawingData, shapeData] }); + if (order) { + const newDrawingData = [...drawingData]; + newDrawingData.splice(index, 1); + this.setState({ drawingData: newDrawingData }); + } + }; + + mainToggle = (stateName, toggle) => { + this.setState({ [stateName]: !toggle }); + }; + + factorLoad = (category, toggle = false) => { + const { name, map } = this.state; + const bound = this.bound; + const factors = []; + let nearbyData; + + // ๊ธฐ์กด ์ง€๋„์— ์žˆ๋˜ ์ •๋ณด๋ฅผ ์ง€์›Œ์คŒ + Object.entries(this.drawList).forEach(([key, value]) => { + value.setMap(null); + delete this.drawList[key]; + }); + // ์œ ์ € ํ˜ธ์žฌ ๋ณด๊ธฐ + if (toggle) { + const toggleObj = {}; + Object.entries(this.newToggleBox).forEach(([key, value]) => { + toggleObj[key] = false; + }); + this.newToggleBox = toggleObj; + } + // ํ•„ํ„ฐ๋ง ํ•˜๊ธฐ + if (category) { + const toggleCategory = { + [category]: !this.newToggleBox[category] + }; + this.newToggleBox = { + ...this.newToggleBox, + ...toggleCategory + }; + Object.entries(this.newToggleBox).forEach(([key, value]) => { + if (value) { + factors.push(key); + } + }); + this.setState({ + factors: factors + }); + nearbyData = async val => { + await this.setState({ + NearByFactorItems: val + }); + }; + } + // TODO: + drawData(name, bound, factors, toggle, this.drawList, map, nearbyData); + }; + + handleChangeDescription = event => { + this.setState({ descriptionValue: event.target.value }); + }; + + handleChangeTitle = event => { + this.setState({ descriptionTitle: event.target.value }); + }; + + descriptionModal = () => { + const { + descriptionModalState, + descriptionValue, + descriptionTitle + } = this.state; + if (descriptionModalState) { + return ( + <div className="descriptionModal"> + <div className="descriptionHeader"> </div> + <textarea + placeholder="์ œ๋ชฉ์„ ์ง€์–ด์ฃผ์„ธ์š”:D" + className="descriptionInputTitle" + type="text" + value={descriptionTitle} + onChange={this.handleChangeTitle} + /> + <textarea + placeholder="ํ˜ธ์žฌ ๋‚ด์šฉ์„ ์ฑ„์›Œ์ฃผ์„ธ์š”:D" + className="descriptionInput" + type="text" + value={descriptionValue} + onChange={this.handleChangeDescription} + /> + <button + className="descriptionCloser" + type="button" + onClick={this.descriptionModalHide} + > + ๋‹ซ๊ธฐ + </button> + <button + className="descriptionSave" + type="button" + onClick={this.descriptionModalSave} + > + ์ €์žฅ + </button> + </div> + ); + } else { + return <div />; + } + }; + + descriptionModalHide = () => { + this.setState({ + descriptionModalState: false, + descriptionValue: '', + descriptionTitle: '' + }); + }; + + descriptionModalSave = () => { + const { descriptionValue, descriptionTitle, drawingData } = this.state; + this.setState({ descriptionModalState: false }); + const arrayOfShapes = drawingData; + arrayOfShapes[arrayOfShapes.length - 1].title = descriptionTitle; + arrayOfShapes[arrayOfShapes.length - 1].value = descriptionValue; + this.setState({ drawingData: arrayOfShapes }); + }; + + descriptionModalShow = () => { + this.setState({ descriptionModalState: true }); + }; + + render() { + const { + map, + name, + drawingData, + showFilter, + showDraw, + showModal, + activeFilter, + activeDraw, + MyInfoButton, + NearByFactorItems, + legendToggle, + showDrawingSetTitleDescriptionModal, + drawingSetTitle, + drawingSetDescription + } = this.state; + + this.toggleAllDraw(); + return ( + <div id="wrapper"> + <div id="map"> + <NearbyFactorDialog + mapLoad={map} + NearByFactorItems={NearByFactorItems} + /> + <div id="loginFavorContainer"> + <div + className="loginFavorBtn" + onClick={this.toggleLoginModal} + onKeyPress={this.toggleLoginModal} + role="button" + tabIndex="0" + > + {`My`} + </div> + <div + className={`loginFavorBtn ${activeFilter}`} + onClick={() => { + if (activeDraw === '') { + this.showFilter(); + } + }} + onKeyPress={() => this.showFilter} + role="button" + tabIndex="0" + > + {`ํ•„ํ„ฐ`} + </div> + <div + className={`loginFavorBtn ${activeDraw}`} + onClick={() => { + if (activeFilter === '') { + this.showDraw(); + this.descriptionModalHide(); + } + }} + onKeyPress={() => this.showDraw} + role="button" + tabIndex="0" + > + {`๊ทธ๋ฆฌ๊ธฐ`} + </div> + </div> + {showModal ? ( + <LoginModal + name={name} + toggleLoginModal={this.toggleLoginModal} + handleUserNameOnChange={this.handleUserNameOnChange} + initUserName={this.initUserName} + /> + ) : null} + <div className={!showFilter ? 'block' : 'none'}> + <FilterContainer + MyInfoButton={MyInfoButton} + myInfoToggle={this.myInfoToggle} + factorLoad={this.factorLoad} + showFilter={this.showFilter} + /> + </div> + <div className={showDraw ? 'block' : 'none'}> + <DrawContainer + handleToggle={this.showDraw} + mapLoad={map} + handleUserNameOnChange={this.handleUserNameOnChange} + drawingData={drawingData} + updateDrawingData={this.updateDrawingData} + toggleLoginModal={this.toggleLoginModal} + NearByFactorItems={NearByFactorItems} + initDrawingListAfterSave={ + this.initDrawingListAfterSave + } + showDraw={this.showDraw} + showDrawingSetTitleDescriptionModal={ + this.showDrawingSetTitleDescriptionModal + } + descriptionModalShow={this.descriptionModalShow} + descriptionModalHide={this.descriptionModalHide} + /> + </div> + {showDrawingSetTitleDescriptionModal ? ( + <DrawingSetTitleDescription + changeDrawingSetTitle={this.changeDrawingSetTitle} + changeDrawingSetDescription={ + this.changeDrawingSetDescription + } + drawingData={drawingData} + toggleLoginModal={this.toggleLoginModal} + initDrawingListAfterSave={ + this.initDrawingListAfterSave + } + showDraw={this.showDraw} + showDrawingSetTitleDescriptionModal={ + this.showDrawingSetTitleDescriptionModal + } + drawingSetTitle={drawingSetTitle} + drawingSetDescription={drawingSetDescription} + /> + ) : null} + <div + className="legend" + onClick={this.toggleLegend} + onKeyPress={this.toggleLegend} + role="button" + tabIndex="0" + /> + <div + className={ + 'colorList ' + (legendToggle ? 'invisible' : '') + } + > + {Object.keys(constants.newToggleBox).map( + (color, index) => { + return ( + <div className="eachColor" key={index}> + <div className="legendColorBox"> + <div className="colorCircle" /> + </div> + <div className="legendTextBox"> + {color} + </div> + </div> + ); + } + )} + </div> + </div> + <div> + <this.descriptionModal /> + </div> + </div> + ); + } +} + +export default App;
JavaScript
๊ฐ‘์ž๊ธฐ ์™œ ๋Œ€๋ฌธ์ž๋กœ ์‹œ์ž‘ํ• ๊นŒ์š”? ์ด๋ฆ„๋„ `deleteDraw` / `unsetDraw` ๋“ฑ์œผ๋กœ ํ•ด์•ผํ•  ๋“ฏ
@@ -0,0 +1,519 @@ +import React, { Component } from 'react'; +import * as d3 from 'd3'; +import drawData from './Module/loadHandle'; +import FilterContainer from './Components/FilterContainer'; +import LoginModal from './Components/LoginModal'; +import DrawContainer from './Components/DrawContainer'; +import './less/App.less'; +import * as constants from './constants'; +import * as MakeSecret from './Module/simpleEncryption'; +import NearbyFactorDialog from './Components/NearbyFactorDialog'; +import DrawingSetTitleDescription from './Components/drawingSetTitleDescriptionModal'; + +class App extends Component { + constructor(props) { + super(props); + this.bound = undefined; + this.drawList = {}; + this.newToggleBox = constants.newToggleBox; + this.state = { + name: undefined, + drawingData: [], + map: undefined, + showFilter: false, + showModal: false, + activeFilter: 'active', + activeDraw: '', + MyInfoButton: false, + showDraw: false, + factors: [], + NearByFactorItems: [], + showDrawingSetTitleDescriptionModal: false, + drawingSetTitle: null, + drawingSetDescription: null, + descriptionModalState: false, + descriptionValue: '', + descriptionTitle: '', + legendToggle: false + // NearByFilteringItems: [] + }; + } + + componentDidMount = async () => { + const naver = window.naver; + const map = await new naver.maps.Map(d3.select('#map').node(), { + zoomControl: true, + zoomControlOptions: { + style: naver.maps.ZoomControlStyle.SMALL, + position: naver.maps.Position.TOP_RIGHT + }, + logoControl: true, + logoControlOptions: { + position: naver.maps.Position.BOTTOM_RIGHT + }, + scaleControl: true, + scaleControlOptions: { + position: naver.maps.Position.BOTTOM_RIGHT + }, + mapDataControl: true, + mapDataControlOptions: { + position: naver.maps.Position.BOTTOM_LEFT + } + }); + + this.setState({ map }); + this.bound = map.getBounds(); + this.mainPageLoad(map); + naver.maps.Event.addListener(map, 'idle', e => { + const { showDraw } = this.state; + this.bound = map.getBounds(); + // ๊ทธ๋ฆฌ๊ธฐ ๋ชจ๋“œ๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ์—๋งŒ ๋ฐ์ดํ„ฐ๋ฅผ ๋ถˆ๋Ÿฌ์˜ด + if (!showDraw) { + this.mainPageLoad(map); + this.deleteDraw(); + } + }); + const name = JSON.parse(localStorage.getItem('token')); + if (name) { + this.setState({ + name: MakeSecret.Decrypt(name) + }); + } + }; + + isDelete = false; + + handleUserNameOnChange = username => { + this.setState({ name: username }); + }; + + showDrawingSetTitleDescriptionModal = value => { + this.setState({ showDrawingSetTitleDescriptionModal: value }); + }; + + changeDrawingSetTitle = text => { + this.setState({ drawingSetTitle: text }); + }; + + changeDrawingSetDescription = text => { + this.setState({ drawingSetDescription: text }); + }; + + mainPageLoad = map => { + const { name, factors } = this.state; + const bound = this.bound; + const nearbyData = async val => { + await this.setState({ + NearByFactorItems: val + }); + }; + drawData(name, bound, factors, false, this.drawList, map, nearbyData); + }; + + toggleAllDraw = () => { + const { showDraw, map } = this.state; + if (showDraw) { + Object.entries(this.drawList).forEach(([key, value]) => { + value.setMap(null); + delete this.drawList[key]; + }); + this.isDelete = true; + } else { + if (this.isDelete) { + this.mainPageLoad(map); + this.isDelete = false; + } + } + }; + + deleteDraw = () => { + Object.entries(this.drawList).forEach(([key, value]) => { + const startPos = {}; + const endPos = {}; + // reference point + startPos.x = value._lineData[0].coord.x; + startPos.y = value._lineData[0].coord.y; + endPos.x = value._lineData[value._lineData.length - 1].coord.x; + endPos.y = value._lineData[value._lineData.length - 1].coord.y; + + if ( + (startPos.x < this.bound._min._lng - 0.01 + || this.bound._max._lng + 0.01 < startPos.x + || startPos.y < this.bound._min._lat - 0.01 + || this.bound._max._lat + 0.01 < startPos.y) + && (endPos.x < this.bound._min._lng - 0.01 + || this.bound._max._lng + 0.01 < endPos.x + || endPos.y < this.bound._min._lat - 0.01 + || this.bound._max._lat + 0.01 < endPos.y) + ) { + value.setMap(null); + delete this.drawList[key]; + } + }); + }; + + toggleLoginModal = () => { + const { showModal } = this.state; + this.setState({ showModal: !showModal }); + }; + + toggleDraw = () => { + const { showDraw } = this.state; + this.setState({ descriptionModalState: false }); + this.setState({ showDraw: !showDraw }); + }; + + toggleLegend = () => { + const { legendToggle } = this.state; + this.setState({ legendToggle: !legendToggle }); + }; + + showFilter = () => { + const { showFilter, activeFilter } = this.state; + if (activeFilter === 'active') { + this.setState({ + showFilter: !showFilter, + activeFilter: '' + }); + } else { + this.setState({ + showFilter: !showFilter, + activeFilter: 'active' + }); + } + }; + + showDraw = () => { + const { showDraw, drawingData, activeDraw } = this.state; + if (drawingData.length) { + const pressedConfirm = confirm( + '์ €์žฅํ•˜์ง€ ์•Š๊ณ  ๊ทธ๋ฆฌ๊ธฐ ์ฐฝ์„ ๋‹ซ์œผ๋ฉด ๊ทธ๋ฆฐ ์ •๋ณด๋Š” ๋ชจ๋‘ ์‚ฌ๋ผ์ง‘๋‹ˆ๋‹ค!\n๊ทธ๋ž˜๋„ ๊ทธ๋ฆฌ๊ธฐ ์ฐฝ์„ ๋‹ซ์œผ์‹œ๊ฒ ์–ด์š”?' + ); + if (pressedConfirm) { + for (let index = 0; index < drawingData.length; index++) { + drawingData[index].figure.onRemove(); + } + this.setState({ drawingData: [] }); + this.setState({ descriptionModalState: false }); + } else if (!pressedConfirm) { + return; + } + } + + if (activeDraw === 'active') { + this.setState({ + showDraw: !showDraw, + activeDraw: '' + }); + } else { + this.setState({ + showDraw: !showDraw, + activeDraw: 'active' + }); + } + }; + + initDrawingListAfterSave = () => { + this.setState({ drawingData: [] }); + }; + + initUserName = () => { + this.setState({ name: undefined }); + }; + + myInfoToggle = () => { + const { MyInfoButton } = this.state; + this.setState({ MyInfoButton: !MyInfoButton }); + this.factorLoad(null, !MyInfoButton); + }; + + updateDrawingData = (shapeData, order = false, index) => { + const { drawingData } = this.state; + this.setState({ drawingData: [...drawingData, shapeData] }); + if (order) { + const newDrawingData = [...drawingData]; + newDrawingData.splice(index, 1); + this.setState({ drawingData: newDrawingData }); + } + }; + + mainToggle = (stateName, toggle) => { + this.setState({ [stateName]: !toggle }); + }; + + factorLoad = (category, toggle = false) => { + const { name, map } = this.state; + const bound = this.bound; + const factors = []; + let nearbyData; + + // ๊ธฐ์กด ์ง€๋„์— ์žˆ๋˜ ์ •๋ณด๋ฅผ ์ง€์›Œ์คŒ + Object.entries(this.drawList).forEach(([key, value]) => { + value.setMap(null); + delete this.drawList[key]; + }); + // ์œ ์ € ํ˜ธ์žฌ ๋ณด๊ธฐ + if (toggle) { + const toggleObj = {}; + Object.entries(this.newToggleBox).forEach(([key, value]) => { + toggleObj[key] = false; + }); + this.newToggleBox = toggleObj; + } + // ํ•„ํ„ฐ๋ง ํ•˜๊ธฐ + if (category) { + const toggleCategory = { + [category]: !this.newToggleBox[category] + }; + this.newToggleBox = { + ...this.newToggleBox, + ...toggleCategory + }; + Object.entries(this.newToggleBox).forEach(([key, value]) => { + if (value) { + factors.push(key); + } + }); + this.setState({ + factors: factors + }); + nearbyData = async val => { + await this.setState({ + NearByFactorItems: val + }); + }; + } + // TODO: + drawData(name, bound, factors, toggle, this.drawList, map, nearbyData); + }; + + handleChangeDescription = event => { + this.setState({ descriptionValue: event.target.value }); + }; + + handleChangeTitle = event => { + this.setState({ descriptionTitle: event.target.value }); + }; + + descriptionModal = () => { + const { + descriptionModalState, + descriptionValue, + descriptionTitle + } = this.state; + if (descriptionModalState) { + return ( + <div className="descriptionModal"> + <div className="descriptionHeader"> </div> + <textarea + placeholder="์ œ๋ชฉ์„ ์ง€์–ด์ฃผ์„ธ์š”:D" + className="descriptionInputTitle" + type="text" + value={descriptionTitle} + onChange={this.handleChangeTitle} + /> + <textarea + placeholder="ํ˜ธ์žฌ ๋‚ด์šฉ์„ ์ฑ„์›Œ์ฃผ์„ธ์š”:D" + className="descriptionInput" + type="text" + value={descriptionValue} + onChange={this.handleChangeDescription} + /> + <button + className="descriptionCloser" + type="button" + onClick={this.descriptionModalHide} + > + ๋‹ซ๊ธฐ + </button> + <button + className="descriptionSave" + type="button" + onClick={this.descriptionModalSave} + > + ์ €์žฅ + </button> + </div> + ); + } else { + return <div />; + } + }; + + descriptionModalHide = () => { + this.setState({ + descriptionModalState: false, + descriptionValue: '', + descriptionTitle: '' + }); + }; + + descriptionModalSave = () => { + const { descriptionValue, descriptionTitle, drawingData } = this.state; + this.setState({ descriptionModalState: false }); + const arrayOfShapes = drawingData; + arrayOfShapes[arrayOfShapes.length - 1].title = descriptionTitle; + arrayOfShapes[arrayOfShapes.length - 1].value = descriptionValue; + this.setState({ drawingData: arrayOfShapes }); + }; + + descriptionModalShow = () => { + this.setState({ descriptionModalState: true }); + }; + + render() { + const { + map, + name, + drawingData, + showFilter, + showDraw, + showModal, + activeFilter, + activeDraw, + MyInfoButton, + NearByFactorItems, + legendToggle, + showDrawingSetTitleDescriptionModal, + drawingSetTitle, + drawingSetDescription + } = this.state; + + this.toggleAllDraw(); + return ( + <div id="wrapper"> + <div id="map"> + <NearbyFactorDialog + mapLoad={map} + NearByFactorItems={NearByFactorItems} + /> + <div id="loginFavorContainer"> + <div + className="loginFavorBtn" + onClick={this.toggleLoginModal} + onKeyPress={this.toggleLoginModal} + role="button" + tabIndex="0" + > + {`My`} + </div> + <div + className={`loginFavorBtn ${activeFilter}`} + onClick={() => { + if (activeDraw === '') { + this.showFilter(); + } + }} + onKeyPress={() => this.showFilter} + role="button" + tabIndex="0" + > + {`ํ•„ํ„ฐ`} + </div> + <div + className={`loginFavorBtn ${activeDraw}`} + onClick={() => { + if (activeFilter === '') { + this.showDraw(); + this.descriptionModalHide(); + } + }} + onKeyPress={() => this.showDraw} + role="button" + tabIndex="0" + > + {`๊ทธ๋ฆฌ๊ธฐ`} + </div> + </div> + {showModal ? ( + <LoginModal + name={name} + toggleLoginModal={this.toggleLoginModal} + handleUserNameOnChange={this.handleUserNameOnChange} + initUserName={this.initUserName} + /> + ) : null} + <div className={!showFilter ? 'block' : 'none'}> + <FilterContainer + MyInfoButton={MyInfoButton} + myInfoToggle={this.myInfoToggle} + factorLoad={this.factorLoad} + showFilter={this.showFilter} + /> + </div> + <div className={showDraw ? 'block' : 'none'}> + <DrawContainer + handleToggle={this.showDraw} + mapLoad={map} + handleUserNameOnChange={this.handleUserNameOnChange} + drawingData={drawingData} + updateDrawingData={this.updateDrawingData} + toggleLoginModal={this.toggleLoginModal} + NearByFactorItems={NearByFactorItems} + initDrawingListAfterSave={ + this.initDrawingListAfterSave + } + showDraw={this.showDraw} + showDrawingSetTitleDescriptionModal={ + this.showDrawingSetTitleDescriptionModal + } + descriptionModalShow={this.descriptionModalShow} + descriptionModalHide={this.descriptionModalHide} + /> + </div> + {showDrawingSetTitleDescriptionModal ? ( + <DrawingSetTitleDescription + changeDrawingSetTitle={this.changeDrawingSetTitle} + changeDrawingSetDescription={ + this.changeDrawingSetDescription + } + drawingData={drawingData} + toggleLoginModal={this.toggleLoginModal} + initDrawingListAfterSave={ + this.initDrawingListAfterSave + } + showDraw={this.showDraw} + showDrawingSetTitleDescriptionModal={ + this.showDrawingSetTitleDescriptionModal + } + drawingSetTitle={drawingSetTitle} + drawingSetDescription={drawingSetDescription} + /> + ) : null} + <div + className="legend" + onClick={this.toggleLegend} + onKeyPress={this.toggleLegend} + role="button" + tabIndex="0" + /> + <div + className={ + 'colorList ' + (legendToggle ? 'invisible' : '') + } + > + {Object.keys(constants.newToggleBox).map( + (color, index) => { + return ( + <div className="eachColor" key={index}> + <div className="legendColorBox"> + <div className="colorCircle" /> + </div> + <div className="legendTextBox"> + {color} + </div> + </div> + ); + } + )} + </div> + </div> + <div> + <this.descriptionModal /> + </div> + </div> + ); + } +} + +export default App;
JavaScript
`0.01`์„ ์ƒ์ˆ˜์ฒ˜๋ฆฌ
@@ -0,0 +1,519 @@ +import React, { Component } from 'react'; +import * as d3 from 'd3'; +import drawData from './Module/loadHandle'; +import FilterContainer from './Components/FilterContainer'; +import LoginModal from './Components/LoginModal'; +import DrawContainer from './Components/DrawContainer'; +import './less/App.less'; +import * as constants from './constants'; +import * as MakeSecret from './Module/simpleEncryption'; +import NearbyFactorDialog from './Components/NearbyFactorDialog'; +import DrawingSetTitleDescription from './Components/drawingSetTitleDescriptionModal'; + +class App extends Component { + constructor(props) { + super(props); + this.bound = undefined; + this.drawList = {}; + this.newToggleBox = constants.newToggleBox; + this.state = { + name: undefined, + drawingData: [], + map: undefined, + showFilter: false, + showModal: false, + activeFilter: 'active', + activeDraw: '', + MyInfoButton: false, + showDraw: false, + factors: [], + NearByFactorItems: [], + showDrawingSetTitleDescriptionModal: false, + drawingSetTitle: null, + drawingSetDescription: null, + descriptionModalState: false, + descriptionValue: '', + descriptionTitle: '', + legendToggle: false + // NearByFilteringItems: [] + }; + } + + componentDidMount = async () => { + const naver = window.naver; + const map = await new naver.maps.Map(d3.select('#map').node(), { + zoomControl: true, + zoomControlOptions: { + style: naver.maps.ZoomControlStyle.SMALL, + position: naver.maps.Position.TOP_RIGHT + }, + logoControl: true, + logoControlOptions: { + position: naver.maps.Position.BOTTOM_RIGHT + }, + scaleControl: true, + scaleControlOptions: { + position: naver.maps.Position.BOTTOM_RIGHT + }, + mapDataControl: true, + mapDataControlOptions: { + position: naver.maps.Position.BOTTOM_LEFT + } + }); + + this.setState({ map }); + this.bound = map.getBounds(); + this.mainPageLoad(map); + naver.maps.Event.addListener(map, 'idle', e => { + const { showDraw } = this.state; + this.bound = map.getBounds(); + // ๊ทธ๋ฆฌ๊ธฐ ๋ชจ๋“œ๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ์—๋งŒ ๋ฐ์ดํ„ฐ๋ฅผ ๋ถˆ๋Ÿฌ์˜ด + if (!showDraw) { + this.mainPageLoad(map); + this.deleteDraw(); + } + }); + const name = JSON.parse(localStorage.getItem('token')); + if (name) { + this.setState({ + name: MakeSecret.Decrypt(name) + }); + } + }; + + isDelete = false; + + handleUserNameOnChange = username => { + this.setState({ name: username }); + }; + + showDrawingSetTitleDescriptionModal = value => { + this.setState({ showDrawingSetTitleDescriptionModal: value }); + }; + + changeDrawingSetTitle = text => { + this.setState({ drawingSetTitle: text }); + }; + + changeDrawingSetDescription = text => { + this.setState({ drawingSetDescription: text }); + }; + + mainPageLoad = map => { + const { name, factors } = this.state; + const bound = this.bound; + const nearbyData = async val => { + await this.setState({ + NearByFactorItems: val + }); + }; + drawData(name, bound, factors, false, this.drawList, map, nearbyData); + }; + + toggleAllDraw = () => { + const { showDraw, map } = this.state; + if (showDraw) { + Object.entries(this.drawList).forEach(([key, value]) => { + value.setMap(null); + delete this.drawList[key]; + }); + this.isDelete = true; + } else { + if (this.isDelete) { + this.mainPageLoad(map); + this.isDelete = false; + } + } + }; + + deleteDraw = () => { + Object.entries(this.drawList).forEach(([key, value]) => { + const startPos = {}; + const endPos = {}; + // reference point + startPos.x = value._lineData[0].coord.x; + startPos.y = value._lineData[0].coord.y; + endPos.x = value._lineData[value._lineData.length - 1].coord.x; + endPos.y = value._lineData[value._lineData.length - 1].coord.y; + + if ( + (startPos.x < this.bound._min._lng - 0.01 + || this.bound._max._lng + 0.01 < startPos.x + || startPos.y < this.bound._min._lat - 0.01 + || this.bound._max._lat + 0.01 < startPos.y) + && (endPos.x < this.bound._min._lng - 0.01 + || this.bound._max._lng + 0.01 < endPos.x + || endPos.y < this.bound._min._lat - 0.01 + || this.bound._max._lat + 0.01 < endPos.y) + ) { + value.setMap(null); + delete this.drawList[key]; + } + }); + }; + + toggleLoginModal = () => { + const { showModal } = this.state; + this.setState({ showModal: !showModal }); + }; + + toggleDraw = () => { + const { showDraw } = this.state; + this.setState({ descriptionModalState: false }); + this.setState({ showDraw: !showDraw }); + }; + + toggleLegend = () => { + const { legendToggle } = this.state; + this.setState({ legendToggle: !legendToggle }); + }; + + showFilter = () => { + const { showFilter, activeFilter } = this.state; + if (activeFilter === 'active') { + this.setState({ + showFilter: !showFilter, + activeFilter: '' + }); + } else { + this.setState({ + showFilter: !showFilter, + activeFilter: 'active' + }); + } + }; + + showDraw = () => { + const { showDraw, drawingData, activeDraw } = this.state; + if (drawingData.length) { + const pressedConfirm = confirm( + '์ €์žฅํ•˜์ง€ ์•Š๊ณ  ๊ทธ๋ฆฌ๊ธฐ ์ฐฝ์„ ๋‹ซ์œผ๋ฉด ๊ทธ๋ฆฐ ์ •๋ณด๋Š” ๋ชจ๋‘ ์‚ฌ๋ผ์ง‘๋‹ˆ๋‹ค!\n๊ทธ๋ž˜๋„ ๊ทธ๋ฆฌ๊ธฐ ์ฐฝ์„ ๋‹ซ์œผ์‹œ๊ฒ ์–ด์š”?' + ); + if (pressedConfirm) { + for (let index = 0; index < drawingData.length; index++) { + drawingData[index].figure.onRemove(); + } + this.setState({ drawingData: [] }); + this.setState({ descriptionModalState: false }); + } else if (!pressedConfirm) { + return; + } + } + + if (activeDraw === 'active') { + this.setState({ + showDraw: !showDraw, + activeDraw: '' + }); + } else { + this.setState({ + showDraw: !showDraw, + activeDraw: 'active' + }); + } + }; + + initDrawingListAfterSave = () => { + this.setState({ drawingData: [] }); + }; + + initUserName = () => { + this.setState({ name: undefined }); + }; + + myInfoToggle = () => { + const { MyInfoButton } = this.state; + this.setState({ MyInfoButton: !MyInfoButton }); + this.factorLoad(null, !MyInfoButton); + }; + + updateDrawingData = (shapeData, order = false, index) => { + const { drawingData } = this.state; + this.setState({ drawingData: [...drawingData, shapeData] }); + if (order) { + const newDrawingData = [...drawingData]; + newDrawingData.splice(index, 1); + this.setState({ drawingData: newDrawingData }); + } + }; + + mainToggle = (stateName, toggle) => { + this.setState({ [stateName]: !toggle }); + }; + + factorLoad = (category, toggle = false) => { + const { name, map } = this.state; + const bound = this.bound; + const factors = []; + let nearbyData; + + // ๊ธฐ์กด ์ง€๋„์— ์žˆ๋˜ ์ •๋ณด๋ฅผ ์ง€์›Œ์คŒ + Object.entries(this.drawList).forEach(([key, value]) => { + value.setMap(null); + delete this.drawList[key]; + }); + // ์œ ์ € ํ˜ธ์žฌ ๋ณด๊ธฐ + if (toggle) { + const toggleObj = {}; + Object.entries(this.newToggleBox).forEach(([key, value]) => { + toggleObj[key] = false; + }); + this.newToggleBox = toggleObj; + } + // ํ•„ํ„ฐ๋ง ํ•˜๊ธฐ + if (category) { + const toggleCategory = { + [category]: !this.newToggleBox[category] + }; + this.newToggleBox = { + ...this.newToggleBox, + ...toggleCategory + }; + Object.entries(this.newToggleBox).forEach(([key, value]) => { + if (value) { + factors.push(key); + } + }); + this.setState({ + factors: factors + }); + nearbyData = async val => { + await this.setState({ + NearByFactorItems: val + }); + }; + } + // TODO: + drawData(name, bound, factors, toggle, this.drawList, map, nearbyData); + }; + + handleChangeDescription = event => { + this.setState({ descriptionValue: event.target.value }); + }; + + handleChangeTitle = event => { + this.setState({ descriptionTitle: event.target.value }); + }; + + descriptionModal = () => { + const { + descriptionModalState, + descriptionValue, + descriptionTitle + } = this.state; + if (descriptionModalState) { + return ( + <div className="descriptionModal"> + <div className="descriptionHeader"> </div> + <textarea + placeholder="์ œ๋ชฉ์„ ์ง€์–ด์ฃผ์„ธ์š”:D" + className="descriptionInputTitle" + type="text" + value={descriptionTitle} + onChange={this.handleChangeTitle} + /> + <textarea + placeholder="ํ˜ธ์žฌ ๋‚ด์šฉ์„ ์ฑ„์›Œ์ฃผ์„ธ์š”:D" + className="descriptionInput" + type="text" + value={descriptionValue} + onChange={this.handleChangeDescription} + /> + <button + className="descriptionCloser" + type="button" + onClick={this.descriptionModalHide} + > + ๋‹ซ๊ธฐ + </button> + <button + className="descriptionSave" + type="button" + onClick={this.descriptionModalSave} + > + ์ €์žฅ + </button> + </div> + ); + } else { + return <div />; + } + }; + + descriptionModalHide = () => { + this.setState({ + descriptionModalState: false, + descriptionValue: '', + descriptionTitle: '' + }); + }; + + descriptionModalSave = () => { + const { descriptionValue, descriptionTitle, drawingData } = this.state; + this.setState({ descriptionModalState: false }); + const arrayOfShapes = drawingData; + arrayOfShapes[arrayOfShapes.length - 1].title = descriptionTitle; + arrayOfShapes[arrayOfShapes.length - 1].value = descriptionValue; + this.setState({ drawingData: arrayOfShapes }); + }; + + descriptionModalShow = () => { + this.setState({ descriptionModalState: true }); + }; + + render() { + const { + map, + name, + drawingData, + showFilter, + showDraw, + showModal, + activeFilter, + activeDraw, + MyInfoButton, + NearByFactorItems, + legendToggle, + showDrawingSetTitleDescriptionModal, + drawingSetTitle, + drawingSetDescription + } = this.state; + + this.toggleAllDraw(); + return ( + <div id="wrapper"> + <div id="map"> + <NearbyFactorDialog + mapLoad={map} + NearByFactorItems={NearByFactorItems} + /> + <div id="loginFavorContainer"> + <div + className="loginFavorBtn" + onClick={this.toggleLoginModal} + onKeyPress={this.toggleLoginModal} + role="button" + tabIndex="0" + > + {`My`} + </div> + <div + className={`loginFavorBtn ${activeFilter}`} + onClick={() => { + if (activeDraw === '') { + this.showFilter(); + } + }} + onKeyPress={() => this.showFilter} + role="button" + tabIndex="0" + > + {`ํ•„ํ„ฐ`} + </div> + <div + className={`loginFavorBtn ${activeDraw}`} + onClick={() => { + if (activeFilter === '') { + this.showDraw(); + this.descriptionModalHide(); + } + }} + onKeyPress={() => this.showDraw} + role="button" + tabIndex="0" + > + {`๊ทธ๋ฆฌ๊ธฐ`} + </div> + </div> + {showModal ? ( + <LoginModal + name={name} + toggleLoginModal={this.toggleLoginModal} + handleUserNameOnChange={this.handleUserNameOnChange} + initUserName={this.initUserName} + /> + ) : null} + <div className={!showFilter ? 'block' : 'none'}> + <FilterContainer + MyInfoButton={MyInfoButton} + myInfoToggle={this.myInfoToggle} + factorLoad={this.factorLoad} + showFilter={this.showFilter} + /> + </div> + <div className={showDraw ? 'block' : 'none'}> + <DrawContainer + handleToggle={this.showDraw} + mapLoad={map} + handleUserNameOnChange={this.handleUserNameOnChange} + drawingData={drawingData} + updateDrawingData={this.updateDrawingData} + toggleLoginModal={this.toggleLoginModal} + NearByFactorItems={NearByFactorItems} + initDrawingListAfterSave={ + this.initDrawingListAfterSave + } + showDraw={this.showDraw} + showDrawingSetTitleDescriptionModal={ + this.showDrawingSetTitleDescriptionModal + } + descriptionModalShow={this.descriptionModalShow} + descriptionModalHide={this.descriptionModalHide} + /> + </div> + {showDrawingSetTitleDescriptionModal ? ( + <DrawingSetTitleDescription + changeDrawingSetTitle={this.changeDrawingSetTitle} + changeDrawingSetDescription={ + this.changeDrawingSetDescription + } + drawingData={drawingData} + toggleLoginModal={this.toggleLoginModal} + initDrawingListAfterSave={ + this.initDrawingListAfterSave + } + showDraw={this.showDraw} + showDrawingSetTitleDescriptionModal={ + this.showDrawingSetTitleDescriptionModal + } + drawingSetTitle={drawingSetTitle} + drawingSetDescription={drawingSetDescription} + /> + ) : null} + <div + className="legend" + onClick={this.toggleLegend} + onKeyPress={this.toggleLegend} + role="button" + tabIndex="0" + /> + <div + className={ + 'colorList ' + (legendToggle ? 'invisible' : '') + } + > + {Object.keys(constants.newToggleBox).map( + (color, index) => { + return ( + <div className="eachColor" key={index}> + <div className="legendColorBox"> + <div className="colorCircle" /> + </div> + <div className="legendTextBox"> + {color} + </div> + </div> + ); + } + )} + </div> + </div> + <div> + <this.descriptionModal /> + </div> + </div> + ); + } +} + +export default App;
JavaScript
์ด๊ฒƒ๋งŒ underscore๋กœ ์‹œ์ž‘ํ•˜๋Š” ์ด์œ ๊ฐ€ ๋ชจ์—์š”? ๊ทธ๋ฆฌ๊ณ  ๋„ค์ด๋ฐ์œผ๋กœ ๋ฌด์Šจ ์ผ์„ ํ•˜๋Š” ๋ฉ”์„œ๋“œ์ธ์ง€ ์•Œ์•„์ฑ„๊ธฐ ํž˜๋“œ๋„ค์š”.
@@ -0,0 +1,519 @@ +import React, { Component } from 'react'; +import * as d3 from 'd3'; +import drawData from './Module/loadHandle'; +import FilterContainer from './Components/FilterContainer'; +import LoginModal from './Components/LoginModal'; +import DrawContainer from './Components/DrawContainer'; +import './less/App.less'; +import * as constants from './constants'; +import * as MakeSecret from './Module/simpleEncryption'; +import NearbyFactorDialog from './Components/NearbyFactorDialog'; +import DrawingSetTitleDescription from './Components/drawingSetTitleDescriptionModal'; + +class App extends Component { + constructor(props) { + super(props); + this.bound = undefined; + this.drawList = {}; + this.newToggleBox = constants.newToggleBox; + this.state = { + name: undefined, + drawingData: [], + map: undefined, + showFilter: false, + showModal: false, + activeFilter: 'active', + activeDraw: '', + MyInfoButton: false, + showDraw: false, + factors: [], + NearByFactorItems: [], + showDrawingSetTitleDescriptionModal: false, + drawingSetTitle: null, + drawingSetDescription: null, + descriptionModalState: false, + descriptionValue: '', + descriptionTitle: '', + legendToggle: false + // NearByFilteringItems: [] + }; + } + + componentDidMount = async () => { + const naver = window.naver; + const map = await new naver.maps.Map(d3.select('#map').node(), { + zoomControl: true, + zoomControlOptions: { + style: naver.maps.ZoomControlStyle.SMALL, + position: naver.maps.Position.TOP_RIGHT + }, + logoControl: true, + logoControlOptions: { + position: naver.maps.Position.BOTTOM_RIGHT + }, + scaleControl: true, + scaleControlOptions: { + position: naver.maps.Position.BOTTOM_RIGHT + }, + mapDataControl: true, + mapDataControlOptions: { + position: naver.maps.Position.BOTTOM_LEFT + } + }); + + this.setState({ map }); + this.bound = map.getBounds(); + this.mainPageLoad(map); + naver.maps.Event.addListener(map, 'idle', e => { + const { showDraw } = this.state; + this.bound = map.getBounds(); + // ๊ทธ๋ฆฌ๊ธฐ ๋ชจ๋“œ๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ์—๋งŒ ๋ฐ์ดํ„ฐ๋ฅผ ๋ถˆ๋Ÿฌ์˜ด + if (!showDraw) { + this.mainPageLoad(map); + this.deleteDraw(); + } + }); + const name = JSON.parse(localStorage.getItem('token')); + if (name) { + this.setState({ + name: MakeSecret.Decrypt(name) + }); + } + }; + + isDelete = false; + + handleUserNameOnChange = username => { + this.setState({ name: username }); + }; + + showDrawingSetTitleDescriptionModal = value => { + this.setState({ showDrawingSetTitleDescriptionModal: value }); + }; + + changeDrawingSetTitle = text => { + this.setState({ drawingSetTitle: text }); + }; + + changeDrawingSetDescription = text => { + this.setState({ drawingSetDescription: text }); + }; + + mainPageLoad = map => { + const { name, factors } = this.state; + const bound = this.bound; + const nearbyData = async val => { + await this.setState({ + NearByFactorItems: val + }); + }; + drawData(name, bound, factors, false, this.drawList, map, nearbyData); + }; + + toggleAllDraw = () => { + const { showDraw, map } = this.state; + if (showDraw) { + Object.entries(this.drawList).forEach(([key, value]) => { + value.setMap(null); + delete this.drawList[key]; + }); + this.isDelete = true; + } else { + if (this.isDelete) { + this.mainPageLoad(map); + this.isDelete = false; + } + } + }; + + deleteDraw = () => { + Object.entries(this.drawList).forEach(([key, value]) => { + const startPos = {}; + const endPos = {}; + // reference point + startPos.x = value._lineData[0].coord.x; + startPos.y = value._lineData[0].coord.y; + endPos.x = value._lineData[value._lineData.length - 1].coord.x; + endPos.y = value._lineData[value._lineData.length - 1].coord.y; + + if ( + (startPos.x < this.bound._min._lng - 0.01 + || this.bound._max._lng + 0.01 < startPos.x + || startPos.y < this.bound._min._lat - 0.01 + || this.bound._max._lat + 0.01 < startPos.y) + && (endPos.x < this.bound._min._lng - 0.01 + || this.bound._max._lng + 0.01 < endPos.x + || endPos.y < this.bound._min._lat - 0.01 + || this.bound._max._lat + 0.01 < endPos.y) + ) { + value.setMap(null); + delete this.drawList[key]; + } + }); + }; + + toggleLoginModal = () => { + const { showModal } = this.state; + this.setState({ showModal: !showModal }); + }; + + toggleDraw = () => { + const { showDraw } = this.state; + this.setState({ descriptionModalState: false }); + this.setState({ showDraw: !showDraw }); + }; + + toggleLegend = () => { + const { legendToggle } = this.state; + this.setState({ legendToggle: !legendToggle }); + }; + + showFilter = () => { + const { showFilter, activeFilter } = this.state; + if (activeFilter === 'active') { + this.setState({ + showFilter: !showFilter, + activeFilter: '' + }); + } else { + this.setState({ + showFilter: !showFilter, + activeFilter: 'active' + }); + } + }; + + showDraw = () => { + const { showDraw, drawingData, activeDraw } = this.state; + if (drawingData.length) { + const pressedConfirm = confirm( + '์ €์žฅํ•˜์ง€ ์•Š๊ณ  ๊ทธ๋ฆฌ๊ธฐ ์ฐฝ์„ ๋‹ซ์œผ๋ฉด ๊ทธ๋ฆฐ ์ •๋ณด๋Š” ๋ชจ๋‘ ์‚ฌ๋ผ์ง‘๋‹ˆ๋‹ค!\n๊ทธ๋ž˜๋„ ๊ทธ๋ฆฌ๊ธฐ ์ฐฝ์„ ๋‹ซ์œผ์‹œ๊ฒ ์–ด์š”?' + ); + if (pressedConfirm) { + for (let index = 0; index < drawingData.length; index++) { + drawingData[index].figure.onRemove(); + } + this.setState({ drawingData: [] }); + this.setState({ descriptionModalState: false }); + } else if (!pressedConfirm) { + return; + } + } + + if (activeDraw === 'active') { + this.setState({ + showDraw: !showDraw, + activeDraw: '' + }); + } else { + this.setState({ + showDraw: !showDraw, + activeDraw: 'active' + }); + } + }; + + initDrawingListAfterSave = () => { + this.setState({ drawingData: [] }); + }; + + initUserName = () => { + this.setState({ name: undefined }); + }; + + myInfoToggle = () => { + const { MyInfoButton } = this.state; + this.setState({ MyInfoButton: !MyInfoButton }); + this.factorLoad(null, !MyInfoButton); + }; + + updateDrawingData = (shapeData, order = false, index) => { + const { drawingData } = this.state; + this.setState({ drawingData: [...drawingData, shapeData] }); + if (order) { + const newDrawingData = [...drawingData]; + newDrawingData.splice(index, 1); + this.setState({ drawingData: newDrawingData }); + } + }; + + mainToggle = (stateName, toggle) => { + this.setState({ [stateName]: !toggle }); + }; + + factorLoad = (category, toggle = false) => { + const { name, map } = this.state; + const bound = this.bound; + const factors = []; + let nearbyData; + + // ๊ธฐ์กด ์ง€๋„์— ์žˆ๋˜ ์ •๋ณด๋ฅผ ์ง€์›Œ์คŒ + Object.entries(this.drawList).forEach(([key, value]) => { + value.setMap(null); + delete this.drawList[key]; + }); + // ์œ ์ € ํ˜ธ์žฌ ๋ณด๊ธฐ + if (toggle) { + const toggleObj = {}; + Object.entries(this.newToggleBox).forEach(([key, value]) => { + toggleObj[key] = false; + }); + this.newToggleBox = toggleObj; + } + // ํ•„ํ„ฐ๋ง ํ•˜๊ธฐ + if (category) { + const toggleCategory = { + [category]: !this.newToggleBox[category] + }; + this.newToggleBox = { + ...this.newToggleBox, + ...toggleCategory + }; + Object.entries(this.newToggleBox).forEach(([key, value]) => { + if (value) { + factors.push(key); + } + }); + this.setState({ + factors: factors + }); + nearbyData = async val => { + await this.setState({ + NearByFactorItems: val + }); + }; + } + // TODO: + drawData(name, bound, factors, toggle, this.drawList, map, nearbyData); + }; + + handleChangeDescription = event => { + this.setState({ descriptionValue: event.target.value }); + }; + + handleChangeTitle = event => { + this.setState({ descriptionTitle: event.target.value }); + }; + + descriptionModal = () => { + const { + descriptionModalState, + descriptionValue, + descriptionTitle + } = this.state; + if (descriptionModalState) { + return ( + <div className="descriptionModal"> + <div className="descriptionHeader"> </div> + <textarea + placeholder="์ œ๋ชฉ์„ ์ง€์–ด์ฃผ์„ธ์š”:D" + className="descriptionInputTitle" + type="text" + value={descriptionTitle} + onChange={this.handleChangeTitle} + /> + <textarea + placeholder="ํ˜ธ์žฌ ๋‚ด์šฉ์„ ์ฑ„์›Œ์ฃผ์„ธ์š”:D" + className="descriptionInput" + type="text" + value={descriptionValue} + onChange={this.handleChangeDescription} + /> + <button + className="descriptionCloser" + type="button" + onClick={this.descriptionModalHide} + > + ๋‹ซ๊ธฐ + </button> + <button + className="descriptionSave" + type="button" + onClick={this.descriptionModalSave} + > + ์ €์žฅ + </button> + </div> + ); + } else { + return <div />; + } + }; + + descriptionModalHide = () => { + this.setState({ + descriptionModalState: false, + descriptionValue: '', + descriptionTitle: '' + }); + }; + + descriptionModalSave = () => { + const { descriptionValue, descriptionTitle, drawingData } = this.state; + this.setState({ descriptionModalState: false }); + const arrayOfShapes = drawingData; + arrayOfShapes[arrayOfShapes.length - 1].title = descriptionTitle; + arrayOfShapes[arrayOfShapes.length - 1].value = descriptionValue; + this.setState({ drawingData: arrayOfShapes }); + }; + + descriptionModalShow = () => { + this.setState({ descriptionModalState: true }); + }; + + render() { + const { + map, + name, + drawingData, + showFilter, + showDraw, + showModal, + activeFilter, + activeDraw, + MyInfoButton, + NearByFactorItems, + legendToggle, + showDrawingSetTitleDescriptionModal, + drawingSetTitle, + drawingSetDescription + } = this.state; + + this.toggleAllDraw(); + return ( + <div id="wrapper"> + <div id="map"> + <NearbyFactorDialog + mapLoad={map} + NearByFactorItems={NearByFactorItems} + /> + <div id="loginFavorContainer"> + <div + className="loginFavorBtn" + onClick={this.toggleLoginModal} + onKeyPress={this.toggleLoginModal} + role="button" + tabIndex="0" + > + {`My`} + </div> + <div + className={`loginFavorBtn ${activeFilter}`} + onClick={() => { + if (activeDraw === '') { + this.showFilter(); + } + }} + onKeyPress={() => this.showFilter} + role="button" + tabIndex="0" + > + {`ํ•„ํ„ฐ`} + </div> + <div + className={`loginFavorBtn ${activeDraw}`} + onClick={() => { + if (activeFilter === '') { + this.showDraw(); + this.descriptionModalHide(); + } + }} + onKeyPress={() => this.showDraw} + role="button" + tabIndex="0" + > + {`๊ทธ๋ฆฌ๊ธฐ`} + </div> + </div> + {showModal ? ( + <LoginModal + name={name} + toggleLoginModal={this.toggleLoginModal} + handleUserNameOnChange={this.handleUserNameOnChange} + initUserName={this.initUserName} + /> + ) : null} + <div className={!showFilter ? 'block' : 'none'}> + <FilterContainer + MyInfoButton={MyInfoButton} + myInfoToggle={this.myInfoToggle} + factorLoad={this.factorLoad} + showFilter={this.showFilter} + /> + </div> + <div className={showDraw ? 'block' : 'none'}> + <DrawContainer + handleToggle={this.showDraw} + mapLoad={map} + handleUserNameOnChange={this.handleUserNameOnChange} + drawingData={drawingData} + updateDrawingData={this.updateDrawingData} + toggleLoginModal={this.toggleLoginModal} + NearByFactorItems={NearByFactorItems} + initDrawingListAfterSave={ + this.initDrawingListAfterSave + } + showDraw={this.showDraw} + showDrawingSetTitleDescriptionModal={ + this.showDrawingSetTitleDescriptionModal + } + descriptionModalShow={this.descriptionModalShow} + descriptionModalHide={this.descriptionModalHide} + /> + </div> + {showDrawingSetTitleDescriptionModal ? ( + <DrawingSetTitleDescription + changeDrawingSetTitle={this.changeDrawingSetTitle} + changeDrawingSetDescription={ + this.changeDrawingSetDescription + } + drawingData={drawingData} + toggleLoginModal={this.toggleLoginModal} + initDrawingListAfterSave={ + this.initDrawingListAfterSave + } + showDraw={this.showDraw} + showDrawingSetTitleDescriptionModal={ + this.showDrawingSetTitleDescriptionModal + } + drawingSetTitle={drawingSetTitle} + drawingSetDescription={drawingSetDescription} + /> + ) : null} + <div + className="legend" + onClick={this.toggleLegend} + onKeyPress={this.toggleLegend} + role="button" + tabIndex="0" + /> + <div + className={ + 'colorList ' + (legendToggle ? 'invisible' : '') + } + > + {Object.keys(constants.newToggleBox).map( + (color, index) => { + return ( + <div className="eachColor" key={index}> + <div className="legendColorBox"> + <div className="colorCircle" /> + </div> + <div className="legendTextBox"> + {color} + </div> + </div> + ); + } + )} + </div> + </div> + <div> + <this.descriptionModal /> + </div> + </div> + ); + } +} + +export default App;
JavaScript
๋ฆฌํ„ด๊ฐ’์ด ๊ธฐ์กด๊ฐ’์ธ๊ฒŒ ์ด์ƒํ•œ๋ฐ, ์‚ดํŽด๋ณด๋‹ˆ ๋ฆฌํ„ด๊ฐ’ ๋ฐ›์•„์„œ ์“ฐ๋Š”๋ฐ๋„ ์—†๋Š”๊ฑฐ ๊ฐ™์•„์š”.
@@ -0,0 +1,519 @@ +import React, { Component } from 'react'; +import * as d3 from 'd3'; +import drawData from './Module/loadHandle'; +import FilterContainer from './Components/FilterContainer'; +import LoginModal from './Components/LoginModal'; +import DrawContainer from './Components/DrawContainer'; +import './less/App.less'; +import * as constants from './constants'; +import * as MakeSecret from './Module/simpleEncryption'; +import NearbyFactorDialog from './Components/NearbyFactorDialog'; +import DrawingSetTitleDescription from './Components/drawingSetTitleDescriptionModal'; + +class App extends Component { + constructor(props) { + super(props); + this.bound = undefined; + this.drawList = {}; + this.newToggleBox = constants.newToggleBox; + this.state = { + name: undefined, + drawingData: [], + map: undefined, + showFilter: false, + showModal: false, + activeFilter: 'active', + activeDraw: '', + MyInfoButton: false, + showDraw: false, + factors: [], + NearByFactorItems: [], + showDrawingSetTitleDescriptionModal: false, + drawingSetTitle: null, + drawingSetDescription: null, + descriptionModalState: false, + descriptionValue: '', + descriptionTitle: '', + legendToggle: false + // NearByFilteringItems: [] + }; + } + + componentDidMount = async () => { + const naver = window.naver; + const map = await new naver.maps.Map(d3.select('#map').node(), { + zoomControl: true, + zoomControlOptions: { + style: naver.maps.ZoomControlStyle.SMALL, + position: naver.maps.Position.TOP_RIGHT + }, + logoControl: true, + logoControlOptions: { + position: naver.maps.Position.BOTTOM_RIGHT + }, + scaleControl: true, + scaleControlOptions: { + position: naver.maps.Position.BOTTOM_RIGHT + }, + mapDataControl: true, + mapDataControlOptions: { + position: naver.maps.Position.BOTTOM_LEFT + } + }); + + this.setState({ map }); + this.bound = map.getBounds(); + this.mainPageLoad(map); + naver.maps.Event.addListener(map, 'idle', e => { + const { showDraw } = this.state; + this.bound = map.getBounds(); + // ๊ทธ๋ฆฌ๊ธฐ ๋ชจ๋“œ๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ์—๋งŒ ๋ฐ์ดํ„ฐ๋ฅผ ๋ถˆ๋Ÿฌ์˜ด + if (!showDraw) { + this.mainPageLoad(map); + this.deleteDraw(); + } + }); + const name = JSON.parse(localStorage.getItem('token')); + if (name) { + this.setState({ + name: MakeSecret.Decrypt(name) + }); + } + }; + + isDelete = false; + + handleUserNameOnChange = username => { + this.setState({ name: username }); + }; + + showDrawingSetTitleDescriptionModal = value => { + this.setState({ showDrawingSetTitleDescriptionModal: value }); + }; + + changeDrawingSetTitle = text => { + this.setState({ drawingSetTitle: text }); + }; + + changeDrawingSetDescription = text => { + this.setState({ drawingSetDescription: text }); + }; + + mainPageLoad = map => { + const { name, factors } = this.state; + const bound = this.bound; + const nearbyData = async val => { + await this.setState({ + NearByFactorItems: val + }); + }; + drawData(name, bound, factors, false, this.drawList, map, nearbyData); + }; + + toggleAllDraw = () => { + const { showDraw, map } = this.state; + if (showDraw) { + Object.entries(this.drawList).forEach(([key, value]) => { + value.setMap(null); + delete this.drawList[key]; + }); + this.isDelete = true; + } else { + if (this.isDelete) { + this.mainPageLoad(map); + this.isDelete = false; + } + } + }; + + deleteDraw = () => { + Object.entries(this.drawList).forEach(([key, value]) => { + const startPos = {}; + const endPos = {}; + // reference point + startPos.x = value._lineData[0].coord.x; + startPos.y = value._lineData[0].coord.y; + endPos.x = value._lineData[value._lineData.length - 1].coord.x; + endPos.y = value._lineData[value._lineData.length - 1].coord.y; + + if ( + (startPos.x < this.bound._min._lng - 0.01 + || this.bound._max._lng + 0.01 < startPos.x + || startPos.y < this.bound._min._lat - 0.01 + || this.bound._max._lat + 0.01 < startPos.y) + && (endPos.x < this.bound._min._lng - 0.01 + || this.bound._max._lng + 0.01 < endPos.x + || endPos.y < this.bound._min._lat - 0.01 + || this.bound._max._lat + 0.01 < endPos.y) + ) { + value.setMap(null); + delete this.drawList[key]; + } + }); + }; + + toggleLoginModal = () => { + const { showModal } = this.state; + this.setState({ showModal: !showModal }); + }; + + toggleDraw = () => { + const { showDraw } = this.state; + this.setState({ descriptionModalState: false }); + this.setState({ showDraw: !showDraw }); + }; + + toggleLegend = () => { + const { legendToggle } = this.state; + this.setState({ legendToggle: !legendToggle }); + }; + + showFilter = () => { + const { showFilter, activeFilter } = this.state; + if (activeFilter === 'active') { + this.setState({ + showFilter: !showFilter, + activeFilter: '' + }); + } else { + this.setState({ + showFilter: !showFilter, + activeFilter: 'active' + }); + } + }; + + showDraw = () => { + const { showDraw, drawingData, activeDraw } = this.state; + if (drawingData.length) { + const pressedConfirm = confirm( + '์ €์žฅํ•˜์ง€ ์•Š๊ณ  ๊ทธ๋ฆฌ๊ธฐ ์ฐฝ์„ ๋‹ซ์œผ๋ฉด ๊ทธ๋ฆฐ ์ •๋ณด๋Š” ๋ชจ๋‘ ์‚ฌ๋ผ์ง‘๋‹ˆ๋‹ค!\n๊ทธ๋ž˜๋„ ๊ทธ๋ฆฌ๊ธฐ ์ฐฝ์„ ๋‹ซ์œผ์‹œ๊ฒ ์–ด์š”?' + ); + if (pressedConfirm) { + for (let index = 0; index < drawingData.length; index++) { + drawingData[index].figure.onRemove(); + } + this.setState({ drawingData: [] }); + this.setState({ descriptionModalState: false }); + } else if (!pressedConfirm) { + return; + } + } + + if (activeDraw === 'active') { + this.setState({ + showDraw: !showDraw, + activeDraw: '' + }); + } else { + this.setState({ + showDraw: !showDraw, + activeDraw: 'active' + }); + } + }; + + initDrawingListAfterSave = () => { + this.setState({ drawingData: [] }); + }; + + initUserName = () => { + this.setState({ name: undefined }); + }; + + myInfoToggle = () => { + const { MyInfoButton } = this.state; + this.setState({ MyInfoButton: !MyInfoButton }); + this.factorLoad(null, !MyInfoButton); + }; + + updateDrawingData = (shapeData, order = false, index) => { + const { drawingData } = this.state; + this.setState({ drawingData: [...drawingData, shapeData] }); + if (order) { + const newDrawingData = [...drawingData]; + newDrawingData.splice(index, 1); + this.setState({ drawingData: newDrawingData }); + } + }; + + mainToggle = (stateName, toggle) => { + this.setState({ [stateName]: !toggle }); + }; + + factorLoad = (category, toggle = false) => { + const { name, map } = this.state; + const bound = this.bound; + const factors = []; + let nearbyData; + + // ๊ธฐ์กด ์ง€๋„์— ์žˆ๋˜ ์ •๋ณด๋ฅผ ์ง€์›Œ์คŒ + Object.entries(this.drawList).forEach(([key, value]) => { + value.setMap(null); + delete this.drawList[key]; + }); + // ์œ ์ € ํ˜ธ์žฌ ๋ณด๊ธฐ + if (toggle) { + const toggleObj = {}; + Object.entries(this.newToggleBox).forEach(([key, value]) => { + toggleObj[key] = false; + }); + this.newToggleBox = toggleObj; + } + // ํ•„ํ„ฐ๋ง ํ•˜๊ธฐ + if (category) { + const toggleCategory = { + [category]: !this.newToggleBox[category] + }; + this.newToggleBox = { + ...this.newToggleBox, + ...toggleCategory + }; + Object.entries(this.newToggleBox).forEach(([key, value]) => { + if (value) { + factors.push(key); + } + }); + this.setState({ + factors: factors + }); + nearbyData = async val => { + await this.setState({ + NearByFactorItems: val + }); + }; + } + // TODO: + drawData(name, bound, factors, toggle, this.drawList, map, nearbyData); + }; + + handleChangeDescription = event => { + this.setState({ descriptionValue: event.target.value }); + }; + + handleChangeTitle = event => { + this.setState({ descriptionTitle: event.target.value }); + }; + + descriptionModal = () => { + const { + descriptionModalState, + descriptionValue, + descriptionTitle + } = this.state; + if (descriptionModalState) { + return ( + <div className="descriptionModal"> + <div className="descriptionHeader"> </div> + <textarea + placeholder="์ œ๋ชฉ์„ ์ง€์–ด์ฃผ์„ธ์š”:D" + className="descriptionInputTitle" + type="text" + value={descriptionTitle} + onChange={this.handleChangeTitle} + /> + <textarea + placeholder="ํ˜ธ์žฌ ๋‚ด์šฉ์„ ์ฑ„์›Œ์ฃผ์„ธ์š”:D" + className="descriptionInput" + type="text" + value={descriptionValue} + onChange={this.handleChangeDescription} + /> + <button + className="descriptionCloser" + type="button" + onClick={this.descriptionModalHide} + > + ๋‹ซ๊ธฐ + </button> + <button + className="descriptionSave" + type="button" + onClick={this.descriptionModalSave} + > + ์ €์žฅ + </button> + </div> + ); + } else { + return <div />; + } + }; + + descriptionModalHide = () => { + this.setState({ + descriptionModalState: false, + descriptionValue: '', + descriptionTitle: '' + }); + }; + + descriptionModalSave = () => { + const { descriptionValue, descriptionTitle, drawingData } = this.state; + this.setState({ descriptionModalState: false }); + const arrayOfShapes = drawingData; + arrayOfShapes[arrayOfShapes.length - 1].title = descriptionTitle; + arrayOfShapes[arrayOfShapes.length - 1].value = descriptionValue; + this.setState({ drawingData: arrayOfShapes }); + }; + + descriptionModalShow = () => { + this.setState({ descriptionModalState: true }); + }; + + render() { + const { + map, + name, + drawingData, + showFilter, + showDraw, + showModal, + activeFilter, + activeDraw, + MyInfoButton, + NearByFactorItems, + legendToggle, + showDrawingSetTitleDescriptionModal, + drawingSetTitle, + drawingSetDescription + } = this.state; + + this.toggleAllDraw(); + return ( + <div id="wrapper"> + <div id="map"> + <NearbyFactorDialog + mapLoad={map} + NearByFactorItems={NearByFactorItems} + /> + <div id="loginFavorContainer"> + <div + className="loginFavorBtn" + onClick={this.toggleLoginModal} + onKeyPress={this.toggleLoginModal} + role="button" + tabIndex="0" + > + {`My`} + </div> + <div + className={`loginFavorBtn ${activeFilter}`} + onClick={() => { + if (activeDraw === '') { + this.showFilter(); + } + }} + onKeyPress={() => this.showFilter} + role="button" + tabIndex="0" + > + {`ํ•„ํ„ฐ`} + </div> + <div + className={`loginFavorBtn ${activeDraw}`} + onClick={() => { + if (activeFilter === '') { + this.showDraw(); + this.descriptionModalHide(); + } + }} + onKeyPress={() => this.showDraw} + role="button" + tabIndex="0" + > + {`๊ทธ๋ฆฌ๊ธฐ`} + </div> + </div> + {showModal ? ( + <LoginModal + name={name} + toggleLoginModal={this.toggleLoginModal} + handleUserNameOnChange={this.handleUserNameOnChange} + initUserName={this.initUserName} + /> + ) : null} + <div className={!showFilter ? 'block' : 'none'}> + <FilterContainer + MyInfoButton={MyInfoButton} + myInfoToggle={this.myInfoToggle} + factorLoad={this.factorLoad} + showFilter={this.showFilter} + /> + </div> + <div className={showDraw ? 'block' : 'none'}> + <DrawContainer + handleToggle={this.showDraw} + mapLoad={map} + handleUserNameOnChange={this.handleUserNameOnChange} + drawingData={drawingData} + updateDrawingData={this.updateDrawingData} + toggleLoginModal={this.toggleLoginModal} + NearByFactorItems={NearByFactorItems} + initDrawingListAfterSave={ + this.initDrawingListAfterSave + } + showDraw={this.showDraw} + showDrawingSetTitleDescriptionModal={ + this.showDrawingSetTitleDescriptionModal + } + descriptionModalShow={this.descriptionModalShow} + descriptionModalHide={this.descriptionModalHide} + /> + </div> + {showDrawingSetTitleDescriptionModal ? ( + <DrawingSetTitleDescription + changeDrawingSetTitle={this.changeDrawingSetTitle} + changeDrawingSetDescription={ + this.changeDrawingSetDescription + } + drawingData={drawingData} + toggleLoginModal={this.toggleLoginModal} + initDrawingListAfterSave={ + this.initDrawingListAfterSave + } + showDraw={this.showDraw} + showDrawingSetTitleDescriptionModal={ + this.showDrawingSetTitleDescriptionModal + } + drawingSetTitle={drawingSetTitle} + drawingSetDescription={drawingSetDescription} + /> + ) : null} + <div + className="legend" + onClick={this.toggleLegend} + onKeyPress={this.toggleLegend} + role="button" + tabIndex="0" + /> + <div + className={ + 'colorList ' + (legendToggle ? 'invisible' : '') + } + > + {Object.keys(constants.newToggleBox).map( + (color, index) => { + return ( + <div className="eachColor" key={index}> + <div className="legendColorBox"> + <div className="colorCircle" /> + </div> + <div className="legendTextBox"> + {color} + </div> + </div> + ); + } + )} + </div> + </div> + <div> + <this.descriptionModal /> + </div> + </div> + ); + } +} + +export default App;
JavaScript
์ดํ›„ ์ฝ”๋“œ๊ฐ€ `mainPageLoad`๋ž‘ ์ค‘๋ณต๋˜๋Š” ๋ถ€๋ถ„์ด ๋งŽ์€๋ฐ ์ผ๋ฐ˜ํ™” ํ•ด์•ผ๊ฒ ๋„ค์š”.
@@ -0,0 +1,519 @@ +import React, { Component } from 'react'; +import * as d3 from 'd3'; +import drawData from './Module/loadHandle'; +import FilterContainer from './Components/FilterContainer'; +import LoginModal from './Components/LoginModal'; +import DrawContainer from './Components/DrawContainer'; +import './less/App.less'; +import * as constants from './constants'; +import * as MakeSecret from './Module/simpleEncryption'; +import NearbyFactorDialog from './Components/NearbyFactorDialog'; +import DrawingSetTitleDescription from './Components/drawingSetTitleDescriptionModal'; + +class App extends Component { + constructor(props) { + super(props); + this.bound = undefined; + this.drawList = {}; + this.newToggleBox = constants.newToggleBox; + this.state = { + name: undefined, + drawingData: [], + map: undefined, + showFilter: false, + showModal: false, + activeFilter: 'active', + activeDraw: '', + MyInfoButton: false, + showDraw: false, + factors: [], + NearByFactorItems: [], + showDrawingSetTitleDescriptionModal: false, + drawingSetTitle: null, + drawingSetDescription: null, + descriptionModalState: false, + descriptionValue: '', + descriptionTitle: '', + legendToggle: false + // NearByFilteringItems: [] + }; + } + + componentDidMount = async () => { + const naver = window.naver; + const map = await new naver.maps.Map(d3.select('#map').node(), { + zoomControl: true, + zoomControlOptions: { + style: naver.maps.ZoomControlStyle.SMALL, + position: naver.maps.Position.TOP_RIGHT + }, + logoControl: true, + logoControlOptions: { + position: naver.maps.Position.BOTTOM_RIGHT + }, + scaleControl: true, + scaleControlOptions: { + position: naver.maps.Position.BOTTOM_RIGHT + }, + mapDataControl: true, + mapDataControlOptions: { + position: naver.maps.Position.BOTTOM_LEFT + } + }); + + this.setState({ map }); + this.bound = map.getBounds(); + this.mainPageLoad(map); + naver.maps.Event.addListener(map, 'idle', e => { + const { showDraw } = this.state; + this.bound = map.getBounds(); + // ๊ทธ๋ฆฌ๊ธฐ ๋ชจ๋“œ๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ์—๋งŒ ๋ฐ์ดํ„ฐ๋ฅผ ๋ถˆ๋Ÿฌ์˜ด + if (!showDraw) { + this.mainPageLoad(map); + this.deleteDraw(); + } + }); + const name = JSON.parse(localStorage.getItem('token')); + if (name) { + this.setState({ + name: MakeSecret.Decrypt(name) + }); + } + }; + + isDelete = false; + + handleUserNameOnChange = username => { + this.setState({ name: username }); + }; + + showDrawingSetTitleDescriptionModal = value => { + this.setState({ showDrawingSetTitleDescriptionModal: value }); + }; + + changeDrawingSetTitle = text => { + this.setState({ drawingSetTitle: text }); + }; + + changeDrawingSetDescription = text => { + this.setState({ drawingSetDescription: text }); + }; + + mainPageLoad = map => { + const { name, factors } = this.state; + const bound = this.bound; + const nearbyData = async val => { + await this.setState({ + NearByFactorItems: val + }); + }; + drawData(name, bound, factors, false, this.drawList, map, nearbyData); + }; + + toggleAllDraw = () => { + const { showDraw, map } = this.state; + if (showDraw) { + Object.entries(this.drawList).forEach(([key, value]) => { + value.setMap(null); + delete this.drawList[key]; + }); + this.isDelete = true; + } else { + if (this.isDelete) { + this.mainPageLoad(map); + this.isDelete = false; + } + } + }; + + deleteDraw = () => { + Object.entries(this.drawList).forEach(([key, value]) => { + const startPos = {}; + const endPos = {}; + // reference point + startPos.x = value._lineData[0].coord.x; + startPos.y = value._lineData[0].coord.y; + endPos.x = value._lineData[value._lineData.length - 1].coord.x; + endPos.y = value._lineData[value._lineData.length - 1].coord.y; + + if ( + (startPos.x < this.bound._min._lng - 0.01 + || this.bound._max._lng + 0.01 < startPos.x + || startPos.y < this.bound._min._lat - 0.01 + || this.bound._max._lat + 0.01 < startPos.y) + && (endPos.x < this.bound._min._lng - 0.01 + || this.bound._max._lng + 0.01 < endPos.x + || endPos.y < this.bound._min._lat - 0.01 + || this.bound._max._lat + 0.01 < endPos.y) + ) { + value.setMap(null); + delete this.drawList[key]; + } + }); + }; + + toggleLoginModal = () => { + const { showModal } = this.state; + this.setState({ showModal: !showModal }); + }; + + toggleDraw = () => { + const { showDraw } = this.state; + this.setState({ descriptionModalState: false }); + this.setState({ showDraw: !showDraw }); + }; + + toggleLegend = () => { + const { legendToggle } = this.state; + this.setState({ legendToggle: !legendToggle }); + }; + + showFilter = () => { + const { showFilter, activeFilter } = this.state; + if (activeFilter === 'active') { + this.setState({ + showFilter: !showFilter, + activeFilter: '' + }); + } else { + this.setState({ + showFilter: !showFilter, + activeFilter: 'active' + }); + } + }; + + showDraw = () => { + const { showDraw, drawingData, activeDraw } = this.state; + if (drawingData.length) { + const pressedConfirm = confirm( + '์ €์žฅํ•˜์ง€ ์•Š๊ณ  ๊ทธ๋ฆฌ๊ธฐ ์ฐฝ์„ ๋‹ซ์œผ๋ฉด ๊ทธ๋ฆฐ ์ •๋ณด๋Š” ๋ชจ๋‘ ์‚ฌ๋ผ์ง‘๋‹ˆ๋‹ค!\n๊ทธ๋ž˜๋„ ๊ทธ๋ฆฌ๊ธฐ ์ฐฝ์„ ๋‹ซ์œผ์‹œ๊ฒ ์–ด์š”?' + ); + if (pressedConfirm) { + for (let index = 0; index < drawingData.length; index++) { + drawingData[index].figure.onRemove(); + } + this.setState({ drawingData: [] }); + this.setState({ descriptionModalState: false }); + } else if (!pressedConfirm) { + return; + } + } + + if (activeDraw === 'active') { + this.setState({ + showDraw: !showDraw, + activeDraw: '' + }); + } else { + this.setState({ + showDraw: !showDraw, + activeDraw: 'active' + }); + } + }; + + initDrawingListAfterSave = () => { + this.setState({ drawingData: [] }); + }; + + initUserName = () => { + this.setState({ name: undefined }); + }; + + myInfoToggle = () => { + const { MyInfoButton } = this.state; + this.setState({ MyInfoButton: !MyInfoButton }); + this.factorLoad(null, !MyInfoButton); + }; + + updateDrawingData = (shapeData, order = false, index) => { + const { drawingData } = this.state; + this.setState({ drawingData: [...drawingData, shapeData] }); + if (order) { + const newDrawingData = [...drawingData]; + newDrawingData.splice(index, 1); + this.setState({ drawingData: newDrawingData }); + } + }; + + mainToggle = (stateName, toggle) => { + this.setState({ [stateName]: !toggle }); + }; + + factorLoad = (category, toggle = false) => { + const { name, map } = this.state; + const bound = this.bound; + const factors = []; + let nearbyData; + + // ๊ธฐ์กด ์ง€๋„์— ์žˆ๋˜ ์ •๋ณด๋ฅผ ์ง€์›Œ์คŒ + Object.entries(this.drawList).forEach(([key, value]) => { + value.setMap(null); + delete this.drawList[key]; + }); + // ์œ ์ € ํ˜ธ์žฌ ๋ณด๊ธฐ + if (toggle) { + const toggleObj = {}; + Object.entries(this.newToggleBox).forEach(([key, value]) => { + toggleObj[key] = false; + }); + this.newToggleBox = toggleObj; + } + // ํ•„ํ„ฐ๋ง ํ•˜๊ธฐ + if (category) { + const toggleCategory = { + [category]: !this.newToggleBox[category] + }; + this.newToggleBox = { + ...this.newToggleBox, + ...toggleCategory + }; + Object.entries(this.newToggleBox).forEach(([key, value]) => { + if (value) { + factors.push(key); + } + }); + this.setState({ + factors: factors + }); + nearbyData = async val => { + await this.setState({ + NearByFactorItems: val + }); + }; + } + // TODO: + drawData(name, bound, factors, toggle, this.drawList, map, nearbyData); + }; + + handleChangeDescription = event => { + this.setState({ descriptionValue: event.target.value }); + }; + + handleChangeTitle = event => { + this.setState({ descriptionTitle: event.target.value }); + }; + + descriptionModal = () => { + const { + descriptionModalState, + descriptionValue, + descriptionTitle + } = this.state; + if (descriptionModalState) { + return ( + <div className="descriptionModal"> + <div className="descriptionHeader"> </div> + <textarea + placeholder="์ œ๋ชฉ์„ ์ง€์–ด์ฃผ์„ธ์š”:D" + className="descriptionInputTitle" + type="text" + value={descriptionTitle} + onChange={this.handleChangeTitle} + /> + <textarea + placeholder="ํ˜ธ์žฌ ๋‚ด์šฉ์„ ์ฑ„์›Œ์ฃผ์„ธ์š”:D" + className="descriptionInput" + type="text" + value={descriptionValue} + onChange={this.handleChangeDescription} + /> + <button + className="descriptionCloser" + type="button" + onClick={this.descriptionModalHide} + > + ๋‹ซ๊ธฐ + </button> + <button + className="descriptionSave" + type="button" + onClick={this.descriptionModalSave} + > + ์ €์žฅ + </button> + </div> + ); + } else { + return <div />; + } + }; + + descriptionModalHide = () => { + this.setState({ + descriptionModalState: false, + descriptionValue: '', + descriptionTitle: '' + }); + }; + + descriptionModalSave = () => { + const { descriptionValue, descriptionTitle, drawingData } = this.state; + this.setState({ descriptionModalState: false }); + const arrayOfShapes = drawingData; + arrayOfShapes[arrayOfShapes.length - 1].title = descriptionTitle; + arrayOfShapes[arrayOfShapes.length - 1].value = descriptionValue; + this.setState({ drawingData: arrayOfShapes }); + }; + + descriptionModalShow = () => { + this.setState({ descriptionModalState: true }); + }; + + render() { + const { + map, + name, + drawingData, + showFilter, + showDraw, + showModal, + activeFilter, + activeDraw, + MyInfoButton, + NearByFactorItems, + legendToggle, + showDrawingSetTitleDescriptionModal, + drawingSetTitle, + drawingSetDescription + } = this.state; + + this.toggleAllDraw(); + return ( + <div id="wrapper"> + <div id="map"> + <NearbyFactorDialog + mapLoad={map} + NearByFactorItems={NearByFactorItems} + /> + <div id="loginFavorContainer"> + <div + className="loginFavorBtn" + onClick={this.toggleLoginModal} + onKeyPress={this.toggleLoginModal} + role="button" + tabIndex="0" + > + {`My`} + </div> + <div + className={`loginFavorBtn ${activeFilter}`} + onClick={() => { + if (activeDraw === '') { + this.showFilter(); + } + }} + onKeyPress={() => this.showFilter} + role="button" + tabIndex="0" + > + {`ํ•„ํ„ฐ`} + </div> + <div + className={`loginFavorBtn ${activeDraw}`} + onClick={() => { + if (activeFilter === '') { + this.showDraw(); + this.descriptionModalHide(); + } + }} + onKeyPress={() => this.showDraw} + role="button" + tabIndex="0" + > + {`๊ทธ๋ฆฌ๊ธฐ`} + </div> + </div> + {showModal ? ( + <LoginModal + name={name} + toggleLoginModal={this.toggleLoginModal} + handleUserNameOnChange={this.handleUserNameOnChange} + initUserName={this.initUserName} + /> + ) : null} + <div className={!showFilter ? 'block' : 'none'}> + <FilterContainer + MyInfoButton={MyInfoButton} + myInfoToggle={this.myInfoToggle} + factorLoad={this.factorLoad} + showFilter={this.showFilter} + /> + </div> + <div className={showDraw ? 'block' : 'none'}> + <DrawContainer + handleToggle={this.showDraw} + mapLoad={map} + handleUserNameOnChange={this.handleUserNameOnChange} + drawingData={drawingData} + updateDrawingData={this.updateDrawingData} + toggleLoginModal={this.toggleLoginModal} + NearByFactorItems={NearByFactorItems} + initDrawingListAfterSave={ + this.initDrawingListAfterSave + } + showDraw={this.showDraw} + showDrawingSetTitleDescriptionModal={ + this.showDrawingSetTitleDescriptionModal + } + descriptionModalShow={this.descriptionModalShow} + descriptionModalHide={this.descriptionModalHide} + /> + </div> + {showDrawingSetTitleDescriptionModal ? ( + <DrawingSetTitleDescription + changeDrawingSetTitle={this.changeDrawingSetTitle} + changeDrawingSetDescription={ + this.changeDrawingSetDescription + } + drawingData={drawingData} + toggleLoginModal={this.toggleLoginModal} + initDrawingListAfterSave={ + this.initDrawingListAfterSave + } + showDraw={this.showDraw} + showDrawingSetTitleDescriptionModal={ + this.showDrawingSetTitleDescriptionModal + } + drawingSetTitle={drawingSetTitle} + drawingSetDescription={drawingSetDescription} + /> + ) : null} + <div + className="legend" + onClick={this.toggleLegend} + onKeyPress={this.toggleLegend} + role="button" + tabIndex="0" + /> + <div + className={ + 'colorList ' + (legendToggle ? 'invisible' : '') + } + > + {Object.keys(constants.newToggleBox).map( + (color, index) => { + return ( + <div className="eachColor" key={index}> + <div className="legendColorBox"> + <div className="colorCircle" /> + </div> + <div className="legendTextBox"> + {color} + </div> + </div> + ); + } + )} + </div> + </div> + <div> + <this.descriptionModal /> + </div> + </div> + ); + } +} + +export default App;
JavaScript
style์„ inline์œผ๋กœ ์ง์ ‘ ์ง€์ •ํ•˜๋Š” ๊ฒƒ ๋ณด๋‹ค๋Š” style์€ `less(css)`์— ์ •์˜ํ•˜๊ณ  class๋ช…์„ toggle ํ•˜๋Š” ๋ฐฉ์‹์„ ์“ฐ๋Š”๊ฒŒ ์ข‹์•„์š”.
@@ -0,0 +1,519 @@ +import React, { Component } from 'react'; +import * as d3 from 'd3'; +import drawData from './Module/loadHandle'; +import FilterContainer from './Components/FilterContainer'; +import LoginModal from './Components/LoginModal'; +import DrawContainer from './Components/DrawContainer'; +import './less/App.less'; +import * as constants from './constants'; +import * as MakeSecret from './Module/simpleEncryption'; +import NearbyFactorDialog from './Components/NearbyFactorDialog'; +import DrawingSetTitleDescription from './Components/drawingSetTitleDescriptionModal'; + +class App extends Component { + constructor(props) { + super(props); + this.bound = undefined; + this.drawList = {}; + this.newToggleBox = constants.newToggleBox; + this.state = { + name: undefined, + drawingData: [], + map: undefined, + showFilter: false, + showModal: false, + activeFilter: 'active', + activeDraw: '', + MyInfoButton: false, + showDraw: false, + factors: [], + NearByFactorItems: [], + showDrawingSetTitleDescriptionModal: false, + drawingSetTitle: null, + drawingSetDescription: null, + descriptionModalState: false, + descriptionValue: '', + descriptionTitle: '', + legendToggle: false + // NearByFilteringItems: [] + }; + } + + componentDidMount = async () => { + const naver = window.naver; + const map = await new naver.maps.Map(d3.select('#map').node(), { + zoomControl: true, + zoomControlOptions: { + style: naver.maps.ZoomControlStyle.SMALL, + position: naver.maps.Position.TOP_RIGHT + }, + logoControl: true, + logoControlOptions: { + position: naver.maps.Position.BOTTOM_RIGHT + }, + scaleControl: true, + scaleControlOptions: { + position: naver.maps.Position.BOTTOM_RIGHT + }, + mapDataControl: true, + mapDataControlOptions: { + position: naver.maps.Position.BOTTOM_LEFT + } + }); + + this.setState({ map }); + this.bound = map.getBounds(); + this.mainPageLoad(map); + naver.maps.Event.addListener(map, 'idle', e => { + const { showDraw } = this.state; + this.bound = map.getBounds(); + // ๊ทธ๋ฆฌ๊ธฐ ๋ชจ๋“œ๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ์—๋งŒ ๋ฐ์ดํ„ฐ๋ฅผ ๋ถˆ๋Ÿฌ์˜ด + if (!showDraw) { + this.mainPageLoad(map); + this.deleteDraw(); + } + }); + const name = JSON.parse(localStorage.getItem('token')); + if (name) { + this.setState({ + name: MakeSecret.Decrypt(name) + }); + } + }; + + isDelete = false; + + handleUserNameOnChange = username => { + this.setState({ name: username }); + }; + + showDrawingSetTitleDescriptionModal = value => { + this.setState({ showDrawingSetTitleDescriptionModal: value }); + }; + + changeDrawingSetTitle = text => { + this.setState({ drawingSetTitle: text }); + }; + + changeDrawingSetDescription = text => { + this.setState({ drawingSetDescription: text }); + }; + + mainPageLoad = map => { + const { name, factors } = this.state; + const bound = this.bound; + const nearbyData = async val => { + await this.setState({ + NearByFactorItems: val + }); + }; + drawData(name, bound, factors, false, this.drawList, map, nearbyData); + }; + + toggleAllDraw = () => { + const { showDraw, map } = this.state; + if (showDraw) { + Object.entries(this.drawList).forEach(([key, value]) => { + value.setMap(null); + delete this.drawList[key]; + }); + this.isDelete = true; + } else { + if (this.isDelete) { + this.mainPageLoad(map); + this.isDelete = false; + } + } + }; + + deleteDraw = () => { + Object.entries(this.drawList).forEach(([key, value]) => { + const startPos = {}; + const endPos = {}; + // reference point + startPos.x = value._lineData[0].coord.x; + startPos.y = value._lineData[0].coord.y; + endPos.x = value._lineData[value._lineData.length - 1].coord.x; + endPos.y = value._lineData[value._lineData.length - 1].coord.y; + + if ( + (startPos.x < this.bound._min._lng - 0.01 + || this.bound._max._lng + 0.01 < startPos.x + || startPos.y < this.bound._min._lat - 0.01 + || this.bound._max._lat + 0.01 < startPos.y) + && (endPos.x < this.bound._min._lng - 0.01 + || this.bound._max._lng + 0.01 < endPos.x + || endPos.y < this.bound._min._lat - 0.01 + || this.bound._max._lat + 0.01 < endPos.y) + ) { + value.setMap(null); + delete this.drawList[key]; + } + }); + }; + + toggleLoginModal = () => { + const { showModal } = this.state; + this.setState({ showModal: !showModal }); + }; + + toggleDraw = () => { + const { showDraw } = this.state; + this.setState({ descriptionModalState: false }); + this.setState({ showDraw: !showDraw }); + }; + + toggleLegend = () => { + const { legendToggle } = this.state; + this.setState({ legendToggle: !legendToggle }); + }; + + showFilter = () => { + const { showFilter, activeFilter } = this.state; + if (activeFilter === 'active') { + this.setState({ + showFilter: !showFilter, + activeFilter: '' + }); + } else { + this.setState({ + showFilter: !showFilter, + activeFilter: 'active' + }); + } + }; + + showDraw = () => { + const { showDraw, drawingData, activeDraw } = this.state; + if (drawingData.length) { + const pressedConfirm = confirm( + '์ €์žฅํ•˜์ง€ ์•Š๊ณ  ๊ทธ๋ฆฌ๊ธฐ ์ฐฝ์„ ๋‹ซ์œผ๋ฉด ๊ทธ๋ฆฐ ์ •๋ณด๋Š” ๋ชจ๋‘ ์‚ฌ๋ผ์ง‘๋‹ˆ๋‹ค!\n๊ทธ๋ž˜๋„ ๊ทธ๋ฆฌ๊ธฐ ์ฐฝ์„ ๋‹ซ์œผ์‹œ๊ฒ ์–ด์š”?' + ); + if (pressedConfirm) { + for (let index = 0; index < drawingData.length; index++) { + drawingData[index].figure.onRemove(); + } + this.setState({ drawingData: [] }); + this.setState({ descriptionModalState: false }); + } else if (!pressedConfirm) { + return; + } + } + + if (activeDraw === 'active') { + this.setState({ + showDraw: !showDraw, + activeDraw: '' + }); + } else { + this.setState({ + showDraw: !showDraw, + activeDraw: 'active' + }); + } + }; + + initDrawingListAfterSave = () => { + this.setState({ drawingData: [] }); + }; + + initUserName = () => { + this.setState({ name: undefined }); + }; + + myInfoToggle = () => { + const { MyInfoButton } = this.state; + this.setState({ MyInfoButton: !MyInfoButton }); + this.factorLoad(null, !MyInfoButton); + }; + + updateDrawingData = (shapeData, order = false, index) => { + const { drawingData } = this.state; + this.setState({ drawingData: [...drawingData, shapeData] }); + if (order) { + const newDrawingData = [...drawingData]; + newDrawingData.splice(index, 1); + this.setState({ drawingData: newDrawingData }); + } + }; + + mainToggle = (stateName, toggle) => { + this.setState({ [stateName]: !toggle }); + }; + + factorLoad = (category, toggle = false) => { + const { name, map } = this.state; + const bound = this.bound; + const factors = []; + let nearbyData; + + // ๊ธฐ์กด ์ง€๋„์— ์žˆ๋˜ ์ •๋ณด๋ฅผ ์ง€์›Œ์คŒ + Object.entries(this.drawList).forEach(([key, value]) => { + value.setMap(null); + delete this.drawList[key]; + }); + // ์œ ์ € ํ˜ธ์žฌ ๋ณด๊ธฐ + if (toggle) { + const toggleObj = {}; + Object.entries(this.newToggleBox).forEach(([key, value]) => { + toggleObj[key] = false; + }); + this.newToggleBox = toggleObj; + } + // ํ•„ํ„ฐ๋ง ํ•˜๊ธฐ + if (category) { + const toggleCategory = { + [category]: !this.newToggleBox[category] + }; + this.newToggleBox = { + ...this.newToggleBox, + ...toggleCategory + }; + Object.entries(this.newToggleBox).forEach(([key, value]) => { + if (value) { + factors.push(key); + } + }); + this.setState({ + factors: factors + }); + nearbyData = async val => { + await this.setState({ + NearByFactorItems: val + }); + }; + } + // TODO: + drawData(name, bound, factors, toggle, this.drawList, map, nearbyData); + }; + + handleChangeDescription = event => { + this.setState({ descriptionValue: event.target.value }); + }; + + handleChangeTitle = event => { + this.setState({ descriptionTitle: event.target.value }); + }; + + descriptionModal = () => { + const { + descriptionModalState, + descriptionValue, + descriptionTitle + } = this.state; + if (descriptionModalState) { + return ( + <div className="descriptionModal"> + <div className="descriptionHeader"> </div> + <textarea + placeholder="์ œ๋ชฉ์„ ์ง€์–ด์ฃผ์„ธ์š”:D" + className="descriptionInputTitle" + type="text" + value={descriptionTitle} + onChange={this.handleChangeTitle} + /> + <textarea + placeholder="ํ˜ธ์žฌ ๋‚ด์šฉ์„ ์ฑ„์›Œ์ฃผ์„ธ์š”:D" + className="descriptionInput" + type="text" + value={descriptionValue} + onChange={this.handleChangeDescription} + /> + <button + className="descriptionCloser" + type="button" + onClick={this.descriptionModalHide} + > + ๋‹ซ๊ธฐ + </button> + <button + className="descriptionSave" + type="button" + onClick={this.descriptionModalSave} + > + ์ €์žฅ + </button> + </div> + ); + } else { + return <div />; + } + }; + + descriptionModalHide = () => { + this.setState({ + descriptionModalState: false, + descriptionValue: '', + descriptionTitle: '' + }); + }; + + descriptionModalSave = () => { + const { descriptionValue, descriptionTitle, drawingData } = this.state; + this.setState({ descriptionModalState: false }); + const arrayOfShapes = drawingData; + arrayOfShapes[arrayOfShapes.length - 1].title = descriptionTitle; + arrayOfShapes[arrayOfShapes.length - 1].value = descriptionValue; + this.setState({ drawingData: arrayOfShapes }); + }; + + descriptionModalShow = () => { + this.setState({ descriptionModalState: true }); + }; + + render() { + const { + map, + name, + drawingData, + showFilter, + showDraw, + showModal, + activeFilter, + activeDraw, + MyInfoButton, + NearByFactorItems, + legendToggle, + showDrawingSetTitleDescriptionModal, + drawingSetTitle, + drawingSetDescription + } = this.state; + + this.toggleAllDraw(); + return ( + <div id="wrapper"> + <div id="map"> + <NearbyFactorDialog + mapLoad={map} + NearByFactorItems={NearByFactorItems} + /> + <div id="loginFavorContainer"> + <div + className="loginFavorBtn" + onClick={this.toggleLoginModal} + onKeyPress={this.toggleLoginModal} + role="button" + tabIndex="0" + > + {`My`} + </div> + <div + className={`loginFavorBtn ${activeFilter}`} + onClick={() => { + if (activeDraw === '') { + this.showFilter(); + } + }} + onKeyPress={() => this.showFilter} + role="button" + tabIndex="0" + > + {`ํ•„ํ„ฐ`} + </div> + <div + className={`loginFavorBtn ${activeDraw}`} + onClick={() => { + if (activeFilter === '') { + this.showDraw(); + this.descriptionModalHide(); + } + }} + onKeyPress={() => this.showDraw} + role="button" + tabIndex="0" + > + {`๊ทธ๋ฆฌ๊ธฐ`} + </div> + </div> + {showModal ? ( + <LoginModal + name={name} + toggleLoginModal={this.toggleLoginModal} + handleUserNameOnChange={this.handleUserNameOnChange} + initUserName={this.initUserName} + /> + ) : null} + <div className={!showFilter ? 'block' : 'none'}> + <FilterContainer + MyInfoButton={MyInfoButton} + myInfoToggle={this.myInfoToggle} + factorLoad={this.factorLoad} + showFilter={this.showFilter} + /> + </div> + <div className={showDraw ? 'block' : 'none'}> + <DrawContainer + handleToggle={this.showDraw} + mapLoad={map} + handleUserNameOnChange={this.handleUserNameOnChange} + drawingData={drawingData} + updateDrawingData={this.updateDrawingData} + toggleLoginModal={this.toggleLoginModal} + NearByFactorItems={NearByFactorItems} + initDrawingListAfterSave={ + this.initDrawingListAfterSave + } + showDraw={this.showDraw} + showDrawingSetTitleDescriptionModal={ + this.showDrawingSetTitleDescriptionModal + } + descriptionModalShow={this.descriptionModalShow} + descriptionModalHide={this.descriptionModalHide} + /> + </div> + {showDrawingSetTitleDescriptionModal ? ( + <DrawingSetTitleDescription + changeDrawingSetTitle={this.changeDrawingSetTitle} + changeDrawingSetDescription={ + this.changeDrawingSetDescription + } + drawingData={drawingData} + toggleLoginModal={this.toggleLoginModal} + initDrawingListAfterSave={ + this.initDrawingListAfterSave + } + showDraw={this.showDraw} + showDrawingSetTitleDescriptionModal={ + this.showDrawingSetTitleDescriptionModal + } + drawingSetTitle={drawingSetTitle} + drawingSetDescription={drawingSetDescription} + /> + ) : null} + <div + className="legend" + onClick={this.toggleLegend} + onKeyPress={this.toggleLegend} + role="button" + tabIndex="0" + /> + <div + className={ + 'colorList ' + (legendToggle ? 'invisible' : '') + } + > + {Object.keys(constants.newToggleBox).map( + (color, index) => { + return ( + <div className="eachColor" key={index}> + <div className="legendColorBox"> + <div className="colorCircle" /> + </div> + <div className="legendTextBox"> + {color} + </div> + </div> + ); + } + )} + </div> + </div> + <div> + <this.descriptionModal /> + </div> + </div> + ); + } +} + +export default App;
JavaScript
์—ฌ๊ธฐ๋„ ๋งˆ์ฐฌ๊ฐ€์ง€
@@ -0,0 +1,519 @@ +import React, { Component } from 'react'; +import * as d3 from 'd3'; +import drawData from './Module/loadHandle'; +import FilterContainer from './Components/FilterContainer'; +import LoginModal from './Components/LoginModal'; +import DrawContainer from './Components/DrawContainer'; +import './less/App.less'; +import * as constants from './constants'; +import * as MakeSecret from './Module/simpleEncryption'; +import NearbyFactorDialog from './Components/NearbyFactorDialog'; +import DrawingSetTitleDescription from './Components/drawingSetTitleDescriptionModal'; + +class App extends Component { + constructor(props) { + super(props); + this.bound = undefined; + this.drawList = {}; + this.newToggleBox = constants.newToggleBox; + this.state = { + name: undefined, + drawingData: [], + map: undefined, + showFilter: false, + showModal: false, + activeFilter: 'active', + activeDraw: '', + MyInfoButton: false, + showDraw: false, + factors: [], + NearByFactorItems: [], + showDrawingSetTitleDescriptionModal: false, + drawingSetTitle: null, + drawingSetDescription: null, + descriptionModalState: false, + descriptionValue: '', + descriptionTitle: '', + legendToggle: false + // NearByFilteringItems: [] + }; + } + + componentDidMount = async () => { + const naver = window.naver; + const map = await new naver.maps.Map(d3.select('#map').node(), { + zoomControl: true, + zoomControlOptions: { + style: naver.maps.ZoomControlStyle.SMALL, + position: naver.maps.Position.TOP_RIGHT + }, + logoControl: true, + logoControlOptions: { + position: naver.maps.Position.BOTTOM_RIGHT + }, + scaleControl: true, + scaleControlOptions: { + position: naver.maps.Position.BOTTOM_RIGHT + }, + mapDataControl: true, + mapDataControlOptions: { + position: naver.maps.Position.BOTTOM_LEFT + } + }); + + this.setState({ map }); + this.bound = map.getBounds(); + this.mainPageLoad(map); + naver.maps.Event.addListener(map, 'idle', e => { + const { showDraw } = this.state; + this.bound = map.getBounds(); + // ๊ทธ๋ฆฌ๊ธฐ ๋ชจ๋“œ๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ์—๋งŒ ๋ฐ์ดํ„ฐ๋ฅผ ๋ถˆ๋Ÿฌ์˜ด + if (!showDraw) { + this.mainPageLoad(map); + this.deleteDraw(); + } + }); + const name = JSON.parse(localStorage.getItem('token')); + if (name) { + this.setState({ + name: MakeSecret.Decrypt(name) + }); + } + }; + + isDelete = false; + + handleUserNameOnChange = username => { + this.setState({ name: username }); + }; + + showDrawingSetTitleDescriptionModal = value => { + this.setState({ showDrawingSetTitleDescriptionModal: value }); + }; + + changeDrawingSetTitle = text => { + this.setState({ drawingSetTitle: text }); + }; + + changeDrawingSetDescription = text => { + this.setState({ drawingSetDescription: text }); + }; + + mainPageLoad = map => { + const { name, factors } = this.state; + const bound = this.bound; + const nearbyData = async val => { + await this.setState({ + NearByFactorItems: val + }); + }; + drawData(name, bound, factors, false, this.drawList, map, nearbyData); + }; + + toggleAllDraw = () => { + const { showDraw, map } = this.state; + if (showDraw) { + Object.entries(this.drawList).forEach(([key, value]) => { + value.setMap(null); + delete this.drawList[key]; + }); + this.isDelete = true; + } else { + if (this.isDelete) { + this.mainPageLoad(map); + this.isDelete = false; + } + } + }; + + deleteDraw = () => { + Object.entries(this.drawList).forEach(([key, value]) => { + const startPos = {}; + const endPos = {}; + // reference point + startPos.x = value._lineData[0].coord.x; + startPos.y = value._lineData[0].coord.y; + endPos.x = value._lineData[value._lineData.length - 1].coord.x; + endPos.y = value._lineData[value._lineData.length - 1].coord.y; + + if ( + (startPos.x < this.bound._min._lng - 0.01 + || this.bound._max._lng + 0.01 < startPos.x + || startPos.y < this.bound._min._lat - 0.01 + || this.bound._max._lat + 0.01 < startPos.y) + && (endPos.x < this.bound._min._lng - 0.01 + || this.bound._max._lng + 0.01 < endPos.x + || endPos.y < this.bound._min._lat - 0.01 + || this.bound._max._lat + 0.01 < endPos.y) + ) { + value.setMap(null); + delete this.drawList[key]; + } + }); + }; + + toggleLoginModal = () => { + const { showModal } = this.state; + this.setState({ showModal: !showModal }); + }; + + toggleDraw = () => { + const { showDraw } = this.state; + this.setState({ descriptionModalState: false }); + this.setState({ showDraw: !showDraw }); + }; + + toggleLegend = () => { + const { legendToggle } = this.state; + this.setState({ legendToggle: !legendToggle }); + }; + + showFilter = () => { + const { showFilter, activeFilter } = this.state; + if (activeFilter === 'active') { + this.setState({ + showFilter: !showFilter, + activeFilter: '' + }); + } else { + this.setState({ + showFilter: !showFilter, + activeFilter: 'active' + }); + } + }; + + showDraw = () => { + const { showDraw, drawingData, activeDraw } = this.state; + if (drawingData.length) { + const pressedConfirm = confirm( + '์ €์žฅํ•˜์ง€ ์•Š๊ณ  ๊ทธ๋ฆฌ๊ธฐ ์ฐฝ์„ ๋‹ซ์œผ๋ฉด ๊ทธ๋ฆฐ ์ •๋ณด๋Š” ๋ชจ๋‘ ์‚ฌ๋ผ์ง‘๋‹ˆ๋‹ค!\n๊ทธ๋ž˜๋„ ๊ทธ๋ฆฌ๊ธฐ ์ฐฝ์„ ๋‹ซ์œผ์‹œ๊ฒ ์–ด์š”?' + ); + if (pressedConfirm) { + for (let index = 0; index < drawingData.length; index++) { + drawingData[index].figure.onRemove(); + } + this.setState({ drawingData: [] }); + this.setState({ descriptionModalState: false }); + } else if (!pressedConfirm) { + return; + } + } + + if (activeDraw === 'active') { + this.setState({ + showDraw: !showDraw, + activeDraw: '' + }); + } else { + this.setState({ + showDraw: !showDraw, + activeDraw: 'active' + }); + } + }; + + initDrawingListAfterSave = () => { + this.setState({ drawingData: [] }); + }; + + initUserName = () => { + this.setState({ name: undefined }); + }; + + myInfoToggle = () => { + const { MyInfoButton } = this.state; + this.setState({ MyInfoButton: !MyInfoButton }); + this.factorLoad(null, !MyInfoButton); + }; + + updateDrawingData = (shapeData, order = false, index) => { + const { drawingData } = this.state; + this.setState({ drawingData: [...drawingData, shapeData] }); + if (order) { + const newDrawingData = [...drawingData]; + newDrawingData.splice(index, 1); + this.setState({ drawingData: newDrawingData }); + } + }; + + mainToggle = (stateName, toggle) => { + this.setState({ [stateName]: !toggle }); + }; + + factorLoad = (category, toggle = false) => { + const { name, map } = this.state; + const bound = this.bound; + const factors = []; + let nearbyData; + + // ๊ธฐ์กด ์ง€๋„์— ์žˆ๋˜ ์ •๋ณด๋ฅผ ์ง€์›Œ์คŒ + Object.entries(this.drawList).forEach(([key, value]) => { + value.setMap(null); + delete this.drawList[key]; + }); + // ์œ ์ € ํ˜ธ์žฌ ๋ณด๊ธฐ + if (toggle) { + const toggleObj = {}; + Object.entries(this.newToggleBox).forEach(([key, value]) => { + toggleObj[key] = false; + }); + this.newToggleBox = toggleObj; + } + // ํ•„ํ„ฐ๋ง ํ•˜๊ธฐ + if (category) { + const toggleCategory = { + [category]: !this.newToggleBox[category] + }; + this.newToggleBox = { + ...this.newToggleBox, + ...toggleCategory + }; + Object.entries(this.newToggleBox).forEach(([key, value]) => { + if (value) { + factors.push(key); + } + }); + this.setState({ + factors: factors + }); + nearbyData = async val => { + await this.setState({ + NearByFactorItems: val + }); + }; + } + // TODO: + drawData(name, bound, factors, toggle, this.drawList, map, nearbyData); + }; + + handleChangeDescription = event => { + this.setState({ descriptionValue: event.target.value }); + }; + + handleChangeTitle = event => { + this.setState({ descriptionTitle: event.target.value }); + }; + + descriptionModal = () => { + const { + descriptionModalState, + descriptionValue, + descriptionTitle + } = this.state; + if (descriptionModalState) { + return ( + <div className="descriptionModal"> + <div className="descriptionHeader"> </div> + <textarea + placeholder="์ œ๋ชฉ์„ ์ง€์–ด์ฃผ์„ธ์š”:D" + className="descriptionInputTitle" + type="text" + value={descriptionTitle} + onChange={this.handleChangeTitle} + /> + <textarea + placeholder="ํ˜ธ์žฌ ๋‚ด์šฉ์„ ์ฑ„์›Œ์ฃผ์„ธ์š”:D" + className="descriptionInput" + type="text" + value={descriptionValue} + onChange={this.handleChangeDescription} + /> + <button + className="descriptionCloser" + type="button" + onClick={this.descriptionModalHide} + > + ๋‹ซ๊ธฐ + </button> + <button + className="descriptionSave" + type="button" + onClick={this.descriptionModalSave} + > + ์ €์žฅ + </button> + </div> + ); + } else { + return <div />; + } + }; + + descriptionModalHide = () => { + this.setState({ + descriptionModalState: false, + descriptionValue: '', + descriptionTitle: '' + }); + }; + + descriptionModalSave = () => { + const { descriptionValue, descriptionTitle, drawingData } = this.state; + this.setState({ descriptionModalState: false }); + const arrayOfShapes = drawingData; + arrayOfShapes[arrayOfShapes.length - 1].title = descriptionTitle; + arrayOfShapes[arrayOfShapes.length - 1].value = descriptionValue; + this.setState({ drawingData: arrayOfShapes }); + }; + + descriptionModalShow = () => { + this.setState({ descriptionModalState: true }); + }; + + render() { + const { + map, + name, + drawingData, + showFilter, + showDraw, + showModal, + activeFilter, + activeDraw, + MyInfoButton, + NearByFactorItems, + legendToggle, + showDrawingSetTitleDescriptionModal, + drawingSetTitle, + drawingSetDescription + } = this.state; + + this.toggleAllDraw(); + return ( + <div id="wrapper"> + <div id="map"> + <NearbyFactorDialog + mapLoad={map} + NearByFactorItems={NearByFactorItems} + /> + <div id="loginFavorContainer"> + <div + className="loginFavorBtn" + onClick={this.toggleLoginModal} + onKeyPress={this.toggleLoginModal} + role="button" + tabIndex="0" + > + {`My`} + </div> + <div + className={`loginFavorBtn ${activeFilter}`} + onClick={() => { + if (activeDraw === '') { + this.showFilter(); + } + }} + onKeyPress={() => this.showFilter} + role="button" + tabIndex="0" + > + {`ํ•„ํ„ฐ`} + </div> + <div + className={`loginFavorBtn ${activeDraw}`} + onClick={() => { + if (activeFilter === '') { + this.showDraw(); + this.descriptionModalHide(); + } + }} + onKeyPress={() => this.showDraw} + role="button" + tabIndex="0" + > + {`๊ทธ๋ฆฌ๊ธฐ`} + </div> + </div> + {showModal ? ( + <LoginModal + name={name} + toggleLoginModal={this.toggleLoginModal} + handleUserNameOnChange={this.handleUserNameOnChange} + initUserName={this.initUserName} + /> + ) : null} + <div className={!showFilter ? 'block' : 'none'}> + <FilterContainer + MyInfoButton={MyInfoButton} + myInfoToggle={this.myInfoToggle} + factorLoad={this.factorLoad} + showFilter={this.showFilter} + /> + </div> + <div className={showDraw ? 'block' : 'none'}> + <DrawContainer + handleToggle={this.showDraw} + mapLoad={map} + handleUserNameOnChange={this.handleUserNameOnChange} + drawingData={drawingData} + updateDrawingData={this.updateDrawingData} + toggleLoginModal={this.toggleLoginModal} + NearByFactorItems={NearByFactorItems} + initDrawingListAfterSave={ + this.initDrawingListAfterSave + } + showDraw={this.showDraw} + showDrawingSetTitleDescriptionModal={ + this.showDrawingSetTitleDescriptionModal + } + descriptionModalShow={this.descriptionModalShow} + descriptionModalHide={this.descriptionModalHide} + /> + </div> + {showDrawingSetTitleDescriptionModal ? ( + <DrawingSetTitleDescription + changeDrawingSetTitle={this.changeDrawingSetTitle} + changeDrawingSetDescription={ + this.changeDrawingSetDescription + } + drawingData={drawingData} + toggleLoginModal={this.toggleLoginModal} + initDrawingListAfterSave={ + this.initDrawingListAfterSave + } + showDraw={this.showDraw} + showDrawingSetTitleDescriptionModal={ + this.showDrawingSetTitleDescriptionModal + } + drawingSetTitle={drawingSetTitle} + drawingSetDescription={drawingSetDescription} + /> + ) : null} + <div + className="legend" + onClick={this.toggleLegend} + onKeyPress={this.toggleLegend} + role="button" + tabIndex="0" + /> + <div + className={ + 'colorList ' + (legendToggle ? 'invisible' : '') + } + > + {Object.keys(constants.newToggleBox).map( + (color, index) => { + return ( + <div className="eachColor" key={index}> + <div className="legendColorBox"> + <div className="colorCircle" /> + </div> + <div className="legendTextBox"> + {color} + </div> + </div> + ); + } + )} + </div> + </div> + <div> + <this.descriptionModal /> + </div> + </div> + ); + } +} + +export default App;
JavaScript
`closeFn` ์ด๋ ‡๊ฒŒ postfix๋กœ ๋„ค์ด๋ฐํ•˜๋Š” ๊ฒƒ๋„ ๋‹ค๋ฅธ ํ•จ์ˆ˜๋“ค๊ณผ๋Š” ๋‹ค๋ฅธ ๋ฐฉ์‹์œผ๋กœ ์ฒ˜๋ฆฌ๋˜์—ˆ๋„ค์š”. ํ†ต์ผ์„ฑ์„ ์œ„ํ•ด ๊ทธ๋ƒฅ ๋–ผ๋Š”๊ฒŒ ์ข‹๊ฒ ์Œ. `onClose` ์ •๋„๋‚˜, ํ˜น์€ ์•„๋ž˜์ชฝ์—” `handle~` ์ด๋Ÿฐ์‹์œผ๋กœ ์ผ์œผ๋‹ˆ `handleToggle` ๋ญ ์ด๋Ÿฐ์‹์ด์–ด๋„ ์ข‹๊ฒ ๊ณ ์š”.
@@ -0,0 +1,62 @@ +import React, { Component } from 'react'; +import PropTypes from 'prop-types'; +import Drawing from './Drawing'; +import '../less/Toolbox.less'; + +class DrawContainer extends Component { + static propTypes = { + drawingData: PropTypes.array.isRequired, + mapLoad: PropTypes.object, + handleToggle: PropTypes.func.isRequired, + updateDrawingData: PropTypes.func.isRequired, + toggleLoginModal: PropTypes.func.isRequired, + NearByFactorItems: PropTypes.array.isRequired, + initDrawingListAfterSave: PropTypes.func.isRequired, + showDraw: PropTypes.func.isRequired, + showDrawingSetTitleDescriptionModal: PropTypes.func.isRequired, + descriptionModalShow: PropTypes.func.isRequired, + descriptionModalHide: PropTypes.func.isRequired + }; + + render() { + const { + drawingData, + mapLoad, + handleToggle, + toggleLoginModal, + updateDrawingData, + NearByFactorItems, + initDrawingListAfterSave, + showDraw, + showDrawingSetTitleDescriptionModal, + descriptionModalShow, + descriptionModalHide + } = this.props; + return ( + <div id="toolbox"> + <div id="tabMenu"> + <div className="eachTabMenu">๊ทธ๋ฆฌ๊ธฐ</div> + </div> + <div> + <div> + <Drawing + map={mapLoad} + drawingData={drawingData} + updateDrawingData={updateDrawingData} + toggleLoginModal={toggleLoginModal} + handleToggle={handleToggle} + NearByFactorItems={NearByFactorItems} + initDrawingListAfterSave={initDrawingListAfterSave} + showDraw={showDraw} + showDrawingSetTitleDescriptionModal={showDrawingSetTitleDescriptionModal} + descriptionModalShow={descriptionModalShow} + descriptionModalHide={descriptionModalHide} + /> + </div> + </div> + </div> + ); + } +} + +export default DrawContainer;
JavaScript
less ๋กœ ๋นผ๋‚ด๊ธฐ
@@ -0,0 +1,62 @@ +import React, { Component } from 'react'; +import PropTypes from 'prop-types'; +import Drawing from './Drawing'; +import '../less/Toolbox.less'; + +class DrawContainer extends Component { + static propTypes = { + drawingData: PropTypes.array.isRequired, + mapLoad: PropTypes.object, + handleToggle: PropTypes.func.isRequired, + updateDrawingData: PropTypes.func.isRequired, + toggleLoginModal: PropTypes.func.isRequired, + NearByFactorItems: PropTypes.array.isRequired, + initDrawingListAfterSave: PropTypes.func.isRequired, + showDraw: PropTypes.func.isRequired, + showDrawingSetTitleDescriptionModal: PropTypes.func.isRequired, + descriptionModalShow: PropTypes.func.isRequired, + descriptionModalHide: PropTypes.func.isRequired + }; + + render() { + const { + drawingData, + mapLoad, + handleToggle, + toggleLoginModal, + updateDrawingData, + NearByFactorItems, + initDrawingListAfterSave, + showDraw, + showDrawingSetTitleDescriptionModal, + descriptionModalShow, + descriptionModalHide + } = this.props; + return ( + <div id="toolbox"> + <div id="tabMenu"> + <div className="eachTabMenu">๊ทธ๋ฆฌ๊ธฐ</div> + </div> + <div> + <div> + <Drawing + map={mapLoad} + drawingData={drawingData} + updateDrawingData={updateDrawingData} + toggleLoginModal={toggleLoginModal} + handleToggle={handleToggle} + NearByFactorItems={NearByFactorItems} + initDrawingListAfterSave={initDrawingListAfterSave} + showDraw={showDraw} + showDrawingSetTitleDescriptionModal={showDrawingSetTitleDescriptionModal} + descriptionModalShow={descriptionModalShow} + descriptionModalHide={descriptionModalHide} + /> + </div> + </div> + </div> + ); + } +} + +export default DrawContainer;
JavaScript
{``} ๋กœ ๊ฐ์Œ€ ํ•„์š”๊ฐ€ ์—†์Œ
@@ -0,0 +1,438 @@ +import React, { Component } from 'react'; +import PropTypes from 'prop-types'; +import '../less/Drawing.less'; +import Button from '../Module/Button'; +import Line from '../CustomOverlay/Line'; +import Arrow from '../CustomOverlay/Arrow'; +import Circle from '../CustomOverlay/Circle'; +import Rect from '../CustomOverlay/Rect'; +import Polygon from '../CustomOverlay/Polygon'; +import MyDrawingElement from './MyDrawingElement'; +import saveHandle from '../Module/saveHandle'; +import * as constants from '../constants'; + +class Drawing extends Component { + static propTypes = { + map: PropTypes.object, + handleToggle: PropTypes.func.isRequired, + toggleLoginModal: PropTypes.func.isRequired, + drawingData: PropTypes.array.isRequired, + updateDrawingData: PropTypes.func.isRequired, + initDrawingListAfterSave: PropTypes.func.isRequired, + showDraw: PropTypes.func.isRequired, + showDrawingSetTitleDescriptionModal: PropTypes.func.isRequired, + descriptionModalShow: PropTypes.func.isRequired, + descriptionModalHide: PropTypes.func.isRequired + }; + + state = { + selectedButton: null, + loadedListener: null, + isInShapeCreateMode: false, + refresh: true, + fillOrNotToggle1: false, + fillOrNotToggle2: false, + isSelectStatus: { + Line: false, + Arrow: false, + Rect: false, + Circle: false, + Polygon: false + } + }; + + color = undefined; + + factorId = undefined; + + fill = undefined; + + handleRequestSave = data => { + const { + toggleLoginModal, + initDrawingListAfterSave, + showDraw, + showDrawingSetTitleDescriptionModal + } = this.props; + this.setState({ + fillOrNotToggle1: false, + fillOrNotToggle2: false + }); + saveHandle( + data, + null, + toggleLoginModal, + initDrawingListAfterSave, + showDraw, + showDrawingSetTitleDescriptionModal + ); + }; + + removeListener = () => { + const naver = window.naver; + const { leftClick } = this.state; + const { rightClick } = this.state; + naver.maps.Event.removeListener(leftClick); + naver.maps.Event.removeListener(rightClick); + }; + + createShapeTest = selectedIcon => { + let position; + const naver = window.naver; + const { map, updateDrawingData, descriptionModalShow } = this.props; + const icons = Object.values(constants.typeOfShape); + const overlays = [Line, Arrow, Rect, Circle, Polygon]; // Change name of index to actual overlay name of import + let Shape; + let shapeIndex; + let moveEvent; + let figure; + let lineData = []; + let isClick = false; + + for (let index = 0; index < icons.length; index++) { + if (selectedIcon === icons[index]) { + Shape = overlays[index]; + shapeIndex = index; + } + } + const shapeName = constants.typeOfShape[shapeIndex]; + const { loadedListener } = this.state; + + if (loadedListener !== null) { + naver.maps.Event.removeListener(loadedListener.leftClick); + naver.maps.Event.removeListener(loadedListener.rightClick); + } + + const leftClick = naver.maps.Event.addListener(map, 'click', e => { + const { coord, offset } = e; + position = { coord, offset }; + lineData.push(position); + isClick = true; + // ์ฒ˜์Œ ํด๋ฆญ์‹œ + if (lineData.length === 1) { + lineData.push(position); + // ํ˜ธ์žฌ์™€ ์ฑ„์šฐ๊ธฐ๋ฅผ ์„ ํƒํ•œ ๊ฒฝ์šฐ + if (this.fill && this.color) { + figure = new Shape({ + factorId: this.factorId, + fill: this.fill, + color: this.color, + lineData: lineData, + naverMap: map + }); + figure.setMap(map); + } else { + if (!this.fill && !this.color) { + alert('๋„ํ˜• ์˜ต์…˜๊ณผ ํ˜ธ์žฌ๋ฅผ ์„ ํƒํ•ด์ฃผ์„ธ์š”'); + } else if (!this.fill) { + alert('๋„ํ˜• ์˜ต์…˜์„ ์„ ํƒํ•ด์ฃผ์„ธ์š”'); + } else if (!this.color) { + alert('ํ˜ธ์žฌ๋ฅผ ์„ ํƒํ•ด์ฃผ์„ธ์š”'); + } + lineData = []; + isClick = false; + } + } else { + if ( + shapeName === 'Rect' + || shapeName === 'Circle' + || shapeName === 'Line' + ) { + updateDrawingData({ + figure, + lineData, + shapeType: shapeName + }); + lineData.pop(); + this.fill = undefined; + this.color = undefined; + naver.maps.Event.removeListener(moveEvent); + naver.maps.Event.removeListener(leftClick); + this.setState({ + isInShapeCreateMode: false + }); + this.selectButton(); + descriptionModalShow(); + } else { + figure.draw(lineData); + } + figure.setMap(map); + } + }); + + moveEvent = naver.maps.Event.addListener(map, 'mousemove', e => { + // ํด๋ฆญ ํ›„ ์ด๋™์‹œ + if (isClick) { + const { coord, offset } = e; + position = { coord, offset }; + lineData[lineData.length - 1] = position; + figure.draw(lineData); + } + }); + + const rightClick = naver.maps.Event.addListener(map, 'rightclick', e => { + if (shapeName === 'Polygon' || shapeName === 'Arrow') { + // ํ•ด๋‹น ํฌ์ธํŠธ๋ฅผ ์ง€์›Œ์คŒ + lineData.pop(); + // ์ฒซ ํด๋ฆญ ์ดํ›„ ์šฐํด๋ฆญ์„ ํ•œ ๊ฒฝ์šฐ + if (lineData.length === 1) { + figure.onRemove(); + } else { + figure.draw(lineData); + updateDrawingData({ + figure, + lineData, + shapeType: shapeName + }); + } + this.setState({ + isInShapeCreateMode: false + }); + this.selectButton(); + descriptionModalShow(); + naver.maps.Event.removeListener(moveEvent); + naver.maps.Event.removeListener(leftClick); + } + naver.maps.Event.removeListener(rightClick); + }); + this.setState({ + loadedListener: { + leftClick, + rightClick + } + }); + }; + + selectButton = selectedIcon => { + const { isInShapeCreateMode, isSelectStatus } = this.state; + const { descriptionModalHide } = this.props; + const resetStatus = { ...isSelectStatus }; + for (const key in resetStatus) { + if (key === selectedIcon && resetStatus[key]) { + resetStatus[key] = false; + } else if (key === selectedIcon) { + resetStatus[key] = !resetStatus[key]; + } else { + resetStatus[key] = false; + } + } + const newStatus = Object.assign({ ...isSelectStatus }, resetStatus); + this.setState({ + selectedButton: selectedIcon, + isInShapeCreateMode: !isInShapeCreateMode, + isSelectStatus: newStatus, + fillOrNotToggle1: false, + fillOrNotToggle2: false + }); + this.createShapeTest(selectedIcon); // Enter parameter for different shape + descriptionModalHide(); + }; + + doNotShowTips = () => { + const { refresh } = this.state; + sessionStorage.setItem('doNotShowTipsForDrawing', JSON.stringify(true)); + this.setState({ refresh: !refresh }); + }; + + fillOrnot = fillval => { + this.fill = fillval; + const { fillOrNotToggle1, fillOrNotToggle2 } = this.state; + if (fillval === 'fill') { + this.setState({ + fillOrNotToggle1: !fillOrNotToggle1 + }); + } else { + this.setState({ + fillOrNotToggle2: !fillOrNotToggle2 + }); + } + }; + + decideFactor = factorNum => { + this.factorId = factorNum + 1; + this.color = constants.colorList[factorNum]; + }; + + render() { + const { + map, + handleToggle, + drawingData, + updateDrawingData + } = this.props; + const { + selectedButton, + isInShapeCreateMode, + isSelectStatus, + fillOrNotToggle1, + fillOrNotToggle2 + } = this.state; + const shapeStatus = Object.values(isSelectStatus).some(el => el === true); + const doNotShowTips = JSON.parse( + sessionStorage.getItem('doNotShowTipsForDrawing') + ); + const newToggleBox = Object.keys(constants.newToggleBox); + + if (isInShapeCreateMode) { + const mapDiv = document.querySelector('#map').childNodes[6]; + if (mapDiv.style.cursor !== 'crosshair') { + mapDiv.style.cursor = 'crosshair'; + } + window.naver.maps.Event.addListener(map, 'mouseup', e => { + const { isInShapeCreateMode } = this.state; + if ( + isInShapeCreateMode + && mapDiv.style.cursor !== 'crosshair' + ) { + mapDiv.style.cursor = 'crosshair'; + } else if ( + !isInShapeCreateMode + && mapDiv.style.cursor !== 'grab' + ) { + mapDiv.style.cursor = 'grab'; + } + }); + window.naver.maps.Event.addListener(map, 'mousedown', e => { + const { isInShapeCreateMode } = this.state; + if ( + isInShapeCreateMode + && mapDiv.style.cursor !== 'crosshair' + ) { + mapDiv.style.cursor = 'crosshair'; + } else if ( + !isInShapeCreateMode + && mapDiv.style.cursor !== 'grabbing' + ) { + mapDiv.style.cursor = 'grabbing'; + } + }); + } else { + if (map) { + const mapDiv = document.querySelector('#map').childNodes[6]; + if (mapDiv.style.cursor !== 'grab') { + mapDiv.style.cursor = 'grab'; + } + } + } + return ( + <div id="drawingComponentContainer"> + {Object.values(constants.typeOfShape).map(shape => { + return ( + <Button + map={map} + key={shape} + icons={shape} + selectButton={this.selectButton} + isSelected={ + selectedButton === shape && isInShapeCreateMode + ? true + : false + } + /> + ); + })} + {shapeStatus ? ( + <div + className={'selectOption ' + (shapeStatus ? '' : 'invisible')} + > + <div className="fillOrNot"> + <div + className={ + 'lineOrFillBox ' + + (fillOrNotToggle1 ? 'a' : '') + } + onClick={() => this.fillOrnot('fill')} + onKeyPress={this.fillOrnot} + role="button" + tabIndex="0" + > + Fill + </div> + <div + className={ + 'lineOrFillBox ' + + (fillOrNotToggle2 ? 'b' : '') + } + onClick={() => this.fillOrnot('none')} + onKeyPress={this.fillOrnot} + role="button" + tabIndex="0" + > + Outline + </div> + </div> + <div className="factorContainerBox"> + {newToggleBox.map((factor, idx) => { + return ( + <div + className="factorBox" + onClick={() => this.decideFactor(idx - 1)} + onKeyPress={this.decideFactor} + role="button" + tabIndex="0" + key={idx} + > + <div className="factorContain"> + <div className="factorColorBox" /> + <div className="factorText"> + {factor} + </div> + </div> + </div> + ); + })} + </div> + </div> + ) : null} + <div id="myDrawingsContainer"> + <MyDrawingElement + drawingData={drawingData} + updateDrawingData={updateDrawingData} + /> + </div> + <div id="saveCloseBtns"> + <button + type="button" + className="saveCloseBtn" + onClick={() => { + this.handleRequestSave(drawingData); + // puppeteer.captureImage(); + }} + > + {`์ €์žฅ`} + </button> + <button + type="button" + className="saveCloseBtn" + onClick={() => { + handleToggle(); + }} + > + {`๋‹ซ๊ธฐ`} + </button> + </div> + {doNotShowTips ? null : ( + <div className="tipModalForDrawing"> + <div className="arrowBoxForDrawing"> + <p> + ํ•„ํ„ฐ๋ณ„๋กœ ๋ถ€๋™์‚ฐ ํ˜ธ์žฌ์ •๋ณด๋ฅผ ๋ณด๊ณ ์‹ถ๋‹ค๋ฉด ๊ทธ๋ฆฌ๊ธฐ + ๋ชจ๋“œ๋ฅผ ๋‹ซ๊ณ  ํ•„ํ„ฐ ๋ฉ”๋‰ด๋ฅผ ์„ ํƒํ•ด์ฃผ์„ธ์š”! + </p> + <div + className="doNotShowTipsForDrawing" + onClick={this.doNotShowTips} + onKeyDown={this.doNotShowTips} + role="button" + tabIndex="0" + > + ๋‹ค์‹œ ๋ณด์ง€ ์•Š๊ธฐ + </div> + </div> + </div> + )} + </div> + ); + } +} + +export default Drawing;
JavaScript
key ์ •์˜ ์•ˆ๋˜์—ˆ์Œ
@@ -0,0 +1,438 @@ +import React, { Component } from 'react'; +import PropTypes from 'prop-types'; +import '../less/Drawing.less'; +import Button from '../Module/Button'; +import Line from '../CustomOverlay/Line'; +import Arrow from '../CustomOverlay/Arrow'; +import Circle from '../CustomOverlay/Circle'; +import Rect from '../CustomOverlay/Rect'; +import Polygon from '../CustomOverlay/Polygon'; +import MyDrawingElement from './MyDrawingElement'; +import saveHandle from '../Module/saveHandle'; +import * as constants from '../constants'; + +class Drawing extends Component { + static propTypes = { + map: PropTypes.object, + handleToggle: PropTypes.func.isRequired, + toggleLoginModal: PropTypes.func.isRequired, + drawingData: PropTypes.array.isRequired, + updateDrawingData: PropTypes.func.isRequired, + initDrawingListAfterSave: PropTypes.func.isRequired, + showDraw: PropTypes.func.isRequired, + showDrawingSetTitleDescriptionModal: PropTypes.func.isRequired, + descriptionModalShow: PropTypes.func.isRequired, + descriptionModalHide: PropTypes.func.isRequired + }; + + state = { + selectedButton: null, + loadedListener: null, + isInShapeCreateMode: false, + refresh: true, + fillOrNotToggle1: false, + fillOrNotToggle2: false, + isSelectStatus: { + Line: false, + Arrow: false, + Rect: false, + Circle: false, + Polygon: false + } + }; + + color = undefined; + + factorId = undefined; + + fill = undefined; + + handleRequestSave = data => { + const { + toggleLoginModal, + initDrawingListAfterSave, + showDraw, + showDrawingSetTitleDescriptionModal + } = this.props; + this.setState({ + fillOrNotToggle1: false, + fillOrNotToggle2: false + }); + saveHandle( + data, + null, + toggleLoginModal, + initDrawingListAfterSave, + showDraw, + showDrawingSetTitleDescriptionModal + ); + }; + + removeListener = () => { + const naver = window.naver; + const { leftClick } = this.state; + const { rightClick } = this.state; + naver.maps.Event.removeListener(leftClick); + naver.maps.Event.removeListener(rightClick); + }; + + createShapeTest = selectedIcon => { + let position; + const naver = window.naver; + const { map, updateDrawingData, descriptionModalShow } = this.props; + const icons = Object.values(constants.typeOfShape); + const overlays = [Line, Arrow, Rect, Circle, Polygon]; // Change name of index to actual overlay name of import + let Shape; + let shapeIndex; + let moveEvent; + let figure; + let lineData = []; + let isClick = false; + + for (let index = 0; index < icons.length; index++) { + if (selectedIcon === icons[index]) { + Shape = overlays[index]; + shapeIndex = index; + } + } + const shapeName = constants.typeOfShape[shapeIndex]; + const { loadedListener } = this.state; + + if (loadedListener !== null) { + naver.maps.Event.removeListener(loadedListener.leftClick); + naver.maps.Event.removeListener(loadedListener.rightClick); + } + + const leftClick = naver.maps.Event.addListener(map, 'click', e => { + const { coord, offset } = e; + position = { coord, offset }; + lineData.push(position); + isClick = true; + // ์ฒ˜์Œ ํด๋ฆญ์‹œ + if (lineData.length === 1) { + lineData.push(position); + // ํ˜ธ์žฌ์™€ ์ฑ„์šฐ๊ธฐ๋ฅผ ์„ ํƒํ•œ ๊ฒฝ์šฐ + if (this.fill && this.color) { + figure = new Shape({ + factorId: this.factorId, + fill: this.fill, + color: this.color, + lineData: lineData, + naverMap: map + }); + figure.setMap(map); + } else { + if (!this.fill && !this.color) { + alert('๋„ํ˜• ์˜ต์…˜๊ณผ ํ˜ธ์žฌ๋ฅผ ์„ ํƒํ•ด์ฃผ์„ธ์š”'); + } else if (!this.fill) { + alert('๋„ํ˜• ์˜ต์…˜์„ ์„ ํƒํ•ด์ฃผ์„ธ์š”'); + } else if (!this.color) { + alert('ํ˜ธ์žฌ๋ฅผ ์„ ํƒํ•ด์ฃผ์„ธ์š”'); + } + lineData = []; + isClick = false; + } + } else { + if ( + shapeName === 'Rect' + || shapeName === 'Circle' + || shapeName === 'Line' + ) { + updateDrawingData({ + figure, + lineData, + shapeType: shapeName + }); + lineData.pop(); + this.fill = undefined; + this.color = undefined; + naver.maps.Event.removeListener(moveEvent); + naver.maps.Event.removeListener(leftClick); + this.setState({ + isInShapeCreateMode: false + }); + this.selectButton(); + descriptionModalShow(); + } else { + figure.draw(lineData); + } + figure.setMap(map); + } + }); + + moveEvent = naver.maps.Event.addListener(map, 'mousemove', e => { + // ํด๋ฆญ ํ›„ ์ด๋™์‹œ + if (isClick) { + const { coord, offset } = e; + position = { coord, offset }; + lineData[lineData.length - 1] = position; + figure.draw(lineData); + } + }); + + const rightClick = naver.maps.Event.addListener(map, 'rightclick', e => { + if (shapeName === 'Polygon' || shapeName === 'Arrow') { + // ํ•ด๋‹น ํฌ์ธํŠธ๋ฅผ ์ง€์›Œ์คŒ + lineData.pop(); + // ์ฒซ ํด๋ฆญ ์ดํ›„ ์šฐํด๋ฆญ์„ ํ•œ ๊ฒฝ์šฐ + if (lineData.length === 1) { + figure.onRemove(); + } else { + figure.draw(lineData); + updateDrawingData({ + figure, + lineData, + shapeType: shapeName + }); + } + this.setState({ + isInShapeCreateMode: false + }); + this.selectButton(); + descriptionModalShow(); + naver.maps.Event.removeListener(moveEvent); + naver.maps.Event.removeListener(leftClick); + } + naver.maps.Event.removeListener(rightClick); + }); + this.setState({ + loadedListener: { + leftClick, + rightClick + } + }); + }; + + selectButton = selectedIcon => { + const { isInShapeCreateMode, isSelectStatus } = this.state; + const { descriptionModalHide } = this.props; + const resetStatus = { ...isSelectStatus }; + for (const key in resetStatus) { + if (key === selectedIcon && resetStatus[key]) { + resetStatus[key] = false; + } else if (key === selectedIcon) { + resetStatus[key] = !resetStatus[key]; + } else { + resetStatus[key] = false; + } + } + const newStatus = Object.assign({ ...isSelectStatus }, resetStatus); + this.setState({ + selectedButton: selectedIcon, + isInShapeCreateMode: !isInShapeCreateMode, + isSelectStatus: newStatus, + fillOrNotToggle1: false, + fillOrNotToggle2: false + }); + this.createShapeTest(selectedIcon); // Enter parameter for different shape + descriptionModalHide(); + }; + + doNotShowTips = () => { + const { refresh } = this.state; + sessionStorage.setItem('doNotShowTipsForDrawing', JSON.stringify(true)); + this.setState({ refresh: !refresh }); + }; + + fillOrnot = fillval => { + this.fill = fillval; + const { fillOrNotToggle1, fillOrNotToggle2 } = this.state; + if (fillval === 'fill') { + this.setState({ + fillOrNotToggle1: !fillOrNotToggle1 + }); + } else { + this.setState({ + fillOrNotToggle2: !fillOrNotToggle2 + }); + } + }; + + decideFactor = factorNum => { + this.factorId = factorNum + 1; + this.color = constants.colorList[factorNum]; + }; + + render() { + const { + map, + handleToggle, + drawingData, + updateDrawingData + } = this.props; + const { + selectedButton, + isInShapeCreateMode, + isSelectStatus, + fillOrNotToggle1, + fillOrNotToggle2 + } = this.state; + const shapeStatus = Object.values(isSelectStatus).some(el => el === true); + const doNotShowTips = JSON.parse( + sessionStorage.getItem('doNotShowTipsForDrawing') + ); + const newToggleBox = Object.keys(constants.newToggleBox); + + if (isInShapeCreateMode) { + const mapDiv = document.querySelector('#map').childNodes[6]; + if (mapDiv.style.cursor !== 'crosshair') { + mapDiv.style.cursor = 'crosshair'; + } + window.naver.maps.Event.addListener(map, 'mouseup', e => { + const { isInShapeCreateMode } = this.state; + if ( + isInShapeCreateMode + && mapDiv.style.cursor !== 'crosshair' + ) { + mapDiv.style.cursor = 'crosshair'; + } else if ( + !isInShapeCreateMode + && mapDiv.style.cursor !== 'grab' + ) { + mapDiv.style.cursor = 'grab'; + } + }); + window.naver.maps.Event.addListener(map, 'mousedown', e => { + const { isInShapeCreateMode } = this.state; + if ( + isInShapeCreateMode + && mapDiv.style.cursor !== 'crosshair' + ) { + mapDiv.style.cursor = 'crosshair'; + } else if ( + !isInShapeCreateMode + && mapDiv.style.cursor !== 'grabbing' + ) { + mapDiv.style.cursor = 'grabbing'; + } + }); + } else { + if (map) { + const mapDiv = document.querySelector('#map').childNodes[6]; + if (mapDiv.style.cursor !== 'grab') { + mapDiv.style.cursor = 'grab'; + } + } + } + return ( + <div id="drawingComponentContainer"> + {Object.values(constants.typeOfShape).map(shape => { + return ( + <Button + map={map} + key={shape} + icons={shape} + selectButton={this.selectButton} + isSelected={ + selectedButton === shape && isInShapeCreateMode + ? true + : false + } + /> + ); + })} + {shapeStatus ? ( + <div + className={'selectOption ' + (shapeStatus ? '' : 'invisible')} + > + <div className="fillOrNot"> + <div + className={ + 'lineOrFillBox ' + + (fillOrNotToggle1 ? 'a' : '') + } + onClick={() => this.fillOrnot('fill')} + onKeyPress={this.fillOrnot} + role="button" + tabIndex="0" + > + Fill + </div> + <div + className={ + 'lineOrFillBox ' + + (fillOrNotToggle2 ? 'b' : '') + } + onClick={() => this.fillOrnot('none')} + onKeyPress={this.fillOrnot} + role="button" + tabIndex="0" + > + Outline + </div> + </div> + <div className="factorContainerBox"> + {newToggleBox.map((factor, idx) => { + return ( + <div + className="factorBox" + onClick={() => this.decideFactor(idx - 1)} + onKeyPress={this.decideFactor} + role="button" + tabIndex="0" + key={idx} + > + <div className="factorContain"> + <div className="factorColorBox" /> + <div className="factorText"> + {factor} + </div> + </div> + </div> + ); + })} + </div> + </div> + ) : null} + <div id="myDrawingsContainer"> + <MyDrawingElement + drawingData={drawingData} + updateDrawingData={updateDrawingData} + /> + </div> + <div id="saveCloseBtns"> + <button + type="button" + className="saveCloseBtn" + onClick={() => { + this.handleRequestSave(drawingData); + // puppeteer.captureImage(); + }} + > + {`์ €์žฅ`} + </button> + <button + type="button" + className="saveCloseBtn" + onClick={() => { + handleToggle(); + }} + > + {`๋‹ซ๊ธฐ`} + </button> + </div> + {doNotShowTips ? null : ( + <div className="tipModalForDrawing"> + <div className="arrowBoxForDrawing"> + <p> + ํ•„ํ„ฐ๋ณ„๋กœ ๋ถ€๋™์‚ฐ ํ˜ธ์žฌ์ •๋ณด๋ฅผ ๋ณด๊ณ ์‹ถ๋‹ค๋ฉด ๊ทธ๋ฆฌ๊ธฐ + ๋ชจ๋“œ๋ฅผ ๋‹ซ๊ณ  ํ•„ํ„ฐ ๋ฉ”๋‰ด๋ฅผ ์„ ํƒํ•ด์ฃผ์„ธ์š”! + </p> + <div + className="doNotShowTipsForDrawing" + onClick={this.doNotShowTips} + onKeyDown={this.doNotShowTips} + role="button" + tabIndex="0" + > + ๋‹ค์‹œ ๋ณด์ง€ ์•Š๊ธฐ + </div> + </div> + </div> + )} + </div> + ); + } +} + +export default Drawing;
JavaScript
์ƒ์ˆ˜๋กœ ๋บ„๊ฒƒ. ๊ณ ์ •๋œ ๊ฐ’์ด๋ผ๋ฉด state๋กœ ์ •์˜ํ•  ํ•„์š”์—†์Œ.
@@ -0,0 +1,438 @@ +import React, { Component } from 'react'; +import PropTypes from 'prop-types'; +import '../less/Drawing.less'; +import Button from '../Module/Button'; +import Line from '../CustomOverlay/Line'; +import Arrow from '../CustomOverlay/Arrow'; +import Circle from '../CustomOverlay/Circle'; +import Rect from '../CustomOverlay/Rect'; +import Polygon from '../CustomOverlay/Polygon'; +import MyDrawingElement from './MyDrawingElement'; +import saveHandle from '../Module/saveHandle'; +import * as constants from '../constants'; + +class Drawing extends Component { + static propTypes = { + map: PropTypes.object, + handleToggle: PropTypes.func.isRequired, + toggleLoginModal: PropTypes.func.isRequired, + drawingData: PropTypes.array.isRequired, + updateDrawingData: PropTypes.func.isRequired, + initDrawingListAfterSave: PropTypes.func.isRequired, + showDraw: PropTypes.func.isRequired, + showDrawingSetTitleDescriptionModal: PropTypes.func.isRequired, + descriptionModalShow: PropTypes.func.isRequired, + descriptionModalHide: PropTypes.func.isRequired + }; + + state = { + selectedButton: null, + loadedListener: null, + isInShapeCreateMode: false, + refresh: true, + fillOrNotToggle1: false, + fillOrNotToggle2: false, + isSelectStatus: { + Line: false, + Arrow: false, + Rect: false, + Circle: false, + Polygon: false + } + }; + + color = undefined; + + factorId = undefined; + + fill = undefined; + + handleRequestSave = data => { + const { + toggleLoginModal, + initDrawingListAfterSave, + showDraw, + showDrawingSetTitleDescriptionModal + } = this.props; + this.setState({ + fillOrNotToggle1: false, + fillOrNotToggle2: false + }); + saveHandle( + data, + null, + toggleLoginModal, + initDrawingListAfterSave, + showDraw, + showDrawingSetTitleDescriptionModal + ); + }; + + removeListener = () => { + const naver = window.naver; + const { leftClick } = this.state; + const { rightClick } = this.state; + naver.maps.Event.removeListener(leftClick); + naver.maps.Event.removeListener(rightClick); + }; + + createShapeTest = selectedIcon => { + let position; + const naver = window.naver; + const { map, updateDrawingData, descriptionModalShow } = this.props; + const icons = Object.values(constants.typeOfShape); + const overlays = [Line, Arrow, Rect, Circle, Polygon]; // Change name of index to actual overlay name of import + let Shape; + let shapeIndex; + let moveEvent; + let figure; + let lineData = []; + let isClick = false; + + for (let index = 0; index < icons.length; index++) { + if (selectedIcon === icons[index]) { + Shape = overlays[index]; + shapeIndex = index; + } + } + const shapeName = constants.typeOfShape[shapeIndex]; + const { loadedListener } = this.state; + + if (loadedListener !== null) { + naver.maps.Event.removeListener(loadedListener.leftClick); + naver.maps.Event.removeListener(loadedListener.rightClick); + } + + const leftClick = naver.maps.Event.addListener(map, 'click', e => { + const { coord, offset } = e; + position = { coord, offset }; + lineData.push(position); + isClick = true; + // ์ฒ˜์Œ ํด๋ฆญ์‹œ + if (lineData.length === 1) { + lineData.push(position); + // ํ˜ธ์žฌ์™€ ์ฑ„์šฐ๊ธฐ๋ฅผ ์„ ํƒํ•œ ๊ฒฝ์šฐ + if (this.fill && this.color) { + figure = new Shape({ + factorId: this.factorId, + fill: this.fill, + color: this.color, + lineData: lineData, + naverMap: map + }); + figure.setMap(map); + } else { + if (!this.fill && !this.color) { + alert('๋„ํ˜• ์˜ต์…˜๊ณผ ํ˜ธ์žฌ๋ฅผ ์„ ํƒํ•ด์ฃผ์„ธ์š”'); + } else if (!this.fill) { + alert('๋„ํ˜• ์˜ต์…˜์„ ์„ ํƒํ•ด์ฃผ์„ธ์š”'); + } else if (!this.color) { + alert('ํ˜ธ์žฌ๋ฅผ ์„ ํƒํ•ด์ฃผ์„ธ์š”'); + } + lineData = []; + isClick = false; + } + } else { + if ( + shapeName === 'Rect' + || shapeName === 'Circle' + || shapeName === 'Line' + ) { + updateDrawingData({ + figure, + lineData, + shapeType: shapeName + }); + lineData.pop(); + this.fill = undefined; + this.color = undefined; + naver.maps.Event.removeListener(moveEvent); + naver.maps.Event.removeListener(leftClick); + this.setState({ + isInShapeCreateMode: false + }); + this.selectButton(); + descriptionModalShow(); + } else { + figure.draw(lineData); + } + figure.setMap(map); + } + }); + + moveEvent = naver.maps.Event.addListener(map, 'mousemove', e => { + // ํด๋ฆญ ํ›„ ์ด๋™์‹œ + if (isClick) { + const { coord, offset } = e; + position = { coord, offset }; + lineData[lineData.length - 1] = position; + figure.draw(lineData); + } + }); + + const rightClick = naver.maps.Event.addListener(map, 'rightclick', e => { + if (shapeName === 'Polygon' || shapeName === 'Arrow') { + // ํ•ด๋‹น ํฌ์ธํŠธ๋ฅผ ์ง€์›Œ์คŒ + lineData.pop(); + // ์ฒซ ํด๋ฆญ ์ดํ›„ ์šฐํด๋ฆญ์„ ํ•œ ๊ฒฝ์šฐ + if (lineData.length === 1) { + figure.onRemove(); + } else { + figure.draw(lineData); + updateDrawingData({ + figure, + lineData, + shapeType: shapeName + }); + } + this.setState({ + isInShapeCreateMode: false + }); + this.selectButton(); + descriptionModalShow(); + naver.maps.Event.removeListener(moveEvent); + naver.maps.Event.removeListener(leftClick); + } + naver.maps.Event.removeListener(rightClick); + }); + this.setState({ + loadedListener: { + leftClick, + rightClick + } + }); + }; + + selectButton = selectedIcon => { + const { isInShapeCreateMode, isSelectStatus } = this.state; + const { descriptionModalHide } = this.props; + const resetStatus = { ...isSelectStatus }; + for (const key in resetStatus) { + if (key === selectedIcon && resetStatus[key]) { + resetStatus[key] = false; + } else if (key === selectedIcon) { + resetStatus[key] = !resetStatus[key]; + } else { + resetStatus[key] = false; + } + } + const newStatus = Object.assign({ ...isSelectStatus }, resetStatus); + this.setState({ + selectedButton: selectedIcon, + isInShapeCreateMode: !isInShapeCreateMode, + isSelectStatus: newStatus, + fillOrNotToggle1: false, + fillOrNotToggle2: false + }); + this.createShapeTest(selectedIcon); // Enter parameter for different shape + descriptionModalHide(); + }; + + doNotShowTips = () => { + const { refresh } = this.state; + sessionStorage.setItem('doNotShowTipsForDrawing', JSON.stringify(true)); + this.setState({ refresh: !refresh }); + }; + + fillOrnot = fillval => { + this.fill = fillval; + const { fillOrNotToggle1, fillOrNotToggle2 } = this.state; + if (fillval === 'fill') { + this.setState({ + fillOrNotToggle1: !fillOrNotToggle1 + }); + } else { + this.setState({ + fillOrNotToggle2: !fillOrNotToggle2 + }); + } + }; + + decideFactor = factorNum => { + this.factorId = factorNum + 1; + this.color = constants.colorList[factorNum]; + }; + + render() { + const { + map, + handleToggle, + drawingData, + updateDrawingData + } = this.props; + const { + selectedButton, + isInShapeCreateMode, + isSelectStatus, + fillOrNotToggle1, + fillOrNotToggle2 + } = this.state; + const shapeStatus = Object.values(isSelectStatus).some(el => el === true); + const doNotShowTips = JSON.parse( + sessionStorage.getItem('doNotShowTipsForDrawing') + ); + const newToggleBox = Object.keys(constants.newToggleBox); + + if (isInShapeCreateMode) { + const mapDiv = document.querySelector('#map').childNodes[6]; + if (mapDiv.style.cursor !== 'crosshair') { + mapDiv.style.cursor = 'crosshair'; + } + window.naver.maps.Event.addListener(map, 'mouseup', e => { + const { isInShapeCreateMode } = this.state; + if ( + isInShapeCreateMode + && mapDiv.style.cursor !== 'crosshair' + ) { + mapDiv.style.cursor = 'crosshair'; + } else if ( + !isInShapeCreateMode + && mapDiv.style.cursor !== 'grab' + ) { + mapDiv.style.cursor = 'grab'; + } + }); + window.naver.maps.Event.addListener(map, 'mousedown', e => { + const { isInShapeCreateMode } = this.state; + if ( + isInShapeCreateMode + && mapDiv.style.cursor !== 'crosshair' + ) { + mapDiv.style.cursor = 'crosshair'; + } else if ( + !isInShapeCreateMode + && mapDiv.style.cursor !== 'grabbing' + ) { + mapDiv.style.cursor = 'grabbing'; + } + }); + } else { + if (map) { + const mapDiv = document.querySelector('#map').childNodes[6]; + if (mapDiv.style.cursor !== 'grab') { + mapDiv.style.cursor = 'grab'; + } + } + } + return ( + <div id="drawingComponentContainer"> + {Object.values(constants.typeOfShape).map(shape => { + return ( + <Button + map={map} + key={shape} + icons={shape} + selectButton={this.selectButton} + isSelected={ + selectedButton === shape && isInShapeCreateMode + ? true + : false + } + /> + ); + })} + {shapeStatus ? ( + <div + className={'selectOption ' + (shapeStatus ? '' : 'invisible')} + > + <div className="fillOrNot"> + <div + className={ + 'lineOrFillBox ' + + (fillOrNotToggle1 ? 'a' : '') + } + onClick={() => this.fillOrnot('fill')} + onKeyPress={this.fillOrnot} + role="button" + tabIndex="0" + > + Fill + </div> + <div + className={ + 'lineOrFillBox ' + + (fillOrNotToggle2 ? 'b' : '') + } + onClick={() => this.fillOrnot('none')} + onKeyPress={this.fillOrnot} + role="button" + tabIndex="0" + > + Outline + </div> + </div> + <div className="factorContainerBox"> + {newToggleBox.map((factor, idx) => { + return ( + <div + className="factorBox" + onClick={() => this.decideFactor(idx - 1)} + onKeyPress={this.decideFactor} + role="button" + tabIndex="0" + key={idx} + > + <div className="factorContain"> + <div className="factorColorBox" /> + <div className="factorText"> + {factor} + </div> + </div> + </div> + ); + })} + </div> + </div> + ) : null} + <div id="myDrawingsContainer"> + <MyDrawingElement + drawingData={drawingData} + updateDrawingData={updateDrawingData} + /> + </div> + <div id="saveCloseBtns"> + <button + type="button" + className="saveCloseBtn" + onClick={() => { + this.handleRequestSave(drawingData); + // puppeteer.captureImage(); + }} + > + {`์ €์žฅ`} + </button> + <button + type="button" + className="saveCloseBtn" + onClick={() => { + handleToggle(); + }} + > + {`๋‹ซ๊ธฐ`} + </button> + </div> + {doNotShowTips ? null : ( + <div className="tipModalForDrawing"> + <div className="arrowBoxForDrawing"> + <p> + ํ•„ํ„ฐ๋ณ„๋กœ ๋ถ€๋™์‚ฐ ํ˜ธ์žฌ์ •๋ณด๋ฅผ ๋ณด๊ณ ์‹ถ๋‹ค๋ฉด ๊ทธ๋ฆฌ๊ธฐ + ๋ชจ๋“œ๋ฅผ ๋‹ซ๊ณ  ํ•„ํ„ฐ ๋ฉ”๋‰ด๋ฅผ ์„ ํƒํ•ด์ฃผ์„ธ์š”! + </p> + <div + className="doNotShowTipsForDrawing" + onClick={this.doNotShowTips} + onKeyDown={this.doNotShowTips} + role="button" + tabIndex="0" + > + ๋‹ค์‹œ ๋ณด์ง€ ์•Š๊ธฐ + </div> + </div> + </div> + )} + </div> + ); + } +} + +export default Drawing;
JavaScript
icons์— ๋Œ€์‘ํ•˜๋Š” overlay ์˜ ํ˜•ํƒœ์ธ๊ฑฐ ๊ฐ™์€๋ฐ ์ƒ์ˆ˜๋กœ ๋นผ์„œ `const SHAPES = [{ icons: 'line', overlay: Line }, ...]` ์ด๋Ÿฐ์‹์œผ๋กœ ์ •์˜ํ•˜๋Š”๊ฒŒ ์ข‹๊ฒ ์Œ.
@@ -0,0 +1,438 @@ +import React, { Component } from 'react'; +import PropTypes from 'prop-types'; +import '../less/Drawing.less'; +import Button from '../Module/Button'; +import Line from '../CustomOverlay/Line'; +import Arrow from '../CustomOverlay/Arrow'; +import Circle from '../CustomOverlay/Circle'; +import Rect from '../CustomOverlay/Rect'; +import Polygon from '../CustomOverlay/Polygon'; +import MyDrawingElement from './MyDrawingElement'; +import saveHandle from '../Module/saveHandle'; +import * as constants from '../constants'; + +class Drawing extends Component { + static propTypes = { + map: PropTypes.object, + handleToggle: PropTypes.func.isRequired, + toggleLoginModal: PropTypes.func.isRequired, + drawingData: PropTypes.array.isRequired, + updateDrawingData: PropTypes.func.isRequired, + initDrawingListAfterSave: PropTypes.func.isRequired, + showDraw: PropTypes.func.isRequired, + showDrawingSetTitleDescriptionModal: PropTypes.func.isRequired, + descriptionModalShow: PropTypes.func.isRequired, + descriptionModalHide: PropTypes.func.isRequired + }; + + state = { + selectedButton: null, + loadedListener: null, + isInShapeCreateMode: false, + refresh: true, + fillOrNotToggle1: false, + fillOrNotToggle2: false, + isSelectStatus: { + Line: false, + Arrow: false, + Rect: false, + Circle: false, + Polygon: false + } + }; + + color = undefined; + + factorId = undefined; + + fill = undefined; + + handleRequestSave = data => { + const { + toggleLoginModal, + initDrawingListAfterSave, + showDraw, + showDrawingSetTitleDescriptionModal + } = this.props; + this.setState({ + fillOrNotToggle1: false, + fillOrNotToggle2: false + }); + saveHandle( + data, + null, + toggleLoginModal, + initDrawingListAfterSave, + showDraw, + showDrawingSetTitleDescriptionModal + ); + }; + + removeListener = () => { + const naver = window.naver; + const { leftClick } = this.state; + const { rightClick } = this.state; + naver.maps.Event.removeListener(leftClick); + naver.maps.Event.removeListener(rightClick); + }; + + createShapeTest = selectedIcon => { + let position; + const naver = window.naver; + const { map, updateDrawingData, descriptionModalShow } = this.props; + const icons = Object.values(constants.typeOfShape); + const overlays = [Line, Arrow, Rect, Circle, Polygon]; // Change name of index to actual overlay name of import + let Shape; + let shapeIndex; + let moveEvent; + let figure; + let lineData = []; + let isClick = false; + + for (let index = 0; index < icons.length; index++) { + if (selectedIcon === icons[index]) { + Shape = overlays[index]; + shapeIndex = index; + } + } + const shapeName = constants.typeOfShape[shapeIndex]; + const { loadedListener } = this.state; + + if (loadedListener !== null) { + naver.maps.Event.removeListener(loadedListener.leftClick); + naver.maps.Event.removeListener(loadedListener.rightClick); + } + + const leftClick = naver.maps.Event.addListener(map, 'click', e => { + const { coord, offset } = e; + position = { coord, offset }; + lineData.push(position); + isClick = true; + // ์ฒ˜์Œ ํด๋ฆญ์‹œ + if (lineData.length === 1) { + lineData.push(position); + // ํ˜ธ์žฌ์™€ ์ฑ„์šฐ๊ธฐ๋ฅผ ์„ ํƒํ•œ ๊ฒฝ์šฐ + if (this.fill && this.color) { + figure = new Shape({ + factorId: this.factorId, + fill: this.fill, + color: this.color, + lineData: lineData, + naverMap: map + }); + figure.setMap(map); + } else { + if (!this.fill && !this.color) { + alert('๋„ํ˜• ์˜ต์…˜๊ณผ ํ˜ธ์žฌ๋ฅผ ์„ ํƒํ•ด์ฃผ์„ธ์š”'); + } else if (!this.fill) { + alert('๋„ํ˜• ์˜ต์…˜์„ ์„ ํƒํ•ด์ฃผ์„ธ์š”'); + } else if (!this.color) { + alert('ํ˜ธ์žฌ๋ฅผ ์„ ํƒํ•ด์ฃผ์„ธ์š”'); + } + lineData = []; + isClick = false; + } + } else { + if ( + shapeName === 'Rect' + || shapeName === 'Circle' + || shapeName === 'Line' + ) { + updateDrawingData({ + figure, + lineData, + shapeType: shapeName + }); + lineData.pop(); + this.fill = undefined; + this.color = undefined; + naver.maps.Event.removeListener(moveEvent); + naver.maps.Event.removeListener(leftClick); + this.setState({ + isInShapeCreateMode: false + }); + this.selectButton(); + descriptionModalShow(); + } else { + figure.draw(lineData); + } + figure.setMap(map); + } + }); + + moveEvent = naver.maps.Event.addListener(map, 'mousemove', e => { + // ํด๋ฆญ ํ›„ ์ด๋™์‹œ + if (isClick) { + const { coord, offset } = e; + position = { coord, offset }; + lineData[lineData.length - 1] = position; + figure.draw(lineData); + } + }); + + const rightClick = naver.maps.Event.addListener(map, 'rightclick', e => { + if (shapeName === 'Polygon' || shapeName === 'Arrow') { + // ํ•ด๋‹น ํฌ์ธํŠธ๋ฅผ ์ง€์›Œ์คŒ + lineData.pop(); + // ์ฒซ ํด๋ฆญ ์ดํ›„ ์šฐํด๋ฆญ์„ ํ•œ ๊ฒฝ์šฐ + if (lineData.length === 1) { + figure.onRemove(); + } else { + figure.draw(lineData); + updateDrawingData({ + figure, + lineData, + shapeType: shapeName + }); + } + this.setState({ + isInShapeCreateMode: false + }); + this.selectButton(); + descriptionModalShow(); + naver.maps.Event.removeListener(moveEvent); + naver.maps.Event.removeListener(leftClick); + } + naver.maps.Event.removeListener(rightClick); + }); + this.setState({ + loadedListener: { + leftClick, + rightClick + } + }); + }; + + selectButton = selectedIcon => { + const { isInShapeCreateMode, isSelectStatus } = this.state; + const { descriptionModalHide } = this.props; + const resetStatus = { ...isSelectStatus }; + for (const key in resetStatus) { + if (key === selectedIcon && resetStatus[key]) { + resetStatus[key] = false; + } else if (key === selectedIcon) { + resetStatus[key] = !resetStatus[key]; + } else { + resetStatus[key] = false; + } + } + const newStatus = Object.assign({ ...isSelectStatus }, resetStatus); + this.setState({ + selectedButton: selectedIcon, + isInShapeCreateMode: !isInShapeCreateMode, + isSelectStatus: newStatus, + fillOrNotToggle1: false, + fillOrNotToggle2: false + }); + this.createShapeTest(selectedIcon); // Enter parameter for different shape + descriptionModalHide(); + }; + + doNotShowTips = () => { + const { refresh } = this.state; + sessionStorage.setItem('doNotShowTipsForDrawing', JSON.stringify(true)); + this.setState({ refresh: !refresh }); + }; + + fillOrnot = fillval => { + this.fill = fillval; + const { fillOrNotToggle1, fillOrNotToggle2 } = this.state; + if (fillval === 'fill') { + this.setState({ + fillOrNotToggle1: !fillOrNotToggle1 + }); + } else { + this.setState({ + fillOrNotToggle2: !fillOrNotToggle2 + }); + } + }; + + decideFactor = factorNum => { + this.factorId = factorNum + 1; + this.color = constants.colorList[factorNum]; + }; + + render() { + const { + map, + handleToggle, + drawingData, + updateDrawingData + } = this.props; + const { + selectedButton, + isInShapeCreateMode, + isSelectStatus, + fillOrNotToggle1, + fillOrNotToggle2 + } = this.state; + const shapeStatus = Object.values(isSelectStatus).some(el => el === true); + const doNotShowTips = JSON.parse( + sessionStorage.getItem('doNotShowTipsForDrawing') + ); + const newToggleBox = Object.keys(constants.newToggleBox); + + if (isInShapeCreateMode) { + const mapDiv = document.querySelector('#map').childNodes[6]; + if (mapDiv.style.cursor !== 'crosshair') { + mapDiv.style.cursor = 'crosshair'; + } + window.naver.maps.Event.addListener(map, 'mouseup', e => { + const { isInShapeCreateMode } = this.state; + if ( + isInShapeCreateMode + && mapDiv.style.cursor !== 'crosshair' + ) { + mapDiv.style.cursor = 'crosshair'; + } else if ( + !isInShapeCreateMode + && mapDiv.style.cursor !== 'grab' + ) { + mapDiv.style.cursor = 'grab'; + } + }); + window.naver.maps.Event.addListener(map, 'mousedown', e => { + const { isInShapeCreateMode } = this.state; + if ( + isInShapeCreateMode + && mapDiv.style.cursor !== 'crosshair' + ) { + mapDiv.style.cursor = 'crosshair'; + } else if ( + !isInShapeCreateMode + && mapDiv.style.cursor !== 'grabbing' + ) { + mapDiv.style.cursor = 'grabbing'; + } + }); + } else { + if (map) { + const mapDiv = document.querySelector('#map').childNodes[6]; + if (mapDiv.style.cursor !== 'grab') { + mapDiv.style.cursor = 'grab'; + } + } + } + return ( + <div id="drawingComponentContainer"> + {Object.values(constants.typeOfShape).map(shape => { + return ( + <Button + map={map} + key={shape} + icons={shape} + selectButton={this.selectButton} + isSelected={ + selectedButton === shape && isInShapeCreateMode + ? true + : false + } + /> + ); + })} + {shapeStatus ? ( + <div + className={'selectOption ' + (shapeStatus ? '' : 'invisible')} + > + <div className="fillOrNot"> + <div + className={ + 'lineOrFillBox ' + + (fillOrNotToggle1 ? 'a' : '') + } + onClick={() => this.fillOrnot('fill')} + onKeyPress={this.fillOrnot} + role="button" + tabIndex="0" + > + Fill + </div> + <div + className={ + 'lineOrFillBox ' + + (fillOrNotToggle2 ? 'b' : '') + } + onClick={() => this.fillOrnot('none')} + onKeyPress={this.fillOrnot} + role="button" + tabIndex="0" + > + Outline + </div> + </div> + <div className="factorContainerBox"> + {newToggleBox.map((factor, idx) => { + return ( + <div + className="factorBox" + onClick={() => this.decideFactor(idx - 1)} + onKeyPress={this.decideFactor} + role="button" + tabIndex="0" + key={idx} + > + <div className="factorContain"> + <div className="factorColorBox" /> + <div className="factorText"> + {factor} + </div> + </div> + </div> + ); + })} + </div> + </div> + ) : null} + <div id="myDrawingsContainer"> + <MyDrawingElement + drawingData={drawingData} + updateDrawingData={updateDrawingData} + /> + </div> + <div id="saveCloseBtns"> + <button + type="button" + className="saveCloseBtn" + onClick={() => { + this.handleRequestSave(drawingData); + // puppeteer.captureImage(); + }} + > + {`์ €์žฅ`} + </button> + <button + type="button" + className="saveCloseBtn" + onClick={() => { + handleToggle(); + }} + > + {`๋‹ซ๊ธฐ`} + </button> + </div> + {doNotShowTips ? null : ( + <div className="tipModalForDrawing"> + <div className="arrowBoxForDrawing"> + <p> + ํ•„ํ„ฐ๋ณ„๋กœ ๋ถ€๋™์‚ฐ ํ˜ธ์žฌ์ •๋ณด๋ฅผ ๋ณด๊ณ ์‹ถ๋‹ค๋ฉด ๊ทธ๋ฆฌ๊ธฐ + ๋ชจ๋“œ๋ฅผ ๋‹ซ๊ณ  ํ•„ํ„ฐ ๋ฉ”๋‰ด๋ฅผ ์„ ํƒํ•ด์ฃผ์„ธ์š”! + </p> + <div + className="doNotShowTipsForDrawing" + onClick={this.doNotShowTips} + onKeyDown={this.doNotShowTips} + role="button" + tabIndex="0" + > + ๋‹ค์‹œ ๋ณด์ง€ ์•Š๊ธฐ + </div> + </div> + </div> + )} + </div> + ); + } +} + +export default Drawing;
JavaScript
break; ์•ˆํ•˜๋ฉด ๋ฐฐ์—ด ๊ณ„์† ์ˆœํšŒํ•จ.
@@ -0,0 +1,96 @@ +import React, { Component } from 'react'; +import '../less/Filter.less'; +import PropTypes from 'prop-types'; +import FilterBox from './FilterBox'; +import * as constants from '../constants'; + +class Filter extends Component { + static propTypes = { + MyInfoButton: PropTypes.bool.isRequired, + myInfoToggle: PropTypes.func.isRequired, + factorLoad: PropTypes.func.isRequired, + showFilter: PropTypes.func.isRequired + }; + + state = { + refresh: true + }; + + doNotShowTips = () => { + const { refresh } = this.state; + sessionStorage.setItem('doNotShowTipsForFilter', JSON.stringify(true)); + this.setState({ refresh: !refresh }); + }; + + render() { + const { + MyInfoButton, + factorLoad, + myInfoToggle, + showFilter + } = this.props; + const doNotShowTips = JSON.parse( + sessionStorage.getItem('doNotShowTipsForFilter') + ); + const factorBox = Object.keys(constants.newToggleBox); + + return ( + <div id="filterContainer"> + <div className="filterBox"> + {factorBox.map(factor => ( + <FilterBox + factorLoad={factorLoad} + factor={factor} + key={factor} + /> + ))} + </div> + + <div className="buttonBox"> + <div + className={ + 'myInfoButton ' + + (MyInfoButton ? 'checked' : 'unChecked') + } + onClick={myInfoToggle} + onKeyPress={myInfoToggle} + role="button" + tabIndex="0" + > + {`๋‚ด ํ˜ธ์žฌ`} + </div> + <div + className="myInfoButton last" + onClick={showFilter} + onKeyPress={showFilter} + role="button" + tabIndex="0" + > + {`๋‹ซ๊ธฐ`} + </div> + </div> + {doNotShowTips ? null : ( + <div className="tipModalForFilter"> + <div className="arrowBoxForFilter"> + <p> + ๋ถ€๋™์‚ฐ ํ˜ธ์žฌ ์ •๋ณด๋ฅผ ๊ทธ๋ฆฌ๋ ค๋ฉด ํ•„ํ„ฐ๋ฅผ ๋‹ซ๊ณ  ๊ทธ๋ฆฌ๊ธฐ + ๋ฉ”๋‰ด๋ฅผ ์„ ํƒํ•ด์ฃผ์„ธ์š”! + </p> + <div + className="doNotShowTipsForFilter" + onClick={this.doNotShowTips} + onKeyDown={this.doNotShowTips} + role="button" + tabIndex="0" + > + ๋‹ค์‹œ ๋ณด์ง€ ์•Š๊ธฐ + </div> + </div> + </div> + )} + </div> + ); + } +} + +export default Filter;
JavaScript
์ƒ์ˆ˜...
@@ -0,0 +1,96 @@ +import React, { Component } from 'react'; +import '../less/Filter.less'; +import PropTypes from 'prop-types'; +import FilterBox from './FilterBox'; +import * as constants from '../constants'; + +class Filter extends Component { + static propTypes = { + MyInfoButton: PropTypes.bool.isRequired, + myInfoToggle: PropTypes.func.isRequired, + factorLoad: PropTypes.func.isRequired, + showFilter: PropTypes.func.isRequired + }; + + state = { + refresh: true + }; + + doNotShowTips = () => { + const { refresh } = this.state; + sessionStorage.setItem('doNotShowTipsForFilter', JSON.stringify(true)); + this.setState({ refresh: !refresh }); + }; + + render() { + const { + MyInfoButton, + factorLoad, + myInfoToggle, + showFilter + } = this.props; + const doNotShowTips = JSON.parse( + sessionStorage.getItem('doNotShowTipsForFilter') + ); + const factorBox = Object.keys(constants.newToggleBox); + + return ( + <div id="filterContainer"> + <div className="filterBox"> + {factorBox.map(factor => ( + <FilterBox + factorLoad={factorLoad} + factor={factor} + key={factor} + /> + ))} + </div> + + <div className="buttonBox"> + <div + className={ + 'myInfoButton ' + + (MyInfoButton ? 'checked' : 'unChecked') + } + onClick={myInfoToggle} + onKeyPress={myInfoToggle} + role="button" + tabIndex="0" + > + {`๋‚ด ํ˜ธ์žฌ`} + </div> + <div + className="myInfoButton last" + onClick={showFilter} + onKeyPress={showFilter} + role="button" + tabIndex="0" + > + {`๋‹ซ๊ธฐ`} + </div> + </div> + {doNotShowTips ? null : ( + <div className="tipModalForFilter"> + <div className="arrowBoxForFilter"> + <p> + ๋ถ€๋™์‚ฐ ํ˜ธ์žฌ ์ •๋ณด๋ฅผ ๊ทธ๋ฆฌ๋ ค๋ฉด ํ•„ํ„ฐ๋ฅผ ๋‹ซ๊ณ  ๊ทธ๋ฆฌ๊ธฐ + ๋ฉ”๋‰ด๋ฅผ ์„ ํƒํ•ด์ฃผ์„ธ์š”! + </p> + <div + className="doNotShowTipsForFilter" + onClick={this.doNotShowTips} + onKeyDown={this.doNotShowTips} + role="button" + tabIndex="0" + > + ๋‹ค์‹œ ๋ณด์ง€ ์•Š๊ธฐ + </div> + </div> + </div> + )} + </div> + ); + } +} + +export default Filter;
JavaScript
css๋กœ ๋นผ๋‚ด๊ธฐ
@@ -0,0 +1,96 @@ +import React, { Component } from 'react'; +import '../less/Filter.less'; +import PropTypes from 'prop-types'; +import FilterBox from './FilterBox'; +import * as constants from '../constants'; + +class Filter extends Component { + static propTypes = { + MyInfoButton: PropTypes.bool.isRequired, + myInfoToggle: PropTypes.func.isRequired, + factorLoad: PropTypes.func.isRequired, + showFilter: PropTypes.func.isRequired + }; + + state = { + refresh: true + }; + + doNotShowTips = () => { + const { refresh } = this.state; + sessionStorage.setItem('doNotShowTipsForFilter', JSON.stringify(true)); + this.setState({ refresh: !refresh }); + }; + + render() { + const { + MyInfoButton, + factorLoad, + myInfoToggle, + showFilter + } = this.props; + const doNotShowTips = JSON.parse( + sessionStorage.getItem('doNotShowTipsForFilter') + ); + const factorBox = Object.keys(constants.newToggleBox); + + return ( + <div id="filterContainer"> + <div className="filterBox"> + {factorBox.map(factor => ( + <FilterBox + factorLoad={factorLoad} + factor={factor} + key={factor} + /> + ))} + </div> + + <div className="buttonBox"> + <div + className={ + 'myInfoButton ' + + (MyInfoButton ? 'checked' : 'unChecked') + } + onClick={myInfoToggle} + onKeyPress={myInfoToggle} + role="button" + tabIndex="0" + > + {`๋‚ด ํ˜ธ์žฌ`} + </div> + <div + className="myInfoButton last" + onClick={showFilter} + onKeyPress={showFilter} + role="button" + tabIndex="0" + > + {`๋‹ซ๊ธฐ`} + </div> + </div> + {doNotShowTips ? null : ( + <div className="tipModalForFilter"> + <div className="arrowBoxForFilter"> + <p> + ๋ถ€๋™์‚ฐ ํ˜ธ์žฌ ์ •๋ณด๋ฅผ ๊ทธ๋ฆฌ๋ ค๋ฉด ํ•„ํ„ฐ๋ฅผ ๋‹ซ๊ณ  ๊ทธ๋ฆฌ๊ธฐ + ๋ฉ”๋‰ด๋ฅผ ์„ ํƒํ•ด์ฃผ์„ธ์š”! + </p> + <div + className="doNotShowTipsForFilter" + onClick={this.doNotShowTips} + onKeyDown={this.doNotShowTips} + role="button" + tabIndex="0" + > + ๋‹ค์‹œ ๋ณด์ง€ ์•Š๊ธฐ + </div> + </div> + </div> + )} + </div> + ); + } +} + +export default Filter;
JavaScript
๊ฐ์Œ€ํ•„์š” ์—†์Œ
@@ -0,0 +1,41 @@ +import { useState, useCallback } from 'react'; +import APIError from '../../api/apiError'; + +interface UseFetchProps<TData> { + queryFn: () => Promise<TData>; + onError?: (error: APIError) => Promise<unknown> | unknown; +} + +interface UseFetchResult<TData> { + query: () => Promise<void>; + isLoading: boolean; + error: APIError | null; + data: TData; +} + +export default function useFetch<TData>({ + queryFn, + onError, +}: UseFetchProps<TData>): UseFetchResult<TData> { + const [isLoading, setLoading] = useState<boolean>(false); + const [error, setError] = useState<APIError | null>(null); + const [data, setData] = useState<TData>({} as TData); + + const query = useCallback(async () => { + setLoading(true); + setError(null); + + try { + const data = await queryFn(); + setData(data); + } catch (error) { + setError(error as APIError); + + if (onError) onError(error as APIError); + } finally { + setLoading(false); + } + }, [queryFn, onError]); + + return { query, isLoading, error, data }; +}
TypeScript
hooks ๋””๋ ‰ํ† ๋ฆฌ๋ฅผ components ๋””๋ ‰ํ† ๋ฆฌ ๋ฐ–์œผ๋กœ ์ด๋™์‹œ์ผœ์•ผ ํ•˜์ง€ ์•Š์„๊นŒ์š”~?
@@ -0,0 +1,80 @@ +import { useEffect, useRef, useState } from 'react'; +import { LowerArrow, UpperArrow } from './Arrows'; +import * as S from './style'; + +interface Option { + content: string; + value: string; +} + +interface DropdownProps { + size: S.Size; + options: Option[]; + defaultContent: string; + onSelect: (value: string) => void; +} + +const Dropdown = ({ + size, + options, + defaultContent, + onSelect, +}: DropdownProps) => { + const [curContent, setCurContent] = useState<string>(defaultContent); + const [isOpened, setIsOpened] = useState<boolean>(false); + const dropdownRef = useRef<HTMLDivElement>(null); + + const handleDropdownClick = () => { + setIsOpened((prev) => !prev); + }; + + const handleOptionSelect = (option: Option) => { + onSelect(option.value); + setCurContent(option.content); + setIsOpened(false); + }; + + const handleClickOutside = (event: MouseEvent) => { + if ( + dropdownRef.current && + !dropdownRef.current.contains(event.target as Node) + ) { + setIsOpened(false); + } + }; + + useEffect(() => { + document.addEventListener('mousedown', handleClickOutside); + return () => { + document.removeEventListener('mousedown', handleClickOutside); + }; + }, []); + + return ( + <S.Container ref={dropdownRef}> + <S.Dropdown size={size} onClick={handleDropdownClick}> + <S.DropdownText selectedOption={curContent}> + {curContent} + </S.DropdownText> + {isOpened ? <UpperArrow /> : <LowerArrow />} + </S.Dropdown> + {isOpened && ( + <S.OptionContainer size={size}> + {options.map((option, index) => { + return ( + <S.Option + key={`${option.content}_${index}`} + id={option.value} + onClick={() => handleOptionSelect(option)} + > + {option.content} + </S.Option> + ); + })} + </S.OptionContainer> + )} + </S.Container> + ); +}; + +export default Dropdown;
Unknown
select ํƒœ๊ทธ๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ์ง์ ‘ ๋ฆฌ์ŠคํŠธ๋กœ ๋งŒ๋“œ๋Š” ์ •์„ฑ์ด ๋Œ€๋‹จํ•ด์š” :>
@@ -0,0 +1,90 @@ +import { useEffect, useState } from 'react'; +import { SortOrder, SortType } from '../../api/types'; +import { + INITIAL_PAGE_NUMBER, + INITIAL_PAGE_SIZE, + PAGE_SIZE, +} from '../../constants/paginationRules'; +import { Category, Product } from '../../types'; +import { productQueries } from './queries/product'; + +export interface UseProductsResult { + products: Product[]; + isLoading: boolean; + error: Error | null; + isLastPage: boolean; + page: number; + fetchNextPage: () => void; + setSort: (value: string) => void; + setCategory: (value: string) => void; +} + +export default function useProducts(): UseProductsResult { + const [products, setProducts] = useState<Product[]>([]); + const [isLastPage, setIsLastPage] = useState(false); + + const [page, setPage] = useState(INITIAL_PAGE_NUMBER); + const [sort, setSort] = useState<SortType>({ price: 'asc', id: 'asc' }); + const [category, setCategory] = useState<Category | ''>(''); + + const { + query: getProducts, + data: productsResponse, + isLoading, + error, + } = productQueries.useGetProducts({ + page, + category, + sort: Object.entries(sort).map(([field, order]) => `${field},${order}`), + size: page === INITIAL_PAGE_NUMBER ? INITIAL_PAGE_SIZE : PAGE_SIZE, + }); + + useEffect(() => { + if (!isLastPage) { + getProducts(); + } + }, [page, sort, category, isLastPage]); + + useEffect(() => { + setIsLastPage(false); + setPage(INITIAL_PAGE_NUMBER); + }, [category, sort]); + + useEffect(() => { + if (productsResponse) { + const { last, content } = productsResponse; + setIsLastPage(last); + setProducts((prevProducts) => + page === INITIAL_PAGE_NUMBER ? content : [...prevProducts, ...content] + ); + } + }, [productsResponse]); + + const fetchNextPage = () => { + if (isLastPage) return; + + // ์„œ๋ฒ„์˜ page size๊ฐ€ 4๋กœ ๊ณ ์ •๋˜์–ด + // page: 0, size: 20 ์š”์ฒญ ์ดํ›„์—” + // page: 5, size: 4 ๋กœ ์š”์ฒญํ•ด์•ผ ํ•จ + setPage((prevPage) => + prevPage !== INITIAL_PAGE_NUMBER + ? prevPage + 1 + : prevPage + INITIAL_PAGE_SIZE / PAGE_SIZE + ); + }; + + return { + products: products ?? [], + isLoading, + error, + page, + fetchNextPage, + setCategory: (value: string) => { + setCategory(value as Category); + }, + setSort: (value: string) => { + setSort((prev) => ({ ...prev, price: value as SortOrder })); + }, + isLastPage, + }; +}
TypeScript
๋ฆฌ๋ทฐ ๊ฐ€์ด๋“œ์— ๋”ฐ๋ผ ๋ฐ์ดํ„ฐ ํŽ˜์นญ ๋กœ์ง ๋ถ€๋ถ„์„ ์กฐ๊ธˆ ๋” ๊ฐœ์„ ํ•œ๋‹ค๋ฉด ์ข‹๊ฒ ๋Š”๋ฐ์š”, ์‚ฌ์‹ค ์ €๋„ ๋ชจ๋ฅด๊ฒ ์–ด์„œ ๊ฐ™์ด ๊ณ ๋ฏผํ•ด๋ณด์•„์š”~~
@@ -11,13 +11,19 @@ "test": "jest" }, "dependencies": { + "identity-obj-proxy": "^3.0.0", + "jest-svg-transformer": "^1.0.0", "react": "^18.2.0", "react-dom": "^18.2.0", "react-error-boundary": "^4.0.13", + "react-router-dom": "^6.23.1", "recoil": "^0.7.7", - "styled-components": "^6.1.11" + "recoil-persist": "^5.1.0", + "styled-components": "^6.1.11", + "styled-reset": "^4.5.2" }, "devDependencies": { + "@eslint/js": "^9.2.0", "@testing-library/jest-dom": "^6.4.5", "@testing-library/react": "^15.0.7", "@types/jest": "^29.5.12", @@ -28,12 +34,19 @@ "@typescript-eslint/parser": "^7.2.0", "@vitejs/plugin-react-swc": "^3.5.0", "eslint": "^8.57.0", - "eslint-plugin-react-hooks": "^4.6.0", + "eslint-config-prettier": "^9.1.0", + "eslint-import-resolver-typescript": "^3.6.1", + "eslint-plugin-prettier": "^5.1.3", + "eslint-plugin-react": "^7.34.1", + "eslint-plugin-react-hooks": "^4.6.2", "eslint-plugin-react-refresh": "^0.4.6", + "globals": "^15.2.0", "jest-environment-jsdom": "^29.7.0", "ts-jest": "^29.1.2", + "ts-jest-mock-import-meta": "^1.2.0", "ts-node": "^10.9.2", "typescript": "^5.2.2", + "typescript-eslint": "^7.9.0", "vite": "^5.2.0" } }
Unknown
์ด๊ฑด ์–ด๋””์— ์“ฐ์˜€๋Š”์ง€ ๊ถ๊ธˆํ•ด์š”~~
@@ -0,0 +1,18 @@ +import * as Styled from './style'; + +interface HeaderProps { + title: string; + onClick?: () => void; +} + +const Header = ({ title, onClick }: HeaderProps) => { + return ( + <Styled.Header> + <Styled.AppTitle onClick={() => onClick && onClick()}> + {title} + </Styled.AppTitle> + </Styled.Header> + ); +}; + +export default Header;
Unknown
๊ทธ๋ƒฅ onClick์„ ๋„ฃ์–ด์ค˜๋„ ๊ดœ์ฐฎ์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,73 @@ +import { CartItem } from '../../type'; +import * as Styled from './style'; +import CheckedBox from '../assets/CheckedBox.svg'; +import UnCheckedBox from '../assets/UnCheckedBox.svg'; +import PlusButton from '../assets/PlusButton.svg'; +import MinusButton from '../assets/MinusButton.svg'; +import BinButton from '../assets/BinButton.svg'; +import { useRecoilState } from 'recoil'; +import { SelectedCartItems } from '../../recoil/selectedCardItems'; + +interface ItemProp { + cartItem: CartItem; + onRemoveItem: (id: number) => void; + onAdjustItemQuantity: (cartItemId: number, quantity: number) => void; +} +const Item = ({ cartItem, onRemoveItem, onAdjustItemQuantity }: ItemProp) => { + const [isSelected, setIsSelected] = useRecoilState( + SelectedCartItems(cartItem.id), + ); + + return ( + <Styled.Item> + <Styled.Divider /> + <Styled.ButtonContainer> + <Styled.Button onClick={() => setIsSelected((prop) => !prop)}> + <img + src={isSelected ? CheckedBox : UnCheckedBox} + alt={isSelected ? '์„ ํƒ๋จ' : '์„ ํƒ๋˜์ง€ ์•Š์Œ'} + /> + </Styled.Button> + <Styled.DeleteButton onClick={() => onRemoveItem(cartItem.id)}> + ์‚ญ์ œ + </Styled.DeleteButton> + </Styled.ButtonContainer> + + <Styled.ItemInfoContainer> + <Styled.ItemImg src={cartItem.product.imageUrl} /> + <Styled.ItemInfo> + <Styled.ItemDetails> + <Styled.ItemName>{cartItem.product.name}</Styled.ItemName> + <Styled.ItemPrice> + {cartItem.product.price.toLocaleString('ko-kr')}์› + </Styled.ItemPrice> + </Styled.ItemDetails> + <Styled.ItemQuantityAdjustment> + <Styled.Button + onClick={() => { + const updatedItemQuantity = cartItem.quantity - 1; + onAdjustItemQuantity(cartItem.id, updatedItemQuantity); + }} + > + <img + src={cartItem.quantity === 1 ? BinButton : MinusButton} + alt="-" + ></img> + </Styled.Button> + <Styled.ItemQuantity>{cartItem.quantity}</Styled.ItemQuantity> + <Styled.Button + onClick={() => { + const updatedItemQuantity = cartItem.quantity + 1; + onAdjustItemQuantity(cartItem.id, updatedItemQuantity); + }} + > + <img src={PlusButton} alt="+"></img> + </Styled.Button> + </Styled.ItemQuantityAdjustment> + </Styled.ItemInfo> + </Styled.ItemInfoContainer> + </Styled.Item> + ); +}; + +export default Item;
Unknown
์ €๋Š” ์™ธ๋ถ€์—์„œ ํ•จ์ˆ˜๋ฅผ ์ฃผ์ž…๋ฐ›์„ ๋•Œ, ์ตœ๋Œ€ํ•œ ์ธ์ž์™€ ๋ฐ˜ํ™˜๊ฐ’ ํƒ€์ž…์„ ์ฃผ์ง€ ์•Š์œผ๋ ค๊ณ  ํ•ด์š”.( ()=>void) ์‚ฌ์šฉ์ฒ˜์—์„œ์˜ ์ž์œ ๋„๋ฅผ ๋†’์ด๊ธฐ ์œ„ํ•จ์ธ๋ฐ์š”. ํ•ด์‹œ๋Š” ํ•จ์ˆ˜๋ฅผ ์ฃผ์ž… ๋ฐ›์„ ๋•Œ ๊ทธ ํ•จ์ˆ˜์˜ ์ธ์ž ํƒ€์ž…์„ ์ฃผ๋Š” ๊ฒƒ ๊ฐ™์•„์š”. ๊ทธ๋ ‡๊ฒŒํ•˜๋Š” ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”??(๊ทผ๋ฐ ์•„๋งˆ ๊ฐœ์ธ ์ทจํ–ฅ์˜ ์˜์—ญ์ผ๋“ฏ..?)
@@ -0,0 +1,68 @@ +import { CartItem } from '../../type'; +import Item from './Item'; +import * as Styled from './style'; +import CheckedBox from '../assets/CheckedBox.svg'; +import UnCheckedBox from '../assets/UnCheckedBox.svg'; +import { useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil'; +import { SelectedAllCardItemsSelector } from '../../recoil/selectedCardItems'; +import { adjustCartItemQuantity, removeCartItem } from '../../api/shoppingCart'; +import { CartItemsSelector, CartItemsState } from '../../recoil/cartItems'; + +const ItemList = () => { + const updateCartItem = useSetRecoilState(CartItemsState); + const cartItems = useRecoilValue(CartItemsSelector); + + const handleDeleteCartItem = async (cartItemId: number) => { + try { + await removeCartItem(cartItemId); + updateCartItem([]); + } catch (error) { + console.error('Failed to remove cart item:', error); + } + }; + const handleAdjustCartItemQuantity = async ( + cartItemId: number, + quantity: number, + ) => { + try { + await adjustCartItemQuantity(cartItemId, quantity); + updateCartItem([]); + } catch (error) { + console.error('์ˆ˜๋Ÿ‰๋ณ€๊ฒฝ ์‹คํŒจ', error); + } + }; + + const cartItemIds = cartItems.map((cartItem) => cartItem.id); + const [selectedAll, setSelectedAll] = useRecoilState( + SelectedAllCardItemsSelector(cartItemIds), + ); + const handleSelectedAll = () => { + setSelectedAll((isSelectedAll) => !isSelectedAll); + }; + + return ( + <Styled.ItemList> + <Styled.TotalSelect> + <Styled.Button onClick={handleSelectedAll}> + <img + src={selectedAll ? CheckedBox : UnCheckedBox} + alt={selectedAll ? '์ „์ฒด ์„ ํƒ' : '์ „์ฒด ์„ ํƒ ํ•ด์ œ'} + /> + </Styled.Button> + <div>์ „์ฒด ์„ ํƒ</div> + </Styled.TotalSelect> + {cartItems.map((cartItem: CartItem) => { + return ( + <Item + key={cartItem.id} + cartItem={cartItem} + onRemoveItem={handleDeleteCartItem} + onAdjustItemQuantity={handleAdjustCartItemQuantity} + /> + ); + })} + </Styled.ItemList> + ); +}; + +export default ItemList;
Unknown
์•„๋งˆ ์ด tryCatch ๋ฌธ์—์„œ๋Š” ๋„คํŠธ์›Œํฌ ์—๋Ÿฌ๋ฅผ ์ปค๋ฒ„ํ•˜๊ธฐ ์œ„ํ•ด ์ด๋Ÿฐ์‹์œผ๋กœ ์ž‘์„ฑํ•œ ๊ฒƒ ๊ฐ™์€๋ฐ์š”. updateCartItem์„ ๋ฐ–์œผ๋กœ ๋นผ๋ฉด ์—๋Ÿฌ ํ•ธ๋“ค๋ง์ด ์กฐ๊ธˆ ๋” ๋ช…ํ™•ํ•ด์งˆ ๊ฒƒ ๊ฐ™์•„์š”. ๋„คํŠธ์›Œํฌ ์—๋Ÿฌ๊ฐ€ ๋‚ฌ์„ ๊ฒฝ์šฐ์—๋Š” catch๋ฌธ์—์„œ return์„ ํ•˜๋ฉด ์›ํ•˜๋Š” ๊ฒฐ๊ณผ๊ฐ€ ๋‚˜์˜ฌ ์ˆ˜ ์žˆ์„ ๊ฒƒ์ด๋ผ๊ณ  ์ƒ๊ฐํ•ด์š”.
@@ -0,0 +1,68 @@ +import { CartItem } from '../../type'; +import Item from './Item'; +import * as Styled from './style'; +import CheckedBox from '../assets/CheckedBox.svg'; +import UnCheckedBox from '../assets/UnCheckedBox.svg'; +import { useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil'; +import { SelectedAllCardItemsSelector } from '../../recoil/selectedCardItems'; +import { adjustCartItemQuantity, removeCartItem } from '../../api/shoppingCart'; +import { CartItemsSelector, CartItemsState } from '../../recoil/cartItems'; + +const ItemList = () => { + const updateCartItem = useSetRecoilState(CartItemsState); + const cartItems = useRecoilValue(CartItemsSelector); + + const handleDeleteCartItem = async (cartItemId: number) => { + try { + await removeCartItem(cartItemId); + updateCartItem([]); + } catch (error) { + console.error('Failed to remove cart item:', error); + } + }; + const handleAdjustCartItemQuantity = async ( + cartItemId: number, + quantity: number, + ) => { + try { + await adjustCartItemQuantity(cartItemId, quantity); + updateCartItem([]); + } catch (error) { + console.error('์ˆ˜๋Ÿ‰๋ณ€๊ฒฝ ์‹คํŒจ', error); + } + }; + + const cartItemIds = cartItems.map((cartItem) => cartItem.id); + const [selectedAll, setSelectedAll] = useRecoilState( + SelectedAllCardItemsSelector(cartItemIds), + ); + const handleSelectedAll = () => { + setSelectedAll((isSelectedAll) => !isSelectedAll); + }; + + return ( + <Styled.ItemList> + <Styled.TotalSelect> + <Styled.Button onClick={handleSelectedAll}> + <img + src={selectedAll ? CheckedBox : UnCheckedBox} + alt={selectedAll ? '์ „์ฒด ์„ ํƒ' : '์ „์ฒด ์„ ํƒ ํ•ด์ œ'} + /> + </Styled.Button> + <div>์ „์ฒด ์„ ํƒ</div> + </Styled.TotalSelect> + {cartItems.map((cartItem: CartItem) => { + return ( + <Item + key={cartItem.id} + cartItem={cartItem} + onRemoveItem={handleDeleteCartItem} + onAdjustItemQuantity={handleAdjustCartItemQuantity} + /> + ); + })} + </Styled.ItemList> + ); +}; + +export default ItemList;
Unknown
๊ทธ๋ฆฌ๊ณ  ์ด๋ ‡๊ฒŒ ์—๋Ÿฌ์ปจํŠธ๋กค์„ ํ•˜๋‹ˆ๊นŒ ๋„คํŠธ์›Œํฌ ์—๋Ÿฌ๊ฐ€ ๋‚ฌ์„ ๋•Œ ์ˆ˜๋Ÿ‰ ๋ฐ˜์˜์ด ์•ˆ๋˜๋Š” ํšจ๊ณผ๊ฐ€ ์žˆ๋„ค์š”! ๋‚™๊ด€์  ์—…๋ฐ์ดํŠธ๋Š” ๋˜์ง€ ์•Š์ง€๋งŒ ์ด๊ฒƒ๋„ ์ด๊ฒƒ ๋‚˜๋ฆ„์˜ ํšจ๊ณผ๊ฐ€ ์žˆ์„ ๊ฒƒ ๊ฐ™๋‹ค๋Š” ์ƒ๊ฐ์ด ๋“ค์–ด์š”!
@@ -0,0 +1,68 @@ +import { CartItem } from '../../type'; +import Item from './Item'; +import * as Styled from './style'; +import CheckedBox from '../assets/CheckedBox.svg'; +import UnCheckedBox from '../assets/UnCheckedBox.svg'; +import { useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil'; +import { SelectedAllCardItemsSelector } from '../../recoil/selectedCardItems'; +import { adjustCartItemQuantity, removeCartItem } from '../../api/shoppingCart'; +import { CartItemsSelector, CartItemsState } from '../../recoil/cartItems'; + +const ItemList = () => { + const updateCartItem = useSetRecoilState(CartItemsState); + const cartItems = useRecoilValue(CartItemsSelector); + + const handleDeleteCartItem = async (cartItemId: number) => { + try { + await removeCartItem(cartItemId); + updateCartItem([]); + } catch (error) { + console.error('Failed to remove cart item:', error); + } + }; + const handleAdjustCartItemQuantity = async ( + cartItemId: number, + quantity: number, + ) => { + try { + await adjustCartItemQuantity(cartItemId, quantity); + updateCartItem([]); + } catch (error) { + console.error('์ˆ˜๋Ÿ‰๋ณ€๊ฒฝ ์‹คํŒจ', error); + } + }; + + const cartItemIds = cartItems.map((cartItem) => cartItem.id); + const [selectedAll, setSelectedAll] = useRecoilState( + SelectedAllCardItemsSelector(cartItemIds), + ); + const handleSelectedAll = () => { + setSelectedAll((isSelectedAll) => !isSelectedAll); + }; + + return ( + <Styled.ItemList> + <Styled.TotalSelect> + <Styled.Button onClick={handleSelectedAll}> + <img + src={selectedAll ? CheckedBox : UnCheckedBox} + alt={selectedAll ? '์ „์ฒด ์„ ํƒ' : '์ „์ฒด ์„ ํƒ ํ•ด์ œ'} + /> + </Styled.Button> + <div>์ „์ฒด ์„ ํƒ</div> + </Styled.TotalSelect> + {cartItems.map((cartItem: CartItem) => { + return ( + <Item + key={cartItem.id} + cartItem={cartItem} + onRemoveItem={handleDeleteCartItem} + onAdjustItemQuantity={handleAdjustCartItemQuantity} + /> + ); + })} + </Styled.ItemList> + ); +}; + +export default ItemList;
Unknown
์‚ญ์ œ๊ธฐ๋Šฅ์ด ์ž˜ ๋™์ž‘ํ•˜๋Š” ์ง€ ๊ถ๊ธˆํ•ด์š”.. ์ฝ”๋“œ๋งŒ ๋ดค์„ ๋•Œ์—๋Š” ์‚ญ์ œ๋ฅผ ํ•˜๋ฉด ๋ชจ๋“  ์•„์ดํ…œ์ด ๋‹ค ์‚ญ์ œ๋  ๊ฒƒ ๊ฐ™๋‹ค๋Š” ๋А๋‚Œ์ด ๋“ค์–ด์„œ์š”
@@ -0,0 +1,549 @@ +import json +import os +from typing import List, Tuple +import requests +import re +import groq +import logging +from review_config import ( + IGNORED_EXTENSIONS, + IGNORED_FILES, + IMPORTANT_FILE_CHANGE_THRESHOLD, + MAX_COMMENTS_PER_FILE +) + +from scripts.review_prompt import ( + get_review_prompt, + get_file_review_prompt, + get_line_comments_prompt, + get_total_comments_prompt +) + +logging.basicConfig(level=logging.DEBUG) +logger = logging.getLogger(__name__) + +groq_client = groq.Groq(api_key=os.environ["GROQ_API_KEY"]) + +def get_pr_files(repo, pr_number, token): + url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}/files" + headers = { + "Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28" + } + + logger.debug(f"PR ํŒŒ์ผ ๊ฐ€์ ธ์˜ค๋Š” ์ค‘. URL: {url}") + logger.debug(f"ํ—ค๋”: {headers}") + + try: + response = requests.get(url, headers=headers) + response.raise_for_status() + return response.json() + except requests.RequestException as e: + logger.error(f"PR ํŒŒ์ผ ๊ฐ€์ ธ์˜ค๊ธฐ ์˜ค๋ฅ˜: {str(e)}") + return None + +def get_latest_commit_id(repo, pr_number, token): + url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}" + headers = { + "Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28" + } + + response = requests.get(url, headers=headers) + response.raise_for_status() + pr_data = response.json() + return pr_data['head']['sha'] + +def review_code_groq(prompt): + try: + response = groq_client.chat.completions.create( + model="llama-3.1-70b-versatile", + messages=[ + {"role": "system", "content": "You are a professional code reviewer from FANNG Senior Developer."}, + {"role": "user", "content": prompt} + ], + temperature=0.7, + max_tokens=2048 + ) + return response.choices[0].message.content + except Exception as e: + logger.error(f"Groq API ํ˜ธ์ถœ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}") + return f"์ฝ”๋“œ ๋ฆฌ๋ทฐ ์ค‘ ๋ฐœ์ƒํ•œ ์—๋Ÿฌ: {str(e)}" + +# def review_code_ollama(pr_content): +# prompt = get_review_prompt(pr_content) +# url = 'http://localhost:11434/api/generate' +# data = { +# "model": "llama3.1", +# "prompt": prompt, +# "stream": False, +# "options": { +# "temperature": 0.7, +# "top_p": 0.8, +# "top_k": 40, +# "num_predict": 1024 +# } +# } +# logger.debug(f"์ฝ”๋“œ ๋ฆฌ๋ทฐ ์ค‘. URL: {url}") +# logger.debug(f"์š”์ฒญ ๋ฐ์ดํ„ฐ: {data}") + +# try: +# response = requests.post(url, json=data) +# response.raise_for_status() +# return response.json()['response'] +# except requests.RequestException as e: +# logger.error(f"์ฝ”๋“œ ๋ฆฌ๋ทฐ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}") +# return f"์ฝ”๋“œ ๋ฆฌ๋ทฐ ์ค‘ ๋ฐœ์ƒํ•œ ์—๋Ÿฌ: {str(e)}" + +def post_review_comment(repo, pr_number, commit_sha, path, position, body, token): + url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}/comments" + headers = { + "Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28" + } + data = { + "body": body, + "commit_id": commit_sha, + "path": path, + "position": position + } + logger.debug(f"๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ ๊ฒŒ์‹œ ์ค‘. URL: {url}") + logger.debug(f"ํ—ค๋”: {headers}") + logger.debug(f"๋ฐ์ดํ„ฐ: {data}") + + try: + response = requests.post(url, headers=headers, json=data) + response.raise_for_status() + logger.info("๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ๊ฐ€ ์„ฑ๊ณต์ ์œผ๋กœ ๊ฒŒ์‹œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค") + except requests.RequestException as e: + logger.error(f"๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ ๊ฒŒ์‹œ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}") + logger.error(f"์‘๋‹ต ๋‚ด์šฉ: {response.content if 'response' in locals() else '์‘๋‹ต ์—†์Œ'}") + logger.error(f"์‘๋‹ต ์ƒํƒœ ์ฝ”๋“œ: {e.response.status_code}") + logger.error(f"์‘๋‹ต ํ—ค๋”: {e.response.headers}") + logger.error(f"์‘๋‹ต ๋‚ด์šฉ: {e.response.text}") + +def summarize_reviews(all_reviews): + summary_prompt = f"๋‹ค์Œ์€ ์ „์ฒด์ ์ธ ์ฝ”๋“œ ๋ฆฌ๋ทฐ ๊ฒฐ๊ณผ์ž…๋‹ˆ๋‹ค : \n\n{''.join(all_reviews)}" + summary = review_code_groq(summary_prompt) + return summary + +def post_pr_comment(repo, pr_number, body, token): + url = f"https://api.github.com/repos/{repo}/issues/{pr_number}/comments" + headers = { + "Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28" + } + data = {"body": body} + + try: + response = requests.post(url, headers=headers, json=data) + response.raise_for_status() + logger.info("PR ์ฝ”๋ฉ˜ํŠธ๊ฐ€ ์„ฑ๊ณต์ ์œผ๋กœ ๊ฒŒ์‹œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.") + except requests.RequestException as e: + logger.error(f"PR ์ฝ”๋ฉ˜ํŠธ ๊ฒŒ์‹œ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}") + logger.error(f"์‘๋‹ต ๋‚ด์šฉ: {response.content if 'response' in locals() else '์‘๋‹ต ์—†์Œ'}") + +def get_pr_context(repo, pr_number, github_token): + url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}" + headers = { + "Authorization": f"Bearer {github_token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28" + } + response = requests.get(url, headers=headers) + response.raise_for_status() + pr_data = response.json() + return { + "title": pr_data['title'], + "description": pr_data['body'] + } + +def get_commit_messages(repo, pr_number, github_token): + url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}/commits" + headers = { + "Authorization": f"Bearer {github_token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28" + } + response = requests.get(url, headers=headers) + response.raise_for_status() + commits = response.json() + return [commit['commit']['message'] for commit in commits] + +def get_changed_files(repo, pr_number, github_token): + url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}/files" + headers = { + "Authorization": f"token {github_token}", + "Accept": "application/vnd.github.v3+json" + } + response = requests.get(url, headers=headers) + files = response.json() + + changed_files_info = [] + for file in files: + status = file['status'] + filename = file['filename'] + additions = file['additions'] + deletions = file['deletions'] + + if status == 'added': + info = f"{filename} (์ถ”๊ฐ€, +{additions}, -0)" + elif status == 'removed': + info = f"{filename} (์‚ญ์ œ)" + else: + info = f"{filename} (์ˆ˜์ •, +{additions}, -{deletions})" + + changed_files_info.append(info) + + return "\n".join(f"{i+1}. {info}" for i, info in enumerate(changed_files_info)) + +def post_line_comments(repo, pr_number, commit_sha, filename, patch, line_comments, token): + url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}/comments" + headers = { + "Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28" + } + + def get_line_numbers(patch): + lines = patch.split('\n') + line_numbers = [] + current_line = 0 + for line in lines: + if line.startswith('@@'): + current_line = int(line.split('+')[1].split(',')[0]) - 1 + elif not line.startswith('-'): + current_line += 1 + if line.startswith('+'): + line_numbers.append(current_line) + return line_numbers + + def post_single_comment(line_num, comment_text, position): + data = { + "body": comment_text.strip(), + "commit_id": commit_sha, + "path": filename, + "line": position + } + logger.debug(f"๋ผ์ธ {line_num}์— ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ ๊ฒŒ์‹œ ์ค‘. URL: {url}") + logger.debug(f"ํ—ค๋”: {headers}") + logger.debug(f"๋ฐ์ดํ„ฐ: {data}") + + try: + response = requests.post(url, headers=headers, json=data) + response.raise_for_status() + logger.info(f"๋ผ์ธ {line_num}์— ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ๊ฐ€ ์„ฑ๊ณต์ ์œผ๋กœ ๊ฒŒ์‹œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค") + except requests.RequestException as e: + logger.error(f"๋ผ์ธ {line_num} ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ ๊ฒŒ์‹œ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}") + logger.error(f"์‘๋‹ต ๋‚ด์šฉ: {response.content if 'response' in locals() else '์‘๋‹ต ์—†์Œ'}") + logger.error(f"์‘๋‹ต ์ƒํƒœ ์ฝ”๋“œ: {e.response.status_code if 'response' in locals() else '์•Œ ์ˆ˜ ์—†์Œ'}") + logger.error(f"์‘๋‹ต ํ—ค๋”: {e.response.headers if 'response' in locals() else '์•Œ ์ˆ˜ ์—†์Œ'}") + logger.error(f"์‘๋‹ต ๋‚ด์šฉ: {e.response.text if 'response' in locals() else '์•Œ ์ˆ˜ ์—†์Œ'}") + + def parse_comments(line_comments: str) -> List[Tuple[int, str]]: + parsed_comments = [] + for comment in line_comments.split('\n'): + match = re.match(r'(\d+):\s*(.*)', comment) + if match: + line_num, comment_text = match.groups() + try: + line_num = int(line_num) + parsed_comments.append((line_num, comment_text)) + except ValueError: + logger.warning(f"์ž˜๋ชป๋œ ๋ผ์ธ ๋ฒˆํ˜ธ ํ˜•์‹: {line_num}") + else: + logger.warning(f"ํŒŒ์‹ฑํ•  ์ˆ˜ ์—†๋Š” ์ฝ”๋ฉ˜ํŠธ ํ˜•์‹: {comment}") + return parsed_comments + + def evaluate_importance(comment: str) -> int: + # ์—ฌ๊ธฐ์— ์ฝ”๋ฉ˜ํŠธ์˜ ์ค‘์š”๋„๋ฅผ ํ‰๊ฐ€ํ•˜๋Š” ๋กœ์ง์„ ๊ตฌํ˜„ํ•ฉ๋‹ˆ๋‹ค. + # ์˜ˆ๋ฅผ ๋“ค์–ด, ํŠน์ • ํ‚ค์›Œ๋“œ์˜ ์กด์žฌ ์—ฌ๋ถ€, ์ฝ”๋ฉ˜ํŠธ์˜ ๊ธธ์ด ๋“ฑ์„ ๊ณ ๋ คํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. + importance = 0 + if "์ค‘์š”" in comment or "critical" in comment.lower(): + importance += 5 + if "๋ฒ„๊ทธ" in comment or "bug" in comment.lower(): + importance += 4 + if "๊ฐœ์„ " in comment or "improvement" in comment.lower(): + importance += 3 + importance += len(comment) // 50 # ๊ธด ์ฝ”๋ฉ˜ํŠธ์— ์•ฝ๊ฐ„์˜ ๊ฐ€์ค‘์น˜ ๋ถ€์—ฌ + return importance + + line_numbers = get_line_numbers(patch) + parsed_comments = parse_comments(line_comments) + + # ์ค‘์š”๋„์— ๋”ฐ๋ผ ์ฝ”๋ฉ˜ํŠธ ์ •๋ ฌ + sorted_comments = sorted(parsed_comments, key=lambda x: evaluate_importance(x[1]), reverse=True) + + comments_posted = 0 + # ๋ผ์ธ ์ฝ”๋ฉ˜ํŠธ ํŒŒ์‹ฑ ๋ฐ ๊ฒŒ์‹œ + for line_num, comment_text in sorted_comments[:MAX_COMMENTS_PER_FILE]: + if 0 <= line_num - 1 < len(line_numbers): + position = line_numbers[line_num - 1] + if post_single_comment(line_num, comment_text, position): + comments_posted += 1 + else: + logger.warning(f"๋ผ์ธ {line_num}์ด ์œ ํšจํ•œ ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚ฌ์Šต๋‹ˆ๋‹ค.") + + # for comment in line_comments.split('\n'): + # if comments_posted >= MAX_COMMENTS_PER_FILE: + # logger.info(f"{filename}: ์ตœ๋Œ€ ์ฝ”๋ฉ˜ํŠธ ์ˆ˜({MAX_COMMENTS_PER_FILE})์— ๋„๋‹ฌํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‚˜๋จธ์ง€ ์ฝ”๋ฉ˜ํŠธ๋Š” ์ƒ๋žต๋ฉ๋‹ˆ๋‹ค.") + # break + + # match = re.match(r'(\d+):\s*(.*)', comment) + # if match: + # line_num, comment_text = match.groups() + # try: + # line_num = int(line_num) + # if 0 <= line_num - 1 < len(line_numbers): + # position = line_numbers[line_num - 1] + # if post_single_comment(line_num, comment_text, position): + # comments_posted += 1 + # else: + # logger.warning(f"๋ผ์ธ {line_num}์ด ์œ ํšจํ•œ ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚ฌ์Šต๋‹ˆ๋‹ค.") + # except ValueError: + # logger.warning(f"์ž˜๋ชป๋œ ๋ผ์ธ ๋ฒˆํ˜ธ ํ˜•์‹: {line_num}") + # else: + # logger.warning(f"ํŒŒ์‹ฑํ•  ์ˆ˜ ์—†๋Š” ์ฝ”๋ฉ˜ํŠธ ํ˜•์‹: {comment}") + + if comments_posted == 0: + logger.info(f"{filename}: ์ถ”๊ฐ€๋œ ์ฝ”๋ฉ˜ํŠธ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.") + else: + logger.info(f"{filename}: ์ด {comments_posted}๊ฐœ์˜ ์ฝ”๋ฉ˜ํŠธ๊ฐ€ ์ถ”๊ฐ€๋˜์—ˆ์Šต๋‹ˆ๋‹ค.") + + logger.info("๋ชจ๋“  ๋ผ์ธ ์ฝ”๋ฉ˜ํŠธ ์ฒ˜๋ฆฌ ์™„๋ฃŒ") + +def get_environment_variables(): + try: + github_token = os.environ['GITHUB_TOKEN'] + repo = os.environ['GITHUB_REPOSITORY'] + event_path = os.environ['GITHUB_EVENT_PATH'] + return github_token, repo, event_path + except KeyError as e: + logger.error(f"ํ™˜๊ฒฝ ๋ณ€์ˆ˜๊ฐ€ ์„ค์ •๋˜์ง€ ์•Š์Œ: {str(e)}") + raise + +def fetch_pr_data(repo, pr_number, github_token): + pr_files = get_pr_files(repo, pr_number, github_token) + if not pr_files: + logger.warning("ํŒŒ์ผ์„ ์ฐพ์„ ์ˆ˜ ์—†๊ฑฐ๋‚˜ PR ํŒŒ์ผ์„ ๊ฐ€์ ธ์˜ค๋Š” ๋ฐ ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค.") + return None, None + latest_commit_id = get_latest_commit_id(repo, pr_number, github_token) + return pr_files, latest_commit_id + +def get_importance_threshold(file, total_pr_changes): + base_threshold = 0.5 # ๊ธฐ๋ณธ ์ž„๊ณ„๊ฐ’์„ 0.5๋กœ ์„ค์ • (๋” ๋งŽ์€ ํŒŒ์ผ์„ ์ค‘์š”ํ•˜๊ฒŒ ๊ฐ„์ฃผ) + + # ํŒŒ์ผ ํ™•์žฅ์ž์— ๋”ฐ๋ฅธ ๊ฐ€์ค‘์น˜ + extension_weights = { + # ๋ฐฑ์—”๋“œ ํŒŒ์ผ (๋†’์€ ๊ฐ€์ค‘์น˜) + '.py': 1.2, # Python ํŒŒ์ผ + + # ํ”„๋ก ํŠธ์—”๋“œ ํŒŒ์ผ (๋†’์€ ๊ฐ€์ค‘์น˜) + '.js': 1.2, # JavaScript ํŒŒ์ผ + '.jsx': 1.2, # React JSX ํŒŒ์ผ + '.ts': 1.2, # TypeScript ํŒŒ์ผ + '.tsx': 1.2, # React TypeScript ํŒŒ์ผ + + # ์Šคํƒ€์ผ ํŒŒ์ผ (์ค‘๊ฐ„ ๊ฐ€์ค‘์น˜) + '.css': 1.0, # CSS ํŒŒ์ผ + '.scss': 1.0, # SCSS ํŒŒ์ผ + + # ์„ค์ • ํŒŒ์ผ (๋‚ฎ์€ ๊ฐ€์ค‘์น˜) + '.json': 0.9, # JSON ์„ค์ • ํŒŒ์ผ + '.yml': 0.9, # YAML ์„ค์ • ํŒŒ์ผ + '.env': 0.9, # ํ™˜๊ฒฝ ๋ณ€์ˆ˜ ํŒŒ์ผ + + # ๋ฌธ์„œ ํŒŒ์ผ (๊ฐ€์žฅ ๋‚ฎ์€ ๊ฐ€์ค‘์น˜) + '.md': 0.7, # Markdown ๋ฌธ์„œ + '.txt': 0.7, # ํ…์ŠคํŠธ ๋ฌธ์„œ + } + + # ํŒŒ์ผ ํ™•์žฅ์ž ์ถ”์ถœ + _, ext = os.path.splitext(file['filename']) + + # ํ™•์žฅ์ž์— ๋”ฐ๋ฅธ ๊ฐ€์ค‘์น˜ ์ ์šฉ (๊ธฐ๋ณธ๊ฐ’ 1.0) + weight = extension_weights.get(ext.lower(), 1.0) + + # PR ์ „์ฒด ๋ณ€๊ฒฝ ํฌ๊ธฐ์— ๋”ฐ๋ฅธ ์กฐ์ • (ํŒ€ ๊ทœ๋ชจ๊ฐ€ ์ž‘์œผ๋ฏ€๋กœ ๊ธฐ์ค€์„ ๋‚ฎ์ถค) + if total_pr_changes > 500: # ๋Œ€๊ทœ๋ชจ PR ๊ธฐ์ค€์„ 500์ค„๋กœ ๋‚ฎ์ถค + base_threshold *= 0.9 # ๋Œ€๊ทœ๋ชจ PR์˜ ๊ฒฝ์šฐ ์ž„๊ณ„๊ฐ’ ๋‚ฎ์ถค + elif total_pr_changes < 50: # ์†Œ๊ทœ๋ชจ PR ๊ธฐ์ค€์„ 50์ค„๋กœ ๋‚ฎ์ถค + base_threshold *= 1.1 # ์†Œ๊ทœ๋ชจ PR์˜ ๊ฒฝ์šฐ ์ž„๊ณ„๊ฐ’ ๋†’์ž„ + + # ํŒŒ์ผ ํฌ๊ธฐ์— ๋”ฐ๋ฅธ ์กฐ์ • + file_size = file.get('changes', 0) + if file_size < 30: # ์ž‘์€ ํŒŒ์ผ ๊ธฐ์ค€์„ 30์ค„๋กœ ๋‚ฎ์ถค + base_threshold *= 1.2 # ์ž‘์€ ํŒŒ์ผ์˜ ๊ฒฝ์šฐ ์ž„๊ณ„๊ฐ’ ๋†’์ž„ + elif file_size > 300: # ํฐ ํŒŒ์ผ ๊ธฐ์ค€์„ 300์ค„๋กœ ๋‚ฎ์ถค + base_threshold *= 0.8 # ํฐ ํŒŒ์ผ์˜ ๊ฒฝ์šฐ ์ž„๊ณ„๊ฐ’ ๋‚ฎ์ถค + + return min(base_threshold * weight, 1.0) # ์ตœ๋Œ€๊ฐ’์„ 1.0์œผ๋กœ ์ œํ•œ + +def is_important_file(file, total_pr_changes): + filename = file['filename'] + if filename in IGNORED_FILES: + logger.debug(f"๋ฌด์‹œ๋œ ํŒŒ์ผ: {filename}") + return False + + if any(filename.endswith(ext) for ext in IGNORED_EXTENSIONS): + logger.debug(f"๋ฌด์‹œํ•  ํ™•์žฅ์ž ํŒŒ์ผ: {filename}") + return False + + if file['status'] == 'removed': + logger.info(f"์‚ญ์ œ๋œ ํŒŒ์ผ: {file['filename']}") + return True + + total_changes = file.get('changes', 0) + additions = file.get('additions', 0) + deletions = file.get('deletions', 0) + + # ํŒŒ์ผ์˜ ์ „์ฒด ํฌ๊ธฐ ๋Œ€๋น„ ๋ณ€๊ฒฝ๋œ ๋ผ์ธ ์ˆ˜์˜ ๋น„์œจ + change_ratio = total_changes / total_pr_changes if total_pr_changes > 0 else 0 + importance_threshold = get_importance_threshold(file, total_pr_changes) + + is_important = total_changes > IMPORTANT_FILE_CHANGE_THRESHOLD or change_ratio > importance_threshold + + if is_important: + logger.info(f"์ค‘์š” ํŒŒ์ผ๋กœ ์„ ์ •: {filename} (๋ณ€๊ฒฝ: {total_changes}์ค„, ์ถ”๊ฐ€: {additions}, ์‚ญ์ œ: {deletions}, ๋น„์œจ: {change_ratio:.2f}, ์ž„๊ณ„๊ฐ’: {importance_threshold:.2f})") + else: + logger.debug(f"์ผ๋ฐ˜ ํŒŒ์ผ: {filename} (๋ณ€๊ฒฝ: {total_changes}์ค„, ์ถ”๊ฐ€: {additions}, ์‚ญ์ œ: {deletions}, ๋น„์œจ: {change_ratio:.2f}, ์ž„๊ณ„๊ฐ’: {importance_threshold:.2f})") + + return is_important + +def generate_reviews(pr_files, repo, pr_number, latest_commit_id, github_token): + all_code = "" + total_pr_changes = sum(file.get('changes', 0) for file in pr_files) + + important_files = [f for f in pr_files if is_important_file(f, total_pr_changes)] + + logger.info(f"์ด {len(pr_files)}๊ฐœ ํŒŒ์ผ ์ค‘ {len(important_files)}๊ฐœ ํŒŒ์ผ์ด ์ค‘์š” ํŒŒ์ผ๋กœ ์„ ์ •๋˜์—ˆ์Šต๋‹ˆ๋‹ค.") + logger.info(f"PR ์ „์ฒด ๋ณ€๊ฒฝ ํฌ๊ธฐ: {total_pr_changes}์ค„") + + for file in pr_files: + if file['status'] == 'removed': + all_code += f"File: {file['filename']} (DELETED)\n\n" + else: + logger.info(f"ํŒŒ์ผ ๋ฆฌ๋ทฐ ์ค‘: {file['filename']}") + content = requests.get(file['raw_url']).text + all_code += f"File: {file['filename']}\n{content}\n\n" + + if not all_code: + logger.warning("๋ฆฌ๋ทฐํ•  ์ฝ”๋“œ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. ๋ชจ๋“  ํŒŒ์ผ ๋‚ด์šฉ์„ ๊ฐ€์ ธ์˜ค๋Š” ๋ฐ ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค.") + return None, [] + + pr_context = get_pr_context(repo, pr_number, github_token) + commit_messages = get_commit_messages(repo, pr_number, github_token) + changed_files = get_changed_files(repo, pr_number, github_token) + + # ๊ฐœ์„ ๋œ ๋ฆฌ๋ทฐ ํ”„๋กฌํ”„ํŠธ ์ƒ์„ฑ + review_prompt = get_review_prompt(all_code, pr_context, commit_messages, changed_files) + + # ์ „์ฒด ์ฝ”๋“œ์— ๋Œ€ํ•œ ์ƒ์„ธํ•œ ๋ฆฌ๋ทฐ + overall_review = review_code_groq(review_prompt) + + # ์ค‘์š” ํŒŒ์ผ์— ๋Œ€ํ•œ ์ƒ์„ธ ๋ฆฌ๋ทฐ (๋ผ์ธ ๋ณ„ ์ฝ”๋ฉ˜ํŠธ ๋น„ํ™œ์„ฑํ™”) + # for file in important_files: + # logger.info(f"์ค‘์š” ํŒŒ์ผ ์ƒ์„ธ ๋ฆฌ๋ทฐ ์ค‘: {file['filename']}") + # if file['status'] == 'removed': + # file_review = f"ํŒŒ์ผ '{file['filename']}'์ด(๊ฐ€) ์‚ญ์ œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ์ด ๋ณ€๊ฒฝ์ด ์ ์ ˆํ•œ์ง€ ํ™•์ธํ•ด ์ฃผ์„ธ์š”." + # else: + # content = requests.get(file['raw_url']).text + # file_review_prompt = get_file_review_prompt(file['filename'], content) + # file_review = review_code_groq(file_review_prompt) + + # # ํŒŒ์ผ ์ „์ฒด์— ๋Œ€ํ•œ ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ + # post_file_comment( + # repo, + # pr_number, + # latest_commit_id, + # file['filename'], + # file_review, + # github_token + # ) + + # # ๋ผ์ธ ๋ณ„ ์ฝ”๋ฉ˜ํŠธ + # line_comments_prompt = get_line_comments_prompt(file['filename'], content) + # line_comments = review_code_groq(line_comments_prompt) + + # post_line_comments( + # repo, + # pr_number, + # latest_commit_id, + # file['filename'], + # file['patch'], + # line_comments, + # github_token + # ) + + return overall_review + +def post_file_comment(repo, pr_number, commit_sha, file_path, body, token): + url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}/comments" + headers = { + "Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28" + } + data = { + "body": body, + "commit_id": commit_sha, + "path": file_path, + "position": 1 + } + + try: + response = requests.post(url, headers=headers, json=data) + response.raise_for_status() + logger.info("PR ํŒŒ์ผ ์ฝ”๋ฉ˜ํŠธ๊ฐ€ ์„ฑ๊ณต์ ์œผ๋กœ ๊ฒŒ์‹œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.") + except requests.RequestException as e: + logger.error(f"PR ์ฝ”๋ฉ˜ํŠธ ๊ฒŒ์‹œ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}") + logger.error(f"์‘๋‹ต ๋‚ด์šฉ: {response.content if 'response' in locals() else '์‘๋‹ต ์—†์Œ'}") + +def main(): + try: + github_token, repo, event_path = get_environment_variables() + + logger.info(f"์ €์žฅ์†Œ ๋ฆฌ๋ทฐ ์‹œ์ž‘: {repo}") + logger.debug(f"GitHub ํ† ํฐ (์ฒ˜์Œ 5์ž): {github_token[:5]}...") + + with open(event_path) as f: + event = json.load(f) + + pr_number = event.get('pull_request', {}).get('number') + if pr_number is None: + logger.error("PR ๋ฒˆํ˜ธ๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. GitHub ์ด๋ฒคํŠธ ํŒŒ์ผ์ด pull_request ์ด๋ฒคํŠธ๋ฅผ ํฌํ•จํ•˜๊ณ  ์žˆ๋Š”์ง€ ํ™•์ธํ•˜์„ธ์š”.") + + logger.info(f"PR ๋ฒˆํ˜ธ {pr_number} ๋ฆฌ๋ทฐ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค.") + + pr_files, latest_commit_id = fetch_pr_data(repo, pr_number, github_token) + if not pr_files: + return + + overall_review = generate_reviews( + pr_files, + repo, + pr_number, + latest_commit_id, + github_token + ) + + if overall_review: + # comment = get_total_comments_prompt(overall_review) + post_pr_comment( + repo, + pr_number, + overall_review, + github_token + ) + + except KeyError as e: + logger.error(f"ํ™˜๊ฒฝ ๋ณ€์ˆ˜๊ฐ€ ์„ค์ •๋˜์ง€ ์•Š์Œ: {str(e)}") + except Exception as e: + logger.error(f"์˜ˆ์ƒ์น˜ ๋ชปํ•œ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}") + +if __name__ == "__main__": + main()
Python
AI Code Review: ๋‹ค์Œ์€ ๊ฐ ํ•ญ๋ชฉ์— ๋Œ€ํ•ด ๋ฌธ์ œ์ ์„ ์ง€์ ํ•˜๊ณ  ๊ฐœ์„  ๋ฐฉ์•ˆ์„ ์ œ์‹œํ•ฉ๋‹ˆ๋‹ค. **1. Pre-condition Check** * `github_token` ๋ณ€์ˆ˜์˜ ์ƒํƒœ๋ฅผ ํ™•์ธํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ํ˜„์žฌ `os.environ['GITHUB_TOKEN']`๊ฐ€ None์ด๋ฉด ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒใ—ใพใ™. `github_token` ๋ณ€์ˆ˜๋Š” ํ™˜๊ฒฝ ๋ณ€์ˆ˜๋กœ ์„ค์ •๋˜์–ด์•ผ ํ•˜๋ฉฐ, None์ด๋ฉด ์ฝ”๋“œ ์ž‘๋™ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. * `repo` ๋ณ€์ˆ˜์˜ ์ƒํƒœ๋ฅผ ํ™•์ธํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ํ˜„์žฌ `os.environ['GITHUB_REPOSITORY']`๊ฐ€ None์ด๋ฉด ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•ฉ๋‹ˆ๋‹ค. `repo` ๋ณ€์ˆ˜๋Š” ํ™˜๊ฒฝ ๋ณ€์ˆ˜๋กœ ์„ค์ •๋˜์–ด์•ผ ํ•˜๋ฉฐ, None์ด๋ฉด ์ฝ”๋“œ ์ž‘๋™ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. **2. Runtime Error Check** * `requests.get(url)`์—์„œ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ๋ฅผ ํ™•์ธํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, URL์ด ์ž˜๋ชป๋˜์—ˆ์„ ๋•Œ ๋˜๋Š” API์— ์—ฐ๊ฒฐํ•˜๋Š” ๋™์•ˆ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * `response.raise_for_status()`์—์„œ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ๋ฅผ ํ™•์ธํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, API์— ์—ฐ๊ฒฐํ•˜๋Š” ๋™์•ˆ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. **3. Optimization** * ์ฝ”๋“œ๊ฐ€ ์„ฑ๋Šฅ์ด ๋–จ์–ด์งˆ ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ Optimizing ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, `requests.get(url)`์—์„œ URL์„ ์—ฌ๋Ÿฌ ๋ฒˆ ์žฌ์ƒ์„ฑํ•˜์ง€ ๋ง๊ณ , ๋ณ€์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ URL์„ ์บ์‹œํ•ฉ๋‹ˆ๋‹ค. * `review_code` ํ•จ์ˆ˜์—์„œ, Code Review API์˜ Response๋ฅผ ์ฒ˜๋ฆฌํ•˜๋Š” ๋ฐ ์‹œ๊ฐ„์ด ๊ฑธ๋ฆฌ๋Š” ๊ฒฝ์šฐ๋ฅผ ํ™•์ธํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, Response๊ฐ€-too-large-Body์˜ ๊ฒฝ์šฐ๋ฅผ ํ™•์ธํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. **4. Security Issue** * GitHub Token์€ secrets๋กœ ์ €์žฅ๋˜์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ํ˜„์žฌ GitHub Token์ด environment variable๋กœ ์ €์žฅ๋˜์–ด ์žˆ์œผ๋ฏ€๋กœ ๋ณด์•ˆ ์œ„ํ—˜์ด ๋  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * `requests.post(url)`์—์„œ, X-GitHub-Api-Version header๊ฐ€ missingํ•œ ๊ฒฝ์šฐ๋ฅผ ํ™•์ธํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ์ด ๊ฒฝ์šฐ, API์— ์—ฐ๊ฒฐํ•˜๋Š” ๋™์•ˆ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. **๊ฐœ์„  ๋ฐฉ์•ˆ** 1. Pre-condition Check * GitHub Token์ด environment variable๋กœ ์„ค์ •๋˜์–ด ์žˆ์œผ๋ฏ€๋กœ `github_token` ๋ณ€์ˆ˜๋ฅผ None์œผ๋กœ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค. * Repository URL์ด environment variable๋กœ ์„ค์ •๋˜์–ด ์žˆ์œผ๋ฏ€๋กœ `repo` ๋ณ€์ˆ˜๋ฅผ None์œผ๋กœ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค. 2. Runtime Error Check * `requests.get(url)`์—์„œ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ๋ฅผ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, URL์ด ์ž˜๋ชป๋˜์—ˆ์„ ๋•Œ ๋˜๋Š” API์— ์—ฐ๊ฒฐํ•˜๋Š” ๋™์•ˆ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * `response.raise_for_status()`์—์„œ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ๋ฅผ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, API์— ์—ฐ๊ฒฐํ•˜๋Š” ๋™์•ˆ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. 3. Optimization * `requests.get(url)`์—์„œ URL์„ ์บ์‹œํ•˜์—ฌ efficiency๋ฅผ ํ–ฅ์ƒ์‹œํ‚ต๋‹ˆ๋‹ค. * `review_code` ํ•จ์ˆ˜์—์„œ Code Review API์˜ Response๋ฅผ ์ฒ˜๋ฆฌํ•˜๋Š” ๋ฐ ์‹œ๊ฐ„์ด ๊ฑธ๋ฆฌ๋Š” ๊ฒฝ์šฐ๋ฅผ ํ™•์ธํ•˜๊ณ , accordingly ์ตœ์ ํ™”ํ•ฉ๋‹ˆ๋‹ค. 4. Security Issue * GitHub Token์€ secrets๋กœ ์ €์žฅ๋˜์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ํ˜„์žฌ GitHub Token์ด environment variable๋กœ stored๋˜์–ด ์žˆ์œผ๋ฏ€๋กœ ๋ณด์•ˆ ์œ„ํ—˜์ด ๋  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * `requests.post(url)`์—์„œ X-GitHub-Api-Version header๊ฐ€ missingํ•œ ๊ฒฝ์šฐ๋ฅผ ํ™•์ธํ•˜๊ณ , accordingly ์ตœ์ ํ™”ํ•ฉ๋‹ˆ๋‹ค. **Updated Code** ```python import os import requests def get_pr_files(repo, pr_number, github_token): url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}/files" headers = {"Authorization": f"token {github_token}"} params = {"state": "added"} try: response = requests.get(url, headers=headers, params=params) response.raise_for_status() except requests.exceptions.RequestException as e: print(f"Error fetching PR files: {e}") return [] return response.json() def get_latest_commit_id(repo, pr_number, github_token): url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}" headers = {"Authorization": f"token {github_token}"} try: response = requests.get(url, headers=headers) response.raise_for_status() except requests.exceptions.RequestException as e: print(f"Error fetching latest commit ID: {e}") return None return response.json()["commit_id"] def review_code(content): # Code Review API Call url = "https://api.code-review.com/review" headers = {"Authorization": "Bearer YOUR_API_KEY"} data = {"content": content} try: response = requests.post(url, headers=headers, json=data) response.raise_for_status() except requests.exceptions.RequestException as e: print(f"Error reviewing code: {e}") return None return response.json()["review"] def main(): try: github_token = os.environ["GITHUB_TOKEN
@@ -0,0 +1,60 @@ +name: AI Code Review + +on: + pull_request: + types: [opened, synchronize] + +permissions: + contents: read + pull-requests: write + +jobs: + code-review: + runs-on: ubuntu-latest + # runs-on: self-hosted + + steps: + - uses: actions/checkout@v4 + + # - name: Set Python Path + # run: echo "PYTHON_PATH=$(which python3)" >> $GITHUB_ENV + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: '3.x' + + # - name: Install dependencies + # run: | + # ${{ env.PYTHON_PATH }} -m pip install --upgrade pip + # ${{ env.PYTHON_PATH }} -m pip install requests + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install requests groq + + - name: Run AI Code Review + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GROQ_API_KEY: ${{ secrets.GROQ_API_KEY }} + run: | + export PYTHONPATH=$PYTHONPATH:${{ github.workspace }} + python .github/scripts/ai_code_review.py + + # - name: Check Ollama availability + # run: | + # curl http://localhost:11434/api/tags + + # - name: Check Python version + # run: | + # python3 --version + # which python3 + + # - name: Run AI Code Review + # env: + # GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # run: | + # echo "Starting AI Code Review" + # export PYTHONPATH=$PYTHONPATH:${{ github.workspace }} + # /usr/local/bin/python3 /Users/jonghyunjung/VisualStudioProjects/neonadeuli-main/.github/scripts/ai_code_review.py + # echo "AI Code Review completed" \ No newline at end of file
Unknown
AI Code Review: 1. Pre-condition Check: - ํ•จ์ˆ˜๋‚˜ ๋ฉ”์„œ๋“œ๊ฐ€ ์˜ฌ๋ฐ”๋ฅด๊ฒŒ ์ž‘๋™ํ•˜๊ธฐ ์œ„ํ•ด ํ•„์š”ํ•œ ๋ณ€์ˆ˜์˜ ์ƒํƒœ๋‚˜ ๊ฐ’์˜ ๋ฒ”์œ„๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๋Š”์ง€ ๊ฒ€์‚ฌ ๋ฌธ์ œ์ : - ํ˜„์žฌ ์ฝ”๋“œ๋Š” GITHUB_TOKEN์„ ์‚ฌ์šฉํ•˜์—ฌ AI Code Review๋ฅผ ์ˆ˜ํ–‰ํ•ฉ๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ GITHUB_TOKEN์€ secrets์— ๅญ˜๊ณ  ์žˆ๋Š” secretes.GITHUB_TOKEN์˜ ๊ฐ’์ด ์˜ฌ๋ฐ”๋ฅธ์ง€ ํ™•์ธ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. - ๋‹ค๋ฅธ ๋ณ€์ˆ˜๋‚˜ ๊ฐ’์ด ์˜ฌ๋ฐ”๋ฅด๊ฒŒ ์„ค์ •๋˜์–ด ์žˆ๋Š”์ง€ ํ™•์ธ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๊ฐœ์„  ๋ฐฉ์•ˆ: - GITHUB_TOKEN์˜ ๊ฐ’์ด ์˜ฌ๋ฐ”๋ฅธ์ง€ ํ™•์ธํ•˜๊ธฐ ์œ„ํ•ด, secrets.GITHUB_TOKEN์„ ์‚ฌ์šฉํ•˜์—ฌ token์˜ ์ƒํƒœ๋ฅผ ๊ฒ€์‚ฌํ•ฉ๋‹ˆ๋‹ค. - ๋ณ€์ˆ˜์™€ ๊ฐ’์˜ ์ƒํƒœ๋ฅผเธ•เธฃเธงเธˆเธชเธญเธšํ•˜๊ธฐ ์œ„ํ•ด, code์—์„œ appropriate pre-condition check๋ฅผ ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค. 2. Runtime Error Check: - Runtime Error ๊ฐ€๋Šฅ์„ฑ์ด ์žˆ๋Š” ์ฝ”๋“œ๋ฅผ ๊ฒ€์‚ฌํ•˜๋ฉฐ, ๊ธฐํƒ€ ์ž ์žฌ์  ์œ„ํ—˜์„ ํ™•์ธ ๋ฌธ์ œ์ : - ํ˜„์žฌ ์ฝ”๋“œ๋Š” curl command๊ฐ€ ์˜ฌ๋ฐ”๋ฅด๊ฒŒ ์ž‘๋™ํ•˜๋Š”์ง€ ํ™•์ธํ•˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค. - pip install request์˜ ๋ฒ„์ „์ด ์˜ฌ๋ฐ”๋ฅธ์ง€ ํ™•์ธ๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค. ๊ฐœ์„  ๋ฐฉ์•ˆ: - curl command๊ฐ€ ์˜ฌ๋ฐ”๋ฅด๊ฒŒ ์ž‘๋™ํ•˜๋Š”์ง€ ํ™•์ธํ•˜๊ธฐ ์œ„ํ•ด, curl command๋ฅผ testํ•ฉ๋‹ˆ๋‹ค. - pip install requests์˜ ๋ฒ„์ „์„ ์˜ฌ๋ฐ”๋ฅธ์ง€ ํ™•์ธํ•˜๊ณ , version์— ๋ฌธ์ œ๊ฐ€ ์žˆ๋Š”์ง€ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค. 3. Optimization: - ์ฝ”๋“œ ํŒจ์น˜์˜ ์ตœ์ ํ™” ํฌ์ธํŠธ๋ฅผ ๊ฒ€์‚ฌ. ์ฝ”๋“œ๊ฐ€ ์„ฑ๋Šฅ์ด ๋–จ์–ด์ง„๋‹ค๊ณ  ํŒ๋‹จ๋˜๋ฉด, ์ตœ์ ํ™”๋œ ์ฝ”๋“œ๋ฅผ ์ถ”์ฒœ ๋ฌธ์ œ์ : - ํ˜„์žฌ ์ฝ”๋“œ๋Š” code-review.py script์—์„œ ์„ฑ๋Šฅ์„ ๊ฐœ์„ ํ•  ์ˆ˜ ์žˆ๋Š” opportunities๊ฐ€ none์ž…๋‹ˆ๋‹ค. ๊ฐœ์„  ๋ฐฉ์•ˆ: - code-review.py script์—์„œ ์„ฑ๋Šฅ์„ ๊ฐœ์„ ํ•  ์ˆ˜ ์žˆ๋Š” opportunities๋ฅผ ๊ฒ€์‚ฌํ•ฉ๋‹ˆ๋‹ค. - ์„ฑ๋Šฅ ๊ฐœ์„ ์„ ์œ„ํ•ด, appropriate optimization technique๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. 4. Security Issue: - ์ฝ”๋“œ๊ฐ€ ์‹ฌ๊ฐํ•œ ๋ณด์•ˆ ๊ฒฐํ•จ์„ ๊ฐ€์ง„ ๋ชจ๋“ˆ์„ ์‚ฌ์šฉํ•˜๊ฑฐ๋‚˜ ๋ณด์•ˆ ์ทจ์•ฝ์ ์„ ํฌํ•จํ•˜๊ณ  ์žˆ๋Š”์ง€ ๊ฒ€์‚ฌ ๋ฌธ์ œ์ : - ํ˜„์žฌ ์ฝ”๋“œ๋Š” requests library๊ฐ€ used but version is not specified. ๊ฐœ์„  ๋ฐฉ์•ˆ: - requests library์˜ version์ด ์˜ฌ๋ฐ”๋ฅธ์ง€ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค. - version์— ๋ฌธ์ œ๊ฐ€ ์žˆ๋Š”์ง€ ํ™•์ธํ•˜๊ณ , version์„ updateํ•˜์—ฌ ๋ณด์•ˆ ์ทจ์•ฝ์ ์„ Addressํ•ฉ๋‹ˆ๋‹ค. ์ด๋Ÿฌํ•œ ๋ฌธ์ œ์ ๊ณผ ๊ฐœ์„  ๋ฐฉ์•ˆ์„ ํ†ตํ•ด ์ฝ”๋“œ๋ฅผ ๊ฐœ์„ ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,101 @@ +REVIEW_PROMPT = """ +You have deep knowledge and expertise in Python, FastAPI for the back end, React and Next.js for the front. +Here is the new PR information. +- title: {title} +- description: {description} +- commit messages: {commit_messages} +- changed files: {changed_files} + +Please understand and review the purpose and context of the change considering PR information and commit message. +Please be sure to thoroughly analyze and review the following format and provide a comprehensive review. +If the author has written a post in accordance with the ๐Ÿ™ review requirements (optional) written in the PR description section, +please provide a solution to resolve the content first. +If not, please find one part of the entire code provided that needs the most improvement and provide a solution. +Please find the number one priority that needs improvement in the entire code you provided and write it strictly in the format below. +-------------------------------------------------------- +## ๐Ÿง‘๐Ÿปโ€๐Ÿ’ป ์ฃผ์š” ๊ธฐ๋Šฅ + +[Provide a brief description of the main features of this file, including its core functionality, expected input and output, and any specific exception cases it handles.] + +## ๐Ÿ” ๊ฐœ์„ ํ•  ์  + +[Write down any areas that need improvement, including performance bottlenecks, readability issues, and security vulnerabilities.] + +## ๐Ÿ“ข ์ œ์•ˆ๋œ ์†”๋ฃจ์…˜ + +1. ํ˜„์žฌ ์ฝ”๋“œ + +[problematic code fragment] + +2. ๊ถŒ์žฅ๋˜๋Š” ๋ณ€๊ฒฝ + +[updated code snippet] + +3. ๋ณ€๊ฒฝ ์ด์œ  + +[Brief reasons why the new approach is better, considering performance, readability, security, etc.] +-------------------------------------------------------- + +Full Code: {all_code} + +If you need to put in a code block, keep it brief, no more than 10 lines of code that needs improvement. +Please write one sentence within 70 characters, including the maximum space, that you need to explain. +If you write one sentence for readability, please write the next sentence in the next column instead of the next one. + +The person receiving this feedback is a Korean developer. +Please make sure to follow the above format strictly in Korean, but please provide specific and constructive feedback. +""" + +FILE_REVIEW_PROMPT = """ +๋‹ค์Œ {filename} ํŒŒ์ผ์˜ ์ฝ”๋“œ๋ฅผ ๋ฆฌ๋ทฐํ•˜๊ณ , ์•„๋ž˜ ํ˜•์‹์œผ๋กœ ์ƒ์„ธํ•œ ๋ฆฌ๋ทฐ๋ฅผ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”: + +## {filename} ํŒŒ์ผ ๋ฆฌ๋ทฐ + +### ์ฃผ์š” ๊ธฐ๋Šฅ +[ํŒŒ์ผ์˜ ์ฃผ์š” ๊ธฐ๋Šฅ ์„ค๋ช…] + +### ์ข‹์€ ์  +[์ข‹์€ ์  ๋‚˜์—ด] + +### ๊ฐœ์„ ํ•  ์  +[๊ฐœ์„ ์ด ํ•„์š”ํ•œ ์  ๋‚˜์—ด] + +### ์ œ์•ˆ ์‚ฌํ•ญ +[๊ตฌ์ฒด์ ์ธ ๊ฐœ์„  ์ œ์•ˆ, ์ฝ”๋“œ ์˜ˆ์‹œ ํฌํ•จ] + +ํŒŒ์ผ ๋‚ด์šฉ: +{content} +""" + +LINE_COMMENTS_PROMPT = """ +๋‹ค์Œ {filename} ํŒŒ์ผ์˜ ์ฝ”๋“œ๋ฅผ ๋ฆฌ๋ทฐํ•˜๊ณ , ์ค‘์š”ํ•œ ๋ผ์ธ์— ๋Œ€ํ•ด ๊ตฌ์ฒด์ ์ธ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”. +ํ˜•์‹์€ '๋ผ์ธ ๋ฒˆํ˜ธ: ์ฝ”๋ฉ˜ํŠธ'๋กœ ํ•ด์ฃผ์„ธ์š”. + +{content} +""" + +OVERALL_COMMENTS_PROMPT = """ +## AI ์ฝ”๋“œ ๋ฆฌ๋ทฐ ์š”์•ฝ + +{overall_review} +""" + +def get_review_prompt(all_code, pr_context, commit_messages, changed_files): + formatted_commit_messages = "\n".join([f"- {msg}" for msg in commit_messages]) + return REVIEW_PROMPT.format( + title=pr_context['title'], + description=pr_context['description'], + commit_messages=formatted_commit_messages, + changed_files=changed_files, + all_code=all_code + ) + +def get_file_review_prompt(filename, content): + return FILE_REVIEW_PROMPT.format(filename=filename, content=content) + +def get_line_comments_prompt(filename, content): + return LINE_COMMENTS_PROMPT.format(filename=filename, content=content) + +def get_total_comments_prompt(overall_review): + return OVERALL_COMMENTS_PROMPT.format(overall_review=overall_review) + \ No newline at end of file
Python
AI Code Review: 1. Pre-condition Check: ๋ฌธ์ œ์ : ์ฝ”๋“œ๋Š” ๋ณ€์ˆ˜์˜ ์ƒํƒœ๋‚˜ ๊ฐ’์˜ ๋ฒ”์œ„๋ฅผ ๊ฒ€์‚ฌํ•˜์ง€ ์•Š๊ณ  directly ์‚ฌ์šฉํ•˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ๋งŽ์Šต๋‹ˆ๋‹ค. ๊ฐœ์„  ๋ฐฉ์•ˆ: ํ•จ์ˆ˜๋‚˜ ๋ฉ”์„œ๋“œ์—์„œ ํ•„์š”ํ•œ ๋ณ€์ˆ˜์˜ ์ƒํƒœ๋‚˜ ๊ฐ’์˜็ฏ„์œ„๋ฅผเธ•เธฃเธงเธˆเธชเธญเธšํ•˜๊ณ , ํ•„์š”ํ•œ ๊ฒฝ์šฐ ์˜ˆ์™ธ ์ฒ˜๋ฆฌ๋‚˜ rร ng์ œ๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, ์ˆซ์ž๊ฐ€ negative๋กœ ๋‚˜์˜ฌ ์ˆ˜ ์žˆ๋Š”์ง€ ํ™•์ธํ•˜๊ธฐ ์œ„ํ•ด `if` ๊ตฌ๋ฌธ๊ณผ `try-except` ๋ธ”๋ก์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ```python def example_function(num): if num < 0: raise ValueError("num should be non-negative") # ... ``` 2. Runtime Error Check: ๋ฌธ์ œ์ : ์ฝ”๋“œ์—์„œ potential runtime error๊ฐ€ ์žˆ๋Š” ๋ถ€๋ถ„์ด ๋งŽ์Šต๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, list.index()์™€ ๊ฐ™์€ ๋ฉ”์†Œ๋“œ๊ฐ€ ์‚ฌ์šฉ๋˜์ง€ ์•Š์•˜์ง€๋งŒ, similar ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒฝ์šฐ์— ๋Œ€ํ•ด warning์„ๅ‘ๅ‡บ์ง€ ๋ชปํ•ฉ๋‹ˆ๋‹ค. ๊ฐœ์„  ๋ฐฉ์•ˆ: potential runtime error๋ฅผ ๊ฐ์ง€ํ•˜๊ณ  warning์„ๅ‘ๅ‡บํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, `warnings` ๋ชจ๋“ˆ์„ ์‚ฌ์šฉํ•˜์—ฌ potential runtime error๋ฅผ ๊ฐ์ง€ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ```python import warnings def example_function(lst): try: lst.index(10) except ValueError as e: warnings.warn(e, UserWarning) ``` 3. Optimization: ๋ฌธ์ œ์ : ์ฝ”๋“œ๊ฐ€ ์„ฑ๋Šฅ์ด ๋–จ์–ด์ง„ ๋ถ€๋ถ„์ด ๋งŽ์Šต๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, for loop์˜ ๊ฒฝ์šฐ, list comprehension์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๊ฐœ์„  ๋ฐฉ์•ˆ: ์ฝ”๋“œ์—์„œ performance bottleneck๋ฅผ ์ฐพ์•„ ์ตœ์ ํ™”ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, `numpy` ๋ชจ๋“ˆ์„ ์‚ฌ์šฉํ•˜์—ฌ array ์—ฐ์‚ฐ์„ speed upํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ```python import numpy as np # original code for i in range(1000000): pass # optimized code arr = np.arange(1000000) np.sum(arr) ``` 4. Security Issue: ๋ฌธ์ œ์ : ์ฝ”๋“œ์—์„œ sensitive data๋ฅผ exposedํ•˜๊ณ , secure communication protocol์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š์€ ๊ฒฝ์šฐ๊ฐ€ ๋งŽ์Šต๋‹ˆ๋‹ค. ๊ฐœ์„  ๋ฐฉ์•ˆ: sensitive data๋ฅผ exposureํ•˜๋Š” ๋ถ€๋ถ„์„ ์ฐพ์•„ secure communication protocol์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, `ssl` ๋ชจ๋“ˆ์„ ์‚ฌ์šฉํ•˜์—ฌ secure connection์„ establishํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ```python import ssl # original code data = open('file.txt', 'r') data.read() # optimized code context = ssl.create_default_context() with ssl.wrap_socket(open('file.txt', 'r'), context=context) as f: data = f.read() ``` ์ด๋Ÿฌํ•œ ๊ฐœ์„  ๋ฐฉ์•ˆ์„ ํ†ตํ•ด ์ฝ”๋“œ๋ฅผ migliorํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ, ์ด ๊ฐœ์„  ๋ฐฉ์•ˆ์€ ํŠน์ • ์ƒํ™ฉ์— ๋”ฐ๋ผ ๋‹ฌ๋ผ์งˆ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,549 @@ +import json +import os +from typing import List, Tuple +import requests +import re +import groq +import logging +from review_config import ( + IGNORED_EXTENSIONS, + IGNORED_FILES, + IMPORTANT_FILE_CHANGE_THRESHOLD, + MAX_COMMENTS_PER_FILE +) + +from scripts.review_prompt import ( + get_review_prompt, + get_file_review_prompt, + get_line_comments_prompt, + get_total_comments_prompt +) + +logging.basicConfig(level=logging.DEBUG) +logger = logging.getLogger(__name__) + +groq_client = groq.Groq(api_key=os.environ["GROQ_API_KEY"]) + +def get_pr_files(repo, pr_number, token): + url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}/files" + headers = { + "Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28" + } + + logger.debug(f"PR ํŒŒ์ผ ๊ฐ€์ ธ์˜ค๋Š” ์ค‘. URL: {url}") + logger.debug(f"ํ—ค๋”: {headers}") + + try: + response = requests.get(url, headers=headers) + response.raise_for_status() + return response.json() + except requests.RequestException as e: + logger.error(f"PR ํŒŒ์ผ ๊ฐ€์ ธ์˜ค๊ธฐ ์˜ค๋ฅ˜: {str(e)}") + return None + +def get_latest_commit_id(repo, pr_number, token): + url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}" + headers = { + "Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28" + } + + response = requests.get(url, headers=headers) + response.raise_for_status() + pr_data = response.json() + return pr_data['head']['sha'] + +def review_code_groq(prompt): + try: + response = groq_client.chat.completions.create( + model="llama-3.1-70b-versatile", + messages=[ + {"role": "system", "content": "You are a professional code reviewer from FANNG Senior Developer."}, + {"role": "user", "content": prompt} + ], + temperature=0.7, + max_tokens=2048 + ) + return response.choices[0].message.content + except Exception as e: + logger.error(f"Groq API ํ˜ธ์ถœ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}") + return f"์ฝ”๋“œ ๋ฆฌ๋ทฐ ์ค‘ ๋ฐœ์ƒํ•œ ์—๋Ÿฌ: {str(e)}" + +# def review_code_ollama(pr_content): +# prompt = get_review_prompt(pr_content) +# url = 'http://localhost:11434/api/generate' +# data = { +# "model": "llama3.1", +# "prompt": prompt, +# "stream": False, +# "options": { +# "temperature": 0.7, +# "top_p": 0.8, +# "top_k": 40, +# "num_predict": 1024 +# } +# } +# logger.debug(f"์ฝ”๋“œ ๋ฆฌ๋ทฐ ์ค‘. URL: {url}") +# logger.debug(f"์š”์ฒญ ๋ฐ์ดํ„ฐ: {data}") + +# try: +# response = requests.post(url, json=data) +# response.raise_for_status() +# return response.json()['response'] +# except requests.RequestException as e: +# logger.error(f"์ฝ”๋“œ ๋ฆฌ๋ทฐ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}") +# return f"์ฝ”๋“œ ๋ฆฌ๋ทฐ ์ค‘ ๋ฐœ์ƒํ•œ ์—๋Ÿฌ: {str(e)}" + +def post_review_comment(repo, pr_number, commit_sha, path, position, body, token): + url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}/comments" + headers = { + "Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28" + } + data = { + "body": body, + "commit_id": commit_sha, + "path": path, + "position": position + } + logger.debug(f"๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ ๊ฒŒ์‹œ ์ค‘. URL: {url}") + logger.debug(f"ํ—ค๋”: {headers}") + logger.debug(f"๋ฐ์ดํ„ฐ: {data}") + + try: + response = requests.post(url, headers=headers, json=data) + response.raise_for_status() + logger.info("๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ๊ฐ€ ์„ฑ๊ณต์ ์œผ๋กœ ๊ฒŒ์‹œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค") + except requests.RequestException as e: + logger.error(f"๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ ๊ฒŒ์‹œ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}") + logger.error(f"์‘๋‹ต ๋‚ด์šฉ: {response.content if 'response' in locals() else '์‘๋‹ต ์—†์Œ'}") + logger.error(f"์‘๋‹ต ์ƒํƒœ ์ฝ”๋“œ: {e.response.status_code}") + logger.error(f"์‘๋‹ต ํ—ค๋”: {e.response.headers}") + logger.error(f"์‘๋‹ต ๋‚ด์šฉ: {e.response.text}") + +def summarize_reviews(all_reviews): + summary_prompt = f"๋‹ค์Œ์€ ์ „์ฒด์ ์ธ ์ฝ”๋“œ ๋ฆฌ๋ทฐ ๊ฒฐ๊ณผ์ž…๋‹ˆ๋‹ค : \n\n{''.join(all_reviews)}" + summary = review_code_groq(summary_prompt) + return summary + +def post_pr_comment(repo, pr_number, body, token): + url = f"https://api.github.com/repos/{repo}/issues/{pr_number}/comments" + headers = { + "Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28" + } + data = {"body": body} + + try: + response = requests.post(url, headers=headers, json=data) + response.raise_for_status() + logger.info("PR ์ฝ”๋ฉ˜ํŠธ๊ฐ€ ์„ฑ๊ณต์ ์œผ๋กœ ๊ฒŒ์‹œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.") + except requests.RequestException as e: + logger.error(f"PR ์ฝ”๋ฉ˜ํŠธ ๊ฒŒ์‹œ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}") + logger.error(f"์‘๋‹ต ๋‚ด์šฉ: {response.content if 'response' in locals() else '์‘๋‹ต ์—†์Œ'}") + +def get_pr_context(repo, pr_number, github_token): + url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}" + headers = { + "Authorization": f"Bearer {github_token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28" + } + response = requests.get(url, headers=headers) + response.raise_for_status() + pr_data = response.json() + return { + "title": pr_data['title'], + "description": pr_data['body'] + } + +def get_commit_messages(repo, pr_number, github_token): + url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}/commits" + headers = { + "Authorization": f"Bearer {github_token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28" + } + response = requests.get(url, headers=headers) + response.raise_for_status() + commits = response.json() + return [commit['commit']['message'] for commit in commits] + +def get_changed_files(repo, pr_number, github_token): + url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}/files" + headers = { + "Authorization": f"token {github_token}", + "Accept": "application/vnd.github.v3+json" + } + response = requests.get(url, headers=headers) + files = response.json() + + changed_files_info = [] + for file in files: + status = file['status'] + filename = file['filename'] + additions = file['additions'] + deletions = file['deletions'] + + if status == 'added': + info = f"{filename} (์ถ”๊ฐ€, +{additions}, -0)" + elif status == 'removed': + info = f"{filename} (์‚ญ์ œ)" + else: + info = f"{filename} (์ˆ˜์ •, +{additions}, -{deletions})" + + changed_files_info.append(info) + + return "\n".join(f"{i+1}. {info}" for i, info in enumerate(changed_files_info)) + +def post_line_comments(repo, pr_number, commit_sha, filename, patch, line_comments, token): + url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}/comments" + headers = { + "Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28" + } + + def get_line_numbers(patch): + lines = patch.split('\n') + line_numbers = [] + current_line = 0 + for line in lines: + if line.startswith('@@'): + current_line = int(line.split('+')[1].split(',')[0]) - 1 + elif not line.startswith('-'): + current_line += 1 + if line.startswith('+'): + line_numbers.append(current_line) + return line_numbers + + def post_single_comment(line_num, comment_text, position): + data = { + "body": comment_text.strip(), + "commit_id": commit_sha, + "path": filename, + "line": position + } + logger.debug(f"๋ผ์ธ {line_num}์— ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ ๊ฒŒ์‹œ ์ค‘. URL: {url}") + logger.debug(f"ํ—ค๋”: {headers}") + logger.debug(f"๋ฐ์ดํ„ฐ: {data}") + + try: + response = requests.post(url, headers=headers, json=data) + response.raise_for_status() + logger.info(f"๋ผ์ธ {line_num}์— ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ๊ฐ€ ์„ฑ๊ณต์ ์œผ๋กœ ๊ฒŒ์‹œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค") + except requests.RequestException as e: + logger.error(f"๋ผ์ธ {line_num} ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ ๊ฒŒ์‹œ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}") + logger.error(f"์‘๋‹ต ๋‚ด์šฉ: {response.content if 'response' in locals() else '์‘๋‹ต ์—†์Œ'}") + logger.error(f"์‘๋‹ต ์ƒํƒœ ์ฝ”๋“œ: {e.response.status_code if 'response' in locals() else '์•Œ ์ˆ˜ ์—†์Œ'}") + logger.error(f"์‘๋‹ต ํ—ค๋”: {e.response.headers if 'response' in locals() else '์•Œ ์ˆ˜ ์—†์Œ'}") + logger.error(f"์‘๋‹ต ๋‚ด์šฉ: {e.response.text if 'response' in locals() else '์•Œ ์ˆ˜ ์—†์Œ'}") + + def parse_comments(line_comments: str) -> List[Tuple[int, str]]: + parsed_comments = [] + for comment in line_comments.split('\n'): + match = re.match(r'(\d+):\s*(.*)', comment) + if match: + line_num, comment_text = match.groups() + try: + line_num = int(line_num) + parsed_comments.append((line_num, comment_text)) + except ValueError: + logger.warning(f"์ž˜๋ชป๋œ ๋ผ์ธ ๋ฒˆํ˜ธ ํ˜•์‹: {line_num}") + else: + logger.warning(f"ํŒŒ์‹ฑํ•  ์ˆ˜ ์—†๋Š” ์ฝ”๋ฉ˜ํŠธ ํ˜•์‹: {comment}") + return parsed_comments + + def evaluate_importance(comment: str) -> int: + # ์—ฌ๊ธฐ์— ์ฝ”๋ฉ˜ํŠธ์˜ ์ค‘์š”๋„๋ฅผ ํ‰๊ฐ€ํ•˜๋Š” ๋กœ์ง์„ ๊ตฌํ˜„ํ•ฉ๋‹ˆ๋‹ค. + # ์˜ˆ๋ฅผ ๋“ค์–ด, ํŠน์ • ํ‚ค์›Œ๋“œ์˜ ์กด์žฌ ์—ฌ๋ถ€, ์ฝ”๋ฉ˜ํŠธ์˜ ๊ธธ์ด ๋“ฑ์„ ๊ณ ๋ คํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. + importance = 0 + if "์ค‘์š”" in comment or "critical" in comment.lower(): + importance += 5 + if "๋ฒ„๊ทธ" in comment or "bug" in comment.lower(): + importance += 4 + if "๊ฐœ์„ " in comment or "improvement" in comment.lower(): + importance += 3 + importance += len(comment) // 50 # ๊ธด ์ฝ”๋ฉ˜ํŠธ์— ์•ฝ๊ฐ„์˜ ๊ฐ€์ค‘์น˜ ๋ถ€์—ฌ + return importance + + line_numbers = get_line_numbers(patch) + parsed_comments = parse_comments(line_comments) + + # ์ค‘์š”๋„์— ๋”ฐ๋ผ ์ฝ”๋ฉ˜ํŠธ ์ •๋ ฌ + sorted_comments = sorted(parsed_comments, key=lambda x: evaluate_importance(x[1]), reverse=True) + + comments_posted = 0 + # ๋ผ์ธ ์ฝ”๋ฉ˜ํŠธ ํŒŒ์‹ฑ ๋ฐ ๊ฒŒ์‹œ + for line_num, comment_text in sorted_comments[:MAX_COMMENTS_PER_FILE]: + if 0 <= line_num - 1 < len(line_numbers): + position = line_numbers[line_num - 1] + if post_single_comment(line_num, comment_text, position): + comments_posted += 1 + else: + logger.warning(f"๋ผ์ธ {line_num}์ด ์œ ํšจํ•œ ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚ฌ์Šต๋‹ˆ๋‹ค.") + + # for comment in line_comments.split('\n'): + # if comments_posted >= MAX_COMMENTS_PER_FILE: + # logger.info(f"{filename}: ์ตœ๋Œ€ ์ฝ”๋ฉ˜ํŠธ ์ˆ˜({MAX_COMMENTS_PER_FILE})์— ๋„๋‹ฌํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‚˜๋จธ์ง€ ์ฝ”๋ฉ˜ํŠธ๋Š” ์ƒ๋žต๋ฉ๋‹ˆ๋‹ค.") + # break + + # match = re.match(r'(\d+):\s*(.*)', comment) + # if match: + # line_num, comment_text = match.groups() + # try: + # line_num = int(line_num) + # if 0 <= line_num - 1 < len(line_numbers): + # position = line_numbers[line_num - 1] + # if post_single_comment(line_num, comment_text, position): + # comments_posted += 1 + # else: + # logger.warning(f"๋ผ์ธ {line_num}์ด ์œ ํšจํ•œ ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚ฌ์Šต๋‹ˆ๋‹ค.") + # except ValueError: + # logger.warning(f"์ž˜๋ชป๋œ ๋ผ์ธ ๋ฒˆํ˜ธ ํ˜•์‹: {line_num}") + # else: + # logger.warning(f"ํŒŒ์‹ฑํ•  ์ˆ˜ ์—†๋Š” ์ฝ”๋ฉ˜ํŠธ ํ˜•์‹: {comment}") + + if comments_posted == 0: + logger.info(f"{filename}: ์ถ”๊ฐ€๋œ ์ฝ”๋ฉ˜ํŠธ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.") + else: + logger.info(f"{filename}: ์ด {comments_posted}๊ฐœ์˜ ์ฝ”๋ฉ˜ํŠธ๊ฐ€ ์ถ”๊ฐ€๋˜์—ˆ์Šต๋‹ˆ๋‹ค.") + + logger.info("๋ชจ๋“  ๋ผ์ธ ์ฝ”๋ฉ˜ํŠธ ์ฒ˜๋ฆฌ ์™„๋ฃŒ") + +def get_environment_variables(): + try: + github_token = os.environ['GITHUB_TOKEN'] + repo = os.environ['GITHUB_REPOSITORY'] + event_path = os.environ['GITHUB_EVENT_PATH'] + return github_token, repo, event_path + except KeyError as e: + logger.error(f"ํ™˜๊ฒฝ ๋ณ€์ˆ˜๊ฐ€ ์„ค์ •๋˜์ง€ ์•Š์Œ: {str(e)}") + raise + +def fetch_pr_data(repo, pr_number, github_token): + pr_files = get_pr_files(repo, pr_number, github_token) + if not pr_files: + logger.warning("ํŒŒ์ผ์„ ์ฐพ์„ ์ˆ˜ ์—†๊ฑฐ๋‚˜ PR ํŒŒ์ผ์„ ๊ฐ€์ ธ์˜ค๋Š” ๋ฐ ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค.") + return None, None + latest_commit_id = get_latest_commit_id(repo, pr_number, github_token) + return pr_files, latest_commit_id + +def get_importance_threshold(file, total_pr_changes): + base_threshold = 0.5 # ๊ธฐ๋ณธ ์ž„๊ณ„๊ฐ’์„ 0.5๋กœ ์„ค์ • (๋” ๋งŽ์€ ํŒŒ์ผ์„ ์ค‘์š”ํ•˜๊ฒŒ ๊ฐ„์ฃผ) + + # ํŒŒ์ผ ํ™•์žฅ์ž์— ๋”ฐ๋ฅธ ๊ฐ€์ค‘์น˜ + extension_weights = { + # ๋ฐฑ์—”๋“œ ํŒŒ์ผ (๋†’์€ ๊ฐ€์ค‘์น˜) + '.py': 1.2, # Python ํŒŒ์ผ + + # ํ”„๋ก ํŠธ์—”๋“œ ํŒŒ์ผ (๋†’์€ ๊ฐ€์ค‘์น˜) + '.js': 1.2, # JavaScript ํŒŒ์ผ + '.jsx': 1.2, # React JSX ํŒŒ์ผ + '.ts': 1.2, # TypeScript ํŒŒ์ผ + '.tsx': 1.2, # React TypeScript ํŒŒ์ผ + + # ์Šคํƒ€์ผ ํŒŒ์ผ (์ค‘๊ฐ„ ๊ฐ€์ค‘์น˜) + '.css': 1.0, # CSS ํŒŒ์ผ + '.scss': 1.0, # SCSS ํŒŒ์ผ + + # ์„ค์ • ํŒŒ์ผ (๋‚ฎ์€ ๊ฐ€์ค‘์น˜) + '.json': 0.9, # JSON ์„ค์ • ํŒŒ์ผ + '.yml': 0.9, # YAML ์„ค์ • ํŒŒ์ผ + '.env': 0.9, # ํ™˜๊ฒฝ ๋ณ€์ˆ˜ ํŒŒ์ผ + + # ๋ฌธ์„œ ํŒŒ์ผ (๊ฐ€์žฅ ๋‚ฎ์€ ๊ฐ€์ค‘์น˜) + '.md': 0.7, # Markdown ๋ฌธ์„œ + '.txt': 0.7, # ํ…์ŠคํŠธ ๋ฌธ์„œ + } + + # ํŒŒ์ผ ํ™•์žฅ์ž ์ถ”์ถœ + _, ext = os.path.splitext(file['filename']) + + # ํ™•์žฅ์ž์— ๋”ฐ๋ฅธ ๊ฐ€์ค‘์น˜ ์ ์šฉ (๊ธฐ๋ณธ๊ฐ’ 1.0) + weight = extension_weights.get(ext.lower(), 1.0) + + # PR ์ „์ฒด ๋ณ€๊ฒฝ ํฌ๊ธฐ์— ๋”ฐ๋ฅธ ์กฐ์ • (ํŒ€ ๊ทœ๋ชจ๊ฐ€ ์ž‘์œผ๋ฏ€๋กœ ๊ธฐ์ค€์„ ๋‚ฎ์ถค) + if total_pr_changes > 500: # ๋Œ€๊ทœ๋ชจ PR ๊ธฐ์ค€์„ 500์ค„๋กœ ๋‚ฎ์ถค + base_threshold *= 0.9 # ๋Œ€๊ทœ๋ชจ PR์˜ ๊ฒฝ์šฐ ์ž„๊ณ„๊ฐ’ ๋‚ฎ์ถค + elif total_pr_changes < 50: # ์†Œ๊ทœ๋ชจ PR ๊ธฐ์ค€์„ 50์ค„๋กœ ๋‚ฎ์ถค + base_threshold *= 1.1 # ์†Œ๊ทœ๋ชจ PR์˜ ๊ฒฝ์šฐ ์ž„๊ณ„๊ฐ’ ๋†’์ž„ + + # ํŒŒ์ผ ํฌ๊ธฐ์— ๋”ฐ๋ฅธ ์กฐ์ • + file_size = file.get('changes', 0) + if file_size < 30: # ์ž‘์€ ํŒŒ์ผ ๊ธฐ์ค€์„ 30์ค„๋กœ ๋‚ฎ์ถค + base_threshold *= 1.2 # ์ž‘์€ ํŒŒ์ผ์˜ ๊ฒฝ์šฐ ์ž„๊ณ„๊ฐ’ ๋†’์ž„ + elif file_size > 300: # ํฐ ํŒŒ์ผ ๊ธฐ์ค€์„ 300์ค„๋กœ ๋‚ฎ์ถค + base_threshold *= 0.8 # ํฐ ํŒŒ์ผ์˜ ๊ฒฝ์šฐ ์ž„๊ณ„๊ฐ’ ๋‚ฎ์ถค + + return min(base_threshold * weight, 1.0) # ์ตœ๋Œ€๊ฐ’์„ 1.0์œผ๋กœ ์ œํ•œ + +def is_important_file(file, total_pr_changes): + filename = file['filename'] + if filename in IGNORED_FILES: + logger.debug(f"๋ฌด์‹œ๋œ ํŒŒ์ผ: {filename}") + return False + + if any(filename.endswith(ext) for ext in IGNORED_EXTENSIONS): + logger.debug(f"๋ฌด์‹œํ•  ํ™•์žฅ์ž ํŒŒ์ผ: {filename}") + return False + + if file['status'] == 'removed': + logger.info(f"์‚ญ์ œ๋œ ํŒŒ์ผ: {file['filename']}") + return True + + total_changes = file.get('changes', 0) + additions = file.get('additions', 0) + deletions = file.get('deletions', 0) + + # ํŒŒ์ผ์˜ ์ „์ฒด ํฌ๊ธฐ ๋Œ€๋น„ ๋ณ€๊ฒฝ๋œ ๋ผ์ธ ์ˆ˜์˜ ๋น„์œจ + change_ratio = total_changes / total_pr_changes if total_pr_changes > 0 else 0 + importance_threshold = get_importance_threshold(file, total_pr_changes) + + is_important = total_changes > IMPORTANT_FILE_CHANGE_THRESHOLD or change_ratio > importance_threshold + + if is_important: + logger.info(f"์ค‘์š” ํŒŒ์ผ๋กœ ์„ ์ •: {filename} (๋ณ€๊ฒฝ: {total_changes}์ค„, ์ถ”๊ฐ€: {additions}, ์‚ญ์ œ: {deletions}, ๋น„์œจ: {change_ratio:.2f}, ์ž„๊ณ„๊ฐ’: {importance_threshold:.2f})") + else: + logger.debug(f"์ผ๋ฐ˜ ํŒŒ์ผ: {filename} (๋ณ€๊ฒฝ: {total_changes}์ค„, ์ถ”๊ฐ€: {additions}, ์‚ญ์ œ: {deletions}, ๋น„์œจ: {change_ratio:.2f}, ์ž„๊ณ„๊ฐ’: {importance_threshold:.2f})") + + return is_important + +def generate_reviews(pr_files, repo, pr_number, latest_commit_id, github_token): + all_code = "" + total_pr_changes = sum(file.get('changes', 0) for file in pr_files) + + important_files = [f for f in pr_files if is_important_file(f, total_pr_changes)] + + logger.info(f"์ด {len(pr_files)}๊ฐœ ํŒŒ์ผ ์ค‘ {len(important_files)}๊ฐœ ํŒŒ์ผ์ด ์ค‘์š” ํŒŒ์ผ๋กœ ์„ ์ •๋˜์—ˆ์Šต๋‹ˆ๋‹ค.") + logger.info(f"PR ์ „์ฒด ๋ณ€๊ฒฝ ํฌ๊ธฐ: {total_pr_changes}์ค„") + + for file in pr_files: + if file['status'] == 'removed': + all_code += f"File: {file['filename']} (DELETED)\n\n" + else: + logger.info(f"ํŒŒ์ผ ๋ฆฌ๋ทฐ ์ค‘: {file['filename']}") + content = requests.get(file['raw_url']).text + all_code += f"File: {file['filename']}\n{content}\n\n" + + if not all_code: + logger.warning("๋ฆฌ๋ทฐํ•  ์ฝ”๋“œ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. ๋ชจ๋“  ํŒŒ์ผ ๋‚ด์šฉ์„ ๊ฐ€์ ธ์˜ค๋Š” ๋ฐ ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค.") + return None, [] + + pr_context = get_pr_context(repo, pr_number, github_token) + commit_messages = get_commit_messages(repo, pr_number, github_token) + changed_files = get_changed_files(repo, pr_number, github_token) + + # ๊ฐœ์„ ๋œ ๋ฆฌ๋ทฐ ํ”„๋กฌํ”„ํŠธ ์ƒ์„ฑ + review_prompt = get_review_prompt(all_code, pr_context, commit_messages, changed_files) + + # ์ „์ฒด ์ฝ”๋“œ์— ๋Œ€ํ•œ ์ƒ์„ธํ•œ ๋ฆฌ๋ทฐ + overall_review = review_code_groq(review_prompt) + + # ์ค‘์š” ํŒŒ์ผ์— ๋Œ€ํ•œ ์ƒ์„ธ ๋ฆฌ๋ทฐ (๋ผ์ธ ๋ณ„ ์ฝ”๋ฉ˜ํŠธ ๋น„ํ™œ์„ฑํ™”) + # for file in important_files: + # logger.info(f"์ค‘์š” ํŒŒ์ผ ์ƒ์„ธ ๋ฆฌ๋ทฐ ์ค‘: {file['filename']}") + # if file['status'] == 'removed': + # file_review = f"ํŒŒ์ผ '{file['filename']}'์ด(๊ฐ€) ์‚ญ์ œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ์ด ๋ณ€๊ฒฝ์ด ์ ์ ˆํ•œ์ง€ ํ™•์ธํ•ด ์ฃผ์„ธ์š”." + # else: + # content = requests.get(file['raw_url']).text + # file_review_prompt = get_file_review_prompt(file['filename'], content) + # file_review = review_code_groq(file_review_prompt) + + # # ํŒŒ์ผ ์ „์ฒด์— ๋Œ€ํ•œ ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ + # post_file_comment( + # repo, + # pr_number, + # latest_commit_id, + # file['filename'], + # file_review, + # github_token + # ) + + # # ๋ผ์ธ ๋ณ„ ์ฝ”๋ฉ˜ํŠธ + # line_comments_prompt = get_line_comments_prompt(file['filename'], content) + # line_comments = review_code_groq(line_comments_prompt) + + # post_line_comments( + # repo, + # pr_number, + # latest_commit_id, + # file['filename'], + # file['patch'], + # line_comments, + # github_token + # ) + + return overall_review + +def post_file_comment(repo, pr_number, commit_sha, file_path, body, token): + url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}/comments" + headers = { + "Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28" + } + data = { + "body": body, + "commit_id": commit_sha, + "path": file_path, + "position": 1 + } + + try: + response = requests.post(url, headers=headers, json=data) + response.raise_for_status() + logger.info("PR ํŒŒ์ผ ์ฝ”๋ฉ˜ํŠธ๊ฐ€ ์„ฑ๊ณต์ ์œผ๋กœ ๊ฒŒ์‹œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.") + except requests.RequestException as e: + logger.error(f"PR ์ฝ”๋ฉ˜ํŠธ ๊ฒŒ์‹œ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}") + logger.error(f"์‘๋‹ต ๋‚ด์šฉ: {response.content if 'response' in locals() else '์‘๋‹ต ์—†์Œ'}") + +def main(): + try: + github_token, repo, event_path = get_environment_variables() + + logger.info(f"์ €์žฅ์†Œ ๋ฆฌ๋ทฐ ์‹œ์ž‘: {repo}") + logger.debug(f"GitHub ํ† ํฐ (์ฒ˜์Œ 5์ž): {github_token[:5]}...") + + with open(event_path) as f: + event = json.load(f) + + pr_number = event.get('pull_request', {}).get('number') + if pr_number is None: + logger.error("PR ๋ฒˆํ˜ธ๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. GitHub ์ด๋ฒคํŠธ ํŒŒ์ผ์ด pull_request ์ด๋ฒคํŠธ๋ฅผ ํฌํ•จํ•˜๊ณ  ์žˆ๋Š”์ง€ ํ™•์ธํ•˜์„ธ์š”.") + + logger.info(f"PR ๋ฒˆํ˜ธ {pr_number} ๋ฆฌ๋ทฐ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค.") + + pr_files, latest_commit_id = fetch_pr_data(repo, pr_number, github_token) + if not pr_files: + return + + overall_review = generate_reviews( + pr_files, + repo, + pr_number, + latest_commit_id, + github_token + ) + + if overall_review: + # comment = get_total_comments_prompt(overall_review) + post_pr_comment( + repo, + pr_number, + overall_review, + github_token + ) + + except KeyError as e: + logger.error(f"ํ™˜๊ฒฝ ๋ณ€์ˆ˜๊ฐ€ ์„ค์ •๋˜์ง€ ์•Š์Œ: {str(e)}") + except Exception as e: + logger.error(f"์˜ˆ์ƒ์น˜ ๋ชปํ•œ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}") + +if __name__ == "__main__": + main()
Python
## .github/scripts/ai_code_review.py ํŒŒ์ผ ๋ฆฌ๋ทฐ ### ์ฃผ์š” ๊ธฐ๋Šฅ ์ด ํŒŒ์ผ์€ GitHub Actions๋ฅผ ํ†ตํ•ด PR(ํ’€ ใƒชใ‚ฏใ‚จใ‚นใƒˆ)์„ ๊ฒ€ํ† ํ•˜๊ณ , ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ๊ฒŒ์‹œํ•˜๋Š” ์Šคํฌ๋ฆฝํŠธ์ž…๋‹ˆ๋‹ค. ์ฃผ์š” ๊ธฐ๋Šฅ์œผ๋กœ๋Š” PR ํŒŒ์ผ์„ ๊ฐ€์ ธ์™€์„œ ์ฝ”๋“œ ๋ฆฌ๋ทฐ๋ฅผ ์ˆ˜ํ–‰ํ•˜๊ณ , ์ค‘์š” ํŒŒ์ผ์— ๋Œ€ํ•œ ์ƒ์„ธ ๋ฆฌ๋ทฐ๋ฅผ ์ˆ˜ํ–‰ํ•˜๋ฉฐ, ๋ผ์ธ ๋ณ„ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ๊ฒŒ์‹œํ•˜๋Š” ๋“ฑ์ด ์žˆ์Šต๋‹ˆ๋‹ค. ### ์ข‹์€ ์  * ์Šคํฌ๋ฆฝํŠธ๋Š” GitHub API๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ PR ํŒŒ์ผ์„ ๊ฐ€์ ธ์™€์„œ ์ฝ”๋“œ ๋ฆฌ๋ทฐ๋ฅผ ์ˆ˜ํ–‰ํ•˜๊ณ , ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ๊ฒŒ์‹œํ•˜๋Š” ๋“ฑ ์ž๋™ํ™”๋œ ์ฝ”๋“œ ๋ฆฌ๋ทฐ ํ”„๋กœ์„ธ์Šค๋ฅผ ๊ตฌํ˜„ํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. * ์ค‘์š” ํŒŒ์ผ์— ๋Œ€ํ•œ ์ƒ์„ธ ๋ฆฌ๋ทฐ๋ฅผ ์ˆ˜ํ–‰ํ•˜๊ณ , ๋ผ์ธ ๋ณ„ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ๊ฒŒ์‹œํ•˜์—ฌ ์ฝ”๋“œ ๋ฆฌ๋ทฐ์˜ ํ’ˆ์งˆ์„ ํ–ฅ์ƒ์‹œํ‚ค๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. * ์Šคํฌ๋ฆฝํŠธ๋Š” ๋กœ๊น…์„ ์‚ฌ์šฉํ•˜์—ฌ ์˜ค๋ฅ˜๋ฅผ ์ถ”์ ํ•˜๊ณ , ๋””๋ฒ„๊น…์„ ์œ„ํ•œ ์ •๋ณด๋ฅผ ์ œ๊ณตํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ### ๊ฐœ์„ ํ•  ์  * ์Šคํฌ๋ฆฝํŠธ๋Š” GitHub API๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ PR ํŒŒ์ผ์„ ๊ฐ€์ ธ์™€์„œ ์ฝ”๋“œ ๋ฆฌ๋ทฐ๋ฅผ ์ˆ˜ํ–‰ํ•˜๊ณ , ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ๊ฒŒ์‹œํ•˜๋Š” ๋“ฑ ์—ฌ๋Ÿฌ ๊ฐ€์ง€ ์ž‘์—…์„ ์ˆ˜ํ–‰ํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ์ด๋Ÿฌํ•œ ์ž‘์—…์„ ๋ณ„๋„์˜ ํ•จ์ˆ˜๋กœ ๋ถ„๋ฆฌํ•˜์—ฌ ์ฝ”๋“œ์˜ ๊ฐ€๋…์„ฑ๊ณผ ์œ ์ง€๋ณด์ˆ˜์„ฑ์„ ํ–ฅ์ƒ์‹œํ‚ฌ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * ์Šคํฌ๋ฆฝํŠธ๋Š” ์ค‘์š” ํŒŒ์ผ์— ๋Œ€ํ•œ ์ƒ์„ธ ๋ฆฌ๋ทฐ๋ฅผ ์ˆ˜ํ–‰ํ•˜๊ณ , ๋ผ์ธ ๋ณ„ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ๊ฒŒ์‹œํ•˜๋Š” ๋“ฑ ์ฝ”๋“œ ๋ฆฌ๋ทฐ์˜ ํ’ˆ์งˆ์„ ํ–ฅ์ƒ์‹œํ‚ค๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ๊ทธ๋Ÿฌ๋‚˜ ์ด๋Ÿฌํ•œ ์ž‘์—…์„ ์ˆ˜ํ–‰ํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜์ด ๊ฐ„๋‹จํ•˜์—ฌ, ์ฝ”๋“œ ๋ฆฌ๋ทฐ์˜ ํ’ˆ์งˆ์„ ํ–ฅ์ƒ์‹œํ‚ค๊ธฐ ์œ„ํ•ด ๋” ๋ณต์žกํ•œ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * ์Šคํฌ๋ฆฝํŠธ๋Š” ๋กœ๊น…์„ ์‚ฌ์šฉํ•˜์—ฌ ์˜ค๋ฅ˜๋ฅผ ์ถ”์ ํ•˜๊ณ , ๋””๋ฒ„๊น…์„ ์œ„ํ•œ ์ •๋ณด๋ฅผ ์ œ๊ณตํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ๊ทธ๋Ÿฌ๋‚˜ ์ด๋Ÿฌํ•œ ๋กœ๊ทธ๋ฅผ ๋” ์ฒด๊ณ„์ ์œผ๋กœ ๊ด€๋ฆฌํ•˜์—ฌ, ์˜ค๋ฅ˜๋ฅผ ๋น ๋ฅด๊ฒŒ ์‹๋ณ„ํ•˜๊ณ  ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ### ์ œ์•ˆ ์‚ฌํ•ญ * ์Šคํฌ๋ฆฝํŠธ๋ฅผ ๋ณ„๋„์˜ ํ•จ์ˆ˜๋กœ ๋ถ„๋ฆฌํ•˜์—ฌ ์ฝ”๋“œ์˜ ๊ฐ€๋…์„ฑ๊ณผ ์œ ์ง€๋ณด์ˆ˜์„ฑ์„ ํ–ฅ์ƒ์‹œํ‚ฌ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, PR ํŒŒ์ผ์„ ๊ฐ€์ ธ์˜ค๋Š” ํ•จ์ˆ˜, ์ฝ”๋“œ ๋ฆฌ๋ทฐ๋ฅผ ์ˆ˜ํ–‰ํ•˜๋Š” ํ•จ์ˆ˜, ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ๊ฒŒ์‹œํ•˜๋Š” ํ•จ์ˆ˜ ๋“ฑ์œผ๋กœ ๋ถ„๋ฆฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * ์ค‘์š” ํŒŒ์ผ์— ๋Œ€ํ•œ ์ƒ์„ธ ๋ฆฌ๋ทฐ๋ฅผ ์ˆ˜ํ–‰ํ•˜๊ณ , ๋ผ์ธ ๋ณ„ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ๊ฒŒ์‹œํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ๋” ๋ณต์žกํ•˜๊ฒŒ ๋งŒ๋“ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, ์ฝ”๋“œ์˜ ๋ณต์žก์„ฑ์„ ๋ถ„์„ํ•˜์—ฌ, ์ค‘์š” ํŒŒ์ผ์„ ์‹๋ณ„ํ•˜๊ณ , ๋ผ์ธ ๋ณ„ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ๊ฒŒ์‹œํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * ๋กœ๊ทธ๋ฅผ ๋” ์ฒด๊ณ„์ ์œผ๋กœ ๊ด€๋ฆฌํ•˜์—ฌ, ์˜ค๋ฅ˜๋ฅผ ๋น ๋ฅด๊ฒŒ ์‹๋ณ„ํ•˜๊ณ  ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, ๋กœ๊ทธ๋ฅผ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์— ์ €์žฅํ•˜์—ฌ, ์˜ค๋ฅ˜๋ฅผ ๋ถ„์„ํ•˜๊ณ , ํŒจํ„ด์„ ์‹๋ณ„ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ```python # ์˜ˆ๋ฅผ ๋“ค์–ด, PR ํŒŒ์ผ์„ ๊ฐ€์ ธ์˜ค๋Š” ํ•จ์ˆ˜ def get_pr_files(repo, pr_number, token): url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}/files" headers = { "Authorization": f"Bearer {token}", "Accept": "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28" } try: response = requests.get(url, headers=headers) response.raise_for_status() return response.json() except requests.RequestException as e: logger.error(f"PR ํŒŒ์ผ ๊ฐ€์ ธ์˜ค๊ธฐ ์˜ค๋ฅ˜: {str(e)}") return None # ์˜ˆ๋ฅผ ๋“ค์–ด, ์ฝ”๋“œ ๋ฆฌ๋ทฐ๋ฅผ ์ˆ˜ํ–‰ํ•˜๋Š” ํ•จ์ˆ˜ def review_code_groq(pr_content): prompt = get_review_prompt(pr_content) try: response = groq_client.chat.completions.create( model="llama-3.1-70b-versatile", messages=[ {"role": "system", "content": "You are an expert code reviewer."}, {"role": "user", "content": prompt} ], temperature=0.7, max_tokens=1024 ) return response.choices[0].message.content except Exception as e: logger.error(f"Groq API ํ˜ธ์ถœ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}") return f"์ฝ”๋“œ ๋ฆฌ๋ทฐ ์ค‘ ๋ฐœ์ƒํ•œ ์—๋Ÿฌ: {str(e)}" # ์˜ˆ๋ฅผ ๋“ค์–ด, ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ๊ฒŒ์‹œํ•˜๋Š” ํ•จ์ˆ˜ def post_review_comment(repo, pr_number, commit_sha, path, position, body, token): url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}/comments" headers = { "Authorization": f"Bearer {token}", "Accept": "application/vnd.github+json", "X-GitHub-Api-Version": "
@@ -0,0 +1,60 @@ +name: AI Code Review + +on: + pull_request: + types: [opened, synchronize] + +permissions: + contents: read + pull-requests: write + +jobs: + code-review: + runs-on: ubuntu-latest + # runs-on: self-hosted + + steps: + - uses: actions/checkout@v4 + + # - name: Set Python Path + # run: echo "PYTHON_PATH=$(which python3)" >> $GITHUB_ENV + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: '3.x' + + # - name: Install dependencies + # run: | + # ${{ env.PYTHON_PATH }} -m pip install --upgrade pip + # ${{ env.PYTHON_PATH }} -m pip install requests + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install requests groq + + - name: Run AI Code Review + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GROQ_API_KEY: ${{ secrets.GROQ_API_KEY }} + run: | + export PYTHONPATH=$PYTHONPATH:${{ github.workspace }} + python .github/scripts/ai_code_review.py + + # - name: Check Ollama availability + # run: | + # curl http://localhost:11434/api/tags + + # - name: Check Python version + # run: | + # python3 --version + # which python3 + + # - name: Run AI Code Review + # env: + # GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # run: | + # echo "Starting AI Code Review" + # export PYTHONPATH=$PYTHONPATH:${{ github.workspace }} + # /usr/local/bin/python3 /Users/jonghyunjung/VisualStudioProjects/neonadeuli-main/.github/scripts/ai_code_review.py + # echo "AI Code Review completed" \ No newline at end of file
Unknown
## .github/workflows/code-review.yml ํŒŒ์ผ ๋ฆฌ๋ทฐ ### ์ฃผ์š” ๊ธฐ๋Šฅ ์ด ํŒŒ์ผ์€ GitHub Actions ์›Œํฌํ”Œ๋กœ์šฐ๋ฅผ ์ •์˜ํ•˜๋ฉฐ, Pull Request ์ด๋ฒคํŠธ์— ๋Œ€ํ•œ ์ฝ”๋“œ ๋ฆฌ๋ทฐ๋ฅผ ์ž๋™ํ™”ํ•ฉ๋‹ˆ๋‹ค. ์›Œํฌํ”Œ๋กœ์šฐ๋Š” Ubuntu ์ตœ์‹  ๋ฒ„์ „์—์„œ ์‹คํ–‰๋˜๋ฉฐ, Python 3.x ํ™˜๊ฒฝ์„ ์„ค์ •ํ•˜๊ณ , ์˜์กด์„ฑ์„ ์„ค์น˜ํ•˜๊ณ , AI ์ฝ”๋“œ ๋ฆฌ๋ทฐ ์Šคํฌ๋ฆฝํŠธ๋ฅผ ์‹คํ–‰ํ•ฉ๋‹ˆ๋‹ค. ### ์ข‹์€ ์  * ์›Œํฌํ”Œ๋กœ์šฐ๋Š” Pull Request ์ด๋ฒคํŠธ์— ๋Œ€ํ•œ ์ฝ”๋“œ ๋ฆฌ๋ทฐ๋ฅผ ์ž๋™ํ™”ํ•˜์—ฌ ๊ฐœ๋ฐœ ํ”„๋กœ์„ธ์Šค๋ฅผ ํšจ์œจ์ ์œผ๋กœ ๊ฐœ์„ ํ•ฉ๋‹ˆ๋‹ค. * Python 3.x ํ™˜๊ฒฝ์„ ์„ค์ •ํ•˜๊ณ , ์˜์กด์„ฑ์„ ์„ค์น˜ํ•˜์—ฌ ์ฝ”๋“œ ๋ฆฌ๋ทฐ ์Šคํฌ๋ฆฝํŠธ๋ฅผ ์‹คํ–‰ํ•˜๊ธฐ ์œ„ํ•œ ํ™˜๊ฒฝ์„ ์ž˜ ์„ค์ •ํ–ˆ์Šต๋‹ˆ๋‹ค. * GITHUB_TOKEN๊ณผ GROQ_API_KEY๋ฅผ ํ™˜๊ฒฝ ๋ณ€์ˆ˜๋กœ ์„ค์ •ํ•˜์—ฌ ๋ณด์•ˆ์„ ๊ฐ•ํ™”ํ–ˆ์Šต๋‹ˆ๋‹ค. ### ๊ฐœ์„ ํ•  ์  * ์›Œํฌํ”Œ๋กœ์šฐ์˜ ์ด๋ฆ„๊ณผ ์„ค๋ช…์ด ๋ช…ํ™•ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ์ด๋ฆ„๊ณผ ์„ค๋ช…์„ ๋” ๋ช…ํ™•ํ•˜๊ฒŒ ์ž‘์„ฑํ•˜์—ฌ ์›Œํฌํ”Œ๋กœ์šฐ์˜ ๋ชฉ์ ์„ ์ดํ•ดํ•˜๊ธฐ ์‰ฝ๊ฒŒ ๋งŒ๋“ค์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. * ์ผ๋ถ€ ๋‹จ๊ณ„์˜ ์ฃผ์„์ด ์ œ๊ฑฐ๋˜์—ˆ์ง€๋งŒ, ์—ฌ์ „ํžˆ ์ผ๋ถ€ ์ฃผ์„์ด ๋‚จ์•„ ์žˆ์Šต๋‹ˆ๋‹ค. ์ฃผ์„์„ ์ œ๊ฑฐํ•˜๊ฑฐ๋‚˜, ์„ค๋ช…์„ ๋” ๋ช…ํ™•ํ•˜๊ฒŒ ์ž‘์„ฑํ•˜์—ฌ ์›Œํฌํ”Œ๋กœ์šฐ์˜ ๋™์ž‘์„ ์ดํ•ดํ•˜๊ธฐ ์‰ฝ๊ฒŒ ๋งŒ๋“ค์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. * ์˜์กด์„ฑ ์„ค์น˜ ๋‹จ๊ณ„์—์„œ pip install ๋ช…๋ น์–ด๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์˜์กด์„ฑ์„ ์„ค์น˜ํ•ฉ๋‹ˆ๋‹ค. ๊ทธ๋Ÿฌ๋‚˜ pip install ๋ช…๋ น์–ด๋Š” ์˜์กด์„ฑ์„ ์„ค์น˜ํ•  ๋•Œ ๋ฒ„์ „์„ ๋ช…์‹œ์ ์œผ๋กœ ์ง€์ •ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ์˜์กด์„ฑ ์„ค์น˜ ๋‹จ๊ณ„์—์„œ ๋ฒ„์ „์„ ๋ช…์‹œ์ ์œผ๋กœ ์ง€์ •ํ•˜์—ฌ ์˜์กด์„ฑ ์„ค์น˜๋ฅผ ๋” ์•ˆ์ •์ ์œผ๋กœ ๋งŒ๋“ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * AI ์ฝ”๋“œ ๋ฆฌ๋ทฐ ์Šคํฌ๋ฆฝํŠธ๋ฅผ ์‹คํ–‰ํ•˜๋Š” ๋‹จ๊ณ„์—์„œ PYTHONPATH ํ™˜๊ฒฝ ๋ณ€์ˆ˜๋ฅผ ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค. ๊ทธ๋Ÿฌ๋‚˜ PYTHONPATH ํ™˜๊ฒฝ ๋ณ€์ˆ˜๊ฐ€ ์ด๋ฏธ ์„ค์ •๋˜์–ด ์žˆ๋Š”์ง€ ํ™•์ธํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. PYTHONPATH ํ™˜๊ฒฝ ๋ณ€์ˆ˜๊ฐ€ ์ด๋ฏธ ์„ค์ •๋˜์–ด ์žˆ๋Š”์ง€ ํ™•์ธํ•˜๊ณ , ์„ค์ •๋˜์–ด ์žˆ์ง€ ์•Š์œผ๋ฉด ์„ค์ •ํ•˜์—ฌ ์Šคํฌ๋ฆฝํŠธ๋ฅผ ์‹คํ–‰ํ•˜๊ธฐ ์œ„ํ•œ ํ™˜๊ฒฝ์„ ๋” ์•ˆ์ •์ ์œผ๋กœ ๋งŒ๋“ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ### ์ œ์•ˆ ์‚ฌํ•ญ * ์›Œํฌํ”Œ๋กœ์šฐ ์ด๋ฆ„๊ณผ ์„ค๋ช…์„ ๋” ๋ช…ํ™•ํ•˜๊ฒŒ ์ž‘์„ฑํ•˜์—ฌ ๋ชฉ์ ์„ ์ดํ•ดํ•˜๊ธฐ ์‰ฝ๊ฒŒ ๋งŒ๋“ค์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ```yml name: AI Code Review Workflow description: Automate code review for Pull Requests ``` * ์˜์กด์„ฑ ์„ค์น˜ ๋‹จ๊ณ„์—์„œ ๋ฒ„์ „์„ ๋ช…์‹œ์ ์œผ๋กœ ์ง€์ •ํ•˜์—ฌ ์˜์กด์„ฑ ์„ค์น˜๋ฅผ ๋” ์•ˆ์ •์ ์œผ๋กœ ๋งŒ๋“ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ```yml - name: Install dependencies run: | python -m pip install --upgrade pip pip install requests==2.28.1 groq==0.4.0 ``` * AI ์ฝ”๋“œ ๋ฆฌ๋ทฐ ์Šคํฌ๋ฆฝํŠธ๋ฅผ ์‹คํ–‰ํ•˜๋Š” ๋‹จ๊ณ„์—์„œ PYTHONPATH ํ™˜๊ฒฝ ๋ณ€์ˆ˜๊ฐ€ ์ด๋ฏธ ์„ค์ •๋˜์–ด ์žˆ๋Š”์ง€ ํ™•์ธํ•˜๊ณ , ์„ค์ •๋˜์–ด ์žˆ์ง€ ์•Š์œผ๋ฉด ์„ค์ •ํ•˜์—ฌ ์Šคํฌ๋ฆฝํŠธ๋ฅผ ์‹คํ–‰ํ•˜๊ธฐ ์œ„ํ•œ ํ™˜๊ฒฝ์„ ๋” ์•ˆ์ •์ ์œผ๋กœ ๋งŒ๋“ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ```yml - name: Run AI Code Review env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GROQ_API_KEY: ${{ secrets.GROQ_API_KEY }} run: | if [ -z "$PYTHONPATH" ]; then export PYTHONPATH=$PYTHONPATH:${{ github.workspace }} fi python .github/scripts/ai_code_review.py ```
@@ -25,3 +25,4 @@ flake8-comprehensions flake8-pytest-style isort mypy +groq \ No newline at end of file
Unknown
## app/backend/requirements.txt ํŒŒ์ผ ๋ฆฌ๋ทฐ ### ์ฃผ์š” ๊ธฐ๋Šฅ app/backend/requirements.txt ํŒŒ์ผ์€ Python ํ”„๋กœ์ ํŠธ์˜ ๋ฐฑ์—”๋“œ ์ข…์†์„ฑ ๋ชฉ๋ก์„ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค. ์ด ํŒŒ์ผ์—๋Š” ํ”„๋กœ์ ํŠธ์—์„œ ์‚ฌ์šฉํ•˜๋Š” ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์™€ ํŒจํ‚ค์ง€์˜ ๋ฒ„์ „์ด ํฌํ•จ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค. ### ์ข‹์€ ์  - ํ”„๋กœ์ ํŠธ์˜ ์ข…์†์„ฑ์„ ๋ช…ํ™•ํ•˜๊ฒŒ ์ •์˜ํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. - ๊ฐ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์™€ ํŒจํ‚ค์ง€์˜ ๋ฒ„์ „์„ ์ง€์ •ํ•˜์—ฌ ํ”„๋กœ์ ํŠธ์˜ ์•ˆ์ •์„ฑ์„ ๋ณด์žฅํ•ฉ๋‹ˆ๋‹ค. - ๋‹ค์–‘ํ•œ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์™€ ํŒจํ‚ค์ง€๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ”„๋กœ์ ํŠธ์˜ ๊ธฐ๋Šฅ์„ ํ™•์žฅํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ### ๊ฐœ์„ ํ•  ์  - ์ผ๋ถ€ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์™€ ํŒจํ‚ค์ง€์˜ ๋ฒ„์ „์ด ๋ช…์‹œ๋˜์–ด ์žˆ์ง€๋งŒ, ๋‚˜๋จธ์ง€ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์™€ ํŒจํ‚ค์ง€์˜ ๋ฒ„์ „์€ ๋ช…์‹œ๋˜์–ด ์žˆ์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๋ชจ๋“  ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์™€ ํŒจํ‚ค์ง€์˜ ๋ฒ„์ „์„ ๋ช…์‹œํ•˜์—ฌ ํ”„๋กœ์ ํŠธ์˜ ์•ˆ์ •์„ฑ์„ ๋ณด์žฅํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. - ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์™€ ํŒจํ‚ค์ง€์˜ ๋ชฉ๋ก์ด ๋‹ค์†Œ ๊ธธ์–ด ๊ด€๋ฆฌํ•˜๊ธฐ ์–ด๋ ต์Šต๋‹ˆ๋‹ค. ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์™€ ํŒจํ‚ค์ง€์˜ ๋ชฉ๋ก์„ ์นดํ…Œ๊ณ ๋ฆฌ๋ณ„๋กœ ๋ถ„๋ฅ˜ํ•˜์—ฌ ๊ด€๋ฆฌํ•˜๋Š” ๊ฒƒ์„ ๊ณ ๋ คํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ### ์ œ์•ˆ ์‚ฌํ•ญ 1. ๋ชจ๋“  ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์™€ ํŒจํ‚ค์ง€์˜ ๋ฒ„์ „์„ ๋ช…์‹œํ•˜์—ฌ ํ”„๋กœ์ ํŠธ์˜ ์•ˆ์ •์„ฑ์„ ๋ณด์žฅํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, `fastapi`์˜ ๋ฒ„์ „์„ ๋ช…์‹œํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ```bash fastapi==0.85.1 ``` 2. ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์™€ ํŒจํ‚ค์ง€์˜ ๋ชฉ๋ก์„ ์นดํ…Œ๊ณ ๋ฆฌ๋ณ„๋กœ ๋ถ„๋ฅ˜ํ•˜์—ฌ ๊ด€๋ฆฌํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, `requirements.txt` ํŒŒ์ผ์„ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์นดํ…Œ๊ณ ๋ฆฌ๋ณ„๋กœ ๋ถ„๋ฅ˜ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ```bash # Web Framework fastapi==0.85.1 uvicorn==0.17.6 # Database sqlalchemy[asyncio]>=2.0.0 asyncpg==0.27.1 # Security passlib==1.7.4 bcrypt==3.2.0 cryptography==3.4.7 # Utilities python-dotenv==0.20.0 alembic==1.8.1 pytest==6.2.5 ``` ์ด๋Ÿฌํ•œ ๋ณ€๊ฒฝ ์‚ฌํ•ญ์„ ์ ์šฉํ•˜๋ฉด ํ”„๋กœ์ ํŠธ์˜ ์•ˆ์ •์„ฑ์„ ๋ณด์žฅํ•˜๊ณ , ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์™€ ํŒจํ‚ค์ง€์˜ ๋ชฉ๋ก์„ ๋” ํšจ์œจ์ ์œผ๋กœ ๊ด€๋ฆฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
@@ -2,7 +2,7 @@ from dotenv import load_dotenv # load .env file -load_dotenv() +load_dotenv('app/backend/.env') from pydantic import ( PostgresDsn, @@ -73,6 +73,9 @@ class Settings(BaseSettings): # ALGORITHM : str # ACCESS_TOKEN_EXPIRE_MINUTES : int + # Groq API + GROQ_API_KEY: str + # ๊ธฐ๋ณธ ์ด๋ฏธ์ง€ URL # DEFAULT_IMAGE_URL : str
Python
## app/backend/src/main/core/config.py ํŒŒ์ผ ๋ฆฌ๋ทฐ ### ์ฃผ์š” ๊ธฐ๋Šฅ ์ด ํŒŒ์ผ์€ ํ”„๋กœ์ ํŠธ์˜ ์„ค์ •์„ ์ •์˜ํ•˜๊ณ  ๊ด€๋ฆฌํ•˜๋Š” ์—ญํ• ์„ ํ•ฉ๋‹ˆ๋‹ค. ํ”„๋กœ์ ํŠธ์˜ ํ™˜๊ฒฝ ๋ณ€์ˆ˜๋ฅผ ๋กœ๋“œํ•˜๊ณ , ์„ค์ • ํด๋ž˜์Šค๋ฅผ ์ •์˜ํ•˜์—ฌ ์„ค์ • ๊ฐ’์„ ๊ด€๋ฆฌํ•ฉ๋‹ˆ๋‹ค. ### ์ข‹์€ ์  * ํ”„๋กœ์ ํŠธ์˜ ์„ค์ •์„ ๋ณ„๋„์˜ ํŒŒ์ผ๋กœ ๋ถ„๋ฆฌํ•˜์—ฌ ๊ด€๋ฆฌํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ์ด๋Š” ํ”„๋กœ์ ํŠธ์˜ ์ฝ”๋“œ๋ฅผ ๊น”๋”ํ•˜๊ฒŒ ์œ ์ง€ํ•˜๊ณ , ์„ค์ • ๊ฐ’์„ ์‰ฝ๊ฒŒ ๊ด€๋ฆฌํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•ฉ๋‹ˆ๋‹ค. * Pydantic์„ ์‚ฌ์šฉํ•˜์—ฌ ์„ค์ • ํด๋ž˜์Šค๋ฅผ ์ •์˜ํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ์ด๋Š” ์„ค์ • ๊ฐ’์˜ ํƒ€์ž…์„ ๊ฐ•์ œํ•˜๊ณ , ์œ ํšจ์„ฑ์„ ๊ฒ€์ฆํ•˜์—ฌ ์˜ค๋ฅ˜๋ฅผ ๋ฐฉ์ง€ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * dotenv๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ™˜๊ฒฝ ๋ณ€์ˆ˜๋ฅผ ๋กœ๋“œํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ์ด๋Š” ํ™˜๊ฒฝ ๋ณ€์ˆ˜๋ฅผ ์‰ฝ๊ฒŒ ์„ค์ •ํ•˜๊ณ  ๊ด€๋ฆฌํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•ฉ๋‹ˆ๋‹ค. ### ๊ฐœ์„ ํ•  ์  * ์„ค์ • ํด๋ž˜์Šค์˜ ์†์„ฑ ์ด๋ฆ„์ด ๋„ˆ๋ฌด ๊ธธ๊ณ , ์ค‘๋ณต์ ์ธ ์ด๋ฆ„์ด ์žˆ์Šต๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, `POSTGRES_USER`์™€ `POSTGRES_PASSWORD`๋Š” `POSTGRES`๋ผ๋Š” ์ ‘๋‘์–ด๊ฐ€ ์ค‘๋ณต๋ฉ๋‹ˆ๋‹ค. ์ด๋ฅผ ๊ฐœ์„ ํ•˜๋ฉด ์ฝ”๋“œ๋ฅผ ๋” ์ฝ๊ธฐ ์‰ฝ๊ณ  ์œ ์ง€ํ•˜๊ธฐ ์‰ฌ์šฐ์‹ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * ์„ค์ • ํด๋ž˜์Šค์˜ ์†์„ฑ์— ๋Œ€ํ•œ ์„ค๋ช…์ด ์—†์Šต๋‹ˆ๋‹ค. ์ด๋Š” ์„ค์ • ๊ฐ’์˜ ์˜๋ฏธ์™€ ์‚ฌ์šฉ ๋ฐฉ๋ฒ•์„ ํŒŒ์•…ํ•˜๊ธฐ ์–ด๋ ต๊ฒŒ ๋งŒ๋“ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๊ฐ ์†์„ฑ์— ๋Œ€ํ•œ ์„ค๋ช…์„ ์ถ”๊ฐ€ํ•˜์—ฌ ์ฝ”๋“œ์˜ ๊ฐ€๋…์„ฑ์„ ํ–ฅ์ƒ์‹œํ‚ฌ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * ์„ค์ • ๊ฐ’์˜ ์œ ํšจ์„ฑ์„ ๊ฒ€์ฆํ•˜๋Š” ๋กœ์ง์ด ์—†์Šต๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, `POSTGRES_PORT`๋Š” 0์—์„œ 65535 ์‚ฌ์ด์˜ ์ •์ˆ˜์—ฌ์•ผ ํ•˜์ง€๋งŒ, ์ด๋ฅผ ๊ฒ€์ฆํ•˜๋Š” ๋กœ์ง์ด ์—†์Šต๋‹ˆ๋‹ค. ์ด๋ฅผ ๊ฐœ์„ ํ•˜๋ฉด ์˜ค๋ฅ˜๋ฅผ ๋ฐฉ์ง€ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ### ์ œ์•ˆ ์‚ฌํ•ญ * ์„ค์ • ํด๋ž˜์Šค์˜ ์†์„ฑ ์ด๋ฆ„์„ ๋‹จ์ˆœํ™”ํ•˜๊ณ , ์ค‘๋ณต์„ ์ œ๊ฑฐํ•˜์—ฌ ์ฝ”๋“œ๋ฅผ ๋” ์ฝ๊ธฐ ์‰ฝ๊ฒŒ ๋งŒ๋“ญ๋‹ˆ๋‹ค. * ๊ฐ ์†์„ฑ์— ๋Œ€ํ•œ ์„ค๋ช…์„ ์ถ”๊ฐ€ํ•˜์—ฌ ์ฝ”๋“œ์˜ ๊ฐ€๋…์„ฑ์„ ํ–ฅ์ƒ์‹œํ‚ต๋‹ˆ๋‹ค. * ์„ค์ • ๊ฐ’์˜ ์œ ํšจ์„ฑ์„ ๊ฒ€์ฆํ•˜๋Š” ๋กœ์ง์„ ์ถ”๊ฐ€ํ•˜์—ฌ ์˜ค๋ฅ˜๋ฅผ ๋ฐฉ์ง€ํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ์‹œ ์ฝ”๋“œ: ```python class Settings(BaseSettings): # ... postgres: dict[str, Any] = Field( ..., description="PostgreSQL ์„ค์ •" ) @root_validator(pre=True) def validate_postgres(cls, values): if "POSTGRES_PORT" in values: if not 0 <= values["POSTGRES_PORT"] <= 65535: raise ValueError("POSTGRES_PORT๋Š” 0์—์„œ 65535 ์‚ฌ์ด์˜ ์ •์ˆ˜์—ฌ์•ผ ํ•ฉ๋‹ˆ๋‹ค.") return values # ... ``` ์ด ์˜ˆ์‹œ ์ฝ”๋“œ๋Š” `postgres`๋ผ๋Š” ์†์„ฑ์„ ์ถ”๊ฐ€ํ•˜์—ฌ PostgreSQL ์„ค์ • ๊ฐ’์„ ๊ด€๋ฆฌํ•˜๊ณ , `validate_postgres`๋ผ๋Š” ์œ ํšจ์„ฑ ๊ฒ€์ฆ ํ•จ์ˆ˜๋ฅผ ์ถ”๊ฐ€ํ•˜์—ฌ `POSTGRES_PORT`์˜ ์œ ํšจ์„ฑ์„ ๊ฒ€์ฆํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,101 @@ +REVIEW_PROMPT = """ +You have deep knowledge and expertise in Python, FastAPI for the back end, React and Next.js for the front. +Here is the new PR information. +- title: {title} +- description: {description} +- commit messages: {commit_messages} +- changed files: {changed_files} + +Please understand and review the purpose and context of the change considering PR information and commit message. +Please be sure to thoroughly analyze and review the following format and provide a comprehensive review. +If the author has written a post in accordance with the ๐Ÿ™ review requirements (optional) written in the PR description section, +please provide a solution to resolve the content first. +If not, please find one part of the entire code provided that needs the most improvement and provide a solution. +Please find the number one priority that needs improvement in the entire code you provided and write it strictly in the format below. +-------------------------------------------------------- +## ๐Ÿง‘๐Ÿปโ€๐Ÿ’ป ์ฃผ์š” ๊ธฐ๋Šฅ + +[Provide a brief description of the main features of this file, including its core functionality, expected input and output, and any specific exception cases it handles.] + +## ๐Ÿ” ๊ฐœ์„ ํ•  ์  + +[Write down any areas that need improvement, including performance bottlenecks, readability issues, and security vulnerabilities.] + +## ๐Ÿ“ข ์ œ์•ˆ๋œ ์†”๋ฃจ์…˜ + +1. ํ˜„์žฌ ์ฝ”๋“œ + +[problematic code fragment] + +2. ๊ถŒ์žฅ๋˜๋Š” ๋ณ€๊ฒฝ + +[updated code snippet] + +3. ๋ณ€๊ฒฝ ์ด์œ  + +[Brief reasons why the new approach is better, considering performance, readability, security, etc.] +-------------------------------------------------------- + +Full Code: {all_code} + +If you need to put in a code block, keep it brief, no more than 10 lines of code that needs improvement. +Please write one sentence within 70 characters, including the maximum space, that you need to explain. +If you write one sentence for readability, please write the next sentence in the next column instead of the next one. + +The person receiving this feedback is a Korean developer. +Please make sure to follow the above format strictly in Korean, but please provide specific and constructive feedback. +""" + +FILE_REVIEW_PROMPT = """ +๋‹ค์Œ {filename} ํŒŒ์ผ์˜ ์ฝ”๋“œ๋ฅผ ๋ฆฌ๋ทฐํ•˜๊ณ , ์•„๋ž˜ ํ˜•์‹์œผ๋กœ ์ƒ์„ธํ•œ ๋ฆฌ๋ทฐ๋ฅผ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”: + +## {filename} ํŒŒ์ผ ๋ฆฌ๋ทฐ + +### ์ฃผ์š” ๊ธฐ๋Šฅ +[ํŒŒ์ผ์˜ ์ฃผ์š” ๊ธฐ๋Šฅ ์„ค๋ช…] + +### ์ข‹์€ ์  +[์ข‹์€ ์  ๋‚˜์—ด] + +### ๊ฐœ์„ ํ•  ์  +[๊ฐœ์„ ์ด ํ•„์š”ํ•œ ์  ๋‚˜์—ด] + +### ์ œ์•ˆ ์‚ฌํ•ญ +[๊ตฌ์ฒด์ ์ธ ๊ฐœ์„  ์ œ์•ˆ, ์ฝ”๋“œ ์˜ˆ์‹œ ํฌํ•จ] + +ํŒŒ์ผ ๋‚ด์šฉ: +{content} +""" + +LINE_COMMENTS_PROMPT = """ +๋‹ค์Œ {filename} ํŒŒ์ผ์˜ ์ฝ”๋“œ๋ฅผ ๋ฆฌ๋ทฐํ•˜๊ณ , ์ค‘์š”ํ•œ ๋ผ์ธ์— ๋Œ€ํ•ด ๊ตฌ์ฒด์ ์ธ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”. +ํ˜•์‹์€ '๋ผ์ธ ๋ฒˆํ˜ธ: ์ฝ”๋ฉ˜ํŠธ'๋กœ ํ•ด์ฃผ์„ธ์š”. + +{content} +""" + +OVERALL_COMMENTS_PROMPT = """ +## AI ์ฝ”๋“œ ๋ฆฌ๋ทฐ ์š”์•ฝ + +{overall_review} +""" + +def get_review_prompt(all_code, pr_context, commit_messages, changed_files): + formatted_commit_messages = "\n".join([f"- {msg}" for msg in commit_messages]) + return REVIEW_PROMPT.format( + title=pr_context['title'], + description=pr_context['description'], + commit_messages=formatted_commit_messages, + changed_files=changed_files, + all_code=all_code + ) + +def get_file_review_prompt(filename, content): + return FILE_REVIEW_PROMPT.format(filename=filename, content=content) + +def get_line_comments_prompt(filename, content): + return LINE_COMMENTS_PROMPT.format(filename=filename, content=content) + +def get_total_comments_prompt(overall_review): + return OVERALL_COMMENTS_PROMPT.format(overall_review=overall_review) + \ No newline at end of file
Python
## scripts/review_prompt.py ํŒŒ์ผ ๋ฆฌ๋ทฐ ### ์ฃผ์š” ๊ธฐ๋Šฅ ์ด ํŒŒ์ผ์€ ์ฝ”๋“œ ๋ฆฌ๋ทฐ์— ๋Œ€ํ•œ ํ”„๋กฌํ”„ํŠธ๋ฅผ ์ œ๊ณตํ•˜๋Š” ๊ธฐ๋Šฅ์„ ๋‹ด๋‹นํ•ฉ๋‹ˆ๋‹ค. ๋‹ค์–‘ํ•œ ์œ ํ˜•์˜ ๋ฆฌ๋ทฐ ํ”„๋กฌํ”„ํŠธ๋ฅผ ์ •์˜ํ•˜๊ณ , ํ•„์š”ํ•œ ๋ฐ์ดํ„ฐ๋ฅผ ํฌํ•จํ•˜์—ฌ ํ”„๋กฌํ”„ํŠธ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜๋“ค์„ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค. ### ์ข‹์€ ์  - ์ฝ”๋“œ๋Š” ๊ฐ€๋…์„ฑ์ด ์ข‹๊ณ , ๊ฐ ํ•จ์ˆ˜์˜ ์—ญํ• ์ด ๋ช…ํ™•ํ•ฉ๋‹ˆ๋‹ค. - ํ”„๋กฌํ”„ํŠธ ํ…œํ”Œ๋ฆฟ์€ string.format() ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋™์ ์œผ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ํฌํ•จํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. - ํ•จ์ˆ˜๋ช…๊ณผ ๋ณ€์ˆ˜๋ช…์ด ๋ช…ํ™•ํ•˜๊ฒŒ ์ •์˜๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค. ### ๊ฐœ์„ ํ•  ์  - ํ•จ์ˆ˜์˜ ์—ญํ• ์ด ๋ช…ํ™•ํ•˜์ง€๋งŒ, ํ•จ์ˆ˜์˜ ์„ค๋ช…๊ณผ ๋„ํ๋จผํŠธ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. ์ด๋Š” ์ฝ”๋“œ์˜ ์ดํ•ด๋ฅผ ์–ด๋ ต๊ฒŒ ๋งŒ๋“ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. - ์—๋Ÿฌ ํ•ธ๋“ค๋ง์ด ์—†์Šต๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, ํ•จ์ˆ˜์— ์ž˜๋ชป๋œ ๋ฐ์ดํ„ฐ๊ฐ€ ์ž…๋ ฅ๋œ ๊ฒฝ์šฐ, ์ ์ ˆํ•œ ์—๋Ÿฌ ๋ฉ”์‹œ์ง€๋ฅผ ๋ฐ˜ํ™˜ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. - ํ”„๋กฌํ”„ํŠธ ํ…œํ”Œ๋ฆฟ์— ๋Œ€ํ•œ ํ…Œ์ŠคํŠธ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. ์ด๋Š” ํ”„๋กฌํ”„ํŠธ ํ…œํ”Œ๋ฆฟ์˜ ์œ ํšจ์„ฑ์„ ํ™•์ธํ•˜๊ธฐ ์œ„ํ•ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. ### ์ œ์•ˆ ์‚ฌํ•ญ 1. ํ•จ์ˆ˜์— ๋Œ€ํ•œ ์„ค๋ช…๊ณผ ๋„ํ๋จผํŠธ๋ฅผ ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค. ```python def get_review_prompt(code): """ ์ „์ฒด ์ฝ”๋“œ ๋ฆฌ๋ทฐ ํ”„๋กฌํ”„ํŠธ๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. Args: code (str): ์ฝ”๋“œ ๋‚ด์šฉ Returns: str: ์ „์ฒด ์ฝ”๋“œ ๋ฆฌ๋ทฐ ํ”„๋กฌํ”„ํŠธ """ return REVIEW_PROMPT.format(code=code) ``` 2. ์—๋Ÿฌ ํ•ธ๋“ค๋ง์„ ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค. ```python def get_file_review_prompt(filename, content): if not filename or not content: raise ValueError("ํŒŒ์ผ๋ช…๊ณผ ๋‚ด์šฉ์€ ๋ฐ˜๋“œ์‹œ ์ œ๊ณต๋˜์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.") return FILE_REVIEW_PROMPT.format(filename=filename, content=content) ``` 3. ํ”„๋กฌํ”„ํŠธ ํ…œํ”Œ๋ฆฟ์— ๋Œ€ํ•œ ํ…Œ์ŠคํŠธ๋ฅผ ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค. ```python import unittest class TestReviewPrompt(unittest.TestCase): def test_get_review_prompt(self): code = "print('Hello World')" prompt = get_review_prompt(code) self.assertIn(code, prompt) def test_get_file_review_prompt(self): filename = "example.py" content = "print('Hello World')" prompt = get_file_review_prompt(filename, content) self.assertIn(filename, prompt) self.assertIn(content, prompt) ``` 4. ํ”„๋กฌํ”„ํŠธ ํ…œํ”Œ๋ฆฟ์„ ๋” ์œ ์—ฐํ•˜๊ฒŒ ๋งŒ๋“ค๊ธฐ ์œ„ํ•ด, ํ…œํ”Œ๋ฆฟ ์—”์ง„์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์„ ๊ณ ๋ คํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,549 @@ +import json +import os +from typing import List, Tuple +import requests +import re +import groq +import logging +from review_config import ( + IGNORED_EXTENSIONS, + IGNORED_FILES, + IMPORTANT_FILE_CHANGE_THRESHOLD, + MAX_COMMENTS_PER_FILE +) + +from scripts.review_prompt import ( + get_review_prompt, + get_file_review_prompt, + get_line_comments_prompt, + get_total_comments_prompt +) + +logging.basicConfig(level=logging.DEBUG) +logger = logging.getLogger(__name__) + +groq_client = groq.Groq(api_key=os.environ["GROQ_API_KEY"]) + +def get_pr_files(repo, pr_number, token): + url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}/files" + headers = { + "Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28" + } + + logger.debug(f"PR ํŒŒ์ผ ๊ฐ€์ ธ์˜ค๋Š” ์ค‘. URL: {url}") + logger.debug(f"ํ—ค๋”: {headers}") + + try: + response = requests.get(url, headers=headers) + response.raise_for_status() + return response.json() + except requests.RequestException as e: + logger.error(f"PR ํŒŒ์ผ ๊ฐ€์ ธ์˜ค๊ธฐ ์˜ค๋ฅ˜: {str(e)}") + return None + +def get_latest_commit_id(repo, pr_number, token): + url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}" + headers = { + "Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28" + } + + response = requests.get(url, headers=headers) + response.raise_for_status() + pr_data = response.json() + return pr_data['head']['sha'] + +def review_code_groq(prompt): + try: + response = groq_client.chat.completions.create( + model="llama-3.1-70b-versatile", + messages=[ + {"role": "system", "content": "You are a professional code reviewer from FANNG Senior Developer."}, + {"role": "user", "content": prompt} + ], + temperature=0.7, + max_tokens=2048 + ) + return response.choices[0].message.content + except Exception as e: + logger.error(f"Groq API ํ˜ธ์ถœ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}") + return f"์ฝ”๋“œ ๋ฆฌ๋ทฐ ์ค‘ ๋ฐœ์ƒํ•œ ์—๋Ÿฌ: {str(e)}" + +# def review_code_ollama(pr_content): +# prompt = get_review_prompt(pr_content) +# url = 'http://localhost:11434/api/generate' +# data = { +# "model": "llama3.1", +# "prompt": prompt, +# "stream": False, +# "options": { +# "temperature": 0.7, +# "top_p": 0.8, +# "top_k": 40, +# "num_predict": 1024 +# } +# } +# logger.debug(f"์ฝ”๋“œ ๋ฆฌ๋ทฐ ์ค‘. URL: {url}") +# logger.debug(f"์š”์ฒญ ๋ฐ์ดํ„ฐ: {data}") + +# try: +# response = requests.post(url, json=data) +# response.raise_for_status() +# return response.json()['response'] +# except requests.RequestException as e: +# logger.error(f"์ฝ”๋“œ ๋ฆฌ๋ทฐ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}") +# return f"์ฝ”๋“œ ๋ฆฌ๋ทฐ ์ค‘ ๋ฐœ์ƒํ•œ ์—๋Ÿฌ: {str(e)}" + +def post_review_comment(repo, pr_number, commit_sha, path, position, body, token): + url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}/comments" + headers = { + "Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28" + } + data = { + "body": body, + "commit_id": commit_sha, + "path": path, + "position": position + } + logger.debug(f"๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ ๊ฒŒ์‹œ ์ค‘. URL: {url}") + logger.debug(f"ํ—ค๋”: {headers}") + logger.debug(f"๋ฐ์ดํ„ฐ: {data}") + + try: + response = requests.post(url, headers=headers, json=data) + response.raise_for_status() + logger.info("๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ๊ฐ€ ์„ฑ๊ณต์ ์œผ๋กœ ๊ฒŒ์‹œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค") + except requests.RequestException as e: + logger.error(f"๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ ๊ฒŒ์‹œ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}") + logger.error(f"์‘๋‹ต ๋‚ด์šฉ: {response.content if 'response' in locals() else '์‘๋‹ต ์—†์Œ'}") + logger.error(f"์‘๋‹ต ์ƒํƒœ ์ฝ”๋“œ: {e.response.status_code}") + logger.error(f"์‘๋‹ต ํ—ค๋”: {e.response.headers}") + logger.error(f"์‘๋‹ต ๋‚ด์šฉ: {e.response.text}") + +def summarize_reviews(all_reviews): + summary_prompt = f"๋‹ค์Œ์€ ์ „์ฒด์ ์ธ ์ฝ”๋“œ ๋ฆฌ๋ทฐ ๊ฒฐ๊ณผ์ž…๋‹ˆ๋‹ค : \n\n{''.join(all_reviews)}" + summary = review_code_groq(summary_prompt) + return summary + +def post_pr_comment(repo, pr_number, body, token): + url = f"https://api.github.com/repos/{repo}/issues/{pr_number}/comments" + headers = { + "Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28" + } + data = {"body": body} + + try: + response = requests.post(url, headers=headers, json=data) + response.raise_for_status() + logger.info("PR ์ฝ”๋ฉ˜ํŠธ๊ฐ€ ์„ฑ๊ณต์ ์œผ๋กœ ๊ฒŒ์‹œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.") + except requests.RequestException as e: + logger.error(f"PR ์ฝ”๋ฉ˜ํŠธ ๊ฒŒ์‹œ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}") + logger.error(f"์‘๋‹ต ๋‚ด์šฉ: {response.content if 'response' in locals() else '์‘๋‹ต ์—†์Œ'}") + +def get_pr_context(repo, pr_number, github_token): + url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}" + headers = { + "Authorization": f"Bearer {github_token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28" + } + response = requests.get(url, headers=headers) + response.raise_for_status() + pr_data = response.json() + return { + "title": pr_data['title'], + "description": pr_data['body'] + } + +def get_commit_messages(repo, pr_number, github_token): + url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}/commits" + headers = { + "Authorization": f"Bearer {github_token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28" + } + response = requests.get(url, headers=headers) + response.raise_for_status() + commits = response.json() + return [commit['commit']['message'] for commit in commits] + +def get_changed_files(repo, pr_number, github_token): + url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}/files" + headers = { + "Authorization": f"token {github_token}", + "Accept": "application/vnd.github.v3+json" + } + response = requests.get(url, headers=headers) + files = response.json() + + changed_files_info = [] + for file in files: + status = file['status'] + filename = file['filename'] + additions = file['additions'] + deletions = file['deletions'] + + if status == 'added': + info = f"{filename} (์ถ”๊ฐ€, +{additions}, -0)" + elif status == 'removed': + info = f"{filename} (์‚ญ์ œ)" + else: + info = f"{filename} (์ˆ˜์ •, +{additions}, -{deletions})" + + changed_files_info.append(info) + + return "\n".join(f"{i+1}. {info}" for i, info in enumerate(changed_files_info)) + +def post_line_comments(repo, pr_number, commit_sha, filename, patch, line_comments, token): + url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}/comments" + headers = { + "Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28" + } + + def get_line_numbers(patch): + lines = patch.split('\n') + line_numbers = [] + current_line = 0 + for line in lines: + if line.startswith('@@'): + current_line = int(line.split('+')[1].split(',')[0]) - 1 + elif not line.startswith('-'): + current_line += 1 + if line.startswith('+'): + line_numbers.append(current_line) + return line_numbers + + def post_single_comment(line_num, comment_text, position): + data = { + "body": comment_text.strip(), + "commit_id": commit_sha, + "path": filename, + "line": position + } + logger.debug(f"๋ผ์ธ {line_num}์— ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ ๊ฒŒ์‹œ ์ค‘. URL: {url}") + logger.debug(f"ํ—ค๋”: {headers}") + logger.debug(f"๋ฐ์ดํ„ฐ: {data}") + + try: + response = requests.post(url, headers=headers, json=data) + response.raise_for_status() + logger.info(f"๋ผ์ธ {line_num}์— ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ๊ฐ€ ์„ฑ๊ณต์ ์œผ๋กœ ๊ฒŒ์‹œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค") + except requests.RequestException as e: + logger.error(f"๋ผ์ธ {line_num} ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ ๊ฒŒ์‹œ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}") + logger.error(f"์‘๋‹ต ๋‚ด์šฉ: {response.content if 'response' in locals() else '์‘๋‹ต ์—†์Œ'}") + logger.error(f"์‘๋‹ต ์ƒํƒœ ์ฝ”๋“œ: {e.response.status_code if 'response' in locals() else '์•Œ ์ˆ˜ ์—†์Œ'}") + logger.error(f"์‘๋‹ต ํ—ค๋”: {e.response.headers if 'response' in locals() else '์•Œ ์ˆ˜ ์—†์Œ'}") + logger.error(f"์‘๋‹ต ๋‚ด์šฉ: {e.response.text if 'response' in locals() else '์•Œ ์ˆ˜ ์—†์Œ'}") + + def parse_comments(line_comments: str) -> List[Tuple[int, str]]: + parsed_comments = [] + for comment in line_comments.split('\n'): + match = re.match(r'(\d+):\s*(.*)', comment) + if match: + line_num, comment_text = match.groups() + try: + line_num = int(line_num) + parsed_comments.append((line_num, comment_text)) + except ValueError: + logger.warning(f"์ž˜๋ชป๋œ ๋ผ์ธ ๋ฒˆํ˜ธ ํ˜•์‹: {line_num}") + else: + logger.warning(f"ํŒŒ์‹ฑํ•  ์ˆ˜ ์—†๋Š” ์ฝ”๋ฉ˜ํŠธ ํ˜•์‹: {comment}") + return parsed_comments + + def evaluate_importance(comment: str) -> int: + # ์—ฌ๊ธฐ์— ์ฝ”๋ฉ˜ํŠธ์˜ ์ค‘์š”๋„๋ฅผ ํ‰๊ฐ€ํ•˜๋Š” ๋กœ์ง์„ ๊ตฌํ˜„ํ•ฉ๋‹ˆ๋‹ค. + # ์˜ˆ๋ฅผ ๋“ค์–ด, ํŠน์ • ํ‚ค์›Œ๋“œ์˜ ์กด์žฌ ์—ฌ๋ถ€, ์ฝ”๋ฉ˜ํŠธ์˜ ๊ธธ์ด ๋“ฑ์„ ๊ณ ๋ คํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. + importance = 0 + if "์ค‘์š”" in comment or "critical" in comment.lower(): + importance += 5 + if "๋ฒ„๊ทธ" in comment or "bug" in comment.lower(): + importance += 4 + if "๊ฐœ์„ " in comment or "improvement" in comment.lower(): + importance += 3 + importance += len(comment) // 50 # ๊ธด ์ฝ”๋ฉ˜ํŠธ์— ์•ฝ๊ฐ„์˜ ๊ฐ€์ค‘์น˜ ๋ถ€์—ฌ + return importance + + line_numbers = get_line_numbers(patch) + parsed_comments = parse_comments(line_comments) + + # ์ค‘์š”๋„์— ๋”ฐ๋ผ ์ฝ”๋ฉ˜ํŠธ ์ •๋ ฌ + sorted_comments = sorted(parsed_comments, key=lambda x: evaluate_importance(x[1]), reverse=True) + + comments_posted = 0 + # ๋ผ์ธ ์ฝ”๋ฉ˜ํŠธ ํŒŒ์‹ฑ ๋ฐ ๊ฒŒ์‹œ + for line_num, comment_text in sorted_comments[:MAX_COMMENTS_PER_FILE]: + if 0 <= line_num - 1 < len(line_numbers): + position = line_numbers[line_num - 1] + if post_single_comment(line_num, comment_text, position): + comments_posted += 1 + else: + logger.warning(f"๋ผ์ธ {line_num}์ด ์œ ํšจํ•œ ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚ฌ์Šต๋‹ˆ๋‹ค.") + + # for comment in line_comments.split('\n'): + # if comments_posted >= MAX_COMMENTS_PER_FILE: + # logger.info(f"{filename}: ์ตœ๋Œ€ ์ฝ”๋ฉ˜ํŠธ ์ˆ˜({MAX_COMMENTS_PER_FILE})์— ๋„๋‹ฌํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‚˜๋จธ์ง€ ์ฝ”๋ฉ˜ํŠธ๋Š” ์ƒ๋žต๋ฉ๋‹ˆ๋‹ค.") + # break + + # match = re.match(r'(\d+):\s*(.*)', comment) + # if match: + # line_num, comment_text = match.groups() + # try: + # line_num = int(line_num) + # if 0 <= line_num - 1 < len(line_numbers): + # position = line_numbers[line_num - 1] + # if post_single_comment(line_num, comment_text, position): + # comments_posted += 1 + # else: + # logger.warning(f"๋ผ์ธ {line_num}์ด ์œ ํšจํ•œ ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚ฌ์Šต๋‹ˆ๋‹ค.") + # except ValueError: + # logger.warning(f"์ž˜๋ชป๋œ ๋ผ์ธ ๋ฒˆํ˜ธ ํ˜•์‹: {line_num}") + # else: + # logger.warning(f"ํŒŒ์‹ฑํ•  ์ˆ˜ ์—†๋Š” ์ฝ”๋ฉ˜ํŠธ ํ˜•์‹: {comment}") + + if comments_posted == 0: + logger.info(f"{filename}: ์ถ”๊ฐ€๋œ ์ฝ”๋ฉ˜ํŠธ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.") + else: + logger.info(f"{filename}: ์ด {comments_posted}๊ฐœ์˜ ์ฝ”๋ฉ˜ํŠธ๊ฐ€ ์ถ”๊ฐ€๋˜์—ˆ์Šต๋‹ˆ๋‹ค.") + + logger.info("๋ชจ๋“  ๋ผ์ธ ์ฝ”๋ฉ˜ํŠธ ์ฒ˜๋ฆฌ ์™„๋ฃŒ") + +def get_environment_variables(): + try: + github_token = os.environ['GITHUB_TOKEN'] + repo = os.environ['GITHUB_REPOSITORY'] + event_path = os.environ['GITHUB_EVENT_PATH'] + return github_token, repo, event_path + except KeyError as e: + logger.error(f"ํ™˜๊ฒฝ ๋ณ€์ˆ˜๊ฐ€ ์„ค์ •๋˜์ง€ ์•Š์Œ: {str(e)}") + raise + +def fetch_pr_data(repo, pr_number, github_token): + pr_files = get_pr_files(repo, pr_number, github_token) + if not pr_files: + logger.warning("ํŒŒ์ผ์„ ์ฐพ์„ ์ˆ˜ ์—†๊ฑฐ๋‚˜ PR ํŒŒ์ผ์„ ๊ฐ€์ ธ์˜ค๋Š” ๋ฐ ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค.") + return None, None + latest_commit_id = get_latest_commit_id(repo, pr_number, github_token) + return pr_files, latest_commit_id + +def get_importance_threshold(file, total_pr_changes): + base_threshold = 0.5 # ๊ธฐ๋ณธ ์ž„๊ณ„๊ฐ’์„ 0.5๋กœ ์„ค์ • (๋” ๋งŽ์€ ํŒŒ์ผ์„ ์ค‘์š”ํ•˜๊ฒŒ ๊ฐ„์ฃผ) + + # ํŒŒ์ผ ํ™•์žฅ์ž์— ๋”ฐ๋ฅธ ๊ฐ€์ค‘์น˜ + extension_weights = { + # ๋ฐฑ์—”๋“œ ํŒŒ์ผ (๋†’์€ ๊ฐ€์ค‘์น˜) + '.py': 1.2, # Python ํŒŒ์ผ + + # ํ”„๋ก ํŠธ์—”๋“œ ํŒŒ์ผ (๋†’์€ ๊ฐ€์ค‘์น˜) + '.js': 1.2, # JavaScript ํŒŒ์ผ + '.jsx': 1.2, # React JSX ํŒŒ์ผ + '.ts': 1.2, # TypeScript ํŒŒ์ผ + '.tsx': 1.2, # React TypeScript ํŒŒ์ผ + + # ์Šคํƒ€์ผ ํŒŒ์ผ (์ค‘๊ฐ„ ๊ฐ€์ค‘์น˜) + '.css': 1.0, # CSS ํŒŒ์ผ + '.scss': 1.0, # SCSS ํŒŒ์ผ + + # ์„ค์ • ํŒŒ์ผ (๋‚ฎ์€ ๊ฐ€์ค‘์น˜) + '.json': 0.9, # JSON ์„ค์ • ํŒŒ์ผ + '.yml': 0.9, # YAML ์„ค์ • ํŒŒ์ผ + '.env': 0.9, # ํ™˜๊ฒฝ ๋ณ€์ˆ˜ ํŒŒ์ผ + + # ๋ฌธ์„œ ํŒŒ์ผ (๊ฐ€์žฅ ๋‚ฎ์€ ๊ฐ€์ค‘์น˜) + '.md': 0.7, # Markdown ๋ฌธ์„œ + '.txt': 0.7, # ํ…์ŠคํŠธ ๋ฌธ์„œ + } + + # ํŒŒ์ผ ํ™•์žฅ์ž ์ถ”์ถœ + _, ext = os.path.splitext(file['filename']) + + # ํ™•์žฅ์ž์— ๋”ฐ๋ฅธ ๊ฐ€์ค‘์น˜ ์ ์šฉ (๊ธฐ๋ณธ๊ฐ’ 1.0) + weight = extension_weights.get(ext.lower(), 1.0) + + # PR ์ „์ฒด ๋ณ€๊ฒฝ ํฌ๊ธฐ์— ๋”ฐ๋ฅธ ์กฐ์ • (ํŒ€ ๊ทœ๋ชจ๊ฐ€ ์ž‘์œผ๋ฏ€๋กœ ๊ธฐ์ค€์„ ๋‚ฎ์ถค) + if total_pr_changes > 500: # ๋Œ€๊ทœ๋ชจ PR ๊ธฐ์ค€์„ 500์ค„๋กœ ๋‚ฎ์ถค + base_threshold *= 0.9 # ๋Œ€๊ทœ๋ชจ PR์˜ ๊ฒฝ์šฐ ์ž„๊ณ„๊ฐ’ ๋‚ฎ์ถค + elif total_pr_changes < 50: # ์†Œ๊ทœ๋ชจ PR ๊ธฐ์ค€์„ 50์ค„๋กœ ๋‚ฎ์ถค + base_threshold *= 1.1 # ์†Œ๊ทœ๋ชจ PR์˜ ๊ฒฝ์šฐ ์ž„๊ณ„๊ฐ’ ๋†’์ž„ + + # ํŒŒ์ผ ํฌ๊ธฐ์— ๋”ฐ๋ฅธ ์กฐ์ • + file_size = file.get('changes', 0) + if file_size < 30: # ์ž‘์€ ํŒŒ์ผ ๊ธฐ์ค€์„ 30์ค„๋กœ ๋‚ฎ์ถค + base_threshold *= 1.2 # ์ž‘์€ ํŒŒ์ผ์˜ ๊ฒฝ์šฐ ์ž„๊ณ„๊ฐ’ ๋†’์ž„ + elif file_size > 300: # ํฐ ํŒŒ์ผ ๊ธฐ์ค€์„ 300์ค„๋กœ ๋‚ฎ์ถค + base_threshold *= 0.8 # ํฐ ํŒŒ์ผ์˜ ๊ฒฝ์šฐ ์ž„๊ณ„๊ฐ’ ๋‚ฎ์ถค + + return min(base_threshold * weight, 1.0) # ์ตœ๋Œ€๊ฐ’์„ 1.0์œผ๋กœ ์ œํ•œ + +def is_important_file(file, total_pr_changes): + filename = file['filename'] + if filename in IGNORED_FILES: + logger.debug(f"๋ฌด์‹œ๋œ ํŒŒ์ผ: {filename}") + return False + + if any(filename.endswith(ext) for ext in IGNORED_EXTENSIONS): + logger.debug(f"๋ฌด์‹œํ•  ํ™•์žฅ์ž ํŒŒ์ผ: {filename}") + return False + + if file['status'] == 'removed': + logger.info(f"์‚ญ์ œ๋œ ํŒŒ์ผ: {file['filename']}") + return True + + total_changes = file.get('changes', 0) + additions = file.get('additions', 0) + deletions = file.get('deletions', 0) + + # ํŒŒ์ผ์˜ ์ „์ฒด ํฌ๊ธฐ ๋Œ€๋น„ ๋ณ€๊ฒฝ๋œ ๋ผ์ธ ์ˆ˜์˜ ๋น„์œจ + change_ratio = total_changes / total_pr_changes if total_pr_changes > 0 else 0 + importance_threshold = get_importance_threshold(file, total_pr_changes) + + is_important = total_changes > IMPORTANT_FILE_CHANGE_THRESHOLD or change_ratio > importance_threshold + + if is_important: + logger.info(f"์ค‘์š” ํŒŒ์ผ๋กœ ์„ ์ •: {filename} (๋ณ€๊ฒฝ: {total_changes}์ค„, ์ถ”๊ฐ€: {additions}, ์‚ญ์ œ: {deletions}, ๋น„์œจ: {change_ratio:.2f}, ์ž„๊ณ„๊ฐ’: {importance_threshold:.2f})") + else: + logger.debug(f"์ผ๋ฐ˜ ํŒŒ์ผ: {filename} (๋ณ€๊ฒฝ: {total_changes}์ค„, ์ถ”๊ฐ€: {additions}, ์‚ญ์ œ: {deletions}, ๋น„์œจ: {change_ratio:.2f}, ์ž„๊ณ„๊ฐ’: {importance_threshold:.2f})") + + return is_important + +def generate_reviews(pr_files, repo, pr_number, latest_commit_id, github_token): + all_code = "" + total_pr_changes = sum(file.get('changes', 0) for file in pr_files) + + important_files = [f for f in pr_files if is_important_file(f, total_pr_changes)] + + logger.info(f"์ด {len(pr_files)}๊ฐœ ํŒŒ์ผ ์ค‘ {len(important_files)}๊ฐœ ํŒŒ์ผ์ด ์ค‘์š” ํŒŒ์ผ๋กœ ์„ ์ •๋˜์—ˆ์Šต๋‹ˆ๋‹ค.") + logger.info(f"PR ์ „์ฒด ๋ณ€๊ฒฝ ํฌ๊ธฐ: {total_pr_changes}์ค„") + + for file in pr_files: + if file['status'] == 'removed': + all_code += f"File: {file['filename']} (DELETED)\n\n" + else: + logger.info(f"ํŒŒ์ผ ๋ฆฌ๋ทฐ ์ค‘: {file['filename']}") + content = requests.get(file['raw_url']).text + all_code += f"File: {file['filename']}\n{content}\n\n" + + if not all_code: + logger.warning("๋ฆฌ๋ทฐํ•  ์ฝ”๋“œ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. ๋ชจ๋“  ํŒŒ์ผ ๋‚ด์šฉ์„ ๊ฐ€์ ธ์˜ค๋Š” ๋ฐ ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค.") + return None, [] + + pr_context = get_pr_context(repo, pr_number, github_token) + commit_messages = get_commit_messages(repo, pr_number, github_token) + changed_files = get_changed_files(repo, pr_number, github_token) + + # ๊ฐœ์„ ๋œ ๋ฆฌ๋ทฐ ํ”„๋กฌํ”„ํŠธ ์ƒ์„ฑ + review_prompt = get_review_prompt(all_code, pr_context, commit_messages, changed_files) + + # ์ „์ฒด ์ฝ”๋“œ์— ๋Œ€ํ•œ ์ƒ์„ธํ•œ ๋ฆฌ๋ทฐ + overall_review = review_code_groq(review_prompt) + + # ์ค‘์š” ํŒŒ์ผ์— ๋Œ€ํ•œ ์ƒ์„ธ ๋ฆฌ๋ทฐ (๋ผ์ธ ๋ณ„ ์ฝ”๋ฉ˜ํŠธ ๋น„ํ™œ์„ฑํ™”) + # for file in important_files: + # logger.info(f"์ค‘์š” ํŒŒ์ผ ์ƒ์„ธ ๋ฆฌ๋ทฐ ์ค‘: {file['filename']}") + # if file['status'] == 'removed': + # file_review = f"ํŒŒ์ผ '{file['filename']}'์ด(๊ฐ€) ์‚ญ์ œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ์ด ๋ณ€๊ฒฝ์ด ์ ์ ˆํ•œ์ง€ ํ™•์ธํ•ด ์ฃผ์„ธ์š”." + # else: + # content = requests.get(file['raw_url']).text + # file_review_prompt = get_file_review_prompt(file['filename'], content) + # file_review = review_code_groq(file_review_prompt) + + # # ํŒŒ์ผ ์ „์ฒด์— ๋Œ€ํ•œ ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ + # post_file_comment( + # repo, + # pr_number, + # latest_commit_id, + # file['filename'], + # file_review, + # github_token + # ) + + # # ๋ผ์ธ ๋ณ„ ์ฝ”๋ฉ˜ํŠธ + # line_comments_prompt = get_line_comments_prompt(file['filename'], content) + # line_comments = review_code_groq(line_comments_prompt) + + # post_line_comments( + # repo, + # pr_number, + # latest_commit_id, + # file['filename'], + # file['patch'], + # line_comments, + # github_token + # ) + + return overall_review + +def post_file_comment(repo, pr_number, commit_sha, file_path, body, token): + url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}/comments" + headers = { + "Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28" + } + data = { + "body": body, + "commit_id": commit_sha, + "path": file_path, + "position": 1 + } + + try: + response = requests.post(url, headers=headers, json=data) + response.raise_for_status() + logger.info("PR ํŒŒ์ผ ์ฝ”๋ฉ˜ํŠธ๊ฐ€ ์„ฑ๊ณต์ ์œผ๋กœ ๊ฒŒ์‹œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.") + except requests.RequestException as e: + logger.error(f"PR ์ฝ”๋ฉ˜ํŠธ ๊ฒŒ์‹œ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}") + logger.error(f"์‘๋‹ต ๋‚ด์šฉ: {response.content if 'response' in locals() else '์‘๋‹ต ์—†์Œ'}") + +def main(): + try: + github_token, repo, event_path = get_environment_variables() + + logger.info(f"์ €์žฅ์†Œ ๋ฆฌ๋ทฐ ์‹œ์ž‘: {repo}") + logger.debug(f"GitHub ํ† ํฐ (์ฒ˜์Œ 5์ž): {github_token[:5]}...") + + with open(event_path) as f: + event = json.load(f) + + pr_number = event.get('pull_request', {}).get('number') + if pr_number is None: + logger.error("PR ๋ฒˆํ˜ธ๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. GitHub ์ด๋ฒคํŠธ ํŒŒ์ผ์ด pull_request ์ด๋ฒคํŠธ๋ฅผ ํฌํ•จํ•˜๊ณ  ์žˆ๋Š”์ง€ ํ™•์ธํ•˜์„ธ์š”.") + + logger.info(f"PR ๋ฒˆํ˜ธ {pr_number} ๋ฆฌ๋ทฐ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค.") + + pr_files, latest_commit_id = fetch_pr_data(repo, pr_number, github_token) + if not pr_files: + return + + overall_review = generate_reviews( + pr_files, + repo, + pr_number, + latest_commit_id, + github_token + ) + + if overall_review: + # comment = get_total_comments_prompt(overall_review) + post_pr_comment( + repo, + pr_number, + overall_review, + github_token + ) + + except KeyError as e: + logger.error(f"ํ™˜๊ฒฝ ๋ณ€์ˆ˜๊ฐ€ ์„ค์ •๋˜์ง€ ์•Š์Œ: {str(e)}") + except Exception as e: + logger.error(f"์˜ˆ์ƒ์น˜ ๋ชปํ•œ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}") + +if __name__ == "__main__": + main()
Python
## ์ „์ฒด ์ฝ”๋“œ ๋ฆฌ๋ทฐ ### ์ฃผ์š” ๊ธฐ๋Šฅ ์ด ์Šคํฌ๋ฆฝํŠธ๋Š” GitHub PR ๋ฆฌ๋ทฐ๋ฅผ ์œ„ํ•œ ์ฝ”๋“œ ๋ฆฌ๋ทฐ ์ž๋™ํ™” ํˆด์ž…๋‹ˆ๋‹ค. ์ฃผ์š” ๊ธฐ๋Šฅ์œผ๋กœ๋Š” PR์— ํฌํ•จ๋œ ํŒŒ์ผ์˜ ์ค‘์š”๋„๋ฅผ ํŒ๋‹จํ•˜๊ณ , ์ค‘์š” ํŒŒ์ผ์— ๋Œ€ํ•œ ์ฝ”๋“œ ๋ฆฌ๋ทฐ๋ฅผ ์ƒ์„ฑํ•˜์—ฌ PR ์ฝ”๋ฉ˜ํŠธ๋กœ ๊ฒŒ์‹œํ•˜๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค. ### ์ข‹์€ ์  1. PR ๋ฆฌ๋ทฐ ํ”„๋กœ์„ธ์Šค๋ฅผ ์ž๋™ํ™”ํ•˜์—ฌ ๋ฆฌ๋ทฐ์–ด์˜ ์—…๋ฌด๋Ÿ‰์„ ์ค„์—ฌ ์ค๋‹ˆ๋‹ค. 2. ์ค‘์š” ํŒŒ์ผ์„ ํŒ๋‹จํ•˜์—ฌ ๋ฆฌ๋ทฐ์˜ ํšจ์œจ์„ฑ์„ ๋†’์ž…๋‹ˆ๋‹ค. 3. GitHub API๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ PR ์ฝ”๋ฉ˜ํŠธ๋ฅผ ์ž๋™์œผ๋กœ ์ƒ์„ฑํ•˜์—ฌ ๋ฆฌ๋ทฐ ํ”„๋กœ์„ธ์Šค๋ฅผ ๊ฐ„์†Œํ™”ํ•ฉ๋‹ˆ๋‹ค. ### ๊ฐœ์„ ํ•  ์  1. ์ฝ”๋“œ์˜ ๊ฐ€๋…์„ฑ์„ ๋†’์ด๊ธฐ ์œ„ํ•ด ํ•จ์ˆ˜ ๋ถ„๋ฆฌ ๋ฐ ์ฃผ์„ ์ถ”๊ฐ€๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. 2. ์˜ค๋ฅ˜ ์ฒ˜๋ฆฌ๋ฅผ ๊ฐ•ํ™”ํ•˜์—ฌ ์˜ˆ์ƒ์น˜ ๋ชปํ•œ ์˜ค๋ฅ˜๋ฅผ ๋ฐฉ์ง€ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. 3. GITHUB\_TOKEN๊ณผ ๊ฐ™์€ ์ค‘์š”ํ•œ ํ™˜๊ฒฝ ๋ณ€์ˆ˜๋ฅผ ์•ˆ์ „ํ•˜๊ฒŒ ๊ด€๋ฆฌํ•  ์ˆ˜ ์žˆ์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. 4. ์ฝ”๋“œ ๋ฆฌ๋ทฐ์˜ ํ’ˆ์งˆ์„ ๋†’์ด๊ธฐ ์œ„ํ•ด ๋” ๋‹ค์–‘ํ•œ ์ฝ”๋“œ ๋ถ„์„ ๋„๊ตฌ๋ฅผ ํ†ตํ•ฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ### ์ œ์•ˆ ์‚ฌํ•ญ 1. ์ฝ”๋“œ์˜ ๊ฐ€๋…์„ฑ์„ ๋†’์ด๊ธฐ ์œ„ํ•ด ํ•จ์ˆ˜ ๋ถ„๋ฆฌ ๋ฐ ์ฃผ์„ ์ถ”๊ฐ€๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. * ์˜ˆ๋ฅผ ๋“ค์–ด, `get_pr_files` ํ•จ์ˆ˜๋Š” PR์— ํฌํ•จ๋œ ํŒŒ์ผ์˜ ๋ชฉ๋ก์„ ๊ฐ€์ ธ์˜ค๋Š” ํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค. ์ด ํ•จ์ˆ˜๋Š” PR์— ํฌํ•จ๋œ ํŒŒ์ผ์˜ ๋ชฉ๋ก์„ ๊ฐ€์ ธ์˜ค๋Š” ๋กœ์ง์„ ์บก์Аํ™”ํ•˜์—ฌ ์ฝ”๋“œ์˜ ๊ฐ€๋…์„ฑ์„ ๋†’์ž…๋‹ˆ๋‹ค. 2. ์˜ค๋ฅ˜ ์ฒ˜๋ฆฌ๋ฅผ ๊ฐ•ํ™”ํ•˜์—ฌ ์˜ˆ์ƒ์น˜ ๋ชปํ•œ ์˜ค๋ฅ˜๋ฅผ ๋ฐฉ์ง€ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * ์˜ˆ๋ฅผ ๋“ค์–ด, `fetch_pr_data` ํ•จ์ˆ˜๋Š” PR ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ ธ์˜ค๋Š” ํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค. ์ด ํ•จ์ˆ˜๋Š” PR ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ ธ์˜ค๋Š” ๋ฐ ์‹คํŒจํ•  ๊ฒฝ์šฐ ์˜ค๋ฅ˜๋ฅผ ๋ฐœ์ƒ์‹œํ‚ค๋Š” ๋Œ€์‹ , None์„ ๋ฐ˜ํ™˜ํ•˜์—ฌ ์˜ค๋ฅ˜๋ฅผ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. 3. GITHUB\_TOKEN๊ณผ ๊ฐ™์€ ์ค‘์š”ํ•œ ํ™˜๊ฒฝ ๋ณ€์ˆ˜๋ฅผ ์•ˆ์ „ํ•˜๊ฒŒ ๊ด€๋ฆฌํ•  ์ˆ˜ ์žˆ์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. * ์˜ˆ๋ฅผ ๋“ค์–ด, ํ™˜๊ฒฝ ๋ณ€์ˆ˜๋ฅผ ์•ˆ์ „ํ•˜๊ฒŒ ๊ด€๋ฆฌํ•˜๊ธฐ ์œ„ํ•ด Hashicorp์˜ Vault์™€ ๊ฐ™์€ ๋น„๋ฐ€ ๊ด€๋ฆฌ ํˆด์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. 4. ์ฝ”๋“œ ๋ฆฌ๋ทฐ์˜ ํ’ˆ์งˆ์„ ๋†’์ด๊ธฐ ์œ„ํ•ด ๋” ๋‹ค์–‘ํ•œ ์ฝ”๋“œ ๋ถ„์„ ๋„๊ตฌ๋ฅผ ํ†ตํ•ฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * ์˜ˆ๋ฅผ ๋“ค์–ด, SonarQube์™€ ๊ฐ™์€ ์ •์  ์ฝ”๋“œ ๋ถ„์„ ๋„๊ตฌ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ฝ”๋“œ์˜ ํ’ˆ์งˆ์„ ๋†’์ผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ## .github/scripts/ai_code_review.py ํŒŒ์ผ ๋ฆฌ๋ทฐ ### ์ฃผ์š” ๊ธฐ๋Šฅ ์ด ํŒŒ์ผ์€ GitHub PR ๋ฆฌ๋ทฐ๋ฅผ ์œ„ํ•œ ์ฝ”๋“œ ๋ฆฌ๋ทฐ ์ž๋™ํ™” ํˆด์˜ ์Šคํฌ๋ฆฝํŠธ์ž…๋‹ˆ๋‹ค. ์ฃผ์š” ๊ธฐ๋Šฅ์œผ๋กœ๋Š” PR์— ํฌํ•จ๋œ ํŒŒ์ผ์˜ ์ค‘์š”๋„๋ฅผ ํŒ๋‹จํ•˜๊ณ , ์ค‘์š” ํŒŒ์ผ์— ๋Œ€ํ•œ ์ฝ”๋“œ ๋ฆฌ๋ทฐ๋ฅผ ์ƒ์„ฑํ•˜์—ฌ PR ์ฝ”๋ฉ˜ํŠธ๋กœ ๊ฒŒ์‹œํ•˜๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค. ### ์ข‹์€ ์  1. PR ๋ฆฌ๋ทฐ ํ”„๋กœ์„ธ์Šค๋ฅผ ์ž๋™ํ™”ํ•˜์—ฌ ๋ฆฌ๋ทฐ์–ด์˜ ์—…๋ฌด๋Ÿ‰์„ ์ค„์—ฌ ์ค๋‹ˆ๋‹ค. 2. ์ค‘์š” ํŒŒ์ผ์„ ํŒ๋‹จํ•˜์—ฌ ๋ฆฌ๋ทฐ์˜ ํšจ์œจ์„ฑ์„ ๋†’์ž…๋‹ˆ๋‹ค. 3. GitHub API๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ PR ์ฝ”๋ฉ˜ํŠธ๋ฅผ ์ž๋™์œผ๋กœ ์ƒ์„ฑํ•˜์—ฌ ๋ฆฌ๋ทฐ ํ”„๋กœ์„ธ์Šค๋ฅผ ๊ฐ„์†Œํ™”ํ•ฉ๋‹ˆ๋‹ค. ### ๊ฐœ์„ ํ•  ์  1. ์ฝ”๋“œ์˜ ๊ฐ€๋…์„ฑ์„ ๋†’์ด๊ธฐ ์œ„ํ•ด ํ•จ์ˆ˜ ๋ถ„๋ฆฌ ๋ฐ ์ฃผ์„ ์ถ”๊ฐ€๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. 2. ์˜ค๋ฅ˜ ์ฒ˜๋ฆฌ๋ฅผ ๊ฐ•ํ™”ํ•˜์—ฌ ์˜ˆ์ƒ์น˜ ๋ชปํ•œ ์˜ค๋ฅ˜๋ฅผ ๋ฐฉ์ง€ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. 3. GITHUB\_TOKEN๊ณผ ๊ฐ™์€ ์ค‘์š”ํ•œ ํ™˜๊ฒฝ ๋ณ€์ˆ˜๋ฅผ ์•ˆ์ „ํ•˜๊ฒŒ ๊ด€๋ฆฌํ•  ์ˆ˜ ์žˆ์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. 4. ์ฝ”๋“œ ๋ฆฌ๋ทฐ์˜ ํ’ˆ์งˆ์„ ๋†’์ด๊ธฐ ์œ„ํ•ด ๋” ๋‹ค์–‘ํ•œ ์ฝ”๋“œ ๋ถ„์„ ๋„๊ตฌ๋ฅผ ํ†ตํ•ฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ### ์ œ์•ˆ ์‚ฌํ•ญ 1. ์ฝ”๋“œ์˜ ๊ฐ€๋…์„ฑ์„ ๋†’์ด๊ธฐ ์œ„ํ•ด ํ•จ์ˆ˜ ๋ถ„๋ฆฌ ๋ฐ ์ฃผ์„ ์ถ”๊ฐ€๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. * ์˜ˆ๋ฅผ ๋“ค์–ด, `get_pr_files` ํ•จ์ˆ˜๋Š” PR์— ํฌํ•จ๋œ ํŒŒ์ผ์˜ ๋ชฉ๋ก์„ ๊ฐ€์ ธ์˜ค๋Š” ํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค. ์ด ํ•จ์ˆ˜๋Š” PR์— ํฌํ•จ๋œ ํŒŒ์ผ์˜ ๋ชฉ๋ก์„ ๊ฐ€์ ธ์˜ค๋Š” ๋กœ์ง์„ ์บก์Аํ™”ํ•˜์—ฌ ์ฝ”๋“œ์˜ ๊ฐ€๋…์„ฑ์„ ๋†’์ž…๋‹ˆ๋‹ค. 2. ์˜ค๋ฅ˜ ์ฒ˜๋ฆฌ๋ฅผ ๊ฐ•ํ™”ํ•˜์—ฌ ์˜ˆ์ƒ์น˜ ๋ชปํ•œ ์˜ค๋ฅ˜๋ฅผ ๋ฐฉ์ง€ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * ์˜ˆ๋ฅผ ๋“ค์–ด, `fetch_pr_data` ํ•จ์ˆ˜๋Š” PR ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ ธ์˜ค๋Š” ํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค. ์ด ํ•จ์ˆ˜๋Š” PR ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ ธ์˜ค๋Š” ๋ฐ ์‹คํŒจํ•  ๊ฒฝ์šฐ ์˜ค๋ฅ˜๋ฅผ ๋ฐœ์ƒ์‹œํ‚ค๋Š” ๋Œ€์‹ , None์„ ๋ฐ˜ํ™˜ํ•˜์—ฌ ์˜ค๋ฅ˜๋ฅผ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. 3. GITHUB\_TOKEN๊ณผ ๊ฐ™์€ ์ค‘์š”ํ•œ ํ™˜๊ฒฝ ๋ณ€์ˆ˜๋ฅผ ์•ˆ์ „ํ•˜๊ฒŒ ๊ด€๋ฆฌํ•  ์ˆ˜ ์žˆ์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. * ์˜ˆ๋ฅผ ๋“ค์–ด, ํ™˜๊ฒฝ ๋ณ€์ˆ˜๋ฅผ ์•ˆ์ „ํ•˜๊ฒŒ ๊ด€๋ฆฌํ•˜๊ธฐ ์œ„ํ•ด Hashicorp์˜ Vault์™€ ๊ฐ™์€ ๋น„๋ฐ€ ๊ด€๋ฆฌ ํˆด์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. 4. ์ฝ”๋“œ ๋ฆฌ๋ทฐ์˜ ํ’ˆ์งˆ์„ ๋†’์ด๊ธฐ ์œ„ํ•ด ๋” ๋‹ค์–‘ํ•œ ์ฝ”๋“œ ๋ถ„์„ ๋„๊ตฌ
@@ -0,0 +1,27 @@ +# ๋ฆฌ๋ทฐ์—์„œ ์ œ์™ธํ•  ํŒŒ์ผ ๋ชฉ๋ก +IGNORED_FILES = [ + '.gitignore', + 'requirements.txt', + 'docker-compose.yml', + 'Dockerfile', + 'setup.cfg', + 'pyproject.toml', + '.env.example', + 'README.md', + 'LICENSE', +] + +# ๋ฆฌ๋ทฐ์—์„œ ์ œ์™ธํ•  ํŒŒ์ผ ํ™•์žฅ์ž +IGNORED_EXTENSIONS = [ + '.md', + '.txt', + '.log', + '.json', + '.yaml', '.yml', +] + +# ์ค‘์š” ํŒŒ์ผ ํŒ๋‹จ ๊ธฐ์ค€ +IMPORTANT_FILE_CHANGE_THRESHOLD = 100 + +# ํŒŒ์ผ๋‹น ์ตœ๋Œ€ ์ฝ”๋ฉ˜ํŠธ ์ˆ˜ +MAX_COMMENTS_PER_FILE = 3 \ No newline at end of file
Python
## .github/scripts/review_config.py ํŒŒ์ผ ๋ฆฌ๋ทฐ ### ์ฃผ์š” ๊ธฐ๋Šฅ ์ด ํŒŒ์ผ์€ GitHub ๋ฆฌ๋ทฐ์— ๋Œ€ํ•œ ์„ค์ •์„ ๊ด€๋ฆฌํ•˜๋Š” ๋ฐ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค. ์ฆ‰, ๋ฆฌ๋ทฐ์—์„œ ์ œ์™ธํ•  ํŒŒ์ผ ๋ชฉ๋ก, ํŒŒ์ผ ํ™•์žฅ์ž, ์ค‘์š” ํŒŒ์ผ ํŒ๋‹จ ๊ธฐ์ค€ ๋“ฑ์„ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค. ### ์ข‹์€ ์  * ํŒŒ์ผ์„ ๊ฐ€๋…์„ฑ ์žˆ๊ฒŒ ๊ตฌ์กฐํ™”ํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. * ๋ณ€์ˆ˜๋ช…์ด ๋ช…ํ™•ํ•˜๊ณ  ์ดํ•ดํ•˜๊ธฐ ์‰ฝ์Šต๋‹ˆ๋‹ค. * ์ฃผ์„์ด ์ ์ ˆํ•˜๊ฒŒ ์ž‘์„ฑ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค. ### ๊ฐœ์„ ํ•  ์  * IGNORED_FILES ๋ชฉ๋ก์ด ๋„ˆ๋ฌด ๊ธธ์–ด ์ฝ”๋“œ ๊ฐ€๋…์„ฑ์„ ํ•ด์นฉ๋‹ˆ๋‹ค. ์ด๋ฅผ ๊ฐœ์„ ํ•˜์—ฌ ๋” ๊ฐ€๋…์„ฑ ์žˆ๊ฒŒ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * IMPORTANT_FILE_CHANGE_THRESHOLD์™€ IMPORTANT_FILE_CHANGE_RATIO์˜ ์˜๋ฏธ๊ฐ€ ๋ช…ํ™•ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ์ฃผ์„์„ ์ถ”๊ฐ€ํ•˜์—ฌ ์˜๋ฏธ๋ฅผ ๋ช…ํ™•ํžˆ ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * ํŒŒ์ผ ํ™•์žฅ์ž ๋ชฉ๋ก์ด ๋„ˆ๋ฌด ๊ธธ์–ด ์ฝ”๋“œ ๊ฐ€๋…์„ฑ์„ ํ•ด์นฉ๋‹ˆ๋‹ค. ์ด๋ฅผ ๊ฐœ์„ ํ•˜์—ฌ ๋” ๊ฐ€๋…์„ฑ ์žˆ๊ฒŒ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ### ์ œ์•ˆ ์‚ฌํ•ญ 1. IGNORED_FILES ๋ชฉ๋ก์„ ๊ฐœ์„ ํ•˜์—ฌ ๋” ๊ฐ€๋…์„ฑ ์žˆ๊ฒŒ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ```python IGNORED_FILES = [ # ํ”„๋กœ์ ํŠธ ์„ค์ • ํŒŒ์ผ '.gitignore', 'requirements.txt', 'docker-compose.yml', 'Dockerfile', 'setup.cfg', 'pyproject.toml', # ํ™˜๊ฒฝ ๋ณ€์ˆ˜ ํŒŒ์ผ '.env.example', # ๋ฌธ์„œ ํŒŒ์ผ 'README.md', 'LICENSE', ] ``` 2. IMPORTANT_FILE_CHANGE_THRESHOLD์™€ IMPORTANT_FILE_CHANGE_RATIO์˜ ์˜๋ฏธ๋ฅผ ๋ช…ํ™•ํžˆ ํ•˜๊ธฐ ์œ„ํ•ด ์ฃผ์„์„ ์ถ”๊ฐ€ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ```python # ์ค‘์š” ํŒŒ์ผ ํŒ๋‹จ ๊ธฐ์ค€ (๋ณ€๊ฒฝ ๋ผ์ธ ์ˆ˜) IMPORTANT_FILE_CHANGE_THRESHOLD = 100 # ์ค‘์š” ํŒŒ์ผ ํŒ๋‹จ ๊ธฐ์ค€ (๋ณ€๊ฒฝ ๋ผ์ธ ๋น„์œจ) IMPORTANT_FILE_CHANGE_RATIO = 0.5 ``` 3. IGNORED_EXTENSIONS ๋ชฉ๋ก์„ ๊ฐœ์„ ํ•˜์—ฌ ๋” ๊ฐ€๋…์„ฑ ์žˆ๊ฒŒ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ```python IGNORED_EXTENSIONS = [ # ํ…์ŠคํŠธ ํŒŒ์ผ '.md', '.txt', '.log', # ๋ฐ์ดํ„ฐ ํŒŒ์ผ '.json', '.yaml', '.yml', ] ```
@@ -2,7 +2,7 @@ from dotenv import load_dotenv # load .env file -load_dotenv() +load_dotenv('app/backend/.env') from pydantic import ( PostgresDsn, @@ -73,6 +73,9 @@ class Settings(BaseSettings): # ALGORITHM : str # ACCESS_TOKEN_EXPIRE_MINUTES : int + # Groq API + GROQ_API_KEY: str + # ๊ธฐ๋ณธ ์ด๋ฏธ์ง€ URL # DEFAULT_IMAGE_URL : str
Python
## app/backend/src/main/core/config.py ํŒŒ์ผ ๋ฆฌ๋ทฐ ### ์ฃผ์š” ๊ธฐ๋Šฅ ์ด ํŒŒ์ผ์€ ํ”„๋กœ์ ํŠธ์˜ ์„ค์ •์„ ๊ด€๋ฆฌํ•˜๋Š” ์—ญํ• ์„ ํ•ฉ๋‹ˆ๋‹ค. ์„ค์ •์€ `.env` ํŒŒ์ผ์—์„œ ์ฝ์–ด๋“ค์—ฌ Pydantic์˜ `BaseSettings` ํด๋ž˜์Šค๋ฅผ ํ†ตํ•ด ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ๋ฅผ ์ˆ˜ํ–‰ํ•˜๊ณ , ์„ค์ •์„ ์ €์žฅํ•˜๋Š” ํด๋ž˜์Šค `Settings`๋ฅผ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค. ### ์ข‹์€ ์  * `.env` ํŒŒ์ผ์„ ์‚ฌ์šฉํ•˜์—ฌ ์„ค์ •์„ ๊ด€๋ฆฌํ•˜๋Š” ๋ฐฉ์‹์€ ์ผ๋ฐ˜์ ์ด๊ณ  ํŽธ๋ฆฌํ•ฉ๋‹ˆ๋‹ค. * Pydantic์˜ `BaseSettings` ํด๋ž˜์Šค๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์„ค์ •์˜ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ๋ฅผ ์ˆ˜ํ–‰ํ•˜๋Š” ๋ฐฉ์‹์€ ์•ˆ์ „ํ•˜๊ณ  ๊ฐ•๋ ฅํ•ฉ๋‹ˆ๋‹ค. * ์„ค์ •์„ ์ €์žฅํ•˜๋Š” ํด๋ž˜์Šค `Settings`์˜ ์†์„ฑ์€ ๋ช…ํ™•ํ•˜๊ณ  ์ผ๊ด€์ ์ž…๋‹ˆ๋‹ค. ### ๊ฐœ์„ ํ•  ์  * ์ผ๋ถ€ ์„ค์ • ํ•ญ๋ชฉ์˜ ์„ค๋ช…์ด ๋ˆ„๋ฝ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, `PROJECT_NAME`์˜ ์˜๋ฏธ๋Š” ๋ฌด์—‡์ธ์ง€ ๋ช…ํ™•ํ•˜๊ฒŒ ์„ค๋ช…๋˜์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. * ์ผ๋ถ€ ์„ค์ • ํ•ญ๋ชฉ์˜ ๋ฐ์ดํ„ฐ ํƒ€์ž…์ด ๋ช…ํ™•ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, `GROQ_API_KEY`์˜ ๋ฐ์ดํ„ฐ ํƒ€์ž…์€ ๋ฌด์—‡์ธ์ง€ ๋ช…ํ™•ํ•˜๊ฒŒ ์„ค๋ช…๋˜์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. * ์„ค์ • ํ•ญ๋ชฉ์˜ ์ˆœ์„œ๋Š” ์ž„์˜์ ์ž…๋‹ˆ๋‹ค. ์„ค์ • ํ•ญ๋ชฉ์„ ์นดํ…Œ๊ณ ๋ฆฌ๋ณ„๋กœ ์ •๋ ฌํ•˜์—ฌ ๊ด€๋ฆฌํ•˜๋Š” ๋ฐฉ์‹์ด ๋” ์ข‹์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * ์„ค์ • ํ•ญ๋ชฉ์˜ ์ด๋ฆ„์€ ์ผ๊ด€์ ์ด์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, `BACKEND_CORS_ORIGINS`์™€ `BACKEND_SESSION_SECRET_KEY`์˜ ์ด๋ฆ„์€ ์ผ๊ด€์ ์ด์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ### ์ œ์•ˆ ์‚ฌํ•ญ * ์„ค์ • ํ•ญ๋ชฉ์˜ ์„ค๋ช…์„ ์ถ”๊ฐ€ํ•˜์—ฌ ์˜๋ฏธ๋ฅผ ๋ช…ํ™•ํ•˜๊ฒŒ ์„ค๋ช…ํ•ฉ๋‹ˆ๋‹ค. * ์„ค์ • ํ•ญ๋ชฉ์˜ ๋ฐ์ดํ„ฐ ํƒ€์ž…์„ ๋ช…ํ™•ํ•˜๊ฒŒ ์„ค๋ช…ํ•ฉ๋‹ˆ๋‹ค. * ์„ค์ • ํ•ญ๋ชฉ์„ ์นดํ…Œ๊ณ ๋ฆฌ๋ณ„๋กœ ์ •๋ ฌํ•˜์—ฌ ๊ด€๋ฆฌํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์„ค์ •, API ์„ค์ •, ๋ณด์•ˆ ์„ค์ • ๋“ฑ์œผ๋กœ ์นดํ…Œ๊ณ ๋ฆฌ๋ฅผ ๋‚˜๋ˆŒ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * ์„ค์ • ํ•ญ๋ชฉ์˜ ์ด๋ฆ„์„ ์ผ๊ด€์ ์œผ๋กœ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, `BACKEND_` ์ ‘๋‘์‚ฌ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋ฐฑ์—”๋“œ ์„ค์ • ํ•ญ๋ชฉ์„ ๊ตฌ๋ถ„ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ```python # ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์„ค์ • class DatabaseSettings: POSTGRES_USER: str POSTGRES_PASSWORD: str POSTGRES_SERVER: str POSTGRES_PORT: int POSTGRES_DB: str @computed_field @property def SQLALCHEMY_DATABASE_URI(self) -> PostgresDsn: return MultiHostUrl.build( scheme="postgresql+asyncpg", username=self.POSTGRES_USER, password=self.POSTGRES_PASSWORD, host=self.POSTGRES_SERVER, port=self.POSTGRES_PORT, path=f"{self.POSTGRES_DB}", ) # API ์„ค์ • class APISettings: GROQ_API_KEY: str # ๋ณด์•ˆ ์„ค์ • class SecuritySettings: SECRET_KEY: str ALGORITHM: str ACCESS_TOKEN_EXPIRE_MINUTES: int # ์„ค์ •์„ ์ €์žฅํ•˜๋Š” ํด๋ž˜์Šค class Settings(BaseSettings): model_config = SettingsConfigDict( env_file=".env", env_ignore_empty=True, extra="ignore" ) database: DatabaseSettings api: APISettings security: SecuritySettings PROJECT_NAME: str settings = Settings() ``` ์ดใ‚ˆใ†ใซ ์„ค์ • ํ•ญ๋ชฉ์„ ์นดํ…Œ๊ณ ๋ฆฌ๋ณ„๋กœ ์ •๋ ฌํ•˜์—ฌ ๊ด€๋ฆฌํ•˜๋ฉด, ์„ค์ • ํ•ญ๋ชฉ์˜ ์˜๋ฏธ๋ฅผ ๋ช…ํ™•ํ•˜๊ฒŒ ์ดํ•ดํ•˜๊ณ  ๊ด€๋ฆฌํ•˜๊ธฐ ๋” ์‰ฝ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,101 @@ +REVIEW_PROMPT = """ +You have deep knowledge and expertise in Python, FastAPI for the back end, React and Next.js for the front. +Here is the new PR information. +- title: {title} +- description: {description} +- commit messages: {commit_messages} +- changed files: {changed_files} + +Please understand and review the purpose and context of the change considering PR information and commit message. +Please be sure to thoroughly analyze and review the following format and provide a comprehensive review. +If the author has written a post in accordance with the ๐Ÿ™ review requirements (optional) written in the PR description section, +please provide a solution to resolve the content first. +If not, please find one part of the entire code provided that needs the most improvement and provide a solution. +Please find the number one priority that needs improvement in the entire code you provided and write it strictly in the format below. +-------------------------------------------------------- +## ๐Ÿง‘๐Ÿปโ€๐Ÿ’ป ์ฃผ์š” ๊ธฐ๋Šฅ + +[Provide a brief description of the main features of this file, including its core functionality, expected input and output, and any specific exception cases it handles.] + +## ๐Ÿ” ๊ฐœ์„ ํ•  ์  + +[Write down any areas that need improvement, including performance bottlenecks, readability issues, and security vulnerabilities.] + +## ๐Ÿ“ข ์ œ์•ˆ๋œ ์†”๋ฃจ์…˜ + +1. ํ˜„์žฌ ์ฝ”๋“œ + +[problematic code fragment] + +2. ๊ถŒ์žฅ๋˜๋Š” ๋ณ€๊ฒฝ + +[updated code snippet] + +3. ๋ณ€๊ฒฝ ์ด์œ  + +[Brief reasons why the new approach is better, considering performance, readability, security, etc.] +-------------------------------------------------------- + +Full Code: {all_code} + +If you need to put in a code block, keep it brief, no more than 10 lines of code that needs improvement. +Please write one sentence within 70 characters, including the maximum space, that you need to explain. +If you write one sentence for readability, please write the next sentence in the next column instead of the next one. + +The person receiving this feedback is a Korean developer. +Please make sure to follow the above format strictly in Korean, but please provide specific and constructive feedback. +""" + +FILE_REVIEW_PROMPT = """ +๋‹ค์Œ {filename} ํŒŒ์ผ์˜ ์ฝ”๋“œ๋ฅผ ๋ฆฌ๋ทฐํ•˜๊ณ , ์•„๋ž˜ ํ˜•์‹์œผ๋กœ ์ƒ์„ธํ•œ ๋ฆฌ๋ทฐ๋ฅผ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”: + +## {filename} ํŒŒ์ผ ๋ฆฌ๋ทฐ + +### ์ฃผ์š” ๊ธฐ๋Šฅ +[ํŒŒ์ผ์˜ ์ฃผ์š” ๊ธฐ๋Šฅ ์„ค๋ช…] + +### ์ข‹์€ ์  +[์ข‹์€ ์  ๋‚˜์—ด] + +### ๊ฐœ์„ ํ•  ์  +[๊ฐœ์„ ์ด ํ•„์š”ํ•œ ์  ๋‚˜์—ด] + +### ์ œ์•ˆ ์‚ฌํ•ญ +[๊ตฌ์ฒด์ ์ธ ๊ฐœ์„  ์ œ์•ˆ, ์ฝ”๋“œ ์˜ˆ์‹œ ํฌํ•จ] + +ํŒŒ์ผ ๋‚ด์šฉ: +{content} +""" + +LINE_COMMENTS_PROMPT = """ +๋‹ค์Œ {filename} ํŒŒ์ผ์˜ ์ฝ”๋“œ๋ฅผ ๋ฆฌ๋ทฐํ•˜๊ณ , ์ค‘์š”ํ•œ ๋ผ์ธ์— ๋Œ€ํ•ด ๊ตฌ์ฒด์ ์ธ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”. +ํ˜•์‹์€ '๋ผ์ธ ๋ฒˆํ˜ธ: ์ฝ”๋ฉ˜ํŠธ'๋กœ ํ•ด์ฃผ์„ธ์š”. + +{content} +""" + +OVERALL_COMMENTS_PROMPT = """ +## AI ์ฝ”๋“œ ๋ฆฌ๋ทฐ ์š”์•ฝ + +{overall_review} +""" + +def get_review_prompt(all_code, pr_context, commit_messages, changed_files): + formatted_commit_messages = "\n".join([f"- {msg}" for msg in commit_messages]) + return REVIEW_PROMPT.format( + title=pr_context['title'], + description=pr_context['description'], + commit_messages=formatted_commit_messages, + changed_files=changed_files, + all_code=all_code + ) + +def get_file_review_prompt(filename, content): + return FILE_REVIEW_PROMPT.format(filename=filename, content=content) + +def get_line_comments_prompt(filename, content): + return LINE_COMMENTS_PROMPT.format(filename=filename, content=content) + +def get_total_comments_prompt(overall_review): + return OVERALL_COMMENTS_PROMPT.format(overall_review=overall_review) + \ No newline at end of file
Python
## scripts/review_prompt.py ํŒŒ์ผ ๋ฆฌ๋ทฐ ### ์ฃผ์š” ๊ธฐ๋Šฅ ์ด ํŒŒ์ผ์€ ์ฝ”๋“œ ๋ฆฌ๋ทฐ์— ๋Œ€ํ•œ ํ”„๋กฌํ”„ํŠธ๋ฅผ ์ œ๊ณตํ•˜๋Š” ํ•จ์ˆ˜๋“ค์„ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค. ํ”„๋กฌํ”„ํŠธ๋Š” ์ „์ฒด ์ฝ”๋“œ ๋ฆฌ๋ทฐ, ํŒŒ์ผ ๋ฆฌ๋ทฐ, ๋ผ์ธ๋ณ„ ์ฝ”๋ฉ˜ํŠธ, ์ „์ฒด ๋ฆฌ๋ทฐ ์š”์•ฝ์„ ์œ„ํ•œ ํ…œํ”Œ๋ฆฟ์„ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค. ### ์ข‹์€ ์  * ํ•จ์ˆ˜๋ช…์ด ๋ช…ํ™•ํ•˜๊ณ  ์ง๊ด€์ ์ž…๋‹ˆ๋‹ค. * ํ”„๋กฌํ”„ํŠธ ํ…œํ”Œ๋ฆฟ์ด ์ •๋ฆฌ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค. * ํ•จ์ˆ˜๊ฐ€ ๋…๋ฆฝ์ ์ด๋ฉฐ ์žฌ์‚ฌ์šฉ์ด ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค. ### ๊ฐœ์„ ํ•  ์  * ํ•จ์ˆ˜์— ๋Œ€ํ•œ ๋ฌธ์„œํ™”๊ฐ€ ๋ถ€์กฑํ•ฉ๋‹ˆ๋‹ค. ํ•จ์ˆ˜์˜ ์„ค๋ช…๊ณผ ํŒŒ๋ผ๋ฏธํ„ฐ์— ๋Œ€ํ•œ ์ •๋ณด๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. * ํ”„๋กฌํ”„ํŠธ ํ…œํ”Œ๋ฆฟ์— ๋Œ€ํ•œ ์„ค๋ช…์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, `{code}`, `{filename}`, `{content}` ๋“ฑ์— ๋Œ€ํ•œ ์„ค๋ช…์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. * ํ•จ์ˆ˜์˜ ๋ฐ˜ํ™˜๊ฐ’์ด ๋ช…ํ™•ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, `get_review_prompt` ํ•จ์ˆ˜๋Š” ๋ฌธ์ž์—ด์„ ๋ฐ˜ํ™˜ํ•˜์ง€๋งŒ, ํƒ€์ž…์ด ๋ช…ํ™•ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ### ์ œ์•ˆ ์‚ฌํ•ญ * ํ•จ์ˆ˜์— ๋Œ€ํ•œ ๋ฌธ์„œํ™”๋ฅผ ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, ํ•จ์ˆ˜์˜ ์„ค๋ช…๊ณผ ํŒŒ๋ผ๋ฏธํ„ฐ์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค. * ํ”„๋กฌํ”„ํŠธ ํ…œํ”Œ๋ฆฟ์— ๋Œ€ํ•œ ์„ค๋ช…์„ ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, `{code}`, `{filename}`, `{content}` ๋“ฑ์— ๋Œ€ํ•œ ์„ค๋ช…์„ ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค. * ํ•จ์ˆ˜์˜ ๋ฐ˜ํ™˜๊ฐ’์„ ๋ช…ํ™•ํ•˜๊ฒŒ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, `get_review_prompt` ํ•จ์ˆ˜์˜ ๋ฐ˜ํ™˜๊ฐ’์„ `str` ํƒ€์ž…์œผ๋กœ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค. ```python def get_review_prompt(code: str) -> str: """ ์ „์ฒด ์ฝ”๋“œ ๋ฆฌ๋ทฐ ํ”„๋กฌํ”„ํŠธ๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. :param code: ์ฝ”๋“œ ๋‚ด์šฉ :return: ์ „์ฒด ์ฝ”๋“œ ๋ฆฌ๋ทฐ ํ”„๋กฌํ”„ํŠธ """ return REVIEW_PROMPT.format(code=code) def get_file_review_prompt(filename: str, content: str) -> str: """ ํŒŒ์ผ ๋ฆฌ๋ทฐ ํ”„๋กฌํ”„ํŠธ๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. :param filename: ํŒŒ์ผ ์ด๋ฆ„ :param content: ํŒŒ์ผ ๋‚ด์šฉ :return: ํŒŒ์ผ ๋ฆฌ๋ทฐ ํ”„๋กฌํ”„ํŠธ """ return FILE_REVIEW_PROMPT.format(filename=filename, content=content) def get_line_comments_prompt(filename: str, content: str) -> str: """ ๋ผ์ธ๋ณ„ ์ฝ”๋ฉ˜ํŠธ ํ”„๋กฌํ”„ํŠธ๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. :param filename: ํŒŒ์ผ ์ด๋ฆ„ :param content: ํŒŒ์ผ ๋‚ด์šฉ :return: ๋ผ์ธ๋ณ„ ์ฝ”๋ฉ˜ํŠธ ํ”„๋กฌํ”„ํŠธ """ return LINE_COMMENTS_PROMPT.format(filename=filename, content=content) def get_total_comments_prompt(overall_review: str) -> str: """ ์ „์ฒด ๋ฆฌ๋ทฐ ์š”์•ฝ ํ”„๋กฌํ”„ํŠธ๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. :param overall_review: ์ „์ฒด ๋ฆฌ๋ทฐ ๋‚ด์šฉ :return: ์ „์ฒด ๋ฆฌ๋ทฐ ์š”์•ฝ ํ”„๋กฌํ”„ํŠธ """ return OVERALL_COMMENTS_PROMPT.format(overall_review=overall_review) ```
@@ -0,0 +1,101 @@ +REVIEW_PROMPT = """ +You have deep knowledge and expertise in Python, FastAPI for the back end, React and Next.js for the front. +Here is the new PR information. +- title: {title} +- description: {description} +- commit messages: {commit_messages} +- changed files: {changed_files} + +Please understand and review the purpose and context of the change considering PR information and commit message. +Please be sure to thoroughly analyze and review the following format and provide a comprehensive review. +If the author has written a post in accordance with the ๐Ÿ™ review requirements (optional) written in the PR description section, +please provide a solution to resolve the content first. +If not, please find one part of the entire code provided that needs the most improvement and provide a solution. +Please find the number one priority that needs improvement in the entire code you provided and write it strictly in the format below. +-------------------------------------------------------- +## ๐Ÿง‘๐Ÿปโ€๐Ÿ’ป ์ฃผ์š” ๊ธฐ๋Šฅ + +[Provide a brief description of the main features of this file, including its core functionality, expected input and output, and any specific exception cases it handles.] + +## ๐Ÿ” ๊ฐœ์„ ํ•  ์  + +[Write down any areas that need improvement, including performance bottlenecks, readability issues, and security vulnerabilities.] + +## ๐Ÿ“ข ์ œ์•ˆ๋œ ์†”๋ฃจ์…˜ + +1. ํ˜„์žฌ ์ฝ”๋“œ + +[problematic code fragment] + +2. ๊ถŒ์žฅ๋˜๋Š” ๋ณ€๊ฒฝ + +[updated code snippet] + +3. ๋ณ€๊ฒฝ ์ด์œ  + +[Brief reasons why the new approach is better, considering performance, readability, security, etc.] +-------------------------------------------------------- + +Full Code: {all_code} + +If you need to put in a code block, keep it brief, no more than 10 lines of code that needs improvement. +Please write one sentence within 70 characters, including the maximum space, that you need to explain. +If you write one sentence for readability, please write the next sentence in the next column instead of the next one. + +The person receiving this feedback is a Korean developer. +Please make sure to follow the above format strictly in Korean, but please provide specific and constructive feedback. +""" + +FILE_REVIEW_PROMPT = """ +๋‹ค์Œ {filename} ํŒŒ์ผ์˜ ์ฝ”๋“œ๋ฅผ ๋ฆฌ๋ทฐํ•˜๊ณ , ์•„๋ž˜ ํ˜•์‹์œผ๋กœ ์ƒ์„ธํ•œ ๋ฆฌ๋ทฐ๋ฅผ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”: + +## {filename} ํŒŒ์ผ ๋ฆฌ๋ทฐ + +### ์ฃผ์š” ๊ธฐ๋Šฅ +[ํŒŒ์ผ์˜ ์ฃผ์š” ๊ธฐ๋Šฅ ์„ค๋ช…] + +### ์ข‹์€ ์  +[์ข‹์€ ์  ๋‚˜์—ด] + +### ๊ฐœ์„ ํ•  ์  +[๊ฐœ์„ ์ด ํ•„์š”ํ•œ ์  ๋‚˜์—ด] + +### ์ œ์•ˆ ์‚ฌํ•ญ +[๊ตฌ์ฒด์ ์ธ ๊ฐœ์„  ์ œ์•ˆ, ์ฝ”๋“œ ์˜ˆ์‹œ ํฌํ•จ] + +ํŒŒ์ผ ๋‚ด์šฉ: +{content} +""" + +LINE_COMMENTS_PROMPT = """ +๋‹ค์Œ {filename} ํŒŒ์ผ์˜ ์ฝ”๋“œ๋ฅผ ๋ฆฌ๋ทฐํ•˜๊ณ , ์ค‘์š”ํ•œ ๋ผ์ธ์— ๋Œ€ํ•ด ๊ตฌ์ฒด์ ์ธ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”. +ํ˜•์‹์€ '๋ผ์ธ ๋ฒˆํ˜ธ: ์ฝ”๋ฉ˜ํŠธ'๋กœ ํ•ด์ฃผ์„ธ์š”. + +{content} +""" + +OVERALL_COMMENTS_PROMPT = """ +## AI ์ฝ”๋“œ ๋ฆฌ๋ทฐ ์š”์•ฝ + +{overall_review} +""" + +def get_review_prompt(all_code, pr_context, commit_messages, changed_files): + formatted_commit_messages = "\n".join([f"- {msg}" for msg in commit_messages]) + return REVIEW_PROMPT.format( + title=pr_context['title'], + description=pr_context['description'], + commit_messages=formatted_commit_messages, + changed_files=changed_files, + all_code=all_code + ) + +def get_file_review_prompt(filename, content): + return FILE_REVIEW_PROMPT.format(filename=filename, content=content) + +def get_line_comments_prompt(filename, content): + return LINE_COMMENTS_PROMPT.format(filename=filename, content=content) + +def get_total_comments_prompt(overall_review): + return OVERALL_COMMENTS_PROMPT.format(overall_review=overall_review) + \ No newline at end of file
Python
REVIEW_PROMPT ๋ณ€์ˆ˜์˜ ์ด๋ฆ„์ด ๋„ˆ๋ฌด ๊ธธ์Šต๋‹ˆ๋‹ค. REVIEW_TEMPLATE๋กœ ๋ฐ”๊ฟ€ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,101 @@ +REVIEW_PROMPT = """ +You have deep knowledge and expertise in Python, FastAPI for the back end, React and Next.js for the front. +Here is the new PR information. +- title: {title} +- description: {description} +- commit messages: {commit_messages} +- changed files: {changed_files} + +Please understand and review the purpose and context of the change considering PR information and commit message. +Please be sure to thoroughly analyze and review the following format and provide a comprehensive review. +If the author has written a post in accordance with the ๐Ÿ™ review requirements (optional) written in the PR description section, +please provide a solution to resolve the content first. +If not, please find one part of the entire code provided that needs the most improvement and provide a solution. +Please find the number one priority that needs improvement in the entire code you provided and write it strictly in the format below. +-------------------------------------------------------- +## ๐Ÿง‘๐Ÿปโ€๐Ÿ’ป ์ฃผ์š” ๊ธฐ๋Šฅ + +[Provide a brief description of the main features of this file, including its core functionality, expected input and output, and any specific exception cases it handles.] + +## ๐Ÿ” ๊ฐœ์„ ํ•  ์  + +[Write down any areas that need improvement, including performance bottlenecks, readability issues, and security vulnerabilities.] + +## ๐Ÿ“ข ์ œ์•ˆ๋œ ์†”๋ฃจ์…˜ + +1. ํ˜„์žฌ ์ฝ”๋“œ + +[problematic code fragment] + +2. ๊ถŒ์žฅ๋˜๋Š” ๋ณ€๊ฒฝ + +[updated code snippet] + +3. ๋ณ€๊ฒฝ ์ด์œ  + +[Brief reasons why the new approach is better, considering performance, readability, security, etc.] +-------------------------------------------------------- + +Full Code: {all_code} + +If you need to put in a code block, keep it brief, no more than 10 lines of code that needs improvement. +Please write one sentence within 70 characters, including the maximum space, that you need to explain. +If you write one sentence for readability, please write the next sentence in the next column instead of the next one. + +The person receiving this feedback is a Korean developer. +Please make sure to follow the above format strictly in Korean, but please provide specific and constructive feedback. +""" + +FILE_REVIEW_PROMPT = """ +๋‹ค์Œ {filename} ํŒŒ์ผ์˜ ์ฝ”๋“œ๋ฅผ ๋ฆฌ๋ทฐํ•˜๊ณ , ์•„๋ž˜ ํ˜•์‹์œผ๋กœ ์ƒ์„ธํ•œ ๋ฆฌ๋ทฐ๋ฅผ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”: + +## {filename} ํŒŒ์ผ ๋ฆฌ๋ทฐ + +### ์ฃผ์š” ๊ธฐ๋Šฅ +[ํŒŒ์ผ์˜ ์ฃผ์š” ๊ธฐ๋Šฅ ์„ค๋ช…] + +### ์ข‹์€ ์  +[์ข‹์€ ์  ๋‚˜์—ด] + +### ๊ฐœ์„ ํ•  ์  +[๊ฐœ์„ ์ด ํ•„์š”ํ•œ ์  ๋‚˜์—ด] + +### ์ œ์•ˆ ์‚ฌํ•ญ +[๊ตฌ์ฒด์ ์ธ ๊ฐœ์„  ์ œ์•ˆ, ์ฝ”๋“œ ์˜ˆ์‹œ ํฌํ•จ] + +ํŒŒ์ผ ๋‚ด์šฉ: +{content} +""" + +LINE_COMMENTS_PROMPT = """ +๋‹ค์Œ {filename} ํŒŒ์ผ์˜ ์ฝ”๋“œ๋ฅผ ๋ฆฌ๋ทฐํ•˜๊ณ , ์ค‘์š”ํ•œ ๋ผ์ธ์— ๋Œ€ํ•ด ๊ตฌ์ฒด์ ์ธ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”. +ํ˜•์‹์€ '๋ผ์ธ ๋ฒˆํ˜ธ: ์ฝ”๋ฉ˜ํŠธ'๋กœ ํ•ด์ฃผ์„ธ์š”. + +{content} +""" + +OVERALL_COMMENTS_PROMPT = """ +## AI ์ฝ”๋“œ ๋ฆฌ๋ทฐ ์š”์•ฝ + +{overall_review} +""" + +def get_review_prompt(all_code, pr_context, commit_messages, changed_files): + formatted_commit_messages = "\n".join([f"- {msg}" for msg in commit_messages]) + return REVIEW_PROMPT.format( + title=pr_context['title'], + description=pr_context['description'], + commit_messages=formatted_commit_messages, + changed_files=changed_files, + all_code=all_code + ) + +def get_file_review_prompt(filename, content): + return FILE_REVIEW_PROMPT.format(filename=filename, content=content) + +def get_line_comments_prompt(filename, content): + return LINE_COMMENTS_PROMPT.format(filename=filename, content=content) + +def get_total_comments_prompt(overall_review): + return OVERALL_COMMENTS_PROMPT.format(overall_review=overall_review) + \ No newline at end of file
Python
FILE_REVIEW_PROMPT ๋ณ€์ˆ˜์˜ ์ด๋ฆ„์ด ๋„ˆ๋ฌด ๊ธธ์Šต๋‹ˆ๋‹ค. FILE_TEMPLATE๋กœ ๋ฐ”๊ฟ€ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,101 @@ +REVIEW_PROMPT = """ +You have deep knowledge and expertise in Python, FastAPI for the back end, React and Next.js for the front. +Here is the new PR information. +- title: {title} +- description: {description} +- commit messages: {commit_messages} +- changed files: {changed_files} + +Please understand and review the purpose and context of the change considering PR information and commit message. +Please be sure to thoroughly analyze and review the following format and provide a comprehensive review. +If the author has written a post in accordance with the ๐Ÿ™ review requirements (optional) written in the PR description section, +please provide a solution to resolve the content first. +If not, please find one part of the entire code provided that needs the most improvement and provide a solution. +Please find the number one priority that needs improvement in the entire code you provided and write it strictly in the format below. +-------------------------------------------------------- +## ๐Ÿง‘๐Ÿปโ€๐Ÿ’ป ์ฃผ์š” ๊ธฐ๋Šฅ + +[Provide a brief description of the main features of this file, including its core functionality, expected input and output, and any specific exception cases it handles.] + +## ๐Ÿ” ๊ฐœ์„ ํ•  ์  + +[Write down any areas that need improvement, including performance bottlenecks, readability issues, and security vulnerabilities.] + +## ๐Ÿ“ข ์ œ์•ˆ๋œ ์†”๋ฃจ์…˜ + +1. ํ˜„์žฌ ์ฝ”๋“œ + +[problematic code fragment] + +2. ๊ถŒ์žฅ๋˜๋Š” ๋ณ€๊ฒฝ + +[updated code snippet] + +3. ๋ณ€๊ฒฝ ์ด์œ  + +[Brief reasons why the new approach is better, considering performance, readability, security, etc.] +-------------------------------------------------------- + +Full Code: {all_code} + +If you need to put in a code block, keep it brief, no more than 10 lines of code that needs improvement. +Please write one sentence within 70 characters, including the maximum space, that you need to explain. +If you write one sentence for readability, please write the next sentence in the next column instead of the next one. + +The person receiving this feedback is a Korean developer. +Please make sure to follow the above format strictly in Korean, but please provide specific and constructive feedback. +""" + +FILE_REVIEW_PROMPT = """ +๋‹ค์Œ {filename} ํŒŒ์ผ์˜ ์ฝ”๋“œ๋ฅผ ๋ฆฌ๋ทฐํ•˜๊ณ , ์•„๋ž˜ ํ˜•์‹์œผ๋กœ ์ƒ์„ธํ•œ ๋ฆฌ๋ทฐ๋ฅผ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”: + +## {filename} ํŒŒ์ผ ๋ฆฌ๋ทฐ + +### ์ฃผ์š” ๊ธฐ๋Šฅ +[ํŒŒ์ผ์˜ ์ฃผ์š” ๊ธฐ๋Šฅ ์„ค๋ช…] + +### ์ข‹์€ ์  +[์ข‹์€ ์  ๋‚˜์—ด] + +### ๊ฐœ์„ ํ•  ์  +[๊ฐœ์„ ์ด ํ•„์š”ํ•œ ์  ๋‚˜์—ด] + +### ์ œ์•ˆ ์‚ฌํ•ญ +[๊ตฌ์ฒด์ ์ธ ๊ฐœ์„  ์ œ์•ˆ, ์ฝ”๋“œ ์˜ˆ์‹œ ํฌํ•จ] + +ํŒŒ์ผ ๋‚ด์šฉ: +{content} +""" + +LINE_COMMENTS_PROMPT = """ +๋‹ค์Œ {filename} ํŒŒ์ผ์˜ ์ฝ”๋“œ๋ฅผ ๋ฆฌ๋ทฐํ•˜๊ณ , ์ค‘์š”ํ•œ ๋ผ์ธ์— ๋Œ€ํ•ด ๊ตฌ์ฒด์ ์ธ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”. +ํ˜•์‹์€ '๋ผ์ธ ๋ฒˆํ˜ธ: ์ฝ”๋ฉ˜ํŠธ'๋กœ ํ•ด์ฃผ์„ธ์š”. + +{content} +""" + +OVERALL_COMMENTS_PROMPT = """ +## AI ์ฝ”๋“œ ๋ฆฌ๋ทฐ ์š”์•ฝ + +{overall_review} +""" + +def get_review_prompt(all_code, pr_context, commit_messages, changed_files): + formatted_commit_messages = "\n".join([f"- {msg}" for msg in commit_messages]) + return REVIEW_PROMPT.format( + title=pr_context['title'], + description=pr_context['description'], + commit_messages=formatted_commit_messages, + changed_files=changed_files, + all_code=all_code + ) + +def get_file_review_prompt(filename, content): + return FILE_REVIEW_PROMPT.format(filename=filename, content=content) + +def get_line_comments_prompt(filename, content): + return LINE_COMMENTS_PROMPT.format(filename=filename, content=content) + +def get_total_comments_prompt(overall_review): + return OVERALL_COMMENTS_PROMPT.format(overall_review=overall_review) + \ No newline at end of file
Python
LINE_COMMENTS_PROMPT ๋ณ€์ˆ˜์˜ ์ด๋ฆ„์ด ๋„ˆ๋ฌด ๊ธธ์Šต๋‹ˆ๋‹ค. LINE_TEMPLATE๋กœ ๋ฐ”๊ฟ€ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,101 @@ +REVIEW_PROMPT = """ +You have deep knowledge and expertise in Python, FastAPI for the back end, React and Next.js for the front. +Here is the new PR information. +- title: {title} +- description: {description} +- commit messages: {commit_messages} +- changed files: {changed_files} + +Please understand and review the purpose and context of the change considering PR information and commit message. +Please be sure to thoroughly analyze and review the following format and provide a comprehensive review. +If the author has written a post in accordance with the ๐Ÿ™ review requirements (optional) written in the PR description section, +please provide a solution to resolve the content first. +If not, please find one part of the entire code provided that needs the most improvement and provide a solution. +Please find the number one priority that needs improvement in the entire code you provided and write it strictly in the format below. +-------------------------------------------------------- +## ๐Ÿง‘๐Ÿปโ€๐Ÿ’ป ์ฃผ์š” ๊ธฐ๋Šฅ + +[Provide a brief description of the main features of this file, including its core functionality, expected input and output, and any specific exception cases it handles.] + +## ๐Ÿ” ๊ฐœ์„ ํ•  ์  + +[Write down any areas that need improvement, including performance bottlenecks, readability issues, and security vulnerabilities.] + +## ๐Ÿ“ข ์ œ์•ˆ๋œ ์†”๋ฃจ์…˜ + +1. ํ˜„์žฌ ์ฝ”๋“œ + +[problematic code fragment] + +2. ๊ถŒ์žฅ๋˜๋Š” ๋ณ€๊ฒฝ + +[updated code snippet] + +3. ๋ณ€๊ฒฝ ์ด์œ  + +[Brief reasons why the new approach is better, considering performance, readability, security, etc.] +-------------------------------------------------------- + +Full Code: {all_code} + +If you need to put in a code block, keep it brief, no more than 10 lines of code that needs improvement. +Please write one sentence within 70 characters, including the maximum space, that you need to explain. +If you write one sentence for readability, please write the next sentence in the next column instead of the next one. + +The person receiving this feedback is a Korean developer. +Please make sure to follow the above format strictly in Korean, but please provide specific and constructive feedback. +""" + +FILE_REVIEW_PROMPT = """ +๋‹ค์Œ {filename} ํŒŒ์ผ์˜ ์ฝ”๋“œ๋ฅผ ๋ฆฌ๋ทฐํ•˜๊ณ , ์•„๋ž˜ ํ˜•์‹์œผ๋กœ ์ƒ์„ธํ•œ ๋ฆฌ๋ทฐ๋ฅผ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”: + +## {filename} ํŒŒ์ผ ๋ฆฌ๋ทฐ + +### ์ฃผ์š” ๊ธฐ๋Šฅ +[ํŒŒ์ผ์˜ ์ฃผ์š” ๊ธฐ๋Šฅ ์„ค๋ช…] + +### ์ข‹์€ ์  +[์ข‹์€ ์  ๋‚˜์—ด] + +### ๊ฐœ์„ ํ•  ์  +[๊ฐœ์„ ์ด ํ•„์š”ํ•œ ์  ๋‚˜์—ด] + +### ์ œ์•ˆ ์‚ฌํ•ญ +[๊ตฌ์ฒด์ ์ธ ๊ฐœ์„  ์ œ์•ˆ, ์ฝ”๋“œ ์˜ˆ์‹œ ํฌํ•จ] + +ํŒŒ์ผ ๋‚ด์šฉ: +{content} +""" + +LINE_COMMENTS_PROMPT = """ +๋‹ค์Œ {filename} ํŒŒ์ผ์˜ ์ฝ”๋“œ๋ฅผ ๋ฆฌ๋ทฐํ•˜๊ณ , ์ค‘์š”ํ•œ ๋ผ์ธ์— ๋Œ€ํ•ด ๊ตฌ์ฒด์ ์ธ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”. +ํ˜•์‹์€ '๋ผ์ธ ๋ฒˆํ˜ธ: ์ฝ”๋ฉ˜ํŠธ'๋กœ ํ•ด์ฃผ์„ธ์š”. + +{content} +""" + +OVERALL_COMMENTS_PROMPT = """ +## AI ์ฝ”๋“œ ๋ฆฌ๋ทฐ ์š”์•ฝ + +{overall_review} +""" + +def get_review_prompt(all_code, pr_context, commit_messages, changed_files): + formatted_commit_messages = "\n".join([f"- {msg}" for msg in commit_messages]) + return REVIEW_PROMPT.format( + title=pr_context['title'], + description=pr_context['description'], + commit_messages=formatted_commit_messages, + changed_files=changed_files, + all_code=all_code + ) + +def get_file_review_prompt(filename, content): + return FILE_REVIEW_PROMPT.format(filename=filename, content=content) + +def get_line_comments_prompt(filename, content): + return LINE_COMMENTS_PROMPT.format(filename=filename, content=content) + +def get_total_comments_prompt(overall_review): + return OVERALL_COMMENTS_PROMPT.format(overall_review=overall_review) + \ No newline at end of file
Python
get_review_prompt ํ•จ์ˆ˜์˜ ์ด๋ฆ„์ด ๋„ˆ๋ฌด ์ผ๋ฐ˜์ ์ž…๋‹ˆ๋‹ค. get_review_template์œผ๋กœ ๋ฐ”๊ฟ€ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,101 @@ +REVIEW_PROMPT = """ +You have deep knowledge and expertise in Python, FastAPI for the back end, React and Next.js for the front. +Here is the new PR information. +- title: {title} +- description: {description} +- commit messages: {commit_messages} +- changed files: {changed_files} + +Please understand and review the purpose and context of the change considering PR information and commit message. +Please be sure to thoroughly analyze and review the following format and provide a comprehensive review. +If the author has written a post in accordance with the ๐Ÿ™ review requirements (optional) written in the PR description section, +please provide a solution to resolve the content first. +If not, please find one part of the entire code provided that needs the most improvement and provide a solution. +Please find the number one priority that needs improvement in the entire code you provided and write it strictly in the format below. +-------------------------------------------------------- +## ๐Ÿง‘๐Ÿปโ€๐Ÿ’ป ์ฃผ์š” ๊ธฐ๋Šฅ + +[Provide a brief description of the main features of this file, including its core functionality, expected input and output, and any specific exception cases it handles.] + +## ๐Ÿ” ๊ฐœ์„ ํ•  ์  + +[Write down any areas that need improvement, including performance bottlenecks, readability issues, and security vulnerabilities.] + +## ๐Ÿ“ข ์ œ์•ˆ๋œ ์†”๋ฃจ์…˜ + +1. ํ˜„์žฌ ์ฝ”๋“œ + +[problematic code fragment] + +2. ๊ถŒ์žฅ๋˜๋Š” ๋ณ€๊ฒฝ + +[updated code snippet] + +3. ๋ณ€๊ฒฝ ์ด์œ  + +[Brief reasons why the new approach is better, considering performance, readability, security, etc.] +-------------------------------------------------------- + +Full Code: {all_code} + +If you need to put in a code block, keep it brief, no more than 10 lines of code that needs improvement. +Please write one sentence within 70 characters, including the maximum space, that you need to explain. +If you write one sentence for readability, please write the next sentence in the next column instead of the next one. + +The person receiving this feedback is a Korean developer. +Please make sure to follow the above format strictly in Korean, but please provide specific and constructive feedback. +""" + +FILE_REVIEW_PROMPT = """ +๋‹ค์Œ {filename} ํŒŒ์ผ์˜ ์ฝ”๋“œ๋ฅผ ๋ฆฌ๋ทฐํ•˜๊ณ , ์•„๋ž˜ ํ˜•์‹์œผ๋กœ ์ƒ์„ธํ•œ ๋ฆฌ๋ทฐ๋ฅผ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”: + +## {filename} ํŒŒ์ผ ๋ฆฌ๋ทฐ + +### ์ฃผ์š” ๊ธฐ๋Šฅ +[ํŒŒ์ผ์˜ ์ฃผ์š” ๊ธฐ๋Šฅ ์„ค๋ช…] + +### ์ข‹์€ ์  +[์ข‹์€ ์  ๋‚˜์—ด] + +### ๊ฐœ์„ ํ•  ์  +[๊ฐœ์„ ์ด ํ•„์š”ํ•œ ์  ๋‚˜์—ด] + +### ์ œ์•ˆ ์‚ฌํ•ญ +[๊ตฌ์ฒด์ ์ธ ๊ฐœ์„  ์ œ์•ˆ, ์ฝ”๋“œ ์˜ˆ์‹œ ํฌํ•จ] + +ํŒŒ์ผ ๋‚ด์šฉ: +{content} +""" + +LINE_COMMENTS_PROMPT = """ +๋‹ค์Œ {filename} ํŒŒ์ผ์˜ ์ฝ”๋“œ๋ฅผ ๋ฆฌ๋ทฐํ•˜๊ณ , ์ค‘์š”ํ•œ ๋ผ์ธ์— ๋Œ€ํ•ด ๊ตฌ์ฒด์ ์ธ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”. +ํ˜•์‹์€ '๋ผ์ธ ๋ฒˆํ˜ธ: ์ฝ”๋ฉ˜ํŠธ'๋กœ ํ•ด์ฃผ์„ธ์š”. + +{content} +""" + +OVERALL_COMMENTS_PROMPT = """ +## AI ์ฝ”๋“œ ๋ฆฌ๋ทฐ ์š”์•ฝ + +{overall_review} +""" + +def get_review_prompt(all_code, pr_context, commit_messages, changed_files): + formatted_commit_messages = "\n".join([f"- {msg}" for msg in commit_messages]) + return REVIEW_PROMPT.format( + title=pr_context['title'], + description=pr_context['description'], + commit_messages=formatted_commit_messages, + changed_files=changed_files, + all_code=all_code + ) + +def get_file_review_prompt(filename, content): + return FILE_REVIEW_PROMPT.format(filename=filename, content=content) + +def get_line_comments_prompt(filename, content): + return LINE_COMMENTS_PROMPT.format(filename=filename, content=content) + +def get_total_comments_prompt(overall_review): + return OVERALL_COMMENTS_PROMPT.format(overall_review=overall_review) + \ No newline at end of file
Python
get_file_review_prompt ํ•จ์ˆ˜์˜ ์ด๋ฆ„์ด ๋„ˆ๋ฌด ์ผ๋ฐ˜์ ์ž…๋‹ˆ๋‹ค. get_file_template์œผ๋กœ ๋ฐ”๊ฟ€ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,101 @@ +REVIEW_PROMPT = """ +You have deep knowledge and expertise in Python, FastAPI for the back end, React and Next.js for the front. +Here is the new PR information. +- title: {title} +- description: {description} +- commit messages: {commit_messages} +- changed files: {changed_files} + +Please understand and review the purpose and context of the change considering PR information and commit message. +Please be sure to thoroughly analyze and review the following format and provide a comprehensive review. +If the author has written a post in accordance with the ๐Ÿ™ review requirements (optional) written in the PR description section, +please provide a solution to resolve the content first. +If not, please find one part of the entire code provided that needs the most improvement and provide a solution. +Please find the number one priority that needs improvement in the entire code you provided and write it strictly in the format below. +-------------------------------------------------------- +## ๐Ÿง‘๐Ÿปโ€๐Ÿ’ป ์ฃผ์š” ๊ธฐ๋Šฅ + +[Provide a brief description of the main features of this file, including its core functionality, expected input and output, and any specific exception cases it handles.] + +## ๐Ÿ” ๊ฐœ์„ ํ•  ์  + +[Write down any areas that need improvement, including performance bottlenecks, readability issues, and security vulnerabilities.] + +## ๐Ÿ“ข ์ œ์•ˆ๋œ ์†”๋ฃจ์…˜ + +1. ํ˜„์žฌ ์ฝ”๋“œ + +[problematic code fragment] + +2. ๊ถŒ์žฅ๋˜๋Š” ๋ณ€๊ฒฝ + +[updated code snippet] + +3. ๋ณ€๊ฒฝ ์ด์œ  + +[Brief reasons why the new approach is better, considering performance, readability, security, etc.] +-------------------------------------------------------- + +Full Code: {all_code} + +If you need to put in a code block, keep it brief, no more than 10 lines of code that needs improvement. +Please write one sentence within 70 characters, including the maximum space, that you need to explain. +If you write one sentence for readability, please write the next sentence in the next column instead of the next one. + +The person receiving this feedback is a Korean developer. +Please make sure to follow the above format strictly in Korean, but please provide specific and constructive feedback. +""" + +FILE_REVIEW_PROMPT = """ +๋‹ค์Œ {filename} ํŒŒ์ผ์˜ ์ฝ”๋“œ๋ฅผ ๋ฆฌ๋ทฐํ•˜๊ณ , ์•„๋ž˜ ํ˜•์‹์œผ๋กœ ์ƒ์„ธํ•œ ๋ฆฌ๋ทฐ๋ฅผ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”: + +## {filename} ํŒŒ์ผ ๋ฆฌ๋ทฐ + +### ์ฃผ์š” ๊ธฐ๋Šฅ +[ํŒŒ์ผ์˜ ์ฃผ์š” ๊ธฐ๋Šฅ ์„ค๋ช…] + +### ์ข‹์€ ์  +[์ข‹์€ ์  ๋‚˜์—ด] + +### ๊ฐœ์„ ํ•  ์  +[๊ฐœ์„ ์ด ํ•„์š”ํ•œ ์  ๋‚˜์—ด] + +### ์ œ์•ˆ ์‚ฌํ•ญ +[๊ตฌ์ฒด์ ์ธ ๊ฐœ์„  ์ œ์•ˆ, ์ฝ”๋“œ ์˜ˆ์‹œ ํฌํ•จ] + +ํŒŒ์ผ ๋‚ด์šฉ: +{content} +""" + +LINE_COMMENTS_PROMPT = """ +๋‹ค์Œ {filename} ํŒŒ์ผ์˜ ์ฝ”๋“œ๋ฅผ ๋ฆฌ๋ทฐํ•˜๊ณ , ์ค‘์š”ํ•œ ๋ผ์ธ์— ๋Œ€ํ•ด ๊ตฌ์ฒด์ ์ธ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”. +ํ˜•์‹์€ '๋ผ์ธ ๋ฒˆํ˜ธ: ์ฝ”๋ฉ˜ํŠธ'๋กœ ํ•ด์ฃผ์„ธ์š”. + +{content} +""" + +OVERALL_COMMENTS_PROMPT = """ +## AI ์ฝ”๋“œ ๋ฆฌ๋ทฐ ์š”์•ฝ + +{overall_review} +""" + +def get_review_prompt(all_code, pr_context, commit_messages, changed_files): + formatted_commit_messages = "\n".join([f"- {msg}" for msg in commit_messages]) + return REVIEW_PROMPT.format( + title=pr_context['title'], + description=pr_context['description'], + commit_messages=formatted_commit_messages, + changed_files=changed_files, + all_code=all_code + ) + +def get_file_review_prompt(filename, content): + return FILE_REVIEW_PROMPT.format(filename=filename, content=content) + +def get_line_comments_prompt(filename, content): + return LINE_COMMENTS_PROMPT.format(filename=filename, content=content) + +def get_total_comments_prompt(overall_review): + return OVERALL_COMMENTS_PROMPT.format(overall_review=overall_review) + \ No newline at end of file
Python
get_line_comments_prompt ํ•จ์ˆ˜์˜ ์ด๋ฆ„์ด ๋„ˆ๋ฌด ์ผ๋ฐ˜์ ์ž…๋‹ˆ๋‹ค. get_line_template์œผ๋กœ ๋ฐ”๊ฟ€ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,101 @@ +REVIEW_PROMPT = """ +You have deep knowledge and expertise in Python, FastAPI for the back end, React and Next.js for the front. +Here is the new PR information. +- title: {title} +- description: {description} +- commit messages: {commit_messages} +- changed files: {changed_files} + +Please understand and review the purpose and context of the change considering PR information and commit message. +Please be sure to thoroughly analyze and review the following format and provide a comprehensive review. +If the author has written a post in accordance with the ๐Ÿ™ review requirements (optional) written in the PR description section, +please provide a solution to resolve the content first. +If not, please find one part of the entire code provided that needs the most improvement and provide a solution. +Please find the number one priority that needs improvement in the entire code you provided and write it strictly in the format below. +-------------------------------------------------------- +## ๐Ÿง‘๐Ÿปโ€๐Ÿ’ป ์ฃผ์š” ๊ธฐ๋Šฅ + +[Provide a brief description of the main features of this file, including its core functionality, expected input and output, and any specific exception cases it handles.] + +## ๐Ÿ” ๊ฐœ์„ ํ•  ์  + +[Write down any areas that need improvement, including performance bottlenecks, readability issues, and security vulnerabilities.] + +## ๐Ÿ“ข ์ œ์•ˆ๋œ ์†”๋ฃจ์…˜ + +1. ํ˜„์žฌ ์ฝ”๋“œ + +[problematic code fragment] + +2. ๊ถŒ์žฅ๋˜๋Š” ๋ณ€๊ฒฝ + +[updated code snippet] + +3. ๋ณ€๊ฒฝ ์ด์œ  + +[Brief reasons why the new approach is better, considering performance, readability, security, etc.] +-------------------------------------------------------- + +Full Code: {all_code} + +If you need to put in a code block, keep it brief, no more than 10 lines of code that needs improvement. +Please write one sentence within 70 characters, including the maximum space, that you need to explain. +If you write one sentence for readability, please write the next sentence in the next column instead of the next one. + +The person receiving this feedback is a Korean developer. +Please make sure to follow the above format strictly in Korean, but please provide specific and constructive feedback. +""" + +FILE_REVIEW_PROMPT = """ +๋‹ค์Œ {filename} ํŒŒ์ผ์˜ ์ฝ”๋“œ๋ฅผ ๋ฆฌ๋ทฐํ•˜๊ณ , ์•„๋ž˜ ํ˜•์‹์œผ๋กœ ์ƒ์„ธํ•œ ๋ฆฌ๋ทฐ๋ฅผ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”: + +## {filename} ํŒŒ์ผ ๋ฆฌ๋ทฐ + +### ์ฃผ์š” ๊ธฐ๋Šฅ +[ํŒŒ์ผ์˜ ์ฃผ์š” ๊ธฐ๋Šฅ ์„ค๋ช…] + +### ์ข‹์€ ์  +[์ข‹์€ ์  ๋‚˜์—ด] + +### ๊ฐœ์„ ํ•  ์  +[๊ฐœ์„ ์ด ํ•„์š”ํ•œ ์  ๋‚˜์—ด] + +### ์ œ์•ˆ ์‚ฌํ•ญ +[๊ตฌ์ฒด์ ์ธ ๊ฐœ์„  ์ œ์•ˆ, ์ฝ”๋“œ ์˜ˆ์‹œ ํฌํ•จ] + +ํŒŒ์ผ ๋‚ด์šฉ: +{content} +""" + +LINE_COMMENTS_PROMPT = """ +๋‹ค์Œ {filename} ํŒŒ์ผ์˜ ์ฝ”๋“œ๋ฅผ ๋ฆฌ๋ทฐํ•˜๊ณ , ์ค‘์š”ํ•œ ๋ผ์ธ์— ๋Œ€ํ•ด ๊ตฌ์ฒด์ ์ธ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”. +ํ˜•์‹์€ '๋ผ์ธ ๋ฒˆํ˜ธ: ์ฝ”๋ฉ˜ํŠธ'๋กœ ํ•ด์ฃผ์„ธ์š”. + +{content} +""" + +OVERALL_COMMENTS_PROMPT = """ +## AI ์ฝ”๋“œ ๋ฆฌ๋ทฐ ์š”์•ฝ + +{overall_review} +""" + +def get_review_prompt(all_code, pr_context, commit_messages, changed_files): + formatted_commit_messages = "\n".join([f"- {msg}" for msg in commit_messages]) + return REVIEW_PROMPT.format( + title=pr_context['title'], + description=pr_context['description'], + commit_messages=formatted_commit_messages, + changed_files=changed_files, + all_code=all_code + ) + +def get_file_review_prompt(filename, content): + return FILE_REVIEW_PROMPT.format(filename=filename, content=content) + +def get_line_comments_prompt(filename, content): + return LINE_COMMENTS_PROMPT.format(filename=filename, content=content) + +def get_total_comments_prompt(overall_review): + return OVERALL_COMMENTS_PROMPT.format(overall_review=overall_review) + \ No newline at end of file
Python
get_total_comments_prompt ํ•จ์ˆ˜์˜ ์ด๋ฆ„์ด ๋„ˆ๋ฌด ์ผ๋ฐ˜์ ์ž…๋‹ˆ๋‹ค. get_total_template์œผ๋กœ ๋ฐ”๊ฟ€ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,549 @@ +import json +import os +from typing import List, Tuple +import requests +import re +import groq +import logging +from review_config import ( + IGNORED_EXTENSIONS, + IGNORED_FILES, + IMPORTANT_FILE_CHANGE_THRESHOLD, + MAX_COMMENTS_PER_FILE +) + +from scripts.review_prompt import ( + get_review_prompt, + get_file_review_prompt, + get_line_comments_prompt, + get_total_comments_prompt +) + +logging.basicConfig(level=logging.DEBUG) +logger = logging.getLogger(__name__) + +groq_client = groq.Groq(api_key=os.environ["GROQ_API_KEY"]) + +def get_pr_files(repo, pr_number, token): + url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}/files" + headers = { + "Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28" + } + + logger.debug(f"PR ํŒŒ์ผ ๊ฐ€์ ธ์˜ค๋Š” ์ค‘. URL: {url}") + logger.debug(f"ํ—ค๋”: {headers}") + + try: + response = requests.get(url, headers=headers) + response.raise_for_status() + return response.json() + except requests.RequestException as e: + logger.error(f"PR ํŒŒ์ผ ๊ฐ€์ ธ์˜ค๊ธฐ ์˜ค๋ฅ˜: {str(e)}") + return None + +def get_latest_commit_id(repo, pr_number, token): + url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}" + headers = { + "Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28" + } + + response = requests.get(url, headers=headers) + response.raise_for_status() + pr_data = response.json() + return pr_data['head']['sha'] + +def review_code_groq(prompt): + try: + response = groq_client.chat.completions.create( + model="llama-3.1-70b-versatile", + messages=[ + {"role": "system", "content": "You are a professional code reviewer from FANNG Senior Developer."}, + {"role": "user", "content": prompt} + ], + temperature=0.7, + max_tokens=2048 + ) + return response.choices[0].message.content + except Exception as e: + logger.error(f"Groq API ํ˜ธ์ถœ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}") + return f"์ฝ”๋“œ ๋ฆฌ๋ทฐ ์ค‘ ๋ฐœ์ƒํ•œ ์—๋Ÿฌ: {str(e)}" + +# def review_code_ollama(pr_content): +# prompt = get_review_prompt(pr_content) +# url = 'http://localhost:11434/api/generate' +# data = { +# "model": "llama3.1", +# "prompt": prompt, +# "stream": False, +# "options": { +# "temperature": 0.7, +# "top_p": 0.8, +# "top_k": 40, +# "num_predict": 1024 +# } +# } +# logger.debug(f"์ฝ”๋“œ ๋ฆฌ๋ทฐ ์ค‘. URL: {url}") +# logger.debug(f"์š”์ฒญ ๋ฐ์ดํ„ฐ: {data}") + +# try: +# response = requests.post(url, json=data) +# response.raise_for_status() +# return response.json()['response'] +# except requests.RequestException as e: +# logger.error(f"์ฝ”๋“œ ๋ฆฌ๋ทฐ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}") +# return f"์ฝ”๋“œ ๋ฆฌ๋ทฐ ์ค‘ ๋ฐœ์ƒํ•œ ์—๋Ÿฌ: {str(e)}" + +def post_review_comment(repo, pr_number, commit_sha, path, position, body, token): + url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}/comments" + headers = { + "Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28" + } + data = { + "body": body, + "commit_id": commit_sha, + "path": path, + "position": position + } + logger.debug(f"๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ ๊ฒŒ์‹œ ์ค‘. URL: {url}") + logger.debug(f"ํ—ค๋”: {headers}") + logger.debug(f"๋ฐ์ดํ„ฐ: {data}") + + try: + response = requests.post(url, headers=headers, json=data) + response.raise_for_status() + logger.info("๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ๊ฐ€ ์„ฑ๊ณต์ ์œผ๋กœ ๊ฒŒ์‹œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค") + except requests.RequestException as e: + logger.error(f"๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ ๊ฒŒ์‹œ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}") + logger.error(f"์‘๋‹ต ๋‚ด์šฉ: {response.content if 'response' in locals() else '์‘๋‹ต ์—†์Œ'}") + logger.error(f"์‘๋‹ต ์ƒํƒœ ์ฝ”๋“œ: {e.response.status_code}") + logger.error(f"์‘๋‹ต ํ—ค๋”: {e.response.headers}") + logger.error(f"์‘๋‹ต ๋‚ด์šฉ: {e.response.text}") + +def summarize_reviews(all_reviews): + summary_prompt = f"๋‹ค์Œ์€ ์ „์ฒด์ ์ธ ์ฝ”๋“œ ๋ฆฌ๋ทฐ ๊ฒฐ๊ณผ์ž…๋‹ˆ๋‹ค : \n\n{''.join(all_reviews)}" + summary = review_code_groq(summary_prompt) + return summary + +def post_pr_comment(repo, pr_number, body, token): + url = f"https://api.github.com/repos/{repo}/issues/{pr_number}/comments" + headers = { + "Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28" + } + data = {"body": body} + + try: + response = requests.post(url, headers=headers, json=data) + response.raise_for_status() + logger.info("PR ์ฝ”๋ฉ˜ํŠธ๊ฐ€ ์„ฑ๊ณต์ ์œผ๋กœ ๊ฒŒ์‹œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.") + except requests.RequestException as e: + logger.error(f"PR ์ฝ”๋ฉ˜ํŠธ ๊ฒŒ์‹œ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}") + logger.error(f"์‘๋‹ต ๋‚ด์šฉ: {response.content if 'response' in locals() else '์‘๋‹ต ์—†์Œ'}") + +def get_pr_context(repo, pr_number, github_token): + url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}" + headers = { + "Authorization": f"Bearer {github_token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28" + } + response = requests.get(url, headers=headers) + response.raise_for_status() + pr_data = response.json() + return { + "title": pr_data['title'], + "description": pr_data['body'] + } + +def get_commit_messages(repo, pr_number, github_token): + url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}/commits" + headers = { + "Authorization": f"Bearer {github_token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28" + } + response = requests.get(url, headers=headers) + response.raise_for_status() + commits = response.json() + return [commit['commit']['message'] for commit in commits] + +def get_changed_files(repo, pr_number, github_token): + url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}/files" + headers = { + "Authorization": f"token {github_token}", + "Accept": "application/vnd.github.v3+json" + } + response = requests.get(url, headers=headers) + files = response.json() + + changed_files_info = [] + for file in files: + status = file['status'] + filename = file['filename'] + additions = file['additions'] + deletions = file['deletions'] + + if status == 'added': + info = f"{filename} (์ถ”๊ฐ€, +{additions}, -0)" + elif status == 'removed': + info = f"{filename} (์‚ญ์ œ)" + else: + info = f"{filename} (์ˆ˜์ •, +{additions}, -{deletions})" + + changed_files_info.append(info) + + return "\n".join(f"{i+1}. {info}" for i, info in enumerate(changed_files_info)) + +def post_line_comments(repo, pr_number, commit_sha, filename, patch, line_comments, token): + url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}/comments" + headers = { + "Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28" + } + + def get_line_numbers(patch): + lines = patch.split('\n') + line_numbers = [] + current_line = 0 + for line in lines: + if line.startswith('@@'): + current_line = int(line.split('+')[1].split(',')[0]) - 1 + elif not line.startswith('-'): + current_line += 1 + if line.startswith('+'): + line_numbers.append(current_line) + return line_numbers + + def post_single_comment(line_num, comment_text, position): + data = { + "body": comment_text.strip(), + "commit_id": commit_sha, + "path": filename, + "line": position + } + logger.debug(f"๋ผ์ธ {line_num}์— ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ ๊ฒŒ์‹œ ์ค‘. URL: {url}") + logger.debug(f"ํ—ค๋”: {headers}") + logger.debug(f"๋ฐ์ดํ„ฐ: {data}") + + try: + response = requests.post(url, headers=headers, json=data) + response.raise_for_status() + logger.info(f"๋ผ์ธ {line_num}์— ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ๊ฐ€ ์„ฑ๊ณต์ ์œผ๋กœ ๊ฒŒ์‹œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค") + except requests.RequestException as e: + logger.error(f"๋ผ์ธ {line_num} ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ ๊ฒŒ์‹œ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}") + logger.error(f"์‘๋‹ต ๋‚ด์šฉ: {response.content if 'response' in locals() else '์‘๋‹ต ์—†์Œ'}") + logger.error(f"์‘๋‹ต ์ƒํƒœ ์ฝ”๋“œ: {e.response.status_code if 'response' in locals() else '์•Œ ์ˆ˜ ์—†์Œ'}") + logger.error(f"์‘๋‹ต ํ—ค๋”: {e.response.headers if 'response' in locals() else '์•Œ ์ˆ˜ ์—†์Œ'}") + logger.error(f"์‘๋‹ต ๋‚ด์šฉ: {e.response.text if 'response' in locals() else '์•Œ ์ˆ˜ ์—†์Œ'}") + + def parse_comments(line_comments: str) -> List[Tuple[int, str]]: + parsed_comments = [] + for comment in line_comments.split('\n'): + match = re.match(r'(\d+):\s*(.*)', comment) + if match: + line_num, comment_text = match.groups() + try: + line_num = int(line_num) + parsed_comments.append((line_num, comment_text)) + except ValueError: + logger.warning(f"์ž˜๋ชป๋œ ๋ผ์ธ ๋ฒˆํ˜ธ ํ˜•์‹: {line_num}") + else: + logger.warning(f"ํŒŒ์‹ฑํ•  ์ˆ˜ ์—†๋Š” ์ฝ”๋ฉ˜ํŠธ ํ˜•์‹: {comment}") + return parsed_comments + + def evaluate_importance(comment: str) -> int: + # ์—ฌ๊ธฐ์— ์ฝ”๋ฉ˜ํŠธ์˜ ์ค‘์š”๋„๋ฅผ ํ‰๊ฐ€ํ•˜๋Š” ๋กœ์ง์„ ๊ตฌํ˜„ํ•ฉ๋‹ˆ๋‹ค. + # ์˜ˆ๋ฅผ ๋“ค์–ด, ํŠน์ • ํ‚ค์›Œ๋“œ์˜ ์กด์žฌ ์—ฌ๋ถ€, ์ฝ”๋ฉ˜ํŠธ์˜ ๊ธธ์ด ๋“ฑ์„ ๊ณ ๋ คํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. + importance = 0 + if "์ค‘์š”" in comment or "critical" in comment.lower(): + importance += 5 + if "๋ฒ„๊ทธ" in comment or "bug" in comment.lower(): + importance += 4 + if "๊ฐœ์„ " in comment or "improvement" in comment.lower(): + importance += 3 + importance += len(comment) // 50 # ๊ธด ์ฝ”๋ฉ˜ํŠธ์— ์•ฝ๊ฐ„์˜ ๊ฐ€์ค‘์น˜ ๋ถ€์—ฌ + return importance + + line_numbers = get_line_numbers(patch) + parsed_comments = parse_comments(line_comments) + + # ์ค‘์š”๋„์— ๋”ฐ๋ผ ์ฝ”๋ฉ˜ํŠธ ์ •๋ ฌ + sorted_comments = sorted(parsed_comments, key=lambda x: evaluate_importance(x[1]), reverse=True) + + comments_posted = 0 + # ๋ผ์ธ ์ฝ”๋ฉ˜ํŠธ ํŒŒ์‹ฑ ๋ฐ ๊ฒŒ์‹œ + for line_num, comment_text in sorted_comments[:MAX_COMMENTS_PER_FILE]: + if 0 <= line_num - 1 < len(line_numbers): + position = line_numbers[line_num - 1] + if post_single_comment(line_num, comment_text, position): + comments_posted += 1 + else: + logger.warning(f"๋ผ์ธ {line_num}์ด ์œ ํšจํ•œ ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚ฌ์Šต๋‹ˆ๋‹ค.") + + # for comment in line_comments.split('\n'): + # if comments_posted >= MAX_COMMENTS_PER_FILE: + # logger.info(f"{filename}: ์ตœ๋Œ€ ์ฝ”๋ฉ˜ํŠธ ์ˆ˜({MAX_COMMENTS_PER_FILE})์— ๋„๋‹ฌํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‚˜๋จธ์ง€ ์ฝ”๋ฉ˜ํŠธ๋Š” ์ƒ๋žต๋ฉ๋‹ˆ๋‹ค.") + # break + + # match = re.match(r'(\d+):\s*(.*)', comment) + # if match: + # line_num, comment_text = match.groups() + # try: + # line_num = int(line_num) + # if 0 <= line_num - 1 < len(line_numbers): + # position = line_numbers[line_num - 1] + # if post_single_comment(line_num, comment_text, position): + # comments_posted += 1 + # else: + # logger.warning(f"๋ผ์ธ {line_num}์ด ์œ ํšจํ•œ ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚ฌ์Šต๋‹ˆ๋‹ค.") + # except ValueError: + # logger.warning(f"์ž˜๋ชป๋œ ๋ผ์ธ ๋ฒˆํ˜ธ ํ˜•์‹: {line_num}") + # else: + # logger.warning(f"ํŒŒ์‹ฑํ•  ์ˆ˜ ์—†๋Š” ์ฝ”๋ฉ˜ํŠธ ํ˜•์‹: {comment}") + + if comments_posted == 0: + logger.info(f"{filename}: ์ถ”๊ฐ€๋œ ์ฝ”๋ฉ˜ํŠธ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.") + else: + logger.info(f"{filename}: ์ด {comments_posted}๊ฐœ์˜ ์ฝ”๋ฉ˜ํŠธ๊ฐ€ ์ถ”๊ฐ€๋˜์—ˆ์Šต๋‹ˆ๋‹ค.") + + logger.info("๋ชจ๋“  ๋ผ์ธ ์ฝ”๋ฉ˜ํŠธ ์ฒ˜๋ฆฌ ์™„๋ฃŒ") + +def get_environment_variables(): + try: + github_token = os.environ['GITHUB_TOKEN'] + repo = os.environ['GITHUB_REPOSITORY'] + event_path = os.environ['GITHUB_EVENT_PATH'] + return github_token, repo, event_path + except KeyError as e: + logger.error(f"ํ™˜๊ฒฝ ๋ณ€์ˆ˜๊ฐ€ ์„ค์ •๋˜์ง€ ์•Š์Œ: {str(e)}") + raise + +def fetch_pr_data(repo, pr_number, github_token): + pr_files = get_pr_files(repo, pr_number, github_token) + if not pr_files: + logger.warning("ํŒŒ์ผ์„ ์ฐพ์„ ์ˆ˜ ์—†๊ฑฐ๋‚˜ PR ํŒŒ์ผ์„ ๊ฐ€์ ธ์˜ค๋Š” ๋ฐ ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค.") + return None, None + latest_commit_id = get_latest_commit_id(repo, pr_number, github_token) + return pr_files, latest_commit_id + +def get_importance_threshold(file, total_pr_changes): + base_threshold = 0.5 # ๊ธฐ๋ณธ ์ž„๊ณ„๊ฐ’์„ 0.5๋กœ ์„ค์ • (๋” ๋งŽ์€ ํŒŒ์ผ์„ ์ค‘์š”ํ•˜๊ฒŒ ๊ฐ„์ฃผ) + + # ํŒŒ์ผ ํ™•์žฅ์ž์— ๋”ฐ๋ฅธ ๊ฐ€์ค‘์น˜ + extension_weights = { + # ๋ฐฑ์—”๋“œ ํŒŒ์ผ (๋†’์€ ๊ฐ€์ค‘์น˜) + '.py': 1.2, # Python ํŒŒ์ผ + + # ํ”„๋ก ํŠธ์—”๋“œ ํŒŒ์ผ (๋†’์€ ๊ฐ€์ค‘์น˜) + '.js': 1.2, # JavaScript ํŒŒ์ผ + '.jsx': 1.2, # React JSX ํŒŒ์ผ + '.ts': 1.2, # TypeScript ํŒŒ์ผ + '.tsx': 1.2, # React TypeScript ํŒŒ์ผ + + # ์Šคํƒ€์ผ ํŒŒ์ผ (์ค‘๊ฐ„ ๊ฐ€์ค‘์น˜) + '.css': 1.0, # CSS ํŒŒ์ผ + '.scss': 1.0, # SCSS ํŒŒ์ผ + + # ์„ค์ • ํŒŒ์ผ (๋‚ฎ์€ ๊ฐ€์ค‘์น˜) + '.json': 0.9, # JSON ์„ค์ • ํŒŒ์ผ + '.yml': 0.9, # YAML ์„ค์ • ํŒŒ์ผ + '.env': 0.9, # ํ™˜๊ฒฝ ๋ณ€์ˆ˜ ํŒŒ์ผ + + # ๋ฌธ์„œ ํŒŒ์ผ (๊ฐ€์žฅ ๋‚ฎ์€ ๊ฐ€์ค‘์น˜) + '.md': 0.7, # Markdown ๋ฌธ์„œ + '.txt': 0.7, # ํ…์ŠคํŠธ ๋ฌธ์„œ + } + + # ํŒŒ์ผ ํ™•์žฅ์ž ์ถ”์ถœ + _, ext = os.path.splitext(file['filename']) + + # ํ™•์žฅ์ž์— ๋”ฐ๋ฅธ ๊ฐ€์ค‘์น˜ ์ ์šฉ (๊ธฐ๋ณธ๊ฐ’ 1.0) + weight = extension_weights.get(ext.lower(), 1.0) + + # PR ์ „์ฒด ๋ณ€๊ฒฝ ํฌ๊ธฐ์— ๋”ฐ๋ฅธ ์กฐ์ • (ํŒ€ ๊ทœ๋ชจ๊ฐ€ ์ž‘์œผ๋ฏ€๋กœ ๊ธฐ์ค€์„ ๋‚ฎ์ถค) + if total_pr_changes > 500: # ๋Œ€๊ทœ๋ชจ PR ๊ธฐ์ค€์„ 500์ค„๋กœ ๋‚ฎ์ถค + base_threshold *= 0.9 # ๋Œ€๊ทœ๋ชจ PR์˜ ๊ฒฝ์šฐ ์ž„๊ณ„๊ฐ’ ๋‚ฎ์ถค + elif total_pr_changes < 50: # ์†Œ๊ทœ๋ชจ PR ๊ธฐ์ค€์„ 50์ค„๋กœ ๋‚ฎ์ถค + base_threshold *= 1.1 # ์†Œ๊ทœ๋ชจ PR์˜ ๊ฒฝ์šฐ ์ž„๊ณ„๊ฐ’ ๋†’์ž„ + + # ํŒŒ์ผ ํฌ๊ธฐ์— ๋”ฐ๋ฅธ ์กฐ์ • + file_size = file.get('changes', 0) + if file_size < 30: # ์ž‘์€ ํŒŒ์ผ ๊ธฐ์ค€์„ 30์ค„๋กœ ๋‚ฎ์ถค + base_threshold *= 1.2 # ์ž‘์€ ํŒŒ์ผ์˜ ๊ฒฝ์šฐ ์ž„๊ณ„๊ฐ’ ๋†’์ž„ + elif file_size > 300: # ํฐ ํŒŒ์ผ ๊ธฐ์ค€์„ 300์ค„๋กœ ๋‚ฎ์ถค + base_threshold *= 0.8 # ํฐ ํŒŒ์ผ์˜ ๊ฒฝ์šฐ ์ž„๊ณ„๊ฐ’ ๋‚ฎ์ถค + + return min(base_threshold * weight, 1.0) # ์ตœ๋Œ€๊ฐ’์„ 1.0์œผ๋กœ ์ œํ•œ + +def is_important_file(file, total_pr_changes): + filename = file['filename'] + if filename in IGNORED_FILES: + logger.debug(f"๋ฌด์‹œ๋œ ํŒŒ์ผ: {filename}") + return False + + if any(filename.endswith(ext) for ext in IGNORED_EXTENSIONS): + logger.debug(f"๋ฌด์‹œํ•  ํ™•์žฅ์ž ํŒŒ์ผ: {filename}") + return False + + if file['status'] == 'removed': + logger.info(f"์‚ญ์ œ๋œ ํŒŒ์ผ: {file['filename']}") + return True + + total_changes = file.get('changes', 0) + additions = file.get('additions', 0) + deletions = file.get('deletions', 0) + + # ํŒŒ์ผ์˜ ์ „์ฒด ํฌ๊ธฐ ๋Œ€๋น„ ๋ณ€๊ฒฝ๋œ ๋ผ์ธ ์ˆ˜์˜ ๋น„์œจ + change_ratio = total_changes / total_pr_changes if total_pr_changes > 0 else 0 + importance_threshold = get_importance_threshold(file, total_pr_changes) + + is_important = total_changes > IMPORTANT_FILE_CHANGE_THRESHOLD or change_ratio > importance_threshold + + if is_important: + logger.info(f"์ค‘์š” ํŒŒ์ผ๋กœ ์„ ์ •: {filename} (๋ณ€๊ฒฝ: {total_changes}์ค„, ์ถ”๊ฐ€: {additions}, ์‚ญ์ œ: {deletions}, ๋น„์œจ: {change_ratio:.2f}, ์ž„๊ณ„๊ฐ’: {importance_threshold:.2f})") + else: + logger.debug(f"์ผ๋ฐ˜ ํŒŒ์ผ: {filename} (๋ณ€๊ฒฝ: {total_changes}์ค„, ์ถ”๊ฐ€: {additions}, ์‚ญ์ œ: {deletions}, ๋น„์œจ: {change_ratio:.2f}, ์ž„๊ณ„๊ฐ’: {importance_threshold:.2f})") + + return is_important + +def generate_reviews(pr_files, repo, pr_number, latest_commit_id, github_token): + all_code = "" + total_pr_changes = sum(file.get('changes', 0) for file in pr_files) + + important_files = [f for f in pr_files if is_important_file(f, total_pr_changes)] + + logger.info(f"์ด {len(pr_files)}๊ฐœ ํŒŒ์ผ ์ค‘ {len(important_files)}๊ฐœ ํŒŒ์ผ์ด ์ค‘์š” ํŒŒ์ผ๋กœ ์„ ์ •๋˜์—ˆ์Šต๋‹ˆ๋‹ค.") + logger.info(f"PR ์ „์ฒด ๋ณ€๊ฒฝ ํฌ๊ธฐ: {total_pr_changes}์ค„") + + for file in pr_files: + if file['status'] == 'removed': + all_code += f"File: {file['filename']} (DELETED)\n\n" + else: + logger.info(f"ํŒŒ์ผ ๋ฆฌ๋ทฐ ์ค‘: {file['filename']}") + content = requests.get(file['raw_url']).text + all_code += f"File: {file['filename']}\n{content}\n\n" + + if not all_code: + logger.warning("๋ฆฌ๋ทฐํ•  ์ฝ”๋“œ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. ๋ชจ๋“  ํŒŒ์ผ ๋‚ด์šฉ์„ ๊ฐ€์ ธ์˜ค๋Š” ๋ฐ ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค.") + return None, [] + + pr_context = get_pr_context(repo, pr_number, github_token) + commit_messages = get_commit_messages(repo, pr_number, github_token) + changed_files = get_changed_files(repo, pr_number, github_token) + + # ๊ฐœ์„ ๋œ ๋ฆฌ๋ทฐ ํ”„๋กฌํ”„ํŠธ ์ƒ์„ฑ + review_prompt = get_review_prompt(all_code, pr_context, commit_messages, changed_files) + + # ์ „์ฒด ์ฝ”๋“œ์— ๋Œ€ํ•œ ์ƒ์„ธํ•œ ๋ฆฌ๋ทฐ + overall_review = review_code_groq(review_prompt) + + # ์ค‘์š” ํŒŒ์ผ์— ๋Œ€ํ•œ ์ƒ์„ธ ๋ฆฌ๋ทฐ (๋ผ์ธ ๋ณ„ ์ฝ”๋ฉ˜ํŠธ ๋น„ํ™œ์„ฑํ™”) + # for file in important_files: + # logger.info(f"์ค‘์š” ํŒŒ์ผ ์ƒ์„ธ ๋ฆฌ๋ทฐ ์ค‘: {file['filename']}") + # if file['status'] == 'removed': + # file_review = f"ํŒŒ์ผ '{file['filename']}'์ด(๊ฐ€) ์‚ญ์ œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ์ด ๋ณ€๊ฒฝ์ด ์ ์ ˆํ•œ์ง€ ํ™•์ธํ•ด ์ฃผ์„ธ์š”." + # else: + # content = requests.get(file['raw_url']).text + # file_review_prompt = get_file_review_prompt(file['filename'], content) + # file_review = review_code_groq(file_review_prompt) + + # # ํŒŒ์ผ ์ „์ฒด์— ๋Œ€ํ•œ ๋ฆฌ๋ทฐ ์ฝ”๋ฉ˜ํŠธ + # post_file_comment( + # repo, + # pr_number, + # latest_commit_id, + # file['filename'], + # file_review, + # github_token + # ) + + # # ๋ผ์ธ ๋ณ„ ์ฝ”๋ฉ˜ํŠธ + # line_comments_prompt = get_line_comments_prompt(file['filename'], content) + # line_comments = review_code_groq(line_comments_prompt) + + # post_line_comments( + # repo, + # pr_number, + # latest_commit_id, + # file['filename'], + # file['patch'], + # line_comments, + # github_token + # ) + + return overall_review + +def post_file_comment(repo, pr_number, commit_sha, file_path, body, token): + url = f"https://api.github.com/repos/{repo}/pulls/{pr_number}/comments" + headers = { + "Authorization": f"Bearer {token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28" + } + data = { + "body": body, + "commit_id": commit_sha, + "path": file_path, + "position": 1 + } + + try: + response = requests.post(url, headers=headers, json=data) + response.raise_for_status() + logger.info("PR ํŒŒ์ผ ์ฝ”๋ฉ˜ํŠธ๊ฐ€ ์„ฑ๊ณต์ ์œผ๋กœ ๊ฒŒ์‹œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.") + except requests.RequestException as e: + logger.error(f"PR ์ฝ”๋ฉ˜ํŠธ ๊ฒŒ์‹œ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}") + logger.error(f"์‘๋‹ต ๋‚ด์šฉ: {response.content if 'response' in locals() else '์‘๋‹ต ์—†์Œ'}") + +def main(): + try: + github_token, repo, event_path = get_environment_variables() + + logger.info(f"์ €์žฅ์†Œ ๋ฆฌ๋ทฐ ์‹œ์ž‘: {repo}") + logger.debug(f"GitHub ํ† ํฐ (์ฒ˜์Œ 5์ž): {github_token[:5]}...") + + with open(event_path) as f: + event = json.load(f) + + pr_number = event.get('pull_request', {}).get('number') + if pr_number is None: + logger.error("PR ๋ฒˆํ˜ธ๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. GitHub ์ด๋ฒคํŠธ ํŒŒ์ผ์ด pull_request ์ด๋ฒคํŠธ๋ฅผ ํฌํ•จํ•˜๊ณ  ์žˆ๋Š”์ง€ ํ™•์ธํ•˜์„ธ์š”.") + + logger.info(f"PR ๋ฒˆํ˜ธ {pr_number} ๋ฆฌ๋ทฐ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค.") + + pr_files, latest_commit_id = fetch_pr_data(repo, pr_number, github_token) + if not pr_files: + return + + overall_review = generate_reviews( + pr_files, + repo, + pr_number, + latest_commit_id, + github_token + ) + + if overall_review: + # comment = get_total_comments_prompt(overall_review) + post_pr_comment( + repo, + pr_number, + overall_review, + github_token + ) + + except KeyError as e: + logger.error(f"ํ™˜๊ฒฝ ๋ณ€์ˆ˜๊ฐ€ ์„ค์ •๋˜์ง€ ์•Š์Œ: {str(e)}") + except Exception as e: + logger.error(f"์˜ˆ์ƒ์น˜ ๋ชปํ•œ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}") + +if __name__ == "__main__": + main()
Python
## .github/scripts/ai_code_review.py ํŒŒ์ผ ๋ฆฌ๋ทฐ ### ์ฃผ์š” ๊ธฐ๋Šฅ ์ด ํŒŒ์ผ์€ GitHub Actions์˜ ์ผ๋ถ€๋กœ ๋™์ž‘ํ•˜๋Š” ํŒŒ์ด์ฌ ์Šคํฌ๋ฆฝํŠธ์ž…๋‹ˆ๋‹ค. ์ด ์Šคํฌ๋ฆฝํŠธ๋Š” PR(ํŽ„ ๋ฆฌํ€˜์ŠคํŠธ)์—์„œ ๋ณ€๊ฒฝ๋œ ํŒŒ์ผ์„ ๊ฐ€์ ธ์™€์„œ, ๊ฐ ํŒŒ์ผ์˜ ์ค‘์š”๋„๋ฅผ ํ‰๊ฐ€ํ•œ ํ›„ ์ค‘์š” ํŒŒ์ผ์— ๋Œ€ํ•œ ์ฝ”๋“œ ๋ฆฌ๋ทฐ๋ฅผ ์ˆ˜ํ–‰ํ•ฉ๋‹ˆ๋‹ค. ์ฝ”๋“œ ๋ฆฌ๋ทฐ๋Š” Groq API๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ž๋™์œผ๋กœ ์ˆ˜ํ–‰๋˜๋ฉฐ, ๋ฆฌ๋ทฐ ๊ฒฐ๊ณผ๋Š” PR์— ์ฝ”๋ฉ˜ํŠธ๋กœ ๊ฒŒ์‹œ๋ฉ๋‹ˆ๋‹ค. ### ์ข‹์€ ์  * ์ด ์Šคํฌ๋ฆฝํŠธ๋Š” PR์—์„œ ๋ณ€๊ฒฝ๋œ ํŒŒ์ผ์„ ์ž๋™์œผ๋กœ ๊ฐ€์ ธ์™€์„œ ์ฝ”๋“œ ๋ฆฌ๋ทฐ๋ฅผ ์ˆ˜ํ–‰ํ•˜๋Š” ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค. ์ด๊ฒƒ์€ ๊ฐœ๋ฐœ์ž๋“ค์ด ์ฝ”๋“œ ๋ฆฌ๋ทฐ๋ฅผ ์ˆ˜ํ–‰ํ•˜๋Š” ๋ฐ ๋งŽ์€ ์‹œ๊ฐ„์„ ์ ˆ์•ฝํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * ์Šคํฌ๋ฆฝํŠธ๋Š” ์ค‘์š” ํŒŒ์ผ์„ ํ‰๊ฐ€ํ•˜์—ฌ ๋ฆฌ๋ทฐ์— ์šฐ์„ ์ˆœ์œ„๋ฅผ ๋ถ€์—ฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ด๊ฒƒ์€ ๊ฐœ๋ฐœ์ž๋“ค์ด ์ฝ”๋“œ ๋ฆฌ๋ทฐ์— ์ง‘์ค‘ํ•ด์•ผ ํ•  ๋ถ€๋ถ„์„ ์‹๋ณ„ํ•˜๋Š” ๋ฐ ๋„์›€์ด ๋ฉ๋‹ˆ๋‹ค. * ์Šคํฌ๋ฆฝํŠธ๋Š” Groq API๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ž๋™์œผ๋กœ ์ฝ”๋“œ ๋ฆฌ๋ทฐ๋ฅผ ์ˆ˜ํ–‰ํ•ฉ๋‹ˆ๋‹ค. ์ด๊ฒƒ์€ ๊ฐœ๋ฐœ์ž๋“ค์ด ์ฝ”๋“œ ๋ฆฌ๋ทฐ๋ฅผ ์ˆ˜ํ–‰ํ•˜๋Š” ๋ฐ ๋งŽ์€ ์‹œ๊ฐ„์„ ์ ˆ์•ฝํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ### ๊ฐœ์„ ํ•  ์  * ์Šคํฌ๋ฆฝํŠธ๋Š” ์—ฌ๋Ÿฌ ๊ฐœ์˜ ํ™˜๊ฒฝ ๋ณ€์ˆ˜์— ์˜์กดํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ์ด๋Ÿฌํ•œ ํ™˜๊ฒฝ ๋ณ€์ˆ˜๊ฐ€ ์„ค์ •๋˜์ง€ ์•Š์€ ๊ฒฝ์šฐ ์Šคํฌ๋ฆฝํŠธ๊ฐ€ ์‹คํŒจํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์Šคํฌ๋ฆฝํŠธ๋Š” ์ด๋Ÿฌํ•œ ํ™˜๊ฒฝ ๋ณ€์ˆ˜๋ฅผ ์„ค์ •ํ•  ์ˆ˜ ์žˆ๋Š” ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. * ์Šคํฌ๋ฆฝํŠธ๋Š” PR์—์„œ ๋ณ€๊ฒฝ๋œ ํŒŒ์ผ์„ ๊ฐ€์ ธ์˜ค๋Š” ๋ฐ GitHub API๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. ์ด API๋Š” ์ œํ•œ๋œ ํ˜ธ์ถœ ํšŸ์ˆ˜๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ์Šคํฌ๋ฆฝํŠธ๋Š” ์ด ์ œํ•œ์„ ์ดˆ๊ณผํ•˜์ง€ ์•Š๋„๋ก ์„ค๊ณ„ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. * ์Šคํฌ๋ฆฝํŠธ๋Š” ์ฝ”๋“œ ๋ฆฌ๋ทฐ ๊ฒฐ๊ณผ๋ฅผ PR์— ์ฝ”๋ฉ˜ํŠธ๋กœ ๊ฒŒ์‹œํ•ฉ๋‹ˆ๋‹ค. ๊ทธ๋Ÿฌ๋‚˜ ์ด ์ฝ”๋ฉ˜ํŠธ๋Š” ๊ฐœ๋ฐœ์ž๋“ค์ด ์ฝ”๋“œ ๋ฆฌ๋ทฐ ๊ฒฐ๊ณผ๋ฅผ ์‰ฝ๊ฒŒ ์ดํ•ดํ•  ์ˆ˜ ์žˆ๋„๋ก ์„ค๊ณ„๋˜์–ด ์žˆ์ง€ ์•Š์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์Šคํฌ๋ฆฝํŠธ๋Š” ์ฝ”๋“œ ๋ฆฌ๋ทฐ ๊ฒฐ๊ณผ๋ฅผ ๋” ์‰ฝ๊ฒŒ ์ดํ•ดํ•  ์ˆ˜ ์žˆ๋„๋ก ์„ค๊ณ„ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ### ์ œ์•ˆ ์‚ฌํ•ญ * ์Šคํฌ๋ฆฝํŠธ๋Š” ํ™˜๊ฒฝ ๋ณ€์ˆ˜๋ฅผ ์„ค์ •ํ•  ์ˆ˜ ์žˆ๋Š” ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, ์Šคํฌ๋ฆฝํŠธ๋Š” `GITHUB_TOKEN` ํ™˜๊ฒฝ ๋ณ€์ˆ˜๋ฅผ ์„ค์ •ํ•  ์ˆ˜ ์žˆ๋Š” ์˜ต์…˜์„ ์ œ๊ณตํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. * ์Šคํฌ๋ฆฝํŠธ๋Š” GitHub API ํ˜ธ์ถœ ํšŸ์ˆ˜๋ฅผ ์ œํ•œํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, ์Šคํฌ๋ฆฝํŠธ๋Š” 1๋ถ„์— 100๋ฒˆ์˜ API ํ˜ธ์ถœ๋งŒ ํ—ˆ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. * ์Šคํฌ๋ฆฝํŠธ๋Š” ์ฝ”๋“œ ๋ฆฌ๋ทฐ ๊ฒฐ๊ณผ๋ฅผ ๋” ์‰ฝ๊ฒŒ ์ดํ•ดํ•  ์ˆ˜ ์žˆ๋„๋ก ์„ค๊ณ„ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, ์Šคํฌ๋ฆฝํŠธ๋Š” ์ฝ”๋“œ ๋ฆฌ๋ทฐ ๊ฒฐ๊ณผ๋ฅผ ๋งˆํฌ๋‹ค์šด ํ˜•์‹์œผ๋กœ ์ œ๊ณตํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ```python # ํ™˜๊ฒฝ ๋ณ€์ˆ˜๋ฅผ ์„ค์ •ํ•  ์ˆ˜ ์žˆ๋Š” ๊ธฐ๋Šฅ์„ ์ œ๊ณต def set_environment_variables(): # GITHUB_TOKEN ํ™˜๊ฒฝ ๋ณ€์ˆ˜๋ฅผ ์„ค์ • os.environ['GITHUB_TOKEN'] = 'your_github_token' # GitHub API ํ˜ธ์ถœ ํšŸ์ˆ˜๋ฅผ ์ œํ•œ def limit_github_api_calls(): # 1๋ถ„์— 100๋ฒˆ์˜ API ํ˜ธ์ถœ๋งŒ ํ—ˆ์šฉ max_calls = 100 calls_per_minute = 0 last_call_time = 0 def make_call(): nonlocal calls_per_minute, last_call_time current_time = time.time() if current_time - last_call_time >= 60: calls_per_minute = 0 last_call_time = current_time if calls_per_minute >= max_calls: raise Exception('GitHub API ํ˜ธ์ถœ ํšŸ์ˆ˜ ์ดˆ๊ณผ') calls_per_minute += 1 return make_call # ์ฝ”๋“œ ๋ฆฌ๋ทฐ ๊ฒฐ๊ณผ๋ฅผ ๋” ์‰ฝ๊ฒŒ ์ดํ•ดํ•  ์ˆ˜ ์žˆ๋„๋ก ์„ค๊ณ„ def format_code_review_result(result): # ๋งˆํฌ๋‹ค์šด ํ˜•์‹์œผ๋กœ ๊ฒฐ๊ณผ๋ฅผ ์ œ๊ณต return f'### ์ฝ”๋“œ ๋ฆฌ๋ทฐ ๊ฒฐ๊ณผ\n\n{result}' ``` ์ด๋Ÿฌํ•œ ์ œ์•ˆ ์‚ฌํ•ญ์„ ๊ตฌํ˜„ํ•˜๋ฉด ์Šคํฌ๋ฆฝํŠธ๊ฐ€ ๋” ์•ˆ์ •์ ์ด๊ณ  ์‚ฌ์šฉ์ž ์นœํ™”์ ์ด๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,27 @@ +# ๋ฆฌ๋ทฐ์—์„œ ์ œ์™ธํ•  ํŒŒ์ผ ๋ชฉ๋ก +IGNORED_FILES = [ + '.gitignore', + 'requirements.txt', + 'docker-compose.yml', + 'Dockerfile', + 'setup.cfg', + 'pyproject.toml', + '.env.example', + 'README.md', + 'LICENSE', +] + +# ๋ฆฌ๋ทฐ์—์„œ ์ œ์™ธํ•  ํŒŒ์ผ ํ™•์žฅ์ž +IGNORED_EXTENSIONS = [ + '.md', + '.txt', + '.log', + '.json', + '.yaml', '.yml', +] + +# ์ค‘์š” ํŒŒ์ผ ํŒ๋‹จ ๊ธฐ์ค€ +IMPORTANT_FILE_CHANGE_THRESHOLD = 100 + +# ํŒŒ์ผ๋‹น ์ตœ๋Œ€ ์ฝ”๋ฉ˜ํŠธ ์ˆ˜ +MAX_COMMENTS_PER_FILE = 3 \ No newline at end of file
Python
## .github/scripts/review_config.py ํŒŒ์ผ ๋ฆฌ๋ทฐ ### ์ฃผ์š” ๊ธฐ๋Šฅ ์ด ํŒŒ์ผ์€ Git ๋ฆฌ๋ทฐ์™€ ๊ด€๋ จ๋œ ์„ค์ •์„ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค. ๋ฆฌ๋ทฐ์—์„œ ์ œ์™ธํ•  ํŒŒ์ผ ๋ชฉ๋ก, ํŒŒ์ผ ํ™•์žฅ์ž, ์ค‘์š” ํŒŒ์ผ ํŒ๋‹จ ๊ธฐ์ค€, ํŒŒ์ผ๋‹น ์ตœ๋Œ€ ์ฝ”๋ฉ˜ํŠธ ์ˆ˜ ๋“ฑ์„ ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค. ### ์ข‹์€ ์  * ํŒŒ์ผ์ด ๊ฐ„๋‹จํ•˜๊ณ  ์ดํ•ดํ•˜๊ธฐ ์‰ฝ์Šต๋‹ˆ๋‹ค. * ๋ณ€์ˆ˜๋ช…์ด ๋ช…ํ™•ํ•˜๊ณ  ์ผ๊ด€์ ์ž…๋‹ˆ๋‹ค. * ์ฃผ์š” ์„ค์ • ํ•ญ๋ชฉ์ด ์ž˜ ์ •๋ฆฌ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค. ### ๊ฐœ์„ ํ•  ์  * ํŒŒ์ผ์— ๋Œ€ํ•œ ์„ค๋ช…์ด ์—†์Šต๋‹ˆ๋‹ค. ํŒŒ์ผ์˜ ๋ชฉ์ ๊ณผ ์‚ฌ์šฉ ๋ฐฉ๋ฒ•์— ๋Œ€ํ•œ ์ฃผ์„์„ ์ถ”๊ฐ€ํ•  ํ•„์š”๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค. * ๋ณ€์ˆ˜์˜ ์˜๋ฏธ์™€ ์‚ฌ์šฉ ์˜ˆ์‹œ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. ๊ฐ ๋ณ€์ˆ˜์— ๋Œ€ํ•œ ์ฃผ์„์„ ์ถ”๊ฐ€ํ•  ํ•„์š”๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค. * ์„ค์ • ํ•ญ๋ชฉ์ด ๋งŽ์•„์งˆ ๊ฒฝ์šฐ, ํŒŒ์ผ์ด ๋ณต์žกํ•ด์งˆ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์„ค์ • ํ•ญ๋ชฉ์„ ๋ถ„๋ฅ˜ํ•˜๊ณ , ๊ฐ ๋ถ„๋ฅ˜๋ณ„๋กœ ๋ณ„๋„์˜ ํŒŒ์ผ๋กœ ๋ถ„๋ฆฌํ•  ํ•„์š”๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค. * ์„ค์ • ํ•ญ๋ชฉ์ด ๋ณ€๊ฒฝ๋  ๊ฒฝ์šฐ, ํŒŒ์ผ์„ ๋‹ค์‹œ ๋ฐฐํฌํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ์„ค์ • ํ•ญ๋ชฉ์„ ์™ธ๋ถ€ ํŒŒ์ผ๋กœ ๋ถ„๋ฆฌํ•˜๊ณ , ํ™˜๊ฒฝ ๋ณ€์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ๊ณ ๋ คํ•  ํ•„์š”๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค. ### ์ œ์•ˆ ์‚ฌํ•ญ * ํŒŒ์ผ์— ๋Œ€ํ•œ ์„ค๋ช…์„ ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค. ```python """ ๋ฆฌ๋ทฐ์™€ ๊ด€๋ จ๋œ ์„ค์ •์„ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค. """ ``` * ๊ฐ ๋ณ€์ˆ˜์— ๋Œ€ํ•œ ์ฃผ์„์„ ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค. ```python # ๋ฆฌ๋ทฐ์—์„œ ์ œ์™ธํ•  ํŒŒ์ผ ๋ชฉ๋ก # .gitignore, requirements.txt ๋“ฑ๊ณผ ๊ฐ™์€ ํŒŒ์ผ์„ ์ œ์™ธํ•ฉ๋‹ˆ๋‹ค. IGNORED_FILES = [ '.gitignore', 'requirements.txt', 'docker-compose.yml', 'Dockerfile', 'setup.cfg', 'pyproject.toml', '.env.example', 'README.md', 'LICENSE', ] # ๋ฆฌ๋ทฐ์—์„œ ์ œ์™ธํ•  ํŒŒ์ผ ํ™•์žฅ์ž # .md, .txt, .log, .json, .yaml, .yml ๋“ฑ๊ณผ ๊ฐ™์€ ํŒŒ์ผ์„ ์ œ์™ธํ•ฉ๋‹ˆ๋‹ค. IGNORED_EXTENSIONS = [ '.md', '.txt', '.log', '.json', '.yaml', '.yml', ] ``` * ์„ค์ • ํ•ญ๋ชฉ์„ ๋ถ„๋ฅ˜ํ•˜๊ณ , ๊ฐ ๋ถ„๋ฅ˜๋ณ„๋กœ ๋ณ„๋„์˜ ํŒŒ์ผ๋กœ ๋ถ„๋ฆฌํ•ฉ๋‹ˆ๋‹ค. ```python # review_config.py import ignored_files import ignored_extensions import important_file_criteria import max_comments_per_file # ๋ฆฌ๋ทฐ์—์„œ ์ œ์™ธํ•  ํŒŒ์ผ ๋ชฉ๋ก IGNORED_FILES = ignored_files.IGNORED_FILES # ๋ฆฌ๋ทฐ์—์„œ ์ œ์™ธํ•  ํŒŒ์ผ ํ™•์žฅ์ž IGNORED_EXTENSIONS = ignored_extensions.IGNORED_EXTENSIONS # ์ค‘์š” ํŒŒ์ผ ํŒ๋‹จ ๊ธฐ์ค€ IMPORTANT_FILE_CHANGE_THRESHOLD = important_file_criteria.IMPORTANT_FILE_CHANGE_THRESHOLD IMPORTANT_FILE_CHANGE_RATIO = important_file_criteria.IMPORTANT_FILE_CHANGE_RATIO # ํŒŒ์ผ๋‹น ์ตœ๋Œ€ ์ฝ”๋ฉ˜ํŠธ ์ˆ˜ MAX_COMMENTS_PER_FILE = max_comments_per_file.MAX_COMMENTS_PER_FILE ``` * ์„ค์ • ํ•ญ๋ชฉ์„ ์™ธ๋ถ€ ํŒŒ์ผ๋กœ ๋ถ„๋ฆฌํ•˜๊ณ , ํ™˜๊ฒฝ ๋ณ€์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ๊ณ ๋ คํ•ฉ๋‹ˆ๋‹ค. ```python import os # ๋ฆฌ๋ทฐ์—์„œ ์ œ์™ธํ•  ํŒŒ์ผ ๋ชฉ๋ก IGNORED_FILES = os.environ.get('IGNORED_FILES', '').split(',') ``` ์ด๋Ÿฌํ•œ ๊ฐœ์„  ์‚ฌํ•ญ์„ ์ ์šฉํ•˜๋ฉด, ์„ค์ • ํŒŒ์ผ์ด ๋” ๋ช…ํ™•ํ•˜๊ณ  ์œ ์ง€๋ณด์ˆ˜๊ฐ€ ์‰ฌ์›Œ์งˆ ๊ฒƒ์ž…๋‹ˆ๋‹ค.
@@ -2,7 +2,7 @@ from dotenv import load_dotenv # load .env file -load_dotenv() +load_dotenv('app/backend/.env') from pydantic import ( PostgresDsn, @@ -73,6 +73,9 @@ class Settings(BaseSettings): # ALGORITHM : str # ACCESS_TOKEN_EXPIRE_MINUTES : int + # Groq API + GROQ_API_KEY: str + # ๊ธฐ๋ณธ ์ด๋ฏธ์ง€ URL # DEFAULT_IMAGE_URL : str
Python
## app/backend/src/main/core/config.py ํŒŒ์ผ ๋ฆฌ๋ทฐ ### ์ฃผ์š” ๊ธฐ๋Šฅ ์ด ํŒŒ์ผ์€ ๋ฐฑ์—”๋“œ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์˜ ์„ค์ •์„ ๊ด€๋ฆฌํ•˜๋Š” ๋ฐ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค. ์„ค์ •์€ ํ™˜๊ฒฝ ๋ณ€์ˆ˜์—์„œ ๋กœ๋“œ๋˜๋ฉฐ, ์„ค์ • ํ•ญ๋ชฉ์€ `Settings` ํด๋ž˜์Šค์— ์ •์˜๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค. ### ์ข‹์€ ์  * ์ด ํŒŒ์ผ์€ ์„ค์ •์„ ๊ด€๋ฆฌํ•˜๋Š” ๋ฐ ์‚ฌ์šฉ๋˜๋Š” `Settings` ํด๋ž˜์Šค๋ฅผ ์ œ๊ณตํ•˜๋ฉฐ, ํ™˜๊ฒฝ ๋ณ€์ˆ˜์—์„œ ์„ค์ • ๊ฐ’์„ ๋กœ๋“œํ•˜๋Š” ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค. * ์„ค์ • ํ•ญ๋ชฉ์€ ๋ช…ํ™•ํ•˜๊ฒŒ ์ •์˜๋˜์–ด ์žˆ์œผ๋ฉฐ, ์„ค์ • ํ•ญ๋ชฉ์˜ ํƒ€์ž…์ด ๋ช…ํ™•ํ•˜๊ฒŒ ์ง€์ •๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค. * `parse_cors` ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ CORS ์„ค์ • ๊ฐ’์„ ํŒŒ์‹ฑํ•˜๋Š” ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค. * `SQLALCHEMY_DATABASE_URI` ์†์„ฑ์„ ๊ณ„์‚ฐํ•˜์—ฌ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค URI๋ฅผ ์ƒ์„ฑํ•˜๋Š” ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค. ### ๊ฐœ์„ ํ•  ์  * ์ผ๋ถ€ ์„ค์ • ํ•ญ๋ชฉ์€ ์ฃผ์„ ์ฒ˜๋ฆฌ๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค. ์ฃผ์„ ์ฒ˜๋ฆฌ๋œ ์„ค์ • ํ•ญ๋ชฉ์€ ์ œ๊ฑฐํ•˜๊ฑฐ๋‚˜ ํ™œ์„ฑํ™”ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. * ์„ค์ • ํ•ญ๋ชฉ์˜ ํƒ€์ž…์ด ๋ช…ํ™•ํ•˜๊ฒŒ ์ง€์ •๋˜์–ด ์žˆ์ง€๋งŒ, ์ผ๋ถ€ ์„ค์ • ํ•ญ๋ชฉ์˜ ์„ค๋ช…์ด ๋ถ€์กฑํ•ฉ๋‹ˆ๋‹ค. * ์ผ๋ถ€ ์„ค์ • ํ•ญ๋ชฉ์€ ์„ค์ • ํ•ญ๋ชฉ์˜ ์„ค๋ช…์ด ์—†์Šต๋‹ˆ๋‹ค. * `Settings` ํด๋ž˜์Šค๋Š” `BaseSettings` ํด๋ž˜์Šค๋ฅผ ์ƒ์†ํ•˜์ง€๋งŒ, `BaseSettings` ํด๋ž˜์Šค์˜ ์†์„ฑ๊ณผ ๋ฉ”์„œ๋“œ๊ฐ€ ๋ช…ํ™•ํ•˜๊ฒŒ ์‚ฌ์šฉ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. * `parse_cors` ํ•จ์ˆ˜๋Š” CORS ์„ค์ • ๊ฐ’์„ ํŒŒ์‹ฑํ•˜๋Š” ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•˜์ง€๋งŒ, CORS ์„ค์ • ๊ฐ’์ด ์œ ํšจํ•˜์ง€ ์•Š์€ ๊ฒฝ์šฐ ์˜ˆ์™ธ๋ฅผ ๋ฐœ์ƒ์‹œํ‚ค์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ### ์ œ์•ˆ ์‚ฌํ•ญ * ์ฃผ์„ ์ฒ˜๋ฆฌ๋œ ์„ค์ • ํ•ญ๋ชฉ์„ ์ œ๊ฑฐํ•˜๊ฑฐ๋‚˜ ํ™œ์„ฑํ™”ํ•˜์„ธ์š”. * ์„ค์ • ํ•ญ๋ชฉ์˜ ์„ค๋ช…์„ ์ถ”๊ฐ€ํ•˜์„ธ์š”. * `Settings` ํด๋ž˜์Šค๋Š” `BaseSettings` ํด๋ž˜์Šค์˜ ์†์„ฑ๊ณผ ๋ฉ”์„œ๋“œ๋ฅผ ๋ช…ํ™•ํ•˜๊ฒŒ ์‚ฌ์šฉํ•˜์„ธ์š”. * `parse_cors` ํ•จ์ˆ˜๋Š” CORS ์„ค์ • ๊ฐ’์ด ์œ ํšจํ•˜์ง€ ์•Š์€ ๊ฒฝ์šฐ ์˜ˆ์™ธ๋ฅผ ๋ฐœ์ƒ์‹œํ‚ค๋„๋ก ์ˆ˜์ •ํ•˜์„ธ์š”. ```python # ์ฃผ์„ ์ฒ˜๋ฆฌ๋œ ์„ค์ • ํ•ญ๋ชฉ์„ ์ œ๊ฑฐํ•˜๊ฑฐ๋‚˜ ํ™œ์„ฑํ™”ํ•˜์„ธ์š”. # BACKEND_CORS_ORIGINS: Annotated[ # list[AnyUrl] | str, BeforeValidator(parse_cors) # ] # ์„ค์ • ํ•ญ๋ชฉ์˜ ์„ค๋ช…์„ ์ถ”๊ฐ€ํ•˜์„ธ์š”. PROJECT_NAME : str # ํ”„๋กœ์ ํŠธ ์ด๋ฆ„ POSTGRES_USER: str # PostgreSQL ์‚ฌ์šฉ์ž ์ด๋ฆ„ POSTGRES_PASSWORD: str # PostgreSQL ๋น„๋ฐ€๋ฒˆํ˜ธ POSTGRES_SERVER: str # PostgreSQL ์„œ๋ฒ„ ์ฃผ์†Œ POSTGRES_PORT: int # PostgreSQL ์„œ๋ฒ„ ํฌํŠธ POSTGRES_DB: str # PostgreSQL ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์ด๋ฆ„ # `parse_cors` ํ•จ์ˆ˜๋Š” CORS ์„ค์ • ๊ฐ’์ด ์œ ํšจํ•˜์ง€ ์•Š์€ ๊ฒฝ์šฐ ์˜ˆ์™ธ๋ฅผ ๋ฐœ์ƒ์‹œํ‚ค๋„๋ก ์ˆ˜์ •ํ•˜์„ธ์š”. def parse_cors(v: Any) -> list[str] | str: if isinstance(v, str) and not v.startswith("["): return [i.strip() for i in v.split(",")] elif isinstance(v, list | str): return v raise ValueError("Invalid CORS value") # `Settings` ํด๋ž˜์Šค๋Š” `BaseSettings` ํด๋ž˜์Šค์˜ ์†์„ฑ๊ณผ ๋ฉ”์„œ๋“œ๋ฅผ ๋ช…ํ™•ํ•˜๊ฒŒ ์‚ฌ์šฉํ•˜์„ธ์š”. class Settings(BaseSettings): model_config = SettingsConfigDict( env_file=".env", env_ignore_empty=True, extra="ignore" ) # ... ``` ์ด๋Ÿฌํ•œ ์ˆ˜์ •์„ ํ†ตํ•ด `config.py` ํŒŒ์ผ์€ ๋” ๋ช…ํ™•ํ•˜๊ฒŒ ๊ด€๋ฆฌํ•  ์ˆ˜ ์žˆ์œผ๋ฉฐ, ์„ค์ • ํ•ญ๋ชฉ์˜ ์„ค๋ช…์ด ์ถ”๊ฐ€๋˜์–ด ๊ฐœ๋ฐœ์ž๊ฐ€ ์„ค์ • ํ•ญ๋ชฉ์„ ์ดํ•ดํ•˜๊ธฐๆ›ดๅŠ ๅฎนๆ˜“ํ•ฉ๋‹ˆ๋‹ค. ๋˜ํ•œ, `parse_cors` ํ•จ์ˆ˜๋Š” CORS ์„ค์ • ๊ฐ’์„ ์œ ํšจํ•˜๊ฒŒ ํŒŒ์‹ฑํ•  ์ˆ˜ ์žˆ์œผ๋ฉฐ, ์˜ˆ์™ธ๋ฅผ ๋ฐœ์ƒ์‹œํ‚ค๋„๋ก ์ˆ˜์ •๋˜์–ด ๊ฐœ๋ฐœ์ž๊ฐ€ ์˜ค๋ฅ˜๋ฅผ ์‰ฝ๊ฒŒ ํ™•์ธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,101 @@ +REVIEW_PROMPT = """ +You have deep knowledge and expertise in Python, FastAPI for the back end, React and Next.js for the front. +Here is the new PR information. +- title: {title} +- description: {description} +- commit messages: {commit_messages} +- changed files: {changed_files} + +Please understand and review the purpose and context of the change considering PR information and commit message. +Please be sure to thoroughly analyze and review the following format and provide a comprehensive review. +If the author has written a post in accordance with the ๐Ÿ™ review requirements (optional) written in the PR description section, +please provide a solution to resolve the content first. +If not, please find one part of the entire code provided that needs the most improvement and provide a solution. +Please find the number one priority that needs improvement in the entire code you provided and write it strictly in the format below. +-------------------------------------------------------- +## ๐Ÿง‘๐Ÿปโ€๐Ÿ’ป ์ฃผ์š” ๊ธฐ๋Šฅ + +[Provide a brief description of the main features of this file, including its core functionality, expected input and output, and any specific exception cases it handles.] + +## ๐Ÿ” ๊ฐœ์„ ํ•  ์  + +[Write down any areas that need improvement, including performance bottlenecks, readability issues, and security vulnerabilities.] + +## ๐Ÿ“ข ์ œ์•ˆ๋œ ์†”๋ฃจ์…˜ + +1. ํ˜„์žฌ ์ฝ”๋“œ + +[problematic code fragment] + +2. ๊ถŒ์žฅ๋˜๋Š” ๋ณ€๊ฒฝ + +[updated code snippet] + +3. ๋ณ€๊ฒฝ ์ด์œ  + +[Brief reasons why the new approach is better, considering performance, readability, security, etc.] +-------------------------------------------------------- + +Full Code: {all_code} + +If you need to put in a code block, keep it brief, no more than 10 lines of code that needs improvement. +Please write one sentence within 70 characters, including the maximum space, that you need to explain. +If you write one sentence for readability, please write the next sentence in the next column instead of the next one. + +The person receiving this feedback is a Korean developer. +Please make sure to follow the above format strictly in Korean, but please provide specific and constructive feedback. +""" + +FILE_REVIEW_PROMPT = """ +๋‹ค์Œ {filename} ํŒŒ์ผ์˜ ์ฝ”๋“œ๋ฅผ ๋ฆฌ๋ทฐํ•˜๊ณ , ์•„๋ž˜ ํ˜•์‹์œผ๋กœ ์ƒ์„ธํ•œ ๋ฆฌ๋ทฐ๋ฅผ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”: + +## {filename} ํŒŒ์ผ ๋ฆฌ๋ทฐ + +### ์ฃผ์š” ๊ธฐ๋Šฅ +[ํŒŒ์ผ์˜ ์ฃผ์š” ๊ธฐ๋Šฅ ์„ค๋ช…] + +### ์ข‹์€ ์  +[์ข‹์€ ์  ๋‚˜์—ด] + +### ๊ฐœ์„ ํ•  ์  +[๊ฐœ์„ ์ด ํ•„์š”ํ•œ ์  ๋‚˜์—ด] + +### ์ œ์•ˆ ์‚ฌํ•ญ +[๊ตฌ์ฒด์ ์ธ ๊ฐœ์„  ์ œ์•ˆ, ์ฝ”๋“œ ์˜ˆ์‹œ ํฌํ•จ] + +ํŒŒ์ผ ๋‚ด์šฉ: +{content} +""" + +LINE_COMMENTS_PROMPT = """ +๋‹ค์Œ {filename} ํŒŒ์ผ์˜ ์ฝ”๋“œ๋ฅผ ๋ฆฌ๋ทฐํ•˜๊ณ , ์ค‘์š”ํ•œ ๋ผ์ธ์— ๋Œ€ํ•ด ๊ตฌ์ฒด์ ์ธ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”. +ํ˜•์‹์€ '๋ผ์ธ ๋ฒˆํ˜ธ: ์ฝ”๋ฉ˜ํŠธ'๋กœ ํ•ด์ฃผ์„ธ์š”. + +{content} +""" + +OVERALL_COMMENTS_PROMPT = """ +## AI ์ฝ”๋“œ ๋ฆฌ๋ทฐ ์š”์•ฝ + +{overall_review} +""" + +def get_review_prompt(all_code, pr_context, commit_messages, changed_files): + formatted_commit_messages = "\n".join([f"- {msg}" for msg in commit_messages]) + return REVIEW_PROMPT.format( + title=pr_context['title'], + description=pr_context['description'], + commit_messages=formatted_commit_messages, + changed_files=changed_files, + all_code=all_code + ) + +def get_file_review_prompt(filename, content): + return FILE_REVIEW_PROMPT.format(filename=filename, content=content) + +def get_line_comments_prompt(filename, content): + return LINE_COMMENTS_PROMPT.format(filename=filename, content=content) + +def get_total_comments_prompt(overall_review): + return OVERALL_COMMENTS_PROMPT.format(overall_review=overall_review) + \ No newline at end of file
Python
## scripts/review_prompt.py ํŒŒ์ผ ๋ฆฌ๋ทฐ ### ์ฃผ์š” ๊ธฐ๋Šฅ ์ด ํŒŒ์ผ์€ ์ฝ”๋“œ ๋ฆฌ๋ทฐ๋ฅผ ์œ„ํ•œ ํ”„๋กฌํ”„ํŠธ๋ฅผ ์ œ๊ณตํ•˜๋Š” ํ•จ์ˆ˜๋“ค์„ ์ •์˜ํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ์ด ํŒŒ์ผ์€ ์ฝ”๋“œ ๋ฆฌ๋ทฐ์— ์‚ฌ์šฉ๋  ํ”„๋กฌํ”„ํŠธ๋ฅผ ์ƒ์„ฑํ•˜์—ฌ ๋ฐ˜ํ™˜ํ•˜๋Š” ์—ญํ• ์„ ํ•ฉ๋‹ˆ๋‹ค. ### ์ข‹์€ ์  * ์ฝ”๋“œ๊ฐ€ ๊ฐ„๊ฒฐํ•˜๊ณ  ์ดํ•ดํ•˜๊ธฐ ์‰ฝ์Šต๋‹ˆ๋‹ค. * ํ•จ์ˆ˜๋ช…์ด ๋ช…ํ™•ํ•˜๊ณ , ํ•จ์ˆ˜์˜ ์—ญํ• ์ด ๋ถ„๋ช…ํ•ฉ๋‹ˆ๋‹ค. * ํ”„๋กฌํ”„ํŠธ์˜ ํ˜•์‹์„ ์ •์˜ํ•˜์—ฌ ์ผ๊ด€์„ฑ์„ ์œ ์ง€ํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ### ๊ฐœ์„ ํ•  ์  * ํ•จ์ˆ˜์˜ ๊ฐ ๋งค๊ฐœ๋ณ€์ˆ˜์— ๋Œ€ํ•œ ์„ค๋ช…์ด ์—†์Šต๋‹ˆ๋‹ค. * ํ”„๋กฌํ”„ํŠธ์˜ ํ˜•์‹์ด ๋ณ€๊ฒฝ๋  ๊ฒฝ์šฐ, ๋ชจ๋“  ํ•จ์ˆ˜์—์„œ ๋ณ€๊ฒฝํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. * ์—๋Ÿฌ ํ•ธ๋“ค๋ง์ด ์—†์Šต๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, ๋งค๊ฐœ๋ณ€์ˆ˜๊ฐ€ ์—†๋Š” ๊ฒฝ์šฐ์— ๋Œ€ํ•œ ์ฒ˜๋ฆฌ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. ### ์ œ์•ˆ ์‚ฌํ•ญ * ํ•จ์ˆ˜์˜ ๊ฐ ๋งค๊ฐœ๋ณ€์ˆ˜์— ๋Œ€ํ•œ ์„ค๋ช…์„ ์ถ”๊ฐ€ํ•˜์„ธ์š”. ์˜ˆ๋ฅผ ๋“ค์–ด, `get_review_prompt` ํ•จ์ˆ˜์˜ `code` ๋งค๊ฐœ๋ณ€์ˆ˜์— ๋Œ€ํ•œ ์„ค๋ช…์„ ์ถ”๊ฐ€ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ```python def get_review_prompt(code: str) -> str: """ ์ „์ฒด ์ฝ”๋“œ ๋ฆฌ๋ทฐ ํ”„๋กฌํ”„ํŠธ๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. Args: code (str): ์ „์ฒด ์ฝ”๋“œ Returns: str: ์ „์ฒด ์ฝ”๋“œ ๋ฆฌ๋ทฐ ํ”„๋กฌํ”„ํŠธ """ return REVIEW_PROMPT.format(code=code) ``` * ํ”„๋กฌํ”„ํŠธ์˜ ํ˜•์‹์„ ์ •์˜ํ•˜์—ฌ ์ผ๊ด€์„ฑ์„ ์œ ์ง€ํ•˜๊ณ , ๋ณ€๊ฒฝ์ด ํ•„์š”ํ•œ ๊ฒฝ์šฐ ๋ชจ๋“  ํ•จ์ˆ˜์—์„œ ๋ณ€๊ฒฝํ•ด์•ผ ํ•˜๋Š” ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•ด, ํ”„๋กฌํ”„ํŠธ์˜ ํ˜•์‹์„ ๋ณ„๋„์˜ ํŒŒ์ผ์ด๋‚˜ ๋ณ€์ˆ˜๋กœ ๋ถ„๋ฆฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ```python # prompts.py REVIEW_PROMPT_TEMPLATE = """ ## ์ „์ฒด ์ฝ”๋“œ ๋ฆฌ๋ทฐ ### ์ข‹์€ ์  [์ข‹์€ ์  ๋‚˜์—ด] ### ๊ฐœ์„ ํ•  ์  [๊ฐœ์„ ์ด ํ•„์š”ํ•œ ์  ๋‚˜์—ด] ### ์ œ์•ˆ ์‚ฌํ•ญ [๊ตฌ์ฒด์ ์ธ ๊ฐœ์„  ์ œ์•ˆ, ์ฝ”๋“œ ์˜ˆ์‹œ ํฌํ•จ] ์ „์ฒด ์ฝ”๋“œ: {code} """ # review_prompt.py from prompts import REVIEW_PROMPT_TEMPLATE def get_review_prompt(code: str) -> str: return REVIEW_PROMPT_TEMPLATE.format(code=code) ``` * ์—๋Ÿฌ ํ•ธ๋“ค๋ง์„ ์ถ”๊ฐ€ํ•˜์—ฌ, ๋งค๊ฐœ๋ณ€์ˆ˜๊ฐ€ ์—†๋Š” ๊ฒฝ์šฐ์— ๋Œ€ํ•œ ์ฒ˜๋ฆฌ๋ฅผ ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ```python def get_review_prompt(code: str) -> str: if not code: raise ValueError("code๋Š” ํ•„์ˆ˜ ๋งค๊ฐœ๋ณ€์ˆ˜์ž…๋‹ˆ๋‹ค.") return REVIEW_PROMPT.format(code=code) ```
@@ -0,0 +1,101 @@ +REVIEW_PROMPT = """ +You have deep knowledge and expertise in Python, FastAPI for the back end, React and Next.js for the front. +Here is the new PR information. +- title: {title} +- description: {description} +- commit messages: {commit_messages} +- changed files: {changed_files} + +Please understand and review the purpose and context of the change considering PR information and commit message. +Please be sure to thoroughly analyze and review the following format and provide a comprehensive review. +If the author has written a post in accordance with the ๐Ÿ™ review requirements (optional) written in the PR description section, +please provide a solution to resolve the content first. +If not, please find one part of the entire code provided that needs the most improvement and provide a solution. +Please find the number one priority that needs improvement in the entire code you provided and write it strictly in the format below. +-------------------------------------------------------- +## ๐Ÿง‘๐Ÿปโ€๐Ÿ’ป ์ฃผ์š” ๊ธฐ๋Šฅ + +[Provide a brief description of the main features of this file, including its core functionality, expected input and output, and any specific exception cases it handles.] + +## ๐Ÿ” ๊ฐœ์„ ํ•  ์  + +[Write down any areas that need improvement, including performance bottlenecks, readability issues, and security vulnerabilities.] + +## ๐Ÿ“ข ์ œ์•ˆ๋œ ์†”๋ฃจ์…˜ + +1. ํ˜„์žฌ ์ฝ”๋“œ + +[problematic code fragment] + +2. ๊ถŒ์žฅ๋˜๋Š” ๋ณ€๊ฒฝ + +[updated code snippet] + +3. ๋ณ€๊ฒฝ ์ด์œ  + +[Brief reasons why the new approach is better, considering performance, readability, security, etc.] +-------------------------------------------------------- + +Full Code: {all_code} + +If you need to put in a code block, keep it brief, no more than 10 lines of code that needs improvement. +Please write one sentence within 70 characters, including the maximum space, that you need to explain. +If you write one sentence for readability, please write the next sentence in the next column instead of the next one. + +The person receiving this feedback is a Korean developer. +Please make sure to follow the above format strictly in Korean, but please provide specific and constructive feedback. +""" + +FILE_REVIEW_PROMPT = """ +๋‹ค์Œ {filename} ํŒŒ์ผ์˜ ์ฝ”๋“œ๋ฅผ ๋ฆฌ๋ทฐํ•˜๊ณ , ์•„๋ž˜ ํ˜•์‹์œผ๋กœ ์ƒ์„ธํ•œ ๋ฆฌ๋ทฐ๋ฅผ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”: + +## {filename} ํŒŒ์ผ ๋ฆฌ๋ทฐ + +### ์ฃผ์š” ๊ธฐ๋Šฅ +[ํŒŒ์ผ์˜ ์ฃผ์š” ๊ธฐ๋Šฅ ์„ค๋ช…] + +### ์ข‹์€ ์  +[์ข‹์€ ์  ๋‚˜์—ด] + +### ๊ฐœ์„ ํ•  ์  +[๊ฐœ์„ ์ด ํ•„์š”ํ•œ ์  ๋‚˜์—ด] + +### ์ œ์•ˆ ์‚ฌํ•ญ +[๊ตฌ์ฒด์ ์ธ ๊ฐœ์„  ์ œ์•ˆ, ์ฝ”๋“œ ์˜ˆ์‹œ ํฌํ•จ] + +ํŒŒ์ผ ๋‚ด์šฉ: +{content} +""" + +LINE_COMMENTS_PROMPT = """ +๋‹ค์Œ {filename} ํŒŒ์ผ์˜ ์ฝ”๋“œ๋ฅผ ๋ฆฌ๋ทฐํ•˜๊ณ , ์ค‘์š”ํ•œ ๋ผ์ธ์— ๋Œ€ํ•ด ๊ตฌ์ฒด์ ์ธ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”. +ํ˜•์‹์€ '๋ผ์ธ ๋ฒˆํ˜ธ: ์ฝ”๋ฉ˜ํŠธ'๋กœ ํ•ด์ฃผ์„ธ์š”. + +{content} +""" + +OVERALL_COMMENTS_PROMPT = """ +## AI ์ฝ”๋“œ ๋ฆฌ๋ทฐ ์š”์•ฝ + +{overall_review} +""" + +def get_review_prompt(all_code, pr_context, commit_messages, changed_files): + formatted_commit_messages = "\n".join([f"- {msg}" for msg in commit_messages]) + return REVIEW_PROMPT.format( + title=pr_context['title'], + description=pr_context['description'], + commit_messages=formatted_commit_messages, + changed_files=changed_files, + all_code=all_code + ) + +def get_file_review_prompt(filename, content): + return FILE_REVIEW_PROMPT.format(filename=filename, content=content) + +def get_line_comments_prompt(filename, content): + return LINE_COMMENTS_PROMPT.format(filename=filename, content=content) + +def get_total_comments_prompt(overall_review): + return OVERALL_COMMENTS_PROMPT.format(overall_review=overall_review) + \ No newline at end of file
Python
REVIEW_PROMPT ๋ณ€์ˆ˜์˜ ์ด๋ฆ„์ด ๋„ˆ๋ฌด ๊ธธ๊ณ  ๋ชจํ˜ธํ•ฉ๋‹ˆ๋‹ค. ๋” ์งง๊ณ  ๋ช…ํ™•ํ•˜๊ฒŒ ์ •์˜ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,101 @@ +REVIEW_PROMPT = """ +You have deep knowledge and expertise in Python, FastAPI for the back end, React and Next.js for the front. +Here is the new PR information. +- title: {title} +- description: {description} +- commit messages: {commit_messages} +- changed files: {changed_files} + +Please understand and review the purpose and context of the change considering PR information and commit message. +Please be sure to thoroughly analyze and review the following format and provide a comprehensive review. +If the author has written a post in accordance with the ๐Ÿ™ review requirements (optional) written in the PR description section, +please provide a solution to resolve the content first. +If not, please find one part of the entire code provided that needs the most improvement and provide a solution. +Please find the number one priority that needs improvement in the entire code you provided and write it strictly in the format below. +-------------------------------------------------------- +## ๐Ÿง‘๐Ÿปโ€๐Ÿ’ป ์ฃผ์š” ๊ธฐ๋Šฅ + +[Provide a brief description of the main features of this file, including its core functionality, expected input and output, and any specific exception cases it handles.] + +## ๐Ÿ” ๊ฐœ์„ ํ•  ์  + +[Write down any areas that need improvement, including performance bottlenecks, readability issues, and security vulnerabilities.] + +## ๐Ÿ“ข ์ œ์•ˆ๋œ ์†”๋ฃจ์…˜ + +1. ํ˜„์žฌ ์ฝ”๋“œ + +[problematic code fragment] + +2. ๊ถŒ์žฅ๋˜๋Š” ๋ณ€๊ฒฝ + +[updated code snippet] + +3. ๋ณ€๊ฒฝ ์ด์œ  + +[Brief reasons why the new approach is better, considering performance, readability, security, etc.] +-------------------------------------------------------- + +Full Code: {all_code} + +If you need to put in a code block, keep it brief, no more than 10 lines of code that needs improvement. +Please write one sentence within 70 characters, including the maximum space, that you need to explain. +If you write one sentence for readability, please write the next sentence in the next column instead of the next one. + +The person receiving this feedback is a Korean developer. +Please make sure to follow the above format strictly in Korean, but please provide specific and constructive feedback. +""" + +FILE_REVIEW_PROMPT = """ +๋‹ค์Œ {filename} ํŒŒ์ผ์˜ ์ฝ”๋“œ๋ฅผ ๋ฆฌ๋ทฐํ•˜๊ณ , ์•„๋ž˜ ํ˜•์‹์œผ๋กœ ์ƒ์„ธํ•œ ๋ฆฌ๋ทฐ๋ฅผ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”: + +## {filename} ํŒŒ์ผ ๋ฆฌ๋ทฐ + +### ์ฃผ์š” ๊ธฐ๋Šฅ +[ํŒŒ์ผ์˜ ์ฃผ์š” ๊ธฐ๋Šฅ ์„ค๋ช…] + +### ์ข‹์€ ์  +[์ข‹์€ ์  ๋‚˜์—ด] + +### ๊ฐœ์„ ํ•  ์  +[๊ฐœ์„ ์ด ํ•„์š”ํ•œ ์  ๋‚˜์—ด] + +### ์ œ์•ˆ ์‚ฌํ•ญ +[๊ตฌ์ฒด์ ์ธ ๊ฐœ์„  ์ œ์•ˆ, ์ฝ”๋“œ ์˜ˆ์‹œ ํฌํ•จ] + +ํŒŒ์ผ ๋‚ด์šฉ: +{content} +""" + +LINE_COMMENTS_PROMPT = """ +๋‹ค์Œ {filename} ํŒŒ์ผ์˜ ์ฝ”๋“œ๋ฅผ ๋ฆฌ๋ทฐํ•˜๊ณ , ์ค‘์š”ํ•œ ๋ผ์ธ์— ๋Œ€ํ•ด ๊ตฌ์ฒด์ ์ธ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”. +ํ˜•์‹์€ '๋ผ์ธ ๋ฒˆํ˜ธ: ์ฝ”๋ฉ˜ํŠธ'๋กœ ํ•ด์ฃผ์„ธ์š”. + +{content} +""" + +OVERALL_COMMENTS_PROMPT = """ +## AI ์ฝ”๋“œ ๋ฆฌ๋ทฐ ์š”์•ฝ + +{overall_review} +""" + +def get_review_prompt(all_code, pr_context, commit_messages, changed_files): + formatted_commit_messages = "\n".join([f"- {msg}" for msg in commit_messages]) + return REVIEW_PROMPT.format( + title=pr_context['title'], + description=pr_context['description'], + commit_messages=formatted_commit_messages, + changed_files=changed_files, + all_code=all_code + ) + +def get_file_review_prompt(filename, content): + return FILE_REVIEW_PROMPT.format(filename=filename, content=content) + +def get_line_comments_prompt(filename, content): + return LINE_COMMENTS_PROMPT.format(filename=filename, content=content) + +def get_total_comments_prompt(overall_review): + return OVERALL_COMMENTS_PROMPT.format(overall_review=overall_review) + \ No newline at end of file
Python
get_review_prompt ํ•จ์ˆ˜์˜ ์ด๋ฆ„์ด ๋„ˆ๋ฌด ๊ธธ๊ณ  ๋ชจํ˜ธํ•ฉ๋‹ˆ๋‹ค. ๋” ์งง๊ณ  ๋ช…ํ™•ํ•˜๊ฒŒ ์ •์˜ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,101 @@ +REVIEW_PROMPT = """ +You have deep knowledge and expertise in Python, FastAPI for the back end, React and Next.js for the front. +Here is the new PR information. +- title: {title} +- description: {description} +- commit messages: {commit_messages} +- changed files: {changed_files} + +Please understand and review the purpose and context of the change considering PR information and commit message. +Please be sure to thoroughly analyze and review the following format and provide a comprehensive review. +If the author has written a post in accordance with the ๐Ÿ™ review requirements (optional) written in the PR description section, +please provide a solution to resolve the content first. +If not, please find one part of the entire code provided that needs the most improvement and provide a solution. +Please find the number one priority that needs improvement in the entire code you provided and write it strictly in the format below. +-------------------------------------------------------- +## ๐Ÿง‘๐Ÿปโ€๐Ÿ’ป ์ฃผ์š” ๊ธฐ๋Šฅ + +[Provide a brief description of the main features of this file, including its core functionality, expected input and output, and any specific exception cases it handles.] + +## ๐Ÿ” ๊ฐœ์„ ํ•  ์  + +[Write down any areas that need improvement, including performance bottlenecks, readability issues, and security vulnerabilities.] + +## ๐Ÿ“ข ์ œ์•ˆ๋œ ์†”๋ฃจ์…˜ + +1. ํ˜„์žฌ ์ฝ”๋“œ + +[problematic code fragment] + +2. ๊ถŒ์žฅ๋˜๋Š” ๋ณ€๊ฒฝ + +[updated code snippet] + +3. ๋ณ€๊ฒฝ ์ด์œ  + +[Brief reasons why the new approach is better, considering performance, readability, security, etc.] +-------------------------------------------------------- + +Full Code: {all_code} + +If you need to put in a code block, keep it brief, no more than 10 lines of code that needs improvement. +Please write one sentence within 70 characters, including the maximum space, that you need to explain. +If you write one sentence for readability, please write the next sentence in the next column instead of the next one. + +The person receiving this feedback is a Korean developer. +Please make sure to follow the above format strictly in Korean, but please provide specific and constructive feedback. +""" + +FILE_REVIEW_PROMPT = """ +๋‹ค์Œ {filename} ํŒŒ์ผ์˜ ์ฝ”๋“œ๋ฅผ ๋ฆฌ๋ทฐํ•˜๊ณ , ์•„๋ž˜ ํ˜•์‹์œผ๋กœ ์ƒ์„ธํ•œ ๋ฆฌ๋ทฐ๋ฅผ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”: + +## {filename} ํŒŒ์ผ ๋ฆฌ๋ทฐ + +### ์ฃผ์š” ๊ธฐ๋Šฅ +[ํŒŒ์ผ์˜ ์ฃผ์š” ๊ธฐ๋Šฅ ์„ค๋ช…] + +### ์ข‹์€ ์  +[์ข‹์€ ์  ๋‚˜์—ด] + +### ๊ฐœ์„ ํ•  ์  +[๊ฐœ์„ ์ด ํ•„์š”ํ•œ ์  ๋‚˜์—ด] + +### ์ œ์•ˆ ์‚ฌํ•ญ +[๊ตฌ์ฒด์ ์ธ ๊ฐœ์„  ์ œ์•ˆ, ์ฝ”๋“œ ์˜ˆ์‹œ ํฌํ•จ] + +ํŒŒ์ผ ๋‚ด์šฉ: +{content} +""" + +LINE_COMMENTS_PROMPT = """ +๋‹ค์Œ {filename} ํŒŒ์ผ์˜ ์ฝ”๋“œ๋ฅผ ๋ฆฌ๋ทฐํ•˜๊ณ , ์ค‘์š”ํ•œ ๋ผ์ธ์— ๋Œ€ํ•ด ๊ตฌ์ฒด์ ์ธ ์ฝ”๋ฉ˜ํŠธ๋ฅผ ์ œ๊ณตํ•ด์ฃผ์„ธ์š”. +ํ˜•์‹์€ '๋ผ์ธ ๋ฒˆํ˜ธ: ์ฝ”๋ฉ˜ํŠธ'๋กœ ํ•ด์ฃผ์„ธ์š”. + +{content} +""" + +OVERALL_COMMENTS_PROMPT = """ +## AI ์ฝ”๋“œ ๋ฆฌ๋ทฐ ์š”์•ฝ + +{overall_review} +""" + +def get_review_prompt(all_code, pr_context, commit_messages, changed_files): + formatted_commit_messages = "\n".join([f"- {msg}" for msg in commit_messages]) + return REVIEW_PROMPT.format( + title=pr_context['title'], + description=pr_context['description'], + commit_messages=formatted_commit_messages, + changed_files=changed_files, + all_code=all_code + ) + +def get_file_review_prompt(filename, content): + return FILE_REVIEW_PROMPT.format(filename=filename, content=content) + +def get_line_comments_prompt(filename, content): + return LINE_COMMENTS_PROMPT.format(filename=filename, content=content) + +def get_total_comments_prompt(overall_review): + return OVERALL_COMMENTS_PROMPT.format(overall_review=overall_review) + \ No newline at end of file
Python
FILE_REVIEW_PROMPT ๋ณ€์ˆ˜์˜ ์ด๋ฆ„์ด ๋„ˆ๋ฌด ๊ธธ๊ณ  ๋ชจํ˜ธํ•ฉ๋‹ˆ๋‹ค. ๋” ์งง๊ณ  ๋ช…ํ™•ํ•˜๊ฒŒ ์ •์˜ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
@@ -8,51 +8,65 @@ public class Game { public static final String DELIMETER = "-"; + + public static final String CAR_NAME_DELIMETER = ","; + private int gameCount; + private Car[] cars; public void start() { - cars = createCar(); + + cars = createCar(); + gameCount = getGameCount(); System.out.println("์‹คํ–‰ ๊ฒฐ๊ณผ"); for (int i = 0; i < gameCount; i++) { job(); } + Winner winner = new Winner(); + System.out.println(FormattingUtil.formattingResult(winner.getWinners(cars)) + "๊ฐ€ ์ตœ์ข… ์šฐ์Šนํ–ˆ์Šต๋‹ˆ๋‹ค."); + } private void job() { for (Car car : this.cars) { car.drive(car.getNumber(), DELIMETER); - System.out.println(car.getStatus()); + System.out.println(car.getName() + ":" + car.getStatus()); } System.out.println(" "); } private int getGameCount() { Scanner scanner = new Scanner(System.in); System.out.println("์‹œ๋„ํ•  ํšŒ์ˆ˜๋Š” ๋ช‡ ํšŒ ์ธ๊ฐ€์š”?"); + int gameCount = scanner.nextInt(); - System.out.println("gameCount = " + gameCount); + System.out.println(gameCount); + return gameCount; } private Car[] createCar() { - int carCount = getCarCount(); - Car[] cars = new Car[carCount]; - for (int i = 0; i < carCount; i++) { - cars[i] = new SmallCar(); + String[] carNameInputArr = getCarNameInputArr(); + int length = carNameInputArr.length; + Car[] cars = new Car[length]; + for (int i = 0; i < length; i++) { + cars[i] = new SmallCar(carNameInputArr[i]); + } return cars; } - private int getCarCount() { - System.out.println("์ž๋™์ฐจ ๋Œ€์ˆ˜๋Š” ๋ช‡ ๋Œ€ ์ธ๊ฐ€์š”?"); + + private String[] getCarNameInputArr() { + System.out.println("๊ฒฝ์ฃผํ•  ์ž๋™์ฐจ ์ด๋ฆ„์„ ์ž…๋ ฅํ•˜์„ธ์š”(์ด๋ฆ„์€ " + CAR_NAME_DELIMETER + "๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๊ตฌ๋ถ„)."); Scanner scanner = new Scanner(System.in); - int carCount = Integer.parseInt(scanner.nextLine()); - System.out.println("์ž๋™์ฐจ ๋Œ€์ˆ˜ = " + carCount); - return carCount; + String carNameInput = scanner.nextLine(); + System.out.println(carNameInput); + return carNameInput.split(CAR_NAME_DELIMETER); } public Car[] getCars() {
Java
![image](https://github.com/next-step/java-racingcar/assets/27044096/d221b9bf-2cb7-4dcb-bafa-016f49e445a2) d, e ๊ฐ€ ์šฐ์Šนํ–ˆ๋Š”๋ฐ ์ œ๋Œ€๋กœ ์ถœ๋ ฅ๋˜๊ณ ์žˆ์ง€ ์•Š๋„ค์š” ๐Ÿ˜…
@@ -0,0 +1,25 @@ +import java.util.List; + +/** + * @author jeongheekim + * @date 3/27/24 + */ +public class FormattingUtil { + private FormattingUtil() {} + + public static String formattingResult(List<String> list) { + StringBuilder sb = new StringBuilder(); + int size = list.size(); + for (int i = 0; i < size; i++) { + sb.append(list.get(i)); + addComma(i, size, sb); + } + return sb.toString(); + } + + private static void addComma(int i, int size, StringBuilder sb) { + if (i < size - 1) { + sb.append(","); + } + } +}
Java
> ๊ทœ์น™ 1: ํ•œ ๋ฉ”์„œ๋“œ์— ์˜ค์ง ํ•œ ๋‹จ๊ณ„์˜ ๋“ค์—ฌ์“ฐ๊ธฐ(indent)๋งŒ ํ•œ๋‹ค. indent๊ฐ€ 2์ด์ƒ์ธ ๋ฉ”์†Œ๋“œ์˜ ๊ฒฝ์šฐ ๋ฉ”์†Œ๋“œ๋ฅผ ๋ถ„๋ฆฌํ•˜๋ฉด indent๋ฅผ ์ค„์ผ ์ˆ˜ ์žˆ๋‹ค. else๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š์•„ indent๋ฅผ ์ค„์ผ ์ˆ˜ ์žˆ๋‹ค. ์ธ๋ดํŠธ๊ฐ€ 2์ด์ƒ์ด๊ตฐ์š” ๐Ÿค”
@@ -0,0 +1,47 @@ +import java.util.ArrayList; +import java.util.List; + +/** + * @author jeongheekim + * @date 3/26/24 + */ +public class Winner { + private List<String> winners = new ArrayList<>(); + private int maxLength; + + public void addWinner(String name) { + this.winners.add(name); + } + + public void updateMaxLength(int length) { + this.maxLength = length; + } + + public List<String> getWinners(Car[] cars) { + this.filterMaxLength(cars); + for (Car car : cars) { + this.checkWinnerCondition(car); + } + return this.winners; + } + + private void filterMaxLength (Car[] cars) { + for (Car car : cars) { + int carStatusLength = car.getStatus().length(); + this.compareMaxLength(carStatusLength); + } + } + + private void compareMaxLength(int carStatusLength) { + if (this.maxLength <= carStatusLength) { + this.updateMaxLength(carStatusLength); + } + } + + private void checkWinnerCondition(Car car) { + int statusLength = car.getStatus().length(); + if (this.maxLength <= statusLength) { + this.addWinner(car.getName()); + } + } +}
Java
๋กœ์ง์— ๋ฌธ์ œ๊ฐ€ ์žˆ๋Š”๊ฒƒ ๊ฐ™์•„์š” ๐Ÿ˜… ์šฐ์Šน์ž๊ฐ€ ๋‘๋ฒˆ ์ถœ๋ ฅ๋˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค ![image](https://github.com/next-step/java-racingcar/assets/27044096/b9f03caf-3eb4-4243-b500-48b046458145)
@@ -0,0 +1,47 @@ +import java.util.ArrayList; +import java.util.List; + +/** + * @author jeongheekim + * @date 3/26/24 + */ +public class Winner { + private List<String> winners = new ArrayList<>(); + private int maxLength; + + public void addWinner(String name) { + this.winners.add(name); + } + + public void updateMaxLength(int length) { + this.maxLength = length; + } + + public List<String> getWinners(Car[] cars) { + this.filterMaxLength(cars); + for (Car car : cars) { + this.checkWinnerCondition(car); + } + return this.winners; + } + + private void filterMaxLength (Car[] cars) { + for (Car car : cars) { + int carStatusLength = car.getStatus().length(); + this.compareMaxLength(carStatusLength); + } + } + + private void compareMaxLength(int carStatusLength) { + if (this.maxLength <= carStatusLength) { + this.updateMaxLength(carStatusLength); + } + } + + private void checkWinnerCondition(Car car) { + int statusLength = car.getStatus().length(); + if (this.maxLength <= statusLength) { + this.addWinner(car.getName()); + } + } +}
Java
์ž๋™์ฐจ์˜ ๊ธธ์ด๋ฅผ ๊บผ๋‚ด์–ด ์ฒ˜๋ฆฌํ•˜๊ณ  ์žˆ๋„ค์š”! ๋””๋ฏธํ„ฐ ๋ฒ•์น™์— ์–ด๊ธ‹๋‚˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค ๋ฉ”์„ธ์ง€๋ฅผ ๋ณด๋‚ด์–ด ์ฒ˜๋ฆฌํ•ด๋ณด๋Š”๊ฑด ์–ด๋–จ๊นŒ์š”? ๐Ÿค” https://mangkyu.tistory.com/147
@@ -1,7 +1,73 @@ package com.ll.nbe342team8.domain.book.book.controller; -import org.springframework.web.bind.annotation.RestController; +import com.ll.nbe342team8.domain.book.book.dto.BookPatchRequestDto; +import com.ll.nbe342team8.domain.book.book.dto.BookResponseDto; +import com.ll.nbe342team8.domain.book.book.entity.Book; +import com.ll.nbe342team8.domain.book.book.service.BookService; +import com.ll.nbe342team8.domain.book.book.type.SortType; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.domain.Page; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +@Slf4j @RestController +@RequestMapping("/books") +@Tag(name = "Book", description = "Book API") +@RequiredArgsConstructor public class BookController { + private final BookService bookService; + + @GetMapping + @Operation(summary = "์ „์ฒด ๋„์„œ ์กฐํšŒ") + public Page<BookResponseDto> getAllBooks(@RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "10") int pageSize, + @RequestParam(defaultValue = "PUBLISHED_DATE") SortType sortType) { + + Page<Book> books = bookService.getAllBooks(page, pageSize, sortType); + return books.map(BookResponseDto::from); + } + + @Operation(summary = "ํŠน์ • ๋„์„œ ์กฐํšŒ") + @GetMapping("/{book-id}") + public BookResponseDto getBookById(@PathVariable("book-id") long bookId) { + Book book = bookService.getBookById(bookId); + return BookResponseDto.from(book); + } + + @Operation(summary = "ํŠน์ • ๋„์„œ ๋Œ“๊ธ€ ์กฐํšŒ") + @GetMapping("/{book-id}/review") + public void getBookReview(@PathVariable("book-id") long bookId) { + + } + + @Operation(summary = "๋„์„œ ์ด๋ฆ„ ๊ฒ€์ƒ‰") + @GetMapping("/search") + public Page<BookResponseDto> searchBooks(@RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "10") int pageSize, + @RequestParam(defaultValue = "PUBLISHED_DATE") SortType sortType, + @RequestParam String title){ + Page<Book> books = bookService.searchBooks(page, pageSize, sortType, title); + return books.map(BookResponseDto::from); + } + + @PostMapping("/admin/books") + public ResponseEntity<?> addBook(@RequestParam(required = false) String isbn13) { + if (isbn13 == null) { + return ResponseEntity.badRequest().body("ISBN13 ๊ฐ’์„ ํฌํ•จํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค."); + } + + return ResponseEntity.ok("์š”์ฒญ ์„ฑ๊ณต: ํ™•์ธ ์™„๋ฃŒ."); + } + + @PatchMapping("/admin/books/{bookId}") + public ResponseEntity<BookResponseDto> updateBookPart(@PathVariable("bookId") Long bookId, + @RequestBody BookPatchRequestDto requestDto) { + BookResponseDto updatedBook = bookService.updateBookPart(bookId, requestDto); + + return ResponseEntity.ok(updatedBook); + } }
Java
- ์ „๋ฐ˜์ ์œผ๋กœ ์ž…๋ ฅ ๋ฐ›๋Š” Parameter์— ๋Œ€ํ•œ ๊ฒ€์ฆ์ด ์—†๋„ค์š”. (์˜ˆ๋ฅผ ๋“ค์–ด, getAllBooks์˜ pageSize ๊ฐ’์œผ๋กœ -100์„ ๋„˜๊ธฐ๋ฉด ์–ด๋–ป๊ฒŒ ๋ ๊นŒ์š”?)
@@ -1,7 +1,73 @@ package com.ll.nbe342team8.domain.book.book.controller; -import org.springframework.web.bind.annotation.RestController; +import com.ll.nbe342team8.domain.book.book.dto.BookPatchRequestDto; +import com.ll.nbe342team8.domain.book.book.dto.BookResponseDto; +import com.ll.nbe342team8.domain.book.book.entity.Book; +import com.ll.nbe342team8.domain.book.book.service.BookService; +import com.ll.nbe342team8.domain.book.book.type.SortType; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.domain.Page; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +@Slf4j @RestController +@RequestMapping("/books") +@Tag(name = "Book", description = "Book API") +@RequiredArgsConstructor public class BookController { + private final BookService bookService; + + @GetMapping + @Operation(summary = "์ „์ฒด ๋„์„œ ์กฐํšŒ") + public Page<BookResponseDto> getAllBooks(@RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "10") int pageSize, + @RequestParam(defaultValue = "PUBLISHED_DATE") SortType sortType) { + + Page<Book> books = bookService.getAllBooks(page, pageSize, sortType); + return books.map(BookResponseDto::from); + } + + @Operation(summary = "ํŠน์ • ๋„์„œ ์กฐํšŒ") + @GetMapping("/{book-id}") + public BookResponseDto getBookById(@PathVariable("book-id") long bookId) { + Book book = bookService.getBookById(bookId); + return BookResponseDto.from(book); + } + + @Operation(summary = "ํŠน์ • ๋„์„œ ๋Œ“๊ธ€ ์กฐํšŒ") + @GetMapping("/{book-id}/review") + public void getBookReview(@PathVariable("book-id") long bookId) { + + } + + @Operation(summary = "๋„์„œ ์ด๋ฆ„ ๊ฒ€์ƒ‰") + @GetMapping("/search") + public Page<BookResponseDto> searchBooks(@RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "10") int pageSize, + @RequestParam(defaultValue = "PUBLISHED_DATE") SortType sortType, + @RequestParam String title){ + Page<Book> books = bookService.searchBooks(page, pageSize, sortType, title); + return books.map(BookResponseDto::from); + } + + @PostMapping("/admin/books") + public ResponseEntity<?> addBook(@RequestParam(required = false) String isbn13) { + if (isbn13 == null) { + return ResponseEntity.badRequest().body("ISBN13 ๊ฐ’์„ ํฌํ•จํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค."); + } + + return ResponseEntity.ok("์š”์ฒญ ์„ฑ๊ณต: ํ™•์ธ ์™„๋ฃŒ."); + } + + @PatchMapping("/admin/books/{bookId}") + public ResponseEntity<BookResponseDto> updateBookPart(@PathVariable("bookId") Long bookId, + @RequestBody BookPatchRequestDto requestDto) { + BookResponseDto updatedBook = bookService.updateBookPart(bookId, requestDto); + + return ResponseEntity.ok(updatedBook); + } }
Java
์–˜๋งŒ ์บ๋ฉ€์ผ€์ด์Šค๋ฅผ ์•ˆ ์“ฐ๋Š” ์ด์œ ๊ฐ€ ์žˆ์„๊นŒ์š”? ์ด๊ฑฐ ๋•Œ๋ฌธ์— `@PathVariable` ์–ด๋…ธํ…Œ์ด์…˜ ๋’ค์— ๋ถˆํ•„์š”ํ•œ ์†์„ฑ๊ฐ’์ด ๊ฐ™์ด ๋ถ™์–ด๋ฒ„๋ ธ๋„ค์š”.
@@ -1,7 +1,73 @@ package com.ll.nbe342team8.domain.book.book.controller; -import org.springframework.web.bind.annotation.RestController; +import com.ll.nbe342team8.domain.book.book.dto.BookPatchRequestDto; +import com.ll.nbe342team8.domain.book.book.dto.BookResponseDto; +import com.ll.nbe342team8.domain.book.book.entity.Book; +import com.ll.nbe342team8.domain.book.book.service.BookService; +import com.ll.nbe342team8.domain.book.book.type.SortType; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.domain.Page; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +@Slf4j @RestController +@RequestMapping("/books") +@Tag(name = "Book", description = "Book API") +@RequiredArgsConstructor public class BookController { + private final BookService bookService; + + @GetMapping + @Operation(summary = "์ „์ฒด ๋„์„œ ์กฐํšŒ") + public Page<BookResponseDto> getAllBooks(@RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "10") int pageSize, + @RequestParam(defaultValue = "PUBLISHED_DATE") SortType sortType) { + + Page<Book> books = bookService.getAllBooks(page, pageSize, sortType); + return books.map(BookResponseDto::from); + } + + @Operation(summary = "ํŠน์ • ๋„์„œ ์กฐํšŒ") + @GetMapping("/{book-id}") + public BookResponseDto getBookById(@PathVariable("book-id") long bookId) { + Book book = bookService.getBookById(bookId); + return BookResponseDto.from(book); + } + + @Operation(summary = "ํŠน์ • ๋„์„œ ๋Œ“๊ธ€ ์กฐํšŒ") + @GetMapping("/{book-id}/review") + public void getBookReview(@PathVariable("book-id") long bookId) { + + } + + @Operation(summary = "๋„์„œ ์ด๋ฆ„ ๊ฒ€์ƒ‰") + @GetMapping("/search") + public Page<BookResponseDto> searchBooks(@RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "10") int pageSize, + @RequestParam(defaultValue = "PUBLISHED_DATE") SortType sortType, + @RequestParam String title){ + Page<Book> books = bookService.searchBooks(page, pageSize, sortType, title); + return books.map(BookResponseDto::from); + } + + @PostMapping("/admin/books") + public ResponseEntity<?> addBook(@RequestParam(required = false) String isbn13) { + if (isbn13 == null) { + return ResponseEntity.badRequest().body("ISBN13 ๊ฐ’์„ ํฌํ•จํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค."); + } + + return ResponseEntity.ok("์š”์ฒญ ์„ฑ๊ณต: ํ™•์ธ ์™„๋ฃŒ."); + } + + @PatchMapping("/admin/books/{bookId}") + public ResponseEntity<BookResponseDto> updateBookPart(@PathVariable("bookId") Long bookId, + @RequestBody BookPatchRequestDto requestDto) { + BookResponseDto updatedBook = bookService.updateBookPart(bookId, requestDto); + + return ResponseEntity.ok(updatedBook); + } }
Java
๊ทธ๋ƒฅ required=false ์˜ต์…˜์„ ๋นผ๋ฉด ๊ตณ์ด ๋ถ„๊ธฐ์ฒ˜๋ฆฌ๋ฅผ ์•ˆํ•ด๋„ ๋˜์ง€ ์•Š์„๊นŒ์š”?
@@ -1,7 +1,73 @@ package com.ll.nbe342team8.domain.book.book.controller; -import org.springframework.web.bind.annotation.RestController; +import com.ll.nbe342team8.domain.book.book.dto.BookPatchRequestDto; +import com.ll.nbe342team8.domain.book.book.dto.BookResponseDto; +import com.ll.nbe342team8.domain.book.book.entity.Book; +import com.ll.nbe342team8.domain.book.book.service.BookService; +import com.ll.nbe342team8.domain.book.book.type.SortType; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.domain.Page; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +@Slf4j @RestController +@RequestMapping("/books") +@Tag(name = "Book", description = "Book API") +@RequiredArgsConstructor public class BookController { + private final BookService bookService; + + @GetMapping + @Operation(summary = "์ „์ฒด ๋„์„œ ์กฐํšŒ") + public Page<BookResponseDto> getAllBooks(@RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "10") int pageSize, + @RequestParam(defaultValue = "PUBLISHED_DATE") SortType sortType) { + + Page<Book> books = bookService.getAllBooks(page, pageSize, sortType); + return books.map(BookResponseDto::from); + } + + @Operation(summary = "ํŠน์ • ๋„์„œ ์กฐํšŒ") + @GetMapping("/{book-id}") + public BookResponseDto getBookById(@PathVariable("book-id") long bookId) { + Book book = bookService.getBookById(bookId); + return BookResponseDto.from(book); + } + + @Operation(summary = "ํŠน์ • ๋„์„œ ๋Œ“๊ธ€ ์กฐํšŒ") + @GetMapping("/{book-id}/review") + public void getBookReview(@PathVariable("book-id") long bookId) { + + } + + @Operation(summary = "๋„์„œ ์ด๋ฆ„ ๊ฒ€์ƒ‰") + @GetMapping("/search") + public Page<BookResponseDto> searchBooks(@RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "10") int pageSize, + @RequestParam(defaultValue = "PUBLISHED_DATE") SortType sortType, + @RequestParam String title){ + Page<Book> books = bookService.searchBooks(page, pageSize, sortType, title); + return books.map(BookResponseDto::from); + } + + @PostMapping("/admin/books") + public ResponseEntity<?> addBook(@RequestParam(required = false) String isbn13) { + if (isbn13 == null) { + return ResponseEntity.badRequest().body("ISBN13 ๊ฐ’์„ ํฌํ•จํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค."); + } + + return ResponseEntity.ok("์š”์ฒญ ์„ฑ๊ณต: ํ™•์ธ ์™„๋ฃŒ."); + } + + @PatchMapping("/admin/books/{bookId}") + public ResponseEntity<BookResponseDto> updateBookPart(@PathVariable("bookId") Long bookId, + @RequestBody BookPatchRequestDto requestDto) { + BookResponseDto updatedBook = bookService.updateBookPart(bookId, requestDto); + + return ResponseEntity.ok(updatedBook); + } }
Java
์œ„ ๋ฉ”์„œ๋“œ์—์„œ๋Š” `long` ์„ ์“ฐ๊ณ , ์—ฌ๊ธฐ์„œ๋Š” `Long` ์„ ์“ฐ๋Š”๋ฐ ํ˜น์‹œ ๋‘˜์„ ๊ตฌ๋ถ„ํ•˜๋Š” ๋‚ด๋ถ€์ ์ธ ์ปจ๋ฒค์…˜์ด ์กด์žฌํ•˜๋Š”๊ฑธ๊นŒ์š”?
@@ -0,0 +1,50 @@ +package com.ll.nbe342team8.domain.book.book.dto; + +import com.ll.nbe342team8.domain.book.category.entity.Category; +import jakarta.validation.constraints.AssertTrue; +import jakarta.validation.constraints.DecimalMin; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.Pattern; +import lombok.Data; + +import java.time.LocalDate; + +@Data +public class BookPatchRequestDto { + private String title; + private String author; + + @Pattern(regexp = "^[0-9]{10}$", message = "ISBN์€ 10์ž๋ฆฌ ์ˆซ์ž์—ฌ์•ผ ํ•ฉ๋‹ˆ๋‹ค.") + private String isbn; // 10์ž๋ฆฌ ์ˆซ์ž๋งŒ ํ—ˆ์šฉ + + @Pattern(regexp = "^[0-9]{13}$", message = "ISBN13์€ 13์ž๋ฆฌ ์ˆซ์ž์—ฌ์•ผ ํ•ฉ๋‹ˆ๋‹ค.") + private String isbn13; // 13์ž๋ฆฌ ์ˆซ์ž๋งŒ ํ—ˆ์šฉ + + private LocalDate pubDate; + + @Min(value = 0, message = "๊ฐ€๊ฒฉ์€ 0 ์ด์ƒ์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.") + private Integer priceStandard; + + @Min(value = 0, message = "๊ฐ€๊ฒฉ์€ 0 ์ด์ƒ์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.") + private Integer priceSales; + + @Min(value = 0, message = "์žฌ๊ณ ๋Š” 0 ์ด์ƒ์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.") + private Integer stock; + + @AssertTrue(message = "status ๊ฐ’์€ 0 ๋˜๋Š” 1์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.") + public boolean isValidStatus() { + return status == null || status == 0 || status == 1; + } + + private Integer status; + + @DecimalMin(value = "0.0", message = "ํ‰์ ์€ 0 ์ด์ƒ์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.") + private Float rating; + + private String toc; + private String cover; + private String description; + private String descriptionImage; + private Category categoryId; + +}
Java
- Controller ์—์„œ `@Valid` ๋ฅผ ์•ˆ ์“ฐ๊ณ  ์žˆ์–ด์„œ, Validation ์ด ์ˆ˜ํ–‰๋˜์ง€ ์•Š์„ ๊ฒƒ์œผ๋กœ ๋ณด์—ฌ์š”. - Dto๋Š” ๊ฐ€๋ณ€์ผ ํ•„์š”๊ฐ€ ์—†๊ณ , (์•„๋งˆ ์ด ํ…์ŠคํŠธ๋ฅผ ๋ณด๊ณ  ์ œ๊ฐ€ ๋งํ•˜๊ฒ ์ง€๋งŒ) ๋ชจ๋˜ ์ž๋ฐ”๋กœ ๋„˜์–ด๊ฐ€๋ฉด์„œ ๋ฐ์ดํ„ฐ์˜ ๋ถˆ๋ณ€์„ฑ์ด ์•„์ฃผ ์ค‘์š”ํ•œ ์ด์Šˆ๋กœ ๋– ์˜ค๋ฅธ ์ƒํ™ฉ์ด์—์š”.`@Data` ๋Œ€์‹ , Record๋กœ ๋Œ€์ฒดํ•ด ์ฃผ์„ธ์š”.
@@ -0,0 +1,50 @@ +package com.ll.nbe342team8.domain.book.book.dto; + +import com.ll.nbe342team8.domain.book.category.entity.Category; +import jakarta.validation.constraints.AssertTrue; +import jakarta.validation.constraints.DecimalMin; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.Pattern; +import lombok.Data; + +import java.time.LocalDate; + +@Data +public class BookPatchRequestDto { + private String title; + private String author; + + @Pattern(regexp = "^[0-9]{10}$", message = "ISBN์€ 10์ž๋ฆฌ ์ˆซ์ž์—ฌ์•ผ ํ•ฉ๋‹ˆ๋‹ค.") + private String isbn; // 10์ž๋ฆฌ ์ˆซ์ž๋งŒ ํ—ˆ์šฉ + + @Pattern(regexp = "^[0-9]{13}$", message = "ISBN13์€ 13์ž๋ฆฌ ์ˆซ์ž์—ฌ์•ผ ํ•ฉ๋‹ˆ๋‹ค.") + private String isbn13; // 13์ž๋ฆฌ ์ˆซ์ž๋งŒ ํ—ˆ์šฉ + + private LocalDate pubDate; + + @Min(value = 0, message = "๊ฐ€๊ฒฉ์€ 0 ์ด์ƒ์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.") + private Integer priceStandard; + + @Min(value = 0, message = "๊ฐ€๊ฒฉ์€ 0 ์ด์ƒ์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.") + private Integer priceSales; + + @Min(value = 0, message = "์žฌ๊ณ ๋Š” 0 ์ด์ƒ์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.") + private Integer stock; + + @AssertTrue(message = "status ๊ฐ’์€ 0 ๋˜๋Š” 1์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.") + public boolean isValidStatus() { + return status == null || status == 0 || status == 1; + } + + private Integer status; + + @DecimalMin(value = "0.0", message = "ํ‰์ ์€ 0 ์ด์ƒ์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.") + private Float rating; + + private String toc; + private String cover; + private String description; + private String descriptionImage; + private Category categoryId; + +}
Java
Float์€ ์ •ํ™•๋„ ๋ฌธ์ œ๋กœ ๊ถŒ์žฅ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. Double๋กœ ๋Œ€์ฒดํ•ด ์ฃผ์„ธ์š”.
@@ -0,0 +1,50 @@ +package com.ll.nbe342team8.domain.book.book.dto; + +import com.ll.nbe342team8.domain.book.category.entity.Category; +import jakarta.validation.constraints.AssertTrue; +import jakarta.validation.constraints.DecimalMin; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.Pattern; +import lombok.Data; + +import java.time.LocalDate; + +@Data +public class BookPatchRequestDto { + private String title; + private String author; + + @Pattern(regexp = "^[0-9]{10}$", message = "ISBN์€ 10์ž๋ฆฌ ์ˆซ์ž์—ฌ์•ผ ํ•ฉ๋‹ˆ๋‹ค.") + private String isbn; // 10์ž๋ฆฌ ์ˆซ์ž๋งŒ ํ—ˆ์šฉ + + @Pattern(regexp = "^[0-9]{13}$", message = "ISBN13์€ 13์ž๋ฆฌ ์ˆซ์ž์—ฌ์•ผ ํ•ฉ๋‹ˆ๋‹ค.") + private String isbn13; // 13์ž๋ฆฌ ์ˆซ์ž๋งŒ ํ—ˆ์šฉ + + private LocalDate pubDate; + + @Min(value = 0, message = "๊ฐ€๊ฒฉ์€ 0 ์ด์ƒ์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.") + private Integer priceStandard; + + @Min(value = 0, message = "๊ฐ€๊ฒฉ์€ 0 ์ด์ƒ์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.") + private Integer priceSales; + + @Min(value = 0, message = "์žฌ๊ณ ๋Š” 0 ์ด์ƒ์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.") + private Integer stock; + + @AssertTrue(message = "status ๊ฐ’์€ 0 ๋˜๋Š” 1์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.") + public boolean isValidStatus() { + return status == null || status == 0 || status == 1; + } + + private Integer status; + + @DecimalMin(value = "0.0", message = "ํ‰์ ์€ 0 ์ด์ƒ์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.") + private Float rating; + + private String toc; + private String cover; + private String description; + private String descriptionImage; + private Category categoryId; + +}
Java
status๋ฅผ ์ˆซ์ž๊ฐ€ ์•„๋‹Œ Enum ์œผ๋กœ ๊ด€๋ฆฌํ•  ์ˆœ ์—†์„๊นŒ์š”?
@@ -0,0 +1,56 @@ +package com.ll.nbe342team8.domain.book.book.dto; + +import com.ll.nbe342team8.domain.book.book.entity.Book; +import com.ll.nbe342team8.domain.book.category.entity.Category; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +public record BookResponseDto(Long id, + String title, + String author, + String isbn, + String isbn13, + String publisher, + LocalDate pubDate, + int priceStandard, + int priceSales, + long salesPoint, + int stock, + int status, + float rating, + String toc, + long reviewCount, + String coverImage, + Integer categoryId, + String description, + String descriptionImage) { + + public static BookResponseDto from(Book book){ + return new BookResponseDto( + book.getId(), + book.getTitle(), + book.getAuthor(), + book.getIsbn(), + book.getIsbn13(), + book.getPublisher(), + book.getPubDate(), + book.getPriceStandard(), + book.getPricesSales(), + book.getSalesPoint(), + book.getStock(), + book.getStatus(), + book.getRating(), + book.getToc(), + book.getReviewCount(), + book.getCoverImage(), + book.getCategoryId().getCategoryId(), + book.getDescription(), + book.getDescriptionImage() + ); + } +}
Java
์–ด๋–ค ๊ณณ์—์„œ๋Š” record๋ฅผ ์“ฐ๊ณ , ์–ด๋–ค ๊ณณ์—์„œ๋Š” @Data ๋ฅผ ์“ฐ๋Š”๊ฑธ ๋ณด๋‹ˆ, ํŒ€ ๋‚ด ์ปจ๋ฒค์…˜์ด ์ •ํ™•ํ•˜๊ฒŒ ํ™•์ •๋˜์ง€ ์•Š์€ ๊ฒƒ ๊ฐ™์•„์š”.
@@ -1,40 +1,108 @@ package com.ll.nbe342team8.domain.book.book.entity; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.ll.nbe342team8.domain.book.book.dto.BookPatchRequestDto; import com.ll.nbe342team8.domain.book.category.entity.Category; +import com.ll.nbe342team8.domain.book.review.entity.Review; import com.ll.nbe342team8.global.jpa.entity.BaseTime; -import jakarta.persistence.Column; -import jakarta.persistence.Entity; -import jakarta.persistence.FetchType; -import jakarta.persistence.ManyToOne; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; +import java.time.LocalDate; +import java.util.List; + @Entity @Getter @Builder @NoArgsConstructor @AllArgsConstructor public class Book extends BaseTime { - @Column(name="title" ,nullable = true,length = 100) + @Column(length = 100) + @NotNull private String title; // ์ œ๋ชฉ - @Column(name = "author", nullable = true) + @NotNull private String author; // ์ €์ž - @Column(name = "price", nullable = true) - private int price; // ๊ฐ€๊ฒฉ + @Column(name = "isbn") + private String isbn; // ISBN + + @NotNull + private String isbn13; // ISBN13 + + @NotNull + private LocalDate pubDate; //์ถœํŒ์ผ + + @NotNull + private int priceStandard; // ์ •๊ฐ€ + + @NotNull + private int pricesSales; // ํŒ๋งค๊ฐ€ - @Column(name = "stock", nullable = true) + @NotNull private int stock; // ์žฌ๊ณ  - @Column(name = "rating", nullable = true) + @NotNull + private int status; // ํŒ๋งค ์ƒํƒœ + private float rating; // ํ‰์  - private String image; // ์ด๋ฏธ์ง€ URL + private String toc; // ๋ชฉ์ฐจ + + private String coverImage; // ์ปค๋ฒ„ ์ด๋ฏธ์ง€ URL + + private String description; // ์ƒ์„ธํŽ˜์ด์ง€ ๊ธ€ + + @Column(name = "description2") + private String descriptionImage; + private long salesPoint; + + private long reviewCount; + + private String publisher; + + @JsonIgnore @ManyToOne(fetch = FetchType.LAZY) - private Category category; // ์นดํ…Œ๊ณ ๋ฆฌ + @NotNull + @JoinColumn(name = "category_id") // @@@์‹คํ–‰ ์ด์ƒํ•˜๋ฉด ์ง€์›Œ๋ณด๊ธฐ@@@ + private Category categoryId; // ์นดํ…Œ๊ณ ๋ฆฌ + + @OneToMany(mappedBy = "book", fetch = FetchType.LAZY) + private List<Review> review; + + public void createReview(float rating) { + this.reviewCount++; + this.rating += rating; + } + + public void deleteReview(float rating) { + this.reviewCount--; + this.rating -= rating; + } + + public void update(BookPatchRequestDto requestDto) { + if (requestDto.getTitle() != null) this.title = requestDto.getTitle(); + if (requestDto.getAuthor() != null) this.author = requestDto.getAuthor(); + if (requestDto.getIsbn() != null) this.isbn = requestDto.getIsbn(); + if (requestDto.getIsbn13() != null) this.isbn13 = requestDto.getIsbn13(); + if (requestDto.getPubDate() != null) this.pubDate = requestDto.getPubDate(); + if (requestDto.getPriceStandard() != null) this.priceStandard = requestDto.getPriceStandard(); + if (requestDto.getPriceSales() != null) this.pricesSales = requestDto.getPriceSales(); + if (requestDto.getStock() != null) this.stock = requestDto.getStock(); + if (requestDto.getStatus() != null) this.status = requestDto.getStatus(); + if (requestDto.getRating() != null) this.rating = requestDto.getRating(); + if (requestDto.getToc() != null) this.toc = requestDto.getToc(); + if (requestDto.getCover() != null) this.coverImage = requestDto.getCover(); + if (requestDto.getDescription() != null) this.description = requestDto.getDescription(); + if (requestDto.getDescriptionImage() != null) this.descriptionImage = requestDto.getDescriptionImage(); + if (requestDto.getCategoryId() != null) this.categoryId = requestDto.getCategoryId(); + } + + }
Java
์œ„์—์„œ๋Š” `@Column` ์„ ์“ฐ๋Š”๋ฐ, ์™œ ์—ฌ๊ธฐ๋ถ€ํ„ฐ๋Š” ์—†์„๊นŒ์š”?
@@ -1,40 +1,108 @@ package com.ll.nbe342team8.domain.book.book.entity; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.ll.nbe342team8.domain.book.book.dto.BookPatchRequestDto; import com.ll.nbe342team8.domain.book.category.entity.Category; +import com.ll.nbe342team8.domain.book.review.entity.Review; import com.ll.nbe342team8.global.jpa.entity.BaseTime; -import jakarta.persistence.Column; -import jakarta.persistence.Entity; -import jakarta.persistence.FetchType; -import jakarta.persistence.ManyToOne; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; +import java.time.LocalDate; +import java.util.List; + @Entity @Getter @Builder @NoArgsConstructor @AllArgsConstructor public class Book extends BaseTime { - @Column(name="title" ,nullable = true,length = 100) + @Column(length = 100) + @NotNull private String title; // ์ œ๋ชฉ - @Column(name = "author", nullable = true) + @NotNull private String author; // ์ €์ž - @Column(name = "price", nullable = true) - private int price; // ๊ฐ€๊ฒฉ + @Column(name = "isbn") + private String isbn; // ISBN + + @NotNull + private String isbn13; // ISBN13 + + @NotNull + private LocalDate pubDate; //์ถœํŒ์ผ + + @NotNull + private int priceStandard; // ์ •๊ฐ€ + + @NotNull + private int pricesSales; // ํŒ๋งค๊ฐ€ - @Column(name = "stock", nullable = true) + @NotNull private int stock; // ์žฌ๊ณ  - @Column(name = "rating", nullable = true) + @NotNull + private int status; // ํŒ๋งค ์ƒํƒœ + private float rating; // ํ‰์  - private String image; // ์ด๋ฏธ์ง€ URL + private String toc; // ๋ชฉ์ฐจ + + private String coverImage; // ์ปค๋ฒ„ ์ด๋ฏธ์ง€ URL + + private String description; // ์ƒ์„ธํŽ˜์ด์ง€ ๊ธ€ + + @Column(name = "description2") + private String descriptionImage; + private long salesPoint; + + private long reviewCount; + + private String publisher; + + @JsonIgnore @ManyToOne(fetch = FetchType.LAZY) - private Category category; // ์นดํ…Œ๊ณ ๋ฆฌ + @NotNull + @JoinColumn(name = "category_id") // @@@์‹คํ–‰ ์ด์ƒํ•˜๋ฉด ์ง€์›Œ๋ณด๊ธฐ@@@ + private Category categoryId; // ์นดํ…Œ๊ณ ๋ฆฌ + + @OneToMany(mappedBy = "book", fetch = FetchType.LAZY) + private List<Review> review; + + public void createReview(float rating) { + this.reviewCount++; + this.rating += rating; + } + + public void deleteReview(float rating) { + this.reviewCount--; + this.rating -= rating; + } + + public void update(BookPatchRequestDto requestDto) { + if (requestDto.getTitle() != null) this.title = requestDto.getTitle(); + if (requestDto.getAuthor() != null) this.author = requestDto.getAuthor(); + if (requestDto.getIsbn() != null) this.isbn = requestDto.getIsbn(); + if (requestDto.getIsbn13() != null) this.isbn13 = requestDto.getIsbn13(); + if (requestDto.getPubDate() != null) this.pubDate = requestDto.getPubDate(); + if (requestDto.getPriceStandard() != null) this.priceStandard = requestDto.getPriceStandard(); + if (requestDto.getPriceSales() != null) this.pricesSales = requestDto.getPriceSales(); + if (requestDto.getStock() != null) this.stock = requestDto.getStock(); + if (requestDto.getStatus() != null) this.status = requestDto.getStatus(); + if (requestDto.getRating() != null) this.rating = requestDto.getRating(); + if (requestDto.getToc() != null) this.toc = requestDto.getToc(); + if (requestDto.getCover() != null) this.coverImage = requestDto.getCover(); + if (requestDto.getDescription() != null) this.description = requestDto.getDescription(); + if (requestDto.getDescriptionImage() != null) this.descriptionImage = requestDto.getDescriptionImage(); + if (requestDto.getCategoryId() != null) this.categoryId = requestDto.getCategoryId(); + } + + }
Java
(์ข€ ์ฑŒ๋ฆฐ์ง•ํ•œ ๋ถ€๋ถ„์ด์—์š”.) ์ผ์ผํžˆ ๋ฐ˜๋ณต๋ฌธ ์•ˆ ์“ฐ๊ณ  update ํ•  ์ˆ˜ ์žˆ์„๊นŒ์š”?
@@ -1,23 +0,0 @@ -package com.ll.nbe342team8.domain.book.book.review.entity; - -import com.ll.nbe342team8.global.jpa.entity.BaseTime; -import jakarta.persistence.Entity; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; - -@Entity -@Getter -@Builder -@NoArgsConstructor -@AllArgsConstructor -public class Review extends BaseTime { - - - String content; - - int rating; - - -}
Java
์š” ๊ณต๋ฐฑ๋“ค๋„ ์ปจ๋ฒค์…˜์— ๋งž๊ฒŒ ์ •๋ฆฌํ•ด์ฃผ์„ธ์š” ใ…Žใ…Ž
@@ -1,9 +1,113 @@ package com.ll.nbe342team8.domain.book.book.service; +import com.ll.nbe342team8.domain.book.book.dto.BookPatchRequestDto; +import com.ll.nbe342team8.domain.book.book.dto.BookResponseDto; +import com.ll.nbe342team8.domain.book.book.dto.ExternalBookDto; +import com.ll.nbe342team8.domain.book.book.entity.Book; +import com.ll.nbe342team8.domain.book.book.repository.BookRepository; +import com.ll.nbe342team8.domain.book.book.type.SortType; +import jakarta.persistence.EntityNotFoundException; import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; @Service @RequiredArgsConstructor public class BookService { -} + + private final ExternalBookApiService externalBookApiService; + private final BookRepository bookRepository; + + public Page<Book> getAllBooks(int page, int pageSize, SortType sortType) { + List<Sort.Order> sorts = new ArrayList<>(); + sorts.add(sortType.getOrder()); + + Pageable pageable = PageRequest.of(page, pageSize, Sort.by(sorts)); + return bookRepository.findAll(pageable); + } + + public Book getBookById(Long id) { + if (id == null) { + throw new IllegalArgumentException("ID ๊ฐ’์ด null์ž…๋‹ˆ๋‹ค."); + } + return bookRepository.findById(id) + .orElseThrow(() -> new IllegalArgumentException("ํ•ด๋‹น ID(" + id + ")์˜ ์ฑ…์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")); + } + + public long count() { + return bookRepository.count(); + } + + public Book create(Book book) { + return bookRepository.save(book); + } + + public Book createReview(Book book, float rating) { + book.createReview(rating); + return bookRepository.save(book); + } + + public Book deleteReview(Book book, float rating) { + book.deleteReview(rating); + return bookRepository.save(book); + } + + public Page<Book> searchBooks(int page, int pageSize, SortType sortType, String title) { + List<Sort.Order> sorts = new ArrayList<>(); + sorts.add(sortType.getOrder()); + + Pageable pageable = PageRequest.of(page, pageSize, Sort.by(sorts)); + return bookRepository.findBooksByTitleContaining(title, pageable); + } + + // ๋„์„œ ์ถ”๊ฐ€ + @Transactional + public Book addBook(String isbn13) { + + if (bookRepository.existsByIsbn13(isbn13)) { + throw new IllegalArgumentException("์ด๋ฏธ ๋“ฑ๋ก๋œ ๋„์„œ์ž…๋‹ˆ๋‹ค."); + } + + ExternalBookDto externalBookDto = externalBookApiService.searchBook(isbn13); + + Book book = mapToEntity(externalBookDto); + + return bookRepository.save(book); + } + + private Book mapToEntity(ExternalBookDto dto) { + return Book.builder() + .title(dto.getTitle()) + .author(dto.getAuthor()) + .isbn(dto.getIsbn()) + .isbn13(dto.getIsbn13()) + .pubDate(LocalDate.parse(dto.getPubDate())) + .priceStandard(dto.getPriceStandard()) + .pricesSales(dto.getPriceSales()) + .toc(dto.getToc()) + .coverImage(dto.getCover()) + .description(dto.getDescription()) + .descriptionImage(dto.getDescriptionImage()) + .categoryId(dto.getCategoryId()) + .build(); + } + + // ๋„์„œ ์ •๋ณด ์ˆ˜์ • + @Transactional + public BookResponseDto updateBookPart(Long bookId, BookPatchRequestDto requestDto) { + Book book = bookRepository.findById(bookId) + .orElseThrow(() -> new EntityNotFoundException("์ฑ…์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")); + + book.update(requestDto); // DTO ์—์„œ null ์ด ์•„๋‹Œ ๊ฐ’๋งŒ ์—…๋ฐ์ดํŠธ + + return BookResponseDto.from(book); + } +} \ No newline at end of file
Java
๊ทธ๋ƒฅ `sortType.getOrder` ๋กœ๋„ ๋Œ€์ฒด๊ฐ€ ๋˜๊ฒ ๋„ค์š”.
@@ -1,9 +1,113 @@ package com.ll.nbe342team8.domain.book.book.service; +import com.ll.nbe342team8.domain.book.book.dto.BookPatchRequestDto; +import com.ll.nbe342team8.domain.book.book.dto.BookResponseDto; +import com.ll.nbe342team8.domain.book.book.dto.ExternalBookDto; +import com.ll.nbe342team8.domain.book.book.entity.Book; +import com.ll.nbe342team8.domain.book.book.repository.BookRepository; +import com.ll.nbe342team8.domain.book.book.type.SortType; +import jakarta.persistence.EntityNotFoundException; import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; @Service @RequiredArgsConstructor public class BookService { -} + + private final ExternalBookApiService externalBookApiService; + private final BookRepository bookRepository; + + public Page<Book> getAllBooks(int page, int pageSize, SortType sortType) { + List<Sort.Order> sorts = new ArrayList<>(); + sorts.add(sortType.getOrder()); + + Pageable pageable = PageRequest.of(page, pageSize, Sort.by(sorts)); + return bookRepository.findAll(pageable); + } + + public Book getBookById(Long id) { + if (id == null) { + throw new IllegalArgumentException("ID ๊ฐ’์ด null์ž…๋‹ˆ๋‹ค."); + } + return bookRepository.findById(id) + .orElseThrow(() -> new IllegalArgumentException("ํ•ด๋‹น ID(" + id + ")์˜ ์ฑ…์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")); + } + + public long count() { + return bookRepository.count(); + } + + public Book create(Book book) { + return bookRepository.save(book); + } + + public Book createReview(Book book, float rating) { + book.createReview(rating); + return bookRepository.save(book); + } + + public Book deleteReview(Book book, float rating) { + book.deleteReview(rating); + return bookRepository.save(book); + } + + public Page<Book> searchBooks(int page, int pageSize, SortType sortType, String title) { + List<Sort.Order> sorts = new ArrayList<>(); + sorts.add(sortType.getOrder()); + + Pageable pageable = PageRequest.of(page, pageSize, Sort.by(sorts)); + return bookRepository.findBooksByTitleContaining(title, pageable); + } + + // ๋„์„œ ์ถ”๊ฐ€ + @Transactional + public Book addBook(String isbn13) { + + if (bookRepository.existsByIsbn13(isbn13)) { + throw new IllegalArgumentException("์ด๋ฏธ ๋“ฑ๋ก๋œ ๋„์„œ์ž…๋‹ˆ๋‹ค."); + } + + ExternalBookDto externalBookDto = externalBookApiService.searchBook(isbn13); + + Book book = mapToEntity(externalBookDto); + + return bookRepository.save(book); + } + + private Book mapToEntity(ExternalBookDto dto) { + return Book.builder() + .title(dto.getTitle()) + .author(dto.getAuthor()) + .isbn(dto.getIsbn()) + .isbn13(dto.getIsbn13()) + .pubDate(LocalDate.parse(dto.getPubDate())) + .priceStandard(dto.getPriceStandard()) + .pricesSales(dto.getPriceSales()) + .toc(dto.getToc()) + .coverImage(dto.getCover()) + .description(dto.getDescription()) + .descriptionImage(dto.getDescriptionImage()) + .categoryId(dto.getCategoryId()) + .build(); + } + + // ๋„์„œ ์ •๋ณด ์ˆ˜์ • + @Transactional + public BookResponseDto updateBookPart(Long bookId, BookPatchRequestDto requestDto) { + Book book = bookRepository.findById(bookId) + .orElseThrow(() -> new EntityNotFoundException("์ฑ…์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")); + + book.update(requestDto); // DTO ์—์„œ null ์ด ์•„๋‹Œ ๊ฐ’๋งŒ ์—…๋ฐ์ดํŠธ + + return BookResponseDto.from(book); + } +} \ No newline at end of file
Java
๋ชจ๋“  ๋กœ์ง ์ „์ฒด์— pageSize์˜ ์ œํ•œ์ด ์—†๋Š”๋ฐ์š”. ๊ทธ๋ ‡๋‹ค๋ฉด ๋งŒ์•ฝ ์ œ๊ฐ€ pageSize=10000000 ์„ ๋„ฃ์œผ๋ฉด ์–ด๋–ป๊ฒŒ ๋ ๊นŒ์š”?
@@ -1,9 +1,113 @@ package com.ll.nbe342team8.domain.book.book.service; +import com.ll.nbe342team8.domain.book.book.dto.BookPatchRequestDto; +import com.ll.nbe342team8.domain.book.book.dto.BookResponseDto; +import com.ll.nbe342team8.domain.book.book.dto.ExternalBookDto; +import com.ll.nbe342team8.domain.book.book.entity.Book; +import com.ll.nbe342team8.domain.book.book.repository.BookRepository; +import com.ll.nbe342team8.domain.book.book.type.SortType; +import jakarta.persistence.EntityNotFoundException; import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; @Service @RequiredArgsConstructor public class BookService { -} + + private final ExternalBookApiService externalBookApiService; + private final BookRepository bookRepository; + + public Page<Book> getAllBooks(int page, int pageSize, SortType sortType) { + List<Sort.Order> sorts = new ArrayList<>(); + sorts.add(sortType.getOrder()); + + Pageable pageable = PageRequest.of(page, pageSize, Sort.by(sorts)); + return bookRepository.findAll(pageable); + } + + public Book getBookById(Long id) { + if (id == null) { + throw new IllegalArgumentException("ID ๊ฐ’์ด null์ž…๋‹ˆ๋‹ค."); + } + return bookRepository.findById(id) + .orElseThrow(() -> new IllegalArgumentException("ํ•ด๋‹น ID(" + id + ")์˜ ์ฑ…์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")); + } + + public long count() { + return bookRepository.count(); + } + + public Book create(Book book) { + return bookRepository.save(book); + } + + public Book createReview(Book book, float rating) { + book.createReview(rating); + return bookRepository.save(book); + } + + public Book deleteReview(Book book, float rating) { + book.deleteReview(rating); + return bookRepository.save(book); + } + + public Page<Book> searchBooks(int page, int pageSize, SortType sortType, String title) { + List<Sort.Order> sorts = new ArrayList<>(); + sorts.add(sortType.getOrder()); + + Pageable pageable = PageRequest.of(page, pageSize, Sort.by(sorts)); + return bookRepository.findBooksByTitleContaining(title, pageable); + } + + // ๋„์„œ ์ถ”๊ฐ€ + @Transactional + public Book addBook(String isbn13) { + + if (bookRepository.existsByIsbn13(isbn13)) { + throw new IllegalArgumentException("์ด๋ฏธ ๋“ฑ๋ก๋œ ๋„์„œ์ž…๋‹ˆ๋‹ค."); + } + + ExternalBookDto externalBookDto = externalBookApiService.searchBook(isbn13); + + Book book = mapToEntity(externalBookDto); + + return bookRepository.save(book); + } + + private Book mapToEntity(ExternalBookDto dto) { + return Book.builder() + .title(dto.getTitle()) + .author(dto.getAuthor()) + .isbn(dto.getIsbn()) + .isbn13(dto.getIsbn13()) + .pubDate(LocalDate.parse(dto.getPubDate())) + .priceStandard(dto.getPriceStandard()) + .pricesSales(dto.getPriceSales()) + .toc(dto.getToc()) + .coverImage(dto.getCover()) + .description(dto.getDescription()) + .descriptionImage(dto.getDescriptionImage()) + .categoryId(dto.getCategoryId()) + .build(); + } + + // ๋„์„œ ์ •๋ณด ์ˆ˜์ • + @Transactional + public BookResponseDto updateBookPart(Long bookId, BookPatchRequestDto requestDto) { + Book book = bookRepository.findById(bookId) + .orElseThrow(() -> new EntityNotFoundException("์ฑ…์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")); + + book.update(requestDto); // DTO ์—์„œ null ์ด ์•„๋‹Œ ๊ฐ’๋งŒ ์—…๋ฐ์ดํŠธ + + return BookResponseDto.from(book); + } +} \ No newline at end of file
Java
+ (์•ฝ๊ฐ„ ์ฑŒ๋ฆฐ์ง•) Spring ์˜ Page ๋Š” ์‹ค์ œ DB ์ฟผ๋ฆฌ์—์„œ ์–ด๋–ป๊ฒŒ ๋˜๋Š”์ง€ ์•„์‹œ๋‚˜์š”? ๊ทธ๊ฒƒ์ด ์–ด๋–ป๊ฒŒ ๋™์ž‘ํ• ๊นŒ์š”?
@@ -1,9 +1,113 @@ package com.ll.nbe342team8.domain.book.book.service; +import com.ll.nbe342team8.domain.book.book.dto.BookPatchRequestDto; +import com.ll.nbe342team8.domain.book.book.dto.BookResponseDto; +import com.ll.nbe342team8.domain.book.book.dto.ExternalBookDto; +import com.ll.nbe342team8.domain.book.book.entity.Book; +import com.ll.nbe342team8.domain.book.book.repository.BookRepository; +import com.ll.nbe342team8.domain.book.book.type.SortType; +import jakarta.persistence.EntityNotFoundException; import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; @Service @RequiredArgsConstructor public class BookService { -} + + private final ExternalBookApiService externalBookApiService; + private final BookRepository bookRepository; + + public Page<Book> getAllBooks(int page, int pageSize, SortType sortType) { + List<Sort.Order> sorts = new ArrayList<>(); + sorts.add(sortType.getOrder()); + + Pageable pageable = PageRequest.of(page, pageSize, Sort.by(sorts)); + return bookRepository.findAll(pageable); + } + + public Book getBookById(Long id) { + if (id == null) { + throw new IllegalArgumentException("ID ๊ฐ’์ด null์ž…๋‹ˆ๋‹ค."); + } + return bookRepository.findById(id) + .orElseThrow(() -> new IllegalArgumentException("ํ•ด๋‹น ID(" + id + ")์˜ ์ฑ…์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")); + } + + public long count() { + return bookRepository.count(); + } + + public Book create(Book book) { + return bookRepository.save(book); + } + + public Book createReview(Book book, float rating) { + book.createReview(rating); + return bookRepository.save(book); + } + + public Book deleteReview(Book book, float rating) { + book.deleteReview(rating); + return bookRepository.save(book); + } + + public Page<Book> searchBooks(int page, int pageSize, SortType sortType, String title) { + List<Sort.Order> sorts = new ArrayList<>(); + sorts.add(sortType.getOrder()); + + Pageable pageable = PageRequest.of(page, pageSize, Sort.by(sorts)); + return bookRepository.findBooksByTitleContaining(title, pageable); + } + + // ๋„์„œ ์ถ”๊ฐ€ + @Transactional + public Book addBook(String isbn13) { + + if (bookRepository.existsByIsbn13(isbn13)) { + throw new IllegalArgumentException("์ด๋ฏธ ๋“ฑ๋ก๋œ ๋„์„œ์ž…๋‹ˆ๋‹ค."); + } + + ExternalBookDto externalBookDto = externalBookApiService.searchBook(isbn13); + + Book book = mapToEntity(externalBookDto); + + return bookRepository.save(book); + } + + private Book mapToEntity(ExternalBookDto dto) { + return Book.builder() + .title(dto.getTitle()) + .author(dto.getAuthor()) + .isbn(dto.getIsbn()) + .isbn13(dto.getIsbn13()) + .pubDate(LocalDate.parse(dto.getPubDate())) + .priceStandard(dto.getPriceStandard()) + .pricesSales(dto.getPriceSales()) + .toc(dto.getToc()) + .coverImage(dto.getCover()) + .description(dto.getDescription()) + .descriptionImage(dto.getDescriptionImage()) + .categoryId(dto.getCategoryId()) + .build(); + } + + // ๋„์„œ ์ •๋ณด ์ˆ˜์ • + @Transactional + public BookResponseDto updateBookPart(Long bookId, BookPatchRequestDto requestDto) { + Book book = bookRepository.findById(bookId) + .orElseThrow(() -> new EntityNotFoundException("์ฑ…์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")); + + book.update(requestDto); // DTO ์—์„œ null ์ด ์•„๋‹Œ ๊ฐ’๋งŒ ์—…๋ฐ์ดํŠธ + + return BookResponseDto.from(book); + } +} \ No newline at end of file
Java
์• ์ดˆ์— ์ž…๋ ฅ ๊ฐ’์—์„œ id๊ฐ€ notnull ์ž„์„ validate ํ•˜๋Š”๊ฒŒ ๋งž์ง€ ์•Š์„๊นŒ์š”? ๊ธฐ๋ณธ์ ์ธ validation ์„ service ๋ ˆ์ด์–ด์—์„œ ์ˆ˜ํ–‰ํ•˜๊ฒŒ ํ•˜์ง€ ๋ง์•„์ฃผ์„ธ์š”.
@@ -0,0 +1,38 @@ +package com.ll.nbe342team8.domain.book.book.service; + +import com.ll.nbe342team8.domain.book.book.dto.ExternalBookDto; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.web.reactive.function.client.WebClient; + +@Service +public class ExternalBookApiService { + + private final WebClient webClient; + private final String ttbkey; + + public ExternalBookApiService(WebClient.Builder webClientBuilder, + @Value("${aladin.ttbkey}") String ttbkey) { + this.webClient = webClientBuilder.baseUrl("http://www.aladin.co.kr/ttb/api/").build(); + this.ttbkey = ttbkey; + } + + public ExternalBookDto searchBook(String isbn13) { + if (isbn13 == null || isbn13.isEmpty()) { + throw new IllegalArgumentException("ISBN13 ๊ฐ’์€ ํ•„์ˆ˜์ž…๋‹ˆ๋‹ค."); + } + + String url = "http://www.aladin.co.kr/ttb/api/ItemLookUp.aspx?" + + "ttbkey=ttbcameogu1634001" // ํ•˜๋“œ์ฝ”๋”ฉ (์ถ”ํ›„์ˆ˜์ •) + + "&itemIdType=ISBN13" + + "&ItemId=" + isbn13 + + "&output=js" + + "&Cover=Big"; + + return webClient.get() + .uri(url) // ํ˜ธ์ถœํ•  URL + .retrieve() // ์‘๋‹ต ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ ธ์˜ด + .bodyToMono(ExternalBookDto.class) // ์‘๋‹ต ๋ฐ์ดํ„ฐ๋ฅผ ExternalBookDto ๋กœ ๋ณ€ํ™˜ + .block(); // ๋น„๋™๊ธฐ ํ˜ธ์ถœ์„ ๋™๊ธฐ์ ์œผ๋กœ ์ฒ˜๋ฆฌ + } +}
Java
UriComponentBuilder ์‚ฌ์šฉ
@@ -0,0 +1,38 @@ +package com.ll.nbe342team8.domain.book.book.service; + +import com.ll.nbe342team8.domain.book.book.dto.ExternalBookDto; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.web.reactive.function.client.WebClient; + +@Service +public class ExternalBookApiService { + + private final WebClient webClient; + private final String ttbkey; + + public ExternalBookApiService(WebClient.Builder webClientBuilder, + @Value("${aladin.ttbkey}") String ttbkey) { + this.webClient = webClientBuilder.baseUrl("http://www.aladin.co.kr/ttb/api/").build(); + this.ttbkey = ttbkey; + } + + public ExternalBookDto searchBook(String isbn13) { + if (isbn13 == null || isbn13.isEmpty()) { + throw new IllegalArgumentException("ISBN13 ๊ฐ’์€ ํ•„์ˆ˜์ž…๋‹ˆ๋‹ค."); + } + + String url = "http://www.aladin.co.kr/ttb/api/ItemLookUp.aspx?" + + "ttbkey=ttbcameogu1634001" // ํ•˜๋“œ์ฝ”๋”ฉ (์ถ”ํ›„์ˆ˜์ •) + + "&itemIdType=ISBN13" + + "&ItemId=" + isbn13 + + "&output=js" + + "&Cover=Big"; + + return webClient.get() + .uri(url) // ํ˜ธ์ถœํ•  URL + .retrieve() // ์‘๋‹ต ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ ธ์˜ด + .bodyToMono(ExternalBookDto.class) // ์‘๋‹ต ๋ฐ์ดํ„ฐ๋ฅผ ExternalBookDto ๋กœ ๋ณ€ํ™˜ + .block(); // ๋น„๋™๊ธฐ ํ˜ธ์ถœ์„ ๋™๊ธฐ์ ์œผ๋กœ ์ฒ˜๋ฆฌ + } +}
Java
Apache Commons StringUtils ์‚ฌ์šฉ์„ ํ•ด ๋ณด์„ธ์š”. `StringUtils.isEmpty(isbn13)`
@@ -1,18 +1,47 @@ package com.ll.nbe342team8.domain.book.category.entity; +import com.ll.nbe342team8.domain.book.book.entity.Book; import com.ll.nbe342team8.global.jpa.entity.BaseEntity; +import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; +import jakarta.persistence.OneToMany; +import jakarta.validation.constraints.NotNull; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; +import java.util.ArrayList; +import java.util.List; + @Entity @Getter @Builder @NoArgsConstructor @AllArgsConstructor public class Category extends BaseEntity { + @NotNull + private Integer categoryId; + + @NotNull + private String categoryName; + + @NotNull + private String mall; + + @NotNull + private String depth1; + + private String depth2; + + private String depth3; + + private String depth4; + + private String depth5; + + @OneToMany(mappedBy = "categoryId", cascade = CascadeType.ALL) + private List<Book> books = new ArrayList<>(); private String category; // ์นดํ…Œ๊ณ ๋ฆฌ ์ข…๋ฅ˜ ex) ๊ตญ๋‚ด๋„์„œ > ๊ฒฝ์ œ/๊ฒฝ์˜ > ์žฌํ…Œํฌ/๊ธˆ์œต > ์žฌํ…Œํฌ > ๋ถ€์ž๋˜๋Š”๋ฒ• }
Java
ํ•ด๋‹น ์นดํ…Œ๊ณ ๋ฆฌ์— ์ฑ…์ด ํ•œ 6๋งŒ๊ฑด ์žˆ๋‹ค๊ณ  ํ•ด ๋ด…์‹œ๋‹ค. ๊ทธ๋Ÿฌ๋ฉด ์นดํ…Œ๊ณ ๋ฆฌ๋ฅผ ์‚ญ์ œํ•˜๊ฒŒ ๋˜๋ฉด ๋ฐ์ดํ„ฐ 6๋งŒ๊ฑด์ด ๊ฐ™์ด ์‚ญ์ œ ๋ ํ…๋ฐ์š”. ์ข€ ๋ถˆ์•ˆ์ •ํ•˜์ง€ ์•Š์„๊นŒ์š”?
@@ -0,0 +1,81 @@ +package com.ll.nbe342team8.domain.book.review.controller; + +import com.ll.nbe342team8.domain.book.book.entity.Book; +import com.ll.nbe342team8.domain.book.book.service.BookService; +import com.ll.nbe342team8.domain.book.review.dto.ReviewResponseDto; +import com.ll.nbe342team8.domain.book.review.entity.Review; +import com.ll.nbe342team8.domain.book.review.service.ReviewService; +import com.ll.nbe342team8.domain.book.review.type.SortType; +import com.ll.nbe342team8.domain.member.member.entity.Member; +import com.ll.nbe342team8.domain.member.member.service.MemberService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequiredArgsConstructor +@Tag(name = "Review", description = "Review API") +@RequestMapping("/reviews") +public class ReviewController { + + private final ReviewService reviewService; + private final BookService bookService; + private final MemberService memberService; + + @GetMapping + @Operation(summary = "์ „์ฒด ๋ฆฌ๋ทฐ ์กฐํšŒ") + public Page<ReviewResponseDto> getAllReviews(@RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "10") int pageSize, + @RequestParam(defaultValue = "CREATE_AT_DESC") SortType sortType) { + Page<Review> reviews = reviewService.getAllReviews(page, pageSize, sortType); + + return reviews.map(ReviewResponseDto::from); + } + + @GetMapping("/{book-id}") + @Operation(summary = "ํŠน์ • ๋„์„œ ๋ฆฌ๋ทฐ ์กฐํšŒ") + public Page<ReviewResponseDto> getReviewsById(@PathVariable("book-id") Long bookId, + @RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "10") int pageSize, + @RequestParam(defaultValue = "CREATE_AT_DESC") SortType sortType) { + Page<Review> reviews = reviewService.getReviewsById(bookId, page, pageSize, sortType); + + return reviews.map(ReviewResponseDto::from); + } + + @DeleteMapping("/{review-id}") + @Operation(summary = "๋ฆฌ๋ทฐ ์‚ญ์ œ") + public void deleteReview(@PathVariable("review-id") Long reviewId) { + reviewService.deleteReview(reviewId); + } + + @PutMapping("/{review-id}") + @Operation(summary = "๋ฆฌ๋ทฐ ์ˆ˜์ •") + public void updateReview(@PathVariable("review-id") Long reviewId, + @RequestParam(name = "content") String content, + @RequestParam(name = "rating") float rating) { + + reviewService.updateReview(reviewId, content, rating); + } + + @PostMapping("/{book-id}/{member-id}") + @Operation(summary = "๋ฆฌ๋ทฐ ๋“ฑ๋ก") + public void createReview(@PathVariable("book-id") Long bookId, + @PathVariable("member-id") Long memberId, + @RequestBody Review req){ + + Book book = bookService.getBookById(bookId); + Member member = memberService.getMemberById(memberId); + + Review review = Review.builder() + .book(book) + .member(member) + .content(req.getContent()) + .rating(req.getRating()) + .build(); + + reviewService.create(review, req.getRating()); + } +}
Java
๋ชจ๋“  Response Code๊ฐ€ 200์ธ๊ฐ€์š”? HttpStatus ์— ๋Œ€ํ•ด ์ž์„ธํžˆ ์•Œ์•„๋ณด๊ณ , ํ•„์š”ํ•œ StatusCode๋ฅผ ์ถ”๊ฐ€ํ•ด ์ฃผ์„ธ์š”.
@@ -0,0 +1,81 @@ +package com.ll.nbe342team8.domain.book.review.controller; + +import com.ll.nbe342team8.domain.book.book.entity.Book; +import com.ll.nbe342team8.domain.book.book.service.BookService; +import com.ll.nbe342team8.domain.book.review.dto.ReviewResponseDto; +import com.ll.nbe342team8.domain.book.review.entity.Review; +import com.ll.nbe342team8.domain.book.review.service.ReviewService; +import com.ll.nbe342team8.domain.book.review.type.SortType; +import com.ll.nbe342team8.domain.member.member.entity.Member; +import com.ll.nbe342team8.domain.member.member.service.MemberService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequiredArgsConstructor +@Tag(name = "Review", description = "Review API") +@RequestMapping("/reviews") +public class ReviewController { + + private final ReviewService reviewService; + private final BookService bookService; + private final MemberService memberService; + + @GetMapping + @Operation(summary = "์ „์ฒด ๋ฆฌ๋ทฐ ์กฐํšŒ") + public Page<ReviewResponseDto> getAllReviews(@RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "10") int pageSize, + @RequestParam(defaultValue = "CREATE_AT_DESC") SortType sortType) { + Page<Review> reviews = reviewService.getAllReviews(page, pageSize, sortType); + + return reviews.map(ReviewResponseDto::from); + } + + @GetMapping("/{book-id}") + @Operation(summary = "ํŠน์ • ๋„์„œ ๋ฆฌ๋ทฐ ์กฐํšŒ") + public Page<ReviewResponseDto> getReviewsById(@PathVariable("book-id") Long bookId, + @RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "10") int pageSize, + @RequestParam(defaultValue = "CREATE_AT_DESC") SortType sortType) { + Page<Review> reviews = reviewService.getReviewsById(bookId, page, pageSize, sortType); + + return reviews.map(ReviewResponseDto::from); + } + + @DeleteMapping("/{review-id}") + @Operation(summary = "๋ฆฌ๋ทฐ ์‚ญ์ œ") + public void deleteReview(@PathVariable("review-id") Long reviewId) { + reviewService.deleteReview(reviewId); + } + + @PutMapping("/{review-id}") + @Operation(summary = "๋ฆฌ๋ทฐ ์ˆ˜์ •") + public void updateReview(@PathVariable("review-id") Long reviewId, + @RequestParam(name = "content") String content, + @RequestParam(name = "rating") float rating) { + + reviewService.updateReview(reviewId, content, rating); + } + + @PostMapping("/{book-id}/{member-id}") + @Operation(summary = "๋ฆฌ๋ทฐ ๋“ฑ๋ก") + public void createReview(@PathVariable("book-id") Long bookId, + @PathVariable("member-id") Long memberId, + @RequestBody Review req){ + + Book book = bookService.getBookById(bookId); + Member member = memberService.getMemberById(memberId); + + Review review = Review.builder() + .book(book) + .member(member) + .content(req.getContent()) + .rating(req.getRating()) + .build(); + + reviewService.create(review, req.getRating()); + } +}
Java
Controller๊ฐ€ ๋˜์—ˆ๋˜ Service๊ฐ€ ๋˜์—ˆ๋˜, Builder ๋กœ์ง์„ ์™ธ๋ถ€์—์„œ ์‚ฌ์šฉํ•˜์ง€ ์•Š์•˜์œผ๋ฉด ์ข‹๊ฒ ์Šต๋‹ˆ๋‹ค. Builder๊ฐ€ ์‹ค์ˆ˜์˜ ์—ฌ์ง€๋ฅผ ์ค„์—ฌ์ฃผ๊ธด ํ•˜์ง€๋งŒ, ์ฝ”๋“œ์˜ ๊ธธ์ด๋ฅผ ์„ธ๋กœ๋กœ ๋Š˜๋ฆฌ๋Š” ๋‹จ์ ์ด ์žˆ๊ณ , Builder๋ฅผ ์„ธํŒ…ํ•˜๋Š” ๋กœ์ง ๋•Œ๋ฌธ์— ๋‹ค๋ฅธ ๋กœ์ง์˜ ๊ฐ€๋…์„ฑ์ด ๋‚˜๋น ์ง€๋Š” ๋‹จ์ ์ด ์žˆ์–ด์š”.
@@ -0,0 +1,22 @@ +package com.ll.nbe342team8.domain.book.review.type; + +import org.springframework.data.domain.Sort; + +public enum SortType { + CREATE_AT_DESC("createDate", Sort.Direction.DESC), // ์ตœ๊ทผ ๋“ฑ๋ก์ˆœ + CREATE_AT_ASC("createDate", Sort.Direction.ASC), // ๊ณผ๊ฑฐ ๋“ฑ๋ก์ˆœ + RATING_DESC("rating", Sort.Direction.DESC), // ํ‰์  ๋†’์€ ์ˆœ + RATING_ASC("rating", Sort.Direction.ASC); // ํ‰์  ๋‚ฎ์€ ์ˆœ + + private final String field; + private final Sort.Direction direction; + + SortType(String field, Sort.Direction direction) { + this.field = field; + this.direction = direction; + } + + public Sort.Order getOrder() { + return new Sort.Order(direction, field); + } +}
Java
๋น„์Šทํ•œ ์ฝ”๋“œ๊ฐ€ ์žˆ๋Š” ๊ฒƒ ๊ฐ™์€๋ฐ์š”, ๋ฌถ์„ ์ˆœ ์—†์„๊นŒ์š”?
@@ -3,83 +3,63 @@ import homeTry.chatting.dto.request.ChattingMessageRequest; import homeTry.chatting.dto.response.ChattingMessageResponse; import homeTry.chatting.exception.badRequestException.InvalidTeamIdException; -import homeTry.chatting.model.entity.Chatting; import homeTry.chatting.repository.ChattingRepository; import homeTry.member.dto.MemberDTO; -import homeTry.team.model.entity.Team; -import homeTry.team.model.entity.TeamMember; -import homeTry.team.repository.TeamRepository; -import homeTry.team.service.TeamMemberService; -import homeTry.team.service.TeamService; -import java.util.List; +import homeTry.team.exception.badRequestException.TeamMemberNotFoundException; +import homeTry.team.model.entity.TeamMemberMapping; +import homeTry.team.service.TeamMemberMappingService; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Slice; -import org.springframework.data.domain.SliceImpl; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service public class ChattingService { - private final TeamService teamService; - private final TeamMemberService teamMemberService; + private final TeamMemberMappingService teamMemberMappingService; private final ChattingRepository chattingRepository; - private final TeamRepository teamRepository; - public ChattingService(TeamService teamService, - TeamMemberService teamMemberService, ChattingRepository chattingRepository, - TeamRepository teamRepository) { - this.teamService = teamService; - this.teamMemberService = teamMemberService; + + public ChattingService(ChattingRepository chattingRepository, TeamMemberMappingService teamMemberMappingService) { this.chattingRepository = chattingRepository; - this.teamRepository = teamRepository; + this.teamMemberMappingService = teamMemberMappingService; } @Transactional public ChattingMessageResponse saveChattingMessage(Long teamId, ChattingMessageRequest chattingMessageRequest, MemberDTO memberDTO) { - //todo: teamService์—์„œ get Team entity ๊ตฌํ˜„ํ•˜๋ฉด ๋ฆฌํŒฉํ„ฐ๋ง ํ•˜๊ธฐ - Team team = teamRepository.findById(teamId).orElseThrow(InvalidTeamIdException::new); - - List<TeamMember> teamMembers = teamMemberService.getTeamMember(team); + TeamMemberMapping teamMemberMapping; - // ํ•ด๋‹น ๋ฉค๋ฒ„ ID์™€ ์ผ์น˜ํ•˜๋Š” TeamMember ๊ฐ์ฒด ์ฐพ๊ธฐ - TeamMember teamMember = teamMembers.stream() - .filter(tm -> tm.getMember().getId().equals(memberDTO.id())) - .findFirst() - .orElseThrow(InvalidTeamIdException::new); + try { + teamMemberMapping = teamMemberMappingService.getTeamMemberMappingById(teamId, memberDTO.id()); + } catch (TeamMemberNotFoundException e) { + throw new InvalidTeamIdException(); + } return ChattingMessageResponse.from( - chattingRepository.save(chattingMessageRequest.toEntity(teamMember))); + chattingRepository.save(chattingMessageRequest.toEntity(teamMemberMapping))); } @Transactional(readOnly = true) public Slice<ChattingMessageResponse> getChattingMessageSlice(Long teamId, MemberDTO memberDTO, Pageable pageable) { - Team team = teamRepository.findById(teamId).orElseThrow(InvalidTeamIdException::new); //์ž˜๋ชป๋œ teamId ๋ฐฉ์ง€ - //todo : getTeamMember(team, member) ๊ตฌํ˜„ํ•˜๊ธฐ - teamMemberService.getTeamMember(team).stream() - .filter(tm -> tm.getMember().getId().equals(memberDTO.id())) - .findFirst() - .orElseThrow(InvalidTeamIdException::new); - - Slice<Chatting> chattingMessageSlice = chattingRepository.findByTeamMemberTeam(team, - pageable); - - List<ChattingMessageResponse> chattingMessageResponseList = chattingMessageSlice.getContent() - .stream() - .map(ChattingMessageResponse::from) - .toList(); - - return new SliceImpl<>(chattingMessageResponseList, chattingMessageSlice.getPageable(), - chattingMessageSlice.hasNext()); - + try { + teamMemberMappingService.getTeamMemberMappingById(teamId, memberDTO.id()); + } catch (TeamMemberNotFoundException e) { + throw new InvalidTeamIdException(); + } + + return chattingRepository.findByTeamMemberMappingTeamId(teamId, pageable) + .map(ChattingMessageResponse::from); } - -} + @Transactional + public void deleteChattingMessageAll(Long teamId) { + chattingRepository.deleteAllByTeamMemberMappingTeamId(teamId); + } +} \ No newline at end of file
Java
Chatting์€ TeamMember์™€ ์—ฐ๊ด€๊ด€๊ณ„๋ฅผ ๋งบ๊ณ  ์žˆ์œผ๋‹ˆ, TeamMember์— ๋Œ€ํ•œ ์ •๋ณด๋งŒ์„ ์•Œ๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. Chatting์—์„œ Team ๋˜๋Š” Member์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ ์–ป๊ณ ์ž ํ•œ๋‹ค๋ฉด,, TeamMemberService๋ฅผ ๋‹จ์ผ ์ง„์ž…์ ์œผ๋กœ ํ™œ์šฉํ•˜๋ฉด ์–ด๋–จ๊นŒ์š”? ๐Ÿ˜ฒ
@@ -1,8 +1,12 @@ package homeTry.chatting.interceptor; +import homeTry.chatting.exception.badRequestException.InactivatedMemberWithValidTokenException; import homeTry.chatting.exception.badRequestException.InvalidChattingTokenException; -import homeTry.common.auth.JwtAuth; +import homeTry.chatting.exception.badRequestException.NoSuchMemberInDbWithValidTokenException; +import homeTry.common.auth.jwt.JwtAuth; import homeTry.member.dto.MemberDTO; +import homeTry.member.exception.badRequestException.InactivatedMemberException; +import homeTry.member.exception.badRequestException.MemberNotFoundException; import homeTry.member.service.MemberService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.Message; @@ -14,6 +18,7 @@ @Component public class StompInterceptor implements ChannelInterceptor { + private final JwtAuth jwtAuth; private final MemberService memberService; @@ -29,23 +34,27 @@ public Message<?> preSend(Message<?> message, MessageChannel channel) { StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message); handleConnectCommand(accessor); - //todo: ์ถ”ํ›„ ๋‹ค๋ฅธ ์ผ€์ด์Šค ์ถ”๊ฐ€ํ•˜๊ธฐ + //์ถ”ํ›„ ๋‹ค๋ฅธ ์ผ€์ด์Šค ์žˆ๋‹ค๋ฉด ์ถ”๊ฐ€ํ•˜๊ธฐ return message; } private void handleConnectCommand(StompHeaderAccessor accessor) { if (accessor.getCommand() == StompCommand.CONNECT) { - String token = String.valueOf(accessor.getNativeHeader("Authorization").getFirst()); - if (token == null || !token.startsWith("Bearer ")) + MemberDTO memberDTO; + + try { + String token = String.valueOf(accessor.getNativeHeader("Authorization").getFirst()) + .substring(7); // Expect after B e a r e r _ + + memberDTO = memberService.getMember(jwtAuth.extractId(token)); + } catch (MemberNotFoundException e) { + throw new NoSuchMemberInDbWithValidTokenException(); + } catch (InactivatedMemberException e) { + throw new InactivatedMemberWithValidTokenException(); + } catch (Exception e) { throw new InvalidChattingTokenException(); - - token = token.substring(7); - - if (!jwtAuth.validateToken(token)) - throw new InvalidChattingTokenException(); - - MemberDTO memberDTO = memberService.getMember(jwtAuth.extractId(token)); + } //์„ธ์…˜์— ์ €์žฅ accessor.getSessionAttributes().put("member", memberDTO);
Java
StompInterceptor๋Š” ํ† ํฐ ์ •๋ณด๋ฅผ ๋ณด๊ณ , ๋ฉค๋ฒ„๊ฐ€ ์กด์žฌํ•˜์ง€ ์•Š์œผ๋ฉด,, Exception์„ ๋ฑ‰๋„๋ก ํ•˜๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ๊ทธ๋ ‡๋‹ค๋ฉด, stompInterceptor๋Š” ํ† ํฐ์ด bearerToken์ธ์ง€, ๋‹ค๋ฅธ ํ† ํฐ์˜ ์ข…๋ฅ˜์ธ์ง€? ์— ๋Œ€ํ•ด์„œ๋Š” ์•„๋ฌด๋Ÿฐ ๊ด€์‹ฌ์‚ฌ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. BearerToken์ด ์œ ํšจํ•œ์ง€? ๋„ ๊ด€์‹ฌ์‚ฌ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. ๋‹จ์ˆœํžˆ ํ˜„์žฌ interceptor์— ๋„˜์–ด์˜จ ํ† ํฐ ์ •๋ณด๋ฅผ ๋ณด๊ณ , ์šฐ๋ฆฌ ์‚ฌ์šฉ์ž๋ผ๋ฉด ์„ธ์…˜์— ๊ทธ ๊ฐ’์„ ๋„ฃ๋Š” ๊ฒƒ์— ๊ด€์‹ฌ์ด ์žˆ์Šต๋‹ˆ๋‹ค. ์ด๋ ‡๊ฒŒ ๊ฐ ํด๋ž˜์Šค์˜ ๊ด€์‹ฌ์‚ฌ๋“ค์„ ์ƒ๊ฐํ•˜๋ฉฐ ์ ์ ˆํ•˜๊ฒŒ ๋ถ„๋ฆฌํ•˜๊ณ , ์บก์Аํ™” ํ•ด๋ณด์‹œ๋ฉด ์žฌ๋ฏธ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š” ๐Ÿ˜„
@@ -1,7 +1,20 @@ package lotto; +import lotto.config.Configuration; +import lotto.controller.BuyLottoController; +import lotto.controller.LottoController; +import lotto.dto.BuyLottoDto; + public class Application { public static void main(String[] args) { - // TODO: ํ”„๋กœ๊ทธ๋žจ ๊ตฌํ˜„ + Configuration configuration = new Configuration(); + LottoController lottoController = configuration.getLottoController(); + BuyLottoController buyLottoController = configuration.getBuyLottoController(); + executeControllers(buyLottoController, lottoController); + } + + private static void executeControllers(BuyLottoController buyLottoController, LottoController lottoController) { + BuyLottoDto buyLottoDto = buyLottoController.buyLotto(); + lottoController.getStatistics(buyLottoDto); } }
Java
ํ˜„์žฌ ์ž‘์„ฑํ•˜์‹  controller์™€ service๋ฅผ ๋ชจ๋‘ applicationํด๋ž˜์Šค์—์„œ ์ƒ์„ฑํ•˜๋„๋ก ๊ตฌํ˜„ํ•˜์‹ ๊ฒƒ๊ฐ™์€๋ฐ ์šฐ์•„ํ•œํ…Œํฌ์ฝ”์Šค 3์ฃผ์ฐจ ๊ณตํ†ต ํ”ผ๋“œ๋ฐฑ์„ ๋ณด์‹œ๋ฉด, > ํ•จ์ˆ˜(๋ฉ”์„œ๋“œ) ๋ผ์ธ์— ๋Œ€ํ•œ ๊ธฐ์ค€ ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์š”๊ตฌ์‚ฌํ•ญ์„ ๋ณด๋ฉด ํ•จ์ˆ˜ 15๋ผ์ธ์œผ๋กœ ์ œํ•œํ•˜๋Š” ์š”๊ตฌ์‚ฌํ•ญ์ด ์žˆ๋‹ค. ์ด ๊ธฐ์ค€์€ main() ํ•จ์ˆ˜์—๋„ ํ•ด๋‹น๋œ๋‹ค. ๊ณต๋ฐฑ ๋ผ์ธ๋„ ํ•œ ๋ผ์ธ์— ํ•ด๋‹นํ•œ๋‹ค. 15๋ผ์ธ์ด ๋„˜์–ด๊ฐ„๋‹ค๋ฉด ํ•จ์ˆ˜ ๋ถ„๋ฆฌ๋ฅผ ์œ„ํ•œ ๊ณ ๋ฏผ์„ ํ•œ๋‹ค. ๋ผ๊ณ  ์ œ์‹œ๋˜์–ด์žˆ์–ด์š”. ๋งŒ์•ฝ ์ดํ›„ controller์™€ service, repository๊นŒ์ง€ ๋งŽ์•„์ง€๊ฒŒ ๋˜๋Š” ํ”„๋กœ๊ทธ๋žจ์ด๋ผ๋ฉด ์œ„ ์š”๊ตฌ์‚ฌํ•ญ์„ ์–ด๊ธฐ๊ฒŒ ๋ ๊ฒƒ๊ฐ™์€๋ฐ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹ค๊นŒ์š”??
@@ -0,0 +1,34 @@ +package lotto.model; + +import static lotto.constant.Constant.THOUSAND; +import static lotto.constant.Constant.ZERO; +import static lotto.exception.ErrorInputException.ErrorMessage.PURCHASE_PRICE_CAN_DIVIDE_BY_THOUSAND; + +import lotto.exception.ErrorInputException; + +public class PurchasePrice { + private final int price; + + private PurchasePrice(int price) { + this.price = price; + isDividedByThousand(); + } + + public static PurchasePrice createPurchasePrice(int price) { + return new PurchasePrice(price); + } + + public int getPrice() { + return price; + } + + private void isDividedByThousand() { + if (price % THOUSAND != ZERO) { + throw new ErrorInputException(PURCHASE_PRICE_CAN_DIVIDE_BY_THOUSAND); + } + } + + public int calculateLottoCount() { + return price / THOUSAND; + } +}
Java
calculateLottoCount๋ฅผ ํ˜ธ์ถœํ• ๋•Œ๋งˆ๋‹ค ๊ตฌ์ž…๊ฐ€๊ฒฉ์—์„œ 1000์„ ๋‚˜๋ˆŒํ…๋ฐ ์ด๋ ‡๊ฒŒ ํ•˜์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!!
@@ -0,0 +1,57 @@ +package lotto.model; + +import static lotto.constant.Constant.ZERO; + +import java.util.Collections; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import lotto.constant.Rank; + +public class Statistics { + private final Map<Rank, Integer> result; + + private Statistics() { + result = new EnumMap<>(Rank.class); + for (Rank rank : Rank.values()) { + result.put(rank, ZERO); + } + } + + public static Statistics createStatistics() { + return new Statistics(); + } + + public Map<Rank, Integer> getResult() { + return Collections.unmodifiableMap(result); + } + + public void calculateMatching(LottoNumbers lottoNumbers, WinnerNumber winnerNumber, BonusNumber bonusNumber) { + List<Lotto> lottos = lottoNumbers.getNumbers(); + + for (Lotto lotto : lottos) { + Rank rank = findRank(lotto, winnerNumber, bonusNumber); + int lottoCount = result.get(rank) + 1; + + result.put(rank, lottoCount); + } + } + + private Rank findRank(Lotto lotto, WinnerNumber winnerNumber, BonusNumber bonusNumber) { + long winnerMatch = countMatchingWinnerNumber(lotto, winnerNumber); + boolean bonusMatch = matchingBonusNumber(lotto, bonusNumber); + + return Rank.findRank(winnerMatch, bonusMatch); + } + + private boolean matchingBonusNumber(Lotto lotto, BonusNumber bonusNumber) { + return lotto.getNumbers().stream() + .anyMatch(number -> number.equals(bonusNumber.isSameBonusNumber(bonusNumber))); + } + + private long countMatchingWinnerNumber(Lotto lotto, WinnerNumber winnerNumber) { + return lotto.getNumbers().stream() + .filter(winnerNumber.getWinnerNumbers()::contains) + .count(); + } +}
Java
int๋กœ ์„ ์–ธํ•˜์…”๋„ ๋์„ํ…๋ฐ long์œผ๋กœ ์„ ์–ธํ•˜์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,40 @@ +package lotto.dto; + +import lotto.model.BonusNumber; +import lotto.model.LottoNumbers; +import lotto.model.PurchasePrice; +import lotto.model.Statistics; +import lotto.model.WinnerNumber; + +public class BuyLottoDto { + private PurchasePrice purchasePrice; + private LottoNumbers lottoNumbers; + private WinnerNumber winnerNumber; + private BonusNumber bonusNumber; + + private BuyLottoDto(PurchasePrice purchasePrice, LottoNumbers lottoNumbers, WinnerNumber winnerNumber, + BonusNumber bonusNumber) { + this.purchasePrice = purchasePrice; + this.lottoNumbers = lottoNumbers; + this.winnerNumber = winnerNumber; + this.bonusNumber = bonusNumber; + } + + public static BuyLottoDto createBuyLottoDto(PurchasePrice purchasePrice, + LottoNumbers lottoNumbers, + WinnerNumber winnerNumber, + BonusNumber bonusNumber) { + return new BuyLottoDto(purchasePrice, lottoNumbers, winnerNumber, bonusNumber); + } + + public PurchasePrice getPurchasePrice() { + return purchasePrice; + } + + public Statistics calculateMatching() { + Statistics statistics = Statistics.createStatistics(); + statistics.calculateMatching(this.lottoNumbers, this.winnerNumber, this.bonusNumber); + return statistics; + } + +}
Java
ํ˜„์žฌ calculateMatching๋ฉ”์†Œ๋“œ๋Š” statics๋„๋ฉ”์ธ์— ์ ‘๊ทผํ•˜๊ธฐ ์œ„ํ•œ ๋ฉ”์†Œ๋“œ๋กœ ๋ณด์—ฌ์ง‘๋‹ˆ๋‹ค! service๊ณ„์ธต์ด ์žˆ๋Š” ์ด์œ ๋Š”, ํ”„๋ ˆ์  ํ…Œ์ด์…˜ ๊ณ„์ธต๊ณผ ๋ฐ์ดํ„ฐ ์—‘์„ธ์Šค ๊ณ„์ธต ์‚ฌ์ด๋ฅผ ์—ฐ๊ฒฐํ•˜๊ธฐ ์œ„ํ•จ์ด์ฃ !! ๋”ฐ๋ผ์„œ ์ด ๋ถ€๋ถ„์€ service์ชฝ์—์„œ ๊ตฌํ˜„๋˜์–ด์•ผํ•œ๋‹ค๊ณ  ์ƒ๊ฐํ•ด์š”!
@@ -0,0 +1,57 @@ +package lotto.model; + +import static lotto.constant.Constant.ZERO; + +import java.util.Collections; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import lotto.constant.Rank; + +public class Statistics { + private final Map<Rank, Integer> result; + + private Statistics() { + result = new EnumMap<>(Rank.class); + for (Rank rank : Rank.values()) { + result.put(rank, ZERO); + } + } + + public static Statistics createStatistics() { + return new Statistics(); + } + + public Map<Rank, Integer> getResult() { + return Collections.unmodifiableMap(result); + } + + public void calculateMatching(LottoNumbers lottoNumbers, WinnerNumber winnerNumber, BonusNumber bonusNumber) { + List<Lotto> lottos = lottoNumbers.getNumbers(); + + for (Lotto lotto : lottos) { + Rank rank = findRank(lotto, winnerNumber, bonusNumber); + int lottoCount = result.get(rank) + 1; + + result.put(rank, lottoCount); + } + } + + private Rank findRank(Lotto lotto, WinnerNumber winnerNumber, BonusNumber bonusNumber) { + long winnerMatch = countMatchingWinnerNumber(lotto, winnerNumber); + boolean bonusMatch = matchingBonusNumber(lotto, bonusNumber); + + return Rank.findRank(winnerMatch, bonusMatch); + } + + private boolean matchingBonusNumber(Lotto lotto, BonusNumber bonusNumber) { + return lotto.getNumbers().stream() + .anyMatch(number -> number.equals(bonusNumber.isSameBonusNumber(bonusNumber))); + } + + private long countMatchingWinnerNumber(Lotto lotto, WinnerNumber winnerNumber) { + return lotto.getNumbers().stream() + .filter(winnerNumber.getWinnerNumbers()::contains) + .count(); + } +}
Java
์žฌํ˜„๋‹˜ ๋•๋ถ„์— EnumMap์— ๋Œ€ํ•ด์„œ ์ฒ˜์Œ์œผ๋กœ ๋ฐฐ์› ๋„ค์š”!! ใ…Žใ…ŽEnumMap์ด ํ•ด์‹œ์ถฉ๋Œ์„ ์•ˆ์ผ์œผํ‚จ๋‹ค๋Š”๋ฐ ๋•๋ถ„์— ๋ฐฐ์›Œ๊ฐ‘๋‹ˆ๋‹ค!!