Skip to content

Latest commit

 

History

History
214 lines (162 loc) · 6.09 KB

File metadata and controls

214 lines (162 loc) · 6.09 KB

Firebase Setup Guide

This guide walks you through connecting Altruist to a real Firebase project.

Prerequisites

  • A Google account
  • Node.js 18+ installed
  • Firebase CLI (npm install -g firebase-tools)

Step 1: Create a Firebase Project

  1. Go to Firebase Console
  2. Click "Create a project"
  3. Name it altruist (or any name you prefer)
  4. Enable/disable Google Analytics as desired
  5. Click "Create project"

Step 2: Enable Firebase Services

Authentication

  1. In the Firebase Console, go to Build → Authentication
  2. Click "Get started"
  3. Enable Email/Password provider
  4. (Optional) Enable Google sign-in provider

Cloud Firestore

  1. Go to Build → Firestore Database
  2. Click "Create database"
  3. Choose Start in production mode
  4. Select your preferred region (e.g., europe-west2 for London)
  5. Click "Enable"

Deploy Security Rules

After creating the database, deploy the security rules:

firebase login
firebase init firestore
# When prompted, use the existing firestore.rules file
firebase deploy --only firestore:rules

Step 3: Get Firebase Config

  1. In the Firebase Console, click the gear iconProject settings
  2. Under "Your apps", click the web icon (</>)
  3. Register your app with nickname altruist-web
  4. Copy the firebaseConfig object

Step 4: Configure Environment Variables

Create a .env.local file in the project root:

VITE_FIREBASE_API_KEY=your-api-key
VITE_FIREBASE_AUTH_DOMAIN=your-project.firebaseapp.com
VITE_FIREBASE_PROJECT_ID=your-project-id
VITE_FIREBASE_STORAGE_BUCKET=your-project.appspot.com
VITE_FIREBASE_MESSAGING_SENDER_ID=your-sender-id
VITE_FIREBASE_APP_ID=your-app-id

Important: Never commit .env.local to version control. It is already in .gitignore.

Step 5: Seed Firestore Data

To populate your database with the mock charity data for development:

// Run this from a Node.js script or Firebase Cloud Function
import { db } from './src/lib/firebase';
import { MOCK_CHARITIES, MOCK_ONS_DATA, MOCK_SURVEYS } from './src/data/mock-data';
import { collection, doc, setDoc } from 'firebase/firestore';

async function seedData() {
  // Seed charities
  for (const charity of MOCK_CHARITIES) {
    await setDoc(doc(db, 'charities', charity.id), charity);
  }
  
  // Seed ONS data
  for (const ons of MOCK_ONS_DATA) {
    await setDoc(doc(db, 'ons_regional_data', ons.lsoaCode), ons);
  }
  
  // Seed surveys
  for (const survey of MOCK_SURVEYS) {
    await setDoc(doc(db, 'surveys', survey.id), survey);
  }
  
  console.log('✅ Data seeded successfully');
}

seedData();

Step 6: Set Up Cloud Functions (Optional)

For production features like ONS data sync and vector search:

firebase init functions
cd functions
npm install

ONS Data Sync Function

import { onSchedule } from 'firebase-functions/v2/scheduler';
import { getFirestore } from 'firebase-admin/firestore';

const db = getFirestore();

const ONS_IMD_ENDPOINT = 
  'https://services1.arcgis.com/ESMARspQHYMw9BZ9/arcgis/rest/services/IMD_2019/FeatureServer/0/query?where=1%3D1&outFields=lsoa11cd,lsoa11nm,IMDScore,IMDDecil&f=json&resultRecordCount=1000';

export const syncONSData = onSchedule('every 30 days', async () => {
  const response = await fetch(ONS_IMD_ENDPOINT);
  const { features } = await response.json();
  
  const batch = db.batch();
  for (const feature of features) {
    const ref = db.collection('ons_regional_data').doc(feature.attributes.lsoa11cd);
    batch.set(ref, {
      lsoaCode: feature.attributes.lsoa11cd,
      lsoaName: feature.attributes.lsoa11nm,
      imdScore: feature.attributes.IMDScore,
      imdDecile: feature.attributes.IMDDecil,
      lastUpdated: new Date().toISOString(),
    });
  }
  await batch.commit();
});

Step 7: Set Up Vector Search (Optional)

For semantic charity search using Vertex AI:

  1. Enable the Vertex AI API in Google Cloud Console
  2. Install the Firebase Vector Search extension:
    firebase ext:install googlecloud/firestore-vector-search
  3. Configure the extension to use the charities collection
  4. Set the text field to a combination of missionStatement + tags + operatingRegions
  5. The extension will automatically generate embeddings when charity documents are created/updated

Alternative: Pinecone

If you prefer Pinecone for vector search:

npm install @pinecone-database/pinecone
import { Pinecone } from '@pinecone-database/pinecone';

const pc = new Pinecone({ apiKey: process.env.PINECONE_API_KEY });
const index = pc.index('altruist-charities');

// Query example
const results = await index.query({
  vector: await generateEmbedding(userQuery),
  topK: 10,
  includeMetadata: true,
});

Step 8: Firebase GenKit for Impact Narratives (Optional)

For AI-generated impact narratives:

npm install @genkit-ai/core @genkit-ai/firebase @genkit-ai/vertexai
import { genkit } from 'genkit';
import { vertexAI } from '@genkit-ai/vertexai';

const ai = genkit({ plugins: [vertexAI({ location: 'europe-west2' })] });

export const generateNarrative = ai.defineFlow(
  'generateImpactNarrative',
  async (input: { metrics: any; donationAmount: number }) => {
    const response = await ai.generate({
      model: 'gemini-2.0-flash',
      prompt: `Generate a compelling impact narrative for a £${input.donationAmount} donation. 
               Metrics: ${JSON.stringify(input.metrics)}. 
               Make it personal, specific, and quantitative.`,
    });
    return response.text();
  }
);

Troubleshooting

"Permission denied" errors

  • Ensure your user document in Firestore has the correct role field
  • Check that security rules are deployed: firebase deploy --only firestore:rules

Firebase config not loading

  • Verify .env.local file exists and contains correct values
  • Restart the dev server after changing environment variables
  • Ensure variable names start with VITE_

Build errors

  • Run npm install to ensure all dependencies are installed
  • Check Node.js version is 18+: node --version