Fix AI chatbot role mapping, add markdown formatting, update system prompts, and handle OpenRouter API errors
This commit is contained in:
@@ -0,0 +1,324 @@
|
||||
/**
|
||||
* admin-chatbot.js — BookKeepPro Admin Chatbot Widget
|
||||
*
|
||||
* Provides:
|
||||
* - Admin status overview (fetches from /api/chatbot/admin-status)
|
||||
* - Admin FAQs
|
||||
*
|
||||
* Requires: auth.js (for authFetch)
|
||||
*/
|
||||
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
/* ─────────────────────────────────────────────
|
||||
Admin FAQ Knowledge Base
|
||||
───────────────────────────────────────────── */
|
||||
const FAQ_DATA = {
|
||||
"Document Review": [
|
||||
{
|
||||
q: "How do I review a document?",
|
||||
a: "From the <a href='/admin-dashboard'>Admin Dashboard</a>, click on any user. You'll see their uploaded documents. Click <b>Approve</b> or <b>Reject</b> and leave a note if needed."
|
||||
},
|
||||
{
|
||||
q: "What happens when I reject a document?",
|
||||
a: "The document's status changes to <b>Rejected</b> and the user is notified. They will see your review note and can upload a corrected version to replace it."
|
||||
},
|
||||
{
|
||||
q: "How do I upload admin documents for a user?",
|
||||
a: "Go to the user's detail page and scroll down to <b>Admin Documents</b>. You can upload tax returns, reports, and other finalized forms there. These will be visible to the user."
|
||||
}
|
||||
],
|
||||
"User Management": [
|
||||
{
|
||||
q: "How do I see user details?",
|
||||
a: "Simply click on any user in the <b>Admin Dashboard</b> table. This will take you to their detailed view where you can see their info and all their documents."
|
||||
},
|
||||
{
|
||||
q: "Can I add another admin?",
|
||||
a: "Currently, Super Admins can only be created via the backend script `create_super_admin.py` for security reasons."
|
||||
}
|
||||
],
|
||||
"Notifications": [
|
||||
{
|
||||
q: "How are users notified?",
|
||||
a: "Users receive automated emails when they sign up, when their documents are ready for review, and when you approve or reject their documents."
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
const CATEGORY_ICONS = {
|
||||
"Document Review": "📑",
|
||||
"User Management": "👥",
|
||||
"Notifications": "🔔"
|
||||
};
|
||||
|
||||
/* ─────────────────────────────────────────────
|
||||
Inject HTML
|
||||
───────────────────────────────────────────── */
|
||||
function injectWidget() {
|
||||
const widget = document.createElement("div");
|
||||
widget.id = "chatbot-widget";
|
||||
widget.innerHTML = `
|
||||
<button class="chatbot-fab" id="chatFab" aria-label="Open admin assistant" style="background: linear-gradient(135deg, var(--navy) 0%, var(--blue) 100%);">
|
||||
<span class="fab-icon">🤖</span>
|
||||
<span class="notif-dot"></span>
|
||||
</button>
|
||||
<div class="chatbot-window" id="chatWindow">
|
||||
<div class="chatbot-header" style="background: linear-gradient(135deg, var(--navy) 0%, #005fa3 100%);">
|
||||
<div class="bot-avatar">🤖</div>
|
||||
<div class="bot-info">
|
||||
<h4>Admin Assistant</h4>
|
||||
<span>System Insights & Help</span>
|
||||
</div>
|
||||
<button class="close-chat" id="chatClose" aria-label="Close chat">✕</button>
|
||||
</div>
|
||||
<div class="chatbot-messages" id="chatMessages"></div>
|
||||
</div>
|
||||
`;
|
||||
document.body.appendChild(widget);
|
||||
}
|
||||
|
||||
/* ─────────────────────────────────────────────
|
||||
Core Chat Logic
|
||||
───────────────────────────────────────────── */
|
||||
let messagesEl;
|
||||
|
||||
function addBotMessage(html) {
|
||||
const div = document.createElement("div");
|
||||
div.className = "chat-msg bot";
|
||||
div.innerHTML = html;
|
||||
messagesEl.appendChild(div);
|
||||
scrollToBottom();
|
||||
}
|
||||
|
||||
function addUserMessage(text) {
|
||||
const div = document.createElement("div");
|
||||
div.className = "chat-msg user";
|
||||
div.style.background = "linear-gradient(135deg, var(--navy), var(--blue))";
|
||||
div.textContent = text;
|
||||
messagesEl.appendChild(div);
|
||||
scrollToBottom();
|
||||
}
|
||||
|
||||
function showTyping() {
|
||||
const div = document.createElement("div");
|
||||
div.className = "typing-indicator";
|
||||
div.id = "typingIndicator";
|
||||
div.innerHTML = "<span></span><span></span><span></span>";
|
||||
messagesEl.appendChild(div);
|
||||
scrollToBottom();
|
||||
}
|
||||
|
||||
function hideTyping() {
|
||||
const el = document.getElementById("typingIndicator");
|
||||
if (el) el.remove();
|
||||
}
|
||||
|
||||
function scrollToBottom() {
|
||||
requestAnimationFrame(() => {
|
||||
messagesEl.scrollTop = messagesEl.scrollHeight;
|
||||
});
|
||||
}
|
||||
|
||||
function botReply(html, delay) {
|
||||
delay = delay || 600;
|
||||
showTyping();
|
||||
setTimeout(() => {
|
||||
hideTyping();
|
||||
addBotMessage(html);
|
||||
}, delay);
|
||||
}
|
||||
|
||||
/* ─────────────────────────────────────────────
|
||||
Quick Replies (Menu Buttons)
|
||||
───────────────────────────────────────────── */
|
||||
function addQuickReplies(options) {
|
||||
const wrapper = document.createElement("div");
|
||||
wrapper.className = "quick-replies";
|
||||
options.forEach(opt => {
|
||||
const btn = document.createElement("button");
|
||||
btn.className = "quick-reply-btn";
|
||||
btn.innerHTML = `<span class="qr-icon">${opt.icon}</span> ${opt.label}`;
|
||||
btn.onclick = () => {
|
||||
addUserMessage(opt.label);
|
||||
opt.action();
|
||||
};
|
||||
wrapper.appendChild(btn);
|
||||
});
|
||||
messagesEl.appendChild(wrapper);
|
||||
scrollToBottom();
|
||||
}
|
||||
|
||||
/* ─────────────────────────────────────────────
|
||||
Main Menu
|
||||
───────────────────────────────────────────── */
|
||||
function showMainMenu() {
|
||||
botReply("Hello Admin! 🛠️ How can I assist you today?", 400);
|
||||
setTimeout(() => {
|
||||
addQuickReplies([
|
||||
{ icon: "📊", label: "System Overview", action: handleSystemOverview },
|
||||
{ icon: "❓", label: "Admin FAQs", action: handleFAQCategories }
|
||||
]);
|
||||
}, 1050);
|
||||
}
|
||||
|
||||
function addBackButton() {
|
||||
const btn = document.createElement("button");
|
||||
btn.className = "back-btn";
|
||||
btn.innerHTML = "← Back to main menu";
|
||||
btn.onclick = () => {
|
||||
addUserMessage("Back to main menu");
|
||||
showMainMenu();
|
||||
};
|
||||
messagesEl.appendChild(btn);
|
||||
scrollToBottom();
|
||||
}
|
||||
|
||||
/* ─────────────────────────────────────────────
|
||||
System Overview Flow
|
||||
───────────────────────────────────────────── */
|
||||
async function handleSystemOverview() {
|
||||
const token = localStorage.getItem("token");
|
||||
if (!token) {
|
||||
botReply('You need to be logged in to view stats.', 500);
|
||||
setTimeout(addBackButton, 1200);
|
||||
return;
|
||||
}
|
||||
|
||||
showTyping();
|
||||
|
||||
try {
|
||||
const res = await window.authFetch("/api/chatbot/admin-status");
|
||||
if (!res || !res.ok) {
|
||||
hideTyping();
|
||||
addBotMessage("Sorry, I couldn't fetch the system status right now.");
|
||||
addBackButton();
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
hideTyping();
|
||||
|
||||
addBotMessage(`Here is the current system overview:`);
|
||||
|
||||
const summaryHtml = `
|
||||
<div class="status-summary" style="grid-template-columns: repeat(2, 1fr);">
|
||||
<div class="summary-item" style="grid-column: span 2;">
|
||||
<span class="count">${data.total_users}</span>
|
||||
<span class="label">Total Users</span>
|
||||
</div>
|
||||
<div class="summary-item pending">
|
||||
<span class="count">${data.pending_personal}</span>
|
||||
<span class="label">Pending Personal</span>
|
||||
</div>
|
||||
<div class="summary-item pending">
|
||||
<span class="count">${data.pending_business}</span>
|
||||
<span class="label">Pending Business</span>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
addBotMessage(summaryHtml);
|
||||
|
||||
if (data.total_pending > 0) {
|
||||
setTimeout(() => {
|
||||
addBotMessage(`You have a total of <b>${data.total_pending} documents</b> waiting for review!`);
|
||||
}, 400);
|
||||
} else {
|
||||
setTimeout(() => {
|
||||
addBotMessage("All caught up! 🎉 There are no pending documents to review right now.");
|
||||
}, 400);
|
||||
}
|
||||
|
||||
setTimeout(addBackButton, 800);
|
||||
|
||||
} catch (err) {
|
||||
hideTyping();
|
||||
addBotMessage("Oops! Something went wrong while fetching stats.");
|
||||
addBackButton();
|
||||
}
|
||||
}
|
||||
|
||||
/* ─────────────────────────────────────────────
|
||||
FAQ Flow
|
||||
───────────────────────────────────────────── */
|
||||
function handleFAQCategories() {
|
||||
botReply("Choose a category to view admin guides:", 400);
|
||||
setTimeout(() => {
|
||||
const options = Object.keys(FAQ_DATA).map(cat => ({
|
||||
icon: CATEGORY_ICONS[cat] || "📌",
|
||||
label: cat,
|
||||
action: () => showFAQList(cat)
|
||||
}));
|
||||
options.push({ icon: "←", label: "Back to main menu", action: showMainMenu });
|
||||
addQuickReplies(options);
|
||||
}, 1050);
|
||||
}
|
||||
|
||||
function showFAQList(category) {
|
||||
addBotMessage(`<b>${CATEGORY_ICONS[category] || ""} ${category}</b> — Select a guide:`);
|
||||
|
||||
const wrapper = document.createElement("div");
|
||||
FAQ_DATA[category].forEach(item => {
|
||||
const btn = document.createElement("button");
|
||||
btn.className = "faq-question";
|
||||
btn.textContent = item.q;
|
||||
btn.onclick = () => {
|
||||
addUserMessage(item.q);
|
||||
botReply(item.a, 500);
|
||||
setTimeout(() => {
|
||||
addQuickReplies([
|
||||
{ icon: "📌", label: "More " + category + " questions", action: () => showFAQList(category) },
|
||||
{ icon: "🏠", label: "Back to main menu", action: showMainMenu }
|
||||
]);
|
||||
}, 1200);
|
||||
};
|
||||
wrapper.appendChild(btn);
|
||||
});
|
||||
messagesEl.appendChild(wrapper);
|
||||
scrollToBottom();
|
||||
}
|
||||
|
||||
/* ─────────────────────────────────────────────
|
||||
Initialize Widget
|
||||
───────────────────────────────────────────── */
|
||||
function init() {
|
||||
injectWidget();
|
||||
|
||||
const fab = document.getElementById("chatFab");
|
||||
const window_ = document.getElementById("chatWindow");
|
||||
const close_ = document.getElementById("chatClose");
|
||||
messagesEl = document.getElementById("chatMessages");
|
||||
|
||||
let isOpen = false;
|
||||
let hasOpened = false;
|
||||
|
||||
function toggle() {
|
||||
isOpen = !isOpen;
|
||||
fab.classList.toggle("open", isOpen);
|
||||
window_.classList.toggle("visible", isOpen);
|
||||
sessionStorage.setItem("admin_chatbot_open", isOpen ? "1" : "0");
|
||||
|
||||
if (isOpen && !hasOpened) {
|
||||
hasOpened = true;
|
||||
showMainMenu();
|
||||
}
|
||||
}
|
||||
|
||||
fab.addEventListener("click", toggle);
|
||||
close_.addEventListener("click", toggle);
|
||||
|
||||
// Restore state from session
|
||||
if (sessionStorage.getItem("admin_chatbot_open") === "1") {
|
||||
toggle();
|
||||
}
|
||||
}
|
||||
|
||||
/* Start when DOM is ready */
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", init);
|
||||
} else {
|
||||
init();
|
||||
}
|
||||
|
||||
})();
|
||||
@@ -0,0 +1,6 @@
|
||||
// admin.js — legacy reference file, not imported by any HTML page.
|
||||
// admin-dashboard.html uses auth.js + inline scripts exclusively.
|
||||
// Kept here as a reference stub; safe to delete if no longer needed.
|
||||
|
||||
// All shared utilities (authFetch, logoutUser, guardAuth, escapeHtml,
|
||||
// reviewBadge, buildYearOptions) are now in /js/auth.js.
|
||||
@@ -0,0 +1,154 @@
|
||||
/**
|
||||
* auth.js — shared utilities loaded by every protected page.
|
||||
*
|
||||
* Provides:
|
||||
* authFetch(url, options) — fetch with Bearer token + auto-redirect on 401
|
||||
* logoutUser() — clear storage and redirect to /login
|
||||
* guardAuth(requiredRoles) — redirect if token missing or role not in list
|
||||
* escapeHtml(str) — XSS-safe string for innerHTML insertion
|
||||
* reviewBadge(status) — returns safe HTML badge string
|
||||
* buildYearOptions(selectId, def) — populate a <select> with current year - 3 years
|
||||
* initSessionWarning() — toast warning + auto-logout before JWT expiry (#17)
|
||||
* makeLabelsKeyboardAccessible(root) — make upload labels keyboard-navigable (#18)
|
||||
*/
|
||||
|
||||
(function () {
|
||||
|
||||
/* ── escapeHtml ──────────────────────────────────────────────────────── */
|
||||
window.escapeHtml = function (str) {
|
||||
return String(str == null ? "" : str)
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'");
|
||||
};
|
||||
|
||||
/* ── authFetch ───────────────────────────────────────────────────────── */
|
||||
window.authFetch = async function (url, options = {}) {
|
||||
const token = localStorage.getItem("token");
|
||||
options.headers = {
|
||||
...(options.headers || {}),
|
||||
Authorization: "Bearer " + token,
|
||||
};
|
||||
const res = await fetch(url, options);
|
||||
if (res.status === 401) {
|
||||
localStorage.removeItem("token");
|
||||
localStorage.removeItem("role");
|
||||
localStorage.removeItem("selected_tax_year");
|
||||
window.location.href = "/login";
|
||||
return null;
|
||||
}
|
||||
return res;
|
||||
};
|
||||
|
||||
/* ── logoutUser ──────────────────────────────────────────────────────── */
|
||||
window.logoutUser = function () {
|
||||
const role = localStorage.getItem("role");
|
||||
localStorage.removeItem("token");
|
||||
localStorage.removeItem("role");
|
||||
localStorage.removeItem("selected_tax_year");
|
||||
window.location.href = "/login";
|
||||
};
|
||||
|
||||
/* ── guardAuth ───────────────────────────────────────────────────────── */
|
||||
window.guardAuth = function (requiredRoles = ["user"]) {
|
||||
const token = localStorage.getItem("token");
|
||||
const role = localStorage.getItem("role");
|
||||
if (!token || !requiredRoles.includes(role)) {
|
||||
localStorage.removeItem("token");
|
||||
localStorage.removeItem("role");
|
||||
localStorage.removeItem("selected_tax_year");
|
||||
window.location.href = "/login";
|
||||
}
|
||||
};
|
||||
|
||||
/* ── reviewBadge ─────────────────────────────────────────────────────── */
|
||||
window.reviewBadge = function (reviewStatus) {
|
||||
const map = {
|
||||
approved: { bg: "#e6f9ec", color: "#2e7d32", text: `<span class="material-symbols-outlined">check</span> Approved` },
|
||||
rejected: { bg: "#fdecea", color: "#c62828", text: `<span class="material-symbols-outlined">close</span> Rejected` },
|
||||
pending: { bg: "#fff8e1", color: "#f57f17", text: `<span class="material-symbols-outlined">pending</span> Pending Review` },
|
||||
};
|
||||
const s = map[reviewStatus] || map.pending;
|
||||
return `<span style="
|
||||
display:inline-block;padding:2px 8px;border-radius:20px;
|
||||
font-size:11px;font-weight:600;
|
||||
background:${s.bg};color:${s.color};vertical-align:middle;margin-left:6px;
|
||||
">${s.text}</span>`;
|
||||
};
|
||||
|
||||
/* ── buildYearOptions ────────────────────────────────────────────────── */
|
||||
window.buildYearOptions = function (selectId, defaultYear) {
|
||||
const sel = document.getElementById(selectId);
|
||||
if (!sel) return;
|
||||
sel.innerHTML = "";
|
||||
const cur = new Date().getFullYear();
|
||||
const def = defaultYear || cur;
|
||||
for (let y = cur; y >= cur - 3; y--) {
|
||||
const o = document.createElement("option");
|
||||
o.value = y;
|
||||
o.textContent = y;
|
||||
if (y === def) o.selected = true;
|
||||
sel.appendChild(o);
|
||||
}
|
||||
};
|
||||
|
||||
/* ── initSessionWarning (#17) ────────────────────────────────────────── */
|
||||
/**
|
||||
* Call once after guardAuth() on every protected page.
|
||||
* Shows a persistent warning toast 5 minutes before token expiry,
|
||||
* then auto-logs out when the token actually expires.
|
||||
*/
|
||||
window.initSessionWarning = function () {
|
||||
const token = localStorage.getItem("token");
|
||||
if (!token) return;
|
||||
try {
|
||||
const payload = JSON.parse(atob(token.split(".")[1]));
|
||||
const expiresIn = (payload.exp * 1000) - Date.now();
|
||||
|
||||
// Already expired — kick out immediately
|
||||
if (expiresIn <= 0) { window.logoutUser(); return; }
|
||||
|
||||
// Warn 5 minutes before expiry
|
||||
const warnAt = expiresIn - 5 * 60 * 1000;
|
||||
if (warnAt > 0) {
|
||||
setTimeout(() => {
|
||||
if (window.showToast) {
|
||||
showToast("Your session expires in 5 minutes. Save your work.", "warning", 0);
|
||||
}
|
||||
}, warnAt);
|
||||
}
|
||||
|
||||
// Auto-logout at exact expiry
|
||||
setTimeout(() => {
|
||||
if (window.showToast) showToast("Session expired. Redirecting to login…", "info");
|
||||
setTimeout(window.logoutUser, 2000);
|
||||
}, expiresIn);
|
||||
|
||||
} catch (e) {
|
||||
// Malformed token — let the next API call handle it via 401
|
||||
}
|
||||
};
|
||||
|
||||
/* ── makeLabelsKeyboardAccessible (#18) ─────────────────────────────── */
|
||||
/**
|
||||
* Make styled <label> upload buttons keyboard-accessible.
|
||||
* Call after rendering any upload labels with tabindex="0".
|
||||
* @param {Element} [root=document] — scope the search to a container
|
||||
*/
|
||||
window.makeLabelsKeyboardAccessible = function (root) {
|
||||
const scope = root || document;
|
||||
scope.querySelectorAll("label.upload-label[tabindex='0']").forEach(lbl => {
|
||||
if (lbl._kbAttached) return;
|
||||
lbl._kbAttached = true;
|
||||
lbl.addEventListener("keydown", e => {
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
e.preventDefault();
|
||||
lbl.click();
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
})();
|
||||
@@ -0,0 +1,416 @@
|
||||
/**
|
||||
* chatbot.js — BookKeepPro Chatbot Widget
|
||||
*
|
||||
* Provides:
|
||||
* - Document status checking (fetches from /api/chatbot/doc-status)
|
||||
* - FAQ answers (hardcoded knowledge base)
|
||||
* - Contact support shortcut
|
||||
*
|
||||
* Requires: auth.js (for authFetch)
|
||||
*/
|
||||
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
/* ─────────────────────────────────────────────
|
||||
FAQ Knowledge Base
|
||||
───────────────────────────────────────────── */
|
||||
const FAQ_DATA = {
|
||||
"Account": [
|
||||
{
|
||||
q: "How do I reset my password?",
|
||||
a: 'Go to the <a href="/login">login page</a> and click <b>"Forgot Password"</b>. Enter your email and we\'ll send a reset link to your inbox.'
|
||||
},
|
||||
{
|
||||
q: "How do I verify my email?",
|
||||
a: 'Check your inbox for a verification email from BookKeepPro. Click the link inside to verify. If you didn\'t receive it, visit the <a href="/resend-verification">Resend Verification</a> page.'
|
||||
},
|
||||
{
|
||||
q: "How do I update my profile?",
|
||||
a: 'Go to your <a href="/profile">Profile page</a> to update your name, phone number, or change your password.'
|
||||
},
|
||||
{
|
||||
q: "Can I change my email address?",
|
||||
a: "Currently, email addresses cannot be changed once registered. Please contact support if you need assistance."
|
||||
}
|
||||
],
|
||||
"Documents": [
|
||||
{
|
||||
q: "What file types are accepted?",
|
||||
a: "We accept <b>PDF, JPG, PNG, WEBP, DOC, and DOCX</b> files. The maximum file size is <b>10 MB</b>."
|
||||
},
|
||||
{
|
||||
q: 'What does "Pending" status mean?',
|
||||
a: 'Your document has been <b>uploaded successfully</b> and is waiting for an admin to review it. You\'ll be notified once it\'s reviewed.'
|
||||
},
|
||||
{
|
||||
q: 'What does "Rejected" mean?',
|
||||
a: "The admin found an issue with your document. Check the <b>review note</b> for details about what needs to be fixed, then re-upload a corrected version."
|
||||
},
|
||||
{
|
||||
q: "How long does review take?",
|
||||
a: "Typically <b>1–3 business days</b>. You'll receive an email notification when your documents are reviewed."
|
||||
},
|
||||
{
|
||||
q: "Can I replace an uploaded document?",
|
||||
a: "Yes! Simply go to the upload page for that document type and upload a new file. It will replace the previous one."
|
||||
}
|
||||
],
|
||||
"Tax Filing": [
|
||||
{
|
||||
q: "What tax years are supported?",
|
||||
a: "We currently support tax years <b>2023, 2024, 2025, and 2026</b>."
|
||||
},
|
||||
{
|
||||
q: "What personal documents do I need?",
|
||||
a: 'An <b>Individual Taxpayer Organizer</b> for your tax year. Visit the <a href="/upload-personal">Personal Documents</a> page for the full checklist.'
|
||||
},
|
||||
{
|
||||
q: "What business documents do I need?",
|
||||
a: '<b>S-Corp, LLC, or Partnership Organizer</b> plus Certificate of Formation, EIN, and Annual Financial Statements. Visit the <a href="/upload-business">Business Documents</a> page.'
|
||||
}
|
||||
],
|
||||
"Security": [
|
||||
{
|
||||
q: "Is my data secure?",
|
||||
a: "Absolutely. All files are stored securely on our servers with <b>encrypted access tokens</b>. Only you and authorized admins can view your documents."
|
||||
},
|
||||
{
|
||||
q: "Who can see my documents?",
|
||||
a: "Only <b>you</b> and <b>authorized BookKeepPro administrators</b>. Your documents are never shared with third parties."
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
const CATEGORY_ICONS = {
|
||||
"Account": "👤",
|
||||
"Documents": "📄",
|
||||
"Tax Filing": "📋",
|
||||
"Security": "🔒"
|
||||
};
|
||||
|
||||
/* ─────────────────────────────────────────────
|
||||
Inject HTML
|
||||
───────────────────────────────────────────── */
|
||||
function injectWidget() {
|
||||
const widget = document.createElement("div");
|
||||
widget.id = "chatbot-widget";
|
||||
widget.innerHTML = `
|
||||
<button class="chatbot-fab" id="chatFab" aria-label="Open chat assistant">
|
||||
<span class="fab-icon">💬</span>
|
||||
<span class="notif-dot"></span>
|
||||
</button>
|
||||
<div class="chatbot-window" id="chatWindow">
|
||||
<div class="chatbot-header">
|
||||
<div class="bot-avatar">🤖</div>
|
||||
<div class="bot-info">
|
||||
<h4>BookKeep Assistant</h4>
|
||||
<span>Always here to help</span>
|
||||
</div>
|
||||
<button class="close-chat" id="chatClose" aria-label="Close chat">✕</button>
|
||||
</div>
|
||||
<div class="chatbot-messages" id="chatMessages"></div>
|
||||
</div>
|
||||
`;
|
||||
document.body.appendChild(widget);
|
||||
}
|
||||
|
||||
/* ─────────────────────────────────────────────
|
||||
Core Chat Logic
|
||||
───────────────────────────────────────────── */
|
||||
let messagesEl;
|
||||
|
||||
function addBotMessage(html) {
|
||||
const div = document.createElement("div");
|
||||
div.className = "chat-msg bot";
|
||||
div.innerHTML = html;
|
||||
messagesEl.appendChild(div);
|
||||
scrollToBottom();
|
||||
}
|
||||
|
||||
function addUserMessage(text) {
|
||||
const div = document.createElement("div");
|
||||
div.className = "chat-msg user";
|
||||
div.textContent = text;
|
||||
messagesEl.appendChild(div);
|
||||
scrollToBottom();
|
||||
}
|
||||
|
||||
function showTyping() {
|
||||
const div = document.createElement("div");
|
||||
div.className = "typing-indicator";
|
||||
div.id = "typingIndicator";
|
||||
div.innerHTML = "<span></span><span></span><span></span>";
|
||||
messagesEl.appendChild(div);
|
||||
scrollToBottom();
|
||||
}
|
||||
|
||||
function hideTyping() {
|
||||
const el = document.getElementById("typingIndicator");
|
||||
if (el) el.remove();
|
||||
}
|
||||
|
||||
function scrollToBottom() {
|
||||
requestAnimationFrame(() => {
|
||||
messagesEl.scrollTop = messagesEl.scrollHeight;
|
||||
});
|
||||
}
|
||||
|
||||
function botReply(html, delay) {
|
||||
delay = delay || 600;
|
||||
showTyping();
|
||||
setTimeout(() => {
|
||||
hideTyping();
|
||||
addBotMessage(html);
|
||||
}, delay);
|
||||
}
|
||||
|
||||
/* ─────────────────────────────────────────────
|
||||
Quick Replies (Menu Buttons)
|
||||
───────────────────────────────────────────── */
|
||||
function addQuickReplies(options) {
|
||||
const wrapper = document.createElement("div");
|
||||
wrapper.className = "quick-replies";
|
||||
options.forEach(opt => {
|
||||
const btn = document.createElement("button");
|
||||
btn.className = "quick-reply-btn";
|
||||
btn.innerHTML = `<span class="qr-icon">${opt.icon}</span> ${opt.label}`;
|
||||
btn.onclick = () => {
|
||||
addUserMessage(opt.label);
|
||||
opt.action();
|
||||
};
|
||||
wrapper.appendChild(btn);
|
||||
});
|
||||
messagesEl.appendChild(wrapper);
|
||||
scrollToBottom();
|
||||
}
|
||||
|
||||
/* ─────────────────────────────────────────────
|
||||
Main Menu
|
||||
───────────────────────────────────────────── */
|
||||
function showMainMenu() {
|
||||
botReply("Hi there! 👋 I'm your BookKeep Assistant. How can I help you today?", 400);
|
||||
setTimeout(() => {
|
||||
addQuickReplies([
|
||||
{ icon: "📄", label: "Check Document Status", action: handleDocStatus },
|
||||
{ icon: "❓", label: "FAQs", action: handleFAQCategories },
|
||||
{ icon: "📞", label: "Contact Support", action: handleContact }
|
||||
]);
|
||||
}, 1050);
|
||||
}
|
||||
|
||||
function addBackButton() {
|
||||
const btn = document.createElement("button");
|
||||
btn.className = "back-btn";
|
||||
btn.innerHTML = "← Back to main menu";
|
||||
btn.onclick = () => {
|
||||
addUserMessage("Back to main menu");
|
||||
showMainMenu();
|
||||
};
|
||||
messagesEl.appendChild(btn);
|
||||
scrollToBottom();
|
||||
}
|
||||
|
||||
/* ─────────────────────────────────────────────
|
||||
Document Status Flow
|
||||
───────────────────────────────────────────── */
|
||||
async function handleDocStatus() {
|
||||
const token = localStorage.getItem("token");
|
||||
if (!token) {
|
||||
botReply('You need to <a href="/login">log in</a> first to check your document status.', 500);
|
||||
setTimeout(addBackButton, 1200);
|
||||
return;
|
||||
}
|
||||
|
||||
showTyping();
|
||||
|
||||
try {
|
||||
const res = await window.authFetch("/api/chatbot/doc-status");
|
||||
if (!res || !res.ok) {
|
||||
hideTyping();
|
||||
addBotMessage("Sorry, I couldn't fetch your document status right now. Please try again later.");
|
||||
addBackButton();
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
hideTyping();
|
||||
|
||||
if (data.summary.total === 0) {
|
||||
addBotMessage("You haven't uploaded any documents yet! 📭");
|
||||
addBotMessage('Head over to <a href="/upload-personal">Personal Documents</a> or <a href="/upload-business">Business Documents</a> to get started.');
|
||||
addBackButton();
|
||||
return;
|
||||
}
|
||||
|
||||
// Summary banner
|
||||
addBotMessage(`Here's your document overview — <b>${data.summary.total} documents</b> total:`);
|
||||
|
||||
const summaryHtml = `
|
||||
<div class="status-summary">
|
||||
<div class="summary-item pending">
|
||||
<span class="count">${data.summary.pending}</span>
|
||||
<span class="label">Pending</span>
|
||||
</div>
|
||||
<div class="summary-item approved">
|
||||
<span class="count">${data.summary.approved}</span>
|
||||
<span class="label">Approved</span>
|
||||
</div>
|
||||
<div class="summary-item rejected">
|
||||
<span class="count">${data.summary.rejected}</span>
|
||||
<span class="label">Rejected</span>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
addBotMessage(summaryHtml);
|
||||
|
||||
// Personal docs
|
||||
if (data.personal.length > 0) {
|
||||
let personalHtml = "<b>📂 Personal Documents:</b>";
|
||||
data.personal.forEach(doc => {
|
||||
personalHtml += buildDocCard(doc.doc_type, doc.status, doc.note, doc.tax_year);
|
||||
});
|
||||
addBotMessage(personalHtml);
|
||||
}
|
||||
|
||||
// Business docs
|
||||
if (data.business.length > 0) {
|
||||
let businessHtml = "<b>💼 Business Documents:</b>";
|
||||
data.business.forEach(doc => {
|
||||
businessHtml += buildDocCard(doc.business_type, doc.status, doc.note, doc.tax_year);
|
||||
});
|
||||
addBotMessage(businessHtml);
|
||||
}
|
||||
|
||||
// Alert on rejected
|
||||
if (data.summary.rejected > 0) {
|
||||
setTimeout(() => {
|
||||
addBotMessage('⚠️ You have <b>' + data.summary.rejected + ' rejected</b> document(s). Please check the review notes and re-upload corrected versions.');
|
||||
}, 300);
|
||||
}
|
||||
|
||||
setTimeout(addBackButton, 500);
|
||||
|
||||
} catch (err) {
|
||||
hideTyping();
|
||||
addBotMessage("Oops! Something went wrong while fetching your status. Please try again.");
|
||||
addBackButton();
|
||||
}
|
||||
}
|
||||
|
||||
function buildDocCard(name, status, note, year) {
|
||||
const statusIcon = status === "approved" ? "🟢" : status === "rejected" ? "🔴" : "🟡";
|
||||
const noteHtml = note ? `<div class="doc-note">📝 ${escapeText(note)}</div>` : "";
|
||||
return `
|
||||
<div class="doc-status-card">
|
||||
<div class="doc-name">${escapeText(name)}</div>
|
||||
<div class="doc-year">Tax Year: ${year}</div>
|
||||
<span class="doc-badge ${status}">${statusIcon} ${status}</span>
|
||||
${noteHtml}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function escapeText(str) {
|
||||
if (typeof window.escapeHtml === "function") return window.escapeHtml(str);
|
||||
const div = document.createElement("div");
|
||||
div.textContent = str || "";
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
/* ─────────────────────────────────────────────
|
||||
FAQ Flow
|
||||
───────────────────────────────────────────── */
|
||||
function handleFAQCategories() {
|
||||
botReply("Choose a category to browse common questions:", 400);
|
||||
setTimeout(() => {
|
||||
const options = Object.keys(FAQ_DATA).map(cat => ({
|
||||
icon: CATEGORY_ICONS[cat] || "📌",
|
||||
label: cat,
|
||||
action: () => showFAQList(cat)
|
||||
}));
|
||||
options.push({ icon: "←", label: "Back to main menu", action: showMainMenu });
|
||||
addQuickReplies(options);
|
||||
}, 1050);
|
||||
}
|
||||
|
||||
function showFAQList(category) {
|
||||
addBotMessage(`<b>${CATEGORY_ICONS[category] || ""} ${category}</b> — Pick a question:`);
|
||||
|
||||
const wrapper = document.createElement("div");
|
||||
FAQ_DATA[category].forEach(item => {
|
||||
const btn = document.createElement("button");
|
||||
btn.className = "faq-question";
|
||||
btn.textContent = item.q;
|
||||
btn.onclick = () => {
|
||||
addUserMessage(item.q);
|
||||
botReply(item.a, 500);
|
||||
setTimeout(() => {
|
||||
addQuickReplies([
|
||||
{ icon: "📌", label: "More " + category + " questions", action: () => showFAQList(category) },
|
||||
{ icon: "🏠", label: "Back to main menu", action: showMainMenu }
|
||||
]);
|
||||
}, 1200);
|
||||
};
|
||||
wrapper.appendChild(btn);
|
||||
});
|
||||
messagesEl.appendChild(wrapper);
|
||||
scrollToBottom();
|
||||
}
|
||||
|
||||
/* ─────────────────────────────────────────────
|
||||
Contact Support Flow
|
||||
───────────────────────────────────────────── */
|
||||
function handleContact() {
|
||||
botReply(
|
||||
'You can reach our team anytime! 📧<br><br>' +
|
||||
'<b>Email:</b> <a href="mailto:atharvg.aiindia@gmail.com">atharvg.aiindia@gmail.com</a><br><br>' +
|
||||
'Or use our <a href="/contact">Contact Form</a> and we\'ll get back to you within 24 hours.',
|
||||
500
|
||||
);
|
||||
setTimeout(addBackButton, 1200);
|
||||
}
|
||||
|
||||
/* ─────────────────────────────────────────────
|
||||
Initialize Widget
|
||||
───────────────────────────────────────────── */
|
||||
function init() {
|
||||
injectWidget();
|
||||
|
||||
const fab = document.getElementById("chatFab");
|
||||
const window_ = document.getElementById("chatWindow");
|
||||
const close_ = document.getElementById("chatClose");
|
||||
messagesEl = document.getElementById("chatMessages");
|
||||
|
||||
let isOpen = false;
|
||||
let hasOpened = false;
|
||||
|
||||
function toggle() {
|
||||
isOpen = !isOpen;
|
||||
fab.classList.toggle("open", isOpen);
|
||||
window_.classList.toggle("visible", isOpen);
|
||||
sessionStorage.setItem("chatbot_open", isOpen ? "1" : "0");
|
||||
|
||||
if (isOpen && !hasOpened) {
|
||||
hasOpened = true;
|
||||
showMainMenu();
|
||||
}
|
||||
}
|
||||
|
||||
fab.addEventListener("click", toggle);
|
||||
close_.addEventListener("click", toggle);
|
||||
|
||||
// Restore state from session
|
||||
if (sessionStorage.getItem("chatbot_open") === "1") {
|
||||
toggle();
|
||||
}
|
||||
}
|
||||
|
||||
/* Start when DOM is ready */
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", init);
|
||||
} else {
|
||||
init();
|
||||
}
|
||||
|
||||
})();
|
||||
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* confirm-modal.js — non-blocking replacement for window.confirm().
|
||||
*
|
||||
* Usage:
|
||||
* const ok = await confirmModal("Delete this document?");
|
||||
* if (!ok) return;
|
||||
*
|
||||
* Optional second argument for the confirm button label:
|
||||
* await confirmModal("Remove user?", "Delete")
|
||||
*/
|
||||
|
||||
(function () {
|
||||
/* Inject styles once */
|
||||
if (!document.getElementById("confirm-modal-styles")) {
|
||||
const style = document.createElement("style");
|
||||
style.id = "confirm-modal-styles";
|
||||
style.textContent = `
|
||||
.cm-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0,0,0,0.35);
|
||||
z-index: 100000;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
animation: cm-fade-in 0.15s ease;
|
||||
}
|
||||
.cm-box {
|
||||
background: #fff;
|
||||
border-radius: 14px;
|
||||
padding: 28px 32px;
|
||||
max-width: 380px;
|
||||
width: 90%;
|
||||
box-shadow: 0 8px 32px rgba(0,0,0,0.18);
|
||||
text-align: center;
|
||||
animation: cm-slide-in 0.15s ease;
|
||||
}
|
||||
.cm-icon {
|
||||
font-size: 36px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.cm-message {
|
||||
font-family: "Poppins", "Segoe UI", sans-serif;
|
||||
font-size: 15px;
|
||||
color: #333;
|
||||
line-height: 1.5;
|
||||
margin-bottom: 22px;
|
||||
white-space: pre-line;
|
||||
}
|
||||
.cm-actions {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
justify-content: center;
|
||||
}
|
||||
.cm-btn {
|
||||
padding: 10px 24px;
|
||||
border-radius: 8px;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
transition: opacity 0.15s;
|
||||
}
|
||||
.cm-btn:hover { opacity: 0.85; }
|
||||
.cm-btn-cancel { background: #f0f0f0; color: #555; }
|
||||
.cm-btn-confirm { background: #ff4d4d; color: #fff; }
|
||||
@keyframes cm-fade-in { from { opacity:0 } to { opacity:1 } }
|
||||
@keyframes cm-slide-in { from { transform:scale(0.92) } to { transform:scale(1) } }
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} message — text shown in the modal
|
||||
* @param {string} [confirmLabel="Confirm"] — label for the confirm button
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
window.confirmModal = function (message, confirmLabel = "Confirm") {
|
||||
return new Promise((resolve) => {
|
||||
const backdrop = document.createElement("div");
|
||||
backdrop.className = "cm-backdrop";
|
||||
|
||||
backdrop.innerHTML = `
|
||||
<div class="cm-box" role="dialog" aria-modal="true">
|
||||
<div class="cm-icon"><span class="material-symbols-outlined">warning</span></div>
|
||||
<div class="cm-message">${escapeHtml ? escapeHtml(message) : message}</div>
|
||||
<div class="cm-actions">
|
||||
<button class="cm-btn cm-btn-cancel" id="cm-cancel">Cancel</button>
|
||||
<button class="cm-btn cm-btn-confirm" id="cm-confirm">${confirmLabel}</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
function cleanup(result) {
|
||||
backdrop.remove();
|
||||
resolve(result);
|
||||
}
|
||||
|
||||
backdrop.querySelector("#cm-cancel").addEventListener("click", () => cleanup(false));
|
||||
backdrop.querySelector("#cm-confirm").addEventListener("click", () => cleanup(true));
|
||||
|
||||
/* Close on backdrop click */
|
||||
backdrop.addEventListener("click", (e) => {
|
||||
if (e.target === backdrop) cleanup(false);
|
||||
});
|
||||
|
||||
/* Close on Escape */
|
||||
function onKeyDown(e) {
|
||||
if (e.key === "Escape") { document.removeEventListener("keydown", onKeyDown); cleanup(false); }
|
||||
}
|
||||
document.addEventListener("keydown", onKeyDown);
|
||||
|
||||
document.body.appendChild(backdrop);
|
||||
/* Focus the cancel button by default (safer UX) */
|
||||
backdrop.querySelector("#cm-cancel").focus();
|
||||
});
|
||||
};
|
||||
})();
|
||||
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* Password strength indicator.
|
||||
* Call initPasswordStrength("inputId") to attach to a password field.
|
||||
* A bar + label appear below the field automatically.
|
||||
*/
|
||||
|
||||
(function () {
|
||||
if (!document.getElementById("pw-strength-styles")) {
|
||||
const style = document.createElement("style");
|
||||
style.id = "pw-strength-styles";
|
||||
style.textContent = `
|
||||
.pw-strength-bar-wrap {
|
||||
height: 4px;
|
||||
background: #e0e0e0;
|
||||
border-radius: 2px;
|
||||
margin-top: -8px;
|
||||
margin-bottom: 10px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.pw-strength-bar {
|
||||
height: 100%;
|
||||
border-radius: 2px;
|
||||
transition: width 0.3s ease, background 0.3s ease;
|
||||
width: 0;
|
||||
}
|
||||
.pw-strength-label {
|
||||
font-size: 12px;
|
||||
margin-bottom: 10px;
|
||||
margin-top: -6px;
|
||||
font-weight: 500;
|
||||
}
|
||||
.pw-weak { background: #c62828; }
|
||||
.pw-medium { background: #f57f17; }
|
||||
.pw-strong { background: #2e7d32; }
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
|
||||
function checkStrength(pw) {
|
||||
if (!pw || pw.length < 8) return { level: "weak", pct: 25, label: "Too short (min 8 chars)", cls: "pw-weak" };
|
||||
const hasUpper = /[A-Z]/.test(pw);
|
||||
const hasNum = /[0-9]/.test(pw);
|
||||
const hasSymbol = /[^A-Za-z0-9]/.test(pw);
|
||||
const long = pw.length >= 12;
|
||||
|
||||
const score = [hasUpper, hasNum, hasSymbol, long].filter(Boolean).length;
|
||||
|
||||
if (score <= 1) return { level: "weak", pct: 33, label: "Weak — add uppercase & numbers", cls: "pw-weak" };
|
||||
if (score === 2) return { level: "medium", pct: 66, label: "Medium — getting better", cls: "pw-medium" };
|
||||
return { level: "strong", pct: 100, label: `Strong password <span class="material-symbols-outlined">check</span>`, cls: "pw-strong" };
|
||||
}
|
||||
|
||||
window.initPasswordStrength = function (inputId) {
|
||||
const input = document.getElementById(inputId);
|
||||
if (!input) return;
|
||||
|
||||
// Create bar + label
|
||||
const barWrap = document.createElement("div");
|
||||
barWrap.className = "pw-strength-bar-wrap";
|
||||
const bar = document.createElement("div");
|
||||
bar.className = "pw-strength-bar";
|
||||
barWrap.appendChild(bar);
|
||||
|
||||
const label = document.createElement("div");
|
||||
label.className = "pw-strength-label";
|
||||
label.style.color = "#888";
|
||||
|
||||
// Insert after input's parent wrapper (handles both plain input and wrapped input)
|
||||
const after = input.closest("div") || input;
|
||||
after.after(label);
|
||||
after.after(barWrap);
|
||||
|
||||
input.addEventListener("input", () => {
|
||||
const val = input.value;
|
||||
if (!val) {
|
||||
bar.style.width = "0";
|
||||
bar.className = "pw-strength-bar";
|
||||
label.textContent = "";
|
||||
return;
|
||||
}
|
||||
const { pct, label: lbl, cls } = checkStrength(val);
|
||||
bar.style.width = pct + "%";
|
||||
bar.className = "pw-strength-bar " + cls;
|
||||
label.innerHTML = lbl;
|
||||
label.style.color = cls === "pw-weak" ? "#c62828" : cls === "pw-medium" ? "#f57f17" : "#2e7d32";
|
||||
});
|
||||
};
|
||||
})();
|
||||
@@ -0,0 +1,70 @@
|
||||
async function signupUser() {
|
||||
const name = document.getElementById('name')?.value?.trim() || '';
|
||||
const email = document.getElementById('email')?.value?.trim() || '';
|
||||
const phone = document.getElementById('phone')?.value?.trim() || '';
|
||||
const password = document.getElementById('password')?.value || '';
|
||||
|
||||
if (!name || !email || !password) {
|
||||
showToast('Please fill in all required fields', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/auth/signup', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name, email, phone, password })
|
||||
});
|
||||
|
||||
const data = await res.json().catch(() => ({}));
|
||||
|
||||
if (!res.ok) {
|
||||
showToast(`Signup failed: ${data.detail || data.error || 'Unknown error'}`, 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
// Email verification required — show message, do NOT log in
|
||||
if (data.email_verification_required) {
|
||||
const container = document.getElementById('signupForm')?.closest('.auth-box')
|
||||
|| document.querySelector('.auth-box');
|
||||
if (container) {
|
||||
container.innerHTML = `
|
||||
<div style="text-align:center;padding:10px 0;">
|
||||
<div style="font-size:52px;margin-bottom:18px;">📧</div>
|
||||
<h2 style="color:#0077c8;margin-bottom:14px;">Check your email</h2>
|
||||
<p style="color:#555;font-size:15px;line-height:1.7;margin-bottom:20px;">
|
||||
We've sent a verification link to<br>
|
||||
<strong>${escapeHtml ? escapeHtml(email) : email}</strong><br><br>
|
||||
Click the link in the email to activate your account.
|
||||
</p>
|
||||
<p style="font-size:13px;color:#888;margin-bottom:6px;">Didn't receive it?</p>
|
||||
<a href="/resend-verification"
|
||||
style="color:#FF7F11;font-weight:600;font-size:14px;text-decoration:none;">
|
||||
Resend verification email
|
||||
</a>
|
||||
<div style="margin-top:20px;">
|
||||
<a href="/login" style="color:#0077c8;font-size:14px;">Back to Login</a>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
} else {
|
||||
showToast('Account created! Check your email to verify before logging in.', 'success', 6000);
|
||||
window.location.href = '/login';
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Admin accounts created via backend bypass verification — log them in directly
|
||||
if (data.access_token) {
|
||||
localStorage.setItem('token', data.access_token);
|
||||
localStorage.setItem('role', data.role || 'user');
|
||||
localStorage.setItem('user_id', data.user_id || '');
|
||||
window.location.href = '/dashboard';
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
console.error('Signup error', err);
|
||||
showToast('Network error. Please try again.', 'error');
|
||||
}
|
||||
}
|
||||
window.signupUser = signupUser;
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Spinner helpers — no dependencies.
|
||||
*
|
||||
* Usage:
|
||||
* showSpinner(container) // replace content with spinner
|
||||
* hideSpinner(container, html) // restore container with new html
|
||||
* spinnerHtml() // returns raw spinner html string (for innerHTML)
|
||||
*/
|
||||
|
||||
(function () {
|
||||
if (!document.getElementById("spinner-styles")) {
|
||||
const style = document.createElement("style");
|
||||
style.id = "spinner-styles";
|
||||
style.textContent = `
|
||||
.spinner-wrap {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
padding: 40px 20px;
|
||||
}
|
||||
.spinner {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border: 3px solid #e0e0e0;
|
||||
border-top-color: #0077c8;
|
||||
border-radius: 50%;
|
||||
animation: _spin 0.7s linear infinite;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.spinner.spinner-sm {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-width: 2px;
|
||||
}
|
||||
@keyframes _spin { to { transform: rotate(360deg); } }
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
|
||||
window.spinnerHtml = function (small = false) {
|
||||
return `<div class="spinner-wrap"><div class="spinner${small ? " spinner-sm" : ""}"></div></div>`;
|
||||
};
|
||||
|
||||
window.showSpinner = function (el) {
|
||||
if (!el) return;
|
||||
el._savedContent = el.innerHTML;
|
||||
el.innerHTML = spinnerHtml();
|
||||
};
|
||||
|
||||
window.hideSpinner = function (el, html) {
|
||||
if (!el) return;
|
||||
el.innerHTML = html !== undefined ? html : (el._savedContent || "");
|
||||
};
|
||||
|
||||
window.setButtonLoading = function(btn, isLoading, originalText = "") {
|
||||
if (!btn) return;
|
||||
if (isLoading) {
|
||||
btn.disabled = true;
|
||||
btn._savedText = btn.innerHTML;
|
||||
btn.innerHTML = `<div class="spinner spinner-sm" style="border-top-color:#fff; border-right-color:rgba(255,255,255,0.3); border-bottom-color:rgba(255,255,255,0.3); border-left-color:rgba(255,255,255,0.3); width:16px; height:16px; display:inline-block; vertical-align:middle; margin-right:8px;"></div> ${originalText || 'Processing...'}`;
|
||||
} else {
|
||||
btn.disabled = false;
|
||||
btn.innerHTML = originalText || btn._savedText || "";
|
||||
}
|
||||
};
|
||||
})();
|
||||
@@ -0,0 +1,40 @@
|
||||
(function() {
|
||||
function setTheme(isDark) {
|
||||
if (isDark) {
|
||||
document.documentElement.classList.add('dark-theme');
|
||||
if (document.body) document.body.classList.add('dark-theme');
|
||||
localStorage.setItem('theme', 'dark');
|
||||
} else {
|
||||
document.documentElement.classList.remove('dark-theme');
|
||||
if (document.body) document.body.classList.remove('dark-theme');
|
||||
localStorage.setItem('theme', 'light');
|
||||
}
|
||||
// Update all toggle icons if they exist
|
||||
document.querySelectorAll('.theme-toggle-icon').forEach(icon => {
|
||||
icon.textContent = isDark ? 'light_mode' : 'dark_mode';
|
||||
});
|
||||
}
|
||||
|
||||
window.toggleTheme = function() {
|
||||
const isDark = document.documentElement.classList.contains('dark-theme');
|
||||
setTheme(!isDark);
|
||||
};
|
||||
|
||||
function initTheme() {
|
||||
const savedTheme = localStorage.getItem('theme');
|
||||
|
||||
if (savedTheme === 'dark') {
|
||||
setTheme(true);
|
||||
} else {
|
||||
setTheme(false);
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize immediately (for documentElement) to avoid flash
|
||||
initTheme();
|
||||
|
||||
// Also run on DOMContentLoaded to ensure body gets the class if script was in <head>
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
initTheme();
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* Toast notification system — no dependencies, no libraries.
|
||||
* Usage:
|
||||
* showToast("Saved successfully") // green success
|
||||
* showToast("Something failed", "error") // red error
|
||||
* showToast("Processing...", "info", 0) // blue, stays until dismissed
|
||||
* showToast("Check your input", "warning") // orange warning
|
||||
*/
|
||||
|
||||
(function () {
|
||||
// Inject styles once
|
||||
if (!document.getElementById("toast-styles")) {
|
||||
const style = document.createElement("style");
|
||||
style.id = "toast-styles";
|
||||
style.textContent = `
|
||||
#toast-container {
|
||||
position: fixed;
|
||||
bottom: 24px;
|
||||
right: 24px;
|
||||
z-index: 99999;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
max-width: 340px;
|
||||
}
|
||||
.toast {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
padding: 13px 16px;
|
||||
border-radius: 10px;
|
||||
font-family: "Poppins", "Segoe UI", sans-serif;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
line-height: 1.4;
|
||||
box-shadow: 0 4px 16px rgba(0,0,0,0.13);
|
||||
cursor: pointer;
|
||||
animation: toast-in 0.3s ease;
|
||||
transition: opacity 0.3s ease, transform 0.3s ease;
|
||||
}
|
||||
.toast.toast-out {
|
||||
opacity: 0;
|
||||
transform: translateX(20px);
|
||||
}
|
||||
.toast.success { background:#e6f9ec; color:#1b5e20; border-left:4px solid #2e7d32; }
|
||||
.toast.error { background:#fdecea; color:#b71c1c; border-left:4px solid #c62828; }
|
||||
.toast.info { background:#e3f2fd; color:#0d47a1; border-left:4px solid #1565c0; }
|
||||
.toast.warning { background:#fff8e1; color:#e65100; border-left:4px solid #f57f17; }
|
||||
.toast-icon { font-size: 18px; flex-shrink: 0; margin-top: 1px; }
|
||||
.toast-msg { flex: 1; }
|
||||
.toast-close { font-size: 16px; cursor: pointer; opacity: 0.5; flex-shrink: 0; margin-top: 1px; }
|
||||
.toast-close:hover { opacity: 1; }
|
||||
@keyframes toast-in {
|
||||
from { opacity: 0; transform: translateX(20px); }
|
||||
to { opacity: 1; transform: translateX(0); }
|
||||
}
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
|
||||
function getContainer() {
|
||||
let c = document.getElementById("toast-container");
|
||||
if (!c) {
|
||||
c = document.createElement("div");
|
||||
c.id = "toast-container";
|
||||
document.body.appendChild(c);
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
const ICONS = {
|
||||
success: '<span class="material-symbols-outlined">check_circle</span>',
|
||||
error: '<span class="material-symbols-outlined">cancel</span>',
|
||||
info: '<span class="material-symbols-outlined">info</span>',
|
||||
warning: '<span class="material-symbols-outlined">warning</span>',
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {string} message — text to show
|
||||
* @param {string} type — "success" | "error" | "info" | "warning"
|
||||
* @param {number} duration — ms before auto-dismiss (0 = stay until clicked)
|
||||
*/
|
||||
window.showToast = function (message, type = "success", duration = 3500) {
|
||||
const container = getContainer();
|
||||
const toast = document.createElement("div");
|
||||
toast.className = `toast ${type}`;
|
||||
|
||||
toast.innerHTML = `
|
||||
<span class="toast-icon">${ICONS[type] || "💬"}</span>
|
||||
<span class="toast-msg">${message}</span>
|
||||
<span class="toast-close" title="Dismiss">✕</span>
|
||||
`;
|
||||
|
||||
function dismiss() {
|
||||
toast.classList.add("toast-out");
|
||||
setTimeout(() => toast.remove(), 300);
|
||||
}
|
||||
|
||||
toast.addEventListener("click", dismiss);
|
||||
|
||||
if (duration > 0) {
|
||||
setTimeout(dismiss, duration);
|
||||
}
|
||||
|
||||
container.appendChild(toast);
|
||||
return toast;
|
||||
};
|
||||
})();
|
||||
Reference in New Issue
Block a user