dev #2

Merged
igodin merged 12 commits from dev into main 2026-07-27 18:37:38 +00:00
5 changed files with 673 additions and 157 deletions
Showing only changes of commit 7a59fd0cd4 - Show all commits

8
package-lock.json generated
View File

@ -6,7 +6,7 @@
"": { "": {
"dependencies": { "dependencies": {
"axios": "^1.13.2", "axios": "^1.13.2",
"dotenv": "^17.2.3" "dotenv": "^17.4.2"
} }
}, },
"node_modules/asynckit": { "node_modules/asynckit": {
@ -61,9 +61,9 @@
} }
}, },
"node_modules/dotenv": { "node_modules/dotenv": {
"version": "17.2.3", "version": "17.4.2",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.2.3.tgz", "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz",
"integrity": "sha512-JVUnt+DUIzu87TABbhPmNfVdBDt18BLOWjMUFJMSi/Qqg7NTYtabbvSNJGOJ7afbRuv9D/lngizHtP7QyLQ+9w==", "integrity": "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==",
"license": "BSD-2-Clause", "license": "BSD-2-Clause",
"engines": { "engines": {
"node": ">=12" "node": ">=12"

View File

@ -1,6 +1,6 @@
{ {
"dependencies": { "dependencies": {
"axios": "^1.13.2", "axios": "^1.13.2",
"dotenv": "^17.2.3" "dotenv": "^17.4.2"
} }
} }

446
src/public/index.html Normal file
View File

@ -0,0 +1,446 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Closed ticket board</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;600&family=IBM+Plex+Sans:wght@400;500;600&display=swap" rel="stylesheet">
<style>
:root {
--ground: #E9EBEC;
--card: #FFFFFF;
--ink: #14181A;
--muted: #6C767C;
--rule: #D3D8DA;
--signal: #14684C;
--signal-soft: #E2F0EA;
--alert: #9B3520;
--sans: "IBM Plex Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
--mono: "IBM Plex Mono", ui-monospace, SFMono-Regular, Menlo, monospace;
}
* { box-sizing: border-box; }
body {
margin: 0;
background: var(--ground);
color: var(--ink);
font-family: var(--sans);
font-size: 15px;
line-height: 1.5;
-webkit-font-smoothing: antialiased;
}
.wrap {
max-width: 860px;
margin: 0 auto;
padding: 32px 20px 80px;
}
/* ---- header ---- */
header {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 12px 20px;
padding-bottom: 14px;
border-bottom: 2px solid var(--ink);
}
h1 {
margin: 0;
font-family: var(--mono);
font-size: 17px;
font-weight: 600;
letter-spacing: -0.01em;
}
.status {
display: flex;
align-items: center;
gap: 7px;
margin-left: auto;
font-family: var(--mono);
font-size: 12px;
color: var(--muted);
}
.dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--muted);
flex: none;
}
.status[data-auth="connected"] .dot {
background: var(--signal);
animation: pulse 2.4s ease-in-out infinite;
}
.status[data-auth="error"] .dot { background: var(--alert); }
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.25; }
}
.meta {
display: flex;
flex-wrap: wrap;
gap: 6px 18px;
margin: 12px 0 0;
font-family: var(--mono);
font-size: 12px;
color: var(--muted);
}
/* ---- panels ---- */
.panel {
margin-top: 24px;
padding: 24px;
background: var(--card);
border: 1px solid var(--rule);
}
.panel h2 {
margin: 0 0 6px;
font-size: 16px;
font-weight: 600;
}
.panel p {
margin: 0 0 16px;
color: var(--muted);
max-width: 52ch;
}
.code {
display: inline-block;
margin-bottom: 16px;
padding: 10px 16px;
background: var(--signal-soft);
font-family: var(--mono);
font-size: 26px;
font-weight: 600;
letter-spacing: 0.12em;
}
button, .button {
display: inline-block;
padding: 9px 18px;
border: none;
background: var(--ink);
color: var(--ground);
font-family: var(--sans);
font-size: 14px;
font-weight: 500;
text-decoration: none;
cursor: pointer;
}
button:hover, .button:hover { background: var(--signal); }
button:focus-visible, .button:focus-visible,
a:focus-visible { outline: 2px solid var(--signal); outline-offset: 2px; }
button.quiet {
background: none;
color: var(--muted);
padding: 4px 0;
font-family: var(--mono);
font-size: 12px;
text-decoration: underline;
text-underline-offset: 3px;
}
button.quiet:hover { background: none; color: var(--ink); }
.error {
margin-top: 20px;
padding: 12px 16px;
background: var(--card);
border-left: 3px solid var(--alert);
font-size: 14px;
}
.error strong { display: block; font-family: var(--mono); font-size: 12px; color: var(--alert); }
/* ---- tallies ---- */
.tallies {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 24px;
}
.tally {
display: flex;
align-items: baseline;
gap: 8px;
padding: 5px 12px;
background: var(--card);
border: 1px solid var(--rule);
font-size: 13px;
}
.tally b {
font-family: var(--mono);
font-size: 12px;
font-weight: 600;
color: var(--signal);
}
/* ---- feed ---- */
.feed { margin-top: 20px; }
.ticket {
--age: 0;
display: grid;
grid-template-columns: 74px 1fr;
background: var(--card);
border: 1px solid var(--rule);
border-bottom: none;
}
.feed .ticket:last-child { border-bottom: 1px solid var(--rule); }
/* The rail is the point of the whole page: how long ago this closed, drained
of color as it ages out of the window. */
.rail {
display: flex;
flex-direction: column;
justify-content: center;
padding: 14px 0 14px 14px;
border-left: 3px solid color-mix(in oklab, var(--signal), var(--rule) calc(var(--age) * 100%));
font-family: var(--mono);
font-size: 15px;
font-weight: 500;
color: color-mix(in oklab, var(--signal), var(--muted) calc(var(--age) * 100%));
}
.rail small {
font-size: 10px;
font-weight: 400;
letter-spacing: 0.08em;
text-transform: uppercase;
color: var(--muted);
}
.body { padding: 14px 16px 14px 4px; min-width: 0; }
.subject {
margin: 0;
font-size: 15px;
font-weight: 500;
overflow-wrap: anywhere;
}
.subject span {
font-family: var(--mono);
font-weight: 600;
color: var(--muted);
margin-right: 8px;
}
.byline {
margin: 3px 0 0;
font-size: 13px;
color: var(--muted);
}
.byline b { color: var(--ink); font-weight: 500; }
.ticket.new { animation: slide 0.35s ease-out; }
@keyframes slide {
from { opacity: 0; transform: translateY(-6px); }
to { opacity: 1; transform: none; }
}
.empty {
margin-top: 20px;
padding: 40px 24px;
background: var(--card);
border: 1px dashed var(--rule);
text-align: center;
color: var(--muted);
}
.empty p { margin: 0; }
footer {
margin-top: 28px;
font-family: var(--mono);
font-size: 11px;
color: var(--muted);
}
@media (max-width: 520px) {
.ticket { grid-template-columns: 62px 1fr; }
.rail { font-size: 13px; padding-left: 10px; }
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { animation: none !important; transition: none !important; }
}
</style>
</head>
<body>
<div class="wrap">
<header>
<h1>Closed ticket board</h1>
<div class="status" id="status" data-auth="disconnected">
<span class="dot"></span><span id="statusText">Not connected</span>
</div>
</header>
<div class="meta" id="meta"></div>
<div id="main"></div>
<footer id="footer"></footer>
</div>
<script>
const $ = id => document.getElementById(id);
let data = null;
let seen = new Set();
let firstLoad = true;
const STATUS_TEXT = {
disconnected: 'Not connected',
pending: 'Waiting for authorization',
connected: 'Live',
error: 'Stopped'
};
function elapsed(ms) {
const mins = Math.floor(ms / 60000);
if (mins < 1) return { value: 'now', label: 'just closed' };
if (mins < 60) return { value: mins + 'm', label: 'ago' };
const hrs = Math.floor(mins / 60);
return { value: hrs + 'h ' + (mins % 60) + 'm', label: 'ago' };
}
function clockTime(ms) {
return new Date(ms).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
}
function esc(text) {
return String(text ?? '').replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
}
async function load() {
try {
const res = await fetch('/api/state');
data = await res.json();
render();
} catch (err) {
$('statusText').textContent = 'Server unreachable';
}
}
function render() {
if (!data) return;
$('status').dataset.auth = data.auth;
$('statusText').textContent = STATUS_TEXT[data.auth] || data.auth;
$('meta').innerHTML = [
'Checks every ' + data.checkMinutes + ' min',
'Window ' + data.windowMinutes + ' min',
data.watching.length ? 'Watching ' + data.watching.length + ' technicians' : 'Watching all technicians',
data.lastCheck ? 'Last check ' + clockTime(data.lastCheck) : ''
].filter(Boolean).map(t => '<span>' + esc(t) + '</span>').join('');
let html = '';
if (data.auth === 'disconnected' || data.auth === 'error') {
html += `<div class="panel">
<h2>Connect to the help desk</h2>
<p>Zoho needs you to approve this board once. Connecting opens an authorization
page and starts the checks as soon as you approve.</p>
<button onclick="connect(this)">Connect</button>
</div>`;
}
if (data.auth === 'pending') {
html += `<div class="panel">
<h2>Approve the board</h2>
<p>Open the authorization page and confirm this code matches the one shown there.</p>
<div class="code">${esc(data.userCode || '...')}</div>
<a class="button" href="${esc(data.verificationUrl || '#')}" target="_blank" rel="noopener">Open authorization page</a>
</div>`;
}
if (data.lastError) {
html += `<div class="error"><strong>Last check failed</strong>${esc(data.lastError)}</div>`;
}
if (data.auth === 'connected') {
const tallies = {};
for (const t of data.tickets) tallies[t.technician] = (tallies[t.technician] || 0) + 1;
const names = Object.keys(tallies).sort((a, b) => tallies[b] - tallies[a]);
if (names.length) {
html += '<div class="tallies">' + names.map(n =>
`<span class="tally">${esc(n)} <b>${tallies[n]}</b></span>`).join('') + '</div>';
}
if (!data.tickets.length) {
html += `<div class="empty"><p>Nothing closed yet. Tickets appear here within a minute of being closed.</p></div>`;
} else {
html += '<div class="feed">' + data.tickets.map(renderTicket).join('') + '</div>';
}
html += '<p style="margin-top:16px"><button class="quiet" onclick="checkNow(this)">Check now</button></p>';
}
$('main').innerHTML = html;
$('footer').textContent = data.tickets && data.tickets.length
? data.tickets.length + ' tickets on the board'
: '';
firstLoad = false;
}
function renderTicket(ticket) {
const age = Date.now() - ticket.closedAt;
const e = elapsed(age);
// 0 = just closed, 1 = fully aged out (one hour on)
const fade = Math.min(age / (60 * 60 * 1000), 1).toFixed(3);
const isNew = !firstLoad && !seen.has(ticket.id);
seen.add(ticket.id);
return `<article class="ticket${isNew ? ' new' : ''}" style="--age:${fade}">
<div class="rail">
${esc(e.value)}
<small>${esc(e.label)}</small>
</div>
<div class="body">
<p class="subject"><span>#${esc(ticket.id)}</span>${esc(ticket.subject || 'No subject')}</p>
<p class="byline"><b>${esc(ticket.technician)}</b> &middot; closed ${esc(ticket.closedDisplay || clockTime(ticket.closedAt))}</p>
</div>
</article>`;
}
async function connect(btn) {
btn.disabled = true;
btn.textContent = 'Connecting...';
await fetch('/api/connect', { method: 'POST' });
load();
}
async function checkNow(btn) {
btn.disabled = true;
btn.textContent = 'Checking...';
await fetch('/api/check', { method: 'POST' });
load();
}
load();
setInterval(load, 5000); // pull fresh state from the server
setInterval(render, 20000); // re-age the rails between pulls
</script>
</body>
</html>

222
src/server.js Normal file
View File

@ -0,0 +1,222 @@
require('dotenv').config({ quiet: true });
const path = require('path');
const express = require('express');
const axios = require('axios');
const { CLIENT_ID, CLIENT_SECRET, TECHNICIAN_NAMES, STATUS_NAMES } = process.env;
const PORT = process.env.PORT || 3000;
if (!CLIENT_ID || !CLIENT_SECRET) {
console.error('Client id and secret missing from .env');
process.exit(1);
}
const technicians = (TECHNICIAN_NAMES ? TECHNICIAN_NAMES.split(',') : []).map(t => t.trim()).filter(Boolean);
const statuses = (STATUS_NAMES ? STATUS_NAMES.split(',') : []).map(s => s.trim()).filter(Boolean);
const WINDOW_MINUTES = 10;
const CHECK_MINUTES = 1;
let accessToken = null;
const state = {
auth: 'disconnected',
verificationUrl: null,
userCode: null,
lastCheck: null,
lastError: null
};
const tickets = new Map();
async function getDeviceCode() {
const params = new URLSearchParams({
client_id: CLIENT_ID,
scope: 'SDPOnDemand.requests.READ',
grant_type: 'device_request',
access_type: 'offline'
});
const res = await axios.post('https://accounts.zoho.com/oauth/v3/device/code', params);
return res.data;
}
function pollForToken(deviceCode, interval, expiresIn) {
const pollParams = new URLSearchParams({
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
code: deviceCode,
grant_type: 'device_token'
});
return new Promise((resolve, reject) => {
const deadline = Date.now() + (expiresIn || 300) * 1000;
const timer = setInterval(async () => {
if (Date.now() > deadline) {
clearInterval(timer);
reject(new Error('The authorization code expired. Connect again.'));
return;
}
try {
const res = await axios.post('https://accounts.zoho.com/oauth/v3/device/token', pollParams);
if (res.data.access_token) {
clearInterval(timer);
accessToken = res.data.access_token;
console.log('Authorization successful');
resolve();
}
} catch (err) {
}
}, interval + 500);
});
}
function toMillis(completedTime) {
if (!completedTime) return null;
const raw = typeof completedTime === 'object' ? completedTime.value : completedTime;
const ms = Number(raw);
return Number.isFinite(ms) ? ms : null;
}
async function fetchClosedTickets() {
if (!accessToken) return;
try {
const windowStart = Date.now() - WINDOW_MINUTES * 60 * 1000;
const listInfo = {
list_info: {
row_count: 50,
sort_field: 'completed_time',
sort_order: 'desc',
fields_required: ['display_id', 'subject', 'status', 'completed_time', 'technician'],
search_criteria: [
{
field: 'status.internal_name',
condition: 'is',
values: statuses.length ? statuses : ['Closed']
},
{
field: 'completed_time',
condition: 'greater_than',
value: windowStart.toString(),
logical_operator: 'and'
}
]
}
};
const response = await axios.get('https://ithelp.mainecc.edu/api/v3/requests', {
params: { input_data: JSON.stringify(listInfo) },
headers: {
Authorization: `Zoho-oauthtoken ${accessToken}`,
Accept: 'application/vnd.manageengine.sdp.v3+json'
}
});
const found = response.data?.requests || [];
for (const ticket of found) {
const closedAt = toMillis(ticket.completed_time);
if (!closedAt || closedAt <= windowStart) continue;
const technician = ticket.technician ? ticket.technician.name : null;
if (!technician) continue;
if (technicians.length && !technicians.includes(technician)) continue;
tickets.set(String(ticket.display_id), {
id: ticket.display_id,
subject: ticket.subject,
technician,
status: ticket.status ? ticket.status.name : null,
closedAt,
closedDisplay: ticket.completed_time?.display_value || null
});
}
const cutoff = Date.now() - 12 * 60 * 60 * 1000;
for (const [key, ticket] of tickets) {
if (ticket.closedAt < cutoff) tickets.delete(key);
}
state.lastCheck = Date.now();
state.lastError = null;
} catch (err) {
const detail = err.response?.data;
state.lastError = detail?.response_status?.messages?.[0]?.message
|| (typeof detail === 'string' ? detail : null)
|| err.message;
state.lastCheck = Date.now();
console.error('Error: ', detail || err.message);
}
}
async function connect() {
state.auth = 'pending';
state.lastError = null;
const deviceData = await getDeviceCode();
state.verificationUrl = deviceData.verification_uri_complete;
state.userCode = deviceData.user_code;
console.log('Open this URL and authorize:', deviceData.verification_uri_complete);
console.log('Code: ', deviceData.user_code);
try {
await pollForToken(deviceData.device_code, deviceData.interval, deviceData.expires_in);
} catch (err) {
state.auth = 'error';
state.lastError = err.message;
state.verificationUrl = null;
state.userCode = null;
return;
}
state.auth = 'connected';
state.verificationUrl = null;
state.userCode = null;
await fetchClosedTickets();
setInterval(fetchClosedTickets, CHECK_MINUTES * 60 * 1000);
}
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.get('/api/state', (req, res) => {
res.json({
...state,
windowMinutes: WINDOW_MINUTES,
checkMinutes: CHECK_MINUTES,
watching: technicians,
serverTime: Date.now(),
tickets: [...tickets.values()].sort((a, b) => b.closedAt - a.closedAt)
});
});
app.post('/api/connect', async (req, res) => {
if (state.auth === 'pending' || state.auth === 'connected') {
return res.json({ ok: true });
}
try {
connect();
res.json({ ok: true });
} catch (err) {
state.auth = 'error';
state.lastError = err.message;
res.status(500).json({ ok: false, error: err.message });
}
});
app.post('/api/check', async (req, res) => {
await fetchClosedTickets();
res.json({ ok: true });
});
app.listen(PORT, () => {
console.log(`Open http://localhost:${PORT}`);
});

View File

@ -1,152 +0,0 @@
//I barely understand this code, so don't ask me to explain it.
// Or do just know it will be very basic explanations.
require('dotenv').config({ quiet: true });
const axios = require('axios');
const { CLIENT_ID, CLIENT_SECRET, TECHNICIAN_NAMES, STATUS_NAMES } = process.env;
if (!CLIENT_ID || !CLIENT_SECRET) {
console.error('Client id and secret missing from .env');
process.exit(1);
}
const technicians = TECHNICIAN_NAMES ? TECHNICIAN_NAMES.split(',') : [];
const statuses = STATUS_NAMES ? STATUS_NAMES.split(',') : [];
let accessToken = null;
async function getDeviceCode() {
const params = new URLSearchParams({
client_id: CLIENT_ID,
scope: 'SDPOnDemand.requests.READ',
grant_type: 'device_request',
access_type: 'offline'
});
const res = await axios.post('https://accounts.zoho.com/oauth/v3/device/code', params);
return res.data;
}
async function pollForToken(deviceCode, interval) {
const pollParams = new URLSearchParams({
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
code: deviceCode,
grant_type: 'device_token'
});
return new Promise((resolve, reject) => {
const pollInterval = setInterval(async () => {
try {
const res = await axios.post('https://accounts.zoho.com/oauth/v3/device/token', pollParams);
if (res.data.access_token) {
clearInterval(pollInterval);
accessToken = res.data.access_token;
console.log('Authorization successful');
resolve();
}
} catch (err) {
}
}, (interval + 500));
});
}
async function fetchClosedTickets() {
if (!accessToken) return;
try {
const tenMinutesAgo = Date.now() - (10 * 60 * 1000);
const listInfo = {
list_info: {
row_count: 50,
sort_field: "completed_time",
sort_order: "desc",
fields_required: ["display_id", "subject", "status", "completed_time", "technician"],
search_criteria: [
{
field: "status.internal_name",
condition: "is",
values: statuses.map(status => status.trim())
},
{
field: "completed_time",
condition: "greater_than",
value: tenMinutesAgo.toString(),
logical_operator: "and"
}
]
}
};
const response = await axios.get(
'https://ithelp.mainecc.edu/api/v3/requests',
{
params: { input_data: JSON.stringify(listInfo) },
headers: {
'Authorization': `Zoho-oauthtoken ${accessToken}`,
'Accept': 'application/vnd.manageengine.sdp.v3+json'
}
}
);
let tickets = response.data?.requests || [];
const trimmedTechnicians = technicians.map(t => t.trim());
tickets = tickets.filter(ticket => {
if (!ticket.completed_time){return false;}
const completedTime = typeof ticket.completed_time === 'object'
? ticket.completed_time.value
: ticket.completed_time;
if (completedTime <= tenMinutesAgo){return false;}
const technicianName = ticket.technician ? ticket.technician.name : null;
if (!technicianName){return false;}
return trimmedTechnicians.includes(technicianName);
});
console.log(`\nCheck ran at ${new Date().toLocaleTimeString()}`);
if (tickets.length === 0) {
console.log("No tickets closed in the last 10 minutes.");
} else {
console.log(`Found ${tickets.length} tickets closed since ${new Date(tenMinutesAgo).toLocaleTimeString()}:`);
console.log('---------------------------------------------------------');
tickets.forEach((ticket) => {
const ticketId = ticket.display_id;
const subject = ticket.subject;
const tech = ticket.technician ? ticket.technician.name : 'Unassigned';
const closedAt = ticket.completed_time ? ticket.completed_time.display_value : 'N/A';
console.log(`ID: ${ticketId} - ${subject}`);
console.log(`Technician: ${tech}`);
console.log(`Closed At: ${closedAt}`);
console.log('---------------------------------------------------------');
});
}
} catch (err) {
console.error('Error: ', err.response?.data || err.message);
}
}
async function main() {
const deviceData = await getDeviceCode();
console.log('Open this URL and authorize:', deviceData.verification_uri_complete);
console.log('Code: ', deviceData.user_code);
await pollForToken(deviceData.device_code, deviceData.interval);
setInterval(fetchClosedTickets, 1 * 60 * 1000); //Only change the first number the first is the amount of minutes between each run
fetchClosedTickets();
}
main().catch(err => console.error(err));