import express from 'express'; import { MongoClient } from 'mongodb'; import { google } from 'googleapis'; import crypto from 'crypto'; import dotenv from 'dotenv'; // For loading environment variables import fs from 'fs'; // For reading the Google credentials JSON file dotenv.config(); // Load .env variables const app = express(); const port = 3000; app.use(express.json()); // Mongo URI from .env const uri = process.env.MONGO_URI; const client = new MongoClient(uri); const dbName = 'inventory'; const collectionName = 'items'; // Load Google credentials from the key.json file const googleCredentialsPath = process.env.GOOGLE_CREDENTIALS_PATH; const googleApisKey = JSON.parse(fs.readFileSync(googleCredentialsPath, 'utf8')); // Initialize Google Sheets API authentication const auth = new google.auth.JWT( googleApisKey.client_email, null, googleApisKey.private_key, ['https://www.googleapis.com/auth/spreadsheets'] ); const spreadsheetId = process.env.SPREADSHEET_ID; const sheets = google.sheets({ version: 'v4', auth }); const range = 'Sheet1!A:H'; // Connect to MongoDB async function connectDB() { try { await client.connect(); console.log('Connected to MongoDB!'); } catch (err) { console.error('Error connecting to MongoDB:', err); process.exit(1); } } connectDB(); // Generate Serial Number function generateSerialNumber() { return `Jadupc${crypto.randomInt(100000, 999999)}`; } // Route to upload device details app.post('/upload', async (req, res) => { const { Verient, mac, os, status, customerAddress, customerNumber, customerName } = req.body; if (!Verient || !mac || !os) { return res.status(400).send('Missing required fields: Verient, mac, os, or status'); } // Check if device already exists in database try { const db = client.db(dbName); const collection = db.collection(collectionName); const existingDevice = await collection.findOne({ mac }); if (existingDevice) { return res.status(400).send('Device with the same MAC address is already registered'); } // Generate serial number const serialNumber = generateSerialNumber(); const newItem = { serialNumber, Verient, mac, os, status: status || 'registered', customerAddress, customerNumber, customerName, }; await collection.insertOne(newItem); console.log('Item successfully added to MongoDB'); try { // Append data to Google Sheets const response = await sheets.spreadsheets.values.append({ spreadsheetId, range, valueInputOption: 'USER_ENTERED', requestBody: { values: [[serialNumber, Verient, mac, os, status, customerAddress, customerNumber, customerName]], }, }); console.log('Data successfully appended to Google Sheets'); res.status(200).send('Device uploaded and added to MongoDB and Google Sheets. Serial Number: ' + serialNumber); } catch (err) { console.error('Error appending to Google Sheets:', err); res.status(500).send('Error uploading to Google Sheets'); } } catch (err) { console.error('Error inserting item into MongoDB:', err); res.status(500).send('Error uploading item to MongoDB'); } }); // Route to check device status app.get('/check-status', async (req, res) => { const { mac, serialNumber } = req.query; if (!mac && !serialNumber) { return res.status(400).send('MAC or Serial Number required'); } try { const db = client.db(dbName); const collection = db.collection(collectionName); const device = await collection.findOne(mac ? { mac } : { serialNumber }); if (!device) { return res.status(200).json({ serialNumber: null, status: 'new' // Default status if not found }); } res.status(200).json({ serialNumber: device.serialNumber, status: device.status // Default status if missing }); } catch (err) { res.status(500).send('Error checking device status'); } }); // Start the server app.listen(port, () => console.log(`Server running on http://localhost:${port}`));