@eeplatform/basic-edu 1.10.0 → 1.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2981,8 +2981,7 @@ var schemaUpdateStatus = import_joi5.default.object({
2981
2981
  status: import_joi5.default.string().valid("pending", "accepted", "rejected", "cancelled").required()
2982
2982
  });
2983
2983
  var gradeLevels = [
2984
- "K1",
2985
- "K2",
2984
+ "kindergarten",
2986
2985
  "grade-1",
2987
2986
  "grade-2",
2988
2987
  "grade-3",
@@ -38840,7 +38839,6 @@ var schemaSectionPreset = import_joi29.default.object({
38840
38839
  description: import_joi29.default.string().max(500).optional().allow(null, ""),
38841
38840
  set: import_joi29.default.array().items(import_joi29.default.string()).required(),
38842
38841
  school: import_joi29.default.string().hex().required(),
38843
- createdBy: import_joi29.default.string().hex().required(),
38844
38842
  createdAt: import_joi29.default.string().isoDate().optional(),
38845
38843
  updatedAt: import_joi29.default.string().isoDate().optional(),
38846
38844
  deletedAt: import_joi29.default.string().isoDate().optional().allow(null, "")
@@ -38857,13 +38855,6 @@ function modelSectionPreset(value) {
38857
38855
  throw new Error("Invalid _id.");
38858
38856
  }
38859
38857
  }
38860
- if (value.createdBy && typeof value.createdBy === "string") {
38861
- try {
38862
- value.createdBy = new import_mongodb27.ObjectId(value.createdBy);
38863
- } catch (error2) {
38864
- throw new Error("Invalid createdBy.");
38865
- }
38866
- }
38867
38858
  if (value.school && typeof value.school === "string") {
38868
38859
  try {
38869
38860
  value.school = new import_mongodb27.ObjectId(value.school);
@@ -38878,7 +38869,6 @@ function modelSectionPreset(value) {
38878
38869
  set: value.set,
38879
38870
  status: value.status ?? "active",
38880
38871
  school: value.school,
38881
- createdBy: value.createdBy,
38882
38872
  createdAt: value.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
38883
38873
  updatedAt: value.updatedAt ?? "",
38884
38874
  deletedAt: value.deletedAt ?? ""
@@ -38899,12 +38889,13 @@ function useSectionPresetRepo() {
38899
38889
  async function createIndexes() {
38900
38890
  try {
38901
38891
  await collection.createIndexes([
38892
+ { key: { school: 1 } },
38902
38893
  { key: { name: 1 } },
38903
38894
  { key: { createdAt: 1 } },
38904
38895
  { key: { createdBy: 1 } },
38905
38896
  { key: { name: "text", description: "text" } },
38906
38897
  {
38907
- key: { name: 1, status: 1 },
38898
+ key: { school: 1, name: 1, status: 1 },
38908
38899
  unique: true,
38909
38900
  name: "unique_section_preset"
38910
38901
  }
@@ -39782,11 +39773,11 @@ function useSectionRepo() {
39782
39773
  }
39783
39774
 
39784
39775
  // src/resources/section/section.controller.ts
39785
- var import_nodejs_utils73 = require("@eeplatform/nodejs-utils");
39786
- var import_joi45 = __toESM(require("joi"));
39776
+ var import_nodejs_utils70 = require("@eeplatform/nodejs-utils");
39777
+ var import_joi43 = __toESM(require("joi"));
39787
39778
 
39788
39779
  // src/resources/section/section.service.ts
39789
- var import_nodejs_utils72 = require("@eeplatform/nodejs-utils");
39780
+ var import_nodejs_utils69 = require("@eeplatform/nodejs-utils");
39790
39781
 
39791
39782
  // src/resources/section-student/section.student.repository.ts
39792
39783
  var import_nodejs_utils54 = require("@eeplatform/nodejs-utils");
@@ -41510,7 +41501,7 @@ function modelTeachingLoadSlot(value) {
41510
41501
  const { error } = schemaTeachingLoadSlot.validate(value);
41511
41502
  if (error) {
41512
41503
  import_nodejs_utils62.logger.info(`Teaching Load Slot Model: ${error.message}`);
41513
- throw new import_nodejs_utils62.BadRequestError(error.message);
41504
+ throw new import_nodejs_utils62.BadRequestError(`${error.message} - model`);
41514
41505
  }
41515
41506
  if (value._id && typeof value._id === "string") {
41516
41507
  try {
@@ -41917,9 +41908,11 @@ function useTeachingLoadSlotController() {
41917
41908
  gradeLevel: import_joi40.default.string().required(),
41918
41909
  startTime: import_joi40.default.string().required(),
41919
41910
  endTime: import_joi40.default.string().required(),
41920
- subject: import_joi40.default.string().hex().required(),
41911
+ subject: import_joi40.default.string().hex().optional().allow("", null),
41921
41912
  subjectName: import_joi40.default.string().optional().allow("", null),
41922
41913
  subjectCode: import_joi40.default.string().optional().allow("", null),
41914
+ routine: import_joi40.default.string().hex().optional().allow("", null),
41915
+ routineName: import_joi40.default.string().optional().allow("", null),
41923
41916
  section: import_joi40.default.string().hex().required(),
41924
41917
  sectionName: import_joi40.default.string().optional().allow("", null),
41925
41918
  duration: import_joi40.default.number().min(0).required(),
@@ -42715,505 +42708,360 @@ function usePersonnelController() {
42715
42708
  };
42716
42709
  }
42717
42710
 
42718
- // src/resources/kindergarten-routine/kindergarten.routine.model.ts
42719
- var import_nodejs_utils69 = require("@eeplatform/nodejs-utils");
42720
- var import_joi43 = __toESM(require("joi"));
42721
- var import_mongodb41 = require("mongodb");
42722
- var schemaKindergartenRoutine = import_joi43.default.object({
42723
- _id: import_joi43.default.string().hex().optional().allow(null, ""),
42724
- title: import_joi43.default.string().max(100).required(),
42725
- section: import_joi43.default.string().hex().optional().allow(null, ""),
42726
- sectionName: import_joi43.default.string().max(100).optional().allow(null, ""),
42727
- classroom: import_joi43.default.string().hex().optional().allow(null, ""),
42728
- classroomName: import_joi43.default.string().max(100).optional().allow(null, ""),
42729
- schedule: import_joi43.default.array().items(import_joi43.default.string()).required(),
42730
- blockTimes: import_joi43.default.array().items(
42731
- import_joi43.default.object({
42732
- title: import_joi43.default.string().required(),
42733
- startTime: import_joi43.default.string().required(),
42734
- endTime: import_joi43.default.string().required(),
42735
- durationMinutes: import_joi43.default.number().required(),
42736
- domains: import_joi43.default.array().items(import_joi43.default.string()).optional()
42737
- })
42738
- ).required(),
42739
- type: import_joi43.default.string().required(),
42740
- durationMinutes: import_joi43.default.number().optional().allow(null, 0),
42741
- school: import_joi43.default.string().hex().required(),
42742
- createdAt: import_joi43.default.string().isoDate().optional().allow(null, ""),
42743
- updatedAt: import_joi43.default.string().isoDate().optional().allow(null, ""),
42744
- deletedAt: import_joi43.default.string().isoDate().optional().allow(null, "")
42745
- });
42746
- var schemaKindergartenRoutineUpdate = import_joi43.default.object({
42747
- title: import_joi43.default.string().max(100).optional().allow(null, ""),
42748
- section: import_joi43.default.string().hex().optional().allow(null, ""),
42749
- sectionName: import_joi43.default.string().max(100).optional().allow(null, ""),
42750
- classroom: import_joi43.default.string().hex().optional().allow(null, ""),
42751
- classroomName: import_joi43.default.string().max(100).optional().allow(null, ""),
42752
- schedule: import_joi43.default.array().items(import_joi43.default.string()).optional().allow(null, ""),
42753
- blockTimes: import_joi43.default.array().items(
42754
- import_joi43.default.object({
42755
- title: import_joi43.default.string().required(),
42756
- startTime: import_joi43.default.string().required(),
42757
- endTime: import_joi43.default.string().required(),
42758
- durationMinutes: import_joi43.default.number().required(),
42759
- domains: import_joi43.default.array().items(import_joi43.default.string()).optional()
42760
- })
42761
- ).optional(),
42762
- durationMinutes: import_joi43.default.number().optional().allow(null, 0)
42763
- });
42764
- function modelKindergartenRoutine(value) {
42765
- const { error } = schemaKindergartenRoutine.validate(value);
42766
- if (error) {
42767
- throw new import_nodejs_utils69.BadRequestError(`Invalid kinder schedule data: ${error.message}`);
42768
- }
42769
- if (value._id && typeof value._id === "string") {
42770
- try {
42771
- value._id = new import_mongodb41.ObjectId(value._id);
42772
- } catch (error2) {
42773
- throw new Error("Invalid _id.");
42711
+ // src/resources/section/section.service.ts
42712
+ function useSectionService() {
42713
+ const { getCountByGradeLevel, getByGradeLevel: getLeanerByGradeLevel } = useLearnerRepo();
42714
+ const { getByGradeLevel } = useGradeLevelRepo();
42715
+ const { add: createSection } = useSectionRepo();
42716
+ const { add: assignStudent } = useSectionStudentRepo();
42717
+ const { getAll: getAllCurriculumSubjects } = useSubjectRepo();
42718
+ const { add: addSectionSubject } = useSectionSubjectRepo();
42719
+ const { getById: getSchoolById } = useSchoolRepo();
42720
+ const { getAll: getAllPersonnel } = usePersonnelRepo();
42721
+ const { add: addTeachingLoad } = useTeachingLoadRepo();
42722
+ function distributeStudents(total, minPer, maxPer) {
42723
+ if (total <= 0)
42724
+ return [];
42725
+ if (minPer <= 0 || maxPer <= 0)
42726
+ return [];
42727
+ if (minPer > maxPer) {
42728
+ throw new import_nodejs_utils69.BadRequestError(
42729
+ "Minimum students per section cannot be greater than maximum."
42730
+ );
42774
42731
  }
42775
- }
42776
- if (value.school && typeof value.school === "string") {
42777
- try {
42778
- value.school = new import_mongodb41.ObjectId(value.school);
42779
- } catch (error2) {
42780
- throw new Error("Invalid school.");
42732
+ const minSections = Math.ceil(total / maxPer);
42733
+ const maxSections = Math.floor(total / minPer);
42734
+ let sectionCount;
42735
+ if (minSections <= maxSections) {
42736
+ sectionCount = minSections;
42737
+ } else {
42738
+ sectionCount = minSections;
42781
42739
  }
42782
- }
42783
- if (value.section && typeof value.section === "string") {
42784
- try {
42785
- value.section = new import_mongodb41.ObjectId(value.section);
42786
- } catch (error2) {
42787
- throw new Error("Invalid section.");
42740
+ const base = Math.floor(total / sectionCount);
42741
+ const extra = total % sectionCount;
42742
+ const sizes = new Array(sectionCount).fill(base);
42743
+ for (let i = 0; i < extra; i++) {
42744
+ sizes[i] += 1;
42788
42745
  }
42789
- }
42790
- if (value.classroom && typeof value.classroom === "string") {
42791
- try {
42792
- value.classroom = new import_mongodb41.ObjectId(value.classroom);
42793
- } catch (error2) {
42794
- throw new Error("Invalid classroom.");
42746
+ for (const size of sizes) {
42747
+ if (size > maxPer) {
42748
+ throw new import_nodejs_utils69.BadRequestError(
42749
+ `Generated section exceeds max limit of ${maxPer}.`
42750
+ );
42751
+ }
42795
42752
  }
42753
+ return sizes;
42796
42754
  }
42797
- return {
42798
- _id: value._id,
42799
- title: value.title,
42800
- section: value.section,
42801
- sectionName: value.sectionName ?? "",
42802
- classroom: value.classroom,
42803
- classroomName: value.classroomName ?? "",
42804
- schedule: value.schedule,
42805
- blockTimes: value.blockTimes,
42806
- type: value.type,
42807
- durationMinutes: value.durationMinutes ?? 0,
42808
- status: value.status ?? "active",
42809
- school: value.school,
42810
- createdAt: value.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
42811
- updatedAt: value.updatedAt ?? "",
42812
- deletedAt: value.deletedAt ?? ""
42813
- };
42814
- }
42815
-
42816
- // src/resources/kindergarten-routine/kindergarten.routine.repository.ts
42817
- var import_nodejs_utils70 = require("@eeplatform/nodejs-utils");
42818
- var import_mongodb42 = require("mongodb");
42819
- function useKindergartenRoutineRepo() {
42820
- const db = import_nodejs_utils70.useAtlas.getDb();
42821
- if (!db) {
42822
- throw new Error("Unable to connect to server.");
42823
- }
42824
- const namespace_collection = "deped.kindergarten.routines";
42825
- const collection = db.collection(namespace_collection);
42826
- const { getCache, setCache, delNamespace } = (0, import_nodejs_utils70.useCache)(namespace_collection);
42827
- async function createIndexes() {
42755
+ async function generateSections(value) {
42756
+ const { error } = schemaGenerateSections.validate(value);
42757
+ if (error) {
42758
+ throw new import_nodejs_utils69.BadRequestError(
42759
+ `Invalid section generation data: ${error.message}`
42760
+ );
42761
+ }
42762
+ const session = import_nodejs_utils69.useAtlas.getClient()?.startSession();
42763
+ if (!session) {
42764
+ throw new Error("Unable to start database session.");
42765
+ }
42828
42766
  try {
42829
- await collection.createIndexes([
42830
- { key: { section: 1 } },
42831
- { key: { classroom: 1 } },
42832
- { key: { schedule: 1 } },
42833
- { key: { type: 1 } },
42834
- { key: { createdAt: 1 } },
42835
- { key: { createdBy: 1 } },
42836
- { key: { sectionName: "text", classroomName: "text" } },
42767
+ await session.startTransaction();
42768
+ const studentCount = await getCountByGradeLevel(
42837
42769
  {
42838
- key: { title: 1, school: 1, type: 1, status: 1 },
42839
- unique: true,
42840
- name: "unique_kindergarten_routine"
42770
+ school: value.school,
42771
+ schoolYear: value.schoolYear,
42772
+ gradeLevel: value.gradeLevel,
42773
+ specialProgram: value.specialProgram
42774
+ },
42775
+ session
42776
+ );
42777
+ if (studentCount === 0) {
42778
+ throw new import_nodejs_utils69.BadRequestError("No learners found for this grade level.");
42779
+ }
42780
+ const gradeLevelData = await getByGradeLevel(
42781
+ {
42782
+ school: value.school,
42783
+ gradeLevel: value.gradeLevel
42784
+ },
42785
+ session
42786
+ );
42787
+ if (!gradeLevelData) {
42788
+ throw new import_nodejs_utils69.BadRequestError("Grade level not found.");
42789
+ }
42790
+ const minPerSection = value.minStudents ?? gradeLevelData.minNumberOfLearners;
42791
+ const maxPerSection = value.maxStudents ?? gradeLevelData.maxNumberOfLearners;
42792
+ const sectionsNeeded = Math.ceil(studentCount / minPerSection);
42793
+ if (sectionsNeeded > value.set.length) {
42794
+ throw new import_nodejs_utils69.BadRequestError(
42795
+ "Insufficient number of section names in set[]."
42796
+ );
42797
+ }
42798
+ const sectionSizes = distributeStudents(
42799
+ studentCount,
42800
+ minPerSection,
42801
+ maxPerSection
42802
+ );
42803
+ if (sectionSizes.length === 0) {
42804
+ throw new import_nodejs_utils69.BadRequestError("Unable to compute section sizes.");
42805
+ }
42806
+ const schoolData = await getSchoolById(value.school);
42807
+ if (!schoolData) {
42808
+ throw new import_nodejs_utils69.BadRequestError("School not found.");
42809
+ }
42810
+ let totalStudentsProcessed = 0;
42811
+ for (let i = 0; i < sectionSizes.length; i++) {
42812
+ const size = sectionSizes[i];
42813
+ const sectionName = value.set[i];
42814
+ const section = await createSection(
42815
+ {
42816
+ school: value.school,
42817
+ schoolYear: value.schoolYear,
42818
+ gradeLevel: value.gradeLevel,
42819
+ name: sectionName,
42820
+ students: size
42821
+ },
42822
+ session
42823
+ );
42824
+ const skip = totalStudentsProcessed;
42825
+ const learners = await getLeanerByGradeLevel(
42826
+ {
42827
+ school: value.school,
42828
+ gradeLevel: value.gradeLevel,
42829
+ skip,
42830
+ limit: size
42831
+ },
42832
+ session
42833
+ );
42834
+ if (!learners.length) {
42835
+ throw new import_nodejs_utils69.BadRequestError(`No learners found for section #${i + 1}.`);
42841
42836
  }
42842
- ]);
42843
- } catch (error) {
42844
- throw new Error("Failed to create index on kindergarten routines.");
42837
+ totalStudentsProcessed += learners.length;
42838
+ for (const student of learners) {
42839
+ if (!student._id) {
42840
+ throw new import_nodejs_utils69.BadRequestError("Learner ID is missing.");
42841
+ }
42842
+ if (!student.learnerInfo.lrn) {
42843
+ throw new import_nodejs_utils69.BadRequestError("Learner LRN is missing.");
42844
+ }
42845
+ await assignStudent(
42846
+ {
42847
+ section: section.toString(),
42848
+ lrn: student.learnerInfo.lrn,
42849
+ student: student._id?.toString(),
42850
+ studentName: `${student.learnerInfo.firstName} ${student.learnerInfo.lastName}`,
42851
+ school: value.school,
42852
+ schoolName: schoolData.name,
42853
+ gradeLevel: value.gradeLevel,
42854
+ educationLevel: gradeLevelData.educationLevel,
42855
+ schoolYear: value.schoolYear,
42856
+ status: "active"
42857
+ },
42858
+ session
42859
+ );
42860
+ }
42861
+ const curriculumSubjects = await getAllCurriculumSubjects({
42862
+ schoolYear: Number(value.schoolYear),
42863
+ gradeLevel: value.gradeLevel,
42864
+ limit: 20
42865
+ });
42866
+ for (const curriculumSubject of curriculumSubjects.items) {
42867
+ await addSectionSubject(
42868
+ {
42869
+ curriculum: curriculumSubject.curriculum.toString(),
42870
+ school: value.school,
42871
+ schoolName: schoolData.name,
42872
+ gradeLevel: value.gradeLevel,
42873
+ educationLevel: gradeLevelData.educationLevel,
42874
+ schoolYear: value.schoolYear,
42875
+ section: section.toString(),
42876
+ sectionName,
42877
+ subjectCode: curriculumSubject.subjectCode,
42878
+ subjectName: curriculumSubject.subjectName,
42879
+ teacher: "",
42880
+ teacherName: "",
42881
+ schedule: "",
42882
+ daysOfWeek: [],
42883
+ classroom: "",
42884
+ classroomName: "",
42885
+ sessionDuration: curriculumSubject.sessionDuration,
42886
+ sessionFrequency: curriculumSubject.sessionFrequency,
42887
+ status: "draft"
42888
+ },
42889
+ session
42890
+ );
42891
+ }
42892
+ }
42893
+ let pageTeacher = 1;
42894
+ let pagesTeachers = 1;
42895
+ let teachers = [];
42896
+ do {
42897
+ const teachersData = await getAllPersonnel({
42898
+ school: value.school,
42899
+ limit: 100
42900
+ });
42901
+ pagesTeachers = teachersData.pages;
42902
+ teachers.push(...teachersData.items);
42903
+ pageTeacher++;
42904
+ } while (pageTeacher < pagesTeachers);
42905
+ if (!teachers.length) {
42906
+ throw new import_nodejs_utils69.BadRequestError(
42907
+ "Could not proceed, no teaching personnel found."
42908
+ );
42909
+ }
42910
+ if (teachers.length) {
42911
+ for (let index = 0; index < teachers.length; index++) {
42912
+ const teacher = teachers[index];
42913
+ if (!teacher._id) {
42914
+ throw new import_nodejs_utils69.BadRequestError("Teacher ID is missing.");
42915
+ }
42916
+ await addTeachingLoad(
42917
+ {
42918
+ school: value.school,
42919
+ schoolName: schoolData.name,
42920
+ schoolYear: value.schoolYear,
42921
+ teacher: teacher._id.toString(),
42922
+ teacherName: `${teacher.firstName} ${teacher.lastName}`,
42923
+ status: "draft"
42924
+ },
42925
+ session
42926
+ );
42927
+ }
42928
+ }
42929
+ await session.commitTransaction();
42930
+ return "Sections generated successfully.";
42931
+ } catch (error2) {
42932
+ await session.abortTransaction();
42933
+ if (error2 instanceof import_nodejs_utils69.AppError) {
42934
+ throw error2;
42935
+ } else {
42936
+ throw new import_nodejs_utils69.InternalServerError("Failed to generate sections.");
42937
+ }
42938
+ } finally {
42939
+ await session?.endSession();
42845
42940
  }
42846
42941
  }
42847
- function delCachedData() {
42848
- delNamespace().then(() => {
42849
- import_nodejs_utils70.logger.log({
42850
- level: "info",
42851
- message: `Cache namespace cleared for ${namespace_collection}`
42852
- });
42853
- }).catch((err) => {
42854
- import_nodejs_utils70.logger.log({
42855
- level: "error",
42856
- message: `Failed to clear cache namespace for ${namespace_collection}: ${err.message}`
42857
- });
42858
- });
42859
- }
42860
- async function add(value, session) {
42942
+ async function generateSectionPreview(value) {
42943
+ const { error } = schemaGenerateSections.validate(value);
42944
+ if (error) {
42945
+ throw new import_nodejs_utils69.BadRequestError(
42946
+ `Invalid section generation data: ${error.message}`
42947
+ );
42948
+ }
42861
42949
  try {
42862
- value = modelKindergartenRoutine(value);
42863
- const res = await collection.insertOne(value, { session });
42864
- delCachedData();
42865
- return res.insertedId;
42866
- } catch (error) {
42867
- import_nodejs_utils70.logger.log({
42868
- level: "error",
42869
- message: error.message
42950
+ const studentCount = await getCountByGradeLevel({
42951
+ school: value.school,
42952
+ schoolYear: value.schoolYear,
42953
+ gradeLevel: value.gradeLevel,
42954
+ specialProgram: value.specialProgram
42870
42955
  });
42871
- if (error instanceof import_nodejs_utils70.AppError) {
42872
- throw error;
42873
- } else {
42874
- const isDuplicated = error.message.includes("duplicate");
42875
- if (isDuplicated) {
42876
- throw new import_nodejs_utils70.BadRequestError("Kinder schedule already exists.");
42877
- }
42878
- throw new Error("Failed to create kindergarten routine.");
42956
+ if (studentCount === 0) {
42957
+ throw new import_nodejs_utils69.BadRequestError("No learners found for this grade level.");
42879
42958
  }
42880
- }
42881
- }
42882
- async function getAll({
42883
- search = "",
42884
- page = 1,
42885
- limit = 10,
42886
- sort = {},
42887
- status = "active",
42888
- createdBy,
42889
- school = "",
42890
- section = "",
42891
- classroom = "",
42892
- type = ""
42893
- } = {}) {
42894
- page = page > 0 ? page - 1 : 0;
42895
- const query = {
42896
- deletedAt: { $in: ["", null] },
42897
- status
42898
- };
42899
- sort = Object.keys(sort).length > 0 ? sort : { _id: 1 };
42900
- const cacheKeyOptions = {
42901
- status,
42902
- page,
42903
- limit,
42904
- sort: JSON.stringify(sort)
42905
- };
42906
- if (createdBy) {
42907
- try {
42908
- query.createdBy = new import_mongodb42.ObjectId(createdBy);
42909
- } catch (error) {
42910
- throw new import_nodejs_utils70.BadRequestError("Invalid createdBy ID.");
42959
+ const gradeLevelData = await getByGradeLevel({
42960
+ school: value.school,
42961
+ gradeLevel: value.gradeLevel
42962
+ });
42963
+ if (!gradeLevelData) {
42964
+ throw new import_nodejs_utils69.BadRequestError("Grade level not found.");
42911
42965
  }
42912
- cacheKeyOptions.createdBy = createdBy;
42913
- }
42914
- if (search) {
42915
- query.$text = { $search: search };
42916
- cacheKeyOptions.search = search;
42917
- }
42918
- if (school) {
42919
- try {
42920
- query.school = new import_mongodb42.ObjectId(school);
42921
- } catch (error) {
42922
- throw new import_nodejs_utils70.BadRequestError("Invalid school ID.");
42966
+ const minPerSection = value.minStudents ?? gradeLevelData.minNumberOfLearners;
42967
+ const maxPerSection = value.maxStudents ?? gradeLevelData.maxNumberOfLearners;
42968
+ const sectionsNeeded = Math.ceil(studentCount / minPerSection);
42969
+ if (sectionsNeeded > value.set.length) {
42970
+ throw new import_nodejs_utils69.BadRequestError(
42971
+ "Insufficient number of section names in set[]."
42972
+ );
42923
42973
  }
42924
- cacheKeyOptions.school = school;
42925
- }
42926
- if (section) {
42927
- try {
42928
- query.section = new import_mongodb42.ObjectId(section);
42929
- } catch (error) {
42930
- throw new import_nodejs_utils70.BadRequestError("Invalid section ID.");
42974
+ const sectionSizes = distributeStudents(
42975
+ studentCount,
42976
+ minPerSection,
42977
+ maxPerSection
42978
+ );
42979
+ if (sectionSizes.length === 0) {
42980
+ throw new import_nodejs_utils69.BadRequestError("Unable to compute section sizes.");
42931
42981
  }
42932
- cacheKeyOptions.section = section;
42933
- }
42934
- if (classroom) {
42935
- try {
42936
- query.classroom = new import_mongodb42.ObjectId(classroom);
42937
- } catch (error) {
42938
- throw new import_nodejs_utils70.BadRequestError("Invalid classroom ID.");
42982
+ const sections = sectionSizes.map((size, index) => ({
42983
+ name: value.set[index],
42984
+ value: size
42985
+ }));
42986
+ return {
42987
+ totalSectionsGenerated: sectionSizes.length,
42988
+ totalStudentsAssigned: studentCount,
42989
+ sections
42990
+ };
42991
+ } catch (error2) {
42992
+ if (error2 instanceof import_nodejs_utils69.AppError) {
42993
+ throw error2;
42994
+ } else {
42995
+ throw new import_nodejs_utils69.InternalServerError("Failed to generate section preview.");
42939
42996
  }
42940
- cacheKeyOptions.classroom = classroom;
42941
42997
  }
42942
- if (type) {
42943
- query.type = type;
42944
- cacheKeyOptions.type = type;
42998
+ }
42999
+ return { generateSections, generateSectionPreview };
43000
+ }
43001
+
43002
+ // src/resources/section/section.controller.ts
43003
+ function useSectionController() {
43004
+ const {
43005
+ add: _add,
43006
+ getAll: _getAll,
43007
+ getById: _getById,
43008
+ getByName: _getByName,
43009
+ getBySchool: _getBySchool,
43010
+ updateFieldById: _updateFieldById,
43011
+ addStudentToSection: _addStudentToSection,
43012
+ removeStudentFromSection: _removeStudentFromSection,
43013
+ deleteById: _deleteById
43014
+ } = useSectionRepo();
43015
+ const {
43016
+ generateSections: _generateSections,
43017
+ generateSectionPreview: _generateSectionPreview
43018
+ } = useSectionService();
43019
+ async function add(req, res, next) {
43020
+ const value = req.body;
43021
+ const { error } = schemaSection.validate(value);
43022
+ if (error) {
43023
+ next(new import_nodejs_utils70.BadRequestError(error.message));
43024
+ return;
42945
43025
  }
42946
- const cacheKey = (0, import_nodejs_utils70.makeCacheKey)(namespace_collection, cacheKeyOptions);
42947
- import_nodejs_utils70.logger.log({
42948
- level: "info",
42949
- message: `Cache key for getAll kindergarten routines: ${cacheKey}`
42950
- });
42951
43026
  try {
42952
- const cached = await getCache(cacheKey);
42953
- if (cached) {
42954
- import_nodejs_utils70.logger.log({
42955
- level: "info",
42956
- message: `Cache hit for getAll kindergarten routines: ${cacheKey}`
42957
- });
42958
- return cached;
42959
- }
42960
- const items = await collection.aggregate([
42961
- { $match: query },
42962
- { $sort: sort },
42963
- { $skip: page * limit },
42964
- { $limit: limit }
42965
- ]).toArray();
42966
- const length = await collection.countDocuments(query);
42967
- const data = (0, import_nodejs_utils70.paginate)(items, page, limit, length);
42968
- setCache(cacheKey, data, 600).then(() => {
42969
- import_nodejs_utils70.logger.log({
42970
- level: "info",
42971
- message: `Cache set for getAll kindergarten routines: ${cacheKey}`
42972
- });
42973
- }).catch((err) => {
42974
- import_nodejs_utils70.logger.log({
42975
- level: "error",
42976
- message: `Failed to set cache for getAll kindergarten routines: ${err.message}`
42977
- });
43027
+ const data = await _add(value);
43028
+ res.json({
43029
+ message: "Successfully created section.",
43030
+ data
42978
43031
  });
42979
- return data;
42980
- } catch (error) {
42981
- import_nodejs_utils70.logger.log({ level: "error", message: `${error}` });
42982
- throw error;
43032
+ return;
43033
+ } catch (error2) {
43034
+ next(error2);
42983
43035
  }
42984
43036
  }
42985
- async function getById(_id) {
42986
- try {
42987
- _id = new import_mongodb42.ObjectId(_id);
42988
- } catch (error) {
42989
- throw new import_nodejs_utils70.BadRequestError(namespace_collection + " Invalid ID.");
43037
+ async function generateSections(req, res, next) {
43038
+ const value = req.body;
43039
+ const { error } = schemaGenerateSections.validate(value);
43040
+ if (error) {
43041
+ next(new import_nodejs_utils70.BadRequestError(error.message));
43042
+ return;
42990
43043
  }
42991
- const cacheKey = (0, import_nodejs_utils70.makeCacheKey)(namespace_collection, { _id: String(_id) });
42992
43044
  try {
42993
- const cached = await getCache(cacheKey);
42994
- if (cached) {
42995
- import_nodejs_utils70.logger.log({
42996
- level: "info",
42997
- message: `Cache hit for getById kindergarten routine: ${cacheKey}`
42998
- });
42999
- return cached;
43000
- }
43001
- const result = await collection.findOne({
43002
- _id,
43003
- deletedAt: { $in: ["", null] }
43004
- });
43005
- setCache(cacheKey, result, 300).then(() => {
43006
- import_nodejs_utils70.logger.log({
43007
- level: "info",
43008
- message: `Cache set for kindergarten routine by id: ${cacheKey}`
43009
- });
43010
- }).catch((err) => {
43011
- import_nodejs_utils70.logger.log({
43012
- level: "error",
43013
- message: `Failed to set cache for kindergarten routine by id: ${err.message}`
43014
- });
43045
+ const data = await _generateSections(value);
43046
+ res.json({
43047
+ message: "Successfully created section.",
43048
+ data
43015
43049
  });
43016
- return result;
43017
- } catch (error) {
43018
- if (error instanceof import_nodejs_utils70.AppError) {
43019
- throw error;
43020
- } else {
43021
- throw new import_nodejs_utils70.InternalServerError("Failed to get kindergarten routine.");
43022
- }
43050
+ return;
43051
+ } catch (error2) {
43052
+ next(error2);
43023
43053
  }
43024
43054
  }
43025
- async function countByDomain(domain) {
43026
- const cacheKey = (0, import_nodejs_utils70.makeCacheKey)(namespace_collection, {
43027
- domain,
43028
- tag: "getByDomain"
43029
- });
43030
- try {
43031
- const cached = await getCache(cacheKey);
43032
- if (cached) {
43033
- import_nodejs_utils70.logger.log({
43034
- level: "info",
43035
- message: `Cache hit for getById kindergarten routine: ${cacheKey}`
43036
- });
43037
- return cached;
43038
- }
43039
- const result = await collection.countDocuments({
43040
- domain,
43041
- status: "active"
43042
- });
43043
- setCache(cacheKey, result, 300).then(() => {
43044
- import_nodejs_utils70.logger.log({
43045
- level: "info",
43046
- message: `Cache set for kindergarten routine by id: ${cacheKey}`
43047
- });
43048
- }).catch((err) => {
43049
- import_nodejs_utils70.logger.log({
43050
- level: "error",
43051
- message: `Failed to set cache for kindergarten routine by id: ${err.message}`
43052
- });
43053
- });
43054
- return result;
43055
- } catch (error) {
43056
- if (error instanceof import_nodejs_utils70.AppError) {
43057
- throw error;
43058
- } else {
43059
- throw new import_nodejs_utils70.InternalServerError("Failed to get kindergarten routine.");
43060
- }
43061
- }
43062
- }
43063
- async function getBySection(section) {
43064
- try {
43065
- section = new import_mongodb42.ObjectId(section);
43066
- } catch (error) {
43067
- throw new import_nodejs_utils70.BadRequestError("Invalid section ID.");
43068
- }
43069
- const cacheKey = (0, import_nodejs_utils70.makeCacheKey)(namespace_collection, {
43070
- section: String(section)
43071
- });
43072
- try {
43073
- const cached = await getCache(cacheKey);
43074
- if (cached) {
43075
- import_nodejs_utils70.logger.log({
43076
- level: "info",
43077
- message: `Cache hit for getBySection kindergarten routine: ${cacheKey}`
43078
- });
43079
- return cached;
43080
- }
43081
- const result = await collection.find({
43082
- section,
43083
- deletedAt: { $in: ["", null] }
43084
- }).toArray();
43085
- setCache(cacheKey, result, 300).then(() => {
43086
- import_nodejs_utils70.logger.log({
43087
- level: "info",
43088
- message: `Cache set for kindergarten routine by section: ${cacheKey}`
43089
- });
43090
- }).catch((err) => {
43091
- import_nodejs_utils70.logger.log({
43092
- level: "error",
43093
- message: `Failed to set cache for kindergarten routine by section: ${err.message}`
43094
- });
43095
- });
43096
- return result;
43097
- } catch (error) {
43098
- if (error instanceof import_nodejs_utils70.AppError) {
43099
- throw error;
43100
- } else {
43101
- throw new import_nodejs_utils70.InternalServerError("Failed to get kindergarten routine.");
43102
- }
43103
- }
43104
- }
43105
- async function updateFieldById({ _id, field, value } = {}, session) {
43106
- const allowedFields = [
43107
- "sectionName",
43108
- "classroomName",
43109
- "schedule",
43110
- "blockTimes",
43111
- "type"
43112
- ];
43113
- if (!allowedFields.includes(field)) {
43114
- throw new import_nodejs_utils70.BadRequestError(
43115
- `Field "${field}" is not allowed to be updated.`
43116
- );
43117
- }
43118
- try {
43119
- _id = new import_mongodb42.ObjectId(_id);
43120
- } catch (error) {
43121
- throw new import_nodejs_utils70.BadRequestError(namespace_collection + " Invalid ID.");
43122
- }
43123
- try {
43124
- await collection.updateOne(
43125
- { _id, deletedAt: { $in: ["", null] } },
43126
- { $set: { [field]: value, updatedAt: (/* @__PURE__ */ new Date()).toISOString() } },
43127
- { session }
43128
- );
43129
- delCachedData();
43130
- return `Successfully updated kindergarten routine ${field}.`;
43131
- } catch (error) {
43132
- throw new import_nodejs_utils70.InternalServerError(
43133
- `Failed to update kindergarten routine ${field}.`
43134
- );
43135
- }
43136
- }
43137
- async function updateById(_id, value, session) {
43138
- const { error } = schemaKindergartenRoutineUpdate.validate(value);
43139
- if (error) {
43140
- throw new import_nodejs_utils70.BadRequestError(
43141
- `Invalid kindergarten routine data: ${error.message}`
43142
- );
43143
- }
43144
- try {
43145
- _id = new import_mongodb42.ObjectId(_id);
43146
- } catch (error2) {
43147
- throw new import_nodejs_utils70.BadRequestError(namespace_collection + " Invalid ID.");
43148
- }
43149
- try {
43150
- await collection.updateOne(
43151
- { _id },
43152
- { $set: { ...value, updatedAt: (/* @__PURE__ */ new Date()).toISOString() } },
43153
- { session }
43154
- );
43155
- delCachedData();
43156
- return `Successfully updated kindergarten routine.`;
43157
- } catch (error2) {
43158
- throw new import_nodejs_utils70.InternalServerError("Failed to update kindergarten routine.");
43159
- }
43160
- }
43161
- async function deleteById(_id) {
43162
- try {
43163
- _id = new import_mongodb42.ObjectId(_id);
43164
- } catch (error) {
43165
- throw new import_nodejs_utils70.BadRequestError(namespace_collection + " Invalid ID.");
43166
- }
43167
- try {
43168
- await collection.updateOne(
43169
- { _id },
43170
- { $set: { status: "deleted", deletedAt: (/* @__PURE__ */ new Date()).toISOString() } }
43171
- );
43172
- delCachedData();
43173
- return "Successfully deleted kindergarten routine.";
43174
- } catch (error) {
43175
- throw new import_nodejs_utils70.InternalServerError("Failed to delete kindergarten routine.");
43176
- }
43177
- }
43178
- return {
43179
- createIndexes,
43180
- add,
43181
- getAll,
43182
- getById,
43183
- countByDomain,
43184
- getBySection,
43185
- updateFieldById,
43186
- updateById,
43187
- deleteById
43188
- };
43189
- }
43190
-
43191
- // src/resources/kindergarten-routine/kindergarten.routine.controller.ts
43192
- var import_nodejs_utils71 = require("@eeplatform/nodejs-utils");
43193
- var import_joi44 = __toESM(require("joi"));
43194
- function useKindergartenRoutineController() {
43195
- const {
43196
- add: _add,
43197
- getAll: _getAll,
43198
- getById: _getById,
43199
- getBySection: _getBySection,
43200
- updateFieldById: _updateFieldById,
43201
- deleteById: _deleteById,
43202
- updateById: _updateById
43203
- } = useKindergartenRoutineRepo();
43204
- async function add(req, res, next) {
43055
+ async function generateSectionPreview(req, res, next) {
43205
43056
  const value = req.body;
43206
- const { error } = schemaKindergartenRoutine.validate(value);
43057
+ const { error } = schemaGenerateSections.validate(value);
43207
43058
  if (error) {
43208
- next(new import_nodejs_utils71.BadRequestError(error.message));
43059
+ next(new import_nodejs_utils70.BadRequestError(error.message));
43209
43060
  return;
43210
43061
  }
43211
43062
  try {
43212
- const data = await _add(value);
43213
- res.json({
43214
- message: "Successfully created kinder schedule.",
43215
- data
43216
- });
43063
+ const data = await _generateSectionPreview(value);
43064
+ res.json(data);
43217
43065
  return;
43218
43066
  } catch (error2) {
43219
43067
  next(error2);
@@ -43221,16 +43069,14 @@ function useKindergartenRoutineController() {
43221
43069
  }
43222
43070
  async function getAll(req, res, next) {
43223
43071
  const query = req.query;
43224
- const validation = import_joi44.default.object({
43225
- page: import_joi44.default.number().min(1).optional().allow("", null),
43226
- limit: import_joi44.default.number().min(1).optional().allow("", null),
43227
- search: import_joi44.default.string().optional().allow("", null),
43228
- status: import_joi44.default.string().optional().allow("", null),
43229
- school: import_joi44.default.string().hex().optional().allow("", null),
43230
- section: import_joi44.default.string().hex().optional().allow("", null),
43231
- classroom: import_joi44.default.string().hex().optional().allow("", null),
43232
- type: import_joi44.default.string().optional().allow("", null),
43233
- createdBy: import_joi44.default.string().hex().optional().allow("", null)
43072
+ const validation = import_joi43.default.object({
43073
+ page: import_joi43.default.number().min(1).optional().allow("", null),
43074
+ limit: import_joi43.default.number().min(1).optional().allow("", null),
43075
+ search: import_joi43.default.string().optional().allow("", null),
43076
+ status: import_joi43.default.string().optional().allow("", null),
43077
+ school: import_joi43.default.string().hex().optional().allow("", null),
43078
+ schoolYear: import_joi43.default.string().optional().allow("", null),
43079
+ gradeLevel: import_joi43.default.string().optional().allow("", null)
43234
43080
  });
43235
43081
  const { error } = validation.validate(query);
43236
43082
  const page = typeof req.query.page === "string" ? Number(req.query.page) : 1;
@@ -43238,22 +43084,20 @@ function useKindergartenRoutineController() {
43238
43084
  const search = req.query.search ?? "";
43239
43085
  const status = req.query.status ?? "active";
43240
43086
  const school = req.query.school ?? "";
43241
- const section = req.query.section ?? "";
43242
- const classroom = req.query.classroom ?? "";
43243
- const type = req.query.type ?? "";
43244
- const createdBy = req.query.createdBy ?? "";
43087
+ const schoolYear = req.query.schoolYear ?? "";
43088
+ const gradeLevel = req.query.gradeLevel ?? "";
43245
43089
  const isPageNumber = isFinite(page);
43246
43090
  if (!isPageNumber) {
43247
- next(new import_nodejs_utils71.BadRequestError("Invalid page number."));
43091
+ next(new import_nodejs_utils70.BadRequestError("Invalid page number."));
43248
43092
  return;
43249
43093
  }
43250
43094
  const isLimitNumber = isFinite(limit);
43251
43095
  if (!isLimitNumber) {
43252
- next(new import_nodejs_utils71.BadRequestError("Invalid limit number."));
43096
+ next(new import_nodejs_utils70.BadRequestError("Invalid limit number."));
43253
43097
  return;
43254
43098
  }
43255
43099
  if (error) {
43256
- next(new import_nodejs_utils71.BadRequestError(error.message));
43100
+ next(new import_nodejs_utils70.BadRequestError(error.message));
43257
43101
  return;
43258
43102
  }
43259
43103
  try {
@@ -43263,10 +43107,8 @@ function useKindergartenRoutineController() {
43263
43107
  search,
43264
43108
  status,
43265
43109
  school,
43266
- section,
43267
- classroom,
43268
- type,
43269
- createdBy: createdBy || void 0
43110
+ schoolYear,
43111
+ gradeLevel
43270
43112
  });
43271
43113
  res.json(data);
43272
43114
  return;
@@ -43276,18 +43118,36 @@ function useKindergartenRoutineController() {
43276
43118
  }
43277
43119
  async function getById(req, res, next) {
43278
43120
  const id = req.params.id;
43279
- const validation = import_joi44.default.object({
43280
- id: import_joi44.default.string().hex().required()
43121
+ const validation = import_joi43.default.object({
43122
+ id: import_joi43.default.string().hex().required()
43281
43123
  });
43282
43124
  const { error } = validation.validate({ id });
43283
43125
  if (error) {
43284
- next(new import_nodejs_utils71.BadRequestError(error.message));
43126
+ next(new import_nodejs_utils70.BadRequestError(error.message));
43285
43127
  return;
43286
43128
  }
43287
43129
  try {
43288
43130
  const data = await _getById(id);
43131
+ res.json(data);
43132
+ return;
43133
+ } catch (error2) {
43134
+ next(error2);
43135
+ }
43136
+ }
43137
+ async function getByName(req, res, next) {
43138
+ const name = req.params.name;
43139
+ const validation = import_joi43.default.object({
43140
+ name: import_joi43.default.string().required()
43141
+ });
43142
+ const { error } = validation.validate({ name });
43143
+ if (error) {
43144
+ next(new import_nodejs_utils70.BadRequestError(error.message));
43145
+ return;
43146
+ }
43147
+ try {
43148
+ const data = await _getByName(name);
43289
43149
  res.json({
43290
- message: "Successfully retrieved kinder schedule.",
43150
+ message: "Successfully retrieved section.",
43291
43151
  data
43292
43152
  });
43293
43153
  return;
@@ -43295,20 +43155,20 @@ function useKindergartenRoutineController() {
43295
43155
  next(error2);
43296
43156
  }
43297
43157
  }
43298
- async function getBySection(req, res, next) {
43299
- const section = req.params.section;
43300
- const validation = import_joi44.default.object({
43301
- section: import_joi44.default.string().hex().required()
43158
+ async function getBySchool(req, res, next) {
43159
+ const school = req.params.school;
43160
+ const validation = import_joi43.default.object({
43161
+ school: import_joi43.default.string().hex().required()
43302
43162
  });
43303
- const { error } = validation.validate({ section });
43163
+ const { error } = validation.validate({ school });
43304
43164
  if (error) {
43305
- next(new import_nodejs_utils71.BadRequestError(error.message));
43165
+ next(new import_nodejs_utils70.BadRequestError(error.message));
43306
43166
  return;
43307
43167
  }
43308
43168
  try {
43309
- const data = await _getBySection(section);
43169
+ const data = await _getBySchool(school);
43310
43170
  res.json({
43311
- message: "Successfully retrieved kinder schedules.",
43171
+ message: "Successfully retrieved sections.",
43312
43172
  data
43313
43173
  });
43314
43174
  return;
@@ -43319,14 +43179,14 @@ function useKindergartenRoutineController() {
43319
43179
  async function updateField(req, res, next) {
43320
43180
  const _id = req.params.id;
43321
43181
  const { field, value } = req.body;
43322
- const validation = import_joi44.default.object({
43323
- _id: import_joi44.default.string().hex().required(),
43324
- field: import_joi44.default.string().valid("sectionName", "classroomName", "schedule", "blockTimes", "type").required(),
43325
- value: import_joi44.default.alternatives().try(import_joi44.default.string(), import_joi44.default.array(), import_joi44.default.object()).required()
43182
+ const validation = import_joi43.default.object({
43183
+ _id: import_joi43.default.string().hex().required(),
43184
+ field: import_joi43.default.string().valid("name", "schoolYear", "gradeLevel", "adviser", "adviserName").required(),
43185
+ value: import_joi43.default.string().required()
43326
43186
  });
43327
43187
  const { error } = validation.validate({ _id, field, value });
43328
43188
  if (error) {
43329
- next(new import_nodejs_utils71.BadRequestError(error.message));
43189
+ next(new import_nodejs_utils70.BadRequestError(error.message));
43330
43190
  return;
43331
43191
  }
43332
43192
  try {
@@ -43337,21 +43197,40 @@ function useKindergartenRoutineController() {
43337
43197
  next(error2);
43338
43198
  }
43339
43199
  }
43340
- async function updateById(req, res, next) {
43200
+ async function addStudent(req, res, next) {
43341
43201
  const _id = req.params.id;
43342
- const payload = req.body;
43343
- const { error: errorId } = import_joi44.default.string().hex().required().validate(_id);
43344
- if (errorId) {
43345
- next(new import_nodejs_utils71.BadRequestError(errorId.message));
43202
+ const { studentId } = req.body;
43203
+ const validation = import_joi43.default.object({
43204
+ _id: import_joi43.default.string().hex().required(),
43205
+ studentId: import_joi43.default.string().required()
43206
+ });
43207
+ const { error } = validation.validate({ _id, studentId });
43208
+ if (error) {
43209
+ next(new import_nodejs_utils70.BadRequestError(error.message));
43346
43210
  return;
43347
43211
  }
43348
- const { error } = schemaKindergartenRoutineUpdate.validate(payload);
43212
+ try {
43213
+ const message = await _addStudentToSection(_id, studentId);
43214
+ res.json({ message });
43215
+ return;
43216
+ } catch (error2) {
43217
+ next(error2);
43218
+ }
43219
+ }
43220
+ async function removeStudent(req, res, next) {
43221
+ const _id = req.params.id;
43222
+ const { studentId } = req.body;
43223
+ const validation = import_joi43.default.object({
43224
+ _id: import_joi43.default.string().hex().required(),
43225
+ studentId: import_joi43.default.string().required()
43226
+ });
43227
+ const { error } = validation.validate({ _id, studentId });
43349
43228
  if (error) {
43350
- next(new import_nodejs_utils71.BadRequestError(error.message));
43229
+ next(new import_nodejs_utils70.BadRequestError(error.message));
43351
43230
  return;
43352
43231
  }
43353
43232
  try {
43354
- const message = await _updateById(_id, payload);
43233
+ const message = await _removeStudentFromSection(_id, studentId);
43355
43234
  res.json({ message });
43356
43235
  return;
43357
43236
  } catch (error2) {
@@ -43360,12 +43239,12 @@ function useKindergartenRoutineController() {
43360
43239
  }
43361
43240
  async function deleteById(req, res, next) {
43362
43241
  const _id = req.params.id;
43363
- const validation = import_joi44.default.object({
43364
- _id: import_joi44.default.string().hex().required()
43242
+ const validation = import_joi43.default.object({
43243
+ _id: import_joi43.default.string().hex().required()
43365
43244
  });
43366
43245
  const { error } = validation.validate({ _id });
43367
43246
  if (error) {
43368
- next(new import_nodejs_utils71.BadRequestError(error.message));
43247
+ next(new import_nodejs_utils70.BadRequestError(error.message));
43369
43248
  return;
43370
43249
  }
43371
43250
  try {
@@ -43378,386 +43257,961 @@ function useKindergartenRoutineController() {
43378
43257
  }
43379
43258
  return {
43380
43259
  add,
43260
+ generateSections,
43261
+ generateSectionPreview,
43381
43262
  getAll,
43382
43263
  getById,
43383
- getBySection,
43264
+ getByName,
43265
+ getBySchool,
43384
43266
  updateField,
43385
- updateById,
43267
+ addStudent,
43268
+ removeStudent,
43386
43269
  deleteById
43387
43270
  };
43388
43271
  }
43389
43272
 
43390
- // src/resources/section/section.service.ts
43391
- function useSectionService() {
43392
- const { getCountByGradeLevel, getByGradeLevel: getLeanerByGradeLevel } = useLearnerRepo();
43393
- const { getByGradeLevel } = useGradeLevelRepo();
43394
- const { add: createSection } = useSectionRepo();
43395
- const { add: assignStudent } = useSectionStudentRepo();
43396
- const { getAll: getAllCurriculumSubjects } = useSubjectRepo();
43397
- const { add: addSectionSubject } = useSectionSubjectRepo();
43398
- const { getById: getSchoolById } = useSchoolRepo();
43399
- const { getAll: getAllPersonnel } = usePersonnelRepo();
43400
- const { add: addTeachingLoad } = useTeachingLoadRepo();
43401
- const { getById: getKindergartenRoutineById, add: addKindergartenRoutine } = useKindergartenRoutineRepo();
43402
- function distributeStudents(total, minPer, maxPer) {
43403
- if (total <= 0)
43404
- return [];
43405
- if (minPer <= 0 || maxPer <= 0)
43406
- return [];
43407
- if (minPer > maxPer) {
43408
- throw new import_nodejs_utils72.BadRequestError(
43409
- "Minimum students per section cannot be greater than maximum."
43410
- );
43273
+ // src/resources/section-student/section.student.controller.ts
43274
+ var import_nodejs_utils71 = require("@eeplatform/nodejs-utils");
43275
+ var import_joi44 = __toESM(require("joi"));
43276
+ function useSectionStudentController() {
43277
+ const { add: _add, getAll: _getAll } = useSectionStudentRepo();
43278
+ async function add(req, res, next) {
43279
+ const value = req.body;
43280
+ const { error } = schemaSectionStudent.validate(value);
43281
+ if (error) {
43282
+ next(new import_nodejs_utils71.BadRequestError(error.message));
43283
+ return;
43411
43284
  }
43412
- const minSections = Math.ceil(total / maxPer);
43413
- const maxSections = Math.floor(total / minPer);
43414
- let sectionCount;
43415
- if (minSections <= maxSections) {
43416
- sectionCount = minSections;
43417
- } else {
43418
- sectionCount = minSections;
43285
+ try {
43286
+ const data = await _add(value);
43287
+ res.json({
43288
+ message: "Successfully created section student.",
43289
+ data
43290
+ });
43291
+ return;
43292
+ } catch (error2) {
43293
+ next(error2);
43419
43294
  }
43420
- const base = Math.floor(total / sectionCount);
43421
- const extra = total % sectionCount;
43422
- const sizes = new Array(sectionCount).fill(base);
43423
- for (let i = 0; i < extra; i++) {
43424
- sizes[i] += 1;
43295
+ }
43296
+ async function getAll(req, res, next) {
43297
+ const query = req.query;
43298
+ const validation = import_joi44.default.object({
43299
+ page: import_joi44.default.number().min(1).optional().allow("", null),
43300
+ limit: import_joi44.default.number().min(1).optional().allow("", null),
43301
+ search: import_joi44.default.string().optional().allow("", null),
43302
+ status: import_joi44.default.string().optional().allow("", null),
43303
+ school: import_joi44.default.string().optional().allow("", null),
43304
+ gradeLevel: import_joi44.default.string().optional().allow("", null),
43305
+ section: import_joi44.default.string().optional().allow("", null),
43306
+ schoolYear: import_joi44.default.string().optional().allow("", null)
43307
+ });
43308
+ const { error } = validation.validate(query);
43309
+ const page = typeof req.query.page === "string" ? Number(req.query.page) : 1;
43310
+ const limit = typeof req.query.limit === "string" ? Number(req.query.limit) : 10;
43311
+ const search = req.query.search ?? "";
43312
+ const status = req.query.status ?? "active";
43313
+ const school = req.query.school ?? "";
43314
+ const gradeLevel = req.query.gradeLevel ?? "";
43315
+ const section = req.query.section ?? "";
43316
+ const schoolYear = req.query.schoolYear ?? "";
43317
+ const isPageNumber = isFinite(page);
43318
+ if (!isPageNumber) {
43319
+ next(new import_nodejs_utils71.BadRequestError("Invalid page number."));
43320
+ return;
43425
43321
  }
43426
- for (const size of sizes) {
43427
- if (size > maxPer) {
43428
- throw new import_nodejs_utils72.BadRequestError(
43429
- `Generated section exceeds max limit of ${maxPer}.`
43430
- );
43431
- }
43322
+ const isLimitNumber = isFinite(limit);
43323
+ if (!isLimitNumber) {
43324
+ next(new import_nodejs_utils71.BadRequestError("Invalid limit number."));
43325
+ return;
43432
43326
  }
43433
- return sizes;
43434
- }
43435
- async function generateSections(value) {
43436
- const { error } = schemaGenerateSections.validate(value);
43437
43327
  if (error) {
43438
- throw new import_nodejs_utils72.BadRequestError(
43439
- `Invalid section generation data: ${error.message}`
43440
- );
43328
+ next(new import_nodejs_utils71.BadRequestError(error.message));
43329
+ return;
43441
43330
  }
43442
- const session = import_nodejs_utils72.useAtlas.getClient()?.startSession();
43443
- if (!session) {
43444
- throw new Error("Unable to start database session.");
43331
+ try {
43332
+ const data = await _getAll({
43333
+ page,
43334
+ limit,
43335
+ search,
43336
+ status,
43337
+ school,
43338
+ gradeLevel,
43339
+ section,
43340
+ schoolYear
43341
+ });
43342
+ res.json(data);
43343
+ return;
43344
+ } catch (error2) {
43345
+ next(error2);
43445
43346
  }
43347
+ }
43348
+ return {
43349
+ add,
43350
+ getAll
43351
+ };
43352
+ }
43353
+
43354
+ // src/resources/building/building.model.ts
43355
+ var import_nodejs_utils72 = require("@eeplatform/nodejs-utils");
43356
+ var import_joi45 = __toESM(require("joi"));
43357
+ var import_mongodb41 = require("mongodb");
43358
+ var schemaBuilding = import_joi45.default.object({
43359
+ _id: import_joi45.default.string().hex().optional(),
43360
+ school: import_joi45.default.string().hex().required(),
43361
+ serial: import_joi45.default.string().optional().allow("", null),
43362
+ name: import_joi45.default.string().required(),
43363
+ levels: import_joi45.default.number().integer().min(1).required(),
43364
+ createdAt: import_joi45.default.date().optional().allow("", null),
43365
+ updatedAt: import_joi45.default.date().optional().allow("", null),
43366
+ deletedAt: import_joi45.default.date().optional().allow("", null),
43367
+ status: import_joi45.default.string().optional().allow("", null)
43368
+ });
43369
+ var schemaBuildingUnit = import_joi45.default.object({
43370
+ _id: import_joi45.default.string().hex().optional(),
43371
+ school: import_joi45.default.string().hex().required(),
43372
+ name: import_joi45.default.string().optional().allow("", null),
43373
+ building: import_joi45.default.string().hex().required(),
43374
+ buildingName: import_joi45.default.string().optional().allow("", null),
43375
+ level: import_joi45.default.number().integer().min(1).required(),
43376
+ category: import_joi45.default.string().required(),
43377
+ type: import_joi45.default.string().required(),
43378
+ seating_capacity: import_joi45.default.number().integer().min(0).required(),
43379
+ standing_capacity: import_joi45.default.number().integer().min(0).required(),
43380
+ description: import_joi45.default.string().optional().allow("", null),
43381
+ unit_of_measurement: import_joi45.default.string().valid("sqm").required(),
43382
+ area: import_joi45.default.number().positive().required(),
43383
+ status: import_joi45.default.string().optional().allow("", null)
43384
+ });
43385
+ var schemaUpdateOptions = import_joi45.default.object({
43386
+ name: import_joi45.default.string().optional().allow("", null),
43387
+ building: import_joi45.default.string().hex().optional().allow("", null),
43388
+ buildingName: import_joi45.default.string().optional().allow("", null),
43389
+ level: import_joi45.default.number().integer().min(1).optional().allow("", null),
43390
+ category: import_joi45.default.string().optional().allow("", null),
43391
+ type: import_joi45.default.string().optional().allow("", null),
43392
+ seating_capacity: import_joi45.default.number().integer().min(0).optional().allow("", null),
43393
+ standing_capacity: import_joi45.default.number().integer().min(0).optional().allow("", null),
43394
+ area: import_joi45.default.number().positive().optional().allow("", null)
43395
+ });
43396
+ function MBuilding(value) {
43397
+ const { error } = schemaBuilding.validate(value);
43398
+ if (error) {
43399
+ import_nodejs_utils72.logger.info(`Building Model: ${error.message}`);
43400
+ throw new import_nodejs_utils72.BadRequestError(error.message);
43401
+ }
43402
+ if (value._id && typeof value._id === "string") {
43446
43403
  try {
43447
- await session.startTransaction();
43448
- const isKindergarten = value.gradeLevel.toLowerCase() === "kindergarten";
43449
- let kindergartenRoutine = null;
43450
- if (isKindergarten) {
43451
- kindergartenRoutine = await getKindergartenRoutineById(
43452
- value.routine ?? ""
43453
- );
43454
- if (!kindergartenRoutine) {
43455
- throw new import_nodejs_utils72.BadRequestError("Kindergarten routine not found.");
43404
+ value._id = new import_mongodb41.ObjectId(value._id);
43405
+ } catch (error2) {
43406
+ throw new import_nodejs_utils72.BadRequestError("Invalid _id format");
43407
+ }
43408
+ }
43409
+ try {
43410
+ value.school = new import_mongodb41.ObjectId(value.school);
43411
+ } catch (error2) {
43412
+ throw new import_nodejs_utils72.BadRequestError("Invalid school format");
43413
+ }
43414
+ return {
43415
+ _id: value._id ?? void 0,
43416
+ school: value.school,
43417
+ serial: value.serial ?? "",
43418
+ name: value.name ?? "",
43419
+ levels: value.levels ?? 0,
43420
+ status: value.status ?? "active",
43421
+ createdAt: value.createdAt ?? /* @__PURE__ */ new Date(),
43422
+ updatedAt: value.updatedAt ?? "",
43423
+ deletedAt: value.deletedAt ?? ""
43424
+ };
43425
+ }
43426
+ function MBuildingUnit(value) {
43427
+ const { error } = schemaBuildingUnit.validate(value);
43428
+ if (error) {
43429
+ import_nodejs_utils72.logger.info(`Building Unit Model: ${error.message}`);
43430
+ throw new import_nodejs_utils72.BadRequestError(error.message);
43431
+ }
43432
+ if (value._id && typeof value._id === "string") {
43433
+ try {
43434
+ value._id = new import_mongodb41.ObjectId(value._id);
43435
+ } catch (error2) {
43436
+ throw new import_nodejs_utils72.BadRequestError("Invalid ID");
43437
+ }
43438
+ }
43439
+ try {
43440
+ value.school = new import_mongodb41.ObjectId(value.school);
43441
+ } catch (error2) {
43442
+ throw new import_nodejs_utils72.BadRequestError("Invalid school ID");
43443
+ }
43444
+ try {
43445
+ value.building = new import_mongodb41.ObjectId(value.building);
43446
+ } catch (error2) {
43447
+ throw new import_nodejs_utils72.BadRequestError("Invalid building ID");
43448
+ }
43449
+ return {
43450
+ _id: value._id ?? void 0,
43451
+ school: value.school,
43452
+ name: value.name ?? "",
43453
+ building: value.building,
43454
+ buildingName: value.buildingName ?? "",
43455
+ level: value.level ?? 0,
43456
+ category: value.category ?? "",
43457
+ type: value.type ?? "",
43458
+ seating_capacity: value.seating_capacity ?? 0,
43459
+ standing_capacity: value.standing_capacity ?? 0,
43460
+ description: value.description ?? "",
43461
+ unit_of_measurement: value.unit_of_measurement ?? "sqm",
43462
+ area: value.area ?? 0,
43463
+ status: value.status ?? "active",
43464
+ createdAt: value.createdAt ?? /* @__PURE__ */ new Date(),
43465
+ updatedAt: value.updatedAt ?? "",
43466
+ deletedAt: value.deletedAt ?? ""
43467
+ };
43468
+ }
43469
+
43470
+ // src/resources/building/building.repository.ts
43471
+ var import_nodejs_utils73 = require("@eeplatform/nodejs-utils");
43472
+ var import_mongodb42 = require("mongodb");
43473
+ function useBuildingRepo() {
43474
+ const db = import_nodejs_utils73.useAtlas.getDb();
43475
+ if (!db) {
43476
+ throw new Error("Unable to connect to server.");
43477
+ }
43478
+ const namespace_collection = "deped.buildings";
43479
+ const collection = db.collection(namespace_collection);
43480
+ const { getCache, setCache, delNamespace } = (0, import_nodejs_utils73.useCache)(namespace_collection);
43481
+ async function createIndexes() {
43482
+ try {
43483
+ await collection.createIndexes([
43484
+ { key: { name: 1 }, unique: true, name: "unique_name_index" },
43485
+ { key: { school: 1 } },
43486
+ { key: { status: 1 } }
43487
+ ]);
43488
+ } catch (error) {
43489
+ throw new Error("Failed to create index on buildings.");
43490
+ }
43491
+ }
43492
+ async function add(value, session) {
43493
+ try {
43494
+ value = MBuilding(value);
43495
+ const res = await collection.insertOne(value, { session });
43496
+ delCachedData();
43497
+ return res.insertedId;
43498
+ } catch (error) {
43499
+ import_nodejs_utils73.logger.log({
43500
+ level: "error",
43501
+ message: error.message
43502
+ });
43503
+ if (error instanceof import_nodejs_utils73.AppError) {
43504
+ throw error;
43505
+ } else {
43506
+ const isDuplicated = error.message.includes("duplicate");
43507
+ if (isDuplicated) {
43508
+ throw new import_nodejs_utils73.BadRequestError("Building already exists.");
43456
43509
  }
43510
+ throw new Error("Failed to create building.");
43457
43511
  }
43458
- const studentCount = await getCountByGradeLevel(
43459
- {
43460
- school: value.school,
43461
- schoolYear: value.schoolYear,
43462
- gradeLevel: value.gradeLevel,
43463
- specialProgram: value.specialProgram
43464
- },
43465
- session
43512
+ }
43513
+ }
43514
+ async function updateById(_id, value, session) {
43515
+ try {
43516
+ _id = new import_mongodb42.ObjectId(_id);
43517
+ } catch (error) {
43518
+ throw new import_nodejs_utils73.BadRequestError(namespace_collection + " Invalid ID.");
43519
+ }
43520
+ try {
43521
+ const res = await collection.updateOne(
43522
+ { _id },
43523
+ { $set: value },
43524
+ { session }
43466
43525
  );
43467
- if (studentCount === 0) {
43468
- throw new import_nodejs_utils72.BadRequestError("No learners found for this grade level.");
43526
+ delCachedData();
43527
+ return res;
43528
+ } catch (error) {
43529
+ import_nodejs_utils73.logger.log({
43530
+ level: "error",
43531
+ message: error.message
43532
+ });
43533
+ if (error instanceof import_nodejs_utils73.AppError) {
43534
+ throw error;
43535
+ } else {
43536
+ throw new Error("Failed to update building.");
43469
43537
  }
43470
- const gradeLevelData = await getByGradeLevel(
43471
- {
43472
- school: value.school,
43473
- gradeLevel: value.gradeLevel
43474
- },
43475
- session
43476
- );
43477
- if (!gradeLevelData) {
43478
- throw new import_nodejs_utils72.BadRequestError("Grade level not found.");
43479
- }
43480
- const minPerSection = value.minStudents ?? gradeLevelData.minNumberOfLearners;
43481
- const maxPerSection = value.maxStudents ?? gradeLevelData.maxNumberOfLearners;
43482
- const sectionsNeeded = Math.ceil(studentCount / minPerSection);
43483
- if (sectionsNeeded > value.set.length) {
43484
- throw new import_nodejs_utils72.BadRequestError(
43485
- "Insufficient number of section names in set[]."
43486
- );
43487
- }
43488
- const sectionSizes = distributeStudents(
43489
- studentCount,
43490
- minPerSection,
43491
- maxPerSection
43492
- );
43493
- if (sectionSizes.length === 0) {
43494
- throw new import_nodejs_utils72.BadRequestError("Unable to compute section sizes.");
43538
+ }
43539
+ }
43540
+ async function getAll({
43541
+ search = "",
43542
+ page = 1,
43543
+ limit = 10,
43544
+ sort = {},
43545
+ school = "",
43546
+ status = "active"
43547
+ } = {}) {
43548
+ page = page > 0 ? page - 1 : 0;
43549
+ const query = {
43550
+ status
43551
+ };
43552
+ sort = Object.keys(sort).length > 0 ? sort : { _id: -1 };
43553
+ if (search) {
43554
+ query.$text = { $search: search };
43555
+ }
43556
+ if (school) {
43557
+ try {
43558
+ query.school = new import_mongodb42.ObjectId(school);
43559
+ } catch (error) {
43560
+ throw new import_nodejs_utils73.BadRequestError("Invalid school ID.");
43495
43561
  }
43496
- const schoolData = await getSchoolById(value.school);
43497
- if (!schoolData) {
43498
- throw new import_nodejs_utils72.BadRequestError("School not found.");
43562
+ }
43563
+ const cacheParams = {
43564
+ page,
43565
+ limit,
43566
+ sort: JSON.stringify(sort)
43567
+ };
43568
+ if (search)
43569
+ cacheParams.search = search;
43570
+ if (school)
43571
+ cacheParams.school = school;
43572
+ if (status !== "active")
43573
+ cacheParams.status = status;
43574
+ const cacheKey = (0, import_nodejs_utils73.makeCacheKey)(namespace_collection, cacheParams);
43575
+ import_nodejs_utils73.logger.log({
43576
+ level: "info",
43577
+ message: `Cache key for getAll buildings: ${cacheKey}`
43578
+ });
43579
+ try {
43580
+ const cached = await getCache(cacheKey);
43581
+ if (cached) {
43582
+ import_nodejs_utils73.logger.log({
43583
+ level: "info",
43584
+ message: `Cache hit for getAll buildings: ${cacheKey}`
43585
+ });
43586
+ return cached;
43499
43587
  }
43500
- let totalStudentsProcessed = 0;
43501
- for (let i = 0; i < sectionSizes.length; i++) {
43502
- const size = sectionSizes[i];
43503
- const sectionName = value.set[i];
43504
- const section = await createSection(
43505
- {
43506
- school: value.school,
43507
- schoolYear: value.schoolYear,
43508
- gradeLevel: value.gradeLevel,
43509
- name: sectionName,
43510
- students: size
43511
- },
43512
- session
43513
- );
43514
- const skip = totalStudentsProcessed;
43515
- const learners = await getLeanerByGradeLevel(
43516
- {
43517
- school: value.school,
43518
- gradeLevel: value.gradeLevel,
43519
- skip,
43520
- limit: size
43521
- },
43522
- session
43523
- );
43524
- if (!learners.length) {
43525
- throw new import_nodejs_utils72.BadRequestError(`No learners found for section #${i + 1}.`);
43526
- }
43527
- totalStudentsProcessed += learners.length;
43528
- for (const student of learners) {
43529
- if (!student._id) {
43530
- throw new import_nodejs_utils72.BadRequestError("Learner ID is missing.");
43531
- }
43532
- if (!student.learnerInfo.lrn) {
43533
- throw new import_nodejs_utils72.BadRequestError("Learner LRN is missing.");
43534
- }
43535
- await assignStudent(
43536
- {
43537
- section: section.toString(),
43538
- lrn: student.learnerInfo.lrn,
43539
- student: student._id?.toString(),
43540
- studentName: `${student.learnerInfo.firstName} ${student.learnerInfo.lastName}`,
43541
- school: value.school,
43542
- schoolName: schoolData.name,
43543
- gradeLevel: value.gradeLevel,
43544
- educationLevel: gradeLevelData.educationLevel,
43545
- schoolYear: value.schoolYear,
43546
- status: "active"
43547
- },
43548
- session
43549
- );
43550
- }
43551
- const curriculumSubjects = await getAllCurriculumSubjects({
43552
- schoolYear: Number(value.schoolYear),
43553
- gradeLevel: value.gradeLevel,
43554
- limit: 20
43588
+ const items = await collection.aggregate([
43589
+ { $match: query },
43590
+ { $sort: sort },
43591
+ { $skip: page * limit },
43592
+ { $limit: limit }
43593
+ ]).toArray();
43594
+ const length = await collection.countDocuments(query);
43595
+ const data = (0, import_nodejs_utils73.paginate)(items, page, limit, length);
43596
+ setCache(cacheKey, data, 600).then(() => {
43597
+ import_nodejs_utils73.logger.log({
43598
+ level: "info",
43599
+ message: `Cache set for getAll buildings: ${cacheKey}`
43555
43600
  });
43556
- for (const curriculumSubject of curriculumSubjects.items) {
43557
- await addSectionSubject(
43558
- {
43559
- curriculum: curriculumSubject.curriculum.toString(),
43560
- school: value.school,
43561
- schoolName: schoolData.name,
43562
- gradeLevel: value.gradeLevel,
43563
- educationLevel: gradeLevelData.educationLevel,
43564
- schoolYear: value.schoolYear,
43565
- section: section.toString(),
43566
- sectionName,
43567
- subjectCode: curriculumSubject.subjectCode,
43568
- subjectName: curriculumSubject.subjectName,
43569
- teacher: "",
43570
- teacherName: "",
43571
- schedule: "",
43572
- daysOfWeek: [],
43573
- classroom: "",
43574
- classroomName: "",
43575
- sessionDuration: curriculumSubject.sessionDuration,
43576
- sessionFrequency: curriculumSubject.sessionFrequency,
43577
- status: "draft"
43578
- },
43579
- session
43580
- );
43581
- }
43582
- if (isKindergarten && kindergartenRoutine) {
43583
- kindergartenRoutine.section = section;
43584
- kindergartenRoutine.sectionName = sectionName;
43585
- kindergartenRoutine.type = "actual";
43586
- await addKindergartenRoutine(kindergartenRoutine, session);
43587
- }
43601
+ }).catch((err) => {
43602
+ import_nodejs_utils73.logger.log({
43603
+ level: "error",
43604
+ message: `Failed to set cache for getAll buildings: ${err.message}`
43605
+ });
43606
+ });
43607
+ return data;
43608
+ } catch (error) {
43609
+ import_nodejs_utils73.logger.log({ level: "error", message: `${error}` });
43610
+ throw error;
43611
+ }
43612
+ }
43613
+ async function getById(_id) {
43614
+ try {
43615
+ _id = new import_mongodb42.ObjectId(_id);
43616
+ } catch (error) {
43617
+ throw new import_nodejs_utils73.BadRequestError(namespace_collection + " Invalid ID.");
43618
+ }
43619
+ const cacheKey = (0, import_nodejs_utils73.makeCacheKey)(namespace_collection, { _id: String(_id) });
43620
+ try {
43621
+ const cached = await getCache(cacheKey);
43622
+ if (cached) {
43623
+ import_nodejs_utils73.logger.log({
43624
+ level: "info",
43625
+ message: `Cache hit for getById building: ${cacheKey}`
43626
+ });
43627
+ return cached;
43588
43628
  }
43589
- let pageTeacher = 1;
43590
- let pagesTeachers = 1;
43591
- let teachers = [];
43592
- do {
43593
- const teachersData = await getAllPersonnel({
43594
- school: value.school,
43595
- limit: 100
43629
+ const result = await collection.findOne({
43630
+ _id
43631
+ });
43632
+ setCache(cacheKey, result, 300).then(() => {
43633
+ import_nodejs_utils73.logger.log({
43634
+ level: "info",
43635
+ message: `Cache set for building by id: ${cacheKey}`
43596
43636
  });
43597
- pagesTeachers = teachersData.pages;
43598
- teachers.push(...teachersData.items);
43599
- pageTeacher++;
43600
- } while (pageTeacher < pagesTeachers);
43601
- if (!teachers.length) {
43602
- throw new import_nodejs_utils72.BadRequestError(
43603
- "Could not proceed, no teaching personnel found."
43604
- );
43637
+ }).catch((err) => {
43638
+ import_nodejs_utils73.logger.log({
43639
+ level: "error",
43640
+ message: `Failed to set cache for building by id: ${err.message}`
43641
+ });
43642
+ });
43643
+ return result;
43644
+ } catch (error) {
43645
+ if (error instanceof import_nodejs_utils73.AppError) {
43646
+ throw error;
43647
+ } else {
43648
+ throw new import_nodejs_utils73.InternalServerError("Failed to get building.");
43605
43649
  }
43606
- if (teachers.length) {
43607
- for (let index = 0; index < teachers.length; index++) {
43608
- const teacher = teachers[index];
43609
- if (!teacher._id) {
43610
- throw new import_nodejs_utils72.BadRequestError("Teacher ID is missing.");
43650
+ }
43651
+ }
43652
+ async function deleteById(_id, session) {
43653
+ try {
43654
+ _id = new import_mongodb42.ObjectId(_id);
43655
+ } catch (error) {
43656
+ throw new import_nodejs_utils73.BadRequestError(namespace_collection + " Invalid ID.");
43657
+ }
43658
+ try {
43659
+ const res = await collection.updateOne(
43660
+ { _id },
43661
+ { $set: { status: "deleted", deletedAt: /* @__PURE__ */ new Date() } }
43662
+ );
43663
+ delCachedData();
43664
+ return res;
43665
+ } catch (error) {
43666
+ import_nodejs_utils73.logger.log({
43667
+ level: "error",
43668
+ message: error.message
43669
+ });
43670
+ if (error instanceof import_nodejs_utils73.AppError) {
43671
+ throw error;
43672
+ } else {
43673
+ throw new import_nodejs_utils73.InternalServerError("Failed to delete building.");
43674
+ }
43675
+ }
43676
+ }
43677
+ function delCachedData() {
43678
+ delNamespace().then(() => {
43679
+ import_nodejs_utils73.logger.log({
43680
+ level: "info",
43681
+ message: `Cache namespace cleared for ${namespace_collection}`
43682
+ });
43683
+ }).catch((err) => {
43684
+ import_nodejs_utils73.logger.log({
43685
+ level: "error",
43686
+ message: `Failed to clear cache namespace for ${namespace_collection}: ${err.message}`
43687
+ });
43688
+ });
43689
+ }
43690
+ return {
43691
+ createIndexes,
43692
+ add,
43693
+ getAll,
43694
+ getById,
43695
+ updateById,
43696
+ deleteById
43697
+ };
43698
+ }
43699
+
43700
+ // src/resources/building/building.service.ts
43701
+ var import_nodejs_utils75 = require("@eeplatform/nodejs-utils");
43702
+
43703
+ // src/resources/building/building-unit.repository.ts
43704
+ var import_nodejs_utils74 = require("@eeplatform/nodejs-utils");
43705
+ var import_mongodb43 = require("mongodb");
43706
+ function useBuildingUnitRepo() {
43707
+ const db = import_nodejs_utils74.useAtlas.getDb();
43708
+ if (!db) {
43709
+ throw new Error("Unable to connect to server.");
43710
+ }
43711
+ const namespace_collection = "deped.building.units";
43712
+ const collection = db.collection(namespace_collection);
43713
+ const { getCache, setCache, delNamespace } = (0, import_nodejs_utils74.useCache)(namespace_collection);
43714
+ async function createIndexes() {
43715
+ try {
43716
+ await collection.createIndexes([
43717
+ {
43718
+ key: { name: 1, building: 1, level: 1 },
43719
+ unique: true,
43720
+ name: "unique_name_index"
43721
+ },
43722
+ { key: { school: 1 } },
43723
+ { key: { building: 1 } },
43724
+ { key: { status: 1 } },
43725
+ { key: { createdAt: 1 } },
43726
+ {
43727
+ key: {
43728
+ name: "text",
43729
+ buildingName: "text",
43730
+ category: "text",
43731
+ type: "text"
43611
43732
  }
43612
- await addTeachingLoad(
43613
- {
43614
- school: value.school,
43615
- schoolName: schoolData.name,
43616
- schoolYear: value.schoolYear,
43617
- teacher: teacher._id.toString(),
43618
- teacherName: `${teacher.firstName} ${teacher.lastName}`,
43619
- status: "draft"
43620
- },
43621
- session
43622
- );
43623
43733
  }
43734
+ ]);
43735
+ } catch (error) {
43736
+ throw new Error("Failed to create index on building units.");
43737
+ }
43738
+ }
43739
+ function delCachedData() {
43740
+ delNamespace().then(() => {
43741
+ import_nodejs_utils74.logger.log({
43742
+ level: "info",
43743
+ message: `Cache namespace cleared for ${namespace_collection}`
43744
+ });
43745
+ }).catch((err) => {
43746
+ import_nodejs_utils74.logger.log({
43747
+ level: "error",
43748
+ message: `Failed to clear cache namespace for ${namespace_collection}: ${err.message}`
43749
+ });
43750
+ });
43751
+ }
43752
+ async function add(value, session) {
43753
+ try {
43754
+ value = MBuildingUnit(value);
43755
+ const res = await collection.insertOne(value, { session });
43756
+ delCachedData();
43757
+ return res.insertedId;
43758
+ } catch (error) {
43759
+ import_nodejs_utils74.logger.log({
43760
+ level: "error",
43761
+ message: error.message
43762
+ });
43763
+ if (error instanceof import_nodejs_utils74.AppError) {
43764
+ throw error;
43765
+ } else {
43766
+ throw new Error("Failed to create building unit.");
43624
43767
  }
43625
- await session.commitTransaction();
43626
- return "Sections generated successfully.";
43768
+ }
43769
+ }
43770
+ async function updateById(_id, value, session) {
43771
+ const { error } = schemaUpdateOptions.validate(value);
43772
+ if (error) {
43773
+ throw new import_nodejs_utils74.BadRequestError(error.message);
43774
+ }
43775
+ try {
43776
+ _id = new import_mongodb43.ObjectId(_id);
43627
43777
  } catch (error2) {
43628
- await session.abortTransaction();
43629
- if (error2 instanceof import_nodejs_utils72.AppError) {
43778
+ throw new import_nodejs_utils74.BadRequestError(namespace_collection + " Invalid ID.");
43779
+ }
43780
+ try {
43781
+ const res = await collection.updateOne(
43782
+ { _id },
43783
+ { $set: value },
43784
+ { session }
43785
+ );
43786
+ delCachedData();
43787
+ return res;
43788
+ } catch (error2) {
43789
+ import_nodejs_utils74.logger.log({
43790
+ level: "error",
43791
+ message: error2.message
43792
+ });
43793
+ if (error2 instanceof import_nodejs_utils74.AppError) {
43630
43794
  throw error2;
43631
43795
  } else {
43632
- throw new import_nodejs_utils72.InternalServerError("Failed to generate sections.");
43796
+ throw new Error("Failed to create building unit.");
43633
43797
  }
43634
- } finally {
43635
- await session?.endSession();
43636
43798
  }
43637
43799
  }
43638
- async function generateSectionPreview(value) {
43639
- const { error } = schemaGenerateSections.validate(value);
43800
+ async function updateByBuildingId(building, value, session) {
43801
+ const { error } = schemaUpdateOptions.validate(value);
43640
43802
  if (error) {
43641
- throw new import_nodejs_utils72.BadRequestError(
43642
- `Invalid section generation data: ${error.message}`
43803
+ throw new import_nodejs_utils74.BadRequestError(error.message);
43804
+ }
43805
+ try {
43806
+ building = new import_mongodb43.ObjectId(building);
43807
+ } catch (error2) {
43808
+ throw new import_nodejs_utils74.BadRequestError("Invalid building ID.");
43809
+ }
43810
+ try {
43811
+ const res = await collection.updateMany(
43812
+ { building },
43813
+ { $set: value },
43814
+ { session }
43643
43815
  );
43816
+ delCachedData();
43817
+ return res;
43818
+ } catch (error2) {
43819
+ import_nodejs_utils74.logger.log({
43820
+ level: "error",
43821
+ message: error2.message
43822
+ });
43823
+ if (error2 instanceof import_nodejs_utils74.AppError) {
43824
+ throw error2;
43825
+ } else {
43826
+ throw new Error("Failed to update building unit.");
43827
+ }
43828
+ }
43829
+ }
43830
+ async function getAll({
43831
+ search = "",
43832
+ page = 1,
43833
+ limit = 10,
43834
+ sort = {},
43835
+ school = "",
43836
+ building = "",
43837
+ type = "",
43838
+ status = "active"
43839
+ } = {}) {
43840
+ page = page > 0 ? page - 1 : 0;
43841
+ const query = {
43842
+ deletedAt: { $in: ["", null] },
43843
+ status: { $in: [status, "", null] }
43844
+ };
43845
+ const cacheParams = {
43846
+ page,
43847
+ limit,
43848
+ sort: JSON.stringify(sort)
43849
+ };
43850
+ sort = Object.keys(sort).length > 0 ? sort : { _id: -1 };
43851
+ if (search) {
43852
+ query.$text = { $search: search };
43853
+ cacheParams.search = search;
43644
43854
  }
43855
+ if (school) {
43856
+ try {
43857
+ query.school = new import_mongodb43.ObjectId(school);
43858
+ } catch (error) {
43859
+ throw new import_nodejs_utils74.BadRequestError("Invalid school ID.");
43860
+ }
43861
+ cacheParams.school = school;
43862
+ }
43863
+ if (building) {
43864
+ try {
43865
+ query.building = new import_mongodb43.ObjectId(building);
43866
+ } catch (error) {
43867
+ throw new import_nodejs_utils74.BadRequestError("Invalid building ID.");
43868
+ }
43869
+ cacheParams.building = building;
43870
+ }
43871
+ if (type) {
43872
+ query.type = type;
43873
+ cacheParams.type = type;
43874
+ }
43875
+ const cacheKey = (0, import_nodejs_utils74.makeCacheKey)(namespace_collection, cacheParams);
43876
+ import_nodejs_utils74.logger.log({
43877
+ level: "info",
43878
+ message: `Cache key for getAll building units: ${cacheKey}`
43879
+ });
43645
43880
  try {
43646
- const studentCount = await getCountByGradeLevel({
43647
- school: value.school,
43648
- schoolYear: value.schoolYear,
43649
- gradeLevel: value.gradeLevel,
43650
- specialProgram: value.specialProgram
43881
+ const cached = await getCache(cacheKey);
43882
+ if (cached) {
43883
+ import_nodejs_utils74.logger.log({
43884
+ level: "info",
43885
+ message: `Cache hit for getAll building units: ${cacheKey}`
43886
+ });
43887
+ return cached;
43888
+ }
43889
+ const items = await collection.aggregate([
43890
+ { $match: query },
43891
+ { $sort: sort },
43892
+ { $skip: page * limit },
43893
+ { $limit: limit }
43894
+ ]).toArray();
43895
+ const length = await collection.countDocuments(query);
43896
+ const data = (0, import_nodejs_utils74.paginate)(items, page, limit, length);
43897
+ setCache(cacheKey, data, 600).then(() => {
43898
+ import_nodejs_utils74.logger.log({
43899
+ level: "info",
43900
+ message: `Cache set for getAll building units: ${cacheKey}`
43901
+ });
43902
+ }).catch((err) => {
43903
+ import_nodejs_utils74.logger.log({
43904
+ level: "error",
43905
+ message: `Failed to set cache for getAll building units: ${err.message}`
43906
+ });
43651
43907
  });
43652
- if (studentCount === 0) {
43653
- throw new import_nodejs_utils72.BadRequestError("No learners found for this grade level.");
43908
+ return data;
43909
+ } catch (error) {
43910
+ import_nodejs_utils74.logger.log({ level: "error", message: `${error}` });
43911
+ throw error;
43912
+ }
43913
+ }
43914
+ async function countByBuilding(building, level) {
43915
+ const query = {
43916
+ status: "active"
43917
+ };
43918
+ const cacheKeyOptions = {
43919
+ ...query,
43920
+ tag: "countByBuilding"
43921
+ };
43922
+ try {
43923
+ query.building = new import_mongodb43.ObjectId(building);
43924
+ cacheKeyOptions.building = String(building);
43925
+ } catch (error) {
43926
+ throw new import_nodejs_utils74.BadRequestError("Invalid building ID.");
43927
+ }
43928
+ if (level) {
43929
+ query.level = level;
43930
+ cacheKeyOptions.level = level;
43931
+ }
43932
+ try {
43933
+ return await collection.countDocuments(query);
43934
+ } catch (error) {
43935
+ import_nodejs_utils74.logger.log({ level: "error", message: `${error}` });
43936
+ throw new import_nodejs_utils74.InternalServerError("Failed to count building units.");
43937
+ }
43938
+ }
43939
+ async function getById(_id) {
43940
+ try {
43941
+ _id = new import_mongodb43.ObjectId(_id);
43942
+ } catch (error) {
43943
+ throw new import_nodejs_utils74.BadRequestError(namespace_collection + " Invalid ID.");
43944
+ }
43945
+ const cacheKey = (0, import_nodejs_utils74.makeCacheKey)(namespace_collection, { _id: String(_id) });
43946
+ try {
43947
+ const cached = await getCache(cacheKey);
43948
+ if (cached) {
43949
+ import_nodejs_utils74.logger.log({
43950
+ level: "info",
43951
+ message: `Cache hit for getById building unit: ${cacheKey}`
43952
+ });
43953
+ return cached;
43654
43954
  }
43655
- const gradeLevelData = await getByGradeLevel({
43656
- school: value.school,
43657
- gradeLevel: value.gradeLevel
43955
+ const result = await collection.findOne({
43956
+ _id,
43957
+ deletedAt: { $in: ["", null] }
43658
43958
  });
43659
- if (!gradeLevelData) {
43660
- throw new import_nodejs_utils72.BadRequestError("Grade level not found.");
43959
+ if (!result) {
43960
+ throw new import_nodejs_utils74.BadRequestError("Building unit not found.");
43661
43961
  }
43662
- const minPerSection = value.minStudents ?? gradeLevelData.minNumberOfLearners;
43663
- const maxPerSection = value.maxStudents ?? gradeLevelData.maxNumberOfLearners;
43664
- const sectionsNeeded = Math.ceil(studentCount / minPerSection);
43665
- if (sectionsNeeded > value.set.length) {
43666
- throw new import_nodejs_utils72.BadRequestError(
43667
- "Insufficient number of section names in set[]."
43668
- );
43962
+ setCache(cacheKey, result, 300).then(() => {
43963
+ import_nodejs_utils74.logger.log({
43964
+ level: "info",
43965
+ message: `Cache set for building unit by id: ${cacheKey}`
43966
+ });
43967
+ }).catch((err) => {
43968
+ import_nodejs_utils74.logger.log({
43969
+ level: "error",
43970
+ message: `Failed to set cache for building unit by id: ${err.message}`
43971
+ });
43972
+ });
43973
+ return result;
43974
+ } catch (error) {
43975
+ if (error instanceof import_nodejs_utils74.AppError) {
43976
+ throw error;
43977
+ } else {
43978
+ throw new import_nodejs_utils74.InternalServerError("Failed to get building unit.");
43669
43979
  }
43670
- const sectionSizes = distributeStudents(
43671
- studentCount,
43672
- minPerSection,
43673
- maxPerSection
43674
- );
43675
- if (sectionSizes.length === 0) {
43676
- throw new import_nodejs_utils72.BadRequestError("Unable to compute section sizes.");
43980
+ }
43981
+ }
43982
+ async function getByBuildingLevel(building, level) {
43983
+ try {
43984
+ building = new import_mongodb43.ObjectId(building);
43985
+ } catch (error) {
43986
+ throw new import_nodejs_utils74.BadRequestError("Invalid building ID.");
43987
+ }
43988
+ const cacheKey = (0, import_nodejs_utils74.makeCacheKey)(namespace_collection, {
43989
+ building: String(building),
43990
+ level
43991
+ });
43992
+ try {
43993
+ const cached = await getCache(cacheKey);
43994
+ if (cached) {
43995
+ import_nodejs_utils74.logger.log({
43996
+ level: "info",
43997
+ message: `Cache hit for getById building unit: ${cacheKey}`
43998
+ });
43999
+ return cached;
43677
44000
  }
43678
- const sections = sectionSizes.map((size, index) => ({
43679
- name: value.set[index],
43680
- value: size
43681
- }));
43682
- return {
43683
- totalSectionsGenerated: sectionSizes.length,
43684
- totalStudentsAssigned: studentCount,
43685
- sections
43686
- };
43687
- } catch (error2) {
43688
- if (error2 instanceof import_nodejs_utils72.AppError) {
43689
- throw error2;
44001
+ const result = await collection.findOne({
44002
+ building,
44003
+ level,
44004
+ status: "active"
44005
+ });
44006
+ setCache(cacheKey, result, 300).then(() => {
44007
+ import_nodejs_utils74.logger.log({
44008
+ level: "info",
44009
+ message: `Cache set for building unit by id: ${cacheKey}`
44010
+ });
44011
+ }).catch((err) => {
44012
+ import_nodejs_utils74.logger.log({
44013
+ level: "error",
44014
+ message: `Failed to set cache for building unit by id: ${err.message}`
44015
+ });
44016
+ });
44017
+ return result;
44018
+ } catch (error) {
44019
+ if (error instanceof import_nodejs_utils74.AppError) {
44020
+ throw error;
43690
44021
  } else {
43691
- throw new import_nodejs_utils72.InternalServerError("Failed to generate section preview.");
44022
+ throw new import_nodejs_utils74.InternalServerError("Failed to get building unit.");
43692
44023
  }
43693
44024
  }
43694
44025
  }
43695
- return { generateSections, generateSectionPreview };
44026
+ async function getByBuilding(building) {
44027
+ try {
44028
+ building = new import_mongodb43.ObjectId(building);
44029
+ } catch (error) {
44030
+ throw new import_nodejs_utils74.BadRequestError("Invalid building ID.");
44031
+ }
44032
+ const cacheKey = (0, import_nodejs_utils74.makeCacheKey)(namespace_collection, {
44033
+ building: String(building)
44034
+ });
44035
+ try {
44036
+ const cached = await getCache(cacheKey);
44037
+ if (cached) {
44038
+ import_nodejs_utils74.logger.log({
44039
+ level: "info",
44040
+ message: `Cache hit for getById building unit: ${cacheKey}`
44041
+ });
44042
+ return cached;
44043
+ }
44044
+ const result = await collection.findOne({
44045
+ building,
44046
+ status: "active"
44047
+ });
44048
+ setCache(cacheKey, result, 300).then(() => {
44049
+ import_nodejs_utils74.logger.log({
44050
+ level: "info",
44051
+ message: `Cache set for building unit by id: ${cacheKey}`
44052
+ });
44053
+ }).catch((err) => {
44054
+ import_nodejs_utils74.logger.log({
44055
+ level: "error",
44056
+ message: `Failed to set cache for building unit by id: ${err.message}`
44057
+ });
44058
+ });
44059
+ return result;
44060
+ } catch (error) {
44061
+ if (error instanceof import_nodejs_utils74.AppError) {
44062
+ throw error;
44063
+ } else {
44064
+ throw new import_nodejs_utils74.InternalServerError("Failed to get building unit.");
44065
+ }
44066
+ }
44067
+ }
44068
+ async function deleteById(_id, session) {
44069
+ try {
44070
+ _id = new import_mongodb43.ObjectId(_id);
44071
+ } catch (error) {
44072
+ throw new import_nodejs_utils74.BadRequestError(namespace_collection + " Invalid ID.");
44073
+ }
44074
+ try {
44075
+ const res = await collection.updateOne(
44076
+ { _id },
44077
+ { $set: { status: "deleted", deletedAt: /* @__PURE__ */ new Date() } },
44078
+ { session }
44079
+ );
44080
+ delCachedData();
44081
+ return "Room/Facility deleted successfully.";
44082
+ } catch (error) {
44083
+ import_nodejs_utils74.logger.log({
44084
+ level: "error",
44085
+ message: error.message
44086
+ });
44087
+ if (error instanceof import_nodejs_utils74.AppError) {
44088
+ throw error;
44089
+ } else {
44090
+ throw new Error("Failed to deleted room/facility.");
44091
+ }
44092
+ }
44093
+ }
44094
+ return {
44095
+ createIndexes,
44096
+ add,
44097
+ getAll,
44098
+ getById,
44099
+ getByBuildingLevel,
44100
+ updateById,
44101
+ getByBuilding,
44102
+ deleteById,
44103
+ updateByBuildingId,
44104
+ countByBuilding
44105
+ };
43696
44106
  }
43697
44107
 
43698
- // src/resources/section/section.controller.ts
43699
- function useSectionController() {
44108
+ // src/resources/building/building.service.ts
44109
+ function useBuildingService() {
43700
44110
  const {
43701
- add: _add,
43702
- getAll: _getAll,
44111
+ updateById: _updateById,
43703
44112
  getById: _getById,
43704
- getByName: _getByName,
43705
- getBySchool: _getBySchool,
43706
- updateFieldById: _updateFieldById,
43707
- addStudentToSection: _addStudentToSection,
43708
- removeStudentFromSection: _removeStudentFromSection,
43709
44113
  deleteById: _deleteById
43710
- } = useSectionRepo();
43711
- const {
43712
- generateSections: _generateSections,
43713
- generateSectionPreview: _generateSectionPreview
43714
- } = useSectionService();
43715
- async function add(req, res, next) {
43716
- const value = req.body;
43717
- const { error } = schemaSection.validate(value);
43718
- if (error) {
43719
- next(new import_nodejs_utils73.BadRequestError(error.message));
43720
- return;
44114
+ } = useBuildingRepo();
44115
+ const { getByBuildingLevel, getByBuilding, updateByBuildingId } = useBuildingUnitRepo();
44116
+ async function updateById(id, data) {
44117
+ data.levels = Number(data.levels);
44118
+ const session = import_nodejs_utils75.useAtlas.getClient()?.startSession();
44119
+ try {
44120
+ const building = await _getById(id);
44121
+ if (!building) {
44122
+ throw new import_nodejs_utils75.NotFoundError("Building not found.");
44123
+ }
44124
+ if (data.levels < building.levels) {
44125
+ const unit = await getByBuildingLevel(id, building.levels);
44126
+ if (unit) {
44127
+ throw new import_nodejs_utils75.BadRequestError(
44128
+ "Cannot reduce floors, there are existing building units at higher floors."
44129
+ );
44130
+ }
44131
+ }
44132
+ session?.startTransaction();
44133
+ if (building.name !== data.name) {
44134
+ await updateByBuildingId(id, { buildingName: data.name }, session);
44135
+ }
44136
+ const result = await _updateById(id, data, session);
44137
+ await session?.commitTransaction();
44138
+ return result;
44139
+ } catch (error) {
44140
+ await session?.abortTransaction();
44141
+ throw error;
44142
+ } finally {
44143
+ session?.endSession();
44144
+ }
44145
+ }
44146
+ async function deleteById(id) {
44147
+ const building = await getByBuilding(id);
44148
+ if (building) {
44149
+ throw new import_nodejs_utils75.BadRequestError(
44150
+ "Cannot delete building with existing room/facility. Please delete room/facility first."
44151
+ );
43721
44152
  }
43722
44153
  try {
43723
- const data = await _add(value);
43724
- res.json({
43725
- message: "Successfully created section.",
43726
- data
43727
- });
43728
- return;
43729
- } catch (error2) {
43730
- next(error2);
44154
+ await _deleteById(id);
44155
+ return "Building deleted successfully.";
44156
+ } catch (error) {
44157
+ throw error;
43731
44158
  }
43732
44159
  }
43733
- async function generateSections(req, res, next) {
44160
+ return {
44161
+ updateById,
44162
+ deleteById
44163
+ };
44164
+ }
44165
+
44166
+ // src/resources/building/building.controller.ts
44167
+ var import_nodejs_utils76 = require("@eeplatform/nodejs-utils");
44168
+ var import_joi46 = __toESM(require("joi"));
44169
+ function useBuildingController() {
44170
+ const { getAll: _getAll, getById: _getById, add: _add } = useBuildingRepo();
44171
+ const { updateById: _updateById, deleteById: _deleteById } = useBuildingService();
44172
+ async function createBuilding(req, res, next) {
43734
44173
  const value = req.body;
43735
- const { error } = schemaGenerateSections.validate(value);
44174
+ const validation = import_joi46.default.object({
44175
+ name: import_joi46.default.string().required(),
44176
+ school: import_joi46.default.string().hex().required(),
44177
+ levels: import_joi46.default.number().integer().min(1).required(),
44178
+ serial: import_joi46.default.string().optional().allow("", null),
44179
+ status: import_joi46.default.string().optional().allow("", null)
44180
+ });
44181
+ const { error } = validation.validate(value);
43736
44182
  if (error) {
43737
- next(new import_nodejs_utils73.BadRequestError(error.message));
44183
+ next(new import_nodejs_utils76.BadRequestError(error.message));
44184
+ import_nodejs_utils76.logger.info(`Controller: ${error.message}`);
43738
44185
  return;
43739
44186
  }
43740
44187
  try {
43741
- const data = await _generateSections(value);
43742
- res.json({
43743
- message: "Successfully created section.",
43744
- data
43745
- });
44188
+ const result = await _add(value);
44189
+ res.json(result);
43746
44190
  return;
43747
44191
  } catch (error2) {
43748
44192
  next(error2);
43749
44193
  }
43750
44194
  }
43751
- async function generateSectionPreview(req, res, next) {
44195
+ async function updateById(req, res, next) {
43752
44196
  const value = req.body;
43753
- const { error } = schemaGenerateSections.validate(value);
44197
+ const id = req.params.id ?? "";
44198
+ const validation = import_joi46.default.object({
44199
+ id: import_joi46.default.string().hex().required(),
44200
+ value: import_joi46.default.object({
44201
+ name: import_joi46.default.string().required(),
44202
+ serial: import_joi46.default.string().optional().allow("", null),
44203
+ levels: import_joi46.default.number().integer().min(1).required()
44204
+ })
44205
+ });
44206
+ const { error } = validation.validate({ id, value });
43754
44207
  if (error) {
43755
- next(new import_nodejs_utils73.BadRequestError(error.message));
44208
+ next(new import_nodejs_utils76.BadRequestError(error.message));
44209
+ import_nodejs_utils76.logger.info(`Controller: ${error.message}`);
43756
44210
  return;
43757
44211
  }
43758
44212
  try {
43759
- const data = await _generateSectionPreview(value);
43760
- res.json(data);
44213
+ const result = await _updateById(id, value);
44214
+ res.json(result);
43761
44215
  return;
43762
44216
  } catch (error2) {
43763
44217
  next(error2);
@@ -43765,48 +44219,42 @@ function useSectionController() {
43765
44219
  }
43766
44220
  async function getAll(req, res, next) {
43767
44221
  const query = req.query;
43768
- const validation = import_joi45.default.object({
43769
- page: import_joi45.default.number().min(1).optional().allow("", null),
43770
- limit: import_joi45.default.number().min(1).optional().allow("", null),
43771
- search: import_joi45.default.string().optional().allow("", null),
43772
- status: import_joi45.default.string().optional().allow("", null),
43773
- school: import_joi45.default.string().hex().optional().allow("", null),
43774
- schoolYear: import_joi45.default.string().optional().allow("", null),
43775
- gradeLevel: import_joi45.default.string().optional().allow("", null)
44222
+ const validation = import_joi46.default.object({
44223
+ page: import_joi46.default.number().min(1).optional().allow("", null),
44224
+ limit: import_joi46.default.number().min(1).optional().allow("", null),
44225
+ search: import_joi46.default.string().optional().allow("", null),
44226
+ school: import_joi46.default.string().hex().optional().allow("", null),
44227
+ status: import_joi46.default.string().optional().allow("", null)
43776
44228
  });
43777
44229
  const { error } = validation.validate(query);
43778
- const page = typeof req.query.page === "string" ? Number(req.query.page) : 1;
43779
- const limit = typeof req.query.limit === "string" ? Number(req.query.limit) : 10;
43780
- const search = req.query.search ?? "";
43781
- const status = req.query.status ?? "active";
43782
- const school = req.query.school ?? "";
43783
- const schoolYear = req.query.schoolYear ?? "";
43784
- const gradeLevel = req.query.gradeLevel ?? "";
43785
- const isPageNumber = isFinite(page);
43786
- if (!isPageNumber) {
43787
- next(new import_nodejs_utils73.BadRequestError("Invalid page number."));
43788
- return;
43789
- }
43790
- const isLimitNumber = isFinite(limit);
43791
- if (!isLimitNumber) {
43792
- next(new import_nodejs_utils73.BadRequestError("Invalid limit number."));
43793
- return;
43794
- }
43795
44230
  if (error) {
43796
- next(new import_nodejs_utils73.BadRequestError(error.message));
44231
+ next(new import_nodejs_utils76.BadRequestError(error.message));
43797
44232
  return;
43798
44233
  }
44234
+ const page = parseInt(req.query.page) ?? 1;
44235
+ let limit = parseInt(req.query.limit) ?? 20;
44236
+ limit = isNaN(limit) ? 20 : limit;
44237
+ const sort = req.query.sort ? String(req.query.sort).split(",") : "";
44238
+ const sortOrder = req.query.sortOrder ? String(req.query.sortOrder).split(",") : "";
44239
+ const sortObj = {};
44240
+ if (sort && Array.isArray(sort) && sort.length && sortOrder && Array.isArray(sortOrder) && sortOrder.length) {
44241
+ sort.forEach((field, index) => {
44242
+ sortObj[field] = sortOrder[index] === "desc" ? -1 : 1;
44243
+ });
44244
+ }
44245
+ const status = req.query.status ?? "active";
44246
+ const school = req.query.school ?? "";
44247
+ const search = req.query.search ?? "";
43799
44248
  try {
43800
- const data = await _getAll({
44249
+ const buildings = await _getAll({
43801
44250
  page,
43802
44251
  limit,
43803
- search,
44252
+ sort: sortObj,
43804
44253
  status,
43805
44254
  school,
43806
- schoolYear,
43807
- gradeLevel
44255
+ search
43808
44256
  });
43809
- res.json(data);
44257
+ res.json(buildings);
43810
44258
  return;
43811
44259
  } catch (error2) {
43812
44260
  next(error2);
@@ -43814,228 +44262,261 @@ function useSectionController() {
43814
44262
  }
43815
44263
  async function getById(req, res, next) {
43816
44264
  const id = req.params.id;
43817
- const validation = import_joi45.default.object({
43818
- id: import_joi45.default.string().hex().required()
44265
+ const validation = import_joi46.default.object({
44266
+ id: import_joi46.default.string().hex().required()
43819
44267
  });
43820
44268
  const { error } = validation.validate({ id });
43821
44269
  if (error) {
43822
- next(new import_nodejs_utils73.BadRequestError(error.message));
44270
+ next(new import_nodejs_utils76.BadRequestError(error.message));
43823
44271
  return;
43824
44272
  }
43825
44273
  try {
43826
- const data = await _getById(id);
43827
- res.json(data);
44274
+ const building = await _getById(id);
44275
+ res.json({
44276
+ message: "Successfully retrieved building.",
44277
+ data: { building }
44278
+ });
43828
44279
  return;
43829
44280
  } catch (error2) {
43830
44281
  next(error2);
43831
44282
  }
43832
44283
  }
43833
- async function getByName(req, res, next) {
43834
- const name = req.params.name;
43835
- const validation = import_joi45.default.object({
43836
- name: import_joi45.default.string().required()
44284
+ async function deleteById(req, res, next) {
44285
+ const id = req.params.id;
44286
+ const validation = import_joi46.default.object({
44287
+ id: import_joi46.default.string().hex().required()
43837
44288
  });
43838
- const { error } = validation.validate({ name });
44289
+ const { error } = validation.validate({ id });
43839
44290
  if (error) {
43840
- next(new import_nodejs_utils73.BadRequestError(error.message));
44291
+ next(new import_nodejs_utils76.BadRequestError(error.message));
43841
44292
  return;
43842
44293
  }
43843
44294
  try {
43844
- const data = await _getByName(name);
43845
- res.json({
43846
- message: "Successfully retrieved section.",
43847
- data
43848
- });
44295
+ const message = await _deleteById(id);
44296
+ res.json(message);
43849
44297
  return;
43850
44298
  } catch (error2) {
43851
44299
  next(error2);
43852
44300
  }
43853
44301
  }
43854
- async function getBySchool(req, res, next) {
43855
- const school = req.params.school;
43856
- const validation = import_joi45.default.object({
43857
- school: import_joi45.default.string().hex().required()
43858
- });
43859
- const { error } = validation.validate({ school });
43860
- if (error) {
43861
- next(new import_nodejs_utils73.BadRequestError(error.message));
43862
- return;
44302
+ return {
44303
+ createBuilding,
44304
+ getAll,
44305
+ getById,
44306
+ updateById,
44307
+ deleteById
44308
+ };
44309
+ }
44310
+
44311
+ // src/resources/building/building-unit.service.ts
44312
+ var import_nodejs_utils77 = require("@eeplatform/nodejs-utils");
44313
+ function useBuildingUnitService() {
44314
+ const {
44315
+ add: _add,
44316
+ countByBuilding,
44317
+ deleteById: _deleteById
44318
+ } = useBuildingUnitRepo();
44319
+ async function add(value) {
44320
+ const session = import_nodejs_utils77.useAtlas.getClient()?.startSession();
44321
+ if (!session) {
44322
+ throw new Error("Unable to start session for building unit service.");
43863
44323
  }
43864
44324
  try {
43865
- const data = await _getBySchool(school);
43866
- res.json({
43867
- message: "Successfully retrieved sections.",
43868
- data
43869
- });
43870
- return;
43871
- } catch (error2) {
43872
- next(error2);
44325
+ await session.startTransaction();
44326
+ const existingCount = await countByBuilding(
44327
+ value.building.building,
44328
+ value.building.level
44329
+ );
44330
+ for (let index = 0; index < value.qty; index++) {
44331
+ const unitNumber = existingCount ? existingCount + index + 1 : index + 1;
44332
+ await _add(
44333
+ { ...value.building, name: `${value.building.name} R${unitNumber}` },
44334
+ session
44335
+ );
44336
+ }
44337
+ await session.commitTransaction();
44338
+ return "Building unit added successfully.";
44339
+ } catch (error) {
44340
+ await session.abortTransaction();
44341
+ throw error;
44342
+ } finally {
44343
+ session.endSession();
43873
44344
  }
43874
44345
  }
43875
- async function updateField(req, res, next) {
43876
- const _id = req.params.id;
43877
- const { field, value } = req.body;
43878
- const validation = import_joi45.default.object({
43879
- _id: import_joi45.default.string().hex().required(),
43880
- field: import_joi45.default.string().valid("name", "schoolYear", "gradeLevel", "adviser", "adviserName").required(),
43881
- value: import_joi45.default.string().required()
43882
- });
43883
- const { error } = validation.validate({ _id, field, value });
43884
- if (error) {
43885
- next(new import_nodejs_utils73.BadRequestError(error.message));
43886
- return;
44346
+ const { getById: getSectionSubjectByClassroom } = useSectionSubjectRepo();
44347
+ async function deleteById(id) {
44348
+ if (!id) {
44349
+ throw new Error("Invalid building unit ID.");
44350
+ }
44351
+ const sectionSubject = await getSectionSubjectByClassroom(id);
44352
+ if (sectionSubject) {
44353
+ throw new Error(
44354
+ "Cannot delete building unit as it is assigned to a section subject."
44355
+ );
43887
44356
  }
43888
44357
  try {
43889
- const message = await _updateFieldById({ _id, field, value });
43890
- res.json({ message });
43891
- return;
43892
- } catch (error2) {
43893
- next(error2);
44358
+ await _deleteById(id);
44359
+ return "Building unit deleted successfully.";
44360
+ } catch (error) {
44361
+ throw new Error("Failed to delete building unit.");
43894
44362
  }
43895
44363
  }
43896
- async function addStudent(req, res, next) {
43897
- const _id = req.params.id;
43898
- const { studentId } = req.body;
43899
- const validation = import_joi45.default.object({
43900
- _id: import_joi45.default.string().hex().required(),
43901
- studentId: import_joi45.default.string().required()
44364
+ return {
44365
+ add,
44366
+ deleteById
44367
+ };
44368
+ }
44369
+
44370
+ // src/resources/building/building-unit.controller.ts
44371
+ var import_nodejs_utils78 = require("@eeplatform/nodejs-utils");
44372
+ var import_joi47 = __toESM(require("joi"));
44373
+ function useBuildingUnitController() {
44374
+ const {
44375
+ getAll: _getAll,
44376
+ getById: _getById,
44377
+ updateById: _updateById
44378
+ } = useBuildingUnitRepo();
44379
+ const { add: _add, deleteById: _deleteById } = useBuildingUnitService();
44380
+ async function add(req, res, next) {
44381
+ const data = req.body;
44382
+ const validation = import_joi47.default.object({
44383
+ building: import_joi47.default.object({
44384
+ school: import_joi47.default.string().hex().required(),
44385
+ name: import_joi47.default.string().optional().allow("", null),
44386
+ building: import_joi47.default.string().hex().required(),
44387
+ buildingName: import_joi47.default.string().optional().allow("", null),
44388
+ level: import_joi47.default.number().integer().min(1).required(),
44389
+ category: import_joi47.default.string().required(),
44390
+ type: import_joi47.default.string().required(),
44391
+ seating_capacity: import_joi47.default.number().integer().min(0).required(),
44392
+ standing_capacity: import_joi47.default.number().integer().min(0).required(),
44393
+ description: import_joi47.default.string().optional().allow("", null),
44394
+ unit_of_measurement: import_joi47.default.string().valid("sqm").required(),
44395
+ area: import_joi47.default.number().positive().required(),
44396
+ status: import_joi47.default.string().optional().allow("", null)
44397
+ }),
44398
+ qty: import_joi47.default.number().integer().min(1).max(20).optional().default(1)
43902
44399
  });
43903
- const { error } = validation.validate({ _id, studentId });
44400
+ const { error } = validation.validate(data);
43904
44401
  if (error) {
43905
- next(new import_nodejs_utils73.BadRequestError(error.message));
44402
+ next(new import_nodejs_utils78.BadRequestError(error.message));
43906
44403
  return;
43907
44404
  }
43908
44405
  try {
43909
- const message = await _addStudentToSection(_id, studentId);
43910
- res.json({ message });
43911
- return;
44406
+ const buildingUnit = await _add(data);
44407
+ res.json({
44408
+ message: "Building unit added successfully.",
44409
+ data: { buildingUnit }
44410
+ });
43912
44411
  } catch (error2) {
43913
44412
  next(error2);
43914
44413
  }
43915
44414
  }
43916
- async function removeStudent(req, res, next) {
43917
- const _id = req.params.id;
43918
- const { studentId } = req.body;
43919
- const validation = import_joi45.default.object({
43920
- _id: import_joi45.default.string().hex().required(),
43921
- studentId: import_joi45.default.string().required()
44415
+ async function updateById(req, res, next) {
44416
+ const data = req.body;
44417
+ const id = req.params.id ?? "";
44418
+ const validation = import_joi47.default.object({
44419
+ id: import_joi47.default.string().hex().required(),
44420
+ value: schemaUpdateOptions
43922
44421
  });
43923
- const { error } = validation.validate({ _id, studentId });
44422
+ const { error } = validation.validate({ id, value: data });
43924
44423
  if (error) {
43925
- next(new import_nodejs_utils73.BadRequestError(error.message));
44424
+ next(new import_nodejs_utils78.BadRequestError(error.message));
43926
44425
  return;
43927
44426
  }
43928
44427
  try {
43929
- const message = await _removeStudentFromSection(_id, studentId);
43930
- res.json({ message });
43931
- return;
44428
+ const buildingUnit = await _updateById(id, data);
44429
+ res.json({
44430
+ message: "Building unit updated successfully.",
44431
+ data: { buildingUnit }
44432
+ });
43932
44433
  } catch (error2) {
43933
44434
  next(error2);
43934
44435
  }
43935
44436
  }
43936
- async function deleteById(req, res, next) {
43937
- const _id = req.params.id;
43938
- const validation = import_joi45.default.object({
43939
- _id: import_joi45.default.string().hex().required()
44437
+ async function getAll(req, res, next) {
44438
+ const query = req.query;
44439
+ const validation = import_joi47.default.object({
44440
+ page: import_joi47.default.number().min(1).optional().allow("", null),
44441
+ limit: import_joi47.default.number().min(1).optional().allow("", null),
44442
+ search: import_joi47.default.string().optional().allow("", null),
44443
+ school: import_joi47.default.string().hex().optional().allow("", null),
44444
+ building: import_joi47.default.string().hex().optional().allow("", null),
44445
+ status: import_joi47.default.string().optional().allow("", null),
44446
+ type: import_joi47.default.string().optional().allow("", null)
43940
44447
  });
43941
- const { error } = validation.validate({ _id });
44448
+ const { error } = validation.validate(query);
43942
44449
  if (error) {
43943
- next(new import_nodejs_utils73.BadRequestError(error.message));
44450
+ next(new import_nodejs_utils78.BadRequestError(error.message));
43944
44451
  return;
43945
44452
  }
44453
+ const page = parseInt(req.query.page) ?? 1;
44454
+ let limit = parseInt(req.query.limit) ?? 20;
44455
+ limit = isNaN(limit) ? 20 : limit;
44456
+ const sort = req.query.sort ? String(req.query.sort).split(",") : "";
44457
+ const sortOrder = req.query.sortOrder ? String(req.query.sortOrder).split(",") : "";
44458
+ const sortObj = {};
44459
+ if (sort && Array.isArray(sort) && sort.length && sortOrder && Array.isArray(sortOrder) && sortOrder.length) {
44460
+ sort.forEach((field, index) => {
44461
+ sortObj[field] = sortOrder[index] === "desc" ? -1 : 1;
44462
+ });
44463
+ }
44464
+ const status = req.query.status ?? "active";
44465
+ const school = req.query.school ?? "";
44466
+ const building = req.query.building ?? "";
44467
+ const search = req.query.search ?? "";
44468
+ const type = req.query.type ?? "";
43946
44469
  try {
43947
- const message = await _deleteById(_id);
43948
- res.json({ message });
44470
+ const buildings = await _getAll({
44471
+ page,
44472
+ limit,
44473
+ sort: sortObj,
44474
+ status,
44475
+ school,
44476
+ search,
44477
+ building,
44478
+ type
44479
+ });
44480
+ res.json(buildings);
43949
44481
  return;
43950
44482
  } catch (error2) {
43951
44483
  next(error2);
43952
44484
  }
43953
44485
  }
43954
- return {
43955
- add,
43956
- generateSections,
43957
- generateSectionPreview,
43958
- getAll,
43959
- getById,
43960
- getByName,
43961
- getBySchool,
43962
- updateField,
43963
- addStudent,
43964
- removeStudent,
43965
- deleteById
43966
- };
43967
- }
43968
-
43969
- // src/resources/section-student/section.student.controller.ts
43970
- var import_nodejs_utils74 = require("@eeplatform/nodejs-utils");
43971
- var import_joi46 = __toESM(require("joi"));
43972
- function useSectionStudentController() {
43973
- const { add: _add, getAll: _getAll } = useSectionStudentRepo();
43974
- async function add(req, res, next) {
43975
- const value = req.body;
43976
- const { error } = schemaSectionStudent.validate(value);
44486
+ async function getById(req, res, next) {
44487
+ const id = req.params.id;
44488
+ const validation = import_joi47.default.object({
44489
+ id: import_joi47.default.string().hex().required()
44490
+ });
44491
+ const { error } = validation.validate({ id });
43977
44492
  if (error) {
43978
- next(new import_nodejs_utils74.BadRequestError(error.message));
44493
+ next(new import_nodejs_utils78.BadRequestError(error.message));
43979
44494
  return;
43980
44495
  }
43981
44496
  try {
43982
- const data = await _add(value);
44497
+ const buildingUnit = await _getById(id);
43983
44498
  res.json({
43984
- message: "Successfully created section student.",
43985
- data
44499
+ message: "Successfully retrieved building unit.",
44500
+ data: { buildingUnit }
43986
44501
  });
43987
44502
  return;
43988
44503
  } catch (error2) {
43989
44504
  next(error2);
43990
44505
  }
43991
44506
  }
43992
- async function getAll(req, res, next) {
43993
- const query = req.query;
43994
- const validation = import_joi46.default.object({
43995
- page: import_joi46.default.number().min(1).optional().allow("", null),
43996
- limit: import_joi46.default.number().min(1).optional().allow("", null),
43997
- search: import_joi46.default.string().optional().allow("", null),
43998
- status: import_joi46.default.string().optional().allow("", null),
43999
- school: import_joi46.default.string().optional().allow("", null),
44000
- gradeLevel: import_joi46.default.string().optional().allow("", null),
44001
- section: import_joi46.default.string().optional().allow("", null),
44002
- schoolYear: import_joi46.default.string().optional().allow("", null)
44507
+ async function deleteById(req, res, next) {
44508
+ const id = req.params.id;
44509
+ const validation = import_joi47.default.object({
44510
+ id: import_joi47.default.string().hex().required()
44003
44511
  });
44004
- const { error } = validation.validate(query);
44005
- const page = typeof req.query.page === "string" ? Number(req.query.page) : 1;
44006
- const limit = typeof req.query.limit === "string" ? Number(req.query.limit) : 10;
44007
- const search = req.query.search ?? "";
44008
- const status = req.query.status ?? "active";
44009
- const school = req.query.school ?? "";
44010
- const gradeLevel = req.query.gradeLevel ?? "";
44011
- const section = req.query.section ?? "";
44012
- const schoolYear = req.query.schoolYear ?? "";
44013
- const isPageNumber = isFinite(page);
44014
- if (!isPageNumber) {
44015
- next(new import_nodejs_utils74.BadRequestError("Invalid page number."));
44016
- return;
44017
- }
44018
- const isLimitNumber = isFinite(limit);
44019
- if (!isLimitNumber) {
44020
- next(new import_nodejs_utils74.BadRequestError("Invalid limit number."));
44021
- return;
44022
- }
44512
+ const { error } = validation.validate({ id });
44023
44513
  if (error) {
44024
- next(new import_nodejs_utils74.BadRequestError(error.message));
44514
+ next(new import_nodejs_utils78.BadRequestError(error.message));
44025
44515
  return;
44026
44516
  }
44027
44517
  try {
44028
- const data = await _getAll({
44029
- page,
44030
- limit,
44031
- search,
44032
- status,
44033
- school,
44034
- gradeLevel,
44035
- section,
44036
- schoolYear
44037
- });
44038
- res.json(data);
44518
+ const message = await _deleteById(id);
44519
+ res.json({ message });
44039
44520
  return;
44040
44521
  } catch (error2) {
44041
44522
  next(error2);
@@ -44043,403 +44524,153 @@ function useSectionStudentController() {
44043
44524
  }
44044
44525
  return {
44045
44526
  add,
44046
- getAll
44527
+ getAll,
44528
+ getById,
44529
+ updateById,
44530
+ deleteById
44047
44531
  };
44048
44532
  }
44049
44533
 
44050
- // src/resources/building/building.model.ts
44051
- var import_nodejs_utils75 = require("@eeplatform/nodejs-utils");
44052
- var import_joi47 = __toESM(require("joi"));
44053
- var import_mongodb43 = require("mongodb");
44054
- var schemaBuilding = import_joi47.default.object({
44055
- _id: import_joi47.default.string().hex().optional(),
44056
- school: import_joi47.default.string().hex().required(),
44057
- serial: import_joi47.default.string().optional().allow("", null),
44058
- name: import_joi47.default.string().required(),
44059
- levels: import_joi47.default.number().integer().min(1).required(),
44060
- createdAt: import_joi47.default.date().optional().allow("", null),
44061
- updatedAt: import_joi47.default.date().optional().allow("", null),
44062
- deletedAt: import_joi47.default.date().optional().allow("", null),
44063
- status: import_joi47.default.string().optional().allow("", null)
44064
- });
44065
- var schemaBuildingUnit = import_joi47.default.object({
44066
- _id: import_joi47.default.string().hex().optional(),
44067
- school: import_joi47.default.string().hex().required(),
44068
- name: import_joi47.default.string().optional().allow("", null),
44069
- building: import_joi47.default.string().hex().required(),
44070
- buildingName: import_joi47.default.string().optional().allow("", null),
44071
- level: import_joi47.default.number().integer().min(1).required(),
44072
- category: import_joi47.default.string().required(),
44073
- type: import_joi47.default.string().required(),
44074
- seating_capacity: import_joi47.default.number().integer().min(0).required(),
44075
- standing_capacity: import_joi47.default.number().integer().min(0).required(),
44076
- description: import_joi47.default.string().optional().allow("", null),
44077
- unit_of_measurement: import_joi47.default.string().valid("sqm").required(),
44078
- area: import_joi47.default.number().positive().required(),
44079
- status: import_joi47.default.string().optional().allow("", null)
44534
+ // src/resources/kindergarten-routine/kindergarten.routine.model.ts
44535
+ var import_nodejs_utils79 = require("@eeplatform/nodejs-utils");
44536
+ var import_joi48 = __toESM(require("joi"));
44537
+ var import_mongodb44 = require("mongodb");
44538
+ var schemaKindergartenRoutine = import_joi48.default.object({
44539
+ _id: import_joi48.default.string().hex().optional().allow(null, ""),
44540
+ title: import_joi48.default.string().max(100).required(),
44541
+ section: import_joi48.default.string().hex().optional().allow(null, ""),
44542
+ sectionName: import_joi48.default.string().max(100).optional().allow(null, ""),
44543
+ classroom: import_joi48.default.string().hex().optional().allow(null, ""),
44544
+ classroomName: import_joi48.default.string().max(100).optional().allow(null, ""),
44545
+ blockTimes: import_joi48.default.array().items(
44546
+ import_joi48.default.object({
44547
+ id: import_joi48.default.number().required(),
44548
+ title: import_joi48.default.string().required(),
44549
+ startTime: import_joi48.default.string().required(),
44550
+ endTime: import_joi48.default.string().required(),
44551
+ durationMinutes: import_joi48.default.number().required(),
44552
+ domains: import_joi48.default.array().items(import_joi48.default.string()).optional()
44553
+ })
44554
+ ).required(),
44555
+ type: import_joi48.default.string().required(),
44556
+ durationMinutes: import_joi48.default.number().optional().allow(null, 0),
44557
+ school: import_joi48.default.string().hex().required(),
44558
+ schoolYear: import_joi48.default.string().optional().allow(null, ""),
44559
+ createdAt: import_joi48.default.string().isoDate().optional().allow(null, ""),
44560
+ updatedAt: import_joi48.default.string().isoDate().optional().allow(null, ""),
44561
+ deletedAt: import_joi48.default.string().isoDate().optional().allow(null, "")
44080
44562
  });
44081
- var schemaUpdateOptions = import_joi47.default.object({
44082
- name: import_joi47.default.string().optional().allow("", null),
44083
- building: import_joi47.default.string().hex().optional().allow("", null),
44084
- buildingName: import_joi47.default.string().optional().allow("", null),
44085
- level: import_joi47.default.number().integer().min(1).optional().allow("", null),
44086
- category: import_joi47.default.string().optional().allow("", null),
44087
- type: import_joi47.default.string().optional().allow("", null),
44088
- seating_capacity: import_joi47.default.number().integer().min(0).optional().allow("", null),
44089
- standing_capacity: import_joi47.default.number().integer().min(0).optional().allow("", null),
44090
- area: import_joi47.default.number().positive().optional().allow("", null)
44563
+ var schemaKindergartenRoutineUpdate = import_joi48.default.object({
44564
+ title: import_joi48.default.string().max(100).optional().allow(null, ""),
44565
+ section: import_joi48.default.string().hex().optional().allow(null, ""),
44566
+ sectionName: import_joi48.default.string().max(100).optional().allow(null, ""),
44567
+ classroom: import_joi48.default.string().hex().optional().allow(null, ""),
44568
+ classroomName: import_joi48.default.string().max(100).optional().allow(null, ""),
44569
+ blockTimes: import_joi48.default.array().items(
44570
+ import_joi48.default.object({
44571
+ id: import_joi48.default.number().required(),
44572
+ title: import_joi48.default.string().required(),
44573
+ startTime: import_joi48.default.string().required(),
44574
+ endTime: import_joi48.default.string().required(),
44575
+ durationMinutes: import_joi48.default.number().required(),
44576
+ domains: import_joi48.default.array().items(import_joi48.default.string()).optional()
44577
+ })
44578
+ ).optional(),
44579
+ durationMinutes: import_joi48.default.number().optional().allow(null, 0)
44091
44580
  });
44092
- function MBuilding(value) {
44093
- const { error } = schemaBuilding.validate(value);
44581
+ function modelKindergartenRoutine(value) {
44582
+ const { error } = schemaKindergartenRoutine.validate(value);
44094
44583
  if (error) {
44095
- import_nodejs_utils75.logger.info(`Building Model: ${error.message}`);
44096
- throw new import_nodejs_utils75.BadRequestError(error.message);
44584
+ throw new import_nodejs_utils79.BadRequestError(
44585
+ `Invalid kindergarten routine data: ${error.message}`
44586
+ );
44097
44587
  }
44098
44588
  if (value._id && typeof value._id === "string") {
44099
44589
  try {
44100
- value._id = new import_mongodb43.ObjectId(value._id);
44590
+ value._id = new import_mongodb44.ObjectId(value._id);
44101
44591
  } catch (error2) {
44102
- throw new import_nodejs_utils75.BadRequestError("Invalid _id format");
44592
+ throw new Error("Invalid _id.");
44103
44593
  }
44104
44594
  }
44105
- try {
44106
- value.school = new import_mongodb43.ObjectId(value.school);
44107
- } catch (error2) {
44108
- throw new import_nodejs_utils75.BadRequestError("Invalid school format");
44109
- }
44110
- return {
44111
- _id: value._id ?? void 0,
44112
- school: value.school,
44113
- serial: value.serial ?? "",
44114
- name: value.name ?? "",
44115
- levels: value.levels ?? 0,
44116
- status: value.status ?? "active",
44117
- createdAt: value.createdAt ?? /* @__PURE__ */ new Date(),
44118
- updatedAt: value.updatedAt ?? "",
44119
- deletedAt: value.deletedAt ?? ""
44120
- };
44121
- }
44122
- function MBuildingUnit(value) {
44123
- const { error } = schemaBuildingUnit.validate(value);
44124
- if (error) {
44125
- import_nodejs_utils75.logger.info(`Building Unit Model: ${error.message}`);
44126
- throw new import_nodejs_utils75.BadRequestError(error.message);
44127
- }
44128
- if (value._id && typeof value._id === "string") {
44595
+ if (value.school && typeof value.school === "string") {
44129
44596
  try {
44130
- value._id = new import_mongodb43.ObjectId(value._id);
44597
+ value.school = new import_mongodb44.ObjectId(value.school);
44131
44598
  } catch (error2) {
44132
- throw new import_nodejs_utils75.BadRequestError("Invalid ID");
44133
- }
44134
- }
44135
- try {
44136
- value.school = new import_mongodb43.ObjectId(value.school);
44137
- } catch (error2) {
44138
- throw new import_nodejs_utils75.BadRequestError("Invalid school ID");
44139
- }
44140
- try {
44141
- value.building = new import_mongodb43.ObjectId(value.building);
44142
- } catch (error2) {
44143
- throw new import_nodejs_utils75.BadRequestError("Invalid building ID");
44144
- }
44145
- return {
44146
- _id: value._id ?? void 0,
44147
- school: value.school,
44148
- name: value.name ?? "",
44149
- building: value.building,
44150
- buildingName: value.buildingName ?? "",
44151
- level: value.level ?? 0,
44152
- category: value.category ?? "",
44153
- type: value.type ?? "",
44154
- seating_capacity: value.seating_capacity ?? 0,
44155
- standing_capacity: value.standing_capacity ?? 0,
44156
- description: value.description ?? "",
44157
- unit_of_measurement: value.unit_of_measurement ?? "sqm",
44158
- area: value.area ?? 0,
44159
- status: value.status ?? "active",
44160
- createdAt: value.createdAt ?? /* @__PURE__ */ new Date(),
44161
- updatedAt: value.updatedAt ?? "",
44162
- deletedAt: value.deletedAt ?? ""
44163
- };
44164
- }
44165
-
44166
- // src/resources/building/building.repository.ts
44167
- var import_nodejs_utils76 = require("@eeplatform/nodejs-utils");
44168
- var import_mongodb44 = require("mongodb");
44169
- function useBuildingRepo() {
44170
- const db = import_nodejs_utils76.useAtlas.getDb();
44171
- if (!db) {
44172
- throw new Error("Unable to connect to server.");
44173
- }
44174
- const namespace_collection = "deped.buildings";
44175
- const collection = db.collection(namespace_collection);
44176
- const { getCache, setCache, delNamespace } = (0, import_nodejs_utils76.useCache)(namespace_collection);
44177
- async function createIndexes() {
44178
- try {
44179
- await collection.createIndexes([
44180
- { key: { name: 1 }, unique: true, name: "unique_name_index" },
44181
- { key: { school: 1 } },
44182
- { key: { status: 1 } }
44183
- ]);
44184
- } catch (error) {
44185
- throw new Error("Failed to create index on buildings.");
44186
- }
44187
- }
44188
- async function add(value, session) {
44189
- try {
44190
- value = MBuilding(value);
44191
- const res = await collection.insertOne(value, { session });
44192
- delCachedData();
44193
- return res.insertedId;
44194
- } catch (error) {
44195
- import_nodejs_utils76.logger.log({
44196
- level: "error",
44197
- message: error.message
44198
- });
44199
- if (error instanceof import_nodejs_utils76.AppError) {
44200
- throw error;
44201
- } else {
44202
- const isDuplicated = error.message.includes("duplicate");
44203
- if (isDuplicated) {
44204
- throw new import_nodejs_utils76.BadRequestError("Building already exists.");
44205
- }
44206
- throw new Error("Failed to create building.");
44207
- }
44208
- }
44209
- }
44210
- async function updateById(_id, value, session) {
44211
- try {
44212
- _id = new import_mongodb44.ObjectId(_id);
44213
- } catch (error) {
44214
- throw new import_nodejs_utils76.BadRequestError(namespace_collection + " Invalid ID.");
44215
- }
44216
- try {
44217
- const res = await collection.updateOne(
44218
- { _id },
44219
- { $set: value },
44220
- { session }
44221
- );
44222
- delCachedData();
44223
- return res;
44224
- } catch (error) {
44225
- import_nodejs_utils76.logger.log({
44226
- level: "error",
44227
- message: error.message
44228
- });
44229
- if (error instanceof import_nodejs_utils76.AppError) {
44230
- throw error;
44231
- } else {
44232
- throw new Error("Failed to update building.");
44233
- }
44234
- }
44235
- }
44236
- async function getAll({
44237
- search = "",
44238
- page = 1,
44239
- limit = 10,
44240
- sort = {},
44241
- school = "",
44242
- status = "active"
44243
- } = {}) {
44244
- page = page > 0 ? page - 1 : 0;
44245
- const query = {
44246
- status
44247
- };
44248
- sort = Object.keys(sort).length > 0 ? sort : { _id: -1 };
44249
- if (search) {
44250
- query.$text = { $search: search };
44251
- }
44252
- if (school) {
44253
- try {
44254
- query.school = new import_mongodb44.ObjectId(school);
44255
- } catch (error) {
44256
- throw new import_nodejs_utils76.BadRequestError("Invalid school ID.");
44257
- }
44258
- }
44259
- const cacheParams = {
44260
- page,
44261
- limit,
44262
- sort: JSON.stringify(sort)
44263
- };
44264
- if (search)
44265
- cacheParams.search = search;
44266
- if (school)
44267
- cacheParams.school = school;
44268
- if (status !== "active")
44269
- cacheParams.status = status;
44270
- const cacheKey = (0, import_nodejs_utils76.makeCacheKey)(namespace_collection, cacheParams);
44271
- import_nodejs_utils76.logger.log({
44272
- level: "info",
44273
- message: `Cache key for getAll buildings: ${cacheKey}`
44274
- });
44275
- try {
44276
- const cached = await getCache(cacheKey);
44277
- if (cached) {
44278
- import_nodejs_utils76.logger.log({
44279
- level: "info",
44280
- message: `Cache hit for getAll buildings: ${cacheKey}`
44281
- });
44282
- return cached;
44283
- }
44284
- const items = await collection.aggregate([
44285
- { $match: query },
44286
- { $sort: sort },
44287
- { $skip: page * limit },
44288
- { $limit: limit }
44289
- ]).toArray();
44290
- const length = await collection.countDocuments(query);
44291
- const data = (0, import_nodejs_utils76.paginate)(items, page, limit, length);
44292
- setCache(cacheKey, data, 600).then(() => {
44293
- import_nodejs_utils76.logger.log({
44294
- level: "info",
44295
- message: `Cache set for getAll buildings: ${cacheKey}`
44296
- });
44297
- }).catch((err) => {
44298
- import_nodejs_utils76.logger.log({
44299
- level: "error",
44300
- message: `Failed to set cache for getAll buildings: ${err.message}`
44301
- });
44302
- });
44303
- return data;
44304
- } catch (error) {
44305
- import_nodejs_utils76.logger.log({ level: "error", message: `${error}` });
44306
- throw error;
44599
+ throw new Error("Invalid school.");
44307
44600
  }
44308
44601
  }
44309
- async function getById(_id) {
44310
- try {
44311
- _id = new import_mongodb44.ObjectId(_id);
44312
- } catch (error) {
44313
- throw new import_nodejs_utils76.BadRequestError(namespace_collection + " Invalid ID.");
44314
- }
44315
- const cacheKey = (0, import_nodejs_utils76.makeCacheKey)(namespace_collection, { _id: String(_id) });
44602
+ if (value.section && typeof value.section === "string") {
44316
44603
  try {
44317
- const cached = await getCache(cacheKey);
44318
- if (cached) {
44319
- import_nodejs_utils76.logger.log({
44320
- level: "info",
44321
- message: `Cache hit for getById building: ${cacheKey}`
44322
- });
44323
- return cached;
44324
- }
44325
- const result = await collection.findOne({
44326
- _id
44327
- });
44328
- setCache(cacheKey, result, 300).then(() => {
44329
- import_nodejs_utils76.logger.log({
44330
- level: "info",
44331
- message: `Cache set for building by id: ${cacheKey}`
44332
- });
44333
- }).catch((err) => {
44334
- import_nodejs_utils76.logger.log({
44335
- level: "error",
44336
- message: `Failed to set cache for building by id: ${err.message}`
44337
- });
44338
- });
44339
- return result;
44340
- } catch (error) {
44341
- if (error instanceof import_nodejs_utils76.AppError) {
44342
- throw error;
44343
- } else {
44344
- throw new import_nodejs_utils76.InternalServerError("Failed to get building.");
44345
- }
44604
+ value.section = new import_mongodb44.ObjectId(value.section);
44605
+ } catch (error2) {
44606
+ throw new Error("Invalid section.");
44346
44607
  }
44347
44608
  }
44348
- async function deleteById(_id, session) {
44349
- try {
44350
- _id = new import_mongodb44.ObjectId(_id);
44351
- } catch (error) {
44352
- throw new import_nodejs_utils76.BadRequestError(namespace_collection + " Invalid ID.");
44353
- }
44609
+ if (value.classroom && typeof value.classroom === "string") {
44354
44610
  try {
44355
- const res = await collection.updateOne(
44356
- { _id },
44357
- { $set: { status: "deleted", deletedAt: /* @__PURE__ */ new Date() } }
44358
- );
44359
- delCachedData();
44360
- return res;
44361
- } catch (error) {
44362
- import_nodejs_utils76.logger.log({
44363
- level: "error",
44364
- message: error.message
44365
- });
44366
- if (error instanceof import_nodejs_utils76.AppError) {
44367
- throw error;
44368
- } else {
44369
- throw new import_nodejs_utils76.InternalServerError("Failed to delete building.");
44370
- }
44611
+ value.classroom = new import_mongodb44.ObjectId(value.classroom);
44612
+ } catch (error2) {
44613
+ throw new Error("Invalid classroom.");
44371
44614
  }
44372
44615
  }
44373
- function delCachedData() {
44374
- delNamespace().then(() => {
44375
- import_nodejs_utils76.logger.log({
44376
- level: "info",
44377
- message: `Cache namespace cleared for ${namespace_collection}`
44378
- });
44379
- }).catch((err) => {
44380
- import_nodejs_utils76.logger.log({
44381
- level: "error",
44382
- message: `Failed to clear cache namespace for ${namespace_collection}: ${err.message}`
44383
- });
44384
- });
44385
- }
44386
44616
  return {
44387
- createIndexes,
44388
- add,
44389
- getAll,
44390
- getById,
44391
- updateById,
44392
- deleteById
44617
+ _id: value._id,
44618
+ title: value.title,
44619
+ section: value.section,
44620
+ sectionName: value.sectionName ?? "",
44621
+ classroom: value.classroom,
44622
+ classroomName: value.classroomName ?? "",
44623
+ blockTimes: value.blockTimes,
44624
+ type: value.type,
44625
+ durationMinutes: value.durationMinutes ?? 0,
44626
+ status: value.status ?? "active",
44627
+ school: value.school,
44628
+ schoolYear: value.schoolYear ?? "",
44629
+ createdAt: value.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
44630
+ updatedAt: value.updatedAt ?? "",
44631
+ deletedAt: value.deletedAt ?? ""
44393
44632
  };
44394
44633
  }
44395
44634
 
44396
- // src/resources/building/building.service.ts
44397
- var import_nodejs_utils78 = require("@eeplatform/nodejs-utils");
44398
-
44399
- // src/resources/building/building-unit.repository.ts
44400
- var import_nodejs_utils77 = require("@eeplatform/nodejs-utils");
44635
+ // src/resources/kindergarten-routine/kindergarten.routine.repository.ts
44636
+ var import_nodejs_utils80 = require("@eeplatform/nodejs-utils");
44401
44637
  var import_mongodb45 = require("mongodb");
44402
- function useBuildingUnitRepo() {
44403
- const db = import_nodejs_utils77.useAtlas.getDb();
44638
+ function useKindergartenRoutineRepo() {
44639
+ const db = import_nodejs_utils80.useAtlas.getDb();
44404
44640
  if (!db) {
44405
44641
  throw new Error("Unable to connect to server.");
44406
44642
  }
44407
- const namespace_collection = "deped.building.units";
44643
+ const namespace_collection = "deped.kindergarten.routines";
44408
44644
  const collection = db.collection(namespace_collection);
44409
- const { getCache, setCache, delNamespace } = (0, import_nodejs_utils77.useCache)(namespace_collection);
44645
+ const { getCache, setCache, delNamespace } = (0, import_nodejs_utils80.useCache)(namespace_collection);
44410
44646
  async function createIndexes() {
44411
44647
  try {
44412
44648
  await collection.createIndexes([
44413
- {
44414
- key: { name: 1, building: 1, level: 1 },
44415
- unique: true,
44416
- name: "unique_name_index"
44417
- },
44418
- { key: { school: 1 } },
44419
- { key: { building: 1 } },
44420
- { key: { status: 1 } },
44649
+ { key: { section: 1 } },
44650
+ { key: { classroom: 1 } },
44651
+ { key: { schedule: 1 } },
44652
+ { key: { type: 1 } },
44421
44653
  { key: { createdAt: 1 } },
44654
+ { key: { createdBy: 1 } },
44655
+ { key: { sectionName: "text", classroomName: "text" } },
44422
44656
  {
44423
- key: {
44424
- name: "text",
44425
- buildingName: "text",
44426
- category: "text",
44427
- type: "text"
44428
- }
44657
+ key: { title: 1, school: 1, type: 1, section: 1, status: 1 },
44658
+ unique: true,
44659
+ name: "unique_kindergarten_routine"
44429
44660
  }
44430
44661
  ]);
44431
44662
  } catch (error) {
44432
- throw new Error("Failed to create index on building units.");
44663
+ throw new Error("Failed to create index on kindergarten routines.");
44433
44664
  }
44434
44665
  }
44435
44666
  function delCachedData() {
44436
44667
  delNamespace().then(() => {
44437
- import_nodejs_utils77.logger.log({
44668
+ import_nodejs_utils80.logger.log({
44438
44669
  level: "info",
44439
44670
  message: `Cache namespace cleared for ${namespace_collection}`
44440
44671
  });
44441
44672
  }).catch((err) => {
44442
- import_nodejs_utils77.logger.log({
44673
+ import_nodejs_utils80.logger.log({
44443
44674
  level: "error",
44444
44675
  message: `Failed to clear cache namespace for ${namespace_collection}: ${err.message}`
44445
44676
  });
@@ -44447,79 +44678,23 @@ function useBuildingUnitRepo() {
44447
44678
  }
44448
44679
  async function add(value, session) {
44449
44680
  try {
44450
- value = MBuildingUnit(value);
44681
+ value = modelKindergartenRoutine(value);
44451
44682
  const res = await collection.insertOne(value, { session });
44452
44683
  delCachedData();
44453
44684
  return res.insertedId;
44454
44685
  } catch (error) {
44455
- import_nodejs_utils77.logger.log({
44686
+ import_nodejs_utils80.logger.log({
44456
44687
  level: "error",
44457
44688
  message: error.message
44458
44689
  });
44459
- if (error instanceof import_nodejs_utils77.AppError) {
44690
+ if (error instanceof import_nodejs_utils80.AppError) {
44460
44691
  throw error;
44461
44692
  } else {
44462
- throw new Error("Failed to create building unit.");
44463
- }
44464
- }
44465
- }
44466
- async function updateById(_id, value, session) {
44467
- const { error } = schemaUpdateOptions.validate(value);
44468
- if (error) {
44469
- throw new import_nodejs_utils77.BadRequestError(error.message);
44470
- }
44471
- try {
44472
- _id = new import_mongodb45.ObjectId(_id);
44473
- } catch (error2) {
44474
- throw new import_nodejs_utils77.BadRequestError(namespace_collection + " Invalid ID.");
44475
- }
44476
- try {
44477
- const res = await collection.updateOne(
44478
- { _id },
44479
- { $set: value },
44480
- { session }
44481
- );
44482
- delCachedData();
44483
- return res;
44484
- } catch (error2) {
44485
- import_nodejs_utils77.logger.log({
44486
- level: "error",
44487
- message: error2.message
44488
- });
44489
- if (error2 instanceof import_nodejs_utils77.AppError) {
44490
- throw error2;
44491
- } else {
44492
- throw new Error("Failed to create building unit.");
44493
- }
44494
- }
44495
- }
44496
- async function updateByBuildingId(building, value, session) {
44497
- const { error } = schemaUpdateOptions.validate(value);
44498
- if (error) {
44499
- throw new import_nodejs_utils77.BadRequestError(error.message);
44500
- }
44501
- try {
44502
- building = new import_mongodb45.ObjectId(building);
44503
- } catch (error2) {
44504
- throw new import_nodejs_utils77.BadRequestError("Invalid building ID.");
44505
- }
44506
- try {
44507
- const res = await collection.updateMany(
44508
- { building },
44509
- { $set: value },
44510
- { session }
44511
- );
44512
- delCachedData();
44513
- return res;
44514
- } catch (error2) {
44515
- import_nodejs_utils77.logger.log({
44516
- level: "error",
44517
- message: error2.message
44518
- });
44519
- if (error2 instanceof import_nodejs_utils77.AppError) {
44520
- throw error2;
44521
- } else {
44522
- throw new Error("Failed to update building unit.");
44693
+ const isDuplicated = error.message.includes("duplicate");
44694
+ if (isDuplicated) {
44695
+ throw new import_nodejs_utils80.BadRequestError("Kinder schedule already exists.");
44696
+ }
44697
+ throw new Error("Failed to create kindergarten routine.");
44523
44698
  }
44524
44699
  }
44525
44700
  }
@@ -44528,57 +44703,81 @@ function useBuildingUnitRepo() {
44528
44703
  page = 1,
44529
44704
  limit = 10,
44530
44705
  sort = {},
44706
+ status = "active",
44707
+ createdBy,
44531
44708
  school = "",
44532
- building = "",
44709
+ section = "",
44710
+ classroom = "",
44533
44711
  type = "",
44534
- status = "active"
44712
+ schoolYear = ""
44535
44713
  } = {}) {
44536
44714
  page = page > 0 ? page - 1 : 0;
44537
44715
  const query = {
44538
44716
  deletedAt: { $in: ["", null] },
44539
- status: { $in: [status, "", null] }
44717
+ status
44540
44718
  };
44541
- const cacheParams = {
44719
+ sort = Object.keys(sort).length > 0 ? sort : { _id: 1 };
44720
+ const cacheKeyOptions = {
44721
+ status,
44542
44722
  page,
44543
44723
  limit,
44544
44724
  sort: JSON.stringify(sort)
44545
44725
  };
44546
- sort = Object.keys(sort).length > 0 ? sort : { _id: -1 };
44726
+ if (createdBy) {
44727
+ try {
44728
+ query.createdBy = new import_mongodb45.ObjectId(createdBy);
44729
+ } catch (error) {
44730
+ throw new import_nodejs_utils80.BadRequestError("Invalid createdBy ID.");
44731
+ }
44732
+ cacheKeyOptions.createdBy = createdBy;
44733
+ }
44547
44734
  if (search) {
44548
44735
  query.$text = { $search: search };
44549
- cacheParams.search = search;
44736
+ cacheKeyOptions.search = search;
44737
+ }
44738
+ if (school) {
44739
+ try {
44740
+ query.school = new import_mongodb45.ObjectId(school);
44741
+ } catch (error) {
44742
+ throw new import_nodejs_utils80.BadRequestError("Invalid school ID.");
44743
+ }
44744
+ cacheKeyOptions.school = school;
44550
44745
  }
44551
- if (school) {
44746
+ if (section) {
44552
44747
  try {
44553
- query.school = new import_mongodb45.ObjectId(school);
44748
+ query.section = new import_mongodb45.ObjectId(section);
44554
44749
  } catch (error) {
44555
- throw new import_nodejs_utils77.BadRequestError("Invalid school ID.");
44750
+ throw new import_nodejs_utils80.BadRequestError("Invalid section ID.");
44556
44751
  }
44557
- cacheParams.school = school;
44752
+ cacheKeyOptions.section = section;
44558
44753
  }
44559
- if (building) {
44754
+ if (classroom) {
44560
44755
  try {
44561
- query.building = new import_mongodb45.ObjectId(building);
44756
+ query.classroom = new import_mongodb45.ObjectId(classroom);
44562
44757
  } catch (error) {
44563
- throw new import_nodejs_utils77.BadRequestError("Invalid building ID.");
44758
+ throw new import_nodejs_utils80.BadRequestError("Invalid classroom ID.");
44564
44759
  }
44565
- cacheParams.building = building;
44760
+ cacheKeyOptions.classroom = classroom;
44566
44761
  }
44567
44762
  if (type) {
44568
44763
  query.type = type;
44569
- cacheParams.type = type;
44764
+ cacheKeyOptions.type = type;
44765
+ }
44766
+ if (schoolYear) {
44767
+ query.schoolYear = schoolYear;
44768
+ cacheKeyOptions.schoolYear = schoolYear;
44570
44769
  }
44571
- const cacheKey = (0, import_nodejs_utils77.makeCacheKey)(namespace_collection, cacheParams);
44572
- import_nodejs_utils77.logger.log({
44770
+ const cacheKey = (0, import_nodejs_utils80.makeCacheKey)(namespace_collection, cacheKeyOptions);
44771
+ import_nodejs_utils80.logger.log({
44573
44772
  level: "info",
44574
- message: `Cache key for getAll building units: ${cacheKey}`
44773
+ message: `Cache key for getAll kindergarten routines: ${cacheKey}`
44575
44774
  });
44576
44775
  try {
44577
44776
  const cached = await getCache(cacheKey);
44578
44777
  if (cached) {
44579
- import_nodejs_utils77.logger.log({
44778
+ import_nodejs_utils80.logger.log({
44580
44779
  level: "info",
44581
- message: `Cache hit for getAll building units: ${cacheKey}`
44780
+ message: `Cache hit for getAll kindergarten routines: ${cacheKey}`
44582
44781
  });
44583
44782
  return cached;
44584
44783
  }
@@ -44589,62 +44788,37 @@ function useBuildingUnitRepo() {
44589
44788
  { $limit: limit }
44590
44789
  ]).toArray();
44591
44790
  const length = await collection.countDocuments(query);
44592
- const data = (0, import_nodejs_utils77.paginate)(items, page, limit, length);
44791
+ const data = (0, import_nodejs_utils80.paginate)(items, page, limit, length);
44593
44792
  setCache(cacheKey, data, 600).then(() => {
44594
- import_nodejs_utils77.logger.log({
44793
+ import_nodejs_utils80.logger.log({
44595
44794
  level: "info",
44596
- message: `Cache set for getAll building units: ${cacheKey}`
44795
+ message: `Cache set for getAll kindergarten routines: ${cacheKey}`
44597
44796
  });
44598
44797
  }).catch((err) => {
44599
- import_nodejs_utils77.logger.log({
44798
+ import_nodejs_utils80.logger.log({
44600
44799
  level: "error",
44601
- message: `Failed to set cache for getAll building units: ${err.message}`
44800
+ message: `Failed to set cache for getAll kindergarten routines: ${err.message}`
44602
44801
  });
44603
44802
  });
44604
44803
  return data;
44605
44804
  } catch (error) {
44606
- import_nodejs_utils77.logger.log({ level: "error", message: `${error}` });
44805
+ import_nodejs_utils80.logger.log({ level: "error", message: `${error}` });
44607
44806
  throw error;
44608
44807
  }
44609
44808
  }
44610
- async function countByBuilding(building, level) {
44611
- const query = {
44612
- status: "active"
44613
- };
44614
- const cacheKeyOptions = {
44615
- ...query,
44616
- tag: "countByBuilding"
44617
- };
44618
- try {
44619
- query.building = new import_mongodb45.ObjectId(building);
44620
- cacheKeyOptions.building = String(building);
44621
- } catch (error) {
44622
- throw new import_nodejs_utils77.BadRequestError("Invalid building ID.");
44623
- }
44624
- if (level) {
44625
- query.level = level;
44626
- cacheKeyOptions.level = level;
44627
- }
44628
- try {
44629
- return await collection.countDocuments(query);
44630
- } catch (error) {
44631
- import_nodejs_utils77.logger.log({ level: "error", message: `${error}` });
44632
- throw new import_nodejs_utils77.InternalServerError("Failed to count building units.");
44633
- }
44634
- }
44635
44809
  async function getById(_id) {
44636
44810
  try {
44637
44811
  _id = new import_mongodb45.ObjectId(_id);
44638
44812
  } catch (error) {
44639
- throw new import_nodejs_utils77.BadRequestError(namespace_collection + " Invalid ID.");
44813
+ throw new import_nodejs_utils80.BadRequestError(namespace_collection + " Invalid ID.");
44640
44814
  }
44641
- const cacheKey = (0, import_nodejs_utils77.makeCacheKey)(namespace_collection, { _id: String(_id) });
44815
+ const cacheKey = (0, import_nodejs_utils80.makeCacheKey)(namespace_collection, { _id: String(_id) });
44642
44816
  try {
44643
44817
  const cached = await getCache(cacheKey);
44644
44818
  if (cached) {
44645
- import_nodejs_utils77.logger.log({
44819
+ import_nodejs_utils80.logger.log({
44646
44820
  level: "info",
44647
- message: `Cache hit for getById building unit: ${cacheKey}`
44821
+ message: `Cache hit for getById kindergarten routine: ${cacheKey}`
44648
44822
  });
44649
44823
  return cached;
44650
44824
  }
@@ -44652,305 +44826,276 @@ function useBuildingUnitRepo() {
44652
44826
  _id,
44653
44827
  deletedAt: { $in: ["", null] }
44654
44828
  });
44655
- if (!result) {
44656
- throw new import_nodejs_utils77.BadRequestError("Building unit not found.");
44657
- }
44658
44829
  setCache(cacheKey, result, 300).then(() => {
44659
- import_nodejs_utils77.logger.log({
44830
+ import_nodejs_utils80.logger.log({
44660
44831
  level: "info",
44661
- message: `Cache set for building unit by id: ${cacheKey}`
44832
+ message: `Cache set for kindergarten routine by id: ${cacheKey}`
44662
44833
  });
44663
44834
  }).catch((err) => {
44664
- import_nodejs_utils77.logger.log({
44835
+ import_nodejs_utils80.logger.log({
44665
44836
  level: "error",
44666
- message: `Failed to set cache for building unit by id: ${err.message}`
44837
+ message: `Failed to set cache for kindergarten routine by id: ${err.message}`
44667
44838
  });
44668
44839
  });
44669
44840
  return result;
44670
44841
  } catch (error) {
44671
- if (error instanceof import_nodejs_utils77.AppError) {
44842
+ if (error instanceof import_nodejs_utils80.AppError) {
44672
44843
  throw error;
44673
44844
  } else {
44674
- throw new import_nodejs_utils77.InternalServerError("Failed to get building unit.");
44845
+ throw new import_nodejs_utils80.InternalServerError("Failed to get kindergarten routine.");
44675
44846
  }
44676
44847
  }
44677
44848
  }
44678
- async function getByBuildingLevel(building, level) {
44679
- try {
44680
- building = new import_mongodb45.ObjectId(building);
44681
- } catch (error) {
44682
- throw new import_nodejs_utils77.BadRequestError("Invalid building ID.");
44683
- }
44684
- const cacheKey = (0, import_nodejs_utils77.makeCacheKey)(namespace_collection, {
44685
- building: String(building),
44686
- level
44849
+ async function countByDomain(domain) {
44850
+ const cacheKey = (0, import_nodejs_utils80.makeCacheKey)(namespace_collection, {
44851
+ domain,
44852
+ tag: "getByDomain"
44687
44853
  });
44688
44854
  try {
44689
44855
  const cached = await getCache(cacheKey);
44690
44856
  if (cached) {
44691
- import_nodejs_utils77.logger.log({
44857
+ import_nodejs_utils80.logger.log({
44692
44858
  level: "info",
44693
- message: `Cache hit for getById building unit: ${cacheKey}`
44859
+ message: `Cache hit for getById kindergarten routine: ${cacheKey}`
44694
44860
  });
44695
44861
  return cached;
44696
44862
  }
44697
- const result = await collection.findOne({
44698
- building,
44699
- level,
44863
+ const result = await collection.countDocuments({
44864
+ domain,
44700
44865
  status: "active"
44701
44866
  });
44702
44867
  setCache(cacheKey, result, 300).then(() => {
44703
- import_nodejs_utils77.logger.log({
44868
+ import_nodejs_utils80.logger.log({
44704
44869
  level: "info",
44705
- message: `Cache set for building unit by id: ${cacheKey}`
44870
+ message: `Cache set for kindergarten routine by id: ${cacheKey}`
44706
44871
  });
44707
44872
  }).catch((err) => {
44708
- import_nodejs_utils77.logger.log({
44873
+ import_nodejs_utils80.logger.log({
44709
44874
  level: "error",
44710
- message: `Failed to set cache for building unit by id: ${err.message}`
44875
+ message: `Failed to set cache for kindergarten routine by id: ${err.message}`
44711
44876
  });
44712
44877
  });
44713
44878
  return result;
44714
44879
  } catch (error) {
44715
- if (error instanceof import_nodejs_utils77.AppError) {
44880
+ if (error instanceof import_nodejs_utils80.AppError) {
44716
44881
  throw error;
44717
44882
  } else {
44718
- throw new import_nodejs_utils77.InternalServerError("Failed to get building unit.");
44883
+ throw new import_nodejs_utils80.InternalServerError("Failed to get kindergarten routine.");
44719
44884
  }
44720
44885
  }
44721
44886
  }
44722
- async function getByBuilding(building) {
44887
+ async function getBySection(section) {
44723
44888
  try {
44724
- building = new import_mongodb45.ObjectId(building);
44889
+ section = new import_mongodb45.ObjectId(section);
44725
44890
  } catch (error) {
44726
- throw new import_nodejs_utils77.BadRequestError("Invalid building ID.");
44891
+ throw new import_nodejs_utils80.BadRequestError("Invalid section ID.");
44727
44892
  }
44728
- const cacheKey = (0, import_nodejs_utils77.makeCacheKey)(namespace_collection, {
44729
- building: String(building)
44893
+ const cacheKey = (0, import_nodejs_utils80.makeCacheKey)(namespace_collection, {
44894
+ section: String(section)
44730
44895
  });
44731
44896
  try {
44732
44897
  const cached = await getCache(cacheKey);
44733
44898
  if (cached) {
44734
- import_nodejs_utils77.logger.log({
44899
+ import_nodejs_utils80.logger.log({
44735
44900
  level: "info",
44736
- message: `Cache hit for getById building unit: ${cacheKey}`
44901
+ message: `Cache hit for getBySection kindergarten routine: ${cacheKey}`
44737
44902
  });
44738
44903
  return cached;
44739
44904
  }
44740
- const result = await collection.findOne({
44741
- building,
44742
- status: "active"
44743
- });
44905
+ const result = await collection.find({
44906
+ section,
44907
+ deletedAt: { $in: ["", null] }
44908
+ }).toArray();
44744
44909
  setCache(cacheKey, result, 300).then(() => {
44745
- import_nodejs_utils77.logger.log({
44910
+ import_nodejs_utils80.logger.log({
44746
44911
  level: "info",
44747
- message: `Cache set for building unit by id: ${cacheKey}`
44912
+ message: `Cache set for kindergarten routine by section: ${cacheKey}`
44748
44913
  });
44749
44914
  }).catch((err) => {
44750
- import_nodejs_utils77.logger.log({
44915
+ import_nodejs_utils80.logger.log({
44751
44916
  level: "error",
44752
- message: `Failed to set cache for building unit by id: ${err.message}`
44917
+ message: `Failed to set cache for kindergarten routine by section: ${err.message}`
44753
44918
  });
44754
44919
  });
44755
44920
  return result;
44756
44921
  } catch (error) {
44757
- if (error instanceof import_nodejs_utils77.AppError) {
44922
+ if (error instanceof import_nodejs_utils80.AppError) {
44758
44923
  throw error;
44759
44924
  } else {
44760
- throw new import_nodejs_utils77.InternalServerError("Failed to get building unit.");
44925
+ throw new import_nodejs_utils80.InternalServerError("Failed to get kindergarten routine.");
44761
44926
  }
44762
44927
  }
44763
44928
  }
44764
- async function deleteById(_id, session) {
44929
+ async function updateFieldById({ _id, field, value } = {}, session) {
44930
+ const allowedFields = [
44931
+ "sectionName",
44932
+ "classroomName",
44933
+ "schedule",
44934
+ "blockTimes",
44935
+ "type"
44936
+ ];
44937
+ if (!allowedFields.includes(field)) {
44938
+ throw new import_nodejs_utils80.BadRequestError(
44939
+ `Field "${field}" is not allowed to be updated.`
44940
+ );
44941
+ }
44765
44942
  try {
44766
44943
  _id = new import_mongodb45.ObjectId(_id);
44767
44944
  } catch (error) {
44768
- throw new import_nodejs_utils77.BadRequestError(namespace_collection + " Invalid ID.");
44945
+ throw new import_nodejs_utils80.BadRequestError(namespace_collection + " Invalid ID.");
44769
44946
  }
44770
44947
  try {
44771
- const res = await collection.updateOne(
44772
- { _id },
44773
- { $set: { status: "deleted", deletedAt: /* @__PURE__ */ new Date() } },
44948
+ await collection.updateOne(
44949
+ { _id, deletedAt: { $in: ["", null] } },
44950
+ { $set: { [field]: value, updatedAt: (/* @__PURE__ */ new Date()).toISOString() } },
44774
44951
  { session }
44775
44952
  );
44776
44953
  delCachedData();
44777
- return "Room/Facility deleted successfully.";
44954
+ return `Successfully updated kindergarten routine ${field}.`;
44778
44955
  } catch (error) {
44779
- import_nodejs_utils77.logger.log({
44780
- level: "error",
44781
- message: error.message
44782
- });
44783
- if (error instanceof import_nodejs_utils77.AppError) {
44784
- throw error;
44785
- } else {
44786
- throw new Error("Failed to deleted room/facility.");
44787
- }
44956
+ throw new import_nodejs_utils80.InternalServerError(
44957
+ `Failed to update kindergarten routine ${field}.`
44958
+ );
44788
44959
  }
44789
44960
  }
44790
- return {
44791
- createIndexes,
44792
- add,
44793
- getAll,
44794
- getById,
44795
- getByBuildingLevel,
44796
- updateById,
44797
- getByBuilding,
44798
- deleteById,
44799
- updateByBuildingId,
44800
- countByBuilding
44801
- };
44802
- }
44803
-
44804
- // src/resources/building/building.service.ts
44805
- function useBuildingService() {
44806
- const {
44807
- updateById: _updateById,
44808
- getById: _getById,
44809
- deleteById: _deleteById
44810
- } = useBuildingRepo();
44811
- const { getByBuildingLevel, getByBuilding, updateByBuildingId } = useBuildingUnitRepo();
44812
- async function updateById(id, data) {
44813
- data.levels = Number(data.levels);
44814
- const session = import_nodejs_utils78.useAtlas.getClient()?.startSession();
44961
+ async function updateById(_id, value, session) {
44962
+ const { error } = schemaKindergartenRoutineUpdate.validate(value);
44963
+ if (error) {
44964
+ throw new import_nodejs_utils80.BadRequestError(
44965
+ `Invalid kindergarten routine data: ${error.message}`
44966
+ );
44967
+ }
44815
44968
  try {
44816
- const building = await _getById(id);
44817
- if (!building) {
44818
- throw new import_nodejs_utils78.NotFoundError("Building not found.");
44819
- }
44820
- if (data.levels < building.levels) {
44821
- const unit = await getByBuildingLevel(id, building.levels);
44822
- if (unit) {
44823
- throw new import_nodejs_utils78.BadRequestError(
44824
- "Cannot reduce floors, there are existing building units at higher floors."
44825
- );
44826
- }
44827
- }
44828
- session?.startTransaction();
44829
- if (building.name !== data.name) {
44830
- await updateByBuildingId(id, { buildingName: data.name }, session);
44831
- }
44832
- const result = await _updateById(id, data, session);
44833
- await session?.commitTransaction();
44834
- return result;
44835
- } catch (error) {
44836
- await session?.abortTransaction();
44837
- throw error;
44838
- } finally {
44839
- session?.endSession();
44969
+ _id = new import_mongodb45.ObjectId(_id);
44970
+ } catch (error2) {
44971
+ throw new import_nodejs_utils80.BadRequestError(namespace_collection + " Invalid ID.");
44840
44972
  }
44841
- }
44842
- async function deleteById(id) {
44843
- const building = await getByBuilding(id);
44844
- if (building) {
44845
- throw new import_nodejs_utils78.BadRequestError(
44846
- "Cannot delete building with existing room/facility. Please delete room/facility first."
44973
+ try {
44974
+ await collection.updateOne(
44975
+ { _id },
44976
+ { $set: { ...value, updatedAt: (/* @__PURE__ */ new Date()).toISOString() } },
44977
+ { session }
44847
44978
  );
44979
+ delCachedData();
44980
+ return `Successfully updated kindergarten routine.`;
44981
+ } catch (error2) {
44982
+ throw new import_nodejs_utils80.InternalServerError("Failed to update kindergarten routine.");
44848
44983
  }
44984
+ }
44985
+ async function deleteById(_id) {
44849
44986
  try {
44850
- await _deleteById(id);
44851
- return "Building deleted successfully.";
44987
+ _id = new import_mongodb45.ObjectId(_id);
44852
44988
  } catch (error) {
44853
- throw error;
44989
+ throw new import_nodejs_utils80.BadRequestError(namespace_collection + " Invalid ID.");
44990
+ }
44991
+ try {
44992
+ await collection.updateOne(
44993
+ { _id },
44994
+ { $set: { status: "deleted", deletedAt: (/* @__PURE__ */ new Date()).toISOString() } }
44995
+ );
44996
+ delCachedData();
44997
+ return "Successfully deleted kindergarten routine.";
44998
+ } catch (error) {
44999
+ throw new import_nodejs_utils80.InternalServerError("Failed to delete kindergarten routine.");
44854
45000
  }
44855
45001
  }
44856
45002
  return {
45003
+ createIndexes,
45004
+ add,
45005
+ getAll,
45006
+ getById,
45007
+ countByDomain,
45008
+ getBySection,
45009
+ updateFieldById,
44857
45010
  updateById,
44858
45011
  deleteById
44859
45012
  };
44860
45013
  }
44861
45014
 
44862
- // src/resources/building/building.controller.ts
44863
- var import_nodejs_utils79 = require("@eeplatform/nodejs-utils");
44864
- var import_joi48 = __toESM(require("joi"));
44865
- function useBuildingController() {
44866
- const { getAll: _getAll, getById: _getById, add: _add } = useBuildingRepo();
44867
- const { updateById: _updateById, deleteById: _deleteById } = useBuildingService();
44868
- async function createBuilding(req, res, next) {
45015
+ // src/resources/kindergarten-routine/kindergarten.routine.controller.ts
45016
+ var import_nodejs_utils81 = require("@eeplatform/nodejs-utils");
45017
+ var import_joi49 = __toESM(require("joi"));
45018
+ function useKindergartenRoutineController() {
45019
+ const {
45020
+ add: _add,
45021
+ getAll: _getAll,
45022
+ getById: _getById,
45023
+ getBySection: _getBySection,
45024
+ updateFieldById: _updateFieldById,
45025
+ deleteById: _deleteById,
45026
+ updateById: _updateById
45027
+ } = useKindergartenRoutineRepo();
45028
+ async function add(req, res, next) {
44869
45029
  const value = req.body;
44870
- const validation = import_joi48.default.object({
44871
- name: import_joi48.default.string().required(),
44872
- school: import_joi48.default.string().hex().required(),
44873
- levels: import_joi48.default.number().integer().min(1).required(),
44874
- serial: import_joi48.default.string().optional().allow("", null),
44875
- status: import_joi48.default.string().optional().allow("", null)
44876
- });
44877
- const { error } = validation.validate(value);
45030
+ const { error } = schemaKindergartenRoutine.validate(value);
44878
45031
  if (error) {
44879
- next(new import_nodejs_utils79.BadRequestError(error.message));
44880
- import_nodejs_utils79.logger.info(`Controller: ${error.message}`);
45032
+ next(new import_nodejs_utils81.BadRequestError(error.message));
44881
45033
  return;
44882
45034
  }
44883
45035
  try {
44884
- const result = await _add(value);
44885
- res.json(result);
45036
+ const data = await _add(value);
45037
+ res.json({
45038
+ message: "Successfully created kinder schedule.",
45039
+ data
45040
+ });
44886
45041
  return;
44887
45042
  } catch (error2) {
44888
45043
  next(error2);
44889
45044
  }
44890
45045
  }
44891
- async function updateById(req, res, next) {
44892
- const value = req.body;
44893
- const id = req.params.id ?? "";
44894
- const validation = import_joi48.default.object({
44895
- id: import_joi48.default.string().hex().required(),
44896
- value: import_joi48.default.object({
44897
- name: import_joi48.default.string().required(),
44898
- serial: import_joi48.default.string().optional().allow("", null),
44899
- levels: import_joi48.default.number().integer().min(1).required()
44900
- })
45046
+ async function getAll(req, res, next) {
45047
+ const query = req.query;
45048
+ const validation = import_joi49.default.object({
45049
+ page: import_joi49.default.number().min(1).optional().allow("", null),
45050
+ limit: import_joi49.default.number().min(1).optional().allow("", null),
45051
+ search: import_joi49.default.string().optional().allow("", null),
45052
+ status: import_joi49.default.string().optional().allow("", null),
45053
+ school: import_joi49.default.string().hex().optional().allow("", null),
45054
+ section: import_joi49.default.string().hex().optional().allow("", null),
45055
+ classroom: import_joi49.default.string().hex().optional().allow("", null),
45056
+ type: import_joi49.default.string().optional().allow("", null),
45057
+ createdBy: import_joi49.default.string().hex().optional().allow("", null),
45058
+ schoolYear: import_joi49.default.string().optional().allow("", null)
44901
45059
  });
44902
- const { error } = validation.validate({ id, value });
44903
- if (error) {
44904
- next(new import_nodejs_utils79.BadRequestError(error.message));
44905
- import_nodejs_utils79.logger.info(`Controller: ${error.message}`);
45060
+ const { error } = validation.validate(query);
45061
+ const page = typeof req.query.page === "string" ? Number(req.query.page) : 1;
45062
+ const limit = typeof req.query.limit === "string" ? Number(req.query.limit) : 10;
45063
+ const search = req.query.search ?? "";
45064
+ const status = req.query.status ?? "active";
45065
+ const school = req.query.school ?? "";
45066
+ const section = req.query.section ?? "";
45067
+ const classroom = req.query.classroom ?? "";
45068
+ const type = req.query.type ?? "";
45069
+ const createdBy = req.query.createdBy ?? "";
45070
+ const schoolYear = req.query.schoolYear ?? "";
45071
+ const isPageNumber = isFinite(page);
45072
+ if (!isPageNumber) {
45073
+ next(new import_nodejs_utils81.BadRequestError("Invalid page number."));
44906
45074
  return;
44907
45075
  }
44908
- try {
44909
- const result = await _updateById(id, value);
44910
- res.json(result);
45076
+ const isLimitNumber = isFinite(limit);
45077
+ if (!isLimitNumber) {
45078
+ next(new import_nodejs_utils81.BadRequestError("Invalid limit number."));
44911
45079
  return;
44912
- } catch (error2) {
44913
- next(error2);
44914
45080
  }
44915
- }
44916
- async function getAll(req, res, next) {
44917
- const query = req.query;
44918
- const validation = import_joi48.default.object({
44919
- page: import_joi48.default.number().min(1).optional().allow("", null),
44920
- limit: import_joi48.default.number().min(1).optional().allow("", null),
44921
- search: import_joi48.default.string().optional().allow("", null),
44922
- school: import_joi48.default.string().hex().optional().allow("", null),
44923
- status: import_joi48.default.string().optional().allow("", null)
44924
- });
44925
- const { error } = validation.validate(query);
44926
45081
  if (error) {
44927
- next(new import_nodejs_utils79.BadRequestError(error.message));
45082
+ next(new import_nodejs_utils81.BadRequestError(error.message));
44928
45083
  return;
44929
45084
  }
44930
- const page = parseInt(req.query.page) ?? 1;
44931
- let limit = parseInt(req.query.limit) ?? 20;
44932
- limit = isNaN(limit) ? 20 : limit;
44933
- const sort = req.query.sort ? String(req.query.sort).split(",") : "";
44934
- const sortOrder = req.query.sortOrder ? String(req.query.sortOrder).split(",") : "";
44935
- const sortObj = {};
44936
- if (sort && Array.isArray(sort) && sort.length && sortOrder && Array.isArray(sortOrder) && sortOrder.length) {
44937
- sort.forEach((field, index) => {
44938
- sortObj[field] = sortOrder[index] === "desc" ? -1 : 1;
44939
- });
44940
- }
44941
- const status = req.query.status ?? "active";
44942
- const school = req.query.school ?? "";
44943
- const search = req.query.search ?? "";
44944
45085
  try {
44945
- const buildings = await _getAll({
45086
+ const data = await _getAll({
44946
45087
  page,
44947
45088
  limit,
44948
- sort: sortObj,
45089
+ search,
44949
45090
  status,
44950
45091
  school,
44951
- search
45092
+ section,
45093
+ classroom,
45094
+ type,
45095
+ createdBy: createdBy || void 0,
45096
+ schoolYear
44952
45097
  });
44953
- res.json(buildings);
45098
+ res.json(data);
44954
45099
  return;
44955
45100
  } catch (error2) {
44956
45101
  next(error2);
@@ -44958,260 +45103,100 @@ function useBuildingController() {
44958
45103
  }
44959
45104
  async function getById(req, res, next) {
44960
45105
  const id = req.params.id;
44961
- const validation = import_joi48.default.object({
44962
- id: import_joi48.default.string().hex().required()
45106
+ const validation = import_joi49.default.object({
45107
+ id: import_joi49.default.string().hex().required()
44963
45108
  });
44964
45109
  const { error } = validation.validate({ id });
44965
45110
  if (error) {
44966
- next(new import_nodejs_utils79.BadRequestError(error.message));
45111
+ next(new import_nodejs_utils81.BadRequestError(error.message));
44967
45112
  return;
44968
45113
  }
44969
45114
  try {
44970
- const building = await _getById(id);
45115
+ const data = await _getById(id);
44971
45116
  res.json({
44972
- message: "Successfully retrieved building.",
44973
- data: { building }
45117
+ message: "Successfully retrieved kinder schedule.",
45118
+ data
44974
45119
  });
44975
45120
  return;
44976
45121
  } catch (error2) {
44977
45122
  next(error2);
44978
45123
  }
44979
45124
  }
44980
- async function deleteById(req, res, next) {
44981
- const id = req.params.id;
44982
- const validation = import_joi48.default.object({
44983
- id: import_joi48.default.string().hex().required()
44984
- });
44985
- const { error } = validation.validate({ id });
44986
- if (error) {
44987
- next(new import_nodejs_utils79.BadRequestError(error.message));
44988
- return;
44989
- }
44990
- try {
44991
- const message = await _deleteById(id);
44992
- res.json(message);
44993
- return;
44994
- } catch (error2) {
44995
- next(error2);
44996
- }
44997
- }
44998
- return {
44999
- createBuilding,
45000
- getAll,
45001
- getById,
45002
- updateById,
45003
- deleteById
45004
- };
45005
- }
45006
-
45007
- // src/resources/building/building-unit.service.ts
45008
- var import_nodejs_utils80 = require("@eeplatform/nodejs-utils");
45009
- function useBuildingUnitService() {
45010
- const {
45011
- add: _add,
45012
- countByBuilding,
45013
- deleteById: _deleteById
45014
- } = useBuildingUnitRepo();
45015
- async function add(value) {
45016
- const session = import_nodejs_utils80.useAtlas.getClient()?.startSession();
45017
- if (!session) {
45018
- throw new Error("Unable to start session for building unit service.");
45019
- }
45020
- try {
45021
- await session.startTransaction();
45022
- const existingCount = await countByBuilding(
45023
- value.building.building,
45024
- value.building.level
45025
- );
45026
- for (let index = 0; index < value.qty; index++) {
45027
- const unitNumber = existingCount ? existingCount + index + 1 : index + 1;
45028
- await _add(
45029
- { ...value.building, name: `${value.building.name} R${unitNumber}` },
45030
- session
45031
- );
45032
- }
45033
- await session.commitTransaction();
45034
- return "Building unit added successfully.";
45035
- } catch (error) {
45036
- await session.abortTransaction();
45037
- throw error;
45038
- } finally {
45039
- session.endSession();
45040
- }
45041
- }
45042
- const { getById: getSectionSubjectByClassroom } = useSectionSubjectRepo();
45043
- async function deleteById(id) {
45044
- if (!id) {
45045
- throw new Error("Invalid building unit ID.");
45046
- }
45047
- const sectionSubject = await getSectionSubjectByClassroom(id);
45048
- if (sectionSubject) {
45049
- throw new Error(
45050
- "Cannot delete building unit as it is assigned to a section subject."
45051
- );
45052
- }
45053
- try {
45054
- await _deleteById(id);
45055
- return "Building unit deleted successfully.";
45056
- } catch (error) {
45057
- throw new Error("Failed to delete building unit.");
45058
- }
45059
- }
45060
- return {
45061
- add,
45062
- deleteById
45063
- };
45064
- }
45065
-
45066
- // src/resources/building/building-unit.controller.ts
45067
- var import_nodejs_utils81 = require("@eeplatform/nodejs-utils");
45068
- var import_joi49 = __toESM(require("joi"));
45069
- function useBuildingUnitController() {
45070
- const {
45071
- getAll: _getAll,
45072
- getById: _getById,
45073
- updateById: _updateById
45074
- } = useBuildingUnitRepo();
45075
- const { add: _add, deleteById: _deleteById } = useBuildingUnitService();
45076
- async function add(req, res, next) {
45077
- const data = req.body;
45125
+ async function getBySection(req, res, next) {
45126
+ const section = req.params.section;
45078
45127
  const validation = import_joi49.default.object({
45079
- building: import_joi49.default.object({
45080
- school: import_joi49.default.string().hex().required(),
45081
- name: import_joi49.default.string().optional().allow("", null),
45082
- building: import_joi49.default.string().hex().required(),
45083
- buildingName: import_joi49.default.string().optional().allow("", null),
45084
- level: import_joi49.default.number().integer().min(1).required(),
45085
- category: import_joi49.default.string().required(),
45086
- type: import_joi49.default.string().required(),
45087
- seating_capacity: import_joi49.default.number().integer().min(0).required(),
45088
- standing_capacity: import_joi49.default.number().integer().min(0).required(),
45089
- description: import_joi49.default.string().optional().allow("", null),
45090
- unit_of_measurement: import_joi49.default.string().valid("sqm").required(),
45091
- area: import_joi49.default.number().positive().required(),
45092
- status: import_joi49.default.string().optional().allow("", null)
45093
- }),
45094
- qty: import_joi49.default.number().integer().min(1).max(20).optional().default(1)
45128
+ section: import_joi49.default.string().hex().required()
45095
45129
  });
45096
- const { error } = validation.validate(data);
45130
+ const { error } = validation.validate({ section });
45097
45131
  if (error) {
45098
45132
  next(new import_nodejs_utils81.BadRequestError(error.message));
45099
45133
  return;
45100
45134
  }
45101
45135
  try {
45102
- const buildingUnit = await _add(data);
45136
+ const data = await _getBySection(section);
45103
45137
  res.json({
45104
- message: "Building unit added successfully.",
45105
- data: { buildingUnit }
45138
+ message: "Successfully retrieved kinder schedules.",
45139
+ data
45106
45140
  });
45107
- } catch (error2) {
45108
- next(error2);
45109
- }
45110
- }
45111
- async function updateById(req, res, next) {
45112
- const data = req.body;
45113
- const id = req.params.id ?? "";
45114
- const validation = import_joi49.default.object({
45115
- id: import_joi49.default.string().hex().required(),
45116
- value: schemaUpdateOptions
45117
- });
45118
- const { error } = validation.validate({ id, value: data });
45119
- if (error) {
45120
- next(new import_nodejs_utils81.BadRequestError(error.message));
45121
45141
  return;
45122
- }
45123
- try {
45124
- const buildingUnit = await _updateById(id, data);
45125
- res.json({
45126
- message: "Building unit updated successfully.",
45127
- data: { buildingUnit }
45128
- });
45129
45142
  } catch (error2) {
45130
45143
  next(error2);
45131
45144
  }
45132
45145
  }
45133
- async function getAll(req, res, next) {
45134
- const query = req.query;
45146
+ async function updateField(req, res, next) {
45147
+ const _id = req.params.id;
45148
+ const { field, value } = req.body;
45135
45149
  const validation = import_joi49.default.object({
45136
- page: import_joi49.default.number().min(1).optional().allow("", null),
45137
- limit: import_joi49.default.number().min(1).optional().allow("", null),
45138
- search: import_joi49.default.string().optional().allow("", null),
45139
- school: import_joi49.default.string().hex().optional().allow("", null),
45140
- building: import_joi49.default.string().hex().optional().allow("", null),
45141
- status: import_joi49.default.string().optional().allow("", null),
45142
- type: import_joi49.default.string().optional().allow("", null)
45150
+ _id: import_joi49.default.string().hex().required(),
45151
+ field: import_joi49.default.string().valid("sectionName", "classroomName", "schedule", "blockTimes", "type").required(),
45152
+ value: import_joi49.default.alternatives().try(import_joi49.default.string(), import_joi49.default.array(), import_joi49.default.object()).required()
45143
45153
  });
45144
- const { error } = validation.validate(query);
45154
+ const { error } = validation.validate({ _id, field, value });
45145
45155
  if (error) {
45146
45156
  next(new import_nodejs_utils81.BadRequestError(error.message));
45147
45157
  return;
45148
45158
  }
45149
- const page = parseInt(req.query.page) ?? 1;
45150
- let limit = parseInt(req.query.limit) ?? 20;
45151
- limit = isNaN(limit) ? 20 : limit;
45152
- const sort = req.query.sort ? String(req.query.sort).split(",") : "";
45153
- const sortOrder = req.query.sortOrder ? String(req.query.sortOrder).split(",") : "";
45154
- const sortObj = {};
45155
- if (sort && Array.isArray(sort) && sort.length && sortOrder && Array.isArray(sortOrder) && sortOrder.length) {
45156
- sort.forEach((field, index) => {
45157
- sortObj[field] = sortOrder[index] === "desc" ? -1 : 1;
45158
- });
45159
- }
45160
- const status = req.query.status ?? "active";
45161
- const school = req.query.school ?? "";
45162
- const building = req.query.building ?? "";
45163
- const search = req.query.search ?? "";
45164
- const type = req.query.type ?? "";
45165
45159
  try {
45166
- const buildings = await _getAll({
45167
- page,
45168
- limit,
45169
- sort: sortObj,
45170
- status,
45171
- school,
45172
- search,
45173
- building,
45174
- type
45175
- });
45176
- res.json(buildings);
45160
+ const message = await _updateFieldById({ _id, field, value });
45161
+ res.json({ message });
45177
45162
  return;
45178
45163
  } catch (error2) {
45179
45164
  next(error2);
45180
45165
  }
45181
45166
  }
45182
- async function getById(req, res, next) {
45183
- const id = req.params.id;
45184
- const validation = import_joi49.default.object({
45185
- id: import_joi49.default.string().hex().required()
45186
- });
45187
- const { error } = validation.validate({ id });
45167
+ async function updateById(req, res, next) {
45168
+ const _id = req.params.id;
45169
+ const payload = req.body;
45170
+ const { error: errorId } = import_joi49.default.string().hex().required().validate(_id);
45171
+ if (errorId) {
45172
+ next(new import_nodejs_utils81.BadRequestError(errorId.message));
45173
+ return;
45174
+ }
45175
+ const { error } = schemaKindergartenRoutineUpdate.validate(payload);
45188
45176
  if (error) {
45189
45177
  next(new import_nodejs_utils81.BadRequestError(error.message));
45190
45178
  return;
45191
45179
  }
45192
45180
  try {
45193
- const buildingUnit = await _getById(id);
45194
- res.json({
45195
- message: "Successfully retrieved building unit.",
45196
- data: { buildingUnit }
45197
- });
45181
+ const message = await _updateById(_id, payload);
45182
+ res.json({ message });
45198
45183
  return;
45199
45184
  } catch (error2) {
45200
45185
  next(error2);
45201
45186
  }
45202
45187
  }
45203
45188
  async function deleteById(req, res, next) {
45204
- const id = req.params.id;
45189
+ const _id = req.params.id;
45205
45190
  const validation = import_joi49.default.object({
45206
- id: import_joi49.default.string().hex().required()
45191
+ _id: import_joi49.default.string().hex().required()
45207
45192
  });
45208
- const { error } = validation.validate({ id });
45193
+ const { error } = validation.validate({ _id });
45209
45194
  if (error) {
45210
45195
  next(new import_nodejs_utils81.BadRequestError(error.message));
45211
45196
  return;
45212
45197
  }
45213
45198
  try {
45214
- const message = await _deleteById(id);
45199
+ const message = await _deleteById(_id);
45215
45200
  res.json({ message });
45216
45201
  return;
45217
45202
  } catch (error2) {
@@ -45222,6 +45207,8 @@ function useBuildingUnitController() {
45222
45207
  add,
45223
45208
  getAll,
45224
45209
  getById,
45210
+ getBySection,
45211
+ updateField,
45225
45212
  updateById,
45226
45213
  deleteById
45227
45214
  };