chore: move js to single file
This commit is contained in:
+3
-223
@@ -142,229 +142,9 @@
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"
|
||||
crossorigin="anonymous"></script>
|
||||
<script src="assets/js/nav.js"></script>
|
||||
<script>
|
||||
const SEND_MAX = 160;
|
||||
|
||||
// GSM-7 basic + extended character set
|
||||
const GSM7 = new Set('@£$¥èéùìòÇ\nØø\rÅåΔ_ΦΓΛΩΠΨΣΘΞÆæßÉ !"#¤%&\'()*+,-./0123456789:;<=>?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà€[]{}\\^|~');
|
||||
const GSM7_EXTENDED = new Set('€[]{}\\^|~');
|
||||
|
||||
function smsEncoding(text) {
|
||||
const isUnicode = [...text].some(c => !GSM7.has(c));
|
||||
const limit = isUnicode ? 70 : 160;
|
||||
const length = isUnicode ? text.length : [...text].reduce((n, c) => n + (GSM7_EXTENDED.has(c) ? 2 : 1), 0);
|
||||
return { length, limit, isUnicode };
|
||||
}
|
||||
|
||||
const msgEl = document.getElementById('message');
|
||||
const countEl = document.getElementById('charCount');
|
||||
const previewEl = document.getElementById('preview');
|
||||
const sectionEl = document.getElementById('previewSection');
|
||||
const placeholderEl = document.getElementById('previewPlaceholder');
|
||||
const sendBtn = document.getElementById('sendBtn');
|
||||
const countSpan = document.getElementById('recipientCount');
|
||||
const recipientsSel = document.getElementById('recipients');
|
||||
const resultEl = document.getElementById('sendResult');
|
||||
let noApiKey = false;
|
||||
|
||||
// ── Populate recipients from API ───────────────────────────
|
||||
async function loadRecipients() {
|
||||
try {
|
||||
const [attData, wsData] = await Promise.all([
|
||||
fetch('/api/attendees.php').then(r => r.json()),
|
||||
fetch('/api/workshops.php').then(r => r.json()),
|
||||
]);
|
||||
const total = attData.total ?? 0;
|
||||
const workshops = wsData.workshops ?? [];
|
||||
|
||||
const opts = [`<option value="all" data-count="${total}">All attendees (${total})</option>`];
|
||||
// Group sessions by workshop name (case-insensitive)
|
||||
const groups = {};
|
||||
workshops.forEach(ws => {
|
||||
const key = ws.workshop_name.toLowerCase();
|
||||
if (!groups[key]) groups[key] = { label: ws.workshop_name, sessions: [] };
|
||||
groups[key].sessions.push(ws);
|
||||
});
|
||||
const fmtTime = ws => ws.workshop_time
|
||||
? new Date(ws.workshop_time.replace(' ', 'T')).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' })
|
||||
: '(no time)';
|
||||
Object.values(groups).forEach(({ label, sessions }) => {
|
||||
if (sessions.length === 1) {
|
||||
const ws = sessions[0];
|
||||
opts.push(`<option value="workshop:${ws.id}" data-count="${ws.attendee_count}">${esc(label)} — ${fmtTime(ws)} (${ws.attendee_count})</option>`);
|
||||
} else {
|
||||
opts.push(`<optgroup label="${esc(label)}">`);
|
||||
sessions.forEach(ws => {
|
||||
opts.push(`<option value="workshop:${ws.id}" data-count="${ws.attendee_count}">${fmtTime(ws)} (${ws.attendee_count})</option>`);
|
||||
});
|
||||
opts.push(`</optgroup>`);
|
||||
}
|
||||
});
|
||||
|
||||
recipientsSel.innerHTML = opts.join('');
|
||||
updateCount();
|
||||
} catch {
|
||||
recipientsSel.innerHTML = '<option value="all" data-count="0">Could not load recipients</option>';
|
||||
}
|
||||
}
|
||||
|
||||
function updateCount() {
|
||||
const selected = recipientsSel.options[recipientsSel.selectedIndex];
|
||||
countSpan.textContent = selected?.dataset.count ?? '0';
|
||||
}
|
||||
|
||||
recipientsSel.addEventListener('change', updateCount);
|
||||
|
||||
// ── Message compose ───────────────────────────────────────
|
||||
function previewText(raw) {
|
||||
return raw
|
||||
.replace(/\{name\}/gi, 'Jordan')
|
||||
.replace(/\{first[_ ]name\}/gi, 'Jordan')
|
||||
.replace(/\{workshop\}/gi, 'Axe Throwing')
|
||||
.replace(/\{workshop_time\}/gi, '13:30');
|
||||
}
|
||||
|
||||
function insertPlaceholder(text) {
|
||||
const start = msgEl.selectionStart;
|
||||
const end = msgEl.selectionEnd;
|
||||
const val = msgEl.value;
|
||||
msgEl.value = val.slice(0, start) + text + val.slice(end);
|
||||
msgEl.selectionStart = msgEl.selectionEnd = start + text.length;
|
||||
msgEl.focus();
|
||||
msgEl.dispatchEvent(new Event('input'));
|
||||
}
|
||||
|
||||
msgEl.addEventListener('input', function () {
|
||||
const val = this.value;
|
||||
const { length, limit, isUnicode } = smsEncoding(val);
|
||||
const remaining = limit - length;
|
||||
|
||||
countEl.innerHTML = `${length}/${limit} characters${isUnicode ? ' <span style="color:#f87171;font-size:0.8em;"><i class="fa-solid fa-triangle-exclamation"></i> Unicode encoding — limit reduced to 70</span>' : ''}`;
|
||||
countEl.className = `d-block mb-2 ${remaining <= 10 ? (remaining <= 0 ? 'text-danger' : 'text-warning') : 'text-muted'}`;
|
||||
|
||||
const empty = val.trim() === '';
|
||||
sectionEl.style.visibility = empty ? 'hidden' : 'visible';
|
||||
placeholderEl.style.display = empty ? '' : 'none';
|
||||
previewEl.textContent = empty ? '' : previewText(val);
|
||||
sendBtn.disabled = empty || noApiKey;
|
||||
resultEl.style.display = 'none';
|
||||
});
|
||||
|
||||
// ── Send ───────────────────────────────────────────────────
|
||||
function esc(str) {
|
||||
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
}
|
||||
|
||||
sendBtn.addEventListener('click', async () => {
|
||||
const message = msgEl.value.trim();
|
||||
if (!message) return;
|
||||
|
||||
const selVal = recipientsSel.value;
|
||||
const isAll = selVal === 'all';
|
||||
const wsId = isAll ? null : parseInt(selVal.split(':')[1]);
|
||||
|
||||
sendBtn.disabled = true;
|
||||
sendBtn.innerHTML = '<i class="fa-solid fa-spinner fa-spin me-2"></i>Sending…';
|
||||
resultEl.style.display = 'none';
|
||||
|
||||
try {
|
||||
const selectedTemplateId = templatePicker.value ? parseInt(templatePicker.value) : null;
|
||||
const payload = {
|
||||
recipient_scope: isAll ? 'all' : 'workshop',
|
||||
};
|
||||
if (selectedTemplateId) {
|
||||
payload.template_id = selectedTemplateId;
|
||||
} else {
|
||||
payload.message = message;
|
||||
}
|
||||
if (!isAll) payload.workshop_session_id = wsId;
|
||||
|
||||
const res = await fetch('/api/send-now.php', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const data = await res.json();
|
||||
|
||||
if (!res.ok) throw new Error(data.error ?? 'Unknown error');
|
||||
|
||||
resultEl.style.display = '';
|
||||
resultEl.innerHTML = `
|
||||
<div style="background:rgba(34,197,94,0.1);border:1px solid rgba(34,197,94,0.3);border-radius:8px;padding:0.75rem 1rem;color:#4ade80;font-size:0.9rem;">
|
||||
<i class="fa-solid fa-circle-check me-2"></i>
|
||||
Sent to ${data.sent} recipient${data.sent !== 1 ? 's' : ''}.
|
||||
</div>`;
|
||||
msgEl.value = '';
|
||||
msgEl.dispatchEvent(new Event('input'));
|
||||
} catch (err) {
|
||||
resultEl.style.display = '';
|
||||
resultEl.innerHTML = `
|
||||
<div style="background:rgba(220,53,69,0.1);border:1px solid rgba(220,53,69,0.3);border-radius:8px;padding:0.75rem 1rem;color:#f87171;font-size:0.9rem;">
|
||||
<i class="fa-solid fa-circle-xmark me-2"></i>${esc(err.message)}
|
||||
</div>`;
|
||||
} finally {
|
||||
sendBtn.disabled = msgEl.value.trim() === '' || noApiKey;
|
||||
sendBtn.innerHTML = '<i class="fa-solid fa-paper-plane me-2"></i>Send to <span id="recipientCount">' + countSpan.textContent + '</span> attendees';
|
||||
}
|
||||
});
|
||||
|
||||
loadRecipients();
|
||||
|
||||
// ── Template picker ───────────────────────────────────────
|
||||
const templatePicker = document.getElementById('templatePicker');
|
||||
let templateBodies = {}; // id → body
|
||||
|
||||
async function loadTemplatePicker() {
|
||||
try {
|
||||
const data = await fetch('/api/templates.php').then(r => r.json());
|
||||
const templates = data.templates ?? [];
|
||||
templateBodies = {};
|
||||
templates.forEach(t => { templateBodies[t.id] = t.body; });
|
||||
templatePicker.innerHTML = '<option value="">— Custom message —</option>'
|
||||
+ templates.map(t => `<option value="${t.id}">${esc(t.name)}</option>`).join('');
|
||||
} catch {
|
||||
// leave the default option in place
|
||||
}
|
||||
}
|
||||
|
||||
templatePicker.addEventListener('change', () => {
|
||||
const body = templateBodies[templatePicker.value];
|
||||
if (body !== undefined) {
|
||||
msgEl.value = body;
|
||||
msgEl.dispatchEvent(new Event('input'));
|
||||
msgEl.focus();
|
||||
}
|
||||
});
|
||||
|
||||
loadTemplatePicker();
|
||||
</script>
|
||||
<script>
|
||||
async function checkAuth() {
|
||||
try {
|
||||
const r = await fetch('/api/admin.php', { redirect: 'manual' });
|
||||
if (r.type === 'opaqueredirect' || !r.ok) { window.location.reload(); return; }
|
||||
const d = await r.json();
|
||||
document.getElementById('sandboxBanner').style.display = d.sandbox_mode ? '' : 'none';
|
||||
document.querySelectorAll('.admin-nav-link').forEach(el => el.classList.toggle('d-none', !d.is_admin));
|
||||
const name = d.name || d.username;
|
||||
if (name) {
|
||||
document.querySelectorAll('.nav-username').forEach(el => { el.textContent = name; });
|
||||
}
|
||||
} catch { }
|
||||
}
|
||||
checkAuth();
|
||||
document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') checkAuth(); });
|
||||
|
||||
async function checkApiKey() {
|
||||
try {
|
||||
const r = await fetch('/api/settings.php?key=clickatell_api_key').then(res => res.json());
|
||||
noApiKey = !r.set;
|
||||
document.getElementById('noApiKeyBanner').style.display = noApiKey ? '' : 'none';
|
||||
if (noApiKey) document.getElementById('sendBtn').disabled = true;
|
||||
} catch { }
|
||||
}
|
||||
checkApiKey();
|
||||
</script>
|
||||
<script src="assets/js/app.js"></script>
|
||||
|
||||
|
||||
<nav class="bottom-nav" aria-label="Navigation">
|
||||
<a href="index.html" class="bottom-nav-item">
|
||||
<i class="fa-solid fa-house"></i>
|
||||
|
||||
Reference in New Issue
Block a user