Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
442 lines (395 loc) · 15.2 KB
/
Copy pathserver.js
File metadata and controls
442 lines (395 loc) · 15.2 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
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { User, Product, Order } = require('./models');
const artisanRoutes = require('./artisanRoutes');
const app = express();
app.set('trust proxy', 1);
app.use(cors());
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ limit: '50mb', extended: true }));
app.use('/api/artisan', artisanRoutes);
app.get('/api/health', (_req, res) => {
res.json({ ok: true, service: 'artisan-api' });
});
app.use((err, req, res, next) => {
if (err?.type === 'entity.too.large') {
return res.status(413).json({ error: 'Request too large. Try a smaller product photo.' });
}
if (err instanceof SyntaxError && err.status === 400 && 'body' in err) {
return res.status(400).json({ error: 'Invalid JSON in request body.' });
}
next(err);
});
const JWT_SECRET = process.env.JWT_SECRET || 'super_secret_artisan_key_2026';
const PAYEE_NAME = process.env.PAYEE_NAME || "Artisan's Compass";
const PAYMENT_QR_IMAGE_URL = process.env.PAYMENT_QR_IMAGE_URL || '';
const PAYEE_UPI_ID = process.env.PAYEE_UPI_ID || '';
const authenticateToken = (req, res, next) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) return res.status(401).json({ error: 'Access denied' });
try {
const verified = jwt.verify(token, JWT_SECRET);
req.user = verified;
next();
} catch (err) {
res.status(403).json({ error: 'Invalid token' });
}
};
mongoose.connect(process.env.MONGO_URI)
.then(async () => {
console.log('Connected to Artisan Database');
mongoose.connection.db.collection('orders').dropIndex('transactionId_1').catch(err => {});
try {
const result = await User.updateMany(
{ role: 'artisan', $or: [ { upi_id: { $exists: false } }, { upi_id: '' } ] },
{ $set: { upi_id: 'dummy@upi', upi_name: 'Dummy Artisan' } }
);
if (result.modifiedCount > 0) {
console.log(`Backfilled ${result.modifiedCount} preexisting artisans with dummy UPI credentials.`);
}
} catch (err) {
console.error('Failed to backfill preexisting artisans:', err);
}
try {
const regionsList = ['Karnataka', 'Tamil Nadu', 'Keralam', 'Andhra Pradesh', 'Telangana'];
const products = await Product.find({});
let updatedCount = 0;
for (const p of products) {
if (!p.region || !regionsList.some(r => r.toLowerCase() === p.region.toLowerCase())) {
p.region = regionsList[Math.floor(Math.random() * regionsList.length)];
await p.save();
updatedCount++;
}
}
if (updatedCount > 0) {
console.log(`Backfilled ${updatedCount} products with random southern regions.`);
}
} catch (err) {
console.error('Failed to backfill product regions:', err);
}
})
.catch(err => console.error('Database connection failed:', err));
const buildUpiIntent = ({ upiId, payeeName, amountInr, transactionId }) => {
const params = new URLSearchParams({
pa: upiId,
pn: payeeName,
am: Number(amountInr).toFixed(2),
cu: 'INR',
tn: `Order ${transactionId}`,
tr: transactionId,
});
return `upi://pay?${params.toString()}`;
};
const getQrImageUrl = (total, transactionId) => {
if (PAYMENT_QR_IMAGE_URL) {
return PAYMENT_QR_IMAGE_URL;
}
if (PAYEE_UPI_ID) {
const upiIntent = buildUpiIntent({
upiId: PAYEE_UPI_ID,
payeeName: PAYEE_NAME,
amountInr: total,
transactionId,
});
return `https://api.qrserver.com/v1/create-qr-code/?size=320x320&data=${encodeURIComponent(upiIntent)}`;
}
return null;
};
app.post('/api/register', async (req, res) => {
try {
const { name, email, password, role, upi_id, upi_name } = req.body;
const existingUser = await User.findOne({ email });
if (existingUser) return res.status(400).json({ error: 'Email already exists' });
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);
const newUser = new User({
name,
email,
password: hashedPassword,
role: role || 'customer',
upi_id: role === 'artisan' ? (upi_id || '') : '',
upi_name: role === 'artisan' ? (upi_name || '') : ''
});
await newUser.save();
const token = jwt.sign({ id: newUser._id }, JWT_SECRET, { expiresIn: '7d' });
res.status(201).json({
token,
user: {
id: newUser._id,
name: newUser.name,
email: newUser.email,
role: newUser.role,
upi_id: newUser.upi_id,
upi_name: newUser.upi_name,
address1: newUser.address1 || '',
address2: newUser.address2 || '',
address3: newUser.address3 || ''
}
});
} catch (err) {
res.status(500).json({ error: 'Signup failed' });
}
});
app.post('/api/login', async (req, res) => {
try {
const { email, password, role } = req.body;
const user = await User.findOne({ email });
if (!user) return res.status(400).json({ error: 'User not found' });
if (role && user.role !== role) {
return res.status(400).json({ error: `Incorrect profile type. This account is registered as a ${user.role}.` });
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) return res.status(400).json({ error: 'Invalid credentials' });
const token = jwt.sign({ id: user._id }, JWT_SECRET, { expiresIn: '7d' });
res.json({
token,
user: {
id: user._id,
name: user.name,
email: user.email,
role: user.role,
upi_id: user.upi_id,
upi_name: user.upi_name,
address1: user.address1 || '',
address2: user.address2 || '',
address3: user.address3 || ''
}
});
} catch (err) {
res.status(500).json({ error: 'Login failed' });
}
});
app.get('/api/products', async (req, res) => {
try {
const { style, region } = req.query;
let query = {};
if (style && style !== 'All') {
query.$or = [
{ form: style },
{ region: style }
];
}
if (region && region !== 'All') {
query.region = { $regex: new RegExp('^' + region.trim() + '$', 'i') };
}
const products = await Product.find(query);
const mappedProducts = products.map(p => ({
_id: p._id,
title: p.name,
price: p.price,
imageUrl: p.imageUrl || 'https://images.unsplash.com/photo-1514432324607-a09d9b4aefdd?q=80&w=600',
description: p.description || `${p.form || 'Handcrafted'} from ${p.region || 'India'}.`,
style: p.form || 'Boho',
artisan: p.artisan || 'Independent Artisan',
artisanId: {
_id: p._id,
brandName: p.artisan || 'Independent Artisan',
bio: `${p.artisan || 'Independent Artisan'} from ${p.region || 'India'}.`,
aesthetic: p.form || 'Boho'
},
region: p.region,
form: p.form,
stock: p.stock
}));
res.json(mappedProducts);
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Failed to fetch products' });
}
});
// Create orders grouped by artisan and return payment details with UPI links
app.post('/api/orders', authenticateToken, async (req, res) => {
try {
const { items } = req.body;
if (!items || items.length === 0) {
return res.status(400).json({ error: 'Cart is empty' });
}
// Group items by artisan
const groups = {};
for (const item of items) {
const artisanName = item.artisan || (item.artisanId && item.artisanId.brandName) || 'Independent Artisan';
if (!groups[artisanName]) {
groups[artisanName] = [];
}
groups[artisanName].push(item);
}
const results = [];
for (const artisanName of Object.keys(groups)) {
const itemsInGroup = groups[artisanName];
const groupTotal = itemsInGroup.reduce((sum, item) => sum + item.price, 0);
// Find artisan UPI details by matching product's artisan name to User.name case-insensitively and trimmed
const trimmedArtisanName = String(artisanName || '').trim();
const artisanUser = await User.findOne({
name: { $regex: new RegExp('^' + trimmedArtisanName.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + '$', 'i') },
role: 'artisan'
});
let upiId;
let payeeName;
if (artisanUser && artisanUser.upi_id && artisanUser.upi_id.trim() !== '') {
// Use the artisan's own registered UPI credentials
upiId = artisanUser.upi_id.trim();
payeeName = (artisanUser.upi_name && artisanUser.upi_name.trim()) ? artisanUser.upi_name.trim() : artisanUser.name;
console.log(`[Orders] Using artisan UPI: pa=${upiId}, pn=${payeeName} for artisan "${artisanName}"`);
} else if (process.env.PAYEE_UPI_ID) {
// Fall back to global env UPI only if artisan has none configured
upiId = process.env.PAYEE_UPI_ID;
payeeName = process.env.PAYEE_NAME || artisanName;
console.warn(`[Orders] Artisan "${artisanName}" has no UPI configured — falling back to env PAYEE_UPI_ID.`);
} else {
// Last resort placeholder so QR still renders but payment will be rejected
upiId = 'dummy@upi';
payeeName = artisanName;
console.error(`[Orders] No UPI found for artisan "${artisanName}" and no PAYEE_UPI_ID env set.`);
}
const transactionId = `TXN-${Date.now()}-${Math.random().toString(36).slice(2, 8).toUpperCase()}`;
// Build upi link: upi://pay?pa=payee_address&pn=payee_name&am=amount&cu=currency_code&tn=transaction_note
const params = new URLSearchParams({
pa: upiId,
pn: payeeName,
am: Number(groupTotal).toFixed(2),
cu: 'INR',
tn: `Order ${transactionId}`
});
const upiLink = `upi://pay?${params.toString()}`;
const newOrder = new Order({
userId: req.user.id,
products: itemsInGroup.map(item => item._id),
total: groupTotal,
status: 'Pending',
});
await newOrder.save();
results.push({
orderId: newOrder._id,
transactionId,
amountInr: groupTotal,
payeeName,
upiId,
upiLink,
items: itemsInGroup
});
}
res.status(201).json({
orders: results,
message: 'Orders created successfully grouped by artisan',
});
} catch (err) {
console.error('Order creation failed:', err);
res.status(500).json({ error: 'Could not start payment' });
}
});
// User confirms they completed UPI payment
app.post('/api/orders/:orderId/confirm', authenticateToken, async (req, res) => {
try {
const { utr } = req.body;
if (!utr || utr.trim() === '') {
return res.status(400).json({ error: 'UTR number is required to confirm payment.' });
}
const order = await Order.findOne({ _id: req.params.orderId, userId: req.user.id });
if (!order) return res.status(404).json({ error: 'Order not found' });
order.status = 'Paid';
order.utr = utr.trim();
await order.save();
res.json({
paid: true,
transactionId: `TXN-${order._id.toString().toUpperCase()}`,
utr: order.utr,
message: 'Order marked as paid with UTR. Seller will verify payment.',
});
} catch (err) {
res.status(500).json({ error: 'Could not confirm order' });
}
});
// Get list of purchased items for a customer
app.get('/api/orders/my-purchased', authenticateToken, async (req, res) => {
try {
const orders = await Order.find({ userId: req.user.id, status: 'Paid' }).populate('products');
const products = [];
orders.forEach(order => {
order.products.forEach(p => {
if (p) {
products.push({
_id: p._id,
title: p.name,
price: p.price,
imageUrl: p.imageUrl,
description: p.description,
style: p.form || 'Boho',
artisan: p.artisan,
purchaseDate: order.updatedAt || order.createdAt
});
}
});
});
res.json(products);
} catch (err) {
res.status(500).json({ error: 'Failed to fetch purchased items' });
}
});
// Edit user profile details (Name, Email, Password, UPI ID, UPI Name, Address 1/2/3)
app.put('/api/user/profile', authenticateToken, async (req, res) => {
try {
const { name, email, password, upi_id, upi_name, address1, address2, address3 } = req.body;
const user = await User.findById(req.user.id);
if (!user) return res.status(404).json({ error: 'User not found' });
if (email && email !== user.email) {
const existingUser = await User.findOne({ email });
if (existingUser) return res.status(400).json({ error: 'Email already in use' });
user.email = email;
}
if (name) user.name = name;
if (password) {
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, salt);
}
if (user.role === 'artisan') {
if (upi_id !== undefined) user.upi_id = upi_id;
if (upi_name !== undefined) user.upi_name = upi_name;
}
if (address1 !== undefined) user.address1 = address1;
if (address2 !== undefined) user.address2 = address2;
if (address3 !== undefined) user.address3 = address3;
await user.save();
res.json({
message: 'Profile updated successfully',
user: {
id: user._id,
name: user.name,
email: user.email,
role: user.role,
upi_id: user.upi_id,
upi_name: user.upi_name,
address1: user.address1 || '',
address2: user.address2 || '',
address3: user.address3 || ''
}
});
} catch (err) {
res.status(500).json({ error: 'Failed to update profile' });
}
});
app.post('/api/seed-india', async (req, res) => {
try {
await Product.deleteMany({});
const indiaProducts = [
{ name: 'Kalamkari Block Print Saree', artisan: 'Lakshmi V.', price: 85, region: 'South India', form: 'Block Printing' },
{ name: 'Kutch Embroidery Bag', artisan: 'Bhavna P.', price: 45, region: 'Gujarat', form: 'Weaving' },
{ name: 'Dhokra Brass Elephant', artisan: 'Ramu D.', price: 120, region: 'Central India', form: 'Brasswork' },
{ name: 'Blue Pottery Vase', artisan: 'Aarav S.', price: 55, region: 'Rajasthan', form: 'Ceramics' },
{ name: 'Kashmiri Walnut Wood Box', artisan: 'Tariq M.', price: 95, region: 'Kashmir', form: 'Wood Carving' },
{ name: 'Assam Silk Stole', artisan: 'Meena B.', price: 70, region: 'North East', form: 'Weaving' },
{ name: 'Bankura Terracotta Horse', artisan: 'Joy G.', price: 35, region: 'East India', form: 'Terracotta' },
];
await Product.insertMany(indiaProducts);
res.json({ message: 'Indian Database Seeded!' });
} catch (error) {
res.status(500).json({ error: 'Seeding failed' });
}
});
app.listen(3000, '0.0.0.0', () => {
console.log('Artisan Server running on port 3000');
});