summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--index.js131
-rw-r--r--package.json1
2 files changed, 120 insertions, 12 deletions
diff --git a/index.js b/index.js
index bd50051..017c4c8 100644
--- a/index.js
+++ b/index.js
@@ -2,8 +2,9 @@ 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
+import dotenv from 'dotenv';
+import fs from 'fs';
+import cors from 'cors';
dotenv.config(); // Load .env variables
@@ -11,6 +12,7 @@ const app = express();
const port = 3000;
app.use(express.json());
+app.use(cors());
// Mongo URI from .env
const uri = process.env.MONGO_URI;
@@ -47,12 +49,10 @@ async function connectDB() {
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;
@@ -60,7 +60,6 @@ app.post('/upload', async (req, res) => {
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);
@@ -70,8 +69,7 @@ app.post('/upload', async (req, res) => {
if (existingDevice) {
return res.status(400).send('Device with the same MAC address is already registered');
}
-
- // Generate serial number
+
const serialNumber = generateSerialNumber();
const newItem = {
@@ -80,22 +78,21 @@ app.post('/upload', async (req, res) => {
mac,
os,
status: status || 'registered',
- customerAddress,
- customerNumber,
customerName,
+ customerNumber,
+ customerAddress,
};
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]],
+ values: [[serialNumber, Verient, mac, os, status, customerName, customerNumber, customerAddress]],
},
});
console.log('Data successfully appended to Google Sheets');
@@ -110,7 +107,6 @@ app.post('/upload', async (req, res) => {
}
});
-// Route to check device status
app.get('/check-status', async (req, res) => {
const { mac, serialNumber } = req.query;
@@ -139,5 +135,116 @@ app.get('/check-status', async (req, res) => {
}
});
+
+app.get('/check-sn', async (req, res) => {
+ const { serialNumber } = req.query;
+
+ if (!serialNumber) {
+ return res.status(400).json({ error: 'Serial Number required' });
+ }
+
+ try {
+ const db = client.db(dbName);
+ const collection = db.collection(collectionName);
+ const device = await collection.findOne({ serialNumber });
+
+ if (!device) {
+ return res.status(200).json({
+ serialNumber: null,
+ status: '',
+ customerName:null , // Default status if not found
+ });
+ }
+
+ res.status(200).json({
+ serialNumber: device.serialNumber, // Keep serial number consistent
+ status: device.status, // Handle missing status field
+ customerName: device.customerName , // Handle missing customerName
+ });
+ } catch (err) {
+ console.error('Error checking device status:', err);
+ res.status(500).json({ error: 'Error checking device status' });
+ }
+});
+
+app.put('/update', async (req, res) => {
+ const { serialNumber, Verient, mac, os, status, customerName, customerNumber, customerAddress } = req.body;
+
+ if (!serialNumber) {
+ return res.status(400).json({ error: 'Serial Number is required' });
+ }
+
+ try {
+ const db = client.db(dbName);
+ const collection = db.collection(collectionName);
+ const existingDevice = await collection.findOne({ serialNumber });
+
+ if (!existingDevice) {
+ return res.status(404).json({ error: 'Device not found' });
+ }
+
+ if (mac && mac !== existingDevice.mac) {
+ const duplicateMac = await collection.findOne({ mac });
+ if (duplicateMac) {
+ return res.status(400).json({ error: 'MAC address is already registered' });
+ }
+ }
+
+ // Update the database entry
+ const updatedData = {
+ ...(Verient && { Verient }),
+ ...(mac && { mac }),
+ ...(os && { os }),
+ ...(status && { status }),
+ ...(customerName && { customerName }),
+ ...(customerNumber && { customerNumber }),
+ ...(customerAddress && { customerAddress }),
+ };
+
+ await collection.updateOne({ serialNumber }, { $set: updatedData });
+
+ console.log('Item successfully updated in MongoDB');
+
+ // Update in Google Sheets
+ try {
+ const sheetData = await sheets.spreadsheets.values.get({ spreadsheetId, range });
+ const rows = sheetData.data.values;
+ const rowIndex = rows.findIndex(row => row[0] === serialNumber);
+
+ if (rowIndex !== -1) {
+ const updatedRow = [
+ serialNumber,
+ Verient || rows[rowIndex][1],
+ mac || rows[rowIndex][2],
+ os || rows[rowIndex][3],
+ status || rows[rowIndex][4],
+ customerName || rows[rowIndex][5],
+ customerNumber || rows[rowIndex][6],
+ customerAddress || rows[rowIndex][7],
+ ];
+
+ await sheets.spreadsheets.values.update({
+ spreadsheetId,
+ range: `Sheet1!A${rowIndex + 1}:H${rowIndex + 1}`,
+ valueInputOption: 'USER_ENTERED',
+ requestBody: { values: [updatedRow] },
+ });
+
+ console.log('Data successfully updated in Google Sheets');
+ }
+
+ res.status(200).json({ message: 'Device updated successfully' });
+ } catch (err) {
+ console.error('Error updating Google Sheets:', err);
+ res.status(500).json({ error: 'Error updating Google Sheets' });
+ }
+ } catch (err) {
+ console.error('Error updating item in MongoDB:', err);
+ res.status(500).json({ error: 'Error updating device in MongoDB' });
+ }
+});
+
+
+
// Start the server
app.listen(port, () => console.log(`Server running on http://localhost:${port}`));
diff --git a/package.json b/package.json
index 5779172..c356d04 100644
--- a/package.json
+++ b/package.json
@@ -7,6 +7,7 @@
"start": "nodemon index.js"
},
"dependencies": {
+ "cors": "^2.8.5",
"crypto": "^1.0.1",
"dotenv": "^16.4.7",
"express": "^4.17.1",