-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
375 lines (315 loc) · 14.1 KB
/
app.py
File metadata and controls
375 lines (315 loc) · 14.1 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
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
from flask import Flask, render_template, request, redirect, url_for, flash, get_flashed_messages
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import os
from datetime import datetime
from extensions import db
from models import EventResourceAllocation
from utils import intervals_overlap, overlap_duration
from datetime import timedelta
from cache import cache
app = Flask(__name__)
# Secret key is required for session and flash messages. Override with env var in production.
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'dev-secret')
app.config['SQLALCHEMY_DATABASE_URI'] = (
'postgresql://postgres:root0601@localhost:5432/event_scheduler'
)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# Cache TTL (seconds). Can be overridden in env or app config.
app.config['CACHE_TTL'] = int(os.environ.get('CACHE_TTL', '300'))
# Optional Bootswatch theme name (e.g., 'cosmo', 'cyborg') set via env var
app.config['BOOTSWATCH_THEME'] = os.environ.get('BOOTSWATCH_THEME', '')
# Initialize the shared SQLAlchemy instance with this app
db.init_app(app)
# Import models after the DB has been configured to avoid circular imports
from models import Event, Resource
# Context processor to provide Bootswatch CSS URL when configured
from flask import current_app
@app.context_processor
def inject_theme():
theme = current_app.config.get('BOOTSWATCH_THEME')
if theme:
url = f"https://cdn.jsdelivr.net/npm/bootswatch@5/dist/{theme}/bootstrap.min.css"
return dict(bootswatch_css=url)
return dict(bootswatch_css=None)
@app.route('/')
def home():
# Redirect to the events list so the full UI (navbar, styles) is displayed
return redirect(url_for('list_events'))
@app.route('/events')
def list_events():
events = Event.query.order_by(Event.start_time).all()
return render_template('events/list.html', events=events)
@app.route('/events/add', methods=['GET', 'POST'])
def add_event():
error = None
if request.method == 'POST':
try:
start = datetime.fromisoformat(request.form['start_time'])
end = datetime.fromisoformat(request.form['end_time'])
except Exception:
error = "Invalid date/time format. Use the provided controls."
else:
if start >= end:
error = "Start time must be before end time."
else:
event = Event(
title=request.form['title'],
start_time=start,
end_time=end,
description=request.form['description']
)
db.session.add(event)
db.session.commit()
# Invalidate caches that depend on events/allocations
cache.clear()
flash('Event created', 'success')
return redirect(url_for('list_events'))
return render_template('events/add.html', error=error)
@app.route('/events/edit/<int:event_id>', methods=['GET', 'POST'])
def edit_event(event_id):
event = Event.query.get_or_404(event_id)
error = None
if request.method == 'POST':
try:
start = datetime.fromisoformat(request.form['start_time'])
end = datetime.fromisoformat(request.form['end_time'])
except Exception:
error = "Invalid date/time format."
else:
if start >= end:
error = "Start time must be before end time."
else:
event.title = request.form['title']
event.start_time = start
event.end_time = end
event.description = request.form['description']
db.session.commit()
# Invalidate caches after modifications
cache.clear()
flash('Event updated', 'success')
return redirect(url_for('list_events'))
return render_template('events/edit.html', event=event, error=error)
@app.route('/resources')
def list_resources():
resources = Resource.query.all()
return render_template('resources/list.html', resources=resources)
@app.route('/resources/add', methods=['GET', 'POST'])
def add_resource():
if request.method == 'POST':
resource = Resource(
resource_name=request.form['name'],
resource_type=request.form['type']
)
db.session.add(resource)
db.session.commit()
# Clear cache after resource changes
cache.clear()
flash('Resource created', 'success')
return redirect(url_for('list_resources'))
return render_template('resources/add.html')
@app.route('/allocate', methods=['GET', 'POST'])
def allocate_resource():
events = Event.query.order_by(Event.start_time).all()
resources = Resource.query.order_by(Resource.resource_name).all()
error = None
if request.method == 'POST':
event_id = int(request.form['event_id'])
resource_id = int(request.form['resource_id'])
event = Event.query.get(event_id)
# Validate event times
if event.start_time >= event.end_time:
error = "Selected event has invalid times (start >= end)."
else:
# Fetch existing allocations for this resource
existing_allocations = EventResourceAllocation.query.filter_by(
resource_id=resource_id
).all()
# Check for duplicate allocation
for allocation in existing_allocations:
if allocation.event_id == event_id:
error = "Resource is already allocated to this event."
break
# Check for conflicting allocations
if not error:
conflicts = []
for allocation in existing_allocations:
existing_event = allocation.event
if intervals_overlap(event.start_time, event.end_time,
existing_event.start_time, existing_event.end_time):
conflicts.append(existing_event.title)
if conflicts:
error = "Conflict detected with: " + ", ".join(conflicts)
if not error:
allocation = EventResourceAllocation(
event_id=event_id,
resource_id=resource_id
)
db.session.add(allocation)
db.session.commit()
# Clear cache after allocation changes
cache.clear()
flash('Resource allocated', 'success')
return redirect(url_for('list_allocations'))
return render_template(
'allocations/allocate.html',
events=events,
resources=resources,
error=error
)
@app.route('/allocations')
def list_allocations():
allocations = EventResourceAllocation.query.order_by(EventResourceAllocation.allocation_id).all()
return render_template('allocations/list.html', allocations=allocations)
@app.route('/allocations/delete/<int:allocation_id>', methods=['POST'])
def delete_allocation(allocation_id):
alloc = EventResourceAllocation.query.get_or_404(allocation_id)
db.session.delete(alloc)
db.session.commit()
cache.clear()
flash('Allocation deleted', 'info')
return redirect(url_for('list_allocations'))
@app.route('/reports/utilisation', methods=['GET', 'POST'])
def resource_utilisation_report():
"""Shows a report of total hours utilised per resource in a given range and upcoming bookings.
Supports CSV export when the form includes `export=csv`.
"""
report = None
error = None
# Defaults for the form: last 30 days
default_end_dt = datetime.now()
default_start_dt = default_end_dt - timedelta(days=30)
default_start = default_start_dt.strftime('%Y-%m-%dT%H:%M')
default_end = default_end_dt.strftime('%Y-%m-%dT%H:%M')
if request.method == 'POST':
try:
start = datetime.fromisoformat(request.form['start'])
end = datetime.fromisoformat(request.form['end'])
except Exception:
error = 'Invalid date/time format. Use the controls.'
else:
if start >= end:
error = 'Start must be before end.'
else:
# Build report: for each resource, sum overlap durations of its allocated events
resources = Resource.query.order_by(Resource.resource_name).all()
report = []
for r in resources:
total_seconds = 0
upcoming = []
# Iterate allocations and compute overlaps
for alloc in r.allocations:
ev = alloc.event
total_seconds += overlap_duration(ev.start_time, ev.end_time, start, end)
# Upcoming bookings within the selected range
if ev.start_time >= start and ev.start_time <= end:
upcoming.append(ev)
total_hours = round(total_seconds / 3600.0, 2)
report.append({'resource': r, 'total_hours': total_hours, 'upcoming': upcoming})
# If CSV export requested, generate CSV response (cached)
if request.form.get('export') == 'csv':
import io, csv
from flask import Response
key = f"util:{start.isoformat()}:{end.isoformat()}"
cached = cache.get(key)
if cached is not None:
resp = Response(cached, mimetype='text/csv')
resp.headers['Content-Disposition'] = 'attachment; filename="resource_utilisation.csv"'
resp.headers['X-Cache'] = 'HIT'
return resp
si = io.StringIO()
cw = csv.writer(si)
cw.writerow(['Resource','Resource Type','Booking Title','Booking Start','Booking End','Overlap Hours'])
for row in report:
resource = row['resource']
total_seconds = 0
# For CSV, include one row per allocated event with non-zero overlap
for alloc in resource.allocations:
ev = alloc.event
overlap_s = overlap_duration(ev.start_time, ev.end_time, start, end)
if overlap_s > 0:
total_seconds += overlap_s
cw.writerow([
resource.resource_name,
resource.resource_type,
ev.title,
ev.start_time.strftime('%Y-%m-%d %H:%M'),
ev.end_time.strftime('%Y-%m-%d %H:%M'),
round(overlap_s/3600.0, 2)
])
# Write a total row for this resource
cw.writerow([
resource.resource_name,
resource.resource_type,
'TOTAL',
'',
'',
round(total_seconds/3600.0, 2)
])
output = si.getvalue()
cache.set(key, output, ttl=app.config.get('CACHE_TTL', 300))
resp = Response(output, mimetype='text/csv')
resp.headers['Content-Disposition'] = 'attachment; filename="resource_utilisation.csv"'
resp.headers['X-Cache'] = 'MISS'
return resp
return render_template('reports/utilisation.html', report=report, error=error, default_start=default_start, default_end=default_end)
@app.route('/reports/utilisation.csv', methods=['GET'])
def resource_utilisation_csv_get():
"""Return CSV for given start/end query parameters.
Example: /reports/utilisation.csv?start=2025-01-10T00:00&end=2025-01-15T00:00
"""
start_s = request.args.get('start')
end_s = request.args.get('end')
if not start_s or not end_s:
return ('start and end query parameters are required', 400)
try:
start = datetime.fromisoformat(start_s)
end = datetime.fromisoformat(end_s)
except Exception:
return ('Invalid date/time format. Use ISO format (YYYY-MM-DDTHH:MM)', 400)
if start >= end:
return ('Start must be before end', 400)
resources = Resource.query.order_by(Resource.resource_name).all()
import io, csv
from flask import Response
key = f"util:{start.isoformat()}:{end.isoformat()}"
cached = cache.get(key)
if cached is not None:
resp = Response(cached, mimetype='text/csv')
resp.headers['Content-Disposition'] = 'attachment; filename="resource_utilisation.csv"'
resp.headers['X-Cache'] = 'HIT'
return resp
si = io.StringIO()
cw = csv.writer(si)
cw.writerow(['Resource','Resource Type','Booking Title','Booking Start','Booking End','Overlap Hours'])
for resource in resources:
total_seconds = 0
for alloc in resource.allocations:
ev = alloc.event
overlap_s = overlap_duration(ev.start_time, ev.end_time, start, end)
if overlap_s > 0:
total_seconds += overlap_s
cw.writerow([
resource.resource_name,
resource.resource_type,
ev.title,
ev.start_time.strftime('%Y-%m-%d %H:%M'),
ev.end_time.strftime('%Y-%m-%d %H:%M'),
round(overlap_s/3600.0, 2)
])
cw.writerow([
resource.resource_name,
resource.resource_type,
'TOTAL',
'',
'',
round(total_seconds/3600.0, 2)
])
output = si.getvalue()
cache.set(key, output, ttl=app.config.get('CACHE_TTL', 300))
resp = Response(output, mimetype='text/csv')
resp.headers['Content-Disposition'] = 'attachment; filename="resource_utilisation.csv"'
resp.headers['X-Cache'] = 'MISS'
return resp
if __name__ == '__main__':
app.run(debug=True)