Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
2028 lines (1883 loc) · 105 KB
/
Copy pathapp.py
File metadata and controls
2028 lines (1883 loc) · 105 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
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
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Garage Logbook - self-hosted vehicle maintenance tracker
# Copyright (C) 2026 Hyprlab
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import os, uuid, sqlite3, hashlib, secrets, csv, io, json, re, calendar, unicodedata, zipfile
from urllib.parse import urlsplit
from datetime import date, datetime, timezone
try:
import fcntl
except ImportError: # non-POSIX; single-process only
fcntl = None
from functools import wraps
from flask import (Flask, render_template, request, jsonify,
redirect, url_for, session, g, Response, send_from_directory, send_file,
has_request_context)
APP_VERSION = '1.3.0'
app = Flask(__name__)
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'change-this-to-a-random-secret-key-in-production')
app.config['UPLOAD_FOLDER'] = os.environ.get('UPLOAD_FOLDER', os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static', 'uploads'))
app.config['MAX_CONTENT_LENGTH'] = 32 * 1024 * 1024
ALLOWED_EXTENSIONS = {'png','jpg','jpeg','gif','webp','heic','heif','pdf'}
# Photos most browsers cannot show, saved as JPEG instead.
CONVERT_TO_JPEG = {'heic','heif'}
ROLES = {'admin','editor'}
DATABASE = os.environ.get('DATABASE_PATH', os.path.join(os.path.dirname(os.path.abspath(__file__)), 'garage_logbook.db'))
# Default editor permissions
DEFAULT_PERMS = {'can_add_cars':True,'can_edit_cars':True,'can_delete_cars':True,
'can_add_records':True,'can_edit_records':True,'can_delete_records':True,
'can_import':False,'can_export':True}
def allowed_file(fn):
return '.' in fn and fn.rsplit('.',1)[1].lower() in ALLOWED_EXTENSIONS
def hash_password(pw, salt=None):
if not salt: salt = secrets.token_hex(16)
return f"{salt}${hashlib.pbkdf2_hmac('sha256', pw.encode(), salt.encode(), 260000).hex()}"
def verify_password(pw, stored):
return hash_password(pw, stored.split('$',1)[0]) == stored
def get_db():
conn = sqlite3.connect(DATABASE, timeout=30)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA foreign_keys=ON")
# Track the connection so teardown_request can roll back and close it even if
# the view raises before reaching its own conn.close(). Without this, a failed
# write leaves an open transaction pinned by the logged traceback, and every
# later write fails with "database is locked" until the worker recycles.
if has_request_context():
if '_db_conns' not in g: g._db_conns = []
g._db_conns.append(conn)
return conn
def init_db():
"""Serialized across worker processes: gunicorn imports this module once per
worker, so without a lock all of them run the migrations concurrently and can
interleave the table-rebuild steps."""
lock_path = DATABASE + '.init.lock'
try:
os.makedirs(os.path.dirname(os.path.abspath(lock_path)), exist_ok=True)
except Exception:
pass
if fcntl is None:
return _init_db()
with open(lock_path, 'w') as lf:
fcntl.flock(lf, fcntl.LOCK_EX)
try:
return _init_db()
finally:
fcntl.flock(lf, fcntl.LOCK_UN)
def _init_db():
conn = get_db()
conn.executescript('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE COLLATE NOCASE,
password TEXT NOT NULL, display_name TEXT,
role TEXT NOT NULL DEFAULT 'editor' CHECK(role IN ('admin','editor')),
permissions TEXT NOT NULL DEFAULT '{}',
must_change_password INTEGER NOT NULL DEFAULT 0,
created_at TEXT DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS cars (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
year INTEGER NOT NULL, make TEXT NOT NULL, model TEXT NOT NULL,
vin TEXT, image TEXT, purchase_date TEXT,
created_at TEXT DEFAULT (datetime('now')),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS maintenance (
id INTEGER PRIMARY KEY AUTOINCREMENT,
car_id INTEGER NOT NULL, title TEXT NOT NULL,
maintenance_type TEXT NOT NULL CHECK(maintenance_type IN ('Repair','Maintenance','Upgrade','Inspection')),
service_date TEXT NOT NULL, odometer INTEGER,
parts_vendor TEXT, cost REAL, notes TEXT,
created_at TEXT DEFAULT (datetime('now')),
FOREIGN KEY (car_id) REFERENCES cars(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS maintenance_images (
id INTEGER PRIMARY KEY AUTOINCREMENT,
maintenance_id INTEGER NOT NULL, filename TEXT NOT NULL,
original_name TEXT, file_type TEXT NOT NULL DEFAULT 'image',
created_at TEXT DEFAULT (datetime('now')),
FOREIGN KEY (maintenance_id) REFERENCES maintenance(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS maintenance_parts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
maintenance_id INTEGER NOT NULL, position INTEGER NOT NULL DEFAULT 0,
name TEXT NOT NULL, vendor TEXT, cost REAL,
FOREIGN KEY (maintenance_id) REFERENCES maintenance(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_parts_maintenance ON maintenance_parts(maintenance_id);
CREATE TABLE IF NOT EXISTS maintenance_links (
id INTEGER PRIMARY KEY AUTOINCREMENT,
maintenance_id INTEGER NOT NULL, position INTEGER NOT NULL DEFAULT 0,
url TEXT NOT NULL, label TEXT,
FOREIGN KEY (maintenance_id) REFERENCES maintenance(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_links_maintenance ON maintenance_links(maintenance_id);
CREATE TABLE IF NOT EXISTS service_reminders (
id INTEGER PRIMARY KEY AUTOINCREMENT,
car_id INTEGER NOT NULL, title TEXT NOT NULL,
interval_type TEXT NOT NULL DEFAULT 'miles',
interval_miles INTEGER NOT NULL DEFAULT 0,
interval_months INTEGER,
last_done_odometer INTEGER, last_done_date TEXT, notes TEXT,
estimated_cost REAL,
created_at TEXT DEFAULT (datetime('now')),
FOREIGN KEY (car_id) REFERENCES cars(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS reminder_links (
id INTEGER PRIMARY KEY AUTOINCREMENT,
reminder_id INTEGER NOT NULL, position INTEGER NOT NULL DEFAULT 0,
url TEXT NOT NULL, label TEXT,
FOREIGN KEY (reminder_id) REFERENCES service_reminders(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_links_reminder ON reminder_links(reminder_id);
CREATE TABLE IF NOT EXISTS vendors (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
name TEXT NOT NULL, match_key TEXT NOT NULL,
created_at TEXT DEFAULT (datetime('now')),
UNIQUE (user_id, match_key),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS app_meta (key TEXT PRIMARY KEY, value TEXT);
CREATE TABLE IF NOT EXISTS user_settings (
user_id INTEGER PRIMARY KEY,
settings TEXT NOT NULL DEFAULT '{}',
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
''')
if conn.execute('SELECT COUNT(*) as c FROM users').fetchone()['c'] == 0:
# OR IGNORE: gunicorn runs several workers, each importing this module.
# Without it the losers of the race crash on the UNIQUE username.
cur = conn.execute('INSERT OR IGNORE INTO users (username,password,display_name,role,permissions,must_change_password) VALUES (?,?,?,?,?,?)',
('admin', hash_password('admin'), 'Administrator', 'admin', '{}', 1))
if cur.rowcount:
print("\n Default admin: admin / admin — change immediately!\n")
conn.commit()
# Migrations
try:
cols = [r['name'] for r in conn.execute("PRAGMA table_info(users)").fetchall()]
if 'must_change_password' not in cols:
conn.execute("ALTER TABLE users ADD COLUMN must_change_password INTEGER NOT NULL DEFAULT 0")
if 'permissions' not in cols:
conn.execute("ALTER TABLE users ADD COLUMN permissions TEXT NOT NULL DEFAULT '{}'")
conn.commit()
except Exception as e:
print(f"Migration users columns: {e}")
# Migration: add user_id to cars if missing
try:
cols = [r['name'] for r in conn.execute("PRAGMA table_info(cars)").fetchall()]
if 'user_id' not in cols:
admin = conn.execute("SELECT id FROM users WHERE role='admin' ORDER BY id LIMIT 1").fetchone()
admin_id = int(admin['id']) if admin else 1
conn.execute(f"ALTER TABLE cars ADD COLUMN user_id INTEGER NOT NULL DEFAULT {admin_id}")
conn.commit()
except Exception as e:
print(f"Migration user_id: {e}")
# Migration: update viewer role to editor
try:
conn.execute("UPDATE users SET role='editor' WHERE role='viewer'")
conn.commit()
except Exception as e:
print(f"Migration viewer->editor: {e}")
# Migration: add file_type to maintenance_images
try:
cols = [r['name'] for r in conn.execute("PRAGMA table_info(maintenance_images)").fetchall()]
if 'file_type' not in cols:
conn.execute("ALTER TABLE maintenance_images ADD COLUMN file_type TEXT NOT NULL DEFAULT 'image'")
conn.commit()
except Exception as e:
print(f"Migration file_type: {e}")
# Migration: repair maintenance_images FK left dangling by the pre-0.2.x
# Inspection-CHECK migration. That version renamed `maintenance` to a temp
# table without disabling foreign keys first; SQLite >=3.25 rewrites
# REFERENCES clauses in other tables to follow a rename, so this table ended
# up pointing at the temp table, which was then dropped. Result: every insert
# here fails with "no such table: main._maint_old".
try:
row = conn.execute("SELECT sql FROM sqlite_master WHERE type='table' AND name='maintenance_images'").fetchone()
if row and ('_maint_old' in (row['sql'] or '') or '_m_old' in (row['sql'] or '')):
conn.executescript("""PRAGMA foreign_keys=OFF;
BEGIN;
CREATE TABLE maintenance_images_new (id INTEGER PRIMARY KEY AUTOINCREMENT,
maintenance_id INTEGER NOT NULL,filename TEXT NOT NULL,original_name TEXT,
file_type TEXT NOT NULL DEFAULT 'image',created_at TEXT DEFAULT (datetime('now')),
FOREIGN KEY (maintenance_id) REFERENCES maintenance(id) ON DELETE CASCADE);
INSERT INTO maintenance_images_new (id,maintenance_id,filename,original_name,file_type,created_at)
SELECT id,maintenance_id,filename,original_name,file_type,created_at FROM maintenance_images;
DROP TABLE maintenance_images;
ALTER TABLE maintenance_images_new RENAME TO maintenance_images;
COMMIT;""")
conn.commit()
print("Migration: repaired dangling maintenance_images foreign key")
except Exception as e:
print(f"Migration maintenance_images FK: {e}")
# Migration: add Inspection CHECK
try:
tbl = conn.execute("SELECT sql FROM sqlite_master WHERE type='table' AND name='maintenance'").fetchone()
if tbl and 'Inspection' not in (tbl['sql'] or ''):
conn.executescript("""PRAGMA foreign_keys=OFF;ALTER TABLE maintenance RENAME TO _m_old;
CREATE TABLE maintenance (id INTEGER PRIMARY KEY AUTOINCREMENT,car_id INTEGER NOT NULL,title TEXT NOT NULL,
maintenance_type TEXT NOT NULL CHECK(maintenance_type IN ('Repair','Maintenance','Upgrade','Inspection')),
service_date TEXT NOT NULL,odometer INTEGER,parts_vendor TEXT,cost REAL,notes TEXT,
created_at TEXT DEFAULT (datetime('now')),FOREIGN KEY (car_id) REFERENCES cars(id) ON DELETE CASCADE);
INSERT INTO maintenance SELECT * FROM _m_old;DROP TABLE _m_old;PRAGMA foreign_keys=ON;""")
conn.commit()
except Exception as e:
print(f"Migration Inspection CHECK: {e}")
# Migration: reminders gained a time-based mode, so interval_miles is no
# longer the only interval. Pre-0.3.2 rows are all mileage-based.
try:
cols = [r['name'] for r in conn.execute("PRAGMA table_info(service_reminders)").fetchall()]
if 'interval_type' not in cols:
conn.execute("ALTER TABLE service_reminders ADD COLUMN interval_type TEXT NOT NULL DEFAULT 'miles'")
if 'interval_months' not in cols:
conn.execute("ALTER TABLE service_reminders ADD COLUMN interval_months INTEGER")
if 'last_done_date' not in cols:
conn.execute("ALTER TABLE service_reminders ADD COLUMN last_done_date TEXT")
if 'estimated_cost' not in cols: # reminders gained an estimated cost
conn.execute("ALTER TABLE service_reminders ADD COLUMN estimated_cost REAL")
conn.commit()
except Exception as e:
print(f"Migration reminder interval columns: {e}")
# Migration: records gained labor, shipping and tax, which add up with their parts.
try:
cols = [r['name'] for r in conn.execute("PRAGMA table_info(maintenance)").fetchall()]
for col in ('labor', 'shipping', 'tax'):
if col not in cols:
conn.execute(f"ALTER TABLE maintenance ADD COLUMN {col} REAL")
conn.commit()
except Exception as e:
print(f"Migration labor, shipping and tax columns: {e}")
# One-time: fill each user's vendor list from the vendors already on their
# records. Recorded in app_meta so vendors removed later stay removed.
try:
if not conn.execute("SELECT 1 FROM app_meta WHERE key='vendors_seeded'").fetchone():
n = seed_vendors_from_records(conn)
conn.execute("INSERT INTO app_meta (key,value) VALUES ('vendors_seeded',datetime('now'))")
conn.commit()
if n: print(f"Migration: saved {n} vendor(s) from existing records")
except Exception as e:
conn.rollback()
print(f"Migration vendors from records: {e}")
conn.close()
def clean_vendor_name(name):
"""Trim and collapse inner whitespace: how a vendor name is stored."""
return ' '.join((name or '').split())
def vendor_key(name):
"""Matching key for vendor names. Ignores case, accents, spacing and
punctuation, and treats '&' as 'and', so 'AutoZone', 'Auto Zone' and
'autozone.' are one vendor. static/js/app.js has the same rule."""
s = unicodedata.normalize('NFKD', name or '')
s = ''.join(c for c in s if not unicodedata.combining(c)).lower().replace('&', 'and')
return ''.join(c for c in s if c.isalnum())
def seed_vendors_from_records(conn):
"""Save the vendors found on each user's records to that user's list,
one per matching key. The spelling used most often wins; ties go to the
most recent record. Returns how many vendors were added."""
rows = conn.execute('''SELECT c.user_id, m.parts_vendor, COUNT(*) AS uses,
MAX(m.service_date || '|' || printf('%010d', m.id)) AS latest
FROM maintenance m JOIN cars c ON c.id=m.car_id
WHERE m.parts_vendor IS NOT NULL AND TRIM(m.parts_vendor) != ''
GROUP BY c.user_id, m.parts_vendor''').fetchall()
# Tally per spelling first: raw values differing only in spacing are one spelling.
tally = {} # (user_id, key) -> {name: [uses, latest]}
for r in rows:
name = clean_vendor_name(r['parts_vendor'])[:VENDOR_NAME_MAX].strip()
k = vendor_key(name)
if not k: continue
t = tally.setdefault((r['user_id'], k), {}).setdefault(name, [0, ''])
t[0] += r['uses']; t[1] = max(t[1], r['latest'])
added = 0
for (uid, k), spellings in tally.items():
name = max(spellings, key=lambda n: tuple(spellings[n]))
added += conn.execute('INSERT OR IGNORE INTO vendors (user_id,name,match_key) VALUES (?,?,?)',
(uid, name, k)).rowcount
return added
def save_upload(file, subfolder):
if file and allowed_file(file.filename):
ext = file.filename.rsplit('.',1)[1].lower()
folder = os.path.join(app.config['UPLOAD_FOLDER'], subfolder)
os.makedirs(folder, exist_ok=True)
if ext in CONVERT_TO_JPEG:
return save_as_jpeg(file, folder)
fn = f"{uuid.uuid4().hex}.{ext}"
file.save(os.path.join(folder, fn))
return fn
return None
def save_as_jpeg(file, folder):
"""An iPhone's HEIC photo, saved as a JPEG every browser and the PDF export
can show. Turned upright, and without its metadata (location included).
None when the file cannot be read as an image."""
from PIL import Image, ImageOps
import pillow_heif
pillow_heif.register_heif_opener()
fn = f"{uuid.uuid4().hex}.jpg"
try:
with Image.open(file.stream) as im:
ImageOps.exif_transpose(im).convert('RGB').save(os.path.join(folder, fn), 'JPEG', quality=88, optimize=True)
except Exception as e:
print(f"Could not convert {file.filename!r} to JPEG: {e}")
return None
return fn
def get_file_type(filename):
if filename and filename.rsplit('.',1)[1].lower() == 'pdf': return 'document'
return 'image'
def get_user_perms(user):
"""Get effective permissions for a user."""
if user['role'] == 'admin':
return {k: True for k in DEFAULT_PERMS}
try:
perms = json.loads(user.get('permissions','{}') or '{}')
return {k: perms.get(k, v) for k, v in DEFAULT_PERMS.items()}
except:
return dict(DEFAULT_PERMS)
VENDOR_NAME_MAX = 100
MONTH_DAYS = 30.44 # average calendar month, for months-to-days comparisons
def _rem_date(v):
"""Parse a stored YYYY-MM-DD date; None for anything unusable."""
if not v: return None
try:
return date.fromisoformat(str(v).strip()[:10])
except (ValueError, TypeError):
return None
def _add_months(d, months):
"""`d` plus N calendar months, clamped to the last day of the target month."""
m = d.month - 1 + int(months)
y, m = d.year + m // 12, m % 12 + 1
return date(y, m, min(d.day, calendar.monthrange(y, m)[1]))
def reminder_status(conn, rem, current_odo=None, today=None):
"""Expand a service_reminders row with its computed due state.
A reminder counts down either mileage or calendar time, per `interval_type`.
Either way the anchor is the most recent service record whose title matches
the reminder's, so logging the service again rolls the next due point
forward on its own. `last_done_odometer` / `last_done_date` hold the manual
mark -- set by hand, or by ticking the counter while logging a record -- and
the anchor is whichever of the two is further along, so marking a counter
reset always takes effect.
`remaining_fraction` is how much of the interval is left, and is the one
field comparable across both modes -- use it to sort mixed lists.
"""
d = dict(rem)
cid = d['car_id']
d['interval_type'] = itype = 'time' if (d.get('interval_type') or 'miles') == 'time' else 'miles'
d.setdefault('interval_months', None)
d.setdefault('last_done_date', None)
d.update(current_odometer=None, last_service_odometer=None, next_due_odometer=None,
miles_remaining=None, last_service_date=None, next_due_date=None,
days_remaining=None, remaining_fraction=None)
if itype == 'time':
match = conn.execute(
"SELECT MAX(service_date) AS s FROM maintenance WHERE car_id=?"
" AND lower(trim(title))=lower(trim(?))", (cid, d['title'])).fetchone()
anchor = max([x for x in (_rem_date(match['s'] if match else None),
_rem_date(d.get('last_done_date'))) if x], default=None)
interval = int(d.get('interval_months') or 0)
d['last_service_date'] = anchor.isoformat() if anchor else None
if anchor is None or interval <= 0:
d['status'] = 'no_baseline'
return d
due = _add_months(anchor, interval)
d['next_due_date'] = due.isoformat()
remaining = (due - (today or date.today())).days
d['days_remaining'] = remaining
d['remaining_fraction'] = remaining / (interval * MONTH_DAYS)
soon = max(14, int(interval * MONTH_DAYS * 0.05))
d['status'] = 'overdue' if remaining <= 0 else ('due_soon' if remaining <= soon else 'ok')
return d
if current_odo is None:
row = conn.execute('SELECT MAX(odometer) AS o FROM maintenance WHERE car_id=?', (cid,)).fetchone()
current_odo = row['o'] if row and row['o'] is not None else None
match = conn.execute(
"SELECT MAX(odometer) AS o FROM maintenance WHERE car_id=? AND odometer IS NOT NULL"
" AND lower(trim(title))=lower(trim(?))", (cid, d['title'])).fetchone()
anchor = max([int(x) for x in (match['o'] if match else None, d.get('last_done_odometer'))
if x is not None], default=None)
interval = int(d.get('interval_miles') or 0)
d['current_odometer'] = current_odo
d['last_service_odometer'] = anchor
if anchor is None or interval <= 0:
d['status'] = 'no_baseline'
return d
next_due = int(anchor) + interval
d['next_due_odometer'] = next_due
if current_odo is None:
d['status'] = 'no_baseline'
return d
remaining = next_due - int(current_odo)
d['miles_remaining'] = remaining
d['remaining_fraction'] = remaining / interval
soon = max(250, int(interval * 0.05))
d['status'] = 'overdue' if remaining <= 0 else ('due_soon' if remaining <= soon else 'ok')
return d
def reset_reminder_baselines(conn, cid, ids, odo, service_date):
"""Restart the named counters from this service record: mileage counters
from its odometer, time counters from its date. Ids that aren't this car's
are ignored, as is a mileage counter on a record with no odometer."""
done = []
for raw in ids:
try: rid = int(str(raw).strip())
except (TypeError, ValueError): continue
rem = conn.execute('SELECT * FROM service_reminders WHERE id=? AND car_id=?', (rid, cid)).fetchone()
if not rem: continue
if (rem['interval_type'] or 'miles') == 'time':
if not _rem_date(service_date): continue
conn.execute('UPDATE service_reminders SET last_done_date=? WHERE id=?', (service_date, rid))
else:
if odo is None: continue
conn.execute('UPDATE service_reminders SET last_done_odometer=? WHERE id=?', (int(odo), rid))
done.append(rid)
return done
def reminder_out(conn, rem):
"""A reminder as the vehicle page shows it: its due state and its links."""
d = reminder_status(conn, rem)
d['links'] = load_links(conn, 'reminder', rem['id'])
return d
def reminder_sort_key(r):
"""Soonest-due first across both interval modes, baseline-less rows last."""
f = r.get('remaining_fraction')
return (f is None, f if f is not None else 0.0)
def parse_reminder_input(d, base=None):
"""Validate reminder JSON/form input, falling back to `base` (the existing
row) for anything the caller omitted. Returns (fields, error)."""
def pick(key, default=None):
v = d.get(key)
if v is not None: return v
if base is not None and key in base.keys(): return base[key]
return default
def interval(key):
# blank means "unchanged" for an interval, never "cleared"
v = d.get(key)
if v is None or not str(v).strip():
v = base[key] if base is not None and key in base.keys() else None
return int(str(v).strip()) if v is not None and str(v).strip() else None
def odometer(key):
# blank *does* clear a manual baseline
v = pick(key)
return int(str(v).strip()) if v is not None and str(v).strip() else None
t = str(pick('title', '') or '').strip()
itype = 'time' if str(pick('interval_type', 'miles') or '').strip().lower() == 'time' else 'miles'
n = str(pick('notes', '') or '').strip()
ld_date = str(pick('last_done_date', '') or '').strip() or None
try:
iv_mi, iv_mo, ld_odo = interval('interval_miles'), interval('interval_months'), odometer('last_done_odometer')
except ValueError:
return None, 'Mileage and interval values must be whole numbers'
# blank clears the estimate; leaving it out keeps the stored one
est, err = parse_money(pick('estimated_cost'), 'Estimated cost')
if err: return None, err
if not t: return None, 'Title is required'
if itype == 'time':
if not iv_mo or iv_mo <= 0: return None, 'Month interval is required and must be greater than zero'
if ld_date and _rem_date(ld_date) is None: return None, 'Last-done date must be a valid date'
else:
if not iv_mi or iv_mi <= 0: return None, 'Mileage interval is required and must be greater than zero'
if ld_odo is not None and ld_odo < 0: return None, 'Last-done mileage cannot be negative'
return {'title': t, 'interval_type': itype, 'interval_miles': iv_mi or 0, 'interval_months': iv_mo,
'last_done_odometer': ld_odo, 'last_done_date': ld_date, 'notes': n or None, 'estimated_cost': est}, None
def can_access_car(conn, cid, user):
"""Check if user can access this car (owns it or is admin)."""
car = conn.execute('SELECT * FROM cars WHERE id=?',(cid,)).fetchone()
if not car: return None
if user['role'] == 'admin' or car['user_id'] == user['id']:
return car
return None
# ── Error Handlers ─────────────────────────────────────
@app.errorhandler(413)
def too_large(e):
if request.path.startswith('/api/backup/restore/'):
return jsonify({'error':f'A piece of the backup was larger than {RESTORE_CHUNK // (1024 * 1024)} MB.'}), 413
if request.path.startswith('/api/'): return jsonify({'error':'File too large (max 32MB)'}), 413
return 'File too large', 413
@app.errorhandler(500)
def server_error(e):
if request.path.startswith('/api/'): return jsonify({'error':'Internal server error'}), 500
return 'Internal server error', 500
@app.teardown_request
def close_db_conns(exc):
"""Release any connection a view opened, rolling back if it failed."""
for conn in g.pop('_db_conns', []):
try:
if exc is not None: conn.rollback()
conn.close()
except Exception:
pass
# ── Auth Middleware ─────────────────────────────────────
@app.before_request
def load_user():
g.user = None
uid = session.get('user_id')
if uid:
conn = get_db()
if session.get('epoch') != session_epoch(conn): # signed in before a restore
conn.close(); session.clear(); return
u = conn.execute('SELECT id,username,display_name,role,permissions,must_change_password FROM users WHERE id=?',(uid,)).fetchone()
conn.close()
if u: g.user = dict(u)
def login_required(f):
@wraps(f)
def dec(*a,**kw):
if not g.user:
if request.path.startswith('/api/'): return jsonify({'error':'Authentication required'}), 401
return redirect(url_for('login_page'))
return f(*a,**kw)
return dec
def role_required(*roles):
def decorator(f):
@wraps(f)
@login_required
def dec(*a,**kw):
if g.user['role'] not in roles: return jsonify({'error':'Insufficient permissions'}), 403
return f(*a,**kw)
return dec
return decorator
def perm_required(perm):
"""Check a specific granular permission."""
def decorator(f):
@wraps(f)
@login_required
def dec(*a,**kw):
perms = get_user_perms(g.user)
if not perms.get(perm, False): return jsonify({'error':'Permission denied'}), 403
return f(*a,**kw)
return dec
return decorator
# ── Pages ──────────────────────────────────────────────
@app.route('/uploads/<path:filename>')
@login_required
def serve_upload(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
@app.route('/login')
def login_page():
if g.user: return redirect(url_for('index'))
conn = get_db(); ts = turnstile_config(conn); conn.close()
return render_template('login.html', version=APP_VERSION, turnstile_site_key=ts['site_key'] if ts['on'] else '')
@app.route('/')
@login_required
def index():
perms = get_user_perms(g.user)
# The saved theme, so the page paints in it before the settings load.
conn = get_db()
row = conn.execute('SELECT settings FROM user_settings WHERE user_id=?', (g.user['id'],)).fetchone()
conn.close()
try: theme = json.loads(row['settings']).get('theme', 'dark') if row else 'dark'
except (ValueError, TypeError): theme = 'dark'
if theme not in ('dark', 'light', 'system'): theme = 'dark'
return render_template('index.html', user=g.user, version=APP_VERSION, perms=perms, theme_pref=theme)
@app.route('/api/version')
def api_version():
return jsonify({'version': APP_VERSION})
# ── Auth API ───────────────────────────────────────────
# Cloudflare Turnstile on the sign-in page, set up by an admin in Settings and
# kept in app_meta. It turns on only after a check made with the keys passes,
# so a wrong key cannot lock everyone out. `flask --app app turnstile-off`
# turns it off from the server if the keys stop working.
TURNSTILE_VERIFY_URL = 'https://challenges.cloudflare.com/turnstile/v0/siteverify'
TURNSTILE_KEY_RE = re.compile(r'^[A-Za-z0-9_-]{10,100}$')
def turnstile_config(conn):
rows = dict(conn.execute("SELECT key,value FROM app_meta WHERE key IN ('turnstile_site_key','turnstile_secret_key','turnstile_on')").fetchall())
site, secret = rows.get('turnstile_site_key') or '', rows.get('turnstile_secret_key') or ''
return {'site_key': site, 'secret_key': secret, 'on': rows.get('turnstile_on') == '1' and bool(site and secret)}
def turnstile_set_on(conn, on):
conn.execute("INSERT OR REPLACE INTO app_meta (key,value) VALUES ('turnstile_on',?)", ('1' if on else '0',))
@app.cli.command('turnstile-off')
def turnstile_off_command():
"""Turn off the sign-in check, for when its keys no longer work."""
conn = get_db(); turnstile_set_on(conn, False); conn.commit(); conn.close()
print('Turnstile is off. Sign in, then set it up again in Settings, Sign-in protection.')
def turnstile_check(token, secret, action='login'):
"""None when Cloudflare confirms a Turnstile token, else the message to
show. Each token passes once, so the page asks for a new one after every
attempt."""
import urllib.request, urllib.parse
token = str(token or '')
if not token or len(token) > 2048: return 'Complete the check above Sign in, then try again.'
# Behind Cloudflare the visitor's address arrives in CF-Connecting-IP; it
# is only a hint to Cloudflare, so a forged one does no harm.
ip = request.headers.get('CF-Connecting-IP') or request.remote_addr or ''
body = urllib.parse.urlencode({'secret': secret, 'response': token, 'remoteip': ip}).encode()
try:
with urllib.request.urlopen(urllib.request.Request(TURNSTILE_VERIFY_URL, data=body), timeout=10) as r:
result = json.load(r)
except Exception as e:
print(f'Turnstile verification failed: {e!r}')
return 'The sign-in check could not be confirmed with Cloudflare. Try again in a moment.'
if not result.get('success'):
codes = result.get('error-codes') or []
if 'invalid-input-secret' in codes: return 'Cloudflare did not accept the secret key.'
return 'The sign-in check did not pass. Try again.'
if result.get('action') and result['action'] != action:
return 'The sign-in check did not pass. Try again.'
return None
@app.route('/api/auth/login', methods=['POST'])
def api_login():
data = request.get_json() or {}
u, p = data.get('username','').strip(), data.get('password','')
if not u or not p: return jsonify({'error':'Username and password required'}), 400
conn = get_db()
ts = turnstile_config(conn)
if ts['on']: # before the password, so it also slows guessing
err = turnstile_check(data.get('turnstile'), ts['secret_key'])
if err: conn.close(); return jsonify({'error': err, 'turnstile': True}), 400
user = conn.execute('SELECT * FROM users WHERE username=?',(u,)).fetchone()
conn.close()
if not user or not verify_password(p, user['password']): return jsonify({'error':'Invalid credentials'}), 401
session.clear(); session['user_id']=user['id']; session.permanent=True
ep = get_db(); session['epoch'] = session_epoch(ep); ep.close()
mcp = 0
try: mcp = user['must_change_password']
except: pass
return jsonify({'id':user['id'],'username':user['username'],'display_name':user['display_name'],
'role':user['role'],'must_change_password':bool(mcp)})
@app.route('/api/auth/logout', methods=['POST'])
def api_logout():
session.clear(); return jsonify({'success':True})
@app.route('/api/auth/me')
@login_required
def api_me():
perms = get_user_perms(g.user)
return jsonify({**g.user, 'effective_permissions': perms})
@app.route('/api/auth/change-password', methods=['POST'])
@login_required
def api_change_password():
data = request.get_json() or {}
cur, new = data.get('current_password',''), data.get('new_password','')
if not cur or not new: return jsonify({'error':'Both passwords required'}), 400
if len(new)<4: return jsonify({'error':'Min 4 characters'}), 400
conn = get_db()
u = conn.execute('SELECT password FROM users WHERE id=?',(g.user['id'],)).fetchone()
if not verify_password(cur, u['password']): conn.close(); return jsonify({'error':'Current password incorrect'}), 401
conn.execute('UPDATE users SET password=?, must_change_password=0 WHERE id=?',(hash_password(new),g.user['id']))
conn.commit(); conn.close()
return jsonify({'success':True})
# ── Settings API ───────────────────────────────────────
@app.route('/api/settings', methods=['GET'])
@login_required
def get_settings():
conn = get_db()
row = conn.execute('SELECT settings FROM user_settings WHERE user_id=?',(g.user['id'],)).fetchone()
conn.close()
defaults = {'dashboard_range':'all','show_vehicles':True,'show_records':True,'show_cost':True,'show_due':True,'theme':'dark'}
if row:
saved = json.loads(row['settings'])
defaults.update(saved)
return jsonify(defaults)
@app.route('/api/settings', methods=['PUT'])
@login_required
def save_settings():
data = request.get_json() or {}
conn = get_db()
s = json.dumps(data)
existing = conn.execute('SELECT user_id FROM user_settings WHERE user_id=?',(g.user['id'],)).fetchone()
if existing: conn.execute('UPDATE user_settings SET settings=? WHERE user_id=?',(s,g.user['id']))
else: conn.execute('INSERT INTO user_settings (user_id,settings) VALUES (?,?)',(g.user['id'],s))
conn.commit(); conn.close()
return jsonify({'success':True})
# ── Vendors API ────────────────────────────────────────
# Each user keeps their own list. Records still store the vendor as plain
# text, so renaming or removing a vendor here never touches existing records.
@app.route('/api/vendors', methods=['GET'])
@login_required
def get_vendors():
conn = get_db()
rows = conn.execute('SELECT id,name FROM vendors WHERE user_id=? ORDER BY name COLLATE NOCASE',(g.user['id'],)).fetchall()
conn.close()
return jsonify([dict(r) for r in rows])
def parse_vendor_name():
"""(name, key, error) from the request body."""
name = clean_vendor_name((request.get_json() or {}).get('name'))
if not name: return None, None, 'Vendor name required'
if len(name) > VENDOR_NAME_MAX: return None, None, f'Max {VENDOR_NAME_MAX} characters'
k = vendor_key(name)
if not k: return None, None, 'Vendor name needs a letter or number'
return name, k, None
@app.route('/api/vendors', methods=['POST'])
@login_required
def add_vendor():
name, k, err = parse_vendor_name()
if err: return jsonify({'error':err}), 400
conn = get_db()
# A name matching a saved vendor returns that vendor instead of a duplicate.
cur = conn.execute('INSERT OR IGNORE INTO vendors (user_id,name,match_key) VALUES (?,?,?)',(g.user['id'],name,k))
conn.commit()
row = dict(conn.execute('SELECT id,name FROM vendors WHERE user_id=? AND match_key=?',(g.user['id'],k)).fetchone())
conn.close()
return jsonify(row), 201 if cur.rowcount else 200
@app.route('/api/vendors/<int:vid>', methods=['PUT'])
@login_required
def rename_vendor(vid):
name, k, err = parse_vendor_name()
if err: return jsonify({'error':err}), 400
conn = get_db()
if not conn.execute('SELECT 1 FROM vendors WHERE id=? AND user_id=?',(vid,g.user['id'])).fetchone():
conn.close(); return jsonify({'error':'Not found'}), 404
clash = conn.execute('SELECT name FROM vendors WHERE user_id=? AND match_key=? AND id!=?',(g.user['id'],k,vid)).fetchone()
if clash: conn.close(); return jsonify({'error':f'"{clash["name"]}" is already saved'}), 409
conn.execute('UPDATE vendors SET name=?,match_key=? WHERE id=?',(name,k,vid))
conn.commit(); conn.close()
return jsonify({'id':vid,'name':name})
@app.route('/api/vendors/<int:vid>', methods=['DELETE'])
@login_required
def delete_vendor(vid):
conn = get_db()
cur = conn.execute('DELETE FROM vendors WHERE id=? AND user_id=?',(vid,g.user['id']))
conn.commit(); conn.close()
if not cur.rowcount: return jsonify({'error':'Not found'}), 404
return jsonify({'success':True})
# ── User Management (admin) ───────────────────────────
# ── Sign-in protection (admins) ────────────────────────
@app.route('/api/settings/turnstile', methods=['GET'])
@role_required('admin')
def get_turnstile():
conn = get_db(); ts = turnstile_config(conn); conn.close()
# The secret key never leaves the server.
return jsonify({'on': ts['on'], 'site_key': ts['site_key'], 'has_secret': bool(ts['secret_key'])})
@app.route('/api/settings/turnstile', methods=['PUT'])
@role_required('admin')
def put_turnstile():
"""Save the keys and turn the check on, once a check made in Settings with
those keys has passed. A blank secret keeps the saved one."""
d = request.get_json(silent=True) or {}
site, secret = str(d.get('site_key') or '').strip(), str(d.get('secret_key') or '').strip()
conn = get_db()
if not secret: secret = turnstile_config(conn)['secret_key']
if not TURNSTILE_KEY_RE.match(site): conn.close(); return jsonify({'error': 'Enter the site key from the Cloudflare dashboard.'}), 400
if not TURNSTILE_KEY_RE.match(secret): conn.close(); return jsonify({'error': 'Enter the secret key from the Cloudflare dashboard.'}), 400
if not d.get('token'): conn.close(); return jsonify({'error': 'Complete the check first.'}), 400
err = turnstile_check(d.get('token'), secret, action='settings')
if err: conn.close(); return jsonify({'error': err if 'secret key' in err or 'Cloudflare' in err else 'The check did not pass with these keys. Check them and try again.'}), 400
conn.executemany("INSERT OR REPLACE INTO app_meta (key,value) VALUES (?,?)",
[('turnstile_site_key', site), ('turnstile_secret_key', secret)])
turnstile_set_on(conn, True)
conn.commit(); conn.close()
return jsonify({'on': True, 'site_key': site, 'has_secret': True})
@app.route('/api/settings/turnstile', methods=['DELETE'])
@role_required('admin')
def delete_turnstile():
"""Turn the check off. With forget, the keys go too."""
conn = get_db(); turnstile_set_on(conn, False)
if request.args.get('forget') == '1':
conn.execute("DELETE FROM app_meta WHERE key IN ('turnstile_site_key','turnstile_secret_key')")
conn.commit(); ts = turnstile_config(conn); conn.close()
return jsonify({'on': False, 'site_key': ts['site_key'], 'has_secret': bool(ts['secret_key'])})
@app.route('/api/users', methods=['GET'])
@role_required('admin')
def get_users():
conn = get_db()
users = conn.execute('SELECT id,username,display_name,role,permissions,created_at FROM users ORDER BY created_at').fetchall()
conn.close()
result = []
for u in users:
d = dict(u)
d['effective_permissions'] = get_user_perms(d)
result.append(d)
return jsonify(result)
@app.route('/api/users', methods=['POST'])
@role_required('admin')
def create_user():
data = request.get_json() or {}
un=data.get('username','').strip().lower(); pw=data.get('password','')
dn=data.get('display_name','').strip(); role=data.get('role','editor').strip()
perms=data.get('permissions',{})
if not un or not pw: return jsonify({'error':'Username and password required'}), 400
if role not in ROLES: return jsonify({'error':'Invalid role'}), 400
if len(pw)<4: return jsonify({'error':'Min 4 chars'}), 400
conn = get_db()
if conn.execute('SELECT id FROM users WHERE username=?',(un,)).fetchone():
conn.close(); return jsonify({'error':'Username exists'}), 409
conn.execute('INSERT INTO users (username,password,display_name,role,permissions) VALUES (?,?,?,?,?)',
(un, hash_password(pw), dn or un, role, json.dumps(perms)))
conn.commit()
u = conn.execute('SELECT id,username,display_name,role,permissions,created_at FROM users WHERE username=?',(un,)).fetchone()
conn.close()
d = dict(u); d['effective_permissions'] = get_user_perms(d)
return jsonify(d), 201
@app.route('/api/users/<int:uid>', methods=['PUT'])
@role_required('admin')
def update_user(uid):
data = request.get_json() or {}
conn = get_db()
user = conn.execute('SELECT * FROM users WHERE id=?',(uid,)).fetchone()
if not user: conn.close(); return jsonify({'error':'Not found'}), 404
dn = data.get('display_name',user['display_name']).strip()
role = data.get('role',user['role']).strip()
perms = data.get('permissions')
npw = data.get('password','').strip()
if role not in ROLES: conn.close(); return jsonify({'error':'Invalid role'}), 400
if user['role']=='admin' and role!='admin':
if conn.execute("SELECT COUNT(*) as c FROM users WHERE role='admin'").fetchone()['c']<=1:
conn.close(); return jsonify({'error':'Cannot remove last admin'}), 400
perm_str = json.dumps(perms) if perms is not None else user['permissions']
if npw:
if len(npw)<4: conn.close(); return jsonify({'error':'Min 4 chars'}), 400
conn.execute('UPDATE users SET display_name=?,role=?,permissions=?,password=? WHERE id=?',(dn,role,perm_str,hash_password(npw),uid))
else:
conn.execute('UPDATE users SET display_name=?,role=?,permissions=? WHERE id=?',(dn,role,perm_str,uid))
conn.commit()
u = conn.execute('SELECT id,username,display_name,role,permissions,created_at FROM users WHERE id=?',(uid,)).fetchone()
conn.close()
d = dict(u); d['effective_permissions'] = get_user_perms(d)
return jsonify(d)
@app.route('/api/users/<int:uid>', methods=['DELETE'])
@role_required('admin')
def delete_user(uid):
conn = get_db()
user = conn.execute('SELECT * FROM users WHERE id=?',(uid,)).fetchone()
if not user: conn.close(); return jsonify({'error':'Not found'}), 404
if uid==g.user['id']: conn.close(); return jsonify({'error':'Cannot delete yourself'}), 400
if user['role']=='admin':
if conn.execute("SELECT COUNT(*) as c FROM users WHERE role='admin'").fetchone()['c']<=1:
conn.close(); return jsonify({'error':'Cannot delete last admin'}), 400
conn.execute('DELETE FROM users WHERE id=?',(uid,))
conn.commit(); conn.close()
return jsonify({'success':True})
# ── Car API (multi-user) ──────────────────────────────
@app.route('/api/cars', methods=['GET'])
@login_required
def get_cars():
q = request.args.get('q','').strip()
conn = get_db()
if g.user['role'] == 'admin':
if q:
cars = conn.execute("SELECT c.*, u.display_name as owner_name FROM cars c JOIN users u ON c.user_id=u.id WHERE c.year LIKE ? OR c.make LIKE ? OR c.model LIKE ? OR c.vin LIKE ? ORDER BY c.created_at DESC",
(f'%{q}%',f'%{q}%',f'%{q}%',f'%{q}%')).fetchall()
else:
cars = conn.execute('SELECT c.*, u.display_name as owner_name FROM cars c JOIN users u ON c.user_id=u.id ORDER BY c.created_at DESC').fetchall()
else:
if q:
cars = conn.execute("SELECT * FROM cars WHERE user_id=? AND (year LIKE ? OR make LIKE ? OR model LIKE ? OR vin LIKE ?) ORDER BY created_at DESC",
(g.user['id'],f'%{q}%',f'%{q}%',f'%{q}%',f'%{q}%')).fetchall()
else:
cars = conn.execute('SELECT * FROM cars WHERE user_id=? ORDER BY created_at DESC',(g.user['id'],)).fetchall()
result = []
for car in cars:
c = dict(car)
s = conn.execute("SELECT COUNT(*) as count, COALESCE(SUM(cost),0) as total_cost, MAX(odometer) as max_odo FROM maintenance WHERE car_id=?",(c['id'],)).fetchone()
c['maintenance_count']=s['count']; c['total_cost']=s['total_cost']; c['latest_odometer']=s['max_odo']
# Upcoming service reminders for the card: soonest first, skipping any
# that have no baseline to count down from.
rems = [reminder_status(conn, r, s['max_odo'])
for r in conn.execute('SELECT * FROM service_reminders WHERE car_id=?', (c['id'],)).fetchall()]
rems = [r for r in rems if r['status'] != 'no_baseline']
rems.sort(key=reminder_sort_key)
c['reminders'] = rems[:3]
c['reminders_total'] = len(rems)
c['reminders_due'] = sum(1 for r in rems if r['status'] in ('overdue','due_soon'))
result.append(c)
conn.close()
return jsonify(result)
@app.route('/api/cars', methods=['POST'])
@perm_required('can_add_cars')
def add_car():
year=request.form.get('year'); make=request.form.get('make','').strip()
model=request.form.get('model','').strip(); vin=request.form.get('vin','').strip()
pd=request.form.get('purchase_date','').strip()
if not year or not make or not model: return jsonify({'error':'Year, make, model required'}), 400
image = save_upload(request.files.get('image'), 'cars') if 'image' in request.files else None
conn = get_db()
cur = conn.execute('INSERT INTO cars (user_id,year,make,model,vin,image,purchase_date) VALUES (?,?,?,?,?,?,?)',
(g.user['id'], int(year), make, model, vin or None, image, pd or None))
conn.commit()
car = dict(conn.execute('SELECT * FROM cars WHERE id=?',(cur.lastrowid,)).fetchone())
conn.close()
return jsonify(car), 201
@app.route('/api/cars/<int:cid>', methods=['GET'])
@login_required
def get_car(cid):
conn = get_db()
car = can_access_car(conn, cid, g.user)
conn.close()
if not car: return jsonify({'error':'Not found'}), 404
return jsonify(dict(car))
@app.route('/api/cars/<int:cid>', methods=['PUT'])
@perm_required('can_edit_cars')
def update_car(cid):
conn = get_db()
car = can_access_car(conn, cid, g.user)
if not car: conn.close(); return jsonify({'error':'Not found'}), 404
year=request.form.get('year',car['year']); make=request.form.get('make',car['make']).strip()
model=request.form.get('model',car['model']).strip(); vin=request.form.get('vin',car['vin'] or '').strip()
pd=request.form.get('purchase_date',car['purchase_date'] or '').strip()
image = car['image']
if 'image' in request.files and request.files['image'].filename:
if car['image']:
p = os.path.join(app.config['UPLOAD_FOLDER'],'cars',car['image'])
if os.path.exists(p): os.remove(p)
image = save_upload(request.files['image'],'cars')
conn.execute('UPDATE cars SET year=?,make=?,model=?,vin=?,image=?,purchase_date=? WHERE id=?',
(int(year),make,model,vin or None,image,pd or None,cid))
conn.commit()
updated = dict(conn.execute('SELECT * FROM cars WHERE id=?',(cid,)).fetchone())
conn.close()
return jsonify(updated)