Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
.git
.gitignore
.claude
.pytest_cache
**/.pytest_cache
**/__pycache__
**/*.pyc
**/node_modules
**/.env
**/.env.*
!**/.env.example
frontend/dist
docs
backend/venv
venv
.venv
103 changes: 103 additions & 0 deletions .github/workflows/docker-publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
name: docker-publish

on:
push:
branches: [main]
tags: ["v*"]
pull_request:
workflow_dispatch:

permissions:
contents: read

jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: "20"
cache: npm
cache-dependency-path: frontend/package-lock.json

- name: Build frontend
working-directory: frontend
run: |
npm ci
npm run build

- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3

- name: Build backend test image
uses: docker/build-push-action@v6
with:
context: .
target: backend
load: true
tags: invoice-manager:ci-test
cache-from: type=gha,scope=backend
cache-to: type=gha,mode=max,scope=backend

- name: Run backend tests
run: docker run --rm invoice-manager:ci-test python -m pytest -q

image:
needs: test
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@v4

- name: Set up QEMU
uses: docker/setup-qemu-action@v3

- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3

- name: Log in to GHCR
if: github.event_name != 'pull_request'
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}

- name: Log in to Docker Hub
if: github.event_name != 'pull_request' && vars.DOCKERHUB_ENABLED == 'true' && vars.DOCKERHUB_NAMESPACE != ''
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}

- name: Extract Docker metadata
id: meta
uses: docker/metadata-action@v5
with:
images: |
ghcr.io/stone16/invoice-manager
name=docker.io/${{ vars.DOCKERHUB_NAMESPACE || 'placeholder' }}/invoice-manager,enable=${{ vars.DOCKERHUB_ENABLED == 'true' && vars.DOCKERHUB_NAMESPACE != '' }}
flavor: |
latest=auto
tags: |
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=edge,branch=main
type=sha

- name: Build and push Docker image
uses: docker/build-push-action@v6
with:
context: .
target: app
platforms: ${{ github.event_name == 'pull_request' && 'linux/amd64' || 'linux/amd64,linux/arm64' }}
push: ${{ github.event_name != 'pull_request' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha,scope=app
cache-to: type=gha,mode=max,scope=app
46 changes: 46 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# syntax=docker/dockerfile:1

FROM --platform=$BUILDPLATFORM node:20-alpine AS web
WORKDIR /web
COPY frontend/package*.json ./
RUN npm ci
COPY frontend/ .
RUN npm run build

FROM python:3.11-slim-bookworm AS backend
WORKDIR /app

# Install system dependencies for PaddleOCR and PDF rendering with retry
RUN for i in 1 2 3 4 5; do \
apt-get update && apt-get install -y --no-install-recommends \
libgomp1 \
libglib2.0-0 \
libgl1 \
libsm6 \
libxext6 \
libxrender1 \
poppler-utils \
&& rm -rf /var/lib/apt/lists/* \
&& break; \
if [ "$i" -eq 5 ]; then exit 1; fi; \
sleep 15; \
done

# Install Python dependencies
COPY backend/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy backend application
COPY backend/ .

EXPOSE 18080

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "18080"]

FROM backend AS app
COPY --from=web /web/dist /app/static
ENV INVOICE_ENV_FILE=/data/.env \
DEBUG=false
VOLUME ["/data", "/root/.paddleocr"]
HEALTHCHECK --interval=15s --timeout=5s --start-period=60s --retries=5 \
CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:18080/api/health', timeout=4)"
48 changes: 31 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -204,28 +204,38 @@

## 🚀 快速开始 | Quick Start

### 最简3步启动 | 3 Steps to Start
### 方式一:普通用户 / NAS 免构建部署(推荐)

无需克隆代码,无需手工创建 `.env`,直接拉取单镜像即可启动(支持 x86_64 与 ARM64):

```bash
# 1. 克隆项目 | Clone
git clone https://github.com/YOUR_USERNAME/invoice_manager.git
cd invoice_manager
# 下载编排文件并启动(NAS 用户可直接复制 deploy/docker-compose.yml 到 Docker 项目面板)
curl -fsSLO https://raw.githubusercontent.com/stone16/Invoice-Manager/main/deploy/docker-compose.yml
docker compose up -d
```

# 2. 配置LLM (可选) | Configure LLM (Optional)
# 在 backend/.env 中设置 API Key,或稍后在界面中配置
# Set API Key in backend/.env, or configure later in UI
- 浏览器访问:`http://<设备或NAS的IP>:15173`(部署在 NAS 上请勿使用 `localhost`)
- API 文档:`http://<设备或NAS的IP>:15173/docs`
- 详细 NAS(绿联 / 群晖 / 威联通 / 飞牛 fnOS)图文步骤与 FAQ 请查看 **[`deploy/README.md`](deploy/README.md)**。

# 3. 启动服务 | Start Services
docker-compose up -d
### 方式二:开发者源码启动

```bash
# 1. 克隆项目 | Clone
git clone https://github.com/stone16/Invoice-Manager.git
cd Invoice-Manager

# 2. 启动服务(无需提前创建 backend/.env,LLM 可在界面「设置」中配置)
docker compose up -d --build
```

### 访问地址 | Access URLs

| 服务 | 地址 | 说明 |
|-----|------|------|
| 前端界面 | http://localhost:15173 | 主操作界面 |
| 后端 API | http://localhost:18080 | REST API |
| API 文档 | http://localhost:18080/docs | Swagger UI |
| 服务 | 单镜像 / NAS 部署 | 开发者源码模式 | 说明 |
|-----|-----------------|--------------|------|
| 前端界面 | `http://<IP>:15173` | `http://localhost:15173` | 主操作界面 |
| API 文档 | `http://<IP>:15173/docs` | `http://localhost:18080/docs` | Swagger UI |
| 后端直连 | (同源 `/api`) | `http://localhost:18080` | 开发调试用 REST API |

### 配置 LLM | Configure LLM

Expand Down Expand Up @@ -408,8 +418,7 @@ invoice_manager/
│ │ ├── schemas/ # Pydantic 数据验证
│ │ ├── config.py # 配置管理
│ │ └── main.py # 应用入口
│ ├── requirements.txt
│ └── Dockerfile
│ └── requirements.txt
│
├── frontend/ # React 前端
│ ├── src/
Expand Down Expand Up @@ -439,7 +448,12 @@ invoice_manager/
│ ├── invoice-manager.pen # UI 设计稿 (Pencil)
│ └── UI_REDESIGN.md # 设计规范文档
│
├── docker-compose.yml # 容器编排
├── deploy/ # NAS / 免构建单镜像部署
│ ├── docker-compose.yml # 2 容器生产编排
│ └── README.md # NAS 中文部署指南与 FAQ
│
├── Dockerfile # 多阶段构建(web → backend → app)
├── docker-compose.yml # 开发者源码编排
└── README.md
```

Expand Down
13 changes: 9 additions & 4 deletions backend/.env.example
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
# 可选文件:不创建也可直接启动;LLM 也可以在启动后通过 Web 界面「设置」配置并自动保存。
DATABASE_URL=postgresql+asyncpg://postgres:postgres@db:5432/invoice_db
OPENAI_API_KEY=your_openai_api_key_here
OPENAI_MODEL=gpt-4o-mini
# Optional: require token to configure LLM via API
LLM_CONFIG_TOKEN=

# 如需通过环境变量预配置 LLM,取消注释并填入真实 API Key
# OPENAI_API_KEY=
# OPENAI_MODEL=gpt-4o-mini

# 可选:管理员口令。设置后,通过界面或 API 修改 LLM 配置时需要输入该口令
# LLM_CONFIG_TOKEN=

DEBUG=true
28 changes: 0 additions & 28 deletions backend/Dockerfile

This file was deleted.

18 changes: 15 additions & 3 deletions backend/app/config.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
from pydantic_settings import BaseSettings, SettingsConfigDict
import os
from functools import lru_cache
from typing import Optional
from pydantic_settings import BaseSettings, SettingsConfigDict


def get_env_file_path() -> str:
"""Return the configured .env file path (defaults to '.env')."""
return os.getenv("INVOICE_ENV_FILE") or ".env"


ENV_FILE = get_env_file_path()


class Settings(BaseSettings):
Expand All @@ -11,6 +20,9 @@ class Settings(BaseSettings):
# Supported providers: openai, anthropic, google, qwen, deepseek, zhipu
llm_provider: str = "" # Active provider (empty = not configured)

# Optional admin token for /api/settings/llm/configure
llm_config_token: str = ""

# OpenAI
openai_api_key: str = ""
openai_model: str = "gpt-4o-mini"
Expand Down Expand Up @@ -55,7 +67,7 @@ class Settings(BaseSettings):
# App
debug: bool = True

model_config = SettingsConfigDict(env_file=".env")
model_config = SettingsConfigDict(env_file=ENV_FILE, extra="ignore")

def get_active_llm_provider(self) -> Optional[str]:
"""Get the active LLM provider based on configuration."""
Expand Down Expand Up @@ -86,7 +98,7 @@ def is_llm_configured(self) -> bool:

@lru_cache
def get_settings() -> Settings:
return Settings()
return Settings(_env_file=get_env_file_path())


def clear_settings_cache():
Expand Down
42 changes: 37 additions & 5 deletions backend/app/main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from fastapi import FastAPI, Request
from pathlib import Path
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from slowapi.errors import RateLimitExceeded

from app.config import get_settings
Expand Down Expand Up @@ -48,6 +50,36 @@ async def startup():
await conn.run_sync(Base.metadata.create_all)


@app.get("/")
async def root():
return {"message": "发票管理系统 API", "version": "1.0.0"}
def mount_spa(target_app: FastAPI, static_dir: Path) -> None:
"""Mount built SPA static assets and catch-all fallback on target_app."""
resolved_static_dir = static_dir.resolve()
assets_dir = resolved_static_dir / "assets"
if assets_dir.is_dir():
target_app.mount("/assets", StaticFiles(directory=assets_dir), name="assets")

@target_app.get("/{full_path:path}", include_in_schema=False)
async def serve_spa(full_path: str):
if full_path == "api" or full_path.startswith("api/"):
raise HTTPException(status_code=404, detail="Not Found")
if full_path:
try:
candidate = (resolved_static_dir / full_path).resolve()
is_safe_file = (
resolved_static_dir in candidate.parents
and candidate.is_file()
)
except (ValueError, OSError):
raise HTTPException(status_code=404, detail="Not Found")
if is_safe_file:
return FileResponse(candidate)
return FileResponse(resolved_static_dir / "index.html")


STATIC_DIR = (Path(__file__).resolve().parent.parent / "static").resolve()

if STATIC_DIR.is_dir():
mount_spa(app, STATIC_DIR)
else:
@app.get("/")
async def root():
return {"message": "发票管理系统 API", "version": "1.0.0"}
Loading
Loading