# v2: 개발 환경 설정 및 더미 데이터 준비 ## 이번 단계에서 할 일 1. Node.js + TypeScript 프로젝트 초기화 2. Google Cloud 프로젝트 생성 3. Service Account 설정 4. 더미 재무 데이터 CSV 생성 ## 1. 프로젝트 초기화 ### 디렉토리 생성 및 npm 초기화 ```bash mkdir -p project cd project npm init -y ``` ### 필요한 패키지 설치 ```bash # TypeScript 및 기본 도구 npm install typescript ts-node @types/node --save-dev # Google APIs npm install googleapis @google-cloud/aiplatform # 유틸리티 npm install dotenv yargs csv-parse npm install @types/yargs --save-dev ``` ### package.json ```json { "name": "google-sheet-financial-dashboard", "version": "1.0.0", "description": "Google Sheet 재무 대시보드 자동화", "main": "dist/index.js", "scripts": { "build": "tsc", "start": "ts-node src/index.ts", "dev": "ts-node src/index.ts" }, "dependencies": { "@google-cloud/aiplatform": "^3.10.0", "csv-parse": "^5.5.0", "dotenv": "^16.3.0", "googleapis": "^128.0.0", "yargs": "^17.7.0" }, "devDependencies": { "@types/node": "^20.10.0", "@types/yargs": "^17.0.0", "ts-node": "^10.9.0", "typescript": "^5.3.0" } } ``` ### tsconfig.json ```json { "compilerOptions": { "target": "ES2020", "module": "commonjs", "lib": ["ES2020"], "outDir": "./dist", "rootDir": "./src", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "resolveJsonModule": true, "declaration": true }, "include": ["src/**/*"], "exclude": ["node_modules", "dist"] } ``` ## 2. Google Cloud 프로젝트 설정 ### 2.1 Google Cloud Console에서 프로젝트 생성 1. [Google Cloud Console](https://console.cloud.google.com) 접속 2. 새 프로젝트 생성: `financial-dashboard-project` 3. 프로젝트 ID 기록 (예: `financial-dashboard-12345`) ### 2.2 필요한 API 활성화 Google Cloud Console > APIs & Services > Enable APIs: | API | 용도 | |-----|------| | Google Sheets API | 스프레드시트 읽기/쓰기/차트 | | Google Drive API | 파일 권한 관리 | | Vertex AI API | Gemini 모델 사용 | ```bash # gcloud CLI로 API 활성화 (선택사항) gcloud services enable sheets.googleapis.com gcloud services enable drive.googleapis.com gcloud services enable aiplatform.googleapis.com ``` ### 2.3 Service Account 생성 1. IAM & Admin > Service Accounts > Create Service Account 2. 서비스 계정 이름: `sheets-dashboard-sa` 3. 역할 부여: - `Editor` (또는 필요한 최소 권한) 4. 키 생성 (JSON) > 다운로드 ### 2.4 서비스 계정 키 파일 저장 ```bash # 프로젝트 루트에 키 파일 저장 mv ~/Downloads/financial-dashboard-xxxxx.json ./service-account-key.json ``` ## 3. 환경 변수 설정 ### .env.example ```env # Google Cloud GOOGLE_PROJECT_ID=your-project-id GOOGLE_APPLICATION_CREDENTIALS=./service-account-key.json # Vertex AI VERTEX_AI_LOCATION=asia-northeast1 # Google Sheets (테스트용) TEST_SPREADSHEET_ID=your-test-spreadsheet-id ``` ### .env (실제 값으로 채우기) ```env GOOGLE_PROJECT_ID=financial-dashboard-12345 GOOGLE_APPLICATION_CREDENTIALS=./service-account-key.json VERTEX_AI_LOCATION=asia-northeast1 TEST_SPREADSHEET_ID=1ABC...XYZ ``` ### .gitignore ```gitignore # Dependencies node_modules/ # Build dist/ # Environment .env *.env.local # Credentials (절대 커밋 금지!) service-account-key.json *.json.key credentials*.json # IDE .vscode/ .idea/ # OS .DS_Store Thumbs.db ``` ## 4. 더미 재무 데이터 생성 ### 4.1 데이터 설계 12개월치(2024년) 일본 가정의 현실적인 재무 데이터를 생성합니다. #### 데이터 필드 | 필드 | 타입 | 설명 | 예시 | |------|------|------|------| | date | string | 거래일 (YYYY-MM-DD) | 2024-01-15 | | type | string | 수입/지출 | income / expense | | category | string | 대분류 | 식비, 주거비 | | subcategory | string | 소분류 | 외식, 월세 | | amount | number | 금액 (엔) | 85000 | | description | string | 상세 설명 | イオン, 月給 | | payment_method | string | 결제 수단 | 신용카드, 계좌이체 | #### 카테고리 구성 **수입 (Income)** | 카테고리 | 세부 | 금액 범위 | 빈도 | |----------|------|----------|------| | 급여 | 월급 | ¥340,000~370,000 | 매월 25일 | | 보너스 | 상여금 | ¥450,000~600,000 | 6월, 12월 | | 부수입 | 부업, 이자, 환급 | ¥1,000~50,000 | 랜덤 | **지출 (Expense)** | 카테고리 | 세부 | 금액 범위 | 월 빈도 | |----------|------|----------|--------| | 식비 | 식료품, 외식, 카페, 배달 | ¥500~15,000 | 15회 | | 주거비 | 월세, 관리비 | 고정 | 1회 | | 유틸리티 | 전기, 가스, 수도, 통신 | ¥3,000~15,000 | 각 1회 | | 교통비 | 전철, 버스, 택시 | ¥200~5,000 | 10회 | | 쇼핑 | 의류, 전자제품, 생활용품 | ¥500~30,000 | 4회 | | 의료비 | 병원, 약국 | ¥1,000~10,000 | 1회 | | 교육비 | 서적, 강의 | ¥1,000~5,000 | 2회 | | 엔터테인먼트 | 영화, 게임, 구독 | ¥500~8,000 | 4회 | | 보험료 | 생명보험 | 고정 ¥12,000 | 1회 | ### 4.2 데이터 생성 스크립트 `data/generate-dummy-data.js`: ```javascript /** * 더미 재무 데이터 생성 스크립트 * 2024년 1월 ~ 12월 (12개월치 거래 내역) */ const fs = require('fs'); // 랜덤 숫자 생성 (min ~ max) function rand(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } // 랜덤 날짜 생성 (해당 월 내) function randomDate(year, month) { const daysInMonth = new Date(year, month, 0).getDate(); const day = rand(1, daysInMonth); return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`; } // 결제 수단 const paymentMethods = ['현금', '신용카드', '체크카드', '계좌이체', 'PayPay', 'Suica']; // 지출 카테고리 설정 const expenseCategories = { '식비': { subcategories: ['식료품', '외식', '카페', '배달'], amountRange: [500, 15000], frequency: 15 }, '주거비': { subcategories: ['월세', '관리비'], fixed: { '월세': 85000, '관리비': 8000 } }, '유틸리티': { subcategories: ['전기', '가스', '수도', '인터넷', '휴대폰'], fixed: { '인터넷': 5500, '휴대폰': 8000 } }, // ... (전체 코드는 data/generate-dummy-data.js 참조) }; // 설명 템플릿 (일본어 상점명) const descriptions = { '식료품': ['イオン', 'セブンイレブン', 'ローソン', 'まいばすけっと'], '외식': ['すき家', '松屋', 'サイゼリヤ', 'マクドナルド', 'ラーメン屋'], '카페': ['スターバックス', 'ドトール', 'タリーズ', 'コメダ珈琲'], // ... }; function generateTransactions() { const transactions = []; const year = 2024; for (let month = 1; month <= 12; month++) { // 급여 (매월 25일) transactions.push({ date: `${year}-${String(month).padStart(2, '0')}-25`, type: 'income', category: '급여', subcategory: '월급', amount: 350000 + rand(-10000, 20000), description: '株式会社〇〇 給与', payment_method: '계좌이체' }); // 보너스 (6월, 12월) if (month === 6 || month === 12) { transactions.push({ date: `${year}-${String(month).padStart(2, '0')}-15`, type: 'income', category: '보너스', subcategory: '상여금', amount: 500000 + rand(-50000, 100000), description: month === 6 ? '夏季賞与' : '冬季賞与', payment_method: '계좌이체' }); } // 지출 항목들... } return transactions.sort((a, b) => a.date.localeCompare(b.date)); } // CSV 생성 및 저장 const transactions = generateTransactions(); const csv = toCSV(transactions); fs.writeFileSync('dummy-financial-data.csv', csv, 'utf-8'); console.log(`✅ 더미 데이터 생성 완료! 총 ${transactions.length}건`); ``` ### 4.3 생성된 데이터 확인 ```bash cd data node generate-dummy-data.js ``` 출력: ``` ✅ 더미 데이터 생성 완료! 총 거래 건수: 544 총 수입: ¥5,343,495 총 지출: ¥4,224,666 순저축: ¥1,118,829 ``` ### 4.4 CSV 데이터 샘플 ```csv date,type,category,subcategory,amount,description,payment_method 2024-01-02,expense,교통비,전철/버스,1074,JR,계좌이체 2024-01-02,expense,엔터테인먼트,영화,4565,イオンシネマ,PayPay 2024-01-03,expense,식비,식료품,6072,まいばすけっと,Suica 2024-01-04,expense,주거비,월세,85000,월세,계좌이체 2024-01-25,income,급여,월급,358432,株式会社〇〇 給与,계좌이체 ... ``` ## 5. 프로젝트 디렉토리 구조 현재까지 생성된 구조: ``` 20251201-create-google-sheet-financial-dashboard/ ├── data/ │ ├── generate-dummy-data.js ✅ 생성 완료 │ └── dummy-financial-data.csv ✅ 544건 데이터 ├── project/ │ ├── src/ (v3에서 생성) │ ├── .env.example ✅ 템플릿 │ ├── .env (사용자가 생성) │ ├── .gitignore ✅ │ ├── package.json ✅ │ ├── tsconfig.json ✅ │ └── service-account-key.json (사용자가 추가) ├── strategy.md ✅ └── create-google-sheet-financial-dashboard-v1.md ✅ ``` ## 6. Google Sheet 테스트용 준비 ### 테스트용 스프레드시트 생성 1. [Google Sheets](https://sheets.google.com) 접속 2. 새 스프레드시트 생성 3. URL에서 Doc ID 복사: - URL: `https://docs.google.com/spreadsheets/d/1ABC...XYZ/edit` - Doc ID: `1ABC...XYZ` ### 서비스 계정에 권한 부여 1. 스프레드시트 열기 2. "공유" 버튼 클릭 3. 서비스 계정 이메일 추가 (예: `sheets-dashboard-sa@project-id.iam.gserviceaccount.com`) 4. "편집자" 권한 부여 ## 다음 단계 v3에서는: - Google Sheets API 연동 코드 작성 - 서비스 계정 인증 구현 - 기본 CRUD 작업 (읽기/쓰기) - 더미 데이터를 Google Sheet에 import --- **작성일**: 2025-12-01 **상태**: ✅ 완료 **다음**: v3 - Google Sheets API 연동 기초