-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
7845 lines (6985 loc) · 376 KB
/
Copy pathapp.py
File metadata and controls
7845 lines (6985 loc) · 376 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
"""
MERIT — Mass Email & Inventory Tool for Virtual Enterprise (VEI) firms
Gmail SMTP · Freeimage.host / Imghippo image hosting · Supabase / Turso database
"""
import base64
import csv
import hashlib
import io
import json
import os as _os
import re
import smtplib
import time
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from datetime import datetime
import urllib.request as _urllib_request
from pathlib import Path
import warnings
# Suppress Pandas warnings about non-SQLAlchemy connectable (sqlite3 / psycopg2)
warnings.filterwarnings("ignore", ".*SQLAlchemy.*")
warnings.filterwarnings("ignore", ".*DBAPI2.*")
import pandas as pd
import streamlit as st
import sqlite3
# ─────────────────────────────────────────────
# Custom CSS for UI enhancements
# ─────────────────────────────────────────────
st.markdown("""
<style>
/* Make toasts stay visible longer / slower fade out */
[data-testid="stToast"] {
animation: toast-fade-in 0.5s, toast-fade-out 0.5s 5.5s forwards !important;
width: auto !important;
max-width: 400px !important;
}
@keyframes toast-fade-in { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
@keyframes toast-fade-out { from { opacity: 1; } to { opacity: 0; } }
/* Fix all buttons - avoid blue text/outlines */
.stButton > button {
transition: all 0.2s ease !important;
outline: none !important;
box-shadow: none !important;
}
/* Primary buttons (Main actions) */
.stButton > button[kind="primary"] {
background-color: #dc2626 !important; /* Red-600 */
border-color: #dc2626 !important;
color: #ffffff !important;
}
.stButton > button[kind="primary"]:hover {
background-color: #ef4444 !important; /* Red-500 */
border-color: #ef4444 !important;
color: #ffffff !important;
transform: translateY(-1.5px);
box-shadow: 0 6px 15px rgba(220, 38, 38, 0.3) !important;
}
.stButton > button[kind="primary"]:focus:not(:active) {
background-color: #dc2626 !important;
border-color: #dc2626 !important;
color: #ffffff !important;
box-shadow: none !important;
}
/* Secondary / Default buttons */
.stButton > button[kind="secondary"] {
background-color: #3f3f46 !important; /* Zinc-700 */
border-color: #3f3f46 !important;
color: #ffffff !important;
}
.stButton > button[kind="secondary"]:hover {
background-color: #52525b !important; /* Zinc-600 */
border-color: #52525b !important;
color: #ffffff !important;
transform: translateY(-1.5px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1) !important;
}
.stButton > button[kind="secondary"]:focus:not(:active) {
background-color: #3f3f46 !important;
border-color: #3f3f46 !important;
color: #ffffff !important;
box-shadow: none !important;
}
.stButton > button:active {
transform: translateY(0px) !important;
}
</style>
""", unsafe_allow_html=True)
_SQLITE_DB = Path(__file__).parent / "data.db"
def _get_sqlite_conn():
conn = sqlite3.connect(str(_SQLITE_DB), check_same_thread=False)
conn.row_factory = sqlite3.Row
return conn
def _sqlite_read_sql(conn, sql: str, params=()) -> "pd.DataFrame":
"""Execute SQL on a sqlite3 connection and return a DataFrame without using pd.read_sql."""
cur = conn.execute(sql, params)
cols = [d[0] for d in cur.description] if cur.description else []
return pd.DataFrame([dict(zip(cols, row)) for row in cur.fetchall()], columns=cols if cols else None)
def _init_sqlite():
conn = _get_sqlite_conn()
conn.executescript("""
CREATE TABLE IF NOT EXISTS products (
sku TEXT PRIMARY KEY,
item_name TEXT NOT NULL,
category TEXT NOT NULL DEFAULT '',
price REAL NOT NULL DEFAULT 0.0,
description TEXT NOT NULL DEFAULT '',
buy_button_url TEXT NOT NULL DEFAULT '',
image_url TEXT NOT NULL DEFAULT 'N/A',
active INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS inventory (
sku TEXT PRIMARY KEY,
item_name TEXT NOT NULL,
category TEXT NOT NULL DEFAULT '',
price REAL NOT NULL DEFAULT 0.0,
unit_cost REAL NOT NULL DEFAULT 0.0,
stock_left INTEGER NOT NULL DEFAULT 0,
status TEXT NOT NULL DEFAULT 'In stock',
image_url TEXT NOT NULL DEFAULT 'N/A',
original_stock INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS outbound_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
recipient_name TEXT NOT NULL,
recipient_email TEXT NOT NULL,
order_number TEXT NOT NULL,
products_list TEXT NOT NULL,
subtotal REAL NOT NULL DEFAULT 0.0,
tax REAL NOT NULL DEFAULT 0.0,
shipping REAL NOT NULL DEFAULT 0.0,
total_cost REAL NOT NULL DEFAULT 0.0,
timestamp TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS email_templates (
template_key TEXT PRIMARY KEY,
html_content TEXT NOT NULL DEFAULT '',
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT NOT NULL UNIQUE,
full_name TEXT NOT NULL DEFAULT '',
role TEXT NOT NULL DEFAULT 'staff',
password_hash TEXT NOT NULL DEFAULT '',
invite_token TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS roles (
id INTEGER PRIMARY KEY AUTOINCREMENT,
role_name TEXT NOT NULL UNIQUE,
pages TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS financials (
id INTEGER PRIMARY KEY AUTOINCREMENT,
entry_date TEXT NOT NULL DEFAULT (date('now')),
category TEXT NOT NULL DEFAULT 'Expense',
description TEXT NOT NULL DEFAULT '',
amount REAL NOT NULL DEFAULT 0.0,
notes TEXT NOT NULL DEFAULT '',
payment_method TEXT NOT NULL DEFAULT '',
tags TEXT NOT NULL DEFAULT '',
is_recurring INTEGER NOT NULL DEFAULT 0,
recur_frequency TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS fin_budgets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
category TEXT NOT NULL,
period TEXT NOT NULL DEFAULT 'monthly',
budget_amount REAL NOT NULL DEFAULT 0.0,
notes TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL DEFAULT (datetime('now')),
UNIQUE(category, period)
);
""")
conn.commit()
# Migrate existing financials table — add columns if missing
try:
_fin_cols = [r[1] for r in conn.execute("PRAGMA table_info(financials)").fetchall()]
for _fc_name, _fc_def in [
("payment_method", "TEXT NOT NULL DEFAULT ''"),
("tags", "TEXT NOT NULL DEFAULT ''"),
("is_recurring", "INTEGER NOT NULL DEFAULT 0"),
("recur_frequency", "TEXT NOT NULL DEFAULT ''"),
]:
if _fc_name not in _fin_cols:
conn.execute(f"ALTER TABLE financials ADD COLUMN {_fc_name} {_fc_def}")
conn.commit()
except Exception:
pass
# Seed default roles if the table is empty
try:
_rc = conn.execute("SELECT COUNT(*) FROM roles").fetchone()[0]
if _rc == 0:
conn.executemany(
"INSERT OR IGNORE INTO roles (role_name, pages) VALUES (?, ?)",
[
("admin", "Mass Email,Products,Inventory,Financials,Settings,API Endpoints"),
("staff", "Mass Email,Products,Inventory,Financials"),
("viewer", "Inventory,Financials"),
]
)
conn.commit()
except Exception: pass
# Migration: add Financials to default role pages if missing
try:
_default_pages = {
"admin": "Mass Email,Products,Inventory,Financials,Settings,API Endpoints",
"staff": "Mass Email,Products,Inventory,Financials",
"viewer": "Inventory,Financials",
}
for _rn, _rp in _default_pages.items():
_row = conn.execute("SELECT pages FROM roles WHERE role_name=?", (_rn,)).fetchone()
if _row and "Financials" not in str(_row[0]):
conn.execute("UPDATE roles SET pages=? WHERE role_name=?", (_rp, _rn))
conn.commit()
except Exception: pass
# Migration for existing outbound_logs (add subtotal, tax, shipping)
try:
cur = conn.cursor()
cur.execute("PRAGMA table_info(outbound_logs)")
cols = [r[1] for r in cur.fetchall()]
if "subtotal" not in cols:
conn.execute("ALTER TABLE outbound_logs ADD COLUMN subtotal REAL NOT NULL DEFAULT 0.0")
conn.execute("ALTER TABLE outbound_logs ADD COLUMN tax REAL NOT NULL DEFAULT 0.0")
conn.execute("ALTER TABLE outbound_logs ADD COLUMN shipping REAL NOT NULL DEFAULT 0.0")
conn.commit()
except Exception: pass
# Migration for existing products table (add description, buy_button_url, active)
try:
cur = conn.cursor()
cur.execute("PRAGMA table_info(products)")
_prod_cols = [r[1] for r in cur.fetchall()]
if "description" not in _prod_cols:
conn.execute("ALTER TABLE products ADD COLUMN description TEXT NOT NULL DEFAULT ''")
if "buy_button_url" not in _prod_cols:
conn.execute("ALTER TABLE products ADD COLUMN buy_button_url TEXT NOT NULL DEFAULT ''")
if "active" not in _prod_cols:
conn.execute("ALTER TABLE products ADD COLUMN active INTEGER NOT NULL DEFAULT 1")
conn.commit()
except Exception: pass
# Migration for users table (add invite_token)
try:
cur = conn.cursor()
cur.execute("PRAGMA table_info(users)")
_user_cols = [r[1] for r in cur.fetchall()]
if "invite_token" not in _user_cols:
conn.execute("ALTER TABLE users ADD COLUMN invite_token TEXT")
conn.commit()
except Exception: pass
conn.close()
_init_sqlite()
def _clear_data_caches():
"""Clear both the @st.cache_data function cache and the per-session state caches."""
st.cache_data.clear()
st.session_state.pop("_products_cache", None)
st.session_state.pop("_inv_cache", None)
def _parse_product_qty(pname: str) -> tuple:
"""Parse 'Product Name x 3' → ('Product Name', 3). Plain names return qty=1."""
m = re.match(r'^(.+?)\s+x\s+(\d+)$', pname.strip(), re.IGNORECASE)
if m:
return m.group(1).strip(), int(m.group(2))
return pname.strip(), 1
# ─────────────────────────────────────────────
# Role-based access control
# ─────────────────────────────────────────────
_ALL_PAGES = ["Mass Email", "Products", "Inventory", "Financials", "Settings", "API Endpoints"]
# Fallback role→pages map used before DB is available
_ROLE_PAGES = {
"admin": list(_ALL_PAGES),
"staff": ["Mass Email", "Products", "Inventory", "Financials"],
"viewer": ["Inventory", "Financials"],
}
_ROLE_LABELS = {
"admin": "Admin — full access",
"staff": "Staff — Email, Products, Inventory, Financials",
"viewer": "Viewer — Inventory & Financials",
}
def _hash_password(password: str) -> str:
salt = _os.urandom(32)
key = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, 100_000)
return salt.hex() + ":" + key.hex()
def _verify_password(stored_hash: str, password: str) -> bool:
try:
salt_hex, key_hex = stored_hash.split(":", 1)
salt = bytes.fromhex(salt_hex)
key = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, 100_000)
return key.hex() == key_hex
except Exception:
return False
@st.cache_data(ttl=30, show_spinner=False)
def _fetch_users_cached(sb_conn_str: str, turso_key: str = "") -> list:
"""Cached fetch of users — takes hashable conn string, returns list of row dicts."""
if sb_conn_str:
try:
conn = _psycopg2_connect(sb_conn_str, connect_timeout=5)
with conn.cursor() as cur:
cur.execute("SELECT id, email, full_name, role, created_at FROM users ORDER BY created_at")
cols = [d[0] for d in cur.description]
rows = [dict(zip(cols, row)) for row in cur.fetchall()]
conn.close()
if rows:
return rows
except Exception:
pass
if turso_key:
try:
_tu, _tt = turso_key.split("|", 1)
rows = _turso_execute_direct(_tu, _tt,
"SELECT id, email, full_name, role, created_at FROM users ORDER BY created_at")
if rows:
return rows
except Exception:
pass
try:
conn = _get_sqlite_conn()
df = _sqlite_read_sql(conn, "SELECT id, email, full_name, role, created_at FROM users ORDER BY created_at")
conn.close()
return df.to_dict("records")
except Exception:
return []
def get_users_from_db(cfg: dict) -> pd.DataFrame:
"""Load users table from Supabase (preferred), Turso, or SQLite fallback. Result is cached 30s."""
sb_cs = _get_effective_supabase_conn_str(cfg) or ""
rows = _fetch_users_cached(sb_cs, _turso_cache_key(cfg))
return pd.DataFrame(rows) if rows else pd.DataFrame()
@st.cache_data(ttl=30, show_spinner=False)
def _fetch_roles_cached(sb_conn_str: str, turso_key: str = "") -> list:
"""Cached fetch of roles — takes hashable conn string, returns list of row dicts."""
if sb_conn_str:
try:
conn = _psycopg2_connect(sb_conn_str, connect_timeout=5)
with conn.cursor() as cur:
cur.execute("SELECT role_name, pages FROM roles ORDER BY role_name")
cols = [d[0] for d in cur.description]
rows = [dict(zip(cols, row)) for row in cur.fetchall()]
conn.close()
if rows:
return rows
except Exception:
pass
if turso_key:
try:
_tu, _tt = turso_key.split("|", 1)
rows = _turso_execute_direct(_tu, _tt,
"SELECT role_name, pages FROM roles ORDER BY role_name")
if rows:
return rows
except Exception:
pass
try:
conn = _get_sqlite_conn()
df = _sqlite_read_sql(conn, "SELECT role_name, pages FROM roles ORDER BY role_name")
conn.close()
return df.to_dict("records")
except Exception:
return []
def get_roles_from_db(cfg: dict) -> pd.DataFrame:
"""Load roles table from Supabase (preferred), Turso, or SQLite fallback. Result is cached 30s."""
sb_cs = _get_effective_supabase_conn_str(cfg) or ""
rows = _fetch_roles_cached(sb_cs, _turso_cache_key(cfg))
return pd.DataFrame(rows) if rows else pd.DataFrame()
def get_pages_for_role(role_name: str, cfg: dict) -> list:
"""Return list of page names for a given role. Falls back to _ROLE_PAGES dict."""
roles_df = get_roles_from_db(cfg)
if not roles_df.empty and role_name in roles_df["role_name"].values:
row = roles_df[roles_df["role_name"] == role_name].iloc[0]
return [p.strip() for p in str(row.get("pages", "")).split(",") if p.strip()]
return list(_ROLE_PAGES.get(role_name, _ROLE_PAGES["admin"]))
def create_role_all_dbs(role_name: str, pages: list, cfg: dict) -> tuple[bool, str]:
"""Create or update a role in SQLite, Supabase, and Turso."""
pages_str = ",".join(pages)
results = []
try:
conn = _get_sqlite_conn()
conn.execute(
"INSERT INTO roles (role_name, pages) VALUES (?, ?) "
"ON CONFLICT(role_name) DO UPDATE SET pages=excluded.pages",
(role_name.lower().strip(), pages_str)
)
conn.commit()
conn.close()
results.append("SQLite")
except Exception as exc:
results.append(f"SQLite failed: {exc}")
conn_sb = _get_supabase_conn(cfg)
if conn_sb is not None:
try:
with conn_sb:
with conn_sb.cursor() as cur:
cur.execute(
"INSERT INTO roles (role_name, pages) VALUES (%s, %s) "
"ON CONFLICT (role_name) DO UPDATE SET pages=EXCLUDED.pages",
(role_name.lower().strip(), pages_str)
)
conn_sb.close()
results.append("Supabase")
except Exception as exc:
results.append(f"Supabase failed: {exc}")
if _has_turso(cfg):
try:
_turso_execute(cfg,
"INSERT INTO roles (role_name, pages) VALUES (?, ?) "
"ON CONFLICT(role_name) DO UPDATE SET pages=excluded.pages",
(role_name.lower().strip(), pages_str))
results.append("Turso")
except Exception as exc:
results.append(f"Turso failed: {exc}")
return any("failed" not in r for r in results), " · ".join(results)
def delete_role_all_dbs(role_name: str, cfg: dict) -> tuple[bool, str]:
"""Delete a role from SQLite, Supabase, and Turso. Refuses to delete built-in roles."""
if role_name in ("admin", "staff", "viewer"):
return False, "Cannot delete built-in roles."
results = []
try:
conn = _get_sqlite_conn()
conn.execute("DELETE FROM roles WHERE role_name=?", (role_name,))
conn.commit()
conn.close()
results.append("SQLite")
except Exception as exc:
results.append(f"SQLite failed: {exc}")
conn_sb = _get_supabase_conn(cfg)
if conn_sb is not None:
try:
with conn_sb:
with conn_sb.cursor() as cur:
cur.execute("DELETE FROM roles WHERE role_name=%s", (role_name,))
conn_sb.close()
results.append("Supabase")
except Exception as exc:
results.append(f"Supabase failed: {exc}")
if _has_turso(cfg):
try:
_turso_execute(cfg, "DELETE FROM roles WHERE role_name=?", (role_name,))
results.append("Turso")
except Exception as exc:
results.append(f"Turso failed: {exc}")
return any("failed" not in r for r in results), " · ".join(results)
def sync_local_to_supabase(cfg: dict) -> tuple[int, int, list]:
"""Sync all local SQLite users and roles to Supabase. Returns (users_synced, roles_synced, errors)."""
errors = []
users_synced = 0
roles_synced = 0
conn_sb = _get_supabase_conn(cfg)
if conn_sb is None:
return 0, 0, ["Supabase not connected"]
try:
# Sync roles
local_conn = _get_sqlite_conn()
local_roles = local_conn.execute("SELECT role_name, pages FROM roles").fetchall()
with conn_sb:
with conn_sb.cursor() as cur:
for row in local_roles:
try:
cur.execute(
"INSERT INTO roles (role_name, pages) VALUES (%s, %s) "
"ON CONFLICT (role_name) DO UPDATE SET pages=EXCLUDED.pages",
(row["role_name"], row["pages"])
)
roles_synced += 1
except Exception as e:
errors.append(f"Role {row['role_name']}: {e}")
# Sync users
local_users = local_conn.execute("SELECT email, full_name, role, password_hash FROM users").fetchall()
with conn_sb:
with conn_sb.cursor() as cur:
for row in local_users:
try:
cur.execute(
"INSERT INTO users (email, full_name, role, password_hash) VALUES (%s, %s, %s, %s) "
"ON CONFLICT (email) DO UPDATE SET full_name=EXCLUDED.full_name, role=EXCLUDED.role",
(row["email"], row["full_name"], row["role"], row["password_hash"])
)
users_synced += 1
except Exception as e:
errors.append(f"User {row['email']}: {e}")
local_conn.close()
conn_sb.close()
except Exception as e:
errors.append(str(e))
return users_synced, roles_synced, errors
def create_user_all_dbs(email: str, full_name: str, role: str, password: str, cfg: dict) -> tuple[bool, str]:
"""Create a new user in SQLite, Supabase, and Turso."""
pw_hash = _hash_password(password)
results = []
# SQLite
try:
conn = _get_sqlite_conn()
conn.execute(
"INSERT INTO users (email, full_name, role, password_hash) VALUES (?, ?, ?, ?)",
(email.lower().strip(), full_name.strip(), role, pw_hash)
)
conn.commit()
conn.close()
results.append("SQLite")
except Exception as exc:
results.append(f"SQLite failed: {exc}")
# Supabase
conn_sb = _get_supabase_conn(cfg)
if conn_sb is not None:
try:
with conn_sb:
with conn_sb.cursor() as cur:
cur.execute(
"INSERT INTO users (email, full_name, role, password_hash) VALUES (%s, %s, %s, %s)",
(email.lower().strip(), full_name.strip(), role, pw_hash)
)
conn_sb.close()
results.append("Supabase")
except Exception as exc:
results.append(f"Supabase failed: {exc}")
# Turso
if _has_turso(cfg):
try:
_turso_execute(cfg,
"INSERT INTO users (email, full_name, role, password_hash) VALUES (?,?,?,?)",
(email.lower().strip(), full_name.strip(), role, pw_hash))
results.append("Turso")
except Exception as exc:
results.append(f"Turso failed: {exc}")
return any("failed" not in r for r in results), " · ".join(results)
def delete_user_all_dbs(email: str, cfg: dict) -> tuple[bool, str]:
"""Delete a user by email from SQLite, Supabase, and Turso."""
results = []
try:
conn = _get_sqlite_conn()
conn.execute("DELETE FROM users WHERE email=?", (email.lower().strip(),))
conn.commit()
conn.close()
results.append("SQLite")
except Exception as exc:
results.append(f"SQLite failed: {exc}")
conn_sb = _get_supabase_conn(cfg)
if conn_sb is not None:
try:
with conn_sb:
with conn_sb.cursor() as cur:
cur.execute("DELETE FROM users WHERE email=%s", (email.lower().strip(),))
conn_sb.close()
results.append("Supabase")
except Exception as exc:
results.append(f"Supabase failed: {exc}")
if _has_turso(cfg):
try:
_turso_execute(cfg, "DELETE FROM users WHERE email=?", (email.lower().strip(),))
results.append("Turso")
except Exception as exc:
results.append(f"Turso failed: {exc}")
return any("failed" not in r for r in results), " · ".join(results)
def create_user_with_invite(email: str, full_name: str, role: str, cfg: dict) -> tuple[bool, str, str]:
"""Create a user without a password via invite link. Returns (ok, message, invite_token)."""
token = hashlib.sha256(
f"{email}{time.time()}{_os.urandom(16).hex()}".encode()
).hexdigest()[:48]
placeholder_hash = f"INVITE_PENDING:{token}"
results = []
try:
conn = _get_sqlite_conn()
conn.execute(
"INSERT INTO users (email, full_name, role, password_hash, invite_token) VALUES (?, ?, ?, ?, ?)",
(email.lower().strip(), full_name.strip(), role, placeholder_hash, token)
)
conn.commit()
conn.close()
results.append("SQLite")
except Exception as exc:
results.append(f"SQLite failed: {exc}")
conn_sb = _get_supabase_conn(cfg)
if conn_sb is not None:
try:
with conn_sb:
with conn_sb.cursor() as cur:
cur.execute(
"INSERT INTO users (email, full_name, role, password_hash, invite_token) VALUES (%s, %s, %s, %s, %s)",
(email.lower().strip(), full_name.strip(), role, placeholder_hash, token)
)
conn_sb.close()
results.append("Supabase")
except Exception as exc:
results.append(f"Supabase failed: {exc}")
if _has_turso(cfg):
try:
_turso_execute(cfg,
"INSERT INTO users (email, full_name, role, password_hash, invite_token) VALUES (?,?,?,?,?)",
(email.lower().strip(), full_name.strip(), role, placeholder_hash, token))
results.append("Turso")
except Exception as exc:
results.append(f"Turso failed: {exc}")
ok = any("failed" not in r for r in results)
return ok, " · ".join(results), token if ok else ""
def validate_invite_token(token: str, cfg: dict) -> dict | None:
"""Return user info dict if invite token is valid and unused, else None."""
if not token:
return None
_sb_cs = _get_effective_supabase_conn_str(cfg)
if _sb_cs:
try:
conn = _psycopg2_connect(_sb_cs)
with conn.cursor() as cur:
cur.execute(
"SELECT email, full_name, role FROM users WHERE invite_token=%s", (token,)
)
row = cur.fetchone()
conn.close()
if row:
return {"email": row[0], "full_name": row[1], "role": row[2]}
except Exception:
pass
if _has_turso(cfg):
try:
rows = _turso_execute(cfg,
"SELECT email, full_name, role FROM users WHERE invite_token=?", (token,))
if rows:
return {"email": rows[0]["email"], "full_name": rows[0]["full_name"], "role": rows[0]["role"]}
except Exception:
pass
try:
conn = _get_sqlite_conn()
row = conn.execute(
"SELECT email, full_name, role FROM users WHERE invite_token=?", (token,)
).fetchone()
conn.close()
if row:
return {"email": row["email"], "full_name": row["full_name"], "role": row["role"]}
except Exception:
pass
return None
def complete_invite(token: str, new_password: str, cfg: dict) -> tuple[bool, str]:
"""Set password and clear invite token, completing the new-user onboarding."""
pw_hash = _hash_password(new_password)
results = []
try:
conn = _get_sqlite_conn()
conn.execute(
"UPDATE users SET password_hash=?, invite_token=NULL WHERE invite_token=?",
(pw_hash, token)
)
conn.commit()
conn.close()
results.append("SQLite")
except Exception as exc:
results.append(f"SQLite failed: {exc}")
conn_sb = _get_supabase_conn(cfg)
if conn_sb is not None:
try:
with conn_sb:
with conn_sb.cursor() as cur:
cur.execute(
"UPDATE users SET password_hash=%s, invite_token=NULL WHERE invite_token=%s",
(pw_hash, token)
)
conn_sb.close()
results.append("Supabase")
except Exception as exc:
results.append(f"Supabase failed: {exc}")
if _has_turso(cfg):
try:
_turso_execute(cfg,
"UPDATE users SET password_hash=?, invite_token=NULL WHERE invite_token=?",
(pw_hash, token))
results.append("Turso")
except Exception as exc:
results.append(f"Turso failed: {exc}")
return any("failed" not in r for r in results), " · ".join(results)
def generate_new_invite_token(email: str, cfg: dict) -> tuple[bool, str]:
"""Regenerate an invite token for an existing user. Returns (ok, token)."""
token = hashlib.sha256(
f"{email}{time.time()}{_os.urandom(16).hex()}".encode()
).hexdigest()[:48]
results = []
try:
conn = _get_sqlite_conn()
conn.execute("UPDATE users SET invite_token=? WHERE email=?", (token, email.lower().strip()))
conn.commit()
conn.close()
results.append("SQLite")
except Exception as exc:
results.append(f"SQLite failed: {exc}")
conn_sb = _get_supabase_conn(cfg)
if conn_sb is not None:
try:
with conn_sb:
with conn_sb.cursor() as cur:
cur.execute(
"UPDATE users SET invite_token=%s WHERE email=%s", (token, email.lower().strip())
)
conn_sb.close()
results.append("Supabase")
except Exception as exc:
results.append(f"Supabase failed: {exc}")
if _has_turso(cfg):
try:
_turso_execute(cfg,
"UPDATE users SET invite_token=? WHERE email=?", (token, email.lower().strip()))
results.append("Turso")
except Exception as exc:
results.append(f"Turso failed: {exc}")
ok = any("failed" not in r for r in results)
return ok, token if ok else ""
def update_user_role_all_dbs(email: str, new_role: str, cfg: dict) -> tuple[bool, str]:
"""Update a user's role in SQLite, Supabase, and Turso."""
results = []
try:
conn = _get_sqlite_conn()
conn.execute("UPDATE users SET role=? WHERE email=?", (new_role, email.lower().strip()))
conn.commit()
conn.close()
results.append("SQLite")
except Exception as exc:
results.append(f"SQLite failed: {exc}")
conn_sb = _get_supabase_conn(cfg)
if conn_sb is not None:
try:
with conn_sb:
with conn_sb.cursor() as cur:
cur.execute("UPDATE users SET role=%s WHERE email=%s", (new_role, email.lower().strip()))
conn_sb.close()
results.append("Supabase")
except Exception as exc:
results.append(f"Supabase failed: {exc}")
if _has_turso(cfg):
try:
_turso_execute(cfg, "UPDATE users SET role=? WHERE email=?", (new_role, email.lower().strip()))
results.append("Turso")
except Exception as exc:
results.append(f"Turso failed: {exc}")
return any("failed" not in r for r in results), " · ".join(results)
def authenticate_user(email: str, password: str, cfg: dict) -> dict | None:
"""Return user dict {email, full_name, role, pages} if credentials valid, else None."""
_em = email.lower().strip()
user = None
# Try Supabase first
_sb_cs = _get_effective_supabase_conn_str(cfg)
if _sb_cs:
try:
conn = _psycopg2_connect(_sb_cs)
with conn.cursor() as cur:
cur.execute("SELECT email, full_name, role, password_hash FROM users WHERE email=%s", (_em,))
row = cur.fetchone()
conn.close()
if row and _verify_password(row[3], password):
user = {"email": row[0], "full_name": row[1], "role": row[2]}
except Exception:
pass
# Try Turso
if user is None and _has_turso(cfg):
try:
rows = _turso_execute(cfg,
"SELECT email, full_name, role, password_hash FROM users WHERE email=?", (_em,))
if rows and _verify_password(rows[0]["password_hash"] or "", password):
user = {"email": rows[0]["email"], "full_name": rows[0]["full_name"], "role": rows[0]["role"]}
except Exception:
pass
# Fall back to SQLite
if user is None:
try:
conn = _get_sqlite_conn()
row = conn.execute(
"SELECT email, full_name, role, password_hash FROM users WHERE email=?", (_em,)
).fetchone()
conn.close()
if row and _verify_password(row["password_hash"], password):
user = {"email": row["email"], "full_name": row["full_name"], "role": row["role"]}
except Exception:
pass
if user is None:
return None
# Load this role's page permissions from DB
user["pages"] = get_pages_for_role(user["role"], cfg)
return user
def save_email_template(key: str, html: str, cfg: dict) -> bool:
"""Save an email template to SQLite, Supabase, and Turso."""
try:
conn = _get_sqlite_conn()
conn.execute("""
INSERT INTO email_templates (template_key, html_content)
VALUES (?, ?)
ON CONFLICT(template_key) DO UPDATE SET
html_content=excluded.html_content,
updated_at=datetime('now')
""", (key, html))
conn.commit()
conn.close()
except Exception: pass
conn_sb = _get_supabase_conn(cfg)
if conn_sb is not None:
try:
with conn_sb:
with conn_sb.cursor() as cur:
cur.execute("""
INSERT INTO email_templates (template_key, html_content)
VALUES (%s, %s)
ON CONFLICT(template_key) DO UPDATE SET
html_content=EXCLUDED.html_content,
updated_at=NOW()
""", (key, html))
conn_sb.close()
except Exception: pass
if _has_turso(cfg):
try:
_turso_execute(cfg,
"INSERT INTO email_templates (template_key, html_content) VALUES (?,?) "
"ON CONFLICT(template_key) DO UPDATE SET html_content=excluded.html_content, "
"updated_at=datetime('now')",
(key, html))
except Exception: pass
return True
def load_email_template(key: str, cfg: dict) -> str:
"""Load an email template by key. Returns '' if not found."""
# Try Supabase first
conn_sb = _get_supabase_conn(cfg)
if conn_sb is not None:
try:
with conn_sb.cursor() as cur:
cur.execute("SELECT html_content FROM email_templates WHERE template_key=%s", (key,))
row = cur.fetchone()
conn_sb.close()
if row and row[0]:
return row[0]
except Exception: pass
# Try Turso
if _has_turso(cfg):
try:
rows = _turso_execute(cfg,
"SELECT html_content FROM email_templates WHERE template_key=?", (key,))
if rows and rows[0].get("html_content"):
return rows[0]["html_content"]
except Exception: pass
# Fall back to SQLite
try:
conn = _get_sqlite_conn()
row = conn.execute("SELECT html_content FROM email_templates WHERE template_key=?", (key,)).fetchone()
conn.close()
if row and row[0]:
return row[0]
except Exception: pass
return ""
# ─────────────────────────────────────────────
# Config persistence
# ─────────────────────────────────────────────
CONFIG_FILE = Path(__file__).parent / "config.json"
# Default SQL run when a user clicks "Setup Tables".
# Shown in an editable text area so users can add their own tables/indexes.
SETUP_SQL = """\
-- ── Inventory table (stock tracking) ─────────────────────────────────────
CREATE TABLE IF NOT EXISTS inventory (
id BIGSERIAL PRIMARY KEY,
sku TEXT NOT NULL,
item_name TEXT NOT NULL,
category TEXT NOT NULL DEFAULT '',
price NUMERIC(10,2) NOT NULL DEFAULT 0.00,
stock_left INTEGER NOT NULL DEFAULT 0,
status TEXT NOT NULL DEFAULT 'In stock',
image_url TEXT NOT NULL DEFAULT 'N/A', -- one URL or comma-separated multiple: "url1,url2"
original_stock INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT inventory_sku_unique UNIQUE (sku)
);
-- Migrations for existing users (Original Stock)
DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='inventory' AND column_name='original_stock') THEN
ALTER TABLE inventory ADD COLUMN original_stock INTEGER NOT NULL DEFAULT 0;
END IF;
END $$;
-- ── Products table (catalog / storefront) ─────────────────────────────────
CREATE TABLE IF NOT EXISTS products (
id BIGSERIAL PRIMARY KEY,
sku TEXT NOT NULL,
name TEXT NOT NULL,
category TEXT NOT NULL DEFAULT '',
price NUMERIC(10,2) NOT NULL DEFAULT 0.00,
description TEXT NOT NULL DEFAULT '',
buy_button_url TEXT NOT NULL DEFAULT '',
image_url TEXT NOT NULL DEFAULT 'N/A', -- one URL or comma-separated multiple: "url1,url2"
active BOOLEAN NOT NULL DEFAULT TRUE, -- true = In Store, false = Out of Store
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT products_sku_unique UNIQUE (sku)
);
-- Migrations for existing users (buy_button_url)
DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='products' AND column_name='buy_button_url') THEN
ALTER TABLE products ADD COLUMN buy_button_url TEXT NOT NULL DEFAULT '';
END IF;
END $$;
-- ── Outbound logs (email history) ─────────────────────────────────────────
CREATE TABLE IF NOT EXISTS outbound_logs (
id BIGSERIAL PRIMARY KEY,
recipient_name TEXT NOT NULL,
recipient_email TEXT NOT NULL,
order_number TEXT NOT NULL,
products_list TEXT NOT NULL,
subtotal NUMERIC(10,2) NOT NULL DEFAULT 0.00,
tax NUMERIC(10,2) NOT NULL DEFAULT 0.00,
shipping NUMERIC(10,2) NOT NULL DEFAULT 0.00,
total_cost NUMERIC(10,2) NOT NULL DEFAULT 0.00,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
-- Migrations for existing users
DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='outbound_logs' AND column_name='subtotal') THEN
ALTER TABLE outbound_logs ADD COLUMN subtotal NUMERIC(10,2) NOT NULL DEFAULT 0.00;
ALTER TABLE outbound_logs ADD COLUMN tax NUMERIC(10,2) NOT NULL DEFAULT 0.00;
ALTER TABLE outbound_logs ADD COLUMN shipping NUMERIC(10,2) NOT NULL DEFAULT 0.00;
END IF;
END $$;
-- ── Email templates (custom HTML templates) ──────────────────────────────
CREATE TABLE IF NOT EXISTS email_templates (
id BIGSERIAL PRIMARY KEY,
template_key TEXT NOT NULL UNIQUE, -- 'order_template' | 'campaign_template'
html_content TEXT NOT NULL DEFAULT '',
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);