@eeplatform/basic-edu 1.10.0 → 1.10.2

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
  }
@@ -39338,6 +39329,7 @@ var schemaSection = import_joi31.default.object({
39338
39329
  _id: import_joi31.default.string().hex().optional().allow(null, ""),
39339
39330
  school: import_joi31.default.string().hex().required(),
39340
39331
  name: import_joi31.default.string().min(1).max(100).required(),
39332
+ label: import_joi31.default.string().max(100).optional().allow(null, ""),
39341
39333
  schoolYear: import_joi31.default.string().required(),
39342
39334
  gradeLevel: import_joi31.default.string().required(),
39343
39335
  students: import_joi31.default.number().integer().min(0).optional(),
@@ -39354,8 +39346,7 @@ var schemaGenerateSections = import_joi31.default.object({
39354
39346
  gradeLevel: import_joi31.default.string().required(),
39355
39347
  minStudents: import_joi31.default.number().integer().min(1).required(),
39356
39348
  maxStudents: import_joi31.default.number().integer().min(import_joi31.default.ref("minStudents")).required(),
39357
- specialProgram: import_joi31.default.string().hex().optional().allow(null, ""),
39358
- set: import_joi31.default.array().items(import_joi31.default.string().min(1).max(100)).required()
39349
+ specialProgram: import_joi31.default.string().hex().optional().allow(null, "")
39359
39350
  });
39360
39351
  function modelSection(value) {
39361
39352
  const { error } = schemaSection.validate(value);
@@ -39387,6 +39378,7 @@ function modelSection(value) {
39387
39378
  _id: value._id,
39388
39379
  school: value.school,
39389
39380
  name: value.name,
39381
+ label: value.label ?? "",
39390
39382
  schoolYear: value.schoolYear,
39391
39383
  gradeLevel: value.gradeLevel,
39392
39384
  adviser: value.adviser,
@@ -39421,7 +39413,7 @@ function useSectionRepo() {
39421
39413
  { key: { createdAt: 1 } },
39422
39414
  { key: { name: "text", schoolYear: "text", gradeLevel: "text" } },
39423
39415
  {
39424
- key: { school: 1, name: 1, schoolYear: 1, status: 1 },
39416
+ key: { school: 1, teacher: 1, schoolYear: 1, status: 1 },
39425
39417
  unique: true,
39426
39418
  name: "unique_section"
39427
39419
  }
@@ -39448,7 +39440,7 @@ function useSectionRepo() {
39448
39440
  value = modelSection(value);
39449
39441
  const res = await collection.insertOne(value, { session });
39450
39442
  delCachedData();
39451
- return res.insertedId;
39443
+ return res.insertedId.toString();
39452
39444
  } catch (error) {
39453
39445
  import_nodejs_utils52.logger.log({
39454
39446
  level: "error",
@@ -39589,6 +39581,54 @@ function useSectionRepo() {
39589
39581
  }
39590
39582
  }
39591
39583
  }
39584
+ async function getSection(options) {
39585
+ const query = {};
39586
+ const cacheKeyOptions = { tag: "getSection" };
39587
+ try {
39588
+ query.school = new import_mongodb30.ObjectId(options.school);
39589
+ cacheKeyOptions.school = String(options.school);
39590
+ } catch (error) {
39591
+ throw new import_nodejs_utils52.BadRequestError("Invalid school ID.");
39592
+ }
39593
+ query.gradeLevel = options.gradeLevel;
39594
+ cacheKeyOptions.gradeLevel = options.gradeLevel;
39595
+ query.name = options.name;
39596
+ cacheKeyOptions.name = options.name;
39597
+ if (options.schoolYear) {
39598
+ query.schoolYear = options.schoolYear;
39599
+ cacheKeyOptions.schoolYear = options.schoolYear;
39600
+ }
39601
+ const cacheKey = (0, import_nodejs_utils52.makeCacheKey)(namespace_collection, cacheKeyOptions);
39602
+ try {
39603
+ const cached = await getCache(cacheKey);
39604
+ if (cached) {
39605
+ import_nodejs_utils52.logger.log({
39606
+ level: "info",
39607
+ message: `Cache hit for getSection: ${cacheKey}`
39608
+ });
39609
+ return cached;
39610
+ }
39611
+ const result = await collection.findOne(query);
39612
+ setCache(cacheKey, result, 300).then(() => {
39613
+ import_nodejs_utils52.logger.log({
39614
+ level: "info",
39615
+ message: `Cache set for section: ${cacheKey}`
39616
+ });
39617
+ }).catch((err) => {
39618
+ import_nodejs_utils52.logger.log({
39619
+ level: "error",
39620
+ message: `Failed to set cache for section: ${err.message}`
39621
+ });
39622
+ });
39623
+ return result;
39624
+ } catch (error) {
39625
+ if (error instanceof import_nodejs_utils52.AppError) {
39626
+ throw error;
39627
+ } else {
39628
+ throw new import_nodejs_utils52.InternalServerError("Failed to get section.");
39629
+ }
39630
+ }
39631
+ }
39592
39632
  async function getByName(name) {
39593
39633
  const cacheKey = (0, import_nodejs_utils52.makeCacheKey)(namespace_collection, { name });
39594
39634
  try {
@@ -39772,6 +39812,7 @@ function useSectionRepo() {
39772
39812
  add,
39773
39813
  getAll,
39774
39814
  getById,
39815
+ getSection,
39775
39816
  getByName,
39776
39817
  getBySchool,
39777
39818
  updateFieldById,
@@ -39782,11 +39823,11 @@ function useSectionRepo() {
39782
39823
  }
39783
39824
 
39784
39825
  // src/resources/section/section.controller.ts
39785
- var import_nodejs_utils73 = require("@eeplatform/nodejs-utils");
39786
- var import_joi45 = __toESM(require("joi"));
39826
+ var import_nodejs_utils70 = require("@eeplatform/nodejs-utils");
39827
+ var import_joi43 = __toESM(require("joi"));
39787
39828
 
39788
39829
  // src/resources/section/section.service.ts
39789
- var import_nodejs_utils72 = require("@eeplatform/nodejs-utils");
39830
+ var import_nodejs_utils69 = require("@eeplatform/nodejs-utils");
39790
39831
 
39791
39832
  // src/resources/section-student/section.student.repository.ts
39792
39833
  var import_nodejs_utils54 = require("@eeplatform/nodejs-utils");
@@ -40016,11 +40057,73 @@ function useSectionStudentRepo() {
40016
40057
  });
40017
40058
  return data;
40018
40059
  }
40060
+ async function getStudent(options) {
40061
+ const query = {};
40062
+ const cacheKeyOptions = { tag: "getStudent" };
40063
+ if (options.learner) {
40064
+ try {
40065
+ query.learner = new import_mongodb32.ObjectId(options.learner);
40066
+ cacheKeyOptions.learner = String(options.learner);
40067
+ } catch (error) {
40068
+ throw new import_nodejs_utils54.BadRequestError("Invalid learner ID.");
40069
+ }
40070
+ }
40071
+ if (options.schoolYear) {
40072
+ query.schoolYear = options.schoolYear;
40073
+ cacheKeyOptions.schoolYear = options.schoolYear;
40074
+ }
40075
+ if (options.section) {
40076
+ try {
40077
+ query.section = new import_mongodb32.ObjectId(options.section);
40078
+ cacheKeyOptions.section = String(options.section);
40079
+ } catch (error) {
40080
+ throw new import_nodejs_utils54.BadRequestError("Invalid section ID.");
40081
+ }
40082
+ }
40083
+ if (options.gradeLevel) {
40084
+ query.gradeLevel = options.gradeLevel;
40085
+ cacheKeyOptions.gradeLevel = options.gradeLevel;
40086
+ }
40087
+ try {
40088
+ query.student = new import_mongodb32.ObjectId(options.student);
40089
+ cacheKeyOptions.student = String(options.student);
40090
+ } catch (error) {
40091
+ throw new import_nodejs_utils54.BadRequestError("Invalid student ID.");
40092
+ }
40093
+ const cacheKey = (0, import_nodejs_utils54.makeCacheKey)(namespace_collection, cacheKeyOptions);
40094
+ try {
40095
+ const cached = await getCache(cacheKey);
40096
+ if (cached) {
40097
+ import_nodejs_utils54.logger.log({
40098
+ level: "info",
40099
+ message: `Cache hit for getStudent section student: ${cacheKey}`
40100
+ });
40101
+ return cached;
40102
+ }
40103
+ const item = await collection.findOne(query);
40104
+ setCache(cacheKey, item, 600).then(() => {
40105
+ import_nodejs_utils54.logger.log({
40106
+ level: "info",
40107
+ message: `Cache set for getStudent section student: ${cacheKey}`
40108
+ });
40109
+ }).catch((err) => {
40110
+ import_nodejs_utils54.logger.log({
40111
+ level: "error",
40112
+ message: `Failed to set cache for getStudent section student: ${err.message}`
40113
+ });
40114
+ });
40115
+ return item;
40116
+ } catch (error) {
40117
+ import_nodejs_utils54.logger.log({ level: "error", message: `${error}` });
40118
+ throw error;
40119
+ }
40120
+ }
40019
40121
  return {
40020
40122
  createIndexes,
40021
40123
  delCachedData,
40022
40124
  add,
40023
- getAll
40125
+ getAll,
40126
+ getStudent
40024
40127
  };
40025
40128
  }
40026
40129
 
@@ -40357,6 +40460,63 @@ function useSectionSubjectRepo() {
40357
40460
  }
40358
40461
  }
40359
40462
  }
40463
+ async function getSectionSubject(options) {
40464
+ const query = {};
40465
+ const cacheKeyOptions = { tag: "getSectionSubject" };
40466
+ if (options.gradeLevel) {
40467
+ query.gradeLevel = options.gradeLevel;
40468
+ cacheKeyOptions.gradeLevel = options.gradeLevel;
40469
+ }
40470
+ if (options.schoolYear) {
40471
+ query.schoolYear = options.schoolYear;
40472
+ cacheKeyOptions.schoolYear = options.schoolYear;
40473
+ }
40474
+ if (options.subjectCode) {
40475
+ query.subjectCode = options.subjectCode;
40476
+ cacheKeyOptions.subjectCode = options.subjectCode;
40477
+ }
40478
+ try {
40479
+ query.section = new import_mongodb34.ObjectId(options.section);
40480
+ cacheKeyOptions.section = String(options.section);
40481
+ } catch (error) {
40482
+ throw new import_nodejs_utils56.BadRequestError("Invalid section ID.");
40483
+ }
40484
+ const cacheKey = (0, import_nodejs_utils56.makeCacheKey)(namespace_collection, cacheKeyOptions);
40485
+ try {
40486
+ const cached = await getCache(cacheKey);
40487
+ if (cached) {
40488
+ import_nodejs_utils56.logger.log({
40489
+ level: "info",
40490
+ message: `Cache hit for getSectionSubject section subjects: ${cacheKey}`
40491
+ });
40492
+ return cached;
40493
+ }
40494
+ const result = await collection.find({
40495
+ ...query,
40496
+ deletedAt: { $in: ["", null] }
40497
+ }).toArray();
40498
+ setCache(cacheKey, result, 300).then(() => {
40499
+ import_nodejs_utils56.logger.log({
40500
+ level: "info",
40501
+ message: `Cache set for section subjects by getSectionSubject: ${cacheKey}`
40502
+ });
40503
+ }).catch((err) => {
40504
+ import_nodejs_utils56.logger.log({
40505
+ level: "error",
40506
+ message: `Failed to set cache for section subjects by getSectionSubject: ${err.message}`
40507
+ });
40508
+ });
40509
+ return result;
40510
+ } catch (error) {
40511
+ if (error instanceof import_nodejs_utils56.AppError) {
40512
+ throw error;
40513
+ } else {
40514
+ throw new import_nodejs_utils56.InternalServerError(
40515
+ "Failed to get section subjects by getSectionSubject."
40516
+ );
40517
+ }
40518
+ }
40519
+ }
40360
40520
  async function getBySection(section) {
40361
40521
  try {
40362
40522
  section = new import_mongodb34.ObjectId(section);
@@ -40589,6 +40749,7 @@ function useSectionSubjectRepo() {
40589
40749
  add,
40590
40750
  getAll,
40591
40751
  getById,
40752
+ getSectionSubject,
40592
40753
  getBySection,
40593
40754
  getByTeacher,
40594
40755
  getBySchool,
@@ -40969,7 +41130,13 @@ function useTeachingLoadRepo() {
40969
41130
  { key: { status: 1 } },
40970
41131
  { key: { school: 1 } },
40971
41132
  { key: { teacher: 1 } },
40972
- { key: { schoolYear: 1 } }
41133
+ { key: { gradeLevel: 1 } },
41134
+ { key: { schoolYear: 1 } },
41135
+ {
41136
+ key: { school: 1, teacher: 1, schoolYear: 1, gradeLevel: 1 },
41137
+ unique: true,
41138
+ name: "unique_teaching_load_index"
41139
+ }
40973
41140
  ]);
40974
41141
  } catch (error) {
40975
41142
  throw new Error("Failed to create index on teaching load.");
@@ -40989,7 +41156,11 @@ function useTeachingLoadRepo() {
40989
41156
  if (error instanceof import_nodejs_utils60.AppError) {
40990
41157
  throw error;
40991
41158
  } else {
40992
- throw new Error("Failed to create teaching load.");
41159
+ const isDuplicated = error.message.includes("duplicate");
41160
+ if (isDuplicated) {
41161
+ throw new import_nodejs_utils60.BadRequestError("Teaching load already exist.");
41162
+ }
41163
+ throw new import_nodejs_utils60.InternalServerError("Failed to create teaching load.");
40993
41164
  }
40994
41165
  }
40995
41166
  }
@@ -41194,23 +41365,32 @@ function useTeachingLoadRepo() {
41194
41365
  }
41195
41366
  }
41196
41367
  }
41197
- async function getByTeacher(teacher, schoolYear) {
41368
+ async function getByTeacher(options) {
41369
+ const query = {};
41370
+ const cacheKeyOptions = { tag: "getByTeacher" };
41371
+ if (options.status) {
41372
+ query.status = options.status;
41373
+ cacheKeyOptions.status = options.status;
41374
+ }
41198
41375
  try {
41199
- teacher = new import_mongodb36.ObjectId(teacher);
41376
+ query.teacher = new import_mongodb36.ObjectId(options.teacher);
41200
41377
  } catch (error) {
41201
41378
  throw new import_nodejs_utils60.BadRequestError("Invalid teacher ID.");
41202
41379
  }
41203
- const query = {
41204
- teacher,
41205
- status: "active"
41206
- };
41207
- if (schoolYear) {
41208
- query.schoolYear = schoolYear;
41380
+ cacheKeyOptions.teacher = String(options.teacher);
41381
+ if (options.schoolYear) {
41382
+ query.schoolYear = options.schoolYear;
41383
+ cacheKeyOptions.schoolYear = options.schoolYear;
41209
41384
  }
41210
- const cacheKey = (0, import_nodejs_utils60.makeCacheKey)(namespace_collection, {
41211
- teacher: String(teacher),
41212
- schoolYear
41213
- });
41385
+ if (options.school) {
41386
+ try {
41387
+ query.school = new import_mongodb36.ObjectId(options.school);
41388
+ } catch (error) {
41389
+ throw new import_nodejs_utils60.BadRequestError("Invalid school ID.");
41390
+ }
41391
+ cacheKeyOptions.school = String(options.school);
41392
+ }
41393
+ const cacheKey = (0, import_nodejs_utils60.makeCacheKey)(namespace_collection, cacheKeyOptions);
41214
41394
  try {
41215
41395
  const cached = await getCache(cacheKey);
41216
41396
  if (cached) {
@@ -41464,7 +41644,7 @@ function useTeachingLoadController() {
41464
41644
  return;
41465
41645
  }
41466
41646
  try {
41467
- const result = await _getByTeacher(teacher, schoolYear);
41647
+ const result = await _getByTeacher({ teacher, schoolYear });
41468
41648
  res.json(result);
41469
41649
  return;
41470
41650
  } catch (error2) {
@@ -41510,7 +41690,7 @@ function modelTeachingLoadSlot(value) {
41510
41690
  const { error } = schemaTeachingLoadSlot.validate(value);
41511
41691
  if (error) {
41512
41692
  import_nodejs_utils62.logger.info(`Teaching Load Slot Model: ${error.message}`);
41513
- throw new import_nodejs_utils62.BadRequestError(error.message);
41693
+ throw new import_nodejs_utils62.BadRequestError(`${error.message} - model`);
41514
41694
  }
41515
41695
  if (value._id && typeof value._id === "string") {
41516
41696
  try {
@@ -41917,9 +42097,11 @@ function useTeachingLoadSlotController() {
41917
42097
  gradeLevel: import_joi40.default.string().required(),
41918
42098
  startTime: import_joi40.default.string().required(),
41919
42099
  endTime: import_joi40.default.string().required(),
41920
- subject: import_joi40.default.string().hex().required(),
42100
+ subject: import_joi40.default.string().hex().optional().allow("", null),
41921
42101
  subjectName: import_joi40.default.string().optional().allow("", null),
41922
42102
  subjectCode: import_joi40.default.string().optional().allow("", null),
42103
+ routine: import_joi40.default.string().hex().optional().allow("", null),
42104
+ routineName: import_joi40.default.string().optional().allow("", null),
41923
42105
  section: import_joi40.default.string().hex().required(),
41924
42106
  sectionName: import_joi40.default.string().optional().allow("", null),
41925
42107
  duration: import_joi40.default.number().min(0).required(),
@@ -42307,7 +42489,9 @@ function usePersonnelRepo() {
42307
42489
  page = 1,
42308
42490
  limit = 10,
42309
42491
  sort = {},
42310
- status = "active"
42492
+ status = "active",
42493
+ gradeLevel = "",
42494
+ classification = ""
42311
42495
  } = {}) {
42312
42496
  page = page > 0 ? page - 1 : 0;
42313
42497
  const query = {
@@ -42331,6 +42515,14 @@ function usePersonnelRepo() {
42331
42515
  }
42332
42516
  cacheParams.school = school;
42333
42517
  }
42518
+ if (gradeLevel) {
42519
+ query.gradeLevels = gradeLevel;
42520
+ cacheParams.gradeLevel = gradeLevel;
42521
+ }
42522
+ if (classification) {
42523
+ query.classification = classification;
42524
+ cacheParams.classification = classification;
42525
+ }
42334
42526
  const cacheKey = (0, import_nodejs_utils67.makeCacheKey)(namespace_collection, cacheParams);
42335
42527
  import_nodejs_utils67.logger.log({
42336
42528
  level: "info",
@@ -42715,522 +42907,436 @@ function usePersonnelController() {
42715
42907
  };
42716
42908
  }
42717
42909
 
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}`);
42910
+ // src/resources/section/section.service.ts
42911
+ function useSectionService() {
42912
+ const { getCountByGradeLevel, getByGradeLevel: getLeanerByGradeLevel } = useLearnerRepo();
42913
+ const { getByGradeLevel } = useGradeLevelRepo();
42914
+ const { add: createSection, getSection } = useSectionRepo();
42915
+ const { add: assignStudent, getStudent } = useSectionStudentRepo();
42916
+ const { getAll: getAllCurriculumSubjects } = useSubjectRepo();
42917
+ const { add: addSectionSubject, getSectionSubject } = useSectionSubjectRepo();
42918
+ const { getById: getSchoolById } = useSchoolRepo();
42919
+ const { getAll: getAllPersonnel } = usePersonnelRepo();
42920
+ const { add: addTeachingLoad, getByTeacher } = useTeachingLoadRepo();
42921
+ function distributeStudents(total, minPer, maxPer) {
42922
+ if (total <= 0)
42923
+ return [];
42924
+ if (minPer <= 0 || maxPer <= 0)
42925
+ return [];
42926
+ if (minPer > maxPer) {
42927
+ throw new import_nodejs_utils69.BadRequestError(
42928
+ "Minimum students per section cannot be greater than maximum."
42929
+ );
42930
+ }
42931
+ const minSections = Math.ceil(total / maxPer);
42932
+ const maxSections = Math.floor(total / minPer);
42933
+ let sectionCount;
42934
+ if (minSections <= maxSections) {
42935
+ sectionCount = minSections;
42936
+ } else {
42937
+ sectionCount = minSections;
42938
+ }
42939
+ const base = Math.floor(total / sectionCount);
42940
+ const extra = total % sectionCount;
42941
+ const sizes = new Array(sectionCount).fill(base);
42942
+ for (let i = 0; i < extra; i++) {
42943
+ sizes[i] += 1;
42944
+ }
42945
+ for (const size of sizes) {
42946
+ if (size > maxPer) {
42947
+ throw new import_nodejs_utils69.BadRequestError(
42948
+ `Generated section exceeds max limit of ${maxPer}.`
42949
+ );
42950
+ }
42951
+ }
42952
+ return sizes;
42768
42953
  }
42769
- if (value._id && typeof value._id === "string") {
42954
+ async function generateSections(value) {
42955
+ const { error } = schemaGenerateSections.validate(value);
42956
+ if (error) {
42957
+ throw new import_nodejs_utils69.BadRequestError(
42958
+ `Invalid section generation data: ${error.message}`
42959
+ );
42960
+ }
42961
+ const session = import_nodejs_utils69.useAtlas.getClient()?.startSession();
42962
+ if (!session) {
42963
+ throw new Error("Unable to start database session.");
42964
+ }
42770
42965
  try {
42771
- value._id = new import_mongodb41.ObjectId(value._id);
42966
+ await session.startTransaction();
42967
+ const studentCount = await getCountByGradeLevel(
42968
+ {
42969
+ school: value.school,
42970
+ schoolYear: value.schoolYear,
42971
+ gradeLevel: value.gradeLevel,
42972
+ specialProgram: value.specialProgram
42973
+ },
42974
+ session
42975
+ );
42976
+ if (studentCount === 0) {
42977
+ throw new import_nodejs_utils69.BadRequestError("No learners found for this grade level.");
42978
+ }
42979
+ const gradeLevelData = await getByGradeLevel(
42980
+ {
42981
+ school: value.school,
42982
+ gradeLevel: value.gradeLevel
42983
+ },
42984
+ session
42985
+ );
42986
+ if (!gradeLevelData) {
42987
+ throw new import_nodejs_utils69.BadRequestError("Grade level not found.");
42988
+ }
42989
+ const minPerSection = value.minStudents ?? gradeLevelData.minNumberOfLearners;
42990
+ const maxPerSection = value.maxStudents ?? gradeLevelData.maxNumberOfLearners;
42991
+ const sectionSizes = distributeStudents(
42992
+ studentCount,
42993
+ minPerSection,
42994
+ maxPerSection
42995
+ );
42996
+ if (sectionSizes.length === 0) {
42997
+ throw new import_nodejs_utils69.BadRequestError("Unable to compute section sizes.");
42998
+ }
42999
+ const schoolData = await getSchoolById(value.school);
43000
+ if (!schoolData) {
43001
+ throw new import_nodejs_utils69.BadRequestError("School not found.");
43002
+ }
43003
+ let totalStudentsProcessed = 0;
43004
+ let sectionsGenerated = 0;
43005
+ let sectionsSkipped = 0;
43006
+ let teachingLoadsCreated = 0;
43007
+ let teachingLoadsSkipped = 0;
43008
+ let studentCreated = 0;
43009
+ let studentSkipped = 0;
43010
+ let subjectsAssigned = 0;
43011
+ let subjectsSkipped = 0;
43012
+ for (let i = 0; i < sectionSizes.length; i++) {
43013
+ const size = sectionSizes[i];
43014
+ const sectionName = String(i + 1);
43015
+ const existingSection = await getSection({
43016
+ gradeLevel: value.gradeLevel,
43017
+ schoolYear: value.schoolYear,
43018
+ name: sectionName,
43019
+ school: value.school
43020
+ });
43021
+ let sectionId = "";
43022
+ if (existingSection) {
43023
+ sectionId = existingSection._id?.toString() || "";
43024
+ sectionsSkipped++;
43025
+ continue;
43026
+ }
43027
+ sectionId = await createSection(
43028
+ {
43029
+ school: value.school,
43030
+ schoolYear: value.schoolYear,
43031
+ gradeLevel: value.gradeLevel,
43032
+ name: sectionName,
43033
+ students: size
43034
+ },
43035
+ session
43036
+ );
43037
+ if (!sectionId) {
43038
+ throw new import_nodejs_utils69.InternalServerError("Required section ID is missing.");
43039
+ }
43040
+ sectionsGenerated++;
43041
+ const skip = totalStudentsProcessed;
43042
+ const learners = await getLeanerByGradeLevel(
43043
+ {
43044
+ school: value.school,
43045
+ gradeLevel: value.gradeLevel,
43046
+ skip,
43047
+ limit: size
43048
+ },
43049
+ session
43050
+ );
43051
+ if (!learners.length) {
43052
+ throw new import_nodejs_utils69.BadRequestError(`No learners found for section #${i + 1}.`);
43053
+ }
43054
+ totalStudentsProcessed += learners.length;
43055
+ for (const student of learners) {
43056
+ if (!student._id) {
43057
+ throw new import_nodejs_utils69.BadRequestError("Learner ID is missing.");
43058
+ }
43059
+ if (!student.learnerInfo.lrn) {
43060
+ throw new import_nodejs_utils69.BadRequestError("Learner LRN is missing.");
43061
+ }
43062
+ const existingStudent = await getStudent({
43063
+ student: student._id.toString(),
43064
+ schoolYear: value.schoolYear,
43065
+ section: sectionId,
43066
+ gradeLevel: value.gradeLevel
43067
+ });
43068
+ if (existingStudent) {
43069
+ studentSkipped++;
43070
+ continue;
43071
+ }
43072
+ await assignStudent(
43073
+ {
43074
+ section: sectionId,
43075
+ lrn: student.learnerInfo.lrn,
43076
+ student: student._id?.toString(),
43077
+ studentName: `${student.learnerInfo.firstName} ${student.learnerInfo.lastName}`,
43078
+ school: value.school,
43079
+ schoolName: schoolData.name,
43080
+ gradeLevel: value.gradeLevel,
43081
+ educationLevel: gradeLevelData.educationLevel,
43082
+ schoolYear: value.schoolYear,
43083
+ status: "active"
43084
+ },
43085
+ session
43086
+ );
43087
+ studentCreated++;
43088
+ }
43089
+ if (value.gradeLevel !== "kindergarten") {
43090
+ const curriculumSubjects = await getAllCurriculumSubjects({
43091
+ schoolYear: Number(value.schoolYear),
43092
+ gradeLevel: value.gradeLevel,
43093
+ limit: 20
43094
+ });
43095
+ for (const curriculumSubject of curriculumSubjects.items) {
43096
+ const existingSectionSubject = await getSectionSubject({
43097
+ section: sectionId,
43098
+ subjectCode: curriculumSubject.subjectCode,
43099
+ schoolYear: value.schoolYear
43100
+ });
43101
+ if (existingSectionSubject) {
43102
+ subjectsSkipped++;
43103
+ continue;
43104
+ }
43105
+ await addSectionSubject(
43106
+ {
43107
+ curriculum: curriculumSubject.curriculum.toString(),
43108
+ school: value.school,
43109
+ schoolName: schoolData.name,
43110
+ gradeLevel: value.gradeLevel,
43111
+ educationLevel: gradeLevelData.educationLevel,
43112
+ schoolYear: value.schoolYear,
43113
+ section: sectionId,
43114
+ sectionName,
43115
+ subjectCode: curriculumSubject.subjectCode,
43116
+ subjectName: curriculumSubject.subjectName,
43117
+ teacher: "",
43118
+ teacherName: "",
43119
+ schedule: "",
43120
+ daysOfWeek: [],
43121
+ classroom: "",
43122
+ classroomName: "",
43123
+ sessionDuration: curriculumSubject.sessionDuration,
43124
+ sessionFrequency: curriculumSubject.sessionFrequency,
43125
+ status: "draft"
43126
+ },
43127
+ session
43128
+ );
43129
+ subjectsAssigned++;
43130
+ }
43131
+ }
43132
+ }
43133
+ let pageTeacher = 1;
43134
+ let pagesTeachers = 1;
43135
+ let teachers = [];
43136
+ do {
43137
+ const teachersData = await getAllPersonnel({
43138
+ school: value.school,
43139
+ limit: 100,
43140
+ gradeLevel: value.gradeLevel,
43141
+ classification: "teaching"
43142
+ });
43143
+ pagesTeachers = teachersData.pages;
43144
+ teachers.push(...teachersData.items);
43145
+ pageTeacher++;
43146
+ } while (pageTeacher < pagesTeachers);
43147
+ if (!teachers.length) {
43148
+ throw new import_nodejs_utils69.BadRequestError(
43149
+ "Could not proceed, no teaching personnel found."
43150
+ );
43151
+ }
43152
+ if (teachers.length) {
43153
+ for (const teacher of teachers) {
43154
+ if (!teacher._id) {
43155
+ throw new import_nodejs_utils69.BadRequestError("Teacher ID is missing.");
43156
+ }
43157
+ const existingLoad = await getByTeacher({
43158
+ teacher: teacher._id.toString(),
43159
+ school: value.school,
43160
+ schoolYear: value.schoolYear
43161
+ });
43162
+ if (existingLoad) {
43163
+ teachingLoadsSkipped++;
43164
+ continue;
43165
+ }
43166
+ await addTeachingLoad(
43167
+ {
43168
+ school: value.school,
43169
+ schoolName: schoolData.name,
43170
+ schoolYear: value.schoolYear,
43171
+ teacher: teacher._id.toString(),
43172
+ teacherName: `${teacher.firstName} ${teacher.lastName}`,
43173
+ status: "draft"
43174
+ },
43175
+ session
43176
+ );
43177
+ teachingLoadsCreated++;
43178
+ }
43179
+ }
43180
+ await session.commitTransaction();
43181
+ return {
43182
+ message: "Sections generated successfully.",
43183
+ summary: {
43184
+ sectionsGenerated,
43185
+ sectionsSkipped,
43186
+ totalSections: sectionsGenerated + sectionsSkipped,
43187
+ studentsProcessed: totalStudentsProcessed,
43188
+ studentCreated,
43189
+ studentSkipped,
43190
+ subjectsAssigned,
43191
+ subjectsSkipped,
43192
+ teachingLoadsCreated,
43193
+ teachingLoadsSkipped,
43194
+ totalStudents: studentCount
43195
+ }
43196
+ };
42772
43197
  } catch (error2) {
42773
- throw new Error("Invalid _id.");
43198
+ await session.abortTransaction();
43199
+ if (error2 instanceof import_nodejs_utils69.AppError) {
43200
+ throw error2;
43201
+ } else {
43202
+ throw new import_nodejs_utils69.InternalServerError("Failed to generate sections.");
43203
+ }
43204
+ } finally {
43205
+ await session?.endSession();
42774
43206
  }
42775
43207
  }
42776
- if (value.school && typeof value.school === "string") {
43208
+ async function generateSectionPreview(value) {
43209
+ const { error } = schemaGenerateSections.validate(value);
43210
+ if (error) {
43211
+ throw new import_nodejs_utils69.BadRequestError(
43212
+ `Invalid section generation data: ${error.message}`
43213
+ );
43214
+ }
42777
43215
  try {
42778
- value.school = new import_mongodb41.ObjectId(value.school);
43216
+ const studentCount = await getCountByGradeLevel({
43217
+ school: value.school,
43218
+ schoolYear: value.schoolYear,
43219
+ gradeLevel: value.gradeLevel,
43220
+ specialProgram: value.specialProgram
43221
+ });
43222
+ if (studentCount === 0) {
43223
+ throw new import_nodejs_utils69.BadRequestError("No learners found for this grade level.");
43224
+ }
43225
+ const gradeLevelData = await getByGradeLevel({
43226
+ school: value.school,
43227
+ gradeLevel: value.gradeLevel
43228
+ });
43229
+ if (!gradeLevelData) {
43230
+ throw new import_nodejs_utils69.BadRequestError("Grade level not found.");
43231
+ }
43232
+ const minPerSection = value.minStudents ?? gradeLevelData.minNumberOfLearners;
43233
+ const maxPerSection = value.maxStudents ?? gradeLevelData.maxNumberOfLearners;
43234
+ const sectionSizes = distributeStudents(
43235
+ studentCount,
43236
+ minPerSection,
43237
+ maxPerSection
43238
+ );
43239
+ if (sectionSizes.length === 0) {
43240
+ throw new import_nodejs_utils69.BadRequestError("Unable to compute section sizes.");
43241
+ }
43242
+ const sections = sectionSizes.map((size, index) => ({
43243
+ name: `${index + 1}`,
43244
+ value: size
43245
+ }));
43246
+ return {
43247
+ totalSectionsGenerated: sectionSizes.length,
43248
+ totalStudentsAssigned: studentCount,
43249
+ sections
43250
+ };
42779
43251
  } catch (error2) {
42780
- throw new Error("Invalid school.");
43252
+ if (error2 instanceof import_nodejs_utils69.AppError) {
43253
+ throw error2;
43254
+ } else {
43255
+ throw new import_nodejs_utils69.InternalServerError("Failed to generate section preview.");
43256
+ }
42781
43257
  }
42782
43258
  }
42783
- if (value.section && typeof value.section === "string") {
43259
+ return { generateSections, generateSectionPreview };
43260
+ }
43261
+
43262
+ // src/resources/section/section.controller.ts
43263
+ function useSectionController() {
43264
+ const {
43265
+ add: _add,
43266
+ getAll: _getAll,
43267
+ getById: _getById,
43268
+ getByName: _getByName,
43269
+ getBySchool: _getBySchool,
43270
+ updateFieldById: _updateFieldById,
43271
+ addStudentToSection: _addStudentToSection,
43272
+ removeStudentFromSection: _removeStudentFromSection,
43273
+ deleteById: _deleteById
43274
+ } = useSectionRepo();
43275
+ const {
43276
+ generateSections: _generateSections,
43277
+ generateSectionPreview: _generateSectionPreview
43278
+ } = useSectionService();
43279
+ async function add(req, res, next) {
43280
+ const value = req.body;
43281
+ const { error } = schemaSection.validate(value);
43282
+ if (error) {
43283
+ next(new import_nodejs_utils70.BadRequestError(error.message));
43284
+ return;
43285
+ }
42784
43286
  try {
42785
- value.section = new import_mongodb41.ObjectId(value.section);
43287
+ const data = await _add(value);
43288
+ res.json({
43289
+ message: "Successfully created section.",
43290
+ data
43291
+ });
43292
+ return;
42786
43293
  } catch (error2) {
42787
- throw new Error("Invalid section.");
43294
+ next(error2);
42788
43295
  }
42789
43296
  }
42790
- if (value.classroom && typeof value.classroom === "string") {
43297
+ async function generateSections(req, res, next) {
43298
+ const value = req.body;
43299
+ const { error } = schemaGenerateSections.validate(value);
43300
+ if (error) {
43301
+ next(new import_nodejs_utils70.BadRequestError(error.message));
43302
+ return;
43303
+ }
42791
43304
  try {
42792
- value.classroom = new import_mongodb41.ObjectId(value.classroom);
43305
+ const data = await _generateSections(value);
43306
+ res.json({
43307
+ message: "Successfully created section.",
43308
+ data
43309
+ });
43310
+ return;
42793
43311
  } catch (error2) {
42794
- throw new Error("Invalid classroom.");
43312
+ next(error2);
42795
43313
  }
42796
43314
  }
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() {
43315
+ async function generateSectionPreview(req, res, next) {
43316
+ const value = req.body;
43317
+ const { error } = schemaGenerateSections.validate(value);
43318
+ if (error) {
43319
+ next(new import_nodejs_utils70.BadRequestError(error.message));
43320
+ return;
43321
+ }
42828
43322
  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" } },
42837
- {
42838
- key: { title: 1, school: 1, type: 1, status: 1 },
42839
- unique: true,
42840
- name: "unique_kindergarten_routine"
42841
- }
42842
- ]);
42843
- } catch (error) {
42844
- throw new Error("Failed to create index on kindergarten routines.");
43323
+ const data = await _generateSectionPreview(value);
43324
+ res.json(data);
43325
+ return;
43326
+ } catch (error2) {
43327
+ next(error2);
42845
43328
  }
42846
43329
  }
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) {
42861
- 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
42870
- });
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.");
42879
- }
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.");
42911
- }
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.");
42923
- }
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.");
42931
- }
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.");
42939
- }
42940
- cacheKeyOptions.classroom = classroom;
42941
- }
42942
- if (type) {
42943
- query.type = type;
42944
- cacheKeyOptions.type = type;
42945
- }
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
- 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
- });
42978
- });
42979
- return data;
42980
- } catch (error) {
42981
- import_nodejs_utils70.logger.log({ level: "error", message: `${error}` });
42982
- throw error;
42983
- }
42984
- }
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.");
42990
- }
42991
- const cacheKey = (0, import_nodejs_utils70.makeCacheKey)(namespace_collection, { _id: String(_id) });
42992
- 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
- });
43015
- });
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
- }
43023
- }
43024
- }
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) {
43205
- const value = req.body;
43206
- const { error } = schemaKindergartenRoutine.validate(value);
43207
- if (error) {
43208
- next(new import_nodejs_utils71.BadRequestError(error.message));
43209
- return;
43210
- }
43211
- try {
43212
- const data = await _add(value);
43213
- res.json({
43214
- message: "Successfully created kinder schedule.",
43215
- data
43216
- });
43217
- return;
43218
- } catch (error2) {
43219
- next(error2);
43220
- }
43221
- }
43222
- async function getAll(req, res, next) {
43223
- 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)
43330
+ async function getAll(req, res, next) {
43331
+ const query = req.query;
43332
+ const validation = import_joi43.default.object({
43333
+ page: import_joi43.default.number().min(1).optional().allow("", null),
43334
+ limit: import_joi43.default.number().min(1).optional().allow("", null),
43335
+ search: import_joi43.default.string().optional().allow("", null),
43336
+ status: import_joi43.default.string().optional().allow("", null),
43337
+ school: import_joi43.default.string().hex().optional().allow("", null),
43338
+ schoolYear: import_joi43.default.string().optional().allow("", null),
43339
+ gradeLevel: import_joi43.default.string().optional().allow("", null)
43234
43340
  });
43235
43341
  const { error } = validation.validate(query);
43236
43342
  const page = typeof req.query.page === "string" ? Number(req.query.page) : 1;
@@ -43238,22 +43344,20 @@ function useKindergartenRoutineController() {
43238
43344
  const search = req.query.search ?? "";
43239
43345
  const status = req.query.status ?? "active";
43240
43346
  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 ?? "";
43347
+ const schoolYear = req.query.schoolYear ?? "";
43348
+ const gradeLevel = req.query.gradeLevel ?? "";
43245
43349
  const isPageNumber = isFinite(page);
43246
43350
  if (!isPageNumber) {
43247
- next(new import_nodejs_utils71.BadRequestError("Invalid page number."));
43351
+ next(new import_nodejs_utils70.BadRequestError("Invalid page number."));
43248
43352
  return;
43249
43353
  }
43250
43354
  const isLimitNumber = isFinite(limit);
43251
43355
  if (!isLimitNumber) {
43252
- next(new import_nodejs_utils71.BadRequestError("Invalid limit number."));
43356
+ next(new import_nodejs_utils70.BadRequestError("Invalid limit number."));
43253
43357
  return;
43254
43358
  }
43255
43359
  if (error) {
43256
- next(new import_nodejs_utils71.BadRequestError(error.message));
43360
+ next(new import_nodejs_utils70.BadRequestError(error.message));
43257
43361
  return;
43258
43362
  }
43259
43363
  try {
@@ -43263,10 +43367,8 @@ function useKindergartenRoutineController() {
43263
43367
  search,
43264
43368
  status,
43265
43369
  school,
43266
- section,
43267
- classroom,
43268
- type,
43269
- createdBy: createdBy || void 0
43370
+ schoolYear,
43371
+ gradeLevel
43270
43372
  });
43271
43373
  res.json(data);
43272
43374
  return;
@@ -43276,18 +43378,36 @@ function useKindergartenRoutineController() {
43276
43378
  }
43277
43379
  async function getById(req, res, next) {
43278
43380
  const id = req.params.id;
43279
- const validation = import_joi44.default.object({
43280
- id: import_joi44.default.string().hex().required()
43381
+ const validation = import_joi43.default.object({
43382
+ id: import_joi43.default.string().hex().required()
43281
43383
  });
43282
43384
  const { error } = validation.validate({ id });
43283
43385
  if (error) {
43284
- next(new import_nodejs_utils71.BadRequestError(error.message));
43386
+ next(new import_nodejs_utils70.BadRequestError(error.message));
43285
43387
  return;
43286
43388
  }
43287
43389
  try {
43288
43390
  const data = await _getById(id);
43391
+ res.json(data);
43392
+ return;
43393
+ } catch (error2) {
43394
+ next(error2);
43395
+ }
43396
+ }
43397
+ async function getByName(req, res, next) {
43398
+ const name = req.params.name;
43399
+ const validation = import_joi43.default.object({
43400
+ name: import_joi43.default.string().required()
43401
+ });
43402
+ const { error } = validation.validate({ name });
43403
+ if (error) {
43404
+ next(new import_nodejs_utils70.BadRequestError(error.message));
43405
+ return;
43406
+ }
43407
+ try {
43408
+ const data = await _getByName(name);
43289
43409
  res.json({
43290
- message: "Successfully retrieved kinder schedule.",
43410
+ message: "Successfully retrieved section.",
43291
43411
  data
43292
43412
  });
43293
43413
  return;
@@ -43295,20 +43415,20 @@ function useKindergartenRoutineController() {
43295
43415
  next(error2);
43296
43416
  }
43297
43417
  }
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()
43418
+ async function getBySchool(req, res, next) {
43419
+ const school = req.params.school;
43420
+ const validation = import_joi43.default.object({
43421
+ school: import_joi43.default.string().hex().required()
43302
43422
  });
43303
- const { error } = validation.validate({ section });
43423
+ const { error } = validation.validate({ school });
43304
43424
  if (error) {
43305
- next(new import_nodejs_utils71.BadRequestError(error.message));
43425
+ next(new import_nodejs_utils70.BadRequestError(error.message));
43306
43426
  return;
43307
43427
  }
43308
43428
  try {
43309
- const data = await _getBySection(section);
43429
+ const data = await _getBySchool(school);
43310
43430
  res.json({
43311
- message: "Successfully retrieved kinder schedules.",
43431
+ message: "Successfully retrieved sections.",
43312
43432
  data
43313
43433
  });
43314
43434
  return;
@@ -43319,14 +43439,14 @@ function useKindergartenRoutineController() {
43319
43439
  async function updateField(req, res, next) {
43320
43440
  const _id = req.params.id;
43321
43441
  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()
43442
+ const validation = import_joi43.default.object({
43443
+ _id: import_joi43.default.string().hex().required(),
43444
+ field: import_joi43.default.string().valid("name", "schoolYear", "gradeLevel", "adviser", "adviserName").required(),
43445
+ value: import_joi43.default.string().required()
43326
43446
  });
43327
43447
  const { error } = validation.validate({ _id, field, value });
43328
43448
  if (error) {
43329
- next(new import_nodejs_utils71.BadRequestError(error.message));
43449
+ next(new import_nodejs_utils70.BadRequestError(error.message));
43330
43450
  return;
43331
43451
  }
43332
43452
  try {
@@ -43337,21 +43457,40 @@ function useKindergartenRoutineController() {
43337
43457
  next(error2);
43338
43458
  }
43339
43459
  }
43340
- async function updateById(req, res, next) {
43460
+ async function addStudent(req, res, next) {
43341
43461
  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));
43462
+ const { studentId } = req.body;
43463
+ const validation = import_joi43.default.object({
43464
+ _id: import_joi43.default.string().hex().required(),
43465
+ studentId: import_joi43.default.string().required()
43466
+ });
43467
+ const { error } = validation.validate({ _id, studentId });
43468
+ if (error) {
43469
+ next(new import_nodejs_utils70.BadRequestError(error.message));
43346
43470
  return;
43347
43471
  }
43348
- const { error } = schemaKindergartenRoutineUpdate.validate(payload);
43472
+ try {
43473
+ const message = await _addStudentToSection(_id, studentId);
43474
+ res.json({ message });
43475
+ return;
43476
+ } catch (error2) {
43477
+ next(error2);
43478
+ }
43479
+ }
43480
+ async function removeStudent(req, res, next) {
43481
+ const _id = req.params.id;
43482
+ const { studentId } = req.body;
43483
+ const validation = import_joi43.default.object({
43484
+ _id: import_joi43.default.string().hex().required(),
43485
+ studentId: import_joi43.default.string().required()
43486
+ });
43487
+ const { error } = validation.validate({ _id, studentId });
43349
43488
  if (error) {
43350
- next(new import_nodejs_utils71.BadRequestError(error.message));
43489
+ next(new import_nodejs_utils70.BadRequestError(error.message));
43351
43490
  return;
43352
43491
  }
43353
43492
  try {
43354
- const message = await _updateById(_id, payload);
43493
+ const message = await _removeStudentFromSection(_id, studentId);
43355
43494
  res.json({ message });
43356
43495
  return;
43357
43496
  } catch (error2) {
@@ -43360,12 +43499,12 @@ function useKindergartenRoutineController() {
43360
43499
  }
43361
43500
  async function deleteById(req, res, next) {
43362
43501
  const _id = req.params.id;
43363
- const validation = import_joi44.default.object({
43364
- _id: import_joi44.default.string().hex().required()
43502
+ const validation = import_joi43.default.object({
43503
+ _id: import_joi43.default.string().hex().required()
43365
43504
  });
43366
43505
  const { error } = validation.validate({ _id });
43367
43506
  if (error) {
43368
- next(new import_nodejs_utils71.BadRequestError(error.message));
43507
+ next(new import_nodejs_utils70.BadRequestError(error.message));
43369
43508
  return;
43370
43509
  }
43371
43510
  try {
@@ -43378,386 +43517,961 @@ function useKindergartenRoutineController() {
43378
43517
  }
43379
43518
  return {
43380
43519
  add,
43520
+ generateSections,
43521
+ generateSectionPreview,
43381
43522
  getAll,
43382
43523
  getById,
43383
- getBySection,
43524
+ getByName,
43525
+ getBySchool,
43384
43526
  updateField,
43385
- updateById,
43527
+ addStudent,
43528
+ removeStudent,
43386
43529
  deleteById
43387
43530
  };
43388
43531
  }
43389
43532
 
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
- );
43533
+ // src/resources/section-student/section.student.controller.ts
43534
+ var import_nodejs_utils71 = require("@eeplatform/nodejs-utils");
43535
+ var import_joi44 = __toESM(require("joi"));
43536
+ function useSectionStudentController() {
43537
+ const { add: _add, getAll: _getAll } = useSectionStudentRepo();
43538
+ async function add(req, res, next) {
43539
+ const value = req.body;
43540
+ const { error } = schemaSectionStudent.validate(value);
43541
+ if (error) {
43542
+ next(new import_nodejs_utils71.BadRequestError(error.message));
43543
+ return;
43411
43544
  }
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;
43545
+ try {
43546
+ const data = await _add(value);
43547
+ res.json({
43548
+ message: "Successfully created section student.",
43549
+ data
43550
+ });
43551
+ return;
43552
+ } catch (error2) {
43553
+ next(error2);
43419
43554
  }
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;
43555
+ }
43556
+ async function getAll(req, res, next) {
43557
+ const query = req.query;
43558
+ const validation = import_joi44.default.object({
43559
+ page: import_joi44.default.number().min(1).optional().allow("", null),
43560
+ limit: import_joi44.default.number().min(1).optional().allow("", null),
43561
+ search: import_joi44.default.string().optional().allow("", null),
43562
+ status: import_joi44.default.string().optional().allow("", null),
43563
+ school: import_joi44.default.string().optional().allow("", null),
43564
+ gradeLevel: import_joi44.default.string().optional().allow("", null),
43565
+ section: import_joi44.default.string().optional().allow("", null),
43566
+ schoolYear: import_joi44.default.string().optional().allow("", null)
43567
+ });
43568
+ const { error } = validation.validate(query);
43569
+ const page = typeof req.query.page === "string" ? Number(req.query.page) : 1;
43570
+ const limit = typeof req.query.limit === "string" ? Number(req.query.limit) : 10;
43571
+ const search = req.query.search ?? "";
43572
+ const status = req.query.status ?? "active";
43573
+ const school = req.query.school ?? "";
43574
+ const gradeLevel = req.query.gradeLevel ?? "";
43575
+ const section = req.query.section ?? "";
43576
+ const schoolYear = req.query.schoolYear ?? "";
43577
+ const isPageNumber = isFinite(page);
43578
+ if (!isPageNumber) {
43579
+ next(new import_nodejs_utils71.BadRequestError("Invalid page number."));
43580
+ return;
43425
43581
  }
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
- }
43582
+ const isLimitNumber = isFinite(limit);
43583
+ if (!isLimitNumber) {
43584
+ next(new import_nodejs_utils71.BadRequestError("Invalid limit number."));
43585
+ return;
43432
43586
  }
43433
- return sizes;
43434
- }
43435
- async function generateSections(value) {
43436
- const { error } = schemaGenerateSections.validate(value);
43437
43587
  if (error) {
43438
- throw new import_nodejs_utils72.BadRequestError(
43439
- `Invalid section generation data: ${error.message}`
43440
- );
43441
- }
43442
- const session = import_nodejs_utils72.useAtlas.getClient()?.startSession();
43443
- if (!session) {
43444
- throw new Error("Unable to start database session.");
43588
+ next(new import_nodejs_utils71.BadRequestError(error.message));
43589
+ return;
43445
43590
  }
43446
43591
  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.");
43456
- }
43457
- }
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
43466
- );
43467
- if (studentCount === 0) {
43468
- throw new import_nodejs_utils72.BadRequestError("No learners found for this grade level.");
43469
- }
43470
- const gradeLevelData = await getByGradeLevel(
43471
- {
43472
- school: value.school,
43473
- gradeLevel: value.gradeLevel
43474
- },
43475
- session
43592
+ const data = await _getAll({
43593
+ page,
43594
+ limit,
43595
+ search,
43596
+ status,
43597
+ school,
43598
+ gradeLevel,
43599
+ section,
43600
+ schoolYear
43601
+ });
43602
+ res.json(data);
43603
+ return;
43604
+ } catch (error2) {
43605
+ next(error2);
43606
+ }
43607
+ }
43608
+ return {
43609
+ add,
43610
+ getAll
43611
+ };
43612
+ }
43613
+
43614
+ // src/resources/building/building.model.ts
43615
+ var import_nodejs_utils72 = require("@eeplatform/nodejs-utils");
43616
+ var import_joi45 = __toESM(require("joi"));
43617
+ var import_mongodb41 = require("mongodb");
43618
+ var schemaBuilding = import_joi45.default.object({
43619
+ _id: import_joi45.default.string().hex().optional(),
43620
+ school: import_joi45.default.string().hex().required(),
43621
+ serial: import_joi45.default.string().optional().allow("", null),
43622
+ name: import_joi45.default.string().required(),
43623
+ levels: import_joi45.default.number().integer().min(1).required(),
43624
+ createdAt: import_joi45.default.date().optional().allow("", null),
43625
+ updatedAt: import_joi45.default.date().optional().allow("", null),
43626
+ deletedAt: import_joi45.default.date().optional().allow("", null),
43627
+ status: import_joi45.default.string().optional().allow("", null)
43628
+ });
43629
+ var schemaBuildingUnit = import_joi45.default.object({
43630
+ _id: import_joi45.default.string().hex().optional(),
43631
+ school: import_joi45.default.string().hex().required(),
43632
+ name: import_joi45.default.string().optional().allow("", null),
43633
+ building: import_joi45.default.string().hex().required(),
43634
+ buildingName: import_joi45.default.string().optional().allow("", null),
43635
+ level: import_joi45.default.number().integer().min(1).required(),
43636
+ category: import_joi45.default.string().required(),
43637
+ type: import_joi45.default.string().required(),
43638
+ seating_capacity: import_joi45.default.number().integer().min(0).required(),
43639
+ standing_capacity: import_joi45.default.number().integer().min(0).required(),
43640
+ description: import_joi45.default.string().optional().allow("", null),
43641
+ unit_of_measurement: import_joi45.default.string().valid("sqm").required(),
43642
+ area: import_joi45.default.number().positive().required(),
43643
+ status: import_joi45.default.string().optional().allow("", null)
43644
+ });
43645
+ var schemaUpdateOptions = import_joi45.default.object({
43646
+ name: import_joi45.default.string().optional().allow("", null),
43647
+ building: import_joi45.default.string().hex().optional().allow("", null),
43648
+ buildingName: import_joi45.default.string().optional().allow("", null),
43649
+ level: import_joi45.default.number().integer().min(1).optional().allow("", null),
43650
+ category: import_joi45.default.string().optional().allow("", null),
43651
+ type: import_joi45.default.string().optional().allow("", null),
43652
+ seating_capacity: import_joi45.default.number().integer().min(0).optional().allow("", null),
43653
+ standing_capacity: import_joi45.default.number().integer().min(0).optional().allow("", null),
43654
+ area: import_joi45.default.number().positive().optional().allow("", null)
43655
+ });
43656
+ function MBuilding(value) {
43657
+ const { error } = schemaBuilding.validate(value);
43658
+ if (error) {
43659
+ import_nodejs_utils72.logger.info(`Building Model: ${error.message}`);
43660
+ throw new import_nodejs_utils72.BadRequestError(error.message);
43661
+ }
43662
+ if (value._id && typeof value._id === "string") {
43663
+ try {
43664
+ value._id = new import_mongodb41.ObjectId(value._id);
43665
+ } catch (error2) {
43666
+ throw new import_nodejs_utils72.BadRequestError("Invalid _id format");
43667
+ }
43668
+ }
43669
+ try {
43670
+ value.school = new import_mongodb41.ObjectId(value.school);
43671
+ } catch (error2) {
43672
+ throw new import_nodejs_utils72.BadRequestError("Invalid school format");
43673
+ }
43674
+ return {
43675
+ _id: value._id ?? void 0,
43676
+ school: value.school,
43677
+ serial: value.serial ?? "",
43678
+ name: value.name ?? "",
43679
+ levels: value.levels ?? 0,
43680
+ status: value.status ?? "active",
43681
+ createdAt: value.createdAt ?? /* @__PURE__ */ new Date(),
43682
+ updatedAt: value.updatedAt ?? "",
43683
+ deletedAt: value.deletedAt ?? ""
43684
+ };
43685
+ }
43686
+ function MBuildingUnit(value) {
43687
+ const { error } = schemaBuildingUnit.validate(value);
43688
+ if (error) {
43689
+ import_nodejs_utils72.logger.info(`Building Unit Model: ${error.message}`);
43690
+ throw new import_nodejs_utils72.BadRequestError(error.message);
43691
+ }
43692
+ if (value._id && typeof value._id === "string") {
43693
+ try {
43694
+ value._id = new import_mongodb41.ObjectId(value._id);
43695
+ } catch (error2) {
43696
+ throw new import_nodejs_utils72.BadRequestError("Invalid ID");
43697
+ }
43698
+ }
43699
+ try {
43700
+ value.school = new import_mongodb41.ObjectId(value.school);
43701
+ } catch (error2) {
43702
+ throw new import_nodejs_utils72.BadRequestError("Invalid school ID");
43703
+ }
43704
+ try {
43705
+ value.building = new import_mongodb41.ObjectId(value.building);
43706
+ } catch (error2) {
43707
+ throw new import_nodejs_utils72.BadRequestError("Invalid building ID");
43708
+ }
43709
+ return {
43710
+ _id: value._id ?? void 0,
43711
+ school: value.school,
43712
+ name: value.name ?? "",
43713
+ building: value.building,
43714
+ buildingName: value.buildingName ?? "",
43715
+ level: value.level ?? 0,
43716
+ category: value.category ?? "",
43717
+ type: value.type ?? "",
43718
+ seating_capacity: value.seating_capacity ?? 0,
43719
+ standing_capacity: value.standing_capacity ?? 0,
43720
+ description: value.description ?? "",
43721
+ unit_of_measurement: value.unit_of_measurement ?? "sqm",
43722
+ area: value.area ?? 0,
43723
+ status: value.status ?? "active",
43724
+ createdAt: value.createdAt ?? /* @__PURE__ */ new Date(),
43725
+ updatedAt: value.updatedAt ?? "",
43726
+ deletedAt: value.deletedAt ?? ""
43727
+ };
43728
+ }
43729
+
43730
+ // src/resources/building/building.repository.ts
43731
+ var import_nodejs_utils73 = require("@eeplatform/nodejs-utils");
43732
+ var import_mongodb42 = require("mongodb");
43733
+ function useBuildingRepo() {
43734
+ const db = import_nodejs_utils73.useAtlas.getDb();
43735
+ if (!db) {
43736
+ throw new Error("Unable to connect to server.");
43737
+ }
43738
+ const namespace_collection = "deped.buildings";
43739
+ const collection = db.collection(namespace_collection);
43740
+ const { getCache, setCache, delNamespace } = (0, import_nodejs_utils73.useCache)(namespace_collection);
43741
+ async function createIndexes() {
43742
+ try {
43743
+ await collection.createIndexes([
43744
+ { key: { name: 1 }, unique: true, name: "unique_name_index" },
43745
+ { key: { school: 1 } },
43746
+ { key: { status: 1 } }
43747
+ ]);
43748
+ } catch (error) {
43749
+ throw new Error("Failed to create index on buildings.");
43750
+ }
43751
+ }
43752
+ async function add(value, session) {
43753
+ try {
43754
+ value = MBuilding(value);
43755
+ const res = await collection.insertOne(value, { session });
43756
+ delCachedData();
43757
+ return res.insertedId;
43758
+ } catch (error) {
43759
+ import_nodejs_utils73.logger.log({
43760
+ level: "error",
43761
+ message: error.message
43762
+ });
43763
+ if (error instanceof import_nodejs_utils73.AppError) {
43764
+ throw error;
43765
+ } else {
43766
+ const isDuplicated = error.message.includes("duplicate");
43767
+ if (isDuplicated) {
43768
+ throw new import_nodejs_utils73.BadRequestError("Building already exists.");
43769
+ }
43770
+ throw new Error("Failed to create building.");
43771
+ }
43772
+ }
43773
+ }
43774
+ async function updateById(_id, value, session) {
43775
+ try {
43776
+ _id = new import_mongodb42.ObjectId(_id);
43777
+ } catch (error) {
43778
+ throw new import_nodejs_utils73.BadRequestError(namespace_collection + " Invalid ID.");
43779
+ }
43780
+ try {
43781
+ const res = await collection.updateOne(
43782
+ { _id },
43783
+ { $set: value },
43784
+ { session }
43476
43785
  );
43477
- if (!gradeLevelData) {
43478
- throw new import_nodejs_utils72.BadRequestError("Grade level not found.");
43786
+ delCachedData();
43787
+ return res;
43788
+ } catch (error) {
43789
+ import_nodejs_utils73.logger.log({
43790
+ level: "error",
43791
+ message: error.message
43792
+ });
43793
+ if (error instanceof import_nodejs_utils73.AppError) {
43794
+ throw error;
43795
+ } else {
43796
+ throw new Error("Failed to update building.");
43479
43797
  }
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
- );
43798
+ }
43799
+ }
43800
+ async function getAll({
43801
+ search = "",
43802
+ page = 1,
43803
+ limit = 10,
43804
+ sort = {},
43805
+ school = "",
43806
+ status = "active"
43807
+ } = {}) {
43808
+ page = page > 0 ? page - 1 : 0;
43809
+ const query = {
43810
+ status
43811
+ };
43812
+ sort = Object.keys(sort).length > 0 ? sort : { _id: -1 };
43813
+ if (search) {
43814
+ query.$text = { $search: search };
43815
+ }
43816
+ if (school) {
43817
+ try {
43818
+ query.school = new import_mongodb42.ObjectId(school);
43819
+ } catch (error) {
43820
+ throw new import_nodejs_utils73.BadRequestError("Invalid school ID.");
43487
43821
  }
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.");
43822
+ }
43823
+ const cacheParams = {
43824
+ page,
43825
+ limit,
43826
+ sort: JSON.stringify(sort)
43827
+ };
43828
+ if (search)
43829
+ cacheParams.search = search;
43830
+ if (school)
43831
+ cacheParams.school = school;
43832
+ if (status !== "active")
43833
+ cacheParams.status = status;
43834
+ const cacheKey = (0, import_nodejs_utils73.makeCacheKey)(namespace_collection, cacheParams);
43835
+ import_nodejs_utils73.logger.log({
43836
+ level: "info",
43837
+ message: `Cache key for getAll buildings: ${cacheKey}`
43838
+ });
43839
+ try {
43840
+ const cached = await getCache(cacheKey);
43841
+ if (cached) {
43842
+ import_nodejs_utils73.logger.log({
43843
+ level: "info",
43844
+ message: `Cache hit for getAll buildings: ${cacheKey}`
43845
+ });
43846
+ return cached;
43495
43847
  }
43496
- const schoolData = await getSchoolById(value.school);
43497
- if (!schoolData) {
43498
- throw new import_nodejs_utils72.BadRequestError("School not found.");
43848
+ const items = await collection.aggregate([
43849
+ { $match: query },
43850
+ { $sort: sort },
43851
+ { $skip: page * limit },
43852
+ { $limit: limit }
43853
+ ]).toArray();
43854
+ const length = await collection.countDocuments(query);
43855
+ const data = (0, import_nodejs_utils73.paginate)(items, page, limit, length);
43856
+ setCache(cacheKey, data, 600).then(() => {
43857
+ import_nodejs_utils73.logger.log({
43858
+ level: "info",
43859
+ message: `Cache set for getAll buildings: ${cacheKey}`
43860
+ });
43861
+ }).catch((err) => {
43862
+ import_nodejs_utils73.logger.log({
43863
+ level: "error",
43864
+ message: `Failed to set cache for getAll buildings: ${err.message}`
43865
+ });
43866
+ });
43867
+ return data;
43868
+ } catch (error) {
43869
+ import_nodejs_utils73.logger.log({ level: "error", message: `${error}` });
43870
+ throw error;
43871
+ }
43872
+ }
43873
+ async function getById(_id) {
43874
+ try {
43875
+ _id = new import_mongodb42.ObjectId(_id);
43876
+ } catch (error) {
43877
+ throw new import_nodejs_utils73.BadRequestError(namespace_collection + " Invalid ID.");
43878
+ }
43879
+ const cacheKey = (0, import_nodejs_utils73.makeCacheKey)(namespace_collection, { _id: String(_id) });
43880
+ try {
43881
+ const cached = await getCache(cacheKey);
43882
+ if (cached) {
43883
+ import_nodejs_utils73.logger.log({
43884
+ level: "info",
43885
+ message: `Cache hit for getById building: ${cacheKey}`
43886
+ });
43887
+ return cached;
43499
43888
  }
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.");
43889
+ const result = await collection.findOne({
43890
+ _id
43891
+ });
43892
+ setCache(cacheKey, result, 300).then(() => {
43893
+ import_nodejs_utils73.logger.log({
43894
+ level: "info",
43895
+ message: `Cache set for building by id: ${cacheKey}`
43896
+ });
43897
+ }).catch((err) => {
43898
+ import_nodejs_utils73.logger.log({
43899
+ level: "error",
43900
+ message: `Failed to set cache for building by id: ${err.message}`
43901
+ });
43902
+ });
43903
+ return result;
43904
+ } catch (error) {
43905
+ if (error instanceof import_nodejs_utils73.AppError) {
43906
+ throw error;
43907
+ } else {
43908
+ throw new import_nodejs_utils73.InternalServerError("Failed to get building.");
43909
+ }
43910
+ }
43911
+ }
43912
+ async function deleteById(_id, session) {
43913
+ try {
43914
+ _id = new import_mongodb42.ObjectId(_id);
43915
+ } catch (error) {
43916
+ throw new import_nodejs_utils73.BadRequestError(namespace_collection + " Invalid ID.");
43917
+ }
43918
+ try {
43919
+ const res = await collection.updateOne(
43920
+ { _id },
43921
+ { $set: { status: "deleted", deletedAt: /* @__PURE__ */ new Date() } }
43922
+ );
43923
+ delCachedData();
43924
+ return res;
43925
+ } catch (error) {
43926
+ import_nodejs_utils73.logger.log({
43927
+ level: "error",
43928
+ message: error.message
43929
+ });
43930
+ if (error instanceof import_nodejs_utils73.AppError) {
43931
+ throw error;
43932
+ } else {
43933
+ throw new import_nodejs_utils73.InternalServerError("Failed to delete building.");
43934
+ }
43935
+ }
43936
+ }
43937
+ function delCachedData() {
43938
+ delNamespace().then(() => {
43939
+ import_nodejs_utils73.logger.log({
43940
+ level: "info",
43941
+ message: `Cache namespace cleared for ${namespace_collection}`
43942
+ });
43943
+ }).catch((err) => {
43944
+ import_nodejs_utils73.logger.log({
43945
+ level: "error",
43946
+ message: `Failed to clear cache namespace for ${namespace_collection}: ${err.message}`
43947
+ });
43948
+ });
43949
+ }
43950
+ return {
43951
+ createIndexes,
43952
+ add,
43953
+ getAll,
43954
+ getById,
43955
+ updateById,
43956
+ deleteById
43957
+ };
43958
+ }
43959
+
43960
+ // src/resources/building/building.service.ts
43961
+ var import_nodejs_utils75 = require("@eeplatform/nodejs-utils");
43962
+
43963
+ // src/resources/building/building-unit.repository.ts
43964
+ var import_nodejs_utils74 = require("@eeplatform/nodejs-utils");
43965
+ var import_mongodb43 = require("mongodb");
43966
+ function useBuildingUnitRepo() {
43967
+ const db = import_nodejs_utils74.useAtlas.getDb();
43968
+ if (!db) {
43969
+ throw new Error("Unable to connect to server.");
43970
+ }
43971
+ const namespace_collection = "deped.building.units";
43972
+ const collection = db.collection(namespace_collection);
43973
+ const { getCache, setCache, delNamespace } = (0, import_nodejs_utils74.useCache)(namespace_collection);
43974
+ async function createIndexes() {
43975
+ try {
43976
+ await collection.createIndexes([
43977
+ {
43978
+ key: { name: 1, building: 1, level: 1 },
43979
+ unique: true,
43980
+ name: "unique_name_index"
43981
+ },
43982
+ { key: { school: 1 } },
43983
+ { key: { building: 1 } },
43984
+ { key: { status: 1 } },
43985
+ { key: { createdAt: 1 } },
43986
+ {
43987
+ key: {
43988
+ name: "text",
43989
+ buildingName: "text",
43990
+ category: "text",
43991
+ type: "text"
43534
43992
  }
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
43993
  }
43551
- const curriculumSubjects = await getAllCurriculumSubjects({
43552
- schoolYear: Number(value.schoolYear),
43553
- gradeLevel: value.gradeLevel,
43554
- limit: 20
43994
+ ]);
43995
+ } catch (error) {
43996
+ throw new Error("Failed to create index on building units.");
43997
+ }
43998
+ }
43999
+ function delCachedData() {
44000
+ delNamespace().then(() => {
44001
+ import_nodejs_utils74.logger.log({
44002
+ level: "info",
44003
+ message: `Cache namespace cleared for ${namespace_collection}`
44004
+ });
44005
+ }).catch((err) => {
44006
+ import_nodejs_utils74.logger.log({
44007
+ level: "error",
44008
+ message: `Failed to clear cache namespace for ${namespace_collection}: ${err.message}`
44009
+ });
44010
+ });
44011
+ }
44012
+ async function add(value, session) {
44013
+ try {
44014
+ value = MBuildingUnit(value);
44015
+ const res = await collection.insertOne(value, { session });
44016
+ delCachedData();
44017
+ return res.insertedId;
44018
+ } catch (error) {
44019
+ import_nodejs_utils74.logger.log({
44020
+ level: "error",
44021
+ message: error.message
44022
+ });
44023
+ if (error instanceof import_nodejs_utils74.AppError) {
44024
+ throw error;
44025
+ } else {
44026
+ throw new Error("Failed to create building unit.");
44027
+ }
44028
+ }
44029
+ }
44030
+ async function updateById(_id, value, session) {
44031
+ const { error } = schemaUpdateOptions.validate(value);
44032
+ if (error) {
44033
+ throw new import_nodejs_utils74.BadRequestError(error.message);
44034
+ }
44035
+ try {
44036
+ _id = new import_mongodb43.ObjectId(_id);
44037
+ } catch (error2) {
44038
+ throw new import_nodejs_utils74.BadRequestError(namespace_collection + " Invalid ID.");
44039
+ }
44040
+ try {
44041
+ const res = await collection.updateOne(
44042
+ { _id },
44043
+ { $set: value },
44044
+ { session }
44045
+ );
44046
+ delCachedData();
44047
+ return res;
44048
+ } catch (error2) {
44049
+ import_nodejs_utils74.logger.log({
44050
+ level: "error",
44051
+ message: error2.message
44052
+ });
44053
+ if (error2 instanceof import_nodejs_utils74.AppError) {
44054
+ throw error2;
44055
+ } else {
44056
+ throw new Error("Failed to create building unit.");
44057
+ }
44058
+ }
44059
+ }
44060
+ async function updateByBuildingId(building, value, session) {
44061
+ const { error } = schemaUpdateOptions.validate(value);
44062
+ if (error) {
44063
+ throw new import_nodejs_utils74.BadRequestError(error.message);
44064
+ }
44065
+ try {
44066
+ building = new import_mongodb43.ObjectId(building);
44067
+ } catch (error2) {
44068
+ throw new import_nodejs_utils74.BadRequestError("Invalid building ID.");
44069
+ }
44070
+ try {
44071
+ const res = await collection.updateMany(
44072
+ { building },
44073
+ { $set: value },
44074
+ { session }
44075
+ );
44076
+ delCachedData();
44077
+ return res;
44078
+ } catch (error2) {
44079
+ import_nodejs_utils74.logger.log({
44080
+ level: "error",
44081
+ message: error2.message
44082
+ });
44083
+ if (error2 instanceof import_nodejs_utils74.AppError) {
44084
+ throw error2;
44085
+ } else {
44086
+ throw new Error("Failed to update building unit.");
44087
+ }
44088
+ }
44089
+ }
44090
+ async function getAll({
44091
+ search = "",
44092
+ page = 1,
44093
+ limit = 10,
44094
+ sort = {},
44095
+ school = "",
44096
+ building = "",
44097
+ type = "",
44098
+ status = "active"
44099
+ } = {}) {
44100
+ page = page > 0 ? page - 1 : 0;
44101
+ const query = {
44102
+ deletedAt: { $in: ["", null] },
44103
+ status: { $in: [status, "", null] }
44104
+ };
44105
+ const cacheParams = {
44106
+ page,
44107
+ limit,
44108
+ sort: JSON.stringify(sort)
44109
+ };
44110
+ sort = Object.keys(sort).length > 0 ? sort : { _id: -1 };
44111
+ if (search) {
44112
+ query.$text = { $search: search };
44113
+ cacheParams.search = search;
44114
+ }
44115
+ if (school) {
44116
+ try {
44117
+ query.school = new import_mongodb43.ObjectId(school);
44118
+ } catch (error) {
44119
+ throw new import_nodejs_utils74.BadRequestError("Invalid school ID.");
44120
+ }
44121
+ cacheParams.school = school;
44122
+ }
44123
+ if (building) {
44124
+ try {
44125
+ query.building = new import_mongodb43.ObjectId(building);
44126
+ } catch (error) {
44127
+ throw new import_nodejs_utils74.BadRequestError("Invalid building ID.");
44128
+ }
44129
+ cacheParams.building = building;
44130
+ }
44131
+ if (type) {
44132
+ query.type = type;
44133
+ cacheParams.type = type;
44134
+ }
44135
+ const cacheKey = (0, import_nodejs_utils74.makeCacheKey)(namespace_collection, cacheParams);
44136
+ import_nodejs_utils74.logger.log({
44137
+ level: "info",
44138
+ message: `Cache key for getAll building units: ${cacheKey}`
44139
+ });
44140
+ try {
44141
+ const cached = await getCache(cacheKey);
44142
+ if (cached) {
44143
+ import_nodejs_utils74.logger.log({
44144
+ level: "info",
44145
+ message: `Cache hit for getAll building units: ${cacheKey}`
44146
+ });
44147
+ return cached;
44148
+ }
44149
+ const items = await collection.aggregate([
44150
+ { $match: query },
44151
+ { $sort: sort },
44152
+ { $skip: page * limit },
44153
+ { $limit: limit }
44154
+ ]).toArray();
44155
+ const length = await collection.countDocuments(query);
44156
+ const data = (0, import_nodejs_utils74.paginate)(items, page, limit, length);
44157
+ setCache(cacheKey, data, 600).then(() => {
44158
+ import_nodejs_utils74.logger.log({
44159
+ level: "info",
44160
+ message: `Cache set for getAll building units: ${cacheKey}`
44161
+ });
44162
+ }).catch((err) => {
44163
+ import_nodejs_utils74.logger.log({
44164
+ level: "error",
44165
+ message: `Failed to set cache for getAll building units: ${err.message}`
44166
+ });
44167
+ });
44168
+ return data;
44169
+ } catch (error) {
44170
+ import_nodejs_utils74.logger.log({ level: "error", message: `${error}` });
44171
+ throw error;
44172
+ }
44173
+ }
44174
+ async function countByBuilding(building, level) {
44175
+ const query = {
44176
+ status: "active"
44177
+ };
44178
+ const cacheKeyOptions = {
44179
+ ...query,
44180
+ tag: "countByBuilding"
44181
+ };
44182
+ try {
44183
+ query.building = new import_mongodb43.ObjectId(building);
44184
+ cacheKeyOptions.building = String(building);
44185
+ } catch (error) {
44186
+ throw new import_nodejs_utils74.BadRequestError("Invalid building ID.");
44187
+ }
44188
+ if (level) {
44189
+ query.level = level;
44190
+ cacheKeyOptions.level = level;
44191
+ }
44192
+ try {
44193
+ return await collection.countDocuments(query);
44194
+ } catch (error) {
44195
+ import_nodejs_utils74.logger.log({ level: "error", message: `${error}` });
44196
+ throw new import_nodejs_utils74.InternalServerError("Failed to count building units.");
44197
+ }
44198
+ }
44199
+ async function getById(_id) {
44200
+ try {
44201
+ _id = new import_mongodb43.ObjectId(_id);
44202
+ } catch (error) {
44203
+ throw new import_nodejs_utils74.BadRequestError(namespace_collection + " Invalid ID.");
44204
+ }
44205
+ const cacheKey = (0, import_nodejs_utils74.makeCacheKey)(namespace_collection, { _id: String(_id) });
44206
+ try {
44207
+ const cached = await getCache(cacheKey);
44208
+ if (cached) {
44209
+ import_nodejs_utils74.logger.log({
44210
+ level: "info",
44211
+ message: `Cache hit for getById building unit: ${cacheKey}`
43555
44212
  });
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
- }
44213
+ return cached;
43588
44214
  }
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
44215
+ const result = await collection.findOne({
44216
+ _id,
44217
+ deletedAt: { $in: ["", null] }
44218
+ });
44219
+ if (!result) {
44220
+ throw new import_nodejs_utils74.BadRequestError("Building unit not found.");
44221
+ }
44222
+ setCache(cacheKey, result, 300).then(() => {
44223
+ import_nodejs_utils74.logger.log({
44224
+ level: "info",
44225
+ message: `Cache set for building unit by id: ${cacheKey}`
43596
44226
  });
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
- );
44227
+ }).catch((err) => {
44228
+ import_nodejs_utils74.logger.log({
44229
+ level: "error",
44230
+ message: `Failed to set cache for building unit by id: ${err.message}`
44231
+ });
44232
+ });
44233
+ return result;
44234
+ } catch (error) {
44235
+ if (error instanceof import_nodejs_utils74.AppError) {
44236
+ throw error;
44237
+ } else {
44238
+ throw new import_nodejs_utils74.InternalServerError("Failed to get building unit.");
43605
44239
  }
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.");
43611
- }
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
- }
44240
+ }
44241
+ }
44242
+ async function getByBuildingLevel(building, level) {
44243
+ try {
44244
+ building = new import_mongodb43.ObjectId(building);
44245
+ } catch (error) {
44246
+ throw new import_nodejs_utils74.BadRequestError("Invalid building ID.");
44247
+ }
44248
+ const cacheKey = (0, import_nodejs_utils74.makeCacheKey)(namespace_collection, {
44249
+ building: String(building),
44250
+ level
44251
+ });
44252
+ try {
44253
+ const cached = await getCache(cacheKey);
44254
+ if (cached) {
44255
+ import_nodejs_utils74.logger.log({
44256
+ level: "info",
44257
+ message: `Cache hit for getById building unit: ${cacheKey}`
44258
+ });
44259
+ return cached;
43624
44260
  }
43625
- await session.commitTransaction();
43626
- return "Sections generated successfully.";
43627
- } catch (error2) {
43628
- await session.abortTransaction();
43629
- if (error2 instanceof import_nodejs_utils72.AppError) {
43630
- throw error2;
44261
+ const result = await collection.findOne({
44262
+ building,
44263
+ level,
44264
+ status: "active"
44265
+ });
44266
+ setCache(cacheKey, result, 300).then(() => {
44267
+ import_nodejs_utils74.logger.log({
44268
+ level: "info",
44269
+ message: `Cache set for building unit by id: ${cacheKey}`
44270
+ });
44271
+ }).catch((err) => {
44272
+ import_nodejs_utils74.logger.log({
44273
+ level: "error",
44274
+ message: `Failed to set cache for building unit by id: ${err.message}`
44275
+ });
44276
+ });
44277
+ return result;
44278
+ } catch (error) {
44279
+ if (error instanceof import_nodejs_utils74.AppError) {
44280
+ throw error;
43631
44281
  } else {
43632
- throw new import_nodejs_utils72.InternalServerError("Failed to generate sections.");
44282
+ throw new import_nodejs_utils74.InternalServerError("Failed to get building unit.");
43633
44283
  }
43634
- } finally {
43635
- await session?.endSession();
43636
44284
  }
43637
44285
  }
43638
- async function generateSectionPreview(value) {
43639
- const { error } = schemaGenerateSections.validate(value);
43640
- if (error) {
43641
- throw new import_nodejs_utils72.BadRequestError(
43642
- `Invalid section generation data: ${error.message}`
43643
- );
44286
+ async function getByBuilding(building) {
44287
+ try {
44288
+ building = new import_mongodb43.ObjectId(building);
44289
+ } catch (error) {
44290
+ throw new import_nodejs_utils74.BadRequestError("Invalid building ID.");
43644
44291
  }
44292
+ const cacheKey = (0, import_nodejs_utils74.makeCacheKey)(namespace_collection, {
44293
+ building: String(building)
44294
+ });
43645
44295
  try {
43646
- const studentCount = await getCountByGradeLevel({
43647
- school: value.school,
43648
- schoolYear: value.schoolYear,
43649
- gradeLevel: value.gradeLevel,
43650
- specialProgram: value.specialProgram
43651
- });
43652
- if (studentCount === 0) {
43653
- throw new import_nodejs_utils72.BadRequestError("No learners found for this grade level.");
44296
+ const cached = await getCache(cacheKey);
44297
+ if (cached) {
44298
+ import_nodejs_utils74.logger.log({
44299
+ level: "info",
44300
+ message: `Cache hit for getById building unit: ${cacheKey}`
44301
+ });
44302
+ return cached;
43654
44303
  }
43655
- const gradeLevelData = await getByGradeLevel({
43656
- school: value.school,
43657
- gradeLevel: value.gradeLevel
44304
+ const result = await collection.findOne({
44305
+ building,
44306
+ status: "active"
43658
44307
  });
43659
- if (!gradeLevelData) {
43660
- throw new import_nodejs_utils72.BadRequestError("Grade level not found.");
43661
- }
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
- );
44308
+ setCache(cacheKey, result, 300).then(() => {
44309
+ import_nodejs_utils74.logger.log({
44310
+ level: "info",
44311
+ message: `Cache set for building unit by id: ${cacheKey}`
44312
+ });
44313
+ }).catch((err) => {
44314
+ import_nodejs_utils74.logger.log({
44315
+ level: "error",
44316
+ message: `Failed to set cache for building unit by id: ${err.message}`
44317
+ });
44318
+ });
44319
+ return result;
44320
+ } catch (error) {
44321
+ if (error instanceof import_nodejs_utils74.AppError) {
44322
+ throw error;
44323
+ } else {
44324
+ throw new import_nodejs_utils74.InternalServerError("Failed to get building unit.");
43669
44325
  }
43670
- const sectionSizes = distributeStudents(
43671
- studentCount,
43672
- minPerSection,
43673
- maxPerSection
44326
+ }
44327
+ }
44328
+ async function deleteById(_id, session) {
44329
+ try {
44330
+ _id = new import_mongodb43.ObjectId(_id);
44331
+ } catch (error) {
44332
+ throw new import_nodejs_utils74.BadRequestError(namespace_collection + " Invalid ID.");
44333
+ }
44334
+ try {
44335
+ const res = await collection.updateOne(
44336
+ { _id },
44337
+ { $set: { status: "deleted", deletedAt: /* @__PURE__ */ new Date() } },
44338
+ { session }
43674
44339
  );
43675
- if (sectionSizes.length === 0) {
43676
- throw new import_nodejs_utils72.BadRequestError("Unable to compute section sizes.");
43677
- }
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;
44340
+ delCachedData();
44341
+ return "Room/Facility deleted successfully.";
44342
+ } catch (error) {
44343
+ import_nodejs_utils74.logger.log({
44344
+ level: "error",
44345
+ message: error.message
44346
+ });
44347
+ if (error instanceof import_nodejs_utils74.AppError) {
44348
+ throw error;
43690
44349
  } else {
43691
- throw new import_nodejs_utils72.InternalServerError("Failed to generate section preview.");
44350
+ throw new Error("Failed to deleted room/facility.");
43692
44351
  }
43693
44352
  }
43694
44353
  }
43695
- return { generateSections, generateSectionPreview };
44354
+ return {
44355
+ createIndexes,
44356
+ add,
44357
+ getAll,
44358
+ getById,
44359
+ getByBuildingLevel,
44360
+ updateById,
44361
+ getByBuilding,
44362
+ deleteById,
44363
+ updateByBuildingId,
44364
+ countByBuilding
44365
+ };
43696
44366
  }
43697
44367
 
43698
- // src/resources/section/section.controller.ts
43699
- function useSectionController() {
44368
+ // src/resources/building/building.service.ts
44369
+ function useBuildingService() {
43700
44370
  const {
43701
- add: _add,
43702
- getAll: _getAll,
44371
+ updateById: _updateById,
43703
44372
  getById: _getById,
43704
- getByName: _getByName,
43705
- getBySchool: _getBySchool,
43706
- updateFieldById: _updateFieldById,
43707
- addStudentToSection: _addStudentToSection,
43708
- removeStudentFromSection: _removeStudentFromSection,
43709
44373
  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;
44374
+ } = useBuildingRepo();
44375
+ const { getByBuildingLevel, getByBuilding, updateByBuildingId } = useBuildingUnitRepo();
44376
+ async function updateById(id, data) {
44377
+ data.levels = Number(data.levels);
44378
+ const session = import_nodejs_utils75.useAtlas.getClient()?.startSession();
44379
+ try {
44380
+ const building = await _getById(id);
44381
+ if (!building) {
44382
+ throw new import_nodejs_utils75.NotFoundError("Building not found.");
44383
+ }
44384
+ if (data.levels < building.levels) {
44385
+ const unit = await getByBuildingLevel(id, building.levels);
44386
+ if (unit) {
44387
+ throw new import_nodejs_utils75.BadRequestError(
44388
+ "Cannot reduce floors, there are existing building units at higher floors."
44389
+ );
44390
+ }
44391
+ }
44392
+ session?.startTransaction();
44393
+ if (building.name !== data.name) {
44394
+ await updateByBuildingId(id, { buildingName: data.name }, session);
44395
+ }
44396
+ const result = await _updateById(id, data, session);
44397
+ await session?.commitTransaction();
44398
+ return result;
44399
+ } catch (error) {
44400
+ await session?.abortTransaction();
44401
+ throw error;
44402
+ } finally {
44403
+ session?.endSession();
44404
+ }
44405
+ }
44406
+ async function deleteById(id) {
44407
+ const building = await getByBuilding(id);
44408
+ if (building) {
44409
+ throw new import_nodejs_utils75.BadRequestError(
44410
+ "Cannot delete building with existing room/facility. Please delete room/facility first."
44411
+ );
43721
44412
  }
43722
44413
  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);
44414
+ await _deleteById(id);
44415
+ return "Building deleted successfully.";
44416
+ } catch (error) {
44417
+ throw error;
43731
44418
  }
43732
44419
  }
43733
- async function generateSections(req, res, next) {
44420
+ return {
44421
+ updateById,
44422
+ deleteById
44423
+ };
44424
+ }
44425
+
44426
+ // src/resources/building/building.controller.ts
44427
+ var import_nodejs_utils76 = require("@eeplatform/nodejs-utils");
44428
+ var import_joi46 = __toESM(require("joi"));
44429
+ function useBuildingController() {
44430
+ const { getAll: _getAll, getById: _getById, add: _add } = useBuildingRepo();
44431
+ const { updateById: _updateById, deleteById: _deleteById } = useBuildingService();
44432
+ async function createBuilding(req, res, next) {
43734
44433
  const value = req.body;
43735
- const { error } = schemaGenerateSections.validate(value);
44434
+ const validation = import_joi46.default.object({
44435
+ name: import_joi46.default.string().required(),
44436
+ school: import_joi46.default.string().hex().required(),
44437
+ levels: import_joi46.default.number().integer().min(1).required(),
44438
+ serial: import_joi46.default.string().optional().allow("", null),
44439
+ status: import_joi46.default.string().optional().allow("", null)
44440
+ });
44441
+ const { error } = validation.validate(value);
43736
44442
  if (error) {
43737
- next(new import_nodejs_utils73.BadRequestError(error.message));
44443
+ next(new import_nodejs_utils76.BadRequestError(error.message));
44444
+ import_nodejs_utils76.logger.info(`Controller: ${error.message}`);
43738
44445
  return;
43739
44446
  }
43740
44447
  try {
43741
- const data = await _generateSections(value);
43742
- res.json({
43743
- message: "Successfully created section.",
43744
- data
43745
- });
44448
+ const result = await _add(value);
44449
+ res.json(result);
43746
44450
  return;
43747
44451
  } catch (error2) {
43748
44452
  next(error2);
43749
44453
  }
43750
44454
  }
43751
- async function generateSectionPreview(req, res, next) {
44455
+ async function updateById(req, res, next) {
43752
44456
  const value = req.body;
43753
- const { error } = schemaGenerateSections.validate(value);
44457
+ const id = req.params.id ?? "";
44458
+ const validation = import_joi46.default.object({
44459
+ id: import_joi46.default.string().hex().required(),
44460
+ value: import_joi46.default.object({
44461
+ name: import_joi46.default.string().required(),
44462
+ serial: import_joi46.default.string().optional().allow("", null),
44463
+ levels: import_joi46.default.number().integer().min(1).required()
44464
+ })
44465
+ });
44466
+ const { error } = validation.validate({ id, value });
43754
44467
  if (error) {
43755
- next(new import_nodejs_utils73.BadRequestError(error.message));
44468
+ next(new import_nodejs_utils76.BadRequestError(error.message));
44469
+ import_nodejs_utils76.logger.info(`Controller: ${error.message}`);
43756
44470
  return;
43757
44471
  }
43758
44472
  try {
43759
- const data = await _generateSectionPreview(value);
43760
- res.json(data);
44473
+ const result = await _updateById(id, value);
44474
+ res.json(result);
43761
44475
  return;
43762
44476
  } catch (error2) {
43763
44477
  next(error2);
@@ -43765,48 +44479,42 @@ function useSectionController() {
43765
44479
  }
43766
44480
  async function getAll(req, res, next) {
43767
44481
  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)
44482
+ const validation = import_joi46.default.object({
44483
+ page: import_joi46.default.number().min(1).optional().allow("", null),
44484
+ limit: import_joi46.default.number().min(1).optional().allow("", null),
44485
+ search: import_joi46.default.string().optional().allow("", null),
44486
+ school: import_joi46.default.string().hex().optional().allow("", null),
44487
+ status: import_joi46.default.string().optional().allow("", null)
43776
44488
  });
43777
44489
  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
44490
  if (error) {
43796
- next(new import_nodejs_utils73.BadRequestError(error.message));
44491
+ next(new import_nodejs_utils76.BadRequestError(error.message));
43797
44492
  return;
43798
44493
  }
44494
+ const page = parseInt(req.query.page) ?? 1;
44495
+ let limit = parseInt(req.query.limit) ?? 20;
44496
+ limit = isNaN(limit) ? 20 : limit;
44497
+ const sort = req.query.sort ? String(req.query.sort).split(",") : "";
44498
+ const sortOrder = req.query.sortOrder ? String(req.query.sortOrder).split(",") : "";
44499
+ const sortObj = {};
44500
+ if (sort && Array.isArray(sort) && sort.length && sortOrder && Array.isArray(sortOrder) && sortOrder.length) {
44501
+ sort.forEach((field, index) => {
44502
+ sortObj[field] = sortOrder[index] === "desc" ? -1 : 1;
44503
+ });
44504
+ }
44505
+ const status = req.query.status ?? "active";
44506
+ const school = req.query.school ?? "";
44507
+ const search = req.query.search ?? "";
43799
44508
  try {
43800
- const data = await _getAll({
44509
+ const buildings = await _getAll({
43801
44510
  page,
43802
44511
  limit,
43803
- search,
44512
+ sort: sortObj,
43804
44513
  status,
43805
44514
  school,
43806
- schoolYear,
43807
- gradeLevel
44515
+ search
43808
44516
  });
43809
- res.json(data);
44517
+ res.json(buildings);
43810
44518
  return;
43811
44519
  } catch (error2) {
43812
44520
  next(error2);
@@ -43814,228 +44522,261 @@ function useSectionController() {
43814
44522
  }
43815
44523
  async function getById(req, res, next) {
43816
44524
  const id = req.params.id;
43817
- const validation = import_joi45.default.object({
43818
- id: import_joi45.default.string().hex().required()
44525
+ const validation = import_joi46.default.object({
44526
+ id: import_joi46.default.string().hex().required()
43819
44527
  });
43820
44528
  const { error } = validation.validate({ id });
43821
44529
  if (error) {
43822
- next(new import_nodejs_utils73.BadRequestError(error.message));
44530
+ next(new import_nodejs_utils76.BadRequestError(error.message));
43823
44531
  return;
43824
44532
  }
43825
44533
  try {
43826
- const data = await _getById(id);
43827
- res.json(data);
44534
+ const building = await _getById(id);
44535
+ res.json({
44536
+ message: "Successfully retrieved building.",
44537
+ data: { building }
44538
+ });
43828
44539
  return;
43829
44540
  } catch (error2) {
43830
44541
  next(error2);
43831
44542
  }
43832
44543
  }
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()
44544
+ async function deleteById(req, res, next) {
44545
+ const id = req.params.id;
44546
+ const validation = import_joi46.default.object({
44547
+ id: import_joi46.default.string().hex().required()
43837
44548
  });
43838
- const { error } = validation.validate({ name });
44549
+ const { error } = validation.validate({ id });
43839
44550
  if (error) {
43840
- next(new import_nodejs_utils73.BadRequestError(error.message));
44551
+ next(new import_nodejs_utils76.BadRequestError(error.message));
43841
44552
  return;
43842
44553
  }
43843
44554
  try {
43844
- const data = await _getByName(name);
43845
- res.json({
43846
- message: "Successfully retrieved section.",
43847
- data
43848
- });
44555
+ const message = await _deleteById(id);
44556
+ res.json(message);
43849
44557
  return;
43850
44558
  } catch (error2) {
43851
44559
  next(error2);
43852
44560
  }
43853
44561
  }
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;
44562
+ return {
44563
+ createBuilding,
44564
+ getAll,
44565
+ getById,
44566
+ updateById,
44567
+ deleteById
44568
+ };
44569
+ }
44570
+
44571
+ // src/resources/building/building-unit.service.ts
44572
+ var import_nodejs_utils77 = require("@eeplatform/nodejs-utils");
44573
+ function useBuildingUnitService() {
44574
+ const {
44575
+ add: _add,
44576
+ countByBuilding,
44577
+ deleteById: _deleteById
44578
+ } = useBuildingUnitRepo();
44579
+ async function add(value) {
44580
+ const session = import_nodejs_utils77.useAtlas.getClient()?.startSession();
44581
+ if (!session) {
44582
+ throw new Error("Unable to start session for building unit service.");
43863
44583
  }
43864
44584
  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);
44585
+ await session.startTransaction();
44586
+ const existingCount = await countByBuilding(
44587
+ value.building.building,
44588
+ value.building.level
44589
+ );
44590
+ for (let index = 0; index < value.qty; index++) {
44591
+ const unitNumber = existingCount ? existingCount + index + 1 : index + 1;
44592
+ await _add(
44593
+ { ...value.building, name: `${value.building.name} R${unitNumber}` },
44594
+ session
44595
+ );
44596
+ }
44597
+ await session.commitTransaction();
44598
+ return "Building unit added successfully.";
44599
+ } catch (error) {
44600
+ await session.abortTransaction();
44601
+ throw error;
44602
+ } finally {
44603
+ session.endSession();
43873
44604
  }
43874
44605
  }
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;
44606
+ const { getById: getSectionSubjectByClassroom } = useSectionSubjectRepo();
44607
+ async function deleteById(id) {
44608
+ if (!id) {
44609
+ throw new Error("Invalid building unit ID.");
44610
+ }
44611
+ const sectionSubject = await getSectionSubjectByClassroom(id);
44612
+ if (sectionSubject) {
44613
+ throw new Error(
44614
+ "Cannot delete building unit as it is assigned to a section subject."
44615
+ );
43887
44616
  }
43888
44617
  try {
43889
- const message = await _updateFieldById({ _id, field, value });
43890
- res.json({ message });
43891
- return;
43892
- } catch (error2) {
43893
- next(error2);
44618
+ await _deleteById(id);
44619
+ return "Building unit deleted successfully.";
44620
+ } catch (error) {
44621
+ throw new Error("Failed to delete building unit.");
43894
44622
  }
43895
44623
  }
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()
44624
+ return {
44625
+ add,
44626
+ deleteById
44627
+ };
44628
+ }
44629
+
44630
+ // src/resources/building/building-unit.controller.ts
44631
+ var import_nodejs_utils78 = require("@eeplatform/nodejs-utils");
44632
+ var import_joi47 = __toESM(require("joi"));
44633
+ function useBuildingUnitController() {
44634
+ const {
44635
+ getAll: _getAll,
44636
+ getById: _getById,
44637
+ updateById: _updateById
44638
+ } = useBuildingUnitRepo();
44639
+ const { add: _add, deleteById: _deleteById } = useBuildingUnitService();
44640
+ async function add(req, res, next) {
44641
+ const data = req.body;
44642
+ const validation = import_joi47.default.object({
44643
+ building: import_joi47.default.object({
44644
+ school: import_joi47.default.string().hex().required(),
44645
+ name: import_joi47.default.string().optional().allow("", null),
44646
+ building: import_joi47.default.string().hex().required(),
44647
+ buildingName: import_joi47.default.string().optional().allow("", null),
44648
+ level: import_joi47.default.number().integer().min(1).required(),
44649
+ category: import_joi47.default.string().required(),
44650
+ type: import_joi47.default.string().required(),
44651
+ seating_capacity: import_joi47.default.number().integer().min(0).required(),
44652
+ standing_capacity: import_joi47.default.number().integer().min(0).required(),
44653
+ description: import_joi47.default.string().optional().allow("", null),
44654
+ unit_of_measurement: import_joi47.default.string().valid("sqm").required(),
44655
+ area: import_joi47.default.number().positive().required(),
44656
+ status: import_joi47.default.string().optional().allow("", null)
44657
+ }),
44658
+ qty: import_joi47.default.number().integer().min(1).max(20).optional().default(1)
43902
44659
  });
43903
- const { error } = validation.validate({ _id, studentId });
44660
+ const { error } = validation.validate(data);
43904
44661
  if (error) {
43905
- next(new import_nodejs_utils73.BadRequestError(error.message));
44662
+ next(new import_nodejs_utils78.BadRequestError(error.message));
43906
44663
  return;
43907
44664
  }
43908
44665
  try {
43909
- const message = await _addStudentToSection(_id, studentId);
43910
- res.json({ message });
43911
- return;
44666
+ const buildingUnit = await _add(data);
44667
+ res.json({
44668
+ message: "Building unit added successfully.",
44669
+ data: { buildingUnit }
44670
+ });
43912
44671
  } catch (error2) {
43913
44672
  next(error2);
43914
44673
  }
43915
44674
  }
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()
44675
+ async function updateById(req, res, next) {
44676
+ const data = req.body;
44677
+ const id = req.params.id ?? "";
44678
+ const validation = import_joi47.default.object({
44679
+ id: import_joi47.default.string().hex().required(),
44680
+ value: schemaUpdateOptions
43922
44681
  });
43923
- const { error } = validation.validate({ _id, studentId });
44682
+ const { error } = validation.validate({ id, value: data });
43924
44683
  if (error) {
43925
- next(new import_nodejs_utils73.BadRequestError(error.message));
44684
+ next(new import_nodejs_utils78.BadRequestError(error.message));
43926
44685
  return;
43927
44686
  }
43928
44687
  try {
43929
- const message = await _removeStudentFromSection(_id, studentId);
43930
- res.json({ message });
43931
- return;
44688
+ const buildingUnit = await _updateById(id, data);
44689
+ res.json({
44690
+ message: "Building unit updated successfully.",
44691
+ data: { buildingUnit }
44692
+ });
43932
44693
  } catch (error2) {
43933
44694
  next(error2);
43934
44695
  }
43935
44696
  }
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()
44697
+ async function getAll(req, res, next) {
44698
+ const query = req.query;
44699
+ const validation = import_joi47.default.object({
44700
+ page: import_joi47.default.number().min(1).optional().allow("", null),
44701
+ limit: import_joi47.default.number().min(1).optional().allow("", null),
44702
+ search: import_joi47.default.string().optional().allow("", null),
44703
+ school: import_joi47.default.string().hex().optional().allow("", null),
44704
+ building: import_joi47.default.string().hex().optional().allow("", null),
44705
+ status: import_joi47.default.string().optional().allow("", null),
44706
+ type: import_joi47.default.string().optional().allow("", null)
43940
44707
  });
43941
- const { error } = validation.validate({ _id });
44708
+ const { error } = validation.validate(query);
43942
44709
  if (error) {
43943
- next(new import_nodejs_utils73.BadRequestError(error.message));
44710
+ next(new import_nodejs_utils78.BadRequestError(error.message));
43944
44711
  return;
43945
44712
  }
44713
+ const page = parseInt(req.query.page) ?? 1;
44714
+ let limit = parseInt(req.query.limit) ?? 20;
44715
+ limit = isNaN(limit) ? 20 : limit;
44716
+ const sort = req.query.sort ? String(req.query.sort).split(",") : "";
44717
+ const sortOrder = req.query.sortOrder ? String(req.query.sortOrder).split(",") : "";
44718
+ const sortObj = {};
44719
+ if (sort && Array.isArray(sort) && sort.length && sortOrder && Array.isArray(sortOrder) && sortOrder.length) {
44720
+ sort.forEach((field, index) => {
44721
+ sortObj[field] = sortOrder[index] === "desc" ? -1 : 1;
44722
+ });
44723
+ }
44724
+ const status = req.query.status ?? "active";
44725
+ const school = req.query.school ?? "";
44726
+ const building = req.query.building ?? "";
44727
+ const search = req.query.search ?? "";
44728
+ const type = req.query.type ?? "";
43946
44729
  try {
43947
- const message = await _deleteById(_id);
43948
- res.json({ message });
44730
+ const buildings = await _getAll({
44731
+ page,
44732
+ limit,
44733
+ sort: sortObj,
44734
+ status,
44735
+ school,
44736
+ search,
44737
+ building,
44738
+ type
44739
+ });
44740
+ res.json(buildings);
43949
44741
  return;
43950
44742
  } catch (error2) {
43951
44743
  next(error2);
43952
44744
  }
43953
44745
  }
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);
44746
+ async function getById(req, res, next) {
44747
+ const id = req.params.id;
44748
+ const validation = import_joi47.default.object({
44749
+ id: import_joi47.default.string().hex().required()
44750
+ });
44751
+ const { error } = validation.validate({ id });
43977
44752
  if (error) {
43978
- next(new import_nodejs_utils74.BadRequestError(error.message));
44753
+ next(new import_nodejs_utils78.BadRequestError(error.message));
43979
44754
  return;
43980
44755
  }
43981
44756
  try {
43982
- const data = await _add(value);
44757
+ const buildingUnit = await _getById(id);
43983
44758
  res.json({
43984
- message: "Successfully created section student.",
43985
- data
44759
+ message: "Successfully retrieved building unit.",
44760
+ data: { buildingUnit }
43986
44761
  });
43987
44762
  return;
43988
44763
  } catch (error2) {
43989
44764
  next(error2);
43990
44765
  }
43991
44766
  }
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)
44767
+ async function deleteById(req, res, next) {
44768
+ const id = req.params.id;
44769
+ const validation = import_joi47.default.object({
44770
+ id: import_joi47.default.string().hex().required()
44003
44771
  });
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
- }
44772
+ const { error } = validation.validate({ id });
44023
44773
  if (error) {
44024
- next(new import_nodejs_utils74.BadRequestError(error.message));
44774
+ next(new import_nodejs_utils78.BadRequestError(error.message));
44025
44775
  return;
44026
44776
  }
44027
44777
  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);
44778
+ const message = await _deleteById(id);
44779
+ res.json({ message });
44039
44780
  return;
44040
44781
  } catch (error2) {
44041
44782
  next(error2);
@@ -44043,403 +44784,153 @@ function useSectionStudentController() {
44043
44784
  }
44044
44785
  return {
44045
44786
  add,
44046
- getAll
44787
+ getAll,
44788
+ getById,
44789
+ updateById,
44790
+ deleteById
44047
44791
  };
44048
44792
  }
44049
44793
 
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)
44794
+ // src/resources/kindergarten-routine/kindergarten.routine.model.ts
44795
+ var import_nodejs_utils79 = require("@eeplatform/nodejs-utils");
44796
+ var import_joi48 = __toESM(require("joi"));
44797
+ var import_mongodb44 = require("mongodb");
44798
+ var schemaKindergartenRoutine = import_joi48.default.object({
44799
+ _id: import_joi48.default.string().hex().optional().allow(null, ""),
44800
+ title: import_joi48.default.string().max(100).required(),
44801
+ section: import_joi48.default.string().hex().optional().allow(null, ""),
44802
+ sectionName: import_joi48.default.string().max(100).optional().allow(null, ""),
44803
+ classroom: import_joi48.default.string().hex().optional().allow(null, ""),
44804
+ classroomName: import_joi48.default.string().max(100).optional().allow(null, ""),
44805
+ blockTimes: import_joi48.default.array().items(
44806
+ import_joi48.default.object({
44807
+ id: import_joi48.default.number().required(),
44808
+ title: import_joi48.default.string().required(),
44809
+ startTime: import_joi48.default.string().required(),
44810
+ endTime: import_joi48.default.string().required(),
44811
+ durationMinutes: import_joi48.default.number().required(),
44812
+ domains: import_joi48.default.array().items(import_joi48.default.string()).optional()
44813
+ })
44814
+ ).required(),
44815
+ type: import_joi48.default.string().required(),
44816
+ durationMinutes: import_joi48.default.number().optional().allow(null, 0),
44817
+ school: import_joi48.default.string().hex().required(),
44818
+ schoolYear: import_joi48.default.string().optional().allow(null, ""),
44819
+ createdAt: import_joi48.default.string().isoDate().optional().allow(null, ""),
44820
+ updatedAt: import_joi48.default.string().isoDate().optional().allow(null, ""),
44821
+ deletedAt: import_joi48.default.string().isoDate().optional().allow(null, "")
44080
44822
  });
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)
44823
+ var schemaKindergartenRoutineUpdate = import_joi48.default.object({
44824
+ title: import_joi48.default.string().max(100).optional().allow(null, ""),
44825
+ section: import_joi48.default.string().hex().optional().allow(null, ""),
44826
+ sectionName: import_joi48.default.string().max(100).optional().allow(null, ""),
44827
+ classroom: import_joi48.default.string().hex().optional().allow(null, ""),
44828
+ classroomName: import_joi48.default.string().max(100).optional().allow(null, ""),
44829
+ blockTimes: import_joi48.default.array().items(
44830
+ import_joi48.default.object({
44831
+ id: import_joi48.default.number().required(),
44832
+ title: import_joi48.default.string().required(),
44833
+ startTime: import_joi48.default.string().required(),
44834
+ endTime: import_joi48.default.string().required(),
44835
+ durationMinutes: import_joi48.default.number().required(),
44836
+ domains: import_joi48.default.array().items(import_joi48.default.string()).optional()
44837
+ })
44838
+ ).optional(),
44839
+ durationMinutes: import_joi48.default.number().optional().allow(null, 0)
44091
44840
  });
44092
- function MBuilding(value) {
44093
- const { error } = schemaBuilding.validate(value);
44841
+ function modelKindergartenRoutine(value) {
44842
+ const { error } = schemaKindergartenRoutine.validate(value);
44094
44843
  if (error) {
44095
- import_nodejs_utils75.logger.info(`Building Model: ${error.message}`);
44096
- throw new import_nodejs_utils75.BadRequestError(error.message);
44844
+ throw new import_nodejs_utils79.BadRequestError(
44845
+ `Invalid kindergarten routine data: ${error.message}`
44846
+ );
44097
44847
  }
44098
44848
  if (value._id && typeof value._id === "string") {
44099
44849
  try {
44100
- value._id = new import_mongodb43.ObjectId(value._id);
44850
+ value._id = new import_mongodb44.ObjectId(value._id);
44101
44851
  } catch (error2) {
44102
- throw new import_nodejs_utils75.BadRequestError("Invalid _id format");
44852
+ throw new Error("Invalid _id.");
44103
44853
  }
44104
44854
  }
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") {
44855
+ if (value.school && typeof value.school === "string") {
44129
44856
  try {
44130
- value._id = new import_mongodb43.ObjectId(value._id);
44857
+ value.school = new import_mongodb44.ObjectId(value.school);
44131
44858
  } 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;
44859
+ throw new Error("Invalid school.");
44307
44860
  }
44308
44861
  }
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) });
44862
+ if (value.section && typeof value.section === "string") {
44316
44863
  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
- }
44864
+ value.section = new import_mongodb44.ObjectId(value.section);
44865
+ } catch (error2) {
44866
+ throw new Error("Invalid section.");
44346
44867
  }
44347
44868
  }
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
- }
44869
+ if (value.classroom && typeof value.classroom === "string") {
44354
44870
  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
- }
44871
+ value.classroom = new import_mongodb44.ObjectId(value.classroom);
44872
+ } catch (error2) {
44873
+ throw new Error("Invalid classroom.");
44371
44874
  }
44372
44875
  }
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
44876
  return {
44387
- createIndexes,
44388
- add,
44389
- getAll,
44390
- getById,
44391
- updateById,
44392
- deleteById
44877
+ _id: value._id,
44878
+ title: value.title,
44879
+ section: value.section,
44880
+ sectionName: value.sectionName ?? "",
44881
+ classroom: value.classroom,
44882
+ classroomName: value.classroomName ?? "",
44883
+ blockTimes: value.blockTimes,
44884
+ type: value.type,
44885
+ durationMinutes: value.durationMinutes ?? 0,
44886
+ status: value.status ?? "active",
44887
+ school: value.school,
44888
+ schoolYear: value.schoolYear ?? "",
44889
+ createdAt: value.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
44890
+ updatedAt: value.updatedAt ?? "",
44891
+ deletedAt: value.deletedAt ?? ""
44393
44892
  };
44394
44893
  }
44395
44894
 
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");
44895
+ // src/resources/kindergarten-routine/kindergarten.routine.repository.ts
44896
+ var import_nodejs_utils80 = require("@eeplatform/nodejs-utils");
44401
44897
  var import_mongodb45 = require("mongodb");
44402
- function useBuildingUnitRepo() {
44403
- const db = import_nodejs_utils77.useAtlas.getDb();
44898
+ function useKindergartenRoutineRepo() {
44899
+ const db = import_nodejs_utils80.useAtlas.getDb();
44404
44900
  if (!db) {
44405
44901
  throw new Error("Unable to connect to server.");
44406
44902
  }
44407
- const namespace_collection = "deped.building.units";
44903
+ const namespace_collection = "deped.kindergarten.routines";
44408
44904
  const collection = db.collection(namespace_collection);
44409
- const { getCache, setCache, delNamespace } = (0, import_nodejs_utils77.useCache)(namespace_collection);
44905
+ const { getCache, setCache, delNamespace } = (0, import_nodejs_utils80.useCache)(namespace_collection);
44410
44906
  async function createIndexes() {
44411
44907
  try {
44412
44908
  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 } },
44909
+ { key: { section: 1 } },
44910
+ { key: { classroom: 1 } },
44911
+ { key: { schedule: 1 } },
44912
+ { key: { type: 1 } },
44421
44913
  { key: { createdAt: 1 } },
44914
+ { key: { createdBy: 1 } },
44915
+ { key: { sectionName: "text", classroomName: "text" } },
44422
44916
  {
44423
- key: {
44424
- name: "text",
44425
- buildingName: "text",
44426
- category: "text",
44427
- type: "text"
44428
- }
44917
+ key: { title: 1, school: 1, type: 1, section: 1, status: 1 },
44918
+ unique: true,
44919
+ name: "unique_kindergarten_routine"
44429
44920
  }
44430
44921
  ]);
44431
44922
  } catch (error) {
44432
- throw new Error("Failed to create index on building units.");
44923
+ throw new Error("Failed to create index on kindergarten routines.");
44433
44924
  }
44434
44925
  }
44435
44926
  function delCachedData() {
44436
44927
  delNamespace().then(() => {
44437
- import_nodejs_utils77.logger.log({
44928
+ import_nodejs_utils80.logger.log({
44438
44929
  level: "info",
44439
44930
  message: `Cache namespace cleared for ${namespace_collection}`
44440
44931
  });
44441
44932
  }).catch((err) => {
44442
- import_nodejs_utils77.logger.log({
44933
+ import_nodejs_utils80.logger.log({
44443
44934
  level: "error",
44444
44935
  message: `Failed to clear cache namespace for ${namespace_collection}: ${err.message}`
44445
44936
  });
@@ -44447,79 +44938,23 @@ function useBuildingUnitRepo() {
44447
44938
  }
44448
44939
  async function add(value, session) {
44449
44940
  try {
44450
- value = MBuildingUnit(value);
44941
+ value = modelKindergartenRoutine(value);
44451
44942
  const res = await collection.insertOne(value, { session });
44452
44943
  delCachedData();
44453
44944
  return res.insertedId;
44454
44945
  } catch (error) {
44455
- import_nodejs_utils77.logger.log({
44946
+ import_nodejs_utils80.logger.log({
44456
44947
  level: "error",
44457
44948
  message: error.message
44458
44949
  });
44459
- if (error instanceof import_nodejs_utils77.AppError) {
44950
+ if (error instanceof import_nodejs_utils80.AppError) {
44460
44951
  throw error;
44461
44952
  } 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.");
44953
+ const isDuplicated = error.message.includes("duplicate");
44954
+ if (isDuplicated) {
44955
+ throw new import_nodejs_utils80.BadRequestError("Kinder schedule already exists.");
44956
+ }
44957
+ throw new Error("Failed to create kindergarten routine.");
44523
44958
  }
44524
44959
  }
44525
44960
  }
@@ -44528,57 +44963,81 @@ function useBuildingUnitRepo() {
44528
44963
  page = 1,
44529
44964
  limit = 10,
44530
44965
  sort = {},
44966
+ status = "active",
44967
+ createdBy,
44531
44968
  school = "",
44532
- building = "",
44969
+ section = "",
44970
+ classroom = "",
44533
44971
  type = "",
44534
- status = "active"
44972
+ schoolYear = ""
44535
44973
  } = {}) {
44536
44974
  page = page > 0 ? page - 1 : 0;
44537
44975
  const query = {
44538
44976
  deletedAt: { $in: ["", null] },
44539
- status: { $in: [status, "", null] }
44977
+ status
44540
44978
  };
44541
- const cacheParams = {
44979
+ sort = Object.keys(sort).length > 0 ? sort : { _id: 1 };
44980
+ const cacheKeyOptions = {
44981
+ status,
44542
44982
  page,
44543
44983
  limit,
44544
44984
  sort: JSON.stringify(sort)
44545
44985
  };
44546
- sort = Object.keys(sort).length > 0 ? sort : { _id: -1 };
44986
+ if (createdBy) {
44987
+ try {
44988
+ query.createdBy = new import_mongodb45.ObjectId(createdBy);
44989
+ } catch (error) {
44990
+ throw new import_nodejs_utils80.BadRequestError("Invalid createdBy ID.");
44991
+ }
44992
+ cacheKeyOptions.createdBy = createdBy;
44993
+ }
44547
44994
  if (search) {
44548
44995
  query.$text = { $search: search };
44549
- cacheParams.search = search;
44996
+ cacheKeyOptions.search = search;
44997
+ }
44998
+ if (school) {
44999
+ try {
45000
+ query.school = new import_mongodb45.ObjectId(school);
45001
+ } catch (error) {
45002
+ throw new import_nodejs_utils80.BadRequestError("Invalid school ID.");
45003
+ }
45004
+ cacheKeyOptions.school = school;
44550
45005
  }
44551
- if (school) {
45006
+ if (section) {
44552
45007
  try {
44553
- query.school = new import_mongodb45.ObjectId(school);
45008
+ query.section = new import_mongodb45.ObjectId(section);
44554
45009
  } catch (error) {
44555
- throw new import_nodejs_utils77.BadRequestError("Invalid school ID.");
45010
+ throw new import_nodejs_utils80.BadRequestError("Invalid section ID.");
44556
45011
  }
44557
- cacheParams.school = school;
45012
+ cacheKeyOptions.section = section;
44558
45013
  }
44559
- if (building) {
45014
+ if (classroom) {
44560
45015
  try {
44561
- query.building = new import_mongodb45.ObjectId(building);
45016
+ query.classroom = new import_mongodb45.ObjectId(classroom);
44562
45017
  } catch (error) {
44563
- throw new import_nodejs_utils77.BadRequestError("Invalid building ID.");
45018
+ throw new import_nodejs_utils80.BadRequestError("Invalid classroom ID.");
44564
45019
  }
44565
- cacheParams.building = building;
45020
+ cacheKeyOptions.classroom = classroom;
44566
45021
  }
44567
45022
  if (type) {
44568
45023
  query.type = type;
44569
- cacheParams.type = type;
45024
+ cacheKeyOptions.type = type;
45025
+ }
45026
+ if (schoolYear) {
45027
+ query.schoolYear = schoolYear;
45028
+ cacheKeyOptions.schoolYear = schoolYear;
44570
45029
  }
44571
- const cacheKey = (0, import_nodejs_utils77.makeCacheKey)(namespace_collection, cacheParams);
44572
- import_nodejs_utils77.logger.log({
45030
+ const cacheKey = (0, import_nodejs_utils80.makeCacheKey)(namespace_collection, cacheKeyOptions);
45031
+ import_nodejs_utils80.logger.log({
44573
45032
  level: "info",
44574
- message: `Cache key for getAll building units: ${cacheKey}`
45033
+ message: `Cache key for getAll kindergarten routines: ${cacheKey}`
44575
45034
  });
44576
45035
  try {
44577
45036
  const cached = await getCache(cacheKey);
44578
45037
  if (cached) {
44579
- import_nodejs_utils77.logger.log({
45038
+ import_nodejs_utils80.logger.log({
44580
45039
  level: "info",
44581
- message: `Cache hit for getAll building units: ${cacheKey}`
45040
+ message: `Cache hit for getAll kindergarten routines: ${cacheKey}`
44582
45041
  });
44583
45042
  return cached;
44584
45043
  }
@@ -44589,62 +45048,37 @@ function useBuildingUnitRepo() {
44589
45048
  { $limit: limit }
44590
45049
  ]).toArray();
44591
45050
  const length = await collection.countDocuments(query);
44592
- const data = (0, import_nodejs_utils77.paginate)(items, page, limit, length);
45051
+ const data = (0, import_nodejs_utils80.paginate)(items, page, limit, length);
44593
45052
  setCache(cacheKey, data, 600).then(() => {
44594
- import_nodejs_utils77.logger.log({
45053
+ import_nodejs_utils80.logger.log({
44595
45054
  level: "info",
44596
- message: `Cache set for getAll building units: ${cacheKey}`
45055
+ message: `Cache set for getAll kindergarten routines: ${cacheKey}`
44597
45056
  });
44598
45057
  }).catch((err) => {
44599
- import_nodejs_utils77.logger.log({
45058
+ import_nodejs_utils80.logger.log({
44600
45059
  level: "error",
44601
- message: `Failed to set cache for getAll building units: ${err.message}`
45060
+ message: `Failed to set cache for getAll kindergarten routines: ${err.message}`
44602
45061
  });
44603
45062
  });
44604
45063
  return data;
44605
45064
  } catch (error) {
44606
- import_nodejs_utils77.logger.log({ level: "error", message: `${error}` });
45065
+ import_nodejs_utils80.logger.log({ level: "error", message: `${error}` });
44607
45066
  throw error;
44608
45067
  }
44609
45068
  }
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
45069
  async function getById(_id) {
44636
45070
  try {
44637
45071
  _id = new import_mongodb45.ObjectId(_id);
44638
45072
  } catch (error) {
44639
- throw new import_nodejs_utils77.BadRequestError(namespace_collection + " Invalid ID.");
45073
+ throw new import_nodejs_utils80.BadRequestError(namespace_collection + " Invalid ID.");
44640
45074
  }
44641
- const cacheKey = (0, import_nodejs_utils77.makeCacheKey)(namespace_collection, { _id: String(_id) });
45075
+ const cacheKey = (0, import_nodejs_utils80.makeCacheKey)(namespace_collection, { _id: String(_id) });
44642
45076
  try {
44643
45077
  const cached = await getCache(cacheKey);
44644
45078
  if (cached) {
44645
- import_nodejs_utils77.logger.log({
45079
+ import_nodejs_utils80.logger.log({
44646
45080
  level: "info",
44647
- message: `Cache hit for getById building unit: ${cacheKey}`
45081
+ message: `Cache hit for getById kindergarten routine: ${cacheKey}`
44648
45082
  });
44649
45083
  return cached;
44650
45084
  }
@@ -44652,305 +45086,276 @@ function useBuildingUnitRepo() {
44652
45086
  _id,
44653
45087
  deletedAt: { $in: ["", null] }
44654
45088
  });
44655
- if (!result) {
44656
- throw new import_nodejs_utils77.BadRequestError("Building unit not found.");
44657
- }
44658
45089
  setCache(cacheKey, result, 300).then(() => {
44659
- import_nodejs_utils77.logger.log({
45090
+ import_nodejs_utils80.logger.log({
44660
45091
  level: "info",
44661
- message: `Cache set for building unit by id: ${cacheKey}`
45092
+ message: `Cache set for kindergarten routine by id: ${cacheKey}`
44662
45093
  });
44663
45094
  }).catch((err) => {
44664
- import_nodejs_utils77.logger.log({
45095
+ import_nodejs_utils80.logger.log({
44665
45096
  level: "error",
44666
- message: `Failed to set cache for building unit by id: ${err.message}`
45097
+ message: `Failed to set cache for kindergarten routine by id: ${err.message}`
44667
45098
  });
44668
45099
  });
44669
45100
  return result;
44670
45101
  } catch (error) {
44671
- if (error instanceof import_nodejs_utils77.AppError) {
45102
+ if (error instanceof import_nodejs_utils80.AppError) {
44672
45103
  throw error;
44673
45104
  } else {
44674
- throw new import_nodejs_utils77.InternalServerError("Failed to get building unit.");
45105
+ throw new import_nodejs_utils80.InternalServerError("Failed to get kindergarten routine.");
44675
45106
  }
44676
45107
  }
44677
45108
  }
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
45109
+ async function countByDomain(domain) {
45110
+ const cacheKey = (0, import_nodejs_utils80.makeCacheKey)(namespace_collection, {
45111
+ domain,
45112
+ tag: "getByDomain"
44687
45113
  });
44688
45114
  try {
44689
45115
  const cached = await getCache(cacheKey);
44690
45116
  if (cached) {
44691
- import_nodejs_utils77.logger.log({
45117
+ import_nodejs_utils80.logger.log({
44692
45118
  level: "info",
44693
- message: `Cache hit for getById building unit: ${cacheKey}`
45119
+ message: `Cache hit for getById kindergarten routine: ${cacheKey}`
44694
45120
  });
44695
45121
  return cached;
44696
45122
  }
44697
- const result = await collection.findOne({
44698
- building,
44699
- level,
45123
+ const result = await collection.countDocuments({
45124
+ domain,
44700
45125
  status: "active"
44701
45126
  });
44702
45127
  setCache(cacheKey, result, 300).then(() => {
44703
- import_nodejs_utils77.logger.log({
45128
+ import_nodejs_utils80.logger.log({
44704
45129
  level: "info",
44705
- message: `Cache set for building unit by id: ${cacheKey}`
45130
+ message: `Cache set for kindergarten routine by id: ${cacheKey}`
44706
45131
  });
44707
45132
  }).catch((err) => {
44708
- import_nodejs_utils77.logger.log({
45133
+ import_nodejs_utils80.logger.log({
44709
45134
  level: "error",
44710
- message: `Failed to set cache for building unit by id: ${err.message}`
45135
+ message: `Failed to set cache for kindergarten routine by id: ${err.message}`
44711
45136
  });
44712
45137
  });
44713
45138
  return result;
44714
45139
  } catch (error) {
44715
- if (error instanceof import_nodejs_utils77.AppError) {
45140
+ if (error instanceof import_nodejs_utils80.AppError) {
44716
45141
  throw error;
44717
45142
  } else {
44718
- throw new import_nodejs_utils77.InternalServerError("Failed to get building unit.");
45143
+ throw new import_nodejs_utils80.InternalServerError("Failed to get kindergarten routine.");
44719
45144
  }
44720
45145
  }
44721
45146
  }
44722
- async function getByBuilding(building) {
45147
+ async function getBySection(section) {
44723
45148
  try {
44724
- building = new import_mongodb45.ObjectId(building);
45149
+ section = new import_mongodb45.ObjectId(section);
44725
45150
  } catch (error) {
44726
- throw new import_nodejs_utils77.BadRequestError("Invalid building ID.");
45151
+ throw new import_nodejs_utils80.BadRequestError("Invalid section ID.");
44727
45152
  }
44728
- const cacheKey = (0, import_nodejs_utils77.makeCacheKey)(namespace_collection, {
44729
- building: String(building)
45153
+ const cacheKey = (0, import_nodejs_utils80.makeCacheKey)(namespace_collection, {
45154
+ section: String(section)
44730
45155
  });
44731
45156
  try {
44732
45157
  const cached = await getCache(cacheKey);
44733
45158
  if (cached) {
44734
- import_nodejs_utils77.logger.log({
45159
+ import_nodejs_utils80.logger.log({
44735
45160
  level: "info",
44736
- message: `Cache hit for getById building unit: ${cacheKey}`
45161
+ message: `Cache hit for getBySection kindergarten routine: ${cacheKey}`
44737
45162
  });
44738
45163
  return cached;
44739
45164
  }
44740
- const result = await collection.findOne({
44741
- building,
44742
- status: "active"
44743
- });
45165
+ const result = await collection.find({
45166
+ section,
45167
+ deletedAt: { $in: ["", null] }
45168
+ }).toArray();
44744
45169
  setCache(cacheKey, result, 300).then(() => {
44745
- import_nodejs_utils77.logger.log({
45170
+ import_nodejs_utils80.logger.log({
44746
45171
  level: "info",
44747
- message: `Cache set for building unit by id: ${cacheKey}`
45172
+ message: `Cache set for kindergarten routine by section: ${cacheKey}`
44748
45173
  });
44749
45174
  }).catch((err) => {
44750
- import_nodejs_utils77.logger.log({
45175
+ import_nodejs_utils80.logger.log({
44751
45176
  level: "error",
44752
- message: `Failed to set cache for building unit by id: ${err.message}`
45177
+ message: `Failed to set cache for kindergarten routine by section: ${err.message}`
44753
45178
  });
44754
45179
  });
44755
45180
  return result;
44756
45181
  } catch (error) {
44757
- if (error instanceof import_nodejs_utils77.AppError) {
45182
+ if (error instanceof import_nodejs_utils80.AppError) {
44758
45183
  throw error;
44759
45184
  } else {
44760
- throw new import_nodejs_utils77.InternalServerError("Failed to get building unit.");
45185
+ throw new import_nodejs_utils80.InternalServerError("Failed to get kindergarten routine.");
44761
45186
  }
44762
45187
  }
44763
45188
  }
44764
- async function deleteById(_id, session) {
45189
+ async function updateFieldById({ _id, field, value } = {}, session) {
45190
+ const allowedFields = [
45191
+ "sectionName",
45192
+ "classroomName",
45193
+ "schedule",
45194
+ "blockTimes",
45195
+ "type"
45196
+ ];
45197
+ if (!allowedFields.includes(field)) {
45198
+ throw new import_nodejs_utils80.BadRequestError(
45199
+ `Field "${field}" is not allowed to be updated.`
45200
+ );
45201
+ }
44765
45202
  try {
44766
45203
  _id = new import_mongodb45.ObjectId(_id);
44767
45204
  } catch (error) {
44768
- throw new import_nodejs_utils77.BadRequestError(namespace_collection + " Invalid ID.");
45205
+ throw new import_nodejs_utils80.BadRequestError(namespace_collection + " Invalid ID.");
44769
45206
  }
44770
45207
  try {
44771
- const res = await collection.updateOne(
44772
- { _id },
44773
- { $set: { status: "deleted", deletedAt: /* @__PURE__ */ new Date() } },
45208
+ await collection.updateOne(
45209
+ { _id, deletedAt: { $in: ["", null] } },
45210
+ { $set: { [field]: value, updatedAt: (/* @__PURE__ */ new Date()).toISOString() } },
44774
45211
  { session }
44775
45212
  );
44776
45213
  delCachedData();
44777
- return "Room/Facility deleted successfully.";
45214
+ return `Successfully updated kindergarten routine ${field}.`;
44778
45215
  } 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
- }
45216
+ throw new import_nodejs_utils80.InternalServerError(
45217
+ `Failed to update kindergarten routine ${field}.`
45218
+ );
44788
45219
  }
44789
45220
  }
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();
45221
+ async function updateById(_id, value, session) {
45222
+ const { error } = schemaKindergartenRoutineUpdate.validate(value);
45223
+ if (error) {
45224
+ throw new import_nodejs_utils80.BadRequestError(
45225
+ `Invalid kindergarten routine data: ${error.message}`
45226
+ );
45227
+ }
44815
45228
  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();
45229
+ _id = new import_mongodb45.ObjectId(_id);
45230
+ } catch (error2) {
45231
+ throw new import_nodejs_utils80.BadRequestError(namespace_collection + " Invalid ID.");
44840
45232
  }
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."
45233
+ try {
45234
+ await collection.updateOne(
45235
+ { _id },
45236
+ { $set: { ...value, updatedAt: (/* @__PURE__ */ new Date()).toISOString() } },
45237
+ { session }
44847
45238
  );
45239
+ delCachedData();
45240
+ return `Successfully updated kindergarten routine.`;
45241
+ } catch (error2) {
45242
+ throw new import_nodejs_utils80.InternalServerError("Failed to update kindergarten routine.");
44848
45243
  }
45244
+ }
45245
+ async function deleteById(_id) {
44849
45246
  try {
44850
- await _deleteById(id);
44851
- return "Building deleted successfully.";
45247
+ _id = new import_mongodb45.ObjectId(_id);
44852
45248
  } catch (error) {
44853
- throw error;
45249
+ throw new import_nodejs_utils80.BadRequestError(namespace_collection + " Invalid ID.");
45250
+ }
45251
+ try {
45252
+ await collection.updateOne(
45253
+ { _id },
45254
+ { $set: { status: "deleted", deletedAt: (/* @__PURE__ */ new Date()).toISOString() } }
45255
+ );
45256
+ delCachedData();
45257
+ return "Successfully deleted kindergarten routine.";
45258
+ } catch (error) {
45259
+ throw new import_nodejs_utils80.InternalServerError("Failed to delete kindergarten routine.");
44854
45260
  }
44855
45261
  }
44856
45262
  return {
45263
+ createIndexes,
45264
+ add,
45265
+ getAll,
45266
+ getById,
45267
+ countByDomain,
45268
+ getBySection,
45269
+ updateFieldById,
44857
45270
  updateById,
44858
45271
  deleteById
44859
45272
  };
44860
45273
  }
44861
45274
 
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) {
45275
+ // src/resources/kindergarten-routine/kindergarten.routine.controller.ts
45276
+ var import_nodejs_utils81 = require("@eeplatform/nodejs-utils");
45277
+ var import_joi49 = __toESM(require("joi"));
45278
+ function useKindergartenRoutineController() {
45279
+ const {
45280
+ add: _add,
45281
+ getAll: _getAll,
45282
+ getById: _getById,
45283
+ getBySection: _getBySection,
45284
+ updateFieldById: _updateFieldById,
45285
+ deleteById: _deleteById,
45286
+ updateById: _updateById
45287
+ } = useKindergartenRoutineRepo();
45288
+ async function add(req, res, next) {
44869
45289
  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);
45290
+ const { error } = schemaKindergartenRoutine.validate(value);
44878
45291
  if (error) {
44879
- next(new import_nodejs_utils79.BadRequestError(error.message));
44880
- import_nodejs_utils79.logger.info(`Controller: ${error.message}`);
45292
+ next(new import_nodejs_utils81.BadRequestError(error.message));
44881
45293
  return;
44882
45294
  }
44883
45295
  try {
44884
- const result = await _add(value);
44885
- res.json(result);
45296
+ const data = await _add(value);
45297
+ res.json({
45298
+ message: "Successfully created kinder schedule.",
45299
+ data
45300
+ });
44886
45301
  return;
44887
45302
  } catch (error2) {
44888
45303
  next(error2);
44889
45304
  }
44890
45305
  }
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
- })
45306
+ async function getAll(req, res, next) {
45307
+ const query = req.query;
45308
+ const validation = import_joi49.default.object({
45309
+ page: import_joi49.default.number().min(1).optional().allow("", null),
45310
+ limit: import_joi49.default.number().min(1).optional().allow("", null),
45311
+ search: import_joi49.default.string().optional().allow("", null),
45312
+ status: import_joi49.default.string().optional().allow("", null),
45313
+ school: import_joi49.default.string().hex().optional().allow("", null),
45314
+ section: import_joi49.default.string().hex().optional().allow("", null),
45315
+ classroom: import_joi49.default.string().hex().optional().allow("", null),
45316
+ type: import_joi49.default.string().optional().allow("", null),
45317
+ createdBy: import_joi49.default.string().hex().optional().allow("", null),
45318
+ schoolYear: import_joi49.default.string().optional().allow("", null)
44901
45319
  });
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}`);
45320
+ const { error } = validation.validate(query);
45321
+ const page = typeof req.query.page === "string" ? Number(req.query.page) : 1;
45322
+ const limit = typeof req.query.limit === "string" ? Number(req.query.limit) : 10;
45323
+ const search = req.query.search ?? "";
45324
+ const status = req.query.status ?? "active";
45325
+ const school = req.query.school ?? "";
45326
+ const section = req.query.section ?? "";
45327
+ const classroom = req.query.classroom ?? "";
45328
+ const type = req.query.type ?? "";
45329
+ const createdBy = req.query.createdBy ?? "";
45330
+ const schoolYear = req.query.schoolYear ?? "";
45331
+ const isPageNumber = isFinite(page);
45332
+ if (!isPageNumber) {
45333
+ next(new import_nodejs_utils81.BadRequestError("Invalid page number."));
44906
45334
  return;
44907
45335
  }
44908
- try {
44909
- const result = await _updateById(id, value);
44910
- res.json(result);
45336
+ const isLimitNumber = isFinite(limit);
45337
+ if (!isLimitNumber) {
45338
+ next(new import_nodejs_utils81.BadRequestError("Invalid limit number."));
44911
45339
  return;
44912
- } catch (error2) {
44913
- next(error2);
44914
45340
  }
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
45341
  if (error) {
44927
- next(new import_nodejs_utils79.BadRequestError(error.message));
45342
+ next(new import_nodejs_utils81.BadRequestError(error.message));
44928
45343
  return;
44929
45344
  }
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
45345
  try {
44945
- const buildings = await _getAll({
45346
+ const data = await _getAll({
44946
45347
  page,
44947
45348
  limit,
44948
- sort: sortObj,
45349
+ search,
44949
45350
  status,
44950
45351
  school,
44951
- search
45352
+ section,
45353
+ classroom,
45354
+ type,
45355
+ createdBy: createdBy || void 0,
45356
+ schoolYear
44952
45357
  });
44953
- res.json(buildings);
45358
+ res.json(data);
44954
45359
  return;
44955
45360
  } catch (error2) {
44956
45361
  next(error2);
@@ -44958,260 +45363,100 @@ function useBuildingController() {
44958
45363
  }
44959
45364
  async function getById(req, res, next) {
44960
45365
  const id = req.params.id;
44961
- const validation = import_joi48.default.object({
44962
- id: import_joi48.default.string().hex().required()
45366
+ const validation = import_joi49.default.object({
45367
+ id: import_joi49.default.string().hex().required()
44963
45368
  });
44964
45369
  const { error } = validation.validate({ id });
44965
45370
  if (error) {
44966
- next(new import_nodejs_utils79.BadRequestError(error.message));
45371
+ next(new import_nodejs_utils81.BadRequestError(error.message));
44967
45372
  return;
44968
45373
  }
44969
45374
  try {
44970
- const building = await _getById(id);
45375
+ const data = await _getById(id);
44971
45376
  res.json({
44972
- message: "Successfully retrieved building.",
44973
- data: { building }
45377
+ message: "Successfully retrieved kinder schedule.",
45378
+ data
44974
45379
  });
44975
45380
  return;
44976
45381
  } catch (error2) {
44977
45382
  next(error2);
44978
45383
  }
44979
45384
  }
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;
45385
+ async function getBySection(req, res, next) {
45386
+ const section = req.params.section;
45078
45387
  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)
45388
+ section: import_joi49.default.string().hex().required()
45095
45389
  });
45096
- const { error } = validation.validate(data);
45390
+ const { error } = validation.validate({ section });
45097
45391
  if (error) {
45098
45392
  next(new import_nodejs_utils81.BadRequestError(error.message));
45099
45393
  return;
45100
45394
  }
45101
45395
  try {
45102
- const buildingUnit = await _add(data);
45396
+ const data = await _getBySection(section);
45103
45397
  res.json({
45104
- message: "Building unit added successfully.",
45105
- data: { buildingUnit }
45398
+ message: "Successfully retrieved kinder schedules.",
45399
+ data
45106
45400
  });
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
45401
  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
45402
  } catch (error2) {
45130
45403
  next(error2);
45131
45404
  }
45132
45405
  }
45133
- async function getAll(req, res, next) {
45134
- const query = req.query;
45406
+ async function updateField(req, res, next) {
45407
+ const _id = req.params.id;
45408
+ const { field, value } = req.body;
45135
45409
  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)
45410
+ _id: import_joi49.default.string().hex().required(),
45411
+ field: import_joi49.default.string().valid("sectionName", "classroomName", "schedule", "blockTimes", "type").required(),
45412
+ value: import_joi49.default.alternatives().try(import_joi49.default.string(), import_joi49.default.array(), import_joi49.default.object()).required()
45143
45413
  });
45144
- const { error } = validation.validate(query);
45414
+ const { error } = validation.validate({ _id, field, value });
45145
45415
  if (error) {
45146
45416
  next(new import_nodejs_utils81.BadRequestError(error.message));
45147
45417
  return;
45148
45418
  }
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
45419
  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);
45420
+ const message = await _updateFieldById({ _id, field, value });
45421
+ res.json({ message });
45177
45422
  return;
45178
45423
  } catch (error2) {
45179
45424
  next(error2);
45180
45425
  }
45181
45426
  }
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 });
45427
+ async function updateById(req, res, next) {
45428
+ const _id = req.params.id;
45429
+ const payload = req.body;
45430
+ const { error: errorId } = import_joi49.default.string().hex().required().validate(_id);
45431
+ if (errorId) {
45432
+ next(new import_nodejs_utils81.BadRequestError(errorId.message));
45433
+ return;
45434
+ }
45435
+ const { error } = schemaKindergartenRoutineUpdate.validate(payload);
45188
45436
  if (error) {
45189
45437
  next(new import_nodejs_utils81.BadRequestError(error.message));
45190
45438
  return;
45191
45439
  }
45192
45440
  try {
45193
- const buildingUnit = await _getById(id);
45194
- res.json({
45195
- message: "Successfully retrieved building unit.",
45196
- data: { buildingUnit }
45197
- });
45441
+ const message = await _updateById(_id, payload);
45442
+ res.json({ message });
45198
45443
  return;
45199
45444
  } catch (error2) {
45200
45445
  next(error2);
45201
45446
  }
45202
45447
  }
45203
45448
  async function deleteById(req, res, next) {
45204
- const id = req.params.id;
45449
+ const _id = req.params.id;
45205
45450
  const validation = import_joi49.default.object({
45206
- id: import_joi49.default.string().hex().required()
45451
+ _id: import_joi49.default.string().hex().required()
45207
45452
  });
45208
- const { error } = validation.validate({ id });
45453
+ const { error } = validation.validate({ _id });
45209
45454
  if (error) {
45210
45455
  next(new import_nodejs_utils81.BadRequestError(error.message));
45211
45456
  return;
45212
45457
  }
45213
45458
  try {
45214
- const message = await _deleteById(id);
45459
+ const message = await _deleteById(_id);
45215
45460
  res.json({ message });
45216
45461
  return;
45217
45462
  } catch (error2) {
@@ -45222,6 +45467,8 @@ function useBuildingUnitController() {
45222
45467
  add,
45223
45468
  getAll,
45224
45469
  getById,
45470
+ getBySection,
45471
+ updateField,
45225
45472
  updateById,
45226
45473
  deleteById
45227
45474
  };