HTTP, CSS, JavaScript, 그리고 PostgreSQL을 사용하여 간단한 가계부 웹 애플리케이션을 만들 수 있습니다. 이 애플리케이션은 수입 및 지출 데이터를 입력하고, 이를 PostgreSQL 데이터베이스에 저장하며, 화면에 표시하는 기능을 포함합니다.
### 프로젝트 구조
```
/gagyeebu
├── index.html # 메인 페이지
├── style.css # CSS 파일
├── script.js # JavaScript 파일
└── server.js # 서버 스크립트 (Node.js + Express)
```
### 1. `index.html` - 메인 페이지
HTML 구조를 만들고, 수입 및 지출을 입력하는 폼과 기록을 보여줄 테이블을 포함합니다.
```html
가계부
개인 가계부
날짜
항목
수입
지출
잔액
```
### 2. `style.css` - 스타일링
간단한 CSS로 페이지를 스타일링합니다.
```css
body {
font-family: Arial, sans-serif;
margin: 20px;
padding: 0;
background-color: #f4f4f4;
}
h1 {
text-align: center;
}
form {
display: flex;
justify-content: space-between;
margin-bottom: 20px;
}
label {
margin-right: 10px;
}
input {
margin-right: 20px;
}
button {
padding: 5px 15px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
th, td {
padding: 10px;
text-align: left;
border-bottom: 1px solid #ddd;
}
```
### 3. `script.js` - 클라이언트 사이드 스크립트
JavaScript로 폼 제출을 처리하고, 서버와 상호작용하는 코드를 작성합니다.
```javascript
document.getElementById('transaction-form').addEventListener('submit', function(event) {
event.preventDefault();
const date = document.getElementById('date').value;
const description = document.getElementById('description').value;
const income = document.getElementById('income').value || 0;
const expense = document.getElementById('expense').value || 0;
const data = { date, description, income, expense };
fetch('/add-transaction', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => {
if (data.success) {
addTransactionToTable(date, description, income, expense, data.balance);
} else {
alert('Error: ' + data.error);
}
});
});
function addTransactionToTable(date, description, income, expense, balance) {
const table = document.getElementById('transactions-table').getElementsByTagName('tbody')[0];
const newRow = table.insertRow();
const dateCell = newRow.insertCell(0);
const descriptionCell = newRow.insertCell(1);
const incomeCell = newRow.insertCell(2);
const expenseCell = newRow.insertCell(3);
const balanceCell = newRow.insertCell(4);
dateCell.textContent = date;
descriptionCell.textContent = description;
incomeCell.textContent = income;
expenseCell.textContent = expense;
balanceCell.textContent = balance;
}
```
### 4. `server.js` - 서버 사이드 스크립트 (Node.js + Express + PostgreSQL)
Node.js와 Express를 사용해 서버를 구축하고, PostgreSQL과 연결하여 데이터를 저장합니다.
#### 4.1 `server.js` 파일 작성
```javascript
const express = require('express');
const bodyParser = require('body-parser');
const { Pool } = require('pg');
const app = express();
app.use(bodyParser.json());
app.use(express.static('public'));
const pool = new Pool({
user: 'username',
host: 'localhost',
database: 'gagyeebu',
password: 'password',
port: 5432,
});
app.post('/add-transaction', async (req, res) => {
const { date, description, income, expense } = req.body;
try {
await pool.query(
'INSERT INTO transactions (date, description, income, expense) VALUES ($1, $2, $3, $4)',
[date, description, income, expense]
);
const result = await pool.query('SELECT SUM(income - expense) AS balance FROM transactions');
const balance = result.rows[0].balance;
res.json({ success: true, balance });
} catch (error) {
console.error(error);
res.json({ success: false, error: 'Database error' });
}
});
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
```
### 5. PostgreSQL 테이블 생성
PostgreSQL에 테이블을 생성하는 SQL 명령어입니다.
```sql
CREATE DATABASE gagyeebu;
\c gagyeebu;
CREATE TABLE transactions (
id SERIAL PRIMARY KEY,
date DATE NOT NULL,
description VARCHAR(255) NOT NULL,
income NUMERIC(10, 2) DEFAULT 0.00,
expense NUMERIC(10, 2) DEFAULT 0.00
);
```
### 요약
- `index.html`: 사용자가 데이터를 입력할 수 있는 메인 페이지.
- `style.css`: 페이지 스타일링을 위한 CSS 파일.
- `script.js`: 폼 제출을 처리하고 서버와 통신하는 JavaScript 파일.
- `server.js`: Node.js와 Express를 사용해 서버를 구성하고 PostgreSQL에 데이터를 저장하는 서버 스크립트.
이 구조를 활용해 웹 기반의 간단한 가계부를 구축할 수 있습니다. 로컬 환경에서 이 프로젝트를 실행하려면, Node.js, Express, PostgreSQL이 필요하며, 각 파일을 해당 서버에 배치하고 `server.js`를 실행해야 합니다.