File size: 47,053 Bytes
4de97b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
"""Local MOM application. Run python app.py, then open http://127.0.0.1:5000."""
from datetime import date, timedelta
from functools import wraps
from io import BytesIO
from pathlib import Path
import os
import re
import secrets
import sqlite3
import tempfile
import time

from flask import Flask, abort, flash, g, jsonify, redirect, render_template, request, send_file, session, url_for
from werkzeug.security import check_password_hash, generate_password_hash
from seed import DEFAULT_PASSWORD, create_meeting, seed_database, migrate_weekly, next_coordinator

ROOT = Path(__file__).resolve().parent

def preparation_days(meeting_date):
    """The meeting's Monday-Friday reporting week, after the meeting."""
    monday=date.fromisoformat(meeting_date)
    return [monday+timedelta(days=offset) for offset in range(5)]

def create_app(test_config=None):
    app = Flask(__name__)
    data_dir = Path(os.environ.get('MOM_DATA_DIR', ROOT / 'data'))
    app.config.update(DATABASE=str(data_dir/'mom.sqlite3'), SECRET_KEY=os.environ.get('MOM_SECRET_KEY'),
                      MAX_CONTENT_LENGTH=11*1024*1024, SESSION_COOKIE_HTTPONLY=True, REQUIRE_SETUP=True,
                      SESSION_COOKIE_SAMESITE='Lax', PERMANENT_SESSION_LIFETIME=timedelta(hours=8),
                      SESSION_COOKIE_SECURE=os.environ.get('MOM_HTTPS')=='1')
    if test_config:
        app.config.update(test_config)
    Path(app.config['DATABASE']).parent.mkdir(parents=True, exist_ok=True)
    if not app.config['SECRET_KEY']:
        secret_file = Path(app.config['DATABASE']).parent/'.secret_key'
        try:
            with secret_file.open('x', encoding='ascii') as handle:
                handle.write(secrets.token_hex(32))
        except FileExistsError:
            pass
        app.config['SECRET_KEY'] = secret_file.read_text(encoding='ascii').strip()

    def db():
        if 'db' not in g:
            g.db = sqlite3.connect(app.config['DATABASE'], timeout=20)
            g.db.row_factory = sqlite3.Row
            g.db.execute('PRAGMA foreign_keys=ON')
            g.db.execute('PRAGMA journal_mode=WAL')
        return g.db

    @app.teardown_appcontext
    def close_db(error=None):
        connection = g.pop('db', None)
        if connection is not None:
            connection.close()

    with app.app_context():
        db().executescript((ROOT/'schema.sql').read_text())
        migrate_weekly(db())
        seed_database(db(), ROOT/'seed_data.json')
        migrate_weekly(db())

    def csrf():
        if 'csrf' not in session:
            session['csrf'] = secrets.token_hex(32)
        return session['csrf']

    @app.context_processor
    def context():
        current=db().execute("SELECT * FROM meetings WHERE status='active'").fetchone() if g.get('user') else None
        can_coordinate=bool(g.get('user') and current and (g.user['is_admin'] or current['coordinator_id']==g.user['id']))
        administrator=db().execute('SELECT name FROM users WHERE is_admin=1 AND active=1 AND archived=0 ORDER BY id LIMIT 1').fetchone()
        return dict(csrf_token=csrf, today=date.today().isoformat(), token=lambda:secrets.token_hex(20),can_coordinate=can_coordinate,
                    administrator_name=administrator['name'] if administrator else 'your administrator')

    @app.template_filter('datefmt')
    def datefmt(value):
        return date.fromisoformat(value[:10]).strftime('%d %b %Y') if value else 'No date'

    @app.before_request
    def protect():
        g.user = None
        if request.endpoint == 'health':
            return
        if session.get('user_id'):
            g.user = db().execute('SELECT * FROM users WHERE id=? AND active=1',(session['user_id'],)).fetchone()
            if not g.user or g.user['session_version'] != session.get('version'):
                session.clear()
                g.user = None
        if request.method=='POST':
            supplied = request.form.get('csrf_token','')
            if not supplied or not secrets.compare_digest(supplied, session.get('csrf','')):
                abort(400, 'Your form expired. Reload the page and try again.')
            # Serialize writes so closing a meeting cannot race with a stale save.
            db().execute('BEGIN IMMEDIATE')
        if request.endpoint in ('login','static') or request.endpoint is None:
            return
        if not g.user:
            return redirect(url_for('login'))
        if g.user['must_change'] and request.endpoint not in ('password','logout'):
            return redirect(url_for('password'))
        if app.config['REQUIRE_SETUP'] and request.endpoint not in ('setup','password','logout') and not db().execute("SELECT 1 FROM metadata WHERE key='setup_complete'").fetchone():
            if g.user['is_admin']:
                return redirect(url_for('setup'))
            return render_template('setup_waiting.html')

    @app.after_request
    def headers(response):
        response.headers['X-Content-Type-Options']='nosniff'
        frames = "https://huggingface.co" if app.config.get('HF_SPACE') else "'none'"
        if not app.config.get('HF_SPACE'):
            response.headers['X-Frame-Options']='DENY'
        response.headers['Referrer-Policy']='same-origin'
        response.headers['Content-Security-Policy']="default-src 'self'; style-src 'self'; script-src 'self'; img-src 'self' data:; base-uri 'self'; form-action 'self'; frame-ancestors " + frames
        if request.endpoint != 'static':
            response.headers['Cache-Control']='no-store'
        return response

    @app.get('/health')
    @app.get('/healthz')
    @app.get('/api/health')
    def health():
        # Read-only: a probe must never create a missing database or change it.
        try:
            uri = Path(app.config['DATABASE']).resolve().as_uri() + '?mode=ro'
            connection = sqlite3.connect(uri, uri=True, timeout=2)
            try:
                connection.execute('SELECT id FROM users LIMIT 1').fetchone()
            finally:
                connection.close()
            database_ok = True
        except (sqlite3.Error, OSError):
            database_ok = False
        backup = app.extensions.get('dataset_backup')
        return jsonify(status='ok' if database_ok else 'unhealthy',
                       database='ok' if database_ok else 'unavailable',
                       backup=backup.status() if backup else {'enabled': False}), 200 if database_ok else 503

    def admin_only(fn):
        @wraps(fn)
        def inner(*args,**kwargs):
            # Recheck after the POST transaction lock: a concurrent transfer may
            # have revoked the account since before_request first read it.
            current=db().execute('SELECT * FROM users WHERE id=? AND active=1 AND archived=0', (g.user['id'],)).fetchone() if g.user else None
            if not current or not current['is_admin'] or current['session_version']!=session.get('version'):
                abort(403)
            return fn(*args,**kwargs)
        return inner

    def active_meeting():
        meeting = db().execute("SELECT * FROM meetings WHERE status='active'").fetchone()
        if not meeting:
            abort(409,'There is no active meeting. Ask your administrator to create one.')
        return meeting

    from setup_routes import register_setup, register_resume
    register_setup(app,db,admin_only)
    register_resume(app,db,admin_only)

    def entry_person():
        uid=request.args.get('person',str(g.user['id']))
        person=db().execute('SELECT * FROM users WHERE id=?',(uid,)).fetchone()
        if not person:
            abort(404)
        if person['archived']:
            abort(403,'This employee has been removed from the active team. Their history remains in Meeting reports.')
        if person['id']!=g.user['id']:
            current=active_meeting()
            if person['rotation_order'] is not None or not (g.user['is_admin'] or current['coordinator_id']==g.user['id']):
                abort(403,'Only this week’s coordinator can enter reports for people outside the rotation.')
        elif person['rotation_order'] is None and not g.user['is_admin']:
            abort(403,'This week’s report coordinator handles your action review, updates and new actions. You can view them in Meeting reports.')
        return person

    def flow_url(step):
        person=entry_person()
        return url_for('workflow',step=step,person=person['id'] if person['id']!=g.user['id'] else None)

    def submission(mid,uid=None):
        return db().execute('SELECT * FROM submissions WHERE meeting_id=? AND user_id=?',(mid,uid if uid is not None else g.user['id'])).fetchone()

    def editable():
        meeting = active_meeting()
        if request.method=='POST' and request.form.get('meeting_id') != str(meeting['id']):
            abort(409,'The active meeting changed. Reload before saving.')
        sub = submission(meeting['id'],entry_person()['id'])
        if sub and sub['submitted_at']:
            abort(409,'Your entry is submitted. Choose Edit submission from the dashboard first.')
        return meeting

    def text_field(name,limit=3000):
        value=request.form.get(name,'').strip()
        if not value or len(value)>limit or any(ord(c)<32 and c not in '\n\r\t' for c in value):
            raise ValueError(f'Enter {name.replace("_"," ")} between 1 and {limit} characters.')
        return value

    def date_field(name):
        value=request.form.get(name,'')
        if not re.fullmatch(r'\d{4}-\d{2}-\d{2}',value):
            raise ValueError('Choose a valid date.')
        try:
            return date.fromisoformat(value).isoformat()
        except ValueError:
            raise ValueError('Choose a valid date.') from None

    def entry_token():
        value = request.form.get('entry_token','')
        if not re.fullmatch('[a-f0-9]{40}',value):
            abort(400,'Invalid form. Reload and try again.')
        return value

    @app.route('/login',methods=['GET','POST'])
    def login():
        if g.user:
            return redirect(url_for('dashboard'))
        if request.method=='POST':
            user=db().execute('SELECT * FROM users WHERE username=? AND active=1',(request.form.get('username','').strip(),)).fetchone()
            if user and user['locked_until']>time.time():
                flash('Too many attempts. Please try again in five minutes.','error')
            elif user and check_password_hash(user['password_hash'],request.form.get('password','')):
                db().execute('UPDATE users SET failed_attempts=0,locked_until=0 WHERE id=?',(user['id'],))
                db().commit()
                session.clear()
                session.update(user_id=user['id'],version=user['session_version'])
                session.permanent=True
                return redirect(url_for('password' if user['must_change'] else 'dashboard'))
            else:
                if user:
                    attempts=(user['failed_attempts'] if user['locked_until']==0 else 0)+1
                    db().execute('UPDATE users SET failed_attempts=?,locked_until=? WHERE id=?',(attempts,time.time()+300 if attempts>=5 else 0,user['id']))
                    db().commit()
                flash('The username or password is incorrect.','error')
        return render_template('login.html', users=db().execute('SELECT name,username FROM users WHERE active=1 ORDER BY name').fetchall())

    @app.post('/logout')
    def logout():
        session.clear()
        return redirect(url_for('login'))

    @app.route('/password',methods=['GET','POST'])
    def password():
        if request.method=='POST':
            new=request.form.get('new_password','')
            if not check_password_hash(g.user['password_hash'],request.form.get('current_password','')):
                flash('Your current password is incorrect.','error')
            elif len(new)<10 or len(new)>128 or not all((re.search('[A-Z]',new),re.search('[a-z]',new),re.search('[0-9]',new),re.search(r'[^A-Za-z0-9]',new))):
                flash('Use 10–128 characters with uppercase, lowercase, a number and a symbol.','error')
            elif new==DEFAULT_PASSWORD or check_password_hash(g.user['password_hash'],new):
                flash('Choose a password different from your current and default password.','error')
            elif new!=request.form.get('confirm_password'):
                flash('The new passwords do not match.','error')
            else:
                db().execute('UPDATE users SET password_hash=?,must_change=0,session_version=session_version+1 WHERE id=?',(generate_password_hash(new),g.user['id']))
                db().commit()
                session['version']=g.user['session_version']+1
                flash('Your password has been changed.','success')
                return redirect(url_for('dashboard'))
        return render_template('password.html')

    @app.get('/')
    def dashboard():
        meeting=active_meeting()
        uid=g.user['id']
        stats=dict(db().execute('SELECT COUNT(*) total,COALESCE(SUM(r.completed),0) completed FROM reviews r JOIN actions a ON a.id=r.action_id WHERE r.meeting_id=? AND a.user_id=?',(meeting['id'],uid)).fetchone())
        stats['updates']=db().execute('SELECT COUNT(*) FROM updates WHERE meeting_id=? AND user_id=?',(meeting['id'],uid)).fetchone()[0]
        stats['actions']=db().execute('SELECT COUNT(*) FROM actions WHERE meeting_id=? AND user_id=?',(meeting['id'],uid)).fetchone()[0]
        recent=db().execute('SELECT * FROM meetings ORDER BY meeting_date DESC LIMIT 5').fetchall()
        team=db().execute('SELECT COUNT(*) FROM submissions s JOIN users u ON u.id=s.user_id WHERE s.meeting_id=? AND s.submitted_at IS NOT NULL AND u.archived=0',(meeting['id'],)).fetchone()[0]
        total=db().execute('SELECT COUNT(*) FROM users WHERE archived=0').fetchone()[0]
        coordinator=db().execute('SELECT name FROM users WHERE id=?',(meeting['coordinator_id'],)).fetchone()
        return render_template('dashboard.html',meeting=meeting,coordinator=coordinator,stats=stats,sub=submission(meeting['id']),recent=recent,team=team,total=total)

    @app.post('/reopen')
    def reopen():
        meeting=active_meeting()
        if request.form.get('meeting_id') != str(meeting['id']):
            abort(409)
        person=entry_person()
        db().execute('UPDATE submissions SET submitted_at=NULL WHERE meeting_id=? AND user_id=?',(meeting['id'],person['id']))
        db().commit()
        return redirect(flow_url(1))

    @app.route('/entry/<int:step>',methods=['GET','POST'])
    def workflow(step):
        if step not in (1,2,3,4):
            abort(404)
        meeting=editable()
        person=entry_person()
        mid,uid=meeting['id'],person['id']
        meeting_day=date.fromisoformat(meeting['meeting_date'])
        action_min=(meeting_day-timedelta(days=7)).isoformat()
        action_max=(meeting_day+timedelta(days=7)).isoformat()
        def action_deadline(date_value,note_value):
            date_value=(date_value or '').strip()
            note_value=(note_value or '').strip()
            if not date_value and not note_value:
                raise ValueError('Choose a due date or enter a schedule / note for the action.')
            if date_value and note_value:
                raise ValueError('Choose either a due date or a schedule / note, not both.')
            if note_value:
                if len(note_value)>250 or any(ord(c)<32 for c in note_value):
                    raise ValueError('Enter a schedule / note of 1–250 characters on one line.')
                return None,note_value
            if not re.fullmatch(r'\d{4}-\d{2}-\d{2}',date_value):
                raise ValueError('Choose a valid date.')
            try:
                due=date.fromisoformat(date_value).isoformat()
            except ValueError:
                raise ValueError('Choose a valid date.') from None
            if not action_min<=due<=action_max:
                raise ValueError(f'Choose a due date from {action_min} through {action_max}.')
            return due,''
        skipped_action_lines=[]
        sub=submission(mid,uid)
        if step>1 and (not sub or not sub['reviewed']):
            flash('Review your previous actions first.','info')
            return redirect(flow_url(1))
        previous=db().execute('SELECT a.*,r.completed AS checked,m.meeting_date AS source_date FROM reviews r JOIN actions a ON a.id=r.action_id JOIN meetings m ON m.id=a.meeting_id WHERE r.meeting_id=? AND a.user_id=? ORDER BY a.due_date IS NULL,a.due_date,a.id',(mid,uid)).fetchall()
        if request.method=='POST':
            try:
                if step==1:
                    selected=set(request.form.getlist('completed'))
                    allowed={str(a['id']) for a in previous}
                    if not selected.issubset(allowed):
                        abort(403)
                    for a in previous:
                        checked=int(str(a['id']) in selected)
                        db().execute('UPDATE reviews SET completed=? WHERE meeting_id=? AND action_id=?',(checked,mid,a['id']))
                        db().execute('UPDATE actions SET completed=? WHERE id=?',(checked,a['id']))
                    db().execute('INSERT INTO submissions(meeting_id,user_id,reviewed) VALUES(?,?,1) ON CONFLICT(meeting_id,user_id) DO UPDATE SET reviewed=1',(mid,uid))
                    db().commit()
                    return redirect(flow_url(2))
                if step in (2,3):
                    table='updates' if step==2 else 'actions'
                    op=request.form.get('operation','add')
                    if op=='next':
                        return redirect(flow_url(step+1))
                    if op not in ('add','edit','delete'):
                        abort(400)
                    if op in ('edit','delete'):
                        item=db().execute(f'SELECT * FROM {table} WHERE id=? AND meeting_id=? AND user_id=?',(request.form.get('item_id'),mid,uid)).fetchone()
                        if not item:
                            abort(404)
                    if op=='delete':
                        db().execute(f'DELETE FROM {table} WHERE id=?',(item['id'],))
                    else:
                        submitted_bodies=request.form.getlist('body')
                        body=text_field('body')
                        submitted_dates=request.form.getlist('due_date')
                        submitted_notes=request.form.getlist('due_note')
                        bulk_actions=step==3 and op=='add' and (request.form.get('action_entry_mode')=='bulk' or len(submitted_bodies)>1)
                        due,note=None,''
                        if step==3 and not bulk_actions:
                            due,note=action_deadline(request.form.get('due_date'),request.form.get('due_note'))
                        if step==2:
                            duplicate_rows=db().execute('SELECT body FROM updates WHERE meeting_id=? AND user_id=? AND id!=?',(mid,uid,item['id'] if op=='edit' else -1)).fetchall()
                            existing={row['body'] for row in duplicate_rows}
                            if request.form.get('entry_mode')=='bulk' or '\n' in body or '\r' in body:
                                entries=[entry.strip() for submitted_body in submitted_bodies for entry in submitted_body.splitlines() if entry.strip()]
                            else:
                                entries=[body]
                            if request.form.get('entry_mode')=='bulk' or '\n' in body or '\r' in body or len(submitted_bodies)>1:
                                entries=list(dict.fromkeys(entry for entry in entries if entry not in existing))
                                if not entries:
                                    raise ValueError('All of these updates already exist for this meeting.')
                            elif entries[0] in existing:
                                raise ValueError('An update with the same text already exists for this meeting.')
                        if op=='edit':
                            db().execute(f'UPDATE {table} SET body=? WHERE id=?',(body,item['id']))
                            if step==3:
                                db().execute('UPDATE actions SET due_date=?,due_note=? WHERE id=?',(due,note,item['id']))
                        else:
                            if step==2:
                                entries=[entry.strip() for submitted_body in submitted_bodies for entry in submitted_body.splitlines() if entry.strip()] if request.form.get('entry_mode')=='bulk' or '\n' in body or '\r' in body or len(submitted_bodies)>1 else [body]
                                if len(entries)>100:
                                    raise ValueError('You can add up to 100 updates at once.')
                                bulk_token=entry_token()
                                for index,entry in enumerate(entries):
                                    db().execute('INSERT INTO updates(meeting_id,user_id,body,entry_token) VALUES(?,?,?,?) ON CONFLICT(entry_token) DO NOTHING',(mid,uid,entry,f'{bulk_token}-{index}'))
                            else:
                                if bulk_actions:
                                    lines=submitted_bodies if len(submitted_bodies)>1 else body.splitlines()
                                    if len(lines)>100:
                                        raise ValueError('You can add up to 100 actions at once.')
                                    bulk_token=entry_token()
                                    saved_actions=0
                                    for index,line in enumerate(lines):
                                        if not line.strip():
                                            continue
                                        action_body=re.sub(r'^\s*\d+\.\s*','',line).strip()
                                        action_date=submitted_dates[index] if index<len(submitted_dates) else ''
                                        action_note=submitted_notes[index] if index<len(submitted_notes) else ''
                                        match=re.fullmatch(r'(.*?)\s*\[([^\[\]]*)\]\s*',action_body)
                                        if match and (not action_date and not action_note or re.match(r'^\s*\d+\.\s*',line) and match.group(2).strip() in (action_date,action_note)):
                                            action_body=match.group(1).strip()
                                            if action_body.startswith('[') and action_body.endswith(']'):
                                                action_body=action_body[1:-1].strip()
                                            if not action_date and not action_note:
                                                value=match.group(2).strip()
                                                if re.fullmatch(r'\d{4}-\d{2}-\d{2}',value):
                                                    action_date=value
                                                else:
                                                    action_note=value
                                        try:
                                            if not action_body or len(action_body)>3000:
                                                raise ValueError('Enter an action description.')
                                            action_date,action_note=action_deadline(action_date,action_note)
                                        except ValueError:
                                            skipped_action_lines.append(index+1)
                                            continue
                                        db().execute('INSERT INTO actions(meeting_id,user_id,body,due_date,due_note,entry_token) VALUES(?,?,?,?,?,?) ON CONFLICT(entry_token) DO NOTHING',(mid,uid,action_body,action_date,action_note,f'{bulk_token}-{index}'))
                                        saved_actions+=1
                                    if not saved_actions:
                                        raise ValueError('Each action needs a description and either a valid due date or a schedule / note.')
                                else:
                                    db().execute('INSERT INTO actions(meeting_id,user_id,body,due_date,due_note,entry_token) VALUES(?,?,?,?,?,?) ON CONFLICT(entry_token) DO NOTHING',(mid,uid,body,due,note,entry_token()))
                    db().commit()
                    if skipped_action_lines:
                        flash(f'Saved valid actions. Skipped lines {", ".join(map(str,skipped_action_lines))}; each action needs either a date from {action_min} through {action_max} or a schedule / note of up to 250 characters.','info')
                    else:
                        flash('Saved. You can add another item.','success')
                    return redirect(flow_url(step))
                if step==4:
                    db().execute('UPDATE submissions SET submitted_at=CURRENT_TIMESTAMP WHERE meeting_id=? AND user_id=?',(mid,uid))
                    db().commit()
                    flash(f"Meeting entry for {person['name']} has been submitted.",'success')
                    return redirect(url_for('coordinator' if person['id']!=g.user['id'] else 'dashboard'))
            except ValueError as error:
                db().rollback()
                flash(str(error),'error')
        updates=db().execute('SELECT * FROM updates WHERE meeting_id=? AND user_id=? ORDER BY id',(mid,uid)).fetchall()
        actions=db().execute('SELECT * FROM actions WHERE meeting_id=? AND user_id=? ORDER BY id',(mid,uid)).fetchall()
        return render_template('workflow.html',step=step,meeting=meeting,previous=previous,updates=updates,actions=actions,entry_user=person,flow_url=flow_url,action_min=action_min,action_max=action_max)

    def report_data(mid):
        meeting=db().execute('SELECT * FROM meetings WHERE id=?',(mid,)).fetchone()
        if not meeting:
            abort(404)
        users=db().execute('SELECT u.id,u.name,u.rotation_order,u.report_order,u.archived,s.submitted_at,s.reviewed FROM users u LEFT JOIN submissions s ON s.user_id=u.id AND s.meeting_id=? ORDER BY u.name',(mid,)).fetchall()
        updates=db().execute('SELECT x.*,u.name FROM updates x JOIN users u ON u.id=x.user_id WHERE meeting_id=? ORDER BY u.name,x.id',(mid,)).fetchall()
        actions=db().execute('SELECT a.*,u.name FROM actions a JOIN users u ON u.id=a.user_id WHERE meeting_id=? ORDER BY u.name,a.id',(mid,)).fetchall()
        reviews=db().execute('SELECT a.*,u.name,r.completed AS checked,m.meeting_date AS source_date FROM reviews r JOIN actions a ON a.id=r.action_id JOIN users u ON u.id=a.user_id JOIN meetings m ON m.id=a.meeting_id WHERE r.meeting_id=? ORDER BY u.name,a.id',(mid,)).fetchall()
        source_label=meeting['source_file']
        if source_label and source_label.startswith('upload:'):
            source_label='Uploaded previous MOM report'
        return dict(meeting=meeting,source_label=source_label,users=users,updates=updates,actions=actions,reviews=reviews)

    @app.get('/reports')
    def reports():
        meetings=db().execute('SELECT m.*,(SELECT COUNT(*) FROM updates WHERE meeting_id=m.id) update_count,(SELECT COUNT(*) FROM actions WHERE meeting_id=m.id) action_count FROM meetings m ORDER BY meeting_date DESC').fetchall()
        return render_template('reports.html',meetings=meetings)

    @app.get('/reports/<int:mid>')
    def report(mid):
        return render_template('report.html',**report_data(mid))

    @app.get('/reports/<int:mid>/excel')
    def excel(mid):
        from exporter import export_report
        # Build the whole weekly copy from one consistent database snapshot.
        db().execute('BEGIN')
        data=report_data(mid)
        baseline=db().execute('SELECT * FROM meetings WHERE source_file IS NOT NULL AND meeting_date<=? ORDER BY meeting_date DESC LIMIT 1',(data['meeting']['meeting_date'],)).fetchone()
        if not baseline:abort(409,'Upload the previous Excel report before exporting.')
        source=baseline['source_file']
        if source.startswith('upload:'):
            name=source.removeprefix('upload:')
            if not re.fullmatch(r'[a-f0-9]{32}\.xlsx',name):abort(409,'The source workbook reference is invalid.')
            source_path=Path(app.config['DATABASE']).parent/'imports'/name
        else:
            source_path=ROOT/'sources'/Path(source).name
        if not source_path.exists():abort(409,'The previous workbook is missing. Restore its original file from your backup.')
        previous=source_path.read_bytes()
        style_workbook=previous
        aliases={r['source_name']:r['user_id'] for r in db().execute('SELECT * FROM report_owner_aliases WHERE meeting_id=?',(baseline['id'],))}
        # Replay each immutable weekly record onto a copy of its predecessor.
        # This preserves CLOSED history even when a week was never downloaded.
        periods=db().execute('SELECT id FROM meetings WHERE meeting_date>? AND meeting_date<=? ORDER BY meeting_date',(baseline['meeting_date'],data['meeting']['meeting_date'])).fetchall()
        try:
            for period in periods:
                weekly=report_data(period['id']);weekly['owner_map']=aliases
                previous=export_report(weekly,previous,style_workbook=style_workbook).getvalue()
        except ValueError as error:
            abort(409,str(error))
        filename=f"MOM_Technical Report on {date.fromisoformat(data['meeting']['meeting_date']).strftime('%d-%m-%Y')}.xlsx"
        reports_dir=Path(app.config['DATABASE']).parent/'reports';reports_dir.mkdir(exist_ok=True)
        # Atomic replacement permits repeated downloads without duplicate CLOSED rows.
        output_path=reports_dir/filename
        temp_path=reports_dir/(secrets.token_hex(12)+'.tmp')
        temp_path.write_bytes(previous);os.replace(temp_path,output_path)
        return send_file(BytesIO(previous),as_attachment=True,download_name=filename,mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

    @app.get('/reports/<int:mid>/original')
    def original(mid):
        data=report_data(mid)
        filename=data['meeting']['source_file']
        if not filename:
            abort(404)
        if filename.startswith('upload:'):
            name=filename.removeprefix('upload:')
            if not re.fullmatch(r'[a-f0-9]{32}\.xlsx',name):
                abort(404)
            return send_file(Path(app.config['DATABASE']).parent/'imports'/name,as_attachment=True,download_name='Original MOM report.xlsx')
        return send_file(ROOT/'sources'/Path(filename).name,as_attachment=True)

    @app.route('/admin',methods=['GET','POST'])
    @admin_only
    def admin():
        if request.method=='POST':
            try:
                op=request.form.get('operation')
                if op=='meeting':
                    meeting_date=date_field('meeting_date')
                    latest=db().execute('SELECT MAX(meeting_date) FROM meetings').fetchone()[0]
                    if latest and meeting_date<=latest:
                        raise ValueError('The new meeting must be after the latest meeting date.')
                    if date.fromisoformat(meeting_date).weekday()!=0:
                        raise ValueError('Weekly meetings must be scheduled on a Monday.')
                    title=text_field('title',150)
                    location=text_field('location',150)
                    presenter=request.form.get('presenter','').strip()[:100]
                    minutes=request.form.get('minutes_by','').strip()[:100]
                    create_meeting(db(),meeting_date,title,location,presenter,minutes)
                    flash('New meeting opened. Unfinished actions have been carried forward.','success')
                elif op=='add_employee':
                    name=text_field('name',100)
                    username=text_field('username',50).lower()
                    if not re.fullmatch(r'[a-z0-9][a-z0-9_.-]{2,49}',username):
                        raise ValueError('Use a username with 3–50 letters, numbers, dots, hyphens or underscores, starting with a letter or number.')
                    if db().execute('SELECT 1 FROM users WHERE username=?',(username,)).fetchone():
                        raise ValueError('That username is already used, including removed employees. Choose another username or restore the existing account.')
                    position=None
                    if request.form.get('join_rotation')=='1':
                        position=db().execute('SELECT COALESCE(MAX(rotation_order),0)+1 FROM users WHERE archived=0').fetchone()[0]
                        if position>100:
                            raise ValueError('Reorder the rotation to make a position available before adding another member.')
                    report_position=db().execute('SELECT COALESCE(MAX(report_order),0)+1 FROM users').fetchone()[0]
                    db().execute('INSERT INTO users(name,username,password_hash,rotation_order,report_order) VALUES(?,?,?,?,?)',
                                 (name,username,generate_password_hash(DEFAULT_PASSWORD),position,report_position))
                    flash(f'{name} added. Initial password: {DEFAULT_PASSWORD}. They must change it at first login.','success')
                elif op=='transfer_admin':
                    if not check_password_hash(g.user['password_hash'],request.form.get('current_password','')):
                        raise ValueError('Enter your current password to transfer administration.')
                    target=db().execute('SELECT * FROM users WHERE id=? AND active=1 AND archived=0 AND must_change=0',
                                        (request.form.get('new_admin_id'),)).fetchone()
                    if not target or target['id']==g.user['id']:
                        raise ValueError('Choose another active employee who has already set a personal password.')
                    db().execute('UPDATE users SET is_admin=1,session_version=session_version+1 WHERE id=?',(target['id'],))
                    db().execute('UPDATE users SET is_admin=0,session_version=session_version+1 WHERE id=?',(g.user['id'],))
                    db().commit()
                    session.clear()
                    flash(f"Administration transferred to {target['name']}. Both accounts must sign in again. Your account remains a team member.",'success')
                    return redirect(url_for('login'))
                elif op in ('remove_employee','restore_employee'):
                    user=db().execute('SELECT * FROM users WHERE id=?',(request.form.get('user_id'),)).fetchone()
                    if not user:
                        abort(404)
                    if user['is_admin'] or user['id']==g.user['id']:
                        raise ValueError('Transfer administration before removing an administrator.')
                    if op=='remove_employee':
                        if user['archived']:
                            raise ValueError('This employee is already removed.')
                        if not db().execute('SELECT 1 FROM users WHERE active=1 AND archived=0 AND rotation_order IS NOT NULL AND id!=?',(user['id'],)).fetchone():
                            raise ValueError('Keep at least one active employee in the coordinator rotation.')
                        current=active_meeting()
                        if current['coordinator_id']==user['id']:
                            replacement=db().execute('SELECT * FROM users WHERE id=? AND id!=? AND active=1 AND archived=0 AND rotation_order IS NOT NULL',
                                                     (request.form.get('replacement_id'),user['id'])).fetchone()
                            if not replacement:
                                raise ValueError('Choose a replacement from the active rotation before removing the current coordinator.')
                            db().execute('UPDATE meetings SET coordinator_id=?,minutes_by=? WHERE id=?',(replacement['id'],replacement['name'],current['id']))
                        db().execute('UPDATE users SET archived=1,active=0,rotation_order=NULL,session_version=session_version+1 WHERE id=?',(user['id'],))
                        flash(f"{user['name']} removed from the active team. Their past entries and unfinished actions remain in history.",'success')
                    else:
                        if not user['archived']:
                            raise ValueError('This employee is already on the active team.')
                        db().execute('UPDATE users SET archived=0,active=1,rotation_order=NULL,session_version=session_version+1 WHERE id=?',(user['id'],))
                        # Restore their pending checklist without changing completed or submitted reviews.
                        db().execute('INSERT OR IGNORE INTO reviews(meeting_id,action_id) SELECT ?,id FROM actions WHERE user_id=? AND completed=0 AND archived=0',
                                     (active_meeting()['id'],user['id']))
                        flash(f"{user['name']} restored. Their existing password is retained. Add them to the rotation if needed.",'success')
                elif op=='report_order':
                    people=db().execute('SELECT id FROM users WHERE archived=0').fetchall()
                    positions={}
                    for person in people:
                        value=request.form.get(f"report_order_{person['id']}",'').strip()
                        if not value.isdigit() or not 1<=int(value)<=10000:
                            raise ValueError('Give every employee a report position from 1 to 10000. Reload if the team has changed.')
                        positions[person['id']]=int(value)
                    if len(set(positions.values()))!=len(positions):
                        raise ValueError('Each report position must be unique.')
                    for uid,position in positions.items():
                        db().execute('UPDATE users SET report_order=? WHERE id=?',(position,uid))
                    flash('Report order saved. Download the Excel report again to apply it to updates and actions.','success')
                elif op=='rotation':
                    users=db().execute('SELECT id FROM users WHERE archived=0').fetchall()
                    values={}
                    for user in users:
                        value=request.form.get(f"order_{user['id']}",'').strip()
                        if value:
                            if not value.isdigit() or not 1<=int(value)<=100:
                                raise ValueError('Rotation positions must be numbers from 1 to 100, or blank to exclude a person.')
                            values[user['id']]=int(value)
                    if len(set(values.values()))!=len(values):
                        raise ValueError('Each rotation position must be unique.')
                    active_ids={u['id'] for u in db().execute('SELECT id FROM users WHERE active=1 AND archived=0')}
                    if not active_ids.intersection(values):
                        raise ValueError('Keep at least one active member in the rotation.')
                    for user in users:
                        db().execute('UPDATE users SET rotation_order=? WHERE id=?',(values.get(user['id']),user['id']))
                    flash('Coordinator rotation saved. It will apply to future meetings.','success')
                elif op=='assign':
                    target=db().execute('SELECT * FROM users WHERE id=? AND active=1 AND archived=0',(request.form.get('coordinator_id'),)).fetchone()
                    if not target:
                        raise ValueError('Choose an active member.')
                    current=active_meeting()
                    db().execute('UPDATE meetings SET coordinator_id=?,minutes_by=? WHERE id=?',(target['id'],target['name'],current['id']))
                    flash('Current report coordinator updated.','success')
                elif op in ('reset','toggle'):
                    user=db().execute('SELECT * FROM users WHERE id=?',(request.form.get('user_id'),)).fetchone()
                    if not user:
                        abort(404)
                    if user['archived']:
                        raise ValueError('Restore this employee before changing their account access or password.')
                    if user['id']==g.user['id'] or user['is_admin']:
                        raise ValueError('Use Change password for your account. Your administrator account must remain active.')
                    if op=='reset':
                        db().execute('UPDATE users SET password_hash=?,must_change=1,session_version=session_version+1,failed_attempts=0,locked_until=0 WHERE id=?',(generate_password_hash(DEFAULT_PASSWORD),user['id']))
                        flash(f"Password reset for {user['name']}. They must change it at next login.",'success')
                    else:
                        if user['active']:
                            if active_meeting()['coordinator_id']==user['id']:
                                raise ValueError('Assign another current coordinator before disabling this account.')
                            if not db().execute('SELECT 1 FROM users WHERE active=1 AND archived=0 AND rotation_order IS NOT NULL AND id!=?',(user['id'],)).fetchone():
                                raise ValueError('Keep at least one active employee in the rotation.')
                        db().execute('UPDATE users SET active=1-active,session_version=session_version+1 WHERE id=?',(user['id'],))
                        flash('Account access updated.','success')
                else:
                    abort(400)
                db().commit()
                return redirect(url_for('admin'))
            except (ValueError,sqlite3.IntegrityError) as error:
                db().rollback()
                flash(str(error) if isinstance(error,ValueError) else 'This record already exists or conflicts with another change. Reload and try again.','error')
        return render_template('admin.html',users=db().execute('SELECT * FROM users ORDER BY rotation_order IS NULL,rotation_order,name').fetchall(),
                               report_users=db().execute('SELECT * FROM users WHERE archived=0 ORDER BY report_order IS NULL,report_order,name').fetchall(),meeting=active_meeting())

    @app.route('/coordinator',methods=['GET','POST'])
    def coordinator():
        meeting=active_meeting()
        if not g.user['is_admin'] and meeting['coordinator_id']!=g.user['id']:
            abort(403)
        if request.method=='POST':
            if request.form.get('meeting_id')!=str(meeting['id']):
                abort(409,'The meeting changed. Reload and try again.')
            try:
                if request.form.get('operation')=='preparation_date':
                    prepared_on=date_field('prepared_on')
                    allowed={day.isoformat() for day in preparation_days(meeting['meeting_date'])}
                    if prepared_on not in allowed:
                        raise ValueError('Choose a working day in this meeting’s Monday-to-Friday reporting week.')
                    db().execute('UPDATE meetings SET prepared_on=? WHERE id=?',(prepared_on,meeting['id']))
                    flash('Report preparation date saved.','success')
                elif request.form.get('operation')=='details':
                    title=text_field('title',150)
                    location=text_field('location',150)
                    presenter=request.form.get('presenter','').strip()[:100]
                    db().execute('UPDATE meetings SET title=?,location=?,presenter=? WHERE id=?',(title,location,presenter,meeting['id']))
                    flash('Meeting details saved.','success')
                elif request.form.get('operation')=='next':
                    following=(date.fromisoformat(meeting['meeting_date'])+timedelta(days=7)).isoformat()
                    create_meeting(db(),following,meeting['title'],meeting['location'])
                    flash('Next Monday’s meeting is open and the coordinator role has rotated.','success')
                    db().commit()
                    return redirect(url_for('dashboard'))
                else:
                    abort(400)
                db().commit()
                return redirect(url_for('coordinator'))
            except ValueError as error:
                db().rollback()
                flash(str(error),'error')
        data=report_data(meeting['id'])
        data['users']=[user for user in data['users'] if not user['archived']]
        data['next_owner']=next_coordinator(db())
        data['next_date']=(date.fromisoformat(meeting['meeting_date'])+timedelta(days=7)).isoformat()
        data['preparation_days']=preparation_days(meeting['meeting_date'])
        return render_template('coordinator.html',**data)

    @app.get('/admin/backup')
    @admin_only
    def backup():
        with tempfile.TemporaryDirectory() as directory:
            path=Path(directory)/'mom.sqlite3'
            target=sqlite3.connect(path)
            try:
                db().backup(target)
            finally:
                target.close()
            content=BytesIO(path.read_bytes())
        return send_file(content,as_attachment=True,download_name=f'mom-backup-{date.today().isoformat()}.sqlite3',mimetype='application/octet-stream')

    @app.errorhandler(400)
    @app.errorhandler(403)
    @app.errorhandler(404)
    @app.errorhandler(409)
    @app.errorhandler(413)
    def error_page(error):
        return render_template('error.html',error=error),error.code

    return app

if __name__=='__main__':
    from waitress import serve
    import argparse
    parser=argparse.ArgumentParser(description='Run the local MOM application')
    # CHANGE THIS LINE: Set default to '0.0.0.0'
    parser.add_argument('--host', default='0.0.0.0')
    parser.add_argument('--port', type=int, default=5000)
    args=parser.parse_args()
    print(f'MOM is ready at http://{args.host}:{args.port}', flush=True)
    serve(create_app(), host=args.host, port=args.port, threads=4)