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 | 
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 | ๋ก์ง์ ๋ฌธ์ ๊ฐ ์๋๊ฒ ๊ฐ์์ ๐
์ฐ์น์๊ฐ ๋๋ฒ ์ถ๋ ฅ๋๊ณ ์์ต๋๋ค
 |
@@ -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์ด ํด์์ถฉ๋์ ์์ผ์ผํจ๋ค๋๋ฐ ๋๋ถ์ ๋ฐฐ์๊ฐ๋๋ค!! |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.