@goweekdays/core 0.0.21 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -8980,9 +8980,9 @@ var require_iterate = __commonJS({
8980
8980
  var async = require_async();
8981
8981
  var abort = require_abort();
8982
8982
  module.exports = iterate;
8983
- function iterate(list, iterator, state, callback) {
8983
+ function iterate(list, iterator2, state, callback) {
8984
8984
  var key = state["keyedList"] ? state["keyedList"][state.index] : state.index;
8985
- state.jobs[key] = runJob(iterator, key, list[key], function(error, output) {
8985
+ state.jobs[key] = runJob(iterator2, key, list[key], function(error, output) {
8986
8986
  if (!(key in state.jobs)) {
8987
8987
  return;
8988
8988
  }
@@ -8995,12 +8995,12 @@ var require_iterate = __commonJS({
8995
8995
  callback(error, state.results);
8996
8996
  });
8997
8997
  }
8998
- function runJob(iterator, key, item, callback) {
8998
+ function runJob(iterator2, key, item, callback) {
8999
8999
  var aborter;
9000
- if (iterator.length == 2) {
9001
- aborter = iterator(item, async(callback));
9000
+ if (iterator2.length == 2) {
9001
+ aborter = iterator2(item, async(callback));
9002
9002
  } else {
9003
- aborter = iterator(item, key, async(callback));
9003
+ aborter = iterator2(item, key, async(callback));
9004
9004
  }
9005
9005
  return aborter;
9006
9006
  }
@@ -9053,10 +9053,10 @@ var require_parallel = __commonJS({
9053
9053
  var initState = require_state();
9054
9054
  var terminator = require_terminator();
9055
9055
  module.exports = parallel;
9056
- function parallel(list, iterator, callback) {
9056
+ function parallel(list, iterator2, callback) {
9057
9057
  var state = initState(list);
9058
9058
  while (state.index < (state["keyedList"] || list).length) {
9059
- iterate(list, iterator, state, function(error, result) {
9059
+ iterate(list, iterator2, state, function(error, result) {
9060
9060
  if (error) {
9061
9061
  callback(error, result);
9062
9062
  return;
@@ -9082,16 +9082,16 @@ var require_serialOrdered = __commonJS({
9082
9082
  module.exports = serialOrdered;
9083
9083
  module.exports.ascending = ascending;
9084
9084
  module.exports.descending = descending;
9085
- function serialOrdered(list, iterator, sortMethod, callback) {
9085
+ function serialOrdered(list, iterator2, sortMethod, callback) {
9086
9086
  var state = initState(list, sortMethod);
9087
- iterate(list, iterator, state, function iteratorHandler(error, result) {
9087
+ iterate(list, iterator2, state, function iteratorHandler(error, result) {
9088
9088
  if (error) {
9089
9089
  callback(error, result);
9090
9090
  return;
9091
9091
  }
9092
9092
  state.index++;
9093
9093
  if (state.index < (state["keyedList"] || list).length) {
9094
- iterate(list, iterator, state, iteratorHandler);
9094
+ iterate(list, iterator2, state, iteratorHandler);
9095
9095
  return;
9096
9096
  }
9097
9097
  callback(null, state.results);
@@ -9112,8 +9112,8 @@ var require_serial = __commonJS({
9112
9112
  "node_modules/asynckit/serial.js"(exports, module) {
9113
9113
  var serialOrdered = require_serialOrdered();
9114
9114
  module.exports = serial;
9115
- function serial(list, iterator, callback) {
9116
- return serialOrdered(list, iterator, null, callback);
9115
+ function serial(list, iterator2, callback) {
9116
+ return serialOrdered(list, iterator2, null, callback);
9117
9117
  }
9118
9118
  }
9119
9119
  });
@@ -9679,6 +9679,7 @@ var require_get_intrinsic = __commonJS({
9679
9679
  "%eval%": eval,
9680
9680
  // eslint-disable-line no-eval
9681
9681
  "%EvalError%": $EvalError,
9682
+ "%Float16Array%": typeof Float16Array === "undefined" ? undefined2 : Float16Array,
9682
9683
  "%Float32Array%": typeof Float32Array === "undefined" ? undefined2 : Float32Array,
9683
9684
  "%Float64Array%": typeof Float64Array === "undefined" ? undefined2 : Float64Array,
9684
9685
  "%FinalizationRegistry%": typeof FinalizationRegistry === "undefined" ? undefined2 : FinalizationRegistry,
@@ -9951,23 +9952,23 @@ var require_es_set_tostringtag = __commonJS({
9951
9952
  var hasToStringTag = require_shams2()();
9952
9953
  var hasOwn = require_hasown();
9953
9954
  var $TypeError = require_type();
9954
- var toStringTag = hasToStringTag ? Symbol.toStringTag : null;
9955
+ var toStringTag2 = hasToStringTag ? Symbol.toStringTag : null;
9955
9956
  module.exports = function setToStringTag(object, value) {
9956
9957
  var overrideIfSet = arguments.length > 2 && !!arguments[2] && arguments[2].force;
9957
9958
  var nonConfigurable = arguments.length > 2 && !!arguments[2] && arguments[2].nonConfigurable;
9958
9959
  if (typeof overrideIfSet !== "undefined" && typeof overrideIfSet !== "boolean" || typeof nonConfigurable !== "undefined" && typeof nonConfigurable !== "boolean") {
9959
9960
  throw new $TypeError("if provided, the `overrideIfSet` and `nonConfigurable` options must be booleans");
9960
9961
  }
9961
- if (toStringTag && (overrideIfSet || !hasOwn(object, toStringTag))) {
9962
+ if (toStringTag2 && (overrideIfSet || !hasOwn(object, toStringTag2))) {
9962
9963
  if ($defineProperty) {
9963
- $defineProperty(object, toStringTag, {
9964
+ $defineProperty(object, toStringTag2, {
9964
9965
  configurable: !nonConfigurable,
9965
9966
  enumerable: false,
9966
9967
  value,
9967
9968
  writable: false
9968
9969
  });
9969
9970
  } else {
9970
- object[toStringTag] = value;
9971
+ object[toStringTag2] = value;
9971
9972
  }
9972
9973
  }
9973
9974
  };
@@ -12143,7 +12144,6 @@ function useVerificationController() {
12143
12144
  res.json({ message: "Successfully invited user." });
12144
12145
  return;
12145
12146
  } catch (error2) {
12146
- console.log(error2);
12147
12147
  next(error2);
12148
12148
  }
12149
12149
  }
@@ -12750,6 +12750,7 @@ function bind(fn, thisArg) {
12750
12750
  // node_modules/axios/lib/utils.js
12751
12751
  var { toString } = Object.prototype;
12752
12752
  var { getPrototypeOf } = Object;
12753
+ var { iterator, toStringTag } = Symbol;
12753
12754
  var kindOf = ((cache) => (thing) => {
12754
12755
  const str = toString.call(thing);
12755
12756
  return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
@@ -12784,7 +12785,7 @@ var isPlainObject = (val) => {
12784
12785
  return false;
12785
12786
  }
12786
12787
  const prototype3 = getPrototypeOf(val);
12787
- return (prototype3 === null || prototype3 === Object.prototype || Object.getPrototypeOf(prototype3) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
12788
+ return (prototype3 === null || prototype3 === Object.prototype || Object.getPrototypeOf(prototype3) === null) && !(toStringTag in val) && !(iterator in val);
12788
12789
  };
12789
12790
  var isDate = kindOfTest("Date");
12790
12791
  var isFile = kindOfTest("File");
@@ -12936,10 +12937,10 @@ var isTypedArray = ((TypedArray) => {
12936
12937
  };
12937
12938
  })(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array));
12938
12939
  var forEachEntry = (obj, fn) => {
12939
- const generator = obj && obj[Symbol.iterator];
12940
- const iterator = generator.call(obj);
12940
+ const generator = obj && obj[iterator];
12941
+ const _iterator = generator.call(obj);
12941
12942
  let result;
12942
- while ((result = iterator.next()) && !result.done) {
12943
+ while ((result = _iterator.next()) && !result.done) {
12943
12944
  const pair = result.value;
12944
12945
  fn.call(obj, pair[0], pair[1]);
12945
12946
  }
@@ -13009,23 +13010,8 @@ var noop = () => {
13009
13010
  var toFiniteNumber = (value, defaultValue) => {
13010
13011
  return value != null && Number.isFinite(value = +value) ? value : defaultValue;
13011
13012
  };
13012
- var ALPHA = "abcdefghijklmnopqrstuvwxyz";
13013
- var DIGIT = "0123456789";
13014
- var ALPHABET = {
13015
- DIGIT,
13016
- ALPHA,
13017
- ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
13018
- };
13019
- var generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => {
13020
- let str = "";
13021
- const { length } = alphabet;
13022
- while (size--) {
13023
- str += alphabet[Math.random() * length | 0];
13024
- }
13025
- return str;
13026
- };
13027
13013
  function isSpecCompliantForm(thing) {
13028
- return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === "FormData" && thing[Symbol.iterator]);
13014
+ return !!(thing && isFunction(thing.append) && thing[toStringTag] === "FormData" && thing[iterator]);
13029
13015
  }
13030
13016
  var toJSONObject = (obj) => {
13031
13017
  const stack = new Array(10);
@@ -13071,6 +13057,7 @@ var _setImmediate = ((setImmediateSupported, postMessageSupported) => {
13071
13057
  isFunction(_global.postMessage)
13072
13058
  );
13073
13059
  var asap = typeof queueMicrotask !== "undefined" ? queueMicrotask.bind(_global) : typeof process !== "undefined" && process.nextTick || _setImmediate;
13060
+ var isIterable = (thing) => thing != null && isFunction(thing[iterator]);
13074
13061
  var utils_default = {
13075
13062
  isArray,
13076
13063
  isArrayBuffer,
@@ -13122,14 +13109,13 @@ var utils_default = {
13122
13109
  findKey,
13123
13110
  global: _global,
13124
13111
  isContextDefined,
13125
- ALPHABET,
13126
- generateString,
13127
13112
  isSpecCompliantForm,
13128
13113
  toJSONObject,
13129
13114
  isAsyncFn,
13130
13115
  isThenable,
13131
13116
  setImmediate: _setImmediate,
13132
- asap
13117
+ asap,
13118
+ isIterable
13133
13119
  };
13134
13120
 
13135
13121
  // node_modules/axios/lib/core/AxiosError.js
@@ -13461,11 +13447,31 @@ var transitional_default = {
13461
13447
  clarifyTimeoutError: false
13462
13448
  };
13463
13449
 
13450
+ // node_modules/axios/lib/platform/node/index.js
13451
+ import crypto from "crypto";
13452
+
13464
13453
  // node_modules/axios/lib/platform/node/classes/URLSearchParams.js
13465
13454
  import url from "url";
13466
13455
  var URLSearchParams_default = url.URLSearchParams;
13467
13456
 
13468
13457
  // node_modules/axios/lib/platform/node/index.js
13458
+ var ALPHA = "abcdefghijklmnopqrstuvwxyz";
13459
+ var DIGIT = "0123456789";
13460
+ var ALPHABET = {
13461
+ DIGIT,
13462
+ ALPHA,
13463
+ ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
13464
+ };
13465
+ var generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => {
13466
+ let str = "";
13467
+ const { length } = alphabet;
13468
+ const randomValues = new Uint32Array(size);
13469
+ crypto.randomFillSync(randomValues);
13470
+ for (let i = 0; i < size; i++) {
13471
+ str += alphabet[randomValues[i] % length];
13472
+ }
13473
+ return str;
13474
+ };
13469
13475
  var node_default = {
13470
13476
  isNode: true,
13471
13477
  classes: {
@@ -13473,6 +13479,8 @@ var node_default = {
13473
13479
  FormData: FormData_default,
13474
13480
  Blob: typeof Blob !== "undefined" && Blob || null
13475
13481
  },
13482
+ ALPHABET,
13483
+ generateString,
13476
13484
  protocols: ["http", "https", "file", "data"]
13477
13485
  };
13478
13486
 
@@ -13795,10 +13803,15 @@ var AxiosHeaders = class {
13795
13803
  setHeaders(header, valueOrRewrite);
13796
13804
  } else if (utils_default.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
13797
13805
  setHeaders(parseHeaders_default(header), valueOrRewrite);
13798
- } else if (utils_default.isHeaders(header)) {
13799
- for (const [key, value] of header.entries()) {
13800
- setHeader(value, key, rewrite);
13806
+ } else if (utils_default.isObject(header) && utils_default.isIterable(header)) {
13807
+ let obj = {}, dest, key;
13808
+ for (const entry of header) {
13809
+ if (!utils_default.isArray(entry)) {
13810
+ throw TypeError("Object iterator must return a key-value pair");
13811
+ }
13812
+ obj[key = entry[0]] = (dest = obj[key]) ? utils_default.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]] : entry[1];
13801
13813
  }
13814
+ setHeaders(obj, valueOrRewrite);
13802
13815
  } else {
13803
13816
  header != null && setHeader(valueOrRewrite, header, rewrite);
13804
13817
  }
@@ -13902,6 +13915,9 @@ var AxiosHeaders = class {
13902
13915
  toString() {
13903
13916
  return Object.entries(this.toJSON()).map(([header, value]) => header + ": " + value).join("\n");
13904
13917
  }
13918
+ getSetCookie() {
13919
+ return this.get("set-cookie") || [];
13920
+ }
13905
13921
  get [Symbol.toStringTag]() {
13906
13922
  return "AxiosHeaders";
13907
13923
  }
@@ -13998,8 +14014,9 @@ function combineURLs(baseURL, relativeURL) {
13998
14014
  }
13999
14015
 
14000
14016
  // node_modules/axios/lib/core/buildFullPath.js
14001
- function buildFullPath(baseURL, requestedURL) {
14002
- if (baseURL && !isAbsoluteURL(requestedURL)) {
14017
+ function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls) {
14018
+ let isRelativeUrl = !isAbsoluteURL(requestedURL);
14019
+ if (baseURL && (isRelativeUrl || allowAbsoluteUrls == false)) {
14003
14020
  return combineURLs(baseURL, requestedURL);
14004
14021
  }
14005
14022
  return requestedURL;
@@ -14014,7 +14031,7 @@ import util2 from "util";
14014
14031
  import zlib from "zlib";
14015
14032
 
14016
14033
  // node_modules/axios/lib/env/data.js
14017
- var VERSION = "1.7.9";
14034
+ var VERSION = "1.9.0";
14018
14035
 
14019
14036
  // node_modules/axios/lib/helpers/parseProtocol.js
14020
14037
  function parseProtocol(url2) {
@@ -14192,7 +14209,7 @@ var readBlob = async function* (blob) {
14192
14209
  var readBlob_default = readBlob;
14193
14210
 
14194
14211
  // node_modules/axios/lib/helpers/formDataToStream.js
14195
- var BOUNDARY_ALPHABET = utils_default.ALPHABET.ALPHA_DIGIT + "-_";
14212
+ var BOUNDARY_ALPHABET = platform_default.ALPHABET.ALPHA_DIGIT + "-_";
14196
14213
  var textEncoder = typeof TextEncoder === "function" ? new TextEncoder() : new util.TextEncoder();
14197
14214
  var CRLF = "\r\n";
14198
14215
  var CRLF_BYTES = textEncoder.encode(CRLF);
@@ -14235,7 +14252,7 @@ var formDataToStream = (form, headersHandler, options) => {
14235
14252
  const {
14236
14253
  tag = "form-data-boundary",
14237
14254
  size = 25,
14238
- boundary = tag + "-" + utils_default.generateString(size, BOUNDARY_ALPHABET)
14255
+ boundary = tag + "-" + platform_default.generateString(size, BOUNDARY_ALPHABET)
14239
14256
  } = options || {};
14240
14257
  if (!utils_default.isFormData(form)) {
14241
14258
  throw TypeError("FormData instance required");
@@ -14244,7 +14261,7 @@ var formDataToStream = (form, headersHandler, options) => {
14244
14261
  throw Error("boundary must be 10-70 characters long");
14245
14262
  }
14246
14263
  const boundaryBytes = textEncoder.encode("--" + boundary + CRLF);
14247
- const footerBytes = textEncoder.encode("--" + boundary + "--" + CRLF + CRLF);
14264
+ const footerBytes = textEncoder.encode("--" + boundary + "--" + CRLF);
14248
14265
  let contentLength = footerBytes.byteLength;
14249
14266
  const parts = Array.from(form.entries()).map(([name, value]) => {
14250
14267
  const part = new FormDataPart(name, value);
@@ -14552,7 +14569,7 @@ var http_default = isHttpAdapterSupported && function httpAdapter(config2) {
14552
14569
  config2.signal.aborted ? abort() : config2.signal.addEventListener("abort", abort);
14553
14570
  }
14554
14571
  }
14555
- const fullPath = buildFullPath(config2.baseURL, config2.url);
14572
+ const fullPath = buildFullPath(config2.baseURL, config2.url, config2.allowAbsoluteUrls);
14556
14573
  const parsed = new URL(fullPath, platform_default.hasBrowserEnv ? platform_default.origin : void 0);
14557
14574
  const protocol = parsed.protocol || supportedProtocols[0];
14558
14575
  if (protocol === "data:") {
@@ -15044,7 +15061,7 @@ var resolveConfig_default = (config2) => {
15044
15061
  const newConfig = mergeConfig({}, config2);
15045
15062
  let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig;
15046
15063
  newConfig.headers = headers = AxiosHeaders_default.from(headers);
15047
- newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config2.params, config2.paramsSerializer);
15064
+ newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls), config2.params, config2.paramsSerializer);
15048
15065
  if (auth) {
15049
15066
  headers.set(
15050
15067
  "Authorization",
@@ -15274,7 +15291,7 @@ var readStream = async function* (stream4) {
15274
15291
  }
15275
15292
  };
15276
15293
  var trackStream = (stream4, chunkSize, onProgress, onFinish) => {
15277
- const iterator = readBytes(stream4, chunkSize);
15294
+ const iterator2 = readBytes(stream4, chunkSize);
15278
15295
  let bytes = 0;
15279
15296
  let done;
15280
15297
  let _onFinish = (e) => {
@@ -15286,7 +15303,7 @@ var trackStream = (stream4, chunkSize, onProgress, onFinish) => {
15286
15303
  return new ReadableStream({
15287
15304
  async pull(controller) {
15288
15305
  try {
15289
- const { done: done2, value } = await iterator.next();
15306
+ const { done: done2, value } = await iterator2.next();
15290
15307
  if (done2) {
15291
15308
  _onFinish();
15292
15309
  controller.close();
@@ -15305,7 +15322,7 @@ var trackStream = (stream4, chunkSize, onProgress, onFinish) => {
15305
15322
  },
15306
15323
  cancel(reason) {
15307
15324
  _onFinish(reason);
15308
- return iterator.return();
15325
+ return iterator2.return();
15309
15326
  }
15310
15327
  }, {
15311
15328
  highWaterMark: 2
@@ -15464,7 +15481,7 @@ var fetch_default = isFetchSupported && (async (config2) => {
15464
15481
  });
15465
15482
  } catch (err) {
15466
15483
  unsubscribe && unsubscribe();
15467
- if (err && err.name === "TypeError" && /fetch/i.test(err.message)) {
15484
+ if (err && err.name === "TypeError" && /Load failed|fetch/i.test(err.message)) {
15468
15485
  throw Object.assign(
15469
15486
  new AxiosError_default("Network Error", AxiosError_default.ERR_NETWORK, config2, request),
15470
15487
  {
@@ -15643,7 +15660,7 @@ var validator_default = {
15643
15660
  var validators2 = validator_default.validators;
15644
15661
  var Axios = class {
15645
15662
  constructor(instanceConfig) {
15646
- this.defaults = instanceConfig;
15663
+ this.defaults = instanceConfig || {};
15647
15664
  this.interceptors = {
15648
15665
  request: new InterceptorManager_default(),
15649
15666
  response: new InterceptorManager_default()
@@ -15705,6 +15722,12 @@ var Axios = class {
15705
15722
  }, true);
15706
15723
  }
15707
15724
  }
15725
+ if (config2.allowAbsoluteUrls !== void 0) {
15726
+ } else if (this.defaults.allowAbsoluteUrls !== void 0) {
15727
+ config2.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls;
15728
+ } else {
15729
+ config2.allowAbsoluteUrls = true;
15730
+ }
15708
15731
  validator_default.assertOptions(config2, {
15709
15732
  baseUrl: validators2.spelling("baseURL"),
15710
15733
  withXsrfToken: validators2.spelling("withXSRFToken")
@@ -15775,7 +15798,7 @@ var Axios = class {
15775
15798
  }
15776
15799
  getUri(config2) {
15777
15800
  config2 = mergeConfig(this.defaults, config2);
15778
- const fullPath = buildFullPath(config2.baseURL, config2.url);
15801
+ const fullPath = buildFullPath(config2.baseURL, config2.url, config2.allowAbsoluteUrls);
15779
15802
  return buildURL(fullPath, config2.params, config2.paramsSerializer);
15780
15803
  }
15781
15804
  };
@@ -16167,7 +16190,8 @@ var TPaymentMethod = z2.enum([
16167
16190
  "VIRTUAL_ACCOUNT",
16168
16191
  "EWALLET",
16169
16192
  "OVER_THE_COUNTER",
16170
- "QR_CODE"
16193
+ "QR_CODE",
16194
+ "PAYPAL"
16171
16195
  ]);
16172
16196
  var TPaymentMetadata = z2.object({
16173
16197
  userId: z2.union([z2.string().length(24), z2.instanceof(ObjectId10)]).optional(),
@@ -16403,7 +16427,6 @@ function useXenditService() {
16403
16427
  });
16404
16428
  return res.data;
16405
16429
  } catch (error) {
16406
- console.log(error);
16407
16430
  throw new BadRequestError9(
16408
16431
  "Failed to initiate GCash linking and payment request."
16409
16432
  );
@@ -16437,7 +16460,6 @@ function useXenditService() {
16437
16460
  });
16438
16461
  return res.data;
16439
16462
  } catch (error) {
16440
- console.log(error);
16441
16463
  throw new BadRequestError9(
16442
16464
  "Failed to initiate GCash linking and payment request."
16443
16465
  );
@@ -16490,7 +16512,6 @@ function useXenditService() {
16490
16512
  });
16491
16513
  return res.data;
16492
16514
  } catch (error) {
16493
- console.log(error);
16494
16515
  throw new BadRequestError9("Failed to create subscription.");
16495
16516
  }
16496
16517
  }
@@ -16614,7 +16635,29 @@ function useXenditService() {
16614
16635
  const res = await axios2.post("/v2/payment_methods", value);
16615
16636
  return res.data;
16616
16637
  } catch (error) {
16617
- throw new BadRequestError9("Failed to link payment method.");
16638
+ throw new BadRequestError9(
16639
+ error.response.data.message ?? "Failed to link payment method."
16640
+ );
16641
+ }
16642
+ }
16643
+ async function getPaymentMethodsByCustomerId(customerId) {
16644
+ try {
16645
+ const res = await axios2.get("/v2/payment_methods", {
16646
+ params: { customer_id: customerId, status: "ACTIVE" }
16647
+ });
16648
+ return res.data;
16649
+ } catch (error) {
16650
+ throw new BadRequestError9("Failed to get payment methods.");
16651
+ }
16652
+ }
16653
+ async function updatePaymentMethodStatusById(id, status) {
16654
+ try {
16655
+ const res = await axios2.patch(`/v2/payment_methods/${id}`, {
16656
+ status
16657
+ });
16658
+ return res.data;
16659
+ } catch (error) {
16660
+ throw new BadRequestError9("Failed to update status payment methods.");
16618
16661
  }
16619
16662
  }
16620
16663
  return {
@@ -16633,7 +16676,9 @@ function useXenditService() {
16633
16676
  getCustomerById,
16634
16677
  eWalletLinkOnly,
16635
16678
  directDebitLinkOnly,
16636
- cardLinkOnly
16679
+ cardLinkOnly,
16680
+ getPaymentMethodsByCustomerId,
16681
+ updatePaymentMethodStatusById
16637
16682
  };
16638
16683
  }
16639
16684
 
@@ -18026,7 +18071,6 @@ function useRoleController() {
18026
18071
  res.json(data);
18027
18072
  return;
18028
18073
  } catch (error2) {
18029
- console.log(error2);
18030
18074
  next(error2);
18031
18075
  }
18032
18076
  }
@@ -18350,7 +18394,6 @@ function useEntityController() {
18350
18394
  res.json({ message: "Successfully created entity.", id });
18351
18395
  return;
18352
18396
  } catch (error2) {
18353
- console.log(error2);
18354
18397
  next(error2);
18355
18398
  return;
18356
18399
  }
@@ -19682,8 +19725,8 @@ function MSubscription(value) {
19682
19725
  _id: Joi12.string().hex().optional().allow("", null),
19683
19726
  user: Joi12.string().hex().optional().allow("", null),
19684
19727
  org: Joi12.string().hex().optional().allow("", null),
19685
- customerId: Joi12.string().required(),
19686
- paymentMethodId: Joi12.string().required(),
19728
+ customerId: Joi12.string().optional(),
19729
+ paymentMethodId: Joi12.string().optional(),
19687
19730
  amount: Joi12.number().min(0).required(),
19688
19731
  currency: Joi12.string().required(),
19689
19732
  description: Joi12.string().optional().allow("", null),
@@ -19700,7 +19743,7 @@ function MSubscription(value) {
19700
19743
  addedAt: Joi12.date().optional(),
19701
19744
  email: Joi12.string().email().required()
19702
19745
  })
19703
- ).optional().allow([]),
19746
+ ).optional(),
19704
19747
  nextBillingDate: Joi12.date().optional(),
19705
19748
  lastPaymentStatus: Joi12.string().optional().allow("", null),
19706
19749
  failedAttempts: Joi12.number().optional().allow("", null),
@@ -19737,8 +19780,8 @@ function MSubscription(value) {
19737
19780
  _id: value._id,
19738
19781
  user: value.user ?? "",
19739
19782
  org: value.org ?? "",
19740
- customerId: value.customerId,
19741
- paymentMethodId: value.paymentMethodId,
19783
+ customerId: value.customerId ?? "",
19784
+ paymentMethodId: value.paymentMethodId ?? "",
19742
19785
  amount: value.amount,
19743
19786
  currency: value.currency,
19744
19787
  description: value.description ?? "",
@@ -19802,7 +19845,6 @@ function useSubscriptionRepo() {
19802
19845
  const res = await collection.insertOne(value, { session });
19803
19846
  return res.insertedId;
19804
19847
  } catch (error) {
19805
- console.log(error);
19806
19848
  throw new BadRequestError24("Failed to create subscription.");
19807
19849
  }
19808
19850
  }
@@ -20614,8 +20656,19 @@ function useAddressRepo() {
20614
20656
  } catch (error) {
20615
20657
  throw new BadRequestError28("Invalid address ID.");
20616
20658
  }
20659
+ if (value.org) {
20660
+ try {
20661
+ value.org = new ObjectId28(value.org);
20662
+ } catch (error) {
20663
+ throw new BadRequestError28("Invalid org ID.");
20664
+ }
20665
+ }
20617
20666
  try {
20618
- await collection.updateOne({ _id }, { $set: value }, { session });
20667
+ await collection.updateOne(
20668
+ { _id },
20669
+ { $set: value },
20670
+ { session, upsert: true }
20671
+ );
20619
20672
  return "Successfully updated address.";
20620
20673
  } catch (error) {
20621
20674
  throw new BadRequestError28("Failed to update address.");
@@ -20901,6 +20954,7 @@ var TInvoiceItem = z4.object({
20901
20954
  total: z4.number().min(0, { message: "Total amount must be at least 0." })
20902
20955
  });
20903
20956
  var TInvoiceMetadata = z4.object({
20957
+ transactionId: z4.string().optional(),
20904
20958
  userId: z4.union([z4.string().length(24), z4.instanceof(ObjectId30)]).optional(),
20905
20959
  orgId: z4.union([z4.string().length(24), z4.instanceof(ObjectId30)]).optional(),
20906
20960
  billingCycle: z4.enum(["monthly", "yearly", "quarterly"], {
@@ -21270,7 +21324,6 @@ function usePaymentRepo() {
21270
21324
  value = createPayment(value);
21271
21325
  await collection.insertOne(value, { session });
21272
21326
  } catch (error) {
21273
- console.log(error.issues[0].path);
21274
21327
  logger15.log({ level: "error", message: `${error}` });
21275
21328
  const isDuplicated = error.message.includes("duplicate");
21276
21329
  if (isDuplicated) {
@@ -21454,7 +21507,6 @@ function usePriceRepo() {
21454
21507
  }
21455
21508
 
21456
21509
  // src/services/subscription.service.ts
21457
- import { ObjectId as ObjectId35 } from "mongodb";
21458
21510
  function useSubscriptionService() {
21459
21511
  const {
21460
21512
  getByUserId: _getByUserId,
@@ -21489,6 +21541,7 @@ function useSubscriptionService() {
21489
21541
  const { add: addPayment } = usePaymentRepo();
21490
21542
  const { getByType, incrementByType } = useCounterRepo();
21491
21543
  const { getByNameType } = usePriceRepo();
21544
+ const { getByNumber } = useInvoiceRepo();
21492
21545
  function calculateTieredPricing(seats, tiers, prorationFactor = 1) {
21493
21546
  let totalCost = 0;
21494
21547
  let nonProratedCost = 0;
@@ -21519,6 +21572,169 @@ function useSubscriptionService() {
21519
21572
  nonProratedCost: formatAmount(nonProratedCost)
21520
21573
  };
21521
21574
  }
21575
+ async function subscribe(value) {
21576
+ const session = useAtlas23.getClient()?.startSession();
21577
+ session?.startTransaction();
21578
+ try {
21579
+ const _user = await _getUserByUserId(value.user);
21580
+ if (!_user) {
21581
+ throw new BadRequestError36("User not found.");
21582
+ }
21583
+ const orgId = await addOrg(value.org, session);
21584
+ const role = await addRole(
21585
+ {
21586
+ org: orgId.toString(),
21587
+ name: "owner",
21588
+ permissions: ["*"],
21589
+ type: "organization",
21590
+ default: true
21591
+ },
21592
+ session
21593
+ );
21594
+ await addMember(
21595
+ {
21596
+ org: orgId.toString(),
21597
+ orgName: value.org.name,
21598
+ user: value.user,
21599
+ name: `${_user.firstName} ${_user.lastName}`,
21600
+ role: role.toString(),
21601
+ type: "organization"
21602
+ },
21603
+ session
21604
+ );
21605
+ if (!_user.defaultOrg) {
21606
+ await updateUserFieldById(
21607
+ {
21608
+ _id: value.user,
21609
+ field: "defaultOrg",
21610
+ value: orgId.toString()
21611
+ },
21612
+ session
21613
+ );
21614
+ }
21615
+ const description = "GoWeekdays Organization Monthly Subscription.";
21616
+ if (value.promoCode) {
21617
+ await assignByUserId(
21618
+ { user: value.user, code: value.promoCode },
21619
+ session
21620
+ );
21621
+ }
21622
+ const monthlySubscriptionPrice = await getByNameType(
21623
+ "organization-subscription",
21624
+ "monthly-subscription"
21625
+ );
21626
+ if (!monthlySubscriptionPrice) {
21627
+ throw new BadRequestError36(
21628
+ "Failed to fetch monthly subscription price."
21629
+ );
21630
+ }
21631
+ let amount = monthlySubscriptionPrice.value;
21632
+ const items = [];
21633
+ if (value.promoCode) {
21634
+ const promoCode = await getByCode(value.promoCode);
21635
+ if (!promoCode) {
21636
+ throw new BadRequestError36("Promo code not found.");
21637
+ }
21638
+ if (promoCode && promoCode.type === "fixed" && promoCode.fixed_rate !== void 0 && promoCode.fixed_rate >= 0) {
21639
+ amount = promoCode.fixed_rate;
21640
+ items.push({
21641
+ description: "GoWeekdays Monthly Subscription",
21642
+ unitPrice: promoCode.fixed_rate,
21643
+ quantity: 1,
21644
+ seats: value.seats,
21645
+ total: promoCode.fixed_rate * value.seats
21646
+ });
21647
+ }
21648
+ if (promoCode && promoCode.type === "tiered" && promoCode.tiers && promoCode.tiers.length) {
21649
+ const computedTieredInvoice = calculateTieredPricing(
21650
+ value.seats,
21651
+ promoCode.tiers
21652
+ );
21653
+ items.push(...computedTieredInvoice.items);
21654
+ amount = computedTieredInvoice.totalCost;
21655
+ }
21656
+ }
21657
+ if (monthlySubscriptionPrice.saleValue && monthlySubscriptionPrice.saleExpiry && new Date(monthlySubscriptionPrice.saleExpiry) > /* @__PURE__ */ new Date()) {
21658
+ amount = monthlySubscriptionPrice.saleValue;
21659
+ }
21660
+ const subscription = await add(
21661
+ {
21662
+ org: orgId.toString(),
21663
+ amount,
21664
+ currency: value.currency,
21665
+ type: "organization",
21666
+ description,
21667
+ paidSeats: value.seats,
21668
+ currentSeats: value.seats,
21669
+ maxSeats: value.seats,
21670
+ billingCycle: "monthly",
21671
+ promoCode: value.promoCode
21672
+ },
21673
+ session
21674
+ );
21675
+ const invoiceCounter = await getByType("invoice");
21676
+ if (!invoiceCounter) {
21677
+ throw new BadRequestError36("Failed to fetch invoice counter.");
21678
+ }
21679
+ const date = /* @__PURE__ */ new Date();
21680
+ const mm = String(date.getMonth() + 1).padStart(2, "0");
21681
+ const dd = String(date.getDate()).padStart(2, "0");
21682
+ const yyyy = date.getFullYear();
21683
+ const formattedDate = `${mm}-${dd}-${yyyy}`;
21684
+ const invoiceNumber = `inv-${formattedDate}-${invoiceCounter.count + 1}`;
21685
+ const invoiceData = {
21686
+ type: "organization-subscription",
21687
+ invoiceNumber,
21688
+ amount,
21689
+ dueDate: /* @__PURE__ */ new Date(),
21690
+ metadata: {
21691
+ transactionId: value.transactionId,
21692
+ orgId: orgId.toString(),
21693
+ currency: value.currency,
21694
+ subscriptionId: subscription.toString(),
21695
+ description: `Initial invoice for ${value.seats.toLocaleString()} seats`
21696
+ },
21697
+ status: "paid",
21698
+ items: items && items.length ? items : [
21699
+ {
21700
+ description: "GoWeekdays Monthly Subscription",
21701
+ unitPrice: amount,
21702
+ quantity: 1,
21703
+ seats: value.seats,
21704
+ total: amount * value.seats
21705
+ }
21706
+ ]
21707
+ };
21708
+ await addInvoice(invoiceData, session);
21709
+ await incrementByType("invoice", session);
21710
+ await addPayment(
21711
+ {
21712
+ invoiceId: invoiceNumber,
21713
+ amount,
21714
+ paymentMethod: "PAYPAL",
21715
+ status: "completed",
21716
+ metadata: {
21717
+ userId: value.user,
21718
+ orgId: orgId.toString(),
21719
+ currency: value.currency,
21720
+ payment: value.transactionId,
21721
+ subscriptionId: subscription.toString()
21722
+ }
21723
+ },
21724
+ session
21725
+ );
21726
+ await session?.commitTransaction();
21727
+ return {
21728
+ message: "Subscription created successfully.",
21729
+ data: { org: orgId.toString() }
21730
+ };
21731
+ } catch (error) {
21732
+ await session?.abortTransaction();
21733
+ throw error;
21734
+ } finally {
21735
+ session?.endSession();
21736
+ }
21737
+ }
21522
21738
  async function createOrgSubscription(value) {
21523
21739
  const session = useAtlas23.getClient()?.startSession();
21524
21740
  session?.startTransaction();
@@ -21527,11 +21743,9 @@ function useSubscriptionService() {
21527
21743
  if (!_user) {
21528
21744
  throw new BadRequestError36("User not found.");
21529
21745
  }
21530
- value.organization._id = new ObjectId35();
21531
- await addOrg(value.organization, session);
21532
- console.log("value.organization._id", value.organization._id);
21746
+ const orgId = await addOrg(value.organization, session);
21533
21747
  const customerData = {
21534
- reference_id: value.organization._id.toString(),
21748
+ reference_id: orgId.toString(),
21535
21749
  type: value.organization.type === "business" ? "BUSINESS" : "INDIVIDUAL",
21536
21750
  email: value.organization.email
21537
21751
  };
@@ -21552,7 +21766,7 @@ function useSubscriptionService() {
21552
21766
  }
21553
21767
  const role = await addRole(
21554
21768
  {
21555
- org: value.organization._id.toString(),
21769
+ org: orgId.toString(),
21556
21770
  name: "owner",
21557
21771
  permissions: ["*"],
21558
21772
  type: "organization",
@@ -21562,7 +21776,7 @@ function useSubscriptionService() {
21562
21776
  );
21563
21777
  await addMember(
21564
21778
  {
21565
- org: value.organization._id.toString(),
21779
+ org: orgId.toString(),
21566
21780
  orgName: value.organization.name,
21567
21781
  user: value.user,
21568
21782
  name: `${_user.firstName} ${_user.lastName}`,
@@ -21576,7 +21790,7 @@ function useSubscriptionService() {
21576
21790
  {
21577
21791
  _id: value.user,
21578
21792
  field: "defaultOrg",
21579
- value: value.organization._id.toString()
21793
+ value: orgId.toString()
21580
21794
  },
21581
21795
  session
21582
21796
  );
@@ -21585,7 +21799,7 @@ function useSubscriptionService() {
21585
21799
  if (!customer.id) {
21586
21800
  throw new BadRequestError36("Xendit customer account required.");
21587
21801
  }
21588
- value.billingAddress.org = value.organization._id.toString();
21802
+ value.billingAddress.org = orgId.toString();
21589
21803
  await addAddress(value.billingAddress, session);
21590
21804
  const description = "GoWeekdays Organization Monthly Subscription.";
21591
21805
  if (value.promoCode) {
@@ -21634,7 +21848,7 @@ function useSubscriptionService() {
21634
21848
  }
21635
21849
  const subscription = await add(
21636
21850
  {
21637
- org: value.organization._id.toString(),
21851
+ org: orgId.toString(),
21638
21852
  customerId,
21639
21853
  paymentMethodId: value.payment_method_id,
21640
21854
  amount,
@@ -21665,7 +21879,7 @@ function useSubscriptionService() {
21665
21879
  amount,
21666
21880
  dueDate: /* @__PURE__ */ new Date(),
21667
21881
  metadata: {
21668
- orgId: value.organization._id.toString(),
21882
+ orgId: orgId.toString(),
21669
21883
  currency: value.currency,
21670
21884
  subscriptionId: subscription.toString(),
21671
21885
  description: `Initial invoice for ${value.seats.toLocaleString()} seats`
@@ -21701,7 +21915,7 @@ function useSubscriptionService() {
21701
21915
  status: "completed",
21702
21916
  metadata: {
21703
21917
  userId: value.user,
21704
- orgId: value.organization._id.toString(),
21918
+ orgId: orgId.toString(),
21705
21919
  currency: value.currency,
21706
21920
  paymentMethod: value.payment_method_channel,
21707
21921
  paymentMethodType: value.payment_method_type,
@@ -21715,7 +21929,7 @@ function useSubscriptionService() {
21715
21929
  await session?.commitTransaction();
21716
21930
  return {
21717
21931
  message: "Subscription created successfully.",
21718
- data: { org: value.organization._id.toString() }
21932
+ data: { org: orgId.toString() }
21719
21933
  };
21720
21934
  } catch (error) {
21721
21935
  await session?.abortTransaction();
@@ -21981,8 +22195,8 @@ function useSubscriptionService() {
21981
22195
  session?.startTransaction();
21982
22196
  try {
21983
22197
  const payment = await pay({
21984
- customer_id: sub.customerId,
21985
- payment_method_id: sub.paymentMethodId,
22198
+ customer_id: sub.customerId ?? "",
22199
+ payment_method_id: sub.paymentMethodId ?? "",
21986
22200
  amount: sub.amount,
21987
22201
  currency: sub.currency,
21988
22202
  description
@@ -21991,7 +22205,7 @@ function useSubscriptionService() {
21991
22205
  throw new BadRequestError36("Failed to process payment.");
21992
22206
  }
21993
22207
  const customerPaymentMethod = await getPaymentMethodById(
21994
- sub.paymentMethodId
22208
+ sub.paymentMethodId ?? ""
21995
22209
  );
21996
22210
  const paymentData = {
21997
22211
  invoiceId: invoiceNumber,
@@ -22283,15 +22497,15 @@ function useSubscriptionService() {
22283
22497
  let payment = {};
22284
22498
  if (amount) {
22285
22499
  payment = await pay({
22286
- customer_id: subscription.customerId,
22287
- payment_method_id: subscription.paymentMethodId,
22500
+ customer_id: subscription.customerId ?? "",
22501
+ payment_method_id: subscription.paymentMethodId ?? "",
22288
22502
  amount: formatAmount(amount),
22289
22503
  currency: subscription.currency,
22290
22504
  description: "GoWeekdays Organization Monthly Subscription."
22291
22505
  });
22292
22506
  }
22293
22507
  const paymentMethod = await getPaymentMethodById(
22294
- subscription.paymentMethodId
22508
+ subscription.paymentMethodId ?? ""
22295
22509
  );
22296
22510
  if (!paymentMethod) {
22297
22511
  throw new BadRequestError36("Payment method not found.");
@@ -22368,13 +22582,116 @@ function useSubscriptionService() {
22368
22582
  session?.endSession();
22369
22583
  }
22370
22584
  }
22585
+ async function processSubscriptionPayment(invoiceNumber, subscriptionId) {
22586
+ const invoice = await getByNumber(invoiceNumber);
22587
+ if (!invoice) {
22588
+ throw new BadRequestError36("Invoice not found.");
22589
+ }
22590
+ if (invoice.status === "paid") {
22591
+ throw new BadRequestError36("Invoice already paid.");
22592
+ }
22593
+ if (!invoice._id) {
22594
+ throw new BadRequestError36("Invoice ID is missing.");
22595
+ }
22596
+ if (!invoice.metadata?.subscriptionId) {
22597
+ throw new BadRequestError36("Subscription ID is missing.");
22598
+ }
22599
+ if (invoice.metadata.subscriptionId.toString() !== subscriptionId) {
22600
+ throw new BadRequestError36("Subscription ID does not match invoice.");
22601
+ }
22602
+ const subscription = await _getById(invoice.metadata.subscriptionId);
22603
+ if (!subscription) {
22604
+ throw new BadRequestError36("Subscription not found.");
22605
+ }
22606
+ if (!subscription._id) {
22607
+ throw new BadRequestError36("Subscription ID is missing.");
22608
+ }
22609
+ if (!subscription.customerId) {
22610
+ throw new BadRequestError36("Customer ID is missing.");
22611
+ }
22612
+ if (!subscription.paymentMethodId) {
22613
+ throw new BadRequestError36("Payment method ID is missing.");
22614
+ }
22615
+ if (!subscription.amount) {
22616
+ throw new BadRequestError36("Subscription amount is missing.");
22617
+ }
22618
+ if (!subscription.currency) {
22619
+ throw new BadRequestError36("Subscription currency is missing.");
22620
+ }
22621
+ const session = useAtlas23.getClient()?.startSession();
22622
+ try {
22623
+ session?.startTransaction();
22624
+ const payment = await pay({
22625
+ customer_id: subscription.customerId,
22626
+ payment_method_id: subscription.paymentMethodId,
22627
+ amount: subscription.amount,
22628
+ currency: subscription.currency,
22629
+ description: "GoWeekdays Subscription Payment"
22630
+ });
22631
+ if (!payment.id) {
22632
+ throw new BadRequestError36("Failed to process payment.");
22633
+ }
22634
+ const paymentMethod = await getPaymentMethodById(
22635
+ subscription.paymentMethodId
22636
+ );
22637
+ if (!paymentMethod) {
22638
+ throw new BadRequestError36("Payment method not found.");
22639
+ }
22640
+ const paymentData = {
22641
+ invoiceId: invoiceNumber,
22642
+ amount: subscription.amount,
22643
+ paymentMethod: paymentMethod.type,
22644
+ status: "completed",
22645
+ metadata: {
22646
+ userId: String(subscription.user),
22647
+ orgId: String(subscription.org),
22648
+ currency: subscription.currency,
22649
+ paymentMethod: paymentMethod.type === "EWALLET" ? paymentMethod.ewallet.channel_code : paymentMethod.type === "DIRECT_DEBIT" ? paymentMethod.direct_debit.channel_code : "",
22650
+ paymentMethodType: paymentMethod.type,
22651
+ paymentMethodId: subscription.paymentMethodId,
22652
+ payment: payment.id,
22653
+ subscriptionId: subscription._id.toString()
22654
+ }
22655
+ };
22656
+ if (!paymentData.metadata.userId) {
22657
+ delete paymentData.metadata.userId;
22658
+ }
22659
+ if (!paymentData.metadata.orgId) {
22660
+ delete paymentData.metadata.orgId;
22661
+ }
22662
+ await addPayment(paymentData, session);
22663
+ await updateStatusByInvoiceNumber(invoiceNumber, "paid", session);
22664
+ await processSuccessfulPayment(
22665
+ {
22666
+ _id: subscription._id.toString(),
22667
+ nextBillingDate: subscription.nextBillingDate
22668
+ },
22669
+ session
22670
+ );
22671
+ await session?.commitTransaction();
22672
+ } catch (error) {
22673
+ await session?.abortTransaction();
22674
+ logger16.log({
22675
+ level: "error",
22676
+ message: `Failed to process subscription payment: ${error}`
22677
+ });
22678
+ if (error instanceof AppError9) {
22679
+ throw error;
22680
+ }
22681
+ throw new BadRequestError36("Failed to process subscription payment.");
22682
+ } finally {
22683
+ session?.endSession();
22684
+ }
22685
+ }
22371
22686
  return {
22687
+ subscribe,
22372
22688
  getByUserId,
22373
22689
  getStatusByUser,
22374
22690
  createAffiliateSubscription,
22375
22691
  createOrgSubscription,
22376
22692
  processSubscriptions,
22377
- updateSeatsById
22693
+ updateSeatsById,
22694
+ processSubscriptionPayment
22378
22695
  };
22379
22696
  }
22380
22697
 
@@ -22442,8 +22759,39 @@ function useSubscriptionController() {
22442
22759
  getStatusByUser: _getStatusByUser,
22443
22760
  createAffiliateSubscription: _createAffiliateSubscription,
22444
22761
  createOrgSubscription: _createOrgSubscription,
22445
- updateSeatsById: _updateSubscriptionSeats
22762
+ updateSeatsById: _updateSubscriptionSeats,
22763
+ processSubscriptionPayment: _processSubscriptionPayment,
22764
+ subscribe: _subscribe
22446
22765
  } = useSubscriptionService();
22766
+ async function subscribe(req, res, next) {
22767
+ const value = req.body;
22768
+ const validation = Joi20.object({
22769
+ user: Joi20.string().hex().required(),
22770
+ transactionId: Joi20.string().required(),
22771
+ promoCode: Joi20.string().optional().allow("", null),
22772
+ seats: Joi20.number().min(1).required(),
22773
+ perSeatPrice: Joi20.number().min(0).required(),
22774
+ currency: Joi20.string().required(),
22775
+ org: Joi20.object({
22776
+ name: Joi20.string().required(),
22777
+ email: Joi20.string().email().required(),
22778
+ contact: Joi20.string().optional().allow("", null),
22779
+ busInst: Joi20.string().optional().allow("", null),
22780
+ type: Joi20.string().valid("personal", "business").required()
22781
+ })
22782
+ });
22783
+ const { error } = validation.validate(value);
22784
+ if (error) {
22785
+ next(new BadRequestError37(error.message));
22786
+ }
22787
+ try {
22788
+ const id = await _subscribe(value);
22789
+ res.json({ message: "Successfully subscribed.", id });
22790
+ return;
22791
+ } catch (error2) {
22792
+ next(error2);
22793
+ }
22794
+ }
22447
22795
  async function add(req, res, next) {
22448
22796
  const value = req.body;
22449
22797
  const validation = Joi20.object({
@@ -22573,7 +22921,6 @@ function useSubscriptionController() {
22573
22921
  res.json({ message: "Successfully added subscription.", id });
22574
22922
  return;
22575
22923
  } catch (error2) {
22576
- console.log(error2);
22577
22924
  next(error2);
22578
22925
  return;
22579
22926
  }
@@ -22741,7 +23088,28 @@ function useSubscriptionController() {
22741
23088
  return;
22742
23089
  }
22743
23090
  }
23091
+ async function processSubscriptionPayment(req, res, next) {
23092
+ const id = req.params.id ?? "";
23093
+ const invoiceNumber = req.body.invoice ?? "";
23094
+ const { error } = Joi20.object({
23095
+ id: Joi20.string().hex().required(),
23096
+ invoiceNumber: Joi20.string().required()
23097
+ }).validate({ id, invoiceNumber });
23098
+ if (error) {
23099
+ next(new BadRequestError37(error.message));
23100
+ return;
23101
+ }
23102
+ try {
23103
+ const payment = await _processSubscriptionPayment(invoiceNumber, id);
23104
+ res.json(payment);
23105
+ return;
23106
+ } catch (error2) {
23107
+ next(error2);
23108
+ return;
23109
+ }
23110
+ }
22744
23111
  return {
23112
+ subscribe,
22745
23113
  add,
22746
23114
  getByUserId,
22747
23115
  getByOrgId,
@@ -22757,30 +23125,31 @@ function useSubscriptionController() {
22757
23125
  updatePaymentMethodById,
22758
23126
  addBillingContactById,
22759
23127
  updateBillingContactByAddedAt,
22760
- deleteBillingContactByAddedAt
23128
+ deleteBillingContactByAddedAt,
23129
+ processSubscriptionPayment
22761
23130
  };
22762
23131
  }
22763
23132
 
22764
23133
  // src/models/payment-method.model.ts
22765
23134
  import { BadRequestError as BadRequestError38 } from "@goweekdays/utils";
22766
- import { ObjectId as ObjectId36 } from "mongodb";
23135
+ import { ObjectId as ObjectId35 } from "mongodb";
22767
23136
  function MPaymentMethod(value) {
22768
23137
  if (value.user) {
22769
23138
  try {
22770
- value.user = new ObjectId36(value.user);
23139
+ value.user = new ObjectId35(value.user);
22771
23140
  } catch (error) {
22772
23141
  throw new BadRequestError38("Invalid user ID.");
22773
23142
  }
22774
23143
  }
22775
23144
  if (value.org) {
22776
23145
  try {
22777
- value.org = new ObjectId36(value.org);
23146
+ value.org = new ObjectId35(value.org);
22778
23147
  } catch (error) {
22779
23148
  throw new BadRequestError38("Invalid org ID.");
22780
23149
  }
22781
23150
  }
22782
23151
  return {
22783
- _id: value._id ?? new ObjectId36(),
23152
+ _id: value._id ?? new ObjectId35(),
22784
23153
  user: value.user ?? "",
22785
23154
  org: value.org ?? "",
22786
23155
  name: value.name,
@@ -22805,7 +23174,7 @@ import {
22805
23174
  logger as logger17,
22806
23175
  useAtlas as useAtlas24
22807
23176
  } from "@goweekdays/utils";
22808
- import { ObjectId as ObjectId37 } from "mongodb";
23177
+ import { ObjectId as ObjectId36 } from "mongodb";
22809
23178
  function usePaymentMethodRepo() {
22810
23179
  const db = useAtlas24.getDb();
22811
23180
  if (!db) {
@@ -22858,7 +23227,7 @@ function usePaymentMethodRepo() {
22858
23227
  }
22859
23228
  function getByUser(user) {
22860
23229
  try {
22861
- user = new ObjectId37(user);
23230
+ user = new ObjectId36(user);
22862
23231
  } catch (error) {
22863
23232
  throw new BadRequestError39("Invalid user ID.");
22864
23233
  }
@@ -22883,7 +23252,7 @@ function usePaymentMethodRepo() {
22883
23252
  }
22884
23253
  function getByOrg(org) {
22885
23254
  try {
22886
- org = new ObjectId37(org);
23255
+ org = new ObjectId36(org);
22887
23256
  } catch (error) {
22888
23257
  throw new BadRequestError39("Invalid org ID.");
22889
23258
  }
@@ -22918,7 +23287,7 @@ function usePaymentMethodRepo() {
22918
23287
  }
22919
23288
  async function deleteById(_id) {
22920
23289
  try {
22921
- _id = new ObjectId37(_id);
23290
+ _id = new ObjectId36(_id);
22922
23291
  } catch (error) {
22923
23292
  throw new BadRequestError39("Invalid payment method ID.");
22924
23293
  }
@@ -23062,7 +23431,6 @@ function usePaymentMethodService() {
23062
23431
  await session?.commitTransaction();
23063
23432
  return result;
23064
23433
  } catch (error) {
23065
- console.log(error);
23066
23434
  await session?.abortTransaction();
23067
23435
  throw error;
23068
23436
  } finally {
@@ -23084,7 +23452,9 @@ function usePaymentMethodController() {
23084
23452
  cardLinkOnly,
23085
23453
  directDebitLinkOnly,
23086
23454
  eWalletLinkOnly,
23087
- getPaymentMethodById: _getPaymentMethodById
23455
+ getPaymentMethodById: _getPaymentMethodById,
23456
+ getPaymentMethodsByCustomerId: _getPaymentMethodsByCustomerId,
23457
+ updatePaymentMethodStatusById: _updatePaymentMethodStatusById
23088
23458
  } = useXenditService();
23089
23459
  async function linkEWallet(req, res, next) {
23090
23460
  const type = req.body.type ?? "";
@@ -23234,7 +23604,7 @@ function usePaymentMethodController() {
23234
23604
  const type = req.body.type ?? "";
23235
23605
  if (type === "CARD") {
23236
23606
  try {
23237
- EWalletPaymentSchema.parse(req.body);
23607
+ CardPaymentSchema.parse(req.body);
23238
23608
  } catch (error) {
23239
23609
  next(new BadRequestError41(error.issues[0].message));
23240
23610
  return;
@@ -23283,13 +23653,49 @@ function usePaymentMethodController() {
23283
23653
  next(new BadRequestError41("Invalid type"));
23284
23654
  return;
23285
23655
  }
23656
+ async function getPaymentMethodsByCustomerId(req, res, next) {
23657
+ const id = req.params.id ?? "";
23658
+ const validation = Joi21.object({
23659
+ id: Joi21.string().required()
23660
+ });
23661
+ const { error } = validation.validate({ id });
23662
+ if (error) {
23663
+ next(new BadRequestError41(error.message));
23664
+ }
23665
+ try {
23666
+ const result = await _getPaymentMethodsByCustomerId(id);
23667
+ res.json(result);
23668
+ } catch (error2) {
23669
+ next(error2);
23670
+ }
23671
+ }
23672
+ async function updatePaymentMethodStatusById(req, res, next) {
23673
+ const id = req.params.id ?? "";
23674
+ const status = req.body.status ?? "";
23675
+ const validation = Joi21.object({
23676
+ id: Joi21.string().required(),
23677
+ status: Joi21.string().valid("ACTIVE", "INACTIVE").required()
23678
+ });
23679
+ const { error } = validation.validate({ id, status });
23680
+ if (error) {
23681
+ next(new BadRequestError41(error.message));
23682
+ }
23683
+ try {
23684
+ const result = await _updatePaymentMethodStatusById(id, status);
23685
+ res.json(result);
23686
+ } catch (error2) {
23687
+ next(error2);
23688
+ }
23689
+ }
23286
23690
  return {
23287
23691
  linkEWallet,
23288
23692
  linkCard,
23289
23693
  getByUser,
23290
23694
  getByOrg,
23291
23695
  linkOnly,
23292
- getPaymentMethodById
23696
+ getPaymentMethodById,
23697
+ getPaymentMethodsByCustomerId,
23698
+ updatePaymentMethodStatusById
23293
23699
  };
23294
23700
  }
23295
23701
 
@@ -23341,7 +23747,8 @@ function useAddressController() {
23341
23747
  city: Joi22.string().required(),
23342
23748
  province: Joi22.string().required(),
23343
23749
  postalCode: Joi22.string().required(),
23344
- taxId: Joi22.string().optional().allow("", null)
23750
+ taxId: Joi22.string().optional().allow("", null),
23751
+ org: Joi22.string().hex().optional().allow("", null)
23345
23752
  });
23346
23753
  const { error } = validation.validate({ id, ...value });
23347
23754
  if (error) {
@@ -23792,7 +24199,7 @@ function usePromoCodeController() {
23792
24199
  }
23793
24200
 
23794
24201
  // src/models/order.model.ts
23795
- import { ObjectId as ObjectId38 } from "mongodb";
24202
+ import { ObjectId as ObjectId37 } from "mongodb";
23796
24203
 
23797
24204
  // src/validations/order.schema.ts
23798
24205
  import Joi26 from "joi";
@@ -23826,28 +24233,28 @@ function MOrder(value) {
23826
24233
  }
23827
24234
  if (value._id) {
23828
24235
  try {
23829
- value._id = new ObjectId38(value._id);
24236
+ value._id = new ObjectId37(value._id);
23830
24237
  } catch (error2) {
23831
24238
  throw new BadRequestError46("Invalid ID.");
23832
24239
  }
23833
24240
  }
23834
24241
  if (value.user) {
23835
24242
  try {
23836
- value.user = new ObjectId38(value.user);
24243
+ value.user = new ObjectId37(value.user);
23837
24244
  } catch (error2) {
23838
24245
  throw new BadRequestError46("Invalid user ID.");
23839
24246
  }
23840
24247
  }
23841
24248
  if (value.org) {
23842
24249
  try {
23843
- value.org = new ObjectId38(value.org);
24250
+ value.org = new ObjectId37(value.org);
23844
24251
  } catch (error2) {
23845
24252
  throw new BadRequestError46("Invalid org ID.");
23846
24253
  }
23847
24254
  }
23848
24255
  if (value.metadata?.subscriptionId) {
23849
24256
  try {
23850
- value.metadata.subscriptionId = new ObjectId38(
24257
+ value.metadata.subscriptionId = new ObjectId37(
23851
24258
  value.metadata.subscriptionId
23852
24259
  );
23853
24260
  } catch (error2) {
@@ -23880,7 +24287,7 @@ import {
23880
24287
  paginate as paginate14,
23881
24288
  useAtlas as useAtlas27
23882
24289
  } from "@goweekdays/utils";
23883
- import { ObjectId as ObjectId39 } from "mongodb";
24290
+ import { ObjectId as ObjectId38 } from "mongodb";
23884
24291
  function useOrderRepo() {
23885
24292
  const db = useAtlas27.getDb();
23886
24293
  if (!db) {
@@ -23930,7 +24337,7 @@ function useOrderRepo() {
23930
24337
  }
23931
24338
  if (id) {
23932
24339
  try {
23933
- query["metadata.subscriptionId"] = new ObjectId39(id);
24340
+ query["metadata.subscriptionId"] = new ObjectId38(id);
23934
24341
  } catch (error) {
23935
24342
  throw new BadRequestError47("Invalid subscription ID.");
23936
24343
  }
@@ -24001,7 +24408,7 @@ function useOrderController() {
24001
24408
  // src/services/invoice.service.ts
24002
24409
  import { BadRequestError as BadRequestError49, logger as logger19, useAtlas as useAtlas28 } from "@goweekdays/utils";
24003
24410
  function useInvoiceService() {
24004
- const { getOverdueInvoices, updateStatusByInvoiceNumber } = useInvoiceRepo();
24411
+ const { getOverdueInvoices, updateStatusByInvoiceNumber, getByNumber } = useInvoiceRepo();
24005
24412
  const {
24006
24413
  getById,
24007
24414
  processSuccessfulPayment,
@@ -24070,8 +24477,8 @@ function useInvoiceService() {
24070
24477
  const internalPayment = await getByInvoiceId(invoice.invoiceNumber);
24071
24478
  if (!internalPayment) {
24072
24479
  const payment = await pay({
24073
- customer_id: subscription.customerId,
24074
- payment_method_id: subscription.paymentMethodId,
24480
+ customer_id: subscription.customerId ?? "",
24481
+ payment_method_id: subscription.paymentMethodId ?? "",
24075
24482
  amount: invoice.amount,
24076
24483
  currency: invoice.metadata?.currency,
24077
24484
  description: invoice.metadata?.description
@@ -24080,7 +24487,7 @@ function useInvoiceService() {
24080
24487
  throw new BadRequestError49("Failed to process payment.");
24081
24488
  }
24082
24489
  const customerPaymentMethod = await getPaymentMethodById(
24083
- subscription.paymentMethodId
24490
+ subscription.paymentMethodId ?? ""
24084
24491
  );
24085
24492
  const paymentData = {
24086
24493
  invoiceId: invoice.invoiceNumber,