@@ -875,7 +875,7 @@ exports.getQuiz = async (req, res) => {
|
||||
exports.createQuiz = async (req, res) => {
|
||||
try {
|
||||
const { courseId, unitId } = req.params;
|
||||
const { title, is_required, passing_score, max_questions, createdBy } = req.body;
|
||||
const { title, is_required, passing_score, max_questions, shuffle_questions, createdBy } = req.body;
|
||||
|
||||
const unit = await Unit.findOne({ where: { unit_id: unitId, course_id: courseId, ...notDeleted } });
|
||||
if (!unit) return R.error(res, "Unit not found.", 404);
|
||||
@@ -889,6 +889,7 @@ exports.createQuiz = async (req, res) => {
|
||||
is_required: is_required ?? false,
|
||||
passing_score: passing_score ?? 70,
|
||||
max_questions: max_questions ?? null,
|
||||
shuffle_questions: shuffle_questions ?? false,
|
||||
createdBy: createdBy ?? null,
|
||||
});
|
||||
|
||||
@@ -903,15 +904,16 @@ exports.createQuiz = async (req, res) => {
|
||||
exports.updateQuiz = async (req, res) => {
|
||||
try {
|
||||
const { courseId, unitId, quizId } = req.params;
|
||||
const { title, is_required, passing_score, max_questions, updatedBy } = req.body;
|
||||
const { title, is_required, passing_score, max_questions, shuffle_questions, updatedBy } = req.body;
|
||||
|
||||
const quiz = await UnitQuiz.findOne({ where: { quiz_id: quizId, unit_id: unitId, ...notDeleted } });
|
||||
if (!quiz) return R.error(res, "Quiz not found.", 404);
|
||||
|
||||
if (title !== undefined) quiz.title = title;
|
||||
if (is_required !== undefined) quiz.is_required = is_required;
|
||||
if (passing_score !== undefined) quiz.passing_score = passing_score;
|
||||
if (max_questions !== undefined) quiz.max_questions = max_questions;
|
||||
if (title !== undefined) quiz.title = title;
|
||||
if (is_required !== undefined) quiz.is_required = is_required;
|
||||
if (passing_score !== undefined) quiz.passing_score = passing_score;
|
||||
if (max_questions !== undefined) quiz.max_questions = max_questions;
|
||||
if (shuffle_questions !== undefined) quiz.shuffle_questions = shuffle_questions;
|
||||
|
||||
quiz.updatedBy = updatedBy ?? null;
|
||||
|
||||
@@ -1244,7 +1246,7 @@ exports.getAssessment = async (req, res) => {
|
||||
exports.createAssessment = async (req, res) => {
|
||||
try {
|
||||
const { courseId } = req.params;
|
||||
const { title, is_required, passing_score, time_limit_minutes, max_questions, max_attempts, cooldown_hours, createdBy } = req.body;
|
||||
const { title, is_required, passing_score, time_limit_minutes, max_questions, max_attempts, cooldown_hours, shuffle_questions, createdBy } = req.body;
|
||||
|
||||
const course = await Course.findOne({ where: { course_id: courseId, ...notDeleted } });
|
||||
if (!course) return R.error(res, "Course not found.", 404);
|
||||
@@ -1261,6 +1263,7 @@ exports.createAssessment = async (req, res) => {
|
||||
max_questions: max_questions ?? null,
|
||||
max_attempts: max_attempts ?? 3,
|
||||
cooldown_hours: cooldown_hours ?? 24,
|
||||
shuffle_questions: shuffle_questions ?? false,
|
||||
createdBy: createdBy ?? null,
|
||||
});
|
||||
|
||||
@@ -1275,20 +1278,21 @@ exports.createAssessment = async (req, res) => {
|
||||
exports.updateAssessment = async (req, res) => {
|
||||
try {
|
||||
const { courseId, assessmentId } = req.params;
|
||||
const { title, is_required, passing_score, time_limit_minutes, max_questions, max_attempts, cooldown_hours, updatedBy } = req.body;
|
||||
const { title, is_required, passing_score, time_limit_minutes, max_questions, max_attempts, cooldown_hours, shuffle_questions, updatedBy } = req.body;
|
||||
|
||||
const assessment = await CourseAssessment.findOne({
|
||||
where: { assessment_id: assessmentId, course_id: courseId, ...notDeleted },
|
||||
});
|
||||
if (!assessment) return R.error(res, "Assessment not found.", 404);
|
||||
|
||||
if (title !== undefined) assessment.title = title;
|
||||
if (is_required !== undefined) assessment.is_required = is_required;
|
||||
if (passing_score !== undefined) assessment.passing_score = passing_score;
|
||||
if (title !== undefined) assessment.title = title;
|
||||
if (is_required !== undefined) assessment.is_required = is_required;
|
||||
if (passing_score !== undefined) assessment.passing_score = passing_score;
|
||||
if (time_limit_minutes !== undefined) assessment.time_limit_minutes = time_limit_minutes;
|
||||
if (max_questions !== undefined) assessment.max_questions = max_questions;
|
||||
if (max_attempts !== undefined) assessment.max_attempts = max_attempts;
|
||||
if (cooldown_hours !== undefined) assessment.cooldown_hours = cooldown_hours;
|
||||
if (max_questions !== undefined) assessment.max_questions = max_questions;
|
||||
if (max_attempts !== undefined) assessment.max_attempts = max_attempts;
|
||||
if (cooldown_hours !== undefined) assessment.cooldown_hours = cooldown_hours;
|
||||
if (shuffle_questions !== undefined) assessment.shuffle_questions = shuffle_questions;
|
||||
|
||||
assessment.updatedBy = updatedBy ?? null;
|
||||
|
||||
@@ -1423,6 +1427,23 @@ exports.getCoursesFlat = async (req, res) => {
|
||||
}
|
||||
};
|
||||
|
||||
exports.getCoursesBySubscription = async (req, res) => {
|
||||
try {
|
||||
const { slug } = req.query;
|
||||
if (!slug) return R.error(res, 'slug query param is required.', 400);
|
||||
|
||||
const data = await Course.findAll({
|
||||
where: { ...notDeleted, subscription: slug },
|
||||
attributes: ['course_id', 'title', 'description', 'subscription'],
|
||||
order: [['title', 'ASC']],
|
||||
});
|
||||
return R.success(res, 'Courses retrieved.', data);
|
||||
} catch (err) {
|
||||
console.error('[COURSE][BY SUBSCRIPTION]', err);
|
||||
return R.error(res, 'Could not retrieve courses.', 500);
|
||||
}
|
||||
};
|
||||
|
||||
exports.getUnitsFlat = async (req, res) => {
|
||||
try {
|
||||
const rows = await Unit.findAll({
|
||||
@@ -1565,11 +1586,12 @@ exports.syncInstructors = async (req, res) => {
|
||||
// ─── COMPLETIONS HELPERS ──────────────────────────────────────────────────────
|
||||
|
||||
function extractUserInfo(user) {
|
||||
if (!user) return { full_name: null, email: null, avatar_url: null };
|
||||
if (!user) return { full_name: null, email: null, avatar_url: null, deleted: false };
|
||||
return {
|
||||
full_name: user.personal_info?.name?.full_name ?? null,
|
||||
email: user.email ?? null,
|
||||
avatar_url: user.personal_info?.avatar?.url ?? null,
|
||||
deleted: !!user.deletedAt,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1578,12 +1600,13 @@ function groupByUser(attempts) {
|
||||
for (const a of attempts) {
|
||||
const uid = String(a.user_id);
|
||||
if (!map.has(uid)) {
|
||||
const { full_name, email, avatar_url } = extractUserInfo(a.user);
|
||||
const { full_name, email, avatar_url, deleted } = extractUserInfo(a.user);
|
||||
map.set(uid, {
|
||||
user_id: a.user_id,
|
||||
full_name,
|
||||
email,
|
||||
avatar_url,
|
||||
deleted,
|
||||
attempt_count: 0,
|
||||
best_score: 0,
|
||||
passed: false,
|
||||
@@ -1602,10 +1625,36 @@ function groupByUser(attempts) {
|
||||
}
|
||||
|
||||
function buildSummary(attempts) {
|
||||
const takers = new Set(attempts.map((a) => String(a.user_id))).size;
|
||||
const passed = attempts.filter((a) => a.passed).length;
|
||||
const failed = attempts.length - passed;
|
||||
const avg = attempts.length ? Math.round(attempts.reduce((s, a) => s + a.score, 0) / attempts.length) : 0;
|
||||
const takers = new Set(attempts.map((a) => String(a.user_id))).size;
|
||||
const passed = attempts.filter((a) => a.passed).length;
|
||||
const failed = attempts.length - passed;
|
||||
|
||||
/*
|
||||
* ┌─────────────────────────────────────────────────────────────────┐
|
||||
* │ AVG SCORE formula │
|
||||
* │ │
|
||||
* │ avg = Σ( max(score) per user ) / unique_user_count │
|
||||
* │ │
|
||||
* │ Each student contributes exactly once — their personal best. │
|
||||
* │ A student who retries 3× before passing counts once at peak │
|
||||
* │ performance, not three times. Mirrors the "Best Score" column │
|
||||
* │ shown per student in the completions table. │
|
||||
* │ │
|
||||
* │ NOTE: CockroachDB returns INT8 columns as strings via the pg │
|
||||
* │ driver. Coerce with Number() before any arithmetic. │
|
||||
* └─────────────────────────────────────────────────────────────────┘
|
||||
*/
|
||||
const bestByUser = new Map();
|
||||
for (const a of attempts) {
|
||||
const uid = String(a.user_id);
|
||||
const s = Number(a.score);
|
||||
if (!bestByUser.has(uid) || s > bestByUser.get(uid)) bestByUser.set(uid, s);
|
||||
}
|
||||
const bestScores = [...bestByUser.values()];
|
||||
const avg = bestScores.length
|
||||
? Math.round(bestScores.reduce((sum, s) => sum + s, 0) / bestScores.length)
|
||||
: 0;
|
||||
|
||||
return {
|
||||
total_takers: takers,
|
||||
passed_count: passed,
|
||||
@@ -1625,7 +1674,7 @@ exports.getQuizCompletions = async (req, res) => {
|
||||
const attempts = await QuizAttempt.findAll({
|
||||
where: { quiz_id: quizId },
|
||||
attributes: ["attempt_id", "user_id", "attempt_number", "score", "earned_points", "total_points", "passed", "createdAt"],
|
||||
include: [{ model: mdl_Users, as: "user", attributes: ["user_id", "email", "personal_info"] }],
|
||||
include: [{ model: mdl_Users, as: "user", attributes: ["user_id", "email", "personal_info", "deletedAt"], paranoid: false }],
|
||||
order: [["createdAt", "DESC"]],
|
||||
});
|
||||
|
||||
@@ -1649,7 +1698,7 @@ exports.getAssessmentCompletions = async (req, res) => {
|
||||
const attempts = await QuizAttempt.findAll({
|
||||
where: { assessment_id: assessmentId },
|
||||
attributes: ["attempt_id", "user_id", "attempt_number", "score", "earned_points", "total_points", "passed", "createdAt"],
|
||||
include: [{ model: mdl_Users, as: "user", attributes: ["user_id", "email", "personal_info"] }],
|
||||
include: [{ model: mdl_Users, as: "user", attributes: ["user_id", "email", "personal_info", "deletedAt"], paranoid: false }],
|
||||
order: [["createdAt", "DESC"]],
|
||||
});
|
||||
|
||||
@@ -1673,13 +1722,13 @@ exports.getAssessmentSessions = async (req, res) => {
|
||||
const sessions = await AssessmentSession.findAll({
|
||||
where: { assessment_id: assessmentId },
|
||||
attributes: ["session_id", "user_id", "status", "started_at", "expires_at", "attempt_id", "createdAt", "updatedAt"],
|
||||
include: [{ model: mdl_Users, as: "user", attributes: ["user_id", "email", "personal_info"] }],
|
||||
include: [{ model: mdl_Users, as: "user", attributes: ["user_id", "email", "personal_info", "deletedAt"], paranoid: false }],
|
||||
order: [["createdAt", "DESC"]],
|
||||
});
|
||||
|
||||
const rows = sessions.map((s) => {
|
||||
const j = s.toJSON();
|
||||
const { full_name, email, avatar_url } = extractUserInfo(j.user);
|
||||
const { full_name, email, avatar_url, deleted } = extractUserInfo(j.user);
|
||||
const time_spent_seconds = j.status !== 'in_progress' && j.started_at
|
||||
? Math.round((new Date(j.updatedAt) - new Date(j.started_at)) / 1000)
|
||||
: null;
|
||||
@@ -1689,6 +1738,7 @@ exports.getAssessmentSessions = async (req, res) => {
|
||||
full_name,
|
||||
email,
|
||||
avatar_url,
|
||||
deleted,
|
||||
status: j.status,
|
||||
started_at: j.started_at,
|
||||
expires_at: j.expires_at,
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
***********************************************************************************************************************************************************************/
|
||||
"use strict";
|
||||
|
||||
const { Op } = require("sequelize");
|
||||
const jwt = require("jsonwebtoken");
|
||||
|
||||
const R = require("../../utils/response.util");
|
||||
@@ -29,6 +30,21 @@ function resolveIp(req) {
|
||||
return req.ip ?? req.socket?.remoteAddress ?? "unknown";
|
||||
}
|
||||
|
||||
function signToken(asset, userId, ip) {
|
||||
return jwt.sign(
|
||||
{
|
||||
asset_id: asset.asset_id,
|
||||
user_id: userId,
|
||||
storage_key: asset.storage_key,
|
||||
file_type: asset.file_type,
|
||||
mime_type: asset.mime_type,
|
||||
ip,
|
||||
},
|
||||
MEDIA_SECRET,
|
||||
{ expiresIn: TOKEN_TTL_SEC }
|
||||
);
|
||||
}
|
||||
|
||||
// ─── POST /admin/media/token ──────────────────────────────────────────────────
|
||||
|
||||
exports.issueToken = async (req, res) => {
|
||||
@@ -51,20 +67,8 @@ exports.issueToken = async (req, res) => {
|
||||
return R.error(res, "Token flow is for S3 assets only. Use the raw file_url for other providers.", 400);
|
||||
}
|
||||
|
||||
const ip = resolveIp(req);
|
||||
|
||||
const token = jwt.sign(
|
||||
{
|
||||
asset_id,
|
||||
user_id: req.user.user_id,
|
||||
storage_key: asset.storage_key,
|
||||
file_type: asset.file_type,
|
||||
mime_type: asset.mime_type,
|
||||
ip,
|
||||
},
|
||||
MEDIA_SECRET,
|
||||
{ expiresIn: TOKEN_TTL_SEC }
|
||||
);
|
||||
const ip = resolveIp(req);
|
||||
const token = signToken(asset, req.user.user_id, ip);
|
||||
|
||||
// ── Presign thumbnail URL so the browser can load it directly ─────────────
|
||||
let thumbnail_url = null;
|
||||
@@ -88,3 +92,39 @@ exports.issueToken = async (req, res) => {
|
||||
return R.error(res, "Could not issue media token.", 500);
|
||||
}
|
||||
};
|
||||
|
||||
// ─── POST /admin/media/tokens (batch) ───────────────────────────────────────
|
||||
//
|
||||
// Accepts { asset_ids: [id, ...] } — S3 assets only, max 50.
|
||||
// Returns { tokens: { [asset_id]: token } }
|
||||
// One round-trip instead of N per-card requests.
|
||||
|
||||
exports.issueTokensBatch = async (req, res) => {
|
||||
try {
|
||||
const { asset_ids } = req.body;
|
||||
if (!Array.isArray(asset_ids) || !asset_ids.length)
|
||||
return R.error(res, "asset_ids must be a non-empty array.", 400);
|
||||
if (asset_ids.length > 50)
|
||||
return R.error(res, "Maximum 50 asset_ids per batch.", 400);
|
||||
|
||||
const assets = await mdl_Assets.findAll({
|
||||
where: {
|
||||
asset_id: { [Op.in]: asset_ids },
|
||||
storage_provider: "s3",
|
||||
deletedAt: null,
|
||||
},
|
||||
attributes: ["asset_id", "file_type", "storage_key", "mime_type"],
|
||||
});
|
||||
|
||||
const ip = resolveIp(req);
|
||||
const tokens = {};
|
||||
for (const asset of assets) {
|
||||
tokens[String(asset.asset_id)] = signToken(asset, req.user.user_id, ip);
|
||||
}
|
||||
|
||||
return R.success(res, "Tokens issued.", { tokens });
|
||||
} catch (err) {
|
||||
console.error("[ADMIN][MEDIA][TOKENS BATCH]", err);
|
||||
return R.error(res, "Could not issue media tokens.", 500);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
'use strict';
|
||||
|
||||
const mdl_TierCategories = require('../../models/tiers/tier_categories.mdl');
|
||||
const mdl_TierPlans = require('../../models/tiers/tier_plans.mdl');
|
||||
const Asset = require('../../models/assets/assets.mdl');
|
||||
const R = require('../../utils/response.util');
|
||||
const logActivity = require('../../utils/logActivity.util');
|
||||
|
||||
require('../../models/tiers/tier.associations');
|
||||
|
||||
const ASSET_ATTRS = ['asset_id', 'file_url', 'display_name', 'mime_type'];
|
||||
|
||||
const withBadge = [{ model: Asset, as: 'badgeAsset', attributes: ASSET_ATTRS, required: false }];
|
||||
|
||||
// ─── GET /admin/tiers/categories ─────────────────────────────────────────────
|
||||
|
||||
exports.getCategories = async (req, res) => {
|
||||
try {
|
||||
const categories = await mdl_TierCategories.findAll({
|
||||
include: withBadge,
|
||||
order: [['rank', 'ASC']],
|
||||
});
|
||||
return R.success(res, 'Tier categories retrieved.', categories);
|
||||
} catch (err) {
|
||||
console.error('[ADMIN][GET TIER CATEGORIES]', err);
|
||||
return R.error(res, 'Could not retrieve tier categories.', 500);
|
||||
}
|
||||
};
|
||||
|
||||
// ─── GET /admin/tiers/categories/:id ─────────────────────────────────────────
|
||||
|
||||
exports.getCategory = async (req, res) => {
|
||||
try {
|
||||
const cat = await mdl_TierCategories.findByPk(req.params.id, { include: withBadge });
|
||||
if (!cat) return R.error(res, 'Tier category not found.', 404);
|
||||
return R.success(res, 'Tier category retrieved.', cat);
|
||||
} catch (err) {
|
||||
console.error('[ADMIN][GET TIER CATEGORY]', err);
|
||||
return R.error(res, 'Could not retrieve tier category.', 500);
|
||||
}
|
||||
};
|
||||
|
||||
// ─── POST /admin/tiers/categories ────────────────────────────────────────────
|
||||
|
||||
exports.createCategory = async (req, res) => {
|
||||
try {
|
||||
const { slug, name, description, rank, color, badge_asset_id, badge_icon, badge_label } = req.body;
|
||||
if (!slug || !name) return R.error(res, 'slug and name are required.', 400);
|
||||
|
||||
const parsedRank = Number(rank ?? 1);
|
||||
if (parsedRank <= 0) return R.error(res, 'Non-default tier categories must have rank greater than 0.', 400);
|
||||
|
||||
const exists = await mdl_TierCategories.findOne({ where: { slug } });
|
||||
if (exists) return R.error(res, `A tier category with slug "${slug}" already exists.`, 409);
|
||||
|
||||
const cat = await mdl_TierCategories.create({
|
||||
slug, name,
|
||||
description: description ?? null,
|
||||
rank: parsedRank,
|
||||
color: color || 'purple',
|
||||
badge_asset_id: badge_asset_id || null,
|
||||
badge_icon: badge_icon || null,
|
||||
badge_label: badge_label ?? null,
|
||||
is_default: false,
|
||||
is_active: true,
|
||||
});
|
||||
|
||||
logActivity(req.user?.user_id, 'create_tier_category', { entityType: 'tier_category', details: { slug, name } });
|
||||
|
||||
const result = await mdl_TierCategories.findByPk(cat.tier_category_id, { include: withBadge });
|
||||
return R.success(res, 'Tier category created.', result, 201);
|
||||
} catch (err) {
|
||||
console.error('[ADMIN][CREATE TIER CATEGORY]', err);
|
||||
return R.error(res, 'Could not create tier category.', 500);
|
||||
}
|
||||
};
|
||||
|
||||
// ─── PUT /admin/tiers/categories/:id ─────────────────────────────────────────
|
||||
|
||||
exports.updateCategory = async (req, res) => {
|
||||
try {
|
||||
const cat = await mdl_TierCategories.findByPk(req.params.id);
|
||||
if (!cat) return R.error(res, 'Tier category not found.', 404);
|
||||
|
||||
const { name, description, rank, color, badge_asset_id, badge_icon, badge_label, is_active } = req.body;
|
||||
|
||||
if (!cat.is_default && rank !== undefined) {
|
||||
const parsedRank = Number(rank);
|
||||
if (parsedRank <= 0) return R.error(res, 'Non-default tier categories must have rank greater than 0.', 400);
|
||||
}
|
||||
|
||||
await cat.update({
|
||||
name: name ?? cat.name,
|
||||
description: description !== undefined ? (description || null) : cat.description,
|
||||
rank: rank !== undefined ? Number(rank) : cat.rank,
|
||||
color: color !== undefined ? (color || cat.color) : cat.color,
|
||||
badge_asset_id: badge_asset_id !== undefined ? (badge_asset_id || null) : cat.badge_asset_id,
|
||||
badge_icon: badge_icon !== undefined ? (badge_icon || null) : cat.badge_icon,
|
||||
badge_label: badge_label !== undefined ? (badge_label || null) : cat.badge_label,
|
||||
// Default category (free) cannot be deactivated
|
||||
is_active: (!cat.is_default && is_active !== undefined) ? is_active : cat.is_active,
|
||||
});
|
||||
|
||||
logActivity(req.user?.user_id, 'update_tier_category', { entityType: 'tier_category', details: { id: cat.tier_category_id, slug: cat.slug } });
|
||||
|
||||
const result = await mdl_TierCategories.findByPk(cat.tier_category_id, { include: withBadge });
|
||||
return R.success(res, 'Tier category updated.', result);
|
||||
} catch (err) {
|
||||
console.error('[ADMIN][UPDATE TIER CATEGORY]', err);
|
||||
return R.error(res, 'Could not update tier category.', 500);
|
||||
}
|
||||
};
|
||||
|
||||
// ─── DELETE /admin/tiers/categories/:id ──────────────────────────────────────
|
||||
|
||||
exports.deleteCategory = async (req, res) => {
|
||||
try {
|
||||
const cat = await mdl_TierCategories.findByPk(req.params.id);
|
||||
if (!cat) return R.error(res, 'Tier category not found.', 404);
|
||||
if (cat.is_default) return R.error(res, 'The default (Free) tier category cannot be deleted.', 400);
|
||||
|
||||
// Block deletion if active plans still reference this category
|
||||
const activePlans = await mdl_TierPlans.count({
|
||||
where: { tier_category_id: cat.tier_category_id, is_active: true },
|
||||
});
|
||||
if (activePlans > 0)
|
||||
return R.error(res, `Cannot delete — ${activePlans} active plan(s) belong to this category. Archive or reassign them first.`, 409);
|
||||
|
||||
await cat.destroy();
|
||||
logActivity(req.user?.user_id, 'delete_tier_category', { entityType: 'tier_category', details: { slug: cat.slug } });
|
||||
return R.success(res, 'Tier category deleted.');
|
||||
} catch (err) {
|
||||
console.error('[ADMIN][DELETE TIER CATEGORY]', err);
|
||||
return R.error(res, 'Could not delete tier category.', 500);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,170 @@
|
||||
'use strict';
|
||||
|
||||
const mdl_TierCategories = require('../../models/tiers/tier_categories.mdl');
|
||||
const mdl_TierPlans = require('../../models/tiers/tier_plans.mdl');
|
||||
const mdl_PlanPolicies = require('../../models/tiers/plan_policies.mdl');
|
||||
const mdl_SystemBadges = require('../../models/system_badges/system_badges.mdl');
|
||||
const Asset = require('../../models/assets/assets.mdl');
|
||||
const R = require('../../utils/response.util');
|
||||
const logActivity = require('../../utils/logActivity.util');
|
||||
|
||||
require('../../models/tiers/tier.associations');
|
||||
|
||||
const VALID_RULE_TYPES = new Set([
|
||||
'course_subscription_access',
|
||||
'required_active_tier',
|
||||
'group_restriction',
|
||||
]);
|
||||
|
||||
async function validateRules(rules) {
|
||||
if (!Array.isArray(rules)) return 'access_rules must be an array.';
|
||||
|
||||
// Load valid tier slugs dynamically from DB
|
||||
const categories = await mdl_TierCategories.findAll({ attributes: ['slug'] });
|
||||
const validSlugs = new Set(categories.map((c) => c.slug));
|
||||
|
||||
for (const rule of rules) {
|
||||
if (!VALID_RULE_TYPES.has(rule.type)) return `Unknown rule type: ${rule.type}`;
|
||||
|
||||
if (rule.type === 'course_subscription_access') {
|
||||
if (!Array.isArray(rule.levels) || !rule.levels.length)
|
||||
return 'course_subscription_access.levels must be a non-empty array of tier slugs.';
|
||||
}
|
||||
|
||||
if (rule.type === 'required_active_tier') {
|
||||
if (!rule.tier || !validSlugs.has(rule.tier))
|
||||
return `required_active_tier.tier must be a valid tier category slug.`;
|
||||
}
|
||||
|
||||
if (rule.type === 'group_restriction') {
|
||||
if (!Array.isArray(rule.group_ids))
|
||||
return 'group_restriction.group_ids must be an array.';
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const ASSET_ATTRS = ['asset_id', 'file_url', 'display_name', 'mime_type'];
|
||||
|
||||
// ─── PLAN POLICIES ────────────────────────────────────────────────────────────
|
||||
|
||||
exports.getPlanPolicy = async (req, res) => {
|
||||
try {
|
||||
const plan = await mdl_TierPlans.findByPk(req.params.planId);
|
||||
if (!plan) return R.error(res, 'Plan not found.', 404);
|
||||
|
||||
const policy = await mdl_PlanPolicies.findOne({ where: { plan_id: req.params.planId } });
|
||||
return R.success(res, 'Policy retrieved.', policy ?? null);
|
||||
} catch (err) {
|
||||
console.error('[ADMIN][GET PLAN POLICY]', err);
|
||||
return R.error(res, 'Could not retrieve policy.', 500);
|
||||
}
|
||||
};
|
||||
|
||||
exports.upsertPlanPolicy = async (req, res) => {
|
||||
try {
|
||||
const { planId } = req.params;
|
||||
|
||||
const plan = await mdl_TierPlans.findByPk(planId);
|
||||
if (!plan) return R.error(res, 'Plan not found.', 404);
|
||||
|
||||
const { access_rules } = req.body;
|
||||
|
||||
let parsedRules = [];
|
||||
if (access_rules !== undefined) {
|
||||
try {
|
||||
parsedRules = typeof access_rules === 'string' ? JSON.parse(access_rules) : access_rules;
|
||||
} catch {
|
||||
return R.error(res, 'access_rules is not valid JSON.', 400);
|
||||
}
|
||||
const err = await validateRules(parsedRules);
|
||||
if (err) return R.error(res, err, 400);
|
||||
}
|
||||
|
||||
let existing = await mdl_PlanPolicies.findOne({ where: { plan_id: planId } });
|
||||
|
||||
const payload = {
|
||||
plan_id: planId,
|
||||
access_rules: access_rules !== undefined ? parsedRules : (existing?.access_rules ?? []),
|
||||
};
|
||||
|
||||
if (!existing) {
|
||||
existing = await mdl_PlanPolicies.create(payload);
|
||||
logActivity(req.user?.user_id, 'create_plan_policy', { entityType: 'plan_policy', details: { plan_id: planId } });
|
||||
} else {
|
||||
await existing.update(payload);
|
||||
logActivity(req.user?.user_id, 'update_plan_policy', { entityType: 'plan_policy', details: { plan_id: planId } });
|
||||
}
|
||||
|
||||
const result = await mdl_PlanPolicies.findOne({ where: { plan_id: planId } });
|
||||
return R.success(res, 'Policy saved.', result);
|
||||
} catch (err) {
|
||||
console.error('[ADMIN][UPSERT PLAN POLICY]', err);
|
||||
return R.error(res, 'Could not save policy.', 500);
|
||||
}
|
||||
};
|
||||
|
||||
// ─── SYSTEM BADGES ────────────────────────────────────────────────────────────
|
||||
|
||||
exports.getSystemBadges = async (req, res) => {
|
||||
try {
|
||||
const badges = await mdl_SystemBadges.findAll({
|
||||
include: [{ model: Asset, as: 'asset', attributes: ASSET_ATTRS, required: false }],
|
||||
order: [['key', 'ASC']],
|
||||
});
|
||||
return R.success(res, 'System badges retrieved.', badges);
|
||||
} catch (err) {
|
||||
console.error('[ADMIN][GET SYSTEM BADGES]', err);
|
||||
return R.error(res, 'Could not retrieve system badges.', 500);
|
||||
}
|
||||
};
|
||||
|
||||
exports.getSystemBadge = async (req, res) => {
|
||||
try {
|
||||
const badge = await mdl_SystemBadges.findOne({
|
||||
where: { key: req.params.key },
|
||||
include: [{ model: Asset, as: 'asset', attributes: ASSET_ATTRS, required: false }],
|
||||
});
|
||||
if (!badge) return R.error(res, 'System badge not found.', 404);
|
||||
return R.success(res, 'System badge retrieved.', badge);
|
||||
} catch (err) {
|
||||
console.error('[ADMIN][GET SYSTEM BADGE]', err);
|
||||
return R.error(res, 'Could not retrieve system badge.', 500);
|
||||
}
|
||||
};
|
||||
|
||||
exports.upsertSystemBadge = async (req, res) => {
|
||||
try {
|
||||
const { key } = req.params;
|
||||
const { asset_id, label, description, information, active_from, active_until } = req.body;
|
||||
|
||||
let existing = await mdl_SystemBadges.findOne({ where: { key } });
|
||||
|
||||
const payload = {
|
||||
key,
|
||||
asset_id: asset_id !== undefined ? (asset_id || null) : existing?.asset_id ?? null,
|
||||
label: label ?? existing?.label ?? key,
|
||||
description: description ?? existing?.description ?? null,
|
||||
information: information ?? existing?.information ?? null,
|
||||
active_from: active_from !== undefined ? (active_from || null) : existing?.active_from ?? null,
|
||||
active_until: active_until !== undefined ? (active_until || null) : existing?.active_until ?? null,
|
||||
};
|
||||
|
||||
if (!existing) {
|
||||
existing = await mdl_SystemBadges.create(payload);
|
||||
logActivity(req.user?.user_id, 'create_system_badge', { entityType: 'system_badge', details: { key } });
|
||||
} else {
|
||||
await existing.update(payload);
|
||||
logActivity(req.user?.user_id, 'update_system_badge', { entityType: 'system_badge', details: { key } });
|
||||
}
|
||||
|
||||
const result = await mdl_SystemBadges.findOne({
|
||||
where: { key },
|
||||
include: [{ model: Asset, as: 'asset', attributes: ASSET_ATTRS, required: false }],
|
||||
});
|
||||
return R.success(res, 'System badge saved.', result);
|
||||
} catch (err) {
|
||||
console.error('[ADMIN][UPSERT SYSTEM BADGE]', err);
|
||||
return R.error(res, 'Could not save system badge.', 500);
|
||||
}
|
||||
};
|
||||
@@ -10,10 +10,11 @@
|
||||
***********************************************************************************************************************************************************************/
|
||||
const { Op } = require('sequelize');
|
||||
|
||||
const mdl_TierPlans = require('../../models/tiers/tier_plans.mdl');
|
||||
const mdl_UserTiers = require('../../models/tiers/user_tiers.mdl');
|
||||
const mdl_Payments = require('../../models/tiers/payments.mdl');
|
||||
const mdl_Users = require('../../models/users/users.mdl');
|
||||
const mdl_TierCategories = require('../../models/tiers/tier_categories.mdl');
|
||||
const mdl_TierPlans = require('../../models/tiers/tier_plans.mdl');
|
||||
const mdl_UserTiers = require('../../models/tiers/user_tiers.mdl');
|
||||
const mdl_Payments = require('../../models/tiers/payments.mdl');
|
||||
const mdl_Users = require('../../models/users/users.mdl');
|
||||
const mdl_PlanCourses = require('../../models/tiers/plan_courses.mdl');
|
||||
const { Course } = require('../../models/courses/courses.mdl');
|
||||
|
||||
@@ -84,14 +85,24 @@ exports.getPlan = async (req, res) => {
|
||||
|
||||
exports.createPlan = async (req, res) => {
|
||||
try {
|
||||
const { tier, label, duration_days, price, currency } = req.body;
|
||||
if (!tier || !label || !duration_days || !price)
|
||||
return R.error(res, 'tier, label, duration_days, and price are required.', 400);
|
||||
const { tier_category_id, label, duration_days, price, currency } = req.body;
|
||||
if (!tier_category_id || !label || !duration_days || !price)
|
||||
return R.error(res, 'tier_category_id, label, duration_days, and price are required.', 400);
|
||||
|
||||
const plan = await mdl_TierPlans.create({ tier, label, duration_days, price, currency });
|
||||
const category = await mdl_TierCategories.findByPk(tier_category_id);
|
||||
if (!category || !category.is_active)
|
||||
return R.error(res, 'Tier category not found or inactive.', 404);
|
||||
|
||||
if (category.is_default)
|
||||
return R.error(res, 'Plans cannot be created under the default (Free) tier. Free access is automatic.', 400);
|
||||
|
||||
const plan = await mdl_TierPlans.create({
|
||||
tier_category_id: category.tier_category_id,
|
||||
tier: category.slug,
|
||||
label, duration_days, price, currency,
|
||||
});
|
||||
const plain = plan.get({ plain: true });
|
||||
logActivity(req.user?.user_id, 'create_tier_plan', { entityType: 'tier_plan', details: { label: plain.label, tier: plain.tier } });
|
||||
// Serialize plan_id as string — CockroachDB BigInts exceed JS Number.MAX_SAFE_INTEGER
|
||||
return R.success(res, 'Plan created.', { ...plain, plan_id: String(plain.plan_id) }, 201);
|
||||
} catch (err) {
|
||||
console.error('[ADMIN][CREATE PLAN]', err);
|
||||
@@ -104,9 +115,21 @@ exports.updatePlan = async (req, res) => {
|
||||
const plan = await mdl_TierPlans.findByPk(req.params.id);
|
||||
if (!plan) return R.error(res, 'Plan not found.', 404);
|
||||
|
||||
const allowed = ['label', 'duration_days', 'price', 'currency', 'is_active'];
|
||||
const allowed = ['label', 'duration_days', 'price', 'currency', 'is_active', 'tier_category_id'];
|
||||
const updates = {};
|
||||
allowed.forEach((k) => { if (req.body[k] !== undefined) updates[k] = req.body[k]; });
|
||||
for (const k of allowed) {
|
||||
if (req.body[k] !== undefined) updates[k] = req.body[k];
|
||||
}
|
||||
|
||||
// If tier_category_id is being changed, sync the tier slug
|
||||
if (updates.tier_category_id) {
|
||||
const category = await mdl_TierCategories.findByPk(updates.tier_category_id);
|
||||
if (!category || !category.is_active)
|
||||
return R.error(res, 'Tier category not found or inactive.', 404);
|
||||
if (category.is_default)
|
||||
return R.error(res, 'Plans cannot be moved to the Free tier category.', 400);
|
||||
updates.tier = category.slug;
|
||||
}
|
||||
|
||||
await plan.update(updates);
|
||||
logActivity(req.user?.user_id, 'update_tier_plan', { entityType: 'tier_plan', details: { label: plan.label } });
|
||||
@@ -234,16 +257,16 @@ exports.getUserTiers = async (req, res) => {
|
||||
|
||||
exports.grantTier = async (req, res) => {
|
||||
try {
|
||||
const { user_id, tier, plan_id, notes } = req.body;
|
||||
if (!user_id || !tier || !plan_id)
|
||||
return R.error(res, 'user_id, tier, and plan_id are required.', 400);
|
||||
const { user_id, plan_id, notes } = req.body;
|
||||
if (!user_id || !plan_id)
|
||||
return R.error(res, 'user_id and plan_id are required.', 400);
|
||||
|
||||
const user = await mdl_Users.findByPk(user_id);
|
||||
if (!user) return R.error(res, 'User not found.', 404);
|
||||
|
||||
const plan = await mdl_TierPlans.findByPk(plan_id);
|
||||
if (!plan || !plan.is_active) return R.error(res, 'Plan not found or inactive.', 404);
|
||||
if (plan.tier !== tier) return R.error(res, 'Plan tier mismatch.', 400);
|
||||
const tier = plan.tier;
|
||||
|
||||
await mdl_UserTiers.update(
|
||||
{ status: 'expired' },
|
||||
@@ -254,7 +277,7 @@ exports.grantTier = async (req, res) => {
|
||||
const expiresAt = new Date(startsAt.getTime() + plan.duration_days * 86400000);
|
||||
|
||||
const newTier = await mdl_UserTiers.create({
|
||||
user_id, tier, status: 'active',
|
||||
user_id, tier, plan_id, status: 'active',
|
||||
starts_at: startsAt,
|
||||
expires_at: expiresAt,
|
||||
granted_by: req.user.user_id,
|
||||
|
||||
@@ -286,14 +286,28 @@ exports.getUsersNotInGroup = async (req, res) => {
|
||||
try {
|
||||
const { gid: group_id } = req.params;
|
||||
|
||||
// Exclude users already in THIS group
|
||||
const members = await mdl_UserGroupMembers.findAll({ where: { group_id }, attributes: ['user_id'] });
|
||||
const memberIds = members.map((m) => m.user_id);
|
||||
|
||||
const users = await mdl_Users.findAll({
|
||||
where: { user_id: { [Op.notIn]: memberIds.length ? memberIds : [0] } },
|
||||
where: { user_id: { [Op.notIn]: memberIds.length ? memberIds : [0] } },
|
||||
attributes: [
|
||||
'user_id',
|
||||
[Sequelize.literal(`("User"."personal_info"->'name'->>'full_name')`), 'full_name'],
|
||||
// All active groups this user belongs to (excluding NOGRP), comma-separated
|
||||
[
|
||||
Sequelize.literal(`(
|
||||
SELECT STRING_AGG(ug.name || ' (' || ug.group_code || ')', ', ' ORDER BY ug.name)
|
||||
FROM user_group_members ugm
|
||||
JOIN user_groups ug ON ug.group_id = ugm.group_id
|
||||
WHERE ugm.user_id = "User".user_id
|
||||
AND ugm."deletedAt" IS NULL
|
||||
AND ug."deletedAt" IS NULL
|
||||
AND ug.group_code != 'NOGRP'
|
||||
)`),
|
||||
'current_group',
|
||||
],
|
||||
],
|
||||
});
|
||||
|
||||
|
||||
@@ -14,9 +14,11 @@ const crypto = require('crypto');
|
||||
const mdl_Users = require('../../models/users/users.mdl');
|
||||
const mdl_UserSessions = require('../../models/users/user_sessions.mdl');
|
||||
const mdl_Achievements = require('../../models/users/achievements.mdl');
|
||||
const mdl_UserBans = require('../../models/users/user_bans.mdl');
|
||||
const { mdl_UserGroups, mdl_UserGroupMembers } = require('../../models/users/user_groups.mdl');
|
||||
|
||||
const { sendEmail } = require('../../services/email.service');
|
||||
const { fmtDate } = require('../../utils/datetime.util');
|
||||
const logActivity = require('../../utils/logActivity.util');
|
||||
const R = require('../../utils/response.util');
|
||||
const { paginate } = require('../../utils/paginate.util');
|
||||
@@ -383,4 +385,288 @@ exports.getUserAchievements = async (req, res) => {
|
||||
console.error('[ADMIN][GET USER ACHIEVEMENTS]', err);
|
||||
return R.error(res, 'Could not retrieve achievements.', 500);
|
||||
}
|
||||
};
|
||||
|
||||
// ─── BAN USER ─────────────────────────────────────────────────────────────────
|
||||
|
||||
exports.banUser = async (req, res) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
if (Number(id) === req.user.user_id)
|
||||
return R.error(res, 'You cannot ban your own account.', 400);
|
||||
|
||||
const user = await mdl_Users.findByPk(id);
|
||||
if (!user) return R.error(res, 'User not found.', 404);
|
||||
if (user.is_banned) return R.error(res, 'User is already banned.', 400);
|
||||
|
||||
const { reason, ban_type, expires_at } = req.body;
|
||||
|
||||
if (!reason?.trim()) return R.error(res, 'Ban reason is required.', 400);
|
||||
if (!['temporary', 'permanent'].includes(ban_type))
|
||||
return R.error(res, 'Invalid ban type. Must be "temporary" or "permanent".', 400);
|
||||
if (ban_type === 'temporary' && !expires_at)
|
||||
return R.error(res, 'Expiry date is required for temporary bans.', 400);
|
||||
if (ban_type === 'temporary' && new Date(expires_at) <= new Date())
|
||||
return R.error(res, 'Expiry date must be in the future.', 400);
|
||||
|
||||
const banExpiresAt = ban_type === 'temporary' ? new Date(expires_at) : null;
|
||||
|
||||
await sequelize.transaction(async (t) => {
|
||||
await mdl_UserBans.create({
|
||||
user_id: id,
|
||||
banned_by: req.user.user_id,
|
||||
reason: reason.trim(),
|
||||
ban_type,
|
||||
banned_at: new Date(),
|
||||
expires_at: banExpiresAt,
|
||||
}, { transaction: t });
|
||||
|
||||
await user.update({ is_banned: true, ban_expires_at: banExpiresAt }, { transaction: t });
|
||||
|
||||
await mdl_UserSessions.update(
|
||||
{ is_active: false, logout_info: { date: new Date().toISOString(), forced_by: req.user.user_id } },
|
||||
{ where: { user_id: id }, transaction: t }
|
||||
);
|
||||
});
|
||||
|
||||
logActivity(req.user.user_id, 'ban_user', {
|
||||
entityType: 'user',
|
||||
entityId: Number(id),
|
||||
details: { reason: reason.trim(), ban_type, expires_at: banExpiresAt },
|
||||
});
|
||||
|
||||
sendEmail({
|
||||
to: user.email,
|
||||
type: 'BANNED',
|
||||
data: {
|
||||
name: user.personal_info?.name?.full_name ?? 'User',
|
||||
email: user.email,
|
||||
date: fmtDate(new Date()),
|
||||
reason: reason.trim(),
|
||||
ban_type,
|
||||
},
|
||||
}).catch((err) => console.error('[ADMIN][BAN USER] Email failed:', err));
|
||||
|
||||
return R.success(res, 'User banned successfully.');
|
||||
} catch (err) {
|
||||
console.error('[ADMIN][BAN USER]', err);
|
||||
return R.error(res, 'Could not ban user.', 500);
|
||||
}
|
||||
};
|
||||
|
||||
// ─── UNBAN USER ───────────────────────────────────────────────────────────────
|
||||
|
||||
exports.unbanUser = async (req, res) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
const user = await mdl_Users.findByPk(id);
|
||||
if (!user) return R.error(res, 'User not found.', 404);
|
||||
if (!user.is_banned) return R.error(res, 'User is not currently banned.', 400);
|
||||
|
||||
const { lift_reason } = req.body;
|
||||
|
||||
const activeBan = await mdl_UserBans.findOne({
|
||||
where: { user_id: id, is_lifted: false },
|
||||
order: [['banned_at', 'DESC']],
|
||||
});
|
||||
|
||||
await sequelize.transaction(async (t) => {
|
||||
if (activeBan) {
|
||||
await activeBan.update({
|
||||
is_lifted: true,
|
||||
lifted_at: new Date(),
|
||||
lifted_by: req.user.user_id,
|
||||
lift_reason: lift_reason?.trim() || null,
|
||||
}, { transaction: t });
|
||||
}
|
||||
|
||||
await user.update({ is_banned: false, ban_expires_at: null }, { transaction: t });
|
||||
});
|
||||
|
||||
logActivity(req.user.user_id, 'unban_user', { entityType: 'user', entityId: Number(id) });
|
||||
|
||||
sendEmail({
|
||||
to: user.email,
|
||||
type: 'BAN_LIFTED',
|
||||
data: {
|
||||
name: user.personal_info?.name?.full_name ?? 'User',
|
||||
email: user.email,
|
||||
date: fmtDate(new Date()),
|
||||
},
|
||||
}).catch((err) => console.error('[ADMIN][UNBAN USER] Email failed:', err));
|
||||
|
||||
return R.success(res, 'User unbanned successfully.');
|
||||
} catch (err) {
|
||||
console.error('[ADMIN][UNBAN USER]', err);
|
||||
return R.error(res, 'Could not unban user.', 500);
|
||||
}
|
||||
};
|
||||
|
||||
// ─── BULK BAN ─────────────────────────────────────────────────────────────────
|
||||
|
||||
exports.bulkBanUsers = async (req, res) => {
|
||||
try {
|
||||
const { ids, reason, ban_type, expires_at } = req.body;
|
||||
|
||||
if (!Array.isArray(ids) || !ids.length)
|
||||
return R.error(res, 'No user IDs provided.', 400);
|
||||
if (ids.includes(req.user.user_id))
|
||||
return R.error(res, 'You cannot ban your own account.', 400);
|
||||
if (!reason?.trim()) return R.error(res, 'Ban reason is required.', 400);
|
||||
if (!['temporary', 'permanent'].includes(ban_type))
|
||||
return R.error(res, 'Invalid ban type.', 400);
|
||||
if (ban_type === 'temporary' && !expires_at)
|
||||
return R.error(res, 'Expiry date is required for temporary bans.', 400);
|
||||
if (ban_type === 'temporary' && new Date(expires_at) <= new Date())
|
||||
return R.error(res, 'Expiry date must be in the future.', 400);
|
||||
|
||||
const users = await mdl_Users.findAll({ where: { user_id: ids } });
|
||||
if (!users.length) return R.error(res, 'No users found.', 404);
|
||||
|
||||
const unbannedUsers = users.filter((u) => !u.is_banned);
|
||||
if (!unbannedUsers.length)
|
||||
return R.error(res, 'All selected users are already banned.', 400);
|
||||
|
||||
const targetIds = unbannedUsers.map((u) => u.user_id);
|
||||
const banExpiresAt = ban_type === 'temporary' ? new Date(expires_at) : null;
|
||||
const now = new Date();
|
||||
|
||||
await sequelize.transaction(async (t) => {
|
||||
await mdl_UserBans.bulkCreate(
|
||||
targetIds.map((uid) => ({
|
||||
user_id: uid,
|
||||
banned_by: req.user.user_id,
|
||||
reason: reason.trim(),
|
||||
ban_type,
|
||||
banned_at: now,
|
||||
expires_at: banExpiresAt,
|
||||
})),
|
||||
{ transaction: t }
|
||||
);
|
||||
|
||||
await mdl_Users.update(
|
||||
{ is_banned: true, ban_expires_at: banExpiresAt },
|
||||
{ where: { user_id: targetIds }, transaction: t }
|
||||
);
|
||||
|
||||
await mdl_UserSessions.update(
|
||||
{ is_active: false, logout_info: { date: now.toISOString(), forced_by: req.user.user_id } },
|
||||
{ where: { user_id: targetIds }, transaction: t }
|
||||
);
|
||||
});
|
||||
|
||||
const dateStr = fmtDate(new Date());
|
||||
unbannedUsers.forEach((u) => {
|
||||
sendEmail({
|
||||
to: u.email,
|
||||
type: 'BANNED',
|
||||
data: {
|
||||
name: u.personal_info?.name?.full_name ?? 'User',
|
||||
email: u.email,
|
||||
date: dateStr,
|
||||
reason: reason.trim(),
|
||||
ban_type,
|
||||
},
|
||||
}).catch((err) => console.error('[ADMIN][BULK BAN] Email failed:', u.email, err));
|
||||
});
|
||||
|
||||
return R.success(res, `${targetIds.length} user(s) banned successfully.`, {
|
||||
banned_ids: targetIds,
|
||||
skipped_ids: ids.filter((id) => !targetIds.includes(Number(id))),
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('[ADMIN][BULK BAN USERS]', err);
|
||||
return R.error(res, 'Could not ban users.', 500);
|
||||
}
|
||||
};
|
||||
|
||||
// ─── GET USER BAN HISTORY ─────────────────────────────────────────────────────
|
||||
|
||||
exports.getUserBans = async (req, res) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
const user = await mdl_Users.findByPk(id, { attributes: ['user_id'] });
|
||||
if (!user) return R.error(res, 'User not found.', 404);
|
||||
|
||||
const bans = await mdl_UserBans.findAll({
|
||||
where: { user_id: id },
|
||||
include: [
|
||||
{ model: mdl_Users, as: 'banner', attributes: ['user_id', 'email', 'personal_info'] },
|
||||
{ model: mdl_Users, as: 'lifter', attributes: ['user_id', 'email', 'personal_info'] },
|
||||
],
|
||||
order: [['banned_at', 'DESC']],
|
||||
});
|
||||
|
||||
return R.success(res, 'Ban history retrieved.', bans);
|
||||
} catch (err) {
|
||||
console.error('[ADMIN][GET USER BANS]', err);
|
||||
return R.error(res, 'Could not retrieve ban history.', 500);
|
||||
}
|
||||
};
|
||||
|
||||
// ─── BULK UNBAN ───────────────────────────────────────────────────────────────
|
||||
|
||||
exports.bulkUnbanUsers = async (req, res) => {
|
||||
try {
|
||||
const { ids, lift_reason } = req.body;
|
||||
|
||||
if (!Array.isArray(ids) || !ids.length)
|
||||
return R.error(res, 'No user IDs provided.', 400);
|
||||
|
||||
const users = await mdl_Users.findAll({ where: { user_id: ids } });
|
||||
if (!users.length) return R.error(res, 'No users found.', 404);
|
||||
|
||||
const bannedUsers = users.filter((u) => u.is_banned);
|
||||
if (!bannedUsers.length)
|
||||
return R.error(res, 'None of the selected users are currently banned.', 400);
|
||||
|
||||
const targetIds = bannedUsers.map((u) => u.user_id);
|
||||
const now = new Date();
|
||||
|
||||
await sequelize.transaction(async (t) => {
|
||||
await mdl_UserBans.update(
|
||||
{
|
||||
is_lifted: true,
|
||||
lifted_at: now,
|
||||
lifted_by: req.user.user_id,
|
||||
lift_reason: lift_reason?.trim() || null,
|
||||
},
|
||||
{ where: { user_id: targetIds, is_lifted: false }, transaction: t }
|
||||
);
|
||||
|
||||
await mdl_Users.update(
|
||||
{ is_banned: false, ban_expires_at: null },
|
||||
{ where: { user_id: targetIds }, transaction: t }
|
||||
);
|
||||
});
|
||||
|
||||
logActivity(req.user.user_id, 'bulk_unban_users', {
|
||||
entityType: 'user',
|
||||
details: { unban_ids: targetIds },
|
||||
});
|
||||
|
||||
const dateStr = fmtDate(now);
|
||||
bannedUsers.forEach((u) => {
|
||||
sendEmail({
|
||||
to: u.email,
|
||||
type: 'BAN_LIFTED',
|
||||
data: {
|
||||
name: u.personal_info?.name?.full_name ?? 'User',
|
||||
email: u.email,
|
||||
date: dateStr,
|
||||
},
|
||||
}).catch((err) => console.error('[ADMIN][BULK UNBAN] Email failed:', u.email, err));
|
||||
});
|
||||
|
||||
return R.success(res, `${targetIds.length} user(s) unbanned successfully.`, {
|
||||
unbanned_ids: targetIds,
|
||||
skipped_ids: ids.filter((id) => !targetIds.includes(Number(id))),
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('[ADMIN][BULK UNBAN USERS]', err);
|
||||
return R.error(res, 'Could not unban users.', 500);
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user