-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
2153 lines (1904 loc) · 79 KB
/
Copy pathserver.js
File metadata and controls
2153 lines (1904 loc) · 79 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
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const path = require('path');
const crypto = require('crypto');
const axios = require('axios');
const session = require('express-session');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const { Pool } = require('pg');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const app = express();
const PORT = process.env.PORT || 3000;
// Cheese Blockchain Configuration
const CHEESE_API_URL = process.env.CHEESE_BLOCKCHAIN_API_URL || 'http://165.22.252.113:8080';
const TREASURY_WALLET = process.env.FARMERS_CONSENSUS_TREASURY_WALLET || '0x045D4e61757a873DAF5F3B59CCeD9f2585643cc3';
const REGISTRATION_REWARD = parseInt(process.env.REGISTRATION_REWARD_AMOUNT) || 10;
// Revenue Configuration
const TRANSACTION_FEE = parseFloat(process.env.TRANSACTION_FEE) || 0.5; // NCH per registration
const PREMIUM_TIER_FEE = parseFloat(process.env.PREMIUM_TIER_FEE) || 2.0; // NCH for premium features
const HARVEST_VERIFICATION_FEE = parseFloat(process.env.HARVEST_VERIFICATION_FEE) || 1.5; // NCH per verification
const BUYER_REGISTRATION_FEE = parseFloat(process.env.BUYER_REGISTRATION_FEE) || 1.0; // NCH per buyer registration
const BUYER_PREMIUM_FEE = parseFloat(process.env.BUYER_PREMIUM_FEE) || 3.0; // NCH for buyer premium features
const BUYER_MATCHING_FEE = parseFloat(process.env.BUYER_MATCHING_FEE) || 0.25; // NCH per successful farmer-buyer match
// Token Price Configuration (mock prices, would connect to real price feeds in production)
const TOKEN_PRICES = {
NCH: {
USD: 0.05, // $0.05 per NCH
PHP: 2.80, // ₱2.80 per NCH
EUR: 0.045, // €0.045 per NCH
BTC: 0.0000008, // ~0.0000008 BTC per NCH
ETH: 0.000015 // ~0.000015 ETH per NCH
},
updateInterval: 60000 // Update prices every 60 seconds
};
// Current token prices (will be updated periodically)
let currentTokenPrices = { ...TOKEN_PRICES.NCH };
// Function to update token prices (would connect to price APIs in production)
function updateTokenPrices() {
// In production, this would fetch from price APIs like CoinGecko, CoinMarketCap, etc.
// For now, we'll use the mock prices with small random fluctuations to simulate live prices
const fluctuation = 0.02; // 2% max fluctuation
Object.keys(currentTokenPrices).forEach(currency => {
const randomChange = (Math.random() - 0.5) * fluctuation;
currentTokenPrices[currency] = TOKEN_PRICES.NCH[currency] * (1 + randomChange);
});
}
// Update prices periodically
setInterval(updateTokenPrices, TOKEN_PRICES.updateInterval);
// Admin Configuration
const ADMIN_USERNAME = process.env.ADMIN_USERNAME || 'admin';
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || 'secure_password_change_this';
const ADMIN_SESSION_SECRET = process.env.ADMIN_SESSION_SECRET || 'change_this_to_secure_random_string';
// JWT Configuration for user authentication
const JWT_SECRET = process.env.JWT_SECRET || 'change_this_to_secure_random_string_for_jwt';
const JWT_EXPIRES_IN = '7d'; // Token expiration time
// Production safety: refuse to start with default secrets
if (process.env.NODE_ENV === 'production') {
const defaults = [
['ADMIN_PASSWORD', ADMIN_PASSWORD, 'secure_password_change_this'],
['ADMIN_SESSION_SECRET', ADMIN_SESSION_SECRET, 'change_this_to_secure_random_string'],
['JWT_SECRET', JWT_SECRET, 'change_this_to_secure_random_string_for_jwt']
];
for (const [name, value, defaultVal] of defaults) {
if (value === defaultVal) {
console.error(`❌ CRITICAL: ${name} is using default value in production. Set it in environment variables.`);
process.exit(1);
}
}
}
// Input sanitization helper — strips HTML tags to prevent XSS
function sanitizeInput(str) {
if (typeof str !== 'string') return str;
return str.replace(/[<>"'&]/g, (char) => {
const entities = { '<': '<', '>': '>', '"': '"', "'": ''', '&': '&' };
return entities[char] || char;
});
}
// PostgreSQL Database Configuration
let pool = null;
let databaseAvailable = false;
async function initializeDatabasePool() {
if (process.env.DATABASE_URL) {
try {
pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: process.env.NODE_ENV === 'production' ? { rejectUnauthorized: false } : false,
max: 20, // Maximum number of clients in the pool
idleTimeoutMillis: 30000, // Close idle clients after 30 seconds
connectionTimeoutMillis: 10000, // Increased to 10 seconds for Railway cold starts
});
// Test connection immediately
await pool.query('SELECT NOW()');
databaseAvailable = true;
console.log('✅ Database pool created and connected successfully');
return true;
} catch (error) {
console.error('❌ Failed to create database pool:', error.message);
pool = null;
databaseAvailable = false;
// In production, fail hard if database is not available
if (process.env.NODE_ENV === 'production') {
console.error('❌ CRITICAL: Database connection failed in production mode');
console.error('❌ Application cannot start without database in production');
throw new Error('Database connection required in production');
}
console.warn('⚠️ DATABASE_URL set but connection failed, running in in-memory mode');
return false;
}
} else {
console.warn('⚠️ DATABASE_URL not set');
// In production, fail hard if DATABASE_URL is not set
if (process.env.NODE_ENV === 'production') {
console.error('❌ CRITICAL: DATABASE_URL not set in production mode');
console.error('❌ Application cannot start without DATABASE_URL in production');
throw new Error('DATABASE_URL required in production');
}
console.warn('⚠️ Running in in-memory mode (development only)');
return false;
}
}
// Critical database query helper (fails hard in production if database unavailable)
async function safeQuery(text, params) {
if (!pool || !databaseAvailable) {
const errorMsg = 'Database not available';
console.error('❌', errorMsg);
if (process.env.NODE_ENV === 'production') {
throw new Error(`${errorMsg} - Query cannot be executed: ${text.substring(0, 50)}...`);
}
console.warn('⚠️ Returning null for query in development mode');
return null;
}
try {
const result = await pool.query(text, params);
return result;
} catch (error) {
console.error('❌ Database query error:', error.message);
console.error('❌ Query:', text.substring(0, 100));
if (process.env.NODE_ENV === 'production') {
// In production, log the full error but don't crash for individual queries
console.error('❌ Full error details:', error);
}
throw error; // Re-throw to let caller handle it
}
}
// Database schema initialization
async function initializeDatabaseSchema() {
if (!pool || !databaseAvailable) {
console.warn('⚠️ Database not available, skipping schema initialization');
return false;
}
try {
console.log('🔄 Initializing database schema...');
const fs = require('fs');
const schemaPath = path.join(__dirname, 'schema.sql');
if (fs.existsSync(schemaPath)) {
const schema = fs.readFileSync(schemaPath, 'utf8');
// Execute entire schema as a single transaction to handle dependencies correctly
const client = await pool.connect();
try {
await client.query('BEGIN');
await client.query(schema);
// Dynamically add verification_status column if it doesn't exist
await client.query(`
ALTER TABLE farmers_registrations
ADD COLUMN IF NOT EXISTS verification_status VARCHAR(50) DEFAULT 'Pending'
`);
await client.query('COMMIT');
console.log('✅ Database schema initialized successfully');
return true;
} catch (err) {
await client.query('ROLLBACK');
// If schema already exists, that's okay
if (err.message.includes('already exists')) {
console.log('✅ Database schema already exists');
return true;
}
console.error('❌ Schema execution error:', err.message);
throw err;
} finally {
client.release();
}
} else {
console.warn('⚠️ schema.sql not found, skipping schema initialization');
return false;
}
} catch (error) {
console.error('❌ Schema initialization error:', error.message);
if (process.env.NODE_ENV === 'production') {
console.error('❌ CRITICAL: Schema initialization failed in production');
throw error;
}
console.warn('⚠️ Continuing without schema initialization');
return false;
}
}
// Complete database initialization (blocking for production)
async function initializeDatabase() {
try {
console.log('🔄 Starting database initialization...');
// Initialize pool
const poolReady = await initializeDatabasePool();
if (poolReady) {
// Initialize schema
await initializeDatabaseSchema();
// Verify tables exist
const tablesCheck = await safeQuery(`
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public'
`);
if (tablesCheck && tablesCheck.rows.length > 0) {
console.log(`✅ Database verified with ${tablesCheck.rows.length} tables`);
console.log('📋 Tables:', tablesCheck.rows.map(r => r.table_name).join(', '));
}
console.log('✅ Database initialization complete');
return true;
} else {
console.warn('⚠️ Database not available, running in limited mode');
return false;
}
} catch (error) {
console.error('❌ Database initialization failed:', error.message);
if (process.env.NODE_ENV === 'production') {
console.error('❌ CRITICAL: Cannot start application in production without database');
throw error;
}
console.warn('⚠️ Continuing without database (development mode)');
return false;
}
}
// Middleware setup (before database initialization)
app.use(helmet({
contentSecurityPolicy: false, // Disabled because we use inline scripts and CDN resources
crossOriginEmbedderPolicy: false
}));
app.use(cors({ origin: true, credentials: true }));
app.use(express.json());
app.use(express.static(path.join(__dirname), {
setHeaders: (res, path) => {
if (path.endsWith('.html') || path.endsWith('sw.js') || path.endsWith('manifest.json') || path.endsWith('.js') || path.endsWith('.css')) {
res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
res.setHeader('Pragma', 'no-cache');
res.setHeader('Expires', '0');
res.setHeader('Surrogate-Control', 'no-store');
}
}
}));
// Rate limiters
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 10, // 10 attempts per window
message: { success: false, error: 'Too many login attempts. Please try again in 15 minutes.' },
standardHeaders: true,
legacyHeaders: false
});
const apiLimiter = rateLimit({
windowMs: 60 * 1000, // 1 minute
max: 60, // 60 requests per minute
message: { success: false, error: 'Too many requests. Please slow down.' }
});
app.use('/api/', apiLimiter);
// Trust proxy (required for Railway / Render / Heroku reverse proxies)
// Without this, secure cookies are not set behind HTTPS proxies
if (process.env.NODE_ENV === 'production') {
app.set('trust proxy', 1);
}
// Session Middleware
app.use(session({
secret: ADMIN_SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
secure: process.env.NODE_ENV === 'production', // HTTPS only in production
sameSite: 'lax', // Prevents CSRF while allowing same-site navigation
httpOnly: true, // Prevent XSS from reading session cookie
maxAge: 3600000 // 1 hour
}
}));
// Authentication Middleware
function requireAdmin(req, res, next) {
if (req.session.isAdmin) {
next();
} else {
res.status(401).json({ success: false, error: 'Admin authentication required' });
}
}
// JWT Authentication Middleware for regular users
function requireAuth(req, res, next) {
const token = req.header('Authorization')?.replace('Bearer ', '');
if (!token) {
return res.status(401).json({ success: false, error: 'No token provided' });
}
try {
const decoded = jwt.verify(token, JWT_SECRET);
req.user = decoded;
next();
} catch (error) {
return res.status(401).json({ success: false, error: 'Invalid or expired token' });
}
}
// JWT Helper Functions
function generateToken(userId, userType) {
return jwt.sign(
{ userId, userType },
JWT_SECRET,
{ expiresIn: JWT_EXPIRES_IN }
);
}
function verifyToken(token) {
try {
return jwt.verify(token, JWT_SECRET);
} catch (error) {
return null;
}
}
// Password Hashing Helper
async function hashPassword(password) {
const saltRounds = 10;
return await bcrypt.hash(password, saltRounds);
}
async function verifyPassword(password, hash) {
return await bcrypt.compare(password, hash);
}
// In-memory fallback for revenue tracking (used if database fails)
let inMemoryRevenue = {
totalRevenue: 0,
transactionCount: 0,
feeBreakdown: {
transactionFees: 0,
premiumFees: 0,
verificationFees: 0,
buyerRegistrationFees: 0,
buyerPremiumFees: 0,
buyerMatchingFees: 0
},
dailyRevenue: [],
transactions: []
};
// In-memory fallback for crop registrations
let inMemoryRegistrations = [];
function inMemoryRevenueFallback(type, amount, metadata) {
const today = new Date().toISOString().split('T')[0];
inMemoryRevenue.totalRevenue += amount;
inMemoryRevenue.transactionCount++;
inMemoryRevenue.feeBreakdown[`${type}Fees`] += amount;
const existingDay = inMemoryRevenue.dailyRevenue.find(day => day.date === today);
if (existingDay) {
existingDay.revenue += amount;
existingDay.count++;
} else {
inMemoryRevenue.dailyRevenue.push({
date: today,
revenue: amount,
count: 1
});
}
inMemoryRevenue.transactions.push({
type,
amount,
timestamp: new Date().toISOString(),
metadata
});
}
// Blockchain Integration Helper Functions
async function createBlockchainTransaction(registrationData) {
try {
const response = await axios.post(`${CHEESE_API_URL}/api/notary/stamp`, {
hash: generateRegistrationHash(registrationData),
fileName: `farmer-${registrationData.id}`,
category: 'crop_registration',
metadata: {
type: 'farmers_consensus',
farmerId: registrationData.id,
farmerName: registrationData.farmerName,
province: registrationData.province,
municipality: registrationData.municipality,
barangay: registrationData.barangay,
vegetableId: registrationData.vegetableId,
areaHa: registrationData.areaHa,
expectedYield: registrationData.expectedYieldTons,
plantingDate: registrationData.plantingDate,
harvestDate: registrationData.harvestDate
}
});
return response.data;
} catch (error) {
console.error('Blockchain transaction failed:', error);
throw new Error('Failed to record on blockchain');
}
}
// Revenue Tracking Functions
async function recordRevenue(type, amount, metadata = {}) {
try {
if (!pool) {
console.warn('⚠️ Database not available, using in-memory fallback');
inMemoryRevenueFallback(type, amount, metadata);
return;
}
const client = await pool.connect();
try {
await client.query('BEGIN');
// Record individual transaction
await client.query(
'INSERT INTO revenue_transactions (transaction_type, amount, related_id, metadata, transaction_timestamp) VALUES ($1, $2, $3, $4, CURRENT_TIMESTAMP)',
[type, amount, metadata.related_id || null, JSON.stringify(metadata)]
);
// Update daily revenue
const today = new Date().toISOString().split('T')[0];
await client.query(`
INSERT INTO daily_revenue (date, total_revenue, transaction_count)
VALUES ($1, $2, 1)
ON CONFLICT (date) DO UPDATE SET
total_revenue = daily_revenue.total_revenue + EXCLUDED.total_revenue,
transaction_count = daily_revenue.transaction_count + 1
`, [today, amount]);
// Update specific fee type in daily revenue
let feeColumn = '';
switch(type) {
case 'transaction': feeColumn = 'transaction_fees'; break;
case 'premium': feeColumn = 'premium_fees'; break;
case 'verification': feeColumn = 'verification_fees'; break;
case 'buyerRegistration': feeColumn = 'buyer_registration_fees'; break;
case 'buyerPremium': feeColumn = 'buyer_premium_fees'; break;
case 'buyerMatching': feeColumn = 'buyer_matching_fees'; break;
}
if (feeColumn) {
await client.query(`
UPDATE daily_revenue
SET ${feeColumn} = COALESCE(${feeColumn}, 0) + $1
WHERE date = $2
`, [amount, today]);
}
await client.query('COMMIT');
console.log(`💰 Revenue recorded in database: ${amount} NCH (${type})`);
} catch (error) {
await client.query('ROLLBACK');
throw error;
} finally {
client.release();
}
} catch (error) {
console.error('Database revenue recording failed:', error);
// Fallback to in-memory if database fails
console.warn('Using in-memory fallback for revenue tracking');
inMemoryRevenueFallback(type, amount, metadata);
}
}
function generateRegistrationHash(data) {
const dataString = `${data.id}-${data.farmerName}-${data.province}-${data.vegetableId}-${data.areaHa}-${data.plantingDate}`;
return crypto.createHash('sha256').update(dataString).digest('hex');
}
// Philippine geography (PSGC) — provinces, cities/municipalities, barangays
const psgcGeo = require('./lib/psgc-geo');
app.get('/api/geo/provinces', (req, res) => {
try {
res.json({ success: true, data: psgcGeo.getProvinces() });
} catch (err) {
console.error('PSGC provinces error:', err);
res.status(500).json({ success: false, error: 'Failed to load provinces' });
}
});
app.get('/api/geo/municipalities', (req, res) => {
const { regCode, provCode } = req.query;
if (!regCode || !provCode) {
return res.status(400).json({ success: false, error: 'regCode and provCode are required' });
}
try {
res.json({ success: true, data: psgcGeo.getMunicipalities(regCode, provCode) });
} catch (err) {
console.error('PSGC municipalities error:', err);
res.status(500).json({ success: false, error: 'Failed to load municipalities' });
}
});
app.get('/api/geo/barangays', (req, res) => {
const { munCityCode } = req.query;
if (!munCityCode) {
return res.status(400).json({ success: false, error: 'munCityCode is required' });
}
try {
res.json({ success: true, data: psgcGeo.getBarangays(munCityCode) });
} catch (err) {
console.error('PSGC barangays error:', err);
res.status(500).json({ success: false, error: 'Failed to load barangays' });
}
});
// API Routes
// Health check
app.get('/api/health', async (req, res) => {
let blockchainConnected = false;
try {
const bcRes = await axios.get(`${CHEESE_API_URL}/api/health`, { timeout: 3000 });
blockchainConnected = bcRes.status === 200;
} catch (_) { /* blockchain unreachable */ }
res.json({
status: databaseAvailable ? 'healthy' : 'degraded',
service: 'farmers-consensus-api',
database_connected: databaseAvailable,
database_status: databaseAvailable ? 'available' : 'unavailable',
blockchain_connected: blockchainConnected,
cheese_api_url: CHEESE_API_URL,
environment: process.env.NODE_ENV || 'development',
timestamp: new Date().toISOString()
});
});
// Register farmer crop (with blockchain integration)
app.post('/api/farmers/register', async (req, res) => {
try {
const registrationData = req.body;
// Validate required fields
if (!registrationData.farmerName || !registrationData.province || !registrationData.vegetableId) {
return res.status(400).json({
success: false,
error: 'Missing required fields'
});
}
// Sanitize string inputs to prevent XSS
registrationData.farmerName = sanitizeInput(registrationData.farmerName);
registrationData.contact = sanitizeInput(registrationData.contact || '');
registrationData.province = sanitizeInput(registrationData.province);
registrationData.municipality = sanitizeInput(registrationData.municipality || '');
registrationData.barangay = sanitizeInput(registrationData.barangay || '');
registrationData.vegetableId = sanitizeInput(registrationData.vegetableId);
// Check database availability (only fail hard in production)
if (!databaseAvailable && process.env.NODE_ENV === 'production') {
console.error('❌ Database not available for farmer registration');
return res.status(503).json({
success: false,
error: 'Database not available. Please try again later.',
databaseStatus: 'unavailable'
});
}
// Calculate fees and rewards
const isPremium = registrationData.premiumTier || false;
const totalFee = TRANSACTION_FEE + (isPremium ? PREMIUM_TIER_FEE : 0);
const netReward = REGISTRATION_REWARD - totalFee;
// Create blockchain transaction (with dev fallback)
let blockchainResult = { txid: 'FC-TX-' + Date.now(), hash: 'FC-HASH-' + Date.now() };
try {
blockchainResult = await createBlockchainTransaction(registrationData);
} catch (bcError) {
console.warn('⚠️ Blockchain transaction failed, using dev mock receipt:', bcError.message);
}
const farmerId = registrationData.id || `FC-${Date.now()}`;
const verificationStatus = registrationData.verificationStatus || 'Pending';
if (databaseAvailable) {
try {
await safeQuery(
`INSERT INTO farmers_registrations
(farmer_id, farmer_name, contact, province, municipality, barangay,
vegetable_id, area_sqm, area_ha, expected_yield_tons,
planting_date, harvest_date, blockchain_transaction_id, blockchain_hash, premium_tier, verification_status)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16)
ON CONFLICT (farmer_id) DO NOTHING`,
[
farmerId,
registrationData.farmerName,
registrationData.contact || '',
registrationData.province,
registrationData.municipality || '',
registrationData.barangay || '',
registrationData.vegetableId,
registrationData.areaSqm || 0,
registrationData.areaHa || 0,
registrationData.expectedYieldTons || 0,
registrationData.plantingDate || null,
registrationData.harvestDate || null,
blockchainResult.txid || null,
blockchainResult.hash || null,
isPremium,
verificationStatus
]
);
console.log('✅ Farmer saved to database:', registrationData.farmerName);
} catch (dbError) {
console.error('❌ Failed to save farmer to database:', dbError.message);
return res.status(500).json({
success: false,
error: 'Failed to save registration to database',
details: dbError.message
});
}
} else {
console.warn('⚠️ Saving farmer registration in-memory');
const inMemoryReg = {
id: farmerId,
farmerName: registrationData.farmerName,
contact: registrationData.contact || '',
province: registrationData.province,
municipality: registrationData.municipality || '',
barangay: registrationData.barangay || '',
vegetableId: registrationData.vegetableId,
areaSqm: parseFloat(registrationData.areaSqm) || 0,
areaHa: parseFloat(registrationData.areaHa) || 0,
expectedYieldTons: parseFloat(registrationData.expectedYieldTons) || 0,
plantingDate: registrationData.plantingDate || null,
harvestDate: registrationData.harvestDate || null,
blockchainTxId: blockchainResult.txid || null,
blockchainHash: blockchainResult.hash || null,
premiumTier: isPremium,
verificationStatus: verificationStatus,
timestamp: new Date().toISOString()
};
inMemoryRegistrations.unshift(inMemoryReg);
}
// Record revenue for Cheese Blockchain
recordRevenue('transaction', TRANSACTION_FEE, {
farmerId: registrationData.id,
farmerName: registrationData.farmerName,
transactionId: blockchainResult.txid
});
if (isPremium) {
recordRevenue('premium', PREMIUM_TIER_FEE, {
farmerId: registrationData.id,
farmerName: registrationData.farmerName,
features: 'advanced_analytics, priority_verification'
});
}
// Return success with blockchain receipt and fee breakdown
res.json({
success: true,
message: 'Farmer registration recorded on blockchain',
registration: registrationData,
blockchainReceipt: {
transactionId: blockchainResult.txid,
hash: blockchainResult.hash,
timestamp: new Date().toISOString()
},
financial: {
grossReward: REGISTRATION_REWARD,
transactionFee: TRANSACTION_FEE,
premiumFee: isPremium ? PREMIUM_TIER_FEE : 0,
totalFees: totalFee,
netReward: netReward,
currency: 'NCH'
},
reward: {
amount: netReward,
currency: 'NCH',
note: 'Net reward after Cheese Blockchain fees'
}
});
} catch (error) {
console.error('Registration error:', error);
res.status(500).json({
success: false,
error: 'Registration failed'
});
}
});
// Register buyer (with blockchain integration)
app.post('/api/buyers/register', async (req, res) => {
try {
const buyerData = req.body;
// Validate required fields
if (!buyerData.buyerName || !buyerData.companyName || !buyerData.province) {
return res.status(400).json({
success: false,
error: 'Missing required fields'
});
}
// Sanitize string inputs to prevent XSS
buyerData.buyerName = sanitizeInput(buyerData.buyerName);
buyerData.companyName = sanitizeInput(buyerData.companyName);
buyerData.province = sanitizeInput(buyerData.province);
if (buyerData.email) buyerData.email = sanitizeInput(buyerData.email);
if (buyerData.phone) buyerData.phone = sanitizeInput(buyerData.phone);
if (buyerData.businessType) buyerData.businessType = sanitizeInput(buyerData.businessType);
if (buyerData.annualVolume) buyerData.annualVolume = sanitizeInput(buyerData.annualVolume);
if (buyerData.preferredProvinces) buyerData.preferredProvinces = sanitizeInput(buyerData.preferredProvinces);
// Calculate fees
const isPremium = buyerData.premiumTier || false;
const totalFee = BUYER_REGISTRATION_FEE + (isPremium ? BUYER_PREMIUM_FEE : 0);
// Create blockchain transaction for buyer registration
const blockchainResult = await createBlockchainTransaction({
...buyerData,
category: 'buyer_registration'
});
// Save buyer to database
if (pool) {
try {
await pool.query(
`INSERT INTO buyers
(name, company_name, province, premium_tier, blockchain_txid, registration_date,
contact_email, phone, business_type, annual_volume, preferred_provinces, metadata)
VALUES ($1, $2, $3, $4, $5, CURRENT_TIMESTAMP, $6, $7, $8, $9, $10, $11)`,
[
buyerData.buyerName,
buyerData.companyName,
buyerData.province,
isPremium,
blockchainResult.txid,
buyerData.email || null,
buyerData.phone || null,
buyerData.businessType || null,
buyerData.annualVolume || null,
buyerData.preferredProvinces || null,
JSON.stringify(buyerData)
]
);
console.log('Buyer saved to database:', buyerData.buyerName);
} catch (dbError) {
console.error('Failed to save buyer to database:', dbError);
// Continue with registration even if database save fails
}
} else {
console.warn('⚠️ Database not available, skipping buyer database save');
}
// Record revenue for Cheese Blockchain
recordRevenue('buyerRegistration', BUYER_REGISTRATION_FEE, {
buyerId: buyerData.id,
buyerName: buyerData.buyerName,
companyName: buyerData.companyName,
transactionId: blockchainResult.txid
});
if (isPremium) {
recordRevenue('buyerPremium', BUYER_PREMIUM_FEE, {
buyerId: buyerData.id,
buyerName: buyerData.buyerName,
features: 'priority_matching, advanced_analytics, direct_farmer_access'
});
}
// Return success with blockchain receipt and fee breakdown
res.json({
success: true,
message: 'Buyer registration recorded on blockchain',
registration: buyerData,
blockchainReceipt: {
transactionId: blockchainResult.txid,
hash: blockchainResult.hash,
timestamp: new Date().toISOString()
},
financial: {
registrationFee: BUYER_REGISTRATION_FEE,
premiumFee: isPremium ? BUYER_PREMIUM_FEE : 0,
totalFees: totalFee,
currency: 'NCH',
note: 'Buyer registration fees support Cheese Blockchain operations'
}
});
} catch (error) {
console.error('Buyer registration error:', error);
res.status(500).json({
success: false,
error: 'Buyer registration failed'
});
}
});
// Record farmer-buyer match (generates matching fee)
app.post('/api/matches/create', async (req, res) => {
try {
const matchData = req.body;
// Validate required fields
if (!matchData.farmerId || !matchData.buyerId || !matchData.vegetableId) {
return res.status(400).json({
success: false,
error: 'Missing required fields'
});
}
// Sanitize string inputs to prevent XSS
matchData.farmerId = sanitizeInput(matchData.farmerId);
matchData.buyerId = sanitizeInput(matchData.buyerId);
matchData.vegetableId = sanitizeInput(matchData.vegetableId);
if (matchData.status) matchData.status = sanitizeInput(matchData.status);
if (matchData.deliveryTerms) matchData.deliveryTerms = sanitizeInput(matchData.deliveryTerms);
if (matchData.paymentTerms) matchData.paymentTerms = sanitizeInput(matchData.paymentTerms);
// Create blockchain transaction for the match
const blockchainResult = await createBlockchainTransaction({
...matchData,
category: 'farmer_buyer_match'
});
// Save match to database
if (pool) {
try {
await pool.query(
`INSERT INTO matches
(farmer_id, buyer_id, vegetable_id, quantity, match_value, blockchain_txid, match_date,
status, delivery_terms, payment_terms, metadata)
VALUES ($1, $2, $3, $4, $5, $6, CURRENT_TIMESTAMP, $7, $8, $9, $10)`,
[
matchData.farmerId,
matchData.buyerId,
matchData.vegetableId,
matchData.quantity || null,
matchData.matchValue || null,
blockchainResult.txid,
matchData.status || 'pending',
matchData.deliveryTerms || null,
matchData.paymentTerms || null,
JSON.stringify(matchData)
]
);
console.log('Match saved to database:', matchData.farmerId, '-', matchData.buyerId);
} catch (dbError) {
console.error('Failed to save match to database:', dbError);
// Continue with matching even if database save fails
}
} else {
console.warn('⚠️ Database not available, skipping match database save');
}
// Record matching fee revenue
recordRevenue('buyerMatching', BUYER_MATCHING_FEE, {
farmerId: matchData.farmerId,
buyerId: matchData.buyerId,
vegetableId: matchData.vegetableId,
quantity: matchData.quantity,
matchValue: matchData.matchValue,
transactionId: blockchainResult.txid
});
res.json({
success: true,
message: 'Farmer-buyer match recorded on blockchain',
match: matchData,
blockchainReceipt: {
transactionId: blockchainResult.txid,
hash: blockchainResult.hash,
timestamp: new Date().toISOString()
},
financial: {
matchingFee: BUYER_MATCHING_FEE,
currency: 'NCH'
}
});
} catch (error) {
console.error('Match creation error:', error);
res.status(500).json({
success: false,
error: 'Match creation failed'
});
}
});
// Get blockchain status
app.get('/api/blockchain/status', async (req, res) => {
try {
const response = await axios.get(`${CHEESE_API_URL}/api/health`);
res.json({
success: true,
blockchain: response.data
});
} catch (error) {
res.status(500).json({
success: false,
error: 'Unable to connect to Cheese Blockchain'
});
}
});
// Get registration statistics (from blockchain)
// GET all farmer registrations (for frontend hydration from DB)
app.get('/api/farmers/registrations', async (req, res) => {
try {
let registrations = [];
if (databaseAvailable) {
const result = await safeQuery(
`SELECT farmer_id as id, farmer_name as "farmerName", contact, province,
municipality, barangay, vegetable_id as "vegetableId",
area_sqm as "areaSqm", area_ha as "areaHa",
expected_yield_tons as "expectedYieldTons",
planting_date as "plantingDate", harvest_date as "harvestDate",
registration_timestamp as timestamp,
blockchain_transaction_id as "blockchainTxId",
verification_status as "verificationStatus"
FROM farmers_registrations
ORDER BY registration_timestamp DESC
LIMIT 500`,
[]
);
registrations = result ? result.rows : [];
} else {
registrations = JSON.parse(JSON.stringify(inMemoryRegistrations));
}
// Data Privacy: Mask PII if request is not from an authenticated admin session
if (!req.session.isAdmin) {
registrations.forEach(r => {
if (r.farmerName) {
r.farmerName = r.farmerName.split(' ')[0];
}
if (r.contact) {
const len = r.contact.length;
if (len >= 7) {
r.contact = r.contact.substring(0, 4) + '****' + r.contact.substring(len - 3);
} else {
r.contact = '****';
}
}
});
}
res.json({