chore: relocate backend into apps/api ahead of monorepo merge

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-24 12:20:40 +08:00
co-authored by Claude Sonnet 5
parent af44598df6
commit eaa6d2276a
388 changed files with 0 additions and 13998 deletions
+153
View File
@@ -0,0 +1,153 @@
/***********************************************************************************************************************************************************************
* File Name: audienceResolver.util.js
* Type of Program: Utility
* Description: Shared "who does this target reach" resolution for anything
* broadcast-shaped (notification broadcasts, email broadcasts).
* Extracted out of controllers/admin/notificationBroadcasts.controller.js
* so both features resolve task_list/course/tier_plan targeting
* identically instead of drifting apart.
* Author: Kenneth Obsequio (@lash0000)
* Date Created: Jul. 3, 2026
***********************************************************************************************************************************************************************/
const { Op, QueryTypes } = require('sequelize');
const sequelize = require('../config/db.config');
const mdl_Users = require('../models/users/users.mdl');
const { TaskList } = require('../models/task/task.mdl');
const { Course } = require('../models/courses/courses.mdl');
const mdl_TierCategories = require('../models/tiers/tier_categories.mdl');
const mdl_UserTiers = require('../models/tiers/user_tiers.mdl');
const mdl_TierPlans = require('../models/tiers/tier_plans.mdl');
const mdl_Product = require('../models/courses/products.mdl');
const mdl_CoursePurchase = require('../models/courses/course_purchases.mdl');
const ALLOWED_TARGET_TYPES = ["admin", "user", "both", "task_list", "course", "tier_plan"];
const SCOPED_TARGET_TYPES = ["task_list", "course", "tier_plan"];
async function validateTargetId(target_type, target_id) {
if (target_type === "task_list") {
const row = await TaskList.findOne({ where: { task_list_id: target_id, deletedAt: null } });
if (!row) { const err = new Error("Selected task list was not found."); err.status = 400; throw err; }
} else if (target_type === "course") {
const row = await Course.findOne({ where: { uuid: target_id, deletedAt: null } });
if (!row) { const err = new Error("Selected course was not found."); err.status = 400; throw err; }
} else if (target_type === "tier_plan") {
const row = await mdl_TierPlans.findOne({ where: { plan_id: target_id, deletedAt: null } });
if (!row) { const err = new Error("Selected tier plan was not found."); err.status = 400; throw err; }
}
}
// Rank-0 (free) courses resolve like target_type: 'user' — everyone qualifies.
async function resolveCourseUserIds(courseUuid) {
const course = await Course.findOne({ where: { uuid: courseUuid, deletedAt: null }, attributes: ['course_id', 'subscription'] });
if (!course) return [];
// rank is BIGINT on CockroachDB — Sequelize returns it as a string, so normalize to Number.
const categories = await mdl_TierCategories.findAll({ attributes: ['slug', 'rank'] });
const rankMap = Object.fromEntries(categories.map((c) => [c.slug, Number(c.rank)]));
const courseRank = rankMap[course.subscription] ?? Infinity;
const userIds = new Set();
if (courseRank === 0) {
const users = await mdl_Users.findAll({ attributes: ['user_id'], where: { acc_type: 'user', deletedAt: null }, raw: true });
users.forEach((u) => userIds.add(String(u.user_id)));
return [...userIds];
}
const qualifyingSlugs = Object.entries(rankMap).filter(([, rank]) => rank >= courseRank).map(([slug]) => slug);
if (qualifyingSlugs.length) {
const holders = await mdl_UserTiers.findAll({
attributes: ['user_id'],
where: { status: 'active', tier: { [Op.in]: qualifyingSlugs } },
raw: true,
});
holders.forEach((h) => userIds.add(String(h.user_id)));
}
const product = await mdl_Product.findOne({ where: { purchasable_type: 'course', purchasable_id: course.course_id } });
if (product) {
const purchasers = await mdl_CoursePurchase.findAll({
attributes: ['user_id'],
where: {
product_id: product.id,
status: 'completed',
[Op.or]: [{ expires_at: null }, { expires_at: { [Op.gt]: new Date() } }],
},
raw: true,
});
purchasers.forEach((p) => userIds.add(String(p.user_id)));
}
return [...userIds];
}
async function resolveTaskListUserIds(taskListId) {
const rows = await sequelize.query(
`SELECT DISTINCT ugm.user_id
FROM task_list_groups tlg
JOIN user_group_members ugm ON ugm.group_id = tlg.group_id AND ugm."deletedAt" IS NULL
WHERE tlg.task_list_id = :taskListId`,
{ replacements: { taskListId }, type: QueryTypes.SELECT }
);
return rows.map((r) => String(r.user_id));
}
// user_id → group_id, for deep-linking task_list broadcasts to /group/:groupId/view/:taskListId.
// First matching group wins if a user belongs to more than one group tied to the task list.
async function resolveTaskListUserGroups(taskListId) {
const rows = await sequelize.query(
`SELECT ugm.user_id, tlg.group_id
FROM task_list_groups tlg
JOIN user_group_members ugm ON ugm.group_id = tlg.group_id AND ugm."deletedAt" IS NULL
WHERE tlg.task_list_id = :taskListId`,
{ replacements: { taskListId }, type: QueryTypes.SELECT }
);
const map = {};
for (const r of rows) {
const uid = String(r.user_id);
if (!(uid in map)) map[uid] = r.group_id;
}
return map;
}
async function resolveTierPlanUserIds(planId) {
const holders = await mdl_UserTiers.findAll({
attributes: ['user_id'],
where: { plan_id: planId, status: 'active' },
raw: true,
});
return holders.map((h) => String(h.user_id));
}
// Dispatcher for the 3 "scoped" target types only — 'admin'/'user'/'both' mean
// different things to different callers (e.g. notification broadcasts post to
// the shared admin bell feed for 'admin'; email broadcasts email every admin/
// staff user instead), so those stay caller-specific rather than living here.
async function resolveTargetUserIds(target_type, target_id) {
if (target_type === 'task_list') return resolveTaskListUserIds(target_id);
if (target_type === 'course') return resolveCourseUserIds(target_id);
if (target_type === 'tier_plan') return resolveTierPlanUserIds(target_id);
return [];
}
async function resolveAllUserIds({ transaction } = {}) {
const users = await mdl_Users.findAll({
attributes: ['user_id'],
where: { acc_type: 'user', deletedAt: null },
raw: true,
transaction,
});
return users.map((u) => String(u.user_id));
}
module.exports = {
ALLOWED_TARGET_TYPES,
SCOPED_TARGET_TYPES,
validateTargetId,
resolveCourseUserIds,
resolveTaskListUserIds,
resolveTaskListUserGroups,
resolveTierPlanUserIds,
resolveTargetUserIds,
resolveAllUserIds,
};
+161
View File
@@ -0,0 +1,161 @@
// utils/queryBuilder.js
const { Sequelize, Op } = require("sequelize");
// ─── Custom sort order for ENUM fields ────────────────────────────────────────
const ENUM_SORT_ORDER = {
acc_type: ["admin", "staff", "user"],
reg_type: ["system", "google"],
};
// createdBy/updatedBy/deletedBy filter options come from getFieldValues()
// as { value: user_id, label: full_name } — the filter sheet selects by id,
// so these need an exact match against the bigint column, never the
// substring-on-text-cast path used for everything else (that path compares
// against the raw id and can never match a name-looking value).
const AUDIT_ID_FIELDS = new Set(["createdBy", "updatedBy", "deletedBy"]);
/**
* Builds a Sequelize `where` clause from an array of filters.
*
* @param {Array<{ id: string, value: any }>} filters
* @param {Set<string>} allowedFields
* @param {string} [parentAlias] - main model's table alias (e.g. "User"). Needed
* to qualify Sequelize.col() references — unqualified col() refs throw
* "column reference is ambiguous" as soon as a query joins another table
* that happens to share a column name (e.g. Users + UserGroups both have
* is_active/createdAt/updatedAt/deletedAt).
* @param {Set<string>} [dateFields] - fields whose picklist values are
* calendar days (see below) — matched by range, not substring.
* @returns {Object} Sequelize where clause
*/
function buildWhere(filters = [], allowedFields = new Set(), parentAlias = null, dateFields = new Set()) {
const where = [];
for (const { id, value } of filters) {
if (!id || value === undefined || value === null || value === "") continue;
if (allowedFields.size && !allowedFields.has(id)) continue;
const values = Array.isArray(value) ? value : [value];
if (AUDIT_ID_FIELDS.has(id)) {
where.push({ [id]: { [Op.in]: values } });
continue;
}
const qualifiedCol = parentAlias ? `${parentAlias}.${id}` : id;
// Date/timestamp columns (createdAt, updatedAt, ...) — the filter sheet's
// picklist values are whole calendar days (e.g. "2026-07-16"), but the
// column itself is a full timestamp. Casting the timestamp to TEXT and
// doing a substring iLike match against just the date portion is a loose
// match: it also picks up every OTHER row whose time-of-day component
// happens to render into digits that appear elsewhere in the cast string,
// so a single selected day can silently pull in unrelated rows. Match by
// an explicit [dayStart, nextDayStart) range on the real column instead —
// exact, and immune to how the DB happens to stringify the timestamp.
if (dateFields.has(id) && !id.startsWith("personal_info.")) {
const conditions = values.map((v) => {
const datePart = String(v).slice(0, 10);
const dayStart = new Date(`${datePart}T00:00:00.000Z`);
const dayEnd = new Date(dayStart.getTime() + 24 * 60 * 60 * 1000);
return Sequelize.where(Sequelize.col(qualifiedCol), {
[Op.gte]: dayStart,
[Op.lt]: dayEnd,
});
});
where.push({ [Op.or]: conditions });
continue;
}
const conditions = values.map((v) =>
id.startsWith("personal_info.")
? Sequelize.where(
Sequelize.json(`personal_info.${id.replace("personal_info.", "")}`),
{ [Op.iLike]: `%${v}%` }
)
: Sequelize.where(
Sequelize.cast(Sequelize.col(qualifiedCol), "TEXT"),
{ [Op.iLike]: `%${v}%` }
)
);
where.push({ [Op.or]: conditions });
}
return where.length ? { [Op.and]: where } : {};
}
/**
* Builds a Sequelize `order` clause from an array of sort descriptors.
* Falls back to [["createdAt", "DESC"]] if no valid sort entries.
*
* @param {Array<{ id: string, desc: boolean }>} sort
* @returns {Array} Sequelize order clause
*/
function buildOrder(sort = [], allowedFields = new Set(), computedFields = new Set(), parentAlias = null) {
const order = [];
const qualifiedId = (id) => (parentAlias ? `"${parentAlias}"."${id}"` : `"${id}"`);
for (const { id, desc } of sort) {
if (!id) continue;
if (allowedFields.size && !allowedFields.has(id)) continue;
// ─── Computed (subquery/literal) columns — order by the unqualified
// SELECT alias, since they aren't real columns on the model's table ──
if (computedFields.has(id)) {
order.push([Sequelize.literal(`"${id}"`), desc ? "DESC" : "ASC"]);
continue;
}
// ─── ENUM fields — use CASE for custom sort order ─────────────────────
if (ENUM_SORT_ORDER[id]) {
const sequence = desc
? [...ENUM_SORT_ORDER[id]].reverse()
: ENUM_SORT_ORDER[id];
const caseExpr = sequence
.map((val, i) => `WHEN '${val}' THEN ${i}`)
.join(" ");
order.push([Sequelize.literal(`CASE ${qualifiedId(id)} ${caseExpr} END`)]);
continue;
}
// ─── JSONB dot-notation fields ─────────────────────────────────────────
if (id.startsWith("personal_info.")) {
order.push([Sequelize.json(id), desc ? "DESC" : "ASC"]);
continue;
}
// ─── Regular fields ───────────────────────────────────────────────────
order.push([id, desc ? "DESC" : "ASC"]);
}
return order.length ? order : [["createdAt", "DESC"]];
}
/**
* Convenience wrapper — returns both where and order in one call.
*
* @param {Array} filters
* @param {Array} sort
* @param {Array} [dateFields] - fields to match by day-range instead of substring
* @returns {{ where: Object, order: Array }}
*/
function buildQuery(filters = [], sort = [], allowedFields = [], computedFields = [], parentAlias = null, dateFields = []) {
const fieldSet = new Set(allowedFields);
const computedSet = new Set(computedFields);
const orderFieldSet = new Set([...allowedFields, ...computedFields]);
const dateFieldSet = new Set(dateFields);
return {
// Computed (subquery/literal) columns aren't real table columns — filtering
// via Sequelize.col() would error, so only allow them in ORDER BY, not WHERE.
where: buildWhere(filters, fieldSet, parentAlias, dateFieldSet),
order: buildOrder(sort, orderFieldSet, computedSet, parentAlias),
};
}
module.exports = { buildWhere, buildOrder, buildQuery };
+31
View File
@@ -0,0 +1,31 @@
"use strict";
/**
* Single archive — soft delete one record
*/
async function archiveOne(Model, where, deletedBy, transaction) {
const record = await Model.findOne({ where, transaction });
if (!record) return null;
await record.update({ deletedBy: deletedBy ?? null }, { transaction });
await record.destroy({ transaction });
return record;
}
/**
* Bulk archive — soft delete multiple records by primary key
*/
async function archiveMany(Model, pkField, ids, deletedBy, transaction) {
if (!ids?.length) return 0;
const records = await Model.findAll({ where: { [pkField]: ids, deletedAt: null } });
if (!records.length) return 0;
for (const record of records) {
await record.update({ deletedBy: deletedBy ?? null }, { transaction });
await record.destroy({ transaction });
}
return records.length;
}
module.exports = { archiveOne, archiveMany };
@@ -0,0 +1,245 @@
'use strict';
/***********************************************************************************************************************************************************************
* File Name: completion_requirements.registry.js
* Type of Program: Utility (type → handler registry)
* Description: Declarative dispatch table for the completion-requirement types
* (read_all_content, pass_quiz, watch_percent, watch_video, listen_audio,
* manual_complete), plus the `evaluateEntity` resolver that walks a
* course/unit/lesson's configured
* CompletionRequirement rows (or falls back to today's implicit rule when
* none are configured) and ANDs the results.
*
* `evaluateEntity` lives here rather than in services/courses/completion.service.js
* because unit/course evaluation is recursive (a unit's `read_all_content` rule
* means "every child lesson evaluates to completed", which itself may be governed
* by that lesson's own configured rule) — keeping the resolver next to the handler
* map it recurses through avoids a circular require with the service layer, which
* instead imports `evaluateEntity` from here and layers persistence/cascading on top.
*
* Read dispatch for "is this lesson/unit's own flag completed" branches on whether
* a course context is present:
* - courseId present → CourseReadingProgress (UUID-keyed, global per user+lesson)
* - courseId null → LessonReadingProgress / UnitReadingProgress (BIGINT-keyed,
* the only tables that support a null course_id — required
* for standalone/library unit-and-lesson consumption, since
* CourseReadingProgress.course_id is NOT NULL in the DB).
*
* Author: Kenneth Obsequio (@lash0000)
* Date Created: Jul. 14, 2026
***********************************************************************************************************************************************************************/
const CompletionRequirement = require('../../models/courses/completion_requirement.mdl');
const CompletionRequirementProgress = require('../../models/courses/completion_requirement_progress.mdl');
const CourseReadingProgress = require('../../models/courses/course_reading_progress.mdl');
const LessonReadingProgress = require('../../models/courses/lesson_reading_progress.mdl');
const Lesson = require('../../models/courses/lessons.mdl');
const UnitQuiz = require('../../models/courses/unit_quiz.mdl');
const CourseAssessment = require('../../models/courses/course_assessment.mdl');
const QuizAttempt = require('../../models/courses/quiz_attempt.mdl');
const { getCourseUnitIds, getUnitLessonIds } = require('./hierarchy.util');
// ─── Leaf read helpers ─────────────────────────────────────────────────────────
// Shared by the type handlers below AND by services/courses/completion.service.js,
// which uses these same reads immediately after writing progress within one transaction.
// Shared by manual_complete / watch_video / listen_audio — all three are computed
// entirely at write time (recordManualComplete / recordWatchProgress) and just read
// back the persisted `completed` flag here.
async function isProgressCompleted({ requirement, userId, t }) {
const progress = await CompletionRequirementProgress.findOne({
where: { requirement_id: requirement.requirement_id, user_id: userId },
transaction: t,
});
return !!progress?.completed;
}
async function isLessonComplete({ lessonId, userId, courseId, t }) {
if (courseId) {
const lesson = await Lesson.findOne({ where: { lesson_id: lessonId }, attributes: ['uuid'], transaction: t });
if (!lesson) return false;
const row = await CourseReadingProgress.findOne({
where: { user_id: userId, type: 'lesson', reference_id: lesson.uuid, status: 'completed' },
transaction: t,
});
return !!row;
}
const row = await LessonReadingProgress.findOne({
where: { user_id: userId, lesson_id: lessonId, status: 'completed' },
transaction: t,
});
return !!row;
}
async function isUnitQuizPassed({ unitId, userId, t }) {
const quiz = await UnitQuiz.findOne({ where: { unit_id: unitId }, attributes: ['quiz_id'], transaction: t });
if (!quiz) return false;
const attempt = await QuizAttempt.findOne({
where: { quiz_id: quiz.quiz_id, user_id: userId, passed: true },
transaction: t,
});
return !!attempt;
}
async function isCourseAssessmentPassed({ courseId, userId, t }) {
const assessment = await CourseAssessment.findOne({ where: { course_id: courseId }, attributes: ['assessment_id'], transaction: t });
if (!assessment) return false;
const attempt = await QuizAttempt.findOne({
where: { assessment_id: assessment.assessment_id, user_id: userId, passed: true },
transaction: t,
});
return !!attempt;
}
// Every attached (non-archived) lesson under this unit must itself evaluate to 'completed'.
async function areAllLessonsComplete({ unitId, userId, courseId, t }) {
const lessonIds = await getUnitLessonIds(unitId);
if (!lessonIds.length) return false; // no lessons attached — matches old deriveUnitStatus's "!links.length → in_progress"
for (const lessonId of lessonIds) {
const result = await evaluateEntity({ entityType: 'lesson', entityId: lessonId, userId, courseId, transaction: t });
if (result.status !== 'completed') return false;
}
return true;
}
// Every attached (non-archived) unit under this course must itself evaluate to 'completed'.
async function areAllUnitsComplete({ courseId, userId, t }) {
const unitIds = await getCourseUnitIds(courseId);
if (!unitIds.length) return false; // matches old deriveCourseStatus's "!links.length → in_progress"
for (const unitId of unitIds) {
const result = await evaluateEntity({ entityType: 'unit', entityId: unitId, userId, courseId, transaction: t });
if (result.status !== 'completed') return false;
}
return true;
}
// ─── Type handlers ──────────────────────────────────────────────────────────────
const TYPE_HANDLERS = {
read_all_content: {
validEntityTypes: ['course', 'unit', 'lesson'],
isSatisfied: async ({ entityType, entityId, userId, courseId, t }) => {
if (entityType === 'lesson') return isLessonComplete({ lessonId: entityId, userId, courseId, t });
if (entityType === 'unit') return areAllLessonsComplete({ unitId: entityId, userId, courseId, t });
if (entityType === 'course') return areAllUnitsComplete({ courseId: entityId, userId, t });
return false;
},
},
pass_quiz: {
validEntityTypes: ['unit', 'course'],
isSatisfied: async ({ entityType, entityId, userId, t }) => {
if (entityType === 'unit') return isUnitQuizPassed({ unitId: entityId, userId, t });
if (entityType === 'course') return isCourseAssessmentPassed({ courseId: entityId, userId, t });
return false;
},
},
watch_percent: {
validEntityTypes: ['lesson'],
isSatisfied: async ({ userId, requirement, t }) => {
const progress = await CompletionRequirementProgress.findOne({
where: { requirement_id: requirement.requirement_id, user_id: userId },
transaction: t,
});
if (!progress) return false;
if (progress.completed) return true;
// CockroachDB returns INTEGER columns as strings over the wire (same class of
// issue as the BigInt precision fix) — without Number() coercion this becomes a
// lexicographic string comparison, where e.g. "7" >= "100" is true.
const minPercent = Number(requirement.min_percent ?? 100);
return Number(progress.progress_percent ?? 0) >= minPercent;
},
},
// watch_video / listen_audio: unlike watch_percent (one aggregate figure across
// whichever block is playing), these require EVERY block of the matching type on
// the lesson to individually reach 100% — recordWatchProgress computes that against
// the lesson's current block set and persists the result as `completed`, so reading
// it back here is identical to manual_complete's check.
watch_video: {
validEntityTypes: ['lesson'],
isSatisfied: async ({ userId, requirement, t }) => isProgressCompleted({ requirement, userId, t }),
},
listen_audio: {
validEntityTypes: ['lesson'],
isSatisfied: async ({ userId, requirement, t }) => isProgressCompleted({ requirement, userId, t }),
},
manual_complete: {
validEntityTypes: ['course', 'unit', 'lesson'],
isSatisfied: async ({ userId, requirement, t }) => isProgressCompleted({ requirement, userId, t }),
},
};
// ─── Zero-requirements-configured fallback ──────────────────────────────────────
// Reproduces today's exact implicit behavior so existing content doesn't change
// behavior until an admin explicitly opts into configured requirements.
const DEFAULT_HANDLERS = {
lesson: ({ entityId, userId, courseId, t }) => isLessonComplete({ lessonId: entityId, userId, courseId, t }),
unit: ({ entityId, userId, courseId, t }) => areAllLessonsComplete({ unitId: entityId, userId, courseId, t }),
// A course with no assessment ever built can never reach 'completed' via this default —
// matches the exact (if strict) behavior of the old deriveCourseStatus/hasPassedCourseAssessment.
course: async ({ entityId, userId, t }) => {
const allUnitsRead = await areAllUnitsComplete({ courseId: entityId, userId, t });
if (!allUnitsRead) return false;
return isCourseAssessmentPassed({ courseId: entityId, userId, t });
},
};
// ─── Resolver ────────────────────────────────────────────────────────────────────
/**
* Evaluate whether `entityType`/`entityId` is 'completed' for `userId`, either against
* its configured CompletionRequirement rows (AND'd, `is_required` rows only gate status)
* or — when none are configured — the default implicit rule for that entity_type.
*
* @returns {{ status: 'completed'|'in_progress', evaluated_via: 'configured'|'default', satisfied: string[] }}
*/
async function evaluateEntity({ entityType, entityId, userId, courseId = null, transaction = null }) {
const t = transaction;
// Units always complete by passing their own quiz — overrides whatever
// completion_requirement type (if any) is configured on the unit. A unit
// with no quiz attached never completes (isUnitQuizPassed returns false).
if (entityType === 'unit') {
const completed = await isUnitQuizPassed({ unitId: entityId, userId, t });
return { status: completed ? 'completed' : 'in_progress', evaluated_via: 'quiz_required', satisfied: [] };
}
const rows = await CompletionRequirement.findAll({
where: { entity_type: entityType, entity_id: entityId },
order: [['order', 'ASC']],
transaction: t,
});
if (!rows.length) {
const completed = await DEFAULT_HANDLERS[entityType]({ entityId, userId, courseId, t });
return { status: completed ? 'completed' : 'in_progress', evaluated_via: 'default', satisfied: [] };
}
const satisfied = [];
for (const row of rows) {
const handler = TYPE_HANDLERS[row.type];
if (!handler) continue; // unknown type — ignore rather than hard-fail evaluation
const ok = await handler.isSatisfied({ entityType, entityId, userId, courseId, requirement: row, t });
if (ok) satisfied.push(row.requirement_id);
}
const requiredRows = rows.filter(r => r.is_required);
const allRequiredSatisfied = requiredRows.every(r => satisfied.includes(r.requirement_id));
return { status: allRequiredSatisfied ? 'completed' : 'in_progress', evaluated_via: 'configured', satisfied };
}
// entity_type → allowed requirement types, for admin-side validation (mirrors on the frontend).
const VALID_ENTITY_TYPES = Object.fromEntries(
Object.entries(TYPE_HANDLERS).map(([type, def]) => [type, def.validEntityTypes])
);
module.exports = {
evaluateEntity,
TYPE_HANDLERS,
VALID_ENTITY_TYPES,
// exported for reuse by services/courses/completion.service.js
isLessonComplete,
isUnitQuizPassed,
isCourseAssessmentPassed,
};
+57
View File
@@ -0,0 +1,57 @@
"use strict";
/**
* Grades a submission against the stored correct answers.
*
* The breakdown returned here is what gets sent back to the client, so it
* deliberately never includes which option(s) were correct — only whether
* the user's own answer for each question was right or wrong. Explanation
* text is included only when the question was answered correctly, since
* showing it for a wrong answer would effectively reveal the correct one.
*
* @param {Array} questions - QuizQuestion rows w/ .options (incl. is_correct), already fetched
* @param {Object} answers - { [question_id]: optionId | optionId[] } submitted by the client
*/
function gradeSubmission(questions, answers = {}) {
let totalPoints = 0;
let earnedPoints = 0;
const breakdown = questions.map((q) => {
const points = q.points ?? 1;
totalPoints += points;
const correctIds = (q.options ?? [])
.filter((o) => o.is_correct)
.map((o) => o.option_id);
const submitted = answers[q.question_id];
const submittedIds = Array.isArray(submitted)
? submitted
: (submitted !== undefined && submitted !== null ? [submitted] : []);
const isCorrect =
submittedIds.length === correctIds.length &&
correctIds.every((id) => submittedIds.includes(id));
if (isCorrect) earnedPoints += points;
return {
question_id: q.question_id,
type: q.type,
question: q.question,
points,
is_correct: isCorrect,
selected_option_ids: submittedIds,
explanation: isCorrect ? (q.explanation ?? null) : null,
options: (q.options ?? []).map((o) => ({
option_id: o.option_id,
text: o.text,
})),
};
});
const score = totalPoints > 0 ? Math.round((earnedPoints / totalPoints) * 100) : 0;
return { totalPoints, earnedPoints, score, breakdown };
}
module.exports = { gradeSubmission };
+114
View File
@@ -0,0 +1,114 @@
"use strict";
/***********************************************************************************************************************************************************************
* File Name: hierarchy.util.js
* Type of Program: Utility
* Description: Helpers for the junction-based course hierarchy
* (courses ⇄ course_units ⇄ units ⇄ unit_lessons ⇄ lessons).
*
* Sequelize belongsToMany includes surface the junction row under the through-
* model key ("CourseUnit" / "UnitLesson"). These helpers flatten that back to
* the flat `order_index` field the API has always exposed, so response shapes
* stay identical to the pre-junction era.
*
* Author: Kenneth Obsequio (@lash0000)
* Date Created: Jul. 7, 2026
***********************************************************************************************************************************************************************/
const sequelize = require("../../config/db.config");
// ── Response flattening ───────────────────────────────────────────────────────
/** Sort lessons by their unit_lessons.order_index and flatten it onto each row. */
function flattenLessons(lessons = []) {
return [...lessons]
.map((l) => {
const { UnitLesson: link, ...rest } = l;
return { ...rest, order_index: link?.order_index ?? rest.order_index ?? 0 };
})
.sort((a, b) => (a.order_index ?? 0) - (b.order_index ?? 0));
}
/** Sort units by their course_units.order_index, flatten it, and recurse into lessons. */
function flattenUnits(units = []) {
return [...units]
.map((u) => {
const { CourseUnit: link, ...rest } = u;
return {
...rest,
order_index: link?.order_index ?? rest.order_index ?? 0,
...(rest.lessons ? { lessons: flattenLessons(rest.lessons) } : {}),
};
})
.sort((a, b) => (a.order_index ?? 0) - (b.order_index ?? 0));
}
// ── Junction row maintenance ──────────────────────────────────────────────────
/** Next order_index for appending to a parent (max + 1, or 0 when empty). */
async function nextOrderIndex(JunctionModel, where, transaction) {
const max = await JunctionModel.max("order_index", { where, transaction });
return Number.isFinite(max) ? max + 1 : 0;
}
/**
* Persist a full ordering: ids[i] gets order_index i.
* Ignores ids without an existing junction row.
*/
async function reorderJunction(JunctionModel, parentField, parentId, childField, orderedIds = [], transaction) {
await Promise.all(orderedIds.map((id, i) =>
JunctionModel.update(
{ order_index: i },
{ where: { [parentField]: parentId, [childField]: id }, transaction }
)
));
}
// ── Structure counts (raw SQL — junction traversals) ──────────────────────────
/** Count non-archived lessons reachable from a course through its attached units. */
async function countCourseLessons(courseId) {
const [row] = await sequelize.query(`
SELECT CAST(COUNT(DISTINCT l.lesson_id) AS INTEGER) AS total
FROM lessons l
JOIN unit_lessons ul ON ul.lesson_id = l.lesson_id
JOIN units u ON u.unit_id = ul.unit_id AND u."deletedAt" IS NULL
JOIN course_units cu ON cu.unit_id = u.unit_id AND cu.course_id = :courseId
WHERE l."deletedAt" IS NULL
`, { replacements: { courseId }, type: sequelize.QueryTypes.SELECT });
return Number(row?.total ?? 0);
}
/** Non-archived unit ids attached to a course, in course order. */
async function getCourseUnitIds(courseId) {
const rows = await sequelize.query(`
SELECT u.unit_id
FROM units u
JOIN course_units cu ON cu.unit_id = u.unit_id AND cu.course_id = :courseId
WHERE u."deletedAt" IS NULL
ORDER BY cu.order_index ASC
`, { replacements: { courseId }, type: sequelize.QueryTypes.SELECT });
return rows.map((r) => r.unit_id);
}
/** Non-archived lesson ids attached to a unit, in unit order. */
async function getUnitLessonIds(unitId) {
const rows = await sequelize.query(`
SELECT l.lesson_id
FROM lessons l
JOIN unit_lessons ul ON ul.lesson_id = l.lesson_id AND ul.unit_id = :unitId
WHERE l."deletedAt" IS NULL
ORDER BY ul.order_index ASC
`, { replacements: { unitId }, type: sequelize.QueryTypes.SELECT });
return rows.map((r) => r.lesson_id);
}
module.exports = {
flattenLessons,
flattenUnits,
nextOrderIndex,
reorderJunction,
countCourseLessons,
getCourseUnitIds,
getUnitLessonIds,
};
+16
View File
@@ -0,0 +1,16 @@
"use strict";
/**
* Replace all junction rows for a course in one shot (delete + bulk create).
*/
async function syncJunction(Model, courseId, ids, fkField, transaction) {
await Model.destroy({ where: { course_id: courseId }, transaction });
if (ids?.length) {
await Model.bulkCreate(
ids.map((id) => ({ course_id: courseId, [fkField]: id })),
{ transaction }
);
}
}
module.exports = { syncJunction };
+62
View File
@@ -0,0 +1,62 @@
"use strict";
/**
* For CREATE — plain text array, no IDs needed
* objectives: ["text1"] or [{ text: "text1" }]
*/
async function syncObjectivesCreate(Model, parentField, parentId, objectives, transaction) {
if (!objectives?.length) return;
await Model.bulkCreate(
objectives.map((o, i) => ({
[parentField]: parentId,
text: typeof o === "string" ? o : o.text,
order_index: i,
})),
{ transaction }
);
}
/**
* For UPDATE — upsert by PK field (default "objective_id"), hard delete removed ones
* objectives: [{ objective_id: "123", text: "text1" }, { text: "new" }]
*/
async function syncObjectivesUpdate(Model, parentField, parentId, objectives, transaction, pkField = "objective_id") {
if (!objectives?.length) {
await Model.destroy({ where: { [parentField]: parentId }, force: true, transaction });
return;
}
const existing = await Model.findAll({ where: { [parentField]: parentId }, transaction });
const existingMap = new Map(existing.map((o) => [String(o[pkField]), o]));
const incomingIds = new Set(
objectives.filter((o) => o[pkField]).map((o) => String(o[pkField]))
);
// Hard delete removed
const toDelete = existing.filter((o) => !incomingIds.has(String(o[pkField])));
if (toDelete.length) {
await Model.destroy({
where: { [pkField]: toDelete.map((o) => o[pkField]) },
force: true,
transaction,
});
}
// Update existing or create new
for (let i = 0; i < objectives.length; i++) {
const item = objectives[i];
const record = item[pkField] ? existingMap.get(String(item[pkField])) : null;
if (record) {
await record.update({ text: item.text, order_index: i }, { transaction });
} else {
await Model.create(
{ [parentField]: parentId, text: item.text, order_index: i },
{ transaction }
);
}
}
}
module.exports = { syncObjectivesCreate, syncObjectivesUpdate };
@@ -0,0 +1,45 @@
"use strict";
const { Op } = require("sequelize");
const onlyDeleted = { deletedAt: { [Op.not]: null } };
/**
* Permanently delete a single archived record.
* Returns the record on success, null if not found, false if found but not archived.
*
* @param {Model} Model - Sequelize model
* @param {object} where - Where clause (primary key lookup)
* @param {object} t - Sequelize transaction
*/
async function permanentDeleteOne(Model, where, t) {
const record = await Model.findOne({ where, paranoid: false, transaction: t });
if (!record) return null;
if (!record.deletedAt) return false;
await record.destroy({ force: true, transaction: t });
return record;
}
/**
* Permanently delete many archived records by primary key.
* Returns the count of deleted records.
*
* @param {Model} Model - Sequelize model
* @param {string} pkColumn - Primary key column name (e.g. "course_id")
* @param {Array} ids - Array of primary key values to delete
* @param {object} t - Sequelize transaction
*/
async function permanentDeleteMany(Model, pkColumn, ids, t) {
if (!ids?.length) return 0;
const count = await Model.destroy({
where: { [pkColumn]: ids, ...onlyDeleted },
transaction: t,
paranoid: false,
force: true,
});
return count;
}
module.exports = { permanentDeleteOne, permanentDeleteMany };
@@ -0,0 +1,99 @@
// Fisher-Yates in-place shuffle — shared by shuffleOptions and shuffleQuestions.
function fisherYates(arr) {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
// Randomises the ORDER OF OPTIONS within each question. Pure — returns new
// arrays/objects, never mutates input. Grading is unaffected since
// submitUnitQuiz/submitCourseAssessment always re-fetch questions fresh
// from the DB and never trust the shuffled client-facing order.
function shuffleOptions(questions) {
return questions.map((q) => ({ ...q, options: fisherYates([...(q.options ?? [])]) }));
}
// Randomises the ORDER OF QUESTIONS. Pure — returns a new array.
// Safe: grading re-fetches questions from DB in stored order; client position
// has no effect on correctness checks.
function shuffleQuestions(questions) {
return fisherYates([...questions]);
}
// Single source of truth for both the GET-time info fields and the
// submit-time enforcement check.
//
// type = 'quiz' → unit quizzes: no cooldown, no attempt cap, always open
// type = 'assessment' → course assessments: maxFails failed attempts → cooldownHours cooldown (rolling cycles)
// maxFails / cooldownHours come from the assessment row; null = feature off (no limit/cooldown).
function getAttemptStatus(attempts, type = 'quiz', { maxFails, cooldownHours } = {}) {
const attempt_count = attempts.length;
const has_passed = attempts.some((a) => a.passed);
const best_attempt = attempts.reduce(
(best, a) => (!best || a.score > best.score ? a : best),
null
);
if (type === 'quiz') {
return {
attempt_count,
has_passed,
best_attempt,
attempts_remaining: null,
cooldown_until: null,
window_reset_at: null,
can_attempt: true,
};
}
// Assessment: simulate rolling cycles — N failed attempts → cooldown.
// null means the feature is off: no attempt cap / no cooldown.
const failLimit = maxFails ?? null;
const lockHours = cooldownHours ?? null;
if (failLimit === null || lockHours === null) {
return {
attempt_count,
has_passed,
best_attempt,
attempts_remaining: null,
cooldown_until: null,
window_reset_at: null,
can_attempt: true,
};
}
const sorted = [...attempts].sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt));
let cycle_end = null; // when the current cooldown expires (null = no active or past cooldown)
let failed_in_cycle = 0;
for (const a of sorted) {
// Skip attempts that fall inside a previous cooldown window (they shouldn't exist, but guard anyway)
if (cycle_end && new Date(a.createdAt) < cycle_end) continue;
if (!a.passed) {
failed_in_cycle++;
if (failed_in_cycle >= failLimit) {
cycle_end = new Date(new Date(a.createdAt).getTime() + lockHours * 3600000);
failed_in_cycle = 0;
}
}
}
const now = new Date();
const cooldown_until = (cycle_end && cycle_end > now) ? cycle_end.toISOString() : null;
return {
attempt_count,
has_passed,
best_attempt,
attempts_remaining: null,
cooldown_until,
window_reset_at: null,
can_attempt: !cooldown_until,
};
}
module.exports = { shuffleOptions, shuffleQuestions, getAttemptStatus };
@@ -0,0 +1,99 @@
"use strict";
const REF_TYPE_CONFIG = {
course: { pk: "course_id" },
unit: { pk: "unit_id" },
lesson: { pk: "lesson_id" },
};
/**
* Enriches CoursePrerequisite rows ({ref_type, ref_id, ...}) with the
* referenced entity's title (and subscription tier slug, where the entity
* has one) — one batched findAll per ref_type instead of a query per row.
* Rows whose referenced entity no longer exists (deleted) get title: null
* so callers can drop or flag them instead of crashing.
*/
async function resolvePrerequisiteTitles(prereqs, { Course, Unit, Lesson }) {
if (!prereqs?.length) return prereqs ?? [];
const models = { course: Course, unit: Unit, lesson: Lesson };
// Only Course/Unit carry a subscription tier gate — Lesson has none.
const attrsByType = { course: ["title", "subscription"], unit: ["title", "subscription"], lesson: ["title"] };
const idsByType = { course: new Set(), unit: new Set(), lesson: new Set() };
for (const p of prereqs) {
if (idsByType[p.ref_type]) idsByType[p.ref_type].add(p.ref_id);
}
const infoMaps = {};
for (const [type, { pk }] of Object.entries(REF_TYPE_CONFIG)) {
const ids = [...idsByType[type]];
infoMaps[type] = new Map();
if (!ids.length) continue;
const rows = await models[type].findAll({
where: { [pk]: ids },
attributes: [pk, ...attrsByType[type]],
});
for (const row of rows) infoMaps[type].set(String(row[pk]), row);
}
return prereqs.map((p) => {
const info = infoMaps[p.ref_type]?.get(String(p.ref_id));
return {
...p,
title: info?.title ?? null,
subscription: info?.subscription ?? null,
};
});
}
/**
* Enriches prerequisite rows (already carrying `title`) with `completed` —
* whether the given learner has finished the referenced course/unit/lesson.
* "Completed" means: a Certificate exists for a course prereq, or the
* matching UnitReadingProgress/LessonReadingProgress row has status
* "completed" for a unit/lesson prereq.
*/
async function resolvePrerequisiteCompletion(prereqs, { Certificate, UnitReadingProgress, LessonReadingProgress }, userId) {
if (!prereqs?.length) return prereqs ?? [];
const idsByType = { course: new Set(), unit: new Set(), lesson: new Set() };
for (const p of prereqs) {
if (idsByType[p.ref_type]) idsByType[p.ref_type].add(p.ref_id);
}
const completedIds = { course: new Set(), unit: new Set(), lesson: new Set() };
const courseIds = [...idsByType.course];
if (courseIds.length) {
const certs = await Certificate.findAll({
where: { user_id: userId, course_id: courseIds },
attributes: ["course_id"],
});
certs.forEach((c) => completedIds.course.add(String(c.course_id)));
}
const unitIds = [...idsByType.unit];
if (unitIds.length) {
const rows = await UnitReadingProgress.findAll({
where: { user_id: userId, unit_id: unitIds, status: "completed" },
attributes: ["unit_id"],
});
rows.forEach((r) => completedIds.unit.add(String(r.unit_id)));
}
const lessonIds = [...idsByType.lesson];
if (lessonIds.length) {
const rows = await LessonReadingProgress.findAll({
where: { user_id: userId, lesson_id: lessonIds, status: "completed" },
attributes: ["lesson_id"],
});
rows.forEach((r) => completedIds.lesson.add(String(r.lesson_id)));
}
return prereqs.map((p) => ({
...p,
completed: completedIds[p.ref_type]?.has(String(p.ref_id)) ?? false,
}));
}
module.exports = { resolvePrerequisiteTitles, resolvePrerequisiteCompletion };
+44
View File
@@ -0,0 +1,44 @@
"use strict";
const { Op } = require("sequelize");
const onlyDeleted = { deletedAt: { [Op.not]: null } };
/**
* Soft-restore a single record by clearing deletedAt / deletedBy.
* Returns the record on success, null if not found.
*
* @param {Model} Model - Sequelize model
* @param {object} where - Where clause (must include onlyDeleted or equivalent)
* @param {*} restoredBy - User ID stamped onto updatedBy
* @param {object} t - Sequelize transaction
*/
async function restoreOne(Model, where, restoredBy, t) {
const record = await Model.findOne({ where, paranoid: false });
if (!record) return null;
await record.restore();
await record.update({ updatedBy: restoredBy, deletedBy: null })
return record;
}
/**
* Soft-restore many records by their primary key column.
* Returns the count of restored records.
*
* @param {Model} Model - Sequelize model
* @param {string} pkColumn - Primary key column name (e.g. "course_id")
* @param {Array} ids - Array of primary key values to restore
* @param {*} restoredBy - User ID stamped onto updatedBy
* @param {object} t - Sequelize transaction
*/
async function restoreMany(Model, pkColumn, ids, restoredBy, t) {
const [count] = await Model.update(
{ deletedAt: null, deletedBy: null, updatedBy: restoredBy ?? null },
{ where: { [pkColumn]: ids, ...onlyDeleted }, transaction: t, paranoid: false }
);
return count;
}
module.exports = { restoreOne, restoreMany };
@@ -0,0 +1,63 @@
"use strict";
/***********************************************************************************************************************************************************************
* File Name: taskPrerequisites.util.js
* Type of Program: Utility
* Description: Cycle detection for the explicit Task ↔ Task prerequisite graph
* (task_prerequisites junction table). A task's prerequisite set is
* only meaningful if the graph stays a DAG — this checks whether
* persisting a proposed edge set would introduce a cycle.
*
* Author: Kenneth Obsequio (@lash0000)
* Date Created: Jul. 17, 2026
***********************************************************************************************************************************************************************/
const { TaskPrerequisite } = require("../../models/task/task.mdl");
/**
* Would setting `taskId`'s prerequisites to `newPrereqIds` introduce a cycle?
*
* Loads every existing task_prerequisites edge for the task list, overlays the
* proposed edges for `taskId` (replacing whatever it currently points to), then
* DFS from `taskId` looking for a path back to itself.
*/
async function wouldCreateCycle(taskId, newPrereqIds, taskListId, transaction) {
const { Task } = require("../../models/task/task.mdl");
const siblingTasks = await Task.findAll({
where: { task_list_id: taskListId },
attributes: ["task_id"],
transaction,
});
const siblingIds = siblingTasks.map((t) => t.task_id);
const existingEdges = await TaskPrerequisite.findAll({
where: { task_id: siblingIds },
attributes: ["task_id", "prerequisite_task_id"],
transaction,
});
// adjacency: task_id -> Set(prerequisite_task_id) ("depends on")
const adjacency = new Map();
for (const { task_id, prerequisite_task_id } of existingEdges) {
if (task_id === taskId) continue; // overlay taskId's edges with the proposed set below
if (!adjacency.has(task_id)) adjacency.set(task_id, new Set());
adjacency.get(task_id).add(prerequisite_task_id);
}
adjacency.set(taskId, new Set(newPrereqIds));
// DFS from taskId looking for a path back to taskId
const visited = new Set();
const stack = [...adjacency.get(taskId)];
while (stack.length) {
const current = stack.pop();
if (current === taskId) return true;
if (visited.has(current)) continue;
visited.add(current);
for (const next of adjacency.get(current) ?? []) stack.push(next);
}
return false;
}
module.exports = { wouldCreateCycle };
+53
View File
@@ -0,0 +1,53 @@
/***********************************************************************************************************************************************************************
* File Name: datetime.util.js
* Type of Program: Utility
* Description: Pure date/time formatting helpers for backend use (emails, crons, notifications).
*
* All functions accept an optional options object: { timezone, locale }
* timezone — 'UTC' (default) | 'local' (server's local timezone)
* locale — BCP 47 tag, defaults to 'en-US'
*
* UTC is the default because emails and cron output must be unambiguous regardless
* of where the server runs. Pass { timezone: 'local' } only when displaying times
* relative to the server's configured locale (e.g. admin dashboards, server logs).
***********************************************************************************************************************************************************************/
function tzOpt(timezone) {
return timezone === 'local' ? {} : { timeZone: 'UTC' };
}
function loc(locale) {
return locale ?? 'en-US';
}
/** "June 27, 2026" */
function fmtDate(value, { timezone = 'UTC', locale } = {}) {
if (!value) return '—';
return new Date(value).toLocaleDateString(loc(locale), {
month: 'long', day: 'numeric', year: 'numeric',
...tzOpt(timezone),
});
}
/** "June 27, 2026, 3:45 PM UTC" */
function fmtDateTime(value, { timezone = 'UTC', locale } = {}) {
if (!value) return '—';
return new Date(value).toLocaleString(loc(locale), {
month: 'long', day: 'numeric', year: 'numeric',
hour: 'numeric', minute: '2-digit',
timeZoneName: 'short',
...tzOpt(timezone),
});
}
/** "3:45 PM UTC" */
function fmtTime(value, { timezone = 'UTC', locale } = {}) {
if (!value) return '—';
return new Date(value).toLocaleTimeString(loc(locale), {
hour: 'numeric', minute: '2-digit',
timeZoneName: 'short',
...tzOpt(timezone),
});
}
module.exports = { fmtDate, fmtDateTime, fmtTime };
+98
View File
@@ -0,0 +1,98 @@
/**
* Every user belongs to exactly one group at all times — a real group, or the
* NOGRP placeholder if they haven't been assigned one yet. NOGRP is a normal
* row-backed group (not a computed "users with no group" view), so every
* writer that moves a user in or out of a real group must also keep their
* NOGRP row in sync. This util is the single place that invariant is
* enforced — see project memory "NOGRP dual-membership fix" (2026-07-15) for
* the bug this replaced (users silently stuck in both NOGRP and a real group).
*/
const { mdl_UserGroups, mdl_UserGroupMembers } = require('../models/users/user_groups.mdl');
const NOGRP_CODE = 'NOGRP';
async function getDefaultGroupId() {
const nogrp = await mdl_UserGroups.findOne({ where: { group_code: NOGRP_CODE, is_active: true }, attributes: ['group_id'] });
return nogrp ? nogrp.group_id : null;
}
/** Registration fallback: enroll a brand-new user into NOGRP. */
async function enrollDefaultGroup(user_id, { transaction, createdBy = null } = {}) {
const group_id = await getDefaultGroupId();
if (!group_id) return null;
return mdl_UserGroupMembers.create({ group_id, user_id, createdBy }, { transaction });
}
/**
* Call after adding user_ids to a real group: drops their stale NOGRP row so
* they don't sit in both simultaneously. No-op if group_id being added to IS
* NOGRP itself.
*/
async function dropDefaultGroupMembership(user_ids, group_id, { updatedBy = null } = {}) {
const nogrpId = await getDefaultGroupId();
if (!nogrpId || Number(nogrpId) === Number(group_id)) return;
await mdl_UserGroupMembers.update(
{ deletedBy: updatedBy },
{ where: { user_id: user_ids, group_id: nogrpId } }
);
await mdl_UserGroupMembers.destroy({ where: { user_id: user_ids, group_id: nogrpId } });
}
/**
* Call after removing user_ids from a group: re-enrolls into NOGRP whichever
* of those users are left with zero active group memberships.
*/
async function reconcileDefaultGroup(user_ids, { createdBy = null } = {}) {
const nogrpId = await getDefaultGroupId();
if (!nogrpId) return;
const remaining = await mdl_UserGroupMembers.findAll({
where: { user_id: user_ids }, attributes: ['user_id'], group: ['user_id'],
});
const stillGrouped = new Set(remaining.map((m) => m.user_id));
const orphaned = user_ids.filter((id) => !stillGrouped.has(id));
if (!orphaned.length) return;
await mdl_UserGroupMembers.restore({ where: { user_id: orphaned, group_id: nogrpId } });
await mdl_UserGroupMembers.update(
{ deletedBy: null, updatedBy: createdBy },
{ where: { user_id: orphaned, group_id: nogrpId }, paranoid: false }
);
await mdl_UserGroupMembers.bulkCreate(
orphaned.map((user_id) => ({ user_id, group_id: nogrpId, createdBy })),
{ ignoreDuplicates: true }
);
}
/**
* Invite-link login: if user_id is currently sitting in NOGRP, move them into
* the group identified by group_code. Never reassigns someone already parked
* in a real (non-NOGRP) group — an invite link used post-login only fills in
* an ungrouped user's group, it doesn't override an existing one. No-op if
* group_code doesn't resolve to an active group.
*/
async function switchFromNogrpByCode(user_id, group_code, { updatedBy = null } = {}) {
if (!group_code) return null;
const group = await mdl_UserGroups.findOne({
where: { group_code: group_code.toUpperCase().trim(), is_active: true },
});
if (!group) return null;
const membership = await mdl_UserGroupMembers.findOne({
where: { user_id },
include: [{ model: mdl_UserGroups, attributes: ['group_code'] }],
});
if (membership) {
if (membership.UserGroup?.group_code !== NOGRP_CODE) return null; // already in a real group — leave it alone
if (Number(membership.group_id) === Number(group.group_id)) return group; // already in this exact group
}
await mdl_UserGroupMembers.create({ group_id: group.group_id, user_id, createdBy: updatedBy });
await dropDefaultGroupMembership([user_id], group.group_id, { updatedBy });
return group;
}
module.exports = { NOGRP_CODE, getDefaultGroupId, enrollDefaultGroup, dropDefaultGroupMembership, reconcileDefaultGroup, switchFromNogrpByCode };
+161
View File
@@ -0,0 +1,161 @@
// utils/duration.util.js
const AVG_WORDS_PER_MINUTE = 200;
function stripHtml(html) {
// Simple regex strip — no extra dependency needed
return (html ?? "").replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();
}
/**
* Estimate seconds for a single lesson block
* Block shape: { id, type, content }, where content.duration_seconds holds
* the probed media length for video/audio blocks (see AssetPickerSheet
* consumers — VideoBlock/AudioBlock/TextVideoBlock save it on select).
*/
function estimateBlockDuration(block) {
const mediaDuration = Math.round(Number(block.content?.duration_seconds) || 0);
// Derive word count from HTML content on the fly
const getWordCount = (html) => {
const text = stripHtml(html);
return text ? text.split(" ").filter(Boolean).length : 0;
};
const readingSecs = (html) =>
Math.ceil((getWordCount(html) / AVG_WORDS_PER_MINUTE) * 60);
switch (block.type) {
case "text":
case "markdown":
case "document":
return readingSecs(block.content?.body);
case "code":
return readingSecs(block.content?.code);
case "image":
return 60;
case "video":
case "audio":
return mediaDuration;
case "text-image":
case "text_image":
return readingSecs(block.content?.body) + 60;
case "text-video":
case "text_video":
return readingSecs(block.content?.body) + mediaDuration;
default:
return 0;
}
}
/**
* Recompute and persist a unit's duration_seconds from the sum of its
* non-archived lessons. Used both by recomputeDurations() (a lesson's
* content changed) and directly by archive/restore/delete handlers (a
* lesson was added to or removed from the "counts toward duration" set
* without any of its content changing).
*/
async function recomputeUnitDuration(unitId) {
const Lesson = require("../models/courses/lessons.mdl");
const Unit = require("../models/courses/units.mdl");
const [unitResult] = await Lesson.sequelize.query(`
SELECT COALESCE(SUM(l.duration_seconds), 0) AS total
FROM lessons l
JOIN unit_lessons ul ON ul.lesson_id = l.lesson_id
WHERE ul.unit_id = :unitId AND l."deletedAt" IS NULL
`, { replacements: { unitId }, type: Lesson.sequelize.QueryTypes.SELECT });
await Unit.update({ duration_seconds: unitResult.total }, { where: { unit_id: unitId } });
}
/**
* Recompute and persist a course's duration_seconds from the sum of its
* non-archived units. See recomputeUnitDuration() above for why this is
* split out on its own instead of only living inside recomputeDurations().
*/
async function recomputeCourseDuration(courseId) {
const Unit = require("../models/courses/units.mdl");
const { Course } = require("../models/courses/courses.mdl");
const [courseResult] = await Unit.sequelize.query(`
SELECT COALESCE(SUM(u.duration_seconds), 0) AS total
FROM units u
JOIN course_units cu ON cu.unit_id = u.unit_id
WHERE cu.course_id = :courseId AND u."deletedAt" IS NULL
`, { replacements: { courseId }, type: Unit.sequelize.QueryTypes.SELECT });
await Course.update({ duration_seconds: courseResult.total }, { where: { course_id: courseId } });
}
/**
* Recompute and persist duration_seconds up the chain:
* blocks → lesson → every attached unit → every course those units are attached to.
* A lesson may live in many units, and a unit in many courses, so all parents refresh.
*
* `blocksOverride` lets a caller that just wrote the page (e.g. upsertLessonPage,
* which already has the upserted row in hand) skip the re-read — avoids relying on
* read-after-write visibility of the just-committed upsert.
*/
async function recomputeDurations(lessonId, blocksOverride = null) {
const Lesson = require("../models/courses/lessons.mdl");
const LessonPage = require("../models/courses/lesson_page.mdl");
const UnitLesson = require("../models/courses/unit_lessons.mdl");
const CourseUnit = require("../models/courses/course_units.mdl");
// 1. Lesson duration from blocks
let blocks = blocksOverride;
if (!blocks) {
const page = await LessonPage.findOne({ where: { lesson_id: lessonId } });
blocks = page?.blocks ?? [];
}
const lessonSecs = blocks.reduce(
(sum, block) => sum + estimateBlockDuration(block), 0
);
// Guard against NaN/fractional values before DB write (duration_seconds is INTEGER)
const safeLessonSecs = isNaN(lessonSecs) ? 0 : Math.round(lessonSecs);
await Lesson.update({ duration_seconds: safeLessonSecs }, { where: { lesson_id: lessonId } });
// 2. Every unit that contains this lesson
const unitLinks = await UnitLesson.findAll({ where: { lesson_id: lessonId }, attributes: ["unit_id"] });
const unitIds = [...new Set(unitLinks.map((l) => String(l.unit_id)))];
for (const unitId of unitIds) await recomputeUnitDuration(unitId);
// 3. Every course that contains those units
if (unitIds.length) {
const courseLinks = await CourseUnit.findAll({ where: { unit_id: unitIds }, attributes: ["course_id"] });
const courseIds = [...new Set(courseLinks.map((l) => String(l.course_id)))];
for (const courseId of courseIds) await recomputeCourseDuration(courseId);
}
}
/**
* Format seconds → human readable: "1 hr 10 mins", "45 mins", "30 secs"
*/
function formatDuration(seconds) {
if (!seconds) return "0 mins";
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
const s = seconds % 60;
const parts = [];
if (h) parts.push(`${h} hour${h !== 1 ? "s" : ""}`);
if (m) parts.push(`${m} minute${m !== 1 ? "s" : ""}`);
if (!h && !m && s) parts.push(`${s} second${s !== 1 ? "s" : ""}`);
return parts.join(" ");
}
module.exports = {
estimateBlockDuration,
recomputeDurations,
recomputeUnitDuration,
recomputeCourseDuration,
formatDuration,
};
+94
View File
@@ -0,0 +1,94 @@
const { Sequelize } = require('sequelize')
/**
* Strips a key from every element in a JSONB array using PostgreSQL's
* jsonb_agg + #- operator in a subquery.
*
* @param {string} column - JSONB column e.g. "personal_info"
* @param {string} arrayField - array field name e.g. "addresses"
* @param {string[]} keys - keys to strip from each array element e.g. ["street", "zip"]
* @returns {string} SQL fragment
*/
function buildArrayStrip(column, arrayField, keys) {
const keyRemovals = keys.reduce(
(acc, key) => `(${acc} #- '{${key}}')`,
"elem"
);
return `(
SELECT jsonb_agg(${keyRemovals})
FROM jsonb_array_elements("${column}"->'${arrayField}') AS elem
)`;
}
/**
* Builds a Sequelize literal that strips JSONB paths at the DB level.
* Supports:
* - nested keys: "personal_info.name.given_name"
* - array item keys: "personal_info.addresses[].street"
*
* @param {string} column - JSONB column name e.g. "personal_info"
* @param {string[]} excludePaths - dot-notation paths
* @returns {Array|null} Sequelize literal attribute tuple
*/
function excludeJsonbPaths(column, excludePaths = []) {
const nestedPaths = excludePaths.filter(
(p) => p.startsWith(`${column}.`) && !p.includes("[]")
);
const arrayPaths = excludePaths.filter(
(p) => p.startsWith(`${column}.`) && p.includes("[]")
);
// ─── Group array paths ──────────────────────────────────────────────────────
// Separate bare array strips → "personal_info.addresses[]"
// from key-level strips → "personal_info.addresses[].city"
const bareArrayStrips = new Set(); // fields to remove entirely e.g. "addresses"
const arrayGroups = {}; // fields to partially strip e.g. { addresses: ["city"] }
for (const path of arrayPaths) {
const stripped = path.replace(`${column}.`, ""); // "addresses[].city" or "addresses[]"
if (stripped.endsWith("[]")) {
// ─── Bare array strip — remove the whole field ─────────────────────────
const arrayField = stripped.replace("[]", "");
bareArrayStrips.add(arrayField);
} else {
// ─── Key-level strip — remove specific keys inside each element ────────
const [arrayPart, key] = stripped.split("[]."); // ["addresses", "city"]
const arrayField = arrayPart.replace("[]", "");
// Skip if the whole array is already being stripped entirely
if (bareArrayStrips.has(arrayField)) continue;
if (!arrayGroups[arrayField]) arrayGroups[arrayField] = [];
arrayGroups[arrayField].push(key);
}
}
if (!nestedPaths.length && !bareArrayStrips.size && !Object.keys(arrayGroups).length)
return null;
let literal = `"${column}"`;
// ─── 1. Strip nested keys ───────────────────────────────────────────────────
for (const path of nestedPaths) {
const keys = path.replace(`${column}.`, "").split(".");
literal = `(${literal} #- '{${keys.join(",")}}')`;
}
// ─── 2. Strip entire array fields ──────────────────────────────────────────
for (const arrayField of bareArrayStrips) {
literal = `(${literal} #- '{${arrayField}}')`;
}
// ─── 3. Strip specific keys inside array elements ──────────────────────────
for (const [arrayField, keys] of Object.entries(arrayGroups)) {
const arrayStrip = buildArrayStrip(column, arrayField, keys);
literal = `jsonb_set(${literal}, '{${arrayField}}', COALESCE(${arrayStrip}, '[]'))`;
}
return [Sequelize.literal(literal), column];
}
module.exports = { excludeJsonbPaths };
+129
View File
@@ -0,0 +1,129 @@
const { Op } = require("sequelize");
const sequelize = require("../config/db.config");
const Sequelize = require("sequelize");
const R = require("../utils/response.util"); // adjust path as needed
const mdl_TierCategories = require("../models/tiers/tier_categories.mdl");
const auditByFields = ["createdBy", "updatedBy", "deletedBy"];
const getFieldValues = (Model, logTag, options = {}) => async (req, res) => {
const {
blockedFields = [],
extraDateFields = [],
allowJsonb = false,
paranoid = true,
selfJoin = false, // for users auditing users
} = options;
try {
const { field } = req.query;
if (!field) return R.error(res, "Field is required.", 400);
const dateFields = ["createdAt", "updatedAt", "deletedAt", ...extraDateFields];
// ─── Non-JSONB path ───────────────────────────────────────────────────
if (!field.includes(".")) {
const allowedFields = blockedFields.length
? Object.keys(Model.rawAttributes).filter((f) => !blockedFields.includes(f))
: Object.keys(Model.rawAttributes).filter((f) => Model.rawAttributes[f].filterable === true);
if (!allowedFields.includes(field) && !dateFields.includes(field))
return R.error(res, "Invalid or restricted field.", 400);
// ─── ENUM / BOOLEAN fields — return the canonical value set, not a DISTINCT
// scan of current rows. A DISTINCT query silently omits valid values
// that just don't happen to exist yet (e.g. is_banned when nobody is
// currently banned), which produces an incomplete filter picklist.
const rawType = Model.rawAttributes[field]?.type;
const typeKey = rawType?.constructor?.key || rawType?.key;
if (typeKey === "ENUM") {
return R.success(res, "Field values retrieved.", rawType.values ?? []);
}
if (typeKey === "BOOLEAN") {
return R.success(res, "Field values retrieved.", ["true", "false"]);
}
// ─── Tier gate fields — same reasoning as ENUM above: the picklist should
// reflect every tier category that exists, not just whichever ones a
// DISTINCT scan happens to find already assigned to a row.
if (field === "subscription") {
const categories = await mdl_TierCategories.findAll({
where: { is_active: true },
order: [["rank", "ASC"]],
raw: true,
});
return R.success(res, "Field values retrieved.", categories.map((c) => ({ value: c.slug, label: c.name })));
}
if (auditByFields.includes(field)) {
// Filtering must match the audit column's real (bigint) id — returning
// just the display name here previously made buildWhere() compare a
// name string against the raw id column via a text cast, which can
// never match. Carry both: `value` (id) is what gets filtered on,
// `label` (full_name) is what the filter sheet displays.
const tableName = Model.getTableName();
const [rows] = selfJoin
? await sequelize.query(`
SELECT DISTINCT u1."${field}" AS value, u2."personal_info"->'name'->>'full_name' AS label
FROM "${tableName}" u1
JOIN "${tableName}" u2 ON u2.user_id = u1."${field}"
WHERE u1."${field}" IS NOT NULL
AND u2."personal_info"->'name'->>'full_name' IS NOT NULL
ORDER BY label ASC
`)
: await sequelize.query(`
SELECT DISTINCT t."${field}" AS value, u."personal_info"->'name'->>'full_name' AS label
FROM "${tableName}" t
JOIN users u ON u.user_id = t."${field}"
WHERE t."${field}" IS NOT NULL
AND u."personal_info"->'name'->>'full_name' IS NOT NULL
ORDER BY label ASC
`);
return R.success(res, "Field values retrieved.", rows.filter((r) => r.label));
}
if (dateFields.includes(field)) {
const results = await Model.findAll({
attributes: [[Sequelize.fn("DISTINCT", Sequelize.fn("DATE", Sequelize.col(field))), "value"]],
where: { [field]: { [Op.ne]: null } },
order: [[Sequelize.fn("DATE", Sequelize.col(field)), "DESC"]],
paranoid,
raw: true,
});
return R.success(res, "Field values retrieved.", results.map((r) => r.value).filter(Boolean));
}
const results = await Model.findAll({
attributes: [[Sequelize.fn("DISTINCT", Sequelize.col(field)), "value"]],
where: { [field]: { [Op.ne]: null } },
paranoid,
raw: true,
});
return R.success(res, "Field values retrieved.", results.map((r) => r.value).filter(Boolean).sort());
}
// ─── JSONB dot-notation path ──────────────────────────────────────────
if (!allowJsonb)
return R.error(res, "JSONB fields are not supported.", 400);
const [column, ...pathParts] = field.split(".");
const keys = [...pathParts];
const lastKey = keys.pop();
const jsonbPath = keys.length
? `"${column}"->${keys.map((k) => `'${k}'`).join("->")}->>'${lastKey}'`
: `"${column}"->>'${lastKey}'`;
const results = await Model.findAll({
attributes: [[Sequelize.literal(`DISTINCT ${jsonbPath}`), "value"]],
where: Sequelize.literal(`${jsonbPath} IS NOT NULL`),
raw: true,
});
return R.success(res, "Field values retrieved.", results.map((r) => r.value).filter(Boolean).sort());
} catch (err) {
console.error(`[${logTag}][GET FIELD VALUES]`, err);
return R.error(res, "Could not retrieve field values.", 500);
}
};
module.exports = { getFieldValues };
+94
View File
@@ -0,0 +1,94 @@
/***********************************************************************************************************************************************************************
* File Name: google_oidc.util.js
* Type of Program: Utility
* Description: Manual Google OIDC primitives — no Passport.
* Provides state/nonce generation, PKCE (S256), authorization URL construction,
* authorization code exchange, and ID token verification via google-auth-library.
*
* OIDC flow summary:
* 1. googleRedirect → generateState + generateNonce + generatePKCE → buildAuthUrl → redirect
* 2. googleCallback → verify state cookie → exchangeCode → verifyIdToken → create/find user
*
* Security properties:
* - state : anti-CSRF; verified against signed httpOnly cookie
* - nonce : anti-replay; embedded in ID token by Google and checked here
* - PKCE S256 : prevents auth code interception even if code leaks
*
* Author: Kenneth Obsequio (@lash0000)
* Date Created: Jun. 21, 2026
***********************************************************************************************************************************************************************/
'use strict';
const crypto = require('crypto');
const { OAuth2Client } = require('google-auth-library');
const axios = require('axios');
const GOOGLE_AUTH_URL = 'https://accounts.google.com/o/oauth2/v2/auth';
const GOOGLE_TOKEN_URL = 'https://oauth2.googleapis.com/token';
// Lazily initialised so the module can be required before env is loaded.
let _client;
const getClient = () => {
if (!_client) _client = new OAuth2Client(process.env.GOOGLE_CLIENT_ID);
return _client;
};
// ── Generators ─────────────────────────────────────────────────────────────────
const generateState = () => crypto.randomBytes(32).toString('hex');
const generateNonce = () => crypto.randomBytes(32).toString('hex');
const generatePKCE = () => {
const codeVerifier = crypto.randomBytes(32).toString('base64url');
const codeChallenge = crypto.createHash('sha256').update(codeVerifier).digest('base64url');
return { codeVerifier, codeChallenge };
};
// ── Auth URL ───────────────────────────────────────────────────────────────────
const buildAuthUrl = (state, nonce, codeChallenge) => {
const params = new URLSearchParams({
client_id: process.env.GOOGLE_CLIENT_ID,
redirect_uri: process.env.GOOGLE_CALLBACK_URL,
response_type: 'code',
scope: 'openid email profile',
state,
nonce,
code_challenge: codeChallenge,
code_challenge_method: 'S256',
access_type: 'offline',
prompt: 'select_account',
});
return `${GOOGLE_AUTH_URL}?${params.toString()}`;
};
// ── Code exchange ──────────────────────────────────────────────────────────────
const exchangeCode = async (code, codeVerifier) => {
const { data } = await axios.post(
GOOGLE_TOKEN_URL,
new URLSearchParams({
code,
client_id: process.env.GOOGLE_CLIENT_ID,
client_secret: process.env.GOOGLE_CLIENT_SECRET,
redirect_uri: process.env.GOOGLE_CALLBACK_URL,
grant_type: 'authorization_code',
code_verifier: codeVerifier,
}).toString(),
{ headers: { 'Content-Type': 'application/x-www-form-urlencoded' } },
);
return data; // { access_token, id_token, expires_in, token_type, ... }
};
// ── ID token verification ──────────────────────────────────────────────────────
const verifyIdToken = async (idToken, expectedNonce) => {
const ticket = await getClient().verifyIdToken({
idToken,
audience: process.env.GOOGLE_CLIENT_ID,
});
const payload = ticket.getPayload();
// Verify nonce to prevent token replay attacks.
if (payload.nonce !== expectedNonce) throw new Error('Nonce mismatch');
return payload; // { sub, email, given_name, family_name, name, picture, ... }
};
module.exports = { generateState, generateNonce, generatePKCE, buildAuthUrl, exchangeCode, verifyIdToken };
+26
View File
@@ -0,0 +1,26 @@
const mdl_UserActivity = require('../models/users/user_activity.mdl');
/**
* Fire-and-forget activity logger. Never throws — failures are console-logged only.
*
* @param {number} userId
* @param {string} action — e.g. 'login', 'submit_task', 'deactivate_user'
* @param {Object} [opts]
* @param {string} [opts.entityType] — e.g. 'user', 'task', 'lesson'
* @param {number} [opts.entityId]
* @param {number} [opts.sessionId]
* @param {Object} [opts.details] — free-form JSONB context
*/
function logActivity(userId, action, { entityType = null, entityId = null, sessionId = null, details = null } = {}) {
const numericId = entityId !== null ? Number(entityId) : null;
mdl_UserActivity.create({
user_id: userId,
action,
entity_type: entityType,
entity_id: Number.isFinite(numericId) ? numericId : null,
session_id: sessionId,
details,
}).catch((err) => console.error('[USER_ACTIVITY] Failed to log:', action, err.message));
}
module.exports = logActivity;
+174
View File
@@ -0,0 +1,174 @@
// utils/modelToAttributes.js
const { DataTypes } = require("sequelize");
/**
* Maps Sequelize DataType to a simple UI type string.
*/
function resolveType(dataType) {
if (!dataType) return "text";
const type = dataType.constructor?.key || dataType.key || "";
if (["BIGINT", "INTEGER", "FLOAT", "DOUBLE", "DECIMAL"].includes(type)) return "number";
if (["DATE", "DATEONLY"].includes(type)) return "date";
if (["BOOLEAN"].includes(type)) return "enum";
if (["ENUM"].includes(type)) return "enum";
if (["JSONB", "JSON"].includes(type)) return "jsonb";
return "text";
}
/**
* Resolves options (e.g. enum choices) from a Sequelize field definition.
*/
function resolveOptions(dataType) {
if (!dataType) return "text";
const type = dataType.constructor?.key || dataType.key || "";
if (type === "ENUM") {
return { choices: dataType.values ?? [] };
}
if (type === "BOOLEAN") {
return { choices: ["true", "false"] };
}
return {};
}
/**
* Converts a camelCase or snake_case field name to a readable label.
*/
function toLabel(field) {
return field
.replace(/_/g, " ")
.replace(/([a-z])([A-Z])/g, "$1 $2")
.replace(/\b\w/g, (c) => c.toUpperCase());
}
/**
* Flattens JSONB field paths from a schema definition.
*
* @param {Object} jsonbSchema - e.g. { name: { given_name, full_name }, date_of_birth }
* @param {string} prefix - e.g. "personal_info"
* @returns {Array} flat attribute entries for each leaf path
*/
function flattenJsonb(jsonbSchema = {}, prefix = "", exclude = []) {
const result = [];
for (const [key, value] of Object.entries(jsonbSchema)) {
const path = prefix ? `${prefix}.${key}` : key;
if (exclude.includes(path)) continue;
// Nested object (no `type` key = it's a group, not a leaf)
if (value && typeof value === "object" && !value.type) {
result.push(...flattenJsonb(value, path, exclude));
} else {
result.push({
name: value?.label || toLabel(key), // <-- prefer label
type: value?.type ?? "text",
field: path,
order: value?.order ?? Infinity, // ← carry order from schema
hidden: value?.hidden ?? false, // ← carry hidden flag
filterable: value.filterable ?? true,
options: {},
});
}
}
return result;
}
/**
* Generates an attributes array from a Sequelize model + optional JSONB schema map.
*
* @param {Object} model - Sequelize model (e.g. mdl_Users)
* @param {Object} jsonbSchemas - map of JSONB field names to their schema definition
* e.g. { personal_info: { name: { full_name: "text", given_name: "text" }, date_of_birth: "date" } }
* @param {string[]} exclude - field names to exclude (e.g. ["password", "otp_code"])
* @returns {Array} attributes array
*/
function modelToAttributes(model, { jsonbSchemas = {}, exclude = [], timestampLabels = {}, context = "" } = {}) {
const rawAttrs = model.rawAttributes || model.tableAttributes;
const attributes = [];
const defaultTimestampLabels = {
createdAt: "Created",
modifiedAt: "Modified",
updatedAt: "Modified",
deletedAt: "Deleted",
createdBy: "Created By",
updatedBy: "Modified By",
deletedBy: "Deleted By",
...timestampLabels,
};
// Audit fields excluded from normal loop — handled separately at the end
const auditFields = [
'createdAt', 'updatedAt', 'modifiedAt',
'deletedAt',
'createdBy', 'updatedBy', 'deletedBy',
];
// Ordered audit sequence
const auditSequence = [
{ field: "updatedAt", type: "date", hiddenOnList: false, hiddenOnArchived: true },
{ field: "modifiedAt", type: "date", hiddenOnList: false, hiddenOnArchived: true },
{ field: "updatedBy", type: "text", hiddenOnList: false, hiddenOnArchived: true },
{ field: "createdAt", type: "date", hiddenOnList: false, hiddenOnArchived: true },
{ field: "createdBy", type: "text", hiddenOnList: false, hiddenOnArchived: true },
{ field: "deletedAt", type: "date", hiddenOnList: true, hiddenOnArchived: false },
{ field: "deletedBy", type: "text", hiddenOnList: true, hiddenOnArchived: false },
];
// ── Normal fields (excluding audit) ─────────────────────────────────────────
for (const [field, def] of Object.entries(rawAttrs)) {
if (exclude.includes(field)) continue;
if (auditFields.includes(field)) continue; // skip audit — added later in order
const dataType = def.type;
const type = resolveType(def.type); // ← pass only the type
if (type === "jsonb" && jsonbSchemas[field]) {
attributes.push(...flattenJsonb(jsonbSchemas[field], field, exclude));
continue;
}
if (type === "jsonb") continue;
attributes.push({
name: defaultTimestampLabels[field] ?? def.label ?? toLabel(field),
type,
field,
order: def.order ?? Infinity,
hidden: def.hidden ?? false,
filterable: def.filterable ?? true,
options: resolveOptions(def.type)
});
}
// ── Audit fields in correct sequence ────────────────────────────────────────
for (const { field, type, order, hiddenOnList, hiddenOnArchived, filterable } of auditSequence) {
if (exclude.includes(field)) continue;
if (!rawAttrs[field]) continue; // skip if field doesn't exist on model
const isArchived = context === "archived";
attributes.push({
name: defaultTimestampLabels[field],
type,
field,
order,
hidden: isArchived ? hiddenOnArchived : hiddenOnList,
options: resolveOptions(rawAttrs[field]?.type),
filterable: filterable ?? true,
});
}
// ── Sort by order — DO NOT strip order here, paginate.util does it ───────────
return attributes.sort((a, b) => (a.order ?? Infinity) - (b.order ?? Infinity));
}
module.exports = { modelToAttributes };
@@ -0,0 +1,25 @@
/***********************************************************************************************************************************************************************
* File Name : notificationVisibility.util.js
* Type : Utility
* Description : Shared visibility-window filter for AdminNotification/
* UserNotification rows carrying a denormalized start_date/
* end_date (copied from NotificationBroadcast at send time —
* see notificationBroadcasts.controller.js#sendBroadcast).
* Non-announcement notifications have both columns null, so
* this filter is a no-op for them.
*
* Author: Kenneth Obsequio (@lash0000)
* Date Created: Jul. 11, 2026
***********************************************************************************************************************************************************************/
const { Op } = require('sequelize');
function notInFutureOrExpired(now = new Date()) {
return {
[Op.and]: [
{ [Op.or]: [{ start_date: null }, { start_date: { [Op.lte]: now } }] },
{ [Op.or]: [{ end_date: null }, { end_date: { [Op.gte]: now } }] },
],
};
}
module.exports = { notInFutureOrExpired };
+44
View File
@@ -0,0 +1,44 @@
/***********************************************************************************************************************************************************************
* File Name: otp.util.js
* Type of Program: Utility
* Description: One-Time Password (OTP) generation and validation helpers.
* - generateOTP() → 6-digit numeric string
* - getOTPExpiry() → Date object N minutes from now
* - isOTPExpired() → boolean check on the stored expiry
* Author: rgrgogu
* Date Created: Oct. 6, 2025
***********************************************************************************************************************************************************************
* HOW TO USE:
* const { generateOTP, getOTPExpiry, isOTPExpired } = require('../utils/otp.util');
* user.otp_code = generateOTP();
* user.otp_expires_at = getOTPExpiry();
***********************************************************************************************************************************************************************/
const crypto = require('crypto');
/**
* Generates a cryptographically secure 6-digit OTP.
* @returns {string} e.g. "048291"
*/
const generateOTP = () => {
const bytes = crypto.randomBytes(3); // 3 bytes = 0–16777215
const num = bytes.readUIntBE(0, 3) % 1_000_000; // force to 0–999999
return num.toString().padStart(6, '0');
};
/**
* Returns a Date object N minutes in the future.
* @param {number} [minutes=10]
* @returns {Date}
*/
const getOTPExpiry = (minutes = Number(process.env.OTP_EXPIRY_MINUTES) || 10) => {
return new Date(Date.now() + minutes * 60 * 1000);
};
/**
* Checks whether the stored OTP has expired.
* @param {Date|string} expiresAt
* @returns {boolean}
*/
const isOTPExpired = (expiresAt) => !expiresAt || new Date() > new Date(expiresAt);
module.exports = { generateOTP, getOTPExpiry, isOTPExpired };
+207
View File
@@ -0,0 +1,207 @@
// utils/paginate.util.js
const { Sequelize, Op } = require('sequelize');
const { modelToAttributes } = require('./modelToAttributes.util');
const { excludeJsonbPaths } = require('./excludeJSONBPaths.util');
const { buildQuery } = require('./buildQuery.util');
const PAGE_START = 1;
const PAGE_SIZE = 10;
const MAX_LIMIT = 1000;
function safeParseJSON(value, fallback = []) {
try {
const parsed = JSON.parse(value);
return Array.isArray(parsed) ? parsed : fallback;
} catch {
return fallback;
}
}
/**
* Generates audit subquery attributes for createdBy, updatedBy, deletedBy
*
* @param {Object} mdl_Users - Users model
* @param {string} parentAlias - Sequelize model alias e.g. 'User', 'UserGroup'
* @returns {Array} - Sequelize attribute include array
*/
function auditInclude(mdl_Users, parentAlias = 'User') {
const tableName = mdl_Users.getTableName();
// Falls back to email when full_name hasn't been filled in (e.g. a
// freshly self-registered account) — better than surfacing the raw
// numeric user_id, which is meaningless in the admin UI.
const fullNameSubquery = (foreignKey) =>
Sequelize.literal(`(
SELECT COALESCE(NULLIF((u."personal_info"->>'name')::jsonb->>'full_name', ''), u."email")
FROM "${tableName}" AS u
WHERE u."user_id" = "${parentAlias}"."${foreignKey}"
LIMIT 1
)`);
return {
attributes: [
[fullNameSubquery('createdBy'), 'createdByName'],
[fullNameSubquery('updatedBy'), 'updatedByName'],
[fullNameSubquery('deletedBy'), 'deletedByName'],
],
};
}
const auditIdToName = (row) => {
const map = {
createdBy: 'createdByName',
updatedBy: 'updatedByName',
deletedBy: 'deletedByName',
};
const result = { ...row };
for (const [idField, nameField] of Object.entries(map)) {
if (result[idField] !== null && result[idField] !== undefined) {
result[idField] = result[nameField] ?? result[idField]; // ← use name if available, fallback to id
}
delete result[nameField]; // ← remove the redundant *ByName fields
}
return result;
};
/**
* Reusable paginated findAndCountAll
*
* @param {Object} model - Sequelize model
* @param {Object} req - Express request
* @param {Object} options
* @param {string[]} options.excludeAttributes - fields to exclude
* @param {Object} options.jsonbSchemas - JSONB schema map
* @param {string} options.jsonbColumn - JSONB column name e.g. "personal_info"
* @param {Object} options.findOptions - extra Sequelize options (include, where, etc.)
* @param {Object} options.auditOptions - { mdl_Users, parentAlias } to auto-include audit subqueries
*/
async function paginate(model, req, {
excludeAttributes = [],
jsonbSchemas = {},
jsonbColumn = null,
findOptions = {},
auditOptions = null, // ← { mdl_Users, parentAlias },
computedAttributes = [],
context = "list",
} = {}) {
const page = Math.max(PAGE_START, parseInt(req.query.page, 10) || PAGE_START);
const limit = Math.min(parseInt(req.query.limit, 10) || PAGE_SIZE, MAX_LIMIT);
const offset = (page - PAGE_START) * limit;
const filters = safeParseJSON(req.query.filters);
const sort = safeParseJSON(req.query.sort);
const topLevelExclude = excludeAttributes.filter((f) => !f.includes('.'));
const jsonbExclude = excludeAttributes.filter((f) => f.includes('.'));
const jsonbAttr = jsonbColumn ? excludeJsonbPaths(jsonbColumn, jsonbExclude) : null;
// The stripped jsonbAttr projection is aliased to the same name as the raw
// column (e.g. "personal_info") — without excluding the raw column too, it
// gets selected twice under the same alias, which Postgres/CockroachDB
// accept in a plain SELECT but reject as ambiguous the moment that alias is
// referenced in ORDER BY (e.g. sorting a jsonb-path column).
if (jsonbAttr && jsonbColumn && !topLevelExclude.includes(jsonbColumn)) {
topLevelExclude.push(jsonbColumn);
}
const attributes = modelToAttributes(model, { exclude: excludeAttributes, jsonbSchemas, context });
const ALLOWED_FIELDS = attributes.map((a) => a.field);
const computedFieldKeys = computedAttributes.map((c) => c.key);
const dateFieldKeys = attributes.filter((a) => a.type === 'date').map((a) => a.field);
// Sequelize aliases the main model's table with the model's name by default
// (e.g. `FROM "users" AS "User"`) — needed to qualify Sequelize.col()
// references so they don't collide with same-named columns on joined tables.
const { where, order } = buildQuery(filters, sort, ALLOWED_FIELDS, computedFieldKeys, model.name, dateFieldKeys);
// Build attribute includes: jsonb + audit subqueries + any extra from findOptions
const baseIncludes = jsonbAttr ? [jsonbAttr] : [];
const auditAttrs = auditOptions
? auditInclude(auditOptions.mdl_Users, auditOptions.parentAlias).attributes
: [];
const extraIncludes = findOptions.attributes?.include ?? [];
// ← Convert { key, literal } objects into Sequelize [literal, alias] tuples
const computedIncludes = computedAttributes
.filter((c) => c.literal)
.map((c) => [Sequelize.literal(c.literal), c.key]);
const mergedAttributeIncludes = [
...baseIncludes,
...auditAttrs,
...extraIncludes,
...computedIncludes, // ← now proper tuples
];
const { attributes: _attr, ...restFindOptions } = findOptions;
// Nest rather than shallow-spread — `where` and `restFindOptions.where` can
// both carry an [Op.and] key (the same global Symbol), and spreading two
// objects that share a Symbol key silently drops the first one's value.
const combinedWhere = restFindOptions.where
? { [Op.and]: [where, restFindOptions.where] }
: where;
const { count, rows } = await model.findAndCountAll({
...restFindOptions,
where: combinedWhere,
order,
limit,
offset,
attributes: {
exclude: topLevelExclude,
include: mergedAttributeIncludes,
},
});
const data = rows
.map((row) => row.toJSON?.() ?? row)
.map(auditIdToName)
.map((row) => {
// ← Coerce computed types after toJSON
const result = { ...row };
for (const { key, type } of computedAttributes) {
if (result[key] !== undefined && result[key] !== null) {
if (type === 'number') result[key] = parseInt(result[key], 10);
if (type === 'float') result[key] = parseFloat(result[key]);
}
}
return result;
});
const totalPages = Math.ceil(count / limit);
// ← Append computed metadata
const computedMeta = computedAttributes.map(({ key, label, type, order: ord, filterable, hidden }) => ({
name: label ?? key,
type: type ?? 'text',
field: key,
order: ord ?? Infinity,
options: {},
filterable: filterable,
hidden: hidden ?? false,
}));
// ← Merge, sort, THEN strip order
const mergedAttributes = [...attributes, ...computedMeta]
.sort((a, b) => (a.order ?? Infinity) - (b.order ?? Infinity))
.map(({ order: _, ...rest }) => rest);
return {
data,
pagination: {
page,
limit,
totalRecords: count,
totalPages,
hasPrevPage: page > PAGE_START,
hasNextPage: page < totalPages,
},
attributes: mergedAttributes,
};
}
module.exports = { paginate, auditInclude, safeParseJSON };
+59
View File
@@ -0,0 +1,59 @@
// utils/personalInfo.util.js
/**
* Computes full_name, full_address, full_number
* from a personal_info object before saving to DB.
*
* @param {Object} personalInfo
* @returns {Object} enriched personal_info
*/
function enrichPersonalInfo(personalInfo = {}) {
if (!personalInfo || typeof personalInfo !== 'object') return personalInfo;
const pi = { ...personalInfo };
// ── Full Name ────────────────────────────────────────────────────────────────
if (pi.name) {
const { last_name, given_name, middle_name, extension_name } = pi.name;
pi.name = {
...pi.name,
full_name: [
last_name ? `${last_name},` : null,
given_name,
middle_name,
extension_name,
]
.filter((v) => v && v.trim() !== '')
.join(' '),
};
}
// ── Full Addresses ───────────────────────────────────────────────────────────
if (Array.isArray(pi.addresses)) {
pi.addresses = pi.addresses.map((addr) => ({
...addr,
full_address: [
addr.street,
addr.city,
addr.state,
addr.country,
addr.zip,
]
.filter((v) => v && v.trim() !== '')
.join(', '),
}));
}
// ── Full Phone Numbers ───────────────────────────────────────────────────────
if (Array.isArray(pi.phone_number)) {
pi.phone_number = pi.phone_number.map((phone) => ({
...phone,
full_number: `${phone.country_code || ''}${phone.number || ''}`,
}));
}
return pi;
}
module.exports = { enrichPersonalInfo };
+45
View File
@@ -0,0 +1,45 @@
/***********************************************************************************************************************************************************************
* File Name: purchasable.util.js
* Type of Program: Utility
* Description: Resolves a Product's polymorphic target (purchasable_type +
* purchasable_id → Course | Unit | Lesson) and the checkout
* route for it. Products.mdl.js can't express a single
* Sequelize association across three different target models,
* so this is the shared lookup every consumer (access checks,
* admin product CRUD, client checkout) goes through instead.
*
* Author: Kenneth Obsequio (@lash0000)
* Date Created: Aug. 1, 2026
***********************************************************************************************************************************************************************/
'use strict';
const { Course } = require('../models/courses/courses.mdl');
const Unit = require('../models/courses/units.mdl');
const Lesson = require('../models/courses/lessons.mdl');
const TYPE_MODELS = { course: Course, unit: Unit, lesson: Lesson };
const TYPE_PK = { course: 'course_id', unit: 'unit_id', lesson: 'lesson_id' };
function getPurchasableModel(type) {
return TYPE_MODELS[type] ?? null;
}
// Returns the target row (needs at least uuid/course_id + subscription for
// callers), or null if the type is unknown or the row doesn't exist.
async function resolvePurchasable(type, id) {
const Model = TYPE_MODELS[type];
if (!Model) return null;
return Model.findOne({ where: { [TYPE_PK[type]]: id, deletedAt: null } });
}
// Course checkout stays keyed by numeric course_id (existing convention);
// Unit/Lesson checkout is keyed by uuid, matching how /units/:uuid and
// /lessons/:uuid already work everywhere else in the standalone consumption paths.
function checkoutPath(type, record) {
if (type === 'course') return `/course/${record.course_id}/checkout`;
if (type === 'unit') return `/units/${record.uuid}/checkout`;
if (type === 'lesson') return `/lessons/${record.uuid}/checkout`;
return null;
}
module.exports = { getPurchasableModel, resolvePurchasable, checkoutPath };
+21
View File
@@ -0,0 +1,21 @@
/***********************************************************************************************************************************************************************
* File Name: renderTemplate.util.js
* Type of Program: Utility
* Description: Plain-text {{placeholder}} substitution — no eval/Function, so
* admin-supplied HTML can never execute arbitrary JS. Unknown or
* missing keys resolve to an empty string rather than throwing.
* Author: Kenneth Obsequio (@lash0000)
* Date Created: Jul. 3, 2026
***********************************************************************************************************************************************************************
* HOW TO USE:
* const { renderTemplate } = require('../utils/renderTemplate.util');
* renderTemplate('Hi {{name}}', { name: 'Ken' }); // "Hi Ken"
***********************************************************************************************************************************************************************/
const renderTemplate = (str, data = {}) =>
String(str ?? '').replace(/\{\{\s*(\w+)\s*\}\}/g, (_, key) => {
const val = data[key];
return (val === undefined || val === null) ? '' : String(val);
});
module.exports = { renderTemplate };
+55
View File
@@ -0,0 +1,55 @@
// utils/resolveAvatar.util.js
//
// Resolves a stored avatar into a browser-usable reference at read time.
//
// personal_info.avatar is never handed to the browser as a raw S3 URL —
// same protection as every other media type in this app (see
// controllers/client/media.controller.js): the browser only ever gets a
// short-lived opaque stream_token, proxied through
// GET /client/media/stream/:token, which mints the real presigned URL
// server-side and pipes the bytes back. The real bucket/key/signature never
// reach the DOM.
//
// - S3-stored avatars (avatar.uuid present) → sign a fresh media JWT from
// the stored key on every read (never persist a token/URL on the row).
// - Google-picture avatars (reg_type: 'google', no uuid — see
// auth.controller.js googleCallback) are an external CDN URL and pass
// through unchanged as file_url; there's nothing of ours to sign or hide.
//
const { signMediaToken } = require('../services/mediaToken.service');
async function resolveAvatarUrl(avatar) {
if (!avatar) return avatar ?? null;
if (!avatar.uuid) {
// External URL (e.g. Google) — nothing to sign, just normalize the field
// name to match the { stream_token?, file_url? } shape resolveAssetSrc()
// already expects for every other media payload.
return { ...avatar, url: undefined, file_url: avatar.url };
}
const token = signMediaToken({
storage_key: avatar.uuid,
file_type: 'image',
mime_type: avatar.mime_type,
});
return { ...avatar, url: undefined, file_url: undefined, stream_token: token };
}
// Mutates-and-returns a shallow copy of a user (plain object or Sequelize
// instance) with personal_info.avatar resolved. Safe to call on a user with
// no avatar at all.
async function resolveUserAvatar(user) {
if (!user) return user;
const u = user.toJSON ? user.toJSON() : { ...user };
if (!u.personal_info?.avatar) return u;
u.personal_info = {
...u.personal_info,
avatar: await resolveAvatarUrl(u.personal_info.avatar),
};
return u;
}
module.exports = { resolveAvatarUrl, resolveUserAvatar };
+28
View File
@@ -0,0 +1,28 @@
/***********************************************************************************************************************************************************************
* File Name: response.util.js
* Type of Program: Utility
* Description: Standardised HTTP response helpers.
* Wraps all responses in a consistent envelope:
* { status, message, data?, errors? }
* Author: rgrgogu
* Date Created: Oct. 6, 2025
***********************************************************************************************************************************************************************
* HOW TO USE:
* const R = require('../utils/response.util');
* return R.success(res, 'User created', user, 201);
* return R.error(res, 'Not found', 404);
***********************************************************************************************************************************************************************/
const success = (res, message = 'OK', data = null, statusCode = 200) =>
res.status(statusCode).json({ status: 'success', message, data });
const error = (res, message = 'An error occurred', statusCode = 500, errors = null) => {
const body = { status: 'error', message };
if (errors) body.errors = errors;
return res.status(statusCode).json(body);
};
const validationError = (res, errors) =>
res.status(422).json({ status: 'error', message: 'Validation failed', errors });
module.exports = { success, error, validationError };
+66
View File
@@ -0,0 +1,66 @@
'use strict';
const axios = require('axios');
const UAParser = require('ua-parser-js');
const LOCALHOST = new Set(['::1', '127.0.0.1', '::ffff:127.0.0.1']);
const getIP = (req) => {
const forwarded = req.headers['x-forwarded-for'];
if (forwarded) return forwarded.split(',')[0].trim();
return req.ip || req.connection?.remoteAddress || null;
};
const parseUA = (uaString) => {
const p = new UAParser(uaString || '');
return {
ua: uaString || 'unknown',
browser: [p.getBrowser().name, p.getBrowser().version].filter(Boolean).join(' ') || 'unknown',
os: [p.getOS().name, p.getOS().version].filter(Boolean).join(' ') || 'unknown',
device: p.getDevice().type || 'desktop',
};
};
const getGeo = async (ip) => {
if (!ip || LOCALHOST.has(ip)) return { country: null, region: null, city: null, lat: null, lon: null };
try {
const { data } = await axios.get(
`http://ip-api.com/json/${ip}?fields=status,country,regionName,city,lat,lon`,
{ timeout: 3000 }
);
if (data.status !== 'success') return { country: null, region: null, city: null, lat: null, lon: null };
return { country: data.country, region: data.regionName, city: data.city, lat: data.lat, lon: data.lon };
} catch {
return { country: null, region: null, city: null, lat: null, lon: null };
}
};
/**
* Builds a rich session info object from the request.
* Used for both login_info and logout_info.
*
* @param {import('express').Request} req
* @param {Object} extras — e.g. { forced_by: admin_user_id }
* @returns {Promise<Object>}
*/
const buildSessionInfo = async (req, extras = {}) => {
const ip = getIP(req);
const geo = await getGeo(ip);
return {
date: new Date().toISOString(),
ip_address: ip,
country: geo.country,
region: geo.region,
city: geo.city,
lat: geo.lat,
lon: geo.lon,
device_info: parseUA(req.headers['user-agent']),
...extras,
};
};
module.exports = buildSessionInfo;
module.exports.parseUA = parseUA;
module.exports.getIP = getIP;
+48
View File
@@ -0,0 +1,48 @@
/***********************************************************************************************************************************************************************
* File Name : suspendGuard.util.js
* Type : Utility
* Description : Local-dev-only watchdog that detects the host machine coming
* back from sleep/idle (laptop lid closed, suspended, etc.)
* and stops the dev server immediately.
*
* Why: when the process is frozen mid-sleep, node-cron's own
* heartbeat later finds itself hours behind schedule and logs
* a "[NODE-CRON] missed execution" warning for every tick that
* elapsed — one line per missed minute, easily hundreds after
* an overnight sleep. There's nothing to recover here (no
* request was dropped, no job silently failed); the correct
* behavior is just "the dev server wasn't meaningfully running
* during that time," so we exit instead of logging noise.
*
* Never runs when NODE_ENV=production — the droplet process
* is long-running and must never self-exit on its own.
*
* Author: Kenneth Obsequio (@lash0000)
* Date Created: Aug. 11, 2026
***********************************************************************************************************************************************************************/
'use strict';
const CHECK_INTERVAL_MS = 250;
const GAP_THRESHOLD_MS = 10_000; // far beyond normal event-loop jitter
function startSuspendGuard() {
if (process.env.NODE_ENV === 'production') return;
let last = Date.now();
setInterval(() => {
const now = Date.now();
const gap = now - last - CHECK_INTERVAL_MS;
last = now;
if (gap > GAP_THRESHOLD_MS) {
console.log(
`\n🛑 Dev server was asleep/idle for ~${Math.round(gap / 1000)}s (laptop suspend or similar). ` +
`Stopping instead of letting node-cron dump missed-execution warnings.\n`
);
process.exit(0);
}
}, CHECK_INTERVAL_MS).unref();
}
module.exports = { startSuspendGuard };
+83
View File
@@ -0,0 +1,83 @@
/***********************************************************************************************************************************************************************
* File Name: token.util.js
* Type of Program: Utility
* Description: JWT access & refresh token helpers.
* - generateTokens() → produces { accessToken, refreshToken }
* - verifyAccessToken() → validates and returns decoded payload
* - verifyRefreshToken() → validates the long-lived refresh token
* - hashToken() → SHA-256 hash used to store refresh tokens in DB
* Author: rgrgogu
* Date Created: Oct. 6, 2025
***********************************************************************************************************************************************************************
* HOW TO USE:
* const { generateTokens, verifyAccessToken } = require('../utils/token.util');
* const { accessToken, refreshToken } = generateTokens(user);
***********************************************************************************************************************************************************************/
const jwt = require('jsonwebtoken');
const crypto = require('crypto');
/**
* Generates a signed access token and a signed refresh token.
* @param {object} user - Sequelize User instance
* @returns {{ accessToken: string, refreshToken: string }}
*/
const generateTokens = (user) => {
const payload = {
user_id: user.user_id,
email: user.email,
acc_type: user.acc_type,
reg_type: user.reg_type,
};
const accessToken = jwt.sign(payload, process.env.JWT_SECRET, {
expiresIn: process.env.JWT_EXPIRES_IN || '1d',
});
const refreshToken = jwt.sign(
{ user_id: user.user_id },
process.env.JWT_REFRESH_SECRET,
{ expiresIn: process.env.JWT_REFRESH_EXPIRES_IN || '7d' }
);
return { accessToken, refreshToken };
};
/**
* Verifies an access token.
* @param {string} token
* @returns {object} decoded payload
* @throws if invalid / expired
*/
const verifyAccessToken = (token) =>
jwt.verify(token, process.env.JWT_SECRET);
/**
* Verifies a refresh token.
* @param {string} token
* @returns {object} decoded payload
*/
const verifyRefreshToken = (token) =>
jwt.verify(token, process.env.JWT_REFRESH_SECRET);
/**
* SHA-256 hash a token string for safe DB storage.
* @param {string} token
* @returns {string} hex digest
*/
const hashToken = (token) =>
crypto.createHash('sha256').update(token).digest('hex');
/**
* SHA-256 hash a token string for safe DB storage.
* @param {string} decoded
* @param {number} thresholdDays
* @returns {string} if expired or not
*/
const shouldRotateRefreshToken = (decoded, thresholdDays = 1) => {
const now = Math.floor(Date.now() / 1000);
const timeLeft = decoded.exp - now;
const threshold = thresholdDays * 24 * 60 * 60;
return timeLeft <= threshold;
};
module.exports = { generateTokens, verifyAccessToken, verifyRefreshToken, hashToken, shouldRotateRefreshToken };
@@ -0,0 +1,48 @@
/***********************************************************************************************************************************************************************
* File Name: withTransactionRetry.util.js
* Type of Program: Utility
* Description: Runs a Sequelize transaction, automatically retrying on serialization_failure
* (SQLSTATE 40001) — the transient "restart transaction" error CockroachDB (and
* Postgres SERIALIZABLE) throw when concurrent transactions can't be safely
* ordered. Without a retry, these surface as unhandled 500s on otherwise-correct
* code the moment two requests touch the same row close together.
* Author: Kenneth Obsequio (@lash0000)
* Date Created: Jul. 17, 2026
***********************************************************************************************************************************************************************
* HOW TO USE:
* const { withTransactionRetry } = require('../utils/withTransactionRetry.util');
* const result = await withTransactionRetry(sequelize, async (t) => {
* await Model.upsert({...}, { transaction: t });
* return something;
* });
***********************************************************************************************************************************************************************/
'use strict';
const SERIALIZATION_FAILURE = '40001';
const MAX_RETRIES = 5;
const BASE_DELAY_MS = 50;
function isSerializationFailure(err) {
return err?.parent?.code === SERIALIZATION_FAILURE || err?.original?.code === SERIALIZATION_FAILURE;
}
async function withTransactionRetry(sequelize, fn, { maxRetries = MAX_RETRIES } = {}) {
for (let attempt = 0; ; attempt++) {
const t = await sequelize.transaction();
try {
const result = await fn(t);
await t.commit();
return result;
} catch (err) {
await t.rollback();
if (isSerializationFailure(err) && attempt < maxRetries) {
const delay = BASE_DELAY_MS * 2 ** attempt + Math.random() * BASE_DELAY_MS;
await new Promise((resolve) => setTimeout(resolve, delay));
continue;
}
throw err;
}
}
}
module.exports = { withTransactionRetry, isSerializationFailure };