File size: 7,173 Bytes
840101a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
from supabase import create_client, Client
import os

def init_supabase():
    """Initialize Supabase client"""
    try:
        url = st.secrets.get("SUPABASE_URL")
        key = st.secrets.get("SUPABASE_KEY")
    except:
        url = os.getenv("SUPABASE_URL")
        key = os.getenv("SUPABASE_KEY")
    
    if not url or not key:
        st.error("Supabase credentials not found.")
        return None
    
    return create_client(url, key)

def test_multiple_submissions():
    """Test multiple submission functionality"""
    st.title("πŸ”„ Multiple Submissions Test")
    
    supabase = init_supabase()
    if not supabase:
        st.error("Failed to initialize Supabase client")
        return
    
    try:
        # Test 1: Get a test user
        st.subheader("πŸ‘₯ Getting Test User")
        try:
            users_response = supabase.table('users').select('*').execute()
            if users_response.data:
                test_user = users_response.data[0]
                st.success(f"Using {test_user.get('username')} for testing")
            else:
                st.error("No users found in database")
                return
        except Exception as e:
            st.error(f"❌ Error fetching users: {str(e)}")
            return
        
        # Test 2: Insert multiple submissions
        st.subheader("πŸ“€ Testing Multiple Submissions")
        
        submissions = [
            {
                'username': test_user.get('username'),
                'week_number': 1,
                'submission_type': 'multiple_test',
                'submission_data': {
                    "questions": [{
                        "id": "test_q1",
                        "type": "textarea",
                        "question": "First submission question",
                        "student_answer": "First submission answer",
                        "max_length": 500
                    }]
                },
                'score': 5,
                'max_score': 10
            },
            {
                'username': test_user.get('username'),
                'week_number': 1,
                'submission_type': 'multiple_test',
                'submission_data': {
                    "questions": [{
                        "id": "test_q2",
                        "type": "textarea",
                        "question": "Second submission question",
                        "student_answer": "Second submission answer",
                        "max_length": 500
                    }]
                },
                'score': 8,
                'max_score': 10
            },
            {
                'username': test_user.get('username'),
                'week_number': 1,
                'submission_type': 'multiple_test',
                'submission_data': {
                    "questions": [{
                        "id": "test_q3",
                        "type": "textarea",
                        "question": "Third submission question",
                        "student_answer": "Third submission answer",
                        "max_length": 500
                    }]
                },
                'score': 10,
                'max_score': 10
            }
        ]
        
        # Insert all submissions
        for i, submission in enumerate(submissions, 1):
            st.write(f"**Inserting submission {i}:**")
            st.json(submission)
            
            try:
                response = supabase.table('student_submissions').insert(submission).execute()
                if response.data:
                    st.success(f"βœ… Submission {i} inserted successfully!")
                else:
                    st.error(f"❌ Submission {i} failed - no data returned")
            except Exception as e:
                st.error(f"❌ Submission {i} failed: {str(e)}")
            
            st.markdown("---")
        
        # Test 3: Retrieve all submissions
        st.subheader("πŸ“₯ Testing Submission Retrieval")
        
        try:
            all_submissions = supabase.table('student_submissions').select('*').eq('username', test_user.get('username')).eq('week_number', 1).eq('submission_type', 'multiple_test').order('submitted_at', desc=True).execute()
            
            if all_submissions.data:
                st.success(f"βœ… Found {len(all_submissions.data)} submissions")
                
                # Display all submissions
                for i, submission in enumerate(all_submissions.data, 1):
                    st.markdown(f"**Submission {i}** - {submission['submitted_at']} - Score: {submission['score']}/{submission['max_score']}")
                    st.json(submission['submission_data'])
                    st.markdown("---")
                
                # Show statistics
                scores = [s['score'] for s in all_submissions.data]
                st.info(f"**Statistics:**")
                st.info(f"- Total submissions: {len(all_submissions.data)}")
                st.info(f"- Best score: {max(scores)}")
                st.info(f"- Average score: {sum(scores) / len(scores):.1f}")
                st.info(f"- Latest submission: {all_submissions.data[0]['submitted_at']}")
                
            else:
                st.warning("⚠️ No submissions found")
                
        except Exception as e:
            st.error(f"❌ Error retrieving submissions: {str(e)}")
        
        # Test 4: Test the get_existing_submission function (should get most recent)
        st.subheader("πŸ” Testing Most Recent Submission Function")
        
        try:
            # This simulates the get_existing_submission function
            recent_response = supabase.table('student_submissions').select('*').eq('username', test_user.get('username')).eq('week_number', 1).eq('submission_type', 'multiple_test').order('submitted_at', desc=True).limit(1).execute()
            
            if recent_response.data:
                most_recent = recent_response.data[0]
                st.success("βœ… Most recent submission retrieved successfully!")
                st.info(f"**Most Recent:** {most_recent['submitted_at']} - Score: {most_recent['score']}/{most_recent['max_score']}")
                st.json(most_recent['submission_data'])
            else:
                st.warning("⚠️ No recent submission found")
                
        except Exception as e:
            st.error(f"❌ Error retrieving most recent submission: {str(e)}")
        
        # Test 5: Clean up test data
        st.subheader("🧹 Cleanup")
        
        if st.button("Clean up test submissions"):
            try:
                delete_response = supabase.table('student_submissions').delete().eq('submission_type', 'multiple_test').execute()
                st.success(f"βœ… Cleaned up {len(delete_response.data) if delete_response.data else 0} test submissions")
            except Exception as e:
                st.error(f"❌ Cleanup failed: {str(e)}")
        
    except Exception as e:
        st.error(f"❌ Test failed: {str(e)}")

if __name__ == "__main__":
    test_multiple_submissions()