Fix all 5 deploy gaps: nginx real-IP, volume chown entrypoint, chat cascade migration, template seed, frontend build Makefile

This commit is contained in:
Atharv1705
2026-10-02 16:07:04 +05:30
parent 818185e931
commit 31fbc85565
7 changed files with 133 additions and 51 deletions
-43
View File
@@ -1,43 +0,0 @@
# DATABASE
MYSQL_HOST=localhost
MYSQL_PORT=3306
MYSQL_USER=root
MYSQL_PASSWORD=***REDACTED_PASSWORD***
MYSQL_DATABASE=bookkeepprodb
# SECURITY
SECRET_KEY=9b1c87299fb35d124dd57657e5469bf1d11539c6f05ae2ee4e86fb47b0b4742d
JWT_ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=480
# SERVER SETTINGS
FRONTEND_URL=https://aicpa.duckdns.org/
ALLOWED_ORIGINS=https://aicpa.duckdns.org/
# EMAIL (Gmail SMTP)
ADMIN_EMAIL=atharvg.aiindia@gmail.com
MAIL_FROM=atharvagunjarge5@gmail.com
MAIL_FROM_NAME=BookKeepro
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=atharvagunjarge5@gmail.com
SMTP_PASSWORD=YOUR_NEW_GMAIL_APP_PASSWORD_HERE
SMTP_TLS=True
MAIL_SSL_TLS=False
# GOOGLE DRIVE (If used)
DRIVE_FOLDER_ID=YOUR_NEW_DRIVE_FOLDER_ID_HERE
# OPENROUTER (For Chatbot + OCR)
OPENROUTER_API_KEY=YOUR_NEW_OPENROUTER_KEY_HERE
# OCR Model Config (optional — defaults used if not set)
OCR_TEXT_MODEL=meta-llama/llama-3.3-70b-instruct
OCR_VISION_MODEL=qwen/qwen2.5-vl-72b-instruct
OCR_FALLBACK_MODEL=google/gemma-3-27b-it
# Tesseract language pack (e.g. eng+hin, eng+tam, eng)
TESSERACT_LANG=eng+hin
# Chat model for chatbot
CHAT_MODEL=meta-llama/llama-3.3-70b-instruct
+13 -7
View File
@@ -6,12 +6,14 @@ ENV PYTHONDONTWRITEBYTECODE=1 \
WORKDIR /app
# System deps: Tesseract OCR (Stage 2 of extraction pipeline — CPU-only, no GPU)
# eng: English, hin: Hindi — for bilingual Indian documents (Aadhaar, PAN, etc.)
# System deps: Tesseract OCR (Stage 2 of extraction pipeline -- CPU-only, no GPU)
# eng: English, hin: Hindi -- for bilingual Indian documents (Aadhaar, PAN, etc.)
# su-exec: lightweight tool to drop privileges in the entrypoint script
RUN apt-get update && apt-get install -y --no-install-recommends \
tesseract-ocr \
tesseract-ocr-eng \
tesseract-ocr-hin \
su-exec \
libgl1 \
curl \
&& rm -rf /var/lib/apt/lists/*
@@ -23,23 +25,27 @@ RUN pip install --upgrade pip && pip install -r /tmp/requirements.txt
# Copy app source
COPY . /app
# Copy entrypoint -- runs as root to fix volume ownership, then drops to appuser
COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
# Create non-root user and ensure directories exist for volume mounts
RUN useradd -m appuser && \
mkdir -p /app/uploads /app/services/api/chroma_db && \
chown -R appuser:appuser /app
USER appuser
WORKDIR /app/services/api
EXPOSE 8000
# --forwarded-allow-ips=* trusts X-Forwarded-For from nginx container
# Required so rate limiter and audit logs see real client IPs (not nginx's internal IP)
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
CMD curl -f http://localhost:8000/health || exit 1
# Entrypoint: fixes volume ownership, runs migrations, then drops to appuser
ENTRYPOINT ["/entrypoint.sh"]
# --forwarded-allow-ips=* trusts X-Forwarded-For from nginx container
# Required so rate limiter and audit logs see real client IPs (not nginx internal IP)
# B6 Fix: Drop --workers 4 to prevent scheduler from running 4 times concurrently
CMD ["uvicorn", "app.main:app", \
"--host", "0.0.0.0", \
+40
View File
@@ -0,0 +1,40 @@
# Makefile -- Production deploy helpers for BookKeepro
# Usage on the server: make deploy
.PHONY: deploy build-frontend up down logs restart
## Full deploy: pull, build frontend, rebuild Docker images, restart stack
deploy: build-frontend
docker compose down --remove-orphans
docker compose build --no-cache app
docker compose up -d
@echo "[deploy] Done. Check logs with: make logs"
## Build the React frontend into frontend/dist (required before nginx starts)
## frontend/dist is intentionally NOT in git -- always build on the server.
build-frontend:
@echo "[build] Installing frontend dependencies..."
cd frontend && npm ci --prefer-offline
@echo "[build] Building production bundle..."
cd frontend && npm run build
@echo "[build] frontend/dist is ready."
## Start the stack (assumes frontend/dist already built)
up:
docker compose up -d
## Stop the stack
down:
docker compose down
## Tail logs for all services
logs:
docker compose logs -f --tail=100
## Restart only the app container (e.g. after config change)
restart:
docker compose restart app
## Run DB migrations manually inside the running container
migrate:
docker compose exec app python migrate.py
+16
View File
@@ -0,0 +1,16 @@
#!/bin/sh
# entrypoint.sh -- fix volume ownership then drop to appuser
# Runs as root (before USER appuser in Dockerfile) so it can chown.
# The CMD is then exec'd as appuser via gosu/su-exec.
set -e
# Fix ownership of bind-mounted volumes that may have been created by root.
chown -R appuser:appuser /app/uploads /app/services/api/chroma_db 2>/dev/null || true
# Run migrations
echo "[entrypoint] Running DB migrations..."
su-exec appuser python /app/services/api/migrate.py
# Hand off to the real command (uvicorn) as appuser
echo "[entrypoint] Starting app as appuser..."
exec su-exec appuser "$@"
+9
View File
@@ -1,4 +1,12 @@
server {
# -- Real-IP: trust the Docker bridge so rate-limit keying uses the
# actual client IP, not the shared proxy/bridge address. ----------
set_real_ip_from 172.16.0.0/12; # Docker default bridge range
set_real_ip_from 10.0.0.0/8; # Common overlay networks
set_real_ip_from 127.0.0.1; # local loopback (dev)
real_ip_header X-Forwarded-For;
real_ip_recursive on;
listen 80;
server_name aicpa.duckdns.org 13.140.170.213;
# Security Headers
@@ -96,3 +104,4 @@ server {
}
+1 -1
View File
@@ -220,7 +220,7 @@ class ChatMessage(Base):
__tablename__ = "chat_messages"
id = Column(Integer, primary_key=True, index=True)
session_id = Column(Integer, ForeignKey("chat_sessions.id"), nullable=False)
session_id = Column(Integer, ForeignKey("chat_sessions.id", ondelete="CASCADE"), nullable=False)
role = Column(String(50), nullable=False) # 'user', 'assistant', 'system', 'tool'
content = Column(Text, nullable=True)
tool_calls = Column(JSON, nullable=True)
+54
View File
@@ -144,6 +144,59 @@ def upgrade():
print(" [OK] Backfilled uploaded events for admin_documents")
except Exception as e:
print(f" [WARN] Backfill uploaded events: {e}")
# -- v7: Chat history cascade -- existing DBs need the FK fixed ----
# SQLAlchemy ORM cascade handles Python-side deletes, but the DB-level
# constraint is required when MySQL cascades from a parent delete directly.
for stmt in [
"ALTER TABLE chat_messages DROP FOREIGN KEY chat_messages_ibfk_1",
"ALTER TABLE chat_messages ADD CONSTRAINT fk_chat_messages_session FOREIGN KEY (session_id) REFERENCES chat_sessions(id) ON DELETE CASCADE",
]:
try:
conn.execute(text(stmt))
print(f" [OK] {stmt[:70]}...")
except (OperationalError, ProgrammingError) as e:
msg = str(e).lower()
if "duplicate" in msg or "already exists" in msg or "can't drop" in msg or "check that column" in msg:
print(f" [SKIP] Already applied or key not found: {stmt[:50]}...")
else:
print(f" [WARN] {e}")
# -- v8: Seed required_document_templates for fresh databases ---------
# On a fresh DB the table exists but is empty. Seed 10 default templates
# for both personal and business categories so users see a checklist.
try:
count = conn.execute(text("SELECT COUNT(*) FROM required_document_templates")).scalar()
if count == 0:
import datetime
current_year = datetime.date.today().year
personal_docs = [
"W-2 Form", "1099-NEC / 1099-MISC", "SSA-1099 (Social Security Benefits)",
"Mortgage Interest Statement (1098)", "Charitable Donation Receipts",
"Medical & Dental Expense Receipts", "Student Loan Interest (1098-E)",
"State & Local Tax Payment Records", "Investment Income (1099-B / 1099-DIV)",
"Prior Year Tax Return",
]
business_docs = [
"Profit & Loss Statement", "Balance Sheet",
"Bank Statements (All Accounts)", "Business Expense Receipts",
"Payroll Records / W-3", "1099s Issued to Contractors",
"Vehicle Mileage Log", "Home Office Documentation",
"Business Asset Purchase Invoices", "Prior Year Business Tax Return",
]
for name in personal_docs:
conn.execute(text(
"INSERT IGNORE INTO required_document_templates (category, tax_year, name) VALUES ('personal', :yr, :name)"
), {"yr": current_year, "name": name})
for name in business_docs:
conn.execute(text(
"INSERT IGNORE INTO required_document_templates (category, tax_year, name) VALUES ('business', :yr, :name)"
), {"yr": current_year, "name": name})
print(f" [OK] Seeded {len(personal_docs)} personal + {len(business_docs)} business templates for {current_year}")
else:
print(f" [SKIP] required_document_templates already has {count} rows")
except Exception as e:
print(f" [WARN] Template seed: {e}")
print("\nAll migrations complete.")
except Exception as e:
@@ -152,3 +205,4 @@ def upgrade():
if __name__ == "__main__":
upgrade()