Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file added backend/cd
Empty file.
64 changes: 64 additions & 0 deletions backend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"dependencies": {
"axios": "^1.13.6",
"bcryptjs": "^3.0.3",
"compression": "^1.8.1",
"cors": "^2.8.6",
"dns": "^0.2.2",
"dotenv": "^17.4.2",
Expand Down
31 changes: 31 additions & 0 deletions backend/routes/historyRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,37 @@ router.get("/", protect, getHistory);
// Delete one history item
router.delete("/:id", protect, deleteHistoryItem);

// Bulk delete history items
router.delete("/bulk-delete", protect, async (req, res) => {
try {
const { ids } = req.body; // Expecting an array of IDs in the request body

if (!ids || !Array.isArray(ids) || ids.length === 0) {
return res.status(400).json({
success: false,
message: "Invalid request. 'ids' must be a non-empty array."
});
}

const result = await History.deleteMany({
_id: { $in: ids },
user: req.user.id
});

res.json({
success: true,
deletedCount: result.deletedCount,
message: `${result.deletedCount} items deleted successfully`
});

} catch (error) {
res.status(500).json({
success: false,
message: error.message
});
}
});

// Clear all history
router.delete("/", protect, clearHistory);

Expand Down
24 changes: 24 additions & 0 deletions backend/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const express = require("express");
const seedAdminUser = require("./seeders/adminSeeder");
const { getHealthStatus } = require('./utils/healthCheck');
const cors = require("cors");
const compression = require('compression');
const { v4: uuidv4 } = require('uuid');
const axios = require("axios");

Expand Down Expand Up @@ -61,10 +62,33 @@ const connectWithRetry = async (retries=5, delay=5000) => {
}
};

if(process.env.NODE_ENV === 'development'){
//Log all queries in development mode
mongoose.set('debug',true);
} else {
// Log only slow queries in production mode
const originalExec = mongoose.Query.prototype.exec;
mongoose.Query.prototype.exec = async function() {
const start = Date.now();
const result = await originalExec.apply(this, arguments);
const duration = Date.now() - start;

if(duration > 100){ // Log queries taking longer than 100ms
console.log(`🐢 [${new Date().toISOString()}] Slow Query (${duration}ms):`);
console.log(` Collection: ${this._collection.collectionName}`);
console.log(` Query:`, JSON.stringify(this._conditions));
}

return result;
};
}

// Start connection with retry
connectWithRetry();

app.use(cors());
app.use(compression());
app.use(express.json());
app.use(express.json({limit: '1mb'}));
app.use(express.urlencoded({ extended: true, limit: '1mb' }));
app.get('/health', (req, res) => {
Expand Down
216 changes: 103 additions & 113 deletions frontend/src/components/History.jsx
Original file line number Diff line number Diff line change
@@ -1,116 +1,106 @@
import { useEffect, useState } from "react";
import api from "../utils/axiosInstance";

function History({ darkMode }) {
const [history, setHistory] = useState([]);
const [loading, setLoading] = useState(true);

const fetchHistory = async () => {
try {
const res = await api.get("/api/history");
setHistory(res.data);
} catch (err) {
console.error("Failed to load history:", err);
} finally {
setLoading(false);
}
};

useEffect(() => {
fetchHistory();
}, []);

const deleteItem = async (id) => {
try {
await api.delete(`/api/history/${id}`);

setHistory((prev) =>
prev.filter((item) => item._id !== id)
);
} catch (err) {
console.error(err);
}
};

const clearAll = async () => {
try {
await api.delete("/api/history");

setHistory([]);
} catch (err) {
console.error(err);
}
};

if (loading) {
return <p>Loading history...</p>;
}

return (
<div className="mt-6">
<div className="flex justify-between items-center mb-4">
<h2 className="text-xl font-bold">
📜 History
</h2>

{history.length > 0 && (
<button
onClick={clearAll}
className="bg-red-500 text-white px-3 py-1 rounded-lg"
>
Clear All
</button>
)}
</div>

{history.length === 0 ? (
<p>No history found.</p>
) : (
<div className="space-y-3">
{history.map((item) => (
<div
key={item._id}
className={`p-3 rounded-xl border ${
darkMode
? "bg-gray-800 border-gray-700"
: "bg-white/40 border-gray-300"
}`}
>
<p className="font-medium">
{item.query}
</p>

<p>
Result:{" "}
<span className="font-semibold">
{item.prediction}
</span>
</p>

<p>
Type: {item.type}
</p>

<p className="text-sm opacity-70">
{new Date(
item.createdAt
).toLocaleString()}
</p>

<button
onClick={() =>
deleteItem(item._id)
}
className="mt-2 bg-red-500 text-white px-2 py-1 rounded"
>
Delete
</button>
</div>
))}
import { useState, useEffect } from 'react';
import axios from 'axios';

const History = () => {
const [history, setHistory] = useState([]);
const [selectedItems, setSelectedItems] = useState([]);

const fetchHistory = async () => {
try {
const token = localStorage.getItem('token');
const res = await axios.get('/api/history', {
headers: { Authorization: `Bearer ${token}` }
});
setHistory(res.data.data || []);
} catch (error) {
console.error('Error fetching history:', error);
}
};

useEffect(() => {
fetchHistory();
}, []);

const handleBulkDelete = async () => {
if (!confirm(`Delete ${selectedItems.length} item(s)?`)) return;

try {
const token = localStorage.getItem('token');
await axios.delete('/api/history/bulk-delete', {
headers: { Authorization: `Bearer ${token}` },
data: { ids: selectedItems }
});
setSelectedItems([]);
fetchHistory();
} catch (error) {
alert('Failed to delete items');
}
};

const toggleSelect = (id) => {
setSelectedItems(prev =>
prev.includes(id) ? prev.filter(i => i !== id) : [...prev, id]
);
};

return (
<div style={{ padding: '20px', maxWidth: '800px', margin: '0 auto' }}>
<h2>History</h2>

{selectedItems.length > 0 && (
<button
onClick={handleBulkDelete}
style={{
background: '#ef4444',
color: 'white',
padding: '8px 16px',
border: 'none',
borderRadius: '6px',
cursor: 'pointer',
marginBottom: '10px'
}}
>
Delete Selected ({selectedItems.length})
</button>
)}

{history.length === 0 ? (
<p>No history found.</p>
) : (
history.map(item => (
<div
key={item._id}
style={{
display: 'flex',
alignItems: 'center',
gap: '10px',
padding: '10px 0',
borderBottom: '1px solid #e5e7eb'
}}
>
<input
type="checkbox"
checked={selectedItems.includes(item._id)}
onChange={() => toggleSelect(item._id)}
/>
<span style={{ flex: 1 }}>{item.query}</span>
<span
style={{
padding: '2px 10px',
borderRadius: '12px',
fontSize: '12px',
fontWeight: '600',
background: item.prediction === 'spam' ? '#fee2e2' : '#dcfce7',
color: item.prediction === 'spam' ? '#dc2626' : '#16a34a'
}}
>
{item.prediction}
</span>
</div>
))
)}
</div>
)}
</div>
);
}
);
};

export default History;
Loading