This commit is contained in:
rgrgogu
2026-05-23 14:03:38 +08:00
parent b39e7a2939
commit bf48c95467
5 changed files with 175 additions and 87 deletions
+74 -43
View File
@@ -5,6 +5,11 @@
*
* Author: rgrgogu
* Date Created: Oct. 6, 2025
***********************************************************************************************************************************************************************
* Change History:
* DATE AUTHOR LOG DESCRIPTION
* Oct. 6, 2025 rgrgogu 001 Initial creation - STAR Phase 1
* May 23, 2026 rgrgogu 002 Added group_code to createGroup / updateGroup; added generateGroupCode helper
***********************************************************************************************************************************************************************/
const sequelize = require('../../config/db.config');
const { Op, Sequelize } = require('sequelize');
@@ -12,24 +17,38 @@ const { Op, Sequelize } = require('sequelize');
const mdl_Users = require('../../models/users/users.mdl');
const { mdl_UserGroups, mdl_UserGroupMembers } = require('../../models/users/user_groups.mdl');
const R = require('../../utils/response.util');
const { paginate } = require('../../utils/paginate.util');
const { getFieldValues } = require("../../utils/fieldValues.util");
const R = require('../../utils/response.util');
const { paginate } = require('../../utils/paginate.util');
const { getFieldValues } = require('../../utils/fieldValues.util');
const { excludeAttributes: usersExclude, jsonbSchemas: usersSchemas } = require('../../models/users/users.attributes');
const { excludeAttributes: groupExclude, jsonbSchemas: groupSchemas, computedAttributes: groupComputed } = require('../../models/users/user_groups.attributes');
const auditByFields = ['createdBy', 'updatedBy', 'deletedBy'];
// ─── Helper — generate a unique group code ────────────────────────────────────
/**
* Generates a unique group_code in the format: <SLUG>-<4-char hex>
* e.g. "SALES-A3F1", "ONBOARD-Q1-9C2D"
* Retries up to 5 times in the unlikely event of a collision.
*/
const generateGroupCode = async (name) => {
const slug = name.toUpperCase().trim().replace(/\s+/g, '-').replace(/[^A-Z0-9\-]/g, '').slice(0, 20);
for (let i = 0; i < 5; i++) {
const suffix = Math.random().toString(16).slice(2, 6).toUpperCase();
const code = `${slug}-${suffix}`;
const exists = await mdl_UserGroups.findOne({ where: { group_code: code }, paranoid: false });
if (!exists) return code;
}
throw new Error('Could not generate a unique group code after 5 attempts.');
};
// ─── GET ALL ──────────────────────────────────────────────────────────────────
exports.getGroups = async (req, res) => {
try {
const result = await paginate(mdl_UserGroups, req, {
excludeAttributes: groupExclude,
jsonbSchemas: groupSchemas,
computedAttributes: groupComputed,
context: "list",
context: 'list',
auditOptions: { mdl_Users, parentAlias: 'UserGroup' },
});
@@ -41,7 +60,6 @@ exports.getGroups = async (req, res) => {
};
// ─── GET ONE ──────────────────────────────────────────────────────────────────
exports.getGroup = async (req, res) => {
try {
const group = await mdl_UserGroups.findByPk(req.params.gid);
@@ -52,13 +70,13 @@ exports.getGroup = async (req, res) => {
jsonbSchemas: usersSchemas,
jsonbColumn: 'personal_info',
auditOptions: { mdl_Users, parentAlias: 'User' },
context: "list",
context: 'list',
findOptions: {
include: [{
model: mdl_UserGroupMembers,
where: { group_id: req.params.gid },
model: mdl_UserGroupMembers,
where: { group_id: req.params.gid },
attributes: [],
required: true,
required: true,
}],
},
});
@@ -71,14 +89,25 @@ exports.getGroup = async (req, res) => {
};
// ─── CREATE ───────────────────────────────────────────────────────────────────
exports.createGroup = async (req, res) => {
try {
const { name, description } = req.body;
const { name, description, group_code } = req.body;
if (!name) return R.error(res, 'Group name is required.', 400);
// Use provided group_code (uppercased via model hook), otherwise auto-generate
const code = group_code
? group_code.toUpperCase().trim()
: await generateGroupCode(name);
// Check uniqueness explicitly so we return a clear error message
const duplicate = await mdl_UserGroups.findOne({ where: { group_code: code }, paranoid: false });
if (duplicate) return R.error(res, `Group code "${code}" is already in use.`, 409);
const group = await mdl_UserGroups.create({
name, description, createdBy: req.user.user_id,
name,
description,
group_code: code,
createdBy: req.user.user_id,
});
return R.success(res, 'Group created.', group, 201);
@@ -89,15 +118,26 @@ exports.createGroup = async (req, res) => {
};
// ─── UPDATE ───────────────────────────────────────────────────────────────────
exports.updateGroup = async (req, res) => {
try {
const group = await mdl_UserGroups.findByPk(req.params.gid);
if (!group) return R.error(res, 'Group not found.', 404);
const { name, description } = req.body;
const { name, description, group_code } = req.body;
if (name !== undefined) group.name = name;
if (description !== undefined) group.description = description;
if (group_code !== undefined) {
const code = group_code.toUpperCase().trim();
const duplicate = await mdl_UserGroups.findOne({
where: { group_code: code, group_id: { [Op.ne]: group.group_id } },
paranoid: false,
});
if (duplicate) return R.error(res, `Group code "${code}" is already in use.`, 409);
group.group_code = code;
}
group.updatedBy = req.user.user_id;
await group.save();
@@ -109,11 +149,10 @@ exports.updateGroup = async (req, res) => {
};
// ─── DEACTIVATE ───────────────────────────────────────────────────────────────
exports.deactivateGroup = async (req, res) => {
try {
const group = await mdl_UserGroups.findByPk(req.params.gid);
if (!group) return R.error(res, 'Group not found.', 404);
if (!group) return R.error(res, 'Group not found.', 404);
if (!group.is_active) return R.error(res, 'Group is already deactivated.', 400);
await group.update({ is_active: false, updatedBy: req.user.user_id, deletedBy: req.user.user_id });
@@ -127,13 +166,10 @@ exports.deactivateGroup = async (req, res) => {
};
// ─── RESTORE ──────────────────────────────────────────────────────────────────
exports.restoreGroup = async (req, res) => {
try {
const group = await mdl_UserGroups.findOne({
where: { group_id: req.params.gid }, paranoid: false,
});
if (!group) return R.error(res, 'Group not found.', 404);
const group = await mdl_UserGroups.findOne({ where: { group_id: req.params.gid }, paranoid: false });
if (!group) return R.error(res, 'Group not found.', 404);
if (group.is_active) return R.error(res, 'Group is already active.', 400);
await group.restore();
@@ -147,14 +183,13 @@ exports.restoreGroup = async (req, res) => {
};
// ─── BULK DEACTIVATE ──────────────────────────────────────────────────────────
exports.bulkDeactivateGroups = async (req, res) => {
try {
const { ids } = req.body;
if (!Array.isArray(ids) || !ids.length)
return R.error(res, 'No group IDs provided.', 400);
const groups = await mdl_UserGroups.findAll({ where: { group_id: ids } });
const groups = await mdl_UserGroups.findAll({ where: { group_id: ids } });
if (!groups.length) return R.error(res, 'No groups found.', 404);
const activeGroups = groups.filter((g) => g.is_active && !g.deletedAt);
@@ -180,15 +215,14 @@ exports.bulkDeactivateGroups = async (req, res) => {
};
// ─── BULK RESTORE ─────────────────────────────────────────────────────────────
exports.bulkRestoreGroups = async (req, res) => {
try {
const { ids } = req.body;
if (!Array.isArray(ids) || !ids.length)
return R.error(res, 'No group IDs provided.', 400);
const groups = await mdl_UserGroups.findAll({ where: { group_id: ids }, paranoid: false });
if (!groups.length) return R.error(res, 'No groups found.', 404);
const groups = await mdl_UserGroups.findAll({ where: { group_id: ids }, paranoid: false });
if (!groups.length) return R.error(res, 'No groups found.', 404);
const deletedGroups = groups.filter((g) => g.deletedAt);
if (!deletedGroups.length)
@@ -213,14 +247,13 @@ exports.bulkRestoreGroups = async (req, res) => {
};
// ─── ARCHIVED ─────────────────────────────────────────────────────────────────
exports.getArchivedGroups = async (req, res) => {
try {
const result = await paginate(mdl_UserGroups, req, {
excludeAttributes: groupExclude,
jsonbSchemas: groupSchemas,
computedAttributes: groupComputed,
context: "archived",
context: 'archived',
auditOptions: { mdl_Users, parentAlias: 'UserGroup' },
findOptions: {
paranoid: false,
@@ -236,14 +269,12 @@ exports.getArchivedGroups = async (req, res) => {
};
// ─── FIELD VALUES ─────────────────────────────────────────────────────────────
exports.getGroupFieldValues = getFieldValues(mdl_UserGroups, "GROUP", {
blockedFields: ["deletedAt"],
exports.getGroupFieldValues = getFieldValues(mdl_UserGroups, 'GROUP', {
blockedFields: ['deletedAt'],
paranoid: false,
});
// ─── MEMBERSHIP ───────────────────────────────────────────────────────────────
exports.getUsersNotInGroup = async (req, res) => {
try {
const { gid: group_id } = req.params;
@@ -252,7 +283,7 @@ exports.getUsersNotInGroup = async (req, res) => {
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'],
@@ -272,9 +303,9 @@ exports.getUsersInGroup = async (req, res) => {
const group = await mdl_UserGroups.findByPk(group_id, {
include: [{
model: mdl_Users,
as: 'members',
through: { attributes: [] },
model: mdl_Users,
as: 'members',
through: { attributes: [] },
attributes: [
'user_id',
[Sequelize.literal(`("members"."personal_info"->'name'->>'full_name')`), 'full_name'],
@@ -293,14 +324,14 @@ exports.getUsersInGroup = async (req, res) => {
exports.addUserToGroup = async (req, res) => {
try {
const { gid: group_id } = req.params;
const { user_ids } = req.body;
const { user_ids } = req.body;
if (!Array.isArray(user_ids) || !user_ids.length)
return R.error(res, 'No users provided.', 400);
const existingUsers = await mdl_Users.findAll({ where: { user_id: user_ids }, attributes: ['user_id'] });
const existingIds = existingUsers.map((u) => u.user_id);
const notFound = user_ids.filter((id) => !existingIds.includes(id));
const existingUsers = await mdl_Users.findAll({ where: { user_id: user_ids }, attributes: ['user_id'] });
const existingIds = existingUsers.map((u) => u.user_id);
const notFound = user_ids.filter((id) => !existingIds.includes(id));
if (notFound.length)
return R.error(res, `Users not found: ${notFound.join(', ')}`, 404);
@@ -325,7 +356,7 @@ exports.addUserToGroup = async (req, res) => {
exports.removeUserFromGroup = async (req, res) => {
try {
const { gid: group_id } = req.params;
const { user_ids } = req.body;
const { user_ids } = req.body;
if (!Array.isArray(user_ids) || !user_ids.length)
return R.error(res, 'No users provided.', 400);