Jump to content
Main menu
Main menu
move to sidebar
hide
Navigation
Main page
Recent changes
Random page
freem
Search
Search
Appearance
Create account
Log in
Personal tools
Create account
Log in
Pages for logged out editors
learn more
Contributions
Talk
Editing
Openai/693f3576-eaf4-8011-9c02-8476c83275fd
(section)
Add languages
Page
Discussion
English
Read
Edit
Edit source
View history
Tools
Tools
move to sidebar
hide
Actions
Read
Edit
Edit source
View history
General
What links here
Related changes
Special pages
Page information
Appearance
move to sidebar
hide
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== gpt-5-2-thinking == === User: Build me a mobile app. === Build me a mobile app. The app will be called PBYSA Umpire Check-In. The purpose is for umpires to be able to submit that they were working. They should be able to create an account and login. Once logged in it will automatically fill in the date and time and it will ask them the following questions; What division? Are you the only umpire? === Assistant: Below is a solid MVP build for PBYSA Umpire Check-In: account creation + login + a “check-in” form that auto-fills date… === Below is a solid MVP build for PBYSA Umpire Check-In: account creation + login + a “check-in” form that auto-fills date/time and asks: * What division? * Are you the only umpire? I’ll give you (1) the app flow/spec, (2) the backend/data model, and (3) working starter code using React Native (Expo) + Firebase (fastest way to get Auth + database without running your own server). ==== ### ==== # Welcome - Buttons: Log In / Create Account # Create Account - Email + password # Log In - Email + password # Check-In (main screen after login) - Auto-filled Date and Time (shows current local time) - Division (dropdown or text input) - Only umpire? (Yes/No switch) - Submit - Optional: list of your recent check-ins # Settings - Log out ===== - Must be logged in to submit. ===== * On submit, save: - userId, email - timestamp (server-side if possible) - division - onlyUmpire (true/false) ==== Collection: checkins ==== Each document: <syntaxhighlight lang="json">{ "userId": "abc123", "email": "ump@example.com", "division": "10U", "onlyUmpire": true, "createdAt": "server timestamp" } </syntaxhighlight> ==== ### ==== * Install Node.js * Install Expo CLI (optional; Expo also works via npx) * Create a Firebase project (free tier is fine) - Enable Authentication → Email/Password - Create Firestore Database ===== <syntaxhighlight lang="bash">npx create-expo-app pbysa-umpire-checkin ===== cd pbysa-umpire-checkin npm install firebase </syntaxhighlight> ===== Create src/firebase.js: ===== <syntaxhighlight lang="js">// src/firebase.js import { initializeApp } from "firebase/app"; import { getAuth } from "firebase/auth"; import { getFirestore } from "firebase/firestore"; const firebaseConfig = { apiKey: "YOUR_API_KEY", authDomain: "YOUR_PROJECT.firebaseapp.com", projectId: "YOUR_PROJECT_ID", storageBucket: "YOUR_PROJECT.appspot.com", messagingSenderId: "YOUR_SENDER_ID", appId: "YOUR_APP_ID", }; const app = initializeApp(firebaseConfig); export const auth = getAuth(app); export const db = getFirestore(app); </syntaxhighlight> : ===== Replace App.js with this: ===== <syntaxhighlight lang="js">import React, { useEffect, useMemo, useState } from "react"; import { SafeAreaView, View, Text, TextInput, Pressable, Switch, StyleSheet, Alert } from "react-native"; import { onAuthStateChanged, createUserWithEmailAndPassword, signInWithEmailAndPassword, signOut } from "firebase/auth"; import { addDoc, collection, serverTimestamp } from "firebase/firestore"; import { auth, db } from "./src/firebase"; function Button({ title, onPress, variant = "primary" }) { return ( <Pressable onPress={onPress} style={[styles.button, variant === "secondary" && styles.buttonSecondary]} > <Text style={[styles.buttonText, variant === "secondary" && styles.buttonTextSecondary]}> {title} </Text> </Pressable> ); } function AuthScreen({ mode, onSwitchMode }) { const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const isSignup = mode === "signup"; const handleSubmit = async () => { if (!email.trim() || !password) { Alert.alert("Missing info", "Please enter email and password."); return; } try { if (isSignup) { await createUserWithEmailAndPassword(auth, email.trim(), password); } else { await signInWithEmailAndPassword(auth, email.trim(), password); } } catch (e) { Alert.alert("Auth error", e?.message ?? "Something went wrong."); } }; return ( <SafeAreaView style={styles.container}> <Text style={styles.title}>PBYSA Umpire Check-In</Text> <Text style={styles.subtitle}>{isSignup ? "Create Account" : "Log In"}</Text> <View style={styles.card}> <Text style={styles.label}>Email</Text> <TextInput autoCapitalize="none" keyboardType="email-address" value={email} onChangeText={setEmail} placeholder="you@example.com" style={styles.input} /> <Text style={styles.label}>Password</Text> <TextInput secureTextEntry value={password} onChangeText={setPassword} placeholder="••••••••" style={styles.input} /> <Button title={isSignup ? "Create Account" : "Log In"} onPress={handleSubmit} /> <View style={{ height: 10 }} /> <Button title={isSignup ? "Already have an account? Log in" : "New here? Create an account"} onPress={onSwitchMode} variant="secondary" /> </View> <Text style={styles.footer}>Umpires can submit a check-in to confirm they worked.</Text> </SafeAreaView> ); } function CheckInScreen({ user }) { const [division, setDivision] = useState(""); const [onlyUmpire, setOnlyUmpire] = useState(false); const [submitting, setSubmitting] = useState(false); const now = useMemo(() => new Date(), []); const [clock, setClock] = useState(new Date()); useEffect(() => { const t = setInterval(() => setClock(new Date()), 1000); return () => clearInterval(t); }, []); const formattedDate = clock.toLocaleDateString(); const formattedTime = clock.toLocaleTimeString(); const submit = async () => { if (!division.trim()) { Alert.alert("Missing division", "Please enter the division."); return; } setSubmitting(true); try { await addDoc(collection(db, "checkins"), { userId: user.uid, email: user.email ?? "", division: division.trim(), onlyUmpire, // server timestamp ensures consistency and prevents device clock issues createdAt: serverTimestamp(), // optional: also store device time for display/debug deviceDate: formattedDate, deviceTime: formattedTime, }); Alert.alert("Submitted!", "Your check-in has been recorded."); setDivision(""); setOnlyUmpire(false); } catch (e) { Alert.alert("Submit error", e?.message ?? "Something went wrong submitting your check-in."); } finally { setSubmitting(false); } }; const logout = async () => { try { await signOut(auth); } catch (e) { Alert.alert("Logout error", e?.message ?? "Could not log out."); } }; return ( <SafeAreaView style={styles.container}> <Text style={styles.title}>PBYSA Umpire Check-In</Text> <Text style={styles.subtitle}>Welcome, {user.email}</Text> <View style={styles.card}> <Text style={styles.label}>Date</Text> <Text style={styles.readonly}>{formattedDate}</Text> <Text style={styles.label}>Time</Text> <Text style={styles.readonly}>{formattedTime}</Text> <Text style={styles.label}>What division?</Text> <TextInput value={division} onChangeText={setDivision} placeholder="Example: 8U, 10U, Majors..." style={styles.input} /> <View style={styles.row}> <View style={{ flex: 1 }}> <Text style={styles.label}>Are you the only umpire?</Text> <Text style={styles.hint}>{onlyUmpire ? "Yes" : "No"}</Text> </View> <Switch value={onlyUmpire} onValueChange={setOnlyUmpire} /> </View> <Button title={submitting ? "Submitting..." : "Submit Check-In"} onPress={submit} /> <View style={{ height: 10 }} /> <Button title="Log Out" onPress={logout} variant="secondary" /> </View> <Text style={styles.footer}> Check-ins automatically include date/time and your account email. </Text> </SafeAreaView> ); } export default function App() { const [user, setUser] = useState(null); const [mode, setMode] = useState("login"); // "login" | "signup" const [loadingAuth, setLoadingAuth] = useState(true); useEffect(() => { const unsub = onAuthStateChanged(auth, (u) => { setUser(u); setLoadingAuth(false); }); return () => unsub(); }, []); if (loadingAuth) { return ( <SafeAreaView style={styles.container}> <Text style={styles.title}>PBYSA Umpire Check-In</Text> <Text style={styles.subtitle}>Loading…</Text> </SafeAreaView> ); } if (!user) { return ( <AuthScreen mode={mode} onSwitchMode={() => setMode((m) => (m === "login" ? "signup" : "login"))} /> ); } return <CheckInScreen user={user} />; } const styles = StyleSheet.create({ container: { flex: 1, padding: 18, backgroundColor: "#fff" }, title: { fontSize: 26, fontWeight: "700", marginTop: 8 }, subtitle: { fontSize: 16, marginTop: 6, marginBottom: 14, color: "#333" }, card: { borderWidth: 1, borderColor: "#eee", borderRadius: 14, padding: 16, backgroundColor: "#fafafa", }, label: { fontSize: 14, fontWeight: "600", marginTop: 10, marginBottom: 6 }, hint: { fontSize: 12, color: "#666" }, input: { borderWidth: 1, borderColor: "#ddd", borderRadius: 10, paddingHorizontal: 12, paddingVertical: 10, backgroundColor: "#fff", }, readonly: { fontSize: 16, paddingVertical: 6 }, row: { flexDirection: "row", alignItems: "center", marginTop: 10 }, button: { marginTop: 16, borderRadius: 12, paddingVertical: 12, alignItems: "center", backgroundColor: "#111", }, buttonSecondary: { backgroundColor: "#fff", borderWidth: 1, borderColor: "#111" }, buttonText: { color: "#fff", fontWeight: "700" }, buttonTextSecondary: { color: "#111" }, footer: { marginTop: 14, color: "#666" }, }); </syntaxhighlight> ===== <syntaxhighlight lang="bash">npx expo start ===== </syntaxhighlight> Scan the QR code with Expo Go (iOS/Android) to test. ==== In Firebase → Firestore → Rules, start with: ==== <syntaxhighlight lang="js">rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /checkins/{docId} { allow create: if request.auth != null && request.resource.data.userId == request.auth.uid; // Optional: allow reading only your own records allow read: if request.auth != null && resource.data.userId == request.auth.uid; } } } </syntaxhighlight> ==== - Division as a dropdown list you control (8U/10U/12U/etc.) ==== * Add Field / Location, Game ID, Partner name (if not only umpire) * Admin view for board members to export check-ins (CSV) * Prevent duplicate check-ins within a time window (e.g., 2 hours) * Push confirmation + “history” screen If you tell me iOS, Android, or both, and whether PBYSA wants admins to see all check-ins, I can extend this into: * an admin login role, * an admin dashboard screen (inside the app), * and/or a web admin panel for exporting payroll/assignments. === User: Make divisions a dropdown list. === Make divisions a dropdown list. Division are Teeball, 8U, 10U, 12U, and 15U. Add Field which is 1 through 8. Add a drop down asking if they are a solo umpire and the answer can be yes or no. Enable location and ensure they are within 5,000 feet of 2020 Bauer Road, Pensacola, FL 32506. Make for both iOS and Android. PBYSA wants admins to see all check-ins. === Assistant: Got it. === Got it. Here’s an upgraded both iOS + Android MVP using Expo (React Native) + Firebase with: * Division dropdown: Teeball, 8U, 10U, 12U, 15U * Field dropdown: 1–8 * Solo umpire dropdown: Yes/No * Location enabled + distance gate: must be within 5,000 feet (~1524m) of 2020 Bauer Rd, Pensacola, FL 32506 * Admins can see all check-ins For the location fence, I’m using the MapQuest listing for 2020 Bauer Rd which includes coordinates (30.38448, -87.40056). MapQuest<ref>{{cite web|title=MapQuest|url=https://www.mapquest.com/us/florida/pensacola/32506-9663/2020-bauer-rd-30.38448%2C-87.40056|publisher=mapquest.com|access-date=2025-12-15}}</ref> ==== From your Expo project folder: ==== <syntaxhighlight lang="bash">npm install firebase expo-location npm install @react-native-picker/picker </syntaxhighlight> ==== ### ==== users/{uid}: <syntaxhighlight lang="json">{ "email": "ump@example.com", "role": "umpire" // or "admin" } </syntaxhighlight> ===== Each check-in document: ===== <syntaxhighlight lang="json">{ "userId": "uid", "email": "ump@example.com", "division": "10U", "field": 3, "soloUmpire": "Yes", "createdAt": "server timestamp", "location": { "lat": 30.38, "lng": -87.40 }, "distanceMeters": 412.3 } </syntaxhighlight> How to make an admin: after creating the account, go to Firebase Console → Firestore → users/{uid} and set "role": "admin". ==== In Firebase → Firestore → Rules: ==== <syntaxhighlight lang="js">rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { function isSignedIn() { return request.auth != null; } function isAdmin() { return isSignedIn() && get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == "admin"; } match /users/{uid} { allow read: if isSignedIn() && request.auth.uid == uid; allow create: if isSignedIn() && request.auth.uid == uid; allow update: if isAdmin(); // admins can promote people } match /checkins/{docId} { allow create: if isSignedIn() && request.resource.data.userId == request.auth.uid; // admins can read all; umpires can read their own allow read: if isAdmin() || (isSignedIn() && resource.data.userId == request.auth.uid); } } } </syntaxhighlight> ==== Replace your App.js with the full version below. ==== <syntaxhighlight lang="js">import React, { useEffect, useMemo, useState } from "react"; import { SafeAreaView, View, Text, TextInput, Pressable, StyleSheet, Alert, FlatList, ActivityIndicator, } from "react-native"; import { Picker } from "@react-native-picker/picker"; import * as Location from "expo-location"; import { onAuthStateChanged, createUserWithEmailAndPassword, signInWithEmailAndPassword, signOut, } from "firebase/auth"; import { addDoc, collection, serverTimestamp, doc, setDoc, getDoc, query, orderBy, limit, onSnapshot, where, } from "firebase/firestore"; import { auth, db } from "./src/firebase"; // --- Constants --- const DIVISIONS = ["Teeball", "8U", "10U", "12U", "15U"]; const FIELDS = [1, 2, 3, 4, 5, 6, 7, 8]; const SOLO_OPTIONS = ["Yes", "No"]; // 2020 Bauer Rd, Pensacola, FL 32506 (MapQuest shows coords in URL) const FACILITY = { name: "2020 Bauer Rd, Pensacola, FL 32506", lat: 30.38448, lng: -87.40056, }; // 5,000 feet ≈ 1524 meters const MAX_DISTANCE_METERS = 1524; function Button({ title, onPress, variant = "primary", disabled = false }) { return ( <Pressable onPress={disabled ? undefined : onPress} style={[ styles.button, variant === "secondary" && styles.buttonSecondary, disabled && styles.buttonDisabled, ]} > <Text style={[ styles.buttonText, variant === "secondary" && styles.buttonTextSecondary, disabled && styles.buttonTextDisabled, ]} > {title} </Text> </Pressable> ); } function milesFromMeters(m) { return m / 1609.344; } function formatWhen(ts) { if (!ts) return "—"; const d = ts.toDate ? ts.toDate() : new Date(ts); return d.toLocaleString(); } // --- Auth Screen --- function AuthScreen({ mode, onSwitchMode }) { const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const isSignup = mode === "signup"; const handleSubmit = async () => { if (!email.trim() || !password) { Alert.alert("Missing info", "Please enter email and password."); return; } try { if (isSignup) { const cred = await createUserWithEmailAndPassword(auth, email.trim(), password); // Create user profile with default role await setDoc(doc(db, "users", cred.user.uid), { email: cred.user.email ?? email.trim(), role: "umpire", createdAt: serverTimestamp(), }); } else { await signInWithEmailAndPassword(auth, email.trim(), password); } } catch (e) { Alert.alert("Auth error", e?.message ?? "Something went wrong."); } }; return ( <SafeAreaView style={styles.container}> <Text style={styles.title}>PBYSA Umpire Check-In</Text> <Text style={styles.subtitle}>{isSignup ? "Create Account" : "Log In"}</Text> <View style={styles.card}> <Text style={styles.label}>Email</Text> <TextInput autoCapitalize="none" keyboardType="email-address" value={email} onChangeText={setEmail} placeholder="you@example.com" style={styles.input} /> <Text style={styles.label}>Password</Text> <TextInput secureTextEntry value={password} onChangeText={setPassword} placeholder="••••••••" style={styles.input} /> <Button title={isSignup ? "Create Account" : "Log In"} onPress={handleSubmit} /> <View style={{ height: 10 }} /> <Button title={isSignup ? "Already have an account? Log in" : "New here? Create an account"} onPress={onSwitchMode} variant="secondary" /> </View> <Text style={styles.footer}> Check-ins require location and must be within 5,000 ft of the facility. </Text> </SafeAreaView> ); } // --- Check-In Screen (Umpire) --- function UmpireCheckInScreen({ user, role }) { const [division, setDivision] = useState(DIVISIONS[0]); const [field, setField] = useState(FIELDS[0]); const [soloUmpire, setSoloUmpire] = useState(SOLO_OPTIONS[0]); const [locationStatus, setLocationStatus] = useState("unknown"); // unknown | granted | denied const [checkingLocation, setCheckingLocation] = useState(false); const [submitting, setSubmitting] = useState(false); const [myCheckins, setMyCheckins] = useState([]); useEffect(() => { const qy = query( collection(db, "checkins"), where("userId", "==", user.uid), orderBy("createdAt", "desc"), limit(20) ); const unsub = onSnapshot(qy, (snap) => { setMyCheckins(snap.docs.map((d) => ({ id: d.id, ...d.data() }))); }); return () => unsub(); }, [user.uid]); const requestLocation = async () => { setCheckingLocation(true); try { const { status } = await Location.requestForegroundPermissionsAsync(); if (status !== "granted") { setLocationStatus("denied"); Alert.alert( "Location required", "Please enable location permissions to submit a check-in." ); return; } setLocationStatus("granted"); } finally { setCheckingLocation(false); } }; useEffect(() => { requestLocation(); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const getDistanceToFacilityMeters = async () => { const loc = await Location.getCurrentPositionAsync({ accuracy: Location.Accuracy.Highest, }); const dist = Location.distance( { latitude: loc.coords.latitude, longitude: loc.coords.longitude }, { latitude: FACILITY.lat, longitude: FACILITY.lng } ); return { distanceMeters: dist, coords: { lat: loc.coords.latitude, lng: loc.coords.longitude }, }; }; const submit = async () => { if (locationStatus !== "granted") { Alert.alert("Location required", "Please enable location and try again."); return; } setSubmitting(true); try { const { distanceMeters, coords } = await getDistanceToFacilityMeters(); if (distanceMeters > MAX_DISTANCE_METERS) { Alert.alert( "Not at the facility", <code>You must be within 5,000 feet of ${FACILITY.name}.\n\nYou're about ${milesFromMeters( distanceMeters ).toFixed(2)} miles away.</code> ); return; } await addDoc(collection(db, "checkins"), { userId: user.uid, email: user.email ?? "", division, field: Number(field), soloUmpire, createdAt: serverTimestamp(), location: coords, distanceMeters, }); Alert.alert("Submitted!", "Your check-in has been recorded."); } catch (e) { Alert.alert("Submit error", e?.message ?? "Something went wrong submitting your check-in."); } finally { setSubmitting(false); } }; const logout = async () => { try { await signOut(auth); } catch (e) { Alert.alert("Logout error", e?.message ?? "Could not log out."); } }; return ( <SafeAreaView style={styles.container}> <Text style={styles.title}>PBYSA Umpire Check-In</Text> <Text style={styles.subtitle}> {user.email} • {role} </Text> <View style={styles.card}> <Text style={styles.label}>What division?</Text> <View style={styles.pickerWrap}> <Picker selectedValue={division} onValueChange={(v) => setDivision(v)}> {DIVISIONS.map((d) => ( <Picker.Item key={d} label={d} value={d} /> ))} </Picker> </View> <Text style={styles.label}>Field</Text> <View style={styles.pickerWrap}> <Picker selectedValue={field} onValueChange={(v) => setField(v)}> {FIELDS.map((f) => ( <Picker.Item key={String(f)} label={String(f)} value={f} /> ))} </Picker> </View> <Text style={styles.label}>Solo umpire?</Text> <View style={styles.pickerWrap}> <Picker selectedValue={soloUmpire} onValueChange={(v) => setSoloUmpire(v)}> {SOLO_OPTIONS.map((o) => ( <Picker.Item key={o} label={o} value={o} /> ))} </Picker> </View> <Button title={ checkingLocation ? "Checking location…" : submitting ? "Submitting…" : "Submit Check-In" } onPress={submit} disabled={checkingLocation || submitting} /> <View style={{ height: 10 }} /> <Button title="Log Out" onPress={logout} variant="secondary" /> </View> <Text style={[styles.sectionTitle, { marginTop: 14 }]}>My recent check-ins</Text> <FlatList data={myCheckins} keyExtractor={(item) => item.id} ListEmptyComponent={<Text style={styles.hint}>No check-ins yet.</Text>} renderItem={({ item }) => ( <View style={styles.listRow}> <Text style={styles.listRowTitle}> {item.division} • Field {item.field} • Solo: {item.soloUmpire} </Text> <Text style={styles.listRowSub}> {formatWhen(item.createdAt)} • {Math.round(item.distanceMeters ?? 0)}m </Text> </View> )} /> </SafeAreaView> ); } // --- Admin Screen --- function AdminScreen({ user, role }) { const [allCheckins, setAllCheckins] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { const qy = query(collection(db, "checkins"), orderBy("createdAt", "desc"), limit(100)); const unsub = onSnapshot( qy, (snap) => { setAllCheckins(snap.docs.map((d) => ({ id: d.id, ...d.data() }))); setLoading(false); }, () => setLoading(false) ); return () => unsub(); }, []); const logout = async () => { try { await signOut(auth); } catch (e) { Alert.alert("Logout error", e?.message ?? "Could not log out."); } }; return ( <SafeAreaView style={styles.container}> <Text style={styles.title}>Admin • Check-Ins</Text> <Text style={styles.subtitle}> {user.email} • {role} </Text> <View style={styles.card}> <Text style={styles.hint}> Showing the most recent 100 check-ins (live updates). </Text> <View style={{ height: 10 }} /> <Button title="Log Out" onPress={logout} variant="secondary" /> </View> <Text style={[styles.sectionTitle, { marginTop: 14 }]}>All recent check-ins</Text> {loading ? ( <ActivityIndicator style={{ marginTop: 12 }} /> ) : ( <FlatList data={allCheckins} keyExtractor={(item) => item.id} ListEmptyComponent={<Text style={styles.hint}>No check-ins found.</Text>} renderItem={({ item }) => ( <View style={styles.listRow}> <Text style={styles.listRowTitle}> {item.email || item.userId} • {item.division} • Field {item.field} • Solo:{" "} {item.soloUmpire} </Text> <Text style={styles.listRowSub}> {formatWhen(item.createdAt)} • {Math.round(item.distanceMeters ?? 0)}m </Text> </View> )} /> )} </SafeAreaView> ); } // --- Main App --- export default function App() { const [user, setUser] = useState(null); const [mode, setMode] = useState("login"); // "login" | "signup" const [loadingAuth, setLoadingAuth] = useState(true); const [role, setRole] = useState("umpire"); const [loadingRole, setLoadingRole] = useState(false); useEffect(() => { const unsub = onAuthStateChanged(auth, async (u) => { setUser(u); setLoadingAuth(false); if (u) { setLoadingRole(true); try { const snap = await getDoc(doc(db, "users", u.uid)); const data = snap.exists() ? snap.data() : null; setRole(data?.role || "umpire"); } catch { setRole("umpire"); } finally { setLoadingRole(false); } } else { setRole("umpire"); } }); return () => unsub(); }, []); if (loadingAuth) { return ( <SafeAreaView style={styles.container}> <Text style={styles.title}>PBYSA Umpire Check-In</Text> <Text style={styles.subtitle}>Loading…</Text> </SafeAreaView> ); } if (!user) { return ( <AuthScreen mode={mode} onSwitchMode={() => setMode((m) => (m === "login" ? "signup" : "login"))} /> ); } if (loadingRole) { return ( <SafeAreaView style={styles.container}> <Text style={styles.title}>PBYSA Umpire Check-In</Text> <Text style={styles.subtitle}>Loading profile…</Text> </SafeAreaView> ); } return role === "admin" ? ( <AdminScreen user={user} role={role} /> ) : ( <UmpireCheckInScreen user={user} role={role} /> ); } const styles = StyleSheet.create({ container: { flex: 1, padding: 18, backgroundColor: "#fff" }, title: { fontSize: 26, fontWeight: "700", marginTop: 8 }, subtitle: { fontSize: 14, marginTop: 6, marginBottom: 14, color: "#333" }, card: { borderWidth: 1, borderColor: "#eee", borderRadius: 14, padding: 16, backgroundColor: "#fafafa", }, label: { fontSize: 14, fontWeight: "600", marginTop: 10, marginBottom: 6 }, hint: { fontSize: 12, color: "#666" }, input: { borderWidth: 1, borderColor: "#ddd", borderRadius: 10, paddingHorizontal: 12, paddingVertical: 10, backgroundColor: "#fff", }, pickerWrap: { borderWidth: 1, borderColor: "#ddd", borderRadius: 10, overflow: "hidden", backgroundColor: "#fff", }, button: { marginTop: 16, borderRadius: 12, paddingVertical: 12, alignItems: "center", backgroundColor: "#111", }, buttonSecondary: { backgroundColor: "#fff", borderWidth: 1, borderColor: "#111" }, buttonDisabled: { opacity: 0.6 }, buttonText: { color: "#fff", fontWeight: "700" }, buttonTextSecondary: { color: "#111" }, buttonTextDisabled: { color: "#fff" }, footer: { marginTop: 14, color: "#666" }, sectionTitle: { fontSize: 14, fontWeight: "700" }, listRow: { paddingVertical: 10, borderBottomWidth: 1, borderBottomColor: "#eee", }, listRowTitle: { fontSize: 13, fontWeight: "600" }, listRowSub: { fontSize: 12, color: "#666", marginTop: 2 }, }); </syntaxhighlight> Note: The coordinate source for the address is taken from a MapQuest page that embeds the lat/lng for “2020 Bauer Rd” in the URL. MapQuest<ref>{{cite web|title=MapQuest|url=https://www.mapquest.com/us/florida/pensacola/32506-9663/2020-bauer-rd-30.38448%2C-87.40056|publisher=mapquest.com|access-date=2025-12-15}}</ref> ==== Expo builds both. ==== For local testing: <syntaxhighlight lang="bash">npx expo start </syntaxhighlight> When you’re ready to ship: <syntaxhighlight lang="bash">npx expo install eas-cli npx eas build:configure npx eas build --platform ios npx eas build --platform android </syntaxhighlight> ==== This app blocks submission on the device if the user is outside the 5,000 ft radius. For stronger enforcement (so someone can’t bypass it with a hacked client), the next step is a small Firebase Cloud Function that re-checks the location server-side and rejects invalid submissions. ==== If you want, I can add a simple Admin filter/search (by date, division, field, solo) and a one-tap CSV export workflow. === User: yes please === yes please === Assistant: Perfect — here’s Admin filter/search + CSV export added to the app still iOS + Android via Expo. === Perfect — here’s Admin filter/search + CSV export added to the app (still iOS + Android via Expo). For the geofence center point, we’ll keep using MapQuest’s coordinates for 2020 Bauer Rd, Pensacola, FL 32506: 30.38448, -87.40056. MapQuest<ref>{{cite web|title=MapQuest|url=https://www.mapquest.com/us/florida/pensacola/32506-9663/2020-bauer-rd-30.38448%2C-87.40056|publisher=mapquest.com|access-date=2025-12-15}}</ref> ==== <syntaxhighlight lang="bash">npm install expo-file-system expo-sharing ==== </syntaxhighlight> (You already installed: expo-location and @react-native-picker/picker.) ==== This adds: ==== * Search (email contains) * Division filter (All + your list) * Field filter (All + 1–8) * Solo filter (All/Yes/No) * Date filter (Today / Last 7 days / All) * Export CSV (exports the currently filtered results) ===== <syntaxhighlight lang="js">import * as FileSystem from "expo-file-system"; ===== import * as Sharing from "expo-sharing"; // ... keep your other imports ... function AdminScreen({ user, role }) { const [allCheckins, setAllCheckins] = useState([]); const [loading, setLoading] = useState(true); // Filters const [searchEmail, setSearchEmail] = useState(""); const [divisionFilter, setDivisionFilter] = useState("All"); const [fieldFilter, setFieldFilter] = useState("All"); const [soloFilter, setSoloFilter] = useState("All"); // All | Yes | No const [dateFilter, setDateFilter] = useState("All"); // All | Today | Last7 useEffect(() => { // Pull a reasonable recent window to avoid huge reads; increase if needed. const qy = query(collection(db, "checkins"), orderBy("createdAt", "desc"), limit(500)); const unsub = onSnapshot( qy, (snap) => { setAllCheckins(snap.docs.map((d) => ({ id: d.id, ...d.data() }))); setLoading(false); }, () => setLoading(false) ); return () => unsub(); }, []); const filtered = useMemo(() => { const emailNeedle = searchEmail.trim().toLowerCase(); const now = new Date(); const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()); const startOfLast7 = new Date(startOfToday.getTime() - 7 '' 24 '' 60 '' 60 '' 1000); return allCheckins.filter((c) => { const email = (c.email || "").toLowerCase(); // Email search if (emailNeedle && !email.includes(emailNeedle)) return false; // Division if (divisionFilter !== "All" && c.division !== divisionFilter) return false; // Field if (fieldFilter !== "All" && Number(c.field) !== Number(fieldFilter)) return false; // Solo if (soloFilter !== "All" && c.soloUmpire !== soloFilter) return false; // Date const created = c.createdAt?.toDate?.() ?? null; if (dateFilter === "Today") { if (!created || created < startOfToday) return false; } if (dateFilter === "Last7") { if (!created || created < startOfLast7) return false; } return true; }); }, [allCheckins, searchEmail, divisionFilter, fieldFilter, soloFilter, dateFilter]); const toCsv = (rows) => { const header = [ "createdAt", "email", "division", "field", "soloUmpire", "distanceMeters", "lat", "lng", "userId", "docId", ]; const escape = (v) => { const s = String(v ?? ""); // CSV escape: wrap in quotes if contains comma, quote, or newline if (/[",\n]/.test(s)) return <code>"${s.replace(/"/g, '""')}"</code>; return s; }; const lines = [header.join(",")]; for (const c of rows) { const created = c.createdAt?.toDate?.() ?? null; const line = [ created ? created.toISOString() : "", c.email ?? "", c.division ?? "", c.field ?? "", c.soloUmpire ?? "", c.distanceMeters ?? "", c.location?.lat ?? "", c.location?.lng ?? "", c.userId ?? "", c.id ?? "", ].map(escape); lines.push(line.join(",")); } return lines.join("\n"); }; const exportCsv = async () => { try { if (!filtered.length) { Alert.alert("Nothing to export", "Your current filter returns no results."); return; } const csv = toCsv(filtered); const filename = <code>pbysa_checkins_${new Date().toISOString().slice(0, 10)}.csv</code>; const path = FileSystem.cacheDirectory + filename; await FileSystem.writeAsStringAsync(path, csv, { encoding: FileSystem.EncodingType.UTF8, }); if (!(await Sharing.isAvailableAsync())) { Alert.alert( "Sharing not available", <code>CSV saved to:\n${path}\n\n(Sharing isn't available on this device.)</code> ); return; } await Sharing.shareAsync(path, { mimeType: "text/csv", dialogTitle: "Export Check-Ins CSV", }); } catch (e) { Alert.alert("Export failed", e?.message ?? "Could not export CSV."); } }; const logout = async () => { try { await signOut(auth); } catch (e) { Alert.alert("Logout error", e?.message ?? "Could not log out."); } }; return ( <SafeAreaView style={styles.container}> <Text style={styles.title}>Admin • Check-Ins</Text> <Text style={styles.subtitle}> {user.email} • {role} • Showing {filtered.length} / {allCheckins.length} </Text> <View style={styles.card}> <Text style={styles.label}>Search by email</Text> <TextInput value={searchEmail} onChangeText={setSearchEmail} placeholder="type part of an email…" autoCapitalize="none" style={styles.input} /> <Text style={styles.label}>Division</Text> <View style={styles.pickerWrap}> <Picker selectedValue={divisionFilter} onValueChange={setDivisionFilter}> <Picker.Item label="All" value="All" /> {DIVISIONS.map((d) => ( <Picker.Item key={d} label={d} value={d} /> ))} </Picker> </View> <Text style={styles.label}>Field</Text> <View style={styles.pickerWrap}> <Picker selectedValue={fieldFilter} onValueChange={setFieldFilter}> <Picker.Item label="All" value="All" /> {FIELDS.map((f) => ( <Picker.Item key={String(f)} label={String(f)} value={String(f)} /> ))} </Picker> </View> <Text style={styles.label}>Solo</Text> <View style={styles.pickerWrap}> <Picker selectedValue={soloFilter} onValueChange={setSoloFilter}> <Picker.Item label="All" value="All" /> <Picker.Item label="Yes" value="Yes" /> <Picker.Item label="No" value="No" /> </Picker> </View> <Text style={styles.label}>Date</Text> <View style={styles.pickerWrap}> <Picker selectedValue={dateFilter} onValueChange={setDateFilter}> <Picker.Item label="All" value="All" /> <Picker.Item label="Today" value="Today" /> <Picker.Item label="Last 7 days" value="Last7" /> </Picker> </View> <Button title="Export filtered CSV" onPress={exportCsv} /> <View style={{ height: 10 }} /> <Button title="Log Out" onPress={logout} variant="secondary" /> </View> <Text style={[styles.sectionTitle, { marginTop: 14 }]}>Filtered results</Text> {loading ? ( <ActivityIndicator style={{ marginTop: 12 }} /> ) : ( <FlatList data={filtered} keyExtractor={(item) => item.id} ListEmptyComponent={<Text style={styles.hint}>No check-ins match these filters.</Text>} renderItem={({ item }) => ( <View style={styles.listRow}> <Text style={styles.listRowTitle}> {item.email || item.userId} • {item.division} • Field {item.field} • Solo:{" "} {item.soloUmpire} </Text> <Text style={styles.listRowSub}> {formatWhen(item.createdAt)} • {Math.round(item.distanceMeters ?? 0)}m </Text> </View> )} /> )} </SafeAreaView> ); } </syntaxhighlight> ==== Right now the admin screen loads the most recent 500 check-ins and filters locally. This avoids Firestore “composite index” headaches and keeps the MVP simple. ==== If you expect more than that, the next upgrade is server-side filtering (Firestore where() queries + indexes) or a dedicated admin export Cloud Function. If you want, I can also add: * “Export All (last X days)” without loading them all into the app first, using a Cloud Function * Admin-only user promotion screen (pick a user email → set role to admin) === User: add Admin-only user promotion screen === add Admin-only user promotion screen === Assistant: Yep. === Yep. Here’s an Admin-only User Promotion screen that lets an admin: * Search exact email * View the matched user(s) * Set role to admin or umpire This uses your existing users/{uid} docs and your Firestore rules already allow users updates only by admins. ==== Just confirming the key line is present: ==== <syntaxhighlight lang="js">match /users/{uid} { allow read: if isSignedIn() && request.auth.uid == uid; allow create: if isSignedIn() && request.auth.uid == uid; allow update: if isAdmin(); } </syntaxhighlight> ==== Add the missing Firestore functions: ==== <syntaxhighlight lang="js">import { updateDoc, getDocs } from "firebase/firestore"; </syntaxhighlight> (Keep the existing imports you already have.) ==== ### ==== This wraps two admin screens: * Check-Ins (your current one) * Users (new promotion screen) Paste this entire block in place of your existing AdminScreen function. (Inside it, I kept your check-in filtering/export logic as a separate child component called AdminCheckinsPanel so it’s clean.) <syntaxhighlight lang="js">function AdminScreen({ user, role }) { const [tab, setTab] = useState("checkins"); // "checkins" | "users" const logout = async () => { try { await signOut(auth); } catch (e) { Alert.alert("Logout error", e?.message ?? "Could not log out."); } }; return ( <SafeAreaView style={styles.container}> <Text style={styles.title}>Admin</Text> <Text style={styles.subtitle}> {user.email} • {role} </Text> <View style={[styles.card, { paddingBottom: 8 }]}> <View style={styles.adminTabRow}> <Pressable onPress={() => setTab("checkins")} style={[styles.adminTab, tab === "checkins" && styles.adminTabActive]} > <Text style={[styles.adminTabText, tab === "checkins" && styles.adminTabTextActive]}> Check-Ins </Text> </Pressable> <Pressable onPress={() => setTab("users")} style={[styles.adminTab, tab === "users" && styles.adminTabActive]} > <Text style={[styles.adminTabText, tab === "users" && styles.adminTabTextActive]}> Users </Text> </Pressable> </View> <Button title="Log Out" onPress={logout} variant="secondary" /> </View> {tab === "checkins" ? ( <AdminCheckinsPanel /> ) : ( <AdminUsersPanel /> )} </SafeAreaView> ); } </syntaxhighlight> ==== Paste this below AdminScreen (or anywhere in the file beneath imports) : ==== <syntaxhighlight lang="js">function AdminUsersPanel() { const [emailQuery, setEmailQuery] = useState(""); const [loading, setLoading] = useState(false); const [results, setResults] = useState([]); // [{id, email, role}] const searchByExactEmail = async () => { const q = emailQuery.trim().toLowerCase(); if (!q) { Alert.alert("Enter an email", "Type the user's email address to search."); return; } setLoading(true); try { // exact-match query (fast + index-free) const qy = query(collection(db, "users"), where("email", "==", q)); const snap = await getDocs(qy); const found = snap.docs.map((d) => ({ id: d.id, ...d.data() })); setResults(found); if (!found.length) { Alert.alert("No match", "No user found with that email.\n\nThey must create an account first."); } } catch (e) { Alert.alert("Search error", e?.message ?? "Could not search users."); } finally { setLoading(false); } }; const setRoleForUser = async (uid, newRole) => { try { await updateDoc(doc(db, "users", uid), { role: newRole }); setResults((prev) => prev.map((u) => (u.id === uid ? { ...u, role: newRole } : u))); Alert.alert("Updated", <code>Role set to "${newRole}".</code>); } catch (e) { Alert.alert("Update failed", e?.message ?? "Could not update role."); } }; return ( <View style={{ flex: 1 }}> <Text style={[styles.sectionTitle, { marginTop: 14 }]}>User promotion</Text> <View style={styles.card}> <Text style={styles.hint}> Search by exact email (the same email they used to sign up). Then promote/demote. </Text> <Text style={styles.label}>User email</Text> <TextInput value={emailQuery} onChangeText={setEmailQuery} placeholder="umpire@example.com" autoCapitalize="none" keyboardType="email-address" style={styles.input} /> <Button title={loading ? "Searching…" : "Search"} onPress={searchByExactEmail} disabled={loading} /> </View> <Text style={[styles.sectionTitle, { marginTop: 14 }]}>Results</Text> <FlatList data={results} keyExtractor={(item) => item.id} ListEmptyComponent={<Text style={styles.hint}>No results yet.</Text>} renderItem={({ item }) => ( <View style={styles.listRow}> <Text style={styles.listRowTitle}>{item.email || item.id}</Text> <Text style={styles.listRowSub}>Current role: {item.role || "umpire"}</Text> <View style={styles.roleButtonRow}> <Pressable onPress={() => setRoleForUser(item.id, "admin")} style={[styles.roleButton, styles.roleButtonPrimary]} > <Text style={styles.roleButtonTextPrimary}>Make Admin</Text> </Pressable> <Pressable onPress={() => setRoleForUser(item.id, "umpire")} style={[styles.roleButton, styles.roleButtonSecondary]} > <Text style={styles.roleButtonTextSecondary}>Make Umpire</Text> </Pressable> </View> </View> )} /> </View> ); } </syntaxhighlight> ==== Take your current “filters + CSV export + list” admin screen code and wrap it like this: ==== <syntaxhighlight lang="js">function AdminCheckinsPanel() { // paste your existing Admin check-in logic here // (filters, exportCsv, FlatList, etc.) } </syntaxhighlight> Everything inside it can remain basically the same — just remove the outer <SafeAreaView> because AdminScreen already provides that. ==== Add these to your styles object: ==== <syntaxhighlight lang="js">adminTabRow: { flexDirection: "row", gap: 10, marginBottom: 12, }, adminTab: { flex: 1, paddingVertical: 10, borderRadius: 10, borderWidth: 1, borderColor: "#ddd", alignItems: "center", backgroundColor: "#fff", }, adminTabActive: { borderColor: "#111", }, adminTabText: { fontWeight: "700", color: "#666", }, adminTabTextActive: { color: "#111", }, roleButtonRow: { flexDirection: "row", gap: 10, marginTop: 10, }, roleButton: { flex: 1, paddingVertical: 10, borderRadius: 10, alignItems: "center", }, roleButtonPrimary: { backgroundColor: "#111", }, roleButtonSecondary: { backgroundColor: "#fff", borderWidth: 1, borderColor: "#111", }, roleButtonTextPrimary: { color: "#fff", fontWeight: "800", }, roleButtonTextSecondary: { color: "#111", fontWeight: "800", }, </syntaxhighlight> ==== - This search is exact-match email on purpose (reliable + fast + no indexing hassles). If you want “contains” search, we can do a “starts with” approach (needs extra fields/indexing). ==== * Users must have signed up at least once so a users/{uid} doc exists (your signup flow already creates it). If you paste your current AdminScreen (the one with CSV export) here, I can fold it in and return a single clean App.js with everything wired perfectly.
Summary:
Please note that all contributions to freem are considered to be released under the Creative Commons Attribution-ShareAlike 4.0 (see
Freem:Copyrights
for details). If you do not want your writing to be edited mercilessly and redistributed at will, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource.
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)