feat(reviews): add owner-isolated edit and delete capabilities for user reviews

This commit is contained in:
Adam Eehan committed 2026-11-11 13:11:16 +05:30
1 parent 2b73f8c507
commit 7bc7ae3cb4
2 files changed
+282 -47

No files matched your search

+95 -31
View File
@@ -5,8 +5,8 @@
* *
* Features: * Features:
* - Real-time persistent feedback list storage via secure backend proxy * - Real-time persistent feedback list storage via secure backend proxy
* - Eliminates client-side race conditions, CORS blocks, and overwrites * - Multi-user chronological review preservation
* - Multi-user chronological review preservation (new reviews unshift, existing updates) * - Strict Owner-Only Edit & Delete (Each user can only modify/delete their own review)
* - Automated notification dispatch to Er. Adam Eehan * - Automated notification dispatch to Er. Adam Eehan
*/ */
@@ -65,7 +65,7 @@ async function saveToBin(feedbacks) {
export default async function handler(req, res) { export default async function handler(req, res) {
// CORS & No-Cache Headers // CORS & No-Cache Headers
res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type"); res.setHeader("Access-Control-Allow-Headers", "Content-Type");
res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, proxy-revalidate"); res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, proxy-revalidate");
@@ -91,10 +91,52 @@ export default async function handler(req, res) {
} }
} }
// --- POST: Add new review or update existing review without deleting others --- // --- DELETE (or POST action === 'delete'): Owner-Only Delete ---
const body = req.body || {};
const query = req.query || {};
const action = body.action || query.action;
if (req.method === "DELETE" || action === "delete") {
try {
const targetId = body.id || query.id;
const userEmail = body.email || query.email;
if (!targetId || !userEmail) {
return res.status(400).json({ success: false, error: "Review ID and authenticated user email are required." });
}
const cleanEmail = userEmail.trim().toLowerCase();
const currentFeedbacks = await fetchLatestFromBin();
const existing = currentFeedbacks.find(r => r.id === targetId || (r.email && r.email.toLowerCase() === cleanEmail));
if (!existing) {
return res.status(404).json({ success: false, error: "Review not found in database." });
}
// Security check: Only the owner can delete their review
if (!existing.email || existing.email.toLowerCase() !== cleanEmail) {
return res.status(403).json({ success: false, error: "Unauthorized: You can only delete your own review." });
}
const updatedFeedbacks = currentFeedbacks.filter(r => r.id !== existing.id);
await saveToBin(updatedFeedbacks);
return res.status(200).json({
success: true,
message: "Your review was successfully deleted.",
count: updatedFeedbacks.length,
reviews: updatedFeedbacks
});
} catch (err) {
console.error("[Reviews API] Delete error:", err);
return res.status(500).json({ success: false, error: "Failed to delete review: " + err.message });
}
}
// --- POST: Add new review or edit existing review ---
if (req.method === "POST") { if (req.method === "POST") {
try { try {
const { name, email, photo, rating, tag, text, id, date } = req.body || {}; const { name, email, photo, rating, tag, text, id, date, isEdit } = body;
if (!text || !text.trim()) { if (!text || !text.trim()) {
return res.status(400).json({ success: false, error: "Review text is required." }); return res.status(400).json({ success: false, error: "Review text is required." });
@@ -102,41 +144,64 @@ export default async function handler(req, res) {
const cleanName = (name && name.trim()) ? name.trim() : "Verified Member"; const cleanName = (name && name.trim()) ? name.trim() : "Verified Member";
const cleanEmail = (email && email.trim()) ? email.trim().toLowerCase() : ""; const cleanEmail = (email && email.trim()) ? email.trim().toLowerCase() : "";
if (!cleanEmail) {
return res.status(400).json({ success: false, error: "Authenticated user email is required." });
}
const cleanText = text.trim().slice(0, 1500); const cleanText = text.trim().slice(0, 1500);
const cleanRating = (typeof rating === "number" && rating >= 1 && rating <= 5) ? rating : 5; const cleanRating = (typeof rating === "number" && rating >= 1 && rating <= 5) ? rating : 5;
const cleanTag = (tag && tag.trim()) ? tag.trim() : "Client / Collaborator"; const cleanTag = (tag && tag.trim()) ? tag.trim() : "Client / Collaborator";
const cleanPhoto = (photo && photo.trim()) ? photo.trim() : `https://api.dicebear.com/7.x/initials/svg?seed=${encodeURIComponent(cleanName)}`; const cleanPhoto = (photo && photo.trim()) ? photo.trim() : `https://api.dicebear.com/7.x/initials/svg?seed=${encodeURIComponent(cleanName)}`;
const cleanDate = date || new Date().toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" }); const baseDate = date || new Date().toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
const reviewId = id || ("rev_" + Date.now()); const cleanDate = isEdit ? `${baseDate.replace(" (Edited)", "")} (Edited)` : baseDate;
const newReview = {
id: reviewId,
name: cleanName,
email: cleanEmail,
photo: cleanPhoto,
rating: cleanRating,
tag: cleanTag,
text: cleanText,
date: cleanDate
};
// 1. Fetch current list of reviews from cloud // 1. Fetch current list of reviews from cloud
const currentFeedbacks = await fetchLatestFromBin(); const currentFeedbacks = await fetchLatestFromBin();
// 2. Check if this user (by email) already submitted a review
let updatedFeedbacks = [...currentFeedbacks]; let updatedFeedbacks = [...currentFeedbacks];
// 2. Locate existing review if editing or if user already reviewed
let existingIndex = -1; let existingIndex = -1;
if (id) {
if (cleanEmail) { existingIndex = updatedFeedbacks.findIndex(r => r.id === id);
}
if (existingIndex === -1 && cleanEmail) {
existingIndex = updatedFeedbacks.findIndex(r => r.email && r.email.toLowerCase() === cleanEmail); existingIndex = updatedFeedbacks.findIndex(r => r.email && r.email.toLowerCase() === cleanEmail);
} }
let reviewId = id || ("rev_" + Date.now());
if (existingIndex >= 0) { if (existingIndex >= 0) {
// User is updating their existing review -> Move updated review to top const existingReview = updatedFeedbacks[existingIndex];
// Security check: Only the owner can edit their review
if (existingReview.email && existingReview.email.toLowerCase() !== cleanEmail) {
return res.status(403).json({ success: false, error: "Unauthorized: You can only edit your own review." });
}
reviewId = existingReview.id;
const updatedReview = {
id: reviewId,
name: cleanName,
email: cleanEmail,
photo: cleanPhoto,
rating: cleanRating,
tag: cleanTag,
text: cleanText,
date: cleanDate
};
// Replace in place or move to top
updatedFeedbacks.splice(existingIndex, 1); updatedFeedbacks.splice(existingIndex, 1);
updatedFeedbacks.unshift(newReview); updatedFeedbacks.unshift(updatedReview);
} else { } else {
// New user -> Prepend to the list so older reviews are preserved! // New review
const newReview = {
id: reviewId,
name: cleanName,
email: cleanEmail,
photo: cleanPhoto,
rating: cleanRating,
tag: cleanTag,
text: cleanText,
date: cleanDate
};
updatedFeedbacks.unshift(newReview); updatedFeedbacks.unshift(newReview);
} }
@@ -149,23 +214,22 @@ export default async function handler(req, res) {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json", "Accept": "application/json" }, headers: { "Content-Type": "application/json", "Accept": "application/json" },
body: JSON.stringify({ body: JSON.stringify({
_subject: `🌟 New Real Feedback: ${cleanName} (${cleanRating} Stars) - airaaigroup.in`, _subject: `🌟 ${existingIndex >= 0 ? "Review Edited" : "New Feedback"}: ${cleanName} (${cleanRating} Stars) - airaaigroup.in`,
Name: cleanName, Name: cleanName,
Email: cleanEmail, Email: cleanEmail,
Rating: `${cleanRating} / 5 Stars`, Rating: `${cleanRating} / 5 Stars`,
Category: cleanTag, Category: cleanTag,
Review: cleanText, Review: cleanText,
Date: cleanDate, Date: cleanDate,
IsEdited: existingIndex >= 0,
TotalReviewsInDatabase: updatedFeedbacks.length TotalReviewsInDatabase: updatedFeedbacks.length
}) })
}).catch(() => {}); }).catch(() => {});
} catch (mailErr) { } catch (mailErr) {}
// ignore background mail errors
}
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
message: "Review successfully published and preserved in cloud database.", message: existingIndex >= 0 ? "Review successfully updated." : "Review successfully published and preserved.",
count: updatedFeedbacks.length, count: updatedFeedbacks.length,
reviews: updatedFeedbacks reviews: updatedFeedbacks
}); });
@@ -179,5 +243,5 @@ export default async function handler(req, res) {
} }
} }
return res.status(405).json({ error: "Method not allowed. Use GET or POST." }); return res.status(405).json({ error: "Method not allowed. Use GET, POST, or DELETE." });
} }
+187 -16
View File
@@ -1264,6 +1264,20 @@
<!-- Feedback Submission Form (NO GMAIL INPUT ASKED!) --> <!-- Feedback Submission Form (NO GMAIL INPUT ASKED!) -->
<form id="verified-feedback-form" onsubmit="handleFeedbackSubmit(event)" class="space-y-4"> <form id="verified-feedback-form" onsubmit="handleFeedbackSubmit(event)" class="space-y-4">
<!-- Edit Review Mode Indicator Banner -->
<div id="editing-review-indicator" class="hidden flex items-center justify-between p-3.5 bg-blue-50/90 border border-blue-200 rounded-xl mb-2 animate-fade-in">
<div class="flex items-center gap-2 text-xs font-bold text-blue-900">
<i class="fas fa-pen-to-square text-blue-600"></i>
<span>Editing your published review</span>
</div>
<button
type="button"
onclick="cancelEditReview()"
class="text-xs text-slate-600 hover:text-slate-900 font-semibold px-2.5 py-1 rounded-lg hover:bg-white border border-slate-200 transition flex items-center gap-1"
>
<i class="fas fa-times"></i> Cancel
</button>
</div>
<!-- Star Rating Selection --> <!-- Star Rating Selection -->
<div class="flex items-center gap-3"> <div class="flex items-center gap-3">
<span class="text-sm font-semibold text-[#0a2342]">Your Rating:</span> <span class="text-sm font-semibold text-[#0a2342]">Your Rating:</span>
@@ -2924,6 +2938,7 @@
let currentRating = 5; let currentRating = 5;
let currentTag = "Client / Business Partner"; let currentTag = "Client / Business Partner";
let liveReviews = []; let liveReviews = [];
let editingReviewId = null;
// Initialize on load // Initialize on load
function initReviewsSystem() { function initReviewsSystem() {
@@ -3121,6 +3136,10 @@
if (nameEl) nameEl.textContent = currentUser.name; if (nameEl) nameEl.textContent = currentUser.name;
if (emailEl) emailEl.textContent = currentUser.email; if (emailEl) emailEl.textContent = currentUser.email;
} }
// Update reviews list to display Edit/Delete buttons exclusively for this user
if (typeof renderReviewsList === "function") {
renderReviewsList();
}
} }
function scrollToGoogleAuth() { function scrollToGoogleAuth() {
@@ -3136,6 +3155,7 @@
function googleLogout() { function googleLogout() {
currentUser = null; currentUser = null;
deskUser = null; deskUser = null;
if (typeof cancelEditReview === "function") cancelEditReview();
localStorage.removeItem("aira_google_user"); localStorage.removeItem("aira_google_user");
localStorage.removeItem("aira_founder_desk_user"); localStorage.removeItem("aira_founder_desk_user");
if (window.google && google.accounts && google.accounts.id) { if (window.google && google.accounts && google.accounts.id) {
@@ -3213,6 +3233,117 @@
renderReviewsList(); renderReviewsList();
} }
// 1. Start Editing an Existing Review (Owner only!)
function startEditReview(id) {
if (!currentUser) {
alert("Please sign in with Google to edit your review.");
return;
}
const review = liveReviews.find(r => r.id === id);
if (!review) return;
if (!review.email || review.email.toLowerCase() !== currentUser.email.toLowerCase()) {
alert("Unauthorized: You can only edit your own review!");
return;
}
editingReviewId = review.id;
const feedbackTextEl = document.getElementById("feedbackContent");
if (feedbackTextEl) feedbackTextEl.value = review.text;
setFeedbackRating(review.rating || 5);
if (review.tag) {
currentTag = review.tag;
document.querySelectorAll("#tag-picker .tag-opt").forEach(b => {
if (b.textContent.trim() === review.tag.trim()) {
b.className = "tag-opt active px-3 py-1.5 rounded-lg text-xs font-semibold bg-blue-600 text-white transition";
} else {
b.className = "tag-opt px-3 py-1.5 rounded-lg text-xs font-semibold bg-slate-100 text-slate-700 hover:bg-slate-200 transition";
}
});
}
const submitBtn = document.getElementById("submit-feedback-btn");
if (submitBtn) {
submitBtn.innerHTML = `<i class="fas fa-check text-xs"></i> Update Review`;
}
const indicator = document.getElementById("editing-review-indicator");
if (indicator) indicator.classList.remove("hidden");
const formBox = document.getElementById("google-feedback-loggedin");
if (formBox) {
formBox.scrollIntoView({ behavior: "smooth", block: "center" });
if (feedbackTextEl) feedbackTextEl.focus();
}
}
// 2. Cancel Edit Mode
function cancelEditReview() {
editingReviewId = null;
const feedbackTextEl = document.getElementById("feedbackContent");
if (feedbackTextEl) feedbackTextEl.value = "";
const submitBtn = document.getElementById("submit-feedback-btn");
if (submitBtn) {
submitBtn.innerHTML = `<i class="fas fa-paper-plane text-xs"></i> Post Verified Review`;
}
const indicator = document.getElementById("editing-review-indicator");
if (indicator) indicator.classList.add("hidden");
}
// 3. Delete Review (Owner only!)
async function deleteMyReview(id) {
if (!currentUser) {
alert("Please sign in with Google to manage your review.");
return;
}
const review = liveReviews.find(r => r.id === id);
if (!review) return;
if (!review.email || review.email.toLowerCase() !== currentUser.email.toLowerCase()) {
alert("Unauthorized: You can only delete your own review!");
return;
}
if (!confirm("Are you sure you want to delete your review permanently?")) {
return;
}
try {
const res = await fetch(REVIEWS_API_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
action: "delete",
id: review.id,
email: currentUser.email
})
});
const data = await res.json();
if (res.ok && data.success) {
liveReviews = Array.isArray(data.reviews) ? data.reviews : liveReviews.filter(r => r.id !== review.id);
localStorage.setItem("aira_verified_reviews", JSON.stringify(liveReviews));
renderReviewsList();
if (editingReviewId === review.id) {
cancelEditReview();
}
alert("Your review has been deleted.");
} else {
alert(data.error || "Failed to delete review.");
}
} catch(err) {
console.error("[Delete Review Error]:", err);
alert("Network error while deleting review.");
}
}
// Submit Verified Review via Sovereign API Gateway // Submit Verified Review via Sovereign API Gateway
async function handleFeedbackSubmit(e) { async function handleFeedbackSubmit(e) {
e.preventDefault(); e.preventDefault();
@@ -3225,27 +3356,29 @@
const text = feedbackTextEl.value.trim(); const text = feedbackTextEl.value.trim();
if (!text) return; if (!text) return;
const isEditing = Boolean(editingReviewId);
const submitBtn = document.getElementById("submit-feedback-btn"); const submitBtn = document.getElementById("submit-feedback-btn");
const originalBtnHtml = submitBtn.innerHTML; const originalBtnHtml = submitBtn.innerHTML;
submitBtn.disabled = true; submitBtn.disabled = true;
submitBtn.innerHTML = `<i class="fas fa-spinner fa-spin text-xs"></i> Publishing...`; submitBtn.innerHTML = `<i class="fas fa-spinner fa-spin text-xs"></i> ${isEditing ? "Updating..." : "Publishing..."}`;
const newReview = { const reviewPayload = {
id: "rev_" + Date.now(), id: editingReviewId || ("rev_" + Date.now()),
name: currentUser.name, name: currentUser.name,
email: currentUser.email, email: currentUser.email,
photo: currentUser.picture, photo: currentUser.picture,
rating: currentRating, rating: currentRating,
tag: currentTag, tag: currentTag,
text: text, text: text,
date: new Date().toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" }) date: new Date().toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" }),
isEdit: isEditing
}; };
try { try {
const res = await fetch(REVIEWS_API_URL, { const res = await fetch(REVIEWS_API_URL, {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify(newReview) body: JSON.stringify(reviewPayload)
}); });
if (res.ok) { if (res.ok) {
@@ -3254,29 +3387,31 @@
liveReviews = data.reviews; liveReviews = data.reviews;
} else { } else {
// Optimistic update // Optimistic update
const existingIdx = liveReviews.findIndex(r => r.email && r.email.toLowerCase() === newReview.email.toLowerCase()); const existingIdx = liveReviews.findIndex(r => r.id === reviewPayload.id || (r.email && r.email.toLowerCase() === reviewPayload.email.toLowerCase()));
if (existingIdx >= 0) liveReviews.splice(existingIdx, 1); if (existingIdx >= 0) liveReviews.splice(existingIdx, 1);
liveReviews.unshift(newReview); liveReviews.unshift(reviewPayload);
} }
} else { } else {
throw new Error(`Reviews API returned status ${res.status}`); const errData = await res.json().catch(() => ({}));
throw new Error(errData.error || `Reviews API error ${res.status}`);
} }
} catch(err) { } catch(err) {
console.error("[Reviews] API error, saving optimistically to local cache:", err); console.error("[Reviews] API error, saving optimistically to local cache:", err);
const existingIdx = liveReviews.findIndex(r => r.email && r.email.toLowerCase() === newReview.email.toLowerCase()); alert(err.message || "Could not publish review. Please try again.");
if (existingIdx >= 0) liveReviews.splice(existingIdx, 1); submitBtn.disabled = false;
liveReviews.unshift(newReview); submitBtn.innerHTML = originalBtnHtml;
return;
} }
localStorage.setItem("aira_verified_reviews", JSON.stringify(liveReviews)); localStorage.setItem("aira_verified_reviews", JSON.stringify(liveReviews));
renderReviewsList(); renderReviewsList();
submitBtn.disabled = false; submitBtn.disabled = false;
submitBtn.innerHTML = originalBtnHtml; cancelEditReview();
feedbackTextEl.value = "";
const successBanner = document.getElementById("feedback-success-banner"); const successBanner = document.getElementById("feedback-success-banner");
if (successBanner) { if (successBanner) {
successBanner.innerHTML = `<i class="fas fa-check-circle mr-1.5 text-emerald-600"></i> ${isEditing ? "Your review was successfully updated!" : "Thank you! Your verified review has been posted successfully."}`;
successBanner.classList.remove("hidden"); successBanner.classList.remove("hidden");
setTimeout(() => successBanner.classList.add("hidden"), 6000); setTimeout(() => successBanner.classList.add("hidden"), 6000);
} }
@@ -3317,8 +3452,43 @@
: '<i class="far fa-star text-slate-300 text-xs"></i>'; : '<i class="far fa-star text-slate-300 text-xs"></i>';
} }
const isOwner = Boolean(
currentUser &&
currentUser.email &&
r.email &&
(currentUser.email.trim().toLowerCase() === r.email.trim().toLowerCase())
);
const card = document.createElement("div"); const card = document.createElement("div");
card.className = "bg-white p-7 rounded-2xl border border-slate-200/80 shadow-md hover:shadow-xl transition-all duration-300 flex flex-col justify-between card-hover"; card.className = "bg-white p-7 rounded-2xl border " + (isOwner ? "border-blue-300 ring-2 ring-blue-500/10" : "border-slate-200/80") + " shadow-md hover:shadow-xl transition-all duration-300 flex flex-col justify-between card-hover";
const ownerActionsHtml = isOwner ? `
<div class="flex items-center gap-1.5">
<button
type="button"
onclick="startEditReview('${r.id}')"
class="px-2.5 py-1 text-[11px] font-semibold text-blue-600 bg-blue-50 hover:bg-blue-100 active:scale-95 rounded-lg transition flex items-center gap-1 border border-blue-200/60"
title="Edit your review"
>
<i class="fas fa-pen-to-square text-[10px]"></i> Edit
</button>
<button
type="button"
onclick="deleteMyReview('${r.id}')"
class="px-2.5 py-1 text-[11px] font-semibold text-rose-600 bg-rose-50 hover:bg-rose-100 active:scale-95 rounded-lg transition flex items-center gap-1 border border-rose-200/60"
title="Delete your review"
>
<i class="fas fa-trash-can text-[10px]"></i> Delete
</button>
</div>
` : ``;
const ownerBadgeHtml = isOwner ? `
<span class="text-[10px] font-bold text-blue-700 bg-blue-100/70 border border-blue-200 px-2 py-0.5 rounded-full">
Your Review
</span>
` : ``;
card.innerHTML = ` card.innerHTML = `
<div> <div>
<div class="flex items-start justify-between gap-3 mb-4"> <div class="flex items-start justify-between gap-3 mb-4">
@@ -3330,6 +3500,7 @@
<span class="inline-flex items-center gap-1 text-[10px] font-semibold bg-emerald-50 text-emerald-700 px-2 py-0.5 rounded-full border border-emerald-200"> <span class="inline-flex items-center gap-1 text-[10px] font-semibold bg-emerald-50 text-emerald-700 px-2 py-0.5 rounded-full border border-emerald-200">
<i class="fas fa-check-circle text-emerald-600 text-[9px]"></i> Verified <i class="fas fa-check-circle text-emerald-600 text-[9px]"></i> Verified
</span> </span>
${ownerBadgeHtml}
</div> </div>
<div class="text-[11px] text-slate-500 flex items-center gap-1 mt-0.5 font-mono"> <div class="text-[11px] text-slate-500 flex items-center gap-1 mt-0.5 font-mono">
<i class="fab fa-google text-slate-400 text-[10px]"></i> <i class="fab fa-google text-slate-400 text-[10px]"></i>
@@ -3351,8 +3522,8 @@
</div> </div>
<div class="pt-3 border-t border-slate-100 flex items-center justify-between text-xs text-slate-400"> <div class="pt-3 border-t border-slate-100 flex items-center justify-between text-xs text-slate-400">
<span class="flex items-center gap-1"><i class="fas fa-calendar-check text-[10px] text-blue-400"></i> Google Verified Review</span> <span class="flex items-center gap-1"><i class="fas fa-calendar-check text-[10px] text-blue-400"></i> ${r.date || "Recent"}</span>
<span>${r.date || "Recent"}</span> ${ownerActionsHtml}
</div> </div>
`; `;
container.appendChild(card); container.appendChild(card);