File size: 5,874 Bytes
ed9f15f |
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 176 177 178 179 180 181 182 183 |
/**
* Firebase Service - Handle data persistence and authentication
*/
import { initializeApp } from 'https://www.gstatic.com/firebasejs/10.7.1/firebase-app.js';
import { getFirestore, collection, addDoc, serverTimestamp } from 'https://www.gstatic.com/firebasejs/10.7.1/firebase-firestore.js';
import { getAuth, signInWithEmailAndPassword, signInWithPopup, GoogleAuthProvider, signOut, onAuthStateChanged } from 'https://www.gstatic.com/firebasejs/10.7.1/firebase-auth.js';
// Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyAYbKEaWT99sDO7bUC76LcXKDRK3BBMZ00",
authDomain: "embryo-one.firebaseapp.com",
projectId: "embryo-one",
storageBucket: "embryo-one.firebasestorage.app",
messagingSenderId: "23510355257",
appId: "1:23510355257:web:0ae7edce822704820f6ce8",
measurementId: "G-140V7Z1GRK"
};
// Initialize Firebase
let app;
let db;
let auth;
try {
app = initializeApp(firebaseConfig);
db = getFirestore(app);
auth = getAuth(app);
console.log('Firebase initialized successfully');
} catch (error) {
console.error('Firebase initialization error:', error);
}
/**
* Save embryo grading results to Firebase
* @param {Object} resultData - The grading result data
* @returns {Promise<string>} - Document ID
*/
export async function saveGradingResults(resultData) {
try {
const docRef = await addDoc(collection(db, 'embryo_gradings'), {
...resultData,
createdAt: serverTimestamp()
});
console.log('Results saved with ID:', docRef.id);
return docRef.id;
} catch (error) {
console.error('Error saving results:', error);
throw error;
}
}
/**
* Prepare embryo data for saving
* @param {Array} embryos - Array of embryo objects
* @param {string} mainImageUrl - URL of the main uploaded image
* @param {Array} results - Array of evaluation results
* @param {Object} remarks - Object mapping index to remarks
* @returns {Object} - Formatted data for Firebase
*/
export function prepareEmbryoData(embryos, mainImageUrl, results = [], remarks = {}) {
console.log('Preparing embryo data for Firebase:');
console.log('- Embryos count:', embryos.length);
console.log('- Results count:', results.length);
console.log('- Remarks:', remarks);
return {
mainImage: mainImageUrl,
embryos: embryos.map((embryo, index) => {
// Get result for this embryo
const resultData = results[index];
const result = resultData?.result;
const embryoData = {
embryoNumber: index + 1,
croppedImage: embryo.imageData,
predictedGrade: result?.grade || embryo.grade || 'Unknown',
actualGrade: embryo.actualGrade || '',
quality: result?.quality || embryo.quality || 'Unknown',
confidence: result?.confidence || embryo.confidence || 0,
poorGoodConfidence: result?.poorGoodConfidence || 0,
remarks: remarks[index] || embryo.remarks || '',
isManual: embryo.isManual || false,
detectionConfidence: embryo.confidence || 0
};
console.log(`Embryo ${index + 1} data:`, {
grade: embryoData.predictedGrade,
quality: embryoData.quality,
remarks: embryoData.remarks
});
return embryoData;
}),
totalEmbryos: embryos.length,
timestamp: new Date().toISOString()
};
}
/**
* Check if Firebase is initialized
* @returns {boolean}
*/
export function isFirebaseReady() {
return db !== null && db !== undefined && auth !== null && auth !== undefined;
}
/**
* Authentication Functions
*/
/**
* Sign in with email and password
* @param {string} email - User email
* @param {string} password - User password
* @returns {Promise<Object>} - User credential
*/
export async function signIn(email, password) {
try {
const userCredential = await signInWithEmailAndPassword(auth, email, password);
console.log('User signed in:', userCredential.user.email);
return userCredential;
} catch (error) {
console.error('Sign in error:', error);
throw error;
}
}
/**
* Sign in with Google
* @returns {Promise<Object>} - User credential
*/
export async function signInWithGoogle() {
try {
const provider = new GoogleAuthProvider();
provider.setCustomParameters({
prompt: 'select_account'
});
const userCredential = await signInWithPopup(auth, provider);
console.log('User signed in with Google:', userCredential.user.email);
return userCredential;
} catch (error) {
console.error('Google sign in error:', error);
throw error;
}
}
/**
* Sign out current user
* @returns {Promise<void>}
*/
export async function signOutUser() {
try {
await signOut(auth);
console.log('User signed out');
} catch (error) {
console.error('Sign out error:', error);
throw error;
}
}
/**
* Get current user
* @returns {Object|null} - Current user or null
*/
export function getCurrentUser() {
return auth?.currentUser || null;
}
/**
* Listen to authentication state changes
* @param {Function} callback - Callback function to execute on auth state change
* @returns {Function} - Unsubscribe function
*/
export function onAuthChange(callback) {
if (!auth) {
console.error('Auth not initialized');
return () => {};
}
return onAuthStateChanged(auth, callback);
}
|