-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
1828 lines (1612 loc) · 64.4 KB
/
database.py
File metadata and controls
1828 lines (1612 loc) · 64.4 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
import datetime
import json
import uuid
from typing import Optional, List
from sqlalchemy import create_engine, Column, Integer, String, Text, DateTime, Float, UniqueConstraint, and_, or_ as db_or
from sqlalchemy.orm import declarative_base, sessionmaker
from config import DATABASE_URL
connect_args = {"check_same_thread": False} if DATABASE_URL.startswith("sqlite") else {}
engine_kwargs = {"connect_args": connect_args}
if not DATABASE_URL.startswith("sqlite"):
engine_kwargs["pool_pre_ping"] = True
engine = create_engine(DATABASE_URL, **engine_kwargs)
SessionLocal = sessionmaker(bind=engine)
Base = declarative_base()
class TickerAnalysis(Base):
__tablename__ = "ticker_analyses"
id = Column(Integer, primary_key=True, index=True)
ticker = Column(String(20), index=True, nullable=False)
company_name = Column(String(200), default="")
current_price = Column(Float, nullable=True)
recommendation = Column(String(200), default="") # e.g. "BUY at $298.50 (stop $280.00)"
confidence = Column(String(20), default="") # HIGH, MEDIUM, LOW
short_summary = Column(Text, default="")
full_analysis = Column(Text, default="")
news_data = Column(Text, default="") # JSON string of news articles used
stock_data = Column(Text, default="") # JSON string of stock metrics
analysis_json = Column(Text, default="") # Full AI analysis JSON (all fields)
source = Column(String(50), default="web") # web, telegram
telegram_user = Column(String(200), default="")
telegram_user_id = Column(String(50), default="") # Telegram numeric user ID
user_ip = Column(String(100), default="") # Client IP address
web_user = Column(String(100), default="") # Logged-in web username who requested
share_token = Column(String(32), unique=True, index=True) # Public share link token
created_at = Column(DateTime, default=datetime.datetime.utcnow)
class BlockedUser(Base):
__tablename__ = "blocked_users"
id = Column(Integer, primary_key=True, index=True)
telegram_user_id = Column(String(50), unique=True, index=True, nullable=False)
telegram_username = Column(String(200), default="")
reason = Column(Text, default="")
blocked_at = Column(DateTime, default=datetime.datetime.utcnow)
_RESERVED_CODES = {"1337", "5555"}
def _generate_user_code():
"""Generate a unique random 4-digit user code, avoiding reserved codes."""
import random
code = str(random.randint(1000, 9999))
while code in _RESERVED_CODES:
code = str(random.randint(1000, 9999))
return code
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
username = Column(String(100), unique=True, index=True, nullable=False)
password_hash = Column(String(200), nullable=False)
role = Column(String(20), default="viewer") # "admin" or "viewer"
user_code = Column(String(4), unique=True, index=True)
display_name = Column(String(100), nullable=True)
created_at = Column(DateTime, default=datetime.datetime.utcnow)
class WatchlistItem(Base):
__tablename__ = "watchlist"
id = Column(Integer, primary_key=True, index=True)
ticker = Column(String(20), unique=True, index=True, nullable=False)
added_at = Column(DateTime, default=datetime.datetime.utcnow)
notes = Column(Text, default="")
class PortfolioItem(Base):
__tablename__ = "portfolio_items"
__table_args__ = (UniqueConstraint("user_id", "ticker", name="uq_user_ticker"),)
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, index=True, nullable=False)
ticker = Column(String(20), nullable=False)
company_name = Column(String(200), default="")
shares = Column(Float, nullable=False)
purchase_price = Column(Float, nullable=False)
purchase_date = Column(String(20), default="")
stop_loss = Column(Float, nullable=True)
notes = Column(Text, default="")
sort_order = Column(Integer, default=0)
added_at = Column(DateTime, default=datetime.datetime.utcnow)
class PortfolioTransaction(Base):
__tablename__ = "portfolio_transactions"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, index=True, nullable=False)
portfolio_item_id = Column(Integer, index=True, nullable=True)
ticker = Column(String(20), index=True, nullable=False)
action = Column(String(10), nullable=False) # BUY or SELL
shares = Column(Float, nullable=False)
price = Column(Float, nullable=False)
total_amount = Column(Float, nullable=False)
avg_cost_at_time = Column(Float, nullable=True)
realized_pnl = Column(Float, nullable=True)
notes = Column(Text, default="")
created_at = Column(DateTime, default=datetime.datetime.utcnow)
class UserSettings(Base):
__tablename__ = "user_settings"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, unique=True, index=True, nullable=False)
settings_json = Column(Text, default="{}")
updated_at = Column(DateTime, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow)
class Friendship(Base):
__tablename__ = "friendships"
__table_args__ = (UniqueConstraint("user_id", "friend_id", name="uq_friendship"),)
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, index=True, nullable=False) # requester
friend_id = Column(Integer, index=True, nullable=False) # recipient
status = Column(String(20), default="pending") # pending / accepted / declined
created_at = Column(DateTime, default=datetime.datetime.utcnow)
updated_at = Column(DateTime, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow)
class Message(Base):
__tablename__ = "messages"
id = Column(Integer, primary_key=True, index=True)
sender_id = Column(Integer, index=True, nullable=False)
receiver_id = Column(Integer, index=True, nullable=False)
content = Column(Text, nullable=False)
is_read = Column(Integer, default=0)
created_at = Column(DateTime, default=datetime.datetime.utcnow)
class Tip(Base):
__tablename__ = "tips"
id = Column(Integer, primary_key=True, index=True)
sender_id = Column(Integer, index=True, nullable=False)
receiver_id = Column(Integer, index=True, nullable=False)
ticker = Column(String(20), nullable=False)
breakout_price = Column(Float, nullable=True)
stop_loss = Column(Float, nullable=True)
message = Column(Text, default="")
analysis_share_token = Column(String(32), nullable=True)
expires_at = Column(DateTime, nullable=True)
is_read = Column(Integer, default=0)
created_at = Column(DateTime, default=datetime.datetime.utcnow)
class Reaction(Base):
__tablename__ = "reactions"
__table_args__ = (
UniqueConstraint("user_id", "target_type", "target_id", "emoji", name="uq_reaction"),
)
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, index=True, nullable=False)
target_type = Column(String(20), nullable=False) # "message" or "tip"
target_id = Column(Integer, nullable=False)
emoji = Column(String(30), nullable=False)
created_at = Column(DateTime, default=datetime.datetime.utcnow)
class Notification(Base):
__tablename__ = "notifications"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, index=True, nullable=False)
type = Column(String(30), nullable=False) # friend_request / friend_accepted / message / tip
title = Column(String(200), default="")
body = Column(Text, default="")
reference_id = Column(Integer, nullable=True)
is_read = Column(Integer, default=0)
created_at = Column(DateTime, default=datetime.datetime.utcnow)
def init_db():
Base.metadata.create_all(bind=engine)
# Migrate: add new columns to existing tables (safe for SQLite)
_migrate_add_columns()
# Seed the admin user if no users exist
_seed_admin_user()
def _migrate_add_columns():
"""Add new columns to existing tables if they don't exist."""
from sqlalchemy import text
db = SessionLocal()
try:
migrations = [
("ticker_analyses", "telegram_user_id", "VARCHAR(50) DEFAULT ''"),
("ticker_analyses", "user_ip", "VARCHAR(100) DEFAULT ''"),
("ticker_analyses", "share_token", "VARCHAR(32)"),
("ticker_analyses", "web_user", "VARCHAR(100) DEFAULT ''"),
("portfolio_items", "sort_order", "INTEGER DEFAULT 0"),
("users", "user_code", "VARCHAR(5)"),
("tips", "expires_at", "TIMESTAMP"),
("users", "display_name", "VARCHAR(100)"),
]
for table, col, col_type in migrations:
try:
db.execute(text("ALTER TABLE {} ADD COLUMN {} {}".format(table, col, col_type)))
db.commit()
except Exception:
db.rollback() # Column already exists
# Widen recommendation column for longer values like "BUY at $298.50 (stop $280.00)"
try:
db.execute(text("ALTER TABLE ticker_analyses ALTER COLUMN recommendation TYPE VARCHAR(200)"))
db.commit()
except Exception:
db.rollback() # SQLite ignores column type changes; Postgres may already be correct
# Backfill share_token for existing rows that don't have one
try:
rows = db.execute(text("SELECT id FROM ticker_analyses WHERE share_token IS NULL")).fetchall()
for row in rows:
db.execute(text("UPDATE ticker_analyses SET share_token = :token WHERE id = :id"),
{"token": uuid.uuid4().hex, "id": row[0]})
if rows:
db.commit()
except Exception:
db.rollback()
# Ensure founding users have their assigned codes
try:
_hardcoded = {"sabotage": "1337", "adam": "5555"}
for uname, code in _hardcoded.items():
db.execute(text("UPDATE users SET user_code = :code WHERE LOWER(username) = :uname"),
{"code": code, "uname": uname})
db.commit()
except Exception:
db.rollback()
# Backfill display_name for founding users
try:
_display_names = {"sabotage": "Roy", "adam": "Adam"}
for uname, dname in _display_names.items():
db.execute(text("UPDATE users SET display_name = :dname WHERE LOWER(username) = :uname AND (display_name IS NULL OR display_name = '')"),
{"dname": dname, "uname": uname})
db.commit()
except Exception:
db.rollback()
# Backfill user_code for any users that don't have one
try:
rows = db.execute(text("SELECT id FROM users WHERE user_code IS NULL OR user_code = ''")).fetchall()
existing_codes = set()
if rows:
existing = db.execute(text("SELECT user_code FROM users WHERE user_code IS NOT NULL AND user_code != ''")).fetchall()
existing_codes = {r[0] for r in existing}
existing_codes.update(_RESERVED_CODES)
for row in rows:
code = _generate_user_code()
while code in existing_codes:
code = _generate_user_code()
existing_codes.add(code)
db.execute(text("UPDATE users SET user_code = :code WHERE id = :id"),
{"code": code, "id": row[0]})
if rows:
db.commit()
except Exception:
db.rollback()
finally:
db.close()
def _seed_admin_user():
"""Create the Sabotage admin user if no users exist yet."""
from config import AUTH_USERNAME, AUTH_PASSWORD_HASH
db = SessionLocal()
try:
if db.query(User).count() == 0 and AUTH_USERNAME and AUTH_PASSWORD_HASH:
admin = User(
username=AUTH_USERNAME,
password_hash=AUTH_PASSWORD_HASH,
role="admin",
)
db.add(admin)
db.commit()
except Exception:
db.rollback()
finally:
db.close()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
_ERROR_MARKERS = ["parsing failed", "error analyzing", "quota exhausted",
"an error occurred", "analysis failed"]
def _is_error_analysis(confidence: str, short_summary: str) -> bool:
"""Check if an analysis result is an error/failure."""
lower = short_summary.lower()
return confidence == "LOW" and any(m in lower for m in _ERROR_MARKERS)
def _delete_old_analyses(db, ticker: str, web_user: str = "", source: str = "web", telegram_user_id: str = "", hours: int = 24):
"""Clean up analyses for the same ticker+user from the past N hours.
Allows up to 2 analyses per ticker per user in the time window.
When there are already 2+, deletes older ones keeping only the most recent.
Analyses referenced by tips (via share_token) are always preserved.
"""
cutoff = datetime.datetime.utcnow() - datetime.timedelta(hours=hours)
query = db.query(TickerAnalysis).filter(
TickerAnalysis.ticker == ticker.upper(),
TickerAnalysis.created_at >= cutoff,
)
if source == "telegram" and telegram_user_id:
query = query.filter(TickerAnalysis.telegram_user_id == telegram_user_id)
elif web_user:
query = query.filter(TickerAnalysis.web_user == web_user)
existing = query.order_by(TickerAnalysis.created_at.desc()).all()
if len(existing) < 2:
return # Allow up to 2 analyses before cleanup
# Find share_tokens referenced by tips (must not delete those)
tip_tokens = set()
all_tokens = [a.share_token for a in existing if a.share_token]
if all_tokens:
linked = db.query(Tip.analysis_share_token).filter(
Tip.analysis_share_token.in_(all_tokens)
).all()
tip_tokens = {r[0] for r in linked}
# Keep the most recent, delete the rest (skip tip-linked ones)
for old in existing[1:]:
if old.share_token and old.share_token in tip_tokens:
continue
db.delete(old)
def save_analysis(
ticker: str,
company_name: str,
current_price: Optional[float],
recommendation: str,
confidence: str,
short_summary: str,
full_analysis: str,
news_data: str,
stock_data: str,
source: str = "web",
telegram_user: str = "",
telegram_user_id: str = "",
user_ip: str = "",
analysis_json: str = "",
web_user: str = "",
) -> TickerAnalysis:
db = SessionLocal()
try:
if not _is_error_analysis(confidence, short_summary):
_delete_old_analyses(db, ticker, web_user=web_user, source=source, telegram_user_id=telegram_user_id)
record = TickerAnalysis(
ticker=ticker.upper(),
company_name=company_name,
current_price=current_price,
recommendation=recommendation,
confidence=confidence,
short_summary=short_summary,
full_analysis=full_analysis,
news_data=news_data,
stock_data=stock_data,
analysis_json=analysis_json,
source=source,
telegram_user=telegram_user,
telegram_user_id=telegram_user_id,
user_ip=user_ip,
web_user=web_user,
share_token=uuid.uuid4().hex,
)
db.add(record)
db.commit()
db.refresh(record)
return record
finally:
db.close()
def get_history(days: int = 30, ticker: Optional[str] = None, web_user: Optional[str] = None) -> List[TickerAnalysis]:
"""Get analysis history for the last N days (default 30).
If web_user is provided, only return that user's analyses."""
db = SessionLocal()
try:
cutoff = datetime.datetime.utcnow() - datetime.timedelta(days=days)
query = (
db.query(TickerAnalysis)
.filter(TickerAnalysis.created_at >= cutoff)
.order_by(TickerAnalysis.created_at.desc())
)
if ticker:
query = query.filter(TickerAnalysis.ticker == ticker.upper())
if web_user:
query = query.filter(TickerAnalysis.web_user == web_user)
return query.all()
finally:
db.close()
def get_analysis_by_id(analysis_id: int) -> Optional[TickerAnalysis]:
db = SessionLocal()
try:
return db.query(TickerAnalysis).filter(TickerAnalysis.id == analysis_id).first()
finally:
db.close()
def get_analysis_by_share_token(token: str) -> Optional[TickerAnalysis]:
"""Look up an analysis by its public share token."""
db = SessionLocal()
try:
return db.query(TickerAnalysis).filter(TickerAnalysis.share_token == token).first()
finally:
db.close()
def get_recent_analysis(ticker: str, max_age_minutes: int = 60, web_user: Optional[str] = None) -> Optional[TickerAnalysis]:
"""Get the most recent analysis for a ticker if it's within max_age_minutes.
If web_user is provided, only return that user's analysis."""
db = SessionLocal()
try:
cutoff = datetime.datetime.utcnow() - datetime.timedelta(minutes=max_age_minutes)
query = (
db.query(TickerAnalysis)
.filter(TickerAnalysis.ticker == ticker.upper())
.filter(TickerAnalysis.created_at >= cutoff)
)
if web_user:
query = query.filter(TickerAnalysis.web_user == web_user)
return query.order_by(TickerAnalysis.created_at.desc()).first()
finally:
db.close()
def delete_analysis(analysis_id: int) -> bool:
"""Delete a single analysis record by ID. Returns True if deleted."""
db = SessionLocal()
try:
record = db.query(TickerAnalysis).filter(TickerAnalysis.id == analysis_id).first()
if not record:
return False
db.delete(record)
db.commit()
return True
finally:
db.close()
def delete_all_history(ticker: Optional[str] = None) -> int:
"""Delete all history (or filtered by ticker). Returns count deleted."""
db = SessionLocal()
try:
query = db.query(TickerAnalysis)
if ticker:
query = query.filter(TickerAnalysis.ticker == ticker.upper())
count = query.count()
query.delete(synchronize_session=False)
db.commit()
return count
finally:
db.close()
def get_unique_tickers(web_user: Optional[str] = None) -> List[str]:
db = SessionLocal()
try:
query = db.query(TickerAnalysis.ticker)
if web_user:
query = query.filter(TickerAnalysis.web_user == web_user)
results = query.distinct().all()
return [r[0] for r in results]
finally:
db.close()
# --- Blocked Users ---
def block_user(telegram_user_id: str, telegram_username: str = "", reason: str = "") -> BlockedUser:
"""Block a Telegram user by their numeric user ID."""
db = SessionLocal()
try:
existing = db.query(BlockedUser).filter(BlockedUser.telegram_user_id == telegram_user_id).first()
if existing:
return existing
record = BlockedUser(
telegram_user_id=telegram_user_id,
telegram_username=telegram_username,
reason=reason,
)
db.add(record)
db.commit()
db.refresh(record)
return record
finally:
db.close()
def unblock_user(telegram_user_id: str) -> bool:
"""Unblock a Telegram user. Returns True if a record was deleted."""
db = SessionLocal()
try:
record = db.query(BlockedUser).filter(BlockedUser.telegram_user_id == telegram_user_id).first()
if not record:
return False
db.delete(record)
db.commit()
return True
finally:
db.close()
def is_user_blocked(telegram_user_id: str) -> bool:
"""Check if a Telegram user is blocked."""
db = SessionLocal()
try:
return db.query(BlockedUser).filter(BlockedUser.telegram_user_id == telegram_user_id).first() is not None
finally:
db.close()
def get_blocked_users() -> List[BlockedUser]:
"""Get all blocked users."""
db = SessionLocal()
try:
return db.query(BlockedUser).order_by(BlockedUser.blocked_at.desc()).all()
finally:
db.close()
# --- User Management ---
def get_user_by_username(username: str) -> Optional[User]:
"""Look up a user by username (case-insensitive)."""
db = SessionLocal()
try:
return db.query(User).filter(User.username.ilike(username)).first()
finally:
db.close()
def get_all_users() -> List[User]:
"""Return all users ordered by creation date."""
db = SessionLocal()
try:
return db.query(User).order_by(User.created_at).all()
finally:
db.close()
def create_user(username: str, password_hash: str, role: str = "viewer", display_name: Optional[str] = None) -> User:
"""Create a new user. Raises ValueError if username already exists."""
db = SessionLocal()
try:
existing = db.query(User).filter(User.username.ilike(username)).first()
if existing:
raise ValueError("Username already exists")
# Generate unique 4-digit user code
existing_codes = {u.user_code for u in db.query(User).filter(User.user_code.isnot(None)).all()}
existing_codes.update(_RESERVED_CODES)
code = _generate_user_code()
while code in existing_codes:
code = _generate_user_code()
user = User(username=username, password_hash=password_hash, role=role, user_code=code, display_name=display_name)
db.add(user)
db.commit()
db.refresh(user)
return user
finally:
db.close()
def delete_user(user_id: int) -> bool:
"""Delete a user by ID. Returns True if deleted."""
db = SessionLocal()
try:
user = db.query(User).filter(User.id == user_id).first()
if not user:
return False
db.delete(user)
db.commit()
return True
finally:
db.close()
def update_user_password(user_id: int, new_password_hash: str) -> bool:
"""Update a user's password hash. Returns True if updated."""
db = SessionLocal()
try:
user = db.query(User).filter(User.id == user_id).first()
if not user:
return False
user.password_hash = new_password_hash
db.commit()
return True
finally:
db.close()
def update_user_display_name(user_id: int, display_name: Optional[str]) -> bool:
"""Update a user's display name. Returns True if updated."""
db = SessionLocal()
try:
user = db.query(User).filter(User.id == user_id).first()
if not user:
return False
user.display_name = display_name
db.commit()
return True
finally:
db.close()
# --- Portfolio ---
def get_user_portfolio(user_id: int) -> List[PortfolioItem]:
"""Return all portfolio items for a user, ordered by sort_order then newest."""
db = SessionLocal()
try:
return (
db.query(PortfolioItem)
.filter(PortfolioItem.user_id == user_id)
.order_by(PortfolioItem.sort_order.asc(), PortfolioItem.added_at.desc())
.all()
)
finally:
db.close()
def add_portfolio_item(
user_id: int,
ticker: str,
shares: float,
purchase_price: float,
company_name: str = "",
stop_loss: Optional[float] = None,
notes: str = "",
) -> PortfolioItem:
"""Add a stock to the user's portfolio. Raises ValueError if duplicate."""
db = SessionLocal()
try:
existing = (
db.query(PortfolioItem)
.filter(PortfolioItem.user_id == user_id, PortfolioItem.ticker == ticker.upper())
.first()
)
if existing:
raise ValueError("Ticker {} is already in your portfolio".format(ticker.upper()))
max_order = db.query(PortfolioItem).filter(PortfolioItem.user_id == user_id).count()
item = PortfolioItem(
user_id=user_id,
ticker=ticker.upper(),
company_name=company_name,
shares=shares,
purchase_price=purchase_price,
stop_loss=stop_loss,
notes=notes,
sort_order=max_order,
)
db.add(item)
db.commit()
db.refresh(item)
return item
finally:
db.close()
def update_portfolio_item(
item_id: int,
user_id: int,
shares: Optional[float] = None,
purchase_price: Optional[float] = None,
stop_loss: Optional[float] = None,
notes: Optional[str] = None,
) -> Optional[PortfolioItem]:
"""Partial update of a portfolio item. Returns updated item or None."""
db = SessionLocal()
try:
item = (
db.query(PortfolioItem)
.filter(PortfolioItem.id == item_id, PortfolioItem.user_id == user_id)
.first()
)
if not item:
return None
if shares is not None:
item.shares = shares
if purchase_price is not None:
item.purchase_price = purchase_price
if stop_loss is not None:
item.stop_loss = stop_loss
if notes is not None:
item.notes = notes
db.commit()
db.refresh(item)
return item
finally:
db.close()
def delete_portfolio_item(item_id: int, user_id: int) -> bool:
"""Remove a stock from portfolio. Returns True if deleted."""
db = SessionLocal()
try:
item = (
db.query(PortfolioItem)
.filter(PortfolioItem.id == item_id, PortfolioItem.user_id == user_id)
.first()
)
if not item:
return False
db.delete(item)
db.commit()
return True
finally:
db.close()
# --- Portfolio Transactions (Buy More / Sell) ---
def buy_more_shares(item_id: int, user_id: int, new_shares: float, new_price: float, notes: str = "") -> Optional[PortfolioItem]:
"""Buy more shares of an existing position. Recalculates weighted average cost."""
db = SessionLocal()
try:
item = (
db.query(PortfolioItem)
.filter(PortfolioItem.id == item_id, PortfolioItem.user_id == user_id)
.first()
)
if not item:
return None
old_shares = item.shares
old_avg = item.purchase_price
total_shares = old_shares + new_shares
new_avg = (old_shares * old_avg + new_shares * new_price) / total_shares
item.shares = total_shares
item.purchase_price = round(new_avg, 4)
# Log transaction
txn = PortfolioTransaction(
user_id=user_id,
portfolio_item_id=item.id,
ticker=item.ticker,
action="BUY",
shares=new_shares,
price=new_price,
total_amount=round(new_shares * new_price, 2),
avg_cost_at_time=round(new_avg, 4),
notes=notes,
)
db.add(txn)
db.commit()
db.refresh(item)
return item
finally:
db.close()
def sell_shares(item_id: int, user_id: int, sell_shares_count: float, sell_price: float, notes: str = "") -> dict:
"""Sell shares from a position. Returns dict with updated item (or None if fully sold) and realized P&L."""
db = SessionLocal()
try:
item = (
db.query(PortfolioItem)
.filter(PortfolioItem.id == item_id, PortfolioItem.user_id == user_id)
.first()
)
if not item:
return {"error": "not_found"}
if sell_shares_count > item.shares:
return {"error": "insufficient_shares", "available": item.shares}
avg_cost = item.purchase_price
realized_pnl = round((sell_price - avg_cost) * sell_shares_count, 2)
remaining = round(item.shares - sell_shares_count, 6)
# Log transaction
txn = PortfolioTransaction(
user_id=user_id,
portfolio_item_id=item.id,
ticker=item.ticker,
action="SELL",
shares=sell_shares_count,
price=sell_price,
total_amount=round(sell_shares_count * sell_price, 2),
avg_cost_at_time=avg_cost,
realized_pnl=realized_pnl,
notes=notes,
)
db.add(txn)
if remaining <= 0:
db.delete(item)
db.commit()
return {"item": None, "realized_pnl": realized_pnl, "fully_sold": True, "ticker": item.ticker}
else:
item.shares = remaining
db.commit()
db.refresh(item)
return {"item": item, "realized_pnl": realized_pnl, "fully_sold": False, "ticker": item.ticker}
finally:
db.close()
def get_portfolio_transactions(user_id: int, portfolio_item_id: Optional[int] = None, ticker: Optional[str] = None) -> List[PortfolioTransaction]:
"""Get transaction history for a user, optionally filtered by item or ticker."""
db = SessionLocal()
try:
query = (
db.query(PortfolioTransaction)
.filter(PortfolioTransaction.user_id == user_id)
)
if portfolio_item_id is not None:
query = query.filter(PortfolioTransaction.portfolio_item_id == portfolio_item_id)
if ticker:
query = query.filter(PortfolioTransaction.ticker == ticker.upper())
return query.order_by(PortfolioTransaction.created_at.desc()).all()
finally:
db.close()
def get_realized_pnl_total(user_id: int) -> float:
"""Sum all realized P&L for a user."""
db = SessionLocal()
try:
from sqlalchemy import func
result = (
db.query(func.coalesce(func.sum(PortfolioTransaction.realized_pnl), 0.0))
.filter(PortfolioTransaction.user_id == user_id, PortfolioTransaction.action == "SELL")
.scalar()
)
return round(float(result), 2)
finally:
db.close()
# --- User Settings ---
DEFAULT_SETTINGS = {
"visible_columns": {
"ticker": True, "shares": True, "avg_cost": True, "price": True,
"mkt_value": True, "pct_port": True, "pnl": True, "pnl_pct": True,
"day_pnl": True, "day_pct": True, "signals": True, "actions": True,
},
"visible_cards": {
"total_value": True, "total_cost": True, "total_pnl": True,
"total_return": True, "day_pnl": True, "realized_pnl": True,
},
"show_pie_chart": True,
"column_order": [
"ticker", "shares", "avg_cost", "price", "mkt_value", "pct_port",
"pnl", "pnl_pct", "day_pnl", "day_pnl_pct", "day_pct", "signals", "actions",
],
}
def get_user_settings(user_id: int) -> dict:
"""Return user settings merged with defaults."""
db = SessionLocal()
try:
record = db.query(UserSettings).filter(UserSettings.user_id == user_id).first()
result = json.loads(json.dumps(DEFAULT_SETTINGS)) # deep copy defaults
if record and record.settings_json:
stored = json.loads(record.settings_json)
# Merge stored into defaults
for key in ("visible_columns", "visible_cards"):
if key in stored and isinstance(stored[key], dict):
result[key].update(stored[key])
if "show_pie_chart" in stored:
result["show_pie_chart"] = stored["show_pie_chart"]
if "column_order" in stored and isinstance(stored["column_order"], list):
# Use stored order but ensure all default columns are present
default_cols = result["column_order"]
stored_order = [c for c in stored["column_order"] if c in default_cols]
# Append any new columns not in stored order
for c in default_cols:
if c not in stored_order:
stored_order.append(c)
result["column_order"] = stored_order
return result
finally:
db.close()
def save_user_settings(user_id: int, settings: dict) -> dict:
"""Upsert user settings. Returns the saved settings."""
db = SessionLocal()
try:
record = db.query(UserSettings).filter(UserSettings.user_id == user_id).first()
settings_str = json.dumps(settings)
if record:
record.settings_json = settings_str
record.updated_at = datetime.datetime.utcnow()
else:
record = UserSettings(user_id=user_id, settings_json=settings_str)
db.add(record)
db.commit()
return settings
finally:
db.close()
def reorder_portfolio(user_id: int, item_ids: List[int]) -> bool:
"""Set sort_order for portfolio items based on the given ID order."""
db = SessionLocal()
try:
for idx, item_id in enumerate(item_ids):
db.query(PortfolioItem).filter(
PortfolioItem.id == item_id,
PortfolioItem.user_id == user_id,
).update({"sort_order": idx})
db.commit()
return True
finally:
db.close()
# --- User Lookups for Social ---
def get_user_by_id(user_id: int) -> Optional[User]:
db = SessionLocal()
try:
return db.query(User).filter(User.id == user_id).first()
finally:
db.close()
def get_user_by_code(code: str) -> Optional[User]:
db = SessionLocal()
try:
return db.query(User).filter(User.user_code == code).first()
finally:
db.close()
# --- Friendships ---
def create_friendship(user_id: int, friend_id: int) -> Friendship:
"""Send a friend request. Raises ValueError if already exists."""
db = SessionLocal()
try:
existing = db.query(Friendship).filter(
((Friendship.user_id == user_id) & (Friendship.friend_id == friend_id)) |
((Friendship.user_id == friend_id) & (Friendship.friend_id == user_id))
).first()
if existing:
if existing.status == "declined":
existing.user_id = user_id
existing.friend_id = friend_id
existing.status = "pending"
existing.updated_at = datetime.datetime.utcnow()
db.commit()
db.refresh(existing)
return existing
raise ValueError("Friend request already exists")
f = Friendship(user_id=user_id, friend_id=friend_id, status="pending")
db.add(f)
db.commit()
db.refresh(f)
return f
finally:
db.close()
def get_friends(user_id: int) -> List[dict]:
"""Get accepted friends with user info."""
db = SessionLocal()
try:
rows = db.query(Friendship).filter(
Friendship.status == "accepted",
(Friendship.user_id == user_id) | (Friendship.friend_id == user_id)
).all()
other_ids = [f.friend_id if f.user_id == user_id else f.user_id for f in rows]
if not other_ids:
return []
users = {u.id: u for u in db.query(User).filter(User.id.in_(other_ids)).all()}
result = []
for f in rows:
other_id = f.friend_id if f.user_id == user_id else f.user_id
other = users.get(other_id)
if other:
result.append({
"friendship_id": f.id,