File size: 4,679 Bytes
eaefa6e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a57867a
eaefa6e
 
 
 
 
 
a57867a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eaefa6e
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
import os
from datetime import datetime
from typing import List, Optional

from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field, constr
from sqlmodel import SQLModel, Field as SQLField, Session, create_engine, select


DB_URL = os.getenv("DATABASE_URL", "sqlite:////data/data.db")
engine = create_engine(DB_URL, connect_args={"check_same_thread": False} if DB_URL.startswith("sqlite") else {})


class Feedback(SQLModel, table=True):
    id: Optional[int] = SQLField(default=None, primary_key=True)
    rating: int
    features: Optional[str] = None
    comments: str
    ts: datetime = SQLField(default_factory=datetime.utcnow)
    ua: Optional[str] = None


class FeedbackIn(BaseModel):
    rating: int = Field(ge=1, le=5)
    features: Optional[str] = None
    comments: str = Field(min_length=10)
    ts: Optional[str] = None
    ua: Optional[str] = None


def init_db():
    # Ensure sqlite directory exists
    if DB_URL.startswith("sqlite"):
        # Extract filesystem path from URL
        # Formats we handle: sqlite:///relative.db, sqlite:////absolute.db
        path = DB_URL.split("sqlite:///")[-1]
        if path.startswith("/") and not DB_URL.startswith("sqlite:////"):
            # Normalize accidental triple slash
            pass
        # If absolute path like /data/data.db, ensure parent exists
        dirpath = os.path.dirname("/" + path if not path.startswith("/") else path)
        if dirpath and not os.path.isdir(dirpath):
            os.makedirs(dirpath, exist_ok=True)
    SQLModel.metadata.create_all(engine)


app = FastAPI(title="BKP Feedback API")

# CORS: allow all by default for ease of deployment; tighten in production
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.on_event("startup")
def on_startup():
    init_db()


@app.get("/health")
def health():
    return {"status": "ok"}


@app.post("/api/feedback")
def create_feedback(item: FeedbackIn):
    fb = Feedback(
        rating=item.rating,
        features=item.features,
        comments=item.comments,
        ts=datetime.fromisoformat(item.ts.replace("Z", "+00:00")) if item.ts else datetime.utcnow(),
        ua=item.ua,
    )
    with Session(engine) as session:
        session.add(fb)
        session.commit()
        session.refresh(fb)
        return {"id": fb.id, "ok": True}


@app.get("/api/feedback")
def list_feedback(limit: int = 100):
    with Session(engine) as session:
        rows = session.exec(select(Feedback).order_by(Feedback.id.desc()).limit(limit)).all()
        return rows



# Serve static files in /public at /public path
static_dir = os.path.join(os.path.dirname(__file__), "public")
if os.path.isdir(static_dir):
    app.mount("/public", StaticFiles(directory=static_dir), name="public")


# Admin view: simple HTML table of feedbacks
from fastapi.responses import HTMLResponse

@app.get("/admin", response_class=HTMLResponse)
def admin_view(limit: int = 100):
    with Session(engine) as session:
        rows = session.exec(select(Feedback).order_by(Feedback.id.desc()).limit(limit)).all()
    html = [
        "<html><head><title>Admin Feedback</title>",
        '<meta name="viewport" content="width=device-width,initial-scale=1">',
        '<style>body{font-family:sans-serif;background:#10182a;color:#e8eefc;padding:24px}table{border-collapse:collapse;width:100%;margin-top:16px}th,td{border:1px solid #334366;padding:8px 6px}th{background:#223366}tr:nth-child(even){background:#181f33}caption{font-size:1.3em;margin-bottom:8px}a{color:#5b8cff}</style>',
        "</head><body>",
        "<h1>Data Feedback (Admin View)</h1>",
        f"<p>Total: {len(rows)} | <a href='/api/feedback?limit={limit}'>JSON</a></p>",
        "<table>",
        "<caption>Feedback Terbaru</caption>",
        "<tr><th>ID</th><th>Rating</th><th>Fitur Favorit</th><th>Komentar</th><th>Waktu</th><th>User Agent</th></tr>"
    ]
    for r in rows:
        html.append(f"<tr><td>{r.id}</td><td>{r.rating}</td><td>{r.features or ''}</td><td>{r.comments}</td><td>{r.ts.strftime('%Y-%m-%d %H:%M:%S')}</td><td><small>{(r.ua or '')[:60]}</small></td></tr>")
    html.append("</table></body></html>")
    return "".join(html)


# Serve index.html at root
from fastapi.responses import FileResponse


@app.get("/")
def root():
    index_path = os.path.join(os.path.dirname(__file__), "index.html")
    if os.path.isfile(index_path):
        return FileResponse(index_path)
    raise HTTPException(status_code=404, detail="index.html not found")