mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-20 13:07:57 +09:00
fix: support hash-keyed user docs in all user lookups (#479)
## Summary
- Added `get_user_doc_ref()` helper to `UserService` that finds user
documents regardless of key type (email-keyed or hash-keyed)
- Fixed `get_user()`, `update_user()`, `increment_jobs_completed()` to
fall back to querying by email field when direct doc ID lookup fails
- Fixed webhook `total_spent` update which was using wrong collection
name ("users" instead of "gen_users") and direct doc ID lookup
- Fixed backfill endpoint to use `USERS_COLLECTION` constant instead of
hardcoded "users"
### Context
Firestore has two populations of user docs: 42 email-keyed (doc ID =
email, from current `_save_user`) and 36 hash-keyed (doc ID = SHA256
hash, from older auth). All runtime code used `document(email.lower())`
which silently failed for hash-keyed users, meaning their
`total_jobs_completed` and `total_spent` were never updated.
## Test plan
- [x] All 187 tests pass (backend + frontend)
- [ ] After deploy: run backfill endpoint to recalculate stats for
hash-keyed users
- [ ] Verify admin dashboard shows correct stats for users like
`admin@nomadkaraoke.com`
@coderabbitai ignore
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
1 parent
0281df345e
commit
a286559cfd
4 files changed
+50
-12
No files matched your search
@@ -2994,7 +2994,7 @@ async def backfill_user_stats(
|
||||
db = firestore_lib.Client()
|
||||
|
||||
# Get all users
|
||||
users_docs = list(db.collection("users").stream())
|
||||
users_docs = list(db.collection(USERS_COLLECTION).stream())
|
||||
updated = 0
|
||||
|
||||
for user_doc in users_docs:
|
||||
|
||||
@@ -891,8 +891,11 @@ async def stripe_webhook(
|
||||
if amount_total > 0 and customer_email:
|
||||
try:
|
||||
from google.cloud.firestore_v1 import Increment
|
||||
user_doc_ref = user_service.db.collection("users").document(customer_email.lower().strip())
|
||||
user_doc_ref.update({"total_spent": Increment(amount_total)})
|
||||
user_doc_ref = user_service.get_user_doc_ref(customer_email)
|
||||
if user_doc_ref:
|
||||
user_doc_ref.update({"total_spent": Increment(amount_total)})
|
||||
else:
|
||||
logger.warning(f"No user doc found for {customer_email} to update total_spent")
|
||||
except Exception as spend_err:
|
||||
logger.warning(f"Failed to update total_spent for {customer_email}: {spend_err}")
|
||||
|
||||
|
||||
@@ -59,16 +59,50 @@ class UserService:
|
||||
# User CRUD Operations
|
||||
# =========================================================================
|
||||
|
||||
def get_user_doc_ref(self, email: str):
|
||||
"""Get the Firestore document reference for a user by email.
|
||||
|
||||
Handles both email-keyed docs (doc ID = email) and hash-keyed docs
|
||||
(doc ID = hash, email stored as field). Returns None if not found.
|
||||
"""
|
||||
try:
|
||||
# First try direct lookup by email as doc ID
|
||||
doc_ref = self.db.collection(USERS_COLLECTION).document(email.lower())
|
||||
doc = doc_ref.get()
|
||||
if doc.exists:
|
||||
return doc_ref
|
||||
|
||||
# Fallback: query by email field (for hash-keyed docs)
|
||||
query = self.db.collection(USERS_COLLECTION).where(
|
||||
filter=FieldFilter('email', '==', email.lower())
|
||||
).limit(1)
|
||||
results = list(query.stream())
|
||||
if results:
|
||||
return results[0].reference
|
||||
|
||||
return None
|
||||
except Exception:
|
||||
logger.exception(f"Error finding user doc ref for {email}")
|
||||
return None
|
||||
|
||||
def get_user(self, email: str) -> Optional[User]:
|
||||
"""Get a user by email."""
|
||||
try:
|
||||
doc_ref = self.db.collection(USERS_COLLECTION).document(email.lower())
|
||||
doc = doc_ref.get()
|
||||
|
||||
if not doc.exists:
|
||||
return None
|
||||
if doc.exists:
|
||||
return User(**doc.to_dict())
|
||||
|
||||
return User(**doc.to_dict())
|
||||
# Fallback: query by email field (for hash-keyed docs)
|
||||
query = self.db.collection(USERS_COLLECTION).where(
|
||||
filter=FieldFilter('email', '==', email.lower())
|
||||
).limit(1)
|
||||
results = list(query.stream())
|
||||
if results:
|
||||
return User(**results[0].to_dict())
|
||||
|
||||
return None
|
||||
except Exception:
|
||||
logger.exception(f"Error getting user {email}")
|
||||
return None
|
||||
@@ -127,7 +161,10 @@ class UserService:
|
||||
"""Update user fields."""
|
||||
try:
|
||||
updates['updated_at'] = datetime.utcnow()
|
||||
doc_ref = self.db.collection(USERS_COLLECTION).document(email.lower())
|
||||
doc_ref = self.get_user_doc_ref(email)
|
||||
if not doc_ref:
|
||||
logger.warning(f"Cannot update user {email}: doc not found")
|
||||
return None
|
||||
doc_ref.update(updates)
|
||||
return self.get_user(email)
|
||||
except Exception:
|
||||
@@ -820,12 +857,10 @@ class UserService:
|
||||
def increment_jobs_completed(self, email: str) -> bool:
|
||||
"""Increment the completed jobs counter for a user using atomic increment."""
|
||||
try:
|
||||
# Check user exists first
|
||||
if not self.get_user(email):
|
||||
doc_ref = self.get_user_doc_ref(email)
|
||||
if not doc_ref:
|
||||
return False
|
||||
|
||||
# Use atomic increment to prevent race conditions
|
||||
doc_ref = self.db.collection(USERS_COLLECTION).document(email.lower())
|
||||
doc_ref.update({
|
||||
'total_jobs_completed': Increment(1),
|
||||
'updated_at': datetime.utcnow()
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.130.0"
|
||||
version = "0.131.0"
|
||||
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
|
||||
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
|
||||
license = "MIT"
|
||||
|
||||
Reference in new issue
Block a user