# AI智能记账 **Repository Path**: HelloWorld114/smart-ledger ## Basic Information - **Project Name**: AI智能记账 - **Description**: 一个功能完整的开源个人/家庭记账系统,包含前后端,支持多账户、多账本、AI智能记账、语音输入、OCR小票识别、数据报表、多人协同、预算管理、借贷跟踪等功能。 - **Primary Language**: NodeJS - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 3 - **Created**: 2026-07-22 - **Last Updated**: 2026-07-22 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 💰 Smart Ledger - AI-Powered Bookkeeping System A full-featured open-source personal/family bookkeeping system with frontend and backend, supporting multi-account, multi-ledger, AI smart bookkeeping, voice input, OCR receipt recognition, data reports, multi-user collaboration, budget management, loan tracking, and more. ## 🎯 Features ### ✅ Core Bookkeeping - [x] **Multi-type records**: Expense, Income, Transfer - [x] **Multi-account management**: Cash, WeChat, Alipay, Bank Card, Credit Card, Investments — with custom icons and types - [x] **Two-level category system**: - 11 top-level expense categories (Dining/Transport/Shopping/Entertainment/Housing/Healthcare/Education/Travel/Pets/Gifts/Other) - 7 top-level income categories (Salary/Bonus/Investment/Freelance/Gifts/Refunds/Other) - 3 top-level transfer categories (Account Transfer/Credit Card Payment/Top-up & Withdrawal) - 4-9 preset sub-categories under each top-level category, 80+ commonly used categories total - Support for manually adding custom sub-categories - [x] **Merchant/note association**: Auto-complete (datalist) during entry; new merchant names auto-created - [x] **Billing calendar view**: Monthly view of daily income/expense summaries; click a date to view details - [x] **Advanced filtering**: Multi-dimensional filtering by type, date range, top-level/sub-category - [x] **Quick date filters**: This month / Last month / This year / Last year with one click - [x] **Loan center**: Lent/borrowed records, installment repayment tracking, settlement marking, contact management ### ✅ AI Smart Bookkeeping (Powered by Zhipu GLM-4-Flash / GLM-4V-Flash, free models) - [x] **Natural Language Processing (NLP)**: Input "today's lunch delivery 30 yuan" to auto-recognize type/amount/category/account/date/note - [x] **AI quick entry bar**: Input box at the top of bills page — speak or type, one-click save without a popup - [x] **OCR receipt recognition**: Take a photo or select an image; GLM-4V-Flash multimodal model recognizes receipt amount and merchant - [x] **Voice bookkeeping**: 🎤 Speak naturally to convert to text, then AI parses and auto-fills the entire form; works in both the entry popup and the bills quick bar - [x] **AI bill analysis**: Analyze weekly/monthly/quarterly/yearly bills — spending structure, issue identification, financial advice, financial health score (0-100) - [x] **AI analysis history**: Each analysis result is auto-saved; view past analysis records anytime - [x] **Anomaly detection**: Compare last 30 days vs previous 30 days; auto-detect categories with >50% spending spikes and large expenses - [x] **Month-end forecast**: Based on daily average spending of elapsed days in the month, linearly predict month-end income/expense and balance - [x] **Smart budget recommendations**: Based on last 3 months of historical data, AI recommends next month's category budgets and spending advice - [x] **AI settings**: Configure API Key, model name, endpoint in the profile page; separate config for text and vision models ### ✅ Smart & Quick - [x] **Template bookkeeping**: Save frequent transactions as templates for one-click fill; check "also save as template" when recording to save both the record and template - [x] **Receipt photo upload**: Capture and save receipt photos during entry - [x] **Merchant auto-complete**: Datalist suggests historical merchants when typing notes - [x] **Floating action button**: Purple FAB in bottom-right corner to quickly open the entry popup ### ✅ Ledgers & Collaboration - [x] **Multi-ledger support**: Personal, family, travel, business scenarios; new ledgers auto-initialize categories and accounts - [x] **Multi-user collaboration**: Invite members to a ledger with editor/viewer permissions - [x] **Custom ledger icons**: Choose an emoji icon for each ledger - [x] **Ledger switching**: Top dropdown to quickly switch current ledger; data isolated per ledger ### ✅ Data Analysis & Reports - [x] **Home overview**: Monthly income/expense/balance cards, budget progress bars, Top 5 spending categories, last 5 records, quick links - [x] **Four-period reports**: Weekly/Monthly/Quarterly/Yearly, one-click switch - [x] **Category pie chart**: Toggle expense/income, auto-aggregates sub-categories to top-level - [x] **Category ranking**: Visual progress bars for top spending categories - [x] **Daily income/expense trend line chart**: Dual-line comparison of income vs expense; Canvas rendering with DPR high-res support - [x] **Period comparison bar chart**: Income vs expense across weekly/monthly/quarterly/yearly dimensions - [x] **Account dimension statistics**: Income/expense summary per account - [x] **Budget management**: Monthly total budget + category budgets; overspending red alert; visual progress bars - [x] **Net worth overview**: Home page displays total assets, total liabilities, net worth ### ✅ Other Features - [x] Light/Dark theme toggle (LocalStorage persistence) - [x] CSV export (UTF-8 BOM for Excel Chinese support) - [x] JSON full data backup export - [x] Fully responsive mobile H5 adaptation, supports iOS/Android - [x] JWT authentication + bcrypt password encryption - [x] Modular backend routes; frontend CSS/JS split per page - [x] Data permanently stored on your own server; API Key only saved server-side - [x] New user registration auto-copies system categories and default accounts ## 🛠️ Tech Stack - **Backend**: Node.js + Express + MySQL (mysql2/connection pool) - **Frontend**: Vanilla HTML/CSS/JS (no framework dependencies) - **Database**: MySQL 8.0+ (also supports 5.7) - **Auth**: JWT + bcryptjs - **AI**: Zhipu AI GLM-4-Flash (text) / GLM-4V-Flash (vision OCR) - **Voice**: Browser native Web Speech API (Chinese) - **Charts**: Native Canvas hand-drawn (no Chart.js dependency) ## 🚀 Deployment ### 1. Requirements - Node.js >= 18 (uses native fetch for AI API calls) - MySQL >= 5.7 - Zhipu AI API Key (free registration: https://open.bigmodel.cn) ### 2. Initialize Database ```bash mysql -u root -p ``` ```sql source /smart-ledger/server/init-db.sql; ``` This automatically creates the `smart_ledger` database, all table structures, and initializes default categories (80+) and default accounts. ### 3. Configure Database Connection Edit `server/db.js`, modify to your MySQL connection info: ```javascript const dbConfig = { host: 'localhost', user: 'root', password: 'your_password', database: 'smart_ledger', }; ``` ### 4. Configure AI Features (Optional) After starting the app, go to 「Profile → AI Smart Assistant」 and fill in: - API Endpoint: `https://open.bigmodel.cn/api/paas/v4/chat/completions` (default pre-filled) - API Key: Obtain from Zhipu AI Open Platform - Text Model: `glm-4-flash` (free) - Vision Model: `glm-4v-flash` (free) - Enable AI feature toggle Basic bookkeeping works without configuring AI. ### 5. Install Dependencies & Start ```bash cd server npm install npm start ``` The service runs on `http://localhost:3000` by default. Open it in your browser. Default admin account: `admin` / `123456` (recommend registering your own account). ### 6. Production Deployment Use PM2 for process management: ```bash npm install -g pm2 pm2 start server.js --name smart-ledger pm2 save pm2 startup ``` Configure Nginx reverse proxy (optional): ```nginx server { listen 80; server_name ledger.yourdomain.com; location / { proxy_pass http://127.0.0.1:3000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; client_max_body_size 10m; } } ``` ## 📱 Quick Usage Guide | Action | How | |--------|-----| | Record a transaction | Tap the + FAB in the bottom-right | | Voice entry | Tap 🎤 in the entry popup and speak, or in the bills quick bar | | AI text entry | Type "taxi 25 yuan" in the AI box at the top of the popup and tap Parse, or use the bills AI quick bar | | Photo receipt recognition | Tap 📷 in the bills AI quick bar to take a photo | | View calendar | Tap 「📅 Calendar」 button on bills page | | Filter bills | Tap 「🔍 Filter」 button on bills page; supports date/category filtering | | View reports | Switch to 「Reports」 in bottom nav; select Weekly/Monthly/Quarterly/Yearly | | AI analysis report | Tap 「🤖 AI Smart Analysis」 on reports page | | Switch ledger | Dropdown at top of 「Profile」 page | | Invite members | 「Profile」 → 「Member Management」 → Invite | | Export data | 「Profile」 → 「Export Data」 | | Dark mode | 「Profile」 → Toggle dark mode switch | ## 📂 Project Structure ``` smart-ledger/ ├── server/ # Backend code │ ├── server.js # Express server entry point │ ├── db.js # MySQL connection pool config │ ├── init-db.sql # Database init script (tables + 80+ system categories + defaults) │ ├── package.json │ ├── middleware/ │ │ └── auth.js # JWT auth + ledger permission middleware │ ├── routes/ # Modular routes │ │ ├── auth.js # Register/login/user info │ │ ├── books.js # Ledger CRUD, member invites │ │ ├── accounts.js # Account management │ │ ├── categories.js # Category management (2-level, auto-flattens legacy 3-level) │ │ ├── entities.js # Merchant/member/project management │ │ ├── records.js # Transaction CRUD, list/calendar queries │ │ ├── budgets.js # Budget management (total + category budgets) │ │ ├── loans.js # Loan/repayment management │ │ ├── reports.js # Report stats (pie/ranking/trend/comparison/accounts) │ │ ├── ai.js # AI capabilities: analysis/NLP parse/OCR/anomaly/prediction/budget recommend/history │ │ ├── settings.js # System config (AI config read/write) │ │ ├── upload.js # Receipt image upload │ │ └── export.js # CSV/JSON data export │ └── uploads/ # Uploaded file storage (auto-created) │ └── public/ # Frontend static files (multi-page architecture) ├── index.html # Home page (overview/budgets/rankings/recent records) ├── login.html # Login/register page ├── bills.html # Bills detail page (list + calendar dual view + AI quick bar) ├── accounts.html # Account management page (net worth / account CRUD) ├── reports.html # Data reports page (pie/trend/comparison/AI insights) ├── loans.html # Loan center page ├── profile.html # Profile page (ledger/theme/export/AI settings) ├── css/ │ ├── common.css # Common styles: variables, reset, nav, popup, entry components │ ├── login.css # Login page styles │ ├── home.css # Home page styles │ ├── bills.css # Bills page styles (calendar/filter/AI quick bar) │ ├── accounts.css # Account page styles │ ├── reports.css # Reports page styles (AI analysis/insight cards) │ ├── profile.css # Profile page styles │ └── loans.css # Loan center styles └── js/ ├── common.js # Common library: state/request/auth/entry popup/voice/category selection ├── home.js # Home page logic ├── bills.js # Bills page logic (list/calendar/filter/AI quick entry/OCR) ├── accounts.js # Account page logic ├── reports.js # Reports page logic (AI analysis/anomaly/prediction/budget recommend/history) ├── profile.js # Profile page logic (AI settings) └── loans.js # Loan center logic ``` ## 🔌 API Documentation ### Basic Endpoints | Endpoint | Method | Description | |----------|--------|-------------| | `/api/auth/register` | POST | User registration (auto-creates default ledger + categories + accounts) | | `/api/auth/login` | POST | User login | | `/api/auth/me` | GET/PUT | Get/update user info | | `/api/books` | GET/POST | List/create ledgers | | `/api/books/:id` | PUT/DELETE | Update/delete ledger | | `/api/books/:id/invite` | POST | Invite member for collaboration | | `/api/books/:id/members` | GET/DELETE | View/remove members | | `/api/accounts` | GET/POST | List/create accounts | | `/api/accounts/:id` | PUT/DELETE | Update/delete account | | `/api/categories` | GET/POST | List categories (2-level tree) / create | | `/api/categories/:id` | PUT/DELETE | Update/delete category | | `/api/entities` | GET/POST | List/create merchants/projects | | `/api/records` | GET/POST | List records (supports type/date/category filtering) / create | | `/api/records/:id` | PUT/DELETE | Update/delete record | | `/api/budgets` | GET/POST/DELETE | List/set/delete budgets | | `/api/loans` | GET/POST | List/create loans | | `/api/loans/:id/repay` | POST | Record repayment | | `/api/loans/:id/settle` | POST | Mark as settled | | `/api/reports/summary` | GET | Period report summary (income/categories/trends/accounts/comparison) | | `/api/upload/image` | POST | Receipt image upload | | `/api/export/csv` | GET | Export CSV table | | `/api/export/json` | GET | Export JSON backup | ### AI Endpoints | Endpoint | Method | Description | |----------|--------|-------------| | `/api/ai/analyze` | POST | AI bill analysis (weekly/monthly/quarterly/yearly) with financial health score; results auto-saved to history | | `/api/ai/parse` | POST | NLP natural language parse; input a sentence, returns structured bookkeeping data | | `/api/ai/ocr` | POST | Receipt OCR recognition (base64 image), uses GLM-4V-Flash vision model | | `/api/ai/anomaly` | POST | Anomaly detection (last 30 days vs previous 30 days, >50% growth alert + large expense days) | | `/api/ai/predict` | POST | Month-end income/expense forecast (linear projection + AI commentary) | | `/api/ai/budget-recommend` | POST | AI smart budget recommendations (based on 3 months history, returns category budgets + advice) | | `/api/ai/history` | GET | AI analysis history list (paginated) | | `/api/ai/history/:id` | GET/DELETE | View/delete a single history analysis | ### Config Endpoints | Endpoint | Method | Description | |----------|--------|-------------| | `/api/settings/ai` | GET/PUT | Get/update AI config (api_key securely masked) | ## 🗄️ Database Schema | Table | Description | |-------|-------------| | `users` | User accounts (bcrypt encrypted passwords) | | `books` | Ledgers (multi-ledger support) | | `book_members` | Ledger members (owner/editor/viewer permissions) | | `accounts` | Financial accounts (balance/type/icon) | | `categories` | Categories (2-level hierarchy, supports expense/income/transfer) | | `entities` | Merchants/members/projects | | `records` | Transaction records (core trade records) | | `budgets` | Monthly budgets (total + category budgets) | | `loans` | Loan records (lent/borrowed) | | `loan_records` | Repayment records | | `sys_config` | System config (AI Key/models etc., global) | | `ai_analysis_history` | AI analysis history (persists each analysis result) | ## 🔒 Data Security - All data stored on your own server; never uploaded to any third party - AI API Key only saved in server-side database; masked when returned via frontend API - Passwords stored with bcrypt encryption - JWT token valid for 30 days - All API endpoints require JWT authentication; ledger data isolated via member permissions - HTTPS can be configured for transport security ## 🄯 License MIT