Service Design Specification
tutorhub-tutorcatalog-service documentation
Version: 1.0.45
Scope
This document provides a structured architectural overview of the tutorCatalog microservice, detailing its configuration, data model, authorization logic, business rules, and API design. It has been automatically generated based on the service definition within Mindbricks, ensuring that the information reflects the source of truth used during code generation and deployment.
The document is intended to serve multiple audiences:
- Service architects can use it to validate design decisions and ensure alignment with broader architectural goals.
- Developers and maintainers will find it useful for understanding the structure and behavior of the service, facilitating easier debugging, feature extension, and integration with other systems.
- Stakeholders and reviewers can use it to gain a clear understanding of the service’s capabilities and domain logic.
Note for Frontend Developers: While this document is valuable for understanding business logic and data interactions, please refer to the Service API Documentation for endpoint-level specifications and integration details.
Note for Backend Developers: Since the code for this service is automatically generated by Mindbricks, you typically won’t need to implement or modify it manually. However, this document is especially valuable when you’re building other services—whether within Mindbricks or externally—that need to interact with or depend on this service. It provides a clear reference to the service’s data contracts, business rules, and API structure, helping ensure compatibility and correct integration.
TutorCatalog Service Settings
Handles tutor public profiles, course packs, public categories, and course pack materials with strict public/private access enforcement for course pack content and materials.
Service Overview
This service is configured to listen for HTTP requests on port 3000,
serving both the main API interface and default administrative endpoints.
The following routes are available by default:
- API Test Interface (API Face):
/ - Swagger Documentation:
/swagger - Postman Collection Download:
/getPostmanCollection - Health Checks:
/healthand/admin/health - Current Session Info:
/currentuser - Favicon:
/favicon.ico
The service uses a PostgreSQL database for data storage, with the database name set to tutorhub-tutorcatalog-service.
This service is accessible via the following environment-specific URLs:
- Preview:
https://tutorhub.prw.mindbricks.com/tutorcatalog-api - Staging:
https://tutorhub-stage.mindbricks.co/tutorcatalog-api - Production:
https://tutorhub.mindbricks.co/tutorcatalog-api
Authentication & Security
- Login Required: No
This service does not require user authentication for access. It is designed to be publicly accessible, allowing anonymous users to interact with its endpoints. However, certain CRUD routes may still require login based on their specific configurations.
Service Data Objects
The service uses a PostgreSQL database for data storage, with the database name set to tutorhub-tutorcatalog-service.
Data deletion is managed using a soft delete strategy. Instead of removing records from the database, they are flagged as inactive by setting the isActive field to false.
| Object Name | Description | Public Access |
|---|---|---|
tutorProfile |
Public-facing profile for a tutor, includes certifications, experience, subjects, bio, and photo. | accessPublic |
coursePack |
Publicly listed course pack/structured course offered by a tutor. | accessPrivate |
courseMaterial |
Material (file, video, link, doc) attached to coursePack. Only visible to the owning tutor and students enrolled in the course pack. | accessPrivate |
courseCategory |
Represents a course subject/category; used for filtering and navigation. Admin-maintained. | accessPublic |
tutorProfile Data Object
Object Overview
Description: Public-facing profile for a tutor, includes certifications, experience, subjects, bio, and photo.
This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement.
It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.
Core Configuration
- Soft Delete: Enabled — Determines whether records are marked inactive (
isActive = false) instead of being physically deleted. - Public Access: accessPublic — If enabled, anonymous users may access this object’s data depending on API-level rules.
Properties Schema
| Property | Type | Required | Description |
|---|---|---|---|
tutorId |
ID | Yes | - |
certifications |
String | No | Tutor's certifications (list of certificates, degrees, etc.). |
experience |
Text | No | Brief experience summary or bio. |
subjects |
String | No | Areas of expertise/subjects offered for teaching. |
bio |
Text | No | Optional full-length bio/description. |
profilePhoto |
String | No | Public profile photo URL (may be external or uploaded). |
profileStatus |
Enum | Yes | - |
displayName |
String | No | Tutor's display name, copied from auth user fullname at profile creation. |
- Required properties are mandatory for creating objects and must be provided in the request body if no default value is set.
Array Properties
certifications subjects
Array properties can hold multiple values and are indicated by the [] suffix in their type. Avoid using arrays in properties that are used for relations, as they will not work correctly.
Note that using connection objects instead of arrays is recommended for relations, as they provide better performance and flexibility.
Default Values
Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.
- tutorId: ‘00000000-0000-0000-0000-000000000000’
- profileStatus: pending
Auto Update Properties
tutorId certifications experience subjects bio profilePhoto profileStatus displayName
An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body.
If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false.
These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.
Enum Properties
Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.
- profileStatus: [pending, approved, rejected]
Elastic Search Indexing
tutorId certifications experience subjects bio profilePhoto profileStatus displayName
Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.
Database Indexing
tutorId profileStatus
Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.
Unique Properties
tutorId
Unique properties are enforced to have distinct values across all instances of the data object, preventing duplicate entries.
Note that a unique property is automatically indexed in the database so you will not need to set the Indexed in DB option.
Secondary Key Properties
tutorId
Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.
Relation Properties
tutorId
Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.
- tutorId: ID
Relation to
user.id
The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.
On Delete: Set Null Required: Yes
Filter Properties
tutorId profileStatus
Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.
-
tutorId: ID has a filter named
tutorId -
profileStatus: Enum has a filter named
profileStatus
coursePack Data Object
Object Overview
Description: Publicly listed course pack/structured course offered by a tutor.
This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement.
It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.
Core Configuration
- Soft Delete: Enabled — Determines whether records are marked inactive (
isActive = false) instead of being physically deleted. - Public Access: accessPrivate — If enabled, anonymous users may access this object’s data depending on API-level rules.
Composite Indexes
- coursePackByTutorAndTitle: [tutorProfileId, title] This composite index is defined to optimize query performance for complex queries involving multiple fields.
The index also defines a conflict resolution strategy for duplicate key violations.
When a new record would violate this composite index, the following action will be taken:
On Duplicate: throwError
An error will be thrown, preventing the insertion of conflicting data.
Properties Schema
Display Label Property: title — This property is the default display label for records of this data object. Relation dropdowns and record references in the frontend will show the value of this property as the human-readable label.
| Property | Type | Required | Description |
|---|---|---|---|
tutorProfileId |
ID | Yes | - |
title |
String | Yes | - |
description |
Text | No | - |
price |
Double | Yes | - |
category |
String | Yes | - |
schedulingType |
Enum | Yes | - |
minWeeklyClasses |
Integer | No | - |
preliminaryMeetingRequired |
Boolean | Yes | - |
isPublished |
Boolean | Yes | - |
maxDailyLessons |
Integer | No | - |
requiredClassesCount |
Integer | No | - |
moderationStatus |
Enum | No | Content moderation status. |
moderationNote |
String | No | Admin note for flagged/removed course packs. |
maxPeriodValue |
Integer | No | Maximum time period value for strict scheduling (e.g. 3 for 3 months) |
maxPeriodUnit |
Enum | No | Time unit for maxPeriodValue in strict scheduling |
- Required properties are mandatory for creating objects and must be provided in the request body if no default value is set.
Default Values
Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.
- tutorProfileId: ‘00000000-0000-0000-0000-000000000000’
- title: ‘default’
- price: 0.0
- category: ‘default’
- schedulingType: flexible
- isPublished: true
- moderationStatus: approved
Always Create with Default Values
Some of the default values are set to be always used when creating a new object, even if the property value is provided in the request body. It ensures that the property is always initialized with a default value when the object is created.
- moderationStatus: Will be created with value
approved
Auto Update Properties
tutorProfileId title description price category schedulingType minWeeklyClasses preliminaryMeetingRequired isPublished maxDailyLessons requiredClassesCount moderationStatus moderationNote maxPeriodValue maxPeriodUnit
An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body.
If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false.
These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.
Enum Properties
Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.
-
schedulingType: [flexible, strict]
-
moderationStatus: [approved, flagged, removed]
-
maxPeriodUnit: [weeks, months]
Elastic Search Indexing
tutorProfileId title description price category schedulingType minWeeklyClasses preliminaryMeetingRequired isPublished maxDailyLessons requiredClassesCount moderationStatus maxPeriodValue maxPeriodUnit
Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.
Database Indexing
tutorProfileId title category isPublished moderationStatus
Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.
Secondary Key Properties
tutorProfileId
Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.
Relation Properties
tutorProfileId category
Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.
- tutorProfileId: ID
Relation to
tutorProfile.id
The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.
On Delete: Set Null Required: Yes
- category: String
Relation to
courseCategory.name
The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.
On Delete: Set Null Required: No
Filter Properties
tutorProfileId title category schedulingType isPublished moderationStatus
Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.
-
tutorProfileId: ID has a filter named
tutorProfileId -
title: String has a filter named
courseTitle -
category: String has a filter named
category -
schedulingType: Enum has a filter named
scheduling -
isPublished: Boolean has a filter named
published -
moderationStatus: Enum has a filter named
moderationStatus
courseMaterial Data Object
Object Overview
Description: Material (file, video, link, doc) attached to coursePack. Only visible to the owning tutor and students enrolled in the course pack.
This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement.
It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.
Core Configuration
- Soft Delete: Enabled — Determines whether records are marked inactive (
isActive = false) instead of being physically deleted. - Public Access: accessPrivate — If enabled, anonymous users may access this object’s data depending on API-level rules.
Composite Indexes
- materialPerCourseTitle: [coursePackId, title] This composite index is defined to optimize query performance for complex queries involving multiple fields.
The index also defines a conflict resolution strategy for duplicate key violations.
When a new record would violate this composite index, the following action will be taken:
On Duplicate: throwError
An error will be thrown, preventing the insertion of conflicting data.
Properties Schema
Display Label Property: title — This property is the default display label for records of this data object. Relation dropdowns and record references in the frontend will show the value of this property as the human-readable label.
| Property | Type | Required | Description |
|---|---|---|---|
coursePackId |
ID | Yes | FK to coursePack. |
fileUrl |
String | Yes | URL for file/video/document. For downloads or video links (protected). |
fileType |
Enum | Yes | Type: file, video, document, externalLink. |
title |
String | Yes | Material title (unique per pack). |
description |
Text | No | Additional details about the material resource. |
linkUrl |
String | No | Optional URL for external resource (if fileType = externalLink). |
- Required properties are mandatory for creating objects and must be provided in the request body if no default value is set.
Default Values
Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.
- coursePackId: ‘00000000-0000-0000-0000-000000000000’
- fileUrl: ‘default’
- fileType: “file”
- title: ‘default’
Constant Properties
coursePackId
Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle.
A property is set to be constant if the Allow Update option is set to false.
Auto Update Properties
fileUrl fileType title description linkUrl
An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body.
If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false.
These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.
Enum Properties
Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.
- fileType: [file, video, document, externalLink]
Elastic Search Indexing
coursePackId fileType title description
Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.
Database Indexing
coursePackId title
Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.
Secondary Key Properties
coursePackId
Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.
Relation Properties
coursePackId
Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.
- coursePackId: ID
Relation to
coursePack.id
The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.
On Delete: Set Null Required: Yes
Filter Properties
fileType
Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.
- fileType: Enum has a filter named
type
courseCategory Data Object
Object Overview
Description: Represents a course subject/category; used for filtering and navigation. Admin-maintained.
This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement.
It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.
Core Configuration
- Soft Delete: Enabled — Determines whether records are marked inactive (
isActive = false) instead of being physically deleted. - Public Access: accessPublic — If enabled, anonymous users may access this object’s data depending on API-level rules.
Composite Indexes
- uniqueCategoryName: [name] This composite index is defined to optimize query performance for complex queries involving multiple fields.
The index also defines a conflict resolution strategy for duplicate key violations.
When a new record would violate this composite index, the following action will be taken:
On Duplicate: throwError
An error will be thrown, preventing the insertion of conflicting data.
Properties Schema
Display Label Property: name — This property is the default display label for records of this data object. Relation dropdowns and record references in the frontend will show the value of this property as the human-readable label.
| Property | Type | Required | Description |
|---|---|---|---|
name |
String | Yes | Unique category/subject name. |
description |
Text | No | Category description. |
icon |
String | No | Emoji icon displayed next to the category name (e.g. 📐, 🗣️, 🎵) |
- Required properties are mandatory for creating objects and must be provided in the request body if no default value is set.
Default Values
Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.
- name: ‘default’
- icon: 📚
Auto Update Properties
name description icon
An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body.
If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false.
These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.
Elastic Search Indexing
name description icon
Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.
Database Indexing
name icon
Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.
Unique Properties
name
Unique properties are enforced to have distinct values across all instances of the data object, preventing duplicate entries.
Note that a unique property is automatically indexed in the database so you will not need to set the Indexed in DB option.
Secondary Key Properties
name
Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.
Filter Properties
name
Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.
- name: String has a filter named
name
Business Logic
tutorCatalog has got 20 Business APIs to manage its internal and crud logic. For the details of each business API refer to its chapter.
Service Library
Functions
getTutorProfileIdsBySessionUserId.js
module.exports = async function getTutorProfileIdsBySessionUserId(userId) {
if (!userId) return [];
const db = require("dbLayer");
const items = await db.getTutorProfileListByMQuery({ tutorId: userId, isActive: true });
return items.map(i => i.id);
}
getCoursePackIdsBySessionUserId.js
module.exports = async function getCoursePackIdsBySessionUserId(userId) {
if (!userId) return [];
const tutorProfileIds = await LIB.getTutorProfileIdsBySessionUserId(userId);
if (!tutorProfileIds.length) return [];
const db = require("dbLayer");
const packs = await db.getCoursePackListByMQuery({ tutorProfileId: { $in: tutorProfileIds }, isActive: true });
return packs.map(p => p.id);
}
isMaterialViewAllowedBySession.js
module.exports = async function isMaterialViewAllowedBySession(courseMaterialId, userId, roleId) {
if (!userId || !courseMaterialId) return false;
if (roleId === "admin") return true;
const MODELS = require("models");
const cm = await MODELS.CourseMaterial.findOne({ where: { id: courseMaterialId, isActive: true } });
if (!cm) return false;
const pack = await MODELS.CoursePack.findOne({ where: { id: cm.coursePackId, isActive: true } });
if (!pack) return false;
if (roleId === "tutor") {
const tprofiles = await MODELS.TutorProfile.findAll({ where: { tutorId: userId, isActive: true } });
if (tprofiles.some(tpf => tpf.id === pack.tutorProfileId)) return true;
}
if (roleId === "student") {
const { fetchRemoteListByMQuery } = require("serviceCommon");
const enrolls = await fetchRemoteListByMQuery("enrollmentManagement:enrollment", { studentId: userId, coursePackId: pack.id, isActive: true, enrollmentStatus: "active" }, 0, 1);
if (enrolls && enrolls.length > 0) return true;
}
return false;
}
getAllowedMaterialWhereClause.js
module.exports = async function getAllowedMaterialWhereClause(userId, roleId) {
if (!userId) return { id: null };
if (roleId === "admin") return {};
const db = require("dbLayer");
if (roleId === "tutor") {
const tprofiles = await db.getTutorProfileListByMQuery({ tutorId: userId, isActive: true });
if (!tprofiles.length) return { id: null };
const packs = await db.getCoursePackListByMQuery({ tutorProfileId: { $in: tprofiles.map(p => p.id) }, isActive: true });
const accessiblePackIds = packs.map(p => p.id);
if (!accessiblePackIds.length) return { id: null };
return { coursePackId: { $in: accessiblePackIds } };
}
if (roleId === "student") {
const { fetchRemoteListByMQuery } = require("serviceCommon");
const enrolls = await fetchRemoteListByMQuery("enrollmentManagement:enrollment", { studentId: userId, isActive: true, enrollmentStatus: "active" }, 0, 100);
const enrolledPackIds = enrolls ? enrolls.map(e => e.coursePackId) : [];
if (!enrolledPackIds.length) return { id: null };
return { coursePackId: { $in: enrolledPackIds } };
}
return { id: null };
}
checkCoursePackActiveEnrollments.js
module.exports = async function checkCoursePackActiveEnrollments(coursePackId) {
if (!coursePackId) return { hasActiveEnrollments: false, count: 0, enrollments: [] };
try {
// Use interservice HTTP call to enrollmentManagement's internal fetch endpoint
// This reads from the DB (source of truth), not ES which may be stale
const axios = require('axios');
const { getServiceSecret } = require('common');
// In preview, all services share the same base host with different routes
const baseUrl = process.env.ENROLLMENTMANAGEMENT_API_URL || (process.env.PREVIEW_BASE_URL ? process.env.PREVIEW_BASE_URL + '/enrollmentmanagement-api' : null);
// Fallback: use the _fetchList internal endpoint via M2M or query ES
if (!baseUrl) {
// Try ES as fallback
const { elasticClient } = require('common');
const res = await elasticClient.search({
index: 'tutorhub_enrollment',
body: {
query: {
bool: {
must: [
{ term: { coursePackId: coursePackId } },
{ term: { enrollmentStatus: 'active' } },
{ term: { isActive: true } }
]
}
},
size: 100
}
});
const enrollments = res.hits.hits.map(h => h._source);
return { hasActiveEnrollments: enrollments.length > 0, count: enrollments.length, enrollments };
}
const serviceSecret = getServiceSecret ? getServiceSecret() : process.env.SERVICE_SECRET_KEY;
const url = `${baseUrl}/m2m/getEnrollmentListByMQuery`;
const response = await axios.post(url, {
query: { coursePackId, enrollmentStatus: 'active', isActive: true }
}, {
headers: {
'Content-Type': 'application/json',
...(serviceSecret ? { 'x-service-secret': serviceSecret } : {})
},
timeout: 10000
});
const enrollments = response.data || [];
return { hasActiveEnrollments: enrollments.length > 0, count: enrollments.length, enrollments };
} catch (err) {
console.log('ERROR in checkCoursePackActiveEnrollments:', err.message);
// FAIL SAFE: if we can't check, assume there ARE enrollments to prevent accidental deletion
return { hasActiveEnrollments: true, count: -1, enrollments: [], error: err.message };
}
}
triggerAdminCourseRemovalCascade.js
module.exports = async function triggerAdminCourseRemovalCascade(coursePackId, removalReason, enrollmentCheck, session) {
const { fetchRemoteListByMQuery, callRemoteApi } = require('serviceCommon');
const { elasticClient } = require('common');
if (!enrollmentCheck || !enrollmentCheck.hasActiveEnrollments) {
return { processed: 0, total: 0, refunds: [] };
}
const enrollments = enrollmentCheck.enrollments || [];
const results = { processed: 0, total: enrollments.length, refunds: [], errors: [] };
for (const enrollment of enrollments) {
try {
// Fetch lesson slots to calculate completion percentage
const slotIds = enrollment.lessonSlotIds || [];
let completedCount = 0;
let totalSlots = slotIds.length;
if (totalSlots > 0) {
try {
const slotsRes = await elasticClient.search({
index: 'tutorhub_lessonslot',
body: {
query: { terms: { id: slotIds } },
_source: ['id', 'status'],
size: 500
}
});
const slots = slotsRes.hits.hits.map(h => h._source);
completedCount = slots.filter(s => s.status === 'completed').length;
} catch (esErr) {
console.log('Warning: ES slot lookup failed, assuming 0 completed:', esErr.message);
}
}
// Calculate pro-rata refund amount
const completionRatio = totalSlots > 0 ? completedCount / totalSlots : 0;
let refundAmount = 0;
let refundNote = '';
if (completionRatio === 0) {
refundAmount = enrollment.totalAmount;
refundNote = 'Full refund - no lessons completed';
} else if (completionRatio <= 0.5) {
const unusedSlots = totalSlots - completedCount;
refundAmount = Math.round((unusedSlots / totalSlots) * enrollment.totalAmount * 100) / 100;
refundNote = `Pro-rata refund: ${completedCount}/${totalSlots} lessons completed, refunding ${unusedSlots} unused lessons`;
} else {
refundAmount = 0;
refundNote = `No refund: ${completedCount}/${totalSlots} lessons completed (over 50%)`;
}
// Fetch student data for email notifications
let studentData = null;
try {
const studentRes = await elasticClient.search({
index: 'tutorhub_user',
body: { query: { term: { id: enrollment.studentId } }, _source: ['fullname', 'email'], size: 1 }
});
if (studentRes.hits.hits.length > 0) studentData = studentRes.hits.hits[0]._source;
} catch (e) { console.log('Warning: student lookup failed:', e.message); }
if (refundAmount > 0) {
try {
await callRemoteApi('enrollmentManagement', 'adminRefundEnrollment', {
enrollmentId: enrollment.id,
reason: `Course removed by admin. Reason: ${removalReason || 'No reason provided'}. ${refundNote}`
}, session);
} catch (refundErr) {
console.log('Warning: adminRefundEnrollment failed for', enrollment.id, ':', refundErr.message);
results.errors.push({ enrollmentId: enrollment.id, error: refundErr.message });
}
} else {
try {
await callRemoteApi('enrollmentManagement', 'cancelEnrollment', {
enrollmentId: enrollment.id,
reason: `Course removed by admin. Reason: ${removalReason || 'No reason provided'}. ${refundNote}`
}, session);
} catch (cancelErr) {
console.log('Warning: cancelEnrollment failed for', enrollment.id, ':', cancelErr.message);
results.errors.push({ enrollmentId: enrollment.id, error: cancelErr.message });
}
}
results.refunds.push({
enrollmentId: enrollment.id,
studentId: enrollment.studentId,
studentEmail: studentData ? studentData.email : null,
studentName: studentData ? studentData.fullname : null,
totalAmount: enrollment.totalAmount,
currency: enrollment.currency || 'USD',
refundAmount,
completedLessons: completedCount,
totalLessons: totalSlots,
note: refundNote
});
results.processed++;
} catch (err) {
results.errors.push({ enrollmentId: enrollment.id, error: err.message });
}
}
// Publish individual Kafka events per student for email notifications
try {
const { sendMessageToKafka } = require('common');
const db = require('dbLayer');
const coursePack = await db.getCoursePackById(coursePackId);
const courseTitle = coursePack ? coursePack.title : 'Unknown Course';
for (const refund of results.refunds) {
if (refund.studentEmail) {
await sendMessageToKafka('tutorhub-tutorcatalog-service-coursepack-removed-by-admin', {
coursePackId,
courseTitle,
removalReason: removalReason || 'No reason provided',
student: { email: refund.studentEmail, fullname: refund.studentName },
refundAmount: refund.refundAmount,
totalAmount: refund.totalAmount,
currency: refund.currency,
completedLessons: refund.completedLessons,
totalLessons: refund.totalLessons,
refundNote: refund.note,
removedAt: new Date().toISOString()
});
}
}
} catch (kafkaErr) {
console.log('Warning: failed to publish course removal events:', kafkaErr.message);
}
return results;
}
This document was generated from the service architecture definition and should be kept in sync with implementation changes.