@intlayer/backend 5.1.4 → 5.1.6
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/cjs/controllers/ai.controller.cjs +61 -43
- package/dist/cjs/controllers/ai.controller.cjs.map +1 -1
- package/dist/cjs/controllers/dictionary.controller.cjs +8 -12
- package/dist/cjs/controllers/dictionary.controller.cjs.map +1 -1
- package/dist/cjs/controllers/organization.controller.cjs +17 -1
- package/dist/cjs/controllers/organization.controller.cjs.map +1 -1
- package/dist/cjs/controllers/project.controller.cjs +1 -0
- package/dist/cjs/controllers/project.controller.cjs.map +1 -1
- package/dist/cjs/controllers/sessionAuth.controller.cjs +6 -12
- package/dist/cjs/controllers/sessionAuth.controller.cjs.map +1 -1
- package/dist/cjs/controllers/stripe.controller.cjs +31 -10
- package/dist/cjs/controllers/stripe.controller.cjs.map +1 -1
- package/dist/cjs/controllers/tag.controller.cjs +0 -7
- package/dist/cjs/controllers/tag.controller.cjs.map +1 -1
- package/dist/cjs/controllers/user.controller.cjs +1 -1
- package/dist/cjs/controllers/user.controller.cjs.map +1 -1
- package/dist/cjs/emails/InviteUserEmail.cjs +3 -3
- package/dist/cjs/emails/InviteUserEmail.cjs.map +1 -1
- package/dist/cjs/emails/PasswordChangeConfirmation.cjs +3 -3
- package/dist/cjs/emails/PasswordChangeConfirmation.cjs.map +1 -1
- package/dist/cjs/emails/ResetUserPassword.cjs +3 -3
- package/dist/cjs/emails/ResetUserPassword.cjs.map +1 -1
- package/dist/cjs/emails/SubscriptionPaymentCancellation.cjs +19 -3
- package/dist/cjs/emails/SubscriptionPaymentCancellation.cjs.map +1 -1
- package/dist/cjs/emails/SubscriptionPaymentError.cjs +19 -3
- package/dist/cjs/emails/SubscriptionPaymentError.cjs.map +1 -1
- package/dist/cjs/emails/SubscriptionPaymentSuccess.cjs +19 -3
- package/dist/cjs/emails/SubscriptionPaymentSuccess.cjs.map +1 -1
- package/dist/cjs/emails/ValidateUserEmail.cjs +3 -3
- package/dist/cjs/emails/ValidateUserEmail.cjs.map +1 -1
- package/dist/cjs/emails/Welcome.cjs +3 -3
- package/dist/cjs/emails/Welcome.cjs.map +1 -1
- package/dist/cjs/export.cjs +10 -10
- package/dist/cjs/export.cjs.map +1 -1
- package/dist/cjs/routes/ai.routes.cjs +21 -15
- package/dist/cjs/routes/ai.routes.cjs.map +1 -1
- package/dist/cjs/routes/dictionary.routes.cjs +15 -12
- package/dist/cjs/routes/dictionary.routes.cjs.map +1 -1
- package/dist/cjs/routes/event-listener.routes.cjs +4 -4
- package/dist/cjs/routes/event-listener.routes.cjs.map +1 -1
- package/dist/cjs/routes/organization.routes.cjs +15 -15
- package/dist/cjs/routes/organization.routes.cjs.map +1 -1
- package/dist/cjs/routes/project.routes.cjs +30 -18
- package/dist/cjs/routes/project.routes.cjs.map +1 -1
- package/dist/cjs/routes/sessionAuth.routes.cjs +38 -35
- package/dist/cjs/routes/sessionAuth.routes.cjs.map +1 -1
- package/dist/cjs/routes/stripe.routes.cjs +23 -11
- package/dist/cjs/routes/stripe.routes.cjs.map +1 -1
- package/dist/cjs/routes/tags.routes.cjs +11 -11
- package/dist/cjs/routes/tags.routes.cjs.map +1 -1
- package/dist/cjs/routes/user.routes.cjs +13 -13
- package/dist/cjs/routes/user.routes.cjs.map +1 -1
- package/dist/cjs/schemas/dictionary.schema.cjs +0 -4
- package/dist/cjs/schemas/dictionary.schema.cjs.map +1 -1
- package/dist/cjs/schemas/project.schema.cjs +2 -2
- package/dist/cjs/schemas/project.schema.cjs.map +1 -1
- package/dist/cjs/services/dictionary.service.cjs.map +1 -1
- package/dist/cjs/services/email.service.cjs +1 -1
- package/dist/cjs/services/email.service.cjs.map +1 -1
- package/dist/cjs/services/subscription.service.cjs +81 -2
- package/dist/cjs/services/subscription.service.cjs.map +1 -1
- package/dist/cjs/types/dictionary.types.cjs.map +1 -1
- package/dist/cjs/utils/AI/{askDocQuestion.cjs → askDocQuestion/askDocQuestion.cjs} +1 -1
- package/dist/cjs/utils/AI/askDocQuestion/askDocQuestion.cjs.map +1 -0
- package/dist/{esm/utils/AI → cjs/utils/AI/askDocQuestion}/embeddings.json +4288 -4288
- package/dist/cjs/utils/{auditDictionary → AI/auditDictionary}/index.cjs +5 -3
- package/dist/cjs/utils/AI/auditDictionary/index.cjs.map +1 -0
- package/dist/cjs/utils/{auditDictionaryField → AI/auditDictionaryField}/PROMPT.md +17 -7
- package/dist/cjs/utils/{auditDictionaryField → AI/auditDictionaryField}/index.cjs +5 -3
- package/dist/cjs/utils/AI/auditDictionaryField/index.cjs.map +1 -0
- package/dist/cjs/utils/{auditDictionaryMetadata → AI/auditDictionaryMetadata}/index.cjs +5 -3
- package/dist/cjs/utils/AI/auditDictionaryMetadata/index.cjs.map +1 -0
- package/dist/cjs/utils/AI/autocomplete/PROMPT.md +13 -0
- package/dist/cjs/utils/AI/autocomplete/index.cjs +73 -0
- package/dist/cjs/utils/AI/autocomplete/index.cjs.map +1 -0
- package/dist/cjs/utils/auditTag/index.cjs +4 -2
- package/dist/cjs/utils/auditTag/index.cjs.map +1 -1
- package/dist/cjs/utils/errors/errorCodes.cjs +26 -0
- package/dist/cjs/utils/errors/errorCodes.cjs.map +1 -1
- package/dist/cjs/utils/mongoDB/connectDB.cjs +10 -0
- package/dist/cjs/utils/mongoDB/connectDB.cjs.map +1 -1
- package/dist/cjs/webhooks/stripe.webhook.cjs +42 -0
- package/dist/cjs/webhooks/stripe.webhook.cjs.map +1 -1
- package/dist/esm/controllers/ai.controller.mjs +59 -42
- package/dist/esm/controllers/ai.controller.mjs.map +1 -1
- package/dist/esm/controllers/dictionary.controller.mjs +8 -12
- package/dist/esm/controllers/dictionary.controller.mjs.map +1 -1
- package/dist/esm/controllers/organization.controller.mjs +18 -2
- package/dist/esm/controllers/organization.controller.mjs.map +1 -1
- package/dist/esm/controllers/project.controller.mjs +1 -0
- package/dist/esm/controllers/project.controller.mjs.map +1 -1
- package/dist/esm/controllers/sessionAuth.controller.mjs +6 -12
- package/dist/esm/controllers/sessionAuth.controller.mjs.map +1 -1
- package/dist/esm/controllers/stripe.controller.mjs +30 -10
- package/dist/esm/controllers/stripe.controller.mjs.map +1 -1
- package/dist/esm/controllers/tag.controller.mjs +0 -7
- package/dist/esm/controllers/tag.controller.mjs.map +1 -1
- package/dist/esm/controllers/user.controller.mjs +2 -2
- package/dist/esm/controllers/user.controller.mjs.map +1 -1
- package/dist/esm/emails/InviteUserEmail.mjs +3 -3
- package/dist/esm/emails/InviteUserEmail.mjs.map +1 -1
- package/dist/esm/emails/PasswordChangeConfirmation.mjs +3 -3
- package/dist/esm/emails/PasswordChangeConfirmation.mjs.map +1 -1
- package/dist/esm/emails/ResetUserPassword.mjs +3 -3
- package/dist/esm/emails/ResetUserPassword.mjs.map +1 -1
- package/dist/esm/emails/SubscriptionPaymentCancellation.mjs +19 -3
- package/dist/esm/emails/SubscriptionPaymentCancellation.mjs.map +1 -1
- package/dist/esm/emails/SubscriptionPaymentError.mjs +19 -3
- package/dist/esm/emails/SubscriptionPaymentError.mjs.map +1 -1
- package/dist/esm/emails/SubscriptionPaymentSuccess.mjs +19 -3
- package/dist/esm/emails/SubscriptionPaymentSuccess.mjs.map +1 -1
- package/dist/esm/emails/ValidateUserEmail.mjs +3 -3
- package/dist/esm/emails/ValidateUserEmail.mjs.map +1 -1
- package/dist/esm/emails/Welcome.mjs +3 -3
- package/dist/esm/emails/Welcome.mjs.map +1 -1
- package/dist/esm/export.mjs +10 -10
- package/dist/esm/export.mjs.map +1 -1
- package/dist/esm/routes/ai.routes.mjs +22 -15
- package/dist/esm/routes/ai.routes.mjs.map +1 -1
- package/dist/esm/routes/dictionary.routes.mjs +14 -11
- package/dist/esm/routes/dictionary.routes.mjs.map +1 -1
- package/dist/esm/routes/event-listener.routes.mjs +4 -4
- package/dist/esm/routes/event-listener.routes.mjs.map +1 -1
- package/dist/esm/routes/organization.routes.mjs +13 -13
- package/dist/esm/routes/organization.routes.mjs.map +1 -1
- package/dist/esm/routes/project.routes.mjs +28 -16
- package/dist/esm/routes/project.routes.mjs.map +1 -1
- package/dist/esm/routes/sessionAuth.routes.mjs +37 -34
- package/dist/esm/routes/sessionAuth.routes.mjs.map +1 -1
- package/dist/esm/routes/stripe.routes.mjs +22 -9
- package/dist/esm/routes/stripe.routes.mjs.map +1 -1
- package/dist/esm/routes/tags.routes.mjs +9 -9
- package/dist/esm/routes/tags.routes.mjs.map +1 -1
- package/dist/esm/routes/user.routes.mjs +11 -11
- package/dist/esm/routes/user.routes.mjs.map +1 -1
- package/dist/esm/schemas/dictionary.schema.mjs +0 -4
- package/dist/esm/schemas/dictionary.schema.mjs.map +1 -1
- package/dist/esm/schemas/project.schema.mjs +2 -2
- package/dist/esm/schemas/project.schema.mjs.map +1 -1
- package/dist/esm/services/dictionary.service.mjs.map +1 -1
- package/dist/esm/services/email.service.mjs +1 -1
- package/dist/esm/services/email.service.mjs.map +1 -1
- package/dist/esm/services/subscription.service.mjs +78 -1
- package/dist/esm/services/subscription.service.mjs.map +1 -1
- package/dist/esm/utils/AI/{askDocQuestion.mjs → askDocQuestion/askDocQuestion.mjs} +1 -1
- package/dist/esm/utils/AI/askDocQuestion/askDocQuestion.mjs.map +1 -0
- package/dist/{cjs/utils/AI → esm/utils/AI/askDocQuestion}/embeddings.json +4288 -4288
- package/dist/esm/utils/{auditDictionary → AI/auditDictionary}/index.mjs +5 -3
- package/dist/esm/utils/AI/auditDictionary/index.mjs.map +1 -0
- package/dist/esm/utils/{auditDictionaryField → AI/auditDictionaryField}/PROMPT.md +17 -7
- package/dist/esm/utils/{auditDictionaryField → AI/auditDictionaryField}/index.mjs +5 -3
- package/dist/esm/utils/AI/auditDictionaryField/index.mjs.map +1 -0
- package/dist/esm/utils/{auditDictionaryMetadata → AI/auditDictionaryMetadata}/index.mjs +5 -3
- package/dist/esm/utils/AI/auditDictionaryMetadata/index.mjs.map +1 -0
- package/dist/esm/utils/AI/autocomplete/PROMPT.md +13 -0
- package/dist/esm/utils/AI/autocomplete/index.mjs +48 -0
- package/dist/esm/utils/AI/autocomplete/index.mjs.map +1 -0
- package/dist/esm/utils/auditTag/index.mjs +4 -2
- package/dist/esm/utils/auditTag/index.mjs.map +1 -1
- package/dist/esm/utils/errors/errorCodes.mjs +26 -0
- package/dist/esm/utils/errors/errorCodes.mjs.map +1 -1
- package/dist/esm/utils/mongoDB/connectDB.mjs +10 -0
- package/dist/esm/utils/mongoDB/connectDB.mjs.map +1 -1
- package/dist/esm/webhooks/stripe.webhook.mjs +32 -0
- package/dist/esm/webhooks/stripe.webhook.mjs.map +1 -1
- package/dist/types/controllers/ai.controller.d.ts +17 -2
- package/dist/types/controllers/ai.controller.d.ts.map +1 -1
- package/dist/types/controllers/dictionary.controller.d.ts.map +1 -1
- package/dist/types/controllers/organization.controller.d.ts.map +1 -1
- package/dist/types/controllers/project.controller.d.ts.map +1 -1
- package/dist/types/controllers/sessionAuth.controller.d.ts +4 -3
- package/dist/types/controllers/sessionAuth.controller.d.ts.map +1 -1
- package/dist/types/controllers/stripe.controller.d.ts +15 -7
- package/dist/types/controllers/stripe.controller.d.ts.map +1 -1
- package/dist/types/controllers/tag.controller.d.ts.map +1 -1
- package/dist/types/emails/SubscriptionPaymentCancellation.d.ts +4 -3
- package/dist/types/emails/SubscriptionPaymentCancellation.d.ts.map +1 -1
- package/dist/types/emails/SubscriptionPaymentError.d.ts +4 -3
- package/dist/types/emails/SubscriptionPaymentError.d.ts.map +1 -1
- package/dist/types/emails/SubscriptionPaymentSuccess.d.ts +4 -3
- package/dist/types/emails/SubscriptionPaymentSuccess.d.ts.map +1 -1
- package/dist/types/export.d.ts +5 -5
- package/dist/types/export.d.ts.map +1 -1
- package/dist/types/routes/ai.routes.d.ts +6 -1
- package/dist/types/routes/ai.routes.d.ts.map +1 -1
- package/dist/types/routes/dictionary.routes.d.ts +4 -4
- package/dist/types/routes/dictionary.routes.d.ts.map +1 -1
- package/dist/types/routes/event-listener.routes.d.ts +1 -1
- package/dist/types/routes/event-listener.routes.d.ts.map +1 -1
- package/dist/types/routes/organization.routes.d.ts +5 -5
- package/dist/types/routes/organization.routes.d.ts.map +1 -1
- package/dist/types/routes/project.routes.d.ts +5 -5
- package/dist/types/routes/project.routes.d.ts.map +1 -1
- package/dist/types/routes/sessionAuth.routes.d.ts +4 -7
- package/dist/types/routes/sessionAuth.routes.d.ts.map +1 -1
- package/dist/types/routes/stripe.routes.d.ts +6 -1
- package/dist/types/routes/stripe.routes.d.ts.map +1 -1
- package/dist/types/routes/tags.routes.d.ts +3 -3
- package/dist/types/routes/tags.routes.d.ts.map +1 -1
- package/dist/types/routes/user.routes.d.ts +4 -4
- package/dist/types/routes/user.routes.d.ts.map +1 -1
- package/dist/types/schemas/dictionary.schema.d.ts.map +1 -1
- package/dist/types/services/dictionary.service.d.ts.map +1 -1
- package/dist/types/services/subscription.service.d.ts +9 -0
- package/dist/types/services/subscription.service.d.ts.map +1 -1
- package/dist/types/types/dictionary.types.d.ts +0 -1
- package/dist/types/types/dictionary.types.d.ts.map +1 -1
- package/dist/types/utils/AI/askDocQuestion/askDocQuestion.d.ts.map +1 -0
- package/dist/types/utils/{auditDictionary → AI/auditDictionary}/index.d.ts +8 -5
- package/dist/types/utils/AI/auditDictionary/index.d.ts.map +1 -0
- package/dist/types/utils/{auditDictionaryField → AI/auditDictionaryField}/index.d.ts +8 -5
- package/dist/types/utils/AI/auditDictionaryField/index.d.ts.map +1 -0
- package/dist/types/utils/{auditDictionaryMetadata → AI/auditDictionaryMetadata}/index.d.ts +8 -5
- package/dist/types/utils/AI/auditDictionaryMetadata/index.d.ts.map +1 -0
- package/dist/types/utils/AI/autocomplete/index.d.ts +22 -0
- package/dist/types/utils/AI/autocomplete/index.d.ts.map +1 -0
- package/dist/types/utils/auditTag/index.d.ts +7 -4
- package/dist/types/utils/auditTag/index.d.ts.map +1 -1
- package/dist/types/utils/errors/errorCodes.d.ts +26 -0
- package/dist/types/utils/errors/errorCodes.d.ts.map +1 -1
- package/dist/types/utils/mongoDB/connectDB.d.ts.map +1 -1
- package/dist/types/webhooks/stripe.webhook.d.ts.map +1 -1
- package/package.json +11 -10
- package/dist/cjs/utils/AI/askDocQuestion.cjs.map +0 -1
- package/dist/cjs/utils/auditDictionary/index.cjs.map +0 -1
- package/dist/cjs/utils/auditDictionaryField/index.cjs.map +0 -1
- package/dist/cjs/utils/auditDictionaryMetadata/index.cjs.map +0 -1
- package/dist/esm/utils/AI/askDocQuestion.mjs.map +0 -1
- package/dist/esm/utils/auditDictionary/index.mjs.map +0 -1
- package/dist/esm/utils/auditDictionaryField/index.mjs.map +0 -1
- package/dist/esm/utils/auditDictionaryMetadata/index.mjs.map +0 -1
- package/dist/types/utils/AI/askDocQuestion.d.ts.map +0 -1
- package/dist/types/utils/auditDictionary/index.d.ts.map +0 -1
- package/dist/types/utils/auditDictionaryField/index.d.ts.map +0 -1
- package/dist/types/utils/auditDictionaryMetadata/index.d.ts.map +0 -1
- /package/dist/cjs/utils/{auditDictionary → AI/auditDictionary}/CJS_FORMAT.md +0 -0
- /package/dist/cjs/utils/{auditDictionary → AI/auditDictionary}/JSON_FORMAT.md +0 -0
- /package/dist/cjs/utils/{auditDictionary → AI/auditDictionary}/JSX_FORMAT.md +0 -0
- /package/dist/cjs/utils/{auditDictionary → AI/auditDictionary}/MJS_FORMAT.md +0 -0
- /package/dist/cjs/utils/{auditDictionary → AI/auditDictionary}/PROMPT.md +0 -0
- /package/dist/cjs/utils/{auditDictionary → AI/auditDictionary}/TSX_FORMAT.md +0 -0
- /package/dist/cjs/utils/{auditDictionary → AI/auditDictionary}/TS_FORMAT.md +0 -0
- /package/dist/cjs/utils/{auditDictionaryMetadata → AI/auditDictionaryMetadata}/PROMPT.md +0 -0
- /package/dist/esm/utils/{auditDictionary → AI/auditDictionary}/CJS_FORMAT.md +0 -0
- /package/dist/esm/utils/{auditDictionary → AI/auditDictionary}/JSON_FORMAT.md +0 -0
- /package/dist/esm/utils/{auditDictionary → AI/auditDictionary}/JSX_FORMAT.md +0 -0
- /package/dist/esm/utils/{auditDictionary → AI/auditDictionary}/MJS_FORMAT.md +0 -0
- /package/dist/esm/utils/{auditDictionary → AI/auditDictionary}/PROMPT.md +0 -0
- /package/dist/esm/utils/{auditDictionary → AI/auditDictionary}/TSX_FORMAT.md +0 -0
- /package/dist/esm/utils/{auditDictionary → AI/auditDictionary}/TS_FORMAT.md +0 -0
- /package/dist/esm/utils/{auditDictionaryMetadata → AI/auditDictionaryMetadata}/PROMPT.md +0 -0
- /package/dist/types/utils/AI/{askDocQuestion.d.ts → askDocQuestion/askDocQuestion.d.ts} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/routes/sessionAuth.routes.ts"],"sourcesContent":["import {\n registerEmailPassword,\n loginEmailPassword,\n logOut,\n updatePassword,\n validEmail,\n askResetPassword,\n
|
|
1
|
+
{"version":3,"sources":["../../../src/routes/sessionAuth.routes.ts"],"sourcesContent":["import {\n registerEmailPassword,\n loginEmailPassword,\n logOut,\n updatePassword,\n validEmail,\n askResetPassword,\n definePassword,\n githubCallback,\n googleCallback,\n githubLoginQuery,\n googleLoginQuery,\n verifyEmailStatusSSE,\n checkIfUserHasPassword,\n} from '@controllers/sessionAuth.controller';\nimport { Router } from 'express';\nimport type { Routes } from '@/types/Routes';\n\nexport const sessionAuthRouter: Router = Router();\n\nconst baseURL = () => `${process.env.BACKEND_URL}/api/auth`;\n\nexport const getSessionAuthRoutes = () =>\n ({\n registerEmailPassword: {\n urlModel: '/register',\n url: `${baseURL}/register`,\n method: 'POST',\n },\n loginEmailPassword: {\n urlModel: '/login',\n url: `${baseURL()}/login`,\n method: 'POST',\n },\n logOut: {\n urlModel: '/logout',\n url: `${baseURL()}/logout`,\n method: 'POST',\n },\n updatePassword: {\n urlModel: '/password',\n url: `${baseURL()}/password`,\n method: 'PUT',\n },\n askResetPassword: {\n urlModel: '/password/reset',\n url: `${baseURL()}/password/reset`,\n method: 'POST',\n },\n defineNewPassword: {\n urlModel: '/password/define',\n url: `${baseURL()}/password/define`,\n method: 'POST',\n },\n checkIfUserHasPassword: {\n urlModel: '/password/has',\n url: `${baseURL()}/password/has`,\n method: 'GET',\n },\n validEmail: {\n urlModel: '/:userId/active/:secret',\n url: ({\n userId,\n secret,\n callBack_url,\n }: {\n userId: string;\n secret: string;\n callBack_url?: string;\n }) =>\n `${baseURL()}/${userId}/active/${secret}${\n callBack_url ? `?callBack_url=${callBack_url}` : ''\n }`,\n method: 'GET',\n },\n verifyEmailStatusSSE: {\n urlModel: '/verify-email-status/:userId',\n url: ({ userId }: { userId: string }) =>\n `${baseURL()}/verify-email-status/${userId}`,\n method: 'GET',\n },\n githubLoginQuery: {\n urlModel: '/login/github',\n url: `${baseURL()}/login/github`,\n method: 'GET',\n },\n githubCallback: {\n urlModel: '/callback/github',\n url: `${baseURL()}/callback/github`,\n method: 'GET',\n },\n googleLoginQuery: {\n urlModel: '/login/google',\n url: `${baseURL()}/login/google`,\n method: 'GET',\n },\n googleCallback: {\n urlModel: '/callback/google',\n url: `${baseURL()}/callback/google`,\n method: 'GET',\n },\n }) satisfies Routes;\n\n// Authentication\nsessionAuthRouter.post(\n getSessionAuthRoutes().registerEmailPassword.urlModel,\n registerEmailPassword\n);\nsessionAuthRouter.post(\n getSessionAuthRoutes().loginEmailPassword.urlModel,\n loginEmailPassword\n);\nsessionAuthRouter.post(getSessionAuthRoutes().logOut.urlModel, logOut);\n\n// Password\nsessionAuthRouter.put(\n getSessionAuthRoutes().updatePassword.urlModel,\n updatePassword\n);\nsessionAuthRouter.post(\n getSessionAuthRoutes().askResetPassword.urlModel,\n askResetPassword\n);\nsessionAuthRouter.post(\n getSessionAuthRoutes().defineNewPassword.urlModel,\n definePassword\n);\n\nsessionAuthRouter.get(\n getSessionAuthRoutes().checkIfUserHasPassword.urlModel,\n checkIfUserHasPassword\n);\n\n// Email validation\nsessionAuthRouter.get(getSessionAuthRoutes().validEmail.urlModel, validEmail);\n\n// Verify email status\nsessionAuthRouter.get(\n getSessionAuthRoutes().verifyEmailStatusSSE.urlModel,\n verifyEmailStatusSSE\n);\n\n// Github auth\nsessionAuthRouter.get(\n getSessionAuthRoutes().githubLoginQuery.urlModel,\n githubLoginQuery\n);\nsessionAuthRouter.get(\n getSessionAuthRoutes().githubCallback.urlModel,\n githubCallback\n);\n\n// Google auth\nsessionAuthRouter.get(\n getSessionAuthRoutes().googleLoginQuery.urlModel,\n googleLoginQuery\n);\nsessionAuthRouter.get(\n getSessionAuthRoutes().googleCallback.urlModel,\n googleCallback\n);\n"],"mappings":"AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,cAAc;AAGhB,MAAM,oBAA4B,OAAO;AAEhD,MAAM,UAAU,MAAM,GAAG,QAAQ,IAAI,WAAW;AAEzC,MAAM,uBAAuB,OACjC;AAAA,EACC,uBAAuB;AAAA,IACrB,UAAU;AAAA,IACV,KAAK,GAAG,OAAO;AAAA,IACf,QAAQ;AAAA,EACV;AAAA,EACA,oBAAoB;AAAA,IAClB,UAAU;AAAA,IACV,KAAK,GAAG,QAAQ,CAAC;AAAA,IACjB,QAAQ;AAAA,EACV;AAAA,EACA,QAAQ;AAAA,IACN,UAAU;AAAA,IACV,KAAK,GAAG,QAAQ,CAAC;AAAA,IACjB,QAAQ;AAAA,EACV;AAAA,EACA,gBAAgB;AAAA,IACd,UAAU;AAAA,IACV,KAAK,GAAG,QAAQ,CAAC;AAAA,IACjB,QAAQ;AAAA,EACV;AAAA,EACA,kBAAkB;AAAA,IAChB,UAAU;AAAA,IACV,KAAK,GAAG,QAAQ,CAAC;AAAA,IACjB,QAAQ;AAAA,EACV;AAAA,EACA,mBAAmB;AAAA,IACjB,UAAU;AAAA,IACV,KAAK,GAAG,QAAQ,CAAC;AAAA,IACjB,QAAQ;AAAA,EACV;AAAA,EACA,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AAAA,EACzC;AACF;AAEA,kBAAkB;AAAA,EAChB,qBAAqB,EAAE,uBAAuB;AAAA,EAC9C;AACF;AAGA,kBAAkB,IAAI,qBAAqB,EAAE,WAAW,UAAU,UAAU;AAG5E,kBAAkB;AAAA,EAChB,qBAAqB,EAAE,qBAAqB;AAAA,EAC5C;AACF;AAGA,kBAAkB;AAAA,EAChB,qBAAqB,EAAE,iBAAiB;AAAA,EACxC;AACF;AACA,kBAAkB;AAAA,EAChB,qBAAqB,EAAE,eAAe;AAAA,EACtC;AACF;AAGA,kBAAkB;AAAA,EAChB,qBAAqB,EAAE,iBAAiB;AAAA,EACxC;AACF;AACA,kBAAkB;AAAA,EAChB,qBAAqB,EAAE,eAAe;AAAA,EACtC;AACF;","names":[]}
|
|
@@ -1,26 +1,39 @@
|
|
|
1
1
|
import {
|
|
2
|
+
getPricing,
|
|
2
3
|
cancelSubscription,
|
|
3
4
|
getSubscription
|
|
4
5
|
} from "./../controllers/stripe.controller.mjs";
|
|
5
6
|
import { Router } from "express";
|
|
6
7
|
const stripeRouter = Router();
|
|
7
|
-
const baseURL = `${process.env.BACKEND_URL}/api/stipe`;
|
|
8
|
-
const
|
|
8
|
+
const baseURL = () => `${process.env.BACKEND_URL}/api/stipe`;
|
|
9
|
+
const getStripeRoutes = () => ({
|
|
10
|
+
getPricing: {
|
|
11
|
+
urlModel: "/pricing",
|
|
12
|
+
url: `${baseURL()}/pricing`,
|
|
13
|
+
method: "POST"
|
|
14
|
+
},
|
|
9
15
|
createSubscription: {
|
|
10
16
|
urlModel: "/create-subscription",
|
|
11
|
-
url: `${baseURL}/create-subscription`,
|
|
17
|
+
url: `${baseURL()}/create-subscription`,
|
|
12
18
|
method: "POST"
|
|
13
19
|
},
|
|
14
20
|
cancelSubscription: {
|
|
15
21
|
urlModel: "/cancel-subscription",
|
|
16
|
-
url: `${baseURL}/cancel-subscription`,
|
|
22
|
+
url: `${baseURL()}/cancel-subscription`,
|
|
17
23
|
method: "POST"
|
|
18
24
|
}
|
|
19
|
-
};
|
|
20
|
-
stripeRouter.post(
|
|
21
|
-
stripeRouter.post(
|
|
25
|
+
});
|
|
26
|
+
stripeRouter.post(getStripeRoutes().getPricing.urlModel, getPricing);
|
|
27
|
+
stripeRouter.post(
|
|
28
|
+
getStripeRoutes().createSubscription.urlModel,
|
|
29
|
+
getSubscription
|
|
30
|
+
);
|
|
31
|
+
stripeRouter.post(
|
|
32
|
+
getStripeRoutes().cancelSubscription.urlModel,
|
|
33
|
+
cancelSubscription
|
|
34
|
+
);
|
|
22
35
|
export {
|
|
23
|
-
|
|
24
|
-
|
|
36
|
+
getStripeRoutes,
|
|
37
|
+
stripeRouter
|
|
25
38
|
};
|
|
26
39
|
//# sourceMappingURL=stripe.routes.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/routes/stripe.routes.ts"],"sourcesContent":["import {\n cancelSubscription,\n getSubscription,\n} from '@controllers/stripe.controller';\nimport { Router } from 'express';\nimport type { Routes } from '@/types/Routes';\n\nexport const stripeRouter: Router = Router();\n\nconst baseURL = `${process.env.BACKEND_URL}/api/stipe`;\n\nexport const
|
|
1
|
+
{"version":3,"sources":["../../../src/routes/stripe.routes.ts"],"sourcesContent":["import {\n getPricing,\n cancelSubscription,\n getSubscription,\n} from '@controllers/stripe.controller';\nimport { Router } from 'express';\nimport type { Routes } from '@/types/Routes';\n\nexport const stripeRouter: Router = Router();\n\nconst baseURL = () => `${process.env.BACKEND_URL}/api/stipe`;\n\nexport const getStripeRoutes = () =>\n ({\n getPricing: {\n urlModel: '/pricing',\n url: `${baseURL()}/pricing`,\n method: 'POST',\n },\n createSubscription: {\n urlModel: '/create-subscription',\n url: `${baseURL()}/create-subscription`,\n method: 'POST',\n },\n cancelSubscription: {\n urlModel: '/cancel-subscription',\n url: `${baseURL()}/cancel-subscription`,\n method: 'POST',\n },\n }) satisfies Routes;\n\nstripeRouter.post(getStripeRoutes().getPricing.urlModel, getPricing);\n\nstripeRouter.post(\n getStripeRoutes().createSubscription.urlModel,\n getSubscription\n);\n\nstripeRouter.post(\n getStripeRoutes().cancelSubscription.urlModel,\n cancelSubscription\n);\n"],"mappings":"AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,cAAc;AAGhB,MAAM,eAAuB,OAAO;AAE3C,MAAM,UAAU,MAAM,GAAG,QAAQ,IAAI,WAAW;AAEzC,MAAM,kBAAkB,OAC5B;AAAA,EACC,YAAY;AAAA,IACV,UAAU;AAAA,IACV,KAAK,GAAG,QAAQ,CAAC;AAAA,IACjB,QAAQ;AAAA,EACV;AAAA,EACA,oBAAoB;AAAA,IAClB,UAAU;AAAA,IACV,KAAK,GAAG,QAAQ,CAAC;AAAA,IACjB,QAAQ;AAAA,EACV;AAAA,EACA,oBAAoB;AAAA,IAClB,UAAU;AAAA,IACV,KAAK,GAAG,QAAQ,CAAC;AAAA,IACjB,QAAQ;AAAA,EACV;AACF;AAEF,aAAa,KAAK,gBAAgB,EAAE,WAAW,UAAU,UAAU;AAEnE,aAAa;AAAA,EACX,gBAAgB,EAAE,mBAAmB;AAAA,EACrC;AACF;AAEA,aAAa;AAAA,EACX,gBAAgB,EAAE,mBAAmB;AAAA,EACrC;AACF;","names":[]}
|
|
@@ -6,8 +6,8 @@ import {
|
|
|
6
6
|
} from "./../controllers/tag.controller.mjs";
|
|
7
7
|
import { Router } from "express";
|
|
8
8
|
const tagRouter = Router();
|
|
9
|
-
const baseURL = `${process.env.BACKEND_URL}/api/tag`;
|
|
10
|
-
const
|
|
9
|
+
const baseURL = () => `${process.env.BACKEND_URL}/api/tag`;
|
|
10
|
+
const getTagRoutes = () => ({
|
|
11
11
|
getTags: {
|
|
12
12
|
urlModel: "/",
|
|
13
13
|
url: baseURL,
|
|
@@ -28,13 +28,13 @@ const tagRoutes = {
|
|
|
28
28
|
url: ({ tagId }) => `${baseURL}/${tagId}`,
|
|
29
29
|
method: "DELETE"
|
|
30
30
|
}
|
|
31
|
-
};
|
|
32
|
-
tagRouter.get(
|
|
33
|
-
tagRouter.post(
|
|
34
|
-
tagRouter.put(
|
|
35
|
-
tagRouter.delete(
|
|
31
|
+
});
|
|
32
|
+
tagRouter.get(getTagRoutes().getTags.urlModel, getTags);
|
|
33
|
+
tagRouter.post(getTagRoutes().addTag.urlModel, addTag);
|
|
34
|
+
tagRouter.put(getTagRoutes().updateTag.urlModel, updateTag);
|
|
35
|
+
tagRouter.delete(getTagRoutes().deleteTag.urlModel, deleteTag);
|
|
36
36
|
export {
|
|
37
|
-
|
|
38
|
-
|
|
37
|
+
getTagRoutes,
|
|
38
|
+
tagRouter
|
|
39
39
|
};
|
|
40
40
|
//# sourceMappingURL=tags.routes.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/routes/tags.routes.ts"],"sourcesContent":["import {\n addTag,\n deleteTag,\n getTags,\n updateTag,\n} from '@controllers/tag.controller';\nimport { Router } from 'express';\nimport type { Routes } from '@/types/Routes';\n\nexport const tagRouter: Router = Router();\n\nconst baseURL = `${process.env.BACKEND_URL}/api/tag`;\n\nexport const
|
|
1
|
+
{"version":3,"sources":["../../../src/routes/tags.routes.ts"],"sourcesContent":["import {\n addTag,\n deleteTag,\n getTags,\n updateTag,\n} from '@controllers/tag.controller';\nimport { Router } from 'express';\nimport type { Routes } from '@/types/Routes';\n\nexport const tagRouter: Router = Router();\n\nconst baseURL = () => `${process.env.BACKEND_URL}/api/tag`;\n\nexport const getTagRoutes = () =>\n ({\n getTags: {\n urlModel: '/',\n url: baseURL,\n method: 'GET',\n },\n addTag: {\n urlModel: '/',\n url: baseURL,\n method: 'POST',\n },\n updateTag: {\n urlModel: '/:tagId',\n url: ({ tagId }: { tagId: string }) => `${baseURL}/${tagId}`,\n method: 'PUT',\n },\n deleteTag: {\n urlModel: '/:tagId',\n url: ({ tagId }: { tagId: string }) => `${baseURL}/${tagId}`,\n method: 'DELETE',\n },\n }) satisfies Routes;\n\ntagRouter.get(getTagRoutes().getTags.urlModel, getTags);\n\ntagRouter.post(getTagRoutes().addTag.urlModel, addTag);\ntagRouter.put(getTagRoutes().updateTag.urlModel, updateTag);\ntagRouter.delete(getTagRoutes().deleteTag.urlModel, deleteTag);\n"],"mappings":"AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,cAAc;AAGhB,MAAM,YAAoB,OAAO;AAExC,MAAM,UAAU,MAAM,GAAG,QAAQ,IAAI,WAAW;AAEzC,MAAM,eAAe,OACzB;AAAA,EACC,SAAS;AAAA,IACP,UAAU;AAAA,IACV,KAAK;AAAA,IACL,QAAQ;AAAA,EACV;AAAA,EACA,QAAQ;AAAA,IACN,UAAU;AAAA,IACV,KAAK;AAAA,IACL,QAAQ;AAAA,EACV;AAAA,EACA,WAAW;AAAA,IACT,UAAU;AAAA,IACV,KAAK,CAAC,EAAE,MAAM,MAAyB,GAAG,OAAO,IAAI,KAAK;AAAA,IAC1D,QAAQ;AAAA,EACV;AAAA,EACA,WAAW;AAAA,IACT,UAAU;AAAA,IACV,KAAK,CAAC,EAAE,MAAM,MAAyB,GAAG,OAAO,IAAI,KAAK;AAAA,IAC1D,QAAQ;AAAA,EACV;AACF;AAEF,UAAU,IAAI,aAAa,EAAE,QAAQ,UAAU,OAAO;AAEtD,UAAU,KAAK,aAAa,EAAE,OAAO,UAAU,MAAM;AACrD,UAAU,IAAI,aAAa,EAAE,UAAU,UAAU,SAAS;AAC1D,UAAU,OAAO,aAAa,EAAE,UAAU,UAAU,SAAS;","names":[]}
|
|
@@ -8,8 +8,8 @@ import {
|
|
|
8
8
|
} from "./../controllers/user.controller.mjs";
|
|
9
9
|
import { Router } from "express";
|
|
10
10
|
const userRouter = Router();
|
|
11
|
-
const baseURL = `${process.env.BACKEND_URL}/api/user`;
|
|
12
|
-
const
|
|
11
|
+
const baseURL = () => `${process.env.BACKEND_URL}/api/user`;
|
|
12
|
+
const getUserRoutes = () => ({
|
|
13
13
|
getUsers: {
|
|
14
14
|
urlModel: "/",
|
|
15
15
|
url: baseURL,
|
|
@@ -43,15 +43,15 @@ const userRoutes = {
|
|
|
43
43
|
}) => `${baseURL}/account/${provider}/${providerAccountId}`,
|
|
44
44
|
method: "GET"
|
|
45
45
|
}
|
|
46
|
-
};
|
|
47
|
-
userRouter.get(
|
|
48
|
-
userRouter.put(
|
|
49
|
-
userRouter.post(
|
|
50
|
-
userRouter.get(
|
|
51
|
-
userRouter.get(
|
|
52
|
-
userRouter.get(
|
|
46
|
+
});
|
|
47
|
+
userRouter.get(getUserRoutes().getUsers.urlModel, getUsers);
|
|
48
|
+
userRouter.put(getUserRoutes().updateUser.urlModel, updateUser);
|
|
49
|
+
userRouter.post(getUserRoutes().createUser.urlModel, createUser);
|
|
50
|
+
userRouter.get(getUserRoutes().getUserById.urlModel, getUserById);
|
|
51
|
+
userRouter.get(getUserRoutes().getUserByEmail.urlModel, getUserByEmail);
|
|
52
|
+
userRouter.get(getUserRoutes().getUserByAccount.urlModel, getUserByAccount);
|
|
53
53
|
export {
|
|
54
|
-
|
|
55
|
-
|
|
54
|
+
getUserRoutes,
|
|
55
|
+
userRouter
|
|
56
56
|
};
|
|
57
57
|
//# sourceMappingURL=user.routes.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/routes/user.routes.ts"],"sourcesContent":["import {\n getUsers,\n updateUser,\n getUserByEmail,\n getUserById,\n createUser,\n getUserByAccount,\n} from '@controllers/user.controller';\nimport { Router } from 'express';\nimport type { Routes } from '@/types/Routes';\n\nexport const userRouter: Router = Router();\n\nconst baseURL = `${process.env.BACKEND_URL}/api/user`;\n\nexport const
|
|
1
|
+
{"version":3,"sources":["../../../src/routes/user.routes.ts"],"sourcesContent":["import {\n getUsers,\n updateUser,\n getUserByEmail,\n getUserById,\n createUser,\n getUserByAccount,\n} from '@controllers/user.controller';\nimport { Router } from 'express';\nimport type { Routes } from '@/types/Routes';\n\nexport const userRouter: Router = Router();\n\nconst baseURL = () => `${process.env.BACKEND_URL}/api/user`;\n\nexport const getUserRoutes = () =>\n ({\n getUsers: {\n urlModel: '/',\n url: baseURL,\n method: 'GET',\n },\n updateUser: {\n urlModel: '/',\n url: baseURL,\n method: 'PUT',\n },\n createUser: {\n urlModel: '/',\n url: baseURL,\n method: 'POST',\n },\n getUserById: {\n urlModel: '/:userId',\n url: ({ userId }: { userId: string }) => `${baseURL}/${userId}`,\n method: 'GET',\n },\n getUserByEmail: {\n urlModel: '/email/:email',\n url: ({ email }: { email: string }) => `${baseURL}/email/${email}`,\n method: 'GET',\n },\n getUserByAccount: {\n urlModel: '/account/:provider/:providerAccountId',\n url: ({\n provider,\n providerAccountId,\n }: {\n provider: string;\n providerAccountId: string;\n }) => `${baseURL}/account/${provider}/${providerAccountId}`,\n method: 'GET',\n },\n }) satisfies Routes;\n\nuserRouter.get(getUserRoutes().getUsers.urlModel, getUsers);\nuserRouter.put(getUserRoutes().updateUser.urlModel, updateUser);\nuserRouter.post(getUserRoutes().createUser.urlModel, createUser);\nuserRouter.get(getUserRoutes().getUserById.urlModel, getUserById);\nuserRouter.get(getUserRoutes().getUserByEmail.urlModel, getUserByEmail);\nuserRouter.get(getUserRoutes().getUserByAccount.urlModel, getUserByAccount);\n"],"mappings":"AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,cAAc;AAGhB,MAAM,aAAqB,OAAO;AAEzC,MAAM,UAAU,MAAM,GAAG,QAAQ,IAAI,WAAW;AAEzC,MAAM,gBAAgB,OAC1B;AAAA,EACC,UAAU;AAAA,IACR,UAAU;AAAA,IACV,KAAK;AAAA,IACL,QAAQ;AAAA,EACV;AAAA,EACA,YAAY;AAAA,IACV,UAAU;AAAA,IACV,KAAK;AAAA,IACL,QAAQ;AAAA,EACV;AAAA,EACA,YAAY;AAAA,IACV,UAAU;AAAA,IACV,KAAK;AAAA,IACL,QAAQ;AAAA,EACV;AAAA,EACA,aAAa;AAAA,IACX,UAAU;AAAA,IACV,KAAK,CAAC,EAAE,OAAO,MAA0B,GAAG,OAAO,IAAI,MAAM;AAAA,IAC7D,QAAQ;AAAA,EACV;AAAA,EACA,gBAAgB;AAAA,IACd,UAAU;AAAA,IACV,KAAK,CAAC,EAAE,MAAM,MAAyB,GAAG,OAAO,UAAU,KAAK;AAAA,IAChE,QAAQ;AAAA,EACV;AAAA,EACA,kBAAkB;AAAA,IAChB,UAAU;AAAA,IACV,KAAK,CAAC;AAAA,MACJ;AAAA,MACA;AAAA,IACF,MAGM,GAAG,OAAO,YAAY,QAAQ,IAAI,iBAAiB;AAAA,IACzD,QAAQ;AAAA,EACV;AACF;AAEF,WAAW,IAAI,cAAc,EAAE,SAAS,UAAU,QAAQ;AAC1D,WAAW,IAAI,cAAc,EAAE,WAAW,UAAU,UAAU;AAC9D,WAAW,KAAK,cAAc,EAAE,WAAW,UAAU,UAAU;AAC/D,WAAW,IAAI,cAAc,EAAE,YAAY,UAAU,WAAW;AAChE,WAAW,IAAI,cAAc,EAAE,eAAe,UAAU,cAAc;AACtE,WAAW,IAAI,cAAc,EAAE,iBAAiB,UAAU,gBAAgB;","names":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/schemas/dictionary.schema.ts"],"sourcesContent":["import { Schema } from 'mongoose';\nimport type { Dictionary, VersionedContentEl } from '@/types/dictionary.types';\n\nconst versionedContentElSchema = new Schema<VersionedContentEl>(\n {\n name: {\n type: String,\n },\n description: {\n type: String,\n },\n content: {\n type: Schema.Types.Mixed,\n required: true,\n },\n },\n {\n timestamps: true,\n }\n);\n\nexport const dictionarySchema = new Schema<Dictionary>(\n {\n projectIds: {\n type: [Schema.Types.ObjectId],\n ref: 'Project',\n required: true,\n },\n key: {\n type: String,\n required: true,\n },\n title: {\n type: String,\n default: '',\n },\n description: {\n type: String,\n default: '',\n },\n tags: {\n type: [String],\n default: [],\n },\n content: {\n type: Map,\n of: versionedContentElSchema,\n required: true,\n default: null,\n },\n creatorId: {\n type: Schema.Types.ObjectId,\n ref: 'User',\n required: true,\n },\n filePath: {\n type: Map,\n of: String,\n default: null,\n },\n
|
|
1
|
+
{"version":3,"sources":["../../../src/schemas/dictionary.schema.ts"],"sourcesContent":["import { Schema } from 'mongoose';\nimport type { Dictionary, VersionedContentEl } from '@/types/dictionary.types';\n\nconst versionedContentElSchema = new Schema<VersionedContentEl>(\n {\n name: {\n type: String,\n },\n description: {\n type: String,\n },\n content: {\n type: Schema.Types.Mixed,\n required: true,\n },\n },\n {\n timestamps: true,\n }\n);\n\nexport const dictionarySchema = new Schema<Dictionary>(\n {\n projectIds: {\n type: [Schema.Types.ObjectId],\n ref: 'Project',\n required: true,\n },\n key: {\n type: String,\n required: true,\n },\n title: {\n type: String,\n default: '',\n },\n description: {\n type: String,\n default: '',\n },\n tags: {\n type: [String],\n default: [],\n },\n content: {\n type: Map,\n of: versionedContentElSchema,\n required: true,\n default: null,\n },\n creatorId: {\n type: Schema.Types.ObjectId,\n ref: 'User',\n required: true,\n },\n filePath: {\n type: Map,\n of: String,\n default: null,\n },\n },\n {\n timestamps: true,\n }\n);\n"],"mappings":"AAAA,SAAS,cAAc;AAGvB,MAAM,2BAA2B,IAAI;AAAA,EACnC;AAAA,IACE,MAAM;AAAA,MACJ,MAAM;AAAA,IACR;AAAA,IACA,aAAa;AAAA,MACX,MAAM;AAAA,IACR;AAAA,IACA,SAAS;AAAA,MACP,MAAM,OAAO,MAAM;AAAA,MACnB,UAAU;AAAA,IACZ;AAAA,EACF;AAAA,EACA;AAAA,IACE,YAAY;AAAA,EACd;AACF;AAEO,MAAM,mBAAmB,IAAI;AAAA,EAClC;AAAA,IACE,YAAY;AAAA,MACV,MAAM,CAAC,OAAO,MAAM,QAAQ;AAAA,MAC5B,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,IACA,KAAK;AAAA,MACH,MAAM;AAAA,MACN,UAAU;AAAA,IACZ;AAAA,IACA,OAAO;AAAA,MACL,MAAM;AAAA,MACN,SAAS;AAAA,IACX;AAAA,IACA,aAAa;AAAA,MACX,MAAM;AAAA,MACN,SAAS;AAAA,IACX;AAAA,IACA,MAAM;AAAA,MACJ,MAAM,CAAC,MAAM;AAAA,MACb,SAAS,CAAC;AAAA,IACZ;AAAA,IACA,SAAS;AAAA,MACP,MAAM;AAAA,MACN,IAAI;AAAA,MACJ,UAAU;AAAA,MACV,SAAS;AAAA,IACX;AAAA,IACA,WAAW;AAAA,MACT,MAAM,OAAO,MAAM;AAAA,MACnB,KAAK;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,IACA,UAAU;AAAA,MACR,MAAM;AAAA,MACN,IAAI;AAAA,MACJ,SAAS;AAAA,IACX;AAAA,EACF;AAAA,EACA;AAAA,IACE,YAAY;AAAA,EACd;AACF;","names":[]}
|
|
@@ -17,12 +17,12 @@ const TokenRightsSchema = new Schema({
|
|
|
17
17
|
});
|
|
18
18
|
const oAuth2AccessSchema = new Schema(
|
|
19
19
|
{
|
|
20
|
-
clientId: { type: String, required: true
|
|
20
|
+
clientId: { type: String, required: true },
|
|
21
21
|
clientSecret: { type: String, required: true },
|
|
22
22
|
userId: { type: Schema.Types.ObjectId, ref: "User", required: true },
|
|
23
23
|
name: { type: String, required: true },
|
|
24
24
|
expiresAt: { type: Date },
|
|
25
|
-
accessToken: { type: [String], required: true },
|
|
25
|
+
accessToken: { type: [String], required: true, default: [] },
|
|
26
26
|
rights: { type: TokenRightsSchema, required: true }
|
|
27
27
|
},
|
|
28
28
|
{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/schemas/project.schema.ts"],"sourcesContent":["import { Locales } from '@intlayer/config';\nimport {\n NAME_MIN_LENGTH,\n NAME_MAX_LENGTH,\n MEMBERS_MIN_LENGTH,\n} from '@utils/validation/validateProject';\nimport { Schema } from 'mongoose';\nimport type { Project, Rights, TokenRights } from '@/types/project.types';\n\nconst RightsSchema = new Schema<Rights>({\n read: { type: Boolean, required: true },\n write: { type: Boolean, required: true },\n admin: { type: Boolean, required: true },\n});\n\nexport const TokenRightsSchema = new Schema<TokenRights>({\n dictionary: { type: RightsSchema, required: true },\n project: { type: RightsSchema, required: true },\n organization: { type: RightsSchema, required: true },\n});\n\n// Define the oAuth2Access subdocument schema with timestamps\nconst oAuth2AccessSchema = new Schema(\n {\n clientId: { type: String, required: true
|
|
1
|
+
{"version":3,"sources":["../../../src/schemas/project.schema.ts"],"sourcesContent":["import { Locales } from '@intlayer/config';\nimport {\n NAME_MIN_LENGTH,\n NAME_MAX_LENGTH,\n MEMBERS_MIN_LENGTH,\n} from '@utils/validation/validateProject';\nimport { Schema } from 'mongoose';\nimport type { Project, Rights, TokenRights } from '@/types/project.types';\n\nconst RightsSchema = new Schema<Rights>({\n read: { type: Boolean, required: true },\n write: { type: Boolean, required: true },\n admin: { type: Boolean, required: true },\n});\n\nexport const TokenRightsSchema = new Schema<TokenRights>({\n dictionary: { type: RightsSchema, required: true },\n project: { type: RightsSchema, required: true },\n organization: { type: RightsSchema, required: true },\n});\n\n// Define the oAuth2Access subdocument schema with timestamps\nconst oAuth2AccessSchema = new Schema(\n {\n clientId: { type: String, required: true },\n clientSecret: { type: String, required: true },\n userId: { type: Schema.Types.ObjectId, ref: 'User', required: true },\n name: { type: String, required: true },\n expiresAt: { type: Date },\n accessToken: { type: [String], required: true, default: [] },\n rights: { type: TokenRightsSchema, required: true },\n },\n {\n timestamps: true,\n }\n);\n\nconst projectConfigSchema = new Schema<Project['configuration']>(\n {\n internationalization: {\n locales: {\n type: [String],\n enum: Object.values(Locales),\n required: true,\n },\n defaultLocale: {\n type: String,\n enum: Object.values(Locales),\n },\n },\n editor: {\n applicationURL: {\n type: String,\n },\n cmsURL: {\n type: String,\n },\n },\n },\n {\n _id: false, // Prevents the generation of an _id field for this subdocument\n }\n);\n\nexport const projectSchema = new Schema<Project>(\n {\n organizationId: {\n type: Schema.Types.ObjectId,\n ref: 'Organization',\n required: true,\n },\n name: {\n type: String,\n required: true,\n minlength: NAME_MIN_LENGTH,\n maxlength: NAME_MAX_LENGTH,\n },\n configuration: projectConfigSchema,\n oAuth2Access: [oAuth2AccessSchema],\n membersIds: {\n type: [Schema.Types.ObjectId],\n ref: 'User',\n required: true,\n minlength: MEMBERS_MIN_LENGTH,\n },\n adminsIds: {\n type: [Schema.Types.ObjectId],\n ref: 'User',\n required: true,\n minlength: MEMBERS_MIN_LENGTH,\n },\n creatorId: {\n type: Schema.Types.ObjectId,\n ref: 'User',\n required: true,\n },\n },\n {\n timestamps: true,\n }\n);\n"],"mappings":"AAAA,SAAS,eAAe;AACxB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,cAAc;AAGvB,MAAM,eAAe,IAAI,OAAe;AAAA,EACtC,MAAM,EAAE,MAAM,SAAS,UAAU,KAAK;AAAA,EACtC,OAAO,EAAE,MAAM,SAAS,UAAU,KAAK;AAAA,EACvC,OAAO,EAAE,MAAM,SAAS,UAAU,KAAK;AACzC,CAAC;AAEM,MAAM,oBAAoB,IAAI,OAAoB;AAAA,EACvD,YAAY,EAAE,MAAM,cAAc,UAAU,KAAK;AAAA,EACjD,SAAS,EAAE,MAAM,cAAc,UAAU,KAAK;AAAA,EAC9C,cAAc,EAAE,MAAM,cAAc,UAAU,KAAK;AACrD,CAAC;AAGD,MAAM,qBAAqB,IAAI;AAAA,EAC7B;AAAA,IACE,UAAU,EAAE,MAAM,QAAQ,UAAU,KAAK;AAAA,IACzC,cAAc,EAAE,MAAM,QAAQ,UAAU,KAAK;AAAA,IAC7C,QAAQ,EAAE,MAAM,OAAO,MAAM,UAAU,KAAK,QAAQ,UAAU,KAAK;AAAA,IACnE,MAAM,EAAE,MAAM,QAAQ,UAAU,KAAK;AAAA,IACrC,WAAW,EAAE,MAAM,KAAK;AAAA,IACxB,aAAa,EAAE,MAAM,CAAC,MAAM,GAAG,UAAU,MAAM,SAAS,CAAC,EAAE;AAAA,IAC3D,QAAQ,E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
|
|
|
1
|
-
{"version":3,"sources":["../../../src/services/dictionary.service.ts"],"sourcesContent":["import { DictionaryModel } from '@models/dictionary.model';\nimport { ensureMongoDocumentToObject } from '@utils/ensureMongoDocumentToObject';\nimport { GenericError } from '@utils/errors';\nimport type { DictionaryFilters } from '@utils/filtersAndPagination/getDictionaryFiltersAndPagination';\nimport { removeObjectKeys } from '@utils/removeObjectKeys';\nimport {\n type DictionaryFields,\n validateDictionary,\n} from '@utils/validation/validateDictionary';\nimport type { ObjectId } from 'mongoose';\nimport type {\n Dictionary,\n DictionaryData,\n DictionaryDocument,\n} from '@/types/dictionary.types';\nimport type { Project } from '@/types/project.types';\n\n/**\n * Finds dictionaries based on filters and pagination options.\n * @param filters - MongoDB filter query.\n * @param skip - Number of documents to skip.\n * @param limit - Number of documents to limit.\n * @returns List of dictionaries matching the filters.\n */\nexport const findDictionaries = async (\n filters: DictionaryFilters,\n skip = 0,\n limit = 100\n): Promise<DictionaryDocument[]> => {\n try {\n const dictionaries = await DictionaryModel.aggregate<DictionaryDocument>([\n // Stage 1: Match the filters\n { $match: filters },\n\n // Stage 2: Skip for pagination\n { $skip: skip },\n\n // Stage 3: Limit the number of documents\n { $limit: limit },\n\n // Stage 4: Add the 'availableVersions' field\n {\n $addFields: {\n availableVersions: {\n $map: {\n input: { $objectToArray: '$content' },\n as: 'version',\n in: '$$version.k',\n },\n },\n },\n },\n\n // (Optional) Stage 5: Project the fields you want to include/exclude\n // For example, to exclude the entire 'content' field and keep only 'availableVersions'\n // {\n // $project: {\n // content: 0 // Exclude the 'content' field\n // }\n // }\n ]);\n\n const formattedResults = dictionaries.map(\n (result) => new DictionaryModel(result)\n );\n\n return formattedResults;\n } catch (error) {\n console.error('Error fetching dictionaries:', error);\n throw error;\n }\n};\n\n/**\n * Finds a dictionary by its ID.\n * @param dictionaryId - The ID of the dictionary to find.\n * @returns The dictionary matching the ID.\n */\n/**\n * Finds a dictionary by its ID and includes the 'availableVersions' field.\n * @param dictionaryId - The ID of the dictionary to find.\n * @returns The dictionary matching the ID with available versions.\n */\nexport const getDictionaryById = async (\n dictionaryId: string | ObjectId\n): Promise<DictionaryDocument> => {\n const dictionaries = await DictionaryModel.aggregate<DictionaryDocument>([\n // Stage 1: Match the document by ID\n { $match: { _id: dictionaryId } },\n\n // Stage 2: Add the 'availableVersions' field\n {\n $addFields: {\n availableVersions: {\n $map: {\n input: { $objectToArray: '$content' },\n as: 'version',\n in: '$$version.k',\n },\n },\n },\n },\n ]);\n\n if (!dictionaries.length) {\n throw new GenericError('DICTIONARY_NOT_FOUND', { dictionaryId });\n }\n\n return new DictionaryModel(dictionaries[0]);\n};\n\n/**\n * Finds a dictionary by its ID.\n * @param dictionaryKey - The ID of the dictionary to find.\n * @returns The dictionary matching the ID.\n */\nexport const getDictionaryByKey = async (\n dictionaryKey: string,\n projectId: string | ObjectId\n): Promise<DictionaryDocument> => {\n const dictionaries = await getDictionariesByKeys([dictionaryKey], projectId);\n\n return dictionaries[0];\n};\n\nexport const getDictionariesByKeys = async (\n dictionaryKeys: string[],\n projectId: string | ObjectId\n): Promise<DictionaryDocument[]> => {\n const dictionaries = await DictionaryModel.aggregate<DictionaryDocument>([\n // Stage 1: Match the document by key\n { $match: { key: { $in: dictionaryKeys }, projectIds: projectId } },\n\n // Stage 2: Add the 'availableVersions' field\n {\n $addFields: {\n availableVersions: {\n $map: {\n input: { $objectToArray: '$content' },\n as: 'version',\n in: '$$version.k',\n },\n },\n },\n },\n ]);\n\n if (!dictionaries) {\n throw new GenericError('DICTIONARY_NOT_FOUND', {\n dictionaryKeys,\n projectId,\n });\n }\n\n const formattedResults = dictionaries.map(\n (result) => new DictionaryModel(result)\n );\n\n return formattedResults;\n};\n\nexport const getDictionariesKeys = async (\n projectId: string | ObjectId\n): Promise<string[]> => {\n const dictionaries = await DictionaryModel.find({\n projectIds: projectId,\n }).select('key');\n\n return dictionaries.map((dictionary) => dictionary.key);\n};\n\nexport const getDictionariesByTags = async (\n tags: string[],\n projectId: string | Project['_id']\n): Promise<DictionaryDocument[]> => {\n const dictionaries = await DictionaryModel.aggregate<DictionaryDocument>([\n // Stage 1: Match the document by tags\n {\n $match: {\n tags: { $in: tags },\n projectIds: projectId,\n },\n },\n\n // Stage 2: Add the 'availableVersions' field\n {\n $addFields: {\n availableVersions: {\n $map: {\n input: { $objectToArray: '$content' },\n as: 'version',\n in: '$$version.k',\n },\n },\n },\n },\n ]);\n\n const formattedResults = dictionaries.map(\n (result) => new DictionaryModel(result)\n );\n\n return formattedResults;\n};\n\n/**\n * Counts the total number of dictionaries that match the filters.\n * @param filters - MongoDB filter query.\n * @returns Total number of dictionaries.\n */\nexport const countDictionaries = async (\n filters: DictionaryFilters\n): Promise<number> => {\n const result = await DictionaryModel.countDocuments(filters);\n\n if (typeof result === 'undefined') {\n throw new GenericError('DICTIONARY_COUNT_FAILED', { filters });\n }\n\n return result;\n};\n\n/**\n * Creates a new dictionary in the database.\n * @param dictionary - The dictionary data to create.\n * @returns The created dictionary.\n */\nexport const createDictionary = async (\n dictionary: DictionaryData\n): Promise<DictionaryDocument> => {\n const errors = await validateDictionary(dictionary);\n\n if (Object.keys(errors).length > 0) {\n throw new GenericError('DICTIONARY_INVALID_FIELDS', {\n errors,\n });\n }\n\n return await DictionaryModel.create(dictionary);\n};\n\ntype GetExistingDictionaryResult = {\n existingDictionariesKey: string[];\n newDictionariesKey: string[];\n};\n\n/**\n * Gets the existing dictionaries from the provided list of keys.\n * @param dictionariesKeys - List of dictionary keys to check.\n * @param projectId - The ID of the project to check the dictionaries against.\n * @returns The existing dictionaries and the new dictionaries.\n */\nexport const getExistingDictionaryKey = async (\n dictionariesKeys: string[],\n projectId: string | ObjectId\n): Promise<GetExistingDictionaryResult> => {\n // Fetch dictionaries from the database where the key is in the provided list\n const existingDictionaries = await DictionaryModel.find({\n key: { $in: dictionariesKeys },\n projectIds: projectId,\n });\n\n // Map existing dictionaries to a LocalDictionary object\n const existingDictionariesKey: string[] = [];\n const newDictionariesKey: string[] = [];\n\n for (const key of dictionariesKeys) {\n const isDictionaryExist = existingDictionaries.some(\n (dictionary) => dictionary.key === key\n );\n\n if (isDictionaryExist) {\n existingDictionariesKey.push(key);\n } else {\n newDictionariesKey.push(key);\n }\n }\n\n return { existingDictionariesKey, newDictionariesKey };\n};\n\n/**\n * Updates an existing dictionary in the database by its ID.\n * @param dictionaryId - The ID of the dictionary to update.\n * @param dictionary - The updated dictionary data.\n * @returns The updated dictionary.\n */\nexport const updateDictionaryById = async (\n dictionaryId: string | ObjectId,\n dictionary: Partial<Dictionary>\n): Promise<DictionaryDocument> => {\n const dictionaryObject = ensureMongoDocumentToObject(dictionary);\n const dictionaryToUpdate = removeObjectKeys(dictionaryObject, ['_id']);\n\n const updatedKeys = Object.keys(dictionaryToUpdate) as DictionaryFields;\n const errors = await validateDictionary(dictionaryToUpdate, updatedKeys);\n\n if (Object.keys(errors).length > 0) {\n throw new GenericError('DICTIONARY_INVALID_FIELDS', {\n dictionaryId,\n errors,\n });\n }\n\n const result = await DictionaryModel.updateOne(\n { _id: dictionaryId },\n dictionaryToUpdate\n );\n\n if (result.matchedCount === 0) {\n throw new GenericError('DICTIONARY_UPDATE_FAILED', { dictionaryId });\n }\n\n const updatedDictionary = await getDictionaryById(dictionaryId);\n\n return updatedDictionary;\n};\n\n/**\n * Updates an existing dictionary in the database by its key.\n * @param dictionaryKey - The ID of the dictionary to update.\n * @param dictionary - The updated dictionary data.\n * @returns The updated dictionary.\n */\nexport const updateDictionaryByKey = async (\n dictionaryKey: string,\n dictionary: Partial<Dictionary>,\n projectId: string | ObjectId\n): Promise<DictionaryDocument> => {\n const dictionaryObject = ensureMongoDocumentToObject(dictionary);\n\n const dictionaryToUpdate = removeObjectKeys(dictionaryObject, ['_id']);\n\n const updatedKeys = Object.keys(dictionaryToUpdate) as DictionaryFields;\n const errors = await validateDictionary(dictionaryToUpdate, updatedKeys);\n\n if (Object.keys(errors).length > 0) {\n throw new GenericError('DICTIONARY_INVALID_FIELDS', {\n dictionaryKey,\n projectId,\n errors,\n });\n }\n\n const result = await DictionaryModel.updateOne(\n { key: dictionaryKey, projectIds: projectId },\n dictionaryToUpdate\n );\n\n if (result.matchedCount === 0) {\n throw new GenericError('DICTIONARY_UPDATE_FAILED', { dictionaryKey });\n }\n\n const updatedDictionary = await getDictionaryByKey(dictionaryKey, projectId);\n\n return updatedDictionary;\n};\n\n/**\n * Deletes a dictionary from the database by its ID.\n * @param dictionaryId - The ID of the dictionary to delete.\n * @returns The result of the deletion operation.\n */\nexport const deleteDictionaryById = async (\n dictionaryId: string\n): Promise<DictionaryDocument> => {\n const dictionary = await DictionaryModel.findByIdAndDelete(dictionaryId);\n\n if (!dictionary) {\n throw new GenericError('DICTIONARY_NOT_FOUND', { dictionaryId });\n }\n\n return dictionary;\n};\n\nexport const incrementVersion = (dictionary: Dictionary): string => {\n const VERSION_PREFIX = 'v';\n const availableVersions = dictionary.availableVersions ?? [];\n\n // Get the current version from the version list, default to 'v1' if not present\n const currentVersion =\n availableVersions.length > 0\n ? availableVersions[availableVersions.length - 1]\n : 'v1';\n\n // Function to extract the numeric part of the version\n const getVersionNumber = (version: string): number => {\n const match = version.match(/^v(\\d+)$/);\n if (!match) {\n throw new Error(`Invalid version format: ${version}`);\n }\n return parseInt(match[1], 10);\n };\n\n // Start with the next version number\n let newNumber = getVersionNumber(currentVersion) + 1;\n let newVersion = `${VERSION_PREFIX}${newNumber}`;\n\n // Loop until a unique version is found\n while (availableVersions.includes(newVersion)) {\n newNumber += 1;\n newVersion = `${VERSION_PREFIX}${newNumber}`;\n }\n\n return newVersion;\n};\n"],"mappings":"AAAA,SAAS,uBAAuB;AAChC,SAAS,mCAAmC;AAC5C,SAAS,oBAAoB;AAE7B,SAAS,wBAAwB;AACjC;AAAA,EAEE;AAAA,OACK;AAgBA,MAAM,mBAAmB,OAC9B,SACA,OAAO,GACP,QAAQ,QAC0B;AAClC,MAAI;AACF,UAAM,eAAe,MAAM,gBAAgB,UAA8B;AAAA;AAAA,MAEvE,E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AAI,CAAC,OAAO;AACV,YAAM,IAAI,MAAM,2BAA2B,OAAO,EAAE;AAAA,IACtD;AACA,WAAO,SAAS,MAAM,CAAC,GAAG,EAAE;AAAA,EAC9B;AAGA,MAAI,YAAY,iBAAiB,cAAc,IAAI;AACnD,MAAI,aAAa,GAAG,cAAc,GAAG,SAAS;AAG9C,SAAO,kBAAkB,SAAS,UAAU,GAAG;AAC7C,iBAAa;AACb,iBAAa,GAAG,cAAc,GAAG,SAAS;AAAA,EAC5C;AAEA,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/services/dictionary.service.ts"],"sourcesContent":["import { DictionaryModel } from '@models/dictionary.model';\nimport { ensureMongoDocumentToObject } from '@utils/ensureMongoDocumentToObject';\nimport { GenericError } from '@utils/errors';\nimport type { DictionaryFilters } from '@utils/filtersAndPagination/getDictionaryFiltersAndPagination';\nimport { removeObjectKeys } from '@utils/removeObjectKeys';\nimport {\n type DictionaryFields,\n validateDictionary,\n} from '@utils/validation/validateDictionary';\nimport type { ObjectId } from 'mongoose';\nimport type {\n Dictionary,\n DictionaryData,\n DictionaryDocument,\n} from '@/types/dictionary.types';\nimport type { Project } from '@/types/project.types';\n\n/**\n * Finds dictionaries based on filters and pagination options.\n * @param filters - MongoDB filter query.\n * @param skip - Number of documents to skip.\n * @param limit - Number of documents to limit.\n * @returns List of dictionaries matching the filters.\n */\nexport const findDictionaries = async (\n filters: DictionaryFilters,\n skip = 0,\n limit = 100\n): Promise<DictionaryDocument[]> => {\n try {\n const dictionaries = await DictionaryModel.aggregate<DictionaryDocument>([\n // Stage 1: Match the filters\n { $match: filters },\n\n // Stage 2: Skip for pagination\n { $skip: skip },\n\n // Stage 3: Limit the number of documents\n { $limit: limit },\n\n // Stage 4: Add the 'availableVersions' field\n {\n $addFields: {\n availableVersions: {\n $map: {\n input: { $objectToArray: '$content' },\n as: 'version',\n in: '$$version.k',\n },\n },\n },\n },\n\n // (Optional) Stage 5: Project the fields you want to include/exclude\n // For example, to exclude the entire 'content' field and keep only 'availableVersions'\n // {\n // $project: {\n // content: 0 // Exclude the 'content' field\n // }\n // }\n ]);\n\n const formattedResults = dictionaries.map(\n (result) => new DictionaryModel(result)\n );\n\n return formattedResults;\n } catch (error) {\n console.error('Error fetching dictionaries:', error);\n throw error;\n }\n};\n\n/**\n * Finds a dictionary by its ID.\n * @param dictionaryId - The ID of the dictionary to find.\n * @returns The dictionary matching the ID.\n */\n/**\n * Finds a dictionary by its ID and includes the 'availableVersions' field.\n * @param dictionaryId - The ID of the dictionary to find.\n * @returns The dictionary matching the ID with available versions.\n */\nexport const getDictionaryById = async (\n dictionaryId: string | ObjectId\n): Promise<DictionaryDocument> => {\n const dictionaries = await DictionaryModel.aggregate<DictionaryDocument>([\n // Stage 1: Match the document by ID\n { $match: { _id: dictionaryId } },\n\n // Stage 2: Add the 'availableVersions' field\n {\n $addFields: {\n availableVersions: {\n $map: {\n input: { $objectToArray: '$content' },\n as: 'version',\n in: '$$version.k',\n },\n },\n },\n },\n ]);\n\n if (!dictionaries.length) {\n throw new GenericError('DICTIONARY_NOT_FOUND', { dictionaryId });\n }\n\n return new DictionaryModel(dictionaries[0]);\n};\n\n/**\n * Finds a dictionary by its ID.\n * @param dictionaryKey - The ID of the dictionary to find.\n * @returns The dictionary matching the ID.\n */\nexport const getDictionaryByKey = async (\n dictionaryKey: string,\n projectId: string | ObjectId\n): Promise<DictionaryDocument> => {\n const dictionaries = await getDictionariesByKeys([dictionaryKey], projectId);\n\n return dictionaries[0];\n};\n\nexport const getDictionariesByKeys = async (\n dictionaryKeys: string[],\n projectId: string | ObjectId\n): Promise<DictionaryDocument[]> => {\n const dictionaries = await DictionaryModel.aggregate<DictionaryDocument>([\n // Stage 1: Match the document by key\n { $match: { key: { $in: dictionaryKeys }, projectIds: projectId } },\n\n // Stage 2: Add the 'availableVersions' field\n {\n $addFields: {\n availableVersions: {\n $map: {\n input: { $objectToArray: '$content' },\n as: 'version',\n in: '$$version.k',\n },\n },\n },\n },\n ]);\n\n if (!dictionaries) {\n throw new GenericError('DICTIONARY_NOT_FOUND', {\n dictionaryKeys,\n projectId,\n });\n }\n\n const formattedResults = dictionaries.map(\n (result) => new DictionaryModel(result)\n );\n\n return formattedResults;\n};\n\nexport const getDictionariesKeys = async (\n projectId: string | ObjectId\n): Promise<string[]> => {\n const dictionaries = await DictionaryModel.find({\n projectIds: projectId,\n }).select('key');\n\n return dictionaries.map((dictionary) => dictionary.key);\n};\n\nexport const getDictionariesByTags = async (\n tags: string[],\n projectId: string | Project['_id']\n): Promise<DictionaryDocument[]> => {\n const dictionaries = await DictionaryModel.aggregate<DictionaryDocument>([\n // Stage 1: Match the document by tags\n {\n $match: {\n tags: { $in: tags },\n projectIds: projectId,\n },\n },\n\n // Stage 2: Add the 'availableVersions' field\n {\n $addFields: {\n availableVersions: {\n $map: {\n input: { $objectToArray: '$content' },\n as: 'version',\n in: '$$version.k',\n },\n },\n },\n },\n ]);\n\n const formattedResults = dictionaries.map(\n (result) => new DictionaryModel(result)\n );\n\n return formattedResults;\n};\n\n/**\n * Counts the total number of dictionaries that match the filters.\n * @param filters - MongoDB filter query.\n * @returns Total number of dictionaries.\n */\nexport const countDictionaries = async (\n filters: DictionaryFilters\n): Promise<number> => {\n const result = await DictionaryModel.countDocuments(filters);\n\n if (typeof result === 'undefined') {\n throw new GenericError('DICTIONARY_COUNT_FAILED', { filters });\n }\n\n return result;\n};\n\n/**\n * Creates a new dictionary in the database.\n * @param dictionary - The dictionary data to create.\n * @returns The created dictionary.\n */\nexport const createDictionary = async (\n dictionary: DictionaryData\n): Promise<DictionaryDocument> => {\n const errors = await validateDictionary(dictionary);\n\n if (Object.keys(errors).length > 0) {\n throw new GenericError('DICTIONARY_INVALID_FIELDS', {\n errors,\n });\n }\n\n return await DictionaryModel.create(dictionary);\n};\n\ntype GetExistingDictionaryResult = {\n existingDictionariesKey: string[];\n newDictionariesKey: string[];\n};\n\n/**\n * Gets the existing dictionaries from the provided list of keys.\n * @param dictionariesKeys - List of dictionary keys to check.\n * @param projectId - The ID of the project to check the dictionaries against.\n * @returns The existing dictionaries and the new dictionaries.\n */\nexport const getExistingDictionaryKey = async (\n dictionariesKeys: string[],\n projectId: string | ObjectId\n): Promise<GetExistingDictionaryResult> => {\n // Fetch dictionaries from the database where the key is in the provided list\n const existingDictionaries = await DictionaryModel.find({\n key: { $in: dictionariesKeys },\n projectIds: projectId,\n });\n\n // Map existing dictionaries to a LocalDictionary object\n const existingDictionariesKey: string[] = [];\n const newDictionariesKey: string[] = [];\n\n for (const key of dictionariesKeys) {\n const isDictionaryExist = existingDictionaries.some(\n (dictionary) => dictionary.key === key\n );\n\n if (isDictionaryExist) {\n existingDictionariesKey.push(key);\n } else {\n newDictionariesKey.push(key);\n }\n }\n\n return { existingDictionariesKey, newDictionariesKey };\n};\n\n/**\n * Updates an existing dictionary in the database by its ID.\n * @param dictionaryId - The ID of the dictionary to update.\n * @param dictionary - The updated dictionary data.\n * @returns The updated dictionary.\n */\nexport const updateDictionaryById = async (\n dictionaryId: string | ObjectId,\n dictionary: Partial<Dictionary>\n): Promise<DictionaryDocument> => {\n const dictionaryObject = ensureMongoDocumentToObject(dictionary);\n const dictionaryToUpdate = removeObjectKeys(dictionaryObject, ['_id']);\n\n const updatedKeys = Object.keys(dictionaryToUpdate) as DictionaryFields;\n const errors = await validateDictionary(dictionaryToUpdate, updatedKeys);\n\n if (Object.keys(errors).length > 0) {\n throw new GenericError('DICTIONARY_INVALID_FIELDS', {\n dictionaryId,\n errors,\n });\n }\n\n const result = await DictionaryModel.updateOne(\n { _id: dictionaryId },\n dictionaryToUpdate\n );\n\n if (result.matchedCount === 0) {\n throw new GenericError('DICTIONARY_UPDATE_FAILED', { dictionaryId });\n }\n\n const updatedDictionary = await getDictionaryById(dictionaryId);\n\n return updatedDictionary;\n};\n\n/**\n * Updates an existing dictionary in the database by its key.\n * @param dictionaryKey - The ID of the dictionary to update.\n * @param dictionary - The updated dictionary data.\n * @returns The updated dictionary.\n */\nexport const updateDictionaryByKey = async (\n dictionaryKey: string,\n dictionary: Partial<Dictionary>,\n projectId: string | ObjectId\n): Promise<DictionaryDocument> => {\n const dictionaryObject = ensureMongoDocumentToObject(dictionary);\n const dictionaryToUpdate = removeObjectKeys(dictionaryObject, ['_id']);\n\n const updatedKeys = Object.keys(dictionaryToUpdate) as DictionaryFields;\n const errors = await validateDictionary(dictionaryToUpdate, updatedKeys);\n\n if (Object.keys(errors).length > 0) {\n throw new GenericError('DICTIONARY_INVALID_FIELDS', {\n dictionaryKey,\n projectId,\n errors,\n });\n }\n\n const result = await DictionaryModel.updateOne(\n { key: dictionaryKey, projectIds: projectId },\n dictionaryToUpdate\n );\n\n if (result.matchedCount === 0) {\n throw new GenericError('DICTIONARY_UPDATE_FAILED', { dictionaryKey });\n }\n\n const updatedDictionary = await getDictionaryByKey(dictionaryKey, projectId);\n\n return updatedDictionary;\n};\n\n/**\n * Deletes a dictionary from the database by its ID.\n * @param dictionaryId - The ID of the dictionary to delete.\n * @returns The result of the deletion operation.\n */\nexport const deleteDictionaryById = async (\n dictionaryId: string\n): Promise<DictionaryDocument> => {\n const dictionary = await DictionaryModel.findByIdAndDelete(dictionaryId);\n\n if (!dictionary) {\n throw new GenericError('DICTIONARY_NOT_FOUND', { dictionaryId });\n }\n\n return dictionary;\n};\n\nexport const incrementVersion = (dictionary: Dictionary): string => {\n const VERSION_PREFIX = 'v';\n const availableVersions = dictionary.availableVersions ?? [];\n\n // Get the current version from the version list, default to 'v1' if not present\n const currentVersion =\n availableVersions.length > 0\n ? availableVersions[availableVersions.length - 1]\n : 'v1';\n\n // Function to extract the numeric part of the version\n const getVersionNumber = (version: string): number => {\n const match = version.match(/^v(\\d+)$/);\n if (!match) {\n throw new Error(`Invalid version format: ${version}`);\n }\n return parseInt(match[1], 10);\n };\n\n // Start with the next version number\n let newNumber = getVersionNumber(currentVersion) + 1;\n let newVersion = `${VERSION_PREFIX}${newNumber}`;\n\n // Loop until a unique version is found\n while (availableVersions.includes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AACf,UAAM,IAAI,aAAa,wBAAwB,EAAE,aAAa,CAAC;AAAA,EACjE;AAEA,SAAO;AACT;AAEO,MAAM,mBAAmB,CAAC,eAAmC;AAClE,QAAM,iBAAiB;AACvB,QAAM,oBAAoB,WAAW,qBAAqB,CAAC;AAG3D,QAAM,iBACJ,kBAAkB,SAAS,IACvB,kBAAkB,kBAAkB,SAAS,CAAC,IAC9C;AAGN,QAAM,mBAAmB,CAAC,YAA4B;AACpD,UAAM,QAAQ,QAAQ,MAAM,UAAU;AACtC,QAAI,CAAC,OAAO;AACV,YAAM,IAAI,MAAM,2BAA2B,OAAO,EAAE;AAAA,IACtD;AACA,WAAO,SAAS,MAAM,CAAC,GAAG,EAAE;AAAA,EAC9B;AAGA,MAAI,YAAY,iBAAiB,cAAc,IAAI;AACnD,MAAI,aAAa,GAAG,cAAc,GAAG,SAAS;AAG9C,SAAO,kBAAkB,SAAS,UAAU,GAAG;AAC7C,iBAAa;AACb,iBAAa,GAAG,cAAc,GAAG,SAAS;AAAA,EAC5C;AAEA,SAAO;AACT;","names":[]}
|
|
@@ -183,7 +183,7 @@ const sendEmail = async ({
|
|
|
183
183
|
const EmailComponent = template;
|
|
184
184
|
const react = /* @__PURE__ */ jsx(EmailComponent, { ...props });
|
|
185
185
|
await resend.emails.send({
|
|
186
|
-
from: "Intlayer <no-
|
|
186
|
+
from: "Intlayer <no-reply@intlayer.org>",
|
|
187
187
|
to,
|
|
188
188
|
subject: subject ?? baseSubject,
|
|
189
189
|
react
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/services/email.service.tsx"],"sourcesContent":["import {\n InviteUserEmailEN,\n InviteUserEmailFR,\n InviteUserEmailES,\n} from '@emails/InviteUserEmail';\nimport {\n PasswordChangeConfirmationEmailEN,\n PasswordChangeConfirmationEmailFR,\n PasswordChangeConfirmationEmailES,\n} from '@emails/PasswordChangeConfirmation';\nimport {\n ResetPasswordEmailEN,\n ResetPasswordEmailFR,\n ResetPasswordEmailES,\n} from '@emails/ResetUserPassword';\n\nimport {\n SubscriptionPaymentCancellationEN,\n SubscriptionPaymentCancellationFR,\n SubscriptionPaymentCancellationES,\n} from '@emails/SubscriptionPaymentCancellation';\nimport {\n SubscriptionPaymentErrorEN,\n SubscriptionPaymentErrorFR,\n SubscriptionPaymentErrorES,\n} from '@emails/SubscriptionPaymentError';\nimport {\n SubscriptionPaymentSuccessEN,\n SubscriptionPaymentSuccessFR,\n SubscriptionPaymentSuccessES,\n} from '@emails/SubscriptionPaymentSuccess';\nimport {\n ValidateUserEmailEN,\n ValidateUserEmailFR,\n ValidateUserEmailES,\n} from '@emails/ValidateUserEmail';\nimport {\n WelcomeEmailEN,\n WelcomeEmailFR,\n WelcomeEmailES,\n} from '@emails/Welcome';\n\nimport { logger } from '@logger';\nimport { t } from 'express-intlayer';\nimport type { Locales } from 'intlayer';\nimport type { ComponentProps, JSX } from 'react';\nimport { Resend } from 'resend';\n\ntype EmailComponentsType = (...props: any) => JSX.Element;\ntype EmailComponents = {\n [key: string]: {\n template: EmailComponentsType;\n subject: string;\n };\n};\n\nconst getEmailComponents = (locale?: Locales) =>\n ({\n invite: {\n template: t(\n {\n en: InviteUserEmailEN,\n fr: InviteUserEmailFR,\n es: InviteUserEmailES,\n },\n locale\n ),\n subject: t(\n {\n en: 'You have been invited to join Intlayer',\n fr: 'Vous êtes invité à rejoindre Intlayer',\n es: 'Has sido invitado a unirte a Intlayer',\n },\n locale\n ),\n },\n validate: {\n template: t(\n {\n en: ValidateUserEmailEN,\n fr: ValidateUserEmailFR,\n es: ValidateUserEmailES,\n },\n locale\n ),\n subject: t(\n {\n en: 'Validate your email for Intlayer',\n fr: 'Validez votre email pour Intlayer',\n es: 'Valida tu correo electrónico para Intlayer',\n },\n locale\n ),\n },\n resetPassword: {\n template: t(\n {\n en: ResetPasswordEmailEN,\n fr: ResetPasswordEmailFR,\n es: ResetPasswordEmailES,\n },\n locale\n ),\n subject: t(\n {\n en: 'Reset your password for Intlayer',\n fr: 'Réinitialisez votre mot de passe pour Intlayer',\n es: 'Restablece tu contraseña para Intlayer',\n },\n locale\n ),\n },\n welcome: {\n template: t(\n {\n en: WelcomeEmailEN,\n fr: WelcomeEmailFR,\n es: WelcomeEmailES,\n },\n locale\n ),\n subject: t(\n {\n en: 'Welcome to Intlayer!',\n fr: 'Bienvenue chez Intlayer!',\n es: '¡Bienvenido a Intlayer!',\n },\n locale\n ),\n },\n passwordChangeConfirmation: {\n template: t(\n {\n en: PasswordChangeConfirmationEmailEN,\n fr: PasswordChangeConfirmationEmailFR,\n es: PasswordChangeConfirmationEmailES,\n },\n locale\n ),\n subject: t(\n {\n en: 'Your Intlayer password has been changed',\n fr: 'Votre mot de passe Intlayer a été modifié',\n es: 'Tu contraseña de Intlayer ha sido cambiada',\n },\n locale\n ),\n },\n subscriptionPaymentSuccess: {\n template: t({\n en: SubscriptionPaymentSuccessEN,\n fr: SubscriptionPaymentSuccessFR,\n es: SubscriptionPaymentSuccessES,\n }),\n subject: t({\n en: 'Your payment for Intlayer subscription is confirmed',\n fr: \"Votre paiement pour l'abonnement Intlayer est confirmé\",\n es: 'Tu pago por la suscripción de Intlayer ha sido confirmado',\n }),\n },\n subscriptionPaymentCancellation: {\n template: t({\n en: SubscriptionPaymentCancellationEN,\n fr: SubscriptionPaymentCancellationFR,\n es: SubscriptionPaymentCancellationES,\n }),\n subject: t({\n en: 'Your Intlayer subscription has been canceled',\n fr: 'Votre abonnement Intlayer a été annulé',\n es: 'Tu suscripción de Intlayer ha sido cancelada',\n }),\n },\n subscriptionPaymentError: {\n template: t({\n en: SubscriptionPaymentErrorEN,\n fr: SubscriptionPaymentErrorFR,\n es: SubscriptionPaymentErrorES,\n }),\n subject: t({\n en: 'There was an issue with your Intlayer subscription payment',\n fr: \"Un problème est survenu avec votre paiement pour l'abonnement Intlayer\",\n es: 'Hubo un problema con el pago de tu suscripción de Intlayer',\n }),\n },\n }) satisfies EmailComponents;\n\ntype EmailType = keyof ReturnType<typeof getEmailComponents>;\n\nexport type SendEmailProps<T extends EmailType> = {\n type: T;\n to: string;\n subject?: string;\n locale?: Locales;\n} & ComponentProps<ReturnType<typeof getEmailComponents>[T]['template']>;\n\nexport const sendEmail = async <T extends EmailType>({\n type,\n to,\n subject,\n locale,\n ...props\n}: SendEmailProps<T>) => {\n const resend = new Resend(process.env.RESEND_API_KEY);\n\n const emailComponents = getEmailComponents(locale);\n\n const { template, subject: baseSubject } = emailComponents[type];\n\n type EmailComponentType = (typeof emailComponents)[T]['template'];\n\n const EmailComponent: EmailComponentType = template;\n\n const react = <EmailComponent {...(props as any)} />;\n\n await resend.emails\n .send({\n from: 'Intlayer <no-
|
|
1
|
+
{"version":3,"sources":["../../../src/services/email.service.tsx"],"sourcesContent":["import {\n InviteUserEmailEN,\n InviteUserEmailFR,\n InviteUserEmailES,\n} from '@emails/InviteUserEmail';\nimport {\n PasswordChangeConfirmationEmailEN,\n PasswordChangeConfirmationEmailFR,\n PasswordChangeConfirmationEmailES,\n} from '@emails/PasswordChangeConfirmation';\nimport {\n ResetPasswordEmailEN,\n ResetPasswordEmailFR,\n ResetPasswordEmailES,\n} from '@emails/ResetUserPassword';\n\nimport {\n SubscriptionPaymentCancellationEN,\n SubscriptionPaymentCancellationFR,\n SubscriptionPaymentCancellationES,\n} from '@emails/SubscriptionPaymentCancellation';\nimport {\n SubscriptionPaymentErrorEN,\n SubscriptionPaymentErrorFR,\n SubscriptionPaymentErrorES,\n} from '@emails/SubscriptionPaymentError';\nimport {\n SubscriptionPaymentSuccessEN,\n SubscriptionPaymentSuccessFR,\n SubscriptionPaymentSuccessES,\n} from '@emails/SubscriptionPaymentSuccess';\nimport {\n ValidateUserEmailEN,\n ValidateUserEmailFR,\n ValidateUserEmailES,\n} from '@emails/ValidateUserEmail';\nimport {\n WelcomeEmailEN,\n WelcomeEmailFR,\n WelcomeEmailES,\n} from '@emails/Welcome';\n\nimport { logger } from '@logger';\nimport { t } from 'express-intlayer';\nimport type { Locales } from 'intlayer';\nimport type { ComponentProps, JSX } from 'react';\nimport { Resend } from 'resend';\n\ntype EmailComponentsType = (...props: any) => JSX.Element;\ntype EmailComponents = {\n [key: string]: {\n template: EmailComponentsType;\n subject: string;\n };\n};\n\nconst getEmailComponents = (locale?: Locales) =>\n ({\n invite: {\n template: t(\n {\n en: InviteUserEmailEN,\n fr: InviteUserEmailFR,\n es: InviteUserEmailES,\n },\n locale\n ),\n subject: t(\n {\n en: 'You have been invited to join Intlayer',\n fr: 'Vous êtes invité à rejoindre Intlayer',\n es: 'Has sido invitado a unirte a Intlayer',\n },\n locale\n ),\n },\n validate: {\n template: t(\n {\n en: ValidateUserEmailEN,\n fr: ValidateUserEmailFR,\n es: ValidateUserEmailES,\n },\n locale\n ),\n subject: t(\n {\n en: 'Validate your email for Intlayer',\n fr: 'Validez votre email pour Intlayer',\n es: 'Valida tu correo electrónico para Intlayer',\n },\n locale\n ),\n },\n resetPassword: {\n template: t(\n {\n en: ResetPasswordEmailEN,\n fr: ResetPasswordEmailFR,\n es: ResetPasswordEmailES,\n },\n locale\n ),\n subject: t(\n {\n en: 'Reset your password for Intlayer',\n fr: 'Réinitialisez votre mot de passe pour Intlayer',\n es: 'Restablece tu contraseña para Intlayer',\n },\n locale\n ),\n },\n welcome: {\n template: t(\n {\n en: WelcomeEmailEN,\n fr: WelcomeEmailFR,\n es: WelcomeEmailES,\n },\n locale\n ),\n subject: t(\n {\n en: 'Welcome to Intlayer!',\n fr: 'Bienvenue chez Intlayer!',\n es: '¡Bienvenido a Intlayer!',\n },\n locale\n ),\n },\n passwordChangeConfirmation: {\n template: t(\n {\n en: PasswordChangeConfirmationEmailEN,\n fr: PasswordChangeConfirmationEmailFR,\n es: PasswordChangeConfirmationEmailES,\n },\n locale\n ),\n subject: t(\n {\n en: 'Your Intlayer password has been changed',\n fr: 'Votre mot de passe Intlayer a été modifié',\n es: 'Tu contraseña de Intlayer ha sido cambiada',\n },\n locale\n ),\n },\n subscriptionPaymentSuccess: {\n template: t({\n en: SubscriptionPaymentSuccessEN,\n fr: SubscriptionPaymentSuccessFR,\n es: SubscriptionPaymentSuccessES,\n }),\n subject: t({\n en: 'Your payment for Intlayer subscription is confirmed',\n fr: \"Votre paiement pour l'abonnement Intlayer est confirmé\",\n es: 'Tu pago por la suscripción de Intlayer ha sido confirmado',\n }),\n },\n subscriptionPaymentCancellation: {\n template: t({\n en: SubscriptionPaymentCancellationEN,\n fr: SubscriptionPaymentCancellationFR,\n es: SubscriptionPaymentCancellationES,\n }),\n subject: t({\n en: 'Your Intlayer subscription has been canceled',\n fr: 'Votre abonnement Intlayer a été annulé',\n es: 'Tu suscripción de Intlayer ha sido cancelada',\n }),\n },\n subscriptionPaymentError: {\n template: t({\n en: SubscriptionPaymentErrorEN,\n fr: SubscriptionPaymentErrorFR,\n es: SubscriptionPaymentErrorES,\n }),\n subject: t({\n en: 'There was an issue with your Intlayer subscription payment',\n fr: \"Un problème est survenu avec votre paiement pour l'abonnement Intlayer\",\n es: 'Hubo un problema con el pago de tu suscripción de Intlayer',\n }),\n },\n }) satisfies EmailComponents;\n\ntype EmailType = keyof ReturnType<typeof getEmailComponents>;\n\nexport type SendEmailProps<T extends EmailType> = {\n type: T;\n to: string;\n subject?: string;\n locale?: Locales;\n} & ComponentProps<ReturnType<typeof getEmailComponents>[T]['template']>;\n\nexport const sendEmail = async <T extends EmailType>({\n type,\n to,\n subject,\n locale,\n ...props\n}: SendEmailProps<T>) => {\n const resend = new Resend(process.env.RESEND_API_KEY);\n\n const emailComponents = getEmailComponents(locale);\n\n const { template, subject: baseSubject } = emailComponents[type];\n\n type EmailComponentType = (typeof emailComponents)[T]['template'];\n\n const EmailComponent: EmailComponentType = template;\n\n const react = <EmailComponent {...(props as any)} />;\n\n await resend.emails\n .send({\n from: 'Intlayer <no-reply@intlayer.org>',\n to,\n subject: subject ?? baseSubject,\n react,\n })\n .catch((err) => logger.error(err));\n\n logger.info(`Email sent ${type} to ${to}`);\n};\n"],"mappings":"AAoNgB;AApNhB;AAA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EACA;AAAA,EACA,GAAG;AACL,MAAyB;AACvB,QAAM,SAAS,IAAI,OAAO,QAAQ,IAAI,cAAc;AAEpD,QAAM,kBAAkB,mBAAmB,MAAM;AAEjD,QAAM,EAAE,UAAU,SAAS,YAAY,IAAI,gBAAgB,IAAI;AAI/D,QAAM,iBAAqC;AAE3C,QAAM,QAAQ,oBAAC,kBAAgB,GAAI,OAAe;AAElD,QAAM,OAAO,OACV,KAAK;AAAA,IACJ,MAAM;AAAA,IACN;AAAA,IACA,SAAS,WAAW;AAAA,IACpB;AAAA,EACF,CAAC,EACA,MAAM,CAAC,QAAQ,OAAO,MAAM,GAAG,CAAC;AAEnC,SAAO,KAAK,cAAc,IAAI,OAAO,EAAE,EAAE;AAC3C;","names":[]}
|
|
@@ -126,6 +126,7 @@ const changeSubscriptionStatus = async (subscriptionId, status, userId, organiza
|
|
|
126
126
|
await sendEmail({
|
|
127
127
|
...emailData,
|
|
128
128
|
type: "subscriptionPaymentSuccess",
|
|
129
|
+
organizationName: organization.name,
|
|
129
130
|
subscriptionStartDate: emailData.date,
|
|
130
131
|
manageSubscriptionLink: emailData.link
|
|
131
132
|
});
|
|
@@ -134,6 +135,7 @@ const changeSubscriptionStatus = async (subscriptionId, status, userId, organiza
|
|
|
134
135
|
await sendEmail({
|
|
135
136
|
...emailData,
|
|
136
137
|
type: "subscriptionPaymentCancellation",
|
|
138
|
+
organizationName: organization.name,
|
|
137
139
|
cancellationDate: emailData.date,
|
|
138
140
|
reactivateLink: emailData.link
|
|
139
141
|
});
|
|
@@ -142,6 +144,7 @@ const changeSubscriptionStatus = async (subscriptionId, status, userId, organiza
|
|
|
142
144
|
await sendEmail({
|
|
143
145
|
...emailData,
|
|
144
146
|
type: "subscriptionPaymentError",
|
|
147
|
+
organizationName: organization.name,
|
|
145
148
|
errorDate: emailData.date,
|
|
146
149
|
retryPaymentLink: emailData.link
|
|
147
150
|
});
|
|
@@ -151,9 +154,83 @@ const changeSubscriptionStatus = async (subscriptionId, status, userId, organiza
|
|
|
151
154
|
}
|
|
152
155
|
return updatedOrganization.plan ?? null;
|
|
153
156
|
};
|
|
157
|
+
const getCouponId = async (promoCode) => {
|
|
158
|
+
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
|
|
159
|
+
try {
|
|
160
|
+
const coupons = await stripe.coupons.list();
|
|
161
|
+
const matchingCoupon = coupons.data.find(
|
|
162
|
+
(coupon) => coupon.name === promoCode
|
|
163
|
+
);
|
|
164
|
+
return matchingCoupon ? matchingCoupon.id : null;
|
|
165
|
+
} catch (error) {
|
|
166
|
+
console.error("Error retrieving coupon:", error);
|
|
167
|
+
return null;
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
const getPricing = async (priceIds, promoCode) => {
|
|
171
|
+
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
|
|
172
|
+
try {
|
|
173
|
+
const pricePromises = priceIds.map(
|
|
174
|
+
(priceId) => stripe.prices.retrieve(priceId)
|
|
175
|
+
);
|
|
176
|
+
const prices = await Promise.all(pricePromises);
|
|
177
|
+
const totalAmount = prices.reduce(
|
|
178
|
+
(sum, price) => sum + (price.unit_amount ?? 0),
|
|
179
|
+
0
|
|
180
|
+
);
|
|
181
|
+
let discountAmount = 0;
|
|
182
|
+
let discountType = null;
|
|
183
|
+
if (promoCode) {
|
|
184
|
+
const coupons = await stripe.coupons.list();
|
|
185
|
+
const matchingCoupons = coupons.data.find(
|
|
186
|
+
(coupon) => coupon.name === promoCode
|
|
187
|
+
);
|
|
188
|
+
if (matchingCoupons) {
|
|
189
|
+
if (matchingCoupons.amount_off) {
|
|
190
|
+
discountAmount = matchingCoupons.amount_off;
|
|
191
|
+
discountType = "amount";
|
|
192
|
+
} else if (matchingCoupons.percent_off) {
|
|
193
|
+
discountAmount = matchingCoupons.percent_off;
|
|
194
|
+
discountType = "percentage";
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
const results = {};
|
|
199
|
+
for (const price of prices) {
|
|
200
|
+
if (!price.id || !price.unit_amount) {
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
const originalTotal = price.unit_amount;
|
|
204
|
+
let appliedDiscount = 0;
|
|
205
|
+
let finalTotal = originalTotal;
|
|
206
|
+
if (discountType === "percentage" && discountAmount > 0) {
|
|
207
|
+
appliedDiscount = originalTotal * discountAmount / 100;
|
|
208
|
+
finalTotal = originalTotal - appliedDiscount;
|
|
209
|
+
} else if (discountType === "amount" && totalAmount > 0 && discountAmount > 0) {
|
|
210
|
+
const proportion = originalTotal / totalAmount;
|
|
211
|
+
appliedDiscount = discountAmount * proportion;
|
|
212
|
+
finalTotal = originalTotal - appliedDiscount;
|
|
213
|
+
}
|
|
214
|
+
finalTotal = Math.max(finalTotal, 0);
|
|
215
|
+
results[price.id] = {
|
|
216
|
+
originalTotal,
|
|
217
|
+
discountApplied: appliedDiscount,
|
|
218
|
+
discountType,
|
|
219
|
+
finalTotal,
|
|
220
|
+
currency: price.currency
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
return results;
|
|
224
|
+
} catch (error) {
|
|
225
|
+
console.error("Error calculating pricing per priceId:", error);
|
|
226
|
+
throw new Error("Failed to calculate pricing breakdown.");
|
|
227
|
+
}
|
|
228
|
+
};
|
|
154
229
|
export {
|
|
155
230
|
addOrUpdateSubscription,
|
|
156
231
|
cancelSubscription,
|
|
157
|
-
changeSubscriptionStatus
|
|
232
|
+
changeSubscriptionStatus,
|
|
233
|
+
getCouponId,
|
|
234
|
+
getPricing
|
|
158
235
|
};
|
|
159
236
|
//# sourceMappingURL=subscription.service.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/services/subscription.service.ts"],"sourcesContent":["import { logger } from '@logger';\nimport { GenericError } from '@utils/errors';\nimport { retrievePlanInformation } from '@utils/plan';\nimport Stripe from 'stripe';\nimport { sendEmail } from './email.service';\nimport { getOrganizationById, updatePlan } from './organization.service';\nimport { getUserById } from './user.service';\nimport type { Organization } from '@/types/organization.types';\nimport type { Plan } from '@/types/plan.types';\n\nexport const addOrUpdateSubscription = async (\n subscriptionId: string,\n priceId: string,\n customerId: string,\n userId: string,\n organization: Organization,\n status: Plan['status']\n): Promise<Plan | null> => {\n const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);\n const user = await getUserById(userId);\n\n if (!user) {\n throw new GenericError('USER_NOT_FOUND', {\n userId,\n });\n }\n\n if (user.customerId !== customerId) {\n user.customerId = customerId;\n await user.save();\n }\n\n const planInfo = retrievePlanInformation(priceId);\n\n const subscriptions = await stripe.subscriptions.list({\n customer: customerId,\n status: 'active',\n limit: 1,\n });\n\n if (subscriptions.data.length >= 1) {\n // Active subscription exists; update it to the new plan\n const otherSubscriptionArray = subscriptions.data.filter(\n (subscription) => subscription.id !== subscriptionId\n );\n\n for (const subscription of otherSubscriptionArray) {\n await stripe.subscriptions.cancel(subscription.id);\n }\n }\n\n const updatedOrganization = await updatePlan(organization, {\n creatorId: user._id,\n priceId,\n customerId,\n subscriptionId,\n type: planInfo.type,\n period: planInfo.period,\n status,\n });\n\n if (!updatedOrganization) {\n throw new GenericError('ORGANIZATION_UPDATE_FAILED', {\n organizationId: organization._id,\n });\n }\n\n logger.info(\n `Plan updated for organization ${organization._id} - ${planInfo.type} - ${planInfo.period}`\n );\n\n return updatedOrganization.plan ?? null;\n};\n\nexport const cancelSubscription = async (\n subscriptionId: string | Organization['_id'],\n organizationId: Organization['_id'] | string\n): Promise<Plan | null> => {\n const organization = await getOrganizationById(organizationId);\n\n if (!organization) {\n throw new GenericError('ORGANIZATION_NOT_FOUND', {\n subscriptionId,\n });\n }\n\n if (!subscriptionId) {\n throw new GenericError('NO_SUBSCRIPTION_ID_PROVIDED');\n }\n\n if (!organization.plan) {\n throw new GenericError('ORGANIZATION_PLAN_NOT_FOUND', {\n subscriptionId,\n organizationId: organization._id,\n });\n }\n\n const updatedOrganization = await updatePlan(organization, {\n status: 'canceled',\n });\n\n if (!updatedOrganization) {\n throw new GenericError('ORGANIZATION_UPDATE_FAILED', {\n organizationId: organization._id,\n });\n }\n\n logger.info(\n `Cancelled plan for organization ${updatedOrganization._id} - ${updatedOrganization.plan?.type} - ${updatedOrganization.plan?.period}`\n );\n\n return updatedOrganization.plan ?? null;\n};\n\nexport const changeSubscriptionStatus = async (\n subscriptionId: string,\n status: Plan['status'],\n userId: string,\n organizationId: string\n): Promise<Plan | null> => {\n const organization = await getOrganizationById(organizationId);\n\n if (!organization) {\n throw new GenericError('ORGANIZATION_NOT_FOUND', {\n userId,\n subscriptionId,\n });\n }\n\n if (!organization.plan) {\n throw new GenericError('ORGANIZATION_PLAN_NOT_FOUND', {\n userId,\n subscriptionId,\n organizationId: organization._id,\n });\n }\n\n const updatedOrganization = await updatePlan(organization, {\n status,\n subscriptionId,\n });\n\n if (!updatedOrganization) {\n throw new GenericError('ORGANIZATION_UPDATE_FAILED', {\n organizationId: organization._id,\n });\n }\n\n const user = await getUserById(userId);\n\n if (!user) {\n throw new GenericError('USER_NOT_FOUND', {\n userId,\n subscriptionId,\n });\n }\n\n logger.info(\n `Updated plan status for organization ${organization._id} - Status: ${status}`\n );\n\n const emailData = {\n to: user.email,\n username: user.name,\n email: user.email,\n planName: organization.plan.type,\n date: new Date().toLocaleDateString(),\n link: `${process.env.CLIENT_URL}/dashboard`,\n };\n\n switch (status) {\n case 'active':\n await sendEmail({\n ...emailData,\n type: 'subscriptionPaymentSuccess',\n subscriptionStartDate: emailData.date,\n manageSubscriptionLink: emailData.link,\n });\n break;\n case 'canceled':\n await sendEmail({\n ...emailData,\n type: 'subscriptionPaymentCancellation',\n cancellationDate: emailData.date,\n reactivateLink: emailData.link,\n });\n break;\n case 'incomplete':\n await sendEmail({\n ...emailData,\n type: 'subscriptionPaymentError',\n errorDate: emailData.date,\n retryPaymentLink: emailData.link,\n });\n break;\n default:\n logger.warn(`Unhandled subscription status: ${status}`);\n }\n\n return updatedOrganization.plan ?? null;\n};\n"],"mappings":"AAAA,SAAS,cAAc;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A,EACH;AAEA,QAAM,OAAO,MAAM,YAAY,MAAM;AAErC,MAAI,CAAC,MAAM;AACT,UAAM,IAAI,aAAa,kBAAkB;AAAA,MACvC;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH;AAEA,SAAO;AAAA,IACL,wCAAwC,aAAa,GAAG,cAAc,MAAM;AAAA,EAC9E;AAEA,QAAM,YAAY;AAAA,IAChB,IAAI,KAAK;AAAA,IACT,UAAU,KAAK;AAAA,IACf,OAAO,KAAK;AAAA,IACZ,UAAU,aAAa,KAAK;AAAA,IAC5B,OAAM,oBAAI,KAAK,GAAE,mBAAmB;AAAA,IACpC,MAAM,GAAG,QAAQ,IAAI,UAAU;AAAA,EACjC;AAEA,UAAQ,QAAQ;AAAA,IACd,KAAK;AACH,YAAM,UAAU;AAAA,QACd,GAAG;AAAA,QACH,MAAM;AAAA,QACN,uBAAuB,UAAU;AAAA,QACjC,wBAAwB,UAAU;AAAA,MACpC,CAAC;AACD;AAAA,IACF,KAAK;AACH,YAAM,UAAU;AAAA,QACd,GAAG;AAAA,QACH,MAAM;AAAA,QACN,kBAAkB,UAAU;AAAA,QAC5B,gBAAgB,UAAU;AAAA,MAC5B,CAAC;AACD;AAAA,IACF,KAAK;AACH,YAAM,UAAU;AAAA,QACd,GAAG;AAAA,QACH,MAAM;AAAA,QACN,WAAW,UAAU;AAAA,QACrB,kBAAkB,UAAU;AAAA,MAC9B,CAAC;AACD;AAAA,IACF;AACE,aAAO,KAAK,kCAAkC,MAAM,EAAE;AAAA,EAC1D;AAEA,SAAO,oBAAoB,QAAQ;AACrC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/services/subscription.service.ts"],"sourcesContent":["import { logger } from '@logger';\nimport { GenericError } from '@utils/errors';\nimport { retrievePlanInformation } from '@utils/plan';\nimport Stripe from 'stripe';\nimport { sendEmail } from './email.service';\nimport { getOrganizationById, updatePlan } from './organization.service';\nimport { getUserById } from './user.service';\nimport type { Organization } from '@/types/organization.types';\nimport type { Plan } from '@/types/plan.types';\n\nexport const addOrUpdateSubscription = async (\n subscriptionId: string,\n priceId: string,\n customerId: string,\n userId: string,\n organization: Organization,\n status: Plan['status']\n): Promise<Plan | null> => {\n const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);\n const user = await getUserById(userId);\n\n if (!user) {\n throw new GenericError('USER_NOT_FOUND', {\n userId,\n });\n }\n\n if (user.customerId !== customerId) {\n user.customerId = customerId;\n await user.save();\n }\n\n const planInfo = retrievePlanInformation(priceId);\n\n const subscriptions = await stripe.subscriptions.list({\n customer: customerId,\n status: 'active',\n limit: 1,\n });\n\n if (subscriptions.data.length >= 1) {\n // Active subscription exists; update it to the new plan\n const otherSubscriptionArray = subscriptions.data.filter(\n (subscription) => subscription.id !== subscriptionId\n );\n\n for (const subscription of otherSubscriptionArray) {\n await stripe.subscriptions.cancel(subscription.id);\n }\n }\n\n const updatedOrganization = await updatePlan(organization, {\n creatorId: user._id,\n priceId,\n customerId,\n subscriptionId,\n type: planInfo.type,\n period: planInfo.period,\n status,\n });\n\n if (!updatedOrganization) {\n throw new GenericError('ORGANIZATION_UPDATE_FAILED', {\n organizationId: organization._id,\n });\n }\n\n logger.info(\n `Plan updated for organization ${organization._id} - ${planInfo.type} - ${planInfo.period}`\n );\n\n return updatedOrganization.plan ?? null;\n};\n\nexport const cancelSubscription = async (\n subscriptionId: string | Organization['_id'],\n organizationId: Organization['_id'] | string\n): Promise<Plan | null> => {\n const organization = await getOrganizationById(organizationId);\n\n if (!organization) {\n throw new GenericError('ORGANIZATION_NOT_FOUND', {\n subscriptionId,\n });\n }\n\n if (!subscriptionId) {\n throw new GenericError('NO_SUBSCRIPTION_ID_PROVIDED');\n }\n\n if (!organization.plan) {\n throw new GenericError('ORGANIZATION_PLAN_NOT_FOUND', {\n subscriptionId,\n organizationId: organization._id,\n });\n }\n\n const updatedOrganization = await updatePlan(organization, {\n status: 'canceled',\n });\n\n if (!updatedOrganization) {\n throw new GenericError('ORGANIZATION_UPDATE_FAILED', {\n organizationId: organization._id,\n });\n }\n\n logger.info(\n `Cancelled plan for organization ${updatedOrganization._id} - ${updatedOrganization.plan?.type} - ${updatedOrganization.plan?.period}`\n );\n\n return updatedOrganization.plan ?? null;\n};\n\nexport const changeSubscriptionStatus = async (\n subscriptionId: string,\n status: Plan['status'],\n userId: string,\n organizationId: string\n): Promise<Plan | null> => {\n const organization = await getOrganizationById(organizationId);\n\n if (!organization) {\n throw new GenericError('ORGANIZATION_NOT_FOUND', {\n userId,\n subscriptionId,\n });\n }\n\n if (!organization.plan) {\n throw new GenericError('ORGANIZATION_PLAN_NOT_FOUND', {\n userId,\n subscriptionId,\n organizationId: organization._id,\n });\n }\n\n const updatedOrganization = await updatePlan(organization, {\n status,\n subscriptionId,\n });\n\n if (!updatedOrganization) {\n throw new GenericError('ORGANIZATION_UPDATE_FAILED', {\n organizationId: organization._id,\n });\n }\n\n const user = await getUserById(userId);\n\n if (!user) {\n throw new GenericError('USER_NOT_FOUND', {\n userId,\n subscriptionId,\n });\n }\n\n logger.info(\n `Updated plan status for organization ${organization._id} - Status: ${status}`\n );\n\n const emailData = {\n to: user.email,\n username: user.name,\n email: user.email,\n planName: organization.plan.type,\n date: new Date().toLocaleDateString(),\n link: `${process.env.CLIENT_URL}/dashboard`,\n };\n\n switch (status) {\n case 'active':\n await sendEmail({\n ...emailData,\n type: 'subscriptionPaymentSuccess',\n organizationName: organization.name,\n subscriptionStartDate: emailData.date,\n manageSubscriptionLink: emailData.link,\n });\n break;\n case 'canceled':\n await sendEmail({\n ...emailData,\n type: 'subscriptionPaymentCancellation',\n organizationName: organization.name,\n cancellationDate: emailData.date,\n reactivateLink: emailData.link,\n });\n break;\n case 'incomplete':\n await sendEmail({\n ...emailData,\n type: 'subscriptionPaymentError',\n organizationName: organization.name,\n errorDate: emailData.date,\n retryPaymentLink: emailData.link,\n });\n break;\n default:\n logger.warn(`Unhandled subscription status: ${status}`);\n }\n\n return updatedOrganization.plan ?? null;\n};\n\nexport const getCouponId = async (\n promoCode: string\n): Promise<string | null> => {\n const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);\n\n try {\n // Retrieve the coupon details by name\n const coupons = await stripe.coupons.list();\n const matchingCoupon = coupons.data.find(\n (coupon) => coupon.name === promoCode\n );\n\n return matchingCoupon ? matchingCoupon.id : null;\n } catch (error) {\n console.error('Error retrieving coupon:', error);\n return null;\n }\n};\n\nexport type PricingResult = Record<\n string,\n {\n originalTotal: number;\n discountApplied: number;\n discountType: 'amount' | 'percentage' | null;\n finalTotal: number;\n currency: string;\n }\n>;\n\nexport const getPricing = async (\n priceIds: string[],\n promoCode?: string\n): Promise<PricingResult> => {\n const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);\n\n try {\n // 1. Fetch all price objects\n const pricePromises = priceIds.map((priceId) =>\n stripe.prices.retrieve(priceId)\n );\n const prices = await Promise.all(pricePromises);\n\n // Calculate the total amount before discount (to help with proportional distribution if needed)\n const totalAmount = prices.reduce(\n (sum, price) => sum + (price.unit_amount ?? 0),\n 0\n );\n\n // 2. Retrieve the discount (if promo code is provided)\n let discountAmount = 0;\n let discountType: 'amount' | 'percentage' | null = null;\n\n if (promoCode) {\n const coupons = await stripe.coupons.list();\n const matchingCoupons = coupons.data.find(\n (coupon) => coupon.name === promoCode\n );\n if (matchingCoupons) {\n if (matchingCoupons.amount_off) {\n discountAmount = matchingCoupons.amount_off;\n discountType = 'amount';\n } else if (matchingCoupons.percent_off) {\n // For a percentage discount, we won't store discountAmount as a raw number\n // because each price line is discounted individually by the same percentage.\n discountAmount = matchingCoupons.percent_off;\n discountType = 'percentage';\n }\n }\n }\n\n // 3. Build the result for each priceId\n const results: PricingResult = {};\n\n for (const price of prices) {\n if (!price.id || !price.unit_amount) {\n continue; // Skip any invalid price\n }\n\n const originalTotal = price.unit_amount;\n let appliedDiscount = 0;\n let finalTotal = originalTotal;\n\n // Apply discount based on the discount type\n if (discountType === 'percentage' && discountAmount > 0) {\n // percentage-based discount\n appliedDiscount = (originalTotal * discountAmount) / 100;\n finalTotal = originalTotal - appliedDiscount;\n } else if (\n discountType === 'amount' &&\n totalAmount > 0 &&\n discountAmount > 0\n ) {\n // fixed amount discount - distribute proportionally\n const proportion = originalTotal / totalAmount;\n appliedDiscount = discountAmount * proportion;\n finalTotal = originalTotal - appliedDiscount;\n }\n\n // Prevent final total from going negative due to rounding\n finalTotal = Math.max(finalTotal, 0);\n\n results[price.id] = {\n originalTotal: originalTotal,\n discountApplied: appliedDiscount,\n discountType,\n finalTotal: finalTotal,\n currency: price.currency,\n };\n }\n\n return results;\n } catch (error) {\n console.error('Error calculating pricing per priceId:', error);\n throw new Error('Failed to calculate pricing breakdown.');\n }\n};\n"],"mappings":"AAAA,SAAS,cAAc;AACvB,SAAS,oBAAoB;AAC7B,SAAS,+BAA+B;AACxC,OAAO,YAAY;AACnB,SAAS,iBAAiB;AAC1B,SAAS,qBAAqB,kBAAkB;AAChD,SAAS,mBAAmB;AAIrB,MAAM,0BAA0B,OACrC,gBACA,SACA,YACA,QACA,cACA,WACyB;AACzB,QAAM,SAAS,IAAI,OAAO,QAAQ,IAAI,iBAAkB;AACxD,QAAM,OAAO,MAAM,YAAY,MAAM;AAErC,MAAI,CAAC,MAAM;AACT,UAAM,IAAI,aAAa,kBAAkB;AAAA,MACvC;AAAA,IACF,CAAC;AAAA,EACH;AAEA,MAAI,KAAK,eAAe,YAAY;AAClC,SAAK,aAAa;AAClB,UAAM,KAAK,KAAK;AAAA,EAClB;AAEA,QAAM,WAAW,wBAAwB,OAAO;AAEhD,QAAM,gBAAgB,MAAM,OAAO,cAAc,KAAK;AAAA,IACpD,UAAU;AAAA,IACV,QAAQ;AAAA,IACR,OAAO;AAAA,EACT,CAAC;AAED,MAAI,cAAc,KAAK,UAAU,GAAG;AAElC,UAAM,yBAAyB,cAAc,KAAK;AAAA,MAChD,CAAC,iBAAiB,aAAa,OAAO;AAAA,IACxC;AAEA,eAAW,gBAAgB,wBAAwB;AACjD,YAAM,OAAO,cAAc,OA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jB,WAAW,gBAAgB,aAAa;AAGtC,2BAAiB,gBAAgB;AACjC,yBAAe;AAAA,QACjB;AAAA,MACF;AAAA,IACF;AAGA,UAAM,UAAyB,CAAC;AAEhC,eAAW,SAAS,QAAQ;AAC1B,UAAI,CAAC,MAAM,MAAM,CAAC,MAAM,aAAa;AACnC;AAAA,MACF;AAEA,YAAM,gBAAgB,MAAM;AAC5B,UAAI,kBAAkB;AACtB,UAAI,aAAa;AAGjB,UAAI,iBAAiB,gBAAgB,iBAAiB,GAAG;AAEvD,0BAAmB,gBAAgB,iBAAkB;AACrD,qBAAa,gBAAgB;AAAA,MAC/B,WACE,iBAAiB,YACjB,cAAc,KACd,iBAAiB,GACjB;AAEA,cAAM,aAAa,gBAAgB;AACnC,0BAAkB,iBAAiB;AACnC,qBAAa,gBAAgB;AAAA,MAC/B;AAGA,mBAAa,KAAK,IAAI,YAAY,CAAC;AAEnC,cAAQ,MAAM,EAAE,IAAI;AAAA,QAClB;AAAA,QACA,iBAAiB;AAAA,QACjB;AAAA,QACA;AAAA,QACA,UAAU,MAAM;AAAA,MAClB;AAAA,IACF;AAEA,WAAO;AAAA,EACT,SAAS,OAAO;AACd,YAAQ,MAAM,0CAA0C,KAAK;AAC7D,UAAM,IAAI,MAAM,wCAAwC;AAAA,EAC1D;AACF;","names":[]}
|
|
@@ -92,7 +92,7 @@ const indexMarkdownFiles = async () => {
|
|
|
92
92
|
try {
|
|
93
93
|
if (JSON.stringify(result) !== JSON.stringify(embeddingsList)) {
|
|
94
94
|
fs.writeFileSync(
|
|
95
|
-
"src/utils/AI/embeddings.json",
|
|
95
|
+
"src/utils/AI/askDocQuestion/embeddings.json",
|
|
96
96
|
JSON.stringify(result, null, 2)
|
|
97
97
|
);
|
|
98
98
|
}
|