const { useState, useEffect, useMemo, useRef } = React;
/* ============================================================
API CONFIG - read from window.API_URL
============================================================ */
const API_URL = window.API_URL || "api/api.php";
/* ============================================================
BRAND
============================================================ */
const BRAND = {
primary: "#a4214a",
primarySoft: "#c9527a",
primaryDark: "#6d1633",
ink: "#241D16",
sub: "#7A7168",
border: "#EBE0E4",
panel: "#FFFFFF",
panelBg: "#FDFBFB",
inputBg: "#F8F3F5",
good: "#0E8A5F",
warn: "#C07E0A",
bad: "#C0392B",
bg: "#FFFFFF",
};
/* ============================================================
SLA - service level agreement for answer speed
Target: 80% of days answered within 20 seconds.
NOTE: the store keeps an AVERAGE answer speed per day, not a
per-call breakdown, so a day counts as "within 20s" when its
average answer speed is <= 20s.
============================================================ */
const SLA_THRESHOLD_SECONDS = 20;
const SLA_TARGET_PCT = 80;
/* ============================================================
CALL RESULTS - matches the DSB inbound report
============================================================ */
const CALL_RESULTS = [
"Address Change",
"Accounts Query",
"Article/Editorial inquiry",
"Cancel",
"Cancel Autorenew",
"Change Package/Subscription Type",
"Complaints/Queries About Frequency Change",
"Complex Issue",
"Confirmations",
"Damaged issue",
"Double Charge",
"Duplicate Order",
"General Enquiry",
"Gift Subscription",
"Log-in/Password Assistance",
"Missed/Late Issue",
"New Subscription",
"Payment for Bill-me",
"Receiving Duplicate Copies",
"Referred Back To Agency",
"Refund Request",
"Remove From Mailing List",
"Renewal",
"Request For Receipt/Invoice",
"Rescue Offer Accepted",
"Sample Copy Request",
"Subscription price Issue/Queries",
"Subscription Status",
"Update Payment Details",
];
/* ============================================================
API LAYER
============================================================ */
async function apiLoad() {
try {
const r = await fetch(API_URL + "?api=load");
return await r.json();
} catch (e) { console.error("Load failed", e); return null; }
}
async function apiAuth(passcode) {
if (!API_URL || /YOURDOMAIN/i.test(API_URL)) return { ok: false, reason: "not_configured" };
try {
const r = await fetch(API_URL + "?api=auth", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ passcode }),
});
const j = await r.json();
return { ok: !!j.ok, reason: j.ok ? null : "wrong" };
} catch (e) { return { ok: false, reason: "unreachable" }; }
}
async function apiSave(data, passcode) {
try {
const r = await fetch(API_URL + "?api=save", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ passcode, data }),
});
const j = await r.json();
if (!j.ok) console.error("Save rejected:", j.error);
return j.ok;
} catch (e) { console.error("Save failed", e); return false; }
}
/* ============================================================
DATE HELPERS
============================================================ */
function pad2(n) { return String(n).padStart(2, "0"); }
function isoDate(d) { return d.getFullYear() + "-" + pad2(d.getMonth() + 1) + "-" + pad2(d.getDate()); }
function parseISO(s) { const [y, m, d] = s.split("-").map(Number); return new Date(y, m - 1, d); }
function today() { return isoDate(new Date()); }
function fmtDateLong(iso) {
const d = parseISO(iso);
const days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
const months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
return days[d.getDay()] + " " + d.getDate() + " " + months[d.getMonth()] + " " + d.getFullYear();
}
function fmtDateShort(iso) {
const d = parseISO(iso);
return pad2(d.getDate()) + "/" + pad2(d.getMonth() + 1) + "/" + d.getFullYear();
}
function monthLabel(y, m) {
const months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
return months[m] + " " + y;
}
function monthKey(y, m) { return y + "-" + pad2(m + 1); }
function daysInMonth(y, m) { return new Date(y, m + 1, 0).getDate(); }
function isoWeekOf(d) {
// ISO week: Monday-Sunday. Returns { year, week, start (Monday iso), end (Sunday iso) }
const t = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
const dayNum = t.getUTCDay() || 7;
t.setUTCDate(t.getUTCDate() + 4 - dayNum);
const yearStart = new Date(Date.UTC(t.getUTCFullYear(), 0, 1));
const weekNo = Math.ceil((((t - yearStart) / 86400000) + 1) / 7);
// Monday of that ISO week (in local time)
const monday = new Date(d);
const localDayNum = monday.getDay() || 7;
monday.setDate(monday.getDate() - (localDayNum - 1));
const sunday = new Date(monday);
sunday.setDate(monday.getDate() + 6);
return { year: t.getUTCFullYear(), week: weekNo, start: isoDate(monday), end: isoDate(sunday) };
}
function datesInRange(startIso, endIso) {
const out = [];
const s = parseISO(startIso), e = parseISO(endIso);
const cur = new Date(s);
while (cur <= e) {
out.push(isoDate(cur));
cur.setDate(cur.getDate() + 1);
}
return out;
}
function addMonths(y, m, delta) {
const d = new Date(y, m + delta, 1);
return { year: d.getFullYear(), month: d.getMonth() };
}
function addWeeks(startIso, delta) {
const d = parseISO(startIso);
d.setDate(d.getDate() + delta * 7);
return isoWeekOf(d);
}
/* ============================================================
TIME (SECONDS <-> HH:MM:SS) HELPERS
============================================================ */
function fmtSeconds(sec) {
if (sec == null || isNaN(sec)) return "-";
sec = Math.round(sec);
const h = Math.floor(sec / 3600);
const m = Math.floor((sec % 3600) / 60);
const s = sec % 60;
if (h > 0) return h + ":" + pad2(m) + ":" + pad2(s);
return m + ":" + pad2(s);
}
function parseTime(str) {
// Accepts: "102", "1:42", "01:42", "01:42:00", "0:01:42"
if (str == null) return null;
str = String(str).trim();
if (!str) return null;
if (/^\d+$/.test(str)) return parseInt(str, 10);
const parts = str.split(":").map((p) => parseInt(p, 10));
if (parts.some(isNaN)) return null;
if (parts.length === 2) return parts[0] * 60 + parts[1];
if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
return null;
}
function round1(n) { return Math.round(n * 10) / 10; }
/* ============================================================
CSV EXPORT
============================================================ */
function toCSV(rows) {
return rows.map((r) => r.map((c) => {
const s = String(c == null ? "" : c);
return /[",\n]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s;
}).join(",")).join("\r\n");
}
function downloadCSV(filename, rows) {
const csv = toCSV(rows);
const blob = new Blob(["\uFEFF" + csv], { type: "text/csv;charset=utf-8" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url; a.download = filename;
document.body.appendChild(a); a.click();
document.body.removeChild(a); URL.revokeObjectURL(url);
}
/* ============================================================
IMAGE HELPERS - resize uploaded logo to a sensible size
============================================================ */
async function fileToResizedDataURL(file, maxW, maxH) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
const img = new Image();
img.onload = () => {
let { width, height } = img;
const scale = Math.min(1, maxW / width, maxH / height);
width = Math.round(width * scale);
height = Math.round(height * scale);
const canvas = document.createElement("canvas");
canvas.width = width; canvas.height = height;
const ctx = canvas.getContext("2d");
ctx.imageSmoothingQuality = "high";
ctx.drawImage(img, 0, 0, width, height);
// Choose PNG for logos (transparency support); JPEG only for photos
resolve(canvas.toDataURL("image/png"));
};
img.onerror = reject;
img.src = reader.result;
};
reader.onerror = reject;
reader.readAsDataURL(file);
});
}
/* ============================================================
REPORT MATH
============================================================ */
function totalResults(results) {
if (!results) return 0;
return Object.values(results).reduce((s, n) => s + (Number(n) || 0), 0);
}
function abandonRate(r) {
if (!r || !r.callsReceived) return 0;
return (r.callsReceived - r.callsAnswered) / r.callsReceived * 100;
}
// Whether a single day's average answer speed met the <=20s SLA.
// Returns true, false, or null (no answer-speed data recorded for that day).
function dayMeetsSla(r) {
if (!r || r.avgAnswerSpeedSeconds == null) return null;
return Number(r.avgAnswerSpeedSeconds) <= SLA_THRESHOLD_SECONDS;
}
function aggregateReports(list) {
// Average time fields weighted by call count where sensible, sums for counts
let received = 0, answered = 0;
let talkSum = 0, answerSum = 0, wrapSum = 0;
let talkN = 0, answerN = 0, wrapN = 0;
let slaScoredDays = 0, slaMetDays = 0; // SLA: days answered within 20s
const results = {};
list.forEach((r) => {
received += Number(r.callsReceived) || 0;
answered += Number(r.callsAnswered) || 0;
const meets = dayMeetsSla(r);
if (meets !== null) { slaScoredDays += 1; if (meets) slaMetDays += 1; }
if (r.avgTalkTimeSeconds != null) {
talkSum += (Number(r.avgTalkTimeSeconds) || 0) * (Number(r.callsAnswered) || 1);
talkN += (Number(r.callsAnswered) || 1);
}
if (r.avgAnswerSpeedSeconds != null) {
answerSum += (Number(r.avgAnswerSpeedSeconds) || 0) * (Number(r.callsAnswered) || 1);
answerN += (Number(r.callsAnswered) || 1);
}
if (r.avgWrapTimeSeconds != null) {
wrapSum += (Number(r.avgWrapTimeSeconds) || 0) * (Number(r.callsAnswered) || 1);
wrapN += (Number(r.callsAnswered) || 1);
}
if (r.results) {
Object.entries(r.results).forEach(([k, v]) => {
results[k] = (results[k] || 0) + (Number(v) || 0);
});
}
});
return {
callsReceived: received,
callsAnswered: answered,
avgTalkTimeSeconds: talkN ? talkSum / talkN : null,
avgAnswerSpeedSeconds: answerN ? answerSum / answerN : null,
avgWrapTimeSeconds: wrapN ? wrapSum / wrapN : null,
abandonRate: received ? (received - answered) / received * 100 : 0,
results,
totalBillable: Object.values(results).reduce((s, n) => s + n, 0),
daysWithData: list.length,
slaScoredDays,
slaMetDays,
slaPct: slaScoredDays ? slaMetDays / slaScoredDays * 100 : null,
};
}
/* ============================================================
COMMON UI
============================================================ */
function Panel({ children, style, padding = 24 }) {
return (
{children}
);
}
function Btn({ children, onClick, variant = "primary", disabled, style, ...rest }) {
const styles = {
primary: { background: BRAND.primary, color: "#fff", border: "none" },
outline: { background: "transparent", color: BRAND.primary, border: "1px solid " + BRAND.primary },
ghost: { background: "transparent", color: BRAND.ink, border: "1px solid " + BRAND.border },
danger: { background: BRAND.bad, color: "#fff", border: "none" },
dangerOutline: { background: "transparent", color: BRAND.bad, border: "1px solid " + BRAND.bad + "88" },
};
const base = {
fontFamily: "'Archivo', sans-serif", fontWeight: 700, fontSize: 14,
padding: "10px 18px", borderRadius: 10, cursor: disabled ? "not-allowed" : "pointer",
opacity: disabled ? 0.5 : 1, transition: "transform 0.15s ease, box-shadow 0.15s ease, opacity 0.15s ease",
};
return (
!disabled && (e.currentTarget.style.transform = "translateY(1px)")}
onMouseUp={(e) => (e.currentTarget.style.transform = "translateY(0)")}
onMouseLeave={(e) => (e.currentTarget.style.transform = "translateY(0)")}
{...rest}>{children}
);
}
function Field({ label, children, hint }) {
return (
{label}
{children}
{hint && {hint}
}
);
}
function Input({ value, onChange, type = "text", placeholder, style, ...rest }) {
return (
onChange(e.target.value)}
placeholder={placeholder}
style={{
width: "100%", padding: "10px 12px",
border: "1px solid " + BRAND.border, borderRadius: 10,
background: BRAND.inputBg, color: BRAND.ink, fontSize: 14,
fontFamily: "'Inter', system-ui, sans-serif", outline: "none",
boxSizing: "border-box",
...style,
}}
{...rest} />
);
}
function PanelTitle({ children, sub, right }) {
return (
{children}
{sub &&
{sub}
}
{right}
);
}
function Modal({ children, onClose, maxWidth = 520 }) {
useEffect(() => {
const onKey = (e) => e.key === "Escape" && onClose();
window.addEventListener("keydown", onKey);
document.body.style.overflow = "hidden";
return () => {
window.removeEventListener("keydown", onKey);
document.body.style.overflow = "";
};
}, [onClose]);
return (
e.stopPropagation()}
style={{ background: BRAND.panel, borderRadius: 16, padding: 28, maxWidth, width: "100%",
boxShadow: "0 20px 60px rgba(0,0,0,0.25)" }}>
{children}
);
}
/* ============================================================
LOGIN SCREEN
============================================================ */
function LoginScreen({ onUnlock }) {
const [code, setCode] = useState("");
const [err, setErr] = useState(null);
const [busy, setBusy] = useState(false);
const inputRef = useRef();
useEffect(() => inputRef.current && inputRef.current.focus(), []);
const submit = async () => {
if (!code || busy) return;
setBusy(true);
const res = await apiAuth(code);
setBusy(false);
if (res.ok) {
onUnlock(code);
} else {
setErr(res.reason);
}
};
return (
Call Report Portal
Inbound Call Reporting
{ setCode(v); setErr(null); }}
placeholder="Enter your passcode"
onKeyDown={(e) => e.key === "Enter" && submit()}
style={{ fontSize: 16, textAlign: "center", letterSpacing: "0.15em" }} />
{err === "wrong" && (
Incorrect passcode
)}
{err === "unreachable" && (
Cannot reach the API. Check the api.php upload.
)}
{err === "not_configured" && (
API URL not configured. Open config.js.
)}
{busy ? "Signing in..." : "Sign in"}
© {new Date().getFullYear()} BCC Telemarketing · Kettering · Durban
);
}
/* ============================================================
CAMPAIGNS PAGE - Grid of campaign cards
============================================================ */
function CampaignsPage({ campaigns, reports, onOpen, onAdd, onDelete, onSignOut }) {
const [showAdd, setShowAdd] = useState(false);
const [confirmDel, setConfirmDel] = useState(null);
return (
Sign out
setShowAdd(true)}>+ Add campaign
{campaigns.length === 0 && (
No campaigns yet
Add your first campaign to start logging call reports.
setShowAdd(true)}>+ Add your first campaign
)}
{campaigns.length > 0 && (
{campaigns.map((c) => {
const campaignReports = reports[c.id] || {};
const reportCount = Object.keys(campaignReports).length;
const latest = Object.keys(campaignReports).sort().reverse()[0];
return (
onOpen(c)}
style={{
background: BRAND.panel, border: "1px solid " + BRAND.border, borderRadius: 14,
padding: 22, cursor: "pointer", boxShadow: "0 1px 3px rgba(0,0,0,0.05)",
transition: "transform 0.15s ease, box-shadow 0.15s ease",
display: "flex", flexDirection: "column", gap: 14, minHeight: 210,
}}
onMouseEnter={(e) => { e.currentTarget.style.transform = "translateY(-3px)"; e.currentTarget.style.boxShadow = "0 12px 30px rgba(164, 33, 74, 0.15)"; }}
onMouseLeave={(e) => { e.currentTarget.style.transform = "translateY(0)"; e.currentTarget.style.boxShadow = "0 1px 3px rgba(0,0,0,0.05)"; }}>
{c.logo ? (
) : (
{c.name.split(" ").map((w) => w[0]).slice(0, 3).join("")}
)}
{c.name}
{reportCount === 0 ? "No reports yet" :
reportCount + " report" + (reportCount === 1 ? "" : "s") + (latest ? " · latest " + fmtDateShort(latest) : "")}
{ e.stopPropagation(); setConfirmDel(c); }}
style={{ background: "transparent", border: "none", color: BRAND.sub, fontSize: 12, cursor: "pointer", padding: 4 }}>
Delete
);
})}
)}
{showAdd &&
setShowAdd(false)} onAdd={(c) => { onAdd(c); setShowAdd(false); }} />}
{confirmDel && (
setConfirmDel(null)}>
Delete campaign?
You are about to permanently delete {confirmDel.name} and all {Object.keys(reports[confirmDel.id] || {}).length} of its saved reports. This cannot be undone.
setConfirmDel(null)}>Cancel
{ onDelete(confirmDel.id); setConfirmDel(null); }}>Yes, delete
)}
);
}
function AddCampaignModal({ onClose, onAdd }) {
const [name, setName] = useState("");
const [logo, setLogo] = useState("");
const [busy, setBusy] = useState(false);
const [err, setErr] = useState("");
const handleFile = async (file) => {
if (!file) return;
if (!/^image\//.test(file.type)) { setErr("Please upload an image file (PNG, JPG, SVG)."); return; }
setBusy(true);
try {
const data = await fileToResizedDataURL(file, 600, 400);
setLogo(data);
setErr("");
} catch (e) {
setErr("Could not read that image.");
}
setBusy(false);
};
const submit = () => {
if (!name.trim()) return;
onAdd({ id: "camp-" + Date.now() + "-" + Math.floor(Math.random() * 9999), name: name.trim(), logo, createdAt: Date.now() });
};
return (
Add a campaign
Give it the client name and upload their logo.
Cancel
Create campaign
);
}
/* ---------- Shared header used across pages ---------- */
function Header({ title, sub, children, back }) {
return (
{back}
{title}
{sub &&
{sub}
}
{children}
);
}
/* ============================================================
CAMPAIGN DETAIL - main hub for one campaign
============================================================ */
function CampaignDetail({ campaign, reports, onBack, onSave, onDelete }) {
const [view, setView] = useState("month"); // month | week | day
const nowDate = new Date();
const [monthYear, setMonthYear] = useState({ year: nowDate.getFullYear(), month: nowDate.getMonth() });
const [weekStart, setWeekStart] = useState(isoWeekOf(nowDate).start);
const [selectedDay, setSelectedDay] = useState(null); // ISO date when a day is being viewed/edited
const [editingDay, setEditingDay] = useState(null);
const campaignReports = reports[campaign.id] || {};
return (
{[
{ v: "month", l: "Month view" },
{ v: "week", l: "Week view" },
].map((t) => (
setView(t.v)}
style={{
padding: "12px 20px", background: "transparent", border: "none",
cursor: "pointer", fontFamily: "'Archivo', sans-serif", fontWeight: 600, fontSize: 14,
color: view === t.v ? BRAND.primary : BRAND.sub,
borderBottom: "3px solid " + (view === t.v ? BRAND.primary : "transparent"),
marginBottom: -1,
}}>{t.l}
))}
{view === "month" && (
setMonthYear(addMonths(monthYear.year, monthYear.month, delta))}
onJump={(y, m) => setMonthYear({ year: y, month: m })}
onSelectDay={(iso) => setSelectedDay(iso)}
/>
)}
{view === "week" && (
setWeekStart(addWeeks(weekStart, delta).start)}
onJump={(iso) => setWeekStart(isoWeekOf(parseISO(iso)).start)}
onSelectDay={(iso) => setSelectedDay(iso)}
/>
)}
{selectedDay && (
new Date(new Date().toDateString())}
onClose={() => setSelectedDay(null)}
onEdit={() => setEditingDay(selectedDay)}
/>
)}
{editingDay && (
setEditingDay(null)}
onSave={(report) => { onSave(editingDay, report); setEditingDay(null); }}
onDelete={() => { onDelete(editingDay); setEditingDay(null); setSelectedDay(null); }}
/>
)}
);
}
function BackHeader({ onBack }) {
return (
);
}
function CampaignBanner({ campaign }) {
return (
{campaign.logo ? (
) : (
{campaign.name}
)}
{campaign.logo && (
{campaign.name}
)}
Inbound Call Report
);
}
/* ============================================================
MONTH VIEW - calendar grid + totals + CSV export
============================================================ */
function MonthView({ campaign, year, month, campaignReports, onNav, onJump, onSelectDay }) {
const todayIso = today();
const days = daysInMonth(year, month);
const firstDay = new Date(year, month, 1);
const firstWeekday = (firstDay.getDay() + 6) % 7; // 0 = Monday
// Grid: previous month spillover
const cells = [];
const prevMonth = addMonths(year, month, -1);
const prevDays = daysInMonth(prevMonth.year, prevMonth.month);
for (let i = firstWeekday - 1; i >= 0; i--) {
cells.push({ iso: isoDate(new Date(prevMonth.year, prevMonth.month, prevDays - i)), inMonth: false });
}
for (let d = 1; d <= days; d++) {
cells.push({ iso: isoDate(new Date(year, month, d)), inMonth: true });
}
const nextMonth = addMonths(year, month, 1);
while (cells.length % 7 !== 0 || cells.length < 42) {
const idx = cells.length - firstWeekday - days + 1;
cells.push({ iso: isoDate(new Date(nextMonth.year, nextMonth.month, idx)), inMonth: false });
if (cells.length >= 42) break;
}
// Aggregate for month
const monthReports = Object.entries(campaignReports).filter(([d]) => d.startsWith(monthKey(year, month))).map(([, r]) => r);
const agg = aggregateReports(monthReports);
const missingDays = [];
const filledDays = [];
for (let d = 1; d <= days; d++) {
const iso = isoDate(new Date(year, month, d));
if (iso > todayIso) continue;
if (campaignReports[iso]) filledDays.push(iso);
else missingDays.push(iso);
}
const exportCSV = () => {
const rows = [
["Campaign", campaign.name],
["Period", monthLabel(year, month)],
["Days with data", agg.daysWithData],
[],
["", "Total"],
["Total calls received", agg.callsReceived],
["Total calls answered", agg.callsAnswered],
["Call abandon rate (%)", round1(agg.abandonRate)],
["Average talk time", fmtSeconds(agg.avgTalkTimeSeconds)],
["Average talk time (seconds)", agg.avgTalkTimeSeconds != null ? Math.round(agg.avgTalkTimeSeconds) : ""],
["Average call answer speed", fmtSeconds(agg.avgAnswerSpeedSeconds)],
["Average wrap time", fmtSeconds(agg.avgWrapTimeSeconds)],
["Days answered within " + SLA_THRESHOLD_SECONDS + "s", agg.slaMetDays + " of " + agg.slaScoredDays],
["% days answered within " + SLA_THRESHOLD_SECONDS + "s (target " + SLA_TARGET_PCT + "%)", agg.slaPct != null ? round1(agg.slaPct) + "%" : ""],
[],
["Reason", "Phone Qty"],
...CALL_RESULTS.map((r) => [r, agg.results[r] || 0]),
["TOTAL BILLABLE INTERACTIONS", agg.totalBillable],
];
downloadCSV(campaign.name.replace(/\s+/g, "_") + "_" + monthKey(year, month) + ".csv", rows);
};
const monthOptions = [];
const nowY = new Date().getFullYear();
for (let y = nowY - 2; y <= nowY + 1; y++) {
for (let m = 0; m < 12; m++) monthOptions.push({ y, m });
}
return (
onNav(-1)} style={arrowBtnStyle}>‹
{ const [y, m] = e.target.value.split("-").map(Number); onJump(y, m - 1); }}
style={{ padding: "10px 14px", border: "1px solid " + BRAND.border, borderRadius: 10,
background: BRAND.inputBg, color: BRAND.ink, fontSize: 16, fontFamily: "'Archivo', sans-serif", fontWeight: 700, cursor: "pointer" }}>
{monthOptions.map(({ y, m }) => (
{monthLabel(y, m)}
))}
onNav(1)} style={arrowBtnStyle}>›
{ const d = new Date(); onJump(d.getFullYear(), d.getMonth()); }}>Today
Export CSV
{["Mon","Tue","Wed","Thu","Fri","Sat","Sun"].map((d) => (
{d}
))}
{cells.map((cell, i) => (
onSelectDay(cell.iso)} />
))}
Month at a glance
= 5 ? BRAND.bad : BRAND.good} />
{missingDays.length > 0 && (
{missingDays.length} day{missingDays.length === 1 ? "" : "s"} still need{missingDays.length === 1 ? "s" : ""} a report
Click any amber day in the calendar to fill it in.
)}
{agg.totalBillable > 0 &&
}
);
}
const arrowBtnStyle = {
width: 40, height: 40, borderRadius: 10, border: "1px solid " + BRAND.border, background: BRAND.panel,
fontSize: 22, color: BRAND.primary, cursor: "pointer", fontFamily: "sans-serif", padding: 0, lineHeight: 1,
};
function LegendChip({ color, label }) {
return (
{label}
);
}
function StatRow({ label, value, highlight, last }) {
return (
{label}
{value}
);
}
// Headline SLA block: % of days answered within 20s vs the 80% target.
function SlaBadge({ pct, metDays, scoredDays, style }) {
const hasData = pct != null;
const met = hasData && pct >= SLA_TARGET_PCT;
const accent = !hasData ? BRAND.sub : met ? BRAND.good : BRAND.bad;
const tint = !hasData ? BRAND.panelBg : met ? "#E5F4EA" : "#FBEAE7";
return (
Answered within {SLA_THRESHOLD_SECONDS}s
{hasData ? metDays + " of " + scoredDays + " day" + (scoredDays === 1 ? "" : "s") + " · target " + SLA_TARGET_PCT + "%" : "No answer-speed data yet"}
{hasData ? round1(pct) + "%" : "-"}
{hasData && (
{met ? "SLA met" : "Below target"}
)}
);
}
function CalendarCell({ cell, todayIso, report, onClick }) {
const d = parseISO(cell.iso);
const dayNum = d.getDate();
const isToday = cell.iso === todayIso;
const isFuture = cell.iso > todayIso;
const isFilled = !!report;
let bg = BRAND.panel;
let borderCol = BRAND.border;
let textCol = BRAND.ink;
let numCol = BRAND.ink;
if (!cell.inMonth) {
bg = BRAND.panel; textCol = "#D8D3CE"; numCol = "#D8D3CE";
} else if (isFuture) {
bg = "#FBF8F8"; textCol = "#C6BFB9"; numCol = "#C6BFB9";
} else if (isFilled) {
bg = "#E5F4EA"; borderCol = BRAND.good + "88"; textCol = BRAND.good;
} else if (cell.inMonth && !isFuture) {
bg = "#FFF8E1"; borderCol = "#F5D06A"; textCol = "#7A5A00";
}
if (isToday) {
borderCol = BRAND.primary;
}
return (
cell.inMonth && (e.currentTarget.style.transform = "translateY(-2px)")}
onMouseLeave={(e) => cell.inMonth && (e.currentTarget.style.transform = "translateY(0)")}>
{dayNum}
{isToday && Today }
{isFilled && (
{report.callsReceived || 0} calls
)}
{!isFilled && cell.inMonth && !isFuture && (
Needs report
)}
);
}
/* ============================================================
WEEK VIEW - table of the 7 days in the selected week
============================================================ */
function WeekView({ campaign, weekStart, campaignReports, onNav, onJump, onSelectDay }) {
const todayIso = today();
const dates = datesInRange(weekStart, isoWeekOf(parseISO(weekStart)).end);
const wk = isoWeekOf(parseISO(weekStart));
const weekList = dates.map((d) => campaignReports[d]).filter(Boolean);
const agg = aggregateReports(weekList);
const exportCSV = () => {
const rows = [
["Campaign", campaign.name],
["Week", "W" + pad2(wk.week) + " " + wk.year + " · " + fmtDateShort(wk.start) + " to " + fmtDateShort(wk.end)],
[],
["Date", "Calls received", "Calls answered", "Abandon rate (%)", "Avg talk time (s)", "Avg answer speed (s)", "Avg wrap time (s)"],
...dates.map((d) => {
const r = campaignReports[d];
if (!r) return [fmtDateShort(d), "", "", "", "", "", ""];
return [
fmtDateShort(d), r.callsReceived || 0, r.callsAnswered || 0,
round1(abandonRate(r)),
r.avgTalkTimeSeconds != null ? Math.round(r.avgTalkTimeSeconds) : "",
r.avgAnswerSpeedSeconds != null ? Math.round(r.avgAnswerSpeedSeconds) : "",
r.avgWrapTimeSeconds != null ? Math.round(r.avgWrapTimeSeconds) : "",
];
}),
[],
["Week total received", agg.callsReceived],
["Week total answered", agg.callsAnswered],
["Week abandon rate (%)", round1(agg.abandonRate)],
["Week avg talk time", fmtSeconds(agg.avgTalkTimeSeconds)],
["Week avg answer speed", fmtSeconds(agg.avgAnswerSpeedSeconds)],
["Week avg wrap time", fmtSeconds(agg.avgWrapTimeSeconds)],
["Days answered within " + SLA_THRESHOLD_SECONDS + "s", agg.slaMetDays + " of " + agg.slaScoredDays],
["% days answered within " + SLA_THRESHOLD_SECONDS + "s (target " + SLA_TARGET_PCT + "%)", agg.slaPct != null ? round1(agg.slaPct) + "%" : ""],
[],
["Reason", "Phone Qty"],
...CALL_RESULTS.map((r) => [r, agg.results[r] || 0]),
["TOTAL BILLABLE INTERACTIONS", agg.totalBillable],
];
downloadCSV(campaign.name.replace(/\s+/g, "_") + "_W" + pad2(wk.week) + "_" + wk.year + ".csv", rows);
};
// Build a list of the last ~26 weeks for a dropdown
const weekOptions = [];
const nowMon = new Date();
for (let i = 8; i >= -18; i--) {
const d = new Date(nowMon); d.setDate(d.getDate() - i * 7);
const w = isoWeekOf(d);
weekOptions.push(w);
}
return (
onNav(-1)} style={arrowBtnStyle}>‹
onJump(e.target.value)}
style={{ padding: "10px 14px", border: "1px solid " + BRAND.border, borderRadius: 10,
background: BRAND.inputBg, color: BRAND.ink, fontSize: 14, fontFamily: "'Archivo', sans-serif", fontWeight: 700, cursor: "pointer" }}>
{weekOptions.map((w) => (
Week {pad2(w.week)} · {fmtDateShort(w.start)} - {fmtDateShort(w.end)}
))}
onNav(1)} style={arrowBtnStyle}>›
onJump(isoWeekOf(new Date()).start)}>This week
Export CSV
{["Date","Status","Received","Answered","Abandon %","Talk","Answer","Wrap",""].map((h) => (
{h}
))}
{dates.map((d) => {
const r = campaignReports[d];
const isFuture = d > todayIso;
const isToday = d === todayIso;
return (
{fmtDateShort(d)}
{isToday && TODAY }
{r ? ● Filled
: isFuture ? Future
: ● Missing }
{r ? r.callsReceived || 0 : "-"}
{r ? r.callsAnswered || 0 : "-"}
= 5 ? BRAND.bad : BRAND.ink }}>{r ? round1(abandonRate(r)) + "%" : "-"}
{r ? fmtSeconds(r.avgTalkTimeSeconds) : "-"}
{r ? fmtSeconds(r.avgAnswerSpeedSeconds) : "-"}
{r ? fmtSeconds(r.avgWrapTimeSeconds) : "-"}
{!isFuture && (
onSelectDay(d)}
style={{ background: "transparent", border: "1px solid " + BRAND.border, borderRadius: 8, padding: "6px 12px", color: BRAND.primary, fontSize: 12, fontWeight: 600, cursor: "pointer" }}>
{r ? "View" : "Fill in"}
)}
);
})}
Week total
{agg.callsReceived}
{agg.callsAnswered}
= 5 ? BRAND.bad : BRAND.good }}>{round1(agg.abandonRate)}%
{fmtSeconds(agg.avgTalkTimeSeconds)}
{fmtSeconds(agg.avgAnswerSpeedSeconds)}
{fmtSeconds(agg.avgWrapTimeSeconds)}
{agg.totalBillable > 0 &&
}
);
}
/* ---------- Results breakdown table used by month/week/day views ---------- */
function ResultsBreakdown({ title, results, total }) {
const rows = CALL_RESULTS.map((r) => ({ name: r, count: results[r] || 0 }));
const maxCount = Math.max(1, ...rows.map((r) => r.count));
return (
{title}
{rows.map((r) => (
{r.name}
0 ? BRAND.primary : "transparent" }} />
0 ? BRAND.primary : BRAND.sub }}>{r.count}
))}
Total billable interactions
{total}
);
}
/* ============================================================
DAY MODAL - view a saved day's stats + breakdown
============================================================ */
function DayModal({ campaign, date, report, isFuture, onClose, onEdit }) {
const exportCSV = () => {
if (!report) return;
const rows = [
["Campaign", campaign.name],
["Date", fmtDateLong(date)],
[],
["Total calls received", report.callsReceived],
["Total calls answered", report.callsAnswered],
["Call abandon rate (%)", round1(abandonRate(report))],
["Average talk time", fmtSeconds(report.avgTalkTimeSeconds)],
["Average talk time (seconds)", report.avgTalkTimeSeconds != null ? Math.round(report.avgTalkTimeSeconds) : ""],
["Average call answer speed", fmtSeconds(report.avgAnswerSpeedSeconds)],
["Answered within " + SLA_THRESHOLD_SECONDS + "s", dayMeetsSla(report) === null ? "" : dayMeetsSla(report) ? "Met" : "Missed"],
["Average wrap time", fmtSeconds(report.avgWrapTimeSeconds)],
[],
["Reason", "Phone Qty"],
...CALL_RESULTS.map((r) => [r, (report.results && report.results[r]) || 0]),
["TOTAL BILLABLE INTERACTIONS", totalResults(report.results)],
];
downloadCSV(campaign.name.replace(/\s+/g, "_") + "_" + date + ".csv", rows);
};
return (
{campaign.name}
{fmtDateLong(date)}
×
{isFuture ? (
This day is in the future. Come back after it's happened to log the report.
) : !report ? (
No report has been filled in for this day yet.
Close
Fill in report
) : (
<>
= 5 ? BRAND.bad : BRAND.good} />
Result breakdown
Reason
Phone Qty
{CALL_RESULTS.map((r) => {
const v = (report.results && report.results[r]) || 0;
return (
0 ? "#FFF7FA" : "transparent" }}>
0 ? BRAND.ink : BRAND.sub }}>{r}
0 ? 700 : 400, color: v > 0 ? BRAND.primary : BRAND.sub }}>{v}
);
})}
Total billable interactions
{totalResults(report.results)}
Export CSV
Close
Edit report
>
)}
);
}
function StatTile({ label, value, colour }) {
return (
);
}
/* ============================================================
DAY FORM MODAL - add or edit a report
============================================================ */
function DayFormModal({ campaign, date, existing, onClose, onSave, onDelete }) {
const [callsReceived, setCallsReceived] = useState(existing ? String(existing.callsReceived ?? "") : "");
const [callsAnswered, setCallsAnswered] = useState(existing ? String(existing.callsAnswered ?? "") : "");
const [avgTalk, setAvgTalk] = useState(existing && existing.avgTalkTimeSeconds != null ? fmtSeconds(existing.avgTalkTimeSeconds) : "");
const [avgAnswer, setAvgAnswer] = useState(existing && existing.avgAnswerSpeedSeconds != null ? fmtSeconds(existing.avgAnswerSpeedSeconds) : "");
const [avgWrap, setAvgWrap] = useState(existing && existing.avgWrapTimeSeconds != null ? fmtSeconds(existing.avgWrapTimeSeconds) : "");
const [results, setResults] = useState(() => {
const r = {};
CALL_RESULTS.forEach((n) => {
r[n] = (existing && existing.results && existing.results[n] != null) ? String(existing.results[n]) : "";
});
return r;
});
const [confirmDel, setConfirmDel] = useState(false);
const parsedReceived = parseInt(callsReceived, 10) || 0;
const parsedAnswered = parseInt(callsAnswered, 10) || 0;
const abandonPct = parsedReceived > 0 ? round1((parsedReceived - parsedAnswered) / parsedReceived * 100) : 0;
const parsedResultsTotal = Object.values(results).reduce((s, v) => s + (parseInt(v, 10) || 0), 0);
const talkSec = parseTime(avgTalk);
const answerSec = parseTime(avgAnswer);
const wrapSec = parseTime(avgWrap);
const submit = () => {
if (!callsReceived) return;
const cleanResults = {};
CALL_RESULTS.forEach((n) => {
const v = parseInt(results[n], 10);
if (v && v > 0) cleanResults[n] = v;
});
onSave({
callsReceived: parsedReceived,
callsAnswered: parsedAnswered,
avgTalkTimeSeconds: talkSec,
avgAnswerSpeedSeconds: answerSec,
avgWrapTimeSeconds: wrapSec,
results: cleanResults,
updatedAt: Date.now(),
});
};
return (
{existing ? "Editing report" : "New report"} · {campaign.name}
{fmtDateLong(date)}
×
Result count
Total billable: {parsedResultsTotal}
{CALL_RESULTS.map((r) => (
{r}
setResults({ ...results, [r]: e.target.value })}
style={{
width: 68, padding: "6px 10px",
border: "1px solid " + BRAND.border, borderRadius: 8,
background: BRAND.inputBg, fontSize: 13, textAlign: "right",
fontFamily: "'IBM Plex Mono', monospace",
outline: "none",
}} />
))}
{existing && !confirmDel && (
setConfirmDel(true)}>Delete report
)}
{confirmDel && (
Delete this report?
Yes, delete
setConfirmDel(false)}>Cancel
)}
Cancel
{existing ? "Save changes" : "Save report"}
);
}
/* ============================================================
APP SHELL
============================================================ */
function App() {
const [unlocked, setUnlocked] = useState(false);
const [passcode, setPasscode] = useState("");
const [campaigns, setCampaigns] = useState([]);
const [reports, setReports] = useState({}); // { campaignId: { "YYYY-MM-DD": report } }
const [loading, setLoading] = useState(true);
const [activeCampaign, setActiveCampaign] = useState(null);
const [saving, setSaving] = useState(false);
useEffect(() => {
(async () => {
const d = await apiLoad();
if (d) {
if (Array.isArray(d.campaigns)) setCampaigns(d.campaigns);
if (d.reports && typeof d.reports === "object") setReports(d.reports);
}
setLoading(false);
})();
}, []);
const persist = async (nextCampaigns, nextReports) => {
setSaving(true);
await apiSave({ campaigns: nextCampaigns, reports: nextReports }, passcode);
setSaving(false);
};
const handleUnlock = (code) => {
setPasscode(code);
setUnlocked(true);
};
const addCampaign = (c) => {
const next = [...campaigns, c];
setCampaigns(next);
persist(next, reports);
};
const deleteCampaign = (id) => {
const nextCampaigns = campaigns.filter((c) => c.id !== id);
const nextReports = { ...reports };
delete nextReports[id];
setCampaigns(nextCampaigns);
setReports(nextReports);
persist(nextCampaigns, nextReports);
};
const saveReport = (date, report) => {
if (!activeCampaign) return;
const nextReports = { ...reports };
nextReports[activeCampaign.id] = { ...(nextReports[activeCampaign.id] || {}), [date]: report };
setReports(nextReports);
persist(campaigns, nextReports);
};
const deleteReport = (date) => {
if (!activeCampaign) return;
const nextReports = { ...reports };
if (nextReports[activeCampaign.id]) {
const c = { ...nextReports[activeCampaign.id] };
delete c[date];
nextReports[activeCampaign.id] = c;
}
setReports(nextReports);
persist(campaigns, nextReports);
};
if (!unlocked) {
return
;
}
return (
{loading ? (
Loading...
) : activeCampaign ? (
c.id === activeCampaign.id) || activeCampaign}
reports={reports}
onBack={() => setActiveCampaign(null)}
onSave={saveReport}
onDelete={deleteReport}
/>
) : (
{ setUnlocked(false); setPasscode(""); setActiveCampaign(null); }}
/>
)}
{saving && (
Saving...
)}
);
}
ReactDOM.createRoot(document.getElementById("root")).render(
);