code
stringlengths
41
34.3k
lang
stringclasses
8 values
review
stringlengths
1
4.74k
@@ -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
๊ฐ์Œ€ํ•„์š” ์—†์Œ
@@ -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 ๋ณ€์ˆ˜์˜ ์ด๋ฆ„์ด ๋„ˆ๋ฌด ๊ธธ๊ณ  ๋ชจํ˜ธํ•ฉ๋‹ˆ๋‹ค. ๋” ์งง๊ณ  ๋ช…ํ™•ํ•˜๊ฒŒ ์ •์˜ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
@@ -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์— ๋„˜์–ด์˜จ ํ† ํฐ ์ •๋ณด๋ฅผ ๋ณด๊ณ , ์šฐ๋ฆฌ ์‚ฌ์šฉ์ž๋ผ๋ฉด ์„ธ์…˜์— ๊ทธ ๊ฐ’์„ ๋„ฃ๋Š” ๊ฒƒ์— ๊ด€์‹ฌ์ด ์žˆ์Šต๋‹ˆ๋‹ค. ์ด๋ ‡๊ฒŒ ๊ฐ ํด๋ž˜์Šค์˜ ๊ด€์‹ฌ์‚ฌ๋“ค์„ ์ƒ๊ฐํ•˜๋ฉฐ ์ ์ ˆํ•˜๊ฒŒ ๋ถ„๋ฆฌํ•˜๊ณ , ์บก์Аํ™” ํ•ด๋ณด์‹œ๋ฉด ์žฌ๋ฏธ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š” ๐Ÿ˜„
@@ -8,51 +8,65 @@ public class Game { public static final String DELIMETER = "-"; + + public static final String CAR_NAME_DELIMETER = ","; + private int gameCount; + private Car[] cars; public void start() { - cars = createCar(); + + cars = createCar(); + gameCount = getGameCount(); System.out.println("์‹คํ–‰ ๊ฒฐ๊ณผ"); for (int i = 0; i < gameCount; i++) { job(); } + Winner winner = new Winner(); + System.out.println(FormattingUtil.formattingResult(winner.getWinners(cars)) + "๊ฐ€ ์ตœ์ข… ์šฐ์Šนํ–ˆ์Šต๋‹ˆ๋‹ค."); + } private void job() { for (Car car : this.cars) { car.drive(car.getNumber(), DELIMETER); - System.out.println(car.getStatus()); + System.out.println(car.getName() + ":" + car.getStatus()); } System.out.println(" "); } private int getGameCount() { Scanner scanner = new Scanner(System.in); System.out.println("์‹œ๋„ํ•  ํšŒ์ˆ˜๋Š” ๋ช‡ ํšŒ ์ธ๊ฐ€์š”?"); + int gameCount = scanner.nextInt(); - System.out.println("gameCount = " + gameCount); + System.out.println(gameCount); + return gameCount; } private Car[] createCar() { - int carCount = getCarCount(); - Car[] cars = new Car[carCount]; - for (int i = 0; i < carCount; i++) { - cars[i] = new SmallCar(); + String[] carNameInputArr = getCarNameInputArr(); + int length = carNameInputArr.length; + Car[] cars = new Car[length]; + for (int i = 0; i < length; i++) { + cars[i] = new SmallCar(carNameInputArr[i]); + } return cars; } - private int getCarCount() { - System.out.println("์ž๋™์ฐจ ๋Œ€์ˆ˜๋Š” ๋ช‡ ๋Œ€ ์ธ๊ฐ€์š”?"); + + private String[] getCarNameInputArr() { + System.out.println("๊ฒฝ์ฃผํ•  ์ž๋™์ฐจ ์ด๋ฆ„์„ ์ž…๋ ฅํ•˜์„ธ์š”(์ด๋ฆ„์€ " + CAR_NAME_DELIMETER + "๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๊ตฌ๋ถ„)."); Scanner scanner = new Scanner(System.in); - int carCount = Integer.parseInt(scanner.nextLine()); - System.out.println("์ž๋™์ฐจ ๋Œ€์ˆ˜ = " + carCount); - return carCount; + String carNameInput = scanner.nextLine(); + System.out.println(carNameInput); + return carNameInput.split(CAR_NAME_DELIMETER); } public Car[] getCars() {
Java
![image](https://github.com/next-step/java-racingcar/assets/27044096/d221b9bf-2cb7-4dcb-bafa-016f49e445a2) d, e ๊ฐ€ ์šฐ์Šนํ–ˆ๋Š”๋ฐ ์ œ๋Œ€๋กœ ์ถœ๋ ฅ๋˜๊ณ ์žˆ์ง€ ์•Š๋„ค์š” ๐Ÿ˜…
@@ -0,0 +1,25 @@ +import java.util.List; + +/** + * @author jeongheekim + * @date 3/27/24 + */ +public class FormattingUtil { + private FormattingUtil() {} + + public static String formattingResult(List<String> list) { + StringBuilder sb = new StringBuilder(); + int size = list.size(); + for (int i = 0; i < size; i++) { + sb.append(list.get(i)); + addComma(i, size, sb); + } + return sb.toString(); + } + + private static void addComma(int i, int size, StringBuilder sb) { + if (i < size - 1) { + sb.append(","); + } + } +}
Java
> ๊ทœ์น™ 1: ํ•œ ๋ฉ”์„œ๋“œ์— ์˜ค์ง ํ•œ ๋‹จ๊ณ„์˜ ๋“ค์—ฌ์“ฐ๊ธฐ(indent)๋งŒ ํ•œ๋‹ค. indent๊ฐ€ 2์ด์ƒ์ธ ๋ฉ”์†Œ๋“œ์˜ ๊ฒฝ์šฐ ๋ฉ”์†Œ๋“œ๋ฅผ ๋ถ„๋ฆฌํ•˜๋ฉด indent๋ฅผ ์ค„์ผ ์ˆ˜ ์žˆ๋‹ค. else๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š์•„ indent๋ฅผ ์ค„์ผ ์ˆ˜ ์žˆ๋‹ค. ์ธ๋ดํŠธ๊ฐ€ 2์ด์ƒ์ด๊ตฐ์š” ๐Ÿค”
@@ -0,0 +1,47 @@ +import java.util.ArrayList; +import java.util.List; + +/** + * @author jeongheekim + * @date 3/26/24 + */ +public class Winner { + private List<String> winners = new ArrayList<>(); + private int maxLength; + + public void addWinner(String name) { + this.winners.add(name); + } + + public void updateMaxLength(int length) { + this.maxLength = length; + } + + public List<String> getWinners(Car[] cars) { + this.filterMaxLength(cars); + for (Car car : cars) { + this.checkWinnerCondition(car); + } + return this.winners; + } + + private void filterMaxLength (Car[] cars) { + for (Car car : cars) { + int carStatusLength = car.getStatus().length(); + this.compareMaxLength(carStatusLength); + } + } + + private void compareMaxLength(int carStatusLength) { + if (this.maxLength <= carStatusLength) { + this.updateMaxLength(carStatusLength); + } + } + + private void checkWinnerCondition(Car car) { + int statusLength = car.getStatus().length(); + if (this.maxLength <= statusLength) { + this.addWinner(car.getName()); + } + } +}
Java
๋กœ์ง์— ๋ฌธ์ œ๊ฐ€ ์žˆ๋Š”๊ฒƒ ๊ฐ™์•„์š” ๐Ÿ˜… ์šฐ์Šน์ž๊ฐ€ ๋‘๋ฒˆ ์ถœ๋ ฅ๋˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค ![image](https://github.com/next-step/java-racingcar/assets/27044096/b9f03caf-3eb4-4243-b500-48b046458145)
@@ -0,0 +1,47 @@ +import java.util.ArrayList; +import java.util.List; + +/** + * @author jeongheekim + * @date 3/26/24 + */ +public class Winner { + private List<String> winners = new ArrayList<>(); + private int maxLength; + + public void addWinner(String name) { + this.winners.add(name); + } + + public void updateMaxLength(int length) { + this.maxLength = length; + } + + public List<String> getWinners(Car[] cars) { + this.filterMaxLength(cars); + for (Car car : cars) { + this.checkWinnerCondition(car); + } + return this.winners; + } + + private void filterMaxLength (Car[] cars) { + for (Car car : cars) { + int carStatusLength = car.getStatus().length(); + this.compareMaxLength(carStatusLength); + } + } + + private void compareMaxLength(int carStatusLength) { + if (this.maxLength <= carStatusLength) { + this.updateMaxLength(carStatusLength); + } + } + + private void checkWinnerCondition(Car car) { + int statusLength = car.getStatus().length(); + if (this.maxLength <= statusLength) { + this.addWinner(car.getName()); + } + } +}
Java
์ž๋™์ฐจ์˜ ๊ธธ์ด๋ฅผ ๊บผ๋‚ด์–ด ์ฒ˜๋ฆฌํ•˜๊ณ  ์žˆ๋„ค์š”! ๋””๋ฏธํ„ฐ ๋ฒ•์น™์— ์–ด๊ธ‹๋‚˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค ๋ฉ”์„ธ์ง€๋ฅผ ๋ณด๋‚ด์–ด ์ฒ˜๋ฆฌํ•ด๋ณด๋Š”๊ฑด ์–ด๋–จ๊นŒ์š”? ๐Ÿค” https://mangkyu.tistory.com/147
@@ -1,7 +1,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์ด ํ•ด์‹œ์ถฉ๋Œ์„ ์•ˆ์ผ์œผํ‚จ๋‹ค๋Š”๋ฐ ๋•๋ถ„์— ๋ฐฐ์›Œ๊ฐ‘๋‹ˆ๋‹ค!!
@@ -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
์Œ.. ๋งž์•„์š” ์ €๋„ ์ด ๋ถ€๋ถ„์ด ๋งŽ์ด ๊ฑธ๋ ธ์–ด์š”. ํ•˜์ง€๋งŒ ๋ชจ๋“ˆํ™” ํ•˜๋ฉด ํ•  ์ˆ˜๋ก Application์—์„œ ์ƒ์„ฑํ•ด์ค˜์•ผ ํ•˜๋Š”๊ฒŒ ๋งŽ์•„์ ธ์„œ ๊ณ ๋ฏผ์ด ๋์–ด์š”... ๋‹ค์Œ์—๋Š” controller๋งŒ ์˜์กดํ•˜๊ฒŒ๋” ์ˆ˜์ •ํ•ด๋ด์•ผ๊ฒ ์–ด์š”!!
@@ -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)๋กœ ๋งŒ๋“ค์—ˆ์Šต๋‹ˆ๋‹ค! ๋“ฃ๊ณ ๋ณด๋‹ˆ ๋งŒ์•ฝ ๋กœ๋˜ ๊ฐ€๊ฒฉ์ด ๋ฐ”๋€Œ๊ฒŒ ๋œ๋‹ค๋ฉด ๋‚˜๋ˆ„๋Š” ๊ฐ€๊ฒฉ์„ ์ˆ˜์ •ํ•ด์•ผ ํ•˜๋‹ˆ `THOSAND` ๋Œ€์‹  `LOTTOPRICE`๋กœ ๋ฐ”๋€Œ๋Š”๊ฒŒ ์ข‹๊ฒ ๊ตฐ์š”!
@@ -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
`countMatchingWinnerNumber()` ํ•จ์ˆ˜์—์„œ stream์„ ์“ฐ๋‹ค๋ณด๋‹ˆ return ๊ฐ’์ด long์ด ๋˜์—ˆ์–ด์š”! long์ด๋“  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
๋งž์•„์š”! ์ด ๋กœ์ง์€ service์— ๋ฐฐ์น˜ํ•˜๋Š”๊ฒŒ ๋” ์ ์ ˆํ•  ๊ฒƒ ๊ฐ™๊ตฐ์š”! ๐Ÿ‘
@@ -0,0 +1,109 @@ +package christmas.controller; + +import christmas.domain.Date; +import christmas.domain.EventBadge; +import christmas.domain.Orders; +import christmas.domain.discount.DDayStrategy; +import christmas.domain.discount.Discount; +import christmas.domain.discount.GiftStrategy; +import christmas.domain.discount.SpecialStrategy; +import christmas.domain.discount.WeekdayStrategy; +import christmas.domain.discount.WeekendStrategy; +import christmas.exception.InputException; +import christmas.util.CurrencyUtil; +import christmas.view.InputView; +import christmas.view.OutputView; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Supplier; + +public class PromotionController { + + + public void run() { + OutputView.printGreeting(); + + Date date = initVisitDate(); + Orders orders = initOrders(); + + displayPreviewForEvent(date, orders); + } + + private void displayPreviewForEvent(Date date, Orders orders) { + OutputView.printPreviewTitle(date.getDay()); + OutputView.printOrderedMenu(orders.getStringOrders()); + displayTotalBeforeDiscount(orders); + displayDiscountDetails(date, orders); + } + + private void displayDiscountDetails(Date date, Orders orders) { + Discount discount = applyDiscount(date, orders); + + OutputView.printGiftMenu(discount.getStringGiftMenu()); + OutputView.printBenefitHistory(discount.getDetailedEventHistory()); + + int totalBenefitAmount = discount.getTotalBenefitAmount(); + displayTotalBenefitAmount(totalBenefitAmount); + displayDiscountedTotal(orders, discount); + + displayEventBadge(totalBenefitAmount); + } + + private void displayEventBadge(int totalBenefitAmount) { + EventBadge eventBadge = EventBadge.getEventBadge(totalBenefitAmount); + OutputView.printEventBadge(eventBadge.getName()); + } + + private void displayDiscountedTotal(Orders orders, Discount discount) { + String amount = CurrencyUtil.formatToKor( + orders.calculateTotalBeforeDiscount() + discount.getTotalDiscountAmount()); + OutputView.printDiscountedTotal(amount); + } + + private void displayTotalBenefitAmount(int totalBenefitAmount) { + String totalBenefit = CurrencyUtil.formatToKor(totalBenefitAmount); + OutputView.printTotalBenefit(totalBenefit); + } + + private void displayTotalBeforeDiscount(Orders orders) { + String totalAmount = CurrencyUtil.formatToKor(orders.calculateTotalBeforeDiscount()); + OutputView.printTotalBeforeDiscount(totalAmount); + } + + private Discount applyDiscount(Date date, Orders orders) { + Discount discount = new Discount(List.of( + new DDayStrategy(), + new WeekdayStrategy(), + new WeekendStrategy(), + new SpecialStrategy(), + new GiftStrategy()), + date + ); + discount.checkEvent(orders); + + return discount; + } + + private Orders initOrders() { + return wrapByLoop(() -> { + Orders orders = new Orders(new ArrayList<>()); + orders.createOrder(InputView.getMenu()); + + return orders; + }); + } + + private Date initVisitDate() { + return wrapByLoop(() -> Date.from(InputView.getDate())); + } + + private <T> T wrapByLoop(Supplier<T> supplier) { + while (true) { + try { + return supplier.get(); + } catch (InputException exception) { + System.out.println(exception.getMessage()); + } + } + } +}
Java
์ปจํŠธ๋กค๋Ÿฌ๋‹จ์—์„œ ํ•˜๋Š”๊ฒƒ๋„ ๊ดœ์ฐฎ์ง€๋งŒ ํ•ด๋‹น ๋„๋ฉ”์ธ ๋กœ์ง์œผ๋กœ ๊ฐ€์ ธ๊ฐ€๋Š” ๊ฒƒ๋„ ์ข‹์•„๋ณด์—ฌ์š”!
@@ -0,0 +1,48 @@ +package christmas.domain; + +public enum Event { + NONE("์—†์Œ", 0), + CHRISTMAS_D_DAY_DISCOUNT("ํฌ๋ฆฌ์Šค๋งˆ์Šค ๋””๋ฐ์ด ํ• ์ธ", 1_000), + WEEKDAY_DISCOUNT("ํ‰์ผ ํ• ์ธ", 2_023), + WEEKEND_DISCOUNT("์ฃผ๋ง ํ• ์ธ", 2_023), + SPECIAL_DISCOUNT("ํŠน๋ณ„ ํ• ์ธ", 1_000), + GIFT("์ฆ์ • ์ด๋ฒคํŠธ", 25_000); + + private static final int BASE_AMOUNT_PER_DATE = 100; + + private final String name; + private final int amount; + + Event(String name, int amount) { + this.name = name; + this.amount = amount; + } + + public int calculateTotalAmount(int count, Date date) { + if (this.equals(CHRISTMAS_D_DAY_DISCOUNT)) { + return getAmountOfDDayDiscount(date); + } + + if (isOneTimeEvent()) { + return amount; + } + + return count * amount; + } + + public String getName() { + return name; + } + + public int getAmount() { + return amount; + } + + private boolean isOneTimeEvent() { + return this.equals(SPECIAL_DISCOUNT) || this.equals(GIFT); + } + + private int getAmountOfDDayDiscount(Date date) { + return CHRISTMAS_D_DAY_DISCOUNT.amount + (BASE_AMOUNT_PER_DATE * date.daysSince1Day()); + } +}
Java
์ฝ”๋“œ๊ฐ€ ์ฝ๊ธฐ ํŽธํ•ด์š”!
@@ -0,0 +1,57 @@ +package christmas.domain; + +import christmas.exception.ExceptionMessage; +import christmas.exception.InputException; +import java.util.Arrays; + +public enum Menu { + MUSHROOM_CREAM_SOUP("์–‘์†ก์ด์ˆ˜ํ”„", 6_000, FoodType.APPETIZER), + TAPAS("ํƒ€ํŒŒ์Šค", 5_500, FoodType.APPETIZER), + CAESAR_SALAD("์‹œ์ €์ƒ๋Ÿฌ๋“œ", 8_000, FoodType.APPETIZER), + T_BONE_STEAK("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ", 55_000, FoodType.MAIN), + BARBECUE_RIBS("๋ฐ”๋น„ํ๋ฆฝ", 54_000, FoodType.MAIN), + SEAFOOD_PASTA("ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€", 35_000, FoodType.MAIN), + CHRISTMAS_PASTA("ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€", 25_000, FoodType.MAIN), + CHOCOLATE_CAKE("์ดˆ์ฝ”์ผ€์ดํฌ", 15_000, FoodType.DESSERT), + ICE_CREAM("์•„์ด์Šคํฌ๋ฆผ", 5_000, FoodType.DESSERT), + ZERO_COLA("์ œ๋กœ์ฝœ๋ผ", 3_000, FoodType.BEVERAGE), + RED_WINE("๋ ˆ๋“œ์™€์ธ", 60_000, FoodType.BEVERAGE), + CHAMPAGNE("์ƒดํŽ˜์ธ", 25_000, FoodType.BEVERAGE); + + private final String name; + private final int price; + private final FoodType type; + + Menu(String name, int price, FoodType type) { + this.name = name; + this.price = price; + this.type = type; + } + + public static Menu findMenuByName(String name) { + return Arrays.stream(values()) + .filter(value -> value.name.equals(name)) + .findFirst() + .orElseThrow(() -> new InputException(ExceptionMessage.INVALID_ORDER)); + } + + public static boolean isBeverage(String name) { + return findMenuByName(name).type.equals(FoodType.BEVERAGE); + } + + public boolean isDessert() { + return this.type.equals(FoodType.DESSERT); + } + + public boolean isMain() { + return this.type.equals(FoodType.MAIN); + } + + public String getName() { + return name; + } + + public int getPrice() { + return price; + } +}
Java
Menu Enum์— FoodType Enum ์„ ๊ฐ€์ ธ์™€์„œ ์“ฐ์‹œ๋Š” ์˜๋„๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,19 @@ +package christmas.domain.discount; + +import christmas.domain.Date; +import christmas.domain.Event; +import christmas.domain.Orders; +import java.util.List; + +public class GiftStrategy implements DiscountStrategy { + private static final int GIFT_BASE_AMOUNT = 120_000; + + @Override + public List<Event> getShouldApplyEvents(Orders orders, Date date) { + if (orders.calculateTotalBeforeDiscount() >= GIFT_BASE_AMOUNT) { + return List.of(Event.GIFT); + } + + return List.of(Event.NONE); + } +}
Java
์ธํ„ฐํŽ˜์ด์Šค ํ™œ์šฉ ์ข‹๋„ค์š”!
@@ -0,0 +1,4 @@ +package christmas.dto; + +public record OrderParam(String name, int count) { +}
Java
ํ•ด๋‹น record ๊ฐ์ฒด์˜ ์˜๋„๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค!
@@ -0,0 +1,9 @@ +package christmas.exception; + +public class InputException extends IllegalArgumentException { + public static final String PREFIX = "[ERROR] "; + + public InputException(String message) { + super(PREFIX + message); + } +}
Java
์ €๋Š” ํ”„๋กœ๊ทธ๋žจ์—์„œ ๋ฐœ์ƒํ•˜๋Š” ์˜ˆ์™ธ ์ฒ˜๋ฆฌ ๋ฉ”์†Œ๋“œ๋ฅผ ํ•œ ํŒจํ‚ค์ง€์— ๋ชจ์•„์„œ ๊ด€๋ฆฌํ•˜๊ณ  ์žˆ๋Š”๋ฐ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹ค๊นŒ์š”?
@@ -0,0 +1,72 @@ +package christmas.view; + +public class OutputView { + private static final String GREETING = "์•ˆ๋…•ํ•˜์„ธ์š”! ์šฐํ…Œ์ฝ” ์‹๋‹น 12์›” ์ด๋ฒคํŠธ ํ”Œ๋ž˜๋„ˆ์ž…๋‹ˆ๋‹ค."; + private static final String PREVIEW_TITLE = "12์›” %d์ผ์— ์šฐํ…Œ์ฝ” ์‹๋‹น์—์„œ ๋ฐ›์„ ์ด๋ฒคํŠธ ํ˜œํƒ ๋ฏธ๋ฆฌ ๋ณด๊ธฐ!"; + private static final String ORDERED_MENU = "<์ฃผ๋ฌธ ๋ฉ”๋‰ด>"; + private static final String TOTAL_BEFORE_DISCOUNT = "<ํ• ์ธ ์ „ ์ด์ฃผ๋ฌธ ๊ธˆ์•ก>"; + private static final String GIFT_MENU = "<์ฆ์ • ๋ฉ”๋‰ด>"; + private static final String BENEFIT_HISTORY = "<ํ˜œํƒ ๋‚ด์—ญ>"; + private static final String TOTAL_BENEFIT = "<์ดํ˜œํƒ ๊ธˆ์•ก>"; + private static final String DISCOUNTED_TOTAL = "<ํ• ์ธ ํ›„ ์˜ˆ์ƒ ๊ฒฐ์ œ ๊ธˆ์•ก>"; + private static final String EVENT_BADGE = "<12์›” ์ด๋ฒคํŠธ ๋ฐฐ์ง€>"; + + private OutputView() { + } + + public static void printGreeting() { + print(GREETING); + } + + public static void printPreviewTitle(int date) { + print(String.format(PREVIEW_TITLE, date)); + printLineFeed(); + } + + public static void printOrderedMenu(String orders) { + print(ORDERED_MENU); + print(orders); + } + + public static void printTotalBeforeDiscount(String amount) { + print(TOTAL_BEFORE_DISCOUNT); + print(amount); + printLineFeed(); + } + + public static void printGiftMenu(String menu) { + print(GIFT_MENU); + print(menu); + printLineFeed(); + } + + public static void printBenefitHistory(String history) { + print(BENEFIT_HISTORY); + print(history); + } + + public static void printTotalBenefit(String amount) { + print(TOTAL_BENEFIT); + print(amount); + printLineFeed(); + } + + public static void printDiscountedTotal(String amount) { + print(DISCOUNTED_TOTAL); + print(amount); + printLineFeed(); + } + + public static void printEventBadge(String badge) { + print(EVENT_BADGE); + print(badge); + } + + private static void print(String input) { + System.out.println(input); + } + + private static void printLineFeed() { + System.out.println(); + } +}
Java
ํ•ด๋‹น ๋กœ์ง์„ ๊ตณ์ด Enum์œผ๋กœ ๊ด€๋ฆฌํ•˜์ง€ ์•Š์•˜๋Š”๋ฐ๋„ ๊ฐ€๋…์„ฑ์ด ์ •๋ง ์ข‹๋„ค์š”! ์ธ์‚ฌ์ดํŠธ ์–ป์–ด๊ฐ‘๋‹ˆ๋‹ค!
@@ -0,0 +1,171 @@ +package christmas.domain; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatNoException; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import christmas.exception.ExceptionMessage; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Stream; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +class OrdersTest { + @DisplayName("์Œ๋ฃŒ๋งŒ ์ฃผ๋ฌธํ–ˆ์œผ๋ฉด ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•ด์•ผ ํ•œ๋‹ค.") + @ParameterizedTest + @MethodSource("getOnlyBeverages") + void validateOnlyBeverageTest(List<String> orders) { + // given + Orders newOrders = new Orders(new ArrayList<>()); + + // when, then + assertThatThrownBy(() -> newOrders.createOrder(orders)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(ExceptionMessage.ONLY_BEVERAGE_ORDER); + } + + static Stream<List<String>> getOnlyBeverages() { + return Stream.of( + List.of("์ œ๋กœ์ฝœ๋ผ-10"), + List.of("๋ ˆ๋“œ์™€์ธ-2"), + List.of("์ƒดํŽ˜์ธ-1", "๋ ˆ๋“œ์™€์ธ-2"), + List.of("์ œ๋กœ์ฝœ๋ผ-3", "๋ ˆ๋“œ์™€์ธ-3", "์ƒดํŽ˜์ธ-3") + ); + } + + @DisplayName("์Œ๋ฃŒ์™€ ์Œ์‹์„ ๊ฐ™์ด ์ฃผ๋ฌธํ–ˆ์œผ๋ฉด ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•˜์ง€ ์•Š๋Š”๋‹ค.") + @Test + void validateOnlyBeverageWithFoodTest() { + // given + List<String> orders = Arrays.asList("์ œ๋กœ์ฝœ๋ผ-3", "๋ ˆ๋“œ์™€์ธ-3", "์ƒดํŽ˜์ธ-3", "์ดˆ์ฝ”์ผ€์ดํฌ-1"); + Orders newOrders = new Orders(new ArrayList<>()); + + // when, then + assertThatNoException().isThrownBy(() -> newOrders.createOrder(orders)); + } + + @DisplayName("์ค‘๋ณต ๋ฉ”๋‰ด๋ฅผ ์ฃผ๋ฌธํ–ˆ์„ ๊ฒฝ์šฐ ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•ด์•ผ ํ•œ๋‹ค.") + @ParameterizedTest + @MethodSource("getDuplicatedOrders") + void validateDuplicateTest(List<String> orders) { + // given + Orders newOrders = new Orders(new ArrayList<>()); + + // when, then + assertThatThrownBy(() -> newOrders.createOrder(orders)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(ExceptionMessage.INVALID_ORDER); + } + + static Stream<List<String>> getDuplicatedOrders() { + return Stream.of( + List.of("์ƒดํŽ˜์ธ-1", "์ƒดํŽ˜์ธ-9"), + List.of("์•„์ด์Šคํฌ๋ฆผ-2", "ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€-1", "์•„์ด์Šคํฌ๋ฆผ-11"), + List.of("์ œ๋กœ์ฝœ๋ผ-1", "ํƒ€ํŒŒ์Šค-1", "๋ฐ”๋น„ํ๋ฆฝ-2", "์ œ๋กœ์ฝœ๋ผ-1") + ); + } + + @DisplayName("20๊ฐœ ์ดˆ๊ณผ ์ฃผ๋ฌธํ–ˆ์œผ๋ฉด ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•ด์•ผ ํ•œ๋‹ค.") + @ParameterizedTest + @MethodSource("getOverLimitOrders") + void validateOverLimitTest(List<String> orders) { + // given + Orders newOrders = new Orders(new ArrayList<>()); + + // when, then + assertThatThrownBy(() -> newOrders.createOrder(orders)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(ExceptionMessage.OVER_LIMIT_ORDER); + } + + static Stream<List<String>> getOverLimitOrders() { + return Stream.of( + List.of("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ-21"), + List.of("ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€-10", "์‹œ์ €์ƒ๋Ÿฌ๋“œ-11"), + List.of("์ œ๋กœ์ฝœ๋ผ-5", "์ดˆ์ฝ”์ผ€์ดํฌ-5", "๋ฐ”๋น„ํ๋ฆฝ-5", "ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€-5", "ํƒ€ํŒŒ์Šค-1") + ); + } + + @DisplayName("ํ• ์ธ ์ „ ์ด์ฃผ๋ฌธ ๊ธˆ์•ก์„ ๋ฐ˜ํ™˜ํ•ด์•ผ ํ•œ๋‹ค.") + @Test + void calculateTotalBeforeDiscountTest() { + // given + Orders newOrders = new Orders( + List.of( + Order.of("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ", 2), + Order.of("์ œ๋กœ์ฝœ๋ผ", 2), + Order.of("์‹œ์ €์ƒ๋Ÿฌ๋“œ", 1), + Order.of("์ดˆ์ฝ”์ผ€์ดํฌ", 1), + Order.of("์•„์ด์Šคํฌ๋ฆผ", 1) + )); + + // when + int totalPrice = newOrders.calculateTotalBeforeDiscount(); + + // then + assertThat(totalPrice).isEqualTo(144_000); + } + + @DisplayName("๋””์ €ํŠธ์˜ ๊ฐœ์ˆ˜๋ฅผ ๋ฐ˜ํ™˜ํ•ด์•ผ ํ•œ๋‹ค.") + @Test + void getCountOfDessertTest() { + // given + Orders newOrders = new Orders( + List.of( + Order.of("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ", 2), + Order.of("์ œ๋กœ์ฝœ๋ผ", 2), + Order.of("์ดˆ์ฝ”์ผ€์ดํฌ", 3), + Order.of("์•„์ด์Šคํฌ๋ฆผ", 5) + )); + + // when + int countOfDessert = newOrders.getCountOfDessert(); + + // then + assertThat(countOfDessert).isEqualTo(8); + } + + @DisplayName("๋ฉ”์ธ ๋ฉ”๋‰ด์˜ ๊ฐœ์ˆ˜๋ฅผ ๋ฐ˜ํ™˜ํ•ด์•ผ ํ•œ๋‹ค.") + @Test + void getCountOfMainTest() { + // given + Orders newOrders = new Orders( + List.of( + Order.of("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ", 3), + Order.of("์ œ๋กœ์ฝœ๋ผ", 2), + Order.of("ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€", 1), + Order.of("ํ•ด์‚ฐ๋ฌผํŒŒ์Šคํƒ€", 2) + )); + + // when + int countOfMain = newOrders.getCountOfMain(); + + // then + assertThat(countOfMain).isEqualTo(6); + } + + @DisplayName("๋ฉ”๋‰ด์™€ ๊ฐœ์ˆ˜๋ฅผ ๋ฌธ์ž์—ด๋กœ ๋ฐ˜ํ™˜ํ•ด์•ผ ํ•œ๋‹ค.") + @Test + void getStringOrdersTest() { + // given + Orders newOrders = new Orders( + List.of( + Order.of("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ", 3), + Order.of("์ œ๋กœ์ฝœ๋ผ", 2), + Order.of("ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€", 1) + )); + + // when + String stringOfOrders = newOrders.getStringOrders(); + + // then + assertThat(stringOfOrders) + .contains("ํ‹ฐ๋ณธ์Šคํ…Œ์ดํฌ 3๊ฐœ") + .contains("์ œ๋กœ์ฝœ๋ผ 2๊ฐœ") + .contains("ํฌ๋ฆฌ์Šค๋งˆ์ŠคํŒŒ์Šคํƒ€ 1๊ฐœ"); + } +} \ No newline at end of file
Java
ํ•ด๋‹น ๋กœ์ง์„ @BeforEach ์–ด๋…ธํ…Œ์ด์…˜์„ ํ™œ์šฉํ•˜๋Š”๊ฑด ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹ค๊นŒ์š”?
@@ -0,0 +1,109 @@ +package christmas.controller; + +import christmas.domain.Date; +import christmas.domain.EventBadge; +import christmas.domain.Orders; +import christmas.domain.discount.DDayStrategy; +import christmas.domain.discount.Discount; +import christmas.domain.discount.GiftStrategy; +import christmas.domain.discount.SpecialStrategy; +import christmas.domain.discount.WeekdayStrategy; +import christmas.domain.discount.WeekendStrategy; +import christmas.exception.InputException; +import christmas.util.CurrencyUtil; +import christmas.view.InputView; +import christmas.view.OutputView; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Supplier; + +public class PromotionController { + + + public void run() { + OutputView.printGreeting(); + + Date date = initVisitDate(); + Orders orders = initOrders(); + + displayPreviewForEvent(date, orders); + } + + private void displayPreviewForEvent(Date date, Orders orders) { + OutputView.printPreviewTitle(date.getDay()); + OutputView.printOrderedMenu(orders.getStringOrders()); + displayTotalBeforeDiscount(orders); + displayDiscountDetails(date, orders); + } + + private void displayDiscountDetails(Date date, Orders orders) { + Discount discount = applyDiscount(date, orders); + + OutputView.printGiftMenu(discount.getStringGiftMenu()); + OutputView.printBenefitHistory(discount.getDetailedEventHistory()); + + int totalBenefitAmount = discount.getTotalBenefitAmount(); + displayTotalBenefitAmount(totalBenefitAmount); + displayDiscountedTotal(orders, discount); + + displayEventBadge(totalBenefitAmount); + } + + private void displayEventBadge(int totalBenefitAmount) { + EventBadge eventBadge = EventBadge.getEventBadge(totalBenefitAmount); + OutputView.printEventBadge(eventBadge.getName()); + } + + private void displayDiscountedTotal(Orders orders, Discount discount) { + String amount = CurrencyUtil.formatToKor( + orders.calculateTotalBeforeDiscount() + discount.getTotalDiscountAmount()); + OutputView.printDiscountedTotal(amount); + } + + private void displayTotalBenefitAmount(int totalBenefitAmount) { + String totalBenefit = CurrencyUtil.formatToKor(totalBenefitAmount); + OutputView.printTotalBenefit(totalBenefit); + } + + private void displayTotalBeforeDiscount(Orders orders) { + String totalAmount = CurrencyUtil.formatToKor(orders.calculateTotalBeforeDiscount()); + OutputView.printTotalBeforeDiscount(totalAmount); + } + + private Discount applyDiscount(Date date, Orders orders) { + Discount discount = new Discount(List.of( + new DDayStrategy(), + new WeekdayStrategy(), + new WeekendStrategy(), + new SpecialStrategy(), + new GiftStrategy()), + date + ); + discount.checkEvent(orders); + + return discount; + } + + private Orders initOrders() { + return wrapByLoop(() -> { + Orders orders = new Orders(new ArrayList<>()); + orders.createOrder(InputView.getMenu()); + + return orders; + }); + } + + private Date initVisitDate() { + return wrapByLoop(() -> Date.from(InputView.getDate())); + } + + private <T> T wrapByLoop(Supplier<T> supplier) { + while (true) { + try { + return supplier.get(); + } catch (InputException exception) { + System.out.println(exception.getMessage()); + } + } + } +}
Java
๊ณต๊ฐํ•ฉ๋‹ˆ๋‹ค!!
@@ -0,0 +1,58 @@ +package christmas.domain; + +import christmas.exception.ExceptionMessage; +import christmas.exception.InputException; +import java.time.LocalDate; +import java.time.format.TextStyle; +import java.util.List; +import java.util.Locale; + +public class Date { + private static final int MIN_DATE = 1; + private static final int MAX_DATE = 31; + private static final int OFFSET = 1; + private static final int CHRISTMAS = 25; + private static final String SUNDAY = "์ผ"; + private static final List<String> WEEKDAY = List.of(SUNDAY, "์›”", "ํ™”", "์ˆ˜", "๋ชฉ"); + + private final LocalDate date; + + private Date(int date) { + validateRange(date); + this.date = LocalDate.of(2023, 12, date); + } + + public static Date from(int date) { + return new Date(date); + } + + public boolean isBetween1And25days() { + return getDay() <= CHRISTMAS; + } + + public int daysSince1Day() { + return getDay() - OFFSET; + } + + public boolean isSpecialDay() { + return getDay() == CHRISTMAS || getDayOfWeek().equals(SUNDAY); + } + + public boolean isWeekday() { + return WEEKDAY.contains(getDayOfWeek()); + } + + public int getDay() { + return date.getDayOfMonth(); + } + + private String getDayOfWeek() { + return date.getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.KOREA); + } + + private void validateRange(int date) { + if (date < MIN_DATE || date > MAX_DATE) { + throw new InputException(ExceptionMessage.INVALID_DATE); + } + } +}
Java
"SUNDAY" ๋ฅผ "์ผ" ๋กœ ํ•˜์ง€ ์•Š์œผ์‹  ์ด์œ ๊ฐ€ ์žˆ๋‚˜์š”??
@@ -0,0 +1,61 @@ +package christmas.domain; + +import static christmas.Constants.BASE_COUNT; +import static christmas.Constants.BLANK; +import static christmas.Constants.COUNT; +import static christmas.Constants.LINE_FEED; +import static christmas.Constants.NONE; + +import christmas.exception.ExceptionMessage; +import christmas.exception.InputException; + +public class Order { + private final Menu menu; + private final int count; + + private Order(Menu menu, int count) { + validateCount(count); + this.menu = menu; + this.count = count; + } + + public static Order of(String name, int count) { + return new Order(Menu.findMenuByName(name), count); + } + + public int getTotalPrice() { + return menu.getPrice() * count; + } + + public int getCountPerDessert() { + if (menu.isDessert()) { + return count; + } + + return NONE; + } + + public int getCountPerMain() { + if (menu.isMain()) { + return count; + } + + return NONE; + } + + public String getStringMenuAndCount() { + return new StringBuilder() + .append(menu.getName()) + .append(BLANK) + .append(count) + .append(COUNT) + .append(LINE_FEED) + .toString(); + } + + private void validateCount(int count) { + if (count < BASE_COUNT) { + throw new InputException(ExceptionMessage.INVALID_ORDER); + } + } +}
Java
์ด๊ฑด OutputView ์—์„œ ํ•ด๋„ ์ข‹์„๊ฒƒ ๊ฐ™์€๋ฐ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”??
@@ -0,0 +1,36 @@ +package christmas.domain; + +import java.util.Arrays; +import java.util.Comparator; + +public enum EventBadge { + NONE("์—†์Œ", 0), + STAR("๋ณ„", 5_000), + TREE("ํŠธ๋ฆฌ", 10_000), + SANTA("์‚ฐํƒ€", 20_000); + + private final String name; + private final int price; + + EventBadge(String name, int price) { + this.name = name; + this.price = price; + } + + public static EventBadge getEventBadge(int amount) { + return Arrays.stream(values()) + .sorted(descendOrderByPrice()) + .filter(badge -> badge.price <= Math.abs(amount)) + .findFirst() + .orElse(NONE); + } + + public String getName() { + return name; + } + + private static Comparator<EventBadge> descendOrderByPrice() { + return (o1, o2) -> o2.price - o1.price; + } + +}
Java
์ •๋ง ๊น”๋”ํ•˜๋„ค์š”!!
@@ -0,0 +1,17 @@ +package christmas.domain.discount; + +import christmas.domain.Date; +import christmas.domain.Event; +import christmas.domain.Orders; +import java.util.List; + +public class DDayStrategy implements DiscountStrategy { + @Override + public List<Event> getShouldApplyEvents(Orders orders, Date date) { + if (date.isBetween1And25days()) { + return List.of(Event.CHRISTMAS_D_DAY_DISCOUNT); + } + + return List.of(Event.NONE); + } +}
Java
์ „๋žต ํŒจํ„ด ์‚ฌ์šฉํ•˜์…จ๋„ค์š”! ๐Ÿ‘๐Ÿ‘
@@ -21,6 +21,7 @@ package { if (_instance) { + // NOTE throw ์‹œ์ผœ๋†“๊ณ  catch ์•ˆํ•ด์ฃผ๋ฉด ์–ด๋–ป๊ฒŒ ๋ ๊นŒ์š”? throw new Error("Use getInstance()."); } _instance = this;
Unknown
์‚ฌ์‹ค ์—ฌ๊ธฐ์„œ throw๊ฐ€ ๋‚  ๊ฐ€๋Šฅ์„ฑ์€ ๊ฑฐ์˜ ์—†์–ด๋ณด์ž…๋‹ˆ๋‹ค๋งŒ... ๋ฐ”๊นฅ์— try catch ์ฒ˜๋ฆฌ๋ฅผ ํ•˜์ง€ ์•Š์€ ์ฑ„๋กœ throw๊ฐ€ ๋ฐœ์ƒํ•ด๋ฒ„๋ฆฌ๋ฉด ์–ด๋–ป๊ฒŒ ๋ ๊นŒ์š”?
@@ -1,10 +1,113 @@ package subway; import java.util.Scanner; +import subway.controller.InitController; +import subway.controller.InputController; +import subway.controller.SubwayController; +import subway.domain.Station; +import subway.repository.LineRepository; +import subway.repository.StationRepository; +import subway.service.LineService; +import subway.service.MinimumTimeService; +import subway.service.ShortestPathService; +import subway.service.StationService; +import subway.validation.EndStationValidation; +import subway.validation.MainFunctionValidation; +import subway.validation.SelectRouteValidation; +import subway.validation.StartStationValidation; +import subway.view.Input.InputView; +import subway.view.output.OutputView; public class Application { public static void main(String[] args) { final Scanner scanner = new Scanner(System.in); - // TODO: ํ”„๋กœ๊ทธ๋žจ ๊ตฌํ˜„ + + // ๊ฐ์ฒด ์ƒ์„ฑ + InputView inputView = createInputView(); + OutputView outputView = new OutputView(); + + StationService stationService = createStationService(new StationRepository()); + LineService lineService = createLineService(new LineRepository()); + ShortestPathService shortestPathService = new ShortestPathService(); + MinimumTimeService minimumTimeService = new MinimumTimeService(); + + InitController initController = createInitController(stationService, lineService); + InputController inputController = createInputController(inputView, outputView, scanner); + SubwayController subwayController = createSubwayController(shortestPathService, minimumTimeService, outputView); + + // ๋ฉ”์„œ๋“œ ํ˜ธ์ถœ + executeControllers(initController, inputController, subwayController); + } + + private static InputView createInputView() { + MainFunctionValidation mainFunctionValidation = new MainFunctionValidation(); + SelectRouteValidation selectRouteValidation = new SelectRouteValidation(); + StartStationValidation startStationValidation = new StartStationValidation(); + EndStationValidation endStationValidation = new EndStationValidation(); + return new InputView(mainFunctionValidation, selectRouteValidation, startStationValidation, + endStationValidation); + } + + private static StationService createStationService(StationRepository stationRepository) { + return StationService.createStationService(stationRepository); + } + + private static LineService createLineService(LineRepository lineRepository) { + return LineService.createLineService(lineRepository); + } + + + private static InitController createInitController(StationService stationService, LineService lineService) { + return InitController.createInitController(stationService, lineService); + } + + private static InputController createInputController(InputView inputView, OutputView outputView, Scanner scanner) { + return InputController.createInputController(inputView, outputView, scanner); + } + + private static SubwayController createSubwayController(ShortestPathService shortestPathService, + MinimumTimeService minimumTimeService, + OutputView outputView) { + return SubwayController.createSubwayController(shortestPathService, minimumTimeService, outputView); + } + + + private static void executeControllers(InitController initController, InputController inputController, + SubwayController subwayController) { + initController.init(); + + while (true) { + String mainFunc = inputController.inputMainFunc(); + if (mainFunc.equals("Q")) { + System.exit(0); + } + + if (mainFunc.equals("1")) { + executeRouteSelection(inputController, subwayController); + } + } + } + + private static void executeRouteSelection(InputController inputController, SubwayController subwayController) { + String selectRouteFunc = inputController.inputSelectRoute(); + if (selectRouteFunc.equals("B")) { + return; + } + + Station start = inputStartStation(inputController); + Station end = inputEndStation(inputController, start); + + subwayController.calculateAndPrintRoute(selectRouteFunc, start, end); + } + + private static Station inputStartStation(InputController inputController) { + String stationName = inputController.inputStartStation(); + return new Station(stationName); + } + + private static Station inputEndStation(InputController inputController, Station start) { + String stationName = inputController.inputEndStation(start.getName()); + return new Station(stationName); } } +
Java
์›€ ์—ฌ๊ธฐ๋„ ๋กœ๋˜์™€ ๊ฐ™๊ตฐ์š”! ๋งŒ์•ฝ controller์™€ service์— ๋Œ€ํ•œ ๊ฐ์ฒด ์ƒ์„ฑํ•˜๋Š” ๊ด€์‹ฌ์‚ฌ๋ฅผ ํŠน์ • ํด๋ž˜์Šค์—์„œ ํ•˜๊ณ ์‹ถ๋‹ค๋ฉด Configurationํด๋ž˜์Šค๋ฅผ ๋งŒ๋“œ๋Š”๊ฑด ์–ด๋–จ๊นŒ์š”? ์Šคํ”„๋ง๋ถ€ํŠธ์—์„œ @Configuration์ด Bean์„ ๋“ฑ๋กํ•ด์ฃผ๋Š” ์–ด๋…ธํ…Œ์ด์…˜์ด๋‹ˆ๊นŒ์š”!
@@ -1,10 +1,113 @@ package subway; import java.util.Scanner; +import subway.controller.InitController; +import subway.controller.InputController; +import subway.controller.SubwayController; +import subway.domain.Station; +import subway.repository.LineRepository; +import subway.repository.StationRepository; +import subway.service.LineService; +import subway.service.MinimumTimeService; +import subway.service.ShortestPathService; +import subway.service.StationService; +import subway.validation.EndStationValidation; +import subway.validation.MainFunctionValidation; +import subway.validation.SelectRouteValidation; +import subway.validation.StartStationValidation; +import subway.view.Input.InputView; +import subway.view.output.OutputView; public class Application { public static void main(String[] args) { final Scanner scanner = new Scanner(System.in); - // TODO: ํ”„๋กœ๊ทธ๋žจ ๊ตฌํ˜„ + + // ๊ฐ์ฒด ์ƒ์„ฑ + InputView inputView = createInputView(); + OutputView outputView = new OutputView(); + + StationService stationService = createStationService(new StationRepository()); + LineService lineService = createLineService(new LineRepository()); + ShortestPathService shortestPathService = new ShortestPathService(); + MinimumTimeService minimumTimeService = new MinimumTimeService(); + + InitController initController = createInitController(stationService, lineService); + InputController inputController = createInputController(inputView, outputView, scanner); + SubwayController subwayController = createSubwayController(shortestPathService, minimumTimeService, outputView); + + // ๋ฉ”์„œ๋“œ ํ˜ธ์ถœ + executeControllers(initController, inputController, subwayController); + } + + private static InputView createInputView() { + MainFunctionValidation mainFunctionValidation = new MainFunctionValidation(); + SelectRouteValidation selectRouteValidation = new SelectRouteValidation(); + StartStationValidation startStationValidation = new StartStationValidation(); + EndStationValidation endStationValidation = new EndStationValidation(); + return new InputView(mainFunctionValidation, selectRouteValidation, startStationValidation, + endStationValidation); + } + + private static StationService createStationService(StationRepository stationRepository) { + return StationService.createStationService(stationRepository); + } + + private static LineService createLineService(LineRepository lineRepository) { + return LineService.createLineService(lineRepository); + } + + + private static InitController createInitController(StationService stationService, LineService lineService) { + return InitController.createInitController(stationService, lineService); + } + + private static InputController createInputController(InputView inputView, OutputView outputView, Scanner scanner) { + return InputController.createInputController(inputView, outputView, scanner); + } + + private static SubwayController createSubwayController(ShortestPathService shortestPathService, + MinimumTimeService minimumTimeService, + OutputView outputView) { + return SubwayController.createSubwayController(shortestPathService, minimumTimeService, outputView); + } + + + private static void executeControllers(InitController initController, InputController inputController, + SubwayController subwayController) { + initController.init(); + + while (true) { + String mainFunc = inputController.inputMainFunc(); + if (mainFunc.equals("Q")) { + System.exit(0); + } + + if (mainFunc.equals("1")) { + executeRouteSelection(inputController, subwayController); + } + } + } + + private static void executeRouteSelection(InputController inputController, SubwayController subwayController) { + String selectRouteFunc = inputController.inputSelectRoute(); + if (selectRouteFunc.equals("B")) { + return; + } + + Station start = inputStartStation(inputController); + Station end = inputEndStation(inputController, start); + + subwayController.calculateAndPrintRoute(selectRouteFunc, start, end); + } + + private static Station inputStartStation(InputController inputController) { + String stationName = inputController.inputStartStation(); + return new Station(stationName); + } + + private static Station inputEndStation(InputController inputController, Station start) { + String stationName = inputController.inputEndStation(start.getName()); + return new Station(stationName); } } +
Java
Q๋‚˜ 1๊ฐ™์€ ๊ฐ’์€ Function enumํด๋ž˜์Šค๋กœ ์ ‘๊ทผํ•ด์„œ ์ž‘์„ฑํ•˜์…จ์„ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,44 @@ +package subway.service; + +import static subway.domain.RouteInfo.calculateTotalDistance; +import static subway.domain.RouteInfo.calculateTotalTime; +import static subway.domain.RouteInfo.values; + +import java.util.List; +import org.jgrapht.GraphPath; +import org.jgrapht.alg.shortestpath.DijkstraShortestPath; +import org.jgrapht.graph.DefaultWeightedEdge; +import org.jgrapht.graph.WeightedMultigraph; +import subway.domain.Result; +import subway.domain.RouteInfo; +import subway.domain.Station; + +public class MinimumTimeService { + public Result calculate(Station start, Station end) { + WeightedMultigraph<String, DefaultWeightedEdge> graph = createGraph(values()); + + DijkstraShortestPath<String, DefaultWeightedEdge> dijkstraShortestPath = + new DijkstraShortestPath<>(graph); + + GraphPath<String, DefaultWeightedEdge> shortestPath = + dijkstraShortestPath.getPath(start.getName(), end.getName()); + + List<DefaultWeightedEdge> edges = shortestPath.getEdgeList(); + + int totalDistance = calculateTotalDistance(graph, edges); + int totalTime = calculateTotalTime(graph, edges); + + return Result.createResult(totalDistance, totalTime, shortestPath.getVertexList()); + } + + private WeightedMultigraph<String, DefaultWeightedEdge> createGraph(RouteInfo[] routeInfos) { + WeightedMultigraph<String, DefaultWeightedEdge> graph = + new WeightedMultigraph<>(DefaultWeightedEdge.class); + + for (RouteInfo routeInfo : routeInfos) { + routeInfo.calculateMinimumTime(graph, routeInfo); + } + + return graph; + } +} \ No newline at end of file
Java
์˜คํ˜ธ!! ๊ฐ์ฒด ์ƒ์„ฑํ•˜๋Š” ์ฝ”๋“œ๋ฅผ ๋ถ„๋ฆฌ์‹œ์ผฐ๊ตฐ์š”!! ๋ฐฐ์›Œ๊ฐ‘๋‹ˆ๋‹ค..!!
@@ -0,0 +1,59 @@ +package subway.view.Input; + +import subway.validation.EndStationValidation; +import subway.validation.MainFunctionValidation; +import subway.validation.SelectRouteValidation; +import subway.validation.StartStationValidation; + +public class InputView { + private final MainFunctionValidation mainFunctionValidation; + private final SelectRouteValidation selectRouteValidation; + private final StartStationValidation startStationValidation; + private final EndStationValidation endStationValidation; + + public InputView(MainFunctionValidation mainFunctionValidation, SelectRouteValidation selectRouteValidation, + StartStationValidation startStationValidation, EndStationValidation endStationValidation) { + this.mainFunctionValidation = mainFunctionValidation; + this.selectRouteValidation = selectRouteValidation; + this.startStationValidation = startStationValidation; + this.endStationValidation = endStationValidation; + } + + public String readMainFunc(String input) { + return mainFunctionValidate(input); + } + + public String readSelectRoute(String input) { + return selectRouteValidate(input); + } + + public String readStartStation(String input) { + return startStationValidate(input); + } + + public String readEndStation(String start, String input) { + return endStationValidate(start, input); + } + + private String mainFunctionValidate(String input) { + mainFunctionValidation.isBlank(input); + return mainFunctionValidation.isOneOrQ(input); + } + + private String selectRouteValidate(String input) { + selectRouteValidation.isBlank(input); + return selectRouteValidation.isOneOrTwoOrB(input); + } + + private String startStationValidate(String input) { + startStationValidation.isBlank(input); + return startStationValidation.isRegister(input); + } + + private String endStationValidate(String start, String input) { + endStationValidation.isBlank(input); + endStationValidation.isRegister(input); + return endStationValidation.isDuplicate(start, input); + } +} +
Java
์ด๋ฏธ isBlank๋ฉ”์†Œ๋“œ๊ฐ€ static์œผ๋กœ ํ• ๋‹น๋˜์–ด์žˆ๊ธฐ๋•Œ๋ฌธ์— mainFunctionValidation.isBlank๊ฐ€ ์•„๋‹Œ, MainFunctionValidation.isBlank๋กœ ํ•˜๋Š”๊ฒŒ ๋” ์ ํ•ฉํ•  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -1,10 +1,113 @@ package subway; import java.util.Scanner; +import subway.controller.InitController; +import subway.controller.InputController; +import subway.controller.SubwayController; +import subway.domain.Station; +import subway.repository.LineRepository; +import subway.repository.StationRepository; +import subway.service.LineService; +import subway.service.MinimumTimeService; +import subway.service.ShortestPathService; +import subway.service.StationService; +import subway.validation.EndStationValidation; +import subway.validation.MainFunctionValidation; +import subway.validation.SelectRouteValidation; +import subway.validation.StartStationValidation; +import subway.view.Input.InputView; +import subway.view.output.OutputView; public class Application { public static void main(String[] args) { final Scanner scanner = new Scanner(System.in); - // TODO: ํ”„๋กœ๊ทธ๋žจ ๊ตฌํ˜„ + + // ๊ฐ์ฒด ์ƒ์„ฑ + InputView inputView = createInputView(); + OutputView outputView = new OutputView(); + + StationService stationService = createStationService(new StationRepository()); + LineService lineService = createLineService(new LineRepository()); + ShortestPathService shortestPathService = new ShortestPathService(); + MinimumTimeService minimumTimeService = new MinimumTimeService(); + + InitController initController = createInitController(stationService, lineService); + InputController inputController = createInputController(inputView, outputView, scanner); + SubwayController subwayController = createSubwayController(shortestPathService, minimumTimeService, outputView); + + // ๋ฉ”์„œ๋“œ ํ˜ธ์ถœ + executeControllers(initController, inputController, subwayController); + } + + private static InputView createInputView() { + MainFunctionValidation mainFunctionValidation = new MainFunctionValidation(); + SelectRouteValidation selectRouteValidation = new SelectRouteValidation(); + StartStationValidation startStationValidation = new StartStationValidation(); + EndStationValidation endStationValidation = new EndStationValidation(); + return new InputView(mainFunctionValidation, selectRouteValidation, startStationValidation, + endStationValidation); + } + + private static StationService createStationService(StationRepository stationRepository) { + return StationService.createStationService(stationRepository); + } + + private static LineService createLineService(LineRepository lineRepository) { + return LineService.createLineService(lineRepository); + } + + + private static InitController createInitController(StationService stationService, LineService lineService) { + return InitController.createInitController(stationService, lineService); + } + + private static InputController createInputController(InputView inputView, OutputView outputView, Scanner scanner) { + return InputController.createInputController(inputView, outputView, scanner); + } + + private static SubwayController createSubwayController(ShortestPathService shortestPathService, + MinimumTimeService minimumTimeService, + OutputView outputView) { + return SubwayController.createSubwayController(shortestPathService, minimumTimeService, outputView); + } + + + private static void executeControllers(InitController initController, InputController inputController, + SubwayController subwayController) { + initController.init(); + + while (true) { + String mainFunc = inputController.inputMainFunc(); + if (mainFunc.equals("Q")) { + System.exit(0); + } + + if (mainFunc.equals("1")) { + executeRouteSelection(inputController, subwayController); + } + } + } + + private static void executeRouteSelection(InputController inputController, SubwayController subwayController) { + String selectRouteFunc = inputController.inputSelectRoute(); + if (selectRouteFunc.equals("B")) { + return; + } + + Station start = inputStartStation(inputController); + Station end = inputEndStation(inputController, start); + + subwayController.calculateAndPrintRoute(selectRouteFunc, start, end); + } + + private static Station inputStartStation(InputController inputController) { + String stationName = inputController.inputStartStation(); + return new Station(stationName); + } + + private static Station inputEndStation(InputController inputController, Station start) { + String stationName = inputController.inputEndStation(start.getName()); + return new Station(stationName); } } +
Java
์ตœ์ข… ์ฝ”ํ…Œ์—์„œ ์‚ฌ์šฉํ•  ํ…œํ”Œ๋ฆฟ์„ ๋งŒ๋“ค๋‹ค๋ณด๋‹ˆ ๊ฐ™์€ ํ˜•์‹์œผ๋กœ ๋งŒ๋“ค์–ด์กŒ๊ตฐ์š” ใ…œใ…œ ๋‹ค์‹œ ๊ณ ๋ฏผํ•ด๋ด์•ผ๊ฒ ์Šต๋‹ˆ๋‹ค!!
@@ -0,0 +1,30 @@ +package store.contant; + +public enum Constant { + PRODUCTS_FILE_PATH("./src/main/resources/products.md"), + PROMOTIONS_FILE_PATH("./src/main/resources/promotions.md"), + + Y("Y"), + N("N"), + + YEAR("year"), + MONTH("month"), + DAY("day"), + + DEFAULT_DELIMITER("-"), + COMMA_DELIMITER(","), + + ITEM_DELIMITER("\\[(.*?)]"), + DATE_DELIMITER("(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})"); + + private final String detail; + + Constant(String detail) { + this.detail = detail; + } + + @Override + public String toString() { + return detail; + } +}
Java
์ €๋Š” ๋ชฐ๋ž๋˜ ์ •๊ทœํ‘œํ˜„์‹ ๋ฌธ๋ฒ•์ด๋ผ ์ฐพ์•„๋ณด๋‹ˆ๊นŒ named capturing group ์ด๋ผ๊ณ  ํ•˜๋Š”๊ตฐ์š”.. ์ƒˆ๋กœ์šด๊ฑฐ ๋ฐฐ์›Œ๊ฐ‘๋‹ˆ๋‹ค!
@@ -0,0 +1,126 @@ +package store.view; + +import java.text.NumberFormat; +import store.domain.Product; +import store.domain.Products; +import store.dto.PurchaseDTO; +import store.dto.ReceiptDTO; + +public class OutputView { + private static final NumberFormat format = NumberFormat.getNumberInstance(); + + public static void printProducts(Products products) { + System.out.println(OutputMessage.OUTPUT_HELLO_CONVENIENCE_MESSAGE); + for (String product : products.getNames()) { + Product with = products.getItemWithPromotion(product); + Product without = products.getItemWithoutPromotion(product); + + printWith(with); + printWithout(without, with); + } + System.out.println(); + } + + private static void printWith(Product with) { + if (with != null) { + String price = getPrice(with); + String quantity = getQuantity(with); + String promotion = getPromotion(with); + System.out.println("- " + with.getName() + " " + price + " " + quantity + " " + promotion); + } + } + + private static void printWithout(Product without, Product with) { + if (without == null) { + String price = getPrice(with); + System.out.println("- " + with.getName() + " " + price + " ์žฌ๊ณ  ์—†์Œ"); + return; + } + String price = getPrice(without); + String quantity = getQuantity(without); + System.out.println("- " + without.getName() + " " + price + " " + quantity); + } + + public static void printReceipt(ReceiptDTO receiptDTO, boolean isMembership) { + printPurchaseItems(receiptDTO); + printFreeItems(receiptDTO); + printAccount(receiptDTO, isMembership); + } + + private static void printAccount(ReceiptDTO receiptDTO, boolean isMembership) { + System.out.println(OutputMessage.OUTPUT_RECEIPT_BOTTOM_MESSAGE); + printTotalPrice(receiptDTO); + printPromotionDiscount(receiptDTO); + printMembershipDiscount(receiptDTO, isMembership); + printPayment(receiptDTO, isMembership); + } + + private static void printPayment(ReceiptDTO receiptDTO, boolean isMembership) { + System.out.printf(OutputMessage.OUTPUT_RECEIPT_PAY_MESSAGE.format( + OutputMessage.TO_BE_PAID, + format.format(totalPayment(receiptDTO, isMembership)))); + System.out.println(); + } + + private static int totalPayment(ReceiptDTO receiptDTO, boolean isMembership) { + return receiptDTO.getTotalAmount() - receiptDTO.getFreeAmount() - receiptDTO.getMembershipAmount(isMembership); + } + + private static void printMembershipDiscount(ReceiptDTO receiptDTO, boolean isMembership) { + System.out.printf(OutputMessage.OUTPUT_RECEIPT_DISCOUNT_MESSAGE.format( + OutputMessage.MEMBERSHIP_DISCOUNT, + "-" + format.format(receiptDTO.getMembershipAmount(isMembership)))); + } + + private static void printPromotionDiscount(ReceiptDTO receiptDTO) { + System.out.printf(OutputMessage.OUTPUT_RECEIPT_DISCOUNT_MESSAGE.format( + OutputMessage.PROMOTION_DISCOUNT, + "-" + format.format(receiptDTO.getFreeAmount()))); + } + + private static void printTotalPrice(ReceiptDTO receiptDTO) { + System.out.printf(OutputMessage.OUTPUT_RECEIPT_PRODUCT_MESSAGE.format( + OutputMessage.TOTAL_PRICE, + receiptDTO.getTotalQuantity(), + format.format(receiptDTO.getTotalAmount()))); + } + + private static void printFreeItems(ReceiptDTO receiptDTO) { + System.out.println(OutputMessage.OUTPUT_RECEIPT_MIDDLE_MESSAGE); + for (PurchaseDTO purchaseDTO : receiptDTO.free()) { + System.out.printf(OutputMessage.OUTPUT_RECEIPT_FREE_MESSAGE.format( + purchaseDTO.name(), purchaseDTO.quantity())); + } + } + + private static void printPurchaseItems(ReceiptDTO receiptDTO) { + System.out.println(OutputMessage.OUTPUT_RECEIPT_TOP_MESSAGE); + for (PurchaseDTO purchaseDTO : receiptDTO.cart()) { + System.out.printf(OutputMessage.OUTPUT_RECEIPT_PRODUCT_MESSAGE.format( + purchaseDTO.name(), + purchaseDTO.quantity(), + format.format(purchaseDTO.getTotalAmount())) + ); + } + } + + private static String getPrice(Product product) { + return format.format(product.getPrice()) + OutputMessage.CURRENCY_UNIT; + } + + private static String getPromotion(Product product) { + String promotion = ""; + if (product.getPromotion() != null) { + promotion = product.getPromotion().getName(); + } + return promotion; + } + + private static String getQuantity(Product product) { + String quantity = format.format(product.getStock()) + OutputMessage.QUANTITY_UNIT; + if (product.getStock() == 0) { + quantity = OutputMessage.QUANTITY_EMPTY.toString(); + } + return quantity; + } +}
Java
์ด๋Ÿฐ ๋ถ€๋ถ„์—๋„ DTO๋ฅผ ๋ฐ›์•„์„œ ์ฒ˜๋ฆฌํ•˜๋Š”๊ฑด ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•˜์‹œ๋‚˜์š”?
@@ -0,0 +1,14 @@ +package store.exception; + +public class CustomException extends IllegalArgumentException { + private final String errorMessage; + + public CustomException(String errorMessage) { + super(errorMessage); + this.errorMessage = errorMessage; + } + + public String getErrorMessage() { + return errorMessage; + } +}
Java
CustomException ํด๋ž˜์Šค๋ฅผ ๋”ฐ๋กœ ๋งŒ๋“œ์‹  ์ด์œ ๊ฐ€ ๊ถ๊ธˆํ•ฉ๋‹ˆ๋‹ค (์ด ๋ถ€๋ถ„์€ ์ž˜ ๋ชฐ๋ผ์„œ).
@@ -0,0 +1,57 @@ +package store.view; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import store.contant.Constant; +import store.dto.BuyDTO; +import store.exception.CustomException; +import store.exception.ErrorMessage; + +public class InputHandler { + private static final Pattern patternItem = Pattern.compile(Constant.ITEM_DELIMITER.toString()); + private static final Pattern patternDate = Pattern.compile(Constant.DATE_DELIMITER.toString()); + + public static List<BuyDTO> splitItems(String input) { + Matcher matcher = patternItem.matcher(input); + return matcher.results() + .map(find -> { + String content = find.group(1); + validate(content); + String[] item = split(content); + return new BuyDTO(item[0], toInt(item[1])); + }) + .toList(); + } + + private static void validate(String input) { + if (input.contains("[") || input.contains("]")) { + throw new CustomException(ErrorMessage.NOT_FIT_THE_FORM_MESSAGE.toString()); + } + } + + public static LocalDateTime parseDate(String input) { + Matcher matcher = patternDate.matcher(input); + if (matcher.matches()) { + int year = Integer.parseInt(matcher.group(Constant.YEAR.toString())); + int month = Integer.parseInt(matcher.group(Constant.MONTH.toString())); + int day = Integer.parseInt(matcher.group(Constant.DAY.toString())); + return LocalDate.of(year, month, day).atStartOfDay(); + } + throw new CustomException(ErrorMessage.FILE_IOEXCEPTION_MESSAGE.toString()); + } + + public static int toInt(String input) { + try { + return Integer.parseInt(input); + } catch (NumberFormatException e) { + throw new CustomException(ErrorMessage.NOT_FIT_THE_FORM_MESSAGE.toString()); + } + } + + private static String[] split(String input) { + return input.split(Constant.DEFAULT_DELIMITER.toString()); + } +}
Java
Matcher.results()๋กœ ๋‚˜๋ˆ„๋Š”๊ฑด ๊น”๋”ํ•˜์ง€๋งŒ ํ’ˆ๋ชฉ์„ ๋‚˜๋ˆ„๋Š” ๊ตฌ๋ถ„์ž๋กœ ์‰ผํ‘œ๊ฐ€ ์•„๋‹ˆ์–ด๋„ ์ž‘๋™ํ•ด์„œ, ์š”๊ตฌ์‚ฌํ•ญ์— ๋งž์ถ”๋ ค๋ฉด ์ˆ˜์ •ํ•ด์•ผ ํ•  ๊ฒƒ ๊ฐ™์•„์š”.
@@ -0,0 +1,83 @@ +package store.view; + +import camp.nextstep.edu.missionutils.Console; +import java.util.List; +import store.contant.Constant; +import store.dto.BuyDTO; +import store.exception.CustomException; +import store.exception.ErrorMessage; + +public class InputView { + public static List<BuyDTO> readItem() { + while (true) { + try { + System.out.println(InputMessage.INPUT_PURCHASE_PRODUCT_MESSAGE); + return InputHandler.splitItems(Console.readLine()); + } catch (CustomException e) { + System.out.println(e.getErrorMessage()); + } + } + } + + public static String readMembership() { + while (true) { + try { + System.out.println(InputMessage.INPUT_MEMBERSHIP_MESSAGE); + String input = Console.readLine(); + validate(input); + return input; + } catch (CustomException e) { + System.out.println(e.getErrorMessage()); + } + } + } + + public static String readPromotion(String name, int quantity) { + while (true) { + try { + System.out.printf(InputMessage.INPUT_PROMOTION_MESSAGE.format(name, quantity)); + String input = Console.readLine(); + validate(input); + return input; + } catch (CustomException e) { + System.out.println(e.getErrorMessage()); + } + } + } + + public static String readGetOneFree(String name, int quantity) { + while (true) { + try { + System.out.printf(InputMessage.INPUT_GET_ONE_FREE_MESSAGE.format(name, quantity)); + String input = Console.readLine(); + validate(input); + return input; + } catch (CustomException e) { + System.out.println(e.getErrorMessage()); + } + } + } + + public static String readRePurchase() { + while (true) { + try { + System.out.println(InputMessage.INPUT_RE_PURCHASE_MESSAGE); + String input = Console.readLine(); + validate(input); + return input; + } catch (CustomException e) { + System.out.println(e.getErrorMessage()); + } + } + } + + private static void validate(String input) { + if (isCorrectInput(input)) { + throw new CustomException(ErrorMessage.INVALID_INPUT_MESSAGE.toString()); + } + } + + private static boolean isCorrectInput(String input) { + return !(input.equals(Constant.Y.toString()) || input.equals(Constant.N.toString())); + } +}
Java
validate() ๋„ค์ด๋ฐ์ด ์กฐ๊ธˆ ๋” ๊ตฌ์ฒด์ ์ด๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,108 @@ +package store.controller; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.time.LocalDateTime; +import java.util.List; +import org.junit.platform.commons.logging.Logger; +import org.junit.platform.commons.logging.LoggerFactory; +import store.contant.Constant; +import store.domain.Product; +import store.domain.Products; +import store.domain.Promotion; +import store.domain.Promotions; +import store.dto.ProductsDTO; +import store.dto.ReceiptDTO; +import store.exception.CustomException; +import store.exception.ErrorMessage; +import store.view.InputHandler; +import store.view.InputView; +import store.view.OutputView; + +public class ConvenienceManager { + private final Logger logger = LoggerFactory.getLogger(getClass()); + + private static final String PRODUCTS_FILE_PATH = Constant.PRODUCTS_FILE_PATH.toString(); + private static final String PROMOTIONS_FILE_PATH = Constant.PROMOTIONS_FILE_PATH.toString(); + + private Promotions promotions; + private Products products; + + public ConvenienceManager() { + try { + this.promotions = new Promotions(initPromotions()); + this.products = new Products(initProducts(this.promotions)); + } catch (IOException e) { + logger.info(ErrorMessage.FILE_IOEXCEPTION_MESSAGE::toString); + } + } + + public void run() { + try { + do { + OutputView.printProducts(products); + List<ProductsDTO> sameItems = products.getSameProducts(); + ReceiptDTO receiptDTO = products.buyProduct(sameItems); + membership(receiptDTO); + } while (hasRePurchase()); + } catch (CustomException e) { + System.out.println(e.getErrorMessage()); + } + } + + private void membership(ReceiptDTO receiptDTO) { + if (hasApplyMembership()) { + OutputView.printReceipt(receiptDTO, true); + return; + } + OutputView.printReceipt(receiptDTO, false); + } + + private List<Promotion> initPromotions() throws IOException { + List<String> strings = Files.readAllLines(Paths.get(PROMOTIONS_FILE_PATH)); + return strings.stream() + .skip(1) + .map(this::makePromotion) + .toList(); + } + + private List<Product> initProducts(Promotions promotions) throws IOException { + List<String> strings = Files.readAllLines(Paths.get(PRODUCTS_FILE_PATH)); + return strings.stream() + .skip(1) + .map(line -> makeProduct(promotions, line)) + .toList(); + } + + private Promotion makePromotion(String line) { + final String[] promotion = split(line); + final String name = promotion[0]; + final int buy = Integer.parseInt(promotion[1]); + final int get = Integer.parseInt(promotion[2]); + final LocalDateTime startDate = InputHandler.parseDate(promotion[3]); + final LocalDateTime endDate = InputHandler.parseDate(promotion[4]); + return new Promotion(name, buy, get, startDate, endDate); + } + + private Product makeProduct(Promotions promotions, String line) { + final String[] product = split(line); + final String name = product[0]; + final int price = Integer.parseInt(product[1]); + final int stock = Integer.parseInt(product[2]); + final Promotion promotion = promotions.findPromotion(product[3]); + return new Product(name, price, stock, promotion); + } + + private static String[] split(String line) { + return line.split(Constant.COMMA_DELIMITER.toString()); + } + + private boolean hasRePurchase() { + return InputView.readRePurchase().equals(Constant.Y.toString()); + } + + private boolean hasApplyMembership() { + return InputView.readMembership().equals(Constant.Y.toString()); + } +}
Java
์ปจํŠธ๋กค๋Ÿฌ์˜ ์ƒ์„ฑ์ž๋ž‘ run ๋ถ€๋ถ„์ด ์ •๋ง ๊น”๋”ํ•˜๊ณ  ์ข‹์€ ๊ฒƒ ๊ฐ™์•„์š”!
@@ -0,0 +1,206 @@ +package store.domain; + +import camp.nextstep.edu.missionutils.DateTimes; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import store.contant.Constant; +import store.dto.BuyDTO; +import store.dto.ProductsDTO; +import store.dto.PurchaseDTO; +import store.dto.ReceiptDTO; +import store.dto.StockDTO; +import store.exception.CustomException; +import store.exception.ErrorMessage; +import store.view.InputView; + +public class Products { + private static final int ZERO = 0; + private static final int MINIMUM_STOCK = 1; + + private final List<Product> products; + + public Products(List<Product> products) { + this.products = products; + } + + public ReceiptDTO buyProduct(List<ProductsDTO> items) { + List<PurchaseDTO> purchaseItem = new ArrayList<>(); + List<PurchaseDTO> freeItem = new ArrayList<>(); + addReceipt(items, purchaseItem, freeItem); + return new ReceiptDTO(purchaseItem, freeItem); + } + + private void addReceipt(List<ProductsDTO> items, List<PurchaseDTO> purchaseItem, List<PurchaseDTO> freeItem) { + for (ProductsDTO productsDTO : items) { + buy( + productsDTO.name(), + productsDTO.quantity(), + productsDTO.with(), + productsDTO.without(), + purchaseItem, + freeItem + ); + } + } + + public List<ProductsDTO> getSameProducts() { + while (true) { + try { + List<BuyDTO> shopping = InputView.readItem(); + return changeProductsDTO(shopping); + } catch (CustomException e) { + System.out.println(e.getErrorMessage()); + } + } + } + + public List<Product> getProducts() { + return products; + } + + public List<ProductsDTO> changeProductsDTO(List<BuyDTO> shopping) { + return shopping.stream() + .map(find -> { + Product with = getItemWithPromotion(find.name()); + Product without = getItemWithoutPromotion(find.name()); + return new ProductsDTO(find.name(), find.quantity(), with, without); + }).toList(); + } + + public List<String> getNames() { + return products.stream() + .map(Product::getName) + .distinct() + .toList(); + } + + private void buy( + String name, int quantity, + Product with, Product without, List<PurchaseDTO> purchases, List<PurchaseDTO> frees + ) { + if (hasNullPromotion(purchases, with, without, quantity, name)) { + return; + } + quantity = fillQuantity(quantity, with, name); + StockDTO stockDTO = getPurchaseState(with, quantity, without, name); + addCart(name, purchases, frees, with, stockDTO); + } + + private void addCart( + String name, + List<PurchaseDTO> purchases, List<PurchaseDTO> frees, + Product withPromotion, StockDTO stockDTO + ) { + purchases.add(new PurchaseDTO( + name, withPromotion.getPrice(), stockDTO.getTotalStock(), stockDTO.freeStock(), + stockDTO.remainStock())); + frees.add(new PurchaseDTO( + name, withPromotion.getPrice(), stockDTO.freeStock(), 0, 0)); + } + + private boolean hasNullPromotion( + List<PurchaseDTO> purchaseItem, + Product withPromotion, Product withoutPromotion, + int quantity, String name + ) { + if (isInvalidPromotion(withPromotion)) { + withoutPromotion.notApplyClearanceStock(quantity); + purchaseItem.add(new PurchaseDTO(name, withoutPromotion.getPrice(), quantity, 0, quantity)); + return true; + } + return false; + } + + private StockDTO getPurchaseState(Product withPromotion, int quantity, Product withoutPromotion, String name) { + StockDTO stockDTO = withPromotion.getPurchaseState(quantity); + return clearance(withPromotion, withoutPromotion, name, quantity, stockDTO); + } + + private int fillQuantity(int quantity, Product withPromotion, String name) { + if (isNotApplyPromotion(quantity, withPromotion)) { + int addition = withPromotion.getPromotion().getApplyPromotion() - quantity; + if (hasGetOneFree(name, addition)) { + quantity += addition; + } + } + return quantity; + } + + private StockDTO clearance( + Product with, Product without, + String name, int quantity, StockDTO stockDTO + ) { + if (with.getStock() < quantity) { + if (hasApplyPromotion(name, stockDTO)) { + return nonApplyPromotionItem(with, without, stockDTO); + } + return onlyPromotionItem(with, without, stockDTO); + } + return applyPromotion(with, quantity, stockDTO); + } + + private StockDTO applyPromotion(Product with, int quantity, StockDTO stockDTO) { + with.applyClearanceStock(quantity); + return new StockDTO(0, stockDTO.applyStock(), stockDTO.freeStock()); + } + + private StockDTO onlyPromotionItem(Product with, Product without, StockDTO stockDTO) { + applyPromotionClearance(with, without, stockDTO.applyStock() + stockDTO.freeStock()); + return new StockDTO(0, stockDTO.applyStock(), stockDTO.freeStock()); + } + + private StockDTO nonApplyPromotionItem(Product with, Product without, StockDTO stockDTO) { + applyPromotionClearance(with, without, stockDTO.getTotalStock()); + return new StockDTO(stockDTO.remainStock(), stockDTO.applyStock(), stockDTO.freeStock()); + } + + private void applyPromotionClearance(Product withPromotion, Product withoutPromotion, int quantity) { + validateQuantity(quantity); + int remain = withPromotion.applyClearanceStock(quantity); + if (isRemainStock(remain)) { + withoutPromotion.notApplyClearanceStock(remain); + } + } + + private boolean isRemainStock(int remain) { + return remain > ZERO; + } + + public Product getItemWithPromotion(String name) { + return products.stream() + .filter(product -> product.isSameName(name) && product.isWithPromotion()) + .findFirst() + .orElse(null); + } + + public Product getItemWithoutPromotion(String name) { + return products.stream() + .filter(product -> product.isSameName(name) && !product.isWithPromotion()) + .findFirst() + .orElse(null); + } + + private void validateQuantity(int quantity) { + if (quantity < MINIMUM_STOCK) { + throw new CustomException(ErrorMessage.QUANTITY_OVER_MESSAGE.toString()); + } + } + + private boolean hasGetOneFree(String name, int addition) { + return InputView.readGetOneFree(name, addition).equals(Constant.Y.toString()); + } + + private boolean hasApplyPromotion(String name, StockDTO stockDTO) { + return InputView.readPromotion(name, stockDTO.remainStock()).equals(Constant.Y.toString()); + } + + private boolean isInvalidPromotion(Product withPromotion) { + return withPromotion == null || withPromotion.getPromotion().isLastDate(DateTimes.now()); + } + + private boolean isNotApplyPromotion(int quantity, Product withPromotion) { + return quantity < withPromotion.getPromotion().getApplyPromotion(); + } +}
Java
InputView๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ๋ถ€๋ถ„์„ ์ปจํŠธ๋กค๋Ÿฌ๋ฅผ ๊ฑฐ์น˜๋Š”๊ฒŒ ์ข‹์ง€ ์•Š์„๊นŒ ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,35 @@ +package store.dto; + +import java.util.List; + +public record ReceiptDTO( + List<PurchaseDTO> cart, + List<PurchaseDTO> free +) { + public int getTotalQuantity() { + return cart.stream() + .mapToInt(PurchaseDTO::quantity) + .sum(); + } + + public int getTotalAmount() { + return cart.stream() + .mapToInt(PurchaseDTO::getTotalAmount) + .sum(); + } + + public int getFreeAmount() { + return free.stream() + .mapToInt(PurchaseDTO::getTotalAmount) + .sum(); + } + + public int getMembershipAmount(boolean isMembership) { + if (isMembership) { + return (int) (cart.stream() + .mapToInt(PurchaseDTO::getNotApplyAmount) + .sum() * 0.3); + } + return 0; + } +}
Java
0.3์€ ์ค‘์š”ํ•œ ์ˆซ์ž๋ผ ์ƒ์ˆ˜๋กœ ๋ฐ”๊พธ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค!
@@ -0,0 +1,126 @@ +package store.view; + +import java.text.NumberFormat; +import store.domain.Product; +import store.domain.Products; +import store.dto.PurchaseDTO; +import store.dto.ReceiptDTO; + +public class OutputView { + private static final NumberFormat format = NumberFormat.getNumberInstance(); + + public static void printProducts(Products products) { + System.out.println(OutputMessage.OUTPUT_HELLO_CONVENIENCE_MESSAGE); + for (String product : products.getNames()) { + Product with = products.getItemWithPromotion(product); + Product without = products.getItemWithoutPromotion(product); + + printWith(with); + printWithout(without, with); + } + System.out.println(); + } + + private static void printWith(Product with) { + if (with != null) { + String price = getPrice(with); + String quantity = getQuantity(with); + String promotion = getPromotion(with); + System.out.println("- " + with.getName() + " " + price + " " + quantity + " " + promotion); + } + } + + private static void printWithout(Product without, Product with) { + if (without == null) { + String price = getPrice(with); + System.out.println("- " + with.getName() + " " + price + " ์žฌ๊ณ  ์—†์Œ"); + return; + } + String price = getPrice(without); + String quantity = getQuantity(without); + System.out.println("- " + without.getName() + " " + price + " " + quantity); + } + + public static void printReceipt(ReceiptDTO receiptDTO, boolean isMembership) { + printPurchaseItems(receiptDTO); + printFreeItems(receiptDTO); + printAccount(receiptDTO, isMembership); + } + + private static void printAccount(ReceiptDTO receiptDTO, boolean isMembership) { + System.out.println(OutputMessage.OUTPUT_RECEIPT_BOTTOM_MESSAGE); + printTotalPrice(receiptDTO); + printPromotionDiscount(receiptDTO); + printMembershipDiscount(receiptDTO, isMembership); + printPayment(receiptDTO, isMembership); + } + + private static void printPayment(ReceiptDTO receiptDTO, boolean isMembership) { + System.out.printf(OutputMessage.OUTPUT_RECEIPT_PAY_MESSAGE.format( + OutputMessage.TO_BE_PAID, + format.format(totalPayment(receiptDTO, isMembership)))); + System.out.println(); + } + + private static int totalPayment(ReceiptDTO receiptDTO, boolean isMembership) { + return receiptDTO.getTotalAmount() - receiptDTO.getFreeAmount() - receiptDTO.getMembershipAmount(isMembership); + } + + private static void printMembershipDiscount(ReceiptDTO receiptDTO, boolean isMembership) { + System.out.printf(OutputMessage.OUTPUT_RECEIPT_DISCOUNT_MESSAGE.format( + OutputMessage.MEMBERSHIP_DISCOUNT, + "-" + format.format(receiptDTO.getMembershipAmount(isMembership)))); + } + + private static void printPromotionDiscount(ReceiptDTO receiptDTO) { + System.out.printf(OutputMessage.OUTPUT_RECEIPT_DISCOUNT_MESSAGE.format( + OutputMessage.PROMOTION_DISCOUNT, + "-" + format.format(receiptDTO.getFreeAmount()))); + } + + private static void printTotalPrice(ReceiptDTO receiptDTO) { + System.out.printf(OutputMessage.OUTPUT_RECEIPT_PRODUCT_MESSAGE.format( + OutputMessage.TOTAL_PRICE, + receiptDTO.getTotalQuantity(), + format.format(receiptDTO.getTotalAmount()))); + } + + private static void printFreeItems(ReceiptDTO receiptDTO) { + System.out.println(OutputMessage.OUTPUT_RECEIPT_MIDDLE_MESSAGE); + for (PurchaseDTO purchaseDTO : receiptDTO.free()) { + System.out.printf(OutputMessage.OUTPUT_RECEIPT_FREE_MESSAGE.format( + purchaseDTO.name(), purchaseDTO.quantity())); + } + } + + private static void printPurchaseItems(ReceiptDTO receiptDTO) { + System.out.println(OutputMessage.OUTPUT_RECEIPT_TOP_MESSAGE); + for (PurchaseDTO purchaseDTO : receiptDTO.cart()) { + System.out.printf(OutputMessage.OUTPUT_RECEIPT_PRODUCT_MESSAGE.format( + purchaseDTO.name(), + purchaseDTO.quantity(), + format.format(purchaseDTO.getTotalAmount())) + ); + } + } + + private static String getPrice(Product product) { + return format.format(product.getPrice()) + OutputMessage.CURRENCY_UNIT; + } + + private static String getPromotion(Product product) { + String promotion = ""; + if (product.getPromotion() != null) { + promotion = product.getPromotion().getName(); + } + return promotion; + } + + private static String getQuantity(Product product) { + String quantity = format.format(product.getStock()) + OutputMessage.QUANTITY_UNIT; + if (product.getStock() == 0) { + quantity = OutputMessage.QUANTITY_EMPTY.toString(); + } + return quantity; + } +}
Java
๊ฐœ์ˆ˜๊ฐ€ 0์ด์–ด๋„ ์ถœ๋ ฅ์ด ๋˜๋˜๋ฐ, 0์ผ๋•Œ ์ถœ๋ ฅ์—์„œ ์ œ์™ธ์‹œํ‚ค๋Š” ๊ฒƒ๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
@@ -0,0 +1,108 @@ +package store.controller; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.time.LocalDateTime; +import java.util.List; +import org.junit.platform.commons.logging.Logger; +import org.junit.platform.commons.logging.LoggerFactory; +import store.contant.Constant; +import store.domain.Product; +import store.domain.Products; +import store.domain.Promotion; +import store.domain.Promotions; +import store.dto.ProductsDTO; +import store.dto.ReceiptDTO; +import store.exception.CustomException; +import store.exception.ErrorMessage; +import store.view.InputHandler; +import store.view.InputView; +import store.view.OutputView; + +public class ConvenienceManager { + private final Logger logger = LoggerFactory.getLogger(getClass()); + + private static final String PRODUCTS_FILE_PATH = Constant.PRODUCTS_FILE_PATH.toString(); + private static final String PROMOTIONS_FILE_PATH = Constant.PROMOTIONS_FILE_PATH.toString(); + + private Promotions promotions; + private Products products; + + public ConvenienceManager() { + try { + this.promotions = new Promotions(initPromotions()); + this.products = new Products(initProducts(this.promotions)); + } catch (IOException e) { + logger.info(ErrorMessage.FILE_IOEXCEPTION_MESSAGE::toString); + } + } + + public void run() { + try { + do { + OutputView.printProducts(products); + List<ProductsDTO> sameItems = products.getSameProducts(); + ReceiptDTO receiptDTO = products.buyProduct(sameItems); + membership(receiptDTO); + } while (hasRePurchase()); + } catch (CustomException e) { + System.out.println(e.getErrorMessage()); + } + } + + private void membership(ReceiptDTO receiptDTO) { + if (hasApplyMembership()) { + OutputView.printReceipt(receiptDTO, true); + return; + } + OutputView.printReceipt(receiptDTO, false); + } + + private List<Promotion> initPromotions() throws IOException { + List<String> strings = Files.readAllLines(Paths.get(PROMOTIONS_FILE_PATH)); + return strings.stream() + .skip(1) + .map(this::makePromotion) + .toList(); + } + + private List<Product> initProducts(Promotions promotions) throws IOException { + List<String> strings = Files.readAllLines(Paths.get(PRODUCTS_FILE_PATH)); + return strings.stream() + .skip(1) + .map(line -> makeProduct(promotions, line)) + .toList(); + } + + private Promotion makePromotion(String line) { + final String[] promotion = split(line); + final String name = promotion[0]; + final int buy = Integer.parseInt(promotion[1]); + final int get = Integer.parseInt(promotion[2]); + final LocalDateTime startDate = InputHandler.parseDate(promotion[3]); + final LocalDateTime endDate = InputHandler.parseDate(promotion[4]); + return new Promotion(name, buy, get, startDate, endDate); + } + + private Product makeProduct(Promotions promotions, String line) { + final String[] product = split(line); + final String name = product[0]; + final int price = Integer.parseInt(product[1]); + final int stock = Integer.parseInt(product[2]); + final Promotion promotion = promotions.findPromotion(product[3]); + return new Product(name, price, stock, promotion); + } + + private static String[] split(String line) { + return line.split(Constant.COMMA_DELIMITER.toString()); + } + + private boolean hasRePurchase() { + return InputView.readRePurchase().equals(Constant.Y.toString()); + } + + private boolean hasApplyMembership() { + return InputView.readMembership().equals(Constant.Y.toString()); + } +}
Java
์ด๋ ‡๊ฒŒ ๋˜๋ฉด ํ”„๋กœ๋ชจ์…˜ ๊ธฐ๊ฐ„์— ์ข…๋ฃŒ๋‚ ์งœ๊ฐ€ ์‚ฌ์‹ค ํฌํ•จ์ด ์•ˆ๋˜์–ด์„œ (์ข…๋ฃŒ๋‚ ์งœ๋กœ ๋„˜์–ด๊ฐ€๋Š” 00์‹œ 00๋ถ„ 00์ดˆ ๊นŒ์ง€๋งŒ ํฌํ•จ๋˜๋”๋ผ๊ตฌ์š”), endDate.plusDays(1) ์˜ .atStartOfDay() ๋ฅผ ์‚ฌ์šฉํ•˜๋Š”๊ฒŒ ๋” ๋งž๋‹ค๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค.
@@ -0,0 +1,141 @@ +package com.example.firstproject.controller; + +import com.example.firstproject.dto.ArticleDto; +import com.example.firstproject.dto.BoardDto; +import com.example.firstproject.entity.Article; +import com.example.firstproject.entity.Board; +import com.example.firstproject.service.ArticleService; +import com.example.firstproject.service.BoardService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; + +import java.util.List; + +@Controller +@RequiredArgsConstructor +@RequestMapping("article") +public class ArticleController { + private final ArticleService articleService; + private final BoardService boardService; + + // #.๊ฒŒ์‹œ๋ฌผ ์กฐํšŒ + @GetMapping("{id}") + public String readArticle(@PathVariable("id") Long id, Model model) { + ArticleDto article = articleService.read(id); + model.addAttribute("article", article); + return "article/read"; + } + + // #.๊ฒŒ์‹œ๋ฌผ ์ˆ˜์ • + @GetMapping("/{id}/update") + public String checkUpdatePasswordForm(@PathVariable("id") Long id, Model model) { + model.addAttribute("article", articleService.read(id)); + return "article/updateCheck"; + } + // @.๋น„๋ฐ€๋ฒˆํ˜ธ ํ™•์ธ + @PostMapping("/{id}/verify-update-password") + public String verifyUpdatePassword( + @PathVariable("id") Long id, + @RequestParam("password") String password + ) { + if (articleService.checkingPassword(id,password)) { + // ์ผ์น˜ ํ–ˆ์„ ์‹œ ์ˆ˜์ •ํผ์œผ๋กœ ์ด๋™ + return String.format("redirect:/article/%d/update-form",id); + } else { + // ํ‹€๋ ธ์„ ์‹œ ์—๋Ÿฌ ํŽ˜์ด์ง€๋กœ ์ด๋™ + return "redirect:/article/{id}/password-incorrect"; + } + } + // @.์ˆ˜์ •ํผ + @GetMapping("/{id}/update-form") + public String editForm(@PathVariable("id") Long id, Model model) { + model.addAttribute("article", articleService.read(id)); + return "article/update"; + } + + @PostMapping("/{id}/update-article") + public String updateArticle( + @PathVariable("id") Long id, + @RequestParam("title") String title, + @RequestParam("content") String content, + @RequestParam("password") String password + ) { + articleService.update(id,new ArticleDto(title,content,password)); + return String.format("redirect:/article/%d", id); + } + + + // #.๊ฒŒ์‹œ๋ฌผ ์‚ญ์ œ + @GetMapping("/{id}/delete") + public String checkDeletePasswordForm(@PathVariable("id") Long id, Model model) { + model.addAttribute("article", articleService.read(id)); + return "article/deleteCheck"; + } + // @.๋น„๋ฐ€๋ฒˆํ˜ธ ํ™•์ธ + @PostMapping("/{id}/verify-delete-password") + public String verifyDeletePassword( + @PathVariable("id") Long id, + @RequestParam("password") String password + ) { + if (articleService.checkingPassword(id,password)) { + // ์ผ์น˜ ํ–ˆ์„ ์‹œ ์‚ญ์ œํผ์œผ๋กœ ์ด๋™ + return String.format("redirect:/article/%d/delete-form",id); + } else { + // ํ‹€๋ ธ์„ ์‹œ ์—๋Ÿฌ ํŽ˜์ด์ง€๋กœ ์ด๋™ + return "redirect:/article/{id}/password-incorrect"; + } + } + // @.์‚ญ์ œํผ + @GetMapping("/{id}/delete-form") + public String deleteForm(@PathVariable("id") Long id, Model model) { + model.addAttribute("article", articleService.read(id)); + return "article/delete"; + } + + @PostMapping("/{id}/delete-article") + public String deleteArticle(@PathVariable("id") Long articleId, RedirectAttributes redirectAttributes) { + + articleService.delete(articleId); + Board foundBoard = articleService.findBoardByArticle(articleId); + + redirectAttributes.addAttribute("boardId",foundBoard.getId()); + + return "redirect:/boards/boardId"; + } + +// @GetMapping("/{id}/delete") +// public String deleteForm(@PathVariable("id")Long id, Model model) { +// model.addAttribute("article",articleService.read(id)); +// return "article/delete"; +// } +// @PostMapping("/{id}/delete-article") +// public String deleteArticle( +// @PathVariable("id")Long id, +// @RequestParam("password") String password +// ){ +// +// articleService.delete(id,password); +// +// return String.format("redirect:/article/%d",id); +// } + + + // #. ๋น„๋ฐ€๋ฒˆํ˜ธ๊ฐ€ ํ‹€๋ ธ์„ ์‹œ + @GetMapping("/{id}/password-incorrect") + public String incorrect(@PathVariable("id")Long id, Model model) { + model.addAttribute("article",articleService.read(id)); + return "article/incorrect"; + } + @PostMapping("/{id}/update-article/incorrect") + public String incorrectError(@PathVariable("id")Long id, Model model) { + model.addAttribute("article",articleService.read(id)); + return "redirect:/article/{id}"; + } + + + +} +
Java
delete ๋ฉ”์„œ๋“œ์™€ articleId๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋ฉ”์„œ๋“œ์˜ ์‹œ์ ์„ ๊ณ ๋ คํ•ด๋ณด์‹œ๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™์•„์š”
@@ -0,0 +1,41 @@ +package com.example.firstproject.controller; + +import com.example.firstproject.service.ArticleService; +import com.example.firstproject.service.BoardService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.*; + + +@Controller +@RequiredArgsConstructor +@RequestMapping("boards") +public class BoardController { + + private final BoardService boardService; + private final ArticleService articleService; + + + @GetMapping + public String readAllBoard(Model model){ + model.addAttribute("boards", boardService.readAllBoard()); + return "board/home"; + } + + + @GetMapping("{boardId}") + public String readBoard(@PathVariable("boardId") Long id, Model model) { + model.addAttribute("board", boardService.read(id)); + model.addAttribute("articles", boardService.readByBoardId(id)); + return "board/board"; + } + + // "์ „์ฒด ๊ฒŒ์‹œํŒ" + @GetMapping("/entire-board") + public String entireBoard(Model model) { + model.addAttribute("articles", boardService.readAll()); + return "board/entireBoard"; + } + +}
Java
/ ์Šฌ๋ž˜์‹œ์˜ ์œ ๋ฌด์— ๋”ฐ๋ฅธ ์ฐจ์ด์ ์„ ํ•จ๊ป˜ ๊ณต๋ถ€ํ•ด๋ด…์‹œ๋‹ค