File size: 2,120 Bytes
fbfd0f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import sys
from pathlib import Path

# Add the server root to the python path to import src modules
server_root = Path(__file__).resolve().parent.parent
sys.path.append(str(server_root))

from firebase_admin import firestore
from src.db.firebase import get_firebase_db
from src.utils.logger import setup_logger

logger = setup_logger(__name__)

def migrate_notes_count():
    db = get_firebase_db()
    if not db:
        logger.error("Failed to initialize Firebase database.")
        return

    logger.info("Starting notesCount migration...")

    users_ref = db.collection('users')
    analytics_ref = db.collection('analytics')

    users = users_ref.stream()
    migrated_count = 0
    skipped_count = 0

    for user_doc in users:
        user_data = user_doc.to_dict()
        user_id = user_doc.id

        if 'notesCount' in user_data:
            notes_count = user_data['notesCount']
            logger.info(f"Migrating notesCount ({notes_count}) for user {user_id}")
            
            # Update the analytics collection with notesCount
            analytics_doc_ref = analytics_ref.document(user_id)
            
            # Use merge=True to create the document if it doesn't exist without overwriting other fields
            analytics_doc_ref.set({
                'notesCount': notes_count,
            }, merge=True)

            # Optionally, remove the totalVideos field since we are standardizing on notesCount
            analytics_doc = analytics_doc_ref.get()
            if analytics_doc.exists and 'totalVideos' in analytics_doc.to_dict():
                analytics_doc_ref.update({
                    'totalVideos': firestore.DELETE_FIELD
                })

            # Remove notesCount from the user document
            users_ref.document(user_id).update({
                'notesCount': firestore.DELETE_FIELD
            })

            migrated_count += 1
        else:
            skipped_count += 1

    logger.info(f"Migration completed. Migrated: {migrated_count}, Skipped (no notesCount): {skipped_count}")

if __name__ == "__main__":
    migrate_notes_count()