@eeplatform/core 1.2.1 → 1.3.0

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/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @eeplatform/core
2
2
 
3
+ ## 1.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - ca4131b: Inventory mgmt initial release
8
+
3
9
  ## 1.2.1
4
10
 
5
11
  ### Patch Changes
package/dist/index.d.ts CHANGED
@@ -2534,6 +2534,7 @@ declare function useBuildingUnitRepo(): {
2534
2534
  }, session?: ClientSession) => Promise<mongodb.UpdateResult<bson.Document>>;
2535
2535
  getByBuilding: (building: string | ObjectId) => Promise<TBuildingUnit | null>;
2536
2536
  deleteById: (_id: string | ObjectId, session?: ClientSession) => Promise<string>;
2537
+ updateByBuildingId: (building: string | ObjectId, value: Partial<Pick<TBuildingUnit, "buildingName">>, session?: ClientSession) => Promise<mongodb.UpdateResult<bson.Document>>;
2537
2538
  };
2538
2539
 
2539
2540
  declare function useBuildingController(): {
@@ -2552,6 +2553,94 @@ declare function useBuildingUnitController(): {
2552
2553
  deleteById: (req: Request, res: Response, next: NextFunction) => Promise<void>;
2553
2554
  };
2554
2555
 
2556
+ type TInventory = {
2557
+ _id?: ObjectId;
2558
+ school: ObjectId;
2559
+ name: string;
2560
+ category: string;
2561
+ type: string;
2562
+ unit_of_measurement_category: string;
2563
+ unit_of_measurement_type: string;
2564
+ status?: string;
2565
+ qty?: number;
2566
+ brand?: string;
2567
+ createdAt?: string | Date;
2568
+ updatedAt?: string | Date;
2569
+ deletedAt?: string | Date;
2570
+ condition?: {
2571
+ good: number;
2572
+ disposal: number;
2573
+ lost: number;
2574
+ damaged: number;
2575
+ };
2576
+ metadata?: {
2577
+ title?: string;
2578
+ isbn?: string;
2579
+ author?: string;
2580
+ edition?: string;
2581
+ subject?: string;
2582
+ grade_level?: number;
2583
+ publisher?: string;
2584
+ language?: string;
2585
+ };
2586
+ };
2587
+ declare const schemaInventory: Joi.ObjectSchema<any>;
2588
+ declare const schemaInventoryUpdateOption: Joi.ObjectSchema<any>;
2589
+ declare function MInventory(value: TInventory): {
2590
+ _id: ObjectId;
2591
+ school: ObjectId;
2592
+ name: string;
2593
+ category: string;
2594
+ type: string;
2595
+ brand: string;
2596
+ qty: number;
2597
+ condition: {
2598
+ good: number;
2599
+ disposal: number;
2600
+ lost: number;
2601
+ damaged: number;
2602
+ };
2603
+ unit_of_measurement_category: string;
2604
+ unit_of_measurement_type: string;
2605
+ status: string;
2606
+ createdAt: Date;
2607
+ updatedAt: string | Date;
2608
+ deletedAt: string | Date;
2609
+ metadata: {
2610
+ title?: string | undefined;
2611
+ isbn?: string | undefined;
2612
+ author?: string | undefined;
2613
+ edition?: string | undefined;
2614
+ subject?: string | undefined;
2615
+ grade_level?: number | undefined;
2616
+ publisher?: string | undefined;
2617
+ language?: string | undefined;
2618
+ };
2619
+ };
2620
+
2621
+ declare function useInventoryRepo(): {
2622
+ createIndex: () => Promise<void>;
2623
+ add: (value: TInventory) => Promise<ObjectId>;
2624
+ updateById: (_id: string | ObjectId, value: Partial<Pick<TInventory, "name" | "brand" | "category" | "type" | "unit_of_measurement_category" | "unit_of_measurement_type">>) => Promise<string>;
2625
+ deleteById: (_id: string | ObjectId) => Promise<string>;
2626
+ getById: (_id: string | ObjectId) => Promise<{}>;
2627
+ getAll: ({ page, search, limit, status, school, sort, }?: {
2628
+ page?: number | undefined;
2629
+ search?: string | undefined;
2630
+ limit?: number | undefined;
2631
+ status?: string | undefined;
2632
+ school?: string | ObjectId | undefined;
2633
+ sort?: Record<string, any> | undefined;
2634
+ }) => Promise<{}>;
2635
+ };
2636
+
2637
+ declare function useInventoryController(): {
2638
+ add: (req: Request, res: Response, next: NextFunction) => Promise<void>;
2639
+ getAll: (req: Request, res: Response, next: NextFunction) => Promise<void>;
2640
+ deleteById: (req: Request, res: Response, next: NextFunction) => Promise<void>;
2641
+ updateById: (req: Request, res: Response, next: NextFunction) => Promise<void>;
2642
+ };
2643
+
2555
2644
  declare const MONGO_URI: string;
2556
2645
  declare const MONGO_DB: string;
2557
2646
  declare const PORT: number;
@@ -2588,4 +2677,4 @@ declare const PAYPAL_API_URL: string;
2588
2677
  declare const XENDIT_SECRET_KEY: string;
2589
2678
  declare const XENDIT_BASE_URL: string;
2590
2679
 
2591
- export { ACCESS_TOKEN_EXPIRY, ACCESS_TOKEN_SECRET, APP_ACCOUNT, APP_MAIN, CardPayment, CardPaymentSchema, DEFAULT_USER_EMAIL, DEFAULT_USER_FIRST_NAME, DEFAULT_USER_LAST_NAME, DEFAULT_USER_PASSWORD, DirectDebit, DirectDebitSchema, EWalletPayment, EWalletPaymentSchema, MAILER_EMAIL, MAILER_PASSWORD, MAILER_TRANSPORT_HOST, MAILER_TRANSPORT_PORT, MAILER_TRANSPORT_SECURE, MAddress, MBuilding, MBuildingUnit, MDivision, MEntity, MFile, MMember, MONGO_DB, MONGO_URI, MOrder, MOrg, MPaymentMethod, MPromoCode, MRegion, MRole, MSchool, MSubscription, MToken, MUser, MUserRole, MVerification, PAYPAL_API_URL, PAYPAL_CLIENT_ID, PAYPAL_CLIENT_SECRET, PORT, REDIS_HOST, REDIS_PASSWORD, REDIS_PORT, REFRESH_TOKEN_EXPIRY, REFRESH_TOKEN_SECRET, SECRET_KEY, SPACES_ACCESS_KEY, SPACES_BUCKET, SPACES_ENDPOINT, SPACES_REGION, SPACES_SECRET_KEY, TAddress, TBillingRecipient, TBuilding, TBuildingUnit, TCounter, TDivision, TEntity, TFile, TInvoice, TMember, TMiniRole, TOrder, TOrderMetadata, TOrg, TPayment, TPaymentMethod$1 as TPaymentMethod, TPaymentMethodType, TPrice, TPriceType, TPromoCode, TPromoTier, TRegion, TRole, TSchool, TSubscription, TToken, TUser, TUserRole, TVerification, TVerificationMetadata, VERIFICATION_FORGET_PASSWORD_DURATION, VERIFICATION_USER_INVITE_DURATION, XENDIT_BASE_URL, XENDIT_SECRET_KEY, addressSchema, isDev, schema, schemaBuilding, schemaBuildingUnit, schemaDivision, schemaRegion, schemaSchool, schemaUpdateOptions, useAddressController, useAddressRepo, useAuthController, useAuthService, useBuildingController, useBuildingRepo, useBuildingUnitController, useBuildingUnitRepo, useCounterModel, useCounterRepo, useDivisionController, useDivisionRepo, useDivisionService, useEntityController, useEntityRepo, useFileController, useFileRepo, useFileService, useInvoiceController, useInvoiceModel, useInvoiceRepo, useInvoiceService, useMemberController, useMemberRepo, useOrderController, useOrderRepo, useOrgController, useOrgRepo, useOrgService, usePaymentController, usePaymentMethodController, usePaymentMethodRepo, usePaymentMethodService, usePaymentModel, usePaymentRepo, usePaypalService, usePriceController, usePriceModel, usePriceRepo, usePromoCodeController, usePromoCodeRepo, useRegionController, useRegionRepo, useRegionService, useRoleController, useRoleRepo, useSchoolController, useSchoolRepo, useSchoolService, useSubscriptionController, useSubscriptionRepo, useSubscriptionService, useTokenRepo, useUserController, useUserRepo, useUserService, useVerificationController, useVerificationRepo, useVerificationService, useXenditService, validateCardPayment, validateDirectDebit, validateEWalletPayment };
2680
+ export { ACCESS_TOKEN_EXPIRY, ACCESS_TOKEN_SECRET, APP_ACCOUNT, APP_MAIN, CardPayment, CardPaymentSchema, DEFAULT_USER_EMAIL, DEFAULT_USER_FIRST_NAME, DEFAULT_USER_LAST_NAME, DEFAULT_USER_PASSWORD, DirectDebit, DirectDebitSchema, EWalletPayment, EWalletPaymentSchema, MAILER_EMAIL, MAILER_PASSWORD, MAILER_TRANSPORT_HOST, MAILER_TRANSPORT_PORT, MAILER_TRANSPORT_SECURE, MAddress, MBuilding, MBuildingUnit, MDivision, MEntity, MFile, MInventory, MMember, MONGO_DB, MONGO_URI, MOrder, MOrg, MPaymentMethod, MPromoCode, MRegion, MRole, MSchool, MSubscription, MToken, MUser, MUserRole, MVerification, PAYPAL_API_URL, PAYPAL_CLIENT_ID, PAYPAL_CLIENT_SECRET, PORT, REDIS_HOST, REDIS_PASSWORD, REDIS_PORT, REFRESH_TOKEN_EXPIRY, REFRESH_TOKEN_SECRET, SECRET_KEY, SPACES_ACCESS_KEY, SPACES_BUCKET, SPACES_ENDPOINT, SPACES_REGION, SPACES_SECRET_KEY, TAddress, TBillingRecipient, TBuilding, TBuildingUnit, TCounter, TDivision, TEntity, TFile, TInventory, TInvoice, TMember, TMiniRole, TOrder, TOrderMetadata, TOrg, TPayment, TPaymentMethod$1 as TPaymentMethod, TPaymentMethodType, TPrice, TPriceType, TPromoCode, TPromoTier, TRegion, TRole, TSchool, TSubscription, TToken, TUser, TUserRole, TVerification, TVerificationMetadata, VERIFICATION_FORGET_PASSWORD_DURATION, VERIFICATION_USER_INVITE_DURATION, XENDIT_BASE_URL, XENDIT_SECRET_KEY, addressSchema, isDev, schema, schemaBuilding, schemaBuildingUnit, schemaDivision, schemaInventory, schemaInventoryUpdateOption, schemaRegion, schemaSchool, schemaUpdateOptions, useAddressController, useAddressRepo, useAuthController, useAuthService, useBuildingController, useBuildingRepo, useBuildingUnitController, useBuildingUnitRepo, useCounterModel, useCounterRepo, useDivisionController, useDivisionRepo, useDivisionService, useEntityController, useEntityRepo, useFileController, useFileRepo, useFileService, useInventoryController, useInventoryRepo, useInvoiceController, useInvoiceModel, useInvoiceRepo, useInvoiceService, useMemberController, useMemberRepo, useOrderController, useOrderRepo, useOrgController, useOrgRepo, useOrgService, usePaymentController, usePaymentMethodController, usePaymentMethodRepo, usePaymentMethodService, usePaymentModel, usePaymentRepo, usePaypalService, usePriceController, usePriceModel, usePriceRepo, usePromoCodeController, usePromoCodeRepo, useRegionController, useRegionRepo, useRegionService, useRoleController, useRoleRepo, useSchoolController, useSchoolRepo, useSchoolService, useSubscriptionController, useSubscriptionRepo, useSubscriptionService, useTokenRepo, useUserController, useUserRepo, useUserService, useVerificationController, useVerificationRepo, useVerificationService, useXenditService, validateCardPayment, validateDirectDebit, validateEWalletPayment };
package/dist/index.js CHANGED
@@ -11347,6 +11347,7 @@ __export(src_exports, {
11347
11347
  MDivision: () => MDivision,
11348
11348
  MEntity: () => MEntity,
11349
11349
  MFile: () => MFile,
11350
+ MInventory: () => MInventory,
11350
11351
  MMember: () => MMember,
11351
11352
  MONGO_DB: () => MONGO_DB,
11352
11353
  MONGO_URI: () => MONGO_URI,
@@ -11387,6 +11388,8 @@ __export(src_exports, {
11387
11388
  schemaBuilding: () => schemaBuilding,
11388
11389
  schemaBuildingUnit: () => schemaBuildingUnit,
11389
11390
  schemaDivision: () => schemaDivision,
11391
+ schemaInventory: () => schemaInventory,
11392
+ schemaInventoryUpdateOption: () => schemaInventoryUpdateOption,
11390
11393
  schemaRegion: () => schemaRegion,
11391
11394
  schemaSchool: () => schemaSchool,
11392
11395
  schemaUpdateOptions: () => schemaUpdateOptions,
@@ -11408,6 +11411,8 @@ __export(src_exports, {
11408
11411
  useFileController: () => useFileController,
11409
11412
  useFileRepo: () => useFileRepo,
11410
11413
  useFileService: () => useFileService,
11414
+ useInventoryController: () => useInventoryController,
11415
+ useInventoryRepo: () => useInventoryRepo,
11411
11416
  useInvoiceController: () => useInvoiceController,
11412
11417
  useInvoiceModel: () => useInvoiceModel,
11413
11418
  useInvoiceRepo: () => useInvoiceRepo,
@@ -26991,6 +26996,7 @@ var schemaBuildingUnit = import_joi33.default.object({
26991
26996
  var schemaUpdateOptions = import_joi33.default.object({
26992
26997
  name: import_joi33.default.string().optional().allow("", null),
26993
26998
  building: import_joi33.default.string().hex().optional().allow("", null),
26999
+ buildingName: import_joi33.default.string().optional().allow("", null),
26994
27000
  level: import_joi33.default.number().integer().min(1).optional().allow("", null),
26995
27001
  category: import_joi33.default.string().optional().allow("", null),
26996
27002
  type: import_joi33.default.string().optional().allow("", null),
@@ -27399,6 +27405,36 @@ function useBuildingUnitRepo() {
27399
27405
  }
27400
27406
  }
27401
27407
  }
27408
+ async function updateByBuildingId(building, value, session) {
27409
+ const { error } = schemaUpdateOptions.validate(value);
27410
+ if (error) {
27411
+ throw new import_nodejs_utils68.BadRequestError(error.message);
27412
+ }
27413
+ try {
27414
+ building = new import_mongodb41.ObjectId(building);
27415
+ } catch (error2) {
27416
+ throw new import_nodejs_utils68.BadRequestError("Invalid building ID.");
27417
+ }
27418
+ try {
27419
+ const res = await collection.updateMany(
27420
+ { building },
27421
+ { $set: value },
27422
+ { session }
27423
+ );
27424
+ delCachedData();
27425
+ return res;
27426
+ } catch (error2) {
27427
+ import_nodejs_utils68.logger.log({
27428
+ level: "error",
27429
+ message: error2.message
27430
+ });
27431
+ if (error2 instanceof import_nodejs_utils68.AppError) {
27432
+ throw error2;
27433
+ } else {
27434
+ throw new Error("Failed to update building unit.");
27435
+ }
27436
+ }
27437
+ }
27402
27438
  async function getAll({
27403
27439
  search = "",
27404
27440
  page = 1,
@@ -27646,7 +27682,8 @@ function useBuildingUnitRepo() {
27646
27682
  getByBuildingLevel,
27647
27683
  updateById,
27648
27684
  getByBuilding,
27649
- deleteById
27685
+ deleteById,
27686
+ updateByBuildingId
27650
27687
  };
27651
27688
  }
27652
27689
 
@@ -27662,9 +27699,10 @@ function useBuildingService() {
27662
27699
  getById: _getById,
27663
27700
  deleteById: _deleteById
27664
27701
  } = useBuildingRepo();
27665
- const { getByBuildingLevel, getByBuilding } = useBuildingUnitRepo();
27702
+ const { getByBuildingLevel, getByBuilding, updateByBuildingId } = useBuildingUnitRepo();
27666
27703
  async function updateById(id, data) {
27667
27704
  data.levels = Number(data.levels);
27705
+ const session = import_nodejs_utils69.useAtlas.getClient()?.startSession();
27668
27706
  try {
27669
27707
  const building = await _getById(id);
27670
27708
  if (!building) {
@@ -27678,10 +27716,18 @@ function useBuildingService() {
27678
27716
  );
27679
27717
  }
27680
27718
  }
27681
- const result = await _updateById(id, data);
27719
+ session?.startTransaction();
27720
+ if (building.name !== data.name) {
27721
+ await updateByBuildingId(id, { buildingName: data.name }, session);
27722
+ }
27723
+ const result = await _updateById(id, data, session);
27724
+ await session?.commitTransaction();
27682
27725
  return result;
27683
27726
  } catch (error) {
27727
+ await session?.abortTransaction();
27684
27728
  throw error;
27729
+ } finally {
27730
+ session?.endSession();
27685
27731
  }
27686
27732
  }
27687
27733
  async function deleteById(id) {
@@ -28038,6 +28084,393 @@ function useBuildingUnitController() {
28038
28084
  deleteById
28039
28085
  };
28040
28086
  }
28087
+
28088
+ // src/models/inventory.model.ts
28089
+ var import_nodejs_utils73 = require("@eeplatform/nodejs-utils");
28090
+ var import_joi36 = __toESM(require("joi"));
28091
+ var import_mongodb42 = require("mongodb");
28092
+ var schemaInventory = import_joi36.default.object({
28093
+ _id: import_joi36.default.string().hex().optional(),
28094
+ school: import_joi36.default.string().hex().required(),
28095
+ name: import_joi36.default.string().required(),
28096
+ category: import_joi36.default.string().optional().allow("", null),
28097
+ type: import_joi36.default.string().optional().allow("", null),
28098
+ brand: import_joi36.default.string().optional().allow("", null),
28099
+ unit_of_measurement_category: import_joi36.default.string().required(),
28100
+ unit_of_measurement_type: import_joi36.default.string().required(),
28101
+ status: import_joi36.default.string().optional().allow("", null),
28102
+ createdAt: import_joi36.default.date().optional().allow("", null),
28103
+ updatedAt: import_joi36.default.date().optional().allow("", null),
28104
+ deletedAt: import_joi36.default.date().optional().allow("", null),
28105
+ metadata: import_joi36.default.object({
28106
+ title: import_joi36.default.string().optional().allow("", null),
28107
+ isbn: import_joi36.default.string().optional().allow("", null),
28108
+ author: import_joi36.default.string().optional().allow("", null),
28109
+ edition: import_joi36.default.string().optional().allow("", null),
28110
+ subject: import_joi36.default.string().optional().allow("", null),
28111
+ grade_level: import_joi36.default.number().integer().min(0).optional().allow("", null),
28112
+ publisher: import_joi36.default.string().optional().allow("", null),
28113
+ language: import_joi36.default.string().optional().allow("", null)
28114
+ }).optional().allow(null)
28115
+ });
28116
+ var schemaInventoryUpdateOption = import_joi36.default.object({
28117
+ name: import_joi36.default.string().optional().allow("", null),
28118
+ category: import_joi36.default.string().optional().allow("", null),
28119
+ type: import_joi36.default.string().optional().allow("", null),
28120
+ brand: import_joi36.default.string().optional().allow("", null),
28121
+ qty: import_joi36.default.number().integer().min(0).optional().allow("", null),
28122
+ unit_of_measurement_category: import_joi36.default.string().optional().allow("", null),
28123
+ unit_of_measurement_type: import_joi36.default.string().optional().allow("", null),
28124
+ metadata: import_joi36.default.object({
28125
+ title: import_joi36.default.string().optional().allow("", null),
28126
+ isbn: import_joi36.default.string().optional().allow("", null),
28127
+ author: import_joi36.default.string().optional().allow("", null),
28128
+ edition: import_joi36.default.string().optional().allow("", null),
28129
+ subject: import_joi36.default.string().optional().allow("", null),
28130
+ grade_level: import_joi36.default.number().integer().min(0).optional().allow("", null),
28131
+ publisher: import_joi36.default.string().optional().allow("", null),
28132
+ language: import_joi36.default.string().optional().allow("", null)
28133
+ }).optional().allow(null)
28134
+ });
28135
+ function MInventory(value) {
28136
+ const { error } = schemaInventory.validate(value);
28137
+ if (error) {
28138
+ throw new import_nodejs_utils73.BadRequestError(error.message);
28139
+ }
28140
+ if (value._id && typeof value._id === "string") {
28141
+ try {
28142
+ value._id = new import_mongodb42.ObjectId();
28143
+ } catch (error2) {
28144
+ throw new import_nodejs_utils73.BadRequestError("Invalid ID.");
28145
+ }
28146
+ }
28147
+ try {
28148
+ value.school = new import_mongodb42.ObjectId(value.school);
28149
+ } catch (error2) {
28150
+ throw new import_nodejs_utils73.BadRequestError("Invalid school ID.");
28151
+ }
28152
+ value.createdAt = value.createdAt ? new Date(value.createdAt) : /* @__PURE__ */ new Date();
28153
+ value.updatedAt = value.updatedAt ? new Date(value.updatedAt) : "";
28154
+ value.deletedAt = value.deletedAt ? new Date(value.deletedAt) : "";
28155
+ return {
28156
+ _id: value._id ?? new import_mongodb42.ObjectId(),
28157
+ school: value.school,
28158
+ name: value.name,
28159
+ category: value.category ?? "",
28160
+ type: value.type ?? "",
28161
+ brand: value.brand ?? "",
28162
+ qty: value.qty ?? 0,
28163
+ condition: value.condition ?? {
28164
+ good: 0,
28165
+ disposal: 0,
28166
+ lost: 0,
28167
+ damaged: 0
28168
+ },
28169
+ unit_of_measurement_category: value.unit_of_measurement_category ?? "",
28170
+ unit_of_measurement_type: value.unit_of_measurement_type ?? "",
28171
+ status: value.status ?? "active",
28172
+ createdAt: value.createdAt,
28173
+ updatedAt: value.updatedAt,
28174
+ deletedAt: value.deletedAt,
28175
+ metadata: value.metadata ?? {}
28176
+ };
28177
+ }
28178
+
28179
+ // src/repositories/inventory.repository.ts
28180
+ var import_nodejs_utils74 = require("@eeplatform/nodejs-utils");
28181
+ var import_mongodb43 = require("mongodb");
28182
+ function useInventoryRepo() {
28183
+ const db = import_nodejs_utils74.useAtlas.getDb();
28184
+ if (!db) {
28185
+ throw new import_nodejs_utils74.BadRequestError("Unable to connect to server.");
28186
+ }
28187
+ const namespace_collection = "school.inventories";
28188
+ const collection = db.collection(namespace_collection);
28189
+ const { getCache, setCache, delNamespace } = (0, import_nodejs_utils74.useCache)(namespace_collection);
28190
+ function delCachedData() {
28191
+ delNamespace().then(() => {
28192
+ import_nodejs_utils74.logger.log({
28193
+ level: "info",
28194
+ message: `Cache namespace cleared for ${namespace_collection}`
28195
+ });
28196
+ }).catch((err) => {
28197
+ import_nodejs_utils74.logger.log({
28198
+ level: "error",
28199
+ message: `Failed to clear cache namespace for ${namespace_collection}: ${err.message}`
28200
+ });
28201
+ });
28202
+ }
28203
+ async function createIndex() {
28204
+ try {
28205
+ await collection.createIndexes([
28206
+ { key: { school: 1 } },
28207
+ { key: { name: 1 } },
28208
+ { key: { name: "text" } }
28209
+ ]);
28210
+ } catch (error) {
28211
+ throw new import_nodejs_utils74.BadRequestError("Failed to create index on inventory.");
28212
+ }
28213
+ }
28214
+ async function add(value) {
28215
+ try {
28216
+ value = MInventory(value);
28217
+ const res = await collection.insertOne(value);
28218
+ delCachedData();
28219
+ return res.insertedId;
28220
+ } catch (error) {
28221
+ throw new import_nodejs_utils74.BadRequestError("Failed to create inventory item.");
28222
+ }
28223
+ }
28224
+ async function updateById(_id, value) {
28225
+ const { error } = schemaInventoryUpdateOption.validate(value);
28226
+ if (error) {
28227
+ throw new import_nodejs_utils74.BadRequestError(error.message);
28228
+ }
28229
+ try {
28230
+ _id = new import_mongodb43.ObjectId(_id);
28231
+ } catch (error2) {
28232
+ throw new import_nodejs_utils74.BadRequestError("Invalid ID.");
28233
+ }
28234
+ try {
28235
+ const res = await collection.updateOne({ _id }, { $set: value });
28236
+ if (res.modifiedCount) {
28237
+ delCachedData();
28238
+ }
28239
+ return "Successfully updated inventory item.";
28240
+ } catch (error2) {
28241
+ throw new import_nodejs_utils74.BadRequestError("Failed to update inventory item.");
28242
+ }
28243
+ }
28244
+ async function deleteById(_id) {
28245
+ try {
28246
+ _id = new import_mongodb43.ObjectId(_id);
28247
+ } catch (error) {
28248
+ throw new import_nodejs_utils74.BadRequestError("Invalid ID.");
28249
+ }
28250
+ try {
28251
+ const res = await collection.deleteOne({ _id });
28252
+ if (res.deletedCount) {
28253
+ delCachedData();
28254
+ return "Successfully deleted inventory item.";
28255
+ }
28256
+ return "Successfully deleted inventory item.";
28257
+ } catch (error) {
28258
+ throw new import_nodejs_utils74.BadRequestError("Failed to delete inventory item.");
28259
+ }
28260
+ }
28261
+ async function getById(_id) {
28262
+ try {
28263
+ _id = new import_mongodb43.ObjectId(_id);
28264
+ } catch (error) {
28265
+ throw new import_nodejs_utils74.BadRequestError("Invalid ID.");
28266
+ }
28267
+ const cacheKey = (0, import_nodejs_utils74.makeCacheKey)(namespace_collection, { _id: String(_id) });
28268
+ const cachedData = await getCache(cacheKey);
28269
+ if (cachedData) {
28270
+ return cachedData;
28271
+ }
28272
+ try {
28273
+ const res = await collection.findOne({ _id });
28274
+ if (!res) {
28275
+ throw new import_nodejs_utils74.BadRequestError("Inventory item not found.");
28276
+ }
28277
+ setCache(cacheKey, res).then(() => {
28278
+ import_nodejs_utils74.logger.log({
28279
+ level: "info",
28280
+ message: `Cache set for inventory item by ID: ${cacheKey}`
28281
+ });
28282
+ }).catch((err) => {
28283
+ import_nodejs_utils74.logger.log({
28284
+ level: "error",
28285
+ message: `Failed to set cache for inventory item by ID: ${cacheKey} - ${err.message}`
28286
+ });
28287
+ });
28288
+ return res;
28289
+ } catch (error) {
28290
+ if (error instanceof import_nodejs_utils74.BadRequestError) {
28291
+ throw error;
28292
+ }
28293
+ throw new import_nodejs_utils74.BadRequestError("Failed to retrieve inventory item.");
28294
+ }
28295
+ }
28296
+ async function getAll({
28297
+ page = 1,
28298
+ search = "",
28299
+ limit = 20,
28300
+ status = "active",
28301
+ school = "",
28302
+ sort = { _id: -1 }
28303
+ } = {}) {
28304
+ page = page ? page - 1 : 0;
28305
+ try {
28306
+ school = new import_mongodb43.ObjectId(school);
28307
+ } catch (error) {
28308
+ throw new import_nodejs_utils74.BadRequestError("Invalid school ID.");
28309
+ }
28310
+ const query = {
28311
+ school,
28312
+ status
28313
+ };
28314
+ const cacheKeyOptions = {
28315
+ page,
28316
+ limit,
28317
+ status,
28318
+ school: String(school),
28319
+ sort: JSON.stringify(sort)
28320
+ };
28321
+ if (search) {
28322
+ query.$text = { $search: search };
28323
+ cacheKeyOptions.search = search;
28324
+ }
28325
+ try {
28326
+ const cacheKey = (0, import_nodejs_utils74.makeCacheKey)(namespace_collection, cacheKeyOptions);
28327
+ const cached = await getCache(cacheKey);
28328
+ if (cached) {
28329
+ import_nodejs_utils74.logger.log({
28330
+ level: "info",
28331
+ message: `Cache hit for getAll inventory items: ${cacheKey}`
28332
+ });
28333
+ return cached;
28334
+ }
28335
+ const items = await collection.aggregate([
28336
+ { $match: query },
28337
+ {
28338
+ $sort: sort
28339
+ },
28340
+ {
28341
+ $skip: page * limit
28342
+ },
28343
+ {
28344
+ $limit: limit
28345
+ }
28346
+ ]).toArray();
28347
+ const length = await collection.countDocuments(query);
28348
+ const data = (0, import_nodejs_utils74.paginate)(items, page, limit, length);
28349
+ setCache(cacheKey, data, 500).then(() => {
28350
+ import_nodejs_utils74.logger.log({
28351
+ level: "info",
28352
+ message: `Cache set for getAll inventory items: ${cacheKey}`
28353
+ });
28354
+ }).catch((err) => {
28355
+ import_nodejs_utils74.logger.log({
28356
+ level: "error",
28357
+ message: `Failed to set cache for getAll inventory items: ${err.message}`
28358
+ });
28359
+ });
28360
+ return data;
28361
+ } catch (error) {
28362
+ console.log("Error in getAll:", error);
28363
+ throw new import_nodejs_utils74.BadRequestError("Failed to retrieve inventory items.");
28364
+ }
28365
+ }
28366
+ return {
28367
+ createIndex,
28368
+ add,
28369
+ updateById,
28370
+ deleteById,
28371
+ getById,
28372
+ getAll
28373
+ };
28374
+ }
28375
+
28376
+ // src/controllers/inventory.controller.ts
28377
+ var import_nodejs_utils75 = require("@eeplatform/nodejs-utils");
28378
+ var import_joi37 = __toESM(require("joi"));
28379
+ function useInventoryController() {
28380
+ const {
28381
+ add: _add,
28382
+ getAll: _getAll,
28383
+ deleteById: _deleteById,
28384
+ updateById: _updateById
28385
+ } = useInventoryRepo();
28386
+ async function add(req, res, next) {
28387
+ const value = req.body;
28388
+ const { error } = schemaInventory.validate(value);
28389
+ if (error) {
28390
+ next(new import_nodejs_utils75.BadRequestError(error.message));
28391
+ return;
28392
+ }
28393
+ try {
28394
+ const id = await _add(value);
28395
+ res.json({ message: "Successfully added inventory item.", id });
28396
+ } catch (error2) {
28397
+ next(error2);
28398
+ }
28399
+ }
28400
+ async function getAll(req, res, next) {
28401
+ const query = req.query;
28402
+ const validation = import_joi37.default.object({
28403
+ page: import_joi37.default.number().min(1).optional().allow("", null),
28404
+ limit: import_joi37.default.number().min(1).optional().allow("", null),
28405
+ search: import_joi37.default.string().optional().allow("", null),
28406
+ status: import_joi37.default.string().optional().allow("", null),
28407
+ school: import_joi37.default.string().hex().optional().allow("", null)
28408
+ });
28409
+ const { error } = validation.validate(query);
28410
+ const page = typeof req.query.page === "string" ? Number(req.query.page) : 1;
28411
+ const limit = typeof req.query.limit === "string" ? Number(req.query.limit) : 10;
28412
+ const search = req.query.search ?? "";
28413
+ const status = req.query.status ?? "active";
28414
+ const school = req.query.school ?? "";
28415
+ const isPageNumber = isFinite(page);
28416
+ if (!isPageNumber) {
28417
+ next(new import_nodejs_utils75.BadRequestError("Invalid page number."));
28418
+ return;
28419
+ }
28420
+ const isLimitNumber = isFinite(limit);
28421
+ if (!isLimitNumber) {
28422
+ next(new import_nodejs_utils75.BadRequestError("Invalid limit number."));
28423
+ return;
28424
+ }
28425
+ if (error) {
28426
+ next(new import_nodejs_utils75.BadRequestError(error.message));
28427
+ return;
28428
+ }
28429
+ try {
28430
+ const regions = await _getAll({ page, limit, search, status, school });
28431
+ res.json(regions);
28432
+ return;
28433
+ } catch (error2) {
28434
+ next(error2);
28435
+ }
28436
+ }
28437
+ async function deleteById(req, res, next) {
28438
+ const id = req.params.id;
28439
+ const validation = import_joi37.default.string().hex().required();
28440
+ const { error } = validation.validate(id);
28441
+ if (error) {
28442
+ next(new import_nodejs_utils75.BadRequestError(error.message));
28443
+ return;
28444
+ }
28445
+ try {
28446
+ await _deleteById(id);
28447
+ res.json({ message: "Successfully deleted inventory item.", id });
28448
+ } catch (error2) {
28449
+ next(error2);
28450
+ }
28451
+ }
28452
+ async function updateById(req, res, next) {
28453
+ const id = req.params.id;
28454
+ const value = req.body;
28455
+ const { error } = schemaInventoryUpdateOption.validate(value);
28456
+ if (error) {
28457
+ next(new import_nodejs_utils75.BadRequestError(error.message));
28458
+ return;
28459
+ }
28460
+ try {
28461
+ await _updateById(id, value);
28462
+ res.json({ message: "Successfully updated inventory item.", id });
28463
+ } catch (error2) {
28464
+ next(error2);
28465
+ }
28466
+ }
28467
+ return {
28468
+ add,
28469
+ getAll,
28470
+ deleteById,
28471
+ updateById
28472
+ };
28473
+ }
28041
28474
  // Annotate the CommonJS export names for ESM import in node:
28042
28475
  0 && (module.exports = {
28043
28476
  ACCESS_TOKEN_EXPIRY,
@@ -28062,6 +28495,7 @@ function useBuildingUnitController() {
28062
28495
  MDivision,
28063
28496
  MEntity,
28064
28497
  MFile,
28498
+ MInventory,
28065
28499
  MMember,
28066
28500
  MONGO_DB,
28067
28501
  MONGO_URI,
@@ -28102,6 +28536,8 @@ function useBuildingUnitController() {
28102
28536
  schemaBuilding,
28103
28537
  schemaBuildingUnit,
28104
28538
  schemaDivision,
28539
+ schemaInventory,
28540
+ schemaInventoryUpdateOption,
28105
28541
  schemaRegion,
28106
28542
  schemaSchool,
28107
28543
  schemaUpdateOptions,
@@ -28123,6 +28559,8 @@ function useBuildingUnitController() {
28123
28559
  useFileController,
28124
28560
  useFileRepo,
28125
28561
  useFileService,
28562
+ useInventoryController,
28563
+ useInventoryRepo,
28126
28564
  useInvoiceController,
28127
28565
  useInvoiceModel,
28128
28566
  useInvoiceRepo,