-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
1229 lines (1122 loc) · 38.8 KB
/
Copy pathserver.ts
File metadata and controls
1229 lines (1122 loc) · 38.8 KB
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import express from 'express';
import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';
import helmet from 'helmet';
import compression from 'compression';
import cors from 'cors';
import rateLimit from 'express-rate-limit';
import { body, validationResult } from 'express-validator';
import { initializeApp } from 'firebase/app';
import {
getFirestore,
collection,
doc,
getDoc,
getDocs,
setDoc,
updateDoc,
addDoc,
deleteDoc,
query,
where,
orderBy,
limit,
DocumentReference,
Query,
DocumentData,
} from 'firebase/firestore';
import { GoogleGenAI } from '@google/genai';
import AdmZip from 'adm-zip';
import dotenv from 'dotenv';
dotenv.config();
// Load Firebase config: env vars take priority (Cloud Run / production).
// Falls back to local firebase-applet-config.json for development.
function loadFirebaseConfig(): Record<string, string> {
// If the primary env var is set, build config entirely from env
if (process.env.FIREBASE_API_KEY) {
console.log('Loading Firebase config from environment variables.');
return {
apiKey: process.env.FIREBASE_API_KEY!,
authDomain: process.env.FIREBASE_AUTH_DOMAIN || '',
projectId: process.env.FIREBASE_PROJECT_ID || '',
storageBucket: process.env.FIREBASE_STORAGE_BUCKET || '',
messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID || '',
appId: process.env.FIREBASE_APP_ID || '',
measurementId: process.env.FIREBASE_MEASUREMENT_ID || '',
firestoreDatabaseId: process.env.FIRESTORE_DATABASE_ID || '(default)',
};
}
// Local development fallback — read firebase-applet-config.json
const configPath = path.join(process.cwd(), 'firebase-applet-config.json');
if (fs.existsSync(configPath)) {
console.log('Loading Firebase config from firebase-applet-config.json.');
return JSON.parse(fs.readFileSync(configPath, 'utf-8'));
}
console.warn(
'No Firebase config found (no env vars, no config file). Firestore will use local fallback.'
);
return {};
}
const firebaseConfig = loadFirebaseConfig();
// Initialize Firebase SDK on server
const firebaseApp = initializeApp(firebaseConfig);
const db =
firebaseConfig.firestoreDatabaseId && firebaseConfig.firestoreDatabaseId !== '(default)'
? getFirestore(firebaseApp, firebaseConfig.firestoreDatabaseId)
: getFirestore(firebaseApp);
let useLocalFallback = false;
const LOCAL_DB_PATH = path.join(process.cwd(), 'local_database.json');
interface LocalDatabase {
users: Record<string, any>;
carbon_logs: Record<string, any>;
eco_actions: Record<string, any>;
offsets: Record<string, any>;
[collectionName: string]: Record<string, any>;
}
function loadLocalDB(): LocalDatabase {
if (fs.existsSync(LOCAL_DB_PATH)) {
try {
return JSON.parse(fs.readFileSync(LOCAL_DB_PATH, 'utf-8')) as LocalDatabase;
} catch (e) {
console.error('Error reading local DB:', e);
}
}
const initial: LocalDatabase = {
users: {
'eco-warrior-kishan': {
id: 'eco-warrior-kishan',
email: 'cshreyash219@gmail.com',
displayName: 'Alex Eco-Warrior',
level: 3,
totalXp: 1450,
currentStreak: 6,
totalCo2Saved: 84.5,
createdAt: '2026-06-17T06:05:58-07:00',
updatedAt: '2026-06-17T06:05:58-07:00',
},
},
carbon_logs: {},
eco_actions: {},
offsets: {},
};
saveLocalDB(initial);
return initial;
}
function saveLocalDB(data: LocalDatabase) {
try {
fs.writeFileSync(LOCAL_DB_PATH, JSON.stringify(data, null, 2), 'utf-8');
} catch (e) {
console.error('Error writing to local DB:', e);
}
}
// Custom DB Wrapper APIs
async function getDocWrapper(
collectionName: string,
docId: string,
docRef: DocumentReference<DocumentData>
) {
if (useLocalFallback) {
const data = loadLocalDB();
const collection = data[collectionName] || {};
const record = collection[docId];
return {
exists: () => !!record,
data: () => record,
};
} else {
try {
const snap = await getDoc(docRef);
return snap;
} catch (err) {
console.warn(
'Firestore getDoc failed, falling back to local DB.',
err instanceof Error ? err.message : String(err)
);
// Fallback silently
const data = loadLocalDB();
const collection = data[collectionName] || {};
const record = collection[docId];
return {
exists: () => !!record,
data: () => record,
};
}
}
}
async function setDocWrapper(
collectionName: string,
docId: string,
docRef: DocumentReference<DocumentData>,
payload: DocumentData
) {
if (useLocalFallback) {
const data = loadLocalDB();
if (!data[collectionName]) {
data[collectionName] = {};
}
data[collectionName][docId] = payload;
saveLocalDB(data);
} else {
try {
await setDoc(docRef, payload);
} catch (err) {
console.warn(
'Firestore setDoc failed, falling back to local DB.',
err instanceof Error ? err.message : String(err)
);
const data = loadLocalDB();
if (!data[collectionName]) {
data[collectionName] = {};
}
data[collectionName][docId] = payload;
saveLocalDB(data);
}
}
}
async function updateDocWrapper(
collectionName: string,
docId: string,
docRef: DocumentReference<DocumentData>,
payload: DocumentData
) {
if (useLocalFallback) {
const data = loadLocalDB();
if (data[collectionName] && data[collectionName][docId]) {
data[collectionName][docId] = {
...data[collectionName][docId],
...payload,
};
saveLocalDB(data);
}
} else {
try {
await updateDoc(docRef, payload);
} catch (err) {
console.warn(
'Firestore updateDoc failed, falling back to local DB.',
err instanceof Error ? err.message : String(err)
);
const data = loadLocalDB();
if (data[collectionName] && data[collectionName][docId]) {
data[collectionName][docId] = {
...data[collectionName][docId],
...payload,
};
saveLocalDB(data);
}
}
}
}
async function deleteDocWrapper(
collectionName: string,
docId: string,
docRef: DocumentReference<DocumentData>
) {
if (useLocalFallback) {
const data = loadLocalDB();
if (data[collectionName] && data[collectionName][docId]) {
delete data[collectionName][docId];
saveLocalDB(data);
}
} else {
try {
await deleteDoc(docRef);
} catch (err) {
console.warn(
'Firestore deleteDoc failed, falling back to local DB.',
err instanceof Error ? err.message : String(err)
);
const data = loadLocalDB();
if (data[collectionName] && data[collectionName][docId]) {
delete data[collectionName][docId];
saveLocalDB(data);
}
}
}
}
async function getDocsWrapper(
collectionName: string,
firestoreQuery: Query<DocumentData>,
localFilter: (items: any[]) => any[]
) {
if (useLocalFallback) {
const data = loadLocalDB();
const collection = data[collectionName] || {};
const list = Object.entries(collection).map(([id, val]) => ({ id, ...val }));
const filtered = localFilter(list);
return {
docs: filtered.map((item) => ({
id: item.id,
data: () => {
const { id, ...rest } = item;
return rest;
},
})),
};
} else {
try {
const snap = await getDocs(firestoreQuery);
return snap;
} catch (err) {
console.warn(
'Firestore getDocs failed, listing from local DB.',
err instanceof Error ? err.message : String(err)
);
const data = loadLocalDB();
const collection = data[collectionName] || {};
const list = Object.entries(collection).map(([id, val]) => ({ id, ...val }));
const filtered = localFilter(list);
return {
docs: filtered.map((item) => ({
id: item.id,
data: () => {
const { id, ...rest } = item;
return rest;
},
})),
};
}
}
}
// Function to safely check link to Firestore
import { getDocFromServer } from 'firebase/firestore';
async function checkFirestoreConnection() {
try {
console.log('Locating Cloud Firestore server on project:', firebaseConfig.projectId);
const testDoc = doc(db, 'users', 'ping');
await Promise.race([
getDocFromServer(testDoc),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('Timeout connecting to Firestore')), 1500)
),
]);
console.log('Connected to Google Cloud Firestore successfully.');
} catch (error) {
console.warn(
"Unable to connect to Google Cloud Firestore (Client is offline or project isn't provisioned yet). Switching seamlessly to locally persisted JSON database."
);
useLocalFallback = true;
}
}
// Run connection check immediately
checkFirestoreConnection();
// Initialize Gemini SDK securely on the server
// Initialize Gemini via Vertex AI.
// Uses Application Default Credentials (ADC) — no API key needed.
// On Cloud Run, ADC automatically uses the attached service account.
// Locally, run: gcloud auth application-default login
const VERTEX_PROJECT =
process.env.VERTEX_PROJECT || firebaseConfig.projectId || 'ecotracker-499709';
const VERTEX_LOCATION = process.env.VERTEX_LOCATION || 'us-central1';
console.log(`Gemini via Vertex AI — project: ${VERTEX_PROJECT}, location: ${VERTEX_LOCATION}`);
const ai = new GoogleGenAI({
vertexai: true,
project: VERTEX_PROJECT,
location: VERTEX_LOCATION,
httpOptions: {
headers: {
'User-Agent': 'ecotracker-server',
},
},
});
const app = express();
const PORT = parseInt(process.env.PORT || '8080', 10);
// Security: hide implementation details
app.disable('x-powered-by');
// Rate limiting setup
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 200, // limit each IP to 200 requests per window
message: { error: 'Too many requests from this IP, please try again later.' },
standardHeaders: true,
legacyHeaders: false,
});
// Apply Security Middlewares
if (process.env.NODE_ENV === 'production') {
app.use(
helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", 'https:'],
styleSrc: ["'self'", "'unsafe-inline'", 'https:'],
imgSrc: ["'self'", 'data:', 'https:'],
connectSrc: ["'self'", 'https:'],
},
},
})
);
} else {
// relaxed for local dev & AI studio preview
app.use(
helmet({
frameguard: false,
crossOriginEmbedderPolicy: false,
crossOriginOpenerPolicy: false,
crossOriginResourcePolicy: false,
contentSecurityPolicy: false,
})
);
}
app.use(cors());
app.use(limiter);
app.use(express.json());
// Performance: compress responses and add caching for static assets in production
app.use(compression());
// Operation type descriptor for error management
enum OperationType {
CREATE = 'create',
UPDATE = 'update',
DELETE = 'delete',
LIST = 'list',
GET = 'get',
WRITE = 'write',
}
function handleBackendFirestoreError(error: unknown, op: OperationType, collPath: string) {
const errPayload = {
error: error instanceof Error ? error.message : String(error),
operationType: op,
path: collPath,
serverTimestamp: new Date().toISOString(),
};
console.error('Firestore Backend Error details:', JSON.stringify(errPayload));
return errPayload;
}
// --- REST API ENDPOINTS ---
// Check server status
app.get('/api/health', (req, res) => {
res.json({ status: 'ok', firebaseDb: firebaseConfig.firestoreDatabaseId || 'no-db' });
});
// 1. User Profile Sync
app.get('/api/profile/:userId', async (req, res) => {
const { userId } = req.params;
try {
const userDocRef = doc(db, 'users', userId);
const userSnap = await getDocWrapper('users', userId, userDocRef);
if (userSnap.exists()) {
return res.json(userSnap.data());
} else {
// First-time user creation logic
const newUser = {
id: userId,
email: req.query.email || 'eco_warrior@example.com',
displayName: req.query.displayName || 'Alex Eco-Warrior',
level: 1,
totalXp: 100,
currentStreak: 1,
totalCo2Saved: 0.0,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
};
await setDocWrapper('users', userId, userDocRef, newUser);
return res.json(newUser);
}
} catch (err) {
const info = handleBackendFirestoreError(err, OperationType.GET, `users/${userId}`);
res.status(500).json({ error: 'Failed to load/provision profile', details: info });
}
});
// Update Profile
app.put(
'/api/profile/:userId',
[
body('displayName').isString().isLength({ min: 1, max: 100 }),
body('level').isInt({ min: 0 }),
body('totalXp').isInt({ min: 0 }),
body('currentStreak').isInt({ min: 0 }),
body('totalCo2Saved').isFloat({ min: 0 }),
],
async (req, res) => {
const { userId } = req.params;
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
try {
const userDocRef = doc(db, 'users', userId);
const userSnap = await getDocWrapper('users', userId, userDocRef);
if (!userSnap.exists()) {
return res.status(404).json({ error: 'User not found' });
}
const existingData = userSnap.data();
const payload = {
...existingData,
displayName: req.body.displayName,
level: req.body.level,
totalXp: req.body.totalXp,
currentStreak: req.body.currentStreak,
totalCo2Saved: req.body.totalCo2Saved,
updatedAt: new Date().toISOString(),
};
await setDocWrapper('users', userId, userDocRef, payload);
res.json(payload);
} catch (err) {
const info = handleBackendFirestoreError(err, OperationType.UPDATE, `users/${userId}`);
res.status(500).json({ error: 'Failed to update profile', details: info });
}
}
);
// 2. Carbon Footprint Logs - Fetch Logs
app.get('/api/carbon/logs/:userId', async (req, res) => {
const { userId } = req.params;
try {
const q = query(
collection(db, 'carbon_logs'),
where('userId', '==', userId),
orderBy('date', 'desc'),
limit(50)
);
const snap = await getDocsWrapper('carbon_logs', q, (items) =>
items
.filter((item) => item.userId === userId)
.sort((a, b) => b.date.localeCompare(a.date))
.slice(0, 50)
);
const logs = snap.docs.map((doc) => ({ id: doc.id, ...doc.data() }));
res.json(logs);
} catch (err) {
const info = handleBackendFirestoreError(err, OperationType.LIST, 'carbon_logs');
res.status(500).json({ error: 'Failed to retrieve carbon logs', details: info });
}
});
// Carbon Footprint Logs - Add Log
app.post(
'/api/carbon/logs',
[
body('userId').isString().notEmpty(),
body('date').isISO8601(),
body('category').isIn(['transportation', 'food', 'electricity', 'waste', 'shopping', 'water']),
body('amount').isFloat({ min: 0 }),
body('details').optional().isString(),
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { userId, date, category, amount, details } = req.body;
// Standard high-accuracy conversion algorithms (kg CO2 equivalent)
let calculatedCo2 = 0;
if (category === 'transportation') {
// Amount in kilometers driven. Baseline: 0.18 kg CO2 per km (gas vehicle)
calculatedCo2 = amount * 0.18;
} else if (category === 'food') {
// Amount in meals. Baseline: 1.5 kg CO2 per meal average
calculatedCo2 = amount * 1.5;
} else if (category === 'electricity') {
// Amount in kWh used. Baseline: 0.45 kg CO2 per kWh
calculatedCo2 = amount * 0.45;
} else if (category === 'waste') {
// Amount in kg of waste thrown away. Baseline: 0.5 kg CO2 per kg
calculatedCo2 = amount * 0.5;
} else if (category === 'shopping') {
// Amount in purchases. Baseline: 15 kg CO2 average per manufacturing item
calculatedCo2 = amount * 15;
} else if (category === 'water') {
// Amount in liters of water used. Baseline: 0.001 kg CO2 per liter (pumping & treatment)
calculatedCo2 = amount * 0.001;
}
try {
const logId = `log-${Date.now()}-${Math.random().toString(36).substring(2, 7)}`;
const logRecord = {
id: logId,
userId,
date,
category,
amount,
calculatedCo2: parseFloat(calculatedCo2.toFixed(2)),
createdAt: new Date().toISOString(),
};
await setDocWrapper('carbon_logs', logId, doc(db, 'carbon_logs', logId), logRecord);
// Add experience points for inputting tracking (20 XP)
const userDocRef = doc(db, 'users', userId);
const userSnap = await getDocWrapper('users', userId, userDocRef);
if (userSnap.exists()) {
const u = userSnap.data();
const baseXP = u.totalXp || 0;
const newXP = baseXP + 20;
// Level threshold is Level * 1000 XP
const newLevel = Math.floor(newXP / 1000) + 1;
await updateDocWrapper('users', userId, userDocRef, {
totalXp: newXP,
level: newLevel,
updatedAt: new Date().toISOString(),
});
}
res.status(201).json(logRecord);
} catch (err) {
const info = handleBackendFirestoreError(err, OperationType.CREATE, 'carbon_logs');
res.status(500).json({ error: 'Failed to save carbon log', details: info });
}
}
);
// Delete Carbon Log
app.delete('/api/carbon/logs/:logId', async (req, res) => {
const { logId } = req.params;
try {
const docRef = doc(db, 'carbon_logs', logId);
await deleteDocWrapper('carbon_logs', logId, docRef);
res.json({ success: true, message: 'Log success deleted' });
} catch (err) {
const info = handleBackendFirestoreError(err, OperationType.DELETE, `carbon_logs/${logId}`);
res.status(500).json({ error: 'Failed to delete carbon log', details: info });
}
});
// 3. User Aggregates & Dashboard Stats
app.get('/api/carbon/stats/:userId', async (req, res) => {
const { userId } = req.params;
try {
const q = query(collection(db, 'carbon_logs'), where('userId', '==', userId));
const snap = await getDocsWrapper('carbon_logs', q, (items) =>
items.filter((item) => item.userId === userId)
);
const logs = snap.docs.map((doc) => doc.data() as any);
// Calculate distributions & summaries
const distribution = {
transportation: 0,
food: 0,
electricity: 0,
waste: 0,
shopping: 0,
water: 0,
};
let totalThisMonth = 0;
const now = new Date();
const currentMonthStr = now.toISOString().substring(0, 7); // "YYYY-MM"
logs.forEach((log) => {
if (log.category && distribution.hasOwnProperty(log.category)) {
distribution[log.category as keyof typeof distribution] += log.calculatedCo2 || 0;
}
if (log.date && log.date.substring(0, 7) === currentMonthStr) {
totalThisMonth += log.calculatedCo2 || 0;
}
});
// Make clean numbers
const finalDistribution = Object.fromEntries(
Object.entries(distribution).map(([k, v]) => [k, parseFloat(v.toFixed(1))])
);
// Fetch Eco Action tasks
const actionQ = query(collection(db, 'eco_actions'), where('userId', '==', userId));
const actionSnap = await getDocsWrapper('eco_actions', actionQ, (items) =>
items.filter((item) => item.userId === userId)
);
const actions = actionSnap.docs.map((doc) => doc.data() as any);
const totalCo2Prevented = actions
.filter(
(a: any) => a.status === 'completed' || (a.completedDates && a.completedDates.length > 0)
)
.reduce(
(sum: number, a: any) =>
sum + a.co2Reduction * (a.completedDates ? a.completedDates.length : 1),
0
);
// Fetch offsets funded
const offsetQ = query(collection(db, 'offsets'), where('userId', '==', userId));
const offsetSnap = await getDocsWrapper('offsets', offsetQ, (items) =>
items.filter((item) => item.userId === userId)
);
const offsets = offsetSnap.docs.map((doc) => doc.data() as any);
const totalOffsetCo2 = offsets.reduce((sum: number, o: any) => sum + (o.co2Offset || 0), 0);
// Generate month-on-month trend data for Recharts (past 6 months)
const monthNames = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
];
const trendMap = new Map<string, number>();
// Seed past 6 months to guarantee values
for (let i = 5; i >= 0; i--) {
const d = new Date();
d.setMonth(d.getMonth() - i);
const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
trendMap.set(key, 0);
}
logs.forEach((log) => {
if (log.date) {
const key = log.date.substring(0, 7);
if (trendMap.has(key)) {
trendMap.set(key, trendMap.get(key)! + (log.calculatedCo2 || 0));
}
}
});
const trendData = Array.from(trendMap.entries()).map(([key, val]) => {
const parts = key.split('-');
const monthIdx = parseInt(parts[1]) - 1;
return {
month: monthNames[monthIdx],
emissions: parseFloat(val.toFixed(1)),
};
});
// Sustainability score algorithm (out of 100). Baseline household: ~1200 kg CO2 per month
// Low emissions is a green high sustainability score!
let sustainabilityScore = 100;
if (totalThisMonth > 0) {
// Logarithmic drop from 1200 kg baseline
const fraction = totalThisMonth / 1500;
sustainabilityScore = Math.max(10, Math.floor(100 - fraction * 90));
} else {
sustainabilityScore = 75; // Neutral starting score
}
// Add extra credit points for Co2 savings
if (totalCo2Prevented > 0) {
sustainabilityScore = Math.min(100, sustainabilityScore + Math.floor(totalCo2Prevented / 5));
}
let rankingRating = 'F';
if (sustainabilityScore >= 90) rankingRating = 'A';
else if (sustainabilityScore >= 75) rankingRating = 'B';
else if (sustainabilityScore >= 55) rankingRating = 'C';
else if (sustainabilityScore >= 35) rankingRating = 'D';
else if (sustainabilityScore >= 20) rankingRating = 'E';
res.json({
sustainabilityScore,
rating: rankingRating,
monthlyEmissions: parseFloat(totalThisMonth.toFixed(1)),
co2Prevented: parseFloat(totalCo2Prevented.toFixed(1)),
co2Offset: parseFloat(totalOffsetCo2.toFixed(1)),
distribution: finalDistribution,
trend: trendData,
});
} catch (err) {
const info = handleBackendFirestoreError(err, OperationType.LIST, 'carbon_logs');
res.status(500).json({ error: 'Failed to calculate sustainability stats', details: info });
}
});
// 4. AI Carbon Coach (Gemini interaction endpoint)
app.post(
'/api/carbon/coach',
[
body('userId').isString().notEmpty(),
body('message').isString().isLength({ min: 1, max: 2000 }),
body('chatHistory').optional().isArray(),
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { userId, message, chatHistory } = req.body;
try {
// 1. Gather latest carbon history logs to inject context
const logQ = query(
collection(db, 'carbon_logs'),
where('userId', '==', userId),
orderBy('date', 'desc'),
limit(15)
);
const snap = await getDocsWrapper('carbon_logs', logQ, (items) =>
items
.filter((item) => item.userId === userId)
.sort((a, b) => b.date.localeCompare(a.date))
.slice(0, 15)
);
const logs = snap.docs.map((doc) => doc.data());
let contextStr = 'User is tracking their daily carbon logs. Recent logs:\n';
logs.forEach((l: any) => {
contextStr += `- Date: ${l.date}, Category: ${l.category}, CO2 emitted: ${l.calculatedCo2}kg\n`;
});
// Construct history array correctly formatted for Gemini chats
const formattedHistory: any[] = [];
if (chatHistory && chatHistory.length > 0) {
chatHistory.slice(-10).forEach((entry: any) => {
formattedHistory.push({
role: entry.role === 'user' ? 'user' : 'model',
parts: [{ text: entry.text || entry.message || '' }],
});
});
}
// Add system prompt instruction to keep Coach friendly, knowledgeable, and green
const systemInstruction =
'You are the EcoTracker AI Carbon Coach, powered by Google Gemini. ' +
'Your mission is to help individuals analyze, track, and systematically reduce their carbon footprint. ' +
'Provide scientific yet supportive, actionable advice. Highlight little green choices ' +
'applicable to their profile. Use clean formatting, bold key advice, and bullet points. ' +
'Greet them enthusiastically and keep motivation high!';
// Invoke Gemini via Vertex AI
const response = await ai.models.generateContent({
model: 'gemini-2.0-flash-001',
contents: [
{
role: 'user',
parts: [
{
text: `SYSTEM_CONTEXT: ${systemInstruction}\nUSER_CARBON_DATA:\n${contextStr}\n\nUser Question: ${message}`,
},
],
},
],
});
res.json({ reply: response.text });
} catch (err) {
console.error('Gemini Coach model error:', err);
res.status(500).json({ error: 'Carbon Coach took a walk in the woods. Please try again.' });
}
}
);
// 5. Intelligent AI Assessment (Report Endpoint)
app.post('/api/carbon/assessment', [body('userId').isString().notEmpty()], async (req, res) => {
const { userId } = req.body;
try {
const q = query(collection(db, 'carbon_logs'), where('userId', '==', userId));
const snap = await getDocs(q);
const logs = snap.docs.map((doc) => doc.data());
if (logs.length === 0) {
return res.json({
report:
'### 🌱 Start Tracking!\n\nNo carbon log entries detected yet. Submit your first travel or utility log in the dashboard to kickstart your personalized AI carbon assessment!',
ranking: 'N/A',
});
}
let summaryStr = `User has ${logs.length} footprint entries. Logs breakdown:\n`;
logs.forEach((l: any) => {
summaryStr += `- Category: ${l.category}, Amount: ${l.amount}, CO2: ${l.calculatedCo2} kg on Date: ${l.date}\n`;
});
const aiPrompt =
'Provide a rigorous, actionable personal carbon assessment. Include: ' +
"1. An executive summary rating the user as 'Eco-Apprentice', 'Carbon Stabilizer', or 'Active Eco-Warrior'. " +
'2. Identification of their single highest carbon consumer category. ' +
'3. Exactly 3 strategic micro-actions they can implement this week to save at least 20kg of CO2. ' +
'4. Sound optimistic and scientific. ' +
'Write in clear, beautiful Markdown with elegant spacers.';
const response = await ai.models.generateContent({
model: 'gemini-2.0-flash-001',
contents: [
{ role: 'user', parts: [{ text: `${aiPrompt}\n\nUser Carbon Data:\n${summaryStr}` }] },
],
});
res.json({ report: response.text });
} catch (err) {
console.error('Gemini Assessment error:', err);
res.status(500).json({ error: 'Failed to generate AI Carbon Profile Assessment.' });
}
});
// 6. Eco Actions (Task & Habit tracker)
app.get('/api/eco-actions/:userId', async (req, res) => {
const { userId } = req.params;
try {
const q = query(collection(db, 'eco_actions'), where('userId', '==', userId));
const snap = await getDocsWrapper('eco_actions', q, (items) =>
items.filter((item) => item.userId === userId)
);
const actions = snap.docs.map((doc) => ({ id: doc.id, ...doc.data() }));
// Seed default actions if user doesn't have any yet
if (actions.length === 0) {
const defaults = [
{
title: 'Switch to LED lightbulbs',
category: 'energy',
co2Reduction: 8.5,
status: 'active',
},
{
title: 'Carpool or ride public transit',
category: 'transport',
co2Reduction: 12.0,
status: 'active',
},
{
title: 'Unplug standby vampire electronics',
category: 'energy',
co2Reduction: 3.2,
status: 'active',
},
{
title: 'Switch to a vegan or vegetarian diet',
category: 'food',
co2Reduction: 15.6,
status: 'active',
},
{
title: 'Compost food waste & paper leftovers',
category: 'waste',
co2Reduction: 4.8,
status: 'active',
},
{
title: 'Limit shower times to 5 minutes',
category: 'water',
co2Reduction: 2.1,
status: 'active',
},
];
for (const item of defaults) {
const aid = `act-${Date.now()}-${Math.random().toString(36).substring(2, 7)}`;
const record = {
id: aid,
userId,
title: item.title,
category: item.category,
co2Reduction: item.co2Reduction,
status: item.status,
completedDates: [],
createdAt: new Date().toISOString(),
};
await setDocWrapper('eco_actions', aid, doc(db, 'eco_actions', aid), record);
actions.push(record);
}
}
res.json(actions);
} catch (err) {
const info = handleBackendFirestoreError(err, OperationType.LIST, 'eco_actions');
res.status(500).json({ error: 'Failed to load/provision Eco Actions', details: info });
}
});
app.post(
'/api/eco-actions/complete',
[
body('actionId').isString().notEmpty(),
body('userId').isString().notEmpty(),
body('date').isISO8601(),
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { actionId, userId, date } = req.body;
try {
const actionDocRef = doc(db, 'eco_actions', actionId);
const snap = await getDocWrapper('eco_actions', actionId, actionDocRef);
if (!snap.exists()) {
return res.status(404).json({ error: 'Action item not found' });
}
const data = snap.data();
const completedDates = data.completedDates || [];
if (completedDates.includes(date)) {
return res.status(400).json({ error: 'Action already completed for this date' });
}
const updatedDates = [...completedDates, date];
await updateDocWrapper('eco_actions', actionId, actionDocRef, {
completedDates: updatedDates,
status: updatedDates.length >= 7 ? 'completed' : 'active',
});
// Reward user with experience points (e.g., 50 XP per green action completed)
const userDocRef = doc(db, 'users', userId);
const userSnap = await getDocWrapper('users', userId, userDocRef);
if (userSnap.exists()) {
const u = userSnap.data();
const currentStreak = u.currentStreak || 1;
const baseXP = u.totalXp || 0;
const additionalXP = 50 + currentStreak * 5; // streak multiplier bonus
const newXP = baseXP + additionalXP;
const newLevel = Math.floor(newXP / 1000) + 1;
const newTotalCo2Saved = (u.totalCo2Saved || 0) + data.co2Reduction;
await updateDocWrapper('users', userId, userDocRef, {
totalXp: newXP,
level: newLevel,
totalCo2Saved: parseFloat(newTotalCo2Saved.toFixed(1)),
updatedAt: new Date().toISOString(),