BasitAliii commited on
Commit
4b66c61
·
verified ·
1 Parent(s): fd9459a

Update storage.py

Browse files
Files changed (1) hide show
  1. storage.py +38 -80
storage.py CHANGED
@@ -1,84 +1,42 @@
1
- import json
 
2
  import uuid
3
- from pathlib import Path
4
- from typing import List, Optional, Tuple
5
 
6
- from models import Profile
7
- from config import DATA_FILE
8
-
9
-
10
- class ProfileStore:
11
- def __init__(self, path: Path = DATA_FILE) -> None:
12
- self.path = path
13
- self._ensure_file()
14
-
15
- def _ensure_file(self) -> None:
16
- if not self.path.exists():
17
- self.path.write_text("[]", encoding="utf-8")
18
-
19
- def load_all(self) -> List[Profile]:
20
- try:
21
- data = json.loads(self.path.read_text(encoding="utf-8"))
22
- return [Profile.from_dict(d) for d in data if isinstance(d, dict)]
23
- except json.JSONDecodeError:
24
- return []
25
-
26
- def save_all(self, profiles: List[Profile]) -> None:
27
- self.path.write_text(
28
- json.dumps([p.to_dict() for p in profiles], indent=2, ensure_ascii=False),
29
- encoding="utf-8",
 
 
 
 
 
 
 
 
 
 
30
  )
31
 
32
- def find_by_username(self, username: str) -> Optional[Profile]:
33
- username = (username or "").strip()
34
- for p in self.load_all():
35
- if p.username.lower() == username.lower():
36
- return p
37
- return None
38
-
39
- def add_or_update(self, profile: Profile) -> Tuple[bool, str]:
40
- ok, err = validate_profile(profile)
41
- if not ok:
42
- return False, f"Validation failed: {err}"
43
-
44
- profiles = self.load_all()
45
- existing = next((p for p in profiles if p.username.lower() == profile.username.lower()), None)
46
-
47
- if existing:
48
- existing.offers = profile.offers
49
- existing.wants = profile.wants
50
- existing.availability = profile.availability
51
- existing.preferences = profile.preferences
52
- existing.avatar = profile.avatar
53
- self.save_all(profiles)
54
- return True, "Profile updated."
55
-
56
- profile.id = profile.id or str(uuid.uuid4())
57
- profiles.append(profile)
58
- self.save_all(profiles)
59
- return True, "Profile created."
60
-
61
- # ✅ NEW DELETE METHOD
62
- def delete(self, username: str) -> Tuple[bool, str]:
63
- username = (username or "").strip()
64
- profiles = self.load_all()
65
- profiles_new = [p for p in profiles if p.username.lower() != username.lower()]
66
-
67
- if len(profiles_new) == len(profiles):
68
- return False, "Profile not found."
69
-
70
- self.save_all(profiles_new)
71
- return True, "Profile deleted."
72
-
73
-
74
- def validate_profile(profile: Profile) -> Tuple[bool, Optional[str]]:
75
- if not profile.username:
76
- return False, "Username is required."
77
- if len(profile.username) > 60:
78
- return False, "Username must be 60 characters or fewer."
79
- if not profile.offers and not profile.wants:
80
- return False, "At least one offer or want is required."
81
- for s in profile.offers + profile.wants:
82
- if not s or len(s) > 120:
83
- return False, "Invalid skill entry."
84
- return True, None
 
1
+ from dataclasses import dataclass, asdict
2
+ from typing import List, Dict, Any, Optional
3
  import uuid
 
 
4
 
5
+ from utils import normalize_skill_list
6
+
7
+
8
+ @dataclass
9
+ class Profile:
10
+ id: str
11
+ username: str
12
+ offers: List[str]
13
+ wants: List[str]
14
+ availability: str
15
+ preferences: str
16
+ avatar: Optional[str] = None
17
+
18
+ @staticmethod
19
+ def from_dict(d: Dict[str, Any]) -> "Profile":
20
+ return Profile(
21
+ id=str(d.get("id") or uuid.uuid4()),
22
+ username=str(d.get("username") or "").strip(),
23
+
24
+ # ✅ CRITICAL FIX
25
+ offers=normalize_skill_list(
26
+ ",".join(d.get("offers", []))
27
+ if isinstance(d.get("offers"), list)
28
+ else d.get("offers")
29
+ ),
30
+ wants=normalize_skill_list(
31
+ ",".join(d.get("wants", []))
32
+ if isinstance(d.get("wants"), list)
33
+ else d.get("wants")
34
+ ),
35
+
36
+ availability=str(d.get("availability") or ""),
37
+ preferences=str(d.get("preferences") or ""),
38
+ avatar=d.get("avatar"),
39
  )
40
 
41
+ def to_dict(self) -> Dict[str, Any]:
42
+ return asdict(self)