Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
111 lines (89 loc) · 3.05 KB
/
Copy pathmain.py
File metadata and controls
111 lines (89 loc) · 3.05 KB
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
from typing import Literal, Optional
from fastapi import FastAPI, HTTPException, Query
from pydantic import BaseModel, EmailStr
from db import get_conn
app = FastAPI()
Priority = Literal["low", "medium", "high", "urgent"]
Status = Literal["open", "in_progress", "resolved", "closed"]
class CreateTicketRequest(BaseModel):
customer_id: str
subject: str
priority: Priority
status: Status
created_by: EmailStr
class UpdateTicketStatusRequest(BaseModel):
status: Status
@app.get("/health")
def health():
return {"status": "ok"}
@app.post("/tickets", status_code=201)
def create_ticket(body: CreateTicketRequest):
with get_conn() as conn:
with conn.cursor() as cur:
cur.execute(
"""
INSERT INTO tickets (customer_id, subject, priority, status, created_by)
VALUES (%s, %s, %s, %s, %s)
RETURNING *
""",
(body.customer_id, body.subject, body.priority, body.status, body.created_by),
)
ticket = cur.fetchone()
conn.commit()
return ticket
@app.get("/tickets")
def list_tickets(
customer_id: str = Query(...),
status: Optional[Status] = Query(None),
priority: Optional[Priority] = Query(None),
):
filters = ["customer_id = %s"]
params = [customer_id]
if status:
filters.append("status = %s")
params.append(status)
if priority:
filters.append("priority = %s")
params.append(priority)
sql = "SELECT * FROM tickets WHERE " + " AND ".join(filters) + " ORDER BY created_at DESC"
with get_conn() as conn:
with conn.cursor() as cur:
cur.execute(sql, params)
tickets = cur.fetchall()
return tickets
@app.patch("/tickets/{ticket_id}")
def update_ticket_status(ticket_id: int, body: UpdateTicketStatusRequest):
with get_conn() as conn:
with conn.cursor() as cur:
cur.execute(
"""
UPDATE tickets
SET status = %s, updated_at = NOW()
WHERE id = %s
RETURNING *
""",
(body.status, ticket_id),
)
ticket = cur.fetchone()
conn.commit()
if ticket is None:
raise HTTPException(status_code=404, detail="Ticket not found")
return ticket
@app.get("/customers/{customer_id}/tickets/summary")
def ticket_summary(customer_id: str):
with get_conn() as conn:
with conn.cursor() as cur:
cur.execute(
"""
SELECT
COUNT(*) AS total,
COUNT(*) FILTER (WHERE status = 'open') AS open,
COUNT(*) FILTER (WHERE status = 'closed') AS closed,
MAX(created_at) AS latest_created_at
FROM tickets
WHERE customer_id = %s
""",
(customer_id,),
)
row = cur.fetchone()
return row