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 | 
d, e ๊ฐ ์ฐ์นํ๋๋ฐ ์ ๋๋ก ์ถ๋ ฅ๋๊ณ ์์ง ์๋ค์ ๐
|
@@ -0,0 +1,25 @@
+import java.util.List;
+
+/**
+ * @author jeongheekim
+ * @date 3/27/24
+ */
+public class FormattingUtil {
+ private FormattingUtil() {}
+
+ public static String formattingResult(List<String> list) {
+ StringBuilder sb = new StringBuilder();
+ int size = list.size();
+ for (int i = 0; i < size; i++) {
+ sb.append(list.get(i));
+ addComma(i, size, sb);
+ }
+ return sb.toString();
+ }
+
+ private static void addComma(int i, int size, StringBuilder sb) {
+ if (i < size - 1) {
+ sb.append(",");
+ }
+ }
+} | Java | > ๊ท์น 1: ํ ๋ฉ์๋์ ์ค์ง ํ ๋จ๊ณ์ ๋ค์ฌ์ฐ๊ธฐ(indent)๋ง ํ๋ค.
indent๊ฐ 2์ด์์ธ ๋ฉ์๋์ ๊ฒฝ์ฐ ๋ฉ์๋๋ฅผ ๋ถ๋ฆฌํ๋ฉด indent๋ฅผ ์ค์ผ ์ ์๋ค.
else๋ฅผ ์ฌ์ฉํ์ง ์์ indent๋ฅผ ์ค์ผ ์ ์๋ค.
์ธ๋ดํธ๊ฐ 2์ด์์ด๊ตฐ์ ๐ค |
@@ -0,0 +1,47 @@
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author jeongheekim
+ * @date 3/26/24
+ */
+public class Winner {
+ private List<String> winners = new ArrayList<>();
+ private int maxLength;
+
+ public void addWinner(String name) {
+ this.winners.add(name);
+ }
+
+ public void updateMaxLength(int length) {
+ this.maxLength = length;
+ }
+
+ public List<String> getWinners(Car[] cars) {
+ this.filterMaxLength(cars);
+ for (Car car : cars) {
+ this.checkWinnerCondition(car);
+ }
+ return this.winners;
+ }
+
+ private void filterMaxLength (Car[] cars) {
+ for (Car car : cars) {
+ int carStatusLength = car.getStatus().length();
+ this.compareMaxLength(carStatusLength);
+ }
+ }
+
+ private void compareMaxLength(int carStatusLength) {
+ if (this.maxLength <= carStatusLength) {
+ this.updateMaxLength(carStatusLength);
+ }
+ }
+
+ private void checkWinnerCondition(Car car) {
+ int statusLength = car.getStatus().length();
+ if (this.maxLength <= statusLength) {
+ this.addWinner(car.getName());
+ }
+ }
+} | Java | ๋ก์ง์ ๋ฌธ์ ๊ฐ ์๋๊ฒ ๊ฐ์์ ๐
์ฐ์น์๊ฐ ๋๋ฒ ์ถ๋ ฅ๋๊ณ ์์ต๋๋ค
 |
@@ -0,0 +1,47 @@
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author jeongheekim
+ * @date 3/26/24
+ */
+public class Winner {
+ private List<String> winners = new ArrayList<>();
+ private int maxLength;
+
+ public void addWinner(String name) {
+ this.winners.add(name);
+ }
+
+ public void updateMaxLength(int length) {
+ this.maxLength = length;
+ }
+
+ public List<String> getWinners(Car[] cars) {
+ this.filterMaxLength(cars);
+ for (Car car : cars) {
+ this.checkWinnerCondition(car);
+ }
+ return this.winners;
+ }
+
+ private void filterMaxLength (Car[] cars) {
+ for (Car car : cars) {
+ int carStatusLength = car.getStatus().length();
+ this.compareMaxLength(carStatusLength);
+ }
+ }
+
+ private void compareMaxLength(int carStatusLength) {
+ if (this.maxLength <= carStatusLength) {
+ this.updateMaxLength(carStatusLength);
+ }
+ }
+
+ private void checkWinnerCondition(Car car) {
+ int statusLength = car.getStatus().length();
+ if (this.maxLength <= statusLength) {
+ this.addWinner(car.getName());
+ }
+ }
+} | Java | ์๋์ฐจ์ ๊ธธ์ด๋ฅผ ๊บผ๋ด์ด ์ฒ๋ฆฌํ๊ณ ์๋ค์!
๋๋ฏธํฐ ๋ฒ์น์ ์ด๊ธ๋๊ณ ์์ต๋๋ค
๋ฉ์ธ์ง๋ฅผ ๋ณด๋ด์ด ์ฒ๋ฆฌํด๋ณด๋๊ฑด ์ด๋จ๊น์? ๐ค
https://mangkyu.tistory.com/147 |
@@ -1,7 +1,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 | / ์ฌ๋์์ ์ ๋ฌด์ ๋ฐ๋ฅธ ์ฐจ์ด์ ์ ํจ๊ป ๊ณต๋ถํด๋ด
์๋ค |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.