Merge branch 'aaqil-Branch' into mann-Branch
This commit is contained in:
@@ -6,16 +6,16 @@ exports.getTransactionWithPagination = async (req, res) => {
|
||||
const offset = (page - 1) * limit;
|
||||
try {
|
||||
const [data, _] = await db.execute(
|
||||
`SELECT T.TransactionID, DATE_FORMAT(T.Date, '%b-%d-%Y %h:%i %p') as Date, T.PaymentStatus, U.Name as UserName, P.Name as ProductName
|
||||
`SELECT T.TransactionID, DATE_FORMAT(T.Date, '%b-%d-%Y %h:%i %p') as Date, T.PaymentStatus, U.Name as UserName, P.Name as ProductName
|
||||
FROM Transaction T
|
||||
LEFT JOIN User U ON T.UserID = U.UserID
|
||||
LEFT JOIN Product P ON T.ProductID = P.ProductID
|
||||
ORDER BY T.TransactionID ASC LIMIT ? OFFSET ?`,
|
||||
[limit.toString(), offset.toString()]
|
||||
[limit.toString(), offset.toString()],
|
||||
);
|
||||
|
||||
const [result] = await db.execute(
|
||||
"SELECT COUNT(*) AS count FROM Transaction"
|
||||
"SELECT COUNT(*) AS count FROM Transaction",
|
||||
);
|
||||
const { count: total } = result[0];
|
||||
return res.json({ data, total });
|
||||
@@ -29,7 +29,7 @@ exports.removeTransation = async (req, res) => {
|
||||
try {
|
||||
const [result] = await db.execute(
|
||||
"DELETE FROM Transaction WHERE TransactionID = ?;",
|
||||
[id.toString()]
|
||||
[id.toString()],
|
||||
);
|
||||
return res.json({ message: "Remove transaction successfully!" });
|
||||
} catch (error) {
|
||||
@@ -38,3 +38,188 @@ exports.removeTransation = async (req, res) => {
|
||||
.json({ error: "Cannot remove transactions from database!" });
|
||||
}
|
||||
};
|
||||
// Create a new transaction
|
||||
exports.createTransaction = async (req, res) => {
|
||||
const { userID, productID, date, paymentStatus } = req.body;
|
||||
|
||||
try {
|
||||
// Check if the transaction already exists for the same user and product
|
||||
const [existingTransaction] = await db.execute(
|
||||
`SELECT TransactionID FROM Transaction WHERE UserID = ? AND ProductID = ?`,
|
||||
[userID, productID],
|
||||
);
|
||||
|
||||
if (existingTransaction.length > 0) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: "Transaction already exists for this user and product",
|
||||
});
|
||||
}
|
||||
|
||||
// Format the date
|
||||
const formattedDate = new Date(date)
|
||||
.toISOString()
|
||||
.slice(0, 19)
|
||||
.replace("T", " ");
|
||||
|
||||
// Insert the new transaction
|
||||
const [result] = await db.execute(
|
||||
`INSERT INTO Transaction (UserID, ProductID, Date, PaymentStatus)
|
||||
VALUES (?, ?, ?, ?)`,
|
||||
[userID, productID, formattedDate, paymentStatus],
|
||||
);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: "Transaction created successfully",
|
||||
transactionID: result.insertId,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error creating transaction:", error);
|
||||
res.status(500).json({ error: "Could not create transaction" });
|
||||
}
|
||||
};
|
||||
|
||||
// Get all transactions for a given product
|
||||
exports.getTransactionsByProduct = async (req, res) => {
|
||||
const { productID } = req.params;
|
||||
|
||||
try {
|
||||
const [transactions] = await db.execute(
|
||||
`SELECT
|
||||
T.TransactionID,
|
||||
T.UserID,
|
||||
T.ProductID,
|
||||
T.Date,
|
||||
T.PaymentStatus,
|
||||
P.Name AS ProductName,
|
||||
MIN(I.URL) AS Image_URL
|
||||
FROM Transaction T
|
||||
JOIN Product P ON T.ProductID = P.ProductID
|
||||
LEFT JOIN Image_URL I ON P.ProductID = I.ProductID
|
||||
GROUP BY T.TransactionID, T.UserID, T.ProductID, T.Date, T.PaymentStatus, P.Name`,
|
||||
);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
transactions,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error fetching transactions by product:", error);
|
||||
res.status(500).json({ error: "Could not retrieve transactions" });
|
||||
}
|
||||
};
|
||||
|
||||
// Get all transactions for a given user
|
||||
exports.getTransactionsByUser = async (req, res) => {
|
||||
const { userID } = req.body;
|
||||
|
||||
try {
|
||||
const [transactions] = await db.execute(
|
||||
`SELECT
|
||||
T.TransactionID,
|
||||
T.UserID,
|
||||
T.ProductID,
|
||||
T.Date,
|
||||
T.PaymentStatus,
|
||||
P.Name AS ProductName,
|
||||
I.URL AS Image_URL
|
||||
FROM Transaction T
|
||||
JOIN Product P ON T.ProductID = P.ProductID
|
||||
LEFT JOIN Image_URL I ON P.ProductID = I.ProductID
|
||||
WHERE T.UserID = ?`,
|
||||
[userID],
|
||||
);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
transactions,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error fetching transactions by user:", error);
|
||||
res.status(500).json({ error: "Could not retrieve transactions" });
|
||||
}
|
||||
};
|
||||
|
||||
// Get all transactions in the system
|
||||
exports.getAllTransactions = async (req, res) => {
|
||||
try {
|
||||
const [transactions] = await db.execute(
|
||||
`SELECT
|
||||
T.TransactionID,
|
||||
T.UserID,
|
||||
T.ProductID,
|
||||
T.Date,
|
||||
T.PaymentStatus,
|
||||
P.Name AS ProductName,
|
||||
MIN(I.URL) AS Image_URL
|
||||
FROM Transaction T
|
||||
JOIN Product P ON T.ProductID = P.ProductID
|
||||
LEFT JOIN Image_URL I ON P.ProductID = I.ProductID
|
||||
GROUP BY T.TransactionID, T.UserID, T.ProductID, T.Date, T.PaymentStatus, P.Name`,
|
||||
);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
transactions,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error fetching all transactions:", error);
|
||||
res.status(500).json({ error: "Could not retrieve transactions" });
|
||||
}
|
||||
};
|
||||
|
||||
// Update the payment status of a transaction
|
||||
exports.updatePaymentStatus = async (req, res) => {
|
||||
const { transactionID, paymentStatus } = req.body;
|
||||
|
||||
try {
|
||||
const [result] = await db.execute(
|
||||
`UPDATE Transaction
|
||||
SET PaymentStatus = ?
|
||||
WHERE TransactionID = ?`,
|
||||
[paymentStatus, transactionID],
|
||||
);
|
||||
|
||||
if (result.affectedRows === 0) {
|
||||
return res
|
||||
.status(404)
|
||||
.json({ success: false, message: "Transaction not found" });
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: "Payment status updated successfully",
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error updating payment status:", error);
|
||||
res.status(500).json({ error: "Could not update payment status" });
|
||||
}
|
||||
};
|
||||
|
||||
// Delete a transaction
|
||||
exports.deleteTransaction = async (req, res) => {
|
||||
const { transactionID } = req.body;
|
||||
|
||||
try {
|
||||
const [result] = await db.execute(
|
||||
`DELETE FROM Transaction
|
||||
WHERE TransactionID = ?`,
|
||||
[transactionID],
|
||||
);
|
||||
|
||||
if (result.affectedRows === 0) {
|
||||
return res
|
||||
.status(404)
|
||||
.json({ success: false, message: "Transaction not found" });
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: "Transaction deleted successfully",
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error deleting transaction:", error);
|
||||
res.status(500).json({ error: "Could not delete transaction" });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -9,7 +9,9 @@ const searchRouter = require("./routes/search");
|
||||
const recommendedRouter = require("./routes/recommendation");
|
||||
const history = require("./routes/history");
|
||||
const review = require("./routes/review");
|
||||
|
||||
const categoryRouter = require("./routes/category");
|
||||
|
||||
const transactionRouter = require("./routes/transaction");
|
||||
|
||||
const { generateEmailTransporter } = require("./utils/mail");
|
||||
@@ -44,9 +46,9 @@ app.use("/api/search", searchRouter);
|
||||
app.use("/api/engine", recommendedRouter);
|
||||
app.use("/api/history", history);
|
||||
app.use("/api/review", review);
|
||||
app.use("/api/category", categoryRouter);
|
||||
app.use("/api/transaction", transactionRouter);
|
||||
app.use("/api/category", categoryRouter);
|
||||
app.use("/api/transaction", transactionRouter);
|
||||
|
||||
// Set up a scheduler to run cleanup every hour
|
||||
clean_up_time = 30 * 60 * 1000;
|
||||
|
||||
@@ -1,11 +1,39 @@
|
||||
// routes/transaction.js
|
||||
const express = require("express");
|
||||
const {
|
||||
getTransactionWithPagination,
|
||||
removeTransation,
|
||||
createTransaction,
|
||||
getTransactionsByProduct,
|
||||
getTransactionsByUser,
|
||||
getAllTransactions,
|
||||
updatePaymentStatus,
|
||||
deleteTransaction,
|
||||
} = require("../controllers/transaction");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// logging middleware
|
||||
router.use((req, res, next) => {
|
||||
console.log(`Incoming ${req.method} ${req.originalUrl}`);
|
||||
next();
|
||||
});
|
||||
|
||||
// Create a new transaction
|
||||
router.post("/createTransaction", createTransaction);
|
||||
|
||||
// Get all transactions for a specific product
|
||||
router.get("/getTransactionsByProduct/:productID", getTransactionsByProduct);
|
||||
|
||||
// Get all transactions for a specific user
|
||||
router.post("/getTransactionsByUser", getTransactionsByUser);
|
||||
|
||||
// Get all transactions in the system
|
||||
router.post("/getAllTransactions", getAllTransactions);
|
||||
|
||||
// Update payment status on a transaction
|
||||
router.patch("/updatePaymentStatus", updatePaymentStatus);
|
||||
|
||||
// Delete a transaction
|
||||
router.delete("/deleteTransaction", deleteTransaction);
|
||||
|
||||
router.get("/getTransactions", getTransactionWithPagination);
|
||||
router.delete("/:id", removeTransation);
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ const pool = mysql.createPool({
|
||||
host: "localhost",
|
||||
user: "root",
|
||||
database: "Marketplace",
|
||||
password: "12345678"
|
||||
});
|
||||
|
||||
// const pool = mysql.createPool(
|
||||
|
||||
@@ -18,7 +18,7 @@ async function sendVerificationEmail(email, verificationCode) {
|
||||
|
||||
// Clean up expired verification codes (run this periodically)
|
||||
function cleanupExpiredCodes() {
|
||||
db_con.query(
|
||||
db.query(
|
||||
"DELETE FROM AuthVerification WHERE Date < DATE_SUB(NOW(), INTERVAL 15 MINUTE) AND Authenticated = 0",
|
||||
(err, result) => {
|
||||
if (err) {
|
||||
|
||||
@@ -414,8 +414,45 @@ const ProductDetail = () => {
|
||||
|
||||
<div className="relative">
|
||||
<button
|
||||
onClick={() => setShowContactOptions(!showContactOptions)}
|
||||
className="w-full bg-emerald-700 hover:bg-emerald-700 text-white font-medium py-3 px-4 mb-3"
|
||||
onClick={async () => {
|
||||
try {
|
||||
// Create a transaction record
|
||||
const transactionData = {
|
||||
userID: storedUser.ID, // User ID from session storage
|
||||
productID: product.ProductID, // Product ID from the product details
|
||||
date: new Date().toISOString(), // Current date in ISO format
|
||||
paymentStatus: "Pending", // Default payment status
|
||||
};
|
||||
|
||||
const response = await fetch(
|
||||
"http://localhost:3030/api/transaction/createTransaction",
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(transactionData),
|
||||
},
|
||||
);
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (result.success) {
|
||||
alert("Transaction created successfully!");
|
||||
} else {
|
||||
throw new Error(
|
||||
result.message || "Failed to create transaction",
|
||||
);
|
||||
}
|
||||
|
||||
// Toggle contact options visibility
|
||||
setShowContactOptions(!showContactOptions);
|
||||
} catch (error) {
|
||||
console.error("Error creating transaction:", error);
|
||||
alert(`Error: ${error.message}`);
|
||||
}
|
||||
}}
|
||||
className="w-full bg-green-500 hover:bg-green-600 text-white font-medium py-3 px-4 mb-3"
|
||||
>
|
||||
Contact Seller
|
||||
</button>
|
||||
|
||||
@@ -1,8 +1,213 @@
|
||||
import { useState } from "react";
|
||||
import { useState, useEffect } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { Calendar, CreditCard, Trash2 } from "lucide-react";
|
||||
|
||||
const Transactions = () => {
|
||||
return <div></div>;
|
||||
const [transactions, setTransactions] = useState([]);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchTransactions = async () => {
|
||||
try {
|
||||
const response = await fetch(
|
||||
"http://localhost:3030/api/transaction/getAllTransactions",
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ userID: 1 }), // replace with actual userID
|
||||
}
|
||||
);
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
const { transactions: txData } = await response.json();
|
||||
if (!Array.isArray(txData)) return;
|
||||
|
||||
setTransactions(
|
||||
txData.map((tx) => ({
|
||||
id: tx.TransactionID,
|
||||
productId: tx.ProductID,
|
||||
name: tx.ProductName || "Unnamed Product",
|
||||
price: tx.Price != null ? parseFloat(tx.Price) : null,
|
||||
image: tx.Image_URL || "/default-image.jpg",
|
||||
date: tx.Date,
|
||||
status: tx.PaymentStatus,
|
||||
}))
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch transactions:", error);
|
||||
}
|
||||
};
|
||||
|
||||
fetchTransactions();
|
||||
}, []);
|
||||
|
||||
const deleteTransaction = async (id) => {
|
||||
try {
|
||||
const res = await fetch(
|
||||
"http://localhost:3030/api/transaction/deleteTransaction",
|
||||
{
|
||||
method: "DELETE",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ transactionID: id }),
|
||||
}
|
||||
);
|
||||
const data = await res.json();
|
||||
if (data.success) {
|
||||
setTransactions((prev) => prev.filter((tx) => tx.id !== id));
|
||||
} else {
|
||||
console.error("Delete failed:", data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Error deleting transaction:", err);
|
||||
}
|
||||
};
|
||||
|
||||
const formatDate = (dateString) => {
|
||||
const d = new Date(dateString);
|
||||
return d.toLocaleDateString("en-US", {
|
||||
year: "numeric",
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="max-w-6xl mx-auto">
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<h1 className="text-2xl font-bold text-gray-800">My Transactions</h1>
|
||||
</div>
|
||||
|
||||
{transactions.length === 0 ? (
|
||||
<div className="bg-white border border-gray-200 p-8 text-center">
|
||||
<CreditCard className="h-12 w-12 text-gray-300 mx-auto mb-4" />
|
||||
<h3 className="text-xl font-medium text-gray-700 mb-2">
|
||||
No transactions found
|
||||
</h3>
|
||||
<p className="text-gray-500 mb-4">
|
||||
Once transactions are created, they’ll appear here.
|
||||
</p>
|
||||
<Link
|
||||
to="/"
|
||||
className="inline-block bg-emerald-500 hover:bg-emerald-600 text-white font-medium py-2 px-4"
|
||||
>
|
||||
Browse Listings
|
||||
</Link>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{transactions.map((tx) => (
|
||||
<div
|
||||
key={tx.id}
|
||||
className="relative border-2 border-gray-200 overflow-hidden hover:shadow-md transition-shadow"
|
||||
>
|
||||
{/* Delete Button */}
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
deleteTransaction(tx.id);
|
||||
}}
|
||||
className="absolute bottom-2 right-2 text-red-500 hover:text-red-600 z-10"
|
||||
>
|
||||
<Trash2 size={20} />
|
||||
</button>
|
||||
|
||||
<Link to={`/product/${tx.productId}`}>
|
||||
<div className="h-48 bg-gray-200 flex items-center justify-center">
|
||||
{tx.image ? (
|
||||
<img
|
||||
src={tx.image}
|
||||
alt={tx.name}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="text-gray-400">No image</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="p-4">
|
||||
<h3 className="text-lg font-semibold text-gray-800">
|
||||
{tx.name}
|
||||
</h3>
|
||||
{tx.price !== null && (
|
||||
<p className="text-emerald-600 font-bold mt-1">
|
||||
${tx.price.toFixed(2)}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex items-center text-gray-500 text-sm mt-2">
|
||||
<Calendar className="mr-1" size={16} />
|
||||
{formatDate(tx.date)}
|
||||
</div>
|
||||
<p className="text-gray-600 text-sm mt-1">
|
||||
Status: <span className="font-medium">{tx.status}</span>
|
||||
</p>
|
||||
</div>
|
||||
</Link>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="mt-6 text-sm text-gray-500">
|
||||
Showing {transactions.length}{" "}
|
||||
{transactions.length === 1 ? "transaction" : "transactions"}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<footer className="bg-gray-800 text-white py-6 mt-12">
|
||||
<div className="container mx-auto px-4">
|
||||
<div className="flex flex-col md:flex-row justify-between items-center">
|
||||
<div className="mb-4 md:mb-0">
|
||||
<h3 className="text-lg font-semibold mb-2">
|
||||
Campus Marketplace
|
||||
</h3>
|
||||
<p className="text-gray-400 text-sm">
|
||||
Your trusted university trading platform
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex space-x-6">
|
||||
<div>
|
||||
<h4 className="font-medium mb-2">Quick Links</h4>
|
||||
<ul className="text-sm text-gray-400">
|
||||
<li className="mb-1">
|
||||
<Link to="/" className="hover:text-white transition">
|
||||
Home
|
||||
</Link>
|
||||
</li>
|
||||
<li className="mb-1">
|
||||
<Link
|
||||
to="/selling"
|
||||
className="hover:text-white transition"
|
||||
>
|
||||
Sell an Item
|
||||
</Link>
|
||||
</li>
|
||||
<li className="mb-1">
|
||||
<Link
|
||||
to="/favorites"
|
||||
className="hover:text-white transition"
|
||||
>
|
||||
My Favorites
|
||||
</Link>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="font-medium mb-2">Contact</h4>
|
||||
<ul className="text-sm text-gray-400">
|
||||
<li className="mb-1">support@campusmarket.com</li>
|
||||
<li className="mb-1">University of Calgary</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="border-t border-gray-700 mt-6 pt-6 text-center text-sm text-gray-400">
|
||||
<p>
|
||||
© {new Date().getFullYear()} Campus Marketplace. All rights
|
||||
reserved.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Transactions;
|
||||
|
||||
Reference in New Issue
Block a user