@goweekdays/core 0.1.1 → 1.0.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/dist/index.js CHANGED
@@ -11414,6 +11414,7 @@ __export(src_exports, {
11414
11414
  usePaymentMethodService: () => usePaymentMethodService,
11415
11415
  usePaymentModel: () => usePaymentModel,
11416
11416
  usePaymentRepo: () => usePaymentRepo,
11417
+ usePaypalService: () => usePaypalService,
11417
11418
  usePriceController: () => usePriceController,
11418
11419
  usePriceModel: () => usePriceModel,
11419
11420
  usePriceRepo: () => usePriceRepo,
@@ -18078,21 +18079,20 @@ function useRoleController() {
18078
18079
  } = useRoleService();
18079
18080
  const { updatePermissionsById: _updatePermissionsById } = useRoleRepo();
18080
18081
  async function createRole(req, res, next) {
18081
- const name = req.body.name ?? "";
18082
- const permissions = req.body.permissions ?? [];
18083
- const type = req.body.type ?? "";
18082
+ const payload = req.body;
18084
18083
  const validation = import_joi7.default.object({
18085
18084
  name: import_joi7.default.string().required(),
18086
18085
  permissions: import_joi7.default.array().items(import_joi7.default.string()).required(),
18087
- type: import_joi7.default.string().optional().allow("", null)
18086
+ type: import_joi7.default.string().optional().allow("", null),
18087
+ org: import_joi7.default.string().hex().optional().allow("", null)
18088
18088
  });
18089
- const { error } = validation.validate({ name, permissions, type });
18089
+ const { error } = validation.validate(payload);
18090
18090
  if (error) {
18091
18091
  next(new import_utils44.BadRequestError(error.message));
18092
18092
  return;
18093
18093
  }
18094
18094
  try {
18095
- const role = await _createRole({ name, permissions, type });
18095
+ const role = await _createRole(payload);
18096
18096
  res.json({ message: "Successfully created role.", data: { role } });
18097
18097
  return;
18098
18098
  } catch (error2) {
@@ -20361,7 +20361,7 @@ function useSubscriptionRepo() {
20361
20361
  }
20362
20362
 
20363
20363
  // src/services/subscription.service.ts
20364
- var import_utils69 = require("@goweekdays/utils");
20364
+ var import_utils70 = require("@goweekdays/utils");
20365
20365
 
20366
20366
  // src/repositories/organization.repository.ts
20367
20367
  var import_utils57 = require("@goweekdays/utils");
@@ -20471,7 +20471,7 @@ function useOrgRepo() {
20471
20471
  }
20472
20472
  }
20473
20473
  }
20474
- async function getOrgs({
20474
+ async function getAll({
20475
20475
  search = "",
20476
20476
  page = 1,
20477
20477
  limit = 10,
@@ -20587,7 +20587,7 @@ function useOrgRepo() {
20587
20587
  createTextIndex,
20588
20588
  createUniqueIndex,
20589
20589
  add,
20590
- getOrgs,
20590
+ getAll,
20591
20591
  getById,
20592
20592
  updateFieldById,
20593
20593
  deleteById,
@@ -21075,8 +21075,14 @@ function useInvoiceRepo() {
21075
21075
  );
21076
21076
  }
21077
21077
  }
21078
- async function getByDueDate(dueDate, status) {
21078
+ async function getByDueDate(id, dueDate, status) {
21079
+ try {
21080
+ id = new import_mongodb31.ObjectId(id);
21081
+ } catch (error) {
21082
+ throw new import_utils63.BadRequestError("Invalid ID.");
21083
+ }
21079
21084
  const query = {
21085
+ "metadata.orgId": id,
21080
21086
  dueDate
21081
21087
  };
21082
21088
  if (status) {
@@ -21509,6 +21515,160 @@ function usePriceRepo() {
21509
21515
  };
21510
21516
  }
21511
21517
 
21518
+ // src/services/paypal.service.ts
21519
+ var import_utils69 = require("@goweekdays/utils");
21520
+ function usePaypalService() {
21521
+ async function getAccessToken() {
21522
+ try {
21523
+ const res = await axios_default.post(
21524
+ `${PAYPAL_API_URL}/v1/oauth2/token`,
21525
+ "grant_type=client_credentials",
21526
+ {
21527
+ auth: {
21528
+ username: PAYPAL_CLIENT_ID,
21529
+ password: PAYPAL_CLIENT_SECRET
21530
+ },
21531
+ headers: { "Content-Type": "application/x-www-form-urlencoded" }
21532
+ }
21533
+ );
21534
+ return res.data.access_token;
21535
+ } catch (error) {
21536
+ throw new import_utils69.BadRequestError(
21537
+ "Failed to get PayPal access token. Please check your credentials and try again. " + String(error)
21538
+ );
21539
+ }
21540
+ }
21541
+ async function createInvoice(data) {
21542
+ const invoicePayload = {
21543
+ detail: {
21544
+ invoice_number: data.invoiceNumber ?? `GW-${Date.now()}`,
21545
+ invoice_date: data.invoiceDate || (/* @__PURE__ */ new Date()).toISOString().split("T")[0],
21546
+ payment_term: {
21547
+ due_date: data.invoiceDueDate ?? new Date(Date.now() + 7 * 24 * 60 * 60 * 1e3).toISOString().split("T")[0]
21548
+ },
21549
+ currency_code: data.currency,
21550
+ note: "Please pay within 7 day to avoid organization subscription will be suspension."
21551
+ },
21552
+ invoicer: {
21553
+ name: {
21554
+ full_name: data.customerName
21555
+ },
21556
+ website: "www.goweekdays.com"
21557
+ },
21558
+ primary_recipients: [
21559
+ {
21560
+ billing_info: {
21561
+ name: {
21562
+ full_name: data.customerName || "GoWeekdays Customer"
21563
+ },
21564
+ email_address: data.customerEmail
21565
+ }
21566
+ }
21567
+ ],
21568
+ items: data.items?.length ? data.items.map((i) => {
21569
+ return {
21570
+ name: "Per Seat Charge",
21571
+ description: "Monthly subscription fee per user",
21572
+ quantity: i.quantity,
21573
+ unit_amount: {
21574
+ currency_code: data.currency,
21575
+ value: (i.unitPrice * i.quantity).toFixed(2)
21576
+ },
21577
+ unit_of_measure: "QUANTITY"
21578
+ };
21579
+ }) : [
21580
+ {
21581
+ name: "Per Seat Charge",
21582
+ description: "Monthly subscription fee per user",
21583
+ quantity: data.quantity,
21584
+ unit_amount: {
21585
+ currency_code: data.currency,
21586
+ value: (data.ratePerSeat * data.quantity).toFixed(2)
21587
+ },
21588
+ unit_of_measure: "QUANTITY"
21589
+ }
21590
+ ],
21591
+ configuration: {
21592
+ allow_tip: true,
21593
+ tax_calculated_after_discount: true,
21594
+ tax_inclusive: false
21595
+ },
21596
+ amount: {
21597
+ breakdown: {
21598
+ total_amount: {
21599
+ label: "Total seats charge",
21600
+ amount: {
21601
+ currency_code: data.currency,
21602
+ value: (data.ratePerSeat * data.quantity).toFixed(2)
21603
+ }
21604
+ }
21605
+ }
21606
+ }
21607
+ };
21608
+ try {
21609
+ const accessToken = await getAccessToken();
21610
+ const createDraft = await axios_default.post(
21611
+ `${PAYPAL_API_URL}/v2/invoicing/invoices`,
21612
+ invoicePayload,
21613
+ {
21614
+ headers: {
21615
+ Authorization: `Bearer ${accessToken}`,
21616
+ "Content-Type": "application/json"
21617
+ }
21618
+ }
21619
+ );
21620
+ const invoiceDraft = createDraft.data.href ?? "";
21621
+ const invoiceId = invoiceDraft.split("/").pop() ?? "";
21622
+ await axios_default.post(
21623
+ `${PAYPAL_API_URL}/v2/invoicing/invoices/${invoiceId}/send`,
21624
+ {
21625
+ subject: "GoWeekdays Monthly Invoice",
21626
+ send_to_recipient: true,
21627
+ send_to_invoicer: false
21628
+ },
21629
+ {
21630
+ headers: {
21631
+ Authorization: `Bearer ${accessToken}`,
21632
+ "Content-Type": "application/json"
21633
+ }
21634
+ }
21635
+ );
21636
+ return invoiceId;
21637
+ } catch (error) {
21638
+ console.error(
21639
+ "Error creating and sending PayPal invoice:",
21640
+ error.response.data.details
21641
+ );
21642
+ throw new import_utils69.BadRequestError(
21643
+ "Failed to create and send invoice. Please try again later. " + String(error)
21644
+ );
21645
+ }
21646
+ }
21647
+ async function getInvoiceById(invoiceId) {
21648
+ try {
21649
+ const accessToken = await getAccessToken();
21650
+ const response = await axios_default.get(
21651
+ `${PAYPAL_API_URL}/v2/invoicing/invoices/${invoiceId}`,
21652
+ {
21653
+ headers: {
21654
+ Authorization: `Bearer ${accessToken}`,
21655
+ "Content-Type": "application/json"
21656
+ }
21657
+ }
21658
+ );
21659
+ return response.data;
21660
+ } catch (error) {
21661
+ throw new import_utils69.BadRequestError(
21662
+ "Failed to retrieve invoice. Please check the invoice ID and try again. " + String(error)
21663
+ );
21664
+ }
21665
+ }
21666
+ return {
21667
+ createInvoice,
21668
+ getInvoiceById
21669
+ };
21670
+ }
21671
+
21512
21672
  // src/services/subscription.service.ts
21513
21673
  function useSubscriptionService() {
21514
21674
  const {
@@ -21520,7 +21680,8 @@ function useSubscriptionService() {
21520
21680
  markSubscriptionAsFailed,
21521
21681
  updateSeatsById: _updateSeatsById,
21522
21682
  getById: _getById,
21523
- updateMaxSeatsById
21683
+ updateMaxSeatsById,
21684
+ updateStatusById: _updateStatusById
21524
21685
  } = useSubscriptionRepo();
21525
21686
  const { getUserById: _getUserByUserId, updateUserFieldById } = useUserRepo();
21526
21687
  const {
@@ -21531,7 +21692,7 @@ function useSubscriptionService() {
21531
21692
  getPaymentMethodById,
21532
21693
  createCustomer
21533
21694
  } = useXenditService();
21534
- const { add: addOrg } = useOrgRepo();
21695
+ const { add: addOrg, getById: getOrgById } = useOrgRepo();
21535
21696
  const { add: addAddress } = useAddressRepo();
21536
21697
  const { addRole } = useRoleRepo();
21537
21698
  const { add: addMember, countByOrg } = useMemberRepo();
@@ -21576,12 +21737,12 @@ function useSubscriptionService() {
21576
21737
  };
21577
21738
  }
21578
21739
  async function subscribe(value) {
21579
- const session = import_utils69.useAtlas.getClient()?.startSession();
21740
+ const session = import_utils70.useAtlas.getClient()?.startSession();
21580
21741
  session?.startTransaction();
21581
21742
  try {
21582
21743
  const _user = await _getUserByUserId(value.user);
21583
21744
  if (!_user) {
21584
- throw new import_utils69.BadRequestError("User not found.");
21745
+ throw new import_utils70.BadRequestError("User not found.");
21585
21746
  }
21586
21747
  const orgId = await addOrg(value.org, session);
21587
21748
  const role = await addRole(
@@ -21616,18 +21777,12 @@ function useSubscriptionService() {
21616
21777
  );
21617
21778
  }
21618
21779
  const description = "GoWeekdays Organization Monthly Subscription.";
21619
- if (value.promoCode) {
21620
- await assignByUserId(
21621
- { user: value.user, code: value.promoCode },
21622
- session
21623
- );
21624
- }
21625
21780
  const monthlySubscriptionPrice = await getByNameType(
21626
21781
  "organization-subscription",
21627
21782
  "monthly-subscription"
21628
21783
  );
21629
21784
  if (!monthlySubscriptionPrice) {
21630
- throw new import_utils69.BadRequestError(
21785
+ throw new import_utils70.BadRequestError(
21631
21786
  "Failed to fetch monthly subscription price."
21632
21787
  );
21633
21788
  }
@@ -21636,7 +21791,12 @@ function useSubscriptionService() {
21636
21791
  if (value.promoCode) {
21637
21792
  const promoCode = await getByCode(value.promoCode);
21638
21793
  if (!promoCode) {
21639
- throw new import_utils69.BadRequestError("Promo code not found.");
21794
+ throw new import_utils70.BadRequestError("Promo code not found.");
21795
+ }
21796
+ if (promoCode.assignedTo) {
21797
+ throw new import_utils70.BadRequestError(
21798
+ "Promo code already assigned to another user."
21799
+ );
21640
21800
  }
21641
21801
  if (promoCode && promoCode.type === "fixed" && promoCode.fixed_rate !== void 0 && promoCode.fixed_rate >= 0) {
21642
21802
  amount = promoCode.fixed_rate;
@@ -21677,7 +21837,7 @@ function useSubscriptionService() {
21677
21837
  );
21678
21838
  const invoiceCounter = await getByType("invoice");
21679
21839
  if (!invoiceCounter) {
21680
- throw new import_utils69.BadRequestError("Failed to fetch invoice counter.");
21840
+ throw new import_utils70.BadRequestError("Failed to fetch invoice counter.");
21681
21841
  }
21682
21842
  const date = /* @__PURE__ */ new Date();
21683
21843
  const mm = String(date.getMonth() + 1).padStart(2, "0");
@@ -21726,6 +21886,12 @@ function useSubscriptionService() {
21726
21886
  },
21727
21887
  session
21728
21888
  );
21889
+ if (value.promoCode) {
21890
+ await assignByUserId(
21891
+ { user: value.user, code: value.promoCode },
21892
+ session
21893
+ );
21894
+ }
21729
21895
  await session?.commitTransaction();
21730
21896
  return {
21731
21897
  message: "Subscription created successfully.",
@@ -21739,12 +21905,12 @@ function useSubscriptionService() {
21739
21905
  }
21740
21906
  }
21741
21907
  async function createOrgSubscription(value) {
21742
- const session = import_utils69.useAtlas.getClient()?.startSession();
21908
+ const session = import_utils70.useAtlas.getClient()?.startSession();
21743
21909
  session?.startTransaction();
21744
21910
  try {
21745
21911
  const _user = await _getUserByUserId(value.user);
21746
21912
  if (!_user) {
21747
- throw new import_utils69.BadRequestError("User not found.");
21913
+ throw new import_utils70.BadRequestError("User not found.");
21748
21914
  }
21749
21915
  const orgId = await addOrg(value.organization, session);
21750
21916
  const customerData = {
@@ -21765,7 +21931,7 @@ function useSubscriptionService() {
21765
21931
  }
21766
21932
  const { id: customerId } = await createCustomer(customerData);
21767
21933
  if (!customerId) {
21768
- throw new import_utils69.BadRequestError("Failed to create customer.");
21934
+ throw new import_utils70.BadRequestError("Failed to create customer.");
21769
21935
  }
21770
21936
  const role = await addRole(
21771
21937
  {
@@ -21800,7 +21966,7 @@ function useSubscriptionService() {
21800
21966
  }
21801
21967
  const customer = await getCustomerById(customerId);
21802
21968
  if (!customer.id) {
21803
- throw new import_utils69.BadRequestError("Xendit customer account required.");
21969
+ throw new import_utils70.BadRequestError("Xendit customer account required.");
21804
21970
  }
21805
21971
  value.billingAddress.org = orgId.toString();
21806
21972
  await addAddress(value.billingAddress, session);
@@ -21816,7 +21982,7 @@ function useSubscriptionService() {
21816
21982
  "monthly-subscription"
21817
21983
  );
21818
21984
  if (!monthlySubscriptionPrice) {
21819
- throw new import_utils69.BadRequestError(
21985
+ throw new import_utils70.BadRequestError(
21820
21986
  "Failed to fetch monthly subscription price."
21821
21987
  );
21822
21988
  }
@@ -21825,7 +21991,7 @@ function useSubscriptionService() {
21825
21991
  if (value.promoCode) {
21826
21992
  const promoCode = await getByCode(value.promoCode);
21827
21993
  if (!promoCode) {
21828
- throw new import_utils69.BadRequestError("Promo code not found.");
21994
+ throw new import_utils70.BadRequestError("Promo code not found.");
21829
21995
  }
21830
21996
  if (promoCode && promoCode.type === "fixed" && promoCode.fixed_rate !== void 0 && promoCode.fixed_rate >= 0) {
21831
21997
  amount = promoCode.fixed_rate;
@@ -21868,7 +22034,7 @@ function useSubscriptionService() {
21868
22034
  );
21869
22035
  const invoiceCounter = await getByType("invoice");
21870
22036
  if (!invoiceCounter) {
21871
- throw new import_utils69.BadRequestError("Failed to fetch invoice counter.");
22037
+ throw new import_utils70.BadRequestError("Failed to fetch invoice counter.");
21872
22038
  }
21873
22039
  const date = /* @__PURE__ */ new Date();
21874
22040
  const mm = String(date.getMonth() + 1).padStart(2, "0");
@@ -21942,25 +22108,25 @@ function useSubscriptionService() {
21942
22108
  }
21943
22109
  }
21944
22110
  async function createAffiliateSubscription(value) {
21945
- const session = import_utils69.useAtlas.getClient()?.startSession();
22111
+ const session = import_utils70.useAtlas.getClient()?.startSession();
21946
22112
  session?.startTransaction();
21947
22113
  try {
21948
22114
  const _user = await _getUserByUserId(value.user);
21949
22115
  if (!_user) {
21950
- throw new import_utils69.BadRequestError("User not found.");
22116
+ throw new import_utils70.BadRequestError("User not found.");
21951
22117
  }
21952
22118
  await addAddress(value.billingAddress, session);
21953
22119
  const description = "GoWeekdays affiliate yearly Subscription.";
21954
22120
  const customer = await getCustomerById(value.customer_id);
21955
22121
  if (!customer.id) {
21956
- throw new import_utils69.BadRequestError("Xendit customer account required.");
22122
+ throw new import_utils70.BadRequestError("Xendit customer account required.");
21957
22123
  }
21958
22124
  const affiliateSubscriptionPrice = await getByNameType(
21959
22125
  "affiliate-subscription",
21960
22126
  "yearly-subscription"
21961
22127
  );
21962
22128
  if (!affiliateSubscriptionPrice) {
21963
- throw new import_utils69.BadRequestError(
22129
+ throw new import_utils70.BadRequestError(
21964
22130
  "Failed to fetch affiliate subscription price."
21965
22131
  );
21966
22132
  }
@@ -21972,7 +22138,7 @@ function useSubscriptionService() {
21972
22138
  if (value.promoCode) {
21973
22139
  const promoCode = await getByCode(value.promoCode);
21974
22140
  if (!promoCode) {
21975
- throw new import_utils69.BadRequestError("Promo code not found.");
22141
+ throw new import_utils70.BadRequestError("Promo code not found.");
21976
22142
  }
21977
22143
  if (promoCode && promoCode.type === "fixed" && promoCode.fixed_rate !== void 0 && promoCode.fixed_rate >= 0) {
21978
22144
  amount = promoCode.fixed_rate;
@@ -22004,7 +22170,7 @@ function useSubscriptionService() {
22004
22170
  );
22005
22171
  const invoiceCounter = await getByType("invoice");
22006
22172
  if (!invoiceCounter) {
22007
- throw new import_utils69.BadRequestError("Failed to fetch invoice counter.");
22173
+ throw new import_utils70.BadRequestError("Failed to fetch invoice counter.");
22008
22174
  }
22009
22175
  const date = /* @__PURE__ */ new Date();
22010
22176
  const mm = String(date.getMonth() + 1).padStart(2, "0");
@@ -22076,7 +22242,7 @@ function useSubscriptionService() {
22076
22242
  try {
22077
22243
  const subscription = await _getByUserId(id);
22078
22244
  if (!subscription) {
22079
- throw new import_utils69.BadRequestError("Subscription not found.");
22245
+ throw new import_utils70.BadRequestError("Subscription not found.");
22080
22246
  }
22081
22247
  const customerSubscription = await getSubscription(id);
22082
22248
  return customerSubscription;
@@ -22092,14 +22258,15 @@ function useSubscriptionService() {
22092
22258
  );
22093
22259
  return status;
22094
22260
  } catch (error) {
22095
- throw new import_utils69.BadRequestError("Failed to fetch subscription status");
22261
+ throw new import_utils70.BadRequestError("Failed to fetch subscription status");
22096
22262
  }
22097
22263
  }
22264
+ const { createInvoice } = usePaypalService();
22098
22265
  async function processSubscriptions(batchSize = 100, maxRetries = 7) {
22099
22266
  while (true) {
22100
22267
  const subscriptions = await getDueSubscriptions(batchSize);
22101
22268
  if (subscriptions.length === 0) {
22102
- import_utils69.logger.log({
22269
+ import_utils70.logger.log({
22103
22270
  level: "info",
22104
22271
  message: "No more subscriptions to process."
22105
22272
  });
@@ -22107,10 +22274,10 @@ function useSubscriptionService() {
22107
22274
  }
22108
22275
  await Promise.allSettled(
22109
22276
  subscriptions.map(async (sub) => {
22110
- const session = import_utils69.useAtlas.getClient()?.startSession();
22277
+ const session = import_utils70.useAtlas.getClient()?.startSession();
22111
22278
  try {
22112
22279
  if (!sub._id) {
22113
- throw new import_utils69.BadRequestError("Subscription ID not found.");
22280
+ throw new import_utils70.BadRequestError("Subscription ID not found.");
22114
22281
  }
22115
22282
  sub.maxSeats = sub.maxSeats ?? 0;
22116
22283
  sub.paidSeats = sub.paidSeats ?? 0;
@@ -22121,14 +22288,14 @@ function useSubscriptionService() {
22121
22288
  `${sub.billingCycle}-subscription`
22122
22289
  );
22123
22290
  if (!price) {
22124
- throw new import_utils69.BadRequestError("Failed to fetch subscription price.");
22291
+ throw new import_utils70.BadRequestError("Failed to fetch subscription price.");
22125
22292
  }
22126
22293
  const promoCode = await getByCode(code).catch(() => null);
22127
22294
  let amount = price.value * chargeableSeats;
22128
22295
  const description = `GoWeekdays ${sub.type} ${sub.billingCycle} Subscription`;
22129
22296
  const items = [];
22130
- if (code && promoCode && promoCode.type === "fixed") {
22131
- amount = amount * chargeableSeats;
22297
+ if (code && promoCode && promoCode.type === "fixed" && promoCode.fixed_rate !== void 0 && promoCode.fixed_rate >= 0) {
22298
+ amount = promoCode.fixed_rate * chargeableSeats;
22132
22299
  items.push({
22133
22300
  description,
22134
22301
  unitPrice: amount,
@@ -22146,12 +22313,15 @@ function useSubscriptionService() {
22146
22313
  amount = computedTieredInvoice.totalCost;
22147
22314
  }
22148
22315
  if (!sub.nextBillingDate) {
22149
- throw new import_utils69.BadRequestError("Next billing date not found.");
22316
+ throw new import_utils70.BadRequestError("Next billing date not found.");
22150
22317
  }
22151
- const invoice = await getByDueDate(sub.nextBillingDate);
22318
+ const invoice = await getByDueDate(
22319
+ sub._id.toString(),
22320
+ sub.nextBillingDate
22321
+ );
22152
22322
  const invoiceCounter = await getByType("invoice");
22153
22323
  if (!invoiceCounter) {
22154
- throw new import_utils69.BadRequestError("Failed to fetch invoice counter.");
22324
+ throw new import_utils70.BadRequestError("Failed to fetch invoice counter.");
22155
22325
  }
22156
22326
  const date = /* @__PURE__ */ new Date();
22157
22327
  const mm = String(date.getMonth() + 1).padStart(2, "0");
@@ -22159,7 +22329,29 @@ function useSubscriptionService() {
22159
22329
  const yyyy = date.getFullYear();
22160
22330
  const formattedDate = `${mm}-${dd}-${yyyy}`;
22161
22331
  const invoiceNumber = `inv-${formattedDate}-${invoiceCounter.count + 1}`;
22162
- if (!invoice) {
22332
+ if (!invoice && amount > 0) {
22333
+ let customerEmail = "";
22334
+ let customerName = "";
22335
+ if (sub.type === "organization" && sub.org) {
22336
+ const orgData = await getOrgById(sub.org.toString());
22337
+ customerEmail = orgData.email ?? "";
22338
+ customerName = orgData.name ?? "";
22339
+ }
22340
+ if (sub.type === "affiliate" && sub.user) {
22341
+ const userData = await _getUserByUserId(sub.user.toString());
22342
+ customerEmail = userData?.email ?? "";
22343
+ customerName = `${userData?.firstName} ${userData?.lastName}`;
22344
+ }
22345
+ const paypalInvoice = await createInvoice({
22346
+ invoiceNumber,
22347
+ invoiceDate: (/* @__PURE__ */ new Date()).toISOString().split("T")[0],
22348
+ customerEmail,
22349
+ customerName,
22350
+ quantity: chargeableSeats,
22351
+ ratePerSeat: price.value,
22352
+ currency: sub.currency,
22353
+ items
22354
+ });
22163
22355
  const invoiceData = {
22164
22356
  type: `${sub.type}-subscription`,
22165
22357
  invoiceNumber,
@@ -22171,7 +22363,8 @@ function useSubscriptionService() {
22171
22363
  currency: sub.currency,
22172
22364
  subscriptionId: sub._id.toString(),
22173
22365
  billingCycle: sub.billingCycle,
22174
- description
22366
+ description,
22367
+ transactionId: paypalInvoice
22175
22368
  },
22176
22369
  status: "pending",
22177
22370
  items: items.length ? items : [
@@ -22193,51 +22386,10 @@ function useSubscriptionService() {
22193
22386
  session?.startTransaction();
22194
22387
  await addInvoice(invoiceData, session);
22195
22388
  await incrementByType("invoice", session);
22389
+ await _updateStatusById(sub._id.toString(), "due", session);
22196
22390
  await session?.commitTransaction();
22197
22391
  }
22198
- session?.startTransaction();
22199
- try {
22200
- const payment = await pay({
22201
- customer_id: sub.customerId ?? "",
22202
- payment_method_id: sub.paymentMethodId ?? "",
22203
- amount: sub.amount,
22204
- currency: sub.currency,
22205
- description
22206
- });
22207
- if (!payment.id) {
22208
- throw new import_utils69.BadRequestError("Failed to process payment.");
22209
- }
22210
- const customerPaymentMethod = await getPaymentMethodById(
22211
- sub.paymentMethodId ?? ""
22212
- );
22213
- const paymentData = {
22214
- invoiceId: invoiceNumber,
22215
- amount,
22216
- paymentMethod: customerPaymentMethod.type,
22217
- status: "completed",
22218
- metadata: {
22219
- userId: String(sub.user || ""),
22220
- orgId: String(sub.org || ""),
22221
- currency: sub.currency,
22222
- paymentMethod: customerPaymentMethod.ewallet.channel_code,
22223
- paymentMethodType: customerPaymentMethod.type,
22224
- paymentMethodId: sub.paymentMethodId,
22225
- payment: payment.id,
22226
- subscriptionId: sub._id.toString()
22227
- }
22228
- };
22229
- if (!paymentData.metadata.userId) {
22230
- delete paymentData.metadata.userId;
22231
- }
22232
- if (!paymentData.metadata.orgId) {
22233
- delete paymentData.metadata.orgId;
22234
- }
22235
- await addPayment(paymentData, session);
22236
- await updateStatusByInvoiceNumber(
22237
- invoice ? invoice.invoiceNumber : invoiceNumber,
22238
- "paid",
22239
- session
22240
- );
22392
+ if (!invoice && amount <= 0) {
22241
22393
  await processSuccessfulPayment(
22242
22394
  {
22243
22395
  _id: sub._id.toString(),
@@ -22253,34 +22405,27 @@ function useSubscriptionService() {
22253
22405
  session
22254
22406
  );
22255
22407
  await session?.commitTransaction();
22256
- import_utils69.logger.log({
22257
- level: "info",
22258
- message: `Processed subscription ${sub._id} successfully.`
22259
- });
22260
- } catch (error) {
22261
- import_utils69.logger.log({
22262
- level: "error",
22263
- message: `Failed to process ${sub._id}: ${error}`
22264
- });
22265
- await markSubscriptionAsFailed({
22266
- _id: String(sub._id),
22267
- failed: sub.lastPaymentStatus === "success"
22268
- });
22269
- await session?.abortTransaction();
22270
- throw error;
22271
22408
  }
22409
+ import_utils70.logger.log({
22410
+ level: "info",
22411
+ message: `Processed subscription ${sub._id} successfully.`
22412
+ });
22413
+ return;
22272
22414
  } catch (error) {
22273
22415
  await session?.abortTransaction();
22274
- import_utils69.logger.log({
22416
+ import_utils70.logger.log({
22275
22417
  level: "error",
22276
22418
  message: `Failed to process ${sub._id}: ${error}`
22277
22419
  });
22420
+ throw new Error(
22421
+ `Failed to process subscription ${sub._id}: ${error}`
22422
+ );
22278
22423
  } finally {
22279
22424
  session?.endSession();
22280
22425
  }
22281
22426
  })
22282
22427
  );
22283
- import_utils69.logger.log({
22428
+ import_utils70.logger.log({
22284
22429
  level: "info",
22285
22430
  message: "Processed a batch of subscriptions."
22286
22431
  });
@@ -22305,7 +22450,7 @@ function useSubscriptionService() {
22305
22450
  });
22306
22451
  const { error } = validation.validate({ amount });
22307
22452
  if (error) {
22308
- throw new import_utils69.BadRequestError(error.message);
22453
+ throw new import_utils70.BadRequestError(error.message);
22309
22454
  }
22310
22455
  return Number(amount.toFixed(2));
22311
22456
  }
@@ -22315,7 +22460,7 @@ function useSubscriptionService() {
22315
22460
  let perSeatPrice = price.value;
22316
22461
  let items = [];
22317
22462
  if (!subscription.nextBillingDate) {
22318
- throw new import_utils69.BadRequestError("Next billing date not found.");
22463
+ throw new import_utils70.BadRequestError("Next billing date not found.");
22319
22464
  }
22320
22465
  if (promoCode) {
22321
22466
  if (promoCode.type === "fixed" && promoCode.fixed_rate !== void 0 && promoCode.fixed_rate >= 0) {
@@ -22350,7 +22495,7 @@ function useSubscriptionService() {
22350
22495
  }
22351
22496
  function calculateProration(billingDate) {
22352
22497
  if (!billingDate) {
22353
- throw new import_utils69.BadRequestError("Billing date is required.");
22498
+ throw new import_utils70.BadRequestError("Billing date is required.");
22354
22499
  }
22355
22500
  const nextBillingDate = billingDate;
22356
22501
  const totalDaysInMonth = new Date(
@@ -22368,7 +22513,7 @@ function useSubscriptionService() {
22368
22513
  try {
22369
22514
  const invoiceCounter = await getByType("invoice");
22370
22515
  if (!invoiceCounter) {
22371
- throw new import_utils69.BadRequestError("Failed to fetch invoice counter.");
22516
+ throw new import_utils70.BadRequestError("Failed to fetch invoice counter.");
22372
22517
  }
22373
22518
  const date = /* @__PURE__ */ new Date();
22374
22519
  const mm = String(date.getMonth() + 1).padStart(2, "0");
@@ -22388,28 +22533,32 @@ function useSubscriptionService() {
22388
22533
  });
22389
22534
  const { error } = schema3.validate(value);
22390
22535
  if (error) {
22391
- throw new import_utils69.BadRequestError(error.message);
22536
+ throw new import_utils70.BadRequestError(error.message);
22392
22537
  }
22393
- const session = import_utils69.useAtlas.getClient()?.startSession();
22538
+ const session = import_utils70.useAtlas.getClient()?.startSession();
22394
22539
  try {
22395
22540
  session?.startTransaction();
22396
22541
  const subscription = await _getById(value.subscriptionId);
22397
22542
  if (!subscription) {
22398
- throw new import_utils69.BadRequestError("Subscription not found.");
22543
+ throw new import_utils70.BadRequestError("Subscription not found.");
22544
+ }
22545
+ if (!subscription._id) {
22546
+ throw new import_utils70.BadRequestError("Invalid subscription.");
22399
22547
  }
22400
22548
  if (!subscription.nextBillingDate) {
22401
- throw new import_utils69.BadRequestError("Next billing date not found.");
22549
+ throw new import_utils70.BadRequestError("Next billing date not found.");
22402
22550
  }
22403
22551
  if (!subscription.org) {
22404
- throw new import_utils69.BadRequestError("Organization not found.");
22552
+ throw new import_utils70.BadRequestError("Organization not found.");
22405
22553
  }
22406
22554
  const members = await countByOrg(`${subscription.org}`);
22407
22555
  if (!members) {
22408
- throw new import_utils69.BadRequestError("Failed to fetch members.");
22556
+ throw new import_utils70.BadRequestError("Failed to fetch members.");
22409
22557
  }
22410
22558
  let paidSeats = subscription.paidSeats ?? 0;
22411
22559
  let seats = paidSeats > value.seats ? 0 : value.seats - paidSeats;
22412
22560
  const dueInvoice = await getByDueDate(
22561
+ subscription._id.toString(),
22413
22562
  subscription.nextBillingDate,
22414
22563
  "pending"
22415
22564
  );
@@ -22421,7 +22570,7 @@ function useSubscriptionService() {
22421
22570
  seats = value.seats;
22422
22571
  }
22423
22572
  if (seats === 0 && members > value.seats) {
22424
- throw new import_utils69.BadRequestError(
22573
+ throw new import_utils70.BadRequestError(
22425
22574
  "Cannot reduce seats to less than the number of members. Please remove members before reducing seats."
22426
22575
  );
22427
22576
  }
@@ -22430,7 +22579,7 @@ function useSubscriptionService() {
22430
22579
  "monthly-subscription"
22431
22580
  );
22432
22581
  if (!monthlySubscriptionPrice) {
22433
- throw new import_utils69.BadRequestError(
22582
+ throw new import_utils70.BadRequestError(
22434
22583
  "Failed to fetch monthly subscription price."
22435
22584
  );
22436
22585
  }
@@ -22511,7 +22660,7 @@ function useSubscriptionService() {
22511
22660
  subscription.paymentMethodId ?? ""
22512
22661
  );
22513
22662
  if (!paymentMethod) {
22514
- throw new import_utils69.BadRequestError("Payment method not found.");
22663
+ throw new import_utils70.BadRequestError("Payment method not found.");
22515
22664
  }
22516
22665
  const paymentMetadata = {
22517
22666
  userId: String(subscription.user),
@@ -22573,14 +22722,215 @@ function useSubscriptionService() {
22573
22722
  await session?.commitTransaction();
22574
22723
  } catch (error2) {
22575
22724
  await session?.abortTransaction();
22576
- import_utils69.logger.log({
22725
+ import_utils70.logger.log({
22726
+ level: "error",
22727
+ message: `Failed to update subscription seats: ${error2}`
22728
+ });
22729
+ if (error2 instanceof import_utils70.AppError) {
22730
+ throw error2;
22731
+ }
22732
+ throw new import_utils70.BadRequestError("Failed to update subscription seats.");
22733
+ } finally {
22734
+ session?.endSession();
22735
+ }
22736
+ }
22737
+ async function updateSubscriptionSeats(value) {
22738
+ const schema3 = import_joi18.default.object({
22739
+ transactionId: import_joi18.default.string().optional().allow("", null),
22740
+ subscriptionId: import_joi18.default.string().hex().required(),
22741
+ seats: import_joi18.default.number().min(1).required(),
22742
+ amount: import_joi18.default.number().required()
22743
+ });
22744
+ const { error } = schema3.validate(value);
22745
+ if (error) {
22746
+ throw new import_utils70.BadRequestError(error.message);
22747
+ }
22748
+ const session = import_utils70.useAtlas.getClient()?.startSession();
22749
+ try {
22750
+ session?.startTransaction();
22751
+ const subscription = await _getById(value.subscriptionId);
22752
+ if (!subscription) {
22753
+ throw new import_utils70.BadRequestError("Subscription not found.");
22754
+ }
22755
+ if (!subscription._id) {
22756
+ throw new import_utils70.BadRequestError("Invalid subscription.");
22757
+ }
22758
+ if (!subscription.nextBillingDate) {
22759
+ throw new import_utils70.BadRequestError("Next billing date not found.");
22760
+ }
22761
+ if (!subscription.org) {
22762
+ throw new import_utils70.BadRequestError("Organization not found.");
22763
+ }
22764
+ const members = await countByOrg(`${subscription.org}`);
22765
+ if (!members) {
22766
+ throw new import_utils70.BadRequestError("Failed to fetch members.");
22767
+ }
22768
+ let paidSeats = subscription.paidSeats ?? 0;
22769
+ let seats = paidSeats > value.seats ? 0 : value.seats - paidSeats;
22770
+ const dueInvoice = await getByDueDate(
22771
+ subscription._id.toString(),
22772
+ subscription.nextBillingDate,
22773
+ "pending"
22774
+ );
22775
+ const currentBillingDate = new Date(subscription?.nextBillingDate);
22776
+ const isCancelledManually = !dueInvoice && subscription.status === "cancelled" && subscription.failedAttempts === 0 && (/* @__PURE__ */ new Date()).getTime() > currentBillingDate.getTime();
22777
+ const activeWithOverdueInvoice = dueInvoice && subscription.status === "active" && subscription.failedAttempts && subscription.failedAttempts > 0 && (/* @__PURE__ */ new Date()).getTime() > currentBillingDate.getTime();
22778
+ const isInvoiced = dueInvoice && dueInvoice.status === "pending" && subscription.status === "active" && (/* @__PURE__ */ new Date()).getTime() > currentBillingDate.getTime();
22779
+ if (isCancelledManually || activeWithOverdueInvoice || isInvoiced) {
22780
+ seats = value.seats;
22781
+ }
22782
+ if (seats === 0 && members > value.seats) {
22783
+ throw new import_utils70.BadRequestError(
22784
+ "Cannot reduce seats to less than the number of members. Please remove members before reducing seats."
22785
+ );
22786
+ }
22787
+ const monthlySubscriptionPrice = await getByNameType(
22788
+ "organization-subscription",
22789
+ "monthly-subscription"
22790
+ );
22791
+ if (!monthlySubscriptionPrice) {
22792
+ throw new import_utils70.BadRequestError(
22793
+ "Failed to fetch monthly subscription price."
22794
+ );
22795
+ }
22796
+ let perSeatPrice = monthlySubscriptionPrice.value;
22797
+ if (monthlySubscriptionPrice.saleValue && monthlySubscriptionPrice.saleExpiry && new Date(monthlySubscriptionPrice.saleExpiry) > /* @__PURE__ */ new Date()) {
22798
+ perSeatPrice = monthlySubscriptionPrice.saleValue;
22799
+ }
22800
+ let prorationFactor = calculateProration(
22801
+ new Date(subscription.nextBillingDate)
22802
+ );
22803
+ const isSubscriptionReactivation = subscription.status === "cancelled" && !dueInvoice;
22804
+ const isPassedBillingDate = (/* @__PURE__ */ new Date()).getTime() > new Date(subscription.nextBillingDate).getTime();
22805
+ if (isSubscriptionReactivation && isPassedBillingDate) {
22806
+ prorationFactor = 1;
22807
+ }
22808
+ let amount = perSeatPrice * seats * prorationFactor;
22809
+ let newMonthlySubscriptionPrice = perSeatPrice * seats;
22810
+ let items = [];
22811
+ if (subscription.promoCode) {
22812
+ const promoCode = await getByCode(subscription.promoCode);
22813
+ if (promoCode) {
22814
+ const {
22815
+ amount: amountWithPromoCode,
22816
+ newMonthSubscriptionFee,
22817
+ items: itemWithPromoCode
22818
+ } = calculateAmountWithPromoCode(
22819
+ subscription,
22820
+ monthlySubscriptionPrice,
22821
+ seats,
22822
+ prorationFactor,
22823
+ promoCode
22824
+ );
22825
+ amount = amountWithPromoCode;
22826
+ newMonthlySubscriptionPrice = newMonthSubscriptionFee;
22827
+ items = itemWithPromoCode;
22828
+ }
22829
+ }
22830
+ const invoiceNumber = await generateInvoiceNumber();
22831
+ const invoiceData = {
22832
+ type: "organization-subscription",
22833
+ invoiceNumber,
22834
+ amount: Number(amount.toFixed(2)),
22835
+ dueDate: /* @__PURE__ */ new Date(),
22836
+ metadata: {
22837
+ transactionId: value.transactionId,
22838
+ orgId: String(subscription.org),
22839
+ currency: subscription.currency,
22840
+ subscriptionId: value.subscriptionId,
22841
+ description: `Charge for ${isSubscriptionReactivation ? "" : "additional"} ${seats.toLocaleString()} seats`
22842
+ },
22843
+ status: "paid",
22844
+ items: [
22845
+ {
22846
+ description: "GoWeekdays Monthly Subscription",
22847
+ unitPrice: formatAmount(perSeatPrice),
22848
+ quantity: 1,
22849
+ seats,
22850
+ total: formatAmount(amount)
22851
+ }
22852
+ ]
22853
+ };
22854
+ if (items.length) {
22855
+ invoiceData.items = items;
22856
+ }
22857
+ if (seats && !dueInvoice) {
22858
+ await addInvoice(invoiceData, session);
22859
+ await incrementByType("invoice", session);
22860
+ const paymentMethod = await getPaymentMethodById(
22861
+ subscription.paymentMethodId ?? ""
22862
+ );
22863
+ if (!paymentMethod) {
22864
+ throw new import_utils70.BadRequestError("Payment method not found.");
22865
+ }
22866
+ const paymentMetadata = {
22867
+ userId: String(subscription.user),
22868
+ orgId: String(subscription.org),
22869
+ currency: subscription.currency,
22870
+ paymentMethod: paymentMethod.type === "EWALLET" ? paymentMethod.ewallet.channel_code : paymentMethod.type === "DIRECT_DEBIT" ? paymentMethod.direct_debit.channel_code : "",
22871
+ paymentMethodType: paymentMethod.type,
22872
+ paymentMethodId: subscription.paymentMethodId,
22873
+ payment: value.transactionId,
22874
+ subscriptionId: value.subscriptionId
22875
+ };
22876
+ if (!paymentMetadata.userId) {
22877
+ delete paymentMetadata.userId;
22878
+ }
22879
+ if (!paymentMetadata.orgId) {
22880
+ delete paymentMetadata.orgId;
22881
+ }
22882
+ await addPayment(
22883
+ {
22884
+ invoiceId: invoiceNumber,
22885
+ amount: formatAmount(amount),
22886
+ paymentMethod: paymentMethod.type,
22887
+ status: "completed",
22888
+ metadata: paymentMetadata
22889
+ },
22890
+ session
22891
+ );
22892
+ paidSeats = value.seats;
22893
+ } else if (dueInvoice && dueInvoice.status === "pending") {
22894
+ await updateStatusByInvoiceNumber(
22895
+ dueInvoice.invoiceNumber,
22896
+ "cancelled",
22897
+ session
22898
+ );
22899
+ invoiceData.status = "pending";
22900
+ invoiceData.dueDate = new Date(subscription.nextBillingDate);
22901
+ await addInvoice(invoiceData, session);
22902
+ await incrementByType("invoice", session);
22903
+ }
22904
+ const updateData = {
22905
+ _id: value.subscriptionId,
22906
+ currentSeats: value.seats,
22907
+ maxSeats: 0,
22908
+ paidSeats,
22909
+ amount: newMonthlySubscriptionPrice,
22910
+ status: "",
22911
+ nextBillingDate: ""
22912
+ };
22913
+ if (!dueInvoice && (/* @__PURE__ */ new Date()).getTime() > currentBillingDate.getTime()) {
22914
+ let date = /* @__PURE__ */ new Date();
22915
+ date.setMonth(date.getMonth() + 1);
22916
+ date.setDate(date.getDate() + 1);
22917
+ updateData.nextBillingDate = date.toISOString();
22918
+ }
22919
+ if (!dueInvoice && subscription.status === "cancelled") {
22920
+ updateData.status = "active";
22921
+ }
22922
+ await _updateSeatsById(updateData, session);
22923
+ await session?.commitTransaction();
22924
+ } catch (error2) {
22925
+ await session?.abortTransaction();
22926
+ import_utils70.logger.log({
22577
22927
  level: "error",
22578
22928
  message: `Failed to update subscription seats: ${error2}`
22579
22929
  });
22580
- if (error2 instanceof import_utils69.AppError) {
22930
+ if (error2 instanceof import_utils70.AppError) {
22581
22931
  throw error2;
22582
22932
  }
22583
- throw new import_utils69.BadRequestError("Failed to update subscription seats.");
22933
+ throw new import_utils70.BadRequestError("Failed to update subscription seats.");
22584
22934
  } finally {
22585
22935
  session?.endSession();
22586
22936
  }
@@ -22588,40 +22938,40 @@ function useSubscriptionService() {
22588
22938
  async function processSubscriptionPayment(invoiceNumber, subscriptionId) {
22589
22939
  const invoice = await getByNumber(invoiceNumber);
22590
22940
  if (!invoice) {
22591
- throw new import_utils69.BadRequestError("Invoice not found.");
22941
+ throw new import_utils70.BadRequestError("Invoice not found.");
22592
22942
  }
22593
22943
  if (invoice.status === "paid") {
22594
- throw new import_utils69.BadRequestError("Invoice already paid.");
22944
+ throw new import_utils70.BadRequestError("Invoice already paid.");
22595
22945
  }
22596
22946
  if (!invoice._id) {
22597
- throw new import_utils69.BadRequestError("Invoice ID is missing.");
22947
+ throw new import_utils70.BadRequestError("Invoice ID is missing.");
22598
22948
  }
22599
22949
  if (!invoice.metadata?.subscriptionId) {
22600
- throw new import_utils69.BadRequestError("Subscription ID is missing.");
22950
+ throw new import_utils70.BadRequestError("Subscription ID is missing.");
22601
22951
  }
22602
22952
  if (invoice.metadata.subscriptionId.toString() !== subscriptionId) {
22603
- throw new import_utils69.BadRequestError("Subscription ID does not match invoice.");
22953
+ throw new import_utils70.BadRequestError("Subscription ID does not match invoice.");
22604
22954
  }
22605
22955
  const subscription = await _getById(invoice.metadata.subscriptionId);
22606
22956
  if (!subscription) {
22607
- throw new import_utils69.BadRequestError("Subscription not found.");
22957
+ throw new import_utils70.BadRequestError("Subscription not found.");
22608
22958
  }
22609
22959
  if (!subscription._id) {
22610
- throw new import_utils69.BadRequestError("Subscription ID is missing.");
22960
+ throw new import_utils70.BadRequestError("Subscription ID is missing.");
22611
22961
  }
22612
22962
  if (!subscription.customerId) {
22613
- throw new import_utils69.BadRequestError("Customer ID is missing.");
22963
+ throw new import_utils70.BadRequestError("Customer ID is missing.");
22614
22964
  }
22615
22965
  if (!subscription.paymentMethodId) {
22616
- throw new import_utils69.BadRequestError("Payment method ID is missing.");
22966
+ throw new import_utils70.BadRequestError("Payment method ID is missing.");
22617
22967
  }
22618
22968
  if (!subscription.amount) {
22619
- throw new import_utils69.BadRequestError("Subscription amount is missing.");
22969
+ throw new import_utils70.BadRequestError("Subscription amount is missing.");
22620
22970
  }
22621
22971
  if (!subscription.currency) {
22622
- throw new import_utils69.BadRequestError("Subscription currency is missing.");
22972
+ throw new import_utils70.BadRequestError("Subscription currency is missing.");
22623
22973
  }
22624
- const session = import_utils69.useAtlas.getClient()?.startSession();
22974
+ const session = import_utils70.useAtlas.getClient()?.startSession();
22625
22975
  try {
22626
22976
  session?.startTransaction();
22627
22977
  const payment = await pay({
@@ -22632,13 +22982,13 @@ function useSubscriptionService() {
22632
22982
  description: "GoWeekdays Subscription Payment"
22633
22983
  });
22634
22984
  if (!payment.id) {
22635
- throw new import_utils69.BadRequestError("Failed to process payment.");
22985
+ throw new import_utils70.BadRequestError("Failed to process payment.");
22636
22986
  }
22637
22987
  const paymentMethod = await getPaymentMethodById(
22638
22988
  subscription.paymentMethodId
22639
22989
  );
22640
22990
  if (!paymentMethod) {
22641
- throw new import_utils69.BadRequestError("Payment method not found.");
22991
+ throw new import_utils70.BadRequestError("Payment method not found.");
22642
22992
  }
22643
22993
  const paymentData = {
22644
22994
  invoiceId: invoiceNumber,
@@ -22674,14 +23024,14 @@ function useSubscriptionService() {
22674
23024
  await session?.commitTransaction();
22675
23025
  } catch (error) {
22676
23026
  await session?.abortTransaction();
22677
- import_utils69.logger.log({
23027
+ import_utils70.logger.log({
22678
23028
  level: "error",
22679
23029
  message: `Failed to process subscription payment: ${error}`
22680
23030
  });
22681
- if (error instanceof import_utils69.AppError) {
23031
+ if (error instanceof import_utils70.AppError) {
22682
23032
  throw error;
22683
23033
  }
22684
- throw new import_utils69.BadRequestError("Failed to process subscription payment.");
23034
+ throw new import_utils70.BadRequestError("Failed to process subscription payment.");
22685
23035
  } finally {
22686
23036
  session?.endSession();
22687
23037
  }
@@ -22694,13 +23044,14 @@ function useSubscriptionService() {
22694
23044
  createOrgSubscription,
22695
23045
  processSubscriptions,
22696
23046
  updateSeatsById,
23047
+ updateSubscriptionSeats,
22697
23048
  processSubscriptionPayment
22698
23049
  };
22699
23050
  }
22700
23051
 
22701
23052
  // src/controllers/subscription.controller.ts
22702
23053
  var import_joi20 = __toESM(require("joi"));
22703
- var import_utils70 = require("@goweekdays/utils");
23054
+ var import_utils71 = require("@goweekdays/utils");
22704
23055
 
22705
23056
  // src/validations/subscription.schema.ts
22706
23057
  var import_joi19 = __toESM(require("joi"));
@@ -22762,7 +23113,7 @@ function useSubscriptionController() {
22762
23113
  getStatusByUser: _getStatusByUser,
22763
23114
  createAffiliateSubscription: _createAffiliateSubscription,
22764
23115
  createOrgSubscription: _createOrgSubscription,
22765
- updateSeatsById: _updateSubscriptionSeats,
23116
+ updateSubscriptionSeats: _updateSubscriptionSeats,
22766
23117
  processSubscriptionPayment: _processSubscriptionPayment,
22767
23118
  subscribe: _subscribe
22768
23119
  } = useSubscriptionService();
@@ -22770,7 +23121,7 @@ function useSubscriptionController() {
22770
23121
  const value = req.body;
22771
23122
  const validation = import_joi20.default.object({
22772
23123
  user: import_joi20.default.string().hex().required(),
22773
- transactionId: import_joi20.default.string().required(),
23124
+ transactionId: import_joi20.default.string().optional().allow("", null),
22774
23125
  promoCode: import_joi20.default.string().optional().allow("", null),
22775
23126
  seats: import_joi20.default.number().min(1).required(),
22776
23127
  perSeatPrice: import_joi20.default.number().min(0).required(),
@@ -22785,7 +23136,8 @@ function useSubscriptionController() {
22785
23136
  });
22786
23137
  const { error } = validation.validate(value);
22787
23138
  if (error) {
22788
- next(new import_utils70.BadRequestError(error.message));
23139
+ next(new import_utils71.BadRequestError(error.message));
23140
+ return;
22789
23141
  }
22790
23142
  try {
22791
23143
  const id = await _subscribe(value);
@@ -22803,7 +23155,7 @@ function useSubscriptionController() {
22803
23155
  });
22804
23156
  const { error } = validation.validate(value);
22805
23157
  if (error) {
22806
- next(new import_utils70.BadRequestError(error.message));
23158
+ next(new import_utils71.BadRequestError(error.message));
22807
23159
  }
22808
23160
  try {
22809
23161
  const value2 = req.body;
@@ -22819,7 +23171,7 @@ function useSubscriptionController() {
22819
23171
  const validation = import_joi20.default.string().required();
22820
23172
  const { error } = validation.validate(id);
22821
23173
  if (error) {
22822
- next(new import_utils70.BadRequestError(error.message));
23174
+ next(new import_utils71.BadRequestError(error.message));
22823
23175
  }
22824
23176
  try {
22825
23177
  const subscription = await _getByUserId(id);
@@ -22834,7 +23186,7 @@ function useSubscriptionController() {
22834
23186
  const validation = import_joi20.default.string().required();
22835
23187
  const { error } = validation.validate(id);
22836
23188
  if (error) {
22837
- next(new import_utils70.BadRequestError(error.message));
23189
+ next(new import_utils71.BadRequestError(error.message));
22838
23190
  }
22839
23191
  try {
22840
23192
  const subscription = await _getByAffiliateUserId(id);
@@ -22849,7 +23201,7 @@ function useSubscriptionController() {
22849
23201
  const validation = import_joi20.default.string().required();
22850
23202
  const { error } = validation.validate(id);
22851
23203
  if (error) {
22852
- next(new import_utils70.BadRequestError(error.message));
23204
+ next(new import_utils71.BadRequestError(error.message));
22853
23205
  }
22854
23206
  try {
22855
23207
  const subscription = await _getByOrgId(id);
@@ -22864,7 +23216,7 @@ function useSubscriptionController() {
22864
23216
  const validation = import_joi20.default.string().required();
22865
23217
  const { error } = validation.validate(id);
22866
23218
  if (error) {
22867
- next(new import_utils70.BadRequestError(error.message));
23219
+ next(new import_utils71.BadRequestError(error.message));
22868
23220
  }
22869
23221
  try {
22870
23222
  const subscription = await _getById(id);
@@ -22885,7 +23237,7 @@ function useSubscriptionController() {
22885
23237
  });
22886
23238
  const { error } = validation.validate({ status, search, page });
22887
23239
  if (error) {
22888
- next(new import_utils70.BadRequestError(error.message));
23240
+ next(new import_utils71.BadRequestError(error.message));
22889
23241
  }
22890
23242
  try {
22891
23243
  const subscriptions = await _getSubscriptions({ status, search, page });
@@ -22900,7 +23252,7 @@ function useSubscriptionController() {
22900
23252
  const validation = import_joi20.default.string().required();
22901
23253
  const { error } = validation.validate(id);
22902
23254
  if (error) {
22903
- next(new import_utils70.BadRequestError(error.message));
23255
+ next(new import_utils71.BadRequestError(error.message));
22904
23256
  }
22905
23257
  try {
22906
23258
  const status = await _getStatusByUser(id);
@@ -22916,7 +23268,7 @@ function useSubscriptionController() {
22916
23268
  value.user = req.headers["user"];
22917
23269
  const { error } = subscriptionSchema.validate(value);
22918
23270
  if (error) {
22919
- next(new import_utils70.BadRequestError(error.message));
23271
+ next(new import_utils71.BadRequestError(error.message));
22920
23272
  return;
22921
23273
  }
22922
23274
  try {
@@ -22933,7 +23285,7 @@ function useSubscriptionController() {
22933
23285
  value.user = req.headers["user"];
22934
23286
  const { error } = subscriptionSchema.validate(value);
22935
23287
  if (error) {
22936
- next(new import_utils70.BadRequestError(error.message));
23288
+ next(new import_utils71.BadRequestError(error.message));
22937
23289
  return;
22938
23290
  }
22939
23291
  try {
@@ -22949,13 +23301,14 @@ function useSubscriptionController() {
22949
23301
  const subscriptionId = req.params.id ?? "";
22950
23302
  const value = req.body;
22951
23303
  const { error } = import_joi20.default.object({
23304
+ transactionId: import_joi20.default.string().optional().allow("", null),
22952
23305
  subscriptionId: import_joi20.default.string().required(),
22953
23306
  seats: import_joi20.default.number().required(),
22954
23307
  promoCode: import_joi20.default.string().optional().allow("", null),
22955
23308
  amount: import_joi20.default.number().min(0).optional()
22956
23309
  }).validate({ subscriptionId, ...value });
22957
23310
  if (error) {
22958
- next(new import_utils70.BadRequestError(error.message));
23311
+ next(new import_utils71.BadRequestError(error.message));
22959
23312
  return;
22960
23313
  }
22961
23314
  try {
@@ -22975,7 +23328,7 @@ function useSubscriptionController() {
22975
23328
  promoCode: import_joi20.default.string().optional().allow("", null)
22976
23329
  }).validate({ subscriptionId, promoCode });
22977
23330
  if (error) {
22978
- next(new import_utils70.BadRequestError(error.message));
23331
+ next(new import_utils71.BadRequestError(error.message));
22979
23332
  return;
22980
23333
  }
22981
23334
  try {
@@ -22995,7 +23348,7 @@ function useSubscriptionController() {
22995
23348
  status: import_joi20.default.string().optional().allow("", null)
22996
23349
  }).validate({ subscriptionId, status });
22997
23350
  if (error) {
22998
- next(new import_utils70.BadRequestError(error.message));
23351
+ next(new import_utils71.BadRequestError(error.message));
22999
23352
  return;
23000
23353
  }
23001
23354
  try {
@@ -23015,7 +23368,7 @@ function useSubscriptionController() {
23015
23368
  email: import_joi20.default.string().email().required()
23016
23369
  }).validate({ subscriptionId, email });
23017
23370
  if (error) {
23018
- next(new import_utils70.BadRequestError(error.message));
23371
+ next(new import_utils71.BadRequestError(error.message));
23019
23372
  return;
23020
23373
  }
23021
23374
  try {
@@ -23037,7 +23390,7 @@ function useSubscriptionController() {
23037
23390
  email: import_joi20.default.string().email().required()
23038
23391
  }).validate({ id, addedAt, email });
23039
23392
  if (error) {
23040
- next(new import_utils70.BadRequestError(error.message));
23393
+ next(new import_utils71.BadRequestError(error.message));
23041
23394
  return;
23042
23395
  }
23043
23396
  try {
@@ -23057,7 +23410,7 @@ function useSubscriptionController() {
23057
23410
  addedAt: import_joi20.default.string().isoDate().required()
23058
23411
  }).validate({ id, addedAt });
23059
23412
  if (error) {
23060
- next(new import_utils70.BadRequestError(error.message));
23413
+ next(new import_utils71.BadRequestError(error.message));
23061
23414
  return;
23062
23415
  }
23063
23416
  try {
@@ -23077,7 +23430,7 @@ function useSubscriptionController() {
23077
23430
  paymentMethodId: import_joi20.default.string().optional().allow("", null)
23078
23431
  }).validate({ subscriptionId, paymentMethodId });
23079
23432
  if (error) {
23080
- next(new import_utils70.BadRequestError(error.message));
23433
+ next(new import_utils71.BadRequestError(error.message));
23081
23434
  return;
23082
23435
  }
23083
23436
  try {
@@ -23099,7 +23452,7 @@ function useSubscriptionController() {
23099
23452
  invoiceNumber: import_joi20.default.string().required()
23100
23453
  }).validate({ id, invoiceNumber });
23101
23454
  if (error) {
23102
- next(new import_utils70.BadRequestError(error.message));
23455
+ next(new import_utils71.BadRequestError(error.message));
23103
23456
  return;
23104
23457
  }
23105
23458
  try {
@@ -23134,21 +23487,21 @@ function useSubscriptionController() {
23134
23487
  }
23135
23488
 
23136
23489
  // src/models/payment-method.model.ts
23137
- var import_utils71 = require("@goweekdays/utils");
23490
+ var import_utils72 = require("@goweekdays/utils");
23138
23491
  var import_mongodb35 = require("mongodb");
23139
23492
  function MPaymentMethod(value) {
23140
23493
  if (value.user) {
23141
23494
  try {
23142
23495
  value.user = new import_mongodb35.ObjectId(value.user);
23143
23496
  } catch (error) {
23144
- throw new import_utils71.BadRequestError("Invalid user ID.");
23497
+ throw new import_utils72.BadRequestError("Invalid user ID.");
23145
23498
  }
23146
23499
  }
23147
23500
  if (value.org) {
23148
23501
  try {
23149
23502
  value.org = new import_mongodb35.ObjectId(value.org);
23150
23503
  } catch (error) {
23151
- throw new import_utils71.BadRequestError("Invalid org ID.");
23504
+ throw new import_utils72.BadRequestError("Invalid org ID.");
23152
23505
  }
23153
23506
  }
23154
23507
  return {
@@ -23171,12 +23524,12 @@ function MPaymentMethod(value) {
23171
23524
  }
23172
23525
 
23173
23526
  // src/repositories/payment-method.repository.ts
23174
- var import_utils72 = require("@goweekdays/utils");
23527
+ var import_utils73 = require("@goweekdays/utils");
23175
23528
  var import_mongodb36 = require("mongodb");
23176
23529
  function usePaymentMethodRepo() {
23177
- const db = import_utils72.useAtlas.getDb();
23530
+ const db = import_utils73.useAtlas.getDb();
23178
23531
  if (!db) {
23179
- throw new import_utils72.BadRequestError("Unable to connect to server.");
23532
+ throw new import_utils73.BadRequestError("Unable to connect to server.");
23180
23533
  }
23181
23534
  const collection = db.collection("payment-methods");
23182
23535
  async function createIndex() {
@@ -23186,7 +23539,7 @@ function usePaymentMethodRepo() {
23186
23539
  { key: { org: 1 } }
23187
23540
  ]);
23188
23541
  } catch (error) {
23189
- throw new import_utils72.BadRequestError("Failed to create index on payment method.");
23542
+ throw new import_utils73.BadRequestError("Failed to create index on payment method.");
23190
23543
  }
23191
23544
  }
23192
23545
  async function createUniqueIndex() {
@@ -23204,7 +23557,7 @@ function usePaymentMethodRepo() {
23204
23557
  }
23205
23558
  ]);
23206
23559
  } catch (error) {
23207
- throw new import_utils72.BadRequestError(
23560
+ throw new import_utils73.BadRequestError(
23208
23561
  "Failed to create unique index on payment method."
23209
23562
  );
23210
23563
  }
@@ -23215,19 +23568,19 @@ function usePaymentMethodRepo() {
23215
23568
  await collection.insertOne(value, { session });
23216
23569
  return "Successfully added payment method.";
23217
23570
  } catch (error) {
23218
- import_utils72.logger.log({ level: "error", message: `${error}` });
23571
+ import_utils73.logger.log({ level: "error", message: `${error}` });
23219
23572
  const isDuplicated = error.message.includes("duplicate");
23220
23573
  if (isDuplicated) {
23221
- throw new import_utils72.BadRequestError("Payment method already exist.");
23574
+ throw new import_utils73.BadRequestError("Payment method already exist.");
23222
23575
  }
23223
- throw new import_utils72.InternalServerError("Failed to add payment method.");
23576
+ throw new import_utils73.InternalServerError("Failed to add payment method.");
23224
23577
  }
23225
23578
  }
23226
23579
  function getByUser(user) {
23227
23580
  try {
23228
23581
  user = new import_mongodb36.ObjectId(user);
23229
23582
  } catch (error) {
23230
- throw new import_utils72.BadRequestError("Invalid user ID.");
23583
+ throw new import_utils73.BadRequestError("Invalid user ID.");
23231
23584
  }
23232
23585
  try {
23233
23586
  return collection.aggregate([
@@ -23245,14 +23598,14 @@ function usePaymentMethodRepo() {
23245
23598
  }
23246
23599
  ]).toArray();
23247
23600
  } catch (error) {
23248
- throw new import_utils72.BadRequestError("Failed to get payment methods.");
23601
+ throw new import_utils73.BadRequestError("Failed to get payment methods.");
23249
23602
  }
23250
23603
  }
23251
23604
  function getByOrg(org) {
23252
23605
  try {
23253
23606
  org = new import_mongodb36.ObjectId(org);
23254
23607
  } catch (error) {
23255
- throw new import_utils72.BadRequestError("Invalid org ID.");
23608
+ throw new import_utils73.BadRequestError("Invalid org ID.");
23256
23609
  }
23257
23610
  try {
23258
23611
  return collection.aggregate([
@@ -23270,24 +23623,24 @@ function usePaymentMethodRepo() {
23270
23623
  }
23271
23624
  ]).toArray();
23272
23625
  } catch (error) {
23273
- throw new import_utils72.BadRequestError("Failed to get payment methods.");
23626
+ throw new import_utils73.BadRequestError("Failed to get payment methods.");
23274
23627
  }
23275
23628
  }
23276
23629
  async function getByPaymentMethodId(paymentMethodId) {
23277
23630
  if (!paymentMethodId) {
23278
- throw new import_utils72.BadRequestError("Invalid payment method ID.");
23631
+ throw new import_utils73.BadRequestError("Invalid payment method ID.");
23279
23632
  }
23280
23633
  try {
23281
23634
  return await collection.findOne({ paymentMethodId });
23282
23635
  } catch (error) {
23283
- throw new import_utils72.BadRequestError("Failed to retrieve payment method.");
23636
+ throw new import_utils73.BadRequestError("Failed to retrieve payment method.");
23284
23637
  }
23285
23638
  }
23286
23639
  async function deleteById(_id) {
23287
23640
  try {
23288
23641
  _id = new import_mongodb36.ObjectId(_id);
23289
23642
  } catch (error) {
23290
- throw new import_utils72.BadRequestError("Invalid payment method ID.");
23643
+ throw new import_utils73.BadRequestError("Invalid payment method ID.");
23291
23644
  }
23292
23645
  try {
23293
23646
  await collection.updateOne(
@@ -23296,7 +23649,7 @@ function usePaymentMethodRepo() {
23296
23649
  );
23297
23650
  return "Successfully deleted payment method.";
23298
23651
  } catch (error) {
23299
- throw new import_utils72.BadRequestError("Failed to delete payment method.");
23652
+ throw new import_utils73.BadRequestError("Failed to delete payment method.");
23300
23653
  }
23301
23654
  }
23302
23655
  return {
@@ -23311,7 +23664,7 @@ function usePaymentMethodRepo() {
23311
23664
  }
23312
23665
 
23313
23666
  // src/services/payment-method.service.ts
23314
- var import_utils73 = require("@goweekdays/utils");
23667
+ var import_utils74 = require("@goweekdays/utils");
23315
23668
  function usePaymentMethodService() {
23316
23669
  const { linkPaymentMethodEWallet, linkPaymentMethodCard } = useXenditService();
23317
23670
  const { getUserById } = useUserRepo();
@@ -23362,7 +23715,7 @@ function usePaymentMethodService() {
23362
23715
  failure_return_url = "",
23363
23716
  cancel_return_url = ""
23364
23717
  } = {}) {
23365
- const session = import_utils73.useAtlas.getClient()?.startSession();
23718
+ const session = import_utils74.useAtlas.getClient()?.startSession();
23366
23719
  session?.startTransaction();
23367
23720
  try {
23368
23721
  const paymentMethod = await linkPaymentMethodEWallet({
@@ -23395,15 +23748,15 @@ function usePaymentMethodService() {
23395
23748
  cardholder_name = "",
23396
23749
  currency = "PHP"
23397
23750
  } = {}) {
23398
- const session = import_utils73.useAtlas.getClient()?.startSession();
23751
+ const session = import_utils74.useAtlas.getClient()?.startSession();
23399
23752
  session?.startTransaction();
23400
23753
  try {
23401
23754
  const _user = await getUserById(user);
23402
23755
  if (!_user) {
23403
- throw new import_utils73.BadRequestError("User not found.");
23756
+ throw new import_utils74.BadRequestError("User not found.");
23404
23757
  }
23405
23758
  if (!_user._id) {
23406
- throw new import_utils73.BadRequestError("Invalid user ID.");
23759
+ throw new import_utils74.BadRequestError("Invalid user ID.");
23407
23760
  }
23408
23761
  const result = await linkPaymentMethodCard({
23409
23762
  card_number,
@@ -23443,7 +23796,7 @@ function usePaymentMethodService() {
23443
23796
 
23444
23797
  // src/controllers/payment-method.controller.ts
23445
23798
  var import_joi21 = __toESM(require("joi"));
23446
- var import_utils74 = require("@goweekdays/utils");
23799
+ var import_utils75 = require("@goweekdays/utils");
23447
23800
  function usePaymentMethodController() {
23448
23801
  const { linkEWallet: _linkEWallet, linkCard: _linkCard } = usePaymentMethodService();
23449
23802
  const {
@@ -23475,7 +23828,7 @@ function usePaymentMethodController() {
23475
23828
  cancel_return_url
23476
23829
  });
23477
23830
  if (error) {
23478
- next(new import_utils74.BadRequestError(error.message));
23831
+ next(new import_utils75.BadRequestError(error.message));
23479
23832
  return;
23480
23833
  }
23481
23834
  try {
@@ -23528,7 +23881,7 @@ function usePaymentMethodController() {
23528
23881
  failure_return_url
23529
23882
  });
23530
23883
  if (error) {
23531
- next(new import_utils74.BadRequestError(error.message));
23884
+ next(new import_utils75.BadRequestError(error.message));
23532
23885
  }
23533
23886
  try {
23534
23887
  const result = await _linkCard({
@@ -23557,7 +23910,7 @@ function usePaymentMethodController() {
23557
23910
  });
23558
23911
  const { error } = validation.validate({ user });
23559
23912
  if (error) {
23560
- next(new import_utils74.BadRequestError(error.message));
23913
+ next(new import_utils75.BadRequestError(error.message));
23561
23914
  }
23562
23915
  try {
23563
23916
  const result = await _getByUser(user);
@@ -23573,7 +23926,7 @@ function usePaymentMethodController() {
23573
23926
  });
23574
23927
  const { error } = validation.validate({ org });
23575
23928
  if (error) {
23576
- next(new import_utils74.BadRequestError(error.message));
23929
+ next(new import_utils75.BadRequestError(error.message));
23577
23930
  }
23578
23931
  try {
23579
23932
  const result = await _getByOrg(org);
@@ -23589,7 +23942,7 @@ function usePaymentMethodController() {
23589
23942
  });
23590
23943
  const { error } = validation.validate({ id });
23591
23944
  if (error) {
23592
- next(new import_utils74.BadRequestError(error.message));
23945
+ next(new import_utils75.BadRequestError(error.message));
23593
23946
  }
23594
23947
  try {
23595
23948
  const result = await _getPaymentMethodById(id);
@@ -23604,7 +23957,7 @@ function usePaymentMethodController() {
23604
23957
  try {
23605
23958
  CardPaymentSchema.parse(req.body);
23606
23959
  } catch (error) {
23607
- next(new import_utils74.BadRequestError(error.issues[0].message));
23960
+ next(new import_utils75.BadRequestError(error.issues[0].message));
23608
23961
  return;
23609
23962
  }
23610
23963
  try {
@@ -23620,7 +23973,7 @@ function usePaymentMethodController() {
23620
23973
  try {
23621
23974
  EWalletPaymentSchema.parse(req.body);
23622
23975
  } catch (error) {
23623
- next(new import_utils74.BadRequestError(error.issues[0].message));
23976
+ next(new import_utils75.BadRequestError(error.issues[0].message));
23624
23977
  return;
23625
23978
  }
23626
23979
  try {
@@ -23636,7 +23989,7 @@ function usePaymentMethodController() {
23636
23989
  try {
23637
23990
  DirectDebitSchema.parse(req.body);
23638
23991
  } catch (error) {
23639
- next(new import_utils74.BadRequestError(error.issues[0].message));
23992
+ next(new import_utils75.BadRequestError(error.issues[0].message));
23640
23993
  return;
23641
23994
  }
23642
23995
  try {
@@ -23648,7 +24001,7 @@ function usePaymentMethodController() {
23648
24001
  return;
23649
24002
  }
23650
24003
  }
23651
- next(new import_utils74.BadRequestError("Invalid type"));
24004
+ next(new import_utils75.BadRequestError("Invalid type"));
23652
24005
  return;
23653
24006
  }
23654
24007
  async function getPaymentMethodsByCustomerId(req, res, next) {
@@ -23658,7 +24011,7 @@ function usePaymentMethodController() {
23658
24011
  });
23659
24012
  const { error } = validation.validate({ id });
23660
24013
  if (error) {
23661
- next(new import_utils74.BadRequestError(error.message));
24014
+ next(new import_utils75.BadRequestError(error.message));
23662
24015
  }
23663
24016
  try {
23664
24017
  const result = await _getPaymentMethodsByCustomerId(id);
@@ -23676,7 +24029,7 @@ function usePaymentMethodController() {
23676
24029
  });
23677
24030
  const { error } = validation.validate({ id, status });
23678
24031
  if (error) {
23679
- next(new import_utils74.BadRequestError(error.message));
24032
+ next(new import_utils75.BadRequestError(error.message));
23680
24033
  }
23681
24034
  try {
23682
24035
  const result = await _updatePaymentMethodStatusById(id, status);
@@ -23698,7 +24051,7 @@ function usePaymentMethodController() {
23698
24051
  }
23699
24052
 
23700
24053
  // src/controllers/address.controller.ts
23701
- var import_utils75 = require("@goweekdays/utils");
24054
+ var import_utils76 = require("@goweekdays/utils");
23702
24055
  var import_joi22 = __toESM(require("joi"));
23703
24056
  function useAddressController() {
23704
24057
  const {
@@ -23723,7 +24076,7 @@ function useAddressController() {
23723
24076
  });
23724
24077
  const { error } = validation.validate(value);
23725
24078
  if (error) {
23726
- next(new import_utils75.BadRequestError(error.message));
24079
+ next(new import_utils76.BadRequestError(error.message));
23727
24080
  }
23728
24081
  try {
23729
24082
  const value2 = req.body;
@@ -23750,7 +24103,7 @@ function useAddressController() {
23750
24103
  });
23751
24104
  const { error } = validation.validate({ id, ...value });
23752
24105
  if (error) {
23753
- next(new import_utils75.BadRequestError(error.message));
24106
+ next(new import_utils76.BadRequestError(error.message));
23754
24107
  return;
23755
24108
  }
23756
24109
  try {
@@ -23766,12 +24119,12 @@ function useAddressController() {
23766
24119
  const validation = import_joi22.default.string().hex().required();
23767
24120
  const { error } = validation.validate(user);
23768
24121
  if (error) {
23769
- next(new import_utils75.BadRequestError(error.message));
24122
+ next(new import_utils76.BadRequestError(error.message));
23770
24123
  }
23771
24124
  try {
23772
24125
  const address = await _getByUserId(user);
23773
24126
  if (!address) {
23774
- next(new import_utils75.NotFoundError("Address not found."));
24127
+ next(new import_utils76.NotFoundError("Address not found."));
23775
24128
  return;
23776
24129
  }
23777
24130
  res.json(address);
@@ -23785,12 +24138,12 @@ function useAddressController() {
23785
24138
  const validation = import_joi22.default.string().hex().required();
23786
24139
  const { error } = validation.validate(id);
23787
24140
  if (error) {
23788
- next(new import_utils75.BadRequestError(error.message));
24141
+ next(new import_utils76.BadRequestError(error.message));
23789
24142
  }
23790
24143
  try {
23791
24144
  const address = await _getByOrgId(id);
23792
24145
  if (!address) {
23793
- next(new import_utils75.NotFoundError("Address not found."));
24146
+ next(new import_utils76.NotFoundError("Address not found."));
23794
24147
  return;
23795
24148
  }
23796
24149
  res.json(address);
@@ -23808,19 +24161,19 @@ function useAddressController() {
23808
24161
  }
23809
24162
 
23810
24163
  // src/services/organization.service.ts
23811
- var import_utils76 = require("@goweekdays/utils");
24164
+ var import_utils77 = require("@goweekdays/utils");
23812
24165
  function useOrgService() {
23813
24166
  const { add: addOrg } = useOrgRepo();
23814
24167
  const { addRole } = useRoleRepo();
23815
24168
  const { add: addMember } = useMemberRepo();
23816
24169
  const { getUserById } = useUserRepo();
23817
24170
  async function createOrg({ user = "", name = "", description = "" } = {}) {
23818
- const session = import_utils76.useAtlas.getClient()?.startSession();
24171
+ const session = import_utils77.useAtlas.getClient()?.startSession();
23819
24172
  session?.startTransaction();
23820
24173
  try {
23821
24174
  const _user = await getUserById(user);
23822
24175
  if (!_user) {
23823
- throw new import_utils76.NotFoundError("User not found.");
24176
+ throw new import_utils77.NotFoundError("User not found.");
23824
24177
  }
23825
24178
  const org = await addOrg(
23826
24179
  {
@@ -23864,12 +24217,12 @@ function useOrgService() {
23864
24217
  }
23865
24218
 
23866
24219
  // src/controllers/organization.controller.ts
23867
- var import_utils77 = require("@goweekdays/utils");
24220
+ var import_utils78 = require("@goweekdays/utils");
23868
24221
  var import_joi23 = __toESM(require("joi"));
23869
24222
  function useOrgController() {
23870
24223
  const { createOrg: _createOrg } = useOrgService();
23871
24224
  const { getOrgsByMembership } = useMemberRepo();
23872
- const { getByName: _getByName } = useOrgRepo();
24225
+ const { getByName: _getByName, getAll: getAllOrg } = useOrgRepo();
23873
24226
  async function createOrg(req, res, next) {
23874
24227
  const value = req.body;
23875
24228
  const validation = import_joi23.default.object({
@@ -23882,7 +24235,7 @@ function useOrgController() {
23882
24235
  });
23883
24236
  const { error } = validation.validate(value);
23884
24237
  if (error) {
23885
- next(new import_utils77.BadRequestError(error.message));
24238
+ next(new import_utils78.BadRequestError(error.message));
23886
24239
  return;
23887
24240
  }
23888
24241
  try {
@@ -23897,15 +24250,15 @@ function useOrgController() {
23897
24250
  const page = typeof req.query.page === "string" ? Number(req.query.page) : 1;
23898
24251
  const limit = typeof req.query.limit === "string" ? Number(req.query.limit) : 10;
23899
24252
  const search = req.query.search ?? "";
23900
- const user = req.headers["user"];
24253
+ const user = req.params.user ?? "";
23901
24254
  const isPageNumber = isFinite(page);
23902
24255
  if (!isPageNumber) {
23903
- next(new import_utils77.BadRequestError("Invalid page number."));
24256
+ next(new import_utils78.BadRequestError("Invalid page number."));
23904
24257
  return;
23905
24258
  }
23906
24259
  const isLimitNumber = isFinite(limit);
23907
24260
  if (!isLimitNumber) {
23908
- next(new import_utils77.BadRequestError("Invalid limit number."));
24261
+ next(new import_utils78.BadRequestError("Invalid limit number."));
23909
24262
  return;
23910
24263
  }
23911
24264
  const validation = import_joi23.default.object({
@@ -23916,7 +24269,7 @@ function useOrgController() {
23916
24269
  });
23917
24270
  const { error } = validation.validate({ user, page, limit, search });
23918
24271
  if (error) {
23919
- next(new import_utils77.BadRequestError(error.message));
24272
+ next(new import_utils78.BadRequestError(error.message));
23920
24273
  return;
23921
24274
  }
23922
24275
  try {
@@ -23927,6 +24280,39 @@ function useOrgController() {
23927
24280
  next(error2);
23928
24281
  }
23929
24282
  }
24283
+ async function getAll(req, res, next) {
24284
+ const query = req.query;
24285
+ const validation = import_joi23.default.object({
24286
+ page: import_joi23.default.number().min(1).optional().allow("", null),
24287
+ limit: import_joi23.default.number().min(1).optional().allow("", null),
24288
+ search: import_joi23.default.string().optional().allow("", null)
24289
+ });
24290
+ const { error } = validation.validate(query);
24291
+ const page = typeof req.query.page === "string" ? Number(req.query.page) : 1;
24292
+ const limit = typeof req.query.limit === "string" ? Number(req.query.limit) : 10;
24293
+ const search = req.query.search ?? "";
24294
+ const isPageNumber = isFinite(page);
24295
+ if (!isPageNumber) {
24296
+ next(new import_utils78.BadRequestError("Invalid page number."));
24297
+ return;
24298
+ }
24299
+ const isLimitNumber = isFinite(limit);
24300
+ if (!isLimitNumber) {
24301
+ next(new import_utils78.BadRequestError("Invalid limit number."));
24302
+ return;
24303
+ }
24304
+ if (error) {
24305
+ next(new import_utils78.BadRequestError(error.message));
24306
+ return;
24307
+ }
24308
+ try {
24309
+ const orgs = await getAllOrg({ page, limit, search });
24310
+ res.json(orgs);
24311
+ return;
24312
+ } catch (error2) {
24313
+ next(error2);
24314
+ }
24315
+ }
23930
24316
  async function getByName(req, res, next) {
23931
24317
  const name = req.params.name;
23932
24318
  const validation = import_joi23.default.object({
@@ -23934,7 +24320,7 @@ function useOrgController() {
23934
24320
  });
23935
24321
  const { error } = validation.validate({ name });
23936
24322
  if (error) {
23937
- next(new import_utils77.BadRequestError(error.message));
24323
+ next(new import_utils78.BadRequestError(error.message));
23938
24324
  return;
23939
24325
  }
23940
24326
  try {
@@ -23948,13 +24334,14 @@ function useOrgController() {
23948
24334
  return {
23949
24335
  createOrg,
23950
24336
  getOrgsByUserId,
23951
- getByName
24337
+ getByName,
24338
+ getAll
23952
24339
  };
23953
24340
  }
23954
24341
 
23955
24342
  // src/controllers/member.controller.ts
23956
24343
  var import_joi24 = __toESM(require("joi"));
23957
- var import_utils78 = require("@goweekdays/utils");
24344
+ var import_utils79 = require("@goweekdays/utils");
23958
24345
  function useMemberController() {
23959
24346
  const {
23960
24347
  getByUserId: _getByUserId,
@@ -23968,7 +24355,7 @@ function useMemberController() {
23968
24355
  });
23969
24356
  const { error } = validation.validate({ id: userId });
23970
24357
  if (error) {
23971
- next(new import_utils78.BadRequestError(error.message));
24358
+ next(new import_utils79.BadRequestError(error.message));
23972
24359
  return;
23973
24360
  }
23974
24361
  try {
@@ -24009,7 +24396,7 @@ function useMemberController() {
24009
24396
  status
24010
24397
  });
24011
24398
  if (error) {
24012
- next(new import_utils78.BadRequestError(error.message));
24399
+ next(new import_utils79.BadRequestError(error.message));
24013
24400
  return;
24014
24401
  }
24015
24402
  try {
@@ -24046,7 +24433,7 @@ function useMemberController() {
24046
24433
  limit
24047
24434
  });
24048
24435
  if (error) {
24049
- next(new import_utils78.BadRequestError(error.message));
24436
+ next(new import_utils79.BadRequestError(error.message));
24050
24437
  }
24051
24438
  try {
24052
24439
  const items = await _getOrgsByMembership({
@@ -24069,7 +24456,7 @@ function useMemberController() {
24069
24456
  }
24070
24457
 
24071
24458
  // src/controllers/promo-code.controller.ts
24072
- var import_utils79 = require("@goweekdays/utils");
24459
+ var import_utils80 = require("@goweekdays/utils");
24073
24460
  var import_joi25 = __toESM(require("joi"));
24074
24461
  function usePromoCodeController() {
24075
24462
  const {
@@ -24082,7 +24469,7 @@ function usePromoCodeController() {
24082
24469
  const data = req.body;
24083
24470
  const { error } = schema.validate(data);
24084
24471
  if (error) {
24085
- next(new import_utils79.BadRequestError(error.message));
24472
+ next(new import_utils80.BadRequestError(error.message));
24086
24473
  return;
24087
24474
  }
24088
24475
  try {
@@ -24090,10 +24477,10 @@ function usePromoCodeController() {
24090
24477
  res.json({ message: "Successfully added promo code." });
24091
24478
  return;
24092
24479
  } catch (error2) {
24093
- if (error2 instanceof import_utils79.AppError) {
24480
+ if (error2 instanceof import_utils80.AppError) {
24094
24481
  next(error2);
24095
24482
  } else {
24096
- next(new import_utils79.InternalServerError(error2));
24483
+ next(new import_utils80.InternalServerError(error2));
24097
24484
  }
24098
24485
  }
24099
24486
  }
@@ -24109,22 +24496,22 @@ function usePromoCodeController() {
24109
24496
  });
24110
24497
  const { error } = validation.validate({ code, type, assigned });
24111
24498
  if (error) {
24112
- next(new import_utils79.BadRequestError(error.message));
24499
+ next(new import_utils80.BadRequestError(error.message));
24113
24500
  return;
24114
24501
  }
24115
24502
  try {
24116
24503
  const promoCode = await _getByCode(code, type, assigned);
24117
24504
  if (!promoCode) {
24118
- next(new import_utils79.NotFoundError("Promo code not found."));
24505
+ next(new import_utils80.NotFoundError("Promo code not found."));
24119
24506
  return;
24120
24507
  }
24121
24508
  res.json(promoCode);
24122
24509
  return;
24123
24510
  } catch (error2) {
24124
- if (error2 instanceof import_utils79.AppError) {
24511
+ if (error2 instanceof import_utils80.AppError) {
24125
24512
  next(error2);
24126
24513
  } else {
24127
- next(new import_utils79.InternalServerError(error2));
24514
+ next(new import_utils80.InternalServerError(error2));
24128
24515
  }
24129
24516
  }
24130
24517
  }
@@ -24135,22 +24522,22 @@ function usePromoCodeController() {
24135
24522
  });
24136
24523
  const { error } = validation.validate({ id });
24137
24524
  if (error) {
24138
- next(new import_utils79.BadRequestError(error.message));
24525
+ next(new import_utils80.BadRequestError(error.message));
24139
24526
  return;
24140
24527
  }
24141
24528
  try {
24142
24529
  const promoCode = await _getById(id);
24143
24530
  if (!promoCode) {
24144
- next(new import_utils79.NotFoundError("Promo code not found."));
24531
+ next(new import_utils80.NotFoundError("Promo code not found."));
24145
24532
  return;
24146
24533
  }
24147
24534
  res.json(promoCode);
24148
24535
  return;
24149
24536
  } catch (error2) {
24150
- if (error2 instanceof import_utils79.AppError) {
24537
+ if (error2 instanceof import_utils80.AppError) {
24151
24538
  next(error2);
24152
24539
  } else {
24153
- next(new import_utils79.InternalServerError(error2));
24540
+ next(new import_utils80.InternalServerError(error2));
24154
24541
  }
24155
24542
  }
24156
24543
  }
@@ -24167,7 +24554,7 @@ function usePromoCodeController() {
24167
24554
  });
24168
24555
  const { error } = validation.validate({ page, limit, search, status });
24169
24556
  if (error) {
24170
- next(new import_utils79.BadRequestError(error.message));
24557
+ next(new import_utils80.BadRequestError(error.message));
24171
24558
  return;
24172
24559
  }
24173
24560
  try {
@@ -24218,31 +24605,31 @@ var schema2 = import_joi26.default.object({
24218
24605
  });
24219
24606
 
24220
24607
  // src/models/order.model.ts
24221
- var import_utils80 = require("@goweekdays/utils");
24608
+ var import_utils81 = require("@goweekdays/utils");
24222
24609
  function MOrder(value) {
24223
24610
  const { error } = schema2.validate(value);
24224
24611
  if (error) {
24225
- throw new import_utils80.BadRequestError(error.message);
24612
+ throw new import_utils81.BadRequestError(error.message);
24226
24613
  }
24227
24614
  if (value._id) {
24228
24615
  try {
24229
24616
  value._id = new import_mongodb37.ObjectId(value._id);
24230
24617
  } catch (error2) {
24231
- throw new import_utils80.BadRequestError("Invalid ID.");
24618
+ throw new import_utils81.BadRequestError("Invalid ID.");
24232
24619
  }
24233
24620
  }
24234
24621
  if (value.user) {
24235
24622
  try {
24236
24623
  value.user = new import_mongodb37.ObjectId(value.user);
24237
24624
  } catch (error2) {
24238
- throw new import_utils80.BadRequestError("Invalid user ID.");
24625
+ throw new import_utils81.BadRequestError("Invalid user ID.");
24239
24626
  }
24240
24627
  }
24241
24628
  if (value.org) {
24242
24629
  try {
24243
24630
  value.org = new import_mongodb37.ObjectId(value.org);
24244
24631
  } catch (error2) {
24245
- throw new import_utils80.BadRequestError("Invalid org ID.");
24632
+ throw new import_utils81.BadRequestError("Invalid org ID.");
24246
24633
  }
24247
24634
  }
24248
24635
  if (value.metadata?.subscriptionId) {
@@ -24251,7 +24638,7 @@ function MOrder(value) {
24251
24638
  value.metadata.subscriptionId
24252
24639
  );
24253
24640
  } catch (error2) {
24254
- throw new import_utils80.BadRequestError("Invalid subscription ID.");
24641
+ throw new import_utils81.BadRequestError("Invalid subscription ID.");
24255
24642
  }
24256
24643
  }
24257
24644
  return {
@@ -24272,12 +24659,12 @@ function MOrder(value) {
24272
24659
  }
24273
24660
 
24274
24661
  // src/repositories/order.repository.ts
24275
- var import_utils81 = require("@goweekdays/utils");
24662
+ var import_utils82 = require("@goweekdays/utils");
24276
24663
  var import_mongodb38 = require("mongodb");
24277
24664
  function useOrderRepo() {
24278
- const db = import_utils81.useAtlas.getDb();
24665
+ const db = import_utils82.useAtlas.getDb();
24279
24666
  if (!db) {
24280
- throw new import_utils81.InternalServerError("Unable to connect to server.");
24667
+ throw new import_utils82.InternalServerError("Unable to connect to server.");
24281
24668
  }
24282
24669
  const collection = db.collection("orders");
24283
24670
  function createIndex() {
@@ -24296,11 +24683,11 @@ function useOrderRepo() {
24296
24683
  value = MOrder(value);
24297
24684
  collection.insertOne(value, { session });
24298
24685
  } catch (error) {
24299
- import_utils81.logger.log({ level: "error", message: `${error}` });
24300
- if (error instanceof import_utils81.AppError) {
24686
+ import_utils82.logger.log({ level: "error", message: `${error}` });
24687
+ if (error instanceof import_utils82.AppError) {
24301
24688
  throw error;
24302
24689
  }
24303
- throw new import_utils81.InternalServerError("Internal server error.");
24690
+ throw new import_utils82.InternalServerError("Internal server error.");
24304
24691
  }
24305
24692
  }
24306
24693
  async function getOrders({
@@ -24325,7 +24712,7 @@ function useOrderRepo() {
24325
24712
  try {
24326
24713
  query["metadata.subscriptionId"] = new import_mongodb38.ObjectId(id);
24327
24714
  } catch (error) {
24328
- throw new import_utils81.BadRequestError("Invalid subscription ID.");
24715
+ throw new import_utils82.BadRequestError("Invalid subscription ID.");
24329
24716
  }
24330
24717
  }
24331
24718
  try {
@@ -24336,10 +24723,10 @@ function useOrderRepo() {
24336
24723
  { $limit: limit }
24337
24724
  ]).toArray();
24338
24725
  const length = await collection.countDocuments(query);
24339
- return (0, import_utils81.paginate)(items, page, limit, length);
24726
+ return (0, import_utils82.paginate)(items, page, limit, length);
24340
24727
  } catch (error) {
24341
- import_utils81.logger.log({ level: "error", message: `${error}` });
24342
- throw new import_utils81.InternalServerError("Internal server error.");
24728
+ import_utils82.logger.log({ level: "error", message: `${error}` });
24729
+ throw new import_utils82.InternalServerError("Internal server error.");
24343
24730
  }
24344
24731
  }
24345
24732
  return {
@@ -24350,7 +24737,7 @@ function useOrderRepo() {
24350
24737
  }
24351
24738
 
24352
24739
  // src/controllers/order.controller.ts
24353
- var import_utils82 = require("@goweekdays/utils");
24740
+ var import_utils83 = require("@goweekdays/utils");
24354
24741
  var import_joi27 = __toESM(require("joi"));
24355
24742
  function useOrderController() {
24356
24743
  const { getOrders: _getOrders } = useOrderRepo();
@@ -24369,7 +24756,7 @@ function useOrderController() {
24369
24756
  });
24370
24757
  const { error } = validation.validate({ page, limit, search, status, id });
24371
24758
  if (error) {
24372
- next(new import_utils82.BadRequestError(error.message));
24759
+ next(new import_utils83.BadRequestError(error.message));
24373
24760
  return;
24374
24761
  }
24375
24762
  try {
@@ -24392,7 +24779,7 @@ function useOrderController() {
24392
24779
  }
24393
24780
 
24394
24781
  // src/services/invoice.service.ts
24395
- var import_utils83 = require("@goweekdays/utils");
24782
+ var import_utils84 = require("@goweekdays/utils");
24396
24783
  function useInvoiceService() {
24397
24784
  const { getOverdueInvoices, updateStatusByInvoiceNumber, getByNumber } = useInvoiceRepo();
24398
24785
  const {
@@ -24404,11 +24791,12 @@ function useInvoiceService() {
24404
24791
  } = useSubscriptionRepo();
24405
24792
  const { pay, getPaymentMethodById } = useXenditService();
24406
24793
  const { add: addPayment, getByInvoiceId } = usePaymentRepo();
24794
+ const { getInvoiceById } = usePaypalService();
24407
24795
  async function processOverDueInvoices(BATCH_SIZE = 100, MAX_RETRIES = 7) {
24408
24796
  while (true) {
24409
24797
  const overdueInvoices = await getOverdueInvoices(BATCH_SIZE);
24410
24798
  if (!overdueInvoices.length) {
24411
- import_utils83.logger.log({
24799
+ import_utils84.logger.log({
24412
24800
  level: "info",
24413
24801
  message: "No overdue invoices found."
24414
24802
  });
@@ -24416,23 +24804,23 @@ function useInvoiceService() {
24416
24804
  }
24417
24805
  await Promise.allSettled(
24418
24806
  overdueInvoices.map(async (invoice) => {
24419
- const session = import_utils83.useAtlas.getClient()?.startSession();
24807
+ const session = import_utils84.useAtlas.getClient()?.startSession();
24420
24808
  if (!session) {
24421
- import_utils83.logger.log({
24809
+ import_utils84.logger.log({
24422
24810
  level: "error",
24423
24811
  message: "Failed to start session."
24424
24812
  });
24425
24813
  return;
24426
24814
  }
24427
24815
  if (!invoice._id) {
24428
- import_utils83.logger.log({
24816
+ import_utils84.logger.log({
24429
24817
  level: "error",
24430
24818
  message: "Invoice ID is missing."
24431
24819
  });
24432
24820
  return;
24433
24821
  }
24434
24822
  if (!invoice.metadata?.subscriptionId) {
24435
- import_utils83.logger.log({
24823
+ import_utils84.logger.log({
24436
24824
  level: "error",
24437
24825
  message: "Subscription ID is missing."
24438
24826
  });
@@ -24442,14 +24830,14 @@ function useInvoiceService() {
24442
24830
  invoice.metadata.subscriptionId
24443
24831
  ).catch(() => null);
24444
24832
  if (!subscription) {
24445
- import_utils83.logger.log({
24833
+ import_utils84.logger.log({
24446
24834
  level: "error",
24447
24835
  message: "Subscription not found."
24448
24836
  });
24449
24837
  return;
24450
24838
  }
24451
24839
  if (!subscription._id) {
24452
- import_utils83.logger.log({
24840
+ import_utils84.logger.log({
24453
24841
  level: "error",
24454
24842
  message: "Subscription ID is missing."
24455
24843
  });
@@ -24460,34 +24848,51 @@ function useInvoiceService() {
24460
24848
  if (!invoice.metadata?.currency) {
24461
24849
  throw new Error("Currency is missing.");
24462
24850
  }
24463
- const internalPayment = await getByInvoiceId(invoice.invoiceNumber);
24464
- if (!internalPayment) {
24465
- const payment = await pay({
24466
- customer_id: subscription.customerId ?? "",
24467
- payment_method_id: subscription.paymentMethodId ?? "",
24468
- amount: invoice.amount,
24469
- currency: invoice.metadata?.currency,
24470
- description: invoice.metadata?.description
24471
- });
24472
- if (!payment.id) {
24473
- throw new import_utils83.BadRequestError("Failed to process payment.");
24474
- }
24475
- const customerPaymentMethod = await getPaymentMethodById(
24476
- subscription.paymentMethodId ?? ""
24851
+ if (!invoice.metadata.transactionId) {
24852
+ throw new Error("Transaction ID is missing.");
24853
+ }
24854
+ const paypalInvoice = await getInvoiceById(
24855
+ invoice.metadata.transactionId
24856
+ );
24857
+ const isOverdue = paypalInvoice.status === "SENT" && new Date(paypalInvoice.detail.payment_term.due_date) < /* @__PURE__ */ new Date();
24858
+ if (!isOverdue) {
24859
+ await updateStatusById(
24860
+ subscription._id.toString(),
24861
+ "suspended",
24862
+ session
24863
+ );
24864
+ await session.commitTransaction();
24865
+ return;
24866
+ }
24867
+ const isPaid = paypalInvoice.status === "PAID";
24868
+ if (isPaid && subscription.status !== "active") {
24869
+ await updateStatusById(
24870
+ subscription._id.toString(),
24871
+ "active",
24872
+ session
24873
+ );
24874
+ await updateStatusByInvoiceNumber(
24875
+ invoice.invoiceNumber,
24876
+ "paid",
24877
+ session
24878
+ );
24879
+ await processSuccessfulPayment(
24880
+ {
24881
+ _id: subscription._id,
24882
+ nextBillingDate: subscription.nextBillingDate
24883
+ },
24884
+ session
24477
24885
  );
24478
24886
  const paymentData = {
24479
24887
  invoiceId: invoice.invoiceNumber,
24480
24888
  amount: invoice.amount,
24481
- paymentMethod: customerPaymentMethod.type,
24482
24889
  status: "completed",
24890
+ paymentMethod: "PAYPAL",
24483
24891
  metadata: {
24484
24892
  userId: String(subscription.user || ""),
24485
24893
  orgId: String(subscription.org || ""),
24486
24894
  currency: subscription.currency,
24487
- paymentMethod: customerPaymentMethod.ewallet.channel_code,
24488
- paymentMethodType: customerPaymentMethod.type,
24489
- paymentMethodId: subscription.paymentMethodId,
24490
- payment: payment.id,
24895
+ payment: invoice.metadata.transactionId,
24491
24896
  subscriptionId: subscription._id?.toString()
24492
24897
  }
24493
24898
  };
@@ -24498,70 +24903,31 @@ function useInvoiceService() {
24498
24903
  delete paymentData.metadata.orgId;
24499
24904
  }
24500
24905
  await addPayment(paymentData, session);
24501
- }
24502
- await updateStatusByInvoiceNumber(
24503
- invoice.invoiceNumber,
24504
- "paid",
24505
- session
24506
- );
24507
- await processSuccessfulPayment(
24508
- {
24509
- _id: subscription._id,
24510
- nextBillingDate: subscription.nextBillingDate
24511
- },
24512
- session
24513
- );
24514
- if (!subscription.paidSeats) {
24515
- throw new Error("Subscription paid seats is missing.");
24516
- }
24517
- await updateMaxSeatsById(
24518
- {
24519
- _id: subscription._id.toString(),
24520
- seats: subscription.paidSeats
24521
- },
24522
- session
24523
- );
24524
- await session.commitTransaction();
24525
- } catch (error) {
24526
- import_utils83.logger.log({
24527
- level: "error",
24528
- message: String(error)
24529
- });
24530
- await session.abortTransaction();
24531
- try {
24532
- session.startTransaction();
24533
- await markSubscriptionAsFailed(
24906
+ if (!subscription.paidSeats) {
24907
+ throw new Error("Subscription paid seats is missing.");
24908
+ }
24909
+ await updateMaxSeatsById(
24534
24910
  {
24535
- _id: String(invoice.metadata.subscriptionId)
24911
+ _id: subscription._id.toString(),
24912
+ seats: subscription.paidSeats
24536
24913
  },
24537
24914
  session
24538
24915
  );
24539
- if (subscription.failedAttempts && subscription.failedAttempts + 1 >= MAX_RETRIES) {
24540
- await updateStatusById(
24541
- String(invoice.metadata.subscriptionId),
24542
- "suspended",
24543
- session
24544
- );
24545
- await updateStatusByInvoiceNumber(
24546
- invoice.invoiceNumber,
24547
- "overdue",
24548
- session
24549
- );
24550
- }
24551
24916
  await session.commitTransaction();
24552
- } catch (error2) {
24553
- import_utils83.logger.log({
24554
- level: "error",
24555
- message: String(error2)
24556
- });
24557
- await session.abortTransaction();
24917
+ return;
24558
24918
  }
24919
+ } catch (error) {
24920
+ import_utils84.logger.log({
24921
+ level: "error",
24922
+ message: String(error)
24923
+ });
24924
+ await session.abortTransaction();
24559
24925
  } finally {
24560
24926
  session.endSession();
24561
24927
  }
24562
24928
  })
24563
24929
  );
24564
- import_utils83.logger.log({
24930
+ import_utils84.logger.log({
24565
24931
  level: "info",
24566
24932
  message: "Successfully processed overdue invoices."
24567
24933
  });
@@ -24573,7 +24939,7 @@ function useInvoiceService() {
24573
24939
  }
24574
24940
 
24575
24941
  // src/controllers/invoice.controller.ts
24576
- var import_utils84 = require("@goweekdays/utils");
24942
+ var import_utils85 = require("@goweekdays/utils");
24577
24943
  var import_joi28 = __toESM(require("joi"));
24578
24944
  function useInvoiceController() {
24579
24945
  const {
@@ -24599,7 +24965,7 @@ function useInvoiceController() {
24599
24965
  search
24600
24966
  });
24601
24967
  if (error) {
24602
- next(new import_utils84.BadRequestError(error.message));
24968
+ next(new import_utils85.BadRequestError(error.message));
24603
24969
  return;
24604
24970
  }
24605
24971
  try {
@@ -24620,13 +24986,13 @@ function useInvoiceController() {
24620
24986
  const validation = import_joi28.default.string().required();
24621
24987
  const { error } = validation.validate(number);
24622
24988
  if (error) {
24623
- next(new import_utils84.BadRequestError(error.message));
24989
+ next(new import_utils85.BadRequestError(error.message));
24624
24990
  return;
24625
24991
  }
24626
24992
  try {
24627
24993
  const invoice = await _getByNumber(number);
24628
24994
  if (!invoice) {
24629
- throw new import_utils84.NotFoundError("Invoice not found.");
24995
+ throw new import_utils85.NotFoundError("Invoice not found.");
24630
24996
  }
24631
24997
  res.json(invoice);
24632
24998
  return;
@@ -24637,19 +25003,21 @@ function useInvoiceController() {
24637
25003
  async function getByDueDateStatus(req, res, next) {
24638
25004
  const date = req.params.date;
24639
25005
  const status = req.params.status;
25006
+ const id = req.params.id;
24640
25007
  const validation = import_joi28.default.object({
25008
+ id: import_joi28.default.string().required(),
24641
25009
  date: import_joi28.default.string().required(),
24642
25010
  status: import_joi28.default.string().required()
24643
25011
  });
24644
- const { error } = validation.validate({ date, status });
25012
+ const { error } = validation.validate({ id, date, status });
24645
25013
  if (error) {
24646
- next(new import_utils84.BadRequestError(error.message));
25014
+ next(new import_utils85.BadRequestError(error.message));
24647
25015
  return;
24648
25016
  }
24649
25017
  try {
24650
- const invoice = await _getByDueDate(new Date(date), status);
25018
+ const invoice = await _getByDueDate(id, new Date(date), status);
24651
25019
  if (!invoice) {
24652
- throw new import_utils84.NotFoundError("Invoice not found.");
25020
+ throw new import_utils85.NotFoundError("Invoice not found.");
24653
25021
  }
24654
25022
  res.json(invoice);
24655
25023
  return;
@@ -24665,7 +25033,7 @@ function useInvoiceController() {
24665
25033
  }
24666
25034
 
24667
25035
  // src/controllers/payment.controller.ts
24668
- var import_utils85 = require("@goweekdays/utils");
25036
+ var import_utils86 = require("@goweekdays/utils");
24669
25037
  var import_joi29 = __toESM(require("joi"));
24670
25038
  function usePaymentController() {
24671
25039
  const { getPayments: _getPayments } = usePaymentRepo();
@@ -24684,7 +25052,7 @@ function usePaymentController() {
24684
25052
  });
24685
25053
  const { error } = validation.validate({ page, limit, search, status, id });
24686
25054
  if (error) {
24687
- next(new import_utils85.BadRequestError(error.message));
25055
+ next(new import_utils86.BadRequestError(error.message));
24688
25056
  return;
24689
25057
  }
24690
25058
  try {
@@ -24707,7 +25075,7 @@ function usePaymentController() {
24707
25075
  }
24708
25076
 
24709
25077
  // src/controllers/price.controller.ts
24710
- var import_utils86 = require("@goweekdays/utils");
25078
+ var import_utils87 = require("@goweekdays/utils");
24711
25079
  function usePriceController() {
24712
25080
  const { getByNameType: _getByNameType } = usePriceRepo();
24713
25081
  async function getByNameType(req, res, next) {
@@ -24720,7 +25088,7 @@ function usePriceController() {
24720
25088
  try {
24721
25089
  const price = await _getByNameType(name, type);
24722
25090
  if (!price) {
24723
- throw new import_utils86.BadRequestError("Price not found");
25091
+ throw new import_utils87.BadRequestError("Price not found");
24724
25092
  }
24725
25093
  res.json(price);
24726
25094
  } catch (error) {
@@ -24825,6 +25193,7 @@ function usePriceController() {
24825
25193
  usePaymentMethodService,
24826
25194
  usePaymentModel,
24827
25195
  usePaymentRepo,
25196
+ usePaypalService,
24828
25197
  usePriceController,
24829
25198
  usePriceModel,
24830
25199
  usePriceRepo,