forked from zookinheimer/Lunch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
executable file
·287 lines (233 loc) · 8.58 KB
/
main.py
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
#!/usr/bin/env python
import random
from datetime import datetime
from decouple import config
from fasthtml.common import *
from pathlib import Path
from pony.orm import *
PORT = config('PORT', default=8080, cast=int)
RELOAD = config('RELOAD', default=True, cast=bool)
# css = Path("static/styles.css").read_text()
# javascript = Path("static/script.js").read_text()
hdrs = (
Link(rel="stylesheet", href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"),
HighlightJS(langs=['python', 'javascript', 'html', 'css']),
# Script(javascript),
# Style(css),
)
app, rt = fast_app(
static_path='static',
hdrs=hdrs,
pico=True,
)
setup_toasts(app, duration=2)
db = Database()
class LunchList(db.Entity):
id = PrimaryKey(int, auto=True)
restaurant = Required(str, unique=True)
option = Required(str)
class RecentLunch(db.Entity):
id = PrimaryKey(int, auto=True)
restaurant = Required(str)
date = Required(datetime, default=datetime.now)
db_fn = Path(__file__).parent / "lunch.db"
lunch_list_fn = Path(__file__).parent / "lunch_list.csv"
recent_lunch_fn = Path(__file__).parent / "recent_lunch.csv"
db.bind(provider='sqlite', filename=str(db_fn), create_db=True)
db.generate_mapping(create_tables=True)
@db_session
def create_db_and_tables():
"""Create database and tables if they don't exist."""
if not db_fn.exists():
with open(lunch_list_fn, "r") as f:
for line in f:
if line.startswith("restaurant"):
continue
restaurant, option = line.strip().split(",")
LunchList(restaurant=restaurant, option=option)
with open(recent_lunch_fn, "r") as f:
for line in f:
if line.startswith("restaurant"):
continue
restaurant, date = line.strip().split(",")
date = datetime.strptime(date, "%Y-%m-%d %H:%M:%S.%f")
RecentLunch(restaurant=restaurant, date=date)
@db_session
def get_all_restaurants():
"""Return list of all restaurants."""
return select(r.restaurant for r in LunchList)[:]
@db_session
def get_restaurants(option):
"""Return list of restaurants based on cost."""
return select(r.restaurant for r in LunchList if r.option.lower() == option.lower())[:]
@db_session
def rng_restaurant(option):
"""Return random restaurant based on cost."""
restaurants = get_restaurants(option)
if not restaurants:
return None
if option.lower() != 'cheap' and len(restaurants) >= 15:
# Get recent restaurants
recent = select(r.restaurant for r in RecentLunch).order_by(desc(RecentLunch.date))[:14]
recent = set(recent)
# Filter out recent ones
available = [r for r in restaurants if r not in recent]
if not available:
available = restaurants
choice = random.choice(available)
# Add to recent and cleanup old entries
RecentLunch(restaurant=choice)
# Keep only latest 14 entries
old_entries = select(r for r in RecentLunch).order_by(desc(RecentLunch.date))[14:]
for entry in old_entries:
entry.delete()
return choice
return random.choice(restaurants)
@db_session
def add_restaurant(name, option):
"""Add restaurant to database."""
if LunchList.exists(lambda r: r.restaurant.lower() == name.lower()):
return False
LunchList(restaurant=name, option=option)
return True
@db_session
def delete_restaurant(name):
"""Delete restaurant from database."""
restaurant = LunchList.get(lambda r: r.restaurant.lower() == name.lower())
if not restaurant:
return None
restaurant.delete()
return True
@rt('/')
def index():
return Titled(
"Lunch",
Container(
H2("Click below to find out what's for Lunch", style="text-align: center; margin-bottom: 2rem;"),
Div(
Div(
Input(type="radio", name="option", value="cheap", id="cheap", checked=True),
Label("Cheap", for_="cheap", style="margin-right: 1rem;"),
Input(type="radio", name="option", value="normal", id="normal"),
Label("Normal", for_="normal"),
style="margin-bottom: 2rem;",
),
style="text-align: center;",
),
Div(
Button(
"Roll Lunch",
hx_post="/roll",
hx_include="[name='option']",
hx_target="#result",
hx_swap_oob="true",
style="margin: 0 0.5rem 1rem;",
),
Button(
"Add Restaurant",
hx_get="/add-form",
hx_target="#form-area",
hx_swap_oob="true",
style="margin: 0 0.5rem 1rem;",
),
Button(
"Delete Restaurant",
hx_get="/delete-form",
hx_target="#form-area",
hx_swap_oob="true",
style="margin: 0 0.5rem 1rem;",
),
Button("List All", hx_get="/list", hx_target="#result", hx_swap_oob="true", style="margin-bottom: 1rem;"),
style="text-align: center;",
),
Div(id="result", style="margin-top: 1rem; text-align: center;"),
Div(id="form-area", style="margin-top: 1rem; text-align: center;"),
style="max-width: 800px; margin: 0 auto; padding: 2rem;",
),
)
@rt('/roll')
def roll(option: str, session):
restaurant = rng_restaurant(option)
message = f"Today's {option} lunch is at: {restaurant}" if restaurant else "No restaurants found for that option!"
add_toast(session, message, "success" if restaurant else "error")
return Div(
Div(hx_swap_oob="true", id="form-area"),
)
@rt('/list')
@db_session
def list():
restaurants = select((r.restaurant, r.option) for r in LunchList).order_by(lambda r1, r2: r1[0] > r2[0])[:]
return Div(
Div(
H2("All Restaurants"),
Table(
Tr(Th("Restaurant"), Th("Type")), *[Tr(Td(name), Td(option.title())) for name, option in restaurants], cls="table"
)
if restaurants
else P("No restaurants found!", cls="text-red-500"),
),
Div(hx_swap_oob="true", id="form-area"),
)
@rt('/add')
def add(name: str, option: str, session):
result = add_restaurant(name, option)
if result is False:
add_toast(session, f"{name} already exists!", "error")
else:
add_toast(session, f"Added {name}!", "success")
return Div(
Div(hx_swap_oob="true", id="form-area"),
)
@rt('/delete')
def post(name: str, session):
result = delete_restaurant(name)
if result is None:
add_toast(session, "Restaurant not found!", "error")
else:
add_toast(session, f"{name} deleted!", "success")
return Div(
Div(hx_swap_oob="true", id="form-area"),
)
@rt('/add-form')
def add_form():
return Form(
H3("Add Restaurant", style="margin-bottom: 1rem;"),
Div(
Input(name="name", placeholder="Restaurant name", required=True, style="margin-bottom: 1rem; width: 100%;"),
Div(
Input(type="radio", name="option", value="cheap", id="add-cheap", checked=True),
Label("Cheap", for_="add-cheap", style="margin-right: 1rem;"),
Input(type="radio", name="option", value="normal", id="add-normal"),
Label("Normal", for_="add-normal"),
style="text-align: center; margin-bottom: 1rem;",
),
Button("Add", type="submit", style="width: 100%;"),
style="display: flex; flex-direction: column; align-items: center;",
),
hx_post="/add",
hx_target="#result",
)
@rt('/delete-form')
def delete_form():
restaurants = get_all_restaurants()
if not restaurants:
return P("No restaurants to delete!", cls="text-red-500")
return Form(
H3("Delete Restaurant"),
Select(name="name", required=True)(*[Option(r, value=r) for r in restaurants]),
Button("Delete", type="submit"),
hx_post="/delete",
hx_target="#result",
)
if __name__ == '__main__':
create_db_and_tables()
serve(
host='0.0.0.0',
port=PORT,
reload=RELOAD,
reload_includes=[
'static/*.css',
'static/*.js',
],
reload_excludes=['scratch.py'],
)