fix(assessments): show letter grades not undefined%

cannot triple confirm that this works for all schools but it works for my assessments that are letter-based
This commit is contained in:
2026-06-22 21:47:03 +09:30
parent 6f7788497a
commit 37ae32be59
12 changed files with 619 additions and 101 deletions
@@ -0,0 +1,152 @@
import { getUserInfo } from "@/seqta/ui/AddBetterSEQTAElements";
export interface ArchivedNotification {
notificationID: number;
type: string;
timestamp: string;
title: string;
subtitle: string;
messageID?: number;
assessmentID?: number;
programmeID?: number;
metaclassID?: number;
subjectCode?: string;
firstSavedAt: string;
lastSeenAt: string;
}
export type ArchiveMap = Record<string, ArchivedNotification>;
export type ArchivesByUser = Record<string, ArchiveMap>;
type RawNotification = Record<string, unknown>;
export async function resolveNotificationUserKey(): Promise<string | null> {
try {
const info = await getUserInfo();
const id = info?.id ?? info?.personUUID ?? info?.username;
if (id == null || id === "") return null;
const label =
info?.displayName ?? info?.name ?? info?.username ?? String(id);
return `${location.hostname}:${id}:${String(label).slice(0, 64)}`;
} catch {
return null;
}
}
export async function fetchAllNotifications(): Promise<RawNotification[]> {
const res = await fetch(`${location.origin}/seqta/student/heartbeat?`, {
method: "POST",
headers: { "Content-Type": "application/json; charset=utf-8" },
credentials: "include",
body: JSON.stringify({
timestamp: "1970-01-01 00:00:00.0",
hash: "#?page=/notifications",
}),
});
if (!res.ok) return [];
const json = (await res.json()) as {
notifications?: RawNotification[];
payload?: { notifications?: RawNotification[] };
};
const list = json.notifications ?? json.payload?.notifications;
return Array.isArray(list) ? list : [];
}
function readString(value: unknown): string {
if (value == null) return "";
return String(value).trim();
}
export function normalizeArchivedNotification(
raw: RawNotification,
now = new Date().toISOString(),
): ArchivedNotification | null {
const notificationID = Number(raw.notificationID);
if (!notificationID || Number.isNaN(notificationID)) return null;
const type = readString(raw.type) || "unknown";
const timestamp = readString(raw.timestamp) || now;
if (type === "message" && raw.message && typeof raw.message === "object") {
const message = raw.message as Record<string, unknown>;
return {
notificationID,
type,
timestamp,
title: readString(message.title) || "Message",
subtitle: readString(message.subtitle),
messageID: Number(message.messageID) || undefined,
firstSavedAt: now,
lastSeenAt: now,
};
}
if (
type === "coneqtassessments" &&
raw.coneqtAssessments &&
typeof raw.coneqtAssessments === "object"
) {
const assessment = raw.coneqtAssessments as Record<string, unknown>;
return {
notificationID,
type,
timestamp,
title: readString(assessment.title) || "Assessment",
subtitle: readString(assessment.subtitle) || readString(assessment.subjectCode),
assessmentID: Number(assessment.assessmentID) || undefined,
programmeID: Number(assessment.programmeID) || undefined,
metaclassID: Number(assessment.metaclassID) || undefined,
subjectCode: readString(assessment.subjectCode) || undefined,
firstSavedAt: now,
lastSeenAt: now,
};
}
return {
notificationID,
type,
timestamp,
title: readString(raw.title) || "Notification",
subtitle: readString(raw.subtitle),
firstSavedAt: now,
lastSeenAt: now,
};
}
export function mergeNotificationsIntoArchive(
existing: ArchiveMap,
notifications: RawNotification[],
): ArchiveMap {
const now = new Date().toISOString();
const merged: ArchiveMap = { ...existing };
for (const raw of notifications) {
const normalized = normalizeArchivedNotification(raw, now);
if (!normalized) continue;
const key = String(normalized.notificationID);
const prev = merged[key];
if (prev) {
merged[key] = {
...prev,
...normalized,
firstSavedAt: prev.firstSavedAt,
lastSeenAt: now,
};
} else {
merged[key] = normalized;
}
}
return merged;
}
export function listArchivedNotifications(archive: ArchiveMap): ArchivedNotification[] {
return Object.values(archive).sort(
(a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime(),
);
}
@@ -0,0 +1,165 @@
import type { PluginAPI } from "../../core/types";
import type { ArchivedNotification, ArchiveMap } from "./archive";
import { listArchivedNotifications } from "./archive";
import { delay } from "@/seqta/utils/delay";
import ReactFiber from "@/seqta/utils/ReactFiber";
import { waitForElm } from "@/seqta/utils/waitForElm";
interface ArchiveUIStorage {
archivesByUser?: Record<string, ArchiveMap>;
}
function formatArchiveDate(timestamp: string): string {
const date = new Date(timestamp);
if (Number.isNaN(date.getTime())) return timestamp;
return date.toLocaleString(undefined, {
year: "numeric",
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
});
}
async function openArchivedMessage(item: ArchivedNotification) {
if (!item.messageID) return;
location.hash = `#?page=/messages`;
await waitForElm('[class*="Viewer__Viewer___"] > div', true, 40);
ReactFiber.find('[class*="Viewer__Viewer___"] > div').setState({
selected: new Set([item.messageID]),
});
await delay(10);
const row = document.querySelector('[class*="MessageList__selected___"]');
if (row) (row as HTMLElement).click();
}
function openArchivedAssessment(item: ArchivedNotification) {
if (!item.programmeID || !item.metaclassID) return;
const base = `#?page=/assessments/${item.programmeID}:${item.metaclassID}`;
location.hash = item.assessmentID ? `${base}&item=${item.assessmentID}` : base;
}
function renderArchiveItem(item: ArchivedNotification): HTMLElement {
const row = document.createElement("button");
row.type = "button";
row.className = "bsplus-notification-archive-item";
row.dataset.notificationId = String(item.notificationID);
const title = document.createElement("span");
title.className = "bsplus-notification-archive-title";
title.textContent = item.title;
const meta = document.createElement("span");
meta.className = "bsplus-notification-archive-meta";
const parts = [formatArchiveDate(item.timestamp)];
if (item.subtitle) parts.push(item.subtitle);
if (item.subjectCode) parts.push(item.subjectCode);
meta.textContent = parts.join(" · ");
const badge = document.createElement("span");
badge.className = "bsplus-notification-archive-badge";
badge.textContent = "Saved locally";
row.append(title, meta, badge);
row.addEventListener("click", () => {
if (item.type === "message") {
void openArchivedMessage(item);
} else if (item.type === "coneqtassessments") {
openArchivedAssessment(item);
}
});
return row;
}
export function mountArchiveUI(
api: PluginAPI<Record<string, never>, ArchiveUIStorage>,
getUserKey: () => Promise<string | null>,
) {
const mountOnList = (listEl: HTMLElement) => {
if (listEl.querySelector(".bsplus-notification-archive-bar")) return;
const bar = document.createElement("div");
bar.className = "bsplus-notification-archive-bar";
const toggle = document.createElement("button");
toggle.type = "button";
toggle.className = "bsplus-notification-archive-toggle";
const panel = document.createElement("div");
panel.className = "bsplus-notification-archive-panel";
panel.hidden = true;
const refresh = async () => {
const userKey = await getUserKey();
if (!userKey) {
toggle.textContent = "Saved notifications (sign in required)";
toggle.disabled = true;
panel.replaceChildren();
return;
}
const archivesByUser = api.storage.archivesByUser ?? {};
const archive = archivesByUser[userKey] ?? {};
const items = listArchivedNotifications(archive);
const liveIds = new Set(
Array.from(listEl.querySelectorAll('[class*="notifications__item___"]'))
.map((el) => el.getAttribute("data-id"))
.filter(Boolean),
);
const removedCount = items.filter(
(item) => !liveIds.has(String(item.notificationID)),
).length;
toggle.disabled = false;
toggle.textContent =
items.length === 0
? "Saved notifications (none yet)"
: `Saved notifications (${items.length}${removedCount > 0 ? `, ${removedCount} no longer on SEQTA` : ""})`;
panel.replaceChildren();
if (items.length === 0) {
const empty = document.createElement("p");
empty.className = "bsplus-notification-archive-empty";
empty.textContent =
"Notifications you receive are saved here per account in extension storage.";
panel.append(empty);
return;
}
for (const item of items) {
panel.append(renderArchiveItem(item));
}
};
toggle.addEventListener("click", () => {
panel.hidden = !panel.hidden;
toggle.setAttribute("aria-expanded", panel.hidden ? "false" : "true");
if (!panel.hidden) void refresh();
});
bar.append(toggle, panel);
listEl.append(bar);
void refresh();
};
api.seqta.onMount('[class*="notifications__list___"]', (el) => {
mountOnList(el as HTMLElement);
});
api.storage.onChange("archivesByUser", () => {
document
.querySelectorAll('[class*="notifications__list___"]')
.forEach((el) => {
const bar = el.querySelector(".bsplus-notification-archive-bar");
if (bar) bar.remove();
mountOnList(el as HTMLElement);
});
});
}
@@ -1,19 +1,43 @@
import type { Plugin } from "../../core/types";
import { booleanSetting } from "@/plugins/core/settingsHelpers";
import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage";
import { verboseInfo } from "@/utils/verboseLog";
import {
type ArchivesByUser,
fetchAllNotifications,
mergeNotificationsIntoArchive,
resolveNotificationUserKey,
} from "./archive";
import { mountArchiveUI } from "./archiveUI";
import styles from "./styles.css?inline";
const notificationCollectorSettings = {
saveLocally: booleanSetting({
default: true,
title: "Save notification history locally",
description:
"Keeps a per-account copy in extension storage. SEQTA removes notifications after about a year; these stay until you clear extension data.",
}),
} as const;
interface NotificationCollectorStorage {
lastNotificationCount: number;
lastCheckedTime: string;
consecutiveErrors: number;
archivesByUser: ArchivesByUser;
}
const notificationCollectorPlugin: Plugin<{}, NotificationCollectorStorage> = {
const notificationCollectorPlugin: Plugin<
typeof notificationCollectorSettings,
NotificationCollectorStorage
> = {
id: "notificationCollector",
name: "Notification Collector",
description: "Collects and displays SEQTA notifications",
version: "1.0.0",
settings: {},
description:
"Tracks notifications and saves a local per-account archive that outlasts SEQTA's server retention",
version: "1.1.0",
settings: notificationCollectorSettings,
styles,
disableToggle: true,
run: async (api) => {
@@ -21,24 +45,51 @@ const notificationCollectorPlugin: Plugin<{}, NotificationCollectorStorage> = {
return () => {};
}
await api.storage.loaded;
await api.settings.loaded;
let pollInterval: number | null = null;
let isVisible = !document.hidden;
let baseInterval = 30000; // 30 seconds
const maxInterval = 300000; // 5 minutes max
let archiveSyncInFlight = false;
const baseInterval = 30000;
const maxInterval = 300000;
// Store last notification count in storage
if (!api.storage.lastNotificationCount) {
api.storage.lastNotificationCount = 0;
}
if (!api.storage.consecutiveErrors) {
api.storage.consecutiveErrors = 0;
}
if (!api.storage.archivesByUser) {
api.storage.archivesByUser = {};
}
const syncArchive = async () => {
if (!api.settings.saveLocally || archiveSyncInFlight) return;
archiveSyncInFlight = true;
try {
const userKey = await resolveNotificationUserKey();
if (!userKey) return;
const notifications = await fetchAllNotifications();
const archivesByUser = { ...(api.storage.archivesByUser ?? {}) };
const existing = archivesByUser[userKey] ?? {};
const merged = mergeNotificationsIntoArchive(existing, notifications);
if (JSON.stringify(existing) !== JSON.stringify(merged)) {
archivesByUser[userKey] = merged;
api.storage.archivesByUser = archivesByUser;
}
} catch (error) {
console.warn("[BetterSEQTA+] Notification archive sync failed:", error);
} finally {
archiveSyncInFlight = false;
}
};
const checkNotifications = async () => {
// Skip if tab is not visible to save battery
if (!isVisible) {
return;
}
if (!isVisible) return;
try {
const alertDiv = document.querySelector(
@@ -49,30 +100,17 @@ const notificationCollectorPlugin: Plugin<{}, NotificationCollectorStorage> = {
alertDiv.textContent = api.storage.lastNotificationCount.toString();
}
const response = await fetch(
`${location.origin}/seqta/student/heartbeat?`,
{
method: "POST",
headers: {
"Content-Type": "application/json; charset=utf-8",
},
body: JSON.stringify({
timestamp: "1970-01-01 00:00:00.0",
hash: "#?page=/home",
}),
},
);
const notifications = await fetchAllNotifications();
const notificationCount = notifications.length;
const data = await response.json();
// Store notification count for history
const notificationCount = data.payload.notifications.length;
api.storage.lastNotificationCount = notificationCount;
api.storage.lastCheckedTime = new Date().toISOString();
// Reset error count on success
api.storage.consecutiveErrors = 0;
if (api.settings.saveLocally) {
await syncArchive();
}
if (alertDiv) {
alertDiv.textContent = notificationCount.toString();
} else {
@@ -86,7 +124,6 @@ const notificationCollectorPlugin: Plugin<{}, NotificationCollectorStorage> = {
};
const getNextInterval = () => {
// Exponential backoff on errors, max 5 minutes
const errorMultiplier = Math.min(
Math.pow(2, api.storage.consecutiveErrors || 0),
10,
@@ -95,17 +132,14 @@ const notificationCollectorPlugin: Plugin<{}, NotificationCollectorStorage> = {
};
const startPolling = () => {
if (pollInterval) return; // Already polling
if (pollInterval) return;
checkNotifications();
const scheduleNext = () => {
const interval = getNextInterval();
pollInterval = window.setTimeout(() => {
checkNotifications().then(() => {
if (pollInterval) {
// Only continue if not stopped
scheduleNext();
}
if (pollInterval) scheduleNext();
});
}, interval);
};
@@ -130,29 +164,43 @@ const notificationCollectorPlugin: Plugin<{}, NotificationCollectorStorage> = {
}
};
// Listen for visibility changes to pause/resume polling
const handleVisibilityChange = () => {
isVisible = !document.hidden;
if (isVisible && !pollInterval) {
// Resume polling when tab becomes visible
const alertDiv = document.querySelector(
"[class*='notifications__bubble___']",
);
if (alertDiv) {
startPolling();
}
if (alertDiv) startPolling();
}
};
document.addEventListener("visibilitychange", handleVisibilityChange);
api.seqta.onMount("[class*='notifications__bubble___']", (_) => {
const pageChangeUnregister = api.seqta.onPageChange((page) => {
if (page === "notifications" && api.settings.saveLocally) {
void syncArchive();
}
});
mountArchiveUI(api, resolveNotificationUserKey);
api.seqta.onMount("[class*='notifications__bubble___']", () => {
startPolling();
if (api.settings.saveLocally) {
void syncArchive();
}
});
api.seqta.onMount("[class*='notifications__list___']", () => {
if (api.settings.saveLocally) {
void syncArchive();
}
});
return () => {
stopPolling();
document.removeEventListener("visibilitychange", handleVisibilityChange);
pageChangeUnregister.unregister();
};
},
};
@@ -0,0 +1,87 @@
.bsplus-notification-archive-bar {
margin-top: 0.5rem;
padding-top: 0.5rem;
border-top: 1px solid color-mix(in srgb, var(--text-primary) 12%, transparent);
}
.bsplus-notification-archive-toggle {
display: block;
width: 100%;
border: 1px solid color-mix(in srgb, var(--text-primary) 14%, transparent);
border-radius: 12px;
background: var(--theme-primary, var(--background-primary, #232323));
color: var(--text-primary);
padding: 0.55rem 0.75rem;
font-size: 0.8125rem;
font-weight: 600;
text-align: left;
cursor: pointer;
transition: background-color 150ms ease;
}
.bsplus-notification-archive-toggle:hover:not(:disabled) {
background: var(--theme-secondary, var(--background-secondary, #1a1a1a));
}
.bsplus-notification-archive-toggle:disabled {
opacity: 0.65;
cursor: default;
}
.bsplus-notification-archive-panel {
margin-top: 0.45rem;
max-height: 14rem;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 0.35rem;
}
.bsplus-notification-archive-panel[hidden] {
display: none !important;
}
.bsplus-notification-archive-item {
display: flex;
flex-direction: column;
gap: 0.2rem;
width: 100%;
border: none;
border-left: 3px solid var(--better-main, #3b82f6);
border-radius: 10px;
background: var(--theme-primary, var(--background-primary, #232323));
color: var(--text-primary);
padding: 0.5rem 0.65rem;
text-align: left;
cursor: pointer;
transition: background-color 150ms ease;
}
.bsplus-notification-archive-item:hover {
background: var(--theme-secondary, var(--background-secondary, #1a1a1a));
}
.bsplus-notification-archive-title {
font-size: 0.8125rem;
font-weight: 600;
line-height: 1.3;
}
.bsplus-notification-archive-meta {
font-size: 0.75rem;
opacity: 0.78;
line-height: 1.3;
}
.bsplus-notification-archive-badge {
font-size: 0.6875rem;
font-weight: 600;
opacity: 0.7;
}
.bsplus-notification-archive-empty {
font-size: 0.75rem;
opacity: 0.8;
margin: 0.25rem 0 0;
line-height: 1.4;
}