Skip to content

Commit 6160ee2

Browse files
authored
Merge pull request #97 from pgulb/45-add-button-to-edit-flush-in-pwa
45 add button to edit flush in pwa
2 parents f68b04b + bf6853c commit 6160ee2

File tree

7 files changed

+578
-0
lines changed

7 files changed

+578
-0
lines changed

api/main.py

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import dateutil
1010
import fastapi
1111
import pymongo
12+
from bson.errors import InvalidId
1213
from bson.objectid import ObjectId
1314
from db import (
1415
create_mock_client,
@@ -424,3 +425,66 @@ def give_feedback(
424425
def get_feedback_count(username: str) -> int:
425426
feedbacks = client.flush.feedbacks
426427
return feedbacks.count_documents({"user_id": username})
428+
429+
430+
@app.get("/flush/{flush_id}", status_code=status.HTTP_200_OK)
431+
def get_flush_by_id(
432+
flush_id: str,
433+
credentials: HTTPBasicCredentials = Depends(security),
434+
):
435+
check_creds(credentials)
436+
flushes = client.flush.flushes
437+
try:
438+
flush = flushes.find_one(
439+
filter={"_id": ObjectId(flush_id), "user_id": credentials.username}
440+
)
441+
except InvalidId as e:
442+
logger.error(f"malformed flush id (cannot convert to ObjectId) - {e}")
443+
raise HTTPException(
444+
status_code=status.HTTP_404_NOT_FOUND, detail="Flush not found"
445+
) from e
446+
if flush is None:
447+
logger.error("flush not found by id")
448+
raise HTTPException(
449+
status_code=status.HTTP_404_NOT_FOUND, detail="Flush not found"
450+
)
451+
del flush["user_id"]
452+
flush["_id"] = str(flush["_id"])
453+
flush["time_start"] = flush["time_start"].isoformat()
454+
flush["time_end"] = flush["time_end"].isoformat()
455+
return flush
456+
457+
458+
@app.put("/flush/{flush_id}", status_code=status.HTTP_200_OK)
459+
def edit_flush_by_id(
460+
flush_id: str,
461+
flush: Flush = Query(),
462+
credentials: HTTPBasicCredentials = Depends(security),
463+
):
464+
check_creds(credentials)
465+
flushes = client.flush.flushes
466+
try:
467+
result = flushes.update_one(
468+
filter={"_id": ObjectId(flush_id), "user_id": credentials.username},
469+
update={
470+
"$set": {
471+
"time_start": dateutil.parser.isoparse(flush.time_start),
472+
"time_end": dateutil.parser.isoparse(flush.time_end),
473+
"rating": flush.rating,
474+
"note": sanitize(flush.note),
475+
"phone_used": flush.phone_used,
476+
}
477+
},
478+
upsert=False,
479+
)
480+
except Exception as e:
481+
logger.error(f"error updating flush by id - {e}")
482+
raise HTTPException(
483+
status_code=status.HTTP_400_BAD_REQUEST, detail="Error updating flush"
484+
) from e
485+
if result.matched_count != 1:
486+
logger.error("flush not found by id")
487+
raise HTTPException(
488+
status_code=status.HTTP_404_NOT_FOUND, detail="Flush not found"
489+
)
490+
return Response(status_code=status.HTTP_200_OK)
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
from fastapi import status
2+
from fastapi.testclient import TestClient
3+
from httpx import BasicAuth
4+
from universal.helpers import create_flush, create_user
5+
6+
from api.main import app
7+
8+
client = TestClient(app)
9+
10+
11+
def test_flush_edit():
12+
flushes = [
13+
{
14+
"time_start": "2021-01-01T00:00:00",
15+
"time_end": "2021-01-01T01:00:00",
16+
"rating": 5,
17+
"note": "dddd",
18+
"phone_used": True,
19+
},
20+
{
21+
"time_start": "2021-01-01T01:00:00",
22+
"time_end": "2021-01-01T02:00:00",
23+
"rating": 8,
24+
"note": "test",
25+
"phone_used": True,
26+
},
27+
{
28+
"time_start": "2021-01-01T02:00:00",
29+
"time_end": "2021-01-01T03:00:00",
30+
"rating": 9,
31+
"note": "essa",
32+
"phone_used": False,
33+
},
34+
]
35+
username, password = "testedittingflushes", "testedittingflushes"
36+
create_user(client, username, password)
37+
for f in flushes:
38+
create_flush(client, username, password, f)
39+
response = client.get(
40+
"/flushes",
41+
auth=BasicAuth(username=username, password=password),
42+
)
43+
assert response.status_code == status.HTTP_200_OK
44+
js = response.json()["flushes"]
45+
js.reverse()
46+
assert len(js) == len(flushes)
47+
response = client.put(
48+
f"/flush/{js[0]['_id']}",
49+
auth=BasicAuth(username=username, password=password),
50+
params={
51+
"time_start": "2021-01-01T02:00:00",
52+
"time_end": "2021-01-01T03:00:00",
53+
"rating": 10, # changed
54+
"note": "essa+edit", # changed
55+
"phone_used": False,
56+
},
57+
)
58+
assert response.status_code == status.HTTP_200_OK
59+
response = client.put(
60+
f"/flush/{js[2]['_id']}",
61+
auth=BasicAuth(username=username, password=password),
62+
params={
63+
"time_start": "2021-01-01T01:00:00", # changed
64+
"time_end": "2021-01-01T01:10:00", # changed
65+
"rating": 5,
66+
"note": "dddd",
67+
"phone_used": False, # changed
68+
},
69+
)
70+
assert response.status_code == status.HTTP_200_OK
71+
flushes[2]["rating"] = 10
72+
flushes[2]["note"] = "essa+edit"
73+
flushes[0]["time_start"] = "2021-01-01T01:00:00"
74+
flushes[0]["time_end"] = "2021-01-01T01:10:00"
75+
flushes[0]["phone_used"] = False
76+
response = client.get(
77+
"/flushes",
78+
auth=BasicAuth(username=username, password=password),
79+
)
80+
assert response.status_code == status.HTTP_200_OK
81+
js = response.json()["flushes"]
82+
js.reverse()
83+
assert len(js) == len(flushes)
84+
for i, f in enumerate(js):
85+
response = client.get(
86+
f"/flush/{f['_id']}", auth=BasicAuth(username=username, password=password)
87+
)
88+
assert response.status_code == status.HTTP_200_OK
89+
f_js = response.json()
90+
assert f_js["time_start"] == flushes[i]["time_start"]
91+
assert f_js["time_end"] == flushes[i]["time_end"]
92+
assert f_js["rating"] == flushes[i]["rating"]
93+
assert f_js["note"] == flushes[i]["note"]
94+
assert f_js["phone_used"] == flushes[i]["phone_used"]
95+
fake_id = "fakeid"
96+
response = client.put(
97+
f"/flush/{fake_id}",
98+
auth=BasicAuth(username=username, password=password),
99+
params={
100+
"time_start": "2021-01-01T01:00:00",
101+
"time_end": "2021-01-01T01:10:00",
102+
"rating": 5,
103+
"note": "dddd",
104+
"phone_used": False,
105+
},
106+
)
107+
assert response.status_code == status.HTTP_400_BAD_REQUEST

api/tests/universal/test_getting_flushes.py

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,3 +164,95 @@ def test_getting_flushes_with_skip():
164164
assert len(js) == 0
165165
if response.json()["more_data_available"]:
166166
raise AssertionError
167+
168+
169+
def test_getting_flushes_by_id():
170+
flushes = [
171+
{
172+
"time_start": "2021-01-01T00:00:00",
173+
"time_end": "2021-01-01T01:00:00",
174+
"rating": 5,
175+
"note": "dddd",
176+
"phone_used": True,
177+
},
178+
{
179+
"time_start": "2021-01-01T01:00:00",
180+
"time_end": "2021-01-01T02:00:00",
181+
"rating": 8,
182+
"note": "test",
183+
"phone_used": True,
184+
},
185+
{
186+
"time_start": "2021-01-01T02:00:00",
187+
"time_end": "2021-01-01T03:00:00",
188+
"rating": 9,
189+
"note": "essa",
190+
"phone_used": False,
191+
},
192+
]
193+
username, password = "testgettingflushesbyid", "testgettingflushesbyid"
194+
create_user(client, username, password)
195+
for f in flushes:
196+
create_flush(client, username, password, f)
197+
response = client.get(
198+
"/flushes",
199+
auth=BasicAuth(username=username, password=password),
200+
)
201+
assert response.status_code == status.HTTP_200_OK
202+
js = response.json()["flushes"]
203+
js.reverse()
204+
assert len(js) == len(flushes)
205+
for i, f in enumerate(js):
206+
response = client.get(
207+
f"/flush/{f['_id']}", auth=BasicAuth(username=username, password=password)
208+
)
209+
assert response.status_code == status.HTTP_200_OK
210+
f_js = response.json()
211+
assert f_js["time_start"] == flushes[i]["time_start"]
212+
assert f_js["time_end"] == flushes[i]["time_end"]
213+
assert f_js["rating"] == flushes[i]["rating"]
214+
assert f_js["note"] == flushes[i]["note"]
215+
assert f_js["phone_used"] == flushes[i]["phone_used"]
216+
217+
218+
def test_getting_flushes_by_id_wrong_id():
219+
flushes = [
220+
{
221+
"time_start": "2021-01-01T00:00:00",
222+
"time_end": "2021-01-01T01:00:00",
223+
"rating": 5,
224+
"note": "dddd",
225+
"phone_used": True,
226+
},
227+
{
228+
"time_start": "2021-01-01T01:00:00",
229+
"time_end": "2021-01-01T02:00:00",
230+
"rating": 8,
231+
"note": "test",
232+
"phone_used": True,
233+
},
234+
{
235+
"time_start": "2021-01-01T02:00:00",
236+
"time_end": "2021-01-01T03:00:00",
237+
"rating": 9,
238+
"note": "essa",
239+
"phone_used": False,
240+
},
241+
]
242+
username, password = "testgettingflushesbyid2", "testgettingflushesbyid2"
243+
create_user(client, username, password)
244+
for f in flushes:
245+
create_flush(client, username, password, f)
246+
response = client.get(
247+
"/flushes",
248+
auth=BasicAuth(username=username, password=password),
249+
)
250+
assert response.status_code == status.HTTP_200_OK
251+
js = response.json()["flushes"]
252+
js.reverse()
253+
assert len(js) == len(flushes)
254+
response = client.get(
255+
"/flush/randomwrongid",
256+
auth=BasicAuth(username=username, password=password),
257+
)
258+
assert response.status_code == status.HTTP_404_NOT_FOUND

pwa/flush/apicalls.go

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,3 +340,92 @@ func GiveFeedback(creds Creds, note string) (int, error) {
340340
defer CloseBody(r)
341341
return r.StatusCode, nil
342342
}
343+
344+
func SubmitEditedFlush(creds Creds, flush Flush) (int, error) {
345+
apiUrl, err := GetApiUrl()
346+
if err != nil {
347+
return 0, err
348+
}
349+
req, err := http.NewRequest("PUT", apiUrl+"/flush/"+flush.ID, nil)
350+
if err != nil {
351+
return 0, err
352+
}
353+
req.Header.Add("Authorization", "Basic "+creds.UserColonPass)
354+
q := url.Values{}
355+
q.Add("time_start", flush.TimeStart.Format("2006-01-02 15:04:05"))
356+
q.Add("time_end", flush.TimeEnd.Format("2006-01-02 15:04:05"))
357+
if flush.PhoneUsed {
358+
q.Add("phone_used", "true")
359+
} else {
360+
q.Add("phone_used", "false")
361+
}
362+
q.Add("rating", strconv.Itoa(flush.Rating))
363+
q.Add("note", flush.Note)
364+
req.URL.RawQuery = q.Encode()
365+
r, err := http.DefaultClient.Do(req)
366+
if err != nil {
367+
return 0, err
368+
}
369+
defer CloseBody(r)
370+
if r.StatusCode >= 400 {
371+
b, err := io.ReadAll(r.Body)
372+
if err != nil {
373+
log.Println("error while reading body")
374+
log.Println(err)
375+
} else {
376+
log.Println(string(b))
377+
}
378+
}
379+
return r.StatusCode, nil
380+
}
381+
382+
func GetFlushByID(ctx app.Context, flushID string) (Flush, int, error) {
383+
apiUrl, err := GetApiUrl()
384+
if err != nil {
385+
return Flush{}, 0, err
386+
}
387+
req, err := http.NewRequest("GET", apiUrl+"/flush/"+flushID, nil)
388+
if err != nil {
389+
return Flush{}, 0, err
390+
}
391+
var c Creds
392+
ctx.GetState("creds", &c)
393+
req.Header.Add("Authorization", "Basic "+c.UserColonPass)
394+
r, err := http.DefaultClient.Do(req)
395+
if err != nil {
396+
return Flush{}, 0, err
397+
}
398+
defer CloseBody(r)
399+
bytes, err := io.ReadAll(r.Body)
400+
if err != nil {
401+
return Flush{}, 0, err
402+
}
403+
var temp TempFlush
404+
err = json.Unmarshal(bytes, &temp)
405+
if err != nil {
406+
return Flush{}, 0, err
407+
}
408+
flush := Flush{
409+
Rating: temp.Rating,
410+
PhoneUsed: temp.PhoneUsed,
411+
Note: temp.Note,
412+
ID: temp.ID,
413+
}
414+
flush.TimeStart, err = time.Parse(
415+
"2006-01-02T15:04:05",
416+
temp.TimeStart,
417+
)
418+
if err != nil {
419+
return Flush{}, 0, err
420+
}
421+
flush.TimeEnd, err = time.Parse(
422+
"2006-01-02T15:04:05",
423+
temp.TimeEnd,
424+
)
425+
if err != nil {
426+
return Flush{}, 0, err
427+
}
428+
log.Println("temporary flush struct: ", temp)
429+
log.Println("Flush: ", flush)
430+
return flush, r.StatusCode, nil
431+
}

0 commit comments

Comments
 (0)