@dv4resi/dvss-backend-module-calendar-im 0.0.4 → 0.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +86 -86
- package/dist/index.js +313 -263
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../packages/dvss-integration-libs/src/app.service.ts","../../../packages/dvss-integration-libs/src/app.controller.ts","../../../packages/dvss-integration-libs/src/integration-common-utils/secure-storage/integration-config-secure-storage.service.ts","../../../packages/dvss-integration-libs/src/integration-traffic-router/constants/http.constant.ts","../../../packages/dvss-integration-libs/src/integration-traffic-router/logging/request-logger.service.ts","../../../packages/dvss-integration-libs/src/integration-traffic-router/rate-limiter/rate-limiter.service.ts","../../../packages/dvss-integration-libs/src/integration-traffic-router/gateway/traffic-gateway.service.ts","../../../packages/dvss-integration-libs/src/load-env.ts","../../../packages/dvss-integration-libs/src/app.module.ts","../../../packages/dvss-integration-libs/src/integration-traffic-router/constants/traffic-router.constant.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/auth-management/auth.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/models/credit-management.model.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/models/wellness-management.model.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/models/invoice-management.model.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/models/miscellaneous.model.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/models/customer-payment-management.model.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/wellness/wellness-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/credit-management/credit-booking.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/customer-management/customer-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/package-management/package-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/accounting/subcapabilities/contact-person-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/accounting/subcapabilities/credit-note-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/accounting/subcapabilities/customer-payment-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/accounting/subcapabilities/invoice-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/accounting/subcapabilities/loa-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/accounting/subcapabilities/tax-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/payment/subcapabilities/payment.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/payment/subcapabilities/payment-method-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/payment/subcapabilities/user-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/membership/subcapabilities/customer-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/membership/subcapabilities/membership-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/integration-configuration/integration-configuration.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/integration-resource-management/integration-resource-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/device-management/device-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/access-control/access-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/accounting/subcapabilities/miscellaneous.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/resource-management/resource-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/booking-management/booking-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/webhook-management/webhook-management.base.ts","../../../packages/dvss-integration-libs/src/integration-common-utils/dao/integration-booking.dao.ts","../../../packages/dvss-integration-libs/src/integration-common-utils/dao/integration-common.dao.ts","../../../packages/dvss-integration-libs/src/integration-common-utils/dao/integration-subcapability.dao.ts","../../../packages/dvss-integration-libs/src/integration-common-utils/dao/integration-visitor-credential-mapping.dao.ts","../../../packages/dvss-integration-libs/src/integration-common-utils/dao/integration-configuration.dao.ts","../../../packages/dvss-integration-libs/src/integration-common-utils/dao/integration-service-communication-topic.dao.ts","../../../packages/dvss-integration-libs/src/integration-common-utils/dao/integration-resource-management.dao.ts","../../../packages/dvss-integration-libs/src/integration-common-utils/dao/integration-user-management.dao.ts","../../../packages/dvss-integration-libs/src/integration-common-utils/dao/integration-onprem-deployment.dao.ts","../../../packages/dvss-integration-oauth/src/common/oauth.util.ts","../../../packages/dvss-integration-oauth/src/cache/oauth-token-cache.ts","../../../packages/dvss-integration-oauth/src/grants/authorization-code.handler.ts","../../../packages/dvss-integration-oauth/src/models/oauth.model.ts","../../../packages/dvss-integration-oauth/src/grants/client-credentials.handler.ts","../../../packages/dvss-integration-oauth/src/grants/grant-handler.registry.ts","../../../packages/dvss-integration-oauth/src/store/oauth-provider.dao.ts","../../../packages/dvss-integration-oauth/src/store/oauth-token.dao.ts","../../../packages/dvss-integration-oauth/src/token-manager/oauth-token-manager.ts","../../../packages/dvss-integration-oauth/src/oauth2.provider.ts","../../../packages/dvss-integration-oauth/src/oauth.module.ts","../../../packages/dvss-integration-microsoft/src/common/microsoft.constant.ts","../../../packages/dvss-integration-microsoft/src/common/build-microsoft-integration-config.ts","../../../packages/dvss-integration-microsoft/src/common/microsoft-secure-storage.ts","../../../packages/dvss-integration-microsoft/src/enum/common.enum.ts","../../../packages/dvss-integration-microsoft/src/capabilities/auth/auth.service.ts","../../../packages/dvss-integration-microsoft/src/adapter/microsoft-api-client.service.ts","../../../packages/dvss-integration-microsoft/src/capabilities/booking-management/booking-management.mapper.ts","../../../packages/dvss-integration-microsoft/src/capabilities/booking-management/booking-management.service.ts","../../../packages/dvss-integration-microsoft/src/capabilities/resource-management/resource-management.service.ts","../../../packages/dvss-integration-microsoft/src/capabilities/webhook-management/webhook-management.service.ts","../../../packages/dvss-integration-microsoft/src/capabilities/integration-configuration/integration-configuration.service.ts","../../../packages/dvss-integration-microsoft/src/app.module.ts","../src/common/abstract/adapter-factory.service.ts","../src/common/enum/calendar-provider.enum.ts","../src/handlers/calendar-auth.handler.interface.ts","../src/providers/microsoft/microsoft-calendar-auth.handler.ts","../src/adapters/calendar-auth.adapter.factory.ts","../src/handlers/calendar-booking.handler.interface.ts","../src/providers/microsoft/microsoft-calendar-booking.handler.ts","../src/adapters/calendar-booking.adapter.factory.ts","../src/handlers/calendar-integration-configuration.handler.interface.ts","../src/providers/microsoft/microsoft-calendar-integration-configuration.handler.ts","../src/adapters/calendar-integration-configuration.adapter.factory.ts","../src/handlers/calendar-resource.handler.interface.ts","../src/providers/microsoft/microsoft-calendar-resource.handler.ts","../src/adapters/calendar-resource.adapter.factory.ts","../src/handlers/calendar-webhook.handler.interface.ts","../src/providers/microsoft/microsoft-calendar-webhook.handler.ts","../src/adapters/calendar-webhook.adapter.factory.ts","../src/app.module.ts"],"names":["AppService","getHello","AppController","appService","isPlainObject","value","Array","isArray","isSensitiveStoredField","isSensitive","encrypted","isNonSensitiveStoredField","toSensitivePlaintext","undefined","String","CustomException","resolveMaskStrategy","meta","raw","maskStrategy","MASK_STRATEGY_ENUM","LAST_4","Object","values","includes","IntegrationConfigSecureStorageService","fileName","secretProvider","logger","prepareForWrite","rawConfig","fieldMetadata","keyId","loggedInUserId","SYSTEM_USER_ID","info","name","transformSectionForWrite","prepareForRead","storedConfig","transformSectionForRead","prepareForBackend","transformSectionForBackend","isMaskedUnchanged","incomingValue","storedMasked","isMaskedValue","prepareForUpdate","incomingConfig","existingStoredConfig","transformSectionForUpdate","metadata","result","key","entries","sectionMeta","looksLikeFieldMap","writeFields","fields","fieldMap","out","fieldName","fieldValue","sensitive","plaintext","encrypt","masked","maskValue","stored","decrypt","incoming","existing","existingValue","updateFields","existingField","existingSensitive","incomingString","replaceAll","length","every","v","HTTP_METHOD","REDACTED","SENSITIVE_HEADER_KEYS","Set","SENSITIVE_BODY_KEYS","IntegrationRequestLoggerService","className","logRequest","logData","method","url","headers","requestBody","integrationId","sanitizeHeaders","sanitizePayload","timestamp","Date","logResponse","statusCode","duration","responseBody","logError","error","logIntegrationRequest","sanitized","keys","has","toLowerCase","payload","depth","sanitizeFormEncodedString","map","item","Error","message","record","params","URLSearchParams","didMutate","set","toString","RateLimiterService","validateAndEnforceRateLimit","TrafficGatewayService","httpService","requestLogger","rateLimiter","executeIntegrationRequest","request","integration","_context","startTime","now","prepareHeaders","requestConfig","prepareRequestConfig","fullUrl","constructFullUrl","baseUrl","id","apiMethod","body","apiResponse","executeHttpRequest","responseData","data","status","errorDetails","extractErrorDetails","apiMessage","err","headerType","POST","PUT","PATCH","responseType","requestUrl","normalizedBaseUrl","endsWith","slice","normalizedRequestUrl","startsWith","GET","firstValueFrom","get","post","put","patch","DELETE","delete","errorObject","response","firstString","k","trim","rootEnvPath","resolve","__dirname","config","path","AppModule","imports","ConfigModule","forRoot","envFilePath","isGlobal","HttpModule","register","global","httpsAgent","Agent","rejectUnauthorized","LoggerModule","SecureStorageModule","controllers","providers","exports","TRAFFIC_ROUTER_CONFIGURATION_STORE_KEY","BaseAuth","CREDIT_TYPE_ENUM","CREDIT_STATUS_ENUM","CREDIT_FILTER_BY_ENUM","BOOKABLE_ITEM_TYPE_ENUM","BOOKABLE_ITEM_STATUS_ENUM","GET_CUSTOMER_CREDIT_NOTES_FILTER_BY","GET_CUSTOMER_CREDIT_NOTES_SORT_BY","CREDIT_NOTE_STATUS","GET_INVOICES_SORT_BY_ENUM","GET_RECURRING_INVOICES_SORT_BY_ENUM","GET_INVOICES_FILTER_BY_ENUM","INVOICE_STATUS_ENUM","RECURRING_INVOICE_STATUS","RECURRING_INVOICE_STATUS_ENUM","DOWNLOAD_CUSTOMER_ACCOUNTING_STATEMENT_FILTER_BY_ENUM","DOWNLOAD_CUSTOMER_ACCOUNTING_STATEMENT_STATUS_ENUM","GET_PAYMENTS_FILTER_BY_ENUM","GET_PAYMENTS_FILTER_VALUE_ENUM","GET_PAYMENTS_SORTING_ENUM","BaseWellnessManagement","BaseCreditBooking","BaseCustomerManagement","BasePackageManagement","BaseAccountingContactPersonManagement","BaseAccountingCreditNoteManagement","BaseAccountingCustomerPaymentManagement","BaseAccountingInvoiceManagement","BaseAccountingLOAManagement","BaseAccountingTaxManagement","BasePayment","BasePaymentMethodManagement","BasePaymentUserManagement","BaseMembershipCustomerManagement","BaseMembershipManagement","BaseIntegrationConfiguration","integrationConfigurationDao","commonValidationDatabaseService","secureStorage","validateAddCapabilityIntegrationInput","input","context","getProject","projectId","propertyId","getProperty","resourceMappings","mapping","configuredForType","CONFIGURED_FOR_TYPE_ENUM","PROPERTY","Number","configuredForId","validatePropertyIds","propertyIds","parentId","parentIntegration","getCapabilityIntegration","capabilityIntegrationId","capability","capabilityProvider","Promise","all","getCapability","capabilityId","getCapabilityProvider","capabilityProviderId","providerId","type","category","configStructure","addCapabilityIntegration","options","securedConfig","applySecureStorageForWrite","addCapabilityIntegrationInput","createdBy","availableFor","configuredFor","updateCapabilityIntegration","validateIconAndNickName","updateData","configToUpdate","existingConfig","existingIntegrationConfig","integrationConfig","existingPlatformConfig","platformConfig","existingAccountConfig","accountConfig","useSecureStorage","updateDataForDao","nickname","icon","subcategory","capabilityIntegrationResourceId","groupId","updatedBy","updateResult","syncCapabilityIntegrationResourceMappings","iconName","getCapabilityIntegrations","getCapabilityIntegrationById","fetchBy","getCapabilityIntegrationByProvider","BigInt","kmsKeyId","accessDetails","accessTokenPlain","accessToken","plaintextToken","encryptedBody","details","BaseIntegrationResourceManagement","integrationResourceManagementDao","addResourceToIntegration","offeringId","addResult","addCapabilityIntegrationMapping","OFFERING","ids","idsCount","removeResourceFromIntegration","removeCapabilityIntegrationMapping","updateOfferingIntegrationResourceConfiguration","updateCapabilityIntegrationConfiguration","BaseDeviceManagement","BaseAccessManagement","BaseAccountingMiscellaneousManagement","BaseCalendarResourceManagement","BaseCalendarBookingManagement","BaseCalendarWebhookManagement","IntegrationBookingDao","conn","getOfferingBookingOccurrence","debug","conditions","isNull","schema","offeringBookingOccurrence","deletedAt","eq","offeringBookingOccurrenceId","offeringBooking","offering","offeringBookingId","push","select","offeringIntentId","from","innerJoin","where","and","limit","getOfferingIntent","row","query","offeringIntent","findFirst","DB_CONNECTION","IntegrationCommonDao","getTimezoneForRequest","userBehavior","userIdentityBehaviorMapping","userIdentityId","isNotNull","with","property","timezone","properties","findMany","warn","DEFAULT_TIMEZONE","IntegrationSubcapabilityDao","getSubcapabilityId","rows","subcapability","getSubcapabilities","IntegrationVisitorCredentialMappingDao","generateVisitorCredentialConfigKey","capIntegResourceMappingOfficeVisitorType","OFFICE_VISITOR_CONFIGURATION","extractGenerateCredentialsForVisitorValue","syncVisitorCredentialMapping","isGenerateCredentialEnabled","Boolean","isGenerateCredentialsForVisitorEnabled","createOnly","officeVisitorConfigProfile","db","capIntegResourceMapping","currentConfig","isCurrentGenerateCredentialEnabled","generateCredential","update","updatedAt","insert","CAPABILITY_INTEGRATION_STATUS_ENUM","ACTIVE","IntegrationConfigurationDao","integrationVisitorCredentialMappingDao","integrationSubcapabilityDao","transaction","tx","capabilityIntegrationInsertInput","integrationResult","capabilityIntegration","$returningId","rollback","insertData","createdAt","subcapabilities","subcapabilityId","CAP_INTEG_SUBCAPABILITY_MAPPING_STATUS_ENUM","capIntegSubcapabilityMapping","affectedRows","updateCapabilityIntegrationAccessDetails","expiresInSeconds","expiryAtExpression","sql","inputMap","Map","m","inputKeys","existingMap","e","toDeleteIds","toInsert","deletedBy","inArray","CAPABILITY_TYPE_ENUM","INTEGRATION","getTableColumns","resourceMappingId","resourceMappingConfig","provider","providerIntegrationType","leftJoin","count","MAX_RECORDS_LENGTH","offset","page","sorting","sortBy","by","sortOrder","order","SORTING_ORDER_ENUM","ASC","asc","desc","searchTerm","search","shouldJoinCapability","filters","some","filter","whereConditions","applyFilters","searchPattern","countWhereConditions","countQueryBuilder","as","countQueryWithJoins","countQueryWithPropertyJoin","countQuery","baseQuery","finalQuery","totalCount","records","execute","then","orderBy","filterValues","valuePlaceholders","joinedValues","join","parentConditions","upperValue","toUpperCase","orCondition","or","IntegrationServiceCommunicationTopicDao","upsertTopic","serviceCommunicationTopic","deploymentId","subcapabilityOperation","topicType","topicName","isUniversal","shouldPublish","shouldSubscribe","getServiceCommunicationTopics","topics","IntegrationResourceManagementDao","insertResult","insertedId","insertId","isInserted","checkMappingExists","deleteResult","isSuccess","getCapabilityIntegrationResourceMappingById","IntegrationUserManagementDao","IntegrationOnpremDeploymentDao","addUpdateOnpremDeployment","existingEntry","onPremDeployment","updateOnpremDeployment","addOnpremDeployment","insertedResult","getOnpremDeployment","substituteUrlPlaceholders","replace","matched","hasPersistedIntegrationId","secondsUntil","expiresAt","nowMs","Math","max","floor","getTime","OAUTH_TOKEN_FRESHNESS_BUFFER_MS","isTokenFresh","getIntegrationConfigKmsKeyId","process","env","INTEGRATION_CONFIG_KMS_KEY_ID","delay","ms","setTimeout","getOauthTokenCacheKey","ENV_PREFIX","OAUTH_TOKEN_CACHE_PREFIX","getOauthTokenLockKey","OAUTH_TOKEN_LOCK_PREFIX","OauthTokenCache","redisCacheStoreService","cached","tokenType","refreshToken","token","ttlSeconds","toISOString","del","AuthorizationCodeGrantHandler","mint","tokenUrl","OAUTH_GRANT_TYPE","CLIENT_CREDENTIALS","OAUTH_RFC_GRANT_TYPE","OAUTH_DEFAULT_TOKEN_TYPE","OAUTH_TOKEN_HEADERS","Accept","ClientCredentialsGrantHandler","trafficGatewayService","URL","client_id","credentials","clientId","client_secret","clientSecret","grant_type","scope","integrationContext","authUrl","origin","pathname","access_token","expires_in","token_type","refresh_token","GrantHandlerRegistry","clientCredentialsGrantHandler","authorizationCodeGrantHandler","grantType","resolvePreferredGrant","supportedGrantTypes","OauthProviderDao","findByCapabilityAndProvider","integrationOauthProvider","errorHandler","DATABASE_ERROR_NAMES","DATABASE_ERROR","MODULE_NAME","COMMON","OauthTokenDao","findByCapabilityIntegrationId","integrationOauthToken","upsert","refreshExpiredAt","tokenMetadata","oauthSecretProviderToken","SECRET_PROVIDER","Symbol","OAUTH_LOCK_TTL_SECONDS","OAUTH_LOCK_WAIT_MS","OAUTH_LOCK_MAX_WAIT_MS","OauthTokenManager","sessions","tokenDao","providerDao","tokenCache","grantHandlerRegistry","getValidAccessToken","opts","shouldForceRefresh","forceRefresh","readCachedToken","mintToken","mintWithDistributedLock","storeToken","persistToken","writeMemory","invalidate","lockKey","deadline","ownerId","randomUUID","isAcquired","setIfAbsent","releaseLockIfOwner","existingLock","current","memory","tokenExpiry","redisToken","decryptToken","resolveMintContext","handler","minted","defaultScopes","urlParams","encryptedAccessToken","encryptToken","encryptedRefreshToken","OAuth2Provider","tokenManager","getAuthenticationHeaders","Authorization","testIntegration","IntegrationOauthModule","IntegrationLibsModule","DatastoreModule","MICROSOFT_GRAPH_PATHS","rooms","userCalendarEvents","mailboxEmail","encodeURIComponent","userCalendarEvent","eventId","userCalendarView","startDateTime","endDateTime","subscriptions","subscription","subscriptionId","MICROSOFT_DEFAULT_GRAPH_BASE_URL","MICROSOFT_DEFAULT_AUTH_URL","buildMicrosoftIntegrationConfig","existingBaseUrl","tenantId","MICROSOFT_SECURE_STORAGE","getMicrosoftKmsKeyId","looksLikeStoredSecureConfig","MICROSOFT_CLIENT_CREDENTIALS_GRANT_TYPE","MICROSOFT_DEFAULT_GRAPH_SCOPE","MICROSOFT_DEFAULT_ACCESS_TOKEN_TYPE","MICROSOFT_DEFAULT_HEADERS","MICROSOFT_TOKEN_HEADERS","requireNonEmpty","requireObject","MicrosoftAuthService","oauth2Provider","validateConfig","parseAndValidateConfig","resolvePlaintextConfig","effectiveLoggedInUserId","configForParse","getAccessToken","toMintCredentials","toMicrosoftAccessToken","persistMintedAccessToken","expiresIn","fetchAccessToken","isSuccessful","MicrosoftApiClientService","maxAuthRetryCount","authService","apiCall","executeWithRetry","retryCount","authHeaders","validatedIntegration","hasBody","isUnauthorizedError","GRAPH_EVENT_KNOWN_KEYS","GRAPH_RESOURCE_ATTENDEE_TYPE","toGraphEvent","event","graph","subject","contentType","content","start","dateTime","timeZone","end","location","displayName","showAs","isCancelled","recurrence","toGraphRecurrence","attendees","attendee","mapped","emailAddress","omitUndefined","address","email","resourceId","isAlreadyInvited","pattern","interval","daysOfWeek","firstDayOfWeek","dayOfMonth","month","index","range","startDate","endDate","numberOfOccurrences","recurrenceTimeZone","fromGraphEvent","providerPayload","collectUnknownGraphFields","fromGraphRecurrence","organizerEmail","organizer","syncMetadata","externalEventId","organizerUserEmail","fromEntries","entry","extras","MicrosoftCalendarBookingService","microsoftApiClient","createEvent","resolveMailboxEmail","assertResourceId","graphEvent","resourceAsAttendee","organizerUserMailbox","updateEvent","assertEventId","cancelEvent","deleteGraphEvent","deleteEvent","getEvent","getEvents","hasTimeWindow","events","syncEvents","hasSyncToken","syncToken","reject","NotImplementedException","MicrosoftCalendarResourceService","getResources","resources","room","mapRoom","needle","capacity","building","floorLabel","GRAPH_SUBSCRIPTION_KNOWN_KEYS","MicrosoftCalendarWebhookService","registerWebhook","resource","assertRequired","notificationUrl","expirationDateTime","changeTypes","graphSubscription","toGraphSubscription","fromGraphSubscription","refreshSubscription","deleteSubscription","changeType","clientState","split","MICROSOFT_SECURE_STORAGE_OPTIONS","MicrosoftIntegrationConfigurationService","microsoftAuthService","microsoftConfig","existingStored","asString","mergedCredentials","mergedConfig","updateRequest","integrationForUpdate","CommonValidationDatabaseService","provide","useExisting","AdapterFactoryService","getAdapter","adapter","adapterMap","CALENDAR_PROVIDER_ENUM","ICalendarAuthHandler","MicrosoftCalendarAuthHandler","CalendarAuthAdapterFactory","microsoftCalendarAuthHandler","MICROSOFT_365","ICalendarBookingHandler","MicrosoftCalendarBookingHandler","microsoftCalendarBookingService","addCalendarBooking","updateCalendarBooking","cancelCalendarBooking","deleteCalendarBooking","getCalendarBooking","getCalendarBookings","syncCalendarBookings","CalendarBookingAdapterFactory","microsoftCalendarBookingHandler","ICalendarIntegrationConfigurationHandler","MicrosoftCalendarIntegrationConfigurationHandler","microsoftIntegrationConfigurationService","CalendarIntegrationConfigurationAdapterFactory","microsoftCalendarIntegrationConfigurationHandler","ICalendarResourceHandler","MicrosoftCalendarResourceHandler","microsoftCalendarResourceService","getCalendarResources","CalendarResourceAdapterFactory","microsoftCalendarResourceHandler","ICalendarWebhookHandler","MicrosoftCalendarWebhookHandler","microsoftCalendarWebhookService","registerCalendarWebhook","refreshCalendarWebhook","deleteCalendarWebhook","CalendarWebhookAdapterFactory","microsoftCalendarWebhookHandler","microsoftHandlers","adapterFactories","IntegrationMicrosoftModule"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGO,IAAMA,aAAN,MAAMA;AAAAA,EAAAA;;;EACTC,QAAAA,GAAmB;AACf,IAAA,OAAO,cAAA;AACX,EAAA;AACJ,CAAA;;;;;;;;;;;;;;;;;ACHO,IAAMC,gBAAN,MAAMA;AAAAA,EAAAA;;;;AACT,EAAA,WAAA,CAA6BC,UAAAA,EAAwB;SAAxBA,UAAAA,GAAAA,UAAAA;AAAyB,EAAA;EAGtDF,QAAAA,GAAmB;AACf,IAAA,OAAO,IAAA,CAAKE,WAAWF,QAAAA,EAAQ;AACnC,EAAA;AACJ,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACQA,SAASG,cAAcC,KAAAA,EAAc;AACjC,EAAA,OAAO,OAAOA,UAAU,QAAA,IAAYA,KAAAA,KAAU,QAAQ,CAACC,KAAAA,CAAMC,QAAQF,KAAAA,CAAAA;AACzE;AAFSD,MAAAA,CAAAA,aAAAA,EAAAA,eAAAA,CAAAA;AAIT,SAASI,uBAAuBH,KAAAA,EAAc;AAC1C,EAAA,OAAOD,aAAAA,CAAcC,KAAAA,CAA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ACrBtB,EAAAA,qCAAAA;AACAW,EAAAA,sCAAAA;AACAQ,EAAAA,qCAAAA;AACAhC,EAAAA,kCAAAA;AACAkB,EAAAA;;AAQS3oB,qCAAN,gBAAA,CAAMA;AAAAA,EAAAA;;;AAAW;;;IAJpBC,OAAAA,EAAS;AAAC4c,MAAAA,6BAAAA;AAAuBgN,MAAAA;;IACjC9oB,SAAAA,EAAW;AAAI4oB,MAAAA,GAAAA,iBAAAA;AAAsBC,MAAAA,GAAAA;;IACrC5oB,OAAAA,EAAS;AAAC6b,MAAAA,6BAAAA;AAAuBgN,MAAAA,kCAAAA;AAA+BF,MAAAA,GAAAA,iBAAAA;AAAsBC,MAAAA,GAAAA","file":"index.js","sourcesContent":["import { Injectable } from '@nestjs/common';\n\n@Injectable()\nexport class AppService {\n getHello(): string {\n return 'Hello World!';\n }\n}\n","import { Controller, Get } from '@nestjs/common';\nimport { AppService } from './app.service';\n\n@Controller()\nexport class AppController {\n constructor(private readonly appService: AppService) {}\n\n @Get('integration-libs')\n getHello(): string {\n return this.appService.getHello();\n }\n}\n","import {\n CustomException,\n isMaskedValue,\n LoggerService,\n MASK_STRATEGY_ENUM,\n maskValue,\n SECRET_PROVIDER,\n type SecretProvider,\n SYSTEM_USER_ID,\n} from '@dv4resi/dvss-backend-module-utility';\nimport { Inject, Injectable } from '@nestjs/common';\n\nimport {\n type IIntegrationConfigFieldMetadata,\n type IIntegrationConfigFieldMetadataMap,\n type IIntegrationConfigStructureMetadata,\n} from './types/field-metadata.types';\nimport { type IIntegrationConfigJson, type INonSensitiveStoredField, type ISensitiveStoredField } from './types/stored-config.types';\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isSensitiveStoredField(value: unknown): value is ISensitiveStoredField {\n return isPlainObject(value) && value.isSensitive === true && typeof value.encrypted === 'string';\n}\n\nfunction isNonSensitiveStoredField(value: unknown): value is INonSensitiveStoredField {\n return isPlainObject(value) && value.isSensitive === false && 'value' in value;\n}\n\nfunction toSensitivePlaintext(value: unknown): string {\n if (value === undefined || value === null) {\n return '';\n }\n\n if (typeof value === 'string') {\n return value;\n }\n\n if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {\n return String(value);\n }\n\n throw new CustomException(\n 'BAD_REQUEST',\n 'Sensitive field value must be a string or number',\n 'Sensitive field value must be a primitive on secure storage write',\n );\n}\n\nfunction resolveMaskStrategy(meta: IIntegrationConfigFieldMetadata): MASK_STRATEGY_ENUM {\n const raw = meta.maskStrategy || MASK_STRATEGY_ENUM.LAST_4;\n\n if (Object.values(MASK_STRATEGY_ENUM).includes(raw as MASK_STRATEGY_ENUM)) {\n return raw as MASK_STRATEGY_ENUM;\n }\n\n return MASK_STRATEGY_ENUM.LAST_4;\n}\n\n/**\n * Orchestrates metadata-driven encrypt/mask on write and decrypt/mask on read\n * for capability_integration.config JSON (UIF / integration-libs only).\n */\n@Injectable()\nexport class IntegrationConfigSecureStorageService {\n private readonly fileName = 'integration-config-secure-storage.service.ts';\n\n constructor(\n @Inject(SECRET_PROVIDER) private readonly secretProvider: SecretProvider,\n private readonly logger: LoggerService,\n ) {}\n\n async prepareForWrite(\n rawConfig: IIntegrationConfigJson,\n fieldMetadata: IIntegrationConfigStructureMetadata,\n keyId: string,\n loggedInUserId = SYSTEM_USER_ID,\n ): Promise<IIntegrationConfigJson> {\n this.logger.info(loggedInUserId, this.prepareForWrite.name, this.fileName, 'Preparing integration config for write');\n\n return this.transformSectionForWrite(rawConfig, fieldMetadata, keyId);\n }\n\n prepareForRead(storedConfig: IIntegrationConfigJson): IIntegrationConfigJson {\n return this.transformSectionForRead(storedConfig);\n }\n\n async prepareForBackend(storedConfig: IIntegrationConfigJson, keyId: string, loggedInUserId = SYSTEM_USER_ID): Promise<IIntegrationConfigJson> {\n this.logger.info(loggedInUserId, this.prepareForBackend.name, this.fileName, 'Preparing integration config for backend use');\n\n return this.transformSectionForBackend(storedConfig, keyId);\n }\n\n isMaskedUnchanged(incomingValue: string | undefined | null, storedMasked: string | undefined | null): boolean {\n return isMaskedValue(incomingValue, storedMasked);\n }\n\n async prepareForUpdate(\n incomingConfig: IIntegrationConfigJson,\n existingStoredConfig: IIntegrationConfigJson,\n fieldMetadata: IIntegrationConfigStructureMetadata,\n keyId: string,\n loggedInUserId = SYSTEM_USER_ID,\n ): Promise<IIntegrationConfigJson> {\n this.logger.info(loggedInUserId, this.prepareForUpdate.name, this.fileName, 'Preparing integration config for update');\n\n return this.transformSectionForUpdate(incomingConfig, existingStoredConfig, fieldMetadata, keyId);\n }\n\n private async transformSectionForWrite(\n raw: IIntegrationConfigJson,\n metadata: IIntegrationConfigStructureMetadata,\n keyId: string,\n ): Promise<IIntegrationConfigJson> {\n const result: IIntegrationConfigJson = {};\n\n for (const [key, value] of Object.entries(raw)) {\n const sectionMeta = metadata[key];\n\n if (isPlainObject(value) && isPlainObject(sectionMeta) && this.looksLikeFieldMap(sectionMeta)) {\n result[key] = await this.writeFields(value, sectionMeta as IIntegrationConfigFieldMetadataMap, keyId);\n continue;\n }\n\n if (isPlainObject(value) && isPlainObject(sectionMeta)) {\n result[key] = await this.transformSectionForWrite(value, sectionMeta as IIntegrationConfigStructureMetadata, keyId);\n continue;\n }\n\n result[key] = value;\n }\n\n return result;\n }\n\n private async writeFields(fields: Record<string, unknown>, fieldMap: IIntegrationConfigFieldMetadataMap, keyId: string): Promise<Record<string, unknown>> {\n const out: Record<string, unknown> = {};\n\n for (const [fieldName, fieldValue] of Object.entries(fields)) {\n if (!(fieldName in fieldMap)) {\n out[fieldName] = fieldValue;\n continue;\n }\n\n const meta = fieldMap[fieldName];\n\n if (meta.sensitive) {\n const plaintext = toSensitivePlaintext(fieldValue);\n\n if (!plaintext) {\n throw new CustomException(\n 'BAD_REQUEST',\n `Sensitive field \"${fieldName}\" cannot be empty`,\n `Sensitive field \"${fieldName}\" cannot be empty on prepareForWrite`,\n );\n }\n\n const encrypted = await this.secretProvider.encrypt(plaintext, keyId);\n const masked = maskValue(plaintext, resolveMaskStrategy(meta));\n out[fieldName] = { encrypted, masked, isSensitive: true } satisfies ISensitiveStoredField;\n } else {\n out[fieldName] = { value: fieldValue, isSensitive: false } satisfies INonSensitiveStoredField;\n }\n }\n\n return out;\n }\n\n private transformSectionForRead(stored: IIntegrationConfigJson): IIntegrationConfigJson {\n const result: IIntegrationConfigJson = {};\n\n for (const [key, value] of Object.entries(stored)) {\n if (isSensitiveStoredField(value)) {\n result[key] = value.masked;\n continue;\n }\n\n if (isNonSensitiveStoredField(value)) {\n result[key] = value.value;\n continue;\n }\n\n if (isPlainObject(value)) {\n result[key] = this.transformSectionForRead(value);\n continue;\n }\n\n result[key] = value;\n }\n\n return result;\n }\n\n private async transformSectionForBackend(stored: IIntegrationConfigJson, keyId: string): Promise<IIntegrationConfigJson> {\n const result: IIntegrationConfigJson = {};\n\n for (const [key, value] of Object.entries(stored)) {\n if (isSensitiveStoredField(value)) {\n result[key] = await this.secretProvider.decrypt(value.encrypted, keyId);\n continue;\n }\n\n if (isNonSensitiveStoredField(value)) {\n result[key] = value.value;\n continue;\n }\n\n if (isPlainObject(value)) {\n result[key] = await this.transformSectionForBackend(value, keyId);\n continue;\n }\n\n result[key] = value;\n }\n\n return result;\n }\n\n private async transformSectionForUpdate(\n incoming: IIntegrationConfigJson,\n existing: IIntegrationConfigJson,\n metadata: IIntegrationConfigStructureMetadata,\n keyId: string,\n ): Promise<IIntegrationConfigJson> {\n const result: IIntegrationConfigJson = { ...existing };\n\n for (const [key, incomingValue] of Object.entries(incoming)) {\n const sectionMeta = metadata[key];\n const existingValue = existing[key];\n\n if (isPlainObject(incomingValue) && isPlainObject(sectionMeta) && this.looksLikeFieldMap(sectionMeta)) {\n result[key] = await this.updateFields(\n incomingValue,\n isPlainObject(existingValue) ? existingValue : {},\n sectionMeta as IIntegrationConfigFieldMetadataMap,\n keyId,\n );\n continue;\n }\n\n if (isPlainObject(incomingValue) && isPlainObject(sectionMeta)) {\n result[key] = await this.transformSectionForUpdate(\n incomingValue,\n isPlainObject(existingValue) ? existingValue : {},\n sectionMeta as IIntegrationConfigStructureMetadata,\n keyId,\n );\n continue;\n }\n\n result[key] = incomingValue;\n }\n\n return result;\n }\n\n private async updateFields(\n incoming: Record<string, unknown>,\n existing: Record<string, unknown>,\n fieldMap: IIntegrationConfigFieldMetadataMap,\n keyId: string,\n ): Promise<Record<string, unknown>> {\n const out: Record<string, unknown> = { ...existing };\n\n for (const [fieldName, incomingValue] of Object.entries(incoming)) {\n const existingField = existing[fieldName];\n\n if (!(fieldName in fieldMap)) {\n out[fieldName] = incomingValue;\n continue;\n }\n\n const meta = fieldMap[fieldName];\n\n if (meta.sensitive) {\n const existingSensitive = isSensitiveStoredField(existingField) ? existingField : undefined;\n const incomingString = toSensitivePlaintext(incomingValue);\n\n if (existingSensitive && this.isMaskedUnchanged(incomingString, existingSensitive.masked)) {\n out[fieldName] = existingSensitive;\n continue;\n }\n\n if (!incomingString) {\n throw new CustomException(\n 'BAD_REQUEST',\n `Sensitive field \"${fieldName}\" cannot be empty`,\n `Sensitive field \"${fieldName}\" cannot be empty on prepareForUpdate`,\n );\n }\n\n if (!existingSensitive && incomingString.includes('*') && incomingString.replaceAll('*', '').length <= 4) {\n throw new CustomException(\n 'BAD_REQUEST',\n `Sensitive field \"${fieldName}\" appears to be a masked value; provide the real secret`,\n `Sensitive field \"${fieldName}\" looks masked with no prior stored ciphertext`,\n );\n }\n\n const encrypted = await this.secretProvider.encrypt(incomingString, keyId);\n const masked = maskValue(incomingString, resolveMaskStrategy(meta));\n out[fieldName] = { encrypted, masked, isSensitive: true } satisfies ISensitiveStoredField;\n } else {\n out[fieldName] = { value: incomingValue, isSensitive: false } satisfies INonSensitiveStoredField;\n }\n }\n\n return out;\n }\n\n private looksLikeFieldMap(sectionMeta: Record<string, unknown>): boolean {\n const values = Object.values(sectionMeta);\n\n if (values.length === 0) {\n return false;\n }\n\n return values.every((v) => isPlainObject(v) && typeof (v as { sensitive?: unknown }).sensitive === 'boolean');\n }\n}\n","/**\n * HTTP method constants\n */\nexport enum HTTP_METHOD {\n GET = 'GET',\n POST = 'POST',\n PUT = 'PUT',\n DELETE = 'DELETE',\n PATCH = 'PATCH',\n}\n","import { LoggerService, SYSTEM_USER_ID } from '@dv4resi/dvss-backend-module-utility';\nimport { Injectable } from '@nestjs/common';\n\n/**\n * Request logging data structure\n */\nexport interface IIntegrationRequestLog {\n integrationId?: bigint | string;\n method: string;\n url: string;\n headers?: Record<string, string>;\n requestBody?: unknown;\n responseBody?: unknown;\n statusCode?: number;\n duration?: number;\n loggedInUserId?: bigint;\n timestamp?: Date;\n error?: unknown;\n}\n\nconst REDACTED = '***REDACTED***';\n\n/** Header names (case-insensitive) that must never appear in logs. */\nconst SENSITIVE_HEADER_KEYS = new Set(['authorization', 'api-key', 'apikey', 'x-api-key', 'cookie']);\n\n/**\n * Body / form field names (case-insensitive) that must never appear in logs.\n * Covers OAuth token responses and common credential fields.\n */\nconst SENSITIVE_BODY_KEYS = new Set([\n 'access_token',\n 'refresh_token',\n 'id_token',\n 'token',\n 'client_secret',\n 'clientsecret',\n 'password',\n 'secret',\n 'api_key',\n 'apikey',\n 'authorization',\n]);\n\n/**\n * Service to expose the functionality to log integration requests\n * Uses LoggerService from @dv4resi/dvss-backend-module-utility\n */\n@Injectable()\nexport class IntegrationRequestLoggerService {\n private readonly className = IntegrationRequestLoggerService.name;\n\n constructor(private readonly logger: LoggerService) {}\n\n /**\n * Log integration request (before making the API call)\n *\n * @param logData - The request log data to be logged\n */\n logRequest(logData: IIntegrationRequestLog): void {\n const { loggedInUserId, method, url, headers, requestBody } = logData;\n\n this.logger.info(loggedInUserId || SYSTEM_USER_ID, this.logRequest.name, this.className, `Integration API Request: ${method} ${url}`, {\n integrationId: logData.integrationId,\n method,\n url,\n headers: this.sanitizeHeaders(headers),\n requestBody: this.sanitizePayload(requestBody),\n timestamp: logData.timestamp || new Date(),\n });\n }\n\n /**\n * Log integration response (after successful API call)\n *\n * @param logData - The response log data to be logged\n */\n logResponse(logData: IIntegrationRequestLog): void {\n const { loggedInUserId, method, url, statusCode, duration, responseBody } = logData;\n\n this.logger.info(\n loggedInUserId || SYSTEM_USER_ID,\n this.logResponse.name,\n this.className,\n `Integration API Response: ${method} ${url} - ${statusCode} (${duration}ms)`,\n {\n integrationId: logData.integrationId,\n method,\n url,\n statusCode,\n duration,\n responseBody: this.sanitizePayload(responseBody),\n timestamp: logData.timestamp || new Date(),\n },\n );\n }\n\n /**\n * Log integration error (after failed API call)\n *\n * @param logData - The error log data to be logged\n */\n logError(logData: IIntegrationRequestLog): void {\n const { loggedInUserId, method, url, statusCode, duration, error, responseBody } = logData;\n\n this.logger.error(\n loggedInUserId || SYSTEM_USER_ID,\n this.logError.name,\n this.className,\n `Integration API Error: ${method} ${url} - ${statusCode || 'N/A'} (${duration || 0}ms)`,\n {\n integrationId: logData.integrationId,\n method,\n url,\n statusCode,\n duration,\n error: this.sanitizePayload(error),\n responseBody: this.sanitizePayload(responseBody),\n timestamp: logData.timestamp || new Date(),\n },\n );\n }\n\n /**\n * Log integration request (legacy method for backward compatibility)\n * This method determines whether to log as request, response, or error based on the logData\n *\n * @param logData - The request log data to be logged\n */\n logIntegrationRequest(logData: IIntegrationRequestLog): void {\n if (logData.error) {\n this.logError(logData);\n } else if (logData.statusCode && logData.responseBody !== undefined) {\n this.logResponse(logData);\n } else {\n this.logRequest(logData);\n }\n }\n\n /**\n * Sanitize headers to remove sensitive information\n *\n * @param headers - The headers to sanitize\n * @returns Sanitized headers\n */\n private sanitizeHeaders(headers?: Record<string, string>): Record<string, string> | undefined {\n if (!headers) {\n return undefined;\n }\n\n const sanitized = { ...headers };\n\n for (const key of Object.keys(sanitized)) {\n if (SENSITIVE_HEADER_KEYS.has(key.toLowerCase())) {\n sanitized[key] = REDACTED;\n }\n }\n\n return sanitized;\n }\n\n /**\n * Redact sensitive fields from request/response/error payloads before logging.\n * Handles plain objects, arrays, and `application/x-www-form-urlencoded` strings.\n */\n private sanitizePayload(payload: unknown, depth = 0): unknown {\n if (payload == null || depth > 8) {\n return payload;\n }\n\n if (typeof payload === 'string') {\n return this.sanitizeFormEncodedString(payload);\n }\n\n if (Array.isArray(payload)) {\n return payload.map((item) => this.sanitizePayload(item, depth + 1));\n }\n\n if (typeof payload === 'object') {\n // Avoid cloning Error prototypes into unstructured bags; redact known message fields only.\n if (payload instanceof Error) {\n return {\n name: payload.name,\n message: payload.message,\n };\n }\n\n const record = payload as Record<string, unknown>;\n const sanitized: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(record)) {\n if (SENSITIVE_BODY_KEYS.has(key.toLowerCase())) {\n sanitized[key] = REDACTED;\n continue;\n }\n\n sanitized[key] = this.sanitizePayload(value, depth + 1);\n }\n\n return sanitized;\n }\n\n return payload;\n }\n\n /**\n * Redacts known secret keys in URL-encoded form bodies (e.g. OAuth client_credentials).\n * Non-form strings are returned unchanged.\n */\n private sanitizeFormEncodedString(value: string): string {\n if (!value.includes('=')) {\n return value;\n }\n\n try {\n const params = new URLSearchParams(value);\n let didMutate = false;\n\n for (const key of [...params.keys()]) {\n if (SENSITIVE_BODY_KEYS.has(key.toLowerCase())) {\n params.set(key, REDACTED);\n didMutate = true;\n }\n }\n\n return didMutate ? params.toString() : value;\n } catch {\n return value;\n }\n }\n}\n","import { Injectable } from '@nestjs/common';\n\n/**\n * Service to expose the functionality to validate and enforce rate limits\n */\n@Injectable()\nexport class RateLimiterService {\n /**\n * Validate and enforce rate limit\n *\n * @returns Promise resolving when the rate limit is validated and enforced\n */\n async validateAndEnforceRateLimit(): Promise<void> {\n // TODO Get the rate limit from the configuration store\n // TODO Validate the rate limit\n // TODO Enforce the rate limit\n // TODO If the rate limit is exceeded, throw an error\n // TODO If the rate limit is not exceeded, pass the request to the traffic gateway\n }\n}\n","import { HttpService } from '@nestjs/axios';\nimport { Injectable } from '@nestjs/common';\nimport { firstValueFrom } from 'rxjs';\nimport { HTTP_METHOD } from '../constants/http.constant';\nimport { IntegrationRequestLoggerService, type IIntegrationRequestLog } from '../logging/request-logger.service';\nimport { RateLimiterService } from '../rate-limiter/rate-limiter.service';\nimport { IValidatedCapabilityIntegration } from '../../integration-common-utils';\n\n/**\n * Request configuration for API calls\n */\nexport interface IApiCallRequest<TBody = unknown> {\n apiMethod: HTTP_METHOD;\n url: string;\n baseUrl: string;\n headers?: Record<string, string>;\n body?: TBody;\n responseType?: 'json' | 'text' | 'blob' | 'arraybuffer';\n headerType?: 'json' | 'xml';\n}\n\n/**\n * Request context for deriving rate limits and other settings\n */\nexport interface IIntegrationRequestContext {\n projectId?: bigint;\n propertyId?: bigint;\n capabilityId?: bigint;\n [key: string]: unknown;\n}\n\n/**\n * Service to expose the functionality to execute integration requests\n * This service provides a generic API call method that can be used for any third-party integration\n */\n@Injectable()\nexport class TrafficGatewayService {\n constructor(\n private readonly httpService: HttpService,\n private readonly requestLogger: IntegrationRequestLoggerService,\n private readonly rateLimiter: RateLimiterService,\n ) {}\n\n /**\n * Execute a generic API call to a third-party integration\n *\n * @template TResponse - The expected response type\n * @template TRequestBody - The request body type (optional)\n * @param request - The API call request configuration\n * @param integration - The integration configuration\n * @param loggedInUserId - Optional user ID for logging purposes\n * @param _context - Optional context for deriving rate limits and other settings (projectId, propertyId, etc.)\n * @returns Promise resolving to the API response data\n * @throws Error if the request fails or rate limit is exceeded\n */\n async executeIntegrationRequest<TResponse = unknown, TRequestBody = unknown>(\n request: IApiCallRequest<TRequestBody>,\n integration: IValidatedCapabilityIntegration,\n loggedInUserId?: bigint,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _context?: IIntegrationRequestContext,\n ): Promise<TResponse> {\n const startTime = Date.now();\n\n try {\n // Prepare headers with authorization\n const headers = this.prepareHeaders(request);\n\n // Prepare request configuration\n const requestConfig = this.prepareRequestConfig(request, headers);\n\n // Rate limiting check with context for deriving rate limits\n await this.rateLimiter.validateAndEnforceRateLimit();\n\n // Construct full URL with proper handling of trailing slashes\n const fullUrl = this.constructFullUrl(request.baseUrl, request.url);\n\n // Prepare log data with full URL and headers for request logging\n const logData: IIntegrationRequestLog = {\n integrationId: integration.id,\n method: request.apiMethod,\n url: fullUrl,\n headers,\n requestBody: request.body,\n loggedInUserId,\n timestamp: new Date(),\n };\n\n // Log the request before making the API call\n this.requestLogger.logRequest(logData);\n\n // Execute the HTTP request based on method\n const apiResponse = await this.executeHttpRequest<TResponse>(request, fullUrl, requestConfig);\n\n const duration = Date.now() - startTime;\n const responseData = apiResponse.data;\n\n // Log the successful response\n this.requestLogger.logResponse({\n ...logData,\n responseBody: responseData,\n statusCode: apiResponse.status,\n duration,\n });\n\n return responseData;\n } catch (error) {\n const duration = Date.now() - startTime;\n const errorDetails = this.extractErrorDetails(error);\n\n // Get base URL safely for error logging\n const baseUrl = request.baseUrl;\n const fullUrl = this.constructFullUrl(baseUrl, request.url);\n\n // Log the failed request with API reason (message/error_description) and response body\n this.requestLogger.logError({\n integrationId: integration.id,\n method: request.apiMethod,\n url: fullUrl,\n headers: request.headers,\n requestBody: request.body,\n loggedInUserId,\n timestamp: new Date(),\n error: errorDetails.apiMessage,\n statusCode: errorDetails.statusCode,\n duration,\n responseBody: errorDetails.responseBody,\n });\n\n // Attach apiMessage and statusCode so any integration (Trybe, etc.) can map to its own exceptions\n const err = error as Error & { apiMessage?: string; statusCode?: number };\n err.apiMessage = errorDetails.message;\n err.statusCode = errorDetails.statusCode;\n err.message = errorDetails.apiMessage;\n\n throw error;\n }\n }\n\n /**\n * Prepare headers for the API request\n *\n * @private\n * @param request - The API call request configuration\n * @param apiKey - The API key for authorization\n * @returns Prepared headers object\n */\n private prepareHeaders(request: IApiCallRequest): Record<string, string> {\n request.headerType = request.headerType || 'json';\n\n const headers: Record<string, string> = {\n ...(request.headers || {}),\n };\n\n // Set default content type if not provided for methods that send body\n if (\n !headers['Content-Type'] &&\n request.headerType === 'json' &&\n (request.apiMethod === HTTP_METHOD.POST || request.apiMethod === HTTP_METHOD.PUT || request.apiMethod === HTTP_METHOD.PATCH)\n ) {\n headers['Content-Type'] = 'application/json';\n }\n\n // Set default accept header if not provided\n if (!headers['Accept'] && request.headerType === 'json') {\n headers['Accept'] = 'application/json';\n }\n\n return headers;\n }\n\n /**\n * Prepare request configuration object\n *\n * @private\n * @param request - The API call request configuration\n * @param headers - Prepared headers\n * @returns Request configuration object\n */\n private prepareRequestConfig(request: IApiCallRequest, headers: Record<string, string>): Record<string, unknown> {\n const requestConfig: Record<string, unknown> = {\n headers,\n };\n\n if (request.responseType) {\n requestConfig.responseType = request.responseType;\n }\n\n return requestConfig;\n }\n\n /**\n * Construct full URL from base URL and request URL\n * Handles trailing slashes properly\n *\n * @private\n * @param baseUrl - The base URL from platform config\n * @param requestUrl - The request URL path\n * @returns Constructed full URL\n */\n private constructFullUrl(baseUrl: string, requestUrl: string): string {\n const normalizedBaseUrl = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;\n const normalizedRequestUrl = requestUrl.startsWith('/') ? requestUrl : `/${requestUrl}`;\n\n return `${normalizedBaseUrl}${normalizedRequestUrl}`;\n }\n\n /**\n * Execute HTTP request based on the method\n *\n * @private\n * @template TResponse - The expected response type\n * @param request - The API call request configuration\n * @param fullUrl - The full URL to make the request to\n * @param requestConfig - The request configuration\n * @returns Promise resolving to the HTTP response\n * @throws Error if the HTTP method is unsupported\n */\n private async executeHttpRequest<TResponse>(request: IApiCallRequest, fullUrl: string, requestConfig: Record<string, unknown>) {\n switch (request.apiMethod) {\n case HTTP_METHOD.GET: {\n return await firstValueFrom(this.httpService.get<TResponse>(fullUrl, requestConfig));\n }\n case HTTP_METHOD.POST: {\n return await firstValueFrom(this.httpService.post<TResponse>(fullUrl, request.body, requestConfig));\n }\n case HTTP_METHOD.PUT: {\n return await firstValueFrom(this.httpService.put<TResponse>(fullUrl, request.body, requestConfig));\n }\n case HTTP_METHOD.PATCH: {\n return await firstValueFrom(this.httpService.patch<TResponse>(fullUrl, request.body, requestConfig));\n }\n case HTTP_METHOD.DELETE: {\n return await firstValueFrom(this.httpService.delete<TResponse>(fullUrl, requestConfig));\n }\n default: {\n throw new Error(`Unsupported HTTP method: ${String(request.apiMethod)}`);\n }\n }\n }\n\n /**\n * Extract error details from an error object (e.g. Axios error).\n * Provider-agnostic: derives apiMessage from common response shapes so any integration\n * (Trybe, OAuth, REST, etc.) gets a readable reason. Callers can use statusCode and\n * responseBody to map to their own exceptions (e.g. 404 -> RESOURCE_NOT_FOUND).\n *\n * Supported response.data fields (first string wins): message, error_description,\n * error, detail, msg.\n *\n * @private\n * @param error - The error object\n * @returns Extracted error details including apiMessage for logging and callers\n */\n private extractErrorDetails(error: unknown): {\n message?: string;\n statusCode?: number;\n responseBody?: unknown;\n apiMessage: string;\n } {\n const errorObject = error as {\n status?: number;\n response?: { data?: unknown; status?: number };\n message?: string;\n };\n\n const responseData = errorObject.response?.data;\n const data = typeof responseData === 'object' && responseData !== null ? (responseData as Record<string, unknown>) : undefined;\n\n const firstString = (...keys: string[]): string | undefined => {\n for (const k of keys) {\n const v = data?.[k];\n if (typeof v === 'string' && v.trim()) return v;\n }\n return undefined;\n };\n\n const apiMessage = firstString('message', 'error_description', 'error', 'detail', 'msg') || errorObject.message || 'API error';\n\n return {\n message: errorObject.message,\n statusCode: errorObject.status || errorObject.response?.status,\n responseBody: errorObject.response?.data,\n apiMessage,\n };\n }\n}\n","/**\n * Load environment variables from root .env file\n * This must be imported/required before any other modules that depend on environment variables\n * (e.g., @dv4resi/dvss-backend-module-utility checks env vars at module import time)\n */\nimport { config } from 'dotenv';\nimport { resolve } from 'path';\n\n// Resolve path to root .env file\n// From src/: ../../../\n// From dist/: ../../../\nconst rootEnvPath = resolve(__dirname, '../../../.env');\nconfig({ path: rootEnvPath });\n","// Load environment variables BEFORE importing modules that check env vars at import time\nimport { LoggerModule, SecureStorageModule } from '@dv4resi/dvss-backend-module-utility';\nimport { HttpModule } from '@nestjs/axios';\nimport { Module } from '@nestjs/common';\nimport { ConfigModule } from '@nestjs/config';\nimport { resolve } from 'path';\nimport * as https from 'node:https';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { IntegrationConfigSecureStorageService } from './integration-common-utils/secure-storage';\nimport { TrafficGatewayService } from './integration-traffic-router/gateway/traffic-gateway.service';\nimport { IntegrationRequestLoggerService } from './integration-traffic-router/logging/request-logger.service';\nimport { RateLimiterService } from './integration-traffic-router/rate-limiter/rate-limiter.service';\nimport './load-env';\n\n@Module({\n imports: [\n // Load environment variables from root .env file\n ConfigModule.forRoot({\n envFilePath: resolve(__dirname, '../../../.env'),\n isGlobal: true,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }) as any,\n HttpModule.register({\n global: true,\n httpsAgent: new https.Agent({ rejectUnauthorized: false }),\n }),\n LoggerModule,\n SecureStorageModule,\n ],\n controllers: [AppController],\n providers: [AppService, TrafficGatewayService, IntegrationRequestLoggerService, RateLimiterService, IntegrationConfigSecureStorageService],\n exports: [TrafficGatewayService, IntegrationRequestLoggerService, RateLimiterService, SecureStorageModule, IntegrationConfigSecureStorageService],\n})\nexport class AppModule {}\n","export const TRAFFIC_ROUTER_CONFIGURATION_STORE_KEY = 'traffic-router-configuration-store';\n","import { ICapabilityIntegration, IValidatedCapabilityIntegration } from '../../../integration-common-utils';\n\n/**\n * Base abstract class for integration authentication operations\n * Provides a foundation for implementing authentication functionality\n * for different integration providers\n *\n * This class should be extended by concrete implementations that provide\n * specific authentication operations for different integration systems\n */\nexport abstract class BaseAuth {\n /**\n * Abstract method to validate integration configuration\n * Must be implemented by concrete classes\n *\n * @param config - Integration configuration object\n * @param loggedInUserId - User ID for logging\n * @returns Promise resolving to validated configuration\n */\n abstract validateConfig(integration: ICapabilityIntegration, loggedInUserId: bigint): IValidatedCapabilityIntegration;\n\n /**\n * Abstract method to test integration connection\n * Must be implemented by concrete classes\n *\n * @param integration - Integration object with configuration\n * @param loggedInUserId - User ID for logging\n * @returns Promise resolving when test is completed\n */\n abstract testIntegration(integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<boolean>;\n\n /**\n * Abstract method to fetch an access token from the integration provider.\n * Must be implemented by concrete classes.\n *\n * @param integration - Integration object with configuration\n * @param loggedInUserId - User ID for logging\n * @returns Promise resolving to the access token string\n */\n abstract fetchAccessToken(integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<string>;\n}\n","/**\n * System-level credit and customer credits response types.\n * Aligned with payment MS GetUserCredits / Credit shape for consumption across the system.\n * Integrations map their provider-specific responses to these types.\n */\n\n/** Credit type values aligned with payment MS CREDIT_TYPE_ENUM */\nexport enum CREDIT_TYPE_ENUM {\n COUPON = 'COUPON',\n AMOUNT = 'AMOUNT',\n}\n\n/** Credit status values aligned with payment MS CREDIT_STATUS_ENUM */\nexport enum CREDIT_STATUS_ENUM {\n ACTIVE = 'ACTIVE',\n REDEEMED = 'REDEEMED',\n EXPIRED = 'EXPIRED',\n REVOKED = 'REVOKED',\n}\n\nexport enum CREDIT_FILTER_BY_ENUM {\n TYPE = 'TYPE',\n STATUS = 'STATUS',\n}\n\n/**\n * A single credit in the system format.\n * Matches the shape expected by payment MS Credit (plain interface, no GraphQL).\n * Fields not provided by an integration (e.g. id, projectId) are optional.\n */\nexport interface ICredit {\n id?: bigint;\n name: string;\n description?: string;\n type: CREDIT_TYPE_ENUM;\n status: CREDIT_STATUS_ENUM;\n projectId?: number;\n propertyId?: number;\n externalId?: string;\n expiresAt?: Date;\n expiresDate?: string;\n startsAt?: Date;\n startDate?: string;\n value?: string;\n capabilityIntegrationId?: bigint;\n quantity?: number;\n meta?: Record<string, unknown>;\n}\n\n/**\n * System response for customer credits.\n * Matches payment MS GetUserCredits: { totalCount, records }.\n */\nexport interface IGetCustomerCreditsRequestFilters {\n by: CREDIT_FILTER_BY_ENUM;\n values: string[];\n}\n\nexport interface IGetCustomerCreditsRequestOptions {\n filters?: IGetCustomerCreditsRequestFilters[];\n page?: number;\n count?: number;\n}\n\nexport interface IGetCustomerCreditsRequest {\n customerId: string;\n options?: IGetCustomerCreditsRequestOptions;\n}\n","import { DAY_OF_WEEK, OFFERING_RESOURCE_TYPE, STATUS } from '@dv4resi/dvss-backend-module-datastore/dist/datastore/models';\nimport { IMedia } from '@dv4resi/dvss-backend-module-utility';\n\nexport enum BOOKABLE_ITEM_TYPE_ENUM {\n APPOINTMENT = 'APPOINTMENT',\n SESSION = 'SESSION',\n COURSE = 'COURSE',\n}\n\nexport enum BOOKABLE_ITEM_STATUS_ENUM {\n ACTIVE = 'ACTIVE',\n INACTIVE = 'INACTIVE',\n}\n\nexport interface IBookableItemPriceMeta {\n id?: bigint;\n externalId?: string;\n status?: BOOKABLE_ITEM_STATUS_ENUM;\n price: number;\n currency: string;\n configuredForDays?: DAY_OF_WEEK[];\n config?: Record<string, unknown>;\n}\n\nexport interface IBookableItemPrice {\n id?: bigint;\n label?: string;\n currency: string;\n price: number;\n externalResourceId?: string;\n durationInMinute?: number;\n configuredForDays?: DAY_OF_WEEK[];\n pricesMeta?: IBookableItemPriceMeta[];\n config?: Record<string, unknown>;\n}\n\nexport interface IBookableItemMedia {\n id?: string;\n url?: string;\n originalUrl?: string;\n fileName?: string;\n mimeType?: string;\n thumbnailUrl?: string;\n}\n\nexport interface IBookableItem {\n id?: bigint;\n externalId: string;\n name: string;\n description?: string;\n type: BOOKABLE_ITEM_TYPE_ENUM;\n status?: BOOKABLE_ITEM_STATUS_ENUM;\n icon?: IBookableItemMedia;\n primaryAsset?: IBookableItemMedia;\n prices?: IBookableItemPrice[];\n linkedBookableItems?: IBookableItem[];\n updatedAt?: Date;\n createdAt?: Date;\n meta?: Record<string, unknown>;\n}\n\nexport interface IBookableItemCategory {\n id?: bigint;\n externalId: string;\n name: string;\n description?: string;\n meta?: Record<string, unknown>;\n}\n\nexport interface IWellnessManagementRequestOptions {\n page?: number;\n count?: number;\n}\n\nexport interface IGetAppointmentsRequest {\n shouldFetchAllAppointments: boolean;\n practitionerIds?: string[];\n options?: IWellnessManagementRequestOptions;\n}\n\nexport interface IGetSessionsRequest {\n shouldFetchAllSessions: boolean;\n practitionerIds?: string[];\n options?: IWellnessManagementRequestOptions;\n}\n\nexport interface IGetCoursesRequest {\n shouldFetchAllCourses: boolean;\n options?: IWellnessManagementRequestOptions;\n}\n\nexport interface IGetCategoriesRequest {\n shouldFetchAllCategories: boolean;\n options?: IWellnessManagementRequestOptions;\n}\n\nexport interface IGetBookableItemsFromCreditRequest {\n couponCodeId: string;\n options?: IWellnessManagementRequestOptions;\n}\n\nexport interface IFetchOfferingAvailabilityRequest {\n externalOfferingBookableItemId: string;\n dateTimeFrom: Date;\n dateTimeTo: Date;\n}\n\nexport interface IAvailableTimeSlot {\n fromTime: string;\n toTime: string;\n meta?: unknown;\n}\n\nexport interface IAvailableDateWithSlots {\n date: Date;\n meta?: unknown;\n time: IAvailableTimeSlot[];\n}\n\nexport interface IGetAvailableDatesAndTimeSlotsResponse {\n dates: IAvailableDateWithSlots[];\n}\n\nexport interface IOrderGuest {\n id: string;\n name?: string;\n}\n\nexport interface IGetOrderResponse {\n orderId: string;\n guests: IOrderGuest[];\n}\n\nexport interface ICreateOrderRequest {\n bookingStartTime: Date;\n durationInMinutes?: number;\n meta?: Record<string, unknown>;\n bookableItems: Pick<IBookableItem, 'externalId' | 'type'>[];\n offeringResources: Pick<IOfferingResource, 'externalId'>[];\n currencyMultiplier: number;\n customerId: string;\n customerCreditId?: string;\n}\n\nexport interface ICreateOrderResponse {\n externalBookingId: string;\n items: (Pick<IBookableItem, 'externalId' | 'type' | 'name'> & {\n totalPrice?: number;\n primaryAsset?: IMedia;\n meta: {\n basketItemId: string;\n };\n })[];\n}\n\nexport interface IAddItemToOrderItemConfig {\n offeringId: string;\n offeringType: BOOKABLE_ITEM_TYPE_ENUM;\n guestIds: string[];\n practitionerIds: string[];\n durationMinutes?: number;\n timeIso?: string;\n sessionId?: string;\n}\n\nexport interface IAddItemToOrderRequest {\n orderId: string;\n item: IAddItemToOrderItemConfig;\n}\n\nexport interface IAddItemToOrderResponse {\n name?: string;\n netTotal?: number;\n}\n\nexport interface IAddPaymentToOrderRequest {\n orderId: string;\n amount: number;\n paymentTypeId: string;\n}\n\nexport interface IOfferingResourceMedia {\n meta?: Record<string, unknown>;\n provider?: string;\n}\n\n/**\n * System response type for practitioners/resources aligned with GQL OfferingResource.\n * Union fields map from integration; integration-specific fields go in meta.\n */\nexport interface IOfferingResource {\n id?: bigint;\n externalId: string;\n name: string;\n description?: string;\n type: OFFERING_RESOURCE_TYPE;\n status: STATUS;\n media?: IOfferingResourceMedia;\n meta?: Record<string, unknown>;\n bookableItems?: unknown[];\n createdAt?: Date;\n createdBy?: bigint;\n deletedAt?: Date;\n deletedBy?: bigint;\n isCurrentlyUnavailable?: boolean;\n occurrences?: unknown[];\n offeringId?: bigint;\n priceSummary?: string;\n projectId?: number;\n quantity?: number;\n unavailability?: unknown[];\n updatedAt?: Date;\n updatedBy?: bigint;\n}\n\nexport interface IGetPractitionersRequest {\n shouldFetchAllPractitioners: boolean;\n options?: IWellnessManagementRequestOptions;\n}\n\nexport interface IUpdateOrderRequest {\n orderId: string;\n timezone: string;\n item: {\n externalId: string;\n type: BOOKABLE_ITEM_TYPE_ENUM;\n };\n sessionId?: string;\n durationInMinutes?: number;\n bookingStartDateLabel?: string;\n bookingStartTimeLabel?: string;\n}\n\nexport interface IUpdateOrderResponse {\n success: boolean;\n data?: { id: string };\n}\n","import { schema, SORTING_ORDER_ENUM } from '@dv4resi/dvss-backend-module-datastore';\nimport { ICapabilityIntegration, ICapabilityIntegrationConfig } from './capability-integration.model';\nimport { ITransactionNumberSeries } from './miscellaneous.model';\nimport { ICurrency } from './customer-payment-management.model';\n\nexport interface InvoiceAccessDetails {\n expiryAt?: string;\n accessToken?: string;\n tokenType?: string;\n}\n\nexport interface AccountConfig {\n /** List of available payment methods */\n availablePaymentMethods?: unknown[];\n\n isTaxInclusive?: boolean;\n\n transactionNumberSeries?: ITransactionNumberSeries[];\n}\n\ninterface IIntegrationConfig {\n clientId: string;\n clientSecret: string;\n organizationId: string;\n refreshToken: string;\n}\nexport interface IInvoiceCapabilityIntegrationConfig extends ICapabilityIntegrationConfig {\n accessDetails?: InvoiceAccessDetails;\n accountConfig?: AccountConfig;\n integrationConfig?: IIntegrationConfig;\n}\n\nexport type IInvoiceCapabilityIntegration = Omit<ICapabilityIntegration, 'id' | 'providerId' | 'capabilityId' | 'projectId' | 'config'> &\n typeof schema.capabilityIntegration.$inferSelect & {\n config?: IInvoiceCapabilityIntegrationConfig;\n };\n\nexport interface IInvoiceIntegrationRequest {\n capabilityIntegration: IInvoiceCapabilityIntegration;\n loggedInUserId: bigint;\n}\n\nexport interface IAccountingAPIResponse {\n /** Response code (0 for success) */\n code: number;\n\n /** Response message */\n message: string;\n}\n\nexport interface IInvoiceResponse {\n invoice: IInvoice;\n}\n\nexport interface IInvoice {\n is_inclusive_tax?: boolean;\n invoice_id: string;\n invoice_number: string;\n date: Date; // ISO date string\n due_date: string; // ISO date string\n customer_id: string;\n customer_name?: string;\n salesperson_name?: string;\n email?: string;\n currency_id?: string;\n currency_code: string;\n currency_symbol?: string;\n currency_name_formatted?: string;\n status: string; // e.g., paid\n credits_applied?: number;\n payment_terms?: number;\n payment_terms_label?: string;\n payment_reminder_enabled?: boolean;\n payment_made?: number;\n reference_number?: string;\n sub_total?: number;\n tax_total?: number;\n total?: number;\n balance?: number;\n invoice_url?: string;\n created_time?: Date;\n last_modified_time?: Date;\n discount_type?: string;\n discount?: number | string;\n place_of_supply?: string;\n recurring_invoice_id?: string;\n}\n\nexport interface ICreateRefundRequest {\n refund_mode: string;\n amount: number;\n date: string;\n reference_number?: string;\n description?: string;\n from_account_id: string;\n}\n\nexport interface IApplyCreditNoteForInvoicesRequest {\n invoices: Array<{\n invoice_id: string;\n amount_applied: number;\n }>;\n}\n\nexport interface ICreateCreditNoteForInvoiceRequest {\n customer_id: string;\n date: string;\n is_draft: boolean;\n reference_number?: string;\n notes?: string;\n is_inclusive_tax: boolean;\n salesperson_name?: string;\n place_of_supply?: string;\n custom_fields?: Array<{ api_name: string; value: string }>;\n}\n\nexport interface IAccountingListAPIPageContext {\n page: number;\n per_page: number;\n has_more_page: boolean;\n report_name: string;\n applied_filter: string;\n sort_column: string;\n sort_order: string;\n search_criteria: IAccountingListAPISearchCriteria[];\n}\n\nexport interface IAccountingListAPISearchCriteria {\n column_name: string;\n search_text: string;\n search_text_formatted: string;\n comparator: string;\n}\n\nexport interface IAccountingListAPIResponse {\n /** Response code (0 for success) */\n code: number;\n\n /** Response message */\n message: string;\n\n pageContext: IAccountingListAPIPageContext;\n}\n\nexport enum GET_CUSTOMER_CREDIT_NOTES_FILTER_BY {\n STATUS = 'STATUS',\n REFERENCE_NUMBER = 'REFERENCE_NUMBER',\n}\n\nexport enum GET_CUSTOMER_CREDIT_NOTES_SORT_BY {\n CREATED_TIME = 'CREATED_TIME',\n CUSTOMER_NAME = 'CUSTOMER_NAME',\n CREDITNOTE_NUMBER = 'CREDITNOTE_NUMBER',\n BALANCE = 'BALANCE',\n TOTAL = 'TOTAL',\n DATE = 'DATE',\n}\n\nexport interface IGetCustomerCreditNotesRequest {\n customerId: string;\n options?: {\n filters?: {\n by: GET_CUSTOMER_CREDIT_NOTES_FILTER_BY;\n values: string[];\n }[];\n page?: number;\n count?: number;\n search?: string;\n sort?: {\n by: GET_CUSTOMER_CREDIT_NOTES_SORT_BY;\n order: SORTING_ORDER_ENUM;\n };\n };\n}\n\nexport enum CREDIT_NOTE_STATUS {\n OPEN = 'OPEN',\n CLOSED = 'CLOSED',\n VOID = 'VOID',\n DRAFT = 'DRAFT',\n}\n\nexport interface ICustomerCreditNote {\n creditNoteId: string;\n date: string;\n charge: string;\n operator: string;\n totalAmount: number;\n availableCredit: number;\n status: CREDIT_NOTE_STATUS;\n createdAt: Date;\n updatedAt?: Date;\n}\n\nexport interface IGetCustomerCreditNotesResponse {\n creditNotes: ICustomerCreditNote[];\n hasMorePage: boolean;\n}\n\nexport interface ICreditNoteOperator {\n id?: string;\n type?: string;\n name?: string;\n}\n\nexport interface ICreditNoteAppliedInvoice {\n invoiceId: string;\n invoiceNumber: string;\n appliedAmount: number;\n}\n\nexport interface ICustomerCreditNoteDetail {\n creditNoteId: string;\n creditNoteNumber: string;\n status: CREDIT_NOTE_STATUS;\n customerId: string;\n date: string;\n operator?: ICreditNoteOperator;\n updatedAt?: Date;\n appliedInvoices: ICreditNoteAppliedInvoice[];\n totalAmount: number;\n creditsUsed: number;\n refundAmount: number;\n remainingAmount: number;\n currency?: ICurrency;\n}\n\nexport interface IInvoicesResponse {\n invoices: IAccountingInvoice[];\n hasMorePage: boolean;\n}\nexport interface IAccountingInvoice {\n id: string;\n date: Date;\n chargeId: string;\n category: string;\n status: INVOICE_STATUS_ENUM;\n operator: string;\n totalAmount: number;\n amountDue: number;\n createdAt: Date;\n updatedAt?: Date;\n currency: ICurrency;\n}\n\nexport enum GET_INVOICES_SORT_BY_ENUM {\n CUSTOMER_NAME = 'CUSTOMER_NAME',\n INVOICE_NUMBER = 'INVOICE_NUMBER',\n DATE = 'DATE',\n DUE_DATE = 'DUE_DATE',\n TOTAL = 'TOTAL',\n BALANCE = 'BALANCE',\n CREATED_TIME = 'CREATED_TIME',\n}\n/** Zoho Books recurring invoices support sort by total and created_time only */\nexport enum GET_RECURRING_INVOICES_SORT_BY_ENUM {\n TOTAL = 'TOTAL',\n CREATED_TIME = 'CREATED_TIME',\n}\nexport enum GET_INVOICES_FILTER_BY_ENUM {\n STATUS = 'STATUS',\n CATEGORY = 'CATEGORY',\n ITEM = 'ITEM',\n RESIDENT = 'RESIDENT',\n}\nexport enum INVOICE_STATUS_ENUM {\n SENT = 'SENT',\n DRAFT = 'DRAFT',\n OVERDUE = 'OVERDUE',\n PAID = 'PAID',\n VOID = 'VOID',\n UNPAID = 'UNPAID',\n PARTIALLY_PAID = 'PARTIALLY_PAID',\n VIEWED = 'VIEWED',\n ACTIVE = 'ACTIVE',\n}\nexport interface IGetInvoicesRequest {\n getInvoicesInput?: IGetInvoicesOptions;\n}\nexport interface IGetInvoicesOptions {\n count?: number;\n page?: number;\n search?: string;\n customerId: string;\n sorting?: {\n by: GET_INVOICES_SORT_BY_ENUM;\n order: SORTING_ORDER_ENUM;\n };\n filters?: {\n by: GET_INVOICES_FILTER_BY_ENUM;\n values: string[];\n }[];\n}\n\nexport interface IGetRecurringInvoicesOptions {\n count?: number;\n page?: number;\n search?: string;\n customerId: string;\n sorting?: {\n by: GET_RECURRING_INVOICES_SORT_BY_ENUM;\n order: SORTING_ORDER_ENUM;\n };\n filters?: {\n by: GET_INVOICES_FILTER_BY_ENUM;\n values: string[];\n }[];\n}\n\nexport interface IGetRecurringInvoicesRequest {\n getRecurringInvoicesInput?: IGetRecurringInvoicesOptions;\n}\n\nexport interface IGetRecurringInvoiceInput {\n recurringInvoiceId: string;\n}\n\nexport interface IGetRecurringInvoiceRequest extends IInvoiceIntegrationRequest {\n getRecurringInvoiceInput: IGetRecurringInvoiceInput;\n}\n\nexport enum RECURRING_INVOICE_STATUS {\n ACTIVE = 'ACTIVE',\n STOPPED = 'STOPPED',\n EXPIRED = 'EXPIRED',\n}\n\nexport interface IRecurringInvoices {\n date: string;\n items: string;\n itemDescription: string;\n description: string;\n operator: string;\n totalAmount: number;\n amountDue: number;\n status: RECURRING_INVOICE_STATUS;\n currencyCode: string;\n customerId: string;\n orderNumber: string;\n invoiceId: string;\n recurrenceFrequency: string;\n startDate: string | null;\n endDate: string | null;\n nextInvoiceDate: string | null;\n lastSentDate: string | null;\n repeatEvery: string;\n remark: string;\n createdAt: string;\n}\n\nexport interface IRecurringInvoicesResponse {\n recurringInvoices: IRecurringInvoices[];\n hasMorePage: boolean;\n}\n\nexport interface ICreateRecurringInvoiceLineItem {\n id?: string;\n label: string;\n remark?: string;\n amount: number;\n taxId: string;\n quantity: number;\n}\n\nexport interface ICreateRecurringInvoiceRequest {\n customerId: string;\n items: ICreateRecurringInvoiceLineItem[];\n /** Defaults to the first line item label when omitted. */\n recurrenceName?: string;\n recurrenceFrequency?: string;\n startDate?: string;\n endDate?: string;\n repeatEvery?: number;\n date?: string;\n isInclusiveTax?: boolean;\n allowPartialPayments?: boolean;\n autoNumberGenerationGroupId?: string;\n operator?: string;\n sendEmail?: boolean;\n contactPersonsAssociated?: Array<{ contactPersonId: string }>;\n customFields?: Array<{ name: string; value: string }>;\n}\n\nexport interface ICreateRecurringInvoiceResponse {\n recurringInvoiceId: string;\n}\n\nexport interface IUpdateRecurringInvoiceRequest extends ICreateRecurringInvoiceRequest {\n invoiceId: string;\n}\n\nexport interface IUpdateRecurringInvoiceResponse {\n status: boolean;\n}\n\nexport enum RECURRING_INVOICE_STATUS_ENUM {\n STOP = 'STOP',\n RESUME = 'RESUME',\n}\n\nexport interface IUpdateRecurringInvoiceStatusRequest {\n recurringInvoiceId: string;\n status: RECURRING_INVOICE_STATUS_ENUM;\n}\n","export interface IAccounts {\n id: string;\n name: string;\n type: string;\n}\n\nexport interface IAvailableTaxes {\n id: string;\n name: string;\n percentage: number;\n}\n\nexport interface ITransactionNumberSeriesItem {\n // Making id optional as its not being used for now\n id?: string;\n prefixString: string;\n entityType: string;\n}\nexport interface ITransactionNumberSeries {\n id: string;\n name: string;\n numberSeries: ITransactionNumberSeriesItem[];\n}\n\nexport enum DOWNLOAD_CUSTOMER_ACCOUNTING_STATEMENT_FILTER_BY_ENUM {\n STATUS = 'STATUS',\n}\n\nexport enum DOWNLOAD_CUSTOMER_ACCOUNTING_STATEMENT_STATUS_ENUM {\n ALL = 'ALL',\n}\n\nexport interface IDownloadCustomerAccountingStatementRequest {\n customerId: string;\n fromDate: string;\n toDate: string;\n filters?: Array<{\n by: DOWNLOAD_CUSTOMER_ACCOUNTING_STATEMENT_FILTER_BY_ENUM;\n values: DOWNLOAD_CUSTOMER_ACCOUNTING_STATEMENT_STATUS_ENUM[];\n }>;\n}\n\nexport interface CustomerActivity {\n /** BaseBigIntModelDto */\n id: string;\n /** BaseMetaModelDto */\n createdAt?: Date;\n createdBy?: string;\n updatedAt?: Date;\n updatedBy?: string;\n deletedAt?: Date;\n deletedBy?: string;\n recordedAt?: Date;\n initiatorId?: string;\n initiatorType?: string;\n actionType?: string;\n actionTitle?: string;\n actionSublabel1?: string;\n actionSublabel2?: string;\n actionSublabel3?: string;\n actionNotes?: string;\n projectId: string;\n resourceType?: string;\n resourceTypeId?: string;\n additionalInfo?: Record<string, unknown>;\n author?: ActivityLogAuthor;\n ownerType?: string;\n ownerTypeId?: string;\n note?: Note;\n isInternal?: boolean;\n}\n\nexport interface ActivityLogAuthor {\n id?: string;\n title?: string;\n firstName?: string;\n middleName?: string;\n lastName?: string;\n fullName?: string;\n profileImage?: string;\n}\n\nexport interface Note {\n /** BaseBigIntModelDto */\n id?: string;\n createdAt?: Date;\n createdBy?: string;\n updatedAt?: Date;\n updatedBy?: string;\n deletedAt?: Date;\n deletedBy?: string;\n title?: string;\n description?: string;\n noteCreatorBehaviourType?: string;\n noteCreatorBehaviourId?: string;\n propertyId?: string;\n resourceType?: string;\n resourceId?: string;\n resources?: NoteResource[];\n isPinned?: boolean;\n createdByUser?: UserIdentity;\n updatedByUser?: UserIdentity;\n digitalAssets?: DigitalAsset[];\n projectId?: string;\n attachments?: NoteAttachment[];\n hasAttachment?: boolean;\n noteChangelogs?: NoteChangelog[];\n pinnedAt?: string;\n isRead?: boolean;\n isInternal?: boolean;\n}\nexport interface NoteResource {\n /** NOTE_RESOURCE_TYPE_ENUM as string */\n resourceType?: string;\n /** bigint → string */\n resourceId?: string;\n /** bigint → string (persona userIdentityId) */\n resourceReferenceId?: string;\n}\n\nexport interface DigitalAsset {\n id?: string;\n createdAt?: Date;\n createdBy?: string;\n updatedAt?: Date;\n updatedBy?: string;\n deletedAt?: Date;\n deletedBy?: string;\n name?: string;\n type?: string;\n fileName?: string;\n fileSize?: string;\n description?: string;\n projectId?: string;\n propertyId?: string;\n thumbnailUrl?: string;\n mediaOriginalUrl?: string;\n meta?: Record<string, unknown>;\n scope?: string;\n status?: string;\n resourceAssetMaps?: ResourceAssetMapping[];\n}\n\nexport interface ResourceAssetMapping {\n id?: string;\n createdAt?: Date;\n createdBy?: string;\n updatedAt?: Date;\n updatedBy?: string;\n deletedAt?: Date;\n deletedBy?: string;\n resource?: string;\n resourceId?: string;\n digitalAssetId?: string;\n projectId?: string;\n propertyId?: string;\n}\n\nexport interface NoteAttachment {\n id?: string;\n /** Required asset name */\n name: string;\n /** Required file name */\n fileName: string;\n /** Required file size */\n fileSize: string;\n /** Optional description */\n description?: string;\n /** Optional thumbnail URL */\n thumbnailUrl?: string;\n /** Required media original URL */\n mediaOriginalUrl?: string;\n /** Optional metadata as JSON (Struct) */\n meta?: Record<string, unknown>;\n /** Required scope (DIGITAL_ASSET_SCOPE as string) */\n scope?: string;\n /** Required status (DIGITAL_ASSET_STATUS as string) */\n status?: string;\n /** Required type (DIGITAL_ASSET_TYPE as string) */\n type?: string;\n}\n\nexport interface NoteChangelogRecord {\n /** bigint → string */\n id: string;\n title: string;\n /** bigint → string */\n noteId: string;\n /** int → string */\n projectId: string;\n /** int → string */\n propertyId?: string;\n /** bigint → string */\n resourceId: string;\n description: string;\n /** NOTE_RESOURCE_TYPE_ENUM as string */\n resourceType: string;\n noteChangelog: string;\n /** bigint → string */\n noteEditorBehaviourId: string;\n /** BEHAVIOUR_TYPE_ENUM as string */\n noteEditorBehaviourType: string;\n createdAt?: Date;\n updatedAt?: Date;\n deletedAt?: Date;\n /** bigint → string */\n createdBy?: string;\n /** bigint → string */\n updatedBy?: string;\n /** bigint → string */\n deletedBy?: string;\n createdByUser?: NoteUserIdentity | undefined;\n}\n\nexport interface NoteUserIdentity {\n title?: string;\n fname?: string;\n mname?: string;\n lname?: string;\n fullName?: string;\n /** USER_GENDER_ENUM as string */\n gender?: string;\n /** SEED_SOURCE_ENUM as string */\n seedSource?: string;\n /** int → string */\n idIntegration?: string;\n identityReference?: string;\n /** bigint → string */\n userId?: string;\n metaInfo?: Record<string, unknown>;\n email?: string;\n contactPhone?: string;\n profileImage?: string;\n}\n\nexport interface UserIdentity {\n id?: string;\n createdAt?: Date;\n createdBy?: string;\n updatedAt?: Date;\n updatedBy?: string;\n deletedAt?: Date;\n deletedBy?: string;\n title?: string;\n fname?: string;\n mname?: string;\n lname?: string;\n fullName?: string;\n gender?: string;\n seedSource?: string;\n idIntegration?: number;\n identityReference?: string;\n userId?: string;\n metaInfo?: Record<string, unknown>;\n email?: string;\n contactPhone?: string;\n profileImage?: string;\n}\n\nexport interface NoteChangelog {\n id?: string;\n createdAt?: Date;\n createdBy?: string;\n updatedAt?: Date;\n updatedBy?: string;\n deletedAt?: Date;\n deletedBy?: string;\n title?: string;\n noteId?: string;\n projectId?: string;\n propertyId?: string;\n resourceId?: string;\n description?: string;\n resourceType?: string;\n noteChangelog?: string;\n noteEditorBehaviourId?: string;\n noteEditorBehaviourType?: string;\n createdByUser?: UserIdentity;\n}\n\nexport interface IGetCustomerActivities {\n records: CustomerActivity[];\n hasMorePage: boolean;\n}\n\nexport interface GetFolioActivitiesOptionsInput {\n count?: number;\n page?: number;\n}\n\nexport interface GetCustomerActivitiesInput {\n customerId: string;\n projectId: string;\n propertyTimeZone: string;\n options?: GetFolioActivitiesOptionsInput;\n}\n","import { SORTING_ORDER_ENUM } from '@dv4resi/dvss-backend-module-datastore';\n\nexport interface IGetCustomerPaymentsRequest {\n getCustomerPaymentsOptionsInput?: IGetCustomerPaymentsOptions;\n}\nexport interface IGetCustomerPaymentsOptions {\n count?: number;\n page?: number;\n search?: string;\n customerId: string;\n sorting?: IGetCustomerPaymentsSorting;\n}\nexport enum GET_PAYMENTS_FILTER_BY_ENUM {\n PAYMENT_MODE = 'PAYMENT_MODE',\n}\nexport enum GET_PAYMENTS_FILTER_VALUE_ENUM {\n ALL = 'ALL',\n CHECK = 'CHECK',\n CASH = 'CASH',\n BANK_TRANSFER = 'BANK_TRANSFER',\n PAYPAL = 'PAYPAL',\n CREDIT_CARD = 'CREDIT_CARD',\n GOOGLE_CHECKOUT = 'GOOGLE_CHECKOUT',\n CREDIT = 'CREDIT',\n AUTHORIZENET = 'AUTHORIZENET',\n STRIPE = 'STRIPE',\n PAY_FLOW_PRO = 'PAY_FLOW_PRO',\n BRAIN_TREE = 'BRAIN_TREE',\n TWO_CHECK_OUT = 'TWO_CHECK_OUT',\n BANK_REMITTANCE = 'BANK_REMITTANCE',\n}\nexport enum GET_PAYMENTS_SORTING_ENUM {\n CUSTOMER_NAME = 'CUSTOMER_NAME',\n DATE = 'DATE',\n AMOUNT = 'AMOUNT',\n NOTES = 'NOTES',\n PAYMENT_MODE = 'PAYMENT_MODE',\n}\nexport interface IGetCustomerPaymentsSorting {\n by: GET_PAYMENTS_SORTING_ENUM;\n order: SORTING_ORDER_ENUM;\n}\nexport interface IGetCustomerPaymentsFilter {\n by: GET_PAYMENTS_FILTER_BY_ENUM;\n values: GET_PAYMENTS_FILTER_VALUE_ENUM[];\n}\n\nexport interface IGetCustomerPayments {\n records: ICustomerPaymentRecord[];\n hasMorePage: boolean;\n}\nexport interface ICustomerPaymentRecord {\n customerId: string;\n date: string;\n dueInExcess: number;\n invoiceNumbers: string;\n mode: string;\n operator: string;\n paymentId: string;\n paymentNumber: string;\n referenceId: string;\n remark: string;\n totalAmountReceived: number;\n createdAt: Date;\n updatedAt?: Date;\n refundedAmount: number;\n currency: ICurrency;\n}\n\nexport interface IGetCustomerPaymentRequest {\n paymentId: string;\n}\n\nexport interface IGetCustomerPayment {\n payment: ICustomerPaymentDetails;\n}\n\nexport interface ICustomerPaymentDetails {\n date: Date;\n customerName: string;\n paymentId: string;\n customerId: string;\n totalAmount: number;\n remainingAmount: number;\n createdAt: Date;\n updatedAt: Date;\n paymentMode: string;\n accountId: string;\n accountName?: string;\n accountType?: string;\n referenceNumber?: string;\n bankCharges?: number;\n currency: ICurrency;\n customFields?: Array<{\n apiName: string;\n value: string | number | boolean;\n label?: string;\n customfieldId?: string;\n }>;\n custom_field_hash?: Record<string, string | number | boolean>;\n}\nexport interface ICurrency {\n id: string;\n symbol: string;\n code: string;\n}\n\nexport interface IRefundCustomerPayment {\n paymentId: string;\n amount: number;\n description?: string;\n fromAccountId: string;\n date: string;\n}\n\nexport interface IGetRefundCustomerPayment {\n paymentRefund: IGetCustomerPaymentRefundInfo;\n}\nexport interface IGetCustomerPaymentRefundInfo {\n paymentRefundId: string;\n paymentId: string;\n date: Date;\n refundMode: string;\n referenceNumber: string;\n amount: number;\n exchangeRate: number;\n fromAccountId: string;\n fromAccountName: string;\n description: string;\n htmlString: string;\n}\n\nexport interface ICreateCustomerPaymentRequest {\n customerId: string;\n totalAmount: number;\n date: string;\n paymentMode: string;\n accountId?: string;\n invoices?: Array<{\n invoiceId: string;\n amountApplied: number;\n }>;\n referenceNumber?: string;\n description?: string;\n bankCharges?: number;\n customFields?: Array<{\n apiName: string;\n value: string;\n }>;\n}\n\nexport interface IUpdateCustomerPaymentRequest {\n paymentId: string;\n customerId: string;\n invoices?: Array<{\n invoiceId: string;\n amountApplied: number;\n }>;\n description?: string;\n referenceNumber?: string;\n amount?: number;\n date?: string;\n paymentMethod?: string;\n customFields?: Array<{\n apiName: string;\n value: string;\n }>;\n bankCharges?: number;\n accountId?: string;\n}\n\nexport interface IGetCreateCustomerPayment {\n payment: IGetCreateCustomerPaymentInfo;\n}\nexport interface IGetCreateCustomerPaymentInfo {\n date: Date;\n customerName: string;\n paymentId: string;\n customerId: string;\n totalAmount: number;\n createdAt: Date;\n updatedAt: Date;\n paymentMode: string;\n accountId: string;\n currency: ICurrency;\n}\n","import {\n IUpdateOrderRequest,\n IUpdateOrderResponse,\n type IBookableItem,\n type IBookableItemCategory,\n type ICapabilityIntegration,\n type ICreateOrderRequest,\n type ICreateOrderResponse,\n type IFetchOfferingAvailabilityRequest,\n type IGetAppointmentsRequest,\n type IGetAvailableDatesAndTimeSlotsResponse,\n type IGetBookableItemsFromCreditRequest,\n type IGetCategoriesRequest,\n type IGetCoursesRequest,\n type IGetOrderResponse,\n type IGetPractitionersRequest,\n type IGetSessionsRequest,\n type IOfferingResource,\n} from '../../../integration-common-utils';\nimport { type ISystemResponse } from '../../models/common.model';\n\n/**\n * Base abstract class for wellness management operations\n * Provides a foundation for implementing wellness management functionality\n * within capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific wellness management operations for different systems\n */\nexport abstract class BaseWellnessManagement {\n abstract fetchAppointments(\n request: IGetAppointmentsRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<ISystemResponse<IBookableItem>>;\n\n abstract fetchSessions(request: IGetSessionsRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<ISystemResponse<IBookableItem>>;\n\n abstract fetchCourses(request: IGetCoursesRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<ISystemResponse<IBookableItem>>;\n\n abstract fetchCategories(\n request: IGetCategoriesRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<ISystemResponse<IBookableItemCategory>>;\n\n abstract fetchBookableItemsFromCredit(\n request: IGetBookableItemsFromCreditRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<ISystemResponse<IBookableItem>>;\n\n abstract fetchSessionAvailabilityForOffering(\n request: IFetchOfferingAvailabilityRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IGetAvailableDatesAndTimeSlotsResponse>;\n\n abstract fetchAppointmentAvailabilityForOffering(\n request: IFetchOfferingAvailabilityRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IGetAvailableDatesAndTimeSlotsResponse>;\n\n abstract fetchPractitioners(\n request: IGetPractitionersRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<ISystemResponse<IOfferingResource>>;\n\n /**\n * Creates an external order for an offering booking in the integration platform.\n * This is the only booking-order operation exposed by the skeleton; all\n * provider-specific HTTP orchestration (add customer, add items, credits,\n * submit, etc.) should be encapsulated inside the concrete implementation.\n */\n abstract createOrder(request: ICreateOrderRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<ICreateOrderResponse>;\n\n abstract getOrder(orderId: string, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IGetOrderResponse>;\n\n abstract cancelOrder(orderId: string, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<void>;\n\n abstract updateOrder(request: IUpdateOrderRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IUpdateOrderResponse>;\n\n /**\n * Abstract method to fetch a wellness appointment session\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the appointment session is fetched\n */\n abstract fetchWellnessAppointmentSession(): Promise<void>;\n\n /**\n * Abstract method to check availability of a wellness appointment session\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the availability check is completed\n */\n abstract checkWellnessAppointmentSessionAvailability(): Promise<void>;\n\n /**\n * Abstract method to create a wellness appointment session order\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the appointment session order is created\n */\n abstract createWellnessAppointmentSessionOrder(): Promise<void>;\n\n /**\n * Abstract method to add items to a wellness appointment session order\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the order items are added\n */\n abstract addWellnessAppointmentSessionOrderItems(): Promise<void>;\n\n /**\n * Abstract method to confirm a wellness appointment session order\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the appointment session order is confirmed\n */\n abstract confirmWellnessAppointmentSessionOrder(): Promise<void>;\n}\n","import { ICapabilityIntegration, ICredit, IGetCustomerCreditsRequest } from '../../../integration-common-utils';\nimport { ISystemResponse } from '../../models/common.model';\n\n/**\n * Base abstract class for credit booking operations\n * Provides a foundation for implementing credit booking functionality\n *\n * This class should be extended by concrete implementations that provide\n * specific credit booking operations for different systems\n */\nexport abstract class BaseCreditBooking {\n /**\n * Abstract method to fetch customer credits\n * Must be implemented by concrete classes\n *\n * @param request - The request object containing the customer ID\n * @param integration - The integration object\n * @param loggedInUserId - The user ID of the logged in user\n * @returns Promise resolving to the system customer credits response (totalCount, records)\n */\n abstract fetchCustomerCredits(\n request: IGetCustomerCreditsRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<ISystemResponse<ICredit>>;\n}\n","import {\n IAddCustomerRequest,\n IAddUpdateAccessGroupRequest,\n IAdminCredentials,\n IConfiguration,\n ICustomer,\n ICustomerAddionalDetails,\n ICustomerStatusResponse,\n IDeleteAPIResponse,\n IGetCustomerAccessGroupsInput,\n IGetCustomerAccessGroupsResponse,\n IGetCustomerRequest,\n IListUsersInput,\n IListUsersResponse,\n IUpdateCustomerRequest,\n IUserAccessGroup,\n IValidatedCapabilityIntegration,\n} from '../../../integration-common-utils';\n\n/**\n * Base abstract class for customer management operations\n * Provides a foundation for implementing customer management functionality\n * within capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific customer management operations for different systems\n */\nexport abstract class BaseCustomerManagement {\n /**\n * Create a new customer.\n *\n * @returns Promise resolving to the created customer\n */\n abstract createCustomer(request: IAddCustomerRequest, integration: IValidatedCapabilityIntegration, loggedInUserId: bigint): Promise<ICustomer>;\n\n /**\n * Abstract method to search for customers\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the search is completed\n */\n abstract searchCustomer(request: IGetCustomerRequest, integration: IValidatedCapabilityIntegration, loggedInUserId: bigint): Promise<ICustomer | undefined>;\n\n /**\n * Update an existing customer.\n *\n * @returns Promise resolving to the updated customer data (e.g. id and fields)\n */\n abstract updateCustomer(\n customerId: string,\n request: IUpdateCustomerRequest,\n integration: IValidatedCapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<ICustomer>;\n\n /**\n * Abstract method to delete a customer.\n * Must be implemented by concrete classes.\n *\n * @param customerId - The customer ID to delete\n * @param integration - Capability integration\n * @param loggedInUserId - User ID for logging\n * @returns Promise resolving when the customer is deleted\n */\n abstract deleteCustomer(customerId: string, integration: IValidatedCapabilityIntegration, loggedInUserId: bigint): Promise<IDeleteAPIResponse>;\n\n /**\n * Initializes the customer management service with configuration and credentials\n *\n * This method sets up the service by:\n * 1. Storing the configuration settings\n * 2. Authenticating with the identity server\n * 3. Creating an authenticated Axios instance\n * 4. Setting up authorization headers for subsequent requests\n *\n * @param configuration - system configuration\n * @param credentials - Optional admin credentials (uses config credentials if not provided)\n */\n abstract init(configuration: IConfiguration, credentials?: IAdminCredentials): Promise<void>;\n\n /**\n * Recursively fetches paginated user data from the API\n *\n * This method handles pagination by recursively calling itself when\n * a next_page_link is present in the response. It accumulates all\n * user items across multiple pages into a single array.\n *\n * @param url - API endpoint URL to fetch data from\n * @param loggedInUserId - ID of the user performing the operation\n * @param items - Accumulated items from previous pages (defaults to empty array)\n * @returns Promise containing all user items across all pages\n */\n abstract fetchPage(url: string, loggedInUserId: bigint, items: ICustomer[]): Promise<ICustomer[]>;\n\n /**\n * Retrieves a list of all customers for the configured site\n *\n * This method fetches all users by handling pagination automatically\n * and returning a unified response with all users and total count.\n *\n * @param request - List users request parameters\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise containing the complete list of users and metadata\n */\n abstract listCustomers(request: IListUsersInput, loggedInUserId: bigint): Promise<IListUsersResponse<ICustomer>>;\n\n /**\n * Retrieves a specific customer by their ID\n *\n * @param request - Get user request parameters\n * @param userId - Unique identifier of the user to retrieve\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise containing the user information\n */\n abstract getCustomer(request: ICustomer, userId: string, loggedInUserId: bigint): Promise<ICustomer>;\n\n /**\n * Retrieves a specific customer by their email\n *\n * @param request - Get user request parameters\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise containing the user information\n */\n\n abstract getCustomerByEmail(request: IGetCustomerRequest, loggedInUserId: bigint): Promise<ICustomerAddionalDetails>;\n\n /**\n * Adds a customer to an access group\n *\n * @param request - Add update access group request parameters\n * @param userId - Unique identifier of the user to add to the access group\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise containing the user access group information\n */\n\n abstract addCustomerToAccessGroup(request: IAddUpdateAccessGroupRequest, userId: string, loggedInUserId: bigint): Promise<IUserAccessGroup>;\n\n /**\n * Removes a customer from an access group\n *\n * @param request - Add update access group request parameters\n * @param userId - Unique identifier of the user to remove from the access group\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise containing the user access group information\n */\n\n abstract removeCustomerFromAccessGroup(request: IAddUpdateAccessGroupRequest, userId: string, loggedInUserId: bigint): Promise<IUserAccessGroup>;\n\n /**\n * Resends an invite to a customer\n *\n * @param request - Customer request parameters\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise containing the boolean result\n */\n abstract resendInviteToCustomer(request: ICustomer, loggedInUserId: bigint): Promise<boolean>;\n\n /**\n * Adds a customer to an existing site\n *\n * @param request - Customer request parameters\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise containing the customer information\n */\n abstract addCustomerToExistingSite(request: ICustomer, loggedInUserId: bigint): Promise<ICustomer>;\n\n /**\n * Retrieves a list of access groups for a customer\n *\n * @param request - Get customer access groups request parameters\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise containing the customer access groups information\n */\n abstract getCustomerAccessGroups(request: IGetCustomerAccessGroupsInput, loggedInUserId: bigint): Promise<IGetCustomerAccessGroupsResponse>;\n\n /**\n * Activates a customer where supported by the provider.\n */\n abstract activateCustomer(customerId: string, integration: IValidatedCapabilityIntegration, loggedInUserId: bigint): Promise<ICustomerStatusResponse>;\n\n /**\n * Deactivates a customer where supported by the provider.\n */\n abstract deactivateCustomer(customerId: string, integration: IValidatedCapabilityIntegration, loggedInUserId: bigint): Promise<ICustomerStatusResponse>;\n}\n","/**\n * Base abstract class for package management operations\n * Provides a foundation for implementing package management functionality\n * within capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific package management operations for different systems\n */\nexport abstract class BasePackageManagement {\n /**\n * Abstract method to fetch course types\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the course types are fetched\n */\n abstract fetchCourseTypes(): Promise<void>;\n}\n","import {\n IAPIResponse,\n type ICustomerContactPersonResponse,\n type IAddCustomerContactPersonRequest,\n type IDeleteCustomerContactPersonRequest,\n type IMarkCustomerContactPersonPrimaryRequest,\n type IUpdateCustomerContactPersonRequest,\n type IValidatedCapabilityIntegration,\n} from '../../../../integration-common-utils';\n\n/**\n * Base abstract class for accounting contact person management operations\n * Provides a foundation for implementing contact person management functionality\n * within accounting capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific contact person management operations for different accounting systems\n */\nexport abstract class BaseAccountingContactPersonManagement {\n /**\n * Abstract method to create an accounting contact person\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the contact person is created\n */\n abstract createContactPerson(\n request: IAddCustomerContactPersonRequest,\n integration: IValidatedCapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<ICustomerContactPersonResponse>;\n\n /**\n * Abstract method to update an accounting contact person\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the contact person is updated\n */\n abstract updateContactPerson(\n request: IUpdateCustomerContactPersonRequest,\n integration: IValidatedCapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<ICustomerContactPersonResponse>;\n\n /**\n * Abstract method to delete an accounting contact person\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the contact person is deleted\n */\n abstract deleteContactPerson(\n request: IDeleteCustomerContactPersonRequest,\n integration: IValidatedCapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IAPIResponse>;\n\n /**\n * Abstract method to mark an accounting contact person as primary\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the contact person is marked primary\n */\n abstract markContactPersonPrimary(\n request: IMarkCustomerContactPersonPrimaryRequest,\n integration: IValidatedCapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IAPIResponse>;\n}\n","import {\n ICapabilityIntegration,\n ICreateCreditNoteForInvoiceRequest,\n IAccountingAPIResponse,\n IApplyCreditNoteForInvoicesRequest,\n ICreateRefundRequest,\n IGetCustomerCreditNotesRequest,\n IGetCustomerCreditNotesResponse,\n ICustomerCreditNoteDetail,\n} from '../../../../integration-common-utils';\n\n/**\n * Base abstract class for accounting credit note management operations\n * Provides a foundation for implementing credit note management functionality\n * within accounting capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific credit note management operations for different accounting systems\n */\nexport abstract class BaseAccountingCreditNoteManagement {\n /**\n * Creates a rebate for an invoice\n *\n * @param request - Request containing invoice details\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise resolving when the rebate is created\n */\n abstract applyCreditNoteForInvoices(\n creditNoteId: string,\n rebateRequest: IApplyCreditNoteForInvoicesRequest,\n capabilityIntegration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IAccountingAPIResponse>;\n\n /**\n * Abstract method to refund an accounting invoice\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the invoice is refunded\n */\n abstract createCreditNoteRefund(\n creditNoteId: string,\n refundRequest: ICreateRefundRequest,\n capabilityIntegration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IAccountingAPIResponse>;\n\n /**\n * Creates a credit note for an invoice\n *\n * @param request - Request containing invoice details\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise resolving when the credit note is created\n */\n abstract createCreditNoteForInvoice(\n request: ICreateCreditNoteForInvoiceRequest,\n externalInvoiceId: string,\n capabilityIntegration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IAccountingAPIResponse>;\n\n /**\n * Gets credit notes for a customer\n *\n * @param request - Request containing customer details\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise resolving when the credit notes are retrieved\n */\n abstract getCustomerCreditNotes(\n request: IGetCustomerCreditNotesRequest,\n capabilityIntegration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IGetCustomerCreditNotesResponse>;\n\n /**\n * Gets a credit note by ID\n *\n * @param creditNoteId - External credit note ID\n * @param capabilityIntegration - Capability integration configuration\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise resolving to the mapped credit note detail\n */\n abstract getCreditNote(creditNoteId: string, capabilityIntegration: ICapabilityIntegration, loggedInUserId: bigint): Promise<ICustomerCreditNoteDetail>;\n}\n","import {\n ICapabilityIntegration,\n ICreateCustomerPaymentRequest,\n IGetCreateCustomerPayment,\n IGetCustomerPayment,\n IGetCustomerPaymentRequest,\n IGetCustomerPayments,\n IGetCustomerPaymentsRequest,\n IGetRefundCustomerPayment,\n IRefundCustomerPayment,\n IUpdateCustomerPaymentRequest,\n} from '../../../../integration-common-utils';\n\n/**\n * Base abstract class for accounting customer payment management operations\n * Provides a foundation for implementing customer payment management functionality\n * within accounting capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific customer payment management operations for different accounting systems\n */\nexport abstract class BaseAccountingCustomerPaymentManagement {\n /**\n * Abstract method to create an accounting customer payment\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the customer payment is created\n */\n abstract createCustomerPayment(\n request: ICreateCustomerPaymentRequest,\n capabilityIntegration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IGetCreateCustomerPayment>;\n\n /**\n * Abstract method to update an accounting customer payment (e.g. apply invoices)\n * Must be implemented by concrete classes\n */\n abstract updateCustomerPayment(\n request: IUpdateCustomerPaymentRequest,\n capabilityIntegration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IGetCreateCustomerPayment>;\n\n /**\n * Retrieve bank & cash accounts from the accounting system.\n *\n * @returns Promise resolving to an array of {@link IAccounts}\n */\n abstract getCustomerPayments(\n request: IGetCustomerPaymentsRequest,\n capabilityIntegration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IGetCustomerPayments>;\n\n abstract getCustomerPayment(\n request: IGetCustomerPaymentRequest,\n capabilityIntegration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IGetCustomerPayment>;\n\n abstract downloadCustomerPayment(\n request: IGetCustomerPaymentRequest,\n capabilityIntegration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<ArrayBuffer>;\n\n abstract refundCustomerPayment(\n request: IRefundCustomerPayment,\n capabilityIntegration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IGetRefundCustomerPayment>;\n}\n","import { ICapabilityIntegration } from '../../../../integration-common-utils';\nimport {\n IAccountingAPIResponse,\n ICreateRecurringInvoiceRequest,\n ICreateRecurringInvoiceResponse,\n IGetInvoicesRequest,\n IGetRecurringInvoiceRequest,\n IGetRecurringInvoicesRequest,\n IInvoiceIntegrationRequest,\n IInvoiceResponse,\n IInvoicesResponse,\n IRecurringInvoicesResponse,\n IUpdateRecurringInvoiceRequest,\n IUpdateRecurringInvoiceResponse,\n IUpdateRecurringInvoiceStatusRequest,\n} from '../../../models/invoice-management.model';\n\n/**\n * Base abstract class for accounting invoice management operations\n * Provides a foundation for implementing invoice management functionality\n * within accounting capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific invoice management operations for different accounting systems\n */\nexport abstract class BaseAccountingInvoiceManagement {\n /**\n * Abstract method to create an accounting invoice\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the invoice is created\n */\n abstract createInvoice(request: IInvoiceIntegrationRequest, loggedInUserId: bigint): Promise<IAccountingAPIResponse>;\n\n /**\n * Abstract method to create a recurring invoice\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the recurring invoice is created\n */\n abstract createRecurringInvoice(\n request: ICreateRecurringInvoiceRequest,\n capabilityIntegration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<ICreateRecurringInvoiceResponse>;\n\n /**\n * Abstract method to update an accounting invoice\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the invoice is updated\n */\n abstract updateInvoice(request: IInvoiceIntegrationRequest, loggedInUserId: bigint): Promise<IInvoiceResponse>;\n\n /**\n * Abstract method to delete an accounting invoice\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the invoice is deleted\n */\n abstract deleteInvoice(request: IInvoiceIntegrationRequest, loggedInUserId: bigint): Promise<IAccountingAPIResponse>;\n\n /**\n * Abstract method to download an accounting invoice\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the invoice is downloaded\n */\n\n abstract downloadInvoice(request: IInvoiceIntegrationRequest, loggedInUserId: bigint): Promise<ArrayBuffer>;\n\n /**\n * Abstract method to get an accounting invoice\n *\n * @param request - The invoice request\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise resolving to the invoice\n */\n abstract getInvoice(request: IInvoiceIntegrationRequest, loggedInUserId: bigint): Promise<IInvoiceResponse>;\n\n /**\n * Abstract method to get a recurring invoice by ID\n *\n * @param request - The recurring invoice request\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise resolving to the recurring invoice\n */\n abstract getRecurringInvoice(request: IGetRecurringInvoiceRequest, loggedInUserId: bigint): Promise<unknown>;\n\n /**\n * Creates a customer payment in Zoho Books\n * This marks an invoice as paid or partially paid\n *\n * @param request - Payment request containing customer payment details\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise resolving to payment creation response\n */\n\n abstract markInvoiceAsPaid(request: IInvoiceIntegrationRequest, loggedInUserId: bigint): Promise<IAccountingAPIResponse>;\n\n /**\n * Update the status of an existing invoice (e.g., Mark as paid).\n */\n abstract updateInvoiceStatus(request: IInvoiceIntegrationRequest, loggedInUserId: bigint): Promise<IAccountingAPIResponse>;\n\n abstract getInvoices(request: IGetInvoicesRequest, capabilityIntegration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IInvoicesResponse>;\n\n abstract getRecurringInvoices(\n request: IGetRecurringInvoicesRequest,\n capabilityIntegration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IRecurringInvoicesResponse>;\n\n abstract updateRecurringInvoice(\n request: IUpdateRecurringInvoiceRequest,\n capabilityIntegration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IUpdateRecurringInvoiceResponse>;\n\n abstract markInvoiceAsSent(invoiceId: string, capabilityIntegration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IAccountingAPIResponse>;\n\n abstract updateRecurringInvoiceStatus(\n request: IUpdateRecurringInvoiceStatusRequest,\n capabilityIntegration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IUpdateRecurringInvoiceResponse>;\n}\n","/**\n * Base abstract class for accounting chart of accounts (LOA) management operations\n * Provides a foundation for implementing chart of accounts management functionality\n * within accounting capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific chart of accounts management operations for different accounting systems\n */\nexport abstract class BaseAccountingLOAManagement {\n /**\n * Abstract method to list accounting chart of accounts\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the chart of accounts is listed\n */\n abstract listAccountingChartOfAccounts(): Promise<void>;\n}\n","/**\n * Base abstract class for accounting tax management operations\n * Provides a foundation for implementing tax management functionality\n * within accounting capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific tax management operations for different accounting systems\n */\nexport abstract class BaseAccountingTaxManagement {\n /**\n * Abstract method to list accounting taxes\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the taxes are listed\n */\n abstract listAccountingTaxes(): Promise<void>;\n}\n","/**\n * Base abstract class for payment operations\n * Provides a foundation for implementing payment functionality\n * within payment capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific payment operations for different payment systems\n */\nexport abstract class BasePayment {\n /**\n * Abstract method to create a payment setup intent\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the payment setup intent is created\n */\n abstract createPaymentSetupIntent(): Promise<void>;\n\n /**\n * Abstract method to confirm a payment setup intent\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the payment setup intent is confirmed\n */\n abstract confirmPaymentSetupIntent(): Promise<void>;\n\n /**\n * Abstract method to cancel a payment setup intent\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the payment setup intent is cancelled\n */\n abstract cancelPaymentSetupIntent(): Promise<void>;\n\n /**\n * Abstract method to create a payment ephemeral key\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the payment ephemeral key is created\n */\n abstract createPaymentEphemeralKey(): Promise<void>;\n}\n","/**\n * Base abstract class for payment method management operations\n * Provides a foundation for implementing payment method management functionality\n * within payment capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific payment method management operations for different payment systems\n */\nexport abstract class BasePaymentMethodManagement {\n /**\n * Abstract method to create a payment method\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the payment method is created\n */\n abstract createPaymentMethod(): Promise<void>;\n\n /**\n * Abstract method to attach a payment method to a customer\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the payment method is attached\n */\n abstract attachPaymentMethodToCustomer(): Promise<void>;\n\n /**\n * Abstract method to list payment methods for a customer\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the payment methods are listed\n */\n abstract listPaymentMethodForCustomer(): Promise<void>;\n\n /**\n * Abstract method to detach a payment method from a customer\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the payment method is detached\n */\n abstract detachPaymentMethodFromCustomer(): Promise<void>;\n}\n","/**\n * Base abstract class for payment user management operations\n * Provides a foundation for implementing user management functionality\n * within payment capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific user management operations for different payment systems\n */\nexport abstract class BasePaymentUserManagement {\n /**\n * Abstract method to list payment customers\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the customers are listed\n */\n abstract listPaymentCustomers(): Promise<void>;\n\n /**\n * Abstract method to create a new payment customer\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the customer is created\n */\n abstract createPaymentCustomer(): Promise<void>;\n\n /**\n * Abstract method to update an existing payment customer\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the customer is updated\n */\n abstract updatePaymentCustomer(): Promise<void>;\n\n /**\n * Abstract method to delete a payment customer\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the customer is deleted\n */\n abstract deletePaymentCustomer(): Promise<void>;\n\n /**\n * Abstract method to search for payment customers\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the search is completed\n */\n abstract searchPaymentCustomers(): Promise<void>;\n}\n","/**\n * Base abstract class for membership customer management operations\n * Provides a foundation for implementing customer management functionality\n * within membership capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific customer management operations for different membership systems\n */\nexport abstract class BaseMembershipCustomerManagement {\n /**\n * Abstract method to get all membership customers\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when all customers are retrieved\n */\n abstract getMembershipAllCustomers(): Promise<void>;\n\n /**\n * Abstract method to get a specific membership customer\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the customer is retrieved\n */\n abstract getMembershipCustomer(): Promise<void>;\n\n /**\n * Abstract method to create a new membership customer\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the customer is created\n */\n abstract createMembershipCustomer(): Promise<void>;\n\n /**\n * Abstract method to update an existing membership customer\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the customer is updated\n */\n abstract updateMembershipCustomer(): Promise<void>;\n}\n","/**\n * Base abstract class for membership management operations\n * Provides a foundation for implementing membership management functionality\n * within membership capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific membership management operations for different membership systems\n */\nexport abstract class BaseMembershipManagement {\n /**\n * Abstract method to get membership types\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the membership types are retrieved\n */\n abstract getMembershipTypes(): Promise<void>;\n\n /**\n * Abstract method to get a membership\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the membership is retrieved\n */\n abstract getMembership(): Promise<void>;\n}\n","import type { CAPABILITY_CATEGORY_ENUM, CAPABILITY_TYPE_ENUM } from '@dv4resi/dvss-backend-module-datastore/dist/datastore/models/capability.model';\nimport { CONFIGURED_FOR_TYPE_ENUM } from '@dv4resi/dvss-backend-module-datastore/dist/datastore/models';\nimport type { CommonValidationDatabaseService } from '@dv4resi/dvss-backend-module-datastore';\nimport {\n AddAPIResponse,\n CustomException,\n GraphQLContext,\n LoggerService,\n MASK_STRATEGY_ENUM,\n maskValue,\n type SecretProvider,\n} from '@dv4resi/dvss-backend-module-utility';\nimport { Injectable, Optional } from '@nestjs/common';\nimport type {\n IAddCapabilityIntegration,\n IAddCapabilityIntegrationInput,\n IGetCapabilityIntegrationInput,\n IGetCapabilityIntegrationResult,\n IUpdateCapabilityIntegration,\n} from '../../../integration-common-utils';\nimport type { IntegrationConfigurationDao } from '../../../integration-common-utils/dao/integration-configuration.dao';\nimport type { IntegrationConfigSecureStorageService } from '../../../integration-common-utils/secure-storage/integration-config-secure-storage.service';\nimport type { IIntegrationConfigStructureMetadata } from '../../../integration-common-utils/secure-storage/types/field-metadata.types';\nimport type { ICapabilityIntegration } from '../../models/capability-integration.model';\nimport type {\n IGetCapabilityIntegrationsRequest,\n IGetCapabilityIntegrationsResponse,\n IUpdateCapabilityIntegrationRequest,\n IUpdateCapabilityIntegrationResponse,\n} from '../../models/integration-configuration.model';\n\nexport interface ISecureStorageWriteOptions {\n /** When true, encrypt sensitive config fields before DAO persist. Default false. */\n useSecureStorage?: boolean;\n /** KMS key id or alias required when useSecureStorage is true. */\n kmsKeyId?: string;\n}\n\n@Injectable()\nexport class BaseIntegrationConfiguration {\n protected readonly fileName: string = 'integration-configuration.base.ts';\n\n constructor(\n protected readonly integrationConfigurationDao: IntegrationConfigurationDao,\n protected readonly commonValidationDatabaseService: CommonValidationDatabaseService,\n protected readonly logger: LoggerService,\n @Optional() protected readonly secureStorage?: IntegrationConfigSecureStorageService,\n @Optional() protected readonly secretProvider?: SecretProvider,\n ) {}\n\n /**\n * Validates add-capability-integration input (project, property, parent, capability, provider, configuredFor).\n * Logic copied from project-ms CapabilityIntegrationService.validateAddCapabilityIntegrationInput.\n */\n private async validateAddCapabilityIntegrationInput(\n input: IAddCapabilityIntegrationInput,\n context: GraphQLContext,\n ): Promise<{\n capability: {\n id: bigint;\n type: CAPABILITY_TYPE_ENUM;\n category: CAPABILITY_CATEGORY_ENUM;\n providerId: bigint;\n configStructure?: unknown;\n };\n capabilityProvider: { id: bigint };\n }> {\n await this.commonValidationDatabaseService.getProject({\n projectId: input.projectId,\n });\n\n if (input.propertyId != null) {\n await this.commonValidationDatabaseService.getProperty({\n propertyId: input.propertyId,\n projectId: input.projectId,\n });\n }\n\n if (input.resourceMappings?.length) {\n for (const mapping of input.resourceMappings) {\n if (mapping.configuredForType === CONFIGURED_FOR_TYPE_ENUM.PROPERTY) {\n const propertyId = Number(mapping.configuredForId);\n await this.commonValidationDatabaseService.validatePropertyIds({\n propertyIds: [propertyId],\n projectId: input.projectId,\n });\n }\n }\n }\n\n if (input.parentId != null) {\n const parentIntegration = await this.integrationConfigurationDao.getCapabilityIntegration(\n { capabilityIntegrationId: input.parentId },\n context.loggedInUserId,\n );\n if (!parentIntegration) {\n throw new Error('Parent capability integration not found');\n }\n }\n\n const [capability, capabilityProvider] = await Promise.all([\n this.integrationConfigurationDao.getCapability({ capabilityId: input.capabilityId }, context.loggedInUserId),\n this.integrationConfigurationDao.getCapabilityProvider({ capabilityProviderId: input.capabilityProviderId }, context.loggedInUserId),\n ]);\n\n if (!capability) {\n throw new Error('Capability not found');\n }\n\n if (!capabilityProvider) {\n throw new Error('Capability provider not found');\n }\n\n if (capability.providerId !== capabilityProvider.id) {\n throw new Error(`Capability provider mismatch: capabilityId=${capability.id}, capabilityProviderId=${capability.providerId}`);\n }\n\n return {\n capability: {\n id: capability.id,\n type: capability.type,\n category: capability.category,\n providerId: capability.providerId,\n configStructure: capability.configStructure,\n },\n capabilityProvider: { id: capabilityProvider.id },\n };\n }\n\n /**\n * Add a capability integration (validate then persist via DAO).\n * Same name as project MS call: addCapabilityIntegration.\n */\n async addCapabilityIntegration(\n input: IAddCapabilityIntegrationInput,\n context: GraphQLContext,\n options: ISecureStorageWriteOptions = {},\n ): Promise<AddAPIResponse> {\n const { capability, capabilityProvider } = await this.validateAddCapabilityIntegrationInput(input, context);\n\n const securedConfig = await this.applySecureStorageForWrite(input.config, capability.configStructure, options, context.loggedInUserId);\n\n const addCapabilityIntegrationInput: IAddCapabilityIntegration = {\n ...input,\n config: securedConfig,\n providerId: capabilityProvider.id,\n createdBy: context.loggedInUserId,\n type: capability.type,\n category: capability.category,\n availableFor: input.availableFor,\n configuredFor: input.configuredFor,\n };\n\n const result = await this.integrationConfigurationDao.addCapabilityIntegration(addCapabilityIntegrationInput, context.loggedInUserId);\n\n if (!result || !result.id) {\n throw new Error('Failed to add capability integration');\n }\n\n return result;\n }\n\n /**\n * Update capability integration with config merging support.\n * Handles merging of integrationConfig and platformConfig from existing integration.\n */\n async updateCapabilityIntegration(\n request: IUpdateCapabilityIntegrationRequest,\n integration?: ICapabilityIntegration,\n loggedInUserId?: bigint,\n options: ISecureStorageWriteOptions = {},\n ): Promise<IUpdateCapabilityIntegrationResponse> {\n if (!loggedInUserId) {\n throw new Error('loggedInUserId is required');\n }\n\n this.validateIconAndNickName(request.updateData, loggedInUserId);\n\n if (request.updateData.resourceMappings?.length) {\n for (const mapping of request.updateData.resourceMappings) {\n if (mapping.configuredForType === CONFIGURED_FOR_TYPE_ENUM.PROPERTY) {\n if (!integration?.projectId) {\n throw new CustomException('BAD_REQUEST', 'integration.projectId is required to validate resourceMappings');\n }\n\n const propertyId = Number(mapping.configuredForId);\n\n await this.commonValidationDatabaseService.validatePropertyIds({\n propertyIds: [propertyId],\n projectId: integration.projectId,\n });\n }\n }\n }\n\n let configToUpdate: Record<string, unknown> | undefined;\n const updateData = request.updateData;\n const { resourceMappings } = updateData;\n\n if (updateData.config && integration?.config) {\n const existingConfig = integration.config as Record<string, unknown>;\n\n configToUpdate = {\n ...existingConfig,\n };\n\n const existingIntegrationConfig = (existingConfig.integrationConfig as Record<string, unknown> | undefined) || {};\n configToUpdate.integrationConfig = {\n ...existingIntegrationConfig,\n ...updateData.config.integrationConfig,\n };\n\n const existingPlatformConfig = (existingConfig.platformConfig as Record<string, unknown> | undefined) || {};\n configToUpdate.platformConfig = {\n ...existingPlatformConfig,\n ...updateData.config.platformConfig,\n };\n\n const existingAccountConfig = (existingConfig.accountConfig as Record<string, unknown> | undefined) || {};\n configToUpdate.accountConfig = {\n ...existingAccountConfig,\n ...updateData.config.accountConfig,\n };\n } else if (updateData.config) {\n configToUpdate = updateData.config as unknown as Record<string, unknown>;\n }\n\n if (configToUpdate && options.useSecureStorage) {\n const capabilityId = updateData.capabilityId ?? integration?.capabilityId;\n let configStructure: unknown;\n\n if (capabilityId != null) {\n const capability = await this.integrationConfigurationDao.getCapability({ capabilityId }, loggedInUserId);\n configStructure = capability?.configStructure;\n }\n\n configToUpdate = await this.applySecureStorageForWrite(configToUpdate, configStructure, options, loggedInUserId);\n }\n\n const updateDataForDao: IUpdateCapabilityIntegration = {\n nickname: updateData.nickname,\n icon: updateData.icon as unknown,\n config: configToUpdate as unknown,\n parentId: updateData.parentId,\n propertyId: updateData.propertyId,\n capabilityId: updateData.capabilityId,\n providerId: updateData.capabilityProviderId,\n subcategory: updateData.subcategory,\n capabilityIntegrationResourceId: updateData.capabilityIntegrationResourceId,\n groupId: updateData.groupId,\n status: updateData.status,\n availableFor: updateData.availableFor,\n updatedBy: loggedInUserId,\n };\n\n const updateResult = await this.integrationConfigurationDao.updateCapabilityIntegration(\n { id: request.id, updateData: updateDataForDao, projectId: integration?.projectId as number },\n loggedInUserId,\n );\n\n if (resourceMappings?.length) {\n await this.integrationConfigurationDao.syncCapabilityIntegrationResourceMappings(\n {\n capabilityIntegrationId: request.id,\n projectId: integration?.projectId as number,\n resourceMappings,\n },\n loggedInUserId,\n );\n }\n\n return updateResult;\n }\n\n /**\n * Validates icon and nickname. Can be overridden in subclasses for provider-specific validation.\n */\n protected validateIconAndNickName(updateData: IUpdateCapabilityIntegrationRequest['updateData'], loggedInUserId: bigint): void {\n if (updateData.nickname !== undefined && (updateData.nickname === '' || updateData.nickname.trim() === '')) {\n this.logger.error(loggedInUserId, this.validateIconAndNickName.name, this.fileName, 'Validation failed: nickname cannot be empty or null');\n throw new Error('Nickname cannot be empty');\n }\n\n if (updateData.icon && updateData.icon.meta && typeof updateData.icon.meta === 'object') {\n const meta = updateData.icon.meta as Record<string, unknown>;\n\n if (\n meta.iconName !== undefined &&\n (meta.iconName === null || meta.iconName === '' || (typeof meta.iconName === 'string' && meta.iconName.trim() === ''))\n ) {\n this.logger.error(loggedInUserId, this.validateIconAndNickName.name, this.fileName, 'Validation failed: iconName cannot be empty');\n throw new Error('Icon name cannot be empty');\n }\n }\n }\n\n async getCapabilityIntegrations(request: IGetCapabilityIntegrationsRequest, loggedInUserId: bigint): Promise<IGetCapabilityIntegrationsResponse> {\n return await this.integrationConfigurationDao.getCapabilityIntegrations(request, loggedInUserId);\n }\n\n async getCapabilityIntegration(input: IGetCapabilityIntegrationInput, context: GraphQLContext): Promise<IGetCapabilityIntegrationResult> {\n if (!input.projectId) {\n throw new Error('Project ID is required');\n }\n\n await this.commonValidationDatabaseService.getProject({\n projectId: input.projectId,\n });\n\n let integration: IGetCapabilityIntegrationResult | undefined;\n\n if (input.id) {\n integration = await this.integrationConfigurationDao.getCapabilityIntegrationById(\n {\n id: input.id,\n projectId: input.projectId,\n category: input.category,\n },\n context.loggedInUserId,\n );\n } else if (input.fetchBy) {\n integration = await this.integrationConfigurationDao.getCapabilityIntegrationByProvider(\n {\n projectId: input.projectId,\n category: input.fetchBy.category ?? input.category,\n configuredForType: input.fetchBy.configuredForType,\n configuredForId: BigInt(input.fetchBy.configuredForId),\n },\n context.loggedInUserId,\n );\n }\n\n if (!integration) {\n throw new Error('Capability integration not found');\n }\n\n return integration;\n }\n\n /**\n * When useSecureStorage is true: prepareForWrite on metadata-covered fields + encrypt accessToken if present.\n */\n protected async applySecureStorageForWrite(\n config: Record<string, unknown> | undefined,\n configStructure: unknown,\n options: ISecureStorageWriteOptions,\n loggedInUserId: bigint,\n ): Promise<Record<string, unknown> | undefined> {\n if (!options.useSecureStorage || !config) {\n return config;\n }\n\n if (!this.secureStorage || !this.secretProvider) {\n throw new CustomException(\n 'INTERNAL_ERROR',\n 'Secure storage is not configured.',\n 'Secure storage providers are required when useSecureStorage is true',\n );\n }\n\n if (!options.kmsKeyId) {\n throw new CustomException('BAD_REQUEST', 'Encryption key is required.', 'kmsKeyId is required when useSecureStorage is true');\n }\n\n const fieldMetadata = (configStructure && typeof configStructure === 'object' ? configStructure : {}) as IIntegrationConfigStructureMetadata;\n\n const accessDetails = config.accessDetails;\n const accessTokenPlain =\n accessDetails && typeof accessDetails === 'object' && !Array.isArray(accessDetails)\n ? (accessDetails as Record<string, unknown>).accessToken\n : undefined;\n const plaintextToken = typeof accessTokenPlain === 'string' ? accessTokenPlain : undefined;\n\n const encryptedBody = await this.secureStorage.prepareForWrite(\n {\n integrationConfig: (config.integrationConfig ?? {}) as Record<string, unknown>,\n },\n fieldMetadata,\n options.kmsKeyId,\n loggedInUserId,\n );\n\n let result: Record<string, unknown> = {\n ...config,\n ...encryptedBody,\n };\n\n if (plaintextToken) {\n const encrypted = await this.secretProvider.encrypt(plaintextToken, options.kmsKeyId);\n const masked = maskValue(plaintextToken, MASK_STRATEGY_ENUM.LAST_4);\n const details =\n accessDetails && typeof accessDetails === 'object' && !Array.isArray(accessDetails) ? { ...(accessDetails as Record<string, unknown>) } : {};\n\n details.accessToken = {\n encrypted,\n masked,\n isSensitive: true,\n };\n\n result = {\n ...result,\n accessDetails: details,\n };\n }\n\n return result;\n }\n}\n","import { IntegrationResourceManagementDao } from '../../../integration-common-utils/dao/integration-resource-management.dao';\nimport {\n IAddResourceToIntegrationInput,\n IAddResourceToIntegrationResponse,\n IRemoveResourceFromIntegrationRequest,\n IRemoveResourceFromIntegrationResponse,\n IUpdateOfferingIntegrationResourceConfigurationInput,\n IUpdateOfferingIntegrationResourceConfigurationResponse,\n} from '../../../integration-operation-skeletons/models/integration-resource-management.model';\nimport { GraphQLContext, LoggerService } from '@dv4resi/dvss-backend-module-utility';\nimport { CONFIGURED_FOR_TYPE_ENUM } from '@dv4resi/dvss-backend-module-datastore/dist/datastore/models';\n\n/**\n * Base abstract class for integration resource management operations.\n * Holds only inter-service implementation (DAO calls). Validation (config, mapping exists)\n * lives in provider wrappers (e.g. TrybeIntegrationResourceManagementService).\n * MS is responsible for getOffering, getIntegration, updateOffering, runAfterAddIfNeeded.\n */\nexport abstract class BaseIntegrationResourceManagement {\n private readonly fileName = 'integration-resource-management.base';\n\n constructor(\n protected readonly integrationResourceManagementDao: IntegrationResourceManagementDao,\n protected readonly logger: LoggerService,\n ) {}\n\n /**\n * Adds a resource (capability integration) to an offering integration via UIF.\n * Inter-service implementation only: performs DAO insert. Wrapper must validate\n * config and mapping-exists before calling; caller (MS) does getOffering, getIntegration,\n * updateOffering and runAfterAddIfNeeded.\n *\n * @param input - projectId, offeringId, capabilityIntegrationId, optional config\n * @param context - GraphQL context\n * @returns Promise resolving to { status, ids }\n */\n async addResourceToIntegration(input: IAddResourceToIntegrationInput, context: GraphQLContext): Promise<IAddResourceToIntegrationResponse> {\n this.logger.info(context.loggedInUserId, this.addResourceToIntegration.name, this.fileName, 'addResourceToIntegration called', {\n offeringId: input.offeringId.toString(),\n capabilityIntegrationId: input.capabilityIntegrationId.toString(),\n });\n\n const addResult = await this.integrationResourceManagementDao.addCapabilityIntegrationMapping(\n {\n projectId: input.projectId,\n capabilityIntegrationId: input.capabilityIntegrationId,\n configuredForId: input.offeringId,\n configuredForType: CONFIGURED_FOR_TYPE_ENUM.OFFERING,\n config: input.config,\n },\n context,\n );\n\n const result: IAddResourceToIntegrationResponse = {\n status: addResult.status,\n ids: addResult.ids,\n };\n\n this.logger.info(context.loggedInUserId, this.addResourceToIntegration.name, this.fileName, 'addResourceToIntegration completed', {\n status: result.status,\n idsCount: result.ids.length,\n });\n\n return result;\n }\n\n /**\n * Removes a resource from an offering integration.\n * Generic validation and DAO call; Trybe service adds mapping-exists check before calling.\n */\n async removeResourceFromIntegration(\n request: IRemoveResourceFromIntegrationRequest,\n context: GraphQLContext,\n ): Promise<IRemoveResourceFromIntegrationResponse> {\n const result = await this.integrationResourceManagementDao.removeCapabilityIntegrationMapping(\n {\n capabilityIntegrationId: request.capabilityIntegrationId,\n configuredForId: request.offeringId,\n configuredForType: CONFIGURED_FOR_TYPE_ENUM.OFFERING,\n },\n context,\n );\n\n return { status: result.status };\n }\n\n /**\n * Updates offering integration resource configuration (cap_integ_resource_mapping.config by id).\n * Inter-service implementation only: performs DAO update. Wrapper must validate config before calling\n * (e.g. Trybe validates via validateResourceMappingConfig). Caller (MS) does getOffering,\n * getIntegration, and runAfterUpdateIfNeeded (e.g. handleTrybeIntegration).\n *\n * @param input - id (resource mapping row id), config\n * @param context - GraphQL context\n * @returns Promise resolving to { status }\n */\n async updateOfferingIntegrationResourceConfiguration(\n input: IUpdateOfferingIntegrationResourceConfigurationInput,\n context: GraphQLContext,\n ): Promise<IUpdateOfferingIntegrationResourceConfigurationResponse> {\n this.logger.info(\n context.loggedInUserId,\n this.updateOfferingIntegrationResourceConfiguration.name,\n this.fileName,\n 'updateOfferingIntegrationResourceConfiguration called',\n { id: input.id.toString() },\n );\n\n const result = await this.integrationResourceManagementDao.updateCapabilityIntegrationConfiguration(\n {\n id: input.id,\n config: input.config,\n },\n context,\n );\n\n this.logger.info(\n context.loggedInUserId,\n this.updateOfferingIntegrationResourceConfiguration.name,\n this.fileName,\n 'updateOfferingIntegrationResourceConfiguration completed',\n { status: result.status },\n );\n\n return { status: result.status };\n }\n}\n","import {\n IDeleteDeviceInput,\n IDeleteDeviceResponse,\n IGetDeviceKeyInput,\n IGetDeviceKeyResponse,\n IGetDevicesInput,\n IGetDevicesResponse,\n IRegisterDeviceInput,\n IRegisterDeviceResponse,\n IUpdateDeviceCertificateInput,\n IUpdateDeviceCertificateResponse,\n} from '../../models/device-management.model';\nimport { IAdminCredentials, IConfiguration } from '../../models/customer-management.model';\n\n/**\n * Base abstract class for device management operations\n * Provides a foundation for implementing device management functionality\n * within capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific device management operations for different systems\n */\nexport abstract class BaseDeviceManagement {\n /**\n * Initializes the customer management service with configuration and credentials\n *\n * This method sets up the service by:\n * 1. Storing the configuration settings\n * 2. Authenticating with the identity server\n * 3. Creating an authenticated Axios instance\n * 4. Setting up authorization headers for subsequent requests\n *\n * @param configuration - system configuration\n * @param credentials - Optional admin credentials (uses config credentials if not provided)\n */\n abstract init(configuration: IConfiguration, credentials?: IAdminCredentials): Promise<void>;\n\n /**\n * Registers a new device with the access control system\n *\n * @param request - Device registration input\n * @param loggedInUserId - User ID for logging\n * @returns Promise resolving to the registered device\n */\n\n abstract registerAcsDevice(request: IRegisterDeviceInput, loggedInUserId: bigint): Promise<IRegisterDeviceResponse>;\n\n /**\n * Deregisters a device from the access control system\n *\n * @param request - Device deregistration input\n * @param loggedInUserId - User ID for logging\n * @returns Promise resolving to the deregistered device\n */\n\n abstract deregisterAcsDevice(request: IDeleteDeviceInput, loggedInUserId: bigint): Promise<IDeleteDeviceResponse>;\n\n /**\n * Retrieves devices from the access control system\n *\n * @param request - Device retrieval input\n * @param loggedInUserId - User ID for logging\n * @returns Promise resolving to the retrieved devices\n */\n\n abstract getDevices(request: IGetDevicesInput, loggedInUserId: bigint): Promise<IGetDevicesResponse>;\n\n /**\n * Update device certificate from the control system\n *\n * @param request\n * @param loggedInUserId\n * @returns Promise resolving the updated device certificates\n */\n\n abstract updateDeviceCertificate(request: IUpdateDeviceCertificateInput, loggedInUserId: bigint): Promise<IUpdateDeviceCertificateResponse>;\n\n /**\n * Retrieves the device key from the control system\n *\n * @param request - Device key retrieval input\n * @param loggedInUserId - User ID for logging\n * @returns Promise resolving the device key\n */\n\n abstract getDeviceKey(request: IGetDeviceKeyInput, loggedInUserId: bigint): Promise<IGetDeviceKeyResponse>;\n\n /**\n * Retrieves the device from the control system\n *\n * @param request - Device retrieval input\n * @param loggedInUserId - User ID for logging\n * @returns Promise resolving the device\n */\n\n abstract getDevice(request: IGetDeviceKeyInput, loggedInUserId: bigint): Promise<IRegisterDeviceResponse>;\n\n /**\n * Retrieves the device keys for a user from the control system\n *\n * @param request - User device keys retrieval input\n * @param loggedInUserId - User ID for logging\n * @returns Promise resolving the user device keys\n */\n\n abstract getSiteUserDeviceKeys(request: { userId: string }, loggedInUserId: bigint): Promise<Array<{ id: string; key_uid: string }>>;\n}\n","import { IGetAccessProfilesResponse } from '../../models/access-management.model';\nimport { IAdminCredentials, IConfiguration } from '../../models/customer-management.model';\nimport { IGetDevicesInput } from '../../models/device-management.model';\n\n/**\n * Base abstract class for access management operations\n * Provides a foundation for implementing access management functionality\n * within capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific access management operations for different systems\n */\nexport abstract class BaseAccessManagement {\n /**\n * Initializes the customer management service with configuration and credentials\n *\n * This method sets up the service by:\n * 1. Storing the configuration settings\n * 2. Authenticating with the identity server\n * 3. Creating an authenticated Axios instance\n * 4. Setting up authorization headers for subsequent requests\n *\n * @param configuration - system configuration\n * @param credentials - Optional admin credentials (uses config credentials if not provided)\n */\n abstract init(configuration: IConfiguration, credentials?: IAdminCredentials): Promise<void>;\n\n /**\n * Retrieves the access profiles from the access control system\n *\n * @param request - Access profiles retrieval input [Optional]\n * @param loggedInUserId - User ID for logging\n * @returns Promise resolving the access profiles\n */\n abstract getAccessProfiles(request?: IGetDevicesInput, loggedInUserId?: bigint): Promise<IGetAccessProfilesResponse>;\n}\n","import { ICapabilityIntegration, IAccountingAPIResponse } from '../../../../integration-common-utils';\nimport {\n GetCustomerActivitiesInput,\n IAccounts,\n IAvailableTaxes,\n IDownloadCustomerAccountingStatementRequest,\n IGetCustomerActivities,\n ITransactionNumberSeries,\n} from '../../../models/miscellaneous.model';\n\n/**\n * Base abstract class for accounting miscellaneous management operations\n * Provides a foundation for implementing miscellaneous management functionality\n * within accounting capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific miscellaneous management operations for different accounting systems\n */\nexport abstract class BaseAccountingMiscellaneousManagement {\n /**\n * Retrieve bank & cash accounts from the accounting system.\n *\n * @returns Promise resolving to an array of {@link IAccounts}\n */\n abstract getAccounts(integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IAccounts[]>;\n\n /**\n * Fetches taxes from Zoho Books API\n *\n * @param integration - The Zoho Books integration configuration\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise resolving to list of taxes\n */\n abstract getTaxes(integration: ICapabilityIntegration, loggedInUserId: bigint, page?: number, limit?: number): Promise<IAvailableTaxes[]>;\n\n /**\n * Retrieve transaction number series from the accounting system.\n *\n * @param integration - The accounting integration configuration\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise resolving to list of transaction number series groups\n */\n abstract getTransactionNumberSeries(integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<ITransactionNumberSeries[]>;\n\n abstract downloadCustomerAccountingStatement(\n request: IDownloadCustomerAccountingStatementRequest,\n capabilityIntegration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<ArrayBuffer>;\n\n /**\n * Fetches list of all active items from Zoho Books API\n *\n * @param integration - The Zoho Books integration configuration\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise resolving to list of taxes\n */\n abstract listItems(integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IAccountingAPIResponse>;\n\n abstract getCustomerActivities(\n input: GetCustomerActivitiesInput,\n capabilityIntegration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IGetCustomerActivities>;\n}\n","import type { ICapabilityIntegration } from '../../../integration-common-utils';\nimport type { IGetResourcesRequest, IGetResourcesResponse } from '../../models/resource-management.model';\n\n/**\n * Base abstract class for calendar resource discovery (rooms / resource mailboxes).\n * Provider packages (e.g. Microsoft Graph) extend this with concrete API calls.\n */\nexport abstract class BaseCalendarResourceManagement {\n /**\n * Discovers calendar resources from the provider (e.g. Exchange room mailboxes).\n */\n abstract getResources(request: IGetResourcesRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IGetResourcesResponse>;\n}\n","import type { ICapabilityIntegration } from '../../../integration-common-utils';\nimport type {\n ICancelEventRequest,\n ICreateEventRequest,\n IDeleteEventRequest,\n IEvent,\n IGetEventRequest,\n IGetEventsRequest,\n IGetEventsResponse,\n ISyncEventsRequest,\n ISyncEventsResponse,\n IUpdateEventRequest,\n} from '../../models/booking-management.model';\n\n/**\n * Base abstract class for calendar event / booking lifecycle operations.\n * Provider packages extend this to implement Graph, Google Calendar, etc.\n */\nexport abstract class BaseCalendarBookingManagement {\n abstract createEvent(request: ICreateEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IEvent>;\n\n abstract updateEvent(request: IUpdateEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IEvent>;\n\n abstract cancelEvent(request: ICancelEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<void>;\n\n abstract deleteEvent(request: IDeleteEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<void>;\n\n abstract getEvent(request: IGetEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IEvent>;\n\n abstract getEvents(request: IGetEventsRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IGetEventsResponse>;\n\n abstract syncEvents(request: ISyncEventsRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<ISyncEventsResponse>;\n}\n","import type { ICapabilityIntegration } from '../../../integration-common-utils';\nimport type {\n IDeleteWebhookRequest,\n IRefreshWebhookRequest,\n IRefreshWebhookResponse,\n IRegisterWebhookRequest,\n IRegisterWebhookResponse,\n} from '../../models/webhook-management.model';\n\n/**\n * Base abstract class for calendar webhook / change-notification subscriptions.\n * Providers with expiring subscriptions (e.g. Microsoft Graph) implement register, refresh, and delete.\n */\nexport abstract class BaseCalendarWebhookManagement {\n abstract registerWebhook(request: IRegisterWebhookRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IRegisterWebhookResponse>;\n\n abstract refreshSubscription(\n request: IRefreshWebhookRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IRefreshWebhookResponse>;\n\n abstract deleteSubscription(request: IDeleteWebhookRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<void>;\n}\n","import { appConstants, schema } from '@dv4resi/dvss-backend-module-datastore';\nimport { LoggerService } from '@dv4resi/dvss-backend-module-utility';\nimport { Inject, Injectable } from '@nestjs/common';\nimport { and, eq, isNull } from 'drizzle-orm';\nimport type { MySql2Database } from 'drizzle-orm/mysql2';\nimport { IOfferingBookingOccurrence } from './models';\n\n/**\n * DAO for loading offering booking and related entities used when building\n */\n@Injectable()\nexport class IntegrationBookingDao {\n private readonly fileName = 'integration-booking.dao';\n\n constructor(\n @Inject(appConstants.DB_CONNECTION)\n private readonly conn: MySql2Database<typeof schema>,\n private readonly logger: LoggerService,\n ) {}\n\n async getOfferingBookingOccurrence(input: {\n offeringBookingOccurrenceId: bigint;\n loggedInUserId: bigint;\n offeringBookingId?: bigint;\n }): Promise<IOfferingBookingOccurrence | undefined> {\n this.logger.debug(\n input.loggedInUserId,\n this.getOfferingBookingOccurrence.name,\n this.fileName,\n 'Getting offering booking occurrence with input: ',\n input,\n );\n const conditions = [\n isNull(schema.offeringBookingOccurrence.deletedAt),\n eq(schema.offeringBookingOccurrence.id, input.offeringBookingOccurrenceId),\n isNull(schema.offeringBooking.deletedAt),\n isNull(schema.offering.deletedAt),\n ];\n if (input.offeringBookingId != null) {\n conditions.push(eq(schema.offeringBooking.id, input.offeringBookingId));\n }\n const result = await this.conn\n .select({\n offeringBookingOccurrence: schema.offeringBookingOccurrence,\n offering: schema.offering,\n offeringIntentId: schema.offeringBooking.offeringIntentId,\n })\n .from(schema.offeringBookingOccurrence)\n .innerJoin(schema.offeringBooking, eq(schema.offeringBookingOccurrence.offeringBookingId, schema.offeringBooking.id))\n .innerJoin(schema.offering, eq(schema.offeringBooking.offeringId, schema.offering.id))\n .where(and(...conditions))\n .limit(1);\n if (!result[0] || result[0].offeringIntentId == null) return undefined;\n return {\n offeringBookingOccurrence: result[0].offeringBookingOccurrence,\n offering: result[0].offering,\n offeringIntentId: result[0].offeringIntentId,\n };\n }\n /**\n * Fetches offering intent by id.\n */\n async getOfferingIntent(input: { offeringIntentId: bigint }): Promise<typeof schema.offeringIntent.$inferSelect | undefined> {\n const row = await this.conn.query.offeringIntent.findFirst({\n where: and(isNull(schema.offeringIntent.deletedAt), eq(schema.offeringIntent.id, input.offeringIntentId)),\n });\n return row ?? undefined;\n }\n}\n","import { appConstants, schema } from '@dv4resi/dvss-backend-module-datastore';\nimport { DEFAULT_TIMEZONE, LoggerService } from '@dv4resi/dvss-backend-module-utility';\nimport { Inject, Injectable } from '@nestjs/common';\nimport { and, eq, isNotNull, isNull } from 'drizzle-orm';\nimport type { MySql2Database } from 'drizzle-orm/mysql2';\n\n/**\n * Common DAO for integration utilities.\n * Provides shared database operations used across integrations.\n */\n@Injectable()\nexport class IntegrationCommonDao {\n private readonly fileName = 'integration-common.dao';\n\n constructor(\n @Inject(appConstants.DB_CONNECTION)\n private readonly conn: MySql2Database<typeof schema>,\n private readonly logger: LoggerService,\n ) {}\n\n /**\n * Gets timezone using userContext (first propertyId) with fallback to projectId\n * First tries to get timezone from user's first propertyId, then falls back to projectId\n * @param input - Object containing projectId and loggedInUserId\n * @returns Promise resolving to timezone string\n */\n async getTimezoneForRequest(input: { projectId?: number; loggedInUserId: bigint }): Promise<string> {\n const { projectId, loggedInUserId } = input;\n\n try {\n // First, try to get timezone from userContext (user's first propertyId)\n const userBehavior = await this.conn.query.userIdentityBehaviorMapping.findFirst({\n where: and(\n eq(schema.userIdentityBehaviorMapping.userIdentityId, loggedInUserId),\n isNotNull(schema.userIdentityBehaviorMapping.propertyId),\n isNull(schema.userIdentityBehaviorMapping.deletedAt),\n ),\n with: {\n property: true,\n },\n });\n\n if (userBehavior?.propertyId && userBehavior.property?.timezone) {\n this.logger.info(loggedInUserId, this.getTimezoneForRequest.name, this.fileName, 'Successfully fetched property timezone using userContext', {\n projectId,\n loggedInUserId,\n propertyId: userBehavior.propertyId,\n timezone: userBehavior.property.timezone,\n });\n return userBehavior.property.timezone;\n }\n\n // Fallback: use projectId to fetch properties and use the first propertyId to fetch timezone\n if (projectId) {\n const properties = await this.conn.query.property.findMany({\n where: and(eq(schema.property.projectId, projectId), isNull(schema.property.deletedAt)),\n limit: 1,\n });\n\n if (properties.length > 0 && properties[0].timezone) {\n this.logger.info(loggedInUserId, this.getTimezoneForRequest.name, this.fileName, 'Successfully fetched property timezone using projectId', {\n projectId,\n propertyId: properties[0].id,\n timezone: properties[0].timezone,\n });\n return properties[0].timezone;\n }\n }\n } catch (error: unknown) {\n this.logger.warn(loggedInUserId, this.getTimezoneForRequest.name, this.fileName, 'Error fetching property timezone, using default', {\n projectId,\n error,\n });\n }\n\n return DEFAULT_TIMEZONE;\n }\n}\n","import { appConstants, schema } from '@dv4resi/dvss-backend-module-datastore';\nimport { LoggerService } from '@dv4resi/dvss-backend-module-utility';\nimport { Inject, Injectable } from '@nestjs/common';\nimport { and, eq, isNull } from 'drizzle-orm';\nimport type { MySql2Database } from 'drizzle-orm/mysql2';\nimport { ISubCapability } from './models/integration-subcapability.model';\n\n@Injectable()\nexport class IntegrationSubcapabilityDao {\n private readonly fileName = 'integration-subcapability.dao';\n\n constructor(\n @Inject(appConstants.DB_CONNECTION)\n private readonly conn: MySql2Database<typeof schema>,\n private readonly logger: LoggerService,\n ) {}\n\n /**\n * Returns subcapability id for given capabilityId and subcapability name.\n * Enforces uniqueness: if more than one active row is found, throws an error.\n * If no active row is found, returns undefined (caller decides how to handle).\n */\n async getSubcapabilityId(input: { capabilityId: bigint; name: string }, loggedInUserId: bigint): Promise<bigint | undefined> {\n this.logger.info(loggedInUserId, this.getSubcapabilityId.name, this.fileName, 'IntegrationSubcapabilityDao -> getSubcapabilityId called', { input });\n\n try {\n const rows = await this.conn.query.subcapability.findMany({\n where: and(\n eq(schema.subcapability.capabilityId, input.capabilityId),\n eq(schema.subcapability.name, input.name),\n isNull(schema.subcapability.deletedAt),\n ),\n });\n\n if (rows.length === 0) {\n // Let caller decide how to surface \"not found\"\n this.logger.error(loggedInUserId, this.getSubcapabilityId.name, this.fileName, 'Subcapability not found for given capabilityId and name', {\n input,\n });\n return undefined;\n }\n\n return rows[0].id;\n } catch (error) {\n this.logger.error(loggedInUserId, this.getSubcapabilityId.name, this.fileName, 'Error in getSubcapabilityId', error, { input });\n throw error;\n }\n }\n\n async getSubcapabilities(input: { capabilityId: bigint }, loggedInUserId: bigint): Promise<ISubCapability[]> {\n this.logger.info(loggedInUserId, this.getSubcapabilities.name, this.fileName, 'IntegrationSubcapabilityDao -> getSubcapabilities called', { input });\n\n try {\n return await this.conn.query.subcapability.findMany({\n where: and(eq(schema.subcapability.capabilityId, input.capabilityId), isNull(schema.subcapability.deletedAt)),\n });\n } catch (error) {\n this.logger.error(loggedInUserId, this.getSubcapabilities.name, this.fileName, 'Error in getSubcapabilities', error, { input });\n throw error;\n }\n }\n}\n","import { schema } from '@dv4resi/dvss-backend-module-datastore';\nimport { CONFIGURED_FOR_TYPE_ENUM } from '@dv4resi/dvss-backend-module-datastore/dist/datastore/models';\nimport { CAPABILITY_INTEGRATION_STATUS_ENUM } from '@dv4resi/dvss-backend-module-datastore/dist/datastore/models/capability-integration.model';\nimport { and, eq, isNull } from 'drizzle-orm';\nimport type { MySql2Database } from 'drizzle-orm/mysql2';\n\nexport class IntegrationVisitorCredentialMappingDao {\n private readonly generateVisitorCredentialConfigKey = 'generateCredentialsForVisitor';\n private readonly capIntegResourceMappingOfficeVisitorType = CONFIGURED_FOR_TYPE_ENUM.OFFICE_VISITOR_CONFIGURATION;\n\n extractGenerateCredentialsForVisitorValue(config: unknown): boolean | undefined {\n if (!config || typeof config !== 'object') {\n return undefined;\n }\n\n const integrationConfig = (config as { integrationConfig?: Record<string, unknown> }).integrationConfig;\n const value = integrationConfig?.[this.generateVisitorCredentialConfigKey];\n\n return typeof value === 'boolean' ? value : undefined;\n }\n\n async syncVisitorCredentialMapping(input: {\n db: Pick<MySql2Database<typeof schema>, 'query' | 'insert' | 'update'>;\n capabilityIntegrationId: bigint;\n projectId: number;\n isGenerateCredentialsForVisitorEnabled: boolean | undefined;\n loggedInUserId: bigint;\n createOnly: boolean;\n }): Promise<void> {\n const isGenerateCredentialEnabled = Boolean(input.isGenerateCredentialsForVisitorEnabled);\n\n if (!isGenerateCredentialEnabled && input.createOnly) {\n return;\n }\n\n const officeVisitorConfigProfile = await input.db.query.officeVisitorConfigProfile.findFirst({\n where: and(eq(schema.officeVisitorConfigProfile.projectId, input.projectId), isNull(schema.officeVisitorConfigProfile.deletedAt)),\n });\n\n if (!officeVisitorConfigProfile) {\n return;\n }\n\n const capIntegResourceMapping = await input.db.query.capIntegResourceMapping.findFirst({\n where: and(\n eq(schema.capIntegResourceMapping.capabilityIntegrationId, input.capabilityIntegrationId),\n eq(schema.capIntegResourceMapping.configuredForType, this.capIntegResourceMappingOfficeVisitorType),\n eq(schema.capIntegResourceMapping.configuredForId, officeVisitorConfigProfile.id),\n isNull(schema.capIntegResourceMapping.deletedAt),\n ),\n });\n\n const currentConfig = capIntegResourceMapping?.config as { generateCredential?: unknown } | null | undefined;\n const isCurrentGenerateCredentialEnabled = currentConfig?.generateCredential === true;\n\n if (capIntegResourceMapping) {\n if (isCurrentGenerateCredentialEnabled !== isGenerateCredentialEnabled) {\n await input.db\n .update(schema.capIntegResourceMapping)\n .set({\n config: {\n generateCredential: isGenerateCredentialEnabled,\n },\n updatedAt: new Date(),\n updatedBy: input.loggedInUserId,\n })\n .where(eq(schema.capIntegResourceMapping.id, capIntegResourceMapping.id));\n }\n\n return;\n }\n\n if (!isGenerateCredentialEnabled) {\n return;\n }\n\n await input.db.insert(schema.capIntegResourceMapping).values({\n projectId: input.projectId,\n configuredForId: officeVisitorConfigProfile.id,\n configuredForType: this.capIntegResourceMappingOfficeVisitorType,\n capabilityIntegrationId: input.capabilityIntegrationId,\n config: {\n generateCredential: true,\n },\n createdBy: input.loggedInUserId,\n status: CAPABILITY_INTEGRATION_STATUS_ENUM.ACTIVE,\n });\n }\n}\n","import { appConstants, MAX_RECORDS_LENGTH, schema } from '@dv4resi/dvss-backend-module-datastore';\nimport { SORTING_ORDER_ENUM } from '@dv4resi/dvss-backend-module-datastore/dist/datastore/commons/common.enum';\nimport { CONFIGURED_FOR_TYPE_ENUM } from '@dv4resi/dvss-backend-module-datastore/dist/datastore/models';\nimport {\n CAP_INTEG_SUBCAPABILITY_MAPPING_STATUS_ENUM,\n CAPABILITY_INTEGRATION_STATUS_ENUM,\n} from '@dv4resi/dvss-backend-module-datastore/dist/datastore/models/capability-integration.model';\nimport {\n type ICapability,\n CAPABILITY_TYPE_ENUM,\n type CAPABILITY_CATEGORY_ENUM,\n} from '@dv4resi/dvss-backend-module-datastore/dist/datastore/models/capability.model';\nimport { LoggerService } from '@dv4resi/dvss-backend-module-utility';\nimport { Inject, Injectable } from '@nestjs/common';\nimport { and, asc, desc, eq, getTableColumns, inArray, isNotNull, isNull, or, type SQL, sql } from 'drizzle-orm';\nimport type { MySqlColumn } from 'drizzle-orm/mysql-core';\nimport type { MySql2Database } from 'drizzle-orm/mysql2';\n\nimport type { ICapabilityIntegration } from '../../integration-operation-skeletons/models/capability-integration.model';\nimport type {\n IGetCapabilityIntegrationsRequest,\n IGetCapabilityIntegrationsResponse,\n} from '../../integration-operation-skeletons/models/integration-configuration.model';\nimport {\n CapabilityIntegrationCategory,\n IAddCapabilityIntegration,\n IAddCapIntegResourceMapping,\n IUpdateCapabilityIntegration,\n type IGetCapabilityIntegrationResult,\n} from './models';\nimport { IntegrationSubcapabilityDao } from './integration-subcapability.dao';\nimport { IAddCapIntegSubcapabilityMapping } from './models/integration-subcapability.model';\nimport { IntegrationVisitorCredentialMappingDao } from './integration-visitor-credential-mapping.dao';\n\n/**\n * DAO for integration-configuration persistence (offering get/update).\n * Performs actual DB calls using datastore schema; conn is injected by the host app.\n */\n@Injectable()\nexport class IntegrationConfigurationDao {\n private readonly fileName = 'integration-configuration.dao';\n private readonly integrationVisitorCredentialMappingDao = new IntegrationVisitorCredentialMappingDao();\n\n constructor(\n @Inject(appConstants.DB_CONNECTION)\n private readonly conn: MySql2Database<typeof schema>,\n private readonly logger: LoggerService,\n private readonly integrationSubcapabilityDao: IntegrationSubcapabilityDao,\n ) {}\n\n async addCapabilityIntegration(input: IAddCapabilityIntegration, loggedInUserId: bigint): Promise<{ id: bigint } | undefined> {\n // Log the attempt to add a capability integration\n this.logger.info(loggedInUserId, this.addCapabilityIntegration.name, this.fileName, `CapabilityDaoService -> addCapabilityIntegration called`);\n\n try {\n // Run operations in a transaction\n return this.conn.transaction(async (tx) => {\n const { configuredFor, resourceMappings, ...capabilityIntegrationInsertInput } = input;\n\n // Insert the capability integration record and get its ID\n const [integrationResult] = await tx.insert(schema.capabilityIntegration).values(capabilityIntegrationInsertInput).$returningId();\n\n if (!integrationResult.id) {\n // rollback if insertion failed\n tx.rollback();\n return;\n }\n\n // Add mapping rows (resourceMappings takes precedence; configuredFor kept for backwards compatibility)\n if (resourceMappings?.length) {\n for (const mapping of resourceMappings) {\n const insertData: IAddCapIntegResourceMapping = {\n capabilityIntegrationId: integrationResult.id,\n configuredForId: mapping.configuredForId,\n configuredForType: mapping.configuredForType,\n status: CAPABILITY_INTEGRATION_STATUS_ENUM.ACTIVE,\n projectId: input.projectId,\n config: mapping.config ?? undefined,\n createdAt: new Date(),\n createdBy: loggedInUserId,\n };\n\n await tx.insert(schema.capIntegResourceMapping).values(insertData);\n }\n } else if (configuredFor) {\n const insertData: IAddCapIntegResourceMapping = {\n capabilityIntegrationId: integrationResult.id,\n configuredForId: configuredFor.configuredForId,\n configuredForType: configuredFor.configuredForType,\n status: CAPABILITY_INTEGRATION_STATUS_ENUM.ACTIVE,\n projectId: input.projectId,\n createdAt: new Date(),\n createdBy: loggedInUserId,\n };\n\n await tx.insert(schema.capIntegResourceMapping).values(insertData);\n }\n\n const subcapabilities = await this.integrationSubcapabilityDao.getSubcapabilities({ capabilityId: input.capabilityId }, loggedInUserId);\n\n this.logger.info(\n loggedInUserId,\n this.addCapabilityIntegration.name,\n this.fileName,\n `Subcapabilities ${subcapabilities.length} found for capabilityIntegrationId: ${integrationResult.id}`,\n );\n\n for (const subcapability of subcapabilities) {\n const insertData: IAddCapIntegSubcapabilityMapping = {\n capabilityIntegrationId: integrationResult.id,\n subcapabilityId: subcapability.id,\n projectId: input.projectId,\n createdAt: new Date(),\n createdBy: loggedInUserId,\n status: CAP_INTEG_SUBCAPABILITY_MAPPING_STATUS_ENUM.ACTIVE,\n };\n await tx.insert(schema.capIntegSubcapabilityMapping).values(insertData);\n }\n\n await this.integrationVisitorCredentialMappingDao.syncVisitorCredentialMapping({\n db: tx,\n capabilityIntegrationId: integrationResult.id,\n projectId: input.projectId,\n isGenerateCredentialsForVisitorEnabled: this.integrationVisitorCredentialMappingDao.extractGenerateCredentialsForVisitorValue(input.config),\n loggedInUserId,\n createOnly: true,\n });\n\n return { id: integrationResult.id };\n });\n } catch (error) {\n // Log and rethrow\n this.logger.error(loggedInUserId, this.addCapabilityIntegration.name, this.fileName, 'Error in addCapabilityIntegration', error, input);\n\n throw error;\n }\n }\n\n /**\n * Get capability by id (for add-capability-integration validation).\n * Copied from project-ms CapabilityDaoService.getCapability.\n */\n async getCapability(request: { capabilityId: bigint }, loggedInUserId: bigint): Promise<ICapability | undefined> {\n try {\n this.logger.info(loggedInUserId, this.getCapability.name, this.fileName, 'getCapability called', { request });\n\n return await this.conn.query.capability.findFirst({\n where: and(eq(schema.capability.id, request.capabilityId), isNull(schema.capability.deletedAt)),\n });\n } catch (error) {\n this.logger.error(loggedInUserId, this.getCapability.name, this.fileName, 'Error on getCapability', error, { request });\n\n throw error;\n }\n }\n\n /**\n * Get capability provider by id (for add-capability-integration validation).\n * Copied from project-ms CapabilityProviderDao.getCapabilityProvider.\n */\n async getCapabilityProvider(\n request: { capabilityProviderId: bigint },\n loggedInUserId: bigint,\n ): Promise<typeof schema.capabilityProvider.$inferSelect | undefined> {\n try {\n this.logger.info(loggedInUserId, this.getCapabilityProvider.name, this.fileName, 'getCapabilityProvider called', { request });\n\n return await this.conn.query.capabilityProvider.findFirst({\n where: and(eq(schema.capabilityProvider.id, request.capabilityProviderId), isNull(schema.capabilityProvider.deletedAt)),\n });\n } catch (error) {\n this.logger.error(loggedInUserId, this.getCapabilityProvider.name, this.fileName, 'Error on getCapabilityProvider', error, { request });\n\n throw error;\n }\n }\n\n /**\n * Updates capability integration in the database.\n * Copied from project-ms CapabilityIntegrationDao.updateCapabilityIntegration.\n *\n * @param input - Object containing the integration ID and update data\n * @param loggedInUserId - User ID for logging\n * @returns Promise that resolves to the update operation status\n */\n async updateCapabilityIntegration(\n input: {\n id: bigint;\n updateData: IUpdateCapabilityIntegration;\n projectId: number;\n },\n loggedInUserId: bigint,\n ): Promise<{ status: boolean }> {\n try {\n this.logger.info(loggedInUserId, this.updateCapabilityIntegration.name, this.fileName, 'Updating capability integration', { input });\n\n const response = await this.conn\n .update(schema.capabilityIntegration)\n .set({\n ...input.updateData,\n })\n .where(eq(schema.capabilityIntegration.id, input.id));\n\n const isGenerateCredentialsForVisitorEnabled = this.integrationVisitorCredentialMappingDao.extractGenerateCredentialsForVisitorValue(\n input.updateData.config,\n );\n if (typeof isGenerateCredentialsForVisitorEnabled === 'boolean') {\n await this.integrationVisitorCredentialMappingDao.syncVisitorCredentialMapping({\n db: this.conn,\n capabilityIntegrationId: input.id,\n projectId: input.projectId,\n isGenerateCredentialsForVisitorEnabled,\n loggedInUserId,\n createOnly: false,\n });\n }\n\n return {\n status: response[0].affectedRows > 0,\n };\n } catch (error) {\n this.logger.error(loggedInUserId, this.updateCapabilityIntegration.name, this.fileName, 'Error updating capability integration', error);\n\n throw error;\n }\n }\n\n async updateCapabilityIntegrationAccessDetails(\n capabilityIntegrationId: bigint,\n accessToken: string,\n expiresInSeconds: number,\n loggedInUserId: bigint,\n ): Promise<void> {\n try {\n this.logger.info(\n loggedInUserId,\n this.updateCapabilityIntegrationAccessDetails.name,\n this.fileName,\n 'Updating capability integration access details',\n { capabilityIntegrationId },\n );\n\n const expiryAtExpression = sql`DATE_FORMAT(UTC_TIMESTAMP() + INTERVAL ${expiresInSeconds} SECOND, '%Y-%m-%dT%H:%i:%sZ')`;\n\n await this.conn\n .update(schema.capabilityIntegration)\n .set({\n config: sql`\n JSON_SET(\n JSON_SET(\n COALESCE(${schema.capabilityIntegration.config}, JSON_OBJECT()),\n '$.accessDetails',\n COALESCE(JSON_EXTRACT(COALESCE(${schema.capabilityIntegration.config}, JSON_OBJECT()), '$.accessDetails'), JSON_OBJECT())\n ),\n '$.accessDetails.accessToken', ${accessToken},\n '$.accessDetails.expiryAt', ${expiryAtExpression}\n )\n `,\n updatedBy: loggedInUserId,\n })\n .where(and(eq(schema.capabilityIntegration.id, capabilityIntegrationId), isNull(schema.capabilityIntegration.deletedAt)));\n } catch (error) {\n this.logger.error(\n loggedInUserId,\n this.updateCapabilityIntegrationAccessDetails.name,\n this.fileName,\n 'Error updating capability integration access details',\n error,\n { capabilityIntegrationId },\n );\n\n throw error;\n }\n }\n\n /**\n * Replace cap_integ_resource_mapping rows for the given capabilityIntegrationId and configuredForTypes.\n * Upsert semantics: delete existing rows first, then insert the provided mappings.\n */\n async syncCapabilityIntegrationResourceMappings(\n input: {\n capabilityIntegrationId: bigint;\n projectId: number;\n resourceMappings: Array<{\n configuredForId: bigint;\n configuredForType: CONFIGURED_FOR_TYPE_ENUM;\n config?: typeof schema.capIntegResourceMapping.$inferSelect.config;\n }>;\n },\n loggedInUserId: bigint,\n ): Promise<{ status: boolean }> {\n try {\n if (input.resourceMappings.length === 0) {\n return { status: true };\n }\n\n const inputMap = new Map<string, (typeof input.resourceMappings)[number]>();\n for (const m of input.resourceMappings) {\n inputMap.set(`${m.configuredForId}:${m.configuredForType}`, m);\n }\n\n const inputKeys = new Set(inputMap.keys());\n\n return await this.conn.transaction(async (tx) => {\n const existing = await tx\n .select({\n id: schema.capIntegResourceMapping.id,\n configuredForId: schema.capIntegResourceMapping.configuredForId,\n configuredForType: schema.capIntegResourceMapping.configuredForType,\n })\n .from(schema.capIntegResourceMapping)\n .where(\n and(\n eq(schema.capIntegResourceMapping.capabilityIntegrationId, input.capabilityIntegrationId),\n eq(schema.capIntegResourceMapping.projectId, input.projectId),\n isNull(schema.capIntegResourceMapping.deletedAt),\n ),\n );\n\n const existingMap = new Map<string, (typeof existing)[number]>();\n for (const e of existing) {\n existingMap.set(`${e.configuredForId}:${e.configuredForType}`, e);\n }\n\n const toDeleteIds: bigint[] = [];\n for (const [key, value] of existingMap.entries()) {\n if (!inputKeys.has(key)) {\n toDeleteIds.push(value.id);\n }\n }\n\n const toInsert: IAddCapIntegResourceMapping[] = [];\n for (const [key, mapping] of inputMap.entries()) {\n if (!existingMap.has(key)) {\n toInsert.push({\n capabilityIntegrationId: input.capabilityIntegrationId,\n configuredForId: mapping.configuredForId,\n configuredForType: mapping.configuredForType,\n status: CAPABILITY_INTEGRATION_STATUS_ENUM.ACTIVE,\n projectId: input.projectId,\n config: mapping.config ?? undefined,\n createdAt: new Date(),\n createdBy: loggedInUserId,\n });\n }\n }\n\n if (toDeleteIds.length > 0) {\n await tx\n .update(schema.capIntegResourceMapping)\n .set({\n deletedAt: new Date(),\n deletedBy: loggedInUserId,\n })\n .where(inArray(schema.capIntegResourceMapping.id, toDeleteIds));\n }\n if (toInsert.length > 0) {\n await tx.insert(schema.capIntegResourceMapping).values(toInsert);\n }\n\n return { status: true };\n });\n } catch (error) {\n this.logger.error(\n loggedInUserId,\n this.syncCapabilityIntegrationResourceMappings.name,\n this.fileName,\n 'Error syncing capability integration resource mappings',\n error,\n input,\n );\n\n throw error;\n }\n }\n\n /**\n * Get capability integration by id (for parent validation when parentId is set).\n * Copied from project-ms CapabilityIntegrationDao.getCapabilityIntegration.\n */\n async getCapabilityIntegration(\n input: { capabilityIntegrationId: bigint },\n loggedInUserId: bigint,\n ): Promise<typeof schema.capabilityIntegration.$inferSelect | undefined> {\n try {\n this.logger.info(loggedInUserId, this.getCapabilityIntegration.name, this.fileName, 'getCapabilityIntegration called', input);\n\n return await this.conn.query.capabilityIntegration.findFirst({\n where: and(isNull(schema.capabilityIntegration.deletedAt), eq(schema.capabilityIntegration.id, input.capabilityIntegrationId)),\n });\n } catch (error) {\n this.logger.error(loggedInUserId, this.getCapabilityIntegration.name, this.fileName, 'Error on getCapabilityIntegration', error, input);\n\n throw error;\n }\n }\n\n /**\n * Retrieves capability integration by ID with resource mapping details.\n * Copied from project-ms CapabilityIntegrationDao.getCapabilityIntegrationById.\n */\n async getCapabilityIntegrationById(\n request: {\n id: bigint;\n projectId: number;\n category?: CAPABILITY_CATEGORY_ENUM;\n },\n loggedInUserId: bigint,\n ): Promise<IGetCapabilityIntegrationResult | undefined> {\n try {\n this.logger.info(loggedInUserId, this.getCapabilityIntegrationById.name, this.fileName, 'getCapabilityIntegrationById called', request);\n\n const conditions = [\n eq(schema.capabilityIntegration.id, request.id),\n eq(schema.capabilityIntegration.projectId, request.projectId),\n eq(schema.capabilityIntegration.type, CAPABILITY_TYPE_ENUM.INTEGRATION),\n eq(schema.capabilityIntegration.status, CAPABILITY_INTEGRATION_STATUS_ENUM.ACTIVE),\n isNull(schema.capabilityIntegration.deletedAt),\n isNull(schema.capability.deletedAt),\n ];\n\n if (request.category) {\n conditions.push(eq(schema.capabilityIntegration.category, request.category));\n }\n\n const response = await this.conn\n .select({\n ...getTableColumns(schema.capabilityIntegration),\n resourceMappingId: schema.capIntegResourceMapping.id,\n configuredForId: schema.capIntegResourceMapping.configuredForId,\n configuredForType: schema.capIntegResourceMapping.configuredForType,\n resourceMappingConfig: schema.capIntegResourceMapping.config,\n provider: schema.capability.providerIntegrationType,\n })\n .from(schema.capabilityIntegration)\n .innerJoin(schema.capability, eq(schema.capability.id, schema.capabilityIntegration.capabilityId))\n .leftJoin(\n schema.capIntegResourceMapping,\n and(\n eq(schema.capIntegResourceMapping.capabilityIntegrationId, schema.capabilityIntegration.id),\n eq(schema.capIntegResourceMapping.projectId, request.projectId),\n isNull(schema.capIntegResourceMapping.deletedAt),\n ),\n )\n .where(and(...conditions));\n\n return response[0] as unknown as IGetCapabilityIntegrationResult | undefined;\n } catch (error) {\n this.logger.error(loggedInUserId, this.getCapabilityIntegrationById.name, this.fileName, 'Error on getCapabilityIntegrationById', error, request);\n\n throw error;\n }\n }\n\n /**\n * Retrieves capability integration by provider type and resource mapping.\n * Copied from project-ms CapabilityIntegrationDao.getCapabilityIntegrationByProvider.\n */\n async getCapabilityIntegrationByProvider(\n request: {\n projectId: number;\n category?: CAPABILITY_CATEGORY_ENUM;\n configuredForType: CONFIGURED_FOR_TYPE_ENUM;\n configuredForId: bigint;\n },\n loggedInUserId: bigint,\n ): Promise<IGetCapabilityIntegrationResult | undefined> {\n try {\n this.logger.info(loggedInUserId, this.getCapabilityIntegrationByProvider.name, this.fileName, 'getCapabilityIntegrationByProvider called', request);\n\n const conditions = [\n isNull(schema.capability.deletedAt),\n eq(schema.capabilityIntegration.projectId, request.projectId),\n eq(schema.capabilityIntegration.type, CAPABILITY_TYPE_ENUM.INTEGRATION),\n eq(schema.capabilityIntegration.status, CAPABILITY_INTEGRATION_STATUS_ENUM.ACTIVE),\n isNull(schema.capabilityIntegration.deletedAt),\n eq(schema.capIntegResourceMapping.projectId, request.projectId),\n eq(schema.capIntegResourceMapping.configuredForType, request.configuredForType),\n eq(schema.capIntegResourceMapping.configuredForId, request.configuredForId),\n isNull(schema.capIntegResourceMapping.deletedAt),\n ];\n\n if (request.category) {\n conditions.push(eq(schema.capabilityIntegration.category, request.category));\n }\n\n const response = await this.conn\n .select({\n ...getTableColumns(schema.capabilityIntegration),\n resourceMappingId: schema.capIntegResourceMapping.id,\n configuredForId: schema.capIntegResourceMapping.configuredForId,\n configuredForType: schema.capIntegResourceMapping.configuredForType,\n resourceMappingConfig: schema.capIntegResourceMapping.config,\n provider: schema.capability.providerIntegrationType,\n })\n .from(schema.capabilityIntegration)\n .innerJoin(schema.capability, eq(schema.capability.id, schema.capabilityIntegration.capabilityId))\n .innerJoin(schema.capIntegResourceMapping, eq(schema.capIntegResourceMapping.capabilityIntegrationId, schema.capabilityIntegration.id))\n .where(and(...conditions));\n\n return response[0] as unknown as IGetCapabilityIntegrationResult | undefined;\n } catch (error) {\n this.logger.error(\n loggedInUserId,\n this.getCapabilityIntegrationByProvider.name,\n this.fileName,\n 'Error on getCapabilityIntegrationByProvider',\n error,\n request,\n );\n\n throw error;\n }\n }\n\n /**\n * Get capability integrations with pagination, filtering, sorting, and search.\n * Copied from project-ms CapabilityIntegrationDao.getCapabilityIntegrations.\n */\n async getCapabilityIntegrations(input: IGetCapabilityIntegrationsRequest, loggedInUserId: bigint): Promise<IGetCapabilityIntegrationsResponse> {\n try {\n this.logger.info(loggedInUserId, this.getCapabilityIntegrations.name, this.fileName, 'getCapabilityIntegrations called', input);\n\n const count = input.options?.count ?? MAX_RECORDS_LENGTH;\n const offset = ((input.options?.page ?? 1) - 1) * count;\n\n const sorting = input.options?.sorting;\n let sortBy: MySqlColumn = schema.capabilityIntegration.id;\n\n if (sorting?.by === 'CREATED_AT') {\n sortBy = schema.capabilityIntegration.createdAt;\n } else if (sorting?.by === 'UPDATED_AT') {\n sortBy = schema.capabilityIntegration.updatedAt;\n }\n\n const sortOrder: SQL = sorting?.order === SORTING_ORDER_ENUM.ASC ? asc(sortBy) : desc(sortBy);\n const searchTerm = input.options?.search;\n\n // Determine if we need capability table join (for search, provider filter)\n const shouldJoinCapability = Boolean(searchTerm) || Boolean(input.options?.filters?.some((filter) => filter.by === 'PROVIDER_INTEGRATION_TYPE'));\n\n // Build where conditions for data query\n const whereConditions: SQL[] = [eq(schema.capabilityIntegration.projectId, input.projectId), isNull(schema.capabilityIntegration.deletedAt)];\n\n if (input.category) {\n whereConditions.push(eq(schema.capabilityIntegration.category, input.category as CapabilityIntegrationCategory));\n }\n\n // Apply filters\n if (input.options?.filters && input.options.filters.length > 0) {\n this.applyFilters(whereConditions, input.options);\n }\n\n if (searchTerm) {\n const searchPattern = `%${searchTerm}%`;\n whereConditions.push(sql`(${schema.capabilityIntegration.nickname} LIKE ${searchPattern} OR ${schema.capability.name} LIKE ${searchPattern})`);\n }\n\n // Add capability deletedAt check if capability join is present\n if (shouldJoinCapability) {\n whereConditions.push(isNull(schema.capability.deletedAt));\n }\n\n // Filter out NULL mappings when propertyId is provided\n if (input.propertyId) {\n whereConditions.push(isNotNull(schema.capIntegResourceMapping.id));\n }\n\n // Build count query\n const countWhereConditions: SQL[] = [eq(schema.capabilityIntegration.projectId, input.projectId), isNull(schema.capabilityIntegration.deletedAt)];\n\n if (input.category) {\n countWhereConditions.push(eq(schema.capabilityIntegration.category, input.category as CapabilityIntegrationCategory));\n }\n\n if (input.options?.filters && input.options.filters.length > 0) {\n this.applyFilters(countWhereConditions, input.options);\n }\n\n if (searchTerm) {\n const searchPattern = `%${searchTerm}%`;\n countWhereConditions.push(\n sql`(${schema.capabilityIntegration.nickname} LIKE ${searchPattern} OR ${schema.capability.name} LIKE ${searchPattern})`,\n );\n }\n\n const countQueryBuilder = this.conn\n .select({\n count: sql`count(distinct ${schema.capabilityIntegration.id})`.as('count'),\n })\n .from(schema.capabilityIntegration);\n\n const countQueryWithJoins = shouldJoinCapability\n ? countQueryBuilder.leftJoin(schema.capability, eq(schema.capability.id, schema.capabilityIntegration.capabilityId))\n : countQueryBuilder;\n\n if (shouldJoinCapability) {\n countWhereConditions.push(isNull(schema.capability.deletedAt));\n }\n\n const countQueryWithPropertyJoin = input.propertyId\n ? countQueryWithJoins.leftJoin(\n schema.capIntegResourceMapping,\n and(\n eq(schema.capIntegResourceMapping.capabilityIntegrationId, schema.capabilityIntegration.id),\n eq(schema.capIntegResourceMapping.configuredForType, CONFIGURED_FOR_TYPE_ENUM.PROPERTY),\n eq(schema.capIntegResourceMapping.configuredForId, BigInt(input.propertyId)),\n isNull(schema.capIntegResourceMapping.deletedAt),\n ),\n )\n : countQueryWithJoins;\n\n if (input.propertyId) {\n countWhereConditions.push(isNotNull(schema.capIntegResourceMapping.id));\n }\n\n const countQuery = countQueryWithPropertyJoin.where(and(...countWhereConditions));\n\n // Build data query\n const baseQuery = this.conn\n .select({\n ...getTableColumns(schema.capabilityIntegration),\n provider: schema.capability.providerIntegrationType,\n })\n .from(schema.capabilityIntegration)\n .leftJoin(schema.capability, eq(schema.capability.id, schema.capabilityIntegration.capabilityId));\n\n const finalQuery = input.propertyId\n ? baseQuery\n .leftJoin(\n schema.capIntegResourceMapping,\n and(\n eq(schema.capIntegResourceMapping.capabilityIntegrationId, schema.capabilityIntegration.id),\n eq(schema.capIntegResourceMapping.configuredForType, CONFIGURED_FOR_TYPE_ENUM.PROPERTY),\n eq(schema.capIntegResourceMapping.configuredForId, BigInt(input.propertyId)),\n isNull(schema.capIntegResourceMapping.deletedAt),\n ),\n )\n .where(and(...whereConditions))\n : baseQuery.where(and(...whereConditions));\n\n // Execute queries in parallel\n const [{ count: totalCount }, records] = await Promise.all([\n countQuery.execute().then((result) => result[0]),\n finalQuery.limit(count).offset(offset).orderBy(sortOrder).execute(),\n ]);\n\n return {\n totalCount: Number(totalCount) || 0,\n records: records as unknown as ICapabilityIntegration[],\n };\n } catch (error) {\n this.logger.error(loggedInUserId, this.getCapabilityIntegrations.name, this.fileName, 'Error in getCapabilityIntegrations', error, input);\n\n throw error;\n }\n }\n\n /**\n * Applies filters to where conditions.\n */\n private applyFilters(whereConditions: SQL[], filters: IGetCapabilityIntegrationsRequest['options'] | undefined): void {\n if (!filters || !filters.filters) {\n return;\n }\n\n for (const filter of filters.filters) {\n const filterValues = filter.values;\n\n if (!filterValues || filterValues.length === 0) {\n continue;\n }\n\n switch (filter.by) {\n case 'PROVIDER_INTEGRATION_TYPE': {\n const valuePlaceholders = filterValues.map((value) => sql`${String(value)}`);\n const joinedValues = sql.join(valuePlaceholders, sql`, `);\n whereConditions.push(sql`${schema.capability.providerIntegrationType} IN (${joinedValues})`);\n break;\n }\n\n case 'CAPABILITY_INTEGRATION_TYPE': {\n const parentConditions: SQL[] = [];\n\n for (const value of filterValues) {\n const upperValue = String(value).toUpperCase();\n\n if (upperValue === 'PARENT') {\n parentConditions.push(isNull(schema.capabilityIntegration.parentId));\n } else if (upperValue === 'CHILD') {\n parentConditions.push(isNotNull(schema.capabilityIntegration.parentId));\n }\n }\n\n if (parentConditions.length === 1) {\n whereConditions.push(parentConditions[0]);\n } else if (parentConditions.length > 1) {\n const orCondition = or(...parentConditions);\n\n if (orCondition) {\n whereConditions.push(orCondition);\n }\n }\n break;\n }\n }\n }\n }\n}\n","import { appConstants, schema } from '@dv4resi/dvss-backend-module-datastore';\nimport { LoggerService, SYSTEM_USER_ID } from '@dv4resi/dvss-backend-module-utility';\nimport { Inject, Injectable } from '@nestjs/common';\nimport { and, eq, getTableColumns, isNull } from 'drizzle-orm';\nimport type { MySql2Database } from 'drizzle-orm/mysql2';\nimport { IAddServiceCommunicationTopic, IGetServiceCommunicationTopic } from './models/service-communication-topic.model';\n\n/**\n * DAO for on-prem service communication topics.\n * Performs DB operations on the `service_communication_topic` table using the shared datastore schema.\n */\n@Injectable()\nexport class IntegrationServiceCommunicationTopicDao {\n private readonly fileName = 'integration-service-communication-topic.dao';\n\n constructor(\n @Inject(appConstants.DB_CONNECTION)\n private readonly conn: MySql2Database<typeof schema>,\n private readonly logger: LoggerService,\n ) {}\n\n /**\n * Upserts a service communication topic for a given deployment + capability/subcapability/operation.\n * If a matching topic exists (by deploymentId + capability + subcapability + subcapabilityOperation),\n * it will be updated; otherwise a new row will be inserted.\n */\n async upsertTopic(input: IAddServiceCommunicationTopic, loggedInUserId = SYSTEM_USER_ID): Promise<{ status: boolean }> {\n this.logger.info(loggedInUserId, this.upsertTopic.name, this.fileName, 'IntegrationServiceCommunicationTopicDao -> upsertTopic called', { input });\n\n try {\n const existing = await this.conn.query.serviceCommunicationTopic.findFirst({\n where: and(\n eq(schema.serviceCommunicationTopic.deploymentId, input.deploymentId as bigint),\n eq(schema.serviceCommunicationTopic.projectId, input.projectId as number),\n isNull(schema.serviceCommunicationTopic.deletedAt),\n // capability / subcapability filters are optional\n ...(input.capability ? [eq(schema.serviceCommunicationTopic.capability, input.capability)] : []),\n ...(input.subcapability ? [eq(schema.serviceCommunicationTopic.subcapability, input.subcapability)] : []),\n eq(schema.serviceCommunicationTopic.subcapabilityOperation, input.subcapabilityOperation),\n ...(input.capabilityIntegrationId ? [eq(schema.serviceCommunicationTopic.capabilityIntegrationId, input.capabilityIntegrationId)] : []),\n ),\n });\n\n if (existing) {\n await this.conn\n .update(schema.serviceCommunicationTopic)\n .set({\n topicType: input.topicType,\n topicName: input.topicName,\n isUniversal: input.isUniversal ?? existing.isUniversal,\n shouldPublish: input.shouldPublish ?? existing.shouldPublish,\n shouldSubscribe: input.shouldSubscribe ?? existing.shouldSubscribe,\n updatedAt: new Date(),\n updatedBy: loggedInUserId,\n })\n .where(eq(schema.serviceCommunicationTopic.id, existing.id));\n\n return { status: true };\n }\n\n await this.conn.insert(schema.serviceCommunicationTopic).values({\n projectId: input.projectId,\n propertyId: input.propertyId,\n deploymentId: input.deploymentId,\n capability: input.capability,\n subcapability: input.subcapability,\n subcapabilityOperation: input.subcapabilityOperation,\n topicType: input.topicType,\n topicName: input.topicName,\n isUniversal: input.isUniversal ?? false,\n shouldPublish: input.shouldPublish ?? false,\n shouldSubscribe: input.shouldSubscribe ?? true,\n createdBy: loggedInUserId,\n capabilityIntegrationId: input.capabilityIntegrationId,\n });\n\n return { status: true };\n } catch (error) {\n this.logger.error(loggedInUserId, this.upsertTopic.name, this.fileName, 'Error in upsertTopic', error, { input });\n\n throw error;\n }\n }\n\n /**\n * Returns all service communication topics for a given integration.\n * NOTE: Currently filters by deploymentId using the provided integrationId;\n * once capabilityIntegrationId is available in the public typings, this can\n * be updated to filter by that column instead.\n */\n async getServiceCommunicationTopics(integrationId: bigint, loggedInUserId = SYSTEM_USER_ID): Promise<IGetServiceCommunicationTopic[]> {\n this.logger.info(\n loggedInUserId,\n this.getServiceCommunicationTopics.name,\n this.fileName,\n 'IntegrationServiceCommunicationTopicDao -> getServiceCommunicationTopics called',\n { integrationId },\n );\n\n try {\n const topics = await this.conn\n .select({\n ...getTableColumns(schema.serviceCommunicationTopic),\n subcapability: getTableColumns(schema.subcapability),\n })\n .from(schema.serviceCommunicationTopic)\n .innerJoin(schema.subcapability, eq(schema.subcapability.id, schema.serviceCommunicationTopic.subcapability))\n .where(and(eq(schema.serviceCommunicationTopic.capabilityIntegrationId, integrationId), isNull(schema.serviceCommunicationTopic.deletedAt)));\n\n return topics as IGetServiceCommunicationTopic[];\n } catch (error) {\n this.logger.error(loggedInUserId, this.getServiceCommunicationTopics.name, this.fileName, 'Error in getServiceCommunicationTopics', error, {\n integrationId,\n });\n throw error;\n }\n }\n}\n","import { appConstants, schema } from '@dv4resi/dvss-backend-module-datastore';\nimport type { CONFIGURED_FOR_TYPE_ENUM } from '@dv4resi/dvss-backend-module-datastore/dist/datastore/models';\nimport { CAPABILITY_INTEGRATION_STATUS_ENUM } from '@dv4resi/dvss-backend-module-datastore/dist/datastore/models/capability-integration.model';\nimport { GraphQLContext, LoggerService } from '@dv4resi/dvss-backend-module-utility';\nimport { Inject, Injectable } from '@nestjs/common';\nimport { and, eq, isNull } from 'drizzle-orm';\nimport type { MySql2Database } from 'drizzle-orm/mysql2';\nimport { IAddCapabilityIntegrationMappingResponse, ICapabilityIntegrationResourceMappingRow, IDeleteAPIResponse, IUpdateAPIResponse } from './models';\n\n/**\n * DAO for integration resource management (cap_integ_resource_mapping).\n * Provides checkMappingExists and removeCapabilityIntegrationMapping so UIF/callers\n * can validate and remove capability integration mappings without inter-service calls.\n */\n@Injectable()\nexport class IntegrationResourceManagementDao {\n private readonly fileName = 'integration-resource-management.dao';\n\n constructor(\n @Inject(appConstants.DB_CONNECTION)\n private readonly conn: MySql2Database<typeof schema>,\n private readonly logger: LoggerService,\n ) {}\n\n /**\n * Adds a capability integration resource mapping (insert into cap_integ_resource_mapping).\n * Replaces inter-service gRPC call to project-onboarding-ms for add configurations.\n *\n * @param input - projectId, capabilityIntegrationId, configuredForId, configuredForType, optional config\n * @param context - GraphQL context for loggedInUserId\n * @returns Promise resolving to { status: true, ids: [insertedId] } or { status: false, ids: [] }\n */\n async addCapabilityIntegrationMapping(\n input: {\n projectId: number;\n capabilityIntegrationId: bigint;\n configuredForId: bigint;\n configuredForType: CONFIGURED_FOR_TYPE_ENUM;\n config?: Record<string, unknown>;\n },\n context: GraphQLContext,\n ): Promise<IAddCapabilityIntegrationMappingResponse> {\n try {\n this.logger.info(context.loggedInUserId, this.addCapabilityIntegrationMapping.name, this.fileName, 'Adding capability integration mapping', input);\n\n const insertResult = await this.conn.insert(schema.capIntegResourceMapping).values({\n projectId: input.projectId,\n status: CAPABILITY_INTEGRATION_STATUS_ENUM.ACTIVE,\n capabilityIntegrationId: input.capabilityIntegrationId,\n configuredForId: input.configuredForId,\n configuredForType: input.configuredForType,\n config: input.config ?? null,\n createdBy: context.loggedInUserId,\n });\n\n const raw = insertResult as unknown as { insertId?: number | string }[];\n const insertedId = raw[0]?.insertId != null ? Number(raw[0].insertId) : 0;\n const isInserted = insertedId > 0;\n const ids = isInserted ? [BigInt(insertedId)] : [];\n\n this.logger.info(\n context.loggedInUserId,\n this.addCapabilityIntegrationMapping.name,\n this.fileName,\n `Mapping add ${isInserted ? 'successful' : 'failed'}`,\n { insertedId, status: isInserted },\n );\n\n return { status: isInserted, ids };\n } catch (error) {\n this.logger.error(\n context.loggedInUserId,\n this.addCapabilityIntegrationMapping.name,\n this.fileName,\n 'Error adding capability integration mapping',\n error,\n input,\n );\n throw error;\n }\n }\n\n /**\n * Checks if a capability integration resource mapping exists.\n * Validates that the mapping exists for the given capability integration, configured for ID and type.\n *\n * @param input - Input containing capability integration ID, configured for ID and type\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise that resolves to true if mapping exists, false otherwise\n */\n async checkMappingExists(\n input: {\n capabilityIntegrationId: bigint;\n configuredForId: bigint;\n configuredForType: CONFIGURED_FOR_TYPE_ENUM;\n },\n loggedInUserId: bigint,\n ): Promise<boolean> {\n try {\n this.logger.info(loggedInUserId, this.checkMappingExists.name, this.fileName, `${this.checkMappingExists.name} called`, input);\n\n const response = await this.conn\n .select({ id: schema.capIntegResourceMapping.id })\n .from(schema.capIntegResourceMapping)\n .where(\n and(\n eq(schema.capIntegResourceMapping.capabilityIntegrationId, input.capabilityIntegrationId),\n eq(schema.capIntegResourceMapping.configuredForId, input.configuredForId),\n eq(schema.capIntegResourceMapping.configuredForType, input.configuredForType),\n isNull(schema.capIntegResourceMapping.deletedAt),\n ),\n )\n .limit(1);\n\n return response.length > 0;\n } catch (error) {\n this.logger.error(loggedInUserId, this.checkMappingExists.name, this.fileName, 'Error in checkMappingExists', error, input);\n\n throw error;\n }\n }\n\n /**\n * Removes capability integration resource mapping (soft delete).\n * Sets deletedAt and deletedBy on the matching cap_integ_resource_mapping row.\n * Use this from UIF/callers instead of inter-service call to project-onboarding-ms.\n *\n * @param input - Delete parameters including capability integration ID, configured for ID and type\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise resolving to { status: true } if any row was updated, { status: false } otherwise\n */\n async removeCapabilityIntegrationMapping(\n input: {\n capabilityIntegrationId: bigint;\n configuredForId: bigint;\n configuredForType: CONFIGURED_FOR_TYPE_ENUM;\n },\n context: GraphQLContext,\n ): Promise<IDeleteAPIResponse> {\n try {\n this.logger.info(\n context.loggedInUserId,\n this.removeCapabilityIntegrationMapping.name,\n this.fileName,\n 'Removing capability integration mapping',\n input,\n );\n\n // Build where conditions for the delete operation - match on capability_integration_id, configured_for_id, and configured_for_type\n const whereConditions = [\n isNull(schema.capIntegResourceMapping.deletedAt),\n eq(schema.capIntegResourceMapping.capabilityIntegrationId, input.capabilityIntegrationId),\n eq(schema.capIntegResourceMapping.configuredForId, input.configuredForId),\n eq(schema.capIntegResourceMapping.configuredForType, input.configuredForType),\n ];\n\n // Perform soft delete\n const deleteResult = await this.conn\n .update(schema.capIntegResourceMapping)\n .set({\n deletedAt: new Date(),\n deletedBy: context.loggedInUserId,\n })\n .where(and(...whereConditions));\n\n const isSuccess = deleteResult[0].affectedRows > 0;\n\n this.logger.info(\n context.loggedInUserId,\n this.removeCapabilityIntegrationMapping.name,\n this.fileName,\n `Mapping removal ${isSuccess ? 'successful' : 'failed - no matching records'}`,\n { affectedRows: deleteResult[0].affectedRows },\n );\n\n return { status: isSuccess };\n } catch (error) {\n this.logger.error(\n context.loggedInUserId,\n this.removeCapabilityIntegrationMapping.name,\n this.fileName,\n 'Error removing capability integration mapping',\n error,\n input,\n );\n\n throw error;\n }\n }\n\n /**\n * Gets a capability integration resource mapping by id (non-deleted only).\n * Use from UIF wrappers to validate mapping exists before update.\n *\n * @param id - cap_integ_resource_mapping.id\n * @param loggedInUserId - for logging\n * @returns The mapping row or undefined if not found\n */\n async getCapabilityIntegrationResourceMappingById(id: bigint, loggedInUserId: bigint): Promise<ICapabilityIntegrationResourceMappingRow | undefined> {\n try {\n this.logger.info(\n loggedInUserId,\n this.getCapabilityIntegrationResourceMappingById.name,\n this.fileName,\n `${this.getCapabilityIntegrationResourceMappingById.name} called`,\n { id: id.toString() },\n );\n\n const rows = await this.conn\n .select({\n id: schema.capIntegResourceMapping.id,\n capabilityIntegrationId: schema.capIntegResourceMapping.capabilityIntegrationId,\n configuredForId: schema.capIntegResourceMapping.configuredForId,\n configuredForType: schema.capIntegResourceMapping.configuredForType,\n })\n .from(schema.capIntegResourceMapping)\n .where(and(eq(schema.capIntegResourceMapping.id, id), isNull(schema.capIntegResourceMapping.deletedAt)))\n .limit(1);\n\n return rows[0];\n } catch (error) {\n this.logger.error(\n loggedInUserId,\n this.getCapabilityIntegrationResourceMappingById.name,\n this.fileName,\n 'Error in getCapabilityIntegrationResourceMappingById',\n error,\n { id: id.toString() },\n );\n throw error;\n }\n }\n\n /**\n * Updates capability integration resource mapping config by id.\n * Replaces inter-service gRPC call to project-onboarding-ms for update capability integration configuration.\n *\n * @param input - id (mapping row id), config (new config JSON)\n * @param context - GraphQL context for loggedInUserId\n * @returns Promise resolving to { status: true } if row was updated, { status: false } otherwise\n */\n async updateCapabilityIntegrationConfiguration(\n input: {\n id: bigint;\n config: Record<string, unknown>;\n },\n context: GraphQLContext,\n ): Promise<IUpdateAPIResponse> {\n try {\n this.logger.info(\n context.loggedInUserId,\n this.updateCapabilityIntegrationConfiguration.name,\n this.fileName,\n 'Updating capability integration resource mapping config',\n { id: input.id.toString() },\n );\n\n const updateResult = await this.conn\n .update(schema.capIntegResourceMapping)\n .set({\n config: input.config,\n updatedBy: context.loggedInUserId,\n })\n .where(and(eq(schema.capIntegResourceMapping.id, input.id), isNull(schema.capIntegResourceMapping.deletedAt)));\n\n const isSuccess = updateResult[0].affectedRows > 0;\n\n this.logger.info(\n context.loggedInUserId,\n this.updateCapabilityIntegrationConfiguration.name,\n this.fileName,\n `Mapping config update ${isSuccess ? 'successful' : 'failed - no matching records'}`,\n { affectedRows: updateResult[0].affectedRows },\n );\n\n return { status: isSuccess };\n } catch (error) {\n this.logger.error(\n context.loggedInUserId,\n this.updateCapabilityIntegrationConfiguration.name,\n this.fileName,\n 'Error updating capability integration resource mapping config',\n error,\n input,\n );\n\n throw error;\n }\n }\n}\n","import { appConstants, schema } from '@dv4resi/dvss-backend-module-datastore';\nimport { Inject, Injectable } from '@nestjs/common';\nimport type { MySql2Database } from 'drizzle-orm/mysql2';\n\n/**\n * DAO for integration user-management persistence.\n * Performs actual DB calls using datastore schema; conn is injected by the host app.\n */\n@Injectable()\nexport class IntegrationUserManagementDao {\n constructor(\n @Inject(appConstants.DB_CONNECTION)\n protected readonly conn: MySql2Database<typeof schema>,\n ) {}\n}\n","import { appConstants, schema } from '@dv4resi/dvss-backend-module-datastore';\nimport { IAddUpdateAPIStatusResponseBigInt } from '@dv4resi/dvss-backend-module-datastore/dist/datastore/models';\nimport { LoggerService, SYSTEM_USER_ID } from '@dv4resi/dvss-backend-module-utility';\nimport { Inject, Injectable } from '@nestjs/common';\nimport { and, eq, isNull } from 'drizzle-orm';\nimport type { MySql2Database } from 'drizzle-orm/mysql2';\n\nimport { IAddOnpremDeployment, IUpdateOnpremDeployment } from './models/integration-onprem-deloyment.model';\n\n/**\n * DAO for integration-configuration persistence (offering get/update).\n * Performs actual DB calls using datastore schema; conn is injected by the host app.\n */\n@Injectable()\nexport class IntegrationOnpremDeploymentDao {\n private readonly fileName = 'integration-onprem-deployment.dao';\n\n constructor(\n @Inject(appConstants.DB_CONNECTION)\n private readonly conn: MySql2Database<typeof schema>,\n private readonly logger: LoggerService,\n ) {}\n\n async addUpdateOnpremDeployment(input: IAddOnpremDeployment, loggedInUserId = SYSTEM_USER_ID): Promise<IAddUpdateAPIStatusResponseBigInt> {\n try {\n // Log the attempt to add a capability integration\n this.logger.info(\n loggedInUserId,\n this.addUpdateOnpremDeployment.name,\n this.fileName,\n `IntegrationOnpremDeploymentDao -> addUpdateOnpremDeployment called`,\n {\n input,\n },\n );\n\n //Check if entry exists by projectId and capabilityIntegrationId\n //If entry exists, update the entry\n //If entry does not exist, create a new entry\n const existingEntry = await this.conn.query.onPremDeployment.findFirst({\n where: and(\n eq(schema.onPremDeployment.projectId, input.projectId as number),\n eq(schema.onPremDeployment.capabilityIntegrationId, input.capabilityIntegrationId),\n ),\n });\n if (existingEntry) {\n await this.updateOnpremDeployment(existingEntry.id, input, loggedInUserId);\n\n return { status: true, id: existingEntry.id };\n }\n return this.addOnpremDeployment(input, loggedInUserId);\n } catch (error) {\n // Log and rethrow\n this.logger.error(loggedInUserId, this.addUpdateOnpremDeployment.name, this.fileName, 'Error in addCapabilityIntegration', error, { input });\n\n throw error;\n }\n }\n\n private async addOnpremDeployment(input: IAddOnpremDeployment, loggedInUserId = SYSTEM_USER_ID): Promise<IAddUpdateAPIStatusResponseBigInt> {\n try {\n const [insertedResult] = await this.conn.insert(schema.onPremDeployment).values(input).$returningId();\n\n return { status: true, id: BigInt(insertedResult.id) };\n } catch (error) {\n this.logger.error(loggedInUserId, this.addOnpremDeployment.name, this.fileName, 'Error in addOnpremDeployment', error, { input });\n throw error;\n }\n }\n\n private async updateOnpremDeployment(\n id: bigint,\n updateData: IUpdateOnpremDeployment,\n loggedInUserId = SYSTEM_USER_ID,\n ): Promise<IAddUpdateAPIStatusResponseBigInt> {\n try {\n const result = await this.conn.update(schema.onPremDeployment).set(updateData).where(eq(schema.onPremDeployment.id, id)).execute();\n return { status: result[0].affectedRows > 0, id };\n } catch (error) {\n this.logger.error(loggedInUserId, this.updateOnpremDeployment.name, this.fileName, 'Error in updateOnpremDeployment', error, { id, updateData });\n throw error;\n }\n }\n\n /**\n * Gets an on-prem deployment by capability integration id.\n * Used by Suprema integration to resolve deployment for a given integration.\n */\n async getOnpremDeployment(\n input: { integrationId: bigint; projectId: number },\n loggedInUserId = SYSTEM_USER_ID,\n ): Promise<typeof schema.onPremDeployment.$inferSelect | undefined> {\n try {\n this.logger.info(loggedInUserId, this.getOnpremDeployment.name, this.fileName, 'IntegrationOnpremDeploymentDao -> getOnpremDeployment called', {\n input,\n });\n\n return await this.conn.query.onPremDeployment.findFirst({\n where: and(\n eq(schema.onPremDeployment.projectId, input.projectId),\n eq(schema.onPremDeployment.capabilityIntegrationId, input.integrationId),\n isNull(schema.onPremDeployment.deletedAt),\n ),\n });\n } catch (error) {\n this.logger.error(loggedInUserId, this.getOnpremDeployment.name, this.fileName, 'Error in getOnpremDeployment', error, { input });\n throw error;\n }\n }\n}\n","import { ENV_PREFIX, OAUTH_TOKEN_CACHE_PREFIX, OAUTH_TOKEN_LOCK_PREFIX } from '@dv4resi/dvss-backend-module-datastore';\n\n/**\n * Replaces `{placeholder}` tokens in catalog URLs (e.g. `{tenantId}`).\n * Unknown placeholders are left unchanged.\n */\nexport function substituteUrlPlaceholders(url: string, params: Record<string, string> = {}): string {\n return url.replace(/\\{(\\w+)\\}/g, (matched, name: string) => params[name] ?? matched);\n}\n\nexport function hasPersistedIntegrationId(id?: bigint): id is bigint {\n return id != null && id !== BigInt(0);\n}\n\nexport function secondsUntil(expiresAt: Date, nowMs: number = Date.now()): number {\n return Math.max(0, Math.floor((expiresAt.getTime() - nowMs) / 1000));\n}\n\n/** Tokens within this window of expiry are treated as stale so callers refresh early. */\nexport const OAUTH_TOKEN_FRESHNESS_BUFFER_MS = 60_000;\n\nexport function isTokenFresh(expiresAt: Date, nowMs: number = Date.now()): boolean {\n return expiresAt.getTime() - OAUTH_TOKEN_FRESHNESS_BUFFER_MS > nowMs;\n}\n\nexport function getIntegrationConfigKmsKeyId(): string {\n return process.env.INTEGRATION_CONFIG_KMS_KEY_ID || '';\n}\n\nexport function delay(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n\n/** Exact Redis key for a cached OAuth access token (`{ENV}{oauthToken:}{id}`). */\nexport function getOauthTokenCacheKey(capabilityIntegrationId: bigint): string {\n return `${ENV_PREFIX}${OAUTH_TOKEN_CACHE_PREFIX}${capabilityIntegrationId.toString()}`;\n}\n\n/** Exact Redis key for the OAuth mint lock (`{ENV}{oauthTokenLock:}{id}`). */\nexport function getOauthTokenLockKey(capabilityIntegrationId: bigint): string {\n return `${ENV_PREFIX}${OAUTH_TOKEN_LOCK_PREFIX}${capabilityIntegrationId.toString()}`;\n}\n","import { RedisCacheStoreService } from '@dv4resi/dvss-backend-module-datastore';\nimport { Injectable } from '@nestjs/common';\n\nimport { getOauthTokenCacheKey, secondsUntil } from '../common/oauth.util';\nimport type { IOauthAccessToken } from '../models/oauth.model';\n\ninterface ICachedOauthToken {\n accessToken: string;\n tokenType: string;\n expiresAt: string;\n refreshToken?: string;\n}\n\n@Injectable()\nexport class OauthTokenCache {\n constructor(private readonly redisCacheStoreService: RedisCacheStoreService) {}\n\n async get(capabilityIntegrationId: bigint): Promise<IOauthAccessToken | undefined> {\n const cached = await this.redisCacheStoreService.get<ICachedOauthToken>(getOauthTokenCacheKey(capabilityIntegrationId));\n\n if (!cached?.accessToken || !cached.expiresAt) {\n return undefined;\n }\n\n return {\n accessToken: cached.accessToken,\n tokenType: cached.tokenType,\n expiresAt: new Date(cached.expiresAt),\n refreshToken: cached.refreshToken,\n };\n }\n\n async set(capabilityIntegrationId: bigint, token: IOauthAccessToken): Promise<void> {\n const ttlSeconds = secondsUntil(token.expiresAt);\n\n if (ttlSeconds <= 0) {\n return;\n }\n\n await this.redisCacheStoreService.set(\n getOauthTokenCacheKey(capabilityIntegrationId),\n {\n accessToken: token.accessToken,\n tokenType: token.tokenType,\n expiresAt: token.expiresAt.toISOString(),\n refreshToken: token.refreshToken,\n } satisfies ICachedOauthToken,\n ttlSeconds,\n );\n }\n\n async del(capabilityIntegrationId: bigint): Promise<void> {\n await this.redisCacheStoreService.del(getOauthTokenCacheKey(capabilityIntegrationId));\n }\n}\n","import { Injectable } from '@nestjs/common';\n\nimport type { IOauthAccessToken } from '../models/oauth.model';\nimport type { GrantHandler, IGrantMintRequest } from './grant-handler';\n\n@Injectable()\nexport class AuthorizationCodeGrantHandler implements GrantHandler {\n mint(request: IGrantMintRequest): Promise<IOauthAccessToken> {\n throw new Error(`NotImplemented: authorization_code grant is not supported (${request.tokenUrl})`);\n }\n}\n","export const OAUTH_GRANT_TYPE = {\n AUTHORIZATION_CODE: 'AUTHORIZATION_CODE',\n CLIENT_CREDENTIALS: 'CLIENT_CREDENTIALS',\n} as const;\n\nexport type OauthGrantType = (typeof OAUTH_GRANT_TYPE)[keyof typeof OAUTH_GRANT_TYPE];\n\nexport const OAUTH_RFC_GRANT_TYPE: Record<OauthGrantType, string> = {\n AUTHORIZATION_CODE: 'authorization_code',\n CLIENT_CREDENTIALS: 'client_credentials',\n};\n\nexport const OAUTH_DEFAULT_TOKEN_TYPE = 'Bearer';\n\nexport const OAUTH_TOKEN_HEADERS = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Accept: 'application/json',\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/x-www-form-urlencoded',\n};\n\nexport interface IOauthMintCredentials {\n tokenUrl: string;\n clientId: string;\n clientSecret: string;\n scope?: string;\n urlParams?: Record<string, string>;\n}\n\nexport interface IOauthAccessToken {\n accessToken: string;\n tokenType: string;\n expiresAt: Date;\n refreshToken?: string;\n metadata?: Record<string, unknown>;\n}\n\nexport interface IGetValidAccessTokenOptions {\n forceRefresh?: boolean;\n loggedInUserId?: bigint;\n credentials?: IOauthMintCredentials;\n capabilityId?: bigint;\n providerId?: bigint;\n}\n","import { LoggerService } from '@dv4resi/dvss-backend-module-utility';\nimport { HTTP_METHOD, type IValidatedCapabilityIntegration, TrafficGatewayService } from '@dvss/dvss-integration-libs';\nimport { Injectable } from '@nestjs/common';\n\nimport { OAUTH_DEFAULT_TOKEN_TYPE, OAUTH_RFC_GRANT_TYPE, OAUTH_TOKEN_HEADERS, type IOauthAccessToken } from '../models/oauth.model';\nimport type { GrantHandler, IGrantMintRequest } from './grant-handler';\n\ninterface IOauthTokenHttpResponse {\n access_token?: string;\n token_type?: string;\n expires_in?: number;\n refresh_token?: string;\n}\n\n@Injectable()\nexport class ClientCredentialsGrantHandler implements GrantHandler {\n private readonly fileName = 'client-credentials.handler';\n\n constructor(\n private readonly logger: LoggerService,\n private readonly trafficGatewayService: TrafficGatewayService,\n ) {}\n\n async mint(request: IGrantMintRequest): Promise<IOauthAccessToken> {\n const tokenUrl = new URL(request.tokenUrl);\n const body = new URLSearchParams({\n client_id: request.credentials.clientId,\n client_secret: request.credentials.clientSecret,\n grant_type: OAUTH_RFC_GRANT_TYPE.CLIENT_CREDENTIALS,\n });\n\n if (request.scope) {\n body.set('scope', request.scope);\n }\n\n const loggedInUserId = request.loggedInUserId;\n const integrationContext = {\n id: request.integration.id as bigint,\n capabilityId: request.integration.capabilityId,\n providerId: request.integration.providerId,\n projectId: request.integration.projectId,\n headers: OAUTH_TOKEN_HEADERS,\n config: {\n platformConfig: { authUrl: request.tokenUrl, baseUrl: tokenUrl.origin },\n integrationConfig: {},\n },\n } as unknown as IValidatedCapabilityIntegration;\n\n this.logger.info(loggedInUserId, this.mint.name, this.fileName, 'Minting OAuth access token with client_credentials');\n\n const response = await this.trafficGatewayService.executeIntegrationRequest<IOauthTokenHttpResponse, string>(\n {\n apiMethod: HTTP_METHOD.POST,\n baseUrl: tokenUrl.origin,\n url: `${tokenUrl.pathname}${tokenUrl.search}`,\n body: body.toString(),\n headers: OAUTH_TOKEN_HEADERS,\n },\n integrationContext,\n loggedInUserId,\n );\n\n if (!response.access_token) {\n throw new Error('OAuth token response is missing access_token');\n }\n\n const expiresInSeconds = response.expires_in ?? 0;\n\n return {\n accessToken: response.access_token,\n tokenType: response.token_type ?? OAUTH_DEFAULT_TOKEN_TYPE,\n expiresAt: new Date(Date.now() + expiresInSeconds * 1000),\n refreshToken: response.refresh_token,\n };\n }\n}\n","import { Injectable } from '@nestjs/common';\n\nimport { OAUTH_GRANT_TYPE, type OauthGrantType } from '../models/oauth.model';\nimport { AuthorizationCodeGrantHandler } from './authorization-code.handler';\nimport { ClientCredentialsGrantHandler } from './client-credentials.handler';\nimport type { GrantHandler } from './grant-handler';\n\n@Injectable()\nexport class GrantHandlerRegistry {\n constructor(\n private readonly clientCredentialsGrantHandler: ClientCredentialsGrantHandler,\n private readonly authorizationCodeGrantHandler: AuthorizationCodeGrantHandler,\n ) {}\n\n get(grantType: OauthGrantType): GrantHandler {\n if (grantType === OAUTH_GRANT_TYPE.CLIENT_CREDENTIALS) {\n return this.clientCredentialsGrantHandler;\n }\n\n return this.authorizationCodeGrantHandler;\n }\n\n resolvePreferredGrant(supportedGrantTypes: OauthGrantType[] | undefined): OauthGrantType {\n if (supportedGrantTypes?.includes(OAUTH_GRANT_TYPE.CLIENT_CREDENTIALS)) {\n return OAUTH_GRANT_TYPE.CLIENT_CREDENTIALS;\n }\n\n if (supportedGrantTypes?.length) {\n return supportedGrantTypes[0];\n }\n\n return OAUTH_GRANT_TYPE.CLIENT_CREDENTIALS;\n }\n}\n","import { appConstants, DATABASE_ERROR_NAMES, errorHandler, MODULE_NAME, schema } from '@dv4resi/dvss-backend-module-datastore';\nimport { LoggerService } from '@dv4resi/dvss-backend-module-utility';\nimport { Inject, Injectable } from '@nestjs/common';\nimport { and, eq, isNull } from 'drizzle-orm';\nimport type { MySql2Database } from 'drizzle-orm/mysql2';\n\nimport type { IOauthProvider } from './oauth.model';\n\n@Injectable()\nexport class OauthProviderDao {\n private readonly fileName = 'oauth-provider.dao';\n\n constructor(\n @Inject(appConstants.DB_CONNECTION)\n private readonly conn: MySql2Database<typeof schema>,\n private readonly logger: LoggerService,\n ) {}\n\n async findByCapabilityAndProvider(capabilityId: bigint, providerId: bigint, loggedInUserId: bigint): Promise<IOauthProvider | undefined> {\n this.logger.info(loggedInUserId, this.findByCapabilityAndProvider.name, this.fileName, 'Loading OAuth provider catalog row', {\n capabilityId,\n providerId,\n });\n\n try {\n const rows = await this.conn\n .select()\n .from(schema.integrationOauthProvider)\n .where(\n and(\n eq(schema.integrationOauthProvider.capabilityId, capabilityId),\n eq(schema.integrationOauthProvider.providerId, providerId),\n isNull(schema.integrationOauthProvider.deletedAt),\n ),\n );\n\n return rows[0];\n } catch (error) {\n throw errorHandler(\n loggedInUserId,\n this.findByCapabilityAndProvider.name,\n this.fileName,\n DATABASE_ERROR_NAMES.DATABASE_ERROR,\n MODULE_NAME.COMMON,\n error,\n { capabilityId, providerId },\n ) as Error;\n }\n }\n}\n","import { appConstants, DATABASE_ERROR_NAMES, errorHandler, MODULE_NAME, schema } from '@dv4resi/dvss-backend-module-datastore';\nimport { LoggerService } from '@dv4resi/dvss-backend-module-utility';\nimport { Inject, Injectable } from '@nestjs/common';\nimport { and, eq, isNull } from 'drizzle-orm';\nimport type { MySql2Database } from 'drizzle-orm/mysql2';\n\nimport type { IOauthToken, IUpsertOauthTokenInput } from './oauth.model';\n\n@Injectable()\nexport class OauthTokenDao {\n private readonly fileName = 'oauth-token.dao';\n\n constructor(\n @Inject(appConstants.DB_CONNECTION)\n private readonly conn: MySql2Database<typeof schema>,\n private readonly logger: LoggerService,\n ) {}\n\n async findByCapabilityIntegrationId(capabilityIntegrationId: bigint, loggedInUserId: bigint): Promise<IOauthToken | undefined> {\n this.logger.info(loggedInUserId, this.findByCapabilityIntegrationId.name, this.fileName, 'Loading OAuth token row', { capabilityIntegrationId });\n\n try {\n const rows = await this.conn\n .select()\n .from(schema.integrationOauthToken)\n .where(and(eq(schema.integrationOauthToken.capabilityIntegrationId, capabilityIntegrationId), isNull(schema.integrationOauthToken.deletedAt)));\n\n return rows[0];\n } catch (error) {\n throw errorHandler(\n loggedInUserId,\n this.findByCapabilityIntegrationId.name,\n this.fileName,\n DATABASE_ERROR_NAMES.DATABASE_ERROR,\n MODULE_NAME.COMMON,\n error,\n { capabilityIntegrationId },\n ) as Error;\n }\n }\n\n async upsert(input: IUpsertOauthTokenInput): Promise<void> {\n this.logger.info(input.loggedInUserId, this.upsert.name, this.fileName, 'Upserting OAuth token row', {\n capabilityIntegrationId: input.capabilityIntegrationId,\n });\n\n const existing = await this.findByCapabilityIntegrationId(input.capabilityIntegrationId, input.loggedInUserId);\n const now = new Date();\n\n try {\n if (existing) {\n await this.conn\n .update(schema.integrationOauthToken)\n .set({\n accessToken: input.accessToken,\n refreshToken: input.refreshToken ?? null,\n expiresAt: input.expiresAt,\n refreshExpiredAt: input.refreshExpiredAt ?? null,\n tokenMetadata: input.tokenMetadata ?? null,\n updatedAt: now,\n updatedBy: input.loggedInUserId,\n deletedAt: null,\n deletedBy: null,\n })\n .where(eq(schema.integrationOauthToken.id, existing.id));\n return;\n }\n\n await this.conn.insert(schema.integrationOauthToken).values({\n capabilityIntegrationId: input.capabilityIntegrationId,\n accessToken: input.accessToken,\n refreshToken: input.refreshToken ?? null,\n expiresAt: input.expiresAt,\n refreshExpiredAt: input.refreshExpiredAt ?? null,\n tokenMetadata: input.tokenMetadata ?? null,\n createdAt: now,\n createdBy: input.loggedInUserId,\n });\n } catch (error) {\n throw errorHandler(input.loggedInUserId, this.upsert.name, this.fileName, DATABASE_ERROR_NAMES.DATABASE_ERROR, MODULE_NAME.COMMON, error, {\n capabilityIntegrationId: input.capabilityIntegrationId,\n }) as Error;\n }\n }\n}\n","import { RedisCacheStoreService } from '@dv4resi/dvss-backend-module-datastore';\nimport { LoggerService, SECRET_PROVIDER, type SecretProvider, SYSTEM_USER_ID } from '@dv4resi/dvss-backend-module-utility';\nimport { Inject, Injectable, Optional } from '@nestjs/common';\nimport { randomUUID } from 'crypto';\n\nimport { OauthTokenCache } from '../cache/oauth-token-cache';\nimport {\n delay,\n getIntegrationConfigKmsKeyId,\n getOauthTokenLockKey,\n hasPersistedIntegrationId,\n isTokenFresh,\n substituteUrlPlaceholders,\n} from '../common/oauth.util';\nimport { GrantHandlerRegistry } from '../grants/grant-handler.registry';\nimport type { IGetValidAccessTokenOptions, IOauthAccessToken, IOauthMintCredentials, OauthGrantType } from '../models/oauth.model';\nimport { OauthProviderDao } from '../store/oauth-provider.dao';\nimport { OauthTokenDao } from '../store/oauth-token.dao';\n\n// SECRET_PROVIDER is undefined when tests mock utility without it.\n// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\nconst oauthSecretProviderToken = SECRET_PROVIDER ?? Symbol('SECRET_PROVIDER');\n\nconst OAUTH_LOCK_TTL_SECONDS = 30;\nconst OAUTH_LOCK_WAIT_MS = 100;\nconst OAUTH_LOCK_MAX_WAIT_MS = 10_000;\n\ninterface IMemorySession {\n token: string;\n tokenType: string;\n tokenExpiry: Date;\n refreshToken?: string;\n}\n\n@Injectable()\nexport class OauthTokenManager {\n private readonly fileName = 'oauth-token-manager';\n\n private readonly sessions = new Map<string, IMemorySession>();\n\n constructor(\n private readonly logger: LoggerService,\n private readonly tokenDao: OauthTokenDao,\n private readonly providerDao: OauthProviderDao,\n private readonly tokenCache: OauthTokenCache,\n private readonly redisCacheStoreService: RedisCacheStoreService,\n private readonly grantHandlerRegistry: GrantHandlerRegistry,\n @Optional() @Inject(oauthSecretProviderToken) private readonly secretProvider?: SecretProvider,\n ) {}\n\n async getValidAccessToken(capabilityIntegrationId: bigint | undefined, opts: IGetValidAccessTokenOptions = {}): Promise<IOauthAccessToken> {\n const loggedInUserId = opts.loggedInUserId ?? SYSTEM_USER_ID;\n const shouldForceRefresh = opts.forceRefresh === true;\n\n if (!shouldForceRefresh && hasPersistedIntegrationId(capabilityIntegrationId)) {\n const cached = await this.readCachedToken(capabilityIntegrationId, loggedInUserId);\n if (cached) {\n return cached;\n }\n }\n\n if (!hasPersistedIntegrationId(capabilityIntegrationId)) {\n return this.mintToken(undefined, opts, loggedInUserId);\n }\n\n return this.mintWithDistributedLock(capabilityIntegrationId, opts, loggedInUserId, shouldForceRefresh);\n }\n\n async storeToken(capabilityIntegrationId: bigint, token: IOauthAccessToken, loggedInUserId: bigint = SYSTEM_USER_ID): Promise<void> {\n await this.persistToken(capabilityIntegrationId, token, loggedInUserId);\n this.writeMemory(capabilityIntegrationId, token);\n await this.tokenCache.set(capabilityIntegrationId, token);\n }\n\n async invalidate(capabilityIntegrationId: bigint): Promise<void> {\n this.sessions.delete(capabilityIntegrationId.toString());\n await this.tokenCache.del(capabilityIntegrationId);\n }\n\n private async mintWithDistributedLock(\n capabilityIntegrationId: bigint,\n opts: IGetValidAccessTokenOptions,\n loggedInUserId: bigint,\n shouldForceRefresh: boolean,\n ): Promise<IOauthAccessToken> {\n const lockKey = getOauthTokenLockKey(capabilityIntegrationId);\n const deadline = Date.now() + OAUTH_LOCK_MAX_WAIT_MS;\n\n while (Date.now() < deadline) {\n if (!shouldForceRefresh) {\n const cached = await this.readCachedToken(capabilityIntegrationId, loggedInUserId);\n if (cached) {\n return cached;\n }\n }\n\n const ownerId = randomUUID();\n const isAcquired = await this.redisCacheStoreService.setIfAbsent(lockKey, ownerId, OAUTH_LOCK_TTL_SECONDS);\n\n if (isAcquired) {\n this.logger.info(loggedInUserId, this.mintWithDistributedLock.name, this.fileName, 'OAuth token lock acquired', {\n capabilityIntegrationId: capabilityIntegrationId.toString(),\n });\n\n try {\n if (!shouldForceRefresh) {\n const cached = await this.readCachedToken(capabilityIntegrationId, loggedInUserId);\n if (cached) {\n return cached;\n }\n }\n\n return await this.mintToken(capabilityIntegrationId, opts, loggedInUserId);\n } finally {\n await this.releaseLockIfOwner(lockKey, ownerId);\n }\n }\n\n const existingLock = await this.redisCacheStoreService.get<string>(lockKey);\n if (existingLock == null) {\n this.logger.warn(loggedInUserId, this.mintWithDistributedLock.name, this.fileName, 'OAuth token lock unavailable; minting without lock', {\n capabilityIntegrationId: capabilityIntegrationId.toString(),\n });\n\n if (!shouldForceRefresh) {\n const cached = await this.readCachedToken(capabilityIntegrationId, loggedInUserId);\n if (cached) {\n return cached;\n }\n }\n\n return this.mintToken(capabilityIntegrationId, opts, loggedInUserId);\n }\n\n this.logger.info(loggedInUserId, this.mintWithDistributedLock.name, this.fileName, 'OAuth token lock contention; waiting', {\n capabilityIntegrationId: capabilityIntegrationId.toString(),\n });\n\n await delay(OAUTH_LOCK_WAIT_MS);\n }\n\n this.logger.warn(loggedInUserId, this.mintWithDistributedLock.name, this.fileName, 'OAuth token lock wait timed out; minting without lock', {\n capabilityIntegrationId: capabilityIntegrationId.toString(),\n });\n\n if (!shouldForceRefresh) {\n const cached = await this.readCachedToken(capabilityIntegrationId, loggedInUserId);\n if (cached) {\n return cached;\n }\n }\n\n return this.mintToken(capabilityIntegrationId, opts, loggedInUserId);\n }\n\n private async releaseLockIfOwner(lockKey: string, ownerId: string): Promise<void> {\n const current = await this.redisCacheStoreService.get<string>(lockKey);\n if (current === ownerId) {\n await this.redisCacheStoreService.del(lockKey);\n }\n }\n\n private async readCachedToken(capabilityIntegrationId: bigint, loggedInUserId: bigint): Promise<IOauthAccessToken | undefined> {\n const memory = this.sessions.get(capabilityIntegrationId.toString());\n if (memory && isTokenFresh(memory.tokenExpiry)) {\n return {\n accessToken: memory.token,\n tokenType: memory.tokenType,\n expiresAt: memory.tokenExpiry,\n refreshToken: memory.refreshToken,\n };\n }\n\n const redisToken = await this.tokenCache.get(capabilityIntegrationId);\n if (redisToken && isTokenFresh(redisToken.expiresAt)) {\n this.writeMemory(capabilityIntegrationId, redisToken);\n return redisToken;\n }\n\n const row = await this.tokenDao.findByCapabilityIntegrationId(capabilityIntegrationId, loggedInUserId);\n if (!row || !isTokenFresh(row.expiresAt)) {\n return undefined;\n }\n\n const accessToken = await this.decryptToken(row.accessToken);\n const refreshToken = row.refreshToken ? await this.decryptToken(row.refreshToken) : undefined;\n const token: IOauthAccessToken = {\n accessToken,\n tokenType: (row.tokenMetadata?.tokenType as string | undefined) ?? 'Bearer',\n expiresAt: row.expiresAt,\n refreshToken,\n metadata: row.tokenMetadata ?? undefined,\n };\n\n this.writeMemory(capabilityIntegrationId, token);\n await this.tokenCache.set(capabilityIntegrationId, token);\n return token;\n }\n\n private async mintToken(\n capabilityIntegrationId: bigint | undefined,\n opts: IGetValidAccessTokenOptions,\n loggedInUserId: bigint,\n ): Promise<IOauthAccessToken> {\n if (!opts.credentials) {\n throw new Error('OAuth mint credentials are required when no valid cached token exists');\n }\n\n const { tokenUrl, scope, grantType } = await this.resolveMintContext(opts.credentials, opts, loggedInUserId);\n const handler = this.grantHandlerRegistry.get(grantType);\n\n this.logger.info(loggedInUserId, this.mintToken.name, this.fileName, 'Minting OAuth token', {\n capabilityIntegrationId: capabilityIntegrationId?.toString(),\n grantType,\n });\n\n try {\n const minted = await handler.mint({\n credentials: opts.credentials,\n tokenUrl,\n scope,\n integration: {\n id: capabilityIntegrationId,\n capabilityId: opts.capabilityId,\n providerId: opts.providerId,\n },\n loggedInUserId,\n });\n\n if (!minted.accessToken) {\n throw new Error('OAuth mint returned an empty access token');\n }\n\n if (hasPersistedIntegrationId(capabilityIntegrationId)) {\n await this.storeToken(capabilityIntegrationId, minted, loggedInUserId);\n }\n\n return minted;\n } catch (error) {\n this.logger.error(loggedInUserId, this.mintToken.name, this.fileName, 'OAuth token mint failed', error as Error);\n throw error;\n }\n }\n\n private async resolveMintContext(\n credentials: IOauthMintCredentials,\n opts: IGetValidAccessTokenOptions,\n loggedInUserId: bigint,\n ): Promise<{ tokenUrl: string; scope?: string; grantType: OauthGrantType }> {\n let tokenUrl = credentials.tokenUrl;\n let supportedGrantTypes: OauthGrantType[] | undefined;\n let defaultScopes: string[] | undefined;\n\n if (opts.capabilityId != null && opts.providerId != null) {\n const provider = await this.providerDao.findByCapabilityAndProvider(opts.capabilityId, opts.providerId, loggedInUserId);\n if (provider) {\n tokenUrl = substituteUrlPlaceholders(provider.tokenUrl, credentials.urlParams);\n supportedGrantTypes = provider.supportedGrantTypes as OauthGrantType[];\n defaultScopes = provider.defaultScopes;\n }\n }\n\n tokenUrl = substituteUrlPlaceholders(tokenUrl, credentials.urlParams);\n\n const scope = credentials.scope ?? (defaultScopes?.length ? defaultScopes.join(' ') : undefined);\n const grantType = this.grantHandlerRegistry.resolvePreferredGrant(supportedGrantTypes);\n\n return { tokenUrl, scope, grantType };\n }\n\n private async persistToken(capabilityIntegrationId: bigint, token: IOauthAccessToken, loggedInUserId: bigint): Promise<void> {\n const encryptedAccessToken = await this.encryptToken(token.accessToken);\n const encryptedRefreshToken = token.refreshToken ? await this.encryptToken(token.refreshToken) : undefined;\n\n await this.tokenDao.upsert({\n capabilityIntegrationId,\n accessToken: encryptedAccessToken,\n refreshToken: encryptedRefreshToken,\n expiresAt: token.expiresAt,\n tokenMetadata: {\n ...(token.metadata ?? {}),\n tokenType: token.tokenType,\n },\n loggedInUserId,\n });\n }\n\n private writeMemory(capabilityIntegrationId: bigint, token: IOauthAccessToken): void {\n this.sessions.set(capabilityIntegrationId.toString(), {\n token: token.accessToken,\n tokenType: token.tokenType,\n tokenExpiry: token.expiresAt,\n refreshToken: token.refreshToken,\n });\n }\n\n private async encryptToken(value: string): Promise<string> {\n const keyId = getIntegrationConfigKmsKeyId();\n if (!this.secretProvider || !keyId) {\n throw new Error('OAuth token persist requires SECRET_PROVIDER and INTEGRATION_CONFIG_KMS_KEY_ID');\n }\n\n return this.secretProvider.encrypt(value, keyId);\n }\n\n private async decryptToken(value: string): Promise<string> {\n const keyId = getIntegrationConfigKmsKeyId();\n if (!this.secretProvider || !keyId) {\n throw new Error('OAuth token decrypt requires SECRET_PROVIDER and INTEGRATION_CONFIG_KMS_KEY_ID');\n }\n\n return this.secretProvider.decrypt(value, keyId);\n }\n}\n","import { SYSTEM_USER_ID } from '@dv4resi/dvss-backend-module-utility';\nimport type { ICapabilityIntegration } from '@dvss/dvss-integration-libs';\nimport { Injectable } from '@nestjs/common';\n\nimport type { AuthProvider } from './auth-provider';\nimport type { IGetValidAccessTokenOptions, IOauthAccessToken, IOauthMintCredentials } from './models/oauth.model';\nimport { OauthTokenManager } from './token-manager/oauth-token-manager';\n\n@Injectable()\nexport class OAuth2Provider implements AuthProvider {\n constructor(private readonly tokenManager: OauthTokenManager) {}\n\n async getValidAccessToken(capabilityIntegrationId: bigint | undefined, opts: IGetValidAccessTokenOptions = {}): Promise<IOauthAccessToken> {\n return this.tokenManager.getValidAccessToken(capabilityIntegrationId, opts);\n }\n\n async getAuthenticationHeaders(capabilityIntegrationId: bigint, opts: IGetValidAccessTokenOptions = {}): Promise<Record<string, string>> {\n const token = await this.getValidAccessToken(capabilityIntegrationId, opts);\n return {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Authorization: `${token.tokenType} ${token.accessToken}`,\n };\n }\n\n async testIntegration(integration: ICapabilityIntegration, loggedInUserId: bigint, credentials: IOauthMintCredentials): Promise<boolean> {\n const token = await this.getValidAccessToken(integration.id, {\n forceRefresh: true,\n loggedInUserId,\n credentials,\n capabilityId: integration.capabilityId,\n providerId: integration.providerId,\n });\n\n if (!token.accessToken) {\n throw new Error('OAuth integration test failed: empty access token');\n }\n\n return true;\n }\n\n async storeToken(capabilityIntegrationId: bigint, token: IOauthAccessToken, loggedInUserId?: bigint): Promise<void> {\n await this.tokenManager.storeToken(capabilityIntegrationId, token, loggedInUserId ?? SYSTEM_USER_ID);\n }\n\n async invalidate(capabilityIntegrationId: bigint): Promise<void> {\n await this.tokenManager.invalidate(capabilityIntegrationId);\n }\n}\n","import { DatastoreModule } from '@dv4resi/dvss-backend-module-datastore';\nimport { LoggerModule } from '@dv4resi/dvss-backend-module-utility';\nimport { IntegrationLibsModule } from '@dvss/dvss-integration-libs';\nimport { Module } from '@nestjs/common';\n\nimport { OauthTokenCache } from './cache/oauth-token-cache';\nimport { AuthorizationCodeGrantHandler } from './grants/authorization-code.handler';\nimport { ClientCredentialsGrantHandler } from './grants/client-credentials.handler';\nimport { GrantHandlerRegistry } from './grants/grant-handler.registry';\nimport { OAuth2Provider } from './oauth2.provider';\nimport { OauthProviderDao } from './store/oauth-provider.dao';\nimport { OauthTokenDao } from './store/oauth-token.dao';\nimport { OauthTokenManager } from './token-manager/oauth-token-manager';\n\n@Module({\n imports: [IntegrationLibsModule, LoggerModule, DatastoreModule],\n providers: [\n OauthTokenDao,\n OauthProviderDao,\n OauthTokenCache,\n ClientCredentialsGrantHandler,\n AuthorizationCodeGrantHandler,\n GrantHandlerRegistry,\n OauthTokenManager,\n OAuth2Provider,\n ],\n exports: [OAuth2Provider, OauthTokenManager],\n})\nexport class IntegrationOauthModule {}\n","/**\n * Graph API path fragments used by Microsoft calendar capabilities.\n *\n * `mailboxEmail` is whichever mailbox the operation targets — the organizing user for\n * user-organized bookings, or the room itself for the legacy room-organizes flow. Graph\n * derives the event organizer from this mailbox, and event ids are scoped to it.\n */\nexport const MICROSOFT_GRAPH_PATHS = {\n rooms: '/places/microsoft.graph.room',\n userCalendarEvents: (mailboxEmail: string): string => `/users/${encodeURIComponent(mailboxEmail)}/calendar/events`,\n userCalendarEvent: (mailboxEmail: string, eventId: string): string =>\n `/users/${encodeURIComponent(mailboxEmail)}/calendar/events/${encodeURIComponent(eventId)}`,\n userCalendarView: (mailboxEmail: string, startDateTime: string, endDateTime: string): string =>\n `/users/${encodeURIComponent(mailboxEmail)}/calendarView?startDateTime=${encodeURIComponent(startDateTime)}&endDateTime=${encodeURIComponent(endDateTime)}`,\n subscriptions: '/subscriptions',\n subscription: (subscriptionId: string): string => `/subscriptions/${encodeURIComponent(subscriptionId)}`,\n} as const;\n\nexport const MICROSOFT_DEFAULT_GRAPH_BASE_URL = 'https://graph.microsoft.com/v1.0';\n\n/** Token endpoint template — runtime replaces `{tenantId}` (see auth.service). */\nexport const MICROSOFT_DEFAULT_AUTH_URL = 'https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token';\n","import { MICROSOFT_DEFAULT_AUTH_URL, MICROSOFT_DEFAULT_GRAPH_BASE_URL } from '../common/microsoft.constant';\nimport type { IMicrosoftConfig, IMicrosoftIntegrationConfig } from '../models';\n\nexport type MicrosoftIntegrationConfigInput = Pick<IMicrosoftIntegrationConfig, 'tenantId' | 'clientId' | 'clientSecret'>;\n\n/**\n * Build a full Microsoft integration config with platform URL defaults.\n * Persists authUrl with the real tenantId substituted (not a template placeholder).\n */\nexport function buildMicrosoftIntegrationConfig(integrationConfig: MicrosoftIntegrationConfigInput, existing?: Partial<IMicrosoftConfig>): IMicrosoftConfig {\n const existingBaseUrl = existing?.platformConfig?.baseUrl.trim();\n\n return {\n platformConfig: {\n authUrl: MICROSOFT_DEFAULT_AUTH_URL.replace('{tenantId}', integrationConfig.tenantId),\n baseUrl: existingBaseUrl || MICROSOFT_DEFAULT_GRAPH_BASE_URL,\n },\n integrationConfig: {\n tenantId: integrationConfig.tenantId,\n clientId: integrationConfig.clientId,\n clientSecret: integrationConfig.clientSecret,\n },\n };\n}\n","export const MICROSOFT_SECURE_STORAGE = 'MICROSOFT_INTEGRATION_CONFIG_SECURE_STORAGE';\n\nexport function getMicrosoftKmsKeyId(): string {\n return process.env.INTEGRATION_CONFIG_KMS_KEY_ID || '';\n}\n\nexport function looksLikeStoredSecureConfig(config: Record<string, unknown>): boolean {\n const integrationConfig = config.integrationConfig;\n\n if (typeof integrationConfig !== 'object' || integrationConfig === null || Array.isArray(integrationConfig)) {\n return false;\n }\n\n return Object.values(integrationConfig as Record<string, unknown>).some((value) => typeof value === 'object' && value !== null && 'isSensitive' in value);\n}\n","export const MICROSOFT_CLIENT_CREDENTIALS_GRANT_TYPE = 'client_credentials';\n\nexport const MICROSOFT_DEFAULT_GRAPH_SCOPE = 'https://graph.microsoft.com/.default';\n\nexport const MICROSOFT_DEFAULT_ACCESS_TOKEN_TYPE = 'Bearer';\n\nexport const MICROSOFT_DEFAULT_HEADERS = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Accept: 'application/json',\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/json',\n};\n\nexport const MICROSOFT_TOKEN_HEADERS = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Accept: 'application/json',\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/x-www-form-urlencoded',\n};\n","import { LoggerService, SYSTEM_USER_ID } from '@dv4resi/dvss-backend-module-utility';\nimport {\n BaseAuth,\n type ICapabilityIntegration,\n type IValidatedCapabilityIntegration,\n type IntegrationConfigSecureStorageService,\n} from '@dvss/dvss-integration-libs';\nimport { OAuth2Provider, type IOauthAccessToken, type IOauthMintCredentials, secondsUntil } from '@dvss/dvss-integration-oauth';\nimport { Inject, Injectable, Optional } from '@nestjs/common';\n\nimport { buildMicrosoftIntegrationConfig } from '../../common/build-microsoft-integration-config';\nimport { getMicrosoftKmsKeyId, looksLikeStoredSecureConfig, MICROSOFT_SECURE_STORAGE } from '../../common/microsoft-secure-storage';\nimport { MICROSOFT_DEFAULT_ACCESS_TOKEN_TYPE, MICROSOFT_DEFAULT_GRAPH_SCOPE } from '../../enum';\nimport type { IMicrosoftAccessToken, IMicrosoftConfig } from '../../models';\n\nfunction requireNonEmpty(value: unknown, fieldName: string): asserts value is string {\n if (value == null || (typeof value === 'string' && value.trim() === '')) {\n throw new Error(`Microsoft integration configuration: ${fieldName} is required`);\n }\n}\n\nfunction requireObject(value: unknown, fieldName: string): asserts value is Record<string, unknown> {\n if (value == null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`Microsoft integration configuration: ${fieldName} is required`);\n }\n}\n\n@Injectable()\nexport class MicrosoftAuthService implements BaseAuth {\n private readonly fileName = 'auth.service';\n\n constructor(\n private readonly logger: LoggerService,\n private readonly oauth2Provider: OAuth2Provider,\n @Optional() @Inject(MICROSOFT_SECURE_STORAGE) private readonly secureStorage?: IntegrationConfigSecureStorageService,\n ) {}\n\n /**\n * Validates Azure AD / Graph integration configuration.\n * Authorization headers are resolved on demand via OAuth2Provider (not from config.accessDetails).\n */\n validateConfig(integration: ICapabilityIntegration, loggedInUserId: bigint): IValidatedCapabilityIntegration {\n const config = this.parseAndValidateConfig(integration, loggedInUserId);\n\n return {\n ...integration,\n id: integration.id as bigint,\n config: config as unknown as IValidatedCapabilityIntegration['config'],\n headers: {},\n } as IValidatedCapabilityIntegration;\n }\n\n /**\n * Typed config validation used by API client and other capabilities.\n * Applies platform URL defaults when platformConfig is missing/incomplete.\n */\n parseAndValidateConfig(integration: ICapabilityIntegration | Omit<ICapabilityIntegration, 'id'>, loggedInUserId?: bigint): IMicrosoftConfig {\n this.logger.info(loggedInUserId ?? SYSTEM_USER_ID, this.parseAndValidateConfig.name, this.fileName, 'Validating Microsoft integration config');\n\n const raw = integration.config as Partial<IMicrosoftConfig> | undefined;\n\n if (!raw) {\n throw new Error('Microsoft integration config is required');\n }\n\n const integrationConfig = raw.integrationConfig;\n requireObject(integrationConfig, 'integrationConfig');\n requireNonEmpty(integrationConfig.tenantId, 'integrationConfig.tenantId');\n requireNonEmpty(integrationConfig.clientId, 'integrationConfig.clientId');\n requireNonEmpty(integrationConfig.clientSecret, 'integrationConfig.clientSecret');\n\n const config = buildMicrosoftIntegrationConfig(\n {\n tenantId: integrationConfig.tenantId,\n clientId: integrationConfig.clientId,\n clientSecret: integrationConfig.clientSecret,\n },\n raw,\n );\n\n requireNonEmpty(config.platformConfig.authUrl, 'platformConfig.authUrl');\n requireNonEmpty(config.platformConfig.baseUrl, 'platformConfig.baseUrl');\n\n return config;\n }\n\n /**\n * Decrypts stored secure-storage envelopes when present, then validates.\n * Does not mutate the caller's `integration.config`.\n */\n async resolvePlaintextConfig(integration: ICapabilityIntegration | Omit<ICapabilityIntegration, 'id'>, loggedInUserId?: bigint): Promise<IMicrosoftConfig> {\n const stored = (integration.config ?? {}) as Record<string, unknown>;\n const effectiveLoggedInUserId = loggedInUserId ?? SYSTEM_USER_ID;\n let configForParse: Record<string, unknown> = stored;\n\n if (looksLikeStoredSecureConfig(stored)) {\n if (!this.secureStorage) {\n throw new Error('Microsoft integration configuration: secure storage is required to decrypt stored credentials');\n }\n\n configForParse = (await this.secureStorage.prepareForBackend(stored, getMicrosoftKmsKeyId(), effectiveLoggedInUserId)) as Record<string, unknown>;\n }\n\n return this.parseAndValidateConfig(\n {\n ...integration,\n config: configForParse,\n },\n loggedInUserId,\n );\n }\n\n async getAccessToken(\n integration: ICapabilityIntegration | Omit<ICapabilityIntegration, 'id'>,\n loggedInUserId?: bigint,\n forceRefresh: boolean = false,\n ): Promise<IMicrosoftAccessToken> {\n const config = await this.resolvePlaintextConfig(integration, loggedInUserId);\n const token = await this.oauth2Provider.getValidAccessToken('id' in integration ? integration.id : undefined, {\n forceRefresh,\n loggedInUserId: loggedInUserId ?? SYSTEM_USER_ID,\n credentials: this.toMintCredentials(config),\n capabilityId: integration.capabilityId,\n providerId: integration.providerId,\n });\n\n return this.toMicrosoftAccessToken(token);\n }\n\n /**\n * Persists a previously minted token after capability_integration insert.\n */\n async persistMintedAccessToken(capabilityIntegrationId: bigint, token: IMicrosoftAccessToken, loggedInUserId: bigint): Promise<void> {\n if (token.expiresIn <= 0) {\n return;\n }\n\n await this.oauth2Provider.storeToken(\n capabilityIntegrationId,\n {\n accessToken: token.accessToken,\n tokenType: token.tokenType || MICROSOFT_DEFAULT_ACCESS_TOKEN_TYPE,\n expiresAt: new Date(Date.now() + token.expiresIn * 1000),\n },\n loggedInUserId,\n );\n }\n\n /**\n * BaseAuth contract — returns the access token string.\n */\n async fetchAccessToken(integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<string> {\n const token = await this.getAccessToken(integration, loggedInUserId);\n return token.accessToken;\n }\n\n /**\n * Tests connectivity by obtaining a client-credentials access token.\n */\n async testIntegration(integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<boolean> {\n this.logger.info(loggedInUserId, this.testIntegration.name, this.fileName, 'Testing Microsoft Graph integration');\n\n const config = await this.resolvePlaintextConfig(integration, loggedInUserId);\n const isSuccessful = await this.oauth2Provider.testIntegration(integration, loggedInUserId, this.toMintCredentials(config));\n\n this.logger.info(loggedInUserId, this.testIntegration.name, this.fileName, 'Microsoft Graph integration test successful');\n return isSuccessful;\n }\n\n toMintCredentials(config: IMicrosoftConfig): IOauthMintCredentials {\n return {\n tokenUrl: config.platformConfig.authUrl,\n clientId: config.integrationConfig.clientId,\n clientSecret: config.integrationConfig.clientSecret,\n scope: MICROSOFT_DEFAULT_GRAPH_SCOPE,\n urlParams: { tenantId: config.integrationConfig.tenantId },\n };\n }\n\n private toMicrosoftAccessToken(token: IOauthAccessToken): IMicrosoftAccessToken {\n return {\n accessToken: token.accessToken,\n tokenType: token.tokenType || MICROSOFT_DEFAULT_ACCESS_TOKEN_TYPE,\n expiresIn: secondsUntil(token.expiresAt),\n };\n }\n}\n","import { LoggerService, SYSTEM_USER_ID } from '@dv4resi/dvss-backend-module-utility';\nimport { HTTP_METHOD, type ICapabilityIntegration, type IValidatedCapabilityIntegration, TrafficGatewayService } from '@dvss/dvss-integration-libs';\nimport { OAuth2Provider } from '@dvss/dvss-integration-oauth';\nimport { Injectable } from '@nestjs/common';\n\nimport { MicrosoftAuthService } from '../capabilities/auth/auth.service';\nimport { MICROSOFT_DEFAULT_HEADERS } from '../enum';\n\nexport interface IMicrosoftApiCallRequest<TBody = unknown> {\n apiMethod: HTTP_METHOD;\n url: string;\n body?: TBody;\n headers?: Record<string, string>;\n responseType?: 'json' | 'text' | 'blob' | 'arraybuffer';\n}\n\n@Injectable()\nexport class MicrosoftApiClientService {\n private readonly fileName = 'microsoft-api-client.service';\n\n private readonly maxAuthRetryCount = 2;\n\n constructor(\n private readonly logger: LoggerService,\n private readonly authService: MicrosoftAuthService,\n private readonly oauth2Provider: OAuth2Provider,\n private readonly trafficGatewayService: TrafficGatewayService,\n ) {}\n\n async apiCall<TResponse = unknown, TBody = unknown>(\n request: IMicrosoftApiCallRequest<TBody>,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint = SYSTEM_USER_ID,\n ): Promise<TResponse> {\n return this.executeWithRetry(request, integration, loggedInUserId, 0);\n }\n\n private async executeWithRetry<TResponse = unknown, TBody = unknown>(\n request: IMicrosoftApiCallRequest<TBody>,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n retryCount: number,\n ): Promise<TResponse> {\n const config = await this.authService.resolvePlaintextConfig(integration, loggedInUserId);\n const authHeaders = await this.oauth2Provider.getAuthenticationHeaders(integration.id as bigint, {\n forceRefresh: retryCount > 0,\n loggedInUserId,\n credentials: this.authService.toMintCredentials(config),\n capabilityId: integration.capabilityId,\n providerId: integration.providerId,\n });\n const headers = {\n ...MICROSOFT_DEFAULT_HEADERS,\n ...(request.headers ?? {}),\n ...authHeaders,\n };\n\n const validatedIntegration = {\n ...integration,\n headers,\n } as IValidatedCapabilityIntegration;\n\n this.logger.info(loggedInUserId, this.apiCall.name, this.fileName, 'Microsoft Graph API call', {\n method: request.apiMethod,\n url: request.url,\n hasBody: request.body != null,\n });\n\n try {\n return await this.trafficGatewayService.executeIntegrationRequest<TResponse, TBody>(\n {\n apiMethod: request.apiMethod,\n baseUrl: config.platformConfig.baseUrl,\n url: request.url,\n body: request.body,\n headers,\n responseType: request.responseType,\n },\n validatedIntegration,\n loggedInUserId,\n );\n } catch (error) {\n if (!this.isUnauthorizedError(error) || retryCount >= this.maxAuthRetryCount) {\n throw error;\n }\n\n if (integration.id != null) {\n await this.oauth2Provider.invalidate(integration.id);\n }\n\n this.logger.info(loggedInUserId, this.executeWithRetry.name, this.fileName, 'Retrying Microsoft Graph API call after unauthorized response', {\n retryCount: retryCount + 1,\n url: request.url,\n });\n\n return this.executeWithRetry(request, integration, loggedInUserId, retryCount + 1);\n }\n }\n\n private isUnauthorizedError(error: unknown): boolean {\n const errorObject = error as {\n response?: {\n status?: number;\n };\n status?: number;\n };\n\n return errorObject.response?.status === 401 || errorObject.status === 401;\n }\n}\n","import type { IEvent, IEventSyncMetadata, IRecurrence } from '@dvss/dvss-integration-libs';\n\nimport type { IMicrosoftGraphAttendee, IMicrosoftGraphEvent, IMicrosoftGraphRecurrence } from '../../models';\n\nconst GRAPH_EVENT_KNOWN_KEYS = new Set(['id', 'subject', 'body', 'start', 'end', 'location', 'showAs', 'isCancelled', 'recurrence', 'attendees', 'organizer']);\n\n/** Graph attendee type that books a room/equipment mailbox rather than inviting a person. */\nconst GRAPH_RESOURCE_ATTENDEE_TYPE = 'resource';\n\n/**\n * Maps a system (libs) calendar event to a Microsoft Graph event body.\n * Undefined fields are omitted so PATCH payloads stay partial.\n *\n * `options.resourceId` books a room from a different mailbox: the room is appended as\n * a `resource` attendee so it still receives the invite while the mailbox owner organizes.\n * Omit it when posting into the room's own calendar — the room is already the organizer.\n */\nexport function toGraphEvent(event: IEvent | Partial<IEvent>, options?: { resourceId?: string }): IMicrosoftGraphEvent {\n const graph: IMicrosoftGraphEvent = {};\n\n if (event.subject !== undefined) {\n graph.subject = event.subject;\n }\n if (event.body !== undefined) {\n graph.body = { contentType: 'text', content: event.body };\n }\n if (event.start !== undefined) {\n graph.start = { dateTime: event.start.dateTime, timeZone: event.start.timeZone };\n }\n if (event.end !== undefined) {\n graph.end = { dateTime: event.end.dateTime, timeZone: event.end.timeZone };\n }\n if (event.location !== undefined) {\n graph.location = { displayName: event.location };\n }\n if (event.showAs !== undefined) {\n graph.showAs = event.showAs;\n }\n if (event.isCancelled !== undefined) {\n graph.isCancelled = event.isCancelled;\n }\n if (event.recurrence !== undefined) {\n graph.recurrence = toGraphRecurrence(event.recurrence);\n }\n if (event.attendees !== undefined) {\n graph.attendees = event.attendees.map((attendee) => {\n const mapped: IMicrosoftGraphAttendee = {\n emailAddress: omitUndefined({ address: attendee.email, name: attendee.name }),\n };\n if (attendee.type !== undefined) {\n mapped.type = attendee.type;\n }\n return mapped;\n });\n }\n\n const resourceId = options?.resourceId?.trim();\n if (resourceId) {\n const isAlreadyInvited = graph.attendees?.some((attendee) => attendee.emailAddress?.address?.toLowerCase() === resourceId.toLowerCase());\n if (isAlreadyInvited !== true) {\n graph.attendees = [...(graph.attendees ?? []), { emailAddress: { address: resourceId }, type: GRAPH_RESOURCE_ATTENDEE_TYPE }];\n }\n }\n\n // `organizer` is deliberately not written: Graph derives the organizer from the\n // mailbox in the request URL and silently ignores it on POST/PATCH.\n\n return graph;\n}\n\nexport function toGraphRecurrence(recurrence: IRecurrence): IMicrosoftGraphRecurrence {\n return {\n pattern: omitUndefined({\n type: recurrence.pattern.type,\n interval: recurrence.pattern.interval,\n daysOfWeek: recurrence.pattern.daysOfWeek,\n firstDayOfWeek: recurrence.pattern.firstDayOfWeek,\n dayOfMonth: recurrence.pattern.dayOfMonth,\n month: recurrence.pattern.month,\n index: recurrence.pattern.index,\n }),\n range: omitUndefined({\n type: recurrence.range.type,\n startDate: recurrence.range.startDate,\n endDate: recurrence.range.endDate,\n numberOfOccurrences: recurrence.range.numberOfOccurrences,\n recurrenceTimeZone: recurrence.range.recurrenceTimeZone,\n }),\n };\n}\n\n/**\n * Maps a Microsoft Graph event to the provider-agnostic libs calendar event.\n */\nexport function fromGraphEvent(\n graph: IMicrosoftGraphEvent,\n options?: { resourceId?: string; organizerUserEmail?: string; syncMetadata?: IEventSyncMetadata },\n): IEvent {\n const providerPayload = collectUnknownGraphFields(graph);\n\n return {\n id: graph.id,\n subject: graph.subject ?? '',\n body: graph.body?.content,\n start: graph.start ?? { dateTime: '', timeZone: '' },\n end: graph.end ?? { dateTime: '', timeZone: '' },\n location: graph.location?.displayName,\n resourceId: options?.resourceId,\n recurrence: graph.recurrence ? fromGraphRecurrence(graph.recurrence) : undefined,\n attendees: graph.attendees\n ?.filter((attendee) => Boolean(attendee.emailAddress?.address))\n .map((attendee) => ({\n email: attendee.emailAddress?.address ?? '',\n name: attendee.emailAddress?.name,\n type: attendee.type,\n })),\n organizerEmail: graph.organizer?.emailAddress?.address,\n showAs: graph.showAs,\n isCancelled: graph.isCancelled,\n syncMetadata: omitUndefined({\n ...options?.syncMetadata,\n externalEventId: graph.id ?? options?.syncMetadata?.externalEventId,\n // Event ids are mailbox-scoped — remember which mailbox can address this id.\n // Left undefined when the room organizes; `resourceId` addresses the event then.\n organizerUserEmail: options?.organizerUserEmail ?? options?.syncMetadata?.organizerUserEmail,\n resourceId: options?.resourceId ?? options?.syncMetadata?.resourceId,\n }),\n providerPayload,\n };\n}\n\nexport function fromGraphRecurrence(recurrence: IMicrosoftGraphRecurrence): IRecurrence {\n return {\n pattern: omitUndefined({\n type: recurrence.pattern?.type ?? '',\n interval: recurrence.pattern?.interval ?? 1,\n daysOfWeek: recurrence.pattern?.daysOfWeek,\n firstDayOfWeek: recurrence.pattern?.firstDayOfWeek,\n dayOfMonth: recurrence.pattern?.dayOfMonth,\n month: recurrence.pattern?.month,\n index: recurrence.pattern?.index,\n }),\n range: omitUndefined({\n type: recurrence.range?.type ?? '',\n startDate: recurrence.range?.startDate ?? '',\n endDate: recurrence.range?.endDate,\n numberOfOccurrences: recurrence.range?.numberOfOccurrences,\n recurrenceTimeZone: recurrence.range?.recurrenceTimeZone,\n }),\n };\n}\n\nfunction omitUndefined<T extends Record<string, unknown>>(value: T): T {\n return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined)) as T;\n}\n\nfunction collectUnknownGraphFields(graph: IMicrosoftGraphEvent): Record<string, unknown> | undefined {\n const extras: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(graph as Record<string, unknown>)) {\n if (!GRAPH_EVENT_KNOWN_KEYS.has(key) && value !== undefined) {\n extras[key] = value;\n }\n }\n return Object.keys(extras).length > 0 ? extras : undefined;\n}\n","import { CustomException, LoggerService } from '@dv4resi/dvss-backend-module-utility';\nimport {\n BaseCalendarBookingManagement,\n HTTP_METHOD,\n type ICancelEventRequest,\n type ICapabilityIntegration,\n type ICreateEventRequest,\n type IDeleteEventRequest,\n type IEvent,\n type IGetEventRequest,\n type IGetEventsRequest,\n type IGetEventsResponse,\n type ISyncEventsRequest,\n type ISyncEventsResponse,\n type IUpdateEventRequest,\n} from '@dvss/dvss-integration-libs';\nimport { Injectable, NotImplementedException } from '@nestjs/common';\n\nimport { MicrosoftApiClientService } from '../../adapter/microsoft-api-client.service';\nimport { MICROSOFT_GRAPH_PATHS } from '../../common';\nimport type { IMicrosoftGraphEvent, IMicrosoftGraphEventsResponse } from '../../models';\nimport { fromGraphEvent, toGraphEvent } from './booking-management.mapper';\n\n/**\n * Microsoft Graph calendar event lifecycle.\n * Endpoints:\n * - POST|PATCH|DELETE /users/{mailboxEmail}/calendar/events[/{eventId}]\n * - GET /users/{mailboxEmail}/calendarView (time-windowed list)\n * - Delta / sync via Graph delta queries (syncEvents) — SEN2-27430\n *\n * The mailbox in the URL owns the event: Graph makes its owner the organizer and ignores\n * any `organizer` in the body. Pass `organizerUserEmail` (the booked-for user) to have the\n * user organize and the room attend as a resource; omit it and the room organizes, as before.\n *\n * `organizerUserEmail` and `resourceId` are kept distinct end to end: the local\n * `mailboxEmail` below is the resolved target of the call and may be either of them, but\n * only a genuine user mailbox is ever recorded as `organizerUserEmail` in sync metadata.\n */\n@Injectable()\nexport class MicrosoftCalendarBookingService extends BaseCalendarBookingManagement {\n private readonly fileName = 'booking-management.service';\n\n constructor(\n private readonly logger: LoggerService,\n private readonly microsoftApiClient: MicrosoftApiClientService,\n ) {\n super();\n }\n\n override async createEvent(request: ICreateEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IEvent> {\n try {\n const mailboxEmail = this.resolveMailboxEmail(request);\n this.logger.info(loggedInUserId, this.createEvent.name, this.fileName, 'Create Microsoft Graph calendar event', {\n mailboxEmail,\n resourceId: request.resourceId,\n subject: request.event.subject,\n path: MICROSOFT_GRAPH_PATHS.userCalendarEvents(mailboxEmail),\n });\n this.assertResourceId(request.resourceId);\n\n const graphEvent = await this.microsoftApiClient.apiCall<IMicrosoftGraphEvent>(\n {\n apiMethod: HTTP_METHOD.POST,\n url: MICROSOFT_GRAPH_PATHS.userCalendarEvents(mailboxEmail),\n body: toGraphEvent(request.event, { resourceId: this.resourceAsAttendee(mailboxEmail, request.resourceId) }),\n },\n integration,\n loggedInUserId,\n );\n const mapped = fromGraphEvent(graphEvent, {\n resourceId: request.resourceId,\n organizerUserEmail: this.organizerUserMailbox(request),\n syncMetadata: request.event.syncMetadata,\n });\n this.logger.info(loggedInUserId, this.createEvent.name, this.fileName, 'Created Microsoft Graph calendar event', {\n eventId: mapped.id,\n mailboxEmail,\n resourceId: request.resourceId,\n });\n return mapped;\n } catch (error) {\n this.logger.error(loggedInUserId, this.createEvent.name, this.fileName, 'Error creating Microsoft Graph calendar event', error);\n throw error;\n }\n }\n\n override async updateEvent(request: IUpdateEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IEvent> {\n try {\n const mailboxEmail = this.resolveMailboxEmail(request);\n this.logger.info(loggedInUserId, this.updateEvent.name, this.fileName, 'Update Microsoft Graph calendar event', {\n mailboxEmail,\n resourceId: request.resourceId,\n eventId: request.eventId,\n path: MICROSOFT_GRAPH_PATHS.userCalendarEvent(mailboxEmail, request.eventId),\n });\n this.assertResourceId(request.resourceId);\n this.assertEventId(request.eventId);\n\n const graphEvent = await this.microsoftApiClient.apiCall<IMicrosoftGraphEvent>(\n {\n apiMethod: HTTP_METHOD.PATCH,\n url: MICROSOFT_GRAPH_PATHS.userCalendarEvent(mailboxEmail, request.eventId),\n body: toGraphEvent(request.event),\n },\n integration,\n loggedInUserId,\n );\n const mapped = fromGraphEvent(graphEvent, {\n resourceId: request.resourceId,\n organizerUserEmail: this.organizerUserMailbox(request),\n syncMetadata: request.event.syncMetadata,\n });\n this.logger.info(loggedInUserId, this.updateEvent.name, this.fileName, 'Updated Microsoft Graph calendar event', {\n eventId: mapped.id,\n mailboxEmail,\n resourceId: request.resourceId,\n });\n return mapped;\n } catch (error) {\n this.logger.error(loggedInUserId, this.updateEvent.name, this.fileName, 'Error updating Microsoft Graph calendar event', error);\n throw error;\n }\n }\n\n override async cancelEvent(request: ICancelEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<void> {\n try {\n const mailboxEmail = this.resolveMailboxEmail(request);\n this.logger.info(loggedInUserId, this.cancelEvent.name, this.fileName, 'Cancel Microsoft Graph calendar event', {\n mailboxEmail,\n resourceId: request.resourceId,\n eventId: request.eventId,\n path: MICROSOFT_GRAPH_PATHS.userCalendarEvent(mailboxEmail, request.eventId),\n });\n await this.deleteGraphEvent(mailboxEmail, request.resourceId, request.eventId, integration, loggedInUserId);\n this.logger.info(loggedInUserId, this.cancelEvent.name, this.fileName, 'Cancelled Microsoft Graph calendar event', {\n eventId: request.eventId,\n mailboxEmail,\n resourceId: request.resourceId,\n });\n } catch (error) {\n this.logger.error(loggedInUserId, this.cancelEvent.name, this.fileName, 'Error cancelling Microsoft Graph calendar event', error);\n throw error;\n }\n }\n\n override async deleteEvent(request: IDeleteEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<void> {\n try {\n const mailboxEmail = this.resolveMailboxEmail(request);\n this.logger.info(loggedInUserId, this.deleteEvent.name, this.fileName, 'Delete Microsoft Graph calendar event', {\n mailboxEmail,\n resourceId: request.resourceId,\n eventId: request.eventId,\n path: MICROSOFT_GRAPH_PATHS.userCalendarEvent(mailboxEmail, request.eventId),\n });\n await this.deleteGraphEvent(mailboxEmail, request.resourceId, request.eventId, integration, loggedInUserId);\n this.logger.info(loggedInUserId, this.deleteEvent.name, this.fileName, 'Deleted Microsoft Graph calendar event', {\n eventId: request.eventId,\n mailboxEmail,\n resourceId: request.resourceId,\n });\n } catch (error) {\n this.logger.error(loggedInUserId, this.deleteEvent.name, this.fileName, 'Error deleting Microsoft Graph calendar event', error);\n throw error;\n }\n }\n\n override async getEvent(request: IGetEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IEvent> {\n try {\n const mailboxEmail = this.resolveMailboxEmail(request);\n this.logger.info(loggedInUserId, this.getEvent.name, this.fileName, 'Get Microsoft Graph calendar event', {\n mailboxEmail,\n resourceId: request.resourceId,\n eventId: request.eventId,\n path: MICROSOFT_GRAPH_PATHS.userCalendarEvent(mailboxEmail, request.eventId),\n });\n this.assertResourceId(request.resourceId);\n this.assertEventId(request.eventId);\n\n const graphEvent = await this.microsoftApiClient.apiCall<IMicrosoftGraphEvent>(\n {\n apiMethod: HTTP_METHOD.GET,\n url: MICROSOFT_GRAPH_PATHS.userCalendarEvent(mailboxEmail, request.eventId),\n },\n integration,\n loggedInUserId,\n );\n const mapped = fromGraphEvent(graphEvent, { resourceId: request.resourceId, organizerUserEmail: this.organizerUserMailbox(request) });\n this.logger.info(loggedInUserId, this.getEvent.name, this.fileName, 'Fetched Microsoft Graph calendar event', {\n eventId: mapped.id,\n mailboxEmail,\n resourceId: request.resourceId,\n });\n return mapped;\n } catch (error) {\n this.logger.error(loggedInUserId, this.getEvent.name, this.fileName, 'Error fetching Microsoft Graph calendar event', error);\n throw error;\n }\n }\n\n override async getEvents(request: IGetEventsRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IGetEventsResponse> {\n try {\n this.assertResourceId(request.resourceId);\n const mailboxEmail = this.resolveMailboxEmail(request);\n const url =\n request.start && request.end\n ? MICROSOFT_GRAPH_PATHS.userCalendarView(mailboxEmail, request.start.dateTime, request.end.dateTime)\n : MICROSOFT_GRAPH_PATHS.userCalendarEvents(mailboxEmail);\n\n this.logger.info(loggedInUserId, this.getEvents.name, this.fileName, 'List Microsoft Graph calendar events', {\n mailboxEmail,\n resourceId: request.resourceId,\n path: url,\n hasTimeWindow: Boolean(request.start && request.end),\n });\n\n const response = await this.microsoftApiClient.apiCall<IMicrosoftGraphEventsResponse>(\n { apiMethod: HTTP_METHOD.GET, url },\n integration,\n loggedInUserId,\n );\n const events = (response.value ?? []).map((graphEvent) =>\n fromGraphEvent(graphEvent, { resourceId: request.resourceId, organizerUserEmail: this.organizerUserMailbox(request) }),\n );\n this.logger.info(loggedInUserId, this.getEvents.name, this.fileName, 'Listed Microsoft Graph calendar events', {\n mailboxEmail,\n resourceId: request.resourceId,\n count: events.length,\n });\n return { events };\n } catch (error) {\n this.logger.error(loggedInUserId, this.getEvents.name, this.fileName, 'Error listing Microsoft Graph calendar events', error);\n throw error;\n }\n }\n\n override syncEvents(request: ISyncEventsRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<ISyncEventsResponse> {\n this.logger.info(loggedInUserId, this.syncEvents.name, this.fileName, 'Sync Microsoft Graph calendar events (delta)', {\n resourceId: request.resourceId,\n hasSyncToken: Boolean(request.syncToken),\n });\n void integration;\n void this.microsoftApiClient;\n return Promise.reject(new NotImplementedException('MicrosoftCalendarBookingService.syncEvents is not implemented yet'));\n }\n\n private async deleteGraphEvent(\n mailboxEmail: string,\n resourceId: string,\n eventId: string,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<void> {\n this.assertResourceId(resourceId);\n this.assertEventId(eventId);\n await this.microsoftApiClient.apiCall(\n {\n apiMethod: HTTP_METHOD.DELETE,\n url: MICROSOFT_GRAPH_PATHS.userCalendarEvent(mailboxEmail, eventId),\n },\n integration,\n loggedInUserId,\n );\n }\n\n /**\n * Mailbox the Graph call targets: the organizing user when one is known, otherwise the\n * resource mailbox, which keeps the room-organizes behaviour for callers that cannot\n * resolve a user. The return value is therefore a user *or* a resource mailbox — never\n * store it as `organizerUserEmail`; use `organizerUserMailbox` for that.\n */\n private resolveMailboxEmail(request: { organizerUserEmail?: string; resourceId: string }): string {\n return this.organizerUserMailbox(request) ?? request.resourceId;\n }\n\n /**\n * The organizing user's mailbox, or undefined when the room ends up organizing.\n */\n private organizerUserMailbox(request: { organizerUserEmail?: string }): string | undefined {\n return request.organizerUserEmail?.trim() || undefined;\n }\n\n /**\n * The room only needs to be invited as an attendee when the event lives in someone\n * else's mailbox. Posting into the room's own calendar already books it.\n */\n private resourceAsAttendee(mailboxEmail: string, resourceId: string): string | undefined {\n return mailboxEmail.trim().toLowerCase() === resourceId.trim().toLowerCase() ? undefined : resourceId;\n }\n\n private assertResourceId(resourceId: string | undefined): void {\n if (!resourceId?.trim()) {\n throw new CustomException('BAD_REQUEST', 'resourceId is required');\n }\n }\n\n private assertEventId(eventId: string | undefined): void {\n if (!eventId?.trim()) {\n throw new CustomException('BAD_REQUEST', 'eventId is required');\n }\n }\n}\n","import { LoggerService } from '@dv4resi/dvss-backend-module-utility';\nimport {\n BaseCalendarResourceManagement,\n HTTP_METHOD,\n type ICapabilityIntegration,\n type IGetResourcesRequest,\n type IGetResourcesResponse,\n type IResource,\n} from '@dvss/dvss-integration-libs';\nimport { Injectable } from '@nestjs/common';\n\nimport { MicrosoftApiClientService } from '../../adapter/microsoft-api-client.service';\nimport { MICROSOFT_GRAPH_PATHS } from '../../common';\nimport type { IMicrosoftGraphRoom, IMicrosoftGraphRoomsResponse } from '../../models';\n\n/**\n * Microsoft Graph room mailbox discovery.\n * Endpoint: GET /places/microsoft.graph.room\n */\n@Injectable()\nexport class MicrosoftCalendarResourceService extends BaseCalendarResourceManagement {\n private readonly fileName = 'resource-management.service';\n\n constructor(\n private readonly logger: LoggerService,\n private readonly microsoftApiClient: MicrosoftApiClientService,\n ) {\n super();\n }\n\n override async getResources(request: IGetResourcesRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IGetResourcesResponse> {\n this.logger.info(loggedInUserId, this.getResources.name, this.fileName, 'Fetching Microsoft Graph room mailboxes', {\n search: request.search,\n });\n\n const response = await this.microsoftApiClient.apiCall<IMicrosoftGraphRoomsResponse>(\n {\n apiMethod: HTTP_METHOD.GET,\n url: MICROSOFT_GRAPH_PATHS.rooms,\n },\n integration,\n loggedInUserId,\n );\n\n const resources = (response.value ?? [])\n .map((room) => this.mapRoom(room))\n .filter((room): room is IResource => room !== undefined)\n .filter((room) => {\n if (!request.search) {\n return true;\n }\n const needle = request.search.toLowerCase();\n return room.displayName?.toLowerCase().includes(needle) === true || room.id.toLowerCase().includes(needle);\n });\n\n return { resources };\n }\n\n private mapRoom(room: IMicrosoftGraphRoom): IResource | undefined {\n if (!room.emailAddress) {\n return undefined;\n }\n\n return {\n id: room.emailAddress,\n displayName: room.displayName,\n capacity: room.capacity,\n building: room.building,\n floorLabel: room.floorLabel,\n };\n }\n}\n","import { CustomException, LoggerService } from '@dv4resi/dvss-backend-module-utility';\nimport {\n BaseCalendarWebhookManagement,\n HTTP_METHOD,\n type ICapabilityIntegration,\n type IDeleteWebhookRequest,\n type IRefreshWebhookRequest,\n type IRefreshWebhookResponse,\n type IRegisterWebhookRequest,\n type IRegisterWebhookResponse,\n type IWebhookSubscription,\n} from '@dvss/dvss-integration-libs';\nimport { Injectable } from '@nestjs/common';\n\nimport { MicrosoftApiClientService } from '../../adapter/microsoft-api-client.service';\nimport { MICROSOFT_GRAPH_PATHS } from '../../common';\nimport type { IMicrosoftGraphSubscription } from '../../models';\n\nconst GRAPH_SUBSCRIPTION_KNOWN_KEYS = new Set(['id', 'resource', 'changeType', 'notificationUrl', 'expirationDateTime', 'clientState']);\n\n/**\n * Microsoft Graph change-notification subscriptions.\n * Caller supplies notificationUrl, resource, clientState, and expirationDateTime.\n * Persistence and the Graph validation handshake live outside this package.\n * Endpoints:\n * - POST /subscriptions\n * - PATCH /subscriptions/{id} (renewal)\n * - DELETE /subscriptions/{id}\n */\n@Injectable()\nexport class MicrosoftCalendarWebhookService extends BaseCalendarWebhookManagement {\n private readonly fileName = 'webhook-management.service';\n\n constructor(\n private readonly logger: LoggerService,\n private readonly microsoftApiClient: MicrosoftApiClientService,\n ) {\n super();\n }\n\n override async registerWebhook(\n request: IRegisterWebhookRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IRegisterWebhookResponse> {\n try {\n this.logger.info(loggedInUserId, this.registerWebhook.name, this.fileName, 'Register Microsoft Graph subscription', {\n resource: request.resource,\n path: MICROSOFT_GRAPH_PATHS.subscriptions,\n });\n this.assertRequired(request.resource, 'resource');\n this.assertRequired(request.notificationUrl, 'notificationUrl');\n this.assertRequired(request.expirationDateTime, 'expirationDateTime');\n if (request.changeTypes.length === 0) {\n throw new CustomException('BAD_REQUEST', 'changeTypes is required');\n }\n\n const graphSubscription = await this.microsoftApiClient.apiCall<IMicrosoftGraphSubscription>(\n {\n apiMethod: HTTP_METHOD.POST,\n url: MICROSOFT_GRAPH_PATHS.subscriptions,\n body: this.toGraphSubscription(request),\n },\n integration,\n loggedInUserId,\n );\n const subscription = this.fromGraphSubscription(graphSubscription);\n this.logger.info(loggedInUserId, this.registerWebhook.name, this.fileName, 'Registered Microsoft Graph subscription', {\n subscriptionId: subscription.id,\n resource: subscription.resource,\n });\n return { subscription };\n } catch (error) {\n this.logger.error(loggedInUserId, this.registerWebhook.name, this.fileName, 'Error registering Microsoft Graph subscription', error);\n throw error;\n }\n }\n\n override async refreshSubscription(\n request: IRefreshWebhookRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IRefreshWebhookResponse> {\n try {\n this.logger.info(loggedInUserId, this.refreshSubscription.name, this.fileName, 'Refresh Microsoft Graph subscription', {\n subscriptionId: request.subscriptionId,\n path: MICROSOFT_GRAPH_PATHS.subscription(request.subscriptionId),\n });\n this.assertRequired(request.subscriptionId, 'subscriptionId');\n this.assertRequired(request.expirationDateTime, 'expirationDateTime');\n\n const graphSubscription = await this.microsoftApiClient.apiCall<IMicrosoftGraphSubscription>(\n {\n apiMethod: HTTP_METHOD.PATCH,\n url: MICROSOFT_GRAPH_PATHS.subscription(request.subscriptionId),\n body: { expirationDateTime: request.expirationDateTime },\n },\n integration,\n loggedInUserId,\n );\n const subscription = this.fromGraphSubscription(graphSubscription);\n this.logger.info(loggedInUserId, this.refreshSubscription.name, this.fileName, 'Refreshed Microsoft Graph subscription', {\n subscriptionId: subscription.id,\n });\n return { subscription };\n } catch (error) {\n this.logger.error(loggedInUserId, this.refreshSubscription.name, this.fileName, 'Error refreshing Microsoft Graph subscription', error);\n throw error;\n }\n }\n\n override async deleteSubscription(request: IDeleteWebhookRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<void> {\n try {\n this.logger.info(loggedInUserId, this.deleteSubscription.name, this.fileName, 'Delete Microsoft Graph subscription', {\n subscriptionId: request.subscriptionId,\n path: MICROSOFT_GRAPH_PATHS.subscription(request.subscriptionId),\n });\n this.assertRequired(request.subscriptionId, 'subscriptionId');\n\n await this.microsoftApiClient.apiCall(\n {\n apiMethod: HTTP_METHOD.DELETE,\n url: MICROSOFT_GRAPH_PATHS.subscription(request.subscriptionId),\n },\n integration,\n loggedInUserId,\n );\n this.logger.info(loggedInUserId, this.deleteSubscription.name, this.fileName, 'Deleted Microsoft Graph subscription', {\n subscriptionId: request.subscriptionId,\n });\n } catch (error) {\n this.logger.error(loggedInUserId, this.deleteSubscription.name, this.fileName, 'Error deleting Microsoft Graph subscription', error);\n throw error;\n }\n }\n\n private toGraphSubscription(request: IRegisterWebhookRequest): IMicrosoftGraphSubscription {\n const graph: IMicrosoftGraphSubscription = {\n changeType: request.changeTypes.join(','),\n notificationUrl: request.notificationUrl,\n resource: request.resource,\n expirationDateTime: request.expirationDateTime,\n };\n if (request.clientState !== undefined) {\n graph.clientState = request.clientState;\n }\n return graph;\n }\n\n private fromGraphSubscription(graph: IMicrosoftGraphSubscription): IWebhookSubscription {\n const metadata = this.collectUnknownGraphFields(graph);\n return {\n id: graph.id,\n resource: graph.resource ?? '',\n changeTypes: (graph.changeType ?? '')\n .split(',')\n .map((changeType) => changeType.trim())\n .filter((changeType) => changeType.length > 0),\n notificationUrl: graph.notificationUrl ?? '',\n expirationDateTime: graph.expirationDateTime ?? '',\n clientState: graph.clientState,\n metadata,\n };\n }\n\n private collectUnknownGraphFields(graph: IMicrosoftGraphSubscription): Record<string, unknown> | undefined {\n const extras: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(graph as Record<string, unknown>)) {\n if (!GRAPH_SUBSCRIPTION_KNOWN_KEYS.has(key) && value !== undefined) {\n extras[key] = value;\n }\n }\n return Object.keys(extras).length > 0 ? extras : undefined;\n }\n\n private assertRequired(value: string | undefined, fieldName: string): void {\n if (!value?.trim()) {\n throw new CustomException('BAD_REQUEST', `${fieldName} is required`);\n }\n }\n}\n","import { CommonValidationDatabaseService } from '@dv4resi/dvss-backend-module-datastore';\nimport { type AddAPIResponse, type GraphQLContext, LoggerService, SECRET_PROVIDER, type SecretProvider } from '@dv4resi/dvss-backend-module-utility';\nimport {\n BaseIntegrationConfiguration,\n IntegrationConfigurationDao,\n IntegrationConfigSecureStorageService,\n type IAddCapabilityIntegrationInput,\n type ICapabilityIntegration,\n type IUpdateCapabilityIntegrationRequest,\n type IUpdateCapabilityIntegrationResponse,\n} from '@dvss/dvss-integration-libs';\nimport { Inject, Injectable, Optional } from '@nestjs/common';\n\nimport { buildMicrosoftIntegrationConfig } from '../../common/build-microsoft-integration-config';\nimport { getMicrosoftKmsKeyId, looksLikeStoredSecureConfig } from '../../common/microsoft-secure-storage';\nimport type { IMicrosoftConfig } from '../../models';\nimport { MicrosoftAuthService } from '../auth/auth.service';\n\nconst MICROSOFT_SECURE_STORAGE_OPTIONS = {\n useSecureStorage: true as const,\n get kmsKeyId(): string {\n return getMicrosoftKmsKeyId();\n },\n};\n\n@Injectable()\nexport class MicrosoftIntegrationConfigurationService extends BaseIntegrationConfiguration {\n constructor(\n integrationConfigurationDao: IntegrationConfigurationDao,\n commonValidationDatabaseService: CommonValidationDatabaseService,\n logger: LoggerService,\n private readonly microsoftAuthService: MicrosoftAuthService,\n @Optional() @Inject(IntegrationConfigSecureStorageService) secureStorage?: IntegrationConfigSecureStorageService,\n @Optional() @Inject(SECRET_PROVIDER) secretProvider?: SecretProvider,\n ) {\n super(integrationConfigurationDao, commonValidationDatabaseService, logger, secureStorage, secretProvider);\n }\n\n override async addCapabilityIntegration(input: IAddCapabilityIntegrationInput, context: GraphQLContext): Promise<AddAPIResponse> {\n const rawConfig = (input.config ?? {}) as Partial<IMicrosoftConfig>;\n const integrationConfig = rawConfig.integrationConfig;\n\n if (!integrationConfig?.tenantId || !integrationConfig.clientId || !integrationConfig.clientSecret) {\n throw new Error('Microsoft integrationConfig.tenantId, clientId, and clientSecret are required');\n }\n\n const microsoftConfig = buildMicrosoftIntegrationConfig(\n {\n tenantId: integrationConfig.tenantId,\n clientId: integrationConfig.clientId,\n clientSecret: integrationConfig.clientSecret,\n },\n rawConfig,\n );\n\n const token = await this.microsoftAuthService.getAccessToken(\n {\n config: microsoftConfig,\n capabilityId: input.capabilityId,\n providerId: input.capabilityProviderId,\n } as Omit<ICapabilityIntegration, 'id'>,\n context.loggedInUserId,\n true,\n );\n\n const result = await super.addCapabilityIntegration(\n {\n ...input,\n config: microsoftConfig as unknown as IAddCapabilityIntegrationInput['config'],\n },\n context,\n {\n useSecureStorage: MICROSOFT_SECURE_STORAGE_OPTIONS.useSecureStorage,\n kmsKeyId: MICROSOFT_SECURE_STORAGE_OPTIONS.kmsKeyId,\n },\n );\n\n await this.microsoftAuthService.persistMintedAccessToken(BigInt(result.id), token, context.loggedInUserId);\n\n return result;\n }\n\n override async updateCapabilityIntegration(\n request: IUpdateCapabilityIntegrationRequest,\n integration?: ICapabilityIntegration,\n loggedInUserId?: bigint,\n ): Promise<IUpdateCapabilityIntegrationResponse> {\n if (!request.updateData.config) {\n return super.updateCapabilityIntegration(request, integration, loggedInUserId);\n }\n\n const existingStored = (integration?.config ?? {}) as Record<string, unknown>;\n let existingConfig = existingStored as unknown as Partial<IMicrosoftConfig>;\n\n if (looksLikeStoredSecureConfig(existingStored) && this.secureStorage) {\n const keyId = MICROSOFT_SECURE_STORAGE_OPTIONS.kmsKeyId;\n existingConfig = (await this.secureStorage.prepareForBackend(existingStored, keyId, loggedInUserId)) as unknown as Partial<IMicrosoftConfig>;\n }\n\n const incomingConfig = request.updateData.config as unknown as Partial<IMicrosoftConfig>;\n\n const asString = (value: unknown): string => (typeof value === 'string' ? value : '');\n\n const mergedCredentials = {\n tenantId: asString(incomingConfig.integrationConfig?.tenantId) || asString(existingConfig.integrationConfig?.tenantId) || '',\n clientId: asString(incomingConfig.integrationConfig?.clientId) || asString(existingConfig.integrationConfig?.clientId) || '',\n clientSecret: asString(incomingConfig.integrationConfig?.clientSecret) || asString(existingConfig.integrationConfig?.clientSecret) || '',\n };\n\n const platformConfig = incomingConfig.platformConfig ?? existingConfig.platformConfig;\n const mergedConfig = buildMicrosoftIntegrationConfig(mergedCredentials, platformConfig ? { platformConfig } : undefined);\n\n await this.microsoftAuthService.getAccessToken(\n {\n id: request.id,\n config: mergedConfig,\n capabilityId: integration?.capabilityId,\n providerId: integration?.providerId,\n } as ICapabilityIntegration,\n loggedInUserId,\n true,\n );\n\n const updateRequest: IUpdateCapabilityIntegrationRequest = {\n ...request,\n updateData: {\n ...request.updateData,\n config: {\n ...request.updateData.config,\n ...mergedConfig,\n } as unknown as IUpdateCapabilityIntegrationRequest['updateData']['config'],\n },\n };\n\n const integrationForUpdate = integration\n ? ({\n ...integration,\n config: mergedConfig,\n } as ICapabilityIntegration)\n : integration;\n\n return super.updateCapabilityIntegration(updateRequest, integrationForUpdate, loggedInUserId, {\n useSecureStorage: MICROSOFT_SECURE_STORAGE_OPTIONS.useSecureStorage,\n kmsKeyId: MICROSOFT_SECURE_STORAGE_OPTIONS.kmsKeyId,\n });\n }\n}\n","import { CommonValidationDatabaseService, DatastoreModule } from '@dv4resi/dvss-backend-module-datastore';\nimport { LoggerModule } from '@dv4resi/dvss-backend-module-utility';\nimport {\n IntegrationConfigurationDao,\n IntegrationConfigSecureStorageService,\n IntegrationLibsModule,\n IntegrationSubcapabilityDao,\n} from '@dvss/dvss-integration-libs';\nimport { IntegrationOauthModule } from '@dvss/dvss-integration-oauth';\nimport { Module } from '@nestjs/common';\n\nimport { MicrosoftApiClientService } from './adapter/microsoft-api-client.service';\nimport { MicrosoftAuthService } from './capabilities/auth/auth.service';\nimport { MicrosoftCalendarBookingService } from './capabilities/booking-management/booking-management.service';\nimport { MicrosoftCalendarResourceService } from './capabilities/resource-management/resource-management.service';\nimport { MicrosoftCalendarWebhookService } from './capabilities/webhook-management/webhook-management.service';\nimport { MicrosoftIntegrationConfigurationService } from './capabilities/integration-configuration/integration-configuration.service';\nimport { MICROSOFT_SECURE_STORAGE } from './common/microsoft-secure-storage';\n\n@Module({\n imports: [IntegrationLibsModule, LoggerModule, DatastoreModule, IntegrationOauthModule],\n providers: [\n MicrosoftAuthService,\n MicrosoftApiClientService,\n MicrosoftIntegrationConfigurationService,\n MicrosoftCalendarResourceService,\n MicrosoftCalendarBookingService,\n MicrosoftCalendarWebhookService,\n IntegrationSubcapabilityDao,\n IntegrationConfigurationDao,\n CommonValidationDatabaseService,\n {\n provide: MICROSOFT_SECURE_STORAGE,\n useExisting: IntegrationConfigSecureStorageService,\n },\n ],\n exports: [\n MicrosoftAuthService,\n MicrosoftApiClientService,\n MicrosoftIntegrationConfigurationService,\n MicrosoftCalendarResourceService,\n MicrosoftCalendarBookingService,\n MicrosoftCalendarWebhookService,\n IntegrationSubcapabilityDao,\n IntegrationConfigurationDao,\n CommonValidationDatabaseService,\n IntegrationOauthModule,\n ],\n})\nexport class AppModule {}\n","import { Injectable } from '@nestjs/common';\n\n/**\n * Base helper for calendar-im provider routing.\n * Returns already-injected Nest provider instances (not ModuleRef.create).\n */\n@Injectable()\nexport abstract class AdapterFactoryService<TProvider extends string | number | symbol, TAdapter> {\n abstract readonly adapterMap: Partial<Record<TProvider, TAdapter>>;\n\n getAdapter(provider: TProvider): TAdapter {\n const adapter = this.adapterMap[provider];\n\n if (adapter === undefined) {\n throw new Error(`No calendar adapter found for provider: ${String(provider)}`);\n }\n\n return adapter;\n }\n}\n","/**\n * Calendar provider keys used by CalendarIntegrationManager adapter factories.\n * Values match CAPABILITY_PROVIDER_INTEGRATION_ENUM in datastore / utility.\n */\nexport enum CALENDAR_PROVIDER_ENUM {\n MICROSOFT_365 = 'MICROSOFT_365',\n}\n","import type { ICapabilityIntegration, IValidatedCapabilityIntegration } from '@dvss/dvss-integration-libs';\n\n/**\n * IM orchestration contract for calendar provider auth flows.\n */\nexport abstract class ICalendarAuthHandler {\n abstract validateConfig(integration: ICapabilityIntegration, loggedInUserId: bigint): IValidatedCapabilityIntegration;\n\n abstract testIntegration(integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<boolean>;\n\n abstract fetchAccessToken(integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<string>;\n}\n","import type { ICapabilityIntegration, IValidatedCapabilityIntegration } from '@dvss/dvss-integration-libs';\nimport { MicrosoftAuthService } from '@dvss/dvss-integration-microsoft';\nimport { Injectable } from '@nestjs/common';\n\nimport { ICalendarAuthHandler } from '../../handlers/calendar-auth.handler.interface';\n\n@Injectable()\nexport class MicrosoftCalendarAuthHandler extends ICalendarAuthHandler {\n constructor(private readonly microsoftAuthService: MicrosoftAuthService) {\n super();\n }\n\n override validateConfig(integration: ICapabilityIntegration, loggedInUserId: bigint): IValidatedCapabilityIntegration {\n return this.microsoftAuthService.validateConfig(integration, loggedInUserId);\n }\n\n override async testIntegration(integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<boolean> {\n return this.microsoftAuthService.testIntegration(integration, loggedInUserId);\n }\n\n override async fetchAccessToken(integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<string> {\n return this.microsoftAuthService.fetchAccessToken(integration, loggedInUserId);\n }\n}\n","import { Injectable } from '@nestjs/common';\n\nimport { AdapterFactoryService } from '../common/abstract/adapter-factory.service';\nimport { CALENDAR_PROVIDER_ENUM } from '../common/enum/calendar-provider.enum';\nimport { ICalendarAuthHandler } from '../handlers/calendar-auth.handler.interface';\nimport { MicrosoftCalendarAuthHandler } from '../providers/microsoft/microsoft-calendar-auth.handler';\n\n@Injectable()\nexport class CalendarAuthAdapterFactory extends AdapterFactoryService<CALENDAR_PROVIDER_ENUM, ICalendarAuthHandler> {\n readonly adapterMap: Partial<Record<CALENDAR_PROVIDER_ENUM, ICalendarAuthHandler>>;\n\n constructor(microsoftCalendarAuthHandler: MicrosoftCalendarAuthHandler) {\n super();\n this.adapterMap = {\n [CALENDAR_PROVIDER_ENUM.MICROSOFT_365]: microsoftCalendarAuthHandler,\n };\n }\n}\n","import type {\n ICancelEventRequest,\n ICapabilityIntegration,\n ICreateEventRequest,\n IDeleteEventRequest,\n IEvent,\n IGetEventRequest,\n IGetEventsRequest,\n IGetEventsResponse,\n ISyncEventsRequest,\n ISyncEventsResponse,\n IUpdateEventRequest,\n} from '@dvss/dvss-integration-libs';\n\n/**\n * IM orchestration contract for calendar booking flows.\n * Same shape for every provider. Implementations may invoke multiple\n * vendor Graph/API calls inside a single method before returning to the MS.\n *\n * Method names are MS-facing orchestration APIs (not 1:1 with Graph endpoints).\n */\nexport abstract class ICalendarBookingHandler {\n /**\n * Create a calendar booking. May orchestrate multiple vendor API calls.\n * Example name — finalize with calendar-ms API naming when wiring.\n */\n abstract addCalendarBooking(request: ICreateEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IEvent>;\n\n abstract updateCalendarBooking(request: IUpdateEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IEvent>;\n\n abstract cancelCalendarBooking(request: ICancelEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<void>;\n\n abstract deleteCalendarBooking(request: IDeleteEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<void>;\n\n abstract getCalendarBooking(request: IGetEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IEvent>;\n\n abstract getCalendarBookings(request: IGetEventsRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IGetEventsResponse>;\n\n abstract syncCalendarBookings(request: ISyncEventsRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<ISyncEventsResponse>;\n}\n","import type {\n ICancelEventRequest,\n ICapabilityIntegration,\n ICreateEventRequest,\n IDeleteEventRequest,\n IEvent,\n IGetEventRequest,\n IGetEventsRequest,\n IGetEventsResponse,\n ISyncEventsRequest,\n ISyncEventsResponse,\n IUpdateEventRequest,\n} from '@dvss/dvss-integration-libs';\nimport { MicrosoftCalendarBookingService } from '@dvss/dvss-integration-microsoft';\nimport { Injectable } from '@nestjs/common';\n\nimport { ICalendarBookingHandler } from '../../handlers/calendar-booking.handler.interface';\n\n/**\n * Microsoft 365 orchestration for calendar booking flows.\n * Calls microsoft-package atomic Graph ops in the order required for each flow.\n */\n@Injectable()\nexport class MicrosoftCalendarBookingHandler extends ICalendarBookingHandler {\n constructor(private readonly microsoftCalendarBookingService: MicrosoftCalendarBookingService) {\n super();\n }\n\n override async addCalendarBooking(request: ICreateEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IEvent> {\n // Orchestration seam: add further Graph calls here when a flow needs more than createEvent.\n return this.microsoftCalendarBookingService.createEvent(request, integration, loggedInUserId);\n }\n\n override async updateCalendarBooking(request: IUpdateEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IEvent> {\n return this.microsoftCalendarBookingService.updateEvent(request, integration, loggedInUserId);\n }\n\n override async cancelCalendarBooking(request: ICancelEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<void> {\n return this.microsoftCalendarBookingService.cancelEvent(request, integration, loggedInUserId);\n }\n\n override async deleteCalendarBooking(request: IDeleteEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<void> {\n return this.microsoftCalendarBookingService.deleteEvent(request, integration, loggedInUserId);\n }\n\n override async getCalendarBooking(request: IGetEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IEvent> {\n return this.microsoftCalendarBookingService.getEvent(request, integration, loggedInUserId);\n }\n\n override async getCalendarBookings(request: IGetEventsRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IGetEventsResponse> {\n return this.microsoftCalendarBookingService.getEvents(request, integration, loggedInUserId);\n }\n\n override async syncCalendarBookings(\n request: ISyncEventsRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<ISyncEventsResponse> {\n return this.microsoftCalendarBookingService.syncEvents(request, integration, loggedInUserId);\n }\n}\n","import { Injectable } from '@nestjs/common';\n\nimport { AdapterFactoryService } from '../common/abstract/adapter-factory.service';\nimport { CALENDAR_PROVIDER_ENUM } from '../common/enum/calendar-provider.enum';\nimport { ICalendarBookingHandler } from '../handlers/calendar-booking.handler.interface';\nimport { MicrosoftCalendarBookingHandler } from '../providers/microsoft/microsoft-calendar-booking.handler';\n\n@Injectable()\nexport class CalendarBookingAdapterFactory extends AdapterFactoryService<CALENDAR_PROVIDER_ENUM, ICalendarBookingHandler> {\n readonly adapterMap: Partial<Record<CALENDAR_PROVIDER_ENUM, ICalendarBookingHandler>>;\n\n constructor(microsoftCalendarBookingHandler: MicrosoftCalendarBookingHandler) {\n super();\n this.adapterMap = {\n [CALENDAR_PROVIDER_ENUM.MICROSOFT_365]: microsoftCalendarBookingHandler,\n };\n }\n}\n","import type {\n IAddCapabilityIntegrationInput,\n ICapabilityIntegration,\n IGetCapabilityIntegrationInput,\n IGetCapabilityIntegrationResult,\n IGetCapabilityIntegrationsRequest,\n IGetCapabilityIntegrationsResponse,\n IUpdateCapabilityIntegrationRequest,\n IUpdateCapabilityIntegrationResponse,\n} from '@dvss/dvss-integration-libs';\nimport type { AddAPIResponse, GraphQLContext } from '@dv4resi/dvss-backend-module-utility';\n\n/**\n * IM orchestration contract for calendar capability-integration configuration flows.\n */\nexport abstract class ICalendarIntegrationConfigurationHandler {\n abstract addCapabilityIntegration(input: IAddCapabilityIntegrationInput, context: GraphQLContext): Promise<AddAPIResponse>;\n\n abstract updateCapabilityIntegration(\n request: IUpdateCapabilityIntegrationRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IUpdateCapabilityIntegrationResponse>;\n\n abstract getCapabilityIntegrations(request: IGetCapabilityIntegrationsRequest, loggedInUserId: bigint): Promise<IGetCapabilityIntegrationsResponse>;\n\n abstract getCapabilityIntegration(input: IGetCapabilityIntegrationInput, context: GraphQLContext): Promise<IGetCapabilityIntegrationResult>;\n}\n","import type {\n IAddCapabilityIntegrationInput,\n ICapabilityIntegration,\n IGetCapabilityIntegrationInput,\n IGetCapabilityIntegrationResult,\n IGetCapabilityIntegrationsRequest,\n IGetCapabilityIntegrationsResponse,\n IUpdateCapabilityIntegrationRequest,\n IUpdateCapabilityIntegrationResponse,\n} from '@dvss/dvss-integration-libs';\nimport { MicrosoftIntegrationConfigurationService } from '@dvss/dvss-integration-microsoft';\nimport type { AddAPIResponse, GraphQLContext } from '@dv4resi/dvss-backend-module-utility';\nimport { Injectable } from '@nestjs/common';\n\nimport { ICalendarIntegrationConfigurationHandler } from '../../handlers/calendar-integration-configuration.handler.interface';\n\n@Injectable()\nexport class MicrosoftCalendarIntegrationConfigurationHandler extends ICalendarIntegrationConfigurationHandler {\n constructor(private readonly microsoftIntegrationConfigurationService: MicrosoftIntegrationConfigurationService) {\n super();\n }\n\n override async addCapabilityIntegration(input: IAddCapabilityIntegrationInput, context: GraphQLContext): Promise<AddAPIResponse> {\n return this.microsoftIntegrationConfigurationService.addCapabilityIntegration(input, context);\n }\n\n override async updateCapabilityIntegration(\n request: IUpdateCapabilityIntegrationRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IUpdateCapabilityIntegrationResponse> {\n return this.microsoftIntegrationConfigurationService.updateCapabilityIntegration(request, integration, loggedInUserId);\n }\n\n override async getCapabilityIntegrations(request: IGetCapabilityIntegrationsRequest, loggedInUserId: bigint): Promise<IGetCapabilityIntegrationsResponse> {\n return this.microsoftIntegrationConfigurationService.getCapabilityIntegrations(request, loggedInUserId);\n }\n\n override async getCapabilityIntegration(input: IGetCapabilityIntegrationInput, context: GraphQLContext): Promise<IGetCapabilityIntegrationResult> {\n return this.microsoftIntegrationConfigurationService.getCapabilityIntegration(input, context);\n }\n}\n","import { Injectable } from '@nestjs/common';\n\nimport { AdapterFactoryService } from '../common/abstract/adapter-factory.service';\nimport { CALENDAR_PROVIDER_ENUM } from '../common/enum/calendar-provider.enum';\nimport { ICalendarIntegrationConfigurationHandler } from '../handlers/calendar-integration-configuration.handler.interface';\nimport { MicrosoftCalendarIntegrationConfigurationHandler } from '../providers/microsoft/microsoft-calendar-integration-configuration.handler';\n\n@Injectable()\nexport class CalendarIntegrationConfigurationAdapterFactory extends AdapterFactoryService<CALENDAR_PROVIDER_ENUM, ICalendarIntegrationConfigurationHandler> {\n readonly adapterMap: Partial<Record<CALENDAR_PROVIDER_ENUM, ICalendarIntegrationConfigurationHandler>>;\n\n constructor(microsoftCalendarIntegrationConfigurationHandler: MicrosoftCalendarIntegrationConfigurationHandler) {\n super();\n this.adapterMap = {\n [CALENDAR_PROVIDER_ENUM.MICROSOFT_365]: microsoftCalendarIntegrationConfigurationHandler,\n };\n }\n}\n","import type { ICapabilityIntegration, IGetResourcesRequest, IGetResourcesResponse } from '@dvss/dvss-integration-libs';\n\n/**\n * IM orchestration contract for calendar resource discovery flows.\n */\nexport abstract class ICalendarResourceHandler {\n abstract getCalendarResources(request: IGetResourcesRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IGetResourcesResponse>;\n}\n","import type { ICapabilityIntegration, IGetResourcesRequest, IGetResourcesResponse } from '@dvss/dvss-integration-libs';\nimport { MicrosoftCalendarResourceService } from '@dvss/dvss-integration-microsoft';\nimport { Injectable } from '@nestjs/common';\n\nimport { ICalendarResourceHandler } from '../../handlers/calendar-resource.handler.interface';\n\n@Injectable()\nexport class MicrosoftCalendarResourceHandler extends ICalendarResourceHandler {\n constructor(private readonly microsoftCalendarResourceService: MicrosoftCalendarResourceService) {\n super();\n }\n\n override async getCalendarResources(\n request: IGetResourcesRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IGetResourcesResponse> {\n return this.microsoftCalendarResourceService.getResources(request, integration, loggedInUserId);\n }\n}\n","import { Injectable } from '@nestjs/common';\n\nimport { AdapterFactoryService } from '../common/abstract/adapter-factory.service';\nimport { CALENDAR_PROVIDER_ENUM } from '../common/enum/calendar-provider.enum';\nimport { ICalendarResourceHandler } from '../handlers/calendar-resource.handler.interface';\nimport { MicrosoftCalendarResourceHandler } from '../providers/microsoft/microsoft-calendar-resource.handler';\n\n@Injectable()\nexport class CalendarResourceAdapterFactory extends AdapterFactoryService<CALENDAR_PROVIDER_ENUM, ICalendarResourceHandler> {\n readonly adapterMap: Partial<Record<CALENDAR_PROVIDER_ENUM, ICalendarResourceHandler>>;\n\n constructor(microsoftCalendarResourceHandler: MicrosoftCalendarResourceHandler) {\n super();\n this.adapterMap = {\n [CALENDAR_PROVIDER_ENUM.MICROSOFT_365]: microsoftCalendarResourceHandler,\n };\n }\n}\n","import type {\n ICapabilityIntegration,\n IDeleteWebhookRequest,\n IRefreshWebhookRequest,\n IRefreshWebhookResponse,\n IRegisterWebhookRequest,\n IRegisterWebhookResponse,\n} from '@dvss/dvss-integration-libs';\n\n/**\n * IM orchestration contract for calendar webhook subscription flows.\n */\nexport abstract class ICalendarWebhookHandler {\n abstract registerCalendarWebhook(\n request: IRegisterWebhookRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IRegisterWebhookResponse>;\n\n abstract refreshCalendarWebhook(\n request: IRefreshWebhookRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IRefreshWebhookResponse>;\n\n abstract deleteCalendarWebhook(request: IDeleteWebhookRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<void>;\n}\n","import type {\n ICapabilityIntegration,\n IDeleteWebhookRequest,\n IRefreshWebhookRequest,\n IRefreshWebhookResponse,\n IRegisterWebhookRequest,\n IRegisterWebhookResponse,\n} from '@dvss/dvss-integration-libs';\nimport { MicrosoftCalendarWebhookService } from '@dvss/dvss-integration-microsoft';\nimport { Injectable } from '@nestjs/common';\n\nimport { ICalendarWebhookHandler } from '../../handlers/calendar-webhook.handler.interface';\n\n@Injectable()\nexport class MicrosoftCalendarWebhookHandler extends ICalendarWebhookHandler {\n constructor(private readonly microsoftCalendarWebhookService: MicrosoftCalendarWebhookService) {\n super();\n }\n\n override async registerCalendarWebhook(\n request: IRegisterWebhookRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IRegisterWebhookResponse> {\n return this.microsoftCalendarWebhookService.registerWebhook(request, integration, loggedInUserId);\n }\n\n override async refreshCalendarWebhook(\n request: IRefreshWebhookRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IRefreshWebhookResponse> {\n return this.microsoftCalendarWebhookService.refreshSubscription(request, integration, loggedInUserId);\n }\n\n override async deleteCalendarWebhook(request: IDeleteWebhookRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<void> {\n return this.microsoftCalendarWebhookService.deleteSubscription(request, integration, loggedInUserId);\n }\n}\n","import { Injectable } from '@nestjs/common';\n\nimport { AdapterFactoryService } from '../common/abstract/adapter-factory.service';\nimport { CALENDAR_PROVIDER_ENUM } from '../common/enum/calendar-provider.enum';\nimport { ICalendarWebhookHandler } from '../handlers/calendar-webhook.handler.interface';\nimport { MicrosoftCalendarWebhookHandler } from '../providers/microsoft/microsoft-calendar-webhook.handler';\n\n@Injectable()\nexport class CalendarWebhookAdapterFactory extends AdapterFactoryService<CALENDAR_PROVIDER_ENUM, ICalendarWebhookHandler> {\n readonly adapterMap: Partial<Record<CALENDAR_PROVIDER_ENUM, ICalendarWebhookHandler>>;\n\n constructor(microsoftCalendarWebhookHandler: MicrosoftCalendarWebhookHandler) {\n super();\n this.adapterMap = {\n [CALENDAR_PROVIDER_ENUM.MICROSOFT_365]: microsoftCalendarWebhookHandler,\n };\n }\n}\n","import { Module } from '@nestjs/common';\nimport { IntegrationLibsModule } from '@dvss/dvss-integration-libs';\nimport { IntegrationMicrosoftModule } from '@dvss/dvss-integration-microsoft';\n\nimport { CalendarAuthAdapterFactory } from './adapters/calendar-auth.adapter.factory';\nimport { CalendarBookingAdapterFactory } from './adapters/calendar-booking.adapter.factory';\nimport { CalendarIntegrationConfigurationAdapterFactory } from './adapters/calendar-integration-configuration.adapter.factory';\nimport { CalendarResourceAdapterFactory } from './adapters/calendar-resource.adapter.factory';\nimport { CalendarWebhookAdapterFactory } from './adapters/calendar-webhook.adapter.factory';\nimport { MicrosoftCalendarAuthHandler } from './providers/microsoft/microsoft-calendar-auth.handler';\nimport { MicrosoftCalendarBookingHandler } from './providers/microsoft/microsoft-calendar-booking.handler';\nimport { MicrosoftCalendarIntegrationConfigurationHandler } from './providers/microsoft/microsoft-calendar-integration-configuration.handler';\nimport { MicrosoftCalendarResourceHandler } from './providers/microsoft/microsoft-calendar-resource.handler';\nimport { MicrosoftCalendarWebhookHandler } from './providers/microsoft/microsoft-calendar-webhook.handler';\n\nconst microsoftHandlers = [\n MicrosoftCalendarBookingHandler,\n MicrosoftCalendarResourceHandler,\n MicrosoftCalendarWebhookHandler,\n MicrosoftCalendarAuthHandler,\n MicrosoftCalendarIntegrationConfigurationHandler,\n];\n\nconst adapterFactories = [\n CalendarBookingAdapterFactory,\n CalendarResourceAdapterFactory,\n CalendarWebhookAdapterFactory,\n CalendarAuthAdapterFactory,\n CalendarIntegrationConfigurationAdapterFactory,\n];\n\n@Module({\n imports: [IntegrationLibsModule, IntegrationMicrosoftModule],\n providers: [...microsoftHandlers, ...adapterFactories],\n exports: [IntegrationLibsModule, IntegrationMicrosoftModule, ...microsoftHandlers, ...adapterFactories],\n})\nexport class AppModule {}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../../packages/dvss-integration-libs/src/app.service.ts","../../../packages/dvss-integration-libs/src/app.controller.ts","../../../packages/dvss-integration-libs/src/integration-common-utils/secure-storage/integration-config-secure-storage.service.ts","../../../packages/dvss-integration-libs/src/integration-traffic-router/constants/http.constant.ts","../../../packages/dvss-integration-libs/src/integration-traffic-router/logging/request-logger.service.ts","../../../packages/dvss-integration-libs/src/integration-traffic-router/rate-limiter/rate-limiter.service.ts","../../../packages/dvss-integration-libs/src/integration-traffic-router/gateway/traffic-gateway.service.ts","../../../packages/dvss-integration-libs/src/load-env.ts","../../../packages/dvss-integration-libs/src/app.module.ts","../../../packages/dvss-integration-libs/src/integration-traffic-router/constants/traffic-router.constant.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/auth-management/auth.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/models/credit-management.model.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/models/wellness-management.model.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/models/invoice-management.model.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/models/miscellaneous.model.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/models/customer-payment-management.model.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/models/booking-management.model.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/wellness/wellness-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/credit-management/credit-booking.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/customer-management/customer-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/package-management/package-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/accounting/subcapabilities/contact-person-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/accounting/subcapabilities/credit-note-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/accounting/subcapabilities/customer-payment-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/accounting/subcapabilities/invoice-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/accounting/subcapabilities/loa-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/accounting/subcapabilities/tax-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/payment/subcapabilities/payment.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/payment/subcapabilities/payment-method-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/payment/subcapabilities/user-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/membership/subcapabilities/customer-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/membership/subcapabilities/membership-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/integration-configuration/integration-configuration.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/integration-resource-management/integration-resource-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/device-management/device-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/access-control/access-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/accounting/subcapabilities/miscellaneous.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/resource-management/resource-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/booking-management/booking-management.base.ts","../../../packages/dvss-integration-libs/src/integration-operation-skeletons/capabilities/webhook-management/webhook-management.base.ts","../../../packages/dvss-integration-libs/src/integration-common-utils/dao/integration-booking.dao.ts","../../../packages/dvss-integration-libs/src/integration-common-utils/dao/integration-common.dao.ts","../../../packages/dvss-integration-libs/src/integration-common-utils/dao/integration-subcapability.dao.ts","../../../packages/dvss-integration-libs/src/integration-common-utils/dao/integration-visitor-credential-mapping.dao.ts","../../../packages/dvss-integration-libs/src/integration-common-utils/dao/integration-configuration.dao.ts","../../../packages/dvss-integration-libs/src/integration-common-utils/dao/integration-service-communication-topic.dao.ts","../../../packages/dvss-integration-libs/src/integration-common-utils/dao/integration-resource-management.dao.ts","../../../packages/dvss-integration-libs/src/integration-common-utils/dao/integration-user-management.dao.ts","../../../packages/dvss-integration-libs/src/integration-common-utils/dao/integration-onprem-deployment.dao.ts","../../../packages/dvss-integration-oauth/src/common/oauth.util.ts","../../../packages/dvss-integration-oauth/src/cache/oauth-token-cache.ts","../../../packages/dvss-integration-oauth/src/grants/authorization-code.handler.ts","../../../packages/dvss-integration-oauth/src/models/oauth.model.ts","../../../packages/dvss-integration-oauth/src/grants/client-credentials.handler.ts","../../../packages/dvss-integration-oauth/src/grants/grant-handler.registry.ts","../../../packages/dvss-integration-oauth/src/store/oauth-provider.dao.ts","../../../packages/dvss-integration-oauth/src/store/oauth-token.dao.ts","../../../packages/dvss-integration-oauth/src/token-manager/oauth-token-manager.ts","../../../packages/dvss-integration-oauth/src/oauth2.provider.ts","../../../packages/dvss-integration-oauth/src/oauth.module.ts","../../../packages/dvss-integration-microsoft/src/common/microsoft.constant.ts","../../../packages/dvss-integration-microsoft/src/common/build-microsoft-integration-config.ts","../../../packages/dvss-integration-microsoft/src/common/microsoft-secure-storage.ts","../../../packages/dvss-integration-microsoft/src/enum/common.enum.ts","../../../packages/dvss-integration-microsoft/src/capabilities/auth/auth.service.ts","../../../packages/dvss-integration-microsoft/src/adapter/microsoft-api-client.service.ts","../../../packages/dvss-integration-microsoft/src/capabilities/booking-management/booking-management.mapper.ts","../../../packages/dvss-integration-microsoft/src/capabilities/booking-management/booking-management.service.ts","../../../packages/dvss-integration-microsoft/src/capabilities/resource-management/resource-management.service.ts","../../../packages/dvss-integration-microsoft/src/capabilities/webhook-management/webhook-management.service.ts","../../../packages/dvss-integration-microsoft/src/capabilities/integration-configuration/integration-configuration.service.ts","../../../packages/dvss-integration-microsoft/src/app.module.ts","../src/common/abstract/adapter-factory.service.ts","../src/common/enum/calendar-provider.enum.ts","../src/handlers/calendar-auth.handler.interface.ts","../src/providers/microsoft/microsoft-calendar-auth.handler.ts","../src/adapters/calendar-auth.adapter.factory.ts","../src/handlers/calendar-booking.handler.interface.ts","../src/providers/microsoft/microsoft-calendar-booking.handler.ts","../src/adapters/calendar-booking.adapter.factory.ts","../src/handlers/calendar-integration-configuration.handler.interface.ts","../src/providers/microsoft/microsoft-calendar-integration-configuration.handler.ts","../src/adapters/calendar-integration-configuration.adapter.factory.ts","../src/handlers/calendar-resource.handler.interface.ts","../src/providers/microsoft/microsoft-calendar-resource.handler.ts","../src/adapters/calendar-resource.adapter.factory.ts","../src/handlers/calendar-webhook.handler.interface.ts","../src/providers/microsoft/microsoft-calendar-webhook.handler.ts","../src/adapters/calendar-webhook.adapter.factory.ts","../src/app.module.ts"],"names":["AppService","getHello","AppController","appService","isPlainObject","value","Array","isArray","isSensitiveStoredField","isSensitive","encrypted","isNonSensitiveStoredField","toSensitivePlaintext","undefined","String","CustomException","resolveMaskStrategy","meta","raw","maskStrategy","MASK_STRATEGY_ENUM","LAST_4","Object","values","includes","IntegrationConfigSecureStorageService","fileName","secretProvider","logger","prepareForWrite","rawConfig","fieldMetadata","keyId","loggedInUserId","SYSTEM_USER_ID","info","name","transformSectionForWrite","prepareForRead","storedConfig","transformSectionForRead","prepareForBackend","transformSectionForBackend","isMaskedUnchanged","incomingValue","storedMasked","isMaskedValue","prepareForUpdate","incomingConfig","existingStoredConfig","transformSectionForUpdate","metadata","result","key","entries","sectionMeta","looksLikeFieldMap","writeFields","fields","fieldMap","out","fieldName","fieldValue","sensitive","plaintext","encrypt","masked","maskValue","stored","decrypt","incoming","existing","existingValue","updateFields","existingField","existingSensitive","incomingString","replaceAll","length","every","v","HTTP_METHOD","REDACTED","SENSITIVE_HEADER_KEYS","Set","SENSITIVE_BODY_KEYS","IntegrationRequestLoggerService","className","logRequest","logData","method","url","headers","requestBody","integrationId","sanitizeHeaders","sanitizePayload","timestamp","Date","logResponse","statusCode","duration","responseBody","logError","error","logIntegrationRequest","sanitized","keys","has","toLowerCase","payload","depth","sanitizeFormEncodedString","map","item","Error","message","record","params","URLSearchParams","didMutate","set","toString","RateLimiterService","validateAndEnforceRateLimit","TrafficGatewayService","httpService","requestLogger","rateLimiter","executeIntegrationRequest","request","integration","_context","startTime","now","prepareHeaders","requestConfig","prepareRequestConfig","fullUrl","constructFullUrl","baseUrl","id","apiMethod","body","apiResponse","executeHttpRequest","responseData","data","status","errorDetails","extractErrorDetails","apiMessage","err","headerType","POST","PUT","PATCH","responseType","requestUrl","normalizedBaseUrl","endsWith","slice","normalizedRequestUrl","startsWith","GET","firstValueFrom","get","post","put","patch","DELETE","delete","errorObject","response","firstString","k","trim","rootEnvPath","resolve","__dirname","config","path","AppModule","imports","ConfigModule","forRoot","envFilePath","isGlobal","HttpModule","register","global","httpsAgent","Agent","rejectUnauthorized","LoggerModule","SecureStorageModule","controllers","providers","exports","TRAFFIC_ROUTER_CONFIGURATION_STORE_KEY","BaseAuth","CREDIT_TYPE_ENUM","CREDIT_STATUS_ENUM","CREDIT_FILTER_BY_ENUM","BOOKABLE_ITEM_TYPE_ENUM","BOOKABLE_ITEM_STATUS_ENUM","GET_CUSTOMER_CREDIT_NOTES_FILTER_BY","GET_CUSTOMER_CREDIT_NOTES_SORT_BY","CREDIT_NOTE_STATUS","GET_INVOICES_SORT_BY_ENUM","GET_RECURRING_INVOICES_SORT_BY_ENUM","GET_INVOICES_FILTER_BY_ENUM","INVOICE_STATUS_ENUM","RECURRING_INVOICE_STATUS","RECURRING_INVOICE_STATUS_ENUM","DOWNLOAD_CUSTOMER_ACCOUNTING_STATEMENT_FILTER_BY_ENUM","DOWNLOAD_CUSTOMER_ACCOUNTING_STATEMENT_STATUS_ENUM","GET_PAYMENTS_FILTER_BY_ENUM","GET_PAYMENTS_FILTER_VALUE_ENUM","GET_PAYMENTS_SORTING_ENUM","EVENT_INSTANCE_KIND","BaseWellnessManagement","BaseCreditBooking","BaseCustomerManagement","BasePackageManagement","BaseAccountingContactPersonManagement","BaseAccountingCreditNoteManagement","BaseAccountingCustomerPaymentManagement","BaseAccountingInvoiceManagement","BaseAccountingLOAManagement","BaseAccountingTaxManagement","BasePayment","BasePaymentMethodManagement","BasePaymentUserManagement","BaseMembershipCustomerManagement","BaseMembershipManagement","BaseIntegrationConfiguration","integrationConfigurationDao","commonValidationDatabaseService","secureStorage","validateAddCapabilityIntegrationInput","input","context","getProject","projectId","propertyId","getProperty","resourceMappings","mapping","configuredForType","CONFIGURED_FOR_TYPE_ENUM","PROPERTY","Number","configuredForId","validatePropertyIds","propertyIds","parentId","parentIntegration","getCapabilityIntegration","capabilityIntegrationId","capability","capabilityProvider","Promise","all","getCapability","capabilityId","getCapabilityProvider","capabilityProviderId","providerId","type","category","configStructure","addCapabilityIntegration","options","securedConfig","applySecureStorageForWrite","addCapabilityIntegrationInput","createdBy","availableFor","configuredFor","updateCapabilityIntegration","validateIconAndNickName","updateData","configToUpdate","existingConfig","existingIntegrationConfig","integrationConfig","existingPlatformConfig","platformConfig","existingAccountConfig","accountConfig","useSecureStorage","updateDataForDao","nickname","icon","subcategory","capabilityIntegrationResourceId","groupId","updatedBy","updateResult","syncCapabilityIntegrationResourceMappings","iconName","getCapabilityIntegrations","getCapabilityIntegrationById","fetchBy","getCapabilityIntegrationByProvider","BigInt","kmsKeyId","accessDetails","accessTokenPlain","accessToken","plaintextToken","encryptedBody","details","BaseIntegrationResourceManagement","integrationResourceManagementDao","addResourceToIntegration","offeringId","addResult","addCapabilityIntegrationMapping","OFFERING","ids","idsCount","removeResourceFromIntegration","removeCapabilityIntegrationMapping","updateOfferingIntegrationResourceConfiguration","updateCapabilityIntegrationConfiguration","BaseDeviceManagement","BaseAccessManagement","BaseAccountingMiscellaneousManagement","BaseCalendarResourceManagement","BaseCalendarBookingManagement","BaseCalendarWebhookManagement","IntegrationBookingDao","conn","getOfferingBookingOccurrence","debug","conditions","isNull","schema","offeringBookingOccurrence","deletedAt","eq","offeringBookingOccurrenceId","offeringBooking","offering","offeringBookingId","push","select","offeringIntentId","from","innerJoin","where","and","limit","getOfferingIntent","row","query","offeringIntent","findFirst","DB_CONNECTION","IntegrationCommonDao","getTimezoneForRequest","userBehavior","userIdentityBehaviorMapping","userIdentityId","isNotNull","with","property","timezone","properties","findMany","warn","DEFAULT_TIMEZONE","IntegrationSubcapabilityDao","getSubcapabilityId","rows","subcapability","getSubcapabilities","IntegrationVisitorCredentialMappingDao","generateVisitorCredentialConfigKey","capIntegResourceMappingOfficeVisitorType","OFFICE_VISITOR_CONFIGURATION","extractGenerateCredentialsForVisitorValue","syncVisitorCredentialMapping","isGenerateCredentialEnabled","Boolean","isGenerateCredentialsForVisitorEnabled","createOnly","officeVisitorConfigProfile","db","capIntegResourceMapping","currentConfig","isCurrentGenerateCredentialEnabled","generateCredential","update","updatedAt","insert","CAPABILITY_INTEGRATION_STATUS_ENUM","ACTIVE","IntegrationConfigurationDao","integrationVisitorCredentialMappingDao","integrationSubcapabilityDao","transaction","tx","capabilityIntegrationInsertInput","integrationResult","capabilityIntegration","$returningId","rollback","insertData","createdAt","subcapabilities","subcapabilityId","CAP_INTEG_SUBCAPABILITY_MAPPING_STATUS_ENUM","capIntegSubcapabilityMapping","affectedRows","updateCapabilityIntegrationAccessDetails","expiresInSeconds","expiryAtExpression","sql","inputMap","Map","m","inputKeys","existingMap","e","toDeleteIds","toInsert","deletedBy","inArray","CAPABILITY_TYPE_ENUM","INTEGRATION","getTableColumns","resourceMappingId","resourceMappingConfig","provider","providerIntegrationType","leftJoin","count","MAX_RECORDS_LENGTH","offset","page","sorting","sortBy","by","sortOrder","order","SORTING_ORDER_ENUM","ASC","asc","desc","searchTerm","search","shouldJoinCapability","filters","some","filter","whereConditions","applyFilters","searchPattern","countWhereConditions","countQueryBuilder","as","countQueryWithJoins","countQueryWithPropertyJoin","countQuery","baseQuery","finalQuery","totalCount","records","execute","then","orderBy","filterValues","valuePlaceholders","joinedValues","join","parentConditions","upperValue","toUpperCase","orCondition","or","IntegrationServiceCommunicationTopicDao","upsertTopic","serviceCommunicationTopic","deploymentId","subcapabilityOperation","topicType","topicName","isUniversal","shouldPublish","shouldSubscribe","getServiceCommunicationTopics","topics","IntegrationResourceManagementDao","insertResult","insertedId","insertId","isInserted","checkMappingExists","deleteResult","isSuccess","getCapabilityIntegrationResourceMappingById","IntegrationUserManagementDao","IntegrationOnpremDeploymentDao","addUpdateOnpremDeployment","existingEntry","onPremDeployment","updateOnpremDeployment","addOnpremDeployment","insertedResult","getOnpremDeployment","substituteUrlPlaceholders","replace","matched","hasPersistedIntegrationId","secondsUntil","expiresAt","nowMs","Math","max","floor","getTime","OAUTH_TOKEN_FRESHNESS_BUFFER_MS","isTokenFresh","getIntegrationConfigKmsKeyId","process","env","INTEGRATION_CONFIG_KMS_KEY_ID","delay","ms","setTimeout","getOauthTokenCacheKey","ENV_PREFIX","OAUTH_TOKEN_CACHE_PREFIX","getOauthTokenLockKey","OAUTH_TOKEN_LOCK_PREFIX","OauthTokenCache","redisCacheStoreService","cached","tokenType","refreshToken","token","ttlSeconds","toISOString","del","AuthorizationCodeGrantHandler","mint","tokenUrl","OAUTH_GRANT_TYPE","CLIENT_CREDENTIALS","OAUTH_RFC_GRANT_TYPE","OAUTH_DEFAULT_TOKEN_TYPE","OAUTH_TOKEN_HEADERS","Accept","ClientCredentialsGrantHandler","trafficGatewayService","URL","client_id","credentials","clientId","client_secret","clientSecret","grant_type","scope","integrationContext","authUrl","origin","pathname","access_token","expires_in","token_type","refresh_token","GrantHandlerRegistry","clientCredentialsGrantHandler","authorizationCodeGrantHandler","grantType","resolvePreferredGrant","supportedGrantTypes","OauthProviderDao","findByCapabilityAndProvider","integrationOauthProvider","errorHandler","DATABASE_ERROR_NAMES","DATABASE_ERROR","MODULE_NAME","COMMON","OauthTokenDao","findByCapabilityIntegrationId","integrationOauthToken","upsert","refreshExpiredAt","tokenMetadata","oauthSecretProviderToken","SECRET_PROVIDER","Symbol","OAUTH_LOCK_TTL_SECONDS","OAUTH_LOCK_WAIT_MS","OAUTH_LOCK_MAX_WAIT_MS","OauthTokenManager","sessions","tokenDao","providerDao","tokenCache","grantHandlerRegistry","getValidAccessToken","opts","shouldForceRefresh","forceRefresh","readCachedToken","mintToken","mintWithDistributedLock","storeToken","persistToken","writeMemory","invalidate","lockKey","deadline","ownerId","randomUUID","isAcquired","setIfAbsent","releaseLockIfOwner","existingLock","current","memory","tokenExpiry","redisToken","decryptToken","resolveMintContext","handler","minted","defaultScopes","urlParams","encryptedAccessToken","encryptToken","encryptedRefreshToken","OAuth2Provider","tokenManager","getAuthenticationHeaders","Authorization","testIntegration","IntegrationOauthModule","IntegrationLibsModule","DatastoreModule","MICROSOFT_GRAPH_PATHS","rooms","userCalendarEvents","mailboxEmail","encodeURIComponent","userCalendarEvent","eventId","userCalendarView","startDateTime","endDateTime","subscriptions","subscription","subscriptionId","MICROSOFT_DEFAULT_GRAPH_BASE_URL","MICROSOFT_DEFAULT_AUTH_URL","buildMicrosoftIntegrationConfig","existingBaseUrl","tenantId","MICROSOFT_SECURE_STORAGE","getMicrosoftKmsKeyId","looksLikeStoredSecureConfig","MICROSOFT_CLIENT_CREDENTIALS_GRANT_TYPE","MICROSOFT_DEFAULT_GRAPH_SCOPE","MICROSOFT_DEFAULT_ACCESS_TOKEN_TYPE","MICROSOFT_DEFAULT_HEADERS","MICROSOFT_TOKEN_HEADERS","requireNonEmpty","requireObject","MicrosoftAuthService","oauth2Provider","validateConfig","parseAndValidateConfig","resolvePlaintextConfig","effectiveLoggedInUserId","configForParse","getAccessToken","toMintCredentials","toMicrosoftAccessToken","persistMintedAccessToken","expiresIn","fetchAccessToken","isSuccessful","MicrosoftApiClientService","maxAuthRetryCount","authService","apiCall","executeWithRetry","retryCount","authHeaders","validatedIntegration","hasBody","isUnauthorizedError","GRAPH_RESOURCE_ATTENDEE_TYPE","GRAPH_WEEKDAY","DAY_OF_WEEK","SUN","MON","TUE","WED","THU","FRI","SAT","GRAPH_MONTHLY_INDEX","SCHEDULE_MONTHLY_UNIT","FIRST","SECOND","THIRD","FOURTH","LAST","GRAPH_TYPE_TO_INSTANCE_KIND","singleInstance","SINGLE","seriesMaster","SERIES_MASTER","occurrence","OCCURRENCE","exception","EXCEPTION","toGraphEvent","event","graph","subject","description","notes","contentType","content","bookingStartDateLabel","start","dateTime","toGraphDateTime","bookingStartTimeLabel","isFullDay","timeZone","bookingEndDateLabel","end","bookingEndTimeLabel","isAllDay","isRecurring","schedule","recurrence","scheduleToGraphRecurrence","startDate","endDate","seriesEndDateLabel","attendees","buildGraphAttendees","targetMailbox","spaceMailboxesFromItems","items","seen","isSpace","resources","resource","resourceType","OFFERING_RESOURCE_TYPE","SPACE","email","externalId","add","target","emailAddress","address","requestedForIds","recipientIds","window","range","repeat","SCHEDULE_REPEAT_TYPE","EVERY_DAY","pattern","interval","EVERY_WEEK","daysOfWeek","day","EVERY_MONTH","datesOfMonth","dayOfMonth","monthlyUnit","index","CUSTOM","graphEventToRef","seriesId","seriesMasterId","instanceKind","syncMetadata","omitUndefined","externalEventId","organizerUserEmail","resourceId","excludedDateResults","graphEventsToInstances","startDateLabel","dateLabel","timeLabel","parts","split","hh","mm","ss","fromEntries","entry","MicrosoftCalendarBookingService","microsoftApiClient","createEvent","organizerEmail","roomEmail","pickMailbox","assertMailbox","graphEvent","resolveSkipDatesIfAny","skipDates","organizerUserMailbox","ref","updateEvent","resourceEmail","assertEventId","cancelEvent","deleteGraphEvent","deleteEvent","getEvents","hasWindow","endDateLabel","hasTimeWindow","events","dates","results","date","instanceId","findOccurrenceInstanceId","excluded","find","MicrosoftCalendarResourceService","getResources","room","mapRoom","needle","displayName","capacity","building","floorLabel","GRAPH_SUBSCRIPTION_KNOWN_KEYS","MicrosoftCalendarWebhookService","registerWebhook","assertRequired","notificationUrl","expirationDateTime","changeTypes","graphSubscription","toGraphSubscription","fromGraphSubscription","refreshSubscription","deleteSubscription","changeType","clientState","collectUnknownGraphFields","extras","MICROSOFT_SECURE_STORAGE_OPTIONS","MicrosoftIntegrationConfigurationService","microsoftAuthService","microsoftConfig","existingStored","asString","mergedCredentials","mergedConfig","updateRequest","integrationForUpdate","CommonValidationDatabaseService","provide","useExisting","AdapterFactoryService","getAdapter","adapter","adapterMap","CALENDAR_PROVIDER_ENUM","ICalendarAuthHandler","MicrosoftCalendarAuthHandler","CalendarAuthAdapterFactory","microsoftCalendarAuthHandler","MICROSOFT_365","ICalendarBookingHandler","MicrosoftCalendarBookingHandler","microsoftCalendarBookingService","addCalendarBooking","updateCalendarBooking","cancelCalendarBooking","deleteCalendarBooking","getCalendarBookings","CalendarBookingAdapterFactory","microsoftCalendarBookingHandler","ICalendarIntegrationConfigurationHandler","MicrosoftCalendarIntegrationConfigurationHandler","microsoftIntegrationConfigurationService","CalendarIntegrationConfigurationAdapterFactory","microsoftCalendarIntegrationConfigurationHandler","ICalendarResourceHandler","MicrosoftCalendarResourceHandler","microsoftCalendarResourceService","getCalendarResources","CalendarResourceAdapterFactory","microsoftCalendarResourceHandler","ICalendarWebhookHandler","MicrosoftCalendarWebhookHandler","microsoftCalendarWebhookService","registerCalendarWebhook","refreshCalendarWebhook","deleteCalendarWebhook","CalendarWebhookAdapterFactory","microsoftCalendarWebhookHandler","microsoftHandlers","adapterFactories","IntegrationMicrosoftModule"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGO,IAAMA,aAAN,MAAMA;AAAAA,EAAAA;;;EACTC,QAAAA,GAAmB;AACf,IAAA,OAAO,cAAA;AACX,EAAA;AACJ,CAAA;;;;;;;;;;;;;;;;;ACHO,IAAMC,gBAAN,MAAMA;AAAAA,EAAAA;;;;AACT,EAAA,WAAA,CAA6BC,UAAAA,EAAwB;SAAxBA,UAAAA,GAAAA,UAAAA;AAAyB,EAAA;EAGtDF,QAAAA,GAAmB;AACf,IAAA,OAAO,IAAA,CAAKE,WAAWF,QAAAA,EAAQ;AACnC,EAAA;AACJ,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACQA,SAASG,cAAcC,KAAAA,EAAc;AACjC,EAAA,OAAO,OAAOA,UAAU,QAAA,IAAYA,KAAAA,KAAU,QAAQ,CAACC,KAAAA,CAAMC,QAAQF,KAAAA,CAAAA;AACzE;AAFSD,MAAAA,CAAAA,aAAAA,EAAAA,eAAAA,CAAAA;AAIT,SAASI,uBAAuBH,KAAAA,EAAc;AAC1C,EAAA,OAAOD,aAAAA,CAAcC,KAAAA,CAAAA,IAAUA,KAAAA,CAAMI,gBAAgB,IAAA,IAAQ,OAAOJ,MAAMK,SAAAA,KAAc,QAAA;AAC5F;AAFSF,MAAAA,CAAAA,sBAAAA,EAAAA,wBAAAA,CAAAA;AAIT,SAASG,0BAA0BN,KAAAA,EAAc;AAC7C,EAAA,OAAOD,cAAcC,KAAAA,CAAAA,IAAUA,KAAAA,CAAMI,WAAAA,KAAgB,SAAS,OAAA,IAAWJ,KAAAA;AAC7E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a,GAAG6B;AAC5C,KAAA;AACJ,EAAA;AACJ;;;;;;;;;;;;;;;;;ACFA,IAAMC,iBAAAA,GAAoB;AACtB5B,EAAAA,uCAAAA;AACAe,EAAAA,wCAAAA;AACAM,EAAAA,uCAAAA;AACA1B,EAAAA,oCAAAA;AACAe,EAAAA;;AAGJ,IAAMmB,gBAAAA,GAAmB;AACrBtB,EAAAA,qCAAAA;AACAW,EAAAA,sCAAAA;AACAQ,EAAAA,qCAAAA;AACA9B,EAAAA,kCAAAA;AACAgB,EAAAA;;AAQS5sB,qCAAN,gBAAA,CAAMA;AAAAA,EAAAA;;;AAAW;;;IAJpBC,OAAAA,EAAS;AAAC6c,MAAAA,6BAAAA;AAAuBgR,MAAAA;;IACjC/sB,SAAAA,EAAW;AAAI6sB,MAAAA,GAAAA,iBAAAA;AAAsBC,MAAAA,GAAAA;;IACrC7sB,OAAAA,EAAS;AAAC8b,MAAAA,6BAAAA;AAAuBgR,MAAAA,kCAAAA;AAA+BF,MAAAA,GAAAA,iBAAAA;AAAsBC,MAAAA,GAAAA","file":"index.js","sourcesContent":["import { Injectable } from '@nestjs/common';\n\n@Injectable()\nexport class AppService {\n getHello(): string {\n return 'Hello World!';\n }\n}\n","import { Controller, Get } from '@nestjs/common';\nimport { AppService } from './app.service';\n\n@Controller()\nexport class AppController {\n constructor(private readonly appService: AppService) {}\n\n @Get('integration-libs')\n getHello(): string {\n return this.appService.getHello();\n }\n}\n","import {\n CustomException,\n isMaskedValue,\n LoggerService,\n MASK_STRATEGY_ENUM,\n maskValue,\n SECRET_PROVIDER,\n type SecretProvider,\n SYSTEM_USER_ID,\n} from '@dv4resi/dvss-backend-module-utility';\nimport { Inject, Injectable } from '@nestjs/common';\n\nimport {\n type IIntegrationConfigFieldMetadata,\n type IIntegrationConfigFieldMetadataMap,\n type IIntegrationConfigStructureMetadata,\n} from './types/field-metadata.types';\nimport { type IIntegrationConfigJson, type INonSensitiveStoredField, type ISensitiveStoredField } from './types/stored-config.types';\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isSensitiveStoredField(value: unknown): value is ISensitiveStoredField {\n return isPlainObject(value) && value.isSensitive === true && typeof value.encrypted === 'string';\n}\n\nfunction isNonSensitiveStoredField(value: unknown): value is INonSensitiveStoredField {\n return isPlainObject(value) && value.isSensitive === false && 'value' in value;\n}\n\nfunction toSensitivePlaintext(value: unknown): string {\n if (value === undefined || value === null) {\n return '';\n }\n\n if (typeof value === 'string') {\n return value;\n }\n\n if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {\n return String(value);\n }\n\n throw new CustomException(\n 'BAD_REQUEST',\n 'Sensitive field value must be a string or number',\n 'Sensitive field value must be a primitive on secure storage write',\n );\n}\n\nfunction resolveMaskStrategy(meta: IIntegrationConfigFieldMetadata): MASK_STRATEGY_ENUM {\n const raw = meta.maskStrategy || MASK_STRATEGY_ENUM.LAST_4;\n\n if (Object.values(MASK_STRATEGY_ENUM).includes(raw as MASK_STRATEGY_ENUM)) {\n return raw as MASK_STRATEGY_ENUM;\n }\n\n return MASK_STRATEGY_ENUM.LAST_4;\n}\n\n/**\n * Orchestrates metadata-driven encrypt/mask on write and decrypt/mask on read\n * for capability_integration.config JSON (UIF / integration-libs only).\n */\n@Injectable()\nexport class IntegrationConfigSecureStorageService {\n private readonly fileName = 'integration-config-secure-storage.service.ts';\n\n constructor(\n @Inject(SECRET_PROVIDER) private readonly secretProvider: SecretProvider,\n private readonly logger: LoggerService,\n ) {}\n\n async prepareForWrite(\n rawConfig: IIntegrationConfigJson,\n fieldMetadata: IIntegrationConfigStructureMetadata,\n keyId: string,\n loggedInUserId = SYSTEM_USER_ID,\n ): Promise<IIntegrationConfigJson> {\n this.logger.info(loggedInUserId, this.prepareForWrite.name, this.fileName, 'Preparing integration config for write');\n\n return this.transformSectionForWrite(rawConfig, fieldMetadata, keyId);\n }\n\n prepareForRead(storedConfig: IIntegrationConfigJson): IIntegrationConfigJson {\n return this.transformSectionForRead(storedConfig);\n }\n\n async prepareForBackend(storedConfig: IIntegrationConfigJson, keyId: string, loggedInUserId = SYSTEM_USER_ID): Promise<IIntegrationConfigJson> {\n this.logger.info(loggedInUserId, this.prepareForBackend.name, this.fileName, 'Preparing integration config for backend use');\n\n return this.transformSectionForBackend(storedConfig, keyId);\n }\n\n isMaskedUnchanged(incomingValue: string | undefined | null, storedMasked: string | undefined | null): boolean {\n return isMaskedValue(incomingValue, storedMasked);\n }\n\n async prepareForUpdate(\n incomingConfig: IIntegrationConfigJson,\n existingStoredConfig: IIntegrationConfigJson,\n fieldMetadata: IIntegrationConfigStructureMetadata,\n keyId: string,\n loggedInUserId = SYSTEM_USER_ID,\n ): Promise<IIntegrationConfigJson> {\n this.logger.info(loggedInUserId, this.prepareForUpdate.name, this.fileName, 'Preparing integration config for update');\n\n return this.transformSectionForUpdate(incomingConfig, existingStoredConfig, fieldMetadata, keyId);\n }\n\n private async transformSectionForWrite(\n raw: IIntegrationConfigJson,\n metadata: IIntegrationConfigStructureMetadata,\n keyId: string,\n ): Promise<IIntegrationConfigJson> {\n const result: IIntegrationConfigJson = {};\n\n for (const [key, value] of Object.entries(raw)) {\n const sectionMeta = metadata[key];\n\n if (isPlainObject(value) && isPlainObject(sectionMeta) && this.looksLikeFieldMap(sectionMeta)) {\n result[key] = await this.writeFields(value, sectionMeta as IIntegrationConfigFieldMetadataMap, keyId);\n continue;\n }\n\n if (isPlainObject(value) && isPlainObject(sectionMeta)) {\n result[key] = await this.transformSectionForWrite(value, sectionMeta as IIntegrationConfigStructureMetadata, keyId);\n continue;\n }\n\n result[key] = value;\n }\n\n return result;\n }\n\n private async writeFields(fields: Record<string, unknown>, fieldMap: IIntegrationConfigFieldMetadataMap, keyId: string): Promise<Record<string, unknown>> {\n const out: Record<string, unknown> = {};\n\n for (const [fieldName, fieldValue] of Object.entries(fields)) {\n if (!(fieldName in fieldMap)) {\n out[fieldName] = fieldValue;\n continue;\n }\n\n const meta = fieldMap[fieldName];\n\n if (meta.sensitive) {\n const plaintext = toSensitivePlaintext(fieldValue);\n\n if (!plaintext) {\n throw new CustomException(\n 'BAD_REQUEST',\n `Sensitive field \"${fieldName}\" cannot be empty`,\n `Sensitive field \"${fieldName}\" cannot be empty on prepareForWrite`,\n );\n }\n\n const encrypted = await this.secretProvider.encrypt(plaintext, keyId);\n const masked = maskValue(plaintext, resolveMaskStrategy(meta));\n out[fieldName] = { encrypted, masked, isSensitive: true } satisfies ISensitiveStoredField;\n } else {\n out[fieldName] = { value: fieldValue, isSensitive: false } satisfies INonSensitiveStoredField;\n }\n }\n\n return out;\n }\n\n private transformSectionForRead(stored: IIntegrationConfigJson): IIntegrationConfigJson {\n const result: IIntegrationConfigJson = {};\n\n for (const [key, value] of Object.entries(stored)) {\n if (isSensitiveStoredField(value)) {\n result[key] = value.masked;\n continue;\n }\n\n if (isNonSensitiveStoredField(value)) {\n result[key] = value.value;\n continue;\n }\n\n if (isPlainObject(value)) {\n result[key] = this.transformSectionForRead(value);\n continue;\n }\n\n result[key] = value;\n }\n\n return result;\n }\n\n private async transformSectionForBackend(stored: IIntegrationConfigJson, keyId: string): Promise<IIntegrationConfigJson> {\n const result: IIntegrationConfigJson = {};\n\n for (const [key, value] of Object.entries(stored)) {\n if (isSensitiveStoredField(value)) {\n result[key] = await this.secretProvider.decrypt(value.encrypted, keyId);\n continue;\n }\n\n if (isNonSensitiveStoredField(value)) {\n result[key] = value.value;\n continue;\n }\n\n if (isPlainObject(value)) {\n result[key] = await this.transformSectionForBackend(value, keyId);\n continue;\n }\n\n result[key] = value;\n }\n\n return result;\n }\n\n private async transformSectionForUpdate(\n incoming: IIntegrationConfigJson,\n existing: IIntegrationConfigJson,\n metadata: IIntegrationConfigStructureMetadata,\n keyId: string,\n ): Promise<IIntegrationConfigJson> {\n const result: IIntegrationConfigJson = { ...existing };\n\n for (const [key, incomingValue] of Object.entries(incoming)) {\n const sectionMeta = metadata[key];\n const existingValue = existing[key];\n\n if (isPlainObject(incomingValue) && isPlainObject(sectionMeta) && this.looksLikeFieldMap(sectionMeta)) {\n result[key] = await this.updateFields(\n incomingValue,\n isPlainObject(existingValue) ? existingValue : {},\n sectionMeta as IIntegrationConfigFieldMetadataMap,\n keyId,\n );\n continue;\n }\n\n if (isPlainObject(incomingValue) && isPlainObject(sectionMeta)) {\n result[key] = await this.transformSectionForUpdate(\n incomingValue,\n isPlainObject(existingValue) ? existingValue : {},\n sectionMeta as IIntegrationConfigStructureMetadata,\n keyId,\n );\n continue;\n }\n\n result[key] = incomingValue;\n }\n\n return result;\n }\n\n private async updateFields(\n incoming: Record<string, unknown>,\n existing: Record<string, unknown>,\n fieldMap: IIntegrationConfigFieldMetadataMap,\n keyId: string,\n ): Promise<Record<string, unknown>> {\n const out: Record<string, unknown> = { ...existing };\n\n for (const [fieldName, incomingValue] of Object.entries(incoming)) {\n const existingField = existing[fieldName];\n\n if (!(fieldName in fieldMap)) {\n out[fieldName] = incomingValue;\n continue;\n }\n\n const meta = fieldMap[fieldName];\n\n if (meta.sensitive) {\n const existingSensitive = isSensitiveStoredField(existingField) ? existingField : undefined;\n const incomingString = toSensitivePlaintext(incomingValue);\n\n if (existingSensitive && this.isMaskedUnchanged(incomingString, existingSensitive.masked)) {\n out[fieldName] = existingSensitive;\n continue;\n }\n\n if (!incomingString) {\n throw new CustomException(\n 'BAD_REQUEST',\n `Sensitive field \"${fieldName}\" cannot be empty`,\n `Sensitive field \"${fieldName}\" cannot be empty on prepareForUpdate`,\n );\n }\n\n if (!existingSensitive && incomingString.includes('*') && incomingString.replaceAll('*', '').length <= 4) {\n throw new CustomException(\n 'BAD_REQUEST',\n `Sensitive field \"${fieldName}\" appears to be a masked value; provide the real secret`,\n `Sensitive field \"${fieldName}\" looks masked with no prior stored ciphertext`,\n );\n }\n\n const encrypted = await this.secretProvider.encrypt(incomingString, keyId);\n const masked = maskValue(incomingString, resolveMaskStrategy(meta));\n out[fieldName] = { encrypted, masked, isSensitive: true } satisfies ISensitiveStoredField;\n } else {\n out[fieldName] = { value: incomingValue, isSensitive: false } satisfies INonSensitiveStoredField;\n }\n }\n\n return out;\n }\n\n private looksLikeFieldMap(sectionMeta: Record<string, unknown>): boolean {\n const values = Object.values(sectionMeta);\n\n if (values.length === 0) {\n return false;\n }\n\n return values.every((v) => isPlainObject(v) && typeof (v as { sensitive?: unknown }).sensitive === 'boolean');\n }\n}\n","/**\n * HTTP method constants\n */\nexport enum HTTP_METHOD {\n GET = 'GET',\n POST = 'POST',\n PUT = 'PUT',\n DELETE = 'DELETE',\n PATCH = 'PATCH',\n}\n","import { LoggerService, SYSTEM_USER_ID } from '@dv4resi/dvss-backend-module-utility';\nimport { Injectable } from '@nestjs/common';\n\n/**\n * Request logging data structure\n */\nexport interface IIntegrationRequestLog {\n integrationId?: bigint | string;\n method: string;\n url: string;\n headers?: Record<string, string>;\n requestBody?: unknown;\n responseBody?: unknown;\n statusCode?: number;\n duration?: number;\n loggedInUserId?: bigint;\n timestamp?: Date;\n error?: unknown;\n}\n\nconst REDACTED = '***REDACTED***';\n\n/** Header names (case-insensitive) that must never appear in logs. */\nconst SENSITIVE_HEADER_KEYS = new Set(['authorization', 'api-key', 'apikey', 'x-api-key', 'cookie']);\n\n/**\n * Body / form field names (case-insensitive) that must never appear in logs.\n * Covers OAuth token responses and common credential fields.\n */\nconst SENSITIVE_BODY_KEYS = new Set([\n 'access_token',\n 'refresh_token',\n 'id_token',\n 'token',\n 'client_secret',\n 'clientsecret',\n 'password',\n 'secret',\n 'api_key',\n 'apikey',\n 'authorization',\n]);\n\n/**\n * Service to expose the functionality to log integration requests\n * Uses LoggerService from @dv4resi/dvss-backend-module-utility\n */\n@Injectable()\nexport class IntegrationRequestLoggerService {\n private readonly className = IntegrationRequestLoggerService.name;\n\n constructor(private readonly logger: LoggerService) {}\n\n /**\n * Log integration request (before making the API call)\n *\n * @param logData - The request log data to be logged\n */\n logRequest(logData: IIntegrationRequestLog): void {\n const { loggedInUserId, method, url, headers, requestBody } = logData;\n\n this.logger.info(loggedInUserId || SYSTEM_USER_ID, this.logRequest.name, this.className, `Integration API Request: ${method} ${url}`, {\n integrationId: logData.integrationId,\n method,\n url,\n headers: this.sanitizeHeaders(headers),\n requestBody: this.sanitizePayload(requestBody),\n timestamp: logData.timestamp || new Date(),\n });\n }\n\n /**\n * Log integration response (after successful API call)\n *\n * @param logData - The response log data to be logged\n */\n logResponse(logData: IIntegrationRequestLog): void {\n const { loggedInUserId, method, url, statusCode, duration, responseBody } = logData;\n\n this.logger.info(\n loggedInUserId || SYSTEM_USER_ID,\n this.logResponse.name,\n this.className,\n `Integration API Response: ${method} ${url} - ${statusCode} (${duration}ms)`,\n {\n integrationId: logData.integrationId,\n method,\n url,\n statusCode,\n duration,\n responseBody: this.sanitizePayload(responseBody),\n timestamp: logData.timestamp || new Date(),\n },\n );\n }\n\n /**\n * Log integration error (after failed API call)\n *\n * @param logData - The error log data to be logged\n */\n logError(logData: IIntegrationRequestLog): void {\n const { loggedInUserId, method, url, statusCode, duration, error, responseBody } = logData;\n\n this.logger.error(\n loggedInUserId || SYSTEM_USER_ID,\n this.logError.name,\n this.className,\n `Integration API Error: ${method} ${url} - ${statusCode || 'N/A'} (${duration || 0}ms)`,\n {\n integrationId: logData.integrationId,\n method,\n url,\n statusCode,\n duration,\n error: this.sanitizePayload(error),\n responseBody: this.sanitizePayload(responseBody),\n timestamp: logData.timestamp || new Date(),\n },\n );\n }\n\n /**\n * Log integration request (legacy method for backward compatibility)\n * This method determines whether to log as request, response, or error based on the logData\n *\n * @param logData - The request log data to be logged\n */\n logIntegrationRequest(logData: IIntegrationRequestLog): void {\n if (logData.error) {\n this.logError(logData);\n } else if (logData.statusCode && logData.responseBody !== undefined) {\n this.logResponse(logData);\n } else {\n this.logRequest(logData);\n }\n }\n\n /**\n * Sanitize headers to remove sensitive information\n *\n * @param headers - The headers to sanitize\n * @returns Sanitized headers\n */\n private sanitizeHeaders(headers?: Record<string, string>): Record<string, string> | undefined {\n if (!headers) {\n return undefined;\n }\n\n const sanitized = { ...headers };\n\n for (const key of Object.keys(sanitized)) {\n if (SENSITIVE_HEADER_KEYS.has(key.toLowerCase())) {\n sanitized[key] = REDACTED;\n }\n }\n\n return sanitized;\n }\n\n /**\n * Redact sensitive fields from request/response/error payloads before logging.\n * Handles plain objects, arrays, and `application/x-www-form-urlencoded` strings.\n */\n private sanitizePayload(payload: unknown, depth = 0): unknown {\n if (payload == null || depth > 8) {\n return payload;\n }\n\n if (typeof payload === 'string') {\n return this.sanitizeFormEncodedString(payload);\n }\n\n if (Array.isArray(payload)) {\n return payload.map((item) => this.sanitizePayload(item, depth + 1));\n }\n\n if (typeof payload === 'object') {\n // Avoid cloning Error prototypes into unstructured bags; redact known message fields only.\n if (payload instanceof Error) {\n return {\n name: payload.name,\n message: payload.message,\n };\n }\n\n const record = payload as Record<string, unknown>;\n const sanitized: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(record)) {\n if (SENSITIVE_BODY_KEYS.has(key.toLowerCase())) {\n sanitized[key] = REDACTED;\n continue;\n }\n\n sanitized[key] = this.sanitizePayload(value, depth + 1);\n }\n\n return sanitized;\n }\n\n return payload;\n }\n\n /**\n * Redacts known secret keys in URL-encoded form bodies (e.g. OAuth client_credentials).\n * Non-form strings are returned unchanged.\n */\n private sanitizeFormEncodedString(value: string): string {\n if (!value.includes('=')) {\n return value;\n }\n\n try {\n const params = new URLSearchParams(value);\n let didMutate = false;\n\n for (const key of [...params.keys()]) {\n if (SENSITIVE_BODY_KEYS.has(key.toLowerCase())) {\n params.set(key, REDACTED);\n didMutate = true;\n }\n }\n\n return didMutate ? params.toString() : value;\n } catch {\n return value;\n }\n }\n}\n","import { Injectable } from '@nestjs/common';\n\n/**\n * Service to expose the functionality to validate and enforce rate limits\n */\n@Injectable()\nexport class RateLimiterService {\n /**\n * Validate and enforce rate limit\n *\n * @returns Promise resolving when the rate limit is validated and enforced\n */\n async validateAndEnforceRateLimit(): Promise<void> {\n // TODO Get the rate limit from the configuration store\n // TODO Validate the rate limit\n // TODO Enforce the rate limit\n // TODO If the rate limit is exceeded, throw an error\n // TODO If the rate limit is not exceeded, pass the request to the traffic gateway\n }\n}\n","import { HttpService } from '@nestjs/axios';\nimport { Injectable } from '@nestjs/common';\nimport { firstValueFrom } from 'rxjs';\nimport { HTTP_METHOD } from '../constants/http.constant';\nimport { IntegrationRequestLoggerService, type IIntegrationRequestLog } from '../logging/request-logger.service';\nimport { RateLimiterService } from '../rate-limiter/rate-limiter.service';\nimport { IValidatedCapabilityIntegration } from '../../integration-common-utils';\n\n/**\n * Request configuration for API calls\n */\nexport interface IApiCallRequest<TBody = unknown> {\n apiMethod: HTTP_METHOD;\n url: string;\n baseUrl: string;\n headers?: Record<string, string>;\n body?: TBody;\n responseType?: 'json' | 'text' | 'blob' | 'arraybuffer';\n headerType?: 'json' | 'xml';\n}\n\n/**\n * Request context for deriving rate limits and other settings\n */\nexport interface IIntegrationRequestContext {\n projectId?: bigint;\n propertyId?: bigint;\n capabilityId?: bigint;\n [key: string]: unknown;\n}\n\n/**\n * Service to expose the functionality to execute integration requests\n * This service provides a generic API call method that can be used for any third-party integration\n */\n@Injectable()\nexport class TrafficGatewayService {\n constructor(\n private readonly httpService: HttpService,\n private readonly requestLogger: IntegrationRequestLoggerService,\n private readonly rateLimiter: RateLimiterService,\n ) {}\n\n /**\n * Execute a generic API call to a third-party integration\n *\n * @template TResponse - The expected response type\n * @template TRequestBody - The request body type (optional)\n * @param request - The API call request configuration\n * @param integration - The integration configuration\n * @param loggedInUserId - Optional user ID for logging purposes\n * @param _context - Optional context for deriving rate limits and other settings (projectId, propertyId, etc.)\n * @returns Promise resolving to the API response data\n * @throws Error if the request fails or rate limit is exceeded\n */\n async executeIntegrationRequest<TResponse = unknown, TRequestBody = unknown>(\n request: IApiCallRequest<TRequestBody>,\n integration: IValidatedCapabilityIntegration,\n loggedInUserId?: bigint,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _context?: IIntegrationRequestContext,\n ): Promise<TResponse> {\n const startTime = Date.now();\n\n try {\n // Prepare headers with authorization\n const headers = this.prepareHeaders(request);\n\n // Prepare request configuration\n const requestConfig = this.prepareRequestConfig(request, headers);\n\n // Rate limiting check with context for deriving rate limits\n await this.rateLimiter.validateAndEnforceRateLimit();\n\n // Construct full URL with proper handling of trailing slashes\n const fullUrl = this.constructFullUrl(request.baseUrl, request.url);\n\n // Prepare log data with full URL and headers for request logging\n const logData: IIntegrationRequestLog = {\n integrationId: integration.id,\n method: request.apiMethod,\n url: fullUrl,\n headers,\n requestBody: request.body,\n loggedInUserId,\n timestamp: new Date(),\n };\n\n // Log the request before making the API call\n this.requestLogger.logRequest(logData);\n\n // Execute the HTTP request based on method\n const apiResponse = await this.executeHttpRequest<TResponse>(request, fullUrl, requestConfig);\n\n const duration = Date.now() - startTime;\n const responseData = apiResponse.data;\n\n // Log the successful response\n this.requestLogger.logResponse({\n ...logData,\n responseBody: responseData,\n statusCode: apiResponse.status,\n duration,\n });\n\n return responseData;\n } catch (error) {\n const duration = Date.now() - startTime;\n const errorDetails = this.extractErrorDetails(error);\n\n // Get base URL safely for error logging\n const baseUrl = request.baseUrl;\n const fullUrl = this.constructFullUrl(baseUrl, request.url);\n\n // Log the failed request with API reason (message/error_description) and response body\n this.requestLogger.logError({\n integrationId: integration.id,\n method: request.apiMethod,\n url: fullUrl,\n headers: request.headers,\n requestBody: request.body,\n loggedInUserId,\n timestamp: new Date(),\n error: errorDetails.apiMessage,\n statusCode: errorDetails.statusCode,\n duration,\n responseBody: errorDetails.responseBody,\n });\n\n // Attach apiMessage and statusCode so any integration (Trybe, etc.) can map to its own exceptions\n const err = error as Error & { apiMessage?: string; statusCode?: number };\n err.apiMessage = errorDetails.message;\n err.statusCode = errorDetails.statusCode;\n err.message = errorDetails.apiMessage;\n\n throw error;\n }\n }\n\n /**\n * Prepare headers for the API request\n *\n * @private\n * @param request - The API call request configuration\n * @param apiKey - The API key for authorization\n * @returns Prepared headers object\n */\n private prepareHeaders(request: IApiCallRequest): Record<string, string> {\n request.headerType = request.headerType || 'json';\n\n const headers: Record<string, string> = {\n ...(request.headers || {}),\n };\n\n // Set default content type if not provided for methods that send body\n if (\n !headers['Content-Type'] &&\n request.headerType === 'json' &&\n (request.apiMethod === HTTP_METHOD.POST || request.apiMethod === HTTP_METHOD.PUT || request.apiMethod === HTTP_METHOD.PATCH)\n ) {\n headers['Content-Type'] = 'application/json';\n }\n\n // Set default accept header if not provided\n if (!headers['Accept'] && request.headerType === 'json') {\n headers['Accept'] = 'application/json';\n }\n\n return headers;\n }\n\n /**\n * Prepare request configuration object\n *\n * @private\n * @param request - The API call request configuration\n * @param headers - Prepared headers\n * @returns Request configuration object\n */\n private prepareRequestConfig(request: IApiCallRequest, headers: Record<string, string>): Record<string, unknown> {\n const requestConfig: Record<string, unknown> = {\n headers,\n };\n\n if (request.responseType) {\n requestConfig.responseType = request.responseType;\n }\n\n return requestConfig;\n }\n\n /**\n * Construct full URL from base URL and request URL\n * Handles trailing slashes properly\n *\n * @private\n * @param baseUrl - The base URL from platform config\n * @param requestUrl - The request URL path\n * @returns Constructed full URL\n */\n private constructFullUrl(baseUrl: string, requestUrl: string): string {\n const normalizedBaseUrl = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;\n const normalizedRequestUrl = requestUrl.startsWith('/') ? requestUrl : `/${requestUrl}`;\n\n return `${normalizedBaseUrl}${normalizedRequestUrl}`;\n }\n\n /**\n * Execute HTTP request based on the method\n *\n * @private\n * @template TResponse - The expected response type\n * @param request - The API call request configuration\n * @param fullUrl - The full URL to make the request to\n * @param requestConfig - The request configuration\n * @returns Promise resolving to the HTTP response\n * @throws Error if the HTTP method is unsupported\n */\n private async executeHttpRequest<TResponse>(request: IApiCallRequest, fullUrl: string, requestConfig: Record<string, unknown>) {\n switch (request.apiMethod) {\n case HTTP_METHOD.GET: {\n return await firstValueFrom(this.httpService.get<TResponse>(fullUrl, requestConfig));\n }\n case HTTP_METHOD.POST: {\n return await firstValueFrom(this.httpService.post<TResponse>(fullUrl, request.body, requestConfig));\n }\n case HTTP_METHOD.PUT: {\n return await firstValueFrom(this.httpService.put<TResponse>(fullUrl, request.body, requestConfig));\n }\n case HTTP_METHOD.PATCH: {\n return await firstValueFrom(this.httpService.patch<TResponse>(fullUrl, request.body, requestConfig));\n }\n case HTTP_METHOD.DELETE: {\n return await firstValueFrom(this.httpService.delete<TResponse>(fullUrl, requestConfig));\n }\n default: {\n throw new Error(`Unsupported HTTP method: ${String(request.apiMethod)}`);\n }\n }\n }\n\n /**\n * Extract error details from an error object (e.g. Axios error).\n * Provider-agnostic: derives apiMessage from common response shapes so any integration\n * (Trybe, OAuth, REST, etc.) gets a readable reason. Callers can use statusCode and\n * responseBody to map to their own exceptions (e.g. 404 -> RESOURCE_NOT_FOUND).\n *\n * Supported response.data fields (first string wins): message, error_description,\n * error, detail, msg.\n *\n * @private\n * @param error - The error object\n * @returns Extracted error details including apiMessage for logging and callers\n */\n private extractErrorDetails(error: unknown): {\n message?: string;\n statusCode?: number;\n responseBody?: unknown;\n apiMessage: string;\n } {\n const errorObject = error as {\n status?: number;\n response?: { data?: unknown; status?: number };\n message?: string;\n };\n\n const responseData = errorObject.response?.data;\n const data = typeof responseData === 'object' && responseData !== null ? (responseData as Record<string, unknown>) : undefined;\n\n const firstString = (...keys: string[]): string | undefined => {\n for (const k of keys) {\n const v = data?.[k];\n if (typeof v === 'string' && v.trim()) return v;\n }\n return undefined;\n };\n\n const apiMessage = firstString('message', 'error_description', 'error', 'detail', 'msg') || errorObject.message || 'API error';\n\n return {\n message: errorObject.message,\n statusCode: errorObject.status || errorObject.response?.status,\n responseBody: errorObject.response?.data,\n apiMessage,\n };\n }\n}\n","/**\n * Load environment variables from root .env file\n * This must be imported/required before any other modules that depend on environment variables\n * (e.g., @dv4resi/dvss-backend-module-utility checks env vars at module import time)\n */\nimport { config } from 'dotenv';\nimport { resolve } from 'path';\n\n// Resolve path to root .env file\n// From src/: ../../../\n// From dist/: ../../../\nconst rootEnvPath = resolve(__dirname, '../../../.env');\nconfig({ path: rootEnvPath });\n","// Load environment variables BEFORE importing modules that check env vars at import time\nimport { LoggerModule, SecureStorageModule } from '@dv4resi/dvss-backend-module-utility';\nimport { HttpModule } from '@nestjs/axios';\nimport { Module } from '@nestjs/common';\nimport { ConfigModule } from '@nestjs/config';\nimport { resolve } from 'path';\nimport * as https from 'node:https';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { IntegrationConfigSecureStorageService } from './integration-common-utils/secure-storage';\nimport { TrafficGatewayService } from './integration-traffic-router/gateway/traffic-gateway.service';\nimport { IntegrationRequestLoggerService } from './integration-traffic-router/logging/request-logger.service';\nimport { RateLimiterService } from './integration-traffic-router/rate-limiter/rate-limiter.service';\nimport './load-env';\n\n@Module({\n imports: [\n // Load environment variables from root .env file\n ConfigModule.forRoot({\n envFilePath: resolve(__dirname, '../../../.env'),\n isGlobal: true,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }) as any,\n HttpModule.register({\n global: true,\n httpsAgent: new https.Agent({ rejectUnauthorized: false }),\n }),\n LoggerModule,\n SecureStorageModule,\n ],\n controllers: [AppController],\n providers: [AppService, TrafficGatewayService, IntegrationRequestLoggerService, RateLimiterService, IntegrationConfigSecureStorageService],\n exports: [TrafficGatewayService, IntegrationRequestLoggerService, RateLimiterService, SecureStorageModule, IntegrationConfigSecureStorageService],\n})\nexport class AppModule {}\n","export const TRAFFIC_ROUTER_CONFIGURATION_STORE_KEY = 'traffic-router-configuration-store';\n","import { ICapabilityIntegration, IValidatedCapabilityIntegration } from '../../../integration-common-utils';\n\n/**\n * Base abstract class for integration authentication operations\n * Provides a foundation for implementing authentication functionality\n * for different integration providers\n *\n * This class should be extended by concrete implementations that provide\n * specific authentication operations for different integration systems\n */\nexport abstract class BaseAuth {\n /**\n * Abstract method to validate integration configuration\n * Must be implemented by concrete classes\n *\n * @param config - Integration configuration object\n * @param loggedInUserId - User ID for logging\n * @returns Promise resolving to validated configuration\n */\n abstract validateConfig(integration: ICapabilityIntegration, loggedInUserId: bigint): IValidatedCapabilityIntegration;\n\n /**\n * Abstract method to test integration connection\n * Must be implemented by concrete classes\n *\n * @param integration - Integration object with configuration\n * @param loggedInUserId - User ID for logging\n * @returns Promise resolving when test is completed\n */\n abstract testIntegration(integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<boolean>;\n\n /**\n * Abstract method to fetch an access token from the integration provider.\n * Must be implemented by concrete classes.\n *\n * @param integration - Integration object with configuration\n * @param loggedInUserId - User ID for logging\n * @returns Promise resolving to the access token string\n */\n abstract fetchAccessToken(integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<string>;\n}\n","/**\n * System-level credit and customer credits response types.\n * Aligned with payment MS GetUserCredits / Credit shape for consumption across the system.\n * Integrations map their provider-specific responses to these types.\n */\n\n/** Credit type values aligned with payment MS CREDIT_TYPE_ENUM */\nexport enum CREDIT_TYPE_ENUM {\n COUPON = 'COUPON',\n AMOUNT = 'AMOUNT',\n}\n\n/** Credit status values aligned with payment MS CREDIT_STATUS_ENUM */\nexport enum CREDIT_STATUS_ENUM {\n ACTIVE = 'ACTIVE',\n REDEEMED = 'REDEEMED',\n EXPIRED = 'EXPIRED',\n REVOKED = 'REVOKED',\n}\n\nexport enum CREDIT_FILTER_BY_ENUM {\n TYPE = 'TYPE',\n STATUS = 'STATUS',\n}\n\n/**\n * A single credit in the system format.\n * Matches the shape expected by payment MS Credit (plain interface, no GraphQL).\n * Fields not provided by an integration (e.g. id, projectId) are optional.\n */\nexport interface ICredit {\n id?: bigint;\n name: string;\n description?: string;\n type: CREDIT_TYPE_ENUM;\n status: CREDIT_STATUS_ENUM;\n projectId?: number;\n propertyId?: number;\n externalId?: string;\n expiresAt?: Date;\n expiresDate?: string;\n startsAt?: Date;\n startDate?: string;\n value?: string;\n capabilityIntegrationId?: bigint;\n quantity?: number;\n meta?: Record<string, unknown>;\n}\n\n/**\n * System response for customer credits.\n * Matches payment MS GetUserCredits: { totalCount, records }.\n */\nexport interface IGetCustomerCreditsRequestFilters {\n by: CREDIT_FILTER_BY_ENUM;\n values: string[];\n}\n\nexport interface IGetCustomerCreditsRequestOptions {\n filters?: IGetCustomerCreditsRequestFilters[];\n page?: number;\n count?: number;\n}\n\nexport interface IGetCustomerCreditsRequest {\n customerId: string;\n options?: IGetCustomerCreditsRequestOptions;\n}\n","import { DAY_OF_WEEK, OFFERING_RESOURCE_TYPE, STATUS } from '@dv4resi/dvss-backend-module-datastore/dist/datastore/models';\nimport { IMedia } from '@dv4resi/dvss-backend-module-utility';\n\nexport enum BOOKABLE_ITEM_TYPE_ENUM {\n APPOINTMENT = 'APPOINTMENT',\n SESSION = 'SESSION',\n COURSE = 'COURSE',\n}\n\nexport enum BOOKABLE_ITEM_STATUS_ENUM {\n ACTIVE = 'ACTIVE',\n INACTIVE = 'INACTIVE',\n}\n\nexport interface IBookableItemPriceMeta {\n id?: bigint;\n externalId?: string;\n status?: BOOKABLE_ITEM_STATUS_ENUM;\n price: number;\n currency: string;\n configuredForDays?: DAY_OF_WEEK[];\n config?: Record<string, unknown>;\n}\n\nexport interface IBookableItemPrice {\n id?: bigint;\n label?: string;\n currency: string;\n price: number;\n externalResourceId?: string;\n durationInMinute?: number;\n configuredForDays?: DAY_OF_WEEK[];\n pricesMeta?: IBookableItemPriceMeta[];\n config?: Record<string, unknown>;\n}\n\nexport interface IBookableItemMedia {\n id?: string;\n url?: string;\n originalUrl?: string;\n fileName?: string;\n mimeType?: string;\n thumbnailUrl?: string;\n}\n\nexport interface IBookableItem {\n id?: bigint;\n externalId: string;\n name: string;\n description?: string;\n type: BOOKABLE_ITEM_TYPE_ENUM;\n status?: BOOKABLE_ITEM_STATUS_ENUM;\n icon?: IBookableItemMedia;\n primaryAsset?: IBookableItemMedia;\n prices?: IBookableItemPrice[];\n linkedBookableItems?: IBookableItem[];\n updatedAt?: Date;\n createdAt?: Date;\n meta?: Record<string, unknown>;\n}\n\nexport interface IBookableItemCategory {\n id?: bigint;\n externalId: string;\n name: string;\n description?: string;\n meta?: Record<string, unknown>;\n}\n\nexport interface IWellnessManagementRequestOptions {\n page?: number;\n count?: number;\n}\n\nexport interface IGetAppointmentsRequest {\n shouldFetchAllAppointments: boolean;\n practitionerIds?: string[];\n options?: IWellnessManagementRequestOptions;\n}\n\nexport interface IGetSessionsRequest {\n shouldFetchAllSessions: boolean;\n practitionerIds?: string[];\n options?: IWellnessManagementRequestOptions;\n}\n\nexport interface IGetCoursesRequest {\n shouldFetchAllCourses: boolean;\n options?: IWellnessManagementRequestOptions;\n}\n\nexport interface IGetCategoriesRequest {\n shouldFetchAllCategories: boolean;\n options?: IWellnessManagementRequestOptions;\n}\n\nexport interface IGetBookableItemsFromCreditRequest {\n couponCodeId: string;\n options?: IWellnessManagementRequestOptions;\n}\n\nexport interface IFetchOfferingAvailabilityRequest {\n externalOfferingBookableItemId: string;\n dateTimeFrom: Date;\n dateTimeTo: Date;\n}\n\nexport interface IAvailableTimeSlot {\n fromTime: string;\n toTime: string;\n meta?: unknown;\n}\n\nexport interface IAvailableDateWithSlots {\n date: Date;\n meta?: unknown;\n time: IAvailableTimeSlot[];\n}\n\nexport interface IGetAvailableDatesAndTimeSlotsResponse {\n dates: IAvailableDateWithSlots[];\n}\n\nexport interface IOrderGuest {\n id: string;\n name?: string;\n}\n\nexport interface IGetOrderResponse {\n orderId: string;\n guests: IOrderGuest[];\n}\n\nexport interface ICreateOrderRequest {\n bookingStartTime: Date;\n durationInMinutes?: number;\n meta?: Record<string, unknown>;\n bookableItems: Pick<IBookableItem, 'externalId' | 'type'>[];\n offeringResources: Pick<IOfferingResource, 'externalId'>[];\n currencyMultiplier: number;\n customerId: string;\n customerCreditId?: string;\n}\n\nexport interface ICreateOrderResponse {\n externalBookingId: string;\n items: (Pick<IBookableItem, 'externalId' | 'type' | 'name'> & {\n totalPrice?: number;\n primaryAsset?: IMedia;\n meta: {\n basketItemId: string;\n };\n })[];\n}\n\nexport interface IAddItemToOrderItemConfig {\n offeringId: string;\n offeringType: BOOKABLE_ITEM_TYPE_ENUM;\n guestIds: string[];\n practitionerIds: string[];\n durationMinutes?: number;\n timeIso?: string;\n sessionId?: string;\n}\n\nexport interface IAddItemToOrderRequest {\n orderId: string;\n item: IAddItemToOrderItemConfig;\n}\n\nexport interface IAddItemToOrderResponse {\n name?: string;\n netTotal?: number;\n}\n\nexport interface IAddPaymentToOrderRequest {\n orderId: string;\n amount: number;\n paymentTypeId: string;\n}\n\nexport interface IOfferingResourceMedia {\n meta?: Record<string, unknown>;\n provider?: string;\n}\n\n/**\n * System response type for practitioners/resources aligned with GQL OfferingResource.\n * Union fields map from integration; integration-specific fields go in meta.\n */\nexport interface IOfferingResource {\n id?: bigint;\n externalId: string;\n name: string;\n description?: string;\n type: OFFERING_RESOURCE_TYPE;\n status: STATUS;\n media?: IOfferingResourceMedia;\n meta?: Record<string, unknown>;\n bookableItems?: unknown[];\n createdAt?: Date;\n createdBy?: bigint;\n deletedAt?: Date;\n deletedBy?: bigint;\n isCurrentlyUnavailable?: boolean;\n occurrences?: unknown[];\n offeringId?: bigint;\n priceSummary?: string;\n projectId?: number;\n quantity?: number;\n unavailability?: unknown[];\n updatedAt?: Date;\n updatedBy?: bigint;\n}\n\nexport interface IGetPractitionersRequest {\n shouldFetchAllPractitioners: boolean;\n options?: IWellnessManagementRequestOptions;\n}\n\nexport interface IUpdateOrderRequest {\n orderId: string;\n timezone: string;\n item: {\n externalId: string;\n type: BOOKABLE_ITEM_TYPE_ENUM;\n };\n sessionId?: string;\n durationInMinutes?: number;\n bookingStartDateLabel?: string;\n bookingStartTimeLabel?: string;\n}\n\nexport interface IUpdateOrderResponse {\n success: boolean;\n data?: { id: string };\n}\n","import { schema, SORTING_ORDER_ENUM } from '@dv4resi/dvss-backend-module-datastore';\nimport { ICapabilityIntegration, ICapabilityIntegrationConfig } from './capability-integration.model';\nimport { ITransactionNumberSeries } from './miscellaneous.model';\nimport { ICurrency } from './customer-payment-management.model';\n\nexport interface InvoiceAccessDetails {\n expiryAt?: string;\n accessToken?: string;\n tokenType?: string;\n}\n\nexport interface AccountConfig {\n /** List of available payment methods */\n availablePaymentMethods?: unknown[];\n\n isTaxInclusive?: boolean;\n\n transactionNumberSeries?: ITransactionNumberSeries[];\n}\n\ninterface IIntegrationConfig {\n clientId: string;\n clientSecret: string;\n organizationId: string;\n refreshToken: string;\n}\nexport interface IInvoiceCapabilityIntegrationConfig extends ICapabilityIntegrationConfig {\n accessDetails?: InvoiceAccessDetails;\n accountConfig?: AccountConfig;\n integrationConfig?: IIntegrationConfig;\n}\n\nexport type IInvoiceCapabilityIntegration = Omit<ICapabilityIntegration, 'id' | 'providerId' | 'capabilityId' | 'projectId' | 'config'> &\n typeof schema.capabilityIntegration.$inferSelect & {\n config?: IInvoiceCapabilityIntegrationConfig;\n };\n\nexport interface IInvoiceIntegrationRequest {\n capabilityIntegration: IInvoiceCapabilityIntegration;\n loggedInUserId: bigint;\n}\n\nexport interface IAccountingAPIResponse {\n /** Response code (0 for success) */\n code: number;\n\n /** Response message */\n message: string;\n}\n\nexport interface IInvoiceResponse {\n invoice: IInvoice;\n}\n\nexport interface IInvoice {\n is_inclusive_tax?: boolean;\n invoice_id: string;\n invoice_number: string;\n date: Date; // ISO date string\n due_date: string; // ISO date string\n customer_id: string;\n customer_name?: string;\n salesperson_name?: string;\n email?: string;\n currency_id?: string;\n currency_code: string;\n currency_symbol?: string;\n currency_name_formatted?: string;\n status: string; // e.g., paid\n credits_applied?: number;\n payment_terms?: number;\n payment_terms_label?: string;\n payment_reminder_enabled?: boolean;\n payment_made?: number;\n reference_number?: string;\n sub_total?: number;\n tax_total?: number;\n total?: number;\n balance?: number;\n invoice_url?: string;\n created_time?: Date;\n last_modified_time?: Date;\n discount_type?: string;\n discount?: number | string;\n place_of_supply?: string;\n recurring_invoice_id?: string;\n}\n\nexport interface ICreateRefundRequest {\n refund_mode: string;\n amount: number;\n date: string;\n reference_number?: string;\n description?: string;\n from_account_id: string;\n}\n\nexport interface IApplyCreditNoteForInvoicesRequest {\n invoices: Array<{\n invoice_id: string;\n amount_applied: number;\n }>;\n}\n\nexport interface ICreateCreditNoteForInvoiceRequest {\n customer_id: string;\n date: string;\n is_draft: boolean;\n reference_number?: string;\n notes?: string;\n is_inclusive_tax: boolean;\n salesperson_name?: string;\n place_of_supply?: string;\n custom_fields?: Array<{ api_name: string; value: string }>;\n}\n\nexport interface IAccountingListAPIPageContext {\n page: number;\n per_page: number;\n has_more_page: boolean;\n report_name: string;\n applied_filter: string;\n sort_column: string;\n sort_order: string;\n search_criteria: IAccountingListAPISearchCriteria[];\n}\n\nexport interface IAccountingListAPISearchCriteria {\n column_name: string;\n search_text: string;\n search_text_formatted: string;\n comparator: string;\n}\n\nexport interface IAccountingListAPIResponse {\n /** Response code (0 for success) */\n code: number;\n\n /** Response message */\n message: string;\n\n pageContext: IAccountingListAPIPageContext;\n}\n\nexport enum GET_CUSTOMER_CREDIT_NOTES_FILTER_BY {\n STATUS = 'STATUS',\n REFERENCE_NUMBER = 'REFERENCE_NUMBER',\n}\n\nexport enum GET_CUSTOMER_CREDIT_NOTES_SORT_BY {\n CREATED_TIME = 'CREATED_TIME',\n CUSTOMER_NAME = 'CUSTOMER_NAME',\n CREDITNOTE_NUMBER = 'CREDITNOTE_NUMBER',\n BALANCE = 'BALANCE',\n TOTAL = 'TOTAL',\n DATE = 'DATE',\n}\n\nexport interface IGetCustomerCreditNotesRequest {\n customerId: string;\n options?: {\n filters?: {\n by: GET_CUSTOMER_CREDIT_NOTES_FILTER_BY;\n values: string[];\n }[];\n page?: number;\n count?: number;\n search?: string;\n sort?: {\n by: GET_CUSTOMER_CREDIT_NOTES_SORT_BY;\n order: SORTING_ORDER_ENUM;\n };\n };\n}\n\nexport enum CREDIT_NOTE_STATUS {\n OPEN = 'OPEN',\n CLOSED = 'CLOSED',\n VOID = 'VOID',\n DRAFT = 'DRAFT',\n}\n\nexport interface ICustomerCreditNote {\n creditNoteId: string;\n date: string;\n charge: string;\n operator: string;\n totalAmount: number;\n availableCredit: number;\n status: CREDIT_NOTE_STATUS;\n createdAt: Date;\n updatedAt?: Date;\n}\n\nexport interface IGetCustomerCreditNotesResponse {\n creditNotes: ICustomerCreditNote[];\n hasMorePage: boolean;\n}\n\nexport interface ICreditNoteOperator {\n id?: string;\n type?: string;\n name?: string;\n}\n\nexport interface ICreditNoteAppliedInvoice {\n invoiceId: string;\n invoiceNumber: string;\n appliedAmount: number;\n}\n\nexport interface ICustomerCreditNoteDetail {\n creditNoteId: string;\n creditNoteNumber: string;\n status: CREDIT_NOTE_STATUS;\n customerId: string;\n date: string;\n operator?: ICreditNoteOperator;\n updatedAt?: Date;\n appliedInvoices: ICreditNoteAppliedInvoice[];\n totalAmount: number;\n creditsUsed: number;\n refundAmount: number;\n remainingAmount: number;\n currency?: ICurrency;\n}\n\nexport interface IInvoicesResponse {\n invoices: IAccountingInvoice[];\n hasMorePage: boolean;\n}\nexport interface IAccountingInvoice {\n id: string;\n date: Date;\n chargeId: string;\n category: string;\n status: INVOICE_STATUS_ENUM;\n operator: string;\n totalAmount: number;\n amountDue: number;\n createdAt: Date;\n updatedAt?: Date;\n currency: ICurrency;\n}\n\nexport enum GET_INVOICES_SORT_BY_ENUM {\n CUSTOMER_NAME = 'CUSTOMER_NAME',\n INVOICE_NUMBER = 'INVOICE_NUMBER',\n DATE = 'DATE',\n DUE_DATE = 'DUE_DATE',\n TOTAL = 'TOTAL',\n BALANCE = 'BALANCE',\n CREATED_TIME = 'CREATED_TIME',\n}\n/** Zoho Books recurring invoices support sort by total and created_time only */\nexport enum GET_RECURRING_INVOICES_SORT_BY_ENUM {\n TOTAL = 'TOTAL',\n CREATED_TIME = 'CREATED_TIME',\n}\nexport enum GET_INVOICES_FILTER_BY_ENUM {\n STATUS = 'STATUS',\n CATEGORY = 'CATEGORY',\n ITEM = 'ITEM',\n RESIDENT = 'RESIDENT',\n}\nexport enum INVOICE_STATUS_ENUM {\n SENT = 'SENT',\n DRAFT = 'DRAFT',\n OVERDUE = 'OVERDUE',\n PAID = 'PAID',\n VOID = 'VOID',\n UNPAID = 'UNPAID',\n PARTIALLY_PAID = 'PARTIALLY_PAID',\n VIEWED = 'VIEWED',\n ACTIVE = 'ACTIVE',\n}\nexport interface IGetInvoicesRequest {\n getInvoicesInput?: IGetInvoicesOptions;\n}\nexport interface IGetInvoicesOptions {\n count?: number;\n page?: number;\n search?: string;\n customerId: string;\n sorting?: {\n by: GET_INVOICES_SORT_BY_ENUM;\n order: SORTING_ORDER_ENUM;\n };\n filters?: {\n by: GET_INVOICES_FILTER_BY_ENUM;\n values: string[];\n }[];\n}\n\nexport interface IGetRecurringInvoicesOptions {\n count?: number;\n page?: number;\n search?: string;\n customerId: string;\n sorting?: {\n by: GET_RECURRING_INVOICES_SORT_BY_ENUM;\n order: SORTING_ORDER_ENUM;\n };\n filters?: {\n by: GET_INVOICES_FILTER_BY_ENUM;\n values: string[];\n }[];\n}\n\nexport interface IGetRecurringInvoicesRequest {\n getRecurringInvoicesInput?: IGetRecurringInvoicesOptions;\n}\n\nexport interface IGetRecurringInvoiceInput {\n recurringInvoiceId: string;\n}\n\nexport interface IGetRecurringInvoiceRequest extends IInvoiceIntegrationRequest {\n getRecurringInvoiceInput: IGetRecurringInvoiceInput;\n}\n\nexport enum RECURRING_INVOICE_STATUS {\n ACTIVE = 'ACTIVE',\n STOPPED = 'STOPPED',\n EXPIRED = 'EXPIRED',\n}\n\nexport interface IRecurringInvoices {\n date: string;\n items: string;\n itemDescription: string;\n description: string;\n operator: string;\n totalAmount: number;\n amountDue: number;\n status: RECURRING_INVOICE_STATUS;\n currencyCode: string;\n customerId: string;\n orderNumber: string;\n invoiceId: string;\n recurrenceFrequency: string;\n startDate: string | null;\n endDate: string | null;\n nextInvoiceDate: string | null;\n lastSentDate: string | null;\n repeatEvery: string;\n remark: string;\n createdAt: string;\n}\n\nexport interface IRecurringInvoicesResponse {\n recurringInvoices: IRecurringInvoices[];\n hasMorePage: boolean;\n}\n\nexport interface ICreateRecurringInvoiceLineItem {\n id?: string;\n label: string;\n remark?: string;\n amount: number;\n taxId: string;\n quantity: number;\n}\n\nexport interface ICreateRecurringInvoiceRequest {\n customerId: string;\n items: ICreateRecurringInvoiceLineItem[];\n /** Defaults to the first line item label when omitted. */\n recurrenceName?: string;\n recurrenceFrequency?: string;\n startDate?: string;\n endDate?: string;\n repeatEvery?: number;\n date?: string;\n isInclusiveTax?: boolean;\n allowPartialPayments?: boolean;\n autoNumberGenerationGroupId?: string;\n operator?: string;\n sendEmail?: boolean;\n contactPersonsAssociated?: Array<{ contactPersonId: string }>;\n customFields?: Array<{ name: string; value: string }>;\n}\n\nexport interface ICreateRecurringInvoiceResponse {\n recurringInvoiceId: string;\n}\n\nexport interface IUpdateRecurringInvoiceRequest extends ICreateRecurringInvoiceRequest {\n invoiceId: string;\n}\n\nexport interface IUpdateRecurringInvoiceResponse {\n status: boolean;\n}\n\nexport enum RECURRING_INVOICE_STATUS_ENUM {\n STOP = 'STOP',\n RESUME = 'RESUME',\n}\n\nexport interface IUpdateRecurringInvoiceStatusRequest {\n recurringInvoiceId: string;\n status: RECURRING_INVOICE_STATUS_ENUM;\n}\n","export interface IAccounts {\n id: string;\n name: string;\n type: string;\n}\n\nexport interface IAvailableTaxes {\n id: string;\n name: string;\n percentage: number;\n}\n\nexport interface ITransactionNumberSeriesItem {\n // Making id optional as its not being used for now\n id?: string;\n prefixString: string;\n entityType: string;\n}\nexport interface ITransactionNumberSeries {\n id: string;\n name: string;\n numberSeries: ITransactionNumberSeriesItem[];\n}\n\nexport enum DOWNLOAD_CUSTOMER_ACCOUNTING_STATEMENT_FILTER_BY_ENUM {\n STATUS = 'STATUS',\n}\n\nexport enum DOWNLOAD_CUSTOMER_ACCOUNTING_STATEMENT_STATUS_ENUM {\n ALL = 'ALL',\n}\n\nexport interface IDownloadCustomerAccountingStatementRequest {\n customerId: string;\n fromDate: string;\n toDate: string;\n filters?: Array<{\n by: DOWNLOAD_CUSTOMER_ACCOUNTING_STATEMENT_FILTER_BY_ENUM;\n values: DOWNLOAD_CUSTOMER_ACCOUNTING_STATEMENT_STATUS_ENUM[];\n }>;\n}\n\nexport interface CustomerActivity {\n /** BaseBigIntModelDto */\n id: string;\n /** BaseMetaModelDto */\n createdAt?: Date;\n createdBy?: string;\n updatedAt?: Date;\n updatedBy?: string;\n deletedAt?: Date;\n deletedBy?: string;\n recordedAt?: Date;\n initiatorId?: string;\n initiatorType?: string;\n actionType?: string;\n actionTitle?: string;\n actionSublabel1?: string;\n actionSublabel2?: string;\n actionSublabel3?: string;\n actionNotes?: string;\n projectId: string;\n resourceType?: string;\n resourceTypeId?: string;\n additionalInfo?: Record<string, unknown>;\n author?: ActivityLogAuthor;\n ownerType?: string;\n ownerTypeId?: string;\n note?: Note;\n isInternal?: boolean;\n}\n\nexport interface ActivityLogAuthor {\n id?: string;\n title?: string;\n firstName?: string;\n middleName?: string;\n lastName?: string;\n fullName?: string;\n profileImage?: string;\n}\n\nexport interface Note {\n /** BaseBigIntModelDto */\n id?: string;\n createdAt?: Date;\n createdBy?: string;\n updatedAt?: Date;\n updatedBy?: string;\n deletedAt?: Date;\n deletedBy?: string;\n title?: string;\n description?: string;\n noteCreatorBehaviourType?: string;\n noteCreatorBehaviourId?: string;\n propertyId?: string;\n resourceType?: string;\n resourceId?: string;\n resources?: NoteResource[];\n isPinned?: boolean;\n createdByUser?: UserIdentity;\n updatedByUser?: UserIdentity;\n digitalAssets?: DigitalAsset[];\n projectId?: string;\n attachments?: NoteAttachment[];\n hasAttachment?: boolean;\n noteChangelogs?: NoteChangelog[];\n pinnedAt?: string;\n isRead?: boolean;\n isInternal?: boolean;\n}\nexport interface NoteResource {\n /** NOTE_RESOURCE_TYPE_ENUM as string */\n resourceType?: string;\n /** bigint → string */\n resourceId?: string;\n /** bigint → string (persona userIdentityId) */\n resourceReferenceId?: string;\n}\n\nexport interface DigitalAsset {\n id?: string;\n createdAt?: Date;\n createdBy?: string;\n updatedAt?: Date;\n updatedBy?: string;\n deletedAt?: Date;\n deletedBy?: string;\n name?: string;\n type?: string;\n fileName?: string;\n fileSize?: string;\n description?: string;\n projectId?: string;\n propertyId?: string;\n thumbnailUrl?: string;\n mediaOriginalUrl?: string;\n meta?: Record<string, unknown>;\n scope?: string;\n status?: string;\n resourceAssetMaps?: ResourceAssetMapping[];\n}\n\nexport interface ResourceAssetMapping {\n id?: string;\n createdAt?: Date;\n createdBy?: string;\n updatedAt?: Date;\n updatedBy?: string;\n deletedAt?: Date;\n deletedBy?: string;\n resource?: string;\n resourceId?: string;\n digitalAssetId?: string;\n projectId?: string;\n propertyId?: string;\n}\n\nexport interface NoteAttachment {\n id?: string;\n /** Required asset name */\n name: string;\n /** Required file name */\n fileName: string;\n /** Required file size */\n fileSize: string;\n /** Optional description */\n description?: string;\n /** Optional thumbnail URL */\n thumbnailUrl?: string;\n /** Required media original URL */\n mediaOriginalUrl?: string;\n /** Optional metadata as JSON (Struct) */\n meta?: Record<string, unknown>;\n /** Required scope (DIGITAL_ASSET_SCOPE as string) */\n scope?: string;\n /** Required status (DIGITAL_ASSET_STATUS as string) */\n status?: string;\n /** Required type (DIGITAL_ASSET_TYPE as string) */\n type?: string;\n}\n\nexport interface NoteChangelogRecord {\n /** bigint → string */\n id: string;\n title: string;\n /** bigint → string */\n noteId: string;\n /** int → string */\n projectId: string;\n /** int → string */\n propertyId?: string;\n /** bigint → string */\n resourceId: string;\n description: string;\n /** NOTE_RESOURCE_TYPE_ENUM as string */\n resourceType: string;\n noteChangelog: string;\n /** bigint → string */\n noteEditorBehaviourId: string;\n /** BEHAVIOUR_TYPE_ENUM as string */\n noteEditorBehaviourType: string;\n createdAt?: Date;\n updatedAt?: Date;\n deletedAt?: Date;\n /** bigint → string */\n createdBy?: string;\n /** bigint → string */\n updatedBy?: string;\n /** bigint → string */\n deletedBy?: string;\n createdByUser?: NoteUserIdentity | undefined;\n}\n\nexport interface NoteUserIdentity {\n title?: string;\n fname?: string;\n mname?: string;\n lname?: string;\n fullName?: string;\n /** USER_GENDER_ENUM as string */\n gender?: string;\n /** SEED_SOURCE_ENUM as string */\n seedSource?: string;\n /** int → string */\n idIntegration?: string;\n identityReference?: string;\n /** bigint → string */\n userId?: string;\n metaInfo?: Record<string, unknown>;\n email?: string;\n contactPhone?: string;\n profileImage?: string;\n}\n\nexport interface UserIdentity {\n id?: string;\n createdAt?: Date;\n createdBy?: string;\n updatedAt?: Date;\n updatedBy?: string;\n deletedAt?: Date;\n deletedBy?: string;\n title?: string;\n fname?: string;\n mname?: string;\n lname?: string;\n fullName?: string;\n gender?: string;\n seedSource?: string;\n idIntegration?: number;\n identityReference?: string;\n userId?: string;\n metaInfo?: Record<string, unknown>;\n email?: string;\n contactPhone?: string;\n profileImage?: string;\n}\n\nexport interface NoteChangelog {\n id?: string;\n createdAt?: Date;\n createdBy?: string;\n updatedAt?: Date;\n updatedBy?: string;\n deletedAt?: Date;\n deletedBy?: string;\n title?: string;\n noteId?: string;\n projectId?: string;\n propertyId?: string;\n resourceId?: string;\n description?: string;\n resourceType?: string;\n noteChangelog?: string;\n noteEditorBehaviourId?: string;\n noteEditorBehaviourType?: string;\n createdByUser?: UserIdentity;\n}\n\nexport interface IGetCustomerActivities {\n records: CustomerActivity[];\n hasMorePage: boolean;\n}\n\nexport interface GetFolioActivitiesOptionsInput {\n count?: number;\n page?: number;\n}\n\nexport interface GetCustomerActivitiesInput {\n customerId: string;\n projectId: string;\n propertyTimeZone: string;\n options?: GetFolioActivitiesOptionsInput;\n}\n","import { SORTING_ORDER_ENUM } from '@dv4resi/dvss-backend-module-datastore';\n\nexport interface IGetCustomerPaymentsRequest {\n getCustomerPaymentsOptionsInput?: IGetCustomerPaymentsOptions;\n}\nexport interface IGetCustomerPaymentsOptions {\n count?: number;\n page?: number;\n search?: string;\n customerId: string;\n sorting?: IGetCustomerPaymentsSorting;\n}\nexport enum GET_PAYMENTS_FILTER_BY_ENUM {\n PAYMENT_MODE = 'PAYMENT_MODE',\n}\nexport enum GET_PAYMENTS_FILTER_VALUE_ENUM {\n ALL = 'ALL',\n CHECK = 'CHECK',\n CASH = 'CASH',\n BANK_TRANSFER = 'BANK_TRANSFER',\n PAYPAL = 'PAYPAL',\n CREDIT_CARD = 'CREDIT_CARD',\n GOOGLE_CHECKOUT = 'GOOGLE_CHECKOUT',\n CREDIT = 'CREDIT',\n AUTHORIZENET = 'AUTHORIZENET',\n STRIPE = 'STRIPE',\n PAY_FLOW_PRO = 'PAY_FLOW_PRO',\n BRAIN_TREE = 'BRAIN_TREE',\n TWO_CHECK_OUT = 'TWO_CHECK_OUT',\n BANK_REMITTANCE = 'BANK_REMITTANCE',\n}\nexport enum GET_PAYMENTS_SORTING_ENUM {\n CUSTOMER_NAME = 'CUSTOMER_NAME',\n DATE = 'DATE',\n AMOUNT = 'AMOUNT',\n NOTES = 'NOTES',\n PAYMENT_MODE = 'PAYMENT_MODE',\n CREATED_TIME = 'CREATED_TIME',\n}\nexport interface IGetCustomerPaymentsSorting {\n by: GET_PAYMENTS_SORTING_ENUM;\n order: SORTING_ORDER_ENUM;\n}\nexport interface IGetCustomerPaymentsFilter {\n by: GET_PAYMENTS_FILTER_BY_ENUM;\n values: GET_PAYMENTS_FILTER_VALUE_ENUM[];\n}\n\nexport interface IGetCustomerPayments {\n records: ICustomerPaymentRecord[];\n hasMorePage: boolean;\n}\nexport interface ICustomerPaymentRecord {\n customerId: string;\n date: string;\n dueInExcess: number;\n invoiceNumbers: string;\n mode: string;\n operator: string;\n paymentId: string;\n paymentNumber: string;\n referenceId: string;\n remark: string;\n totalAmountReceived: number;\n createdAt: Date;\n updatedAt?: Date;\n refundedAmount: number;\n currency: ICurrency;\n}\n\nexport interface IGetCustomerPaymentRequest {\n paymentId: string;\n}\n\nexport interface IGetCustomerPayment {\n payment: ICustomerPaymentDetails;\n}\n\nexport interface ICustomerPaymentDetails {\n date: Date;\n customerName: string;\n paymentId: string;\n customerId: string;\n totalAmount: number;\n remainingAmount: number;\n createdAt: Date;\n updatedAt: Date;\n paymentMode: string;\n accountId: string;\n accountName?: string;\n accountType?: string;\n referenceNumber?: string;\n bankCharges?: number;\n currency: ICurrency;\n customFields?: Array<{\n apiName: string;\n value: string | number | boolean;\n label?: string;\n customfieldId?: string;\n }>;\n custom_field_hash?: Record<string, string | number | boolean>;\n}\nexport interface ICurrency {\n id: string;\n symbol: string;\n code: string;\n}\n\nexport interface IRefundCustomerPayment {\n paymentId: string;\n amount: number;\n description?: string;\n fromAccountId: string;\n date: string;\n}\n\nexport interface IGetRefundCustomerPayment {\n paymentRefund: IGetCustomerPaymentRefundInfo;\n}\nexport interface IGetCustomerPaymentRefundInfo {\n paymentRefundId: string;\n paymentId: string;\n date: Date;\n refundMode: string;\n referenceNumber: string;\n amount: number;\n exchangeRate: number;\n fromAccountId: string;\n fromAccountName: string;\n description: string;\n htmlString: string;\n}\n\nexport interface ICreateCustomerPaymentRequest {\n customerId: string;\n totalAmount: number;\n date: string;\n paymentMode: string;\n accountId?: string;\n invoices?: Array<{\n invoiceId: string;\n amountApplied: number;\n }>;\n referenceNumber?: string;\n description?: string;\n bankCharges?: number;\n customFields?: Array<{\n apiName: string;\n value: string;\n }>;\n}\n\nexport interface IUpdateCustomerPaymentRequest {\n paymentId: string;\n customerId: string;\n invoices?: Array<{\n invoiceId: string;\n amountApplied: number;\n }>;\n description?: string;\n referenceNumber?: string;\n amount?: number;\n date?: string;\n paymentMethod?: string;\n customFields?: Array<{\n apiName: string;\n value: string;\n }>;\n bankCharges?: number;\n accountId?: string;\n}\n\nexport interface IGetCreateCustomerPayment {\n payment: IGetCreateCustomerPaymentInfo;\n}\nexport interface IGetCreateCustomerPaymentInfo {\n date: Date;\n customerName: string;\n paymentId: string;\n customerId: string;\n totalAmount: number;\n createdAt: Date;\n updatedAt: Date;\n paymentMode: string;\n accountId: string;\n currency: ICurrency;\n}\n","import type { IScheduleConfig, OFFERING_BOOKING_TIME_TYPE, OFFERING_RESOURCE_TYPE } from '@dv4resi/dvss-backend-module-datastore/dist/datastore/models';\n\nimport type { ICapabilityIntegration } from './capability-integration.model';\n\n// Re-exported so consumers get the booking vocabulary from the same place as the model.\nexport {\n BEHAVIOUR_TYPE_ENUM,\n DAY_OF_WEEK,\n OFFERING_BOOKING_TIME_TYPE,\n OFFERING_BOOKING_TYPE_ENUM,\n SCHEDULE_MONTHLY_UNIT,\n SCHEDULE_REPEAT_TYPE,\n} from '@dv4resi/dvss-backend-module-datastore/dist/datastore/models';\nexport type { IScheduleConfig } from '@dv4resi/dvss-backend-module-datastore/dist/datastore/models';\n\n/**\n * System calendar-booking model — OUTBOUND (DVSS → provider) only.\n *\n * `IBookingEvent` is deliberately identical, key for key, to booking-ms's\n * `AddOfferingBookingInput` (the `addOfferingBooking` GraphQL DTO). Its only job is a value\n * transformation: DVSS platform ids (behaviour ids, SPACE resource ids) are resolved to\n * calendar identities (email addresses) before the event reaches a provider. The final rename\n * of keys to a vendor's API shape (`name`→`subject`, `schedule`→Graph `recurrence`,\n * `requestedForIds`→attendees, …) happens *only* inside each provider's mapper.\n *\n * Fields the input carries for the booking domain but no calendar provider needs\n * (`items`, `customFields`, `assets`, `payment*`, `bookingType`, routing ids) ride along\n * untouched — the mapper ignores them.\n */\n\n/** Where an event sits relative to a recurring series (returned on the outbound result). */\nexport enum EVENT_INSTANCE_KIND {\n SINGLE = 'SINGLE',\n SERIES_MASTER = 'SERIES_MASTER',\n OCCURRENCE = 'OCCURRENCE',\n EXCEPTION = 'EXCEPTION',\n}\n\n/** A booked resource on an item (mirrors `OfferingBookingItemResourceInput`). */\nexport interface IBookingItemResource {\n id: string | number | bigint;\n resourceType?: OFFERING_RESOURCE_TYPE;\n}\n\n/** A booked item (mirrors `AddOfferingBookingItemInput`); commerce internals kept opaque. */\nexport interface IBookingItem {\n id?: bigint;\n externalId?: string;\n type?: string;\n resources?: IBookingItemResource[];\n}\n\n/**\n * Identical key-for-key to booking-ms `AddOfferingBookingInput`, with two differences:\n * - `requestedForIds` / `recipientIds` hold **email addresses** (resolved by DVSS), not\n * behaviour ids;\n * - a few calendar-mechanics fields that the input has no place for (`id`, `timeZone`,\n * `resourceEmails`, `syncMetadata`).\n */\nexport interface IBookingEvent {\n // ── identical key names to AddOfferingBookingInput ─────────────────────────\n name: string;\n description?: string;\n notes?: string | null;\n locationId?: bigint;\n isFullDay?: boolean;\n isRecurring?: boolean;\n paxCount?: number;\n bookingStartDateLabel: string;\n bookingEndDateLabel?: string;\n bookingStartTimeLabel?: string;\n bookingEndTimeLabel?: string;\n bookingTimeType?: OFFERING_BOOKING_TIME_TYPE;\n meta?: unknown;\n /** Email addresses of the requested-for people (resolved from behaviour ids by DVSS). */\n requestedForIds?: string[];\n /** Email addresses of the recipient attendees (resolved from behaviour ids by DVSS). */\n recipientIds?: string[];\n preferences?: unknown[];\n assets?: unknown[];\n items?: IBookingItem[];\n schedule?: IScheduleConfig;\n offeringBookableItemSlotId?: bigint;\n durationInMinutes?: number;\n overrideDates?: string[];\n\n // ── calendar mechanics (not in AddOfferingBookingInput) ────────────────────\n /** Provider event id — set on update / cancel / delete. */\n id?: string;\n /** IANA zone the `booking*Label` wall-clock strings are expressed in (property timezone). */\n timeZone?: string;\n /**\n * Last date of a recurring series (`YYYY-MM-DD`), i.e. the recurrence range end.\n *\n * `bookingStartDateLabel` / `bookingEndDateLabel` describe the **first occurrence's** slot — for a\n * daily 09–17 booking they are both day one — so they cannot double as the range end: sending the\n * first occurrence's end date as `recurrence.range.endDate` collapses the whole series to a single\n * event. Set this alongside `isRecurring` + `schedule`; ignored otherwise.\n */\n seriesEndDateLabel?: string;\n /** Room mailboxes, flattened from `items[].resources[]` SPACE ids by DVSS. */\n syncMetadata?: IEventSyncMetadata;\n}\n\n/**\n * Sync-ownership metadata used to prevent bidirectional sync loops and to persist the bits\n * DVSS needs for later operations on the same provider event.\n */\nexport interface IEventSyncMetadata {\n createdBy?: 'DVSS' | 'PROVIDER';\n syncVersion?: number;\n lastSyncTimestamp?: string;\n externalEventId?: string;\n syncType?: 'SINGLE' | 'RECURRING_SERIES' | 'CUSTOM_DATES';\n externalSeriesId?: string;\n externalEventIds?: { date: string; eventId: string }[];\n /**\n * Mailbox the event was created in. Provider event ids are mailbox-scoped, so later\n * update/cancel/delete must target this mailbox. Undefined ⇒ the resource organized.\n */\n organizerUserEmail?: string;\n /** Room mailbox the event books (an email address, not a numeric id). */\n resourceId?: string;\n /**\n * Per-date outcome of applying `schedule.skipDates`. One entry per date supplied, so the\n * consumer can persist a DB row per occurrence even when exclusion failed for some dates.\n */\n excludedDateResults?: IExcludedDateResult[];\n}\n\n/**\n * Outcome of excluding one date from `schedule.skipDates` within a recurring booking.\n * Providers that can't exclude dates at creation time create the full series first, then\n * resolve each skip date to its occurrence and remove it.\n */\nexport interface IExcludedDateResult {\n /** ISO date (`yyyy-mm-dd`), matching an entry from `schedule.skipDates`. */\n date: string;\n /** Provider event id of that occurrence, when found. Undefined if resolution failed. */\n eventId?: string;\n /** True when the occurrence was found and successfully removed at the provider. */\n excluded: boolean;\n}\n\n/**\n * The mailbox a provider event id belongs to. On create there is no prior mailbox — the\n * target comes from `event.requestedForIds[0]` / `event.resourceEmails[0]`. For every later\n * op the caller passes the mailbox it persisted from the create result\n * (`IEventSyncMetadata.organizerUserEmail`).\n */\ninterface IMailboxScope {\n organizerUserEmail?: string;\n}\n\nexport interface ICreateEventRequest {\n event: IBookingEvent;\n}\n\nexport interface IUpdateEventRequest extends IMailboxScope {\n eventId: string;\n resourceEmail: string;\n event: Partial<IBookingEvent>;\n}\n\nexport interface ICancelEventRequest extends IMailboxScope {\n eventId: string;\n resourceEmail: string;\n}\n\nexport interface IDeleteEventRequest extends IMailboxScope {\n eventId: string;\n resourceEmail: string;\n}\n\nexport interface IGetEventsRequest extends IMailboxScope {\n resourceEmail: string;\n /** Query window (inclusive), as wall-clock date labels in `timeZone`. */\n startDateLabel?: string;\n endDateLabel?: string;\n timeZone?: string;\n}\n\n/** What the consumer persists after a create / update — no rich event is read back. */\nexport interface IBookingEventRef {\n id?: string;\n seriesId?: string;\n instanceKind?: EVENT_INSTANCE_KIND;\n syncMetadata?: IEventSyncMetadata;\n}\n\n/** One provider occurrence, for the single-instance-of-a-series lookup. */\nexport interface IBookingEventInstance {\n id: string;\n startDateLabel: string;\n seriesId?: string;\n}\n\nexport interface IGetEventsResponse {\n events: IBookingEventInstance[];\n}\n\nexport interface IBookingManagementContext {\n integration: ICapabilityIntegration;\n loggedInUserId: bigint;\n}\n","import {\n IUpdateOrderRequest,\n IUpdateOrderResponse,\n type IBookableItem,\n type IBookableItemCategory,\n type ICapabilityIntegration,\n type ICreateOrderRequest,\n type ICreateOrderResponse,\n type IFetchOfferingAvailabilityRequest,\n type IGetAppointmentsRequest,\n type IGetAvailableDatesAndTimeSlotsResponse,\n type IGetBookableItemsFromCreditRequest,\n type IGetCategoriesRequest,\n type IGetCoursesRequest,\n type IGetOrderResponse,\n type IGetPractitionersRequest,\n type IGetSessionsRequest,\n type IOfferingResource,\n} from '../../../integration-common-utils';\nimport { type ISystemResponse } from '../../models/common.model';\n\n/**\n * Base abstract class for wellness management operations\n * Provides a foundation for implementing wellness management functionality\n * within capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific wellness management operations for different systems\n */\nexport abstract class BaseWellnessManagement {\n abstract fetchAppointments(\n request: IGetAppointmentsRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<ISystemResponse<IBookableItem>>;\n\n abstract fetchSessions(request: IGetSessionsRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<ISystemResponse<IBookableItem>>;\n\n abstract fetchCourses(request: IGetCoursesRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<ISystemResponse<IBookableItem>>;\n\n abstract fetchCategories(\n request: IGetCategoriesRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<ISystemResponse<IBookableItemCategory>>;\n\n abstract fetchBookableItemsFromCredit(\n request: IGetBookableItemsFromCreditRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<ISystemResponse<IBookableItem>>;\n\n abstract fetchSessionAvailabilityForOffering(\n request: IFetchOfferingAvailabilityRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IGetAvailableDatesAndTimeSlotsResponse>;\n\n abstract fetchAppointmentAvailabilityForOffering(\n request: IFetchOfferingAvailabilityRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IGetAvailableDatesAndTimeSlotsResponse>;\n\n abstract fetchPractitioners(\n request: IGetPractitionersRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<ISystemResponse<IOfferingResource>>;\n\n /**\n * Creates an external order for an offering booking in the integration platform.\n * This is the only booking-order operation exposed by the skeleton; all\n * provider-specific HTTP orchestration (add customer, add items, credits,\n * submit, etc.) should be encapsulated inside the concrete implementation.\n */\n abstract createOrder(request: ICreateOrderRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<ICreateOrderResponse>;\n\n abstract getOrder(orderId: string, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IGetOrderResponse>;\n\n abstract cancelOrder(orderId: string, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<void>;\n\n abstract updateOrder(request: IUpdateOrderRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IUpdateOrderResponse>;\n\n /**\n * Abstract method to fetch a wellness appointment session\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the appointment session is fetched\n */\n abstract fetchWellnessAppointmentSession(): Promise<void>;\n\n /**\n * Abstract method to check availability of a wellness appointment session\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the availability check is completed\n */\n abstract checkWellnessAppointmentSessionAvailability(): Promise<void>;\n\n /**\n * Abstract method to create a wellness appointment session order\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the appointment session order is created\n */\n abstract createWellnessAppointmentSessionOrder(): Promise<void>;\n\n /**\n * Abstract method to add items to a wellness appointment session order\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the order items are added\n */\n abstract addWellnessAppointmentSessionOrderItems(): Promise<void>;\n\n /**\n * Abstract method to confirm a wellness appointment session order\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the appointment session order is confirmed\n */\n abstract confirmWellnessAppointmentSessionOrder(): Promise<void>;\n}\n","import { ICapabilityIntegration, ICredit, IGetCustomerCreditsRequest } from '../../../integration-common-utils';\nimport { ISystemResponse } from '../../models/common.model';\n\n/**\n * Base abstract class for credit booking operations\n * Provides a foundation for implementing credit booking functionality\n *\n * This class should be extended by concrete implementations that provide\n * specific credit booking operations for different systems\n */\nexport abstract class BaseCreditBooking {\n /**\n * Abstract method to fetch customer credits\n * Must be implemented by concrete classes\n *\n * @param request - The request object containing the customer ID\n * @param integration - The integration object\n * @param loggedInUserId - The user ID of the logged in user\n * @returns Promise resolving to the system customer credits response (totalCount, records)\n */\n abstract fetchCustomerCredits(\n request: IGetCustomerCreditsRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<ISystemResponse<ICredit>>;\n}\n","import {\n IAddCustomerRequest,\n IAddUpdateAccessGroupRequest,\n IAdminCredentials,\n IConfiguration,\n ICustomer,\n ICustomerAddionalDetails,\n ICustomerStatusResponse,\n IDeleteAPIResponse,\n IGetCustomerAccessGroupsInput,\n IGetCustomerAccessGroupsResponse,\n IGetCustomerRequest,\n IListUsersInput,\n IListUsersResponse,\n IUpdateCustomerRequest,\n IUserAccessGroup,\n IValidatedCapabilityIntegration,\n} from '../../../integration-common-utils';\n\n/**\n * Base abstract class for customer management operations\n * Provides a foundation for implementing customer management functionality\n * within capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific customer management operations for different systems\n */\nexport abstract class BaseCustomerManagement {\n /**\n * Create a new customer.\n *\n * @returns Promise resolving to the created customer\n */\n abstract createCustomer(request: IAddCustomerRequest, integration: IValidatedCapabilityIntegration, loggedInUserId: bigint): Promise<ICustomer>;\n\n /**\n * Abstract method to search for customers\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the search is completed\n */\n abstract searchCustomer(request: IGetCustomerRequest, integration: IValidatedCapabilityIntegration, loggedInUserId: bigint): Promise<ICustomer | undefined>;\n\n /**\n * Update an existing customer.\n *\n * @returns Promise resolving to the updated customer data (e.g. id and fields)\n */\n abstract updateCustomer(\n customerId: string,\n request: IUpdateCustomerRequest,\n integration: IValidatedCapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<ICustomer>;\n\n /**\n * Abstract method to delete a customer.\n * Must be implemented by concrete classes.\n *\n * @param customerId - The customer ID to delete\n * @param integration - Capability integration\n * @param loggedInUserId - User ID for logging\n * @returns Promise resolving when the customer is deleted\n */\n abstract deleteCustomer(customerId: string, integration: IValidatedCapabilityIntegration, loggedInUserId: bigint): Promise<IDeleteAPIResponse>;\n\n /**\n * Initializes the customer management service with configuration and credentials\n *\n * This method sets up the service by:\n * 1. Storing the configuration settings\n * 2. Authenticating with the identity server\n * 3. Creating an authenticated Axios instance\n * 4. Setting up authorization headers for subsequent requests\n *\n * @param configuration - system configuration\n * @param credentials - Optional admin credentials (uses config credentials if not provided)\n */\n abstract init(configuration: IConfiguration, credentials?: IAdminCredentials): Promise<void>;\n\n /**\n * Recursively fetches paginated user data from the API\n *\n * This method handles pagination by recursively calling itself when\n * a next_page_link is present in the response. It accumulates all\n * user items across multiple pages into a single array.\n *\n * @param url - API endpoint URL to fetch data from\n * @param loggedInUserId - ID of the user performing the operation\n * @param items - Accumulated items from previous pages (defaults to empty array)\n * @returns Promise containing all user items across all pages\n */\n abstract fetchPage(url: string, loggedInUserId: bigint, items: ICustomer[]): Promise<ICustomer[]>;\n\n /**\n * Retrieves a list of all customers for the configured site\n *\n * This method fetches all users by handling pagination automatically\n * and returning a unified response with all users and total count.\n *\n * @param request - List users request parameters\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise containing the complete list of users and metadata\n */\n abstract listCustomers(request: IListUsersInput, loggedInUserId: bigint): Promise<IListUsersResponse<ICustomer>>;\n\n /**\n * Retrieves a specific customer by their ID\n *\n * @param request - Get user request parameters\n * @param userId - Unique identifier of the user to retrieve\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise containing the user information\n */\n abstract getCustomer(request: ICustomer, userId: string, loggedInUserId: bigint): Promise<ICustomer>;\n\n /**\n * Retrieves a specific customer by their email\n *\n * @param request - Get user request parameters\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise containing the user information\n */\n\n abstract getCustomerByEmail(request: IGetCustomerRequest, loggedInUserId: bigint): Promise<ICustomerAddionalDetails>;\n\n /**\n * Adds a customer to an access group\n *\n * @param request - Add update access group request parameters\n * @param userId - Unique identifier of the user to add to the access group\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise containing the user access group information\n */\n\n abstract addCustomerToAccessGroup(request: IAddUpdateAccessGroupRequest, userId: string, loggedInUserId: bigint): Promise<IUserAccessGroup>;\n\n /**\n * Removes a customer from an access group\n *\n * @param request - Add update access group request parameters\n * @param userId - Unique identifier of the user to remove from the access group\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise containing the user access group information\n */\n\n abstract removeCustomerFromAccessGroup(request: IAddUpdateAccessGroupRequest, userId: string, loggedInUserId: bigint): Promise<IUserAccessGroup>;\n\n /**\n * Resends an invite to a customer\n *\n * @param request - Customer request parameters\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise containing the boolean result\n */\n abstract resendInviteToCustomer(request: ICustomer, loggedInUserId: bigint): Promise<boolean>;\n\n /**\n * Adds a customer to an existing site\n *\n * @param request - Customer request parameters\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise containing the customer information\n */\n abstract addCustomerToExistingSite(request: ICustomer, loggedInUserId: bigint): Promise<ICustomer>;\n\n /**\n * Retrieves a list of access groups for a customer\n *\n * @param request - Get customer access groups request parameters\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise containing the customer access groups information\n */\n abstract getCustomerAccessGroups(request: IGetCustomerAccessGroupsInput, loggedInUserId: bigint): Promise<IGetCustomerAccessGroupsResponse>;\n\n /**\n * Activates a customer where supported by the provider.\n */\n abstract activateCustomer(customerId: string, integration: IValidatedCapabilityIntegration, loggedInUserId: bigint): Promise<ICustomerStatusResponse>;\n\n /**\n * Deactivates a customer where supported by the provider.\n */\n abstract deactivateCustomer(customerId: string, integration: IValidatedCapabilityIntegration, loggedInUserId: bigint): Promise<ICustomerStatusResponse>;\n}\n","/**\n * Base abstract class for package management operations\n * Provides a foundation for implementing package management functionality\n * within capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific package management operations for different systems\n */\nexport abstract class BasePackageManagement {\n /**\n * Abstract method to fetch course types\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the course types are fetched\n */\n abstract fetchCourseTypes(): Promise<void>;\n}\n","import {\n IAPIResponse,\n type ICustomerContactPersonResponse,\n type IAddCustomerContactPersonRequest,\n type IDeleteCustomerContactPersonRequest,\n type IMarkCustomerContactPersonPrimaryRequest,\n type IUpdateCustomerContactPersonRequest,\n type IValidatedCapabilityIntegration,\n} from '../../../../integration-common-utils';\n\n/**\n * Base abstract class for accounting contact person management operations\n * Provides a foundation for implementing contact person management functionality\n * within accounting capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific contact person management operations for different accounting systems\n */\nexport abstract class BaseAccountingContactPersonManagement {\n /**\n * Abstract method to create an accounting contact person\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the contact person is created\n */\n abstract createContactPerson(\n request: IAddCustomerContactPersonRequest,\n integration: IValidatedCapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<ICustomerContactPersonResponse>;\n\n /**\n * Abstract method to update an accounting contact person\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the contact person is updated\n */\n abstract updateContactPerson(\n request: IUpdateCustomerContactPersonRequest,\n integration: IValidatedCapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<ICustomerContactPersonResponse>;\n\n /**\n * Abstract method to delete an accounting contact person\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the contact person is deleted\n */\n abstract deleteContactPerson(\n request: IDeleteCustomerContactPersonRequest,\n integration: IValidatedCapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IAPIResponse>;\n\n /**\n * Abstract method to mark an accounting contact person as primary\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the contact person is marked primary\n */\n abstract markContactPersonPrimary(\n request: IMarkCustomerContactPersonPrimaryRequest,\n integration: IValidatedCapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IAPIResponse>;\n}\n","import {\n ICapabilityIntegration,\n ICreateCreditNoteForInvoiceRequest,\n IAccountingAPIResponse,\n IApplyCreditNoteForInvoicesRequest,\n ICreateRefundRequest,\n IGetCustomerCreditNotesRequest,\n IGetCustomerCreditNotesResponse,\n ICustomerCreditNoteDetail,\n} from '../../../../integration-common-utils';\n\n/**\n * Base abstract class for accounting credit note management operations\n * Provides a foundation for implementing credit note management functionality\n * within accounting capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific credit note management operations for different accounting systems\n */\nexport abstract class BaseAccountingCreditNoteManagement {\n /**\n * Creates a rebate for an invoice\n *\n * @param request - Request containing invoice details\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise resolving when the rebate is created\n */\n abstract applyCreditNoteForInvoices(\n creditNoteId: string,\n rebateRequest: IApplyCreditNoteForInvoicesRequest,\n capabilityIntegration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IAccountingAPIResponse>;\n\n /**\n * Abstract method to refund an accounting invoice\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the invoice is refunded\n */\n abstract createCreditNoteRefund(\n creditNoteId: string,\n refundRequest: ICreateRefundRequest,\n capabilityIntegration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IAccountingAPIResponse>;\n\n /**\n * Creates a credit note for an invoice\n *\n * @param request - Request containing invoice details\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise resolving when the credit note is created\n */\n abstract createCreditNoteForInvoice(\n request: ICreateCreditNoteForInvoiceRequest,\n externalInvoiceId: string,\n capabilityIntegration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IAccountingAPIResponse>;\n\n /**\n * Gets credit notes for a customer\n *\n * @param request - Request containing customer details\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise resolving when the credit notes are retrieved\n */\n abstract getCustomerCreditNotes(\n request: IGetCustomerCreditNotesRequest,\n capabilityIntegration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IGetCustomerCreditNotesResponse>;\n\n /**\n * Gets a credit note by ID\n *\n * @param creditNoteId - External credit note ID\n * @param capabilityIntegration - Capability integration configuration\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise resolving to the mapped credit note detail\n */\n abstract getCreditNote(creditNoteId: string, capabilityIntegration: ICapabilityIntegration, loggedInUserId: bigint): Promise<ICustomerCreditNoteDetail>;\n}\n","import {\n ICapabilityIntegration,\n ICreateCustomerPaymentRequest,\n IGetCreateCustomerPayment,\n IGetCustomerPayment,\n IGetCustomerPaymentRequest,\n IGetCustomerPayments,\n IGetCustomerPaymentsRequest,\n IGetRefundCustomerPayment,\n IRefundCustomerPayment,\n IUpdateCustomerPaymentRequest,\n} from '../../../../integration-common-utils';\n\n/**\n * Base abstract class for accounting customer payment management operations\n * Provides a foundation for implementing customer payment management functionality\n * within accounting capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific customer payment management operations for different accounting systems\n */\nexport abstract class BaseAccountingCustomerPaymentManagement {\n /**\n * Abstract method to create an accounting customer payment\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the customer payment is created\n */\n abstract createCustomerPayment(\n request: ICreateCustomerPaymentRequest,\n capabilityIntegration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IGetCreateCustomerPayment>;\n\n /**\n * Abstract method to update an accounting customer payment (e.g. apply invoices)\n * Must be implemented by concrete classes\n */\n abstract updateCustomerPayment(\n request: IUpdateCustomerPaymentRequest,\n capabilityIntegration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IGetCreateCustomerPayment>;\n\n /**\n * Retrieve bank & cash accounts from the accounting system.\n *\n * @returns Promise resolving to an array of {@link IAccounts}\n */\n abstract getCustomerPayments(\n request: IGetCustomerPaymentsRequest,\n capabilityIntegration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IGetCustomerPayments>;\n\n abstract getCustomerPayment(\n request: IGetCustomerPaymentRequest,\n capabilityIntegration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IGetCustomerPayment>;\n\n abstract downloadCustomerPayment(\n request: IGetCustomerPaymentRequest,\n capabilityIntegration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<ArrayBuffer>;\n\n abstract refundCustomerPayment(\n request: IRefundCustomerPayment,\n capabilityIntegration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IGetRefundCustomerPayment>;\n}\n","import { ICapabilityIntegration } from '../../../../integration-common-utils';\nimport {\n IAccountingAPIResponse,\n ICreateRecurringInvoiceRequest,\n ICreateRecurringInvoiceResponse,\n IGetInvoicesRequest,\n IGetRecurringInvoiceRequest,\n IGetRecurringInvoicesRequest,\n IInvoiceIntegrationRequest,\n IInvoiceResponse,\n IInvoicesResponse,\n IRecurringInvoicesResponse,\n IUpdateRecurringInvoiceRequest,\n IUpdateRecurringInvoiceResponse,\n IUpdateRecurringInvoiceStatusRequest,\n} from '../../../models/invoice-management.model';\n\n/**\n * Base abstract class for accounting invoice management operations\n * Provides a foundation for implementing invoice management functionality\n * within accounting capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific invoice management operations for different accounting systems\n */\nexport abstract class BaseAccountingInvoiceManagement {\n /**\n * Abstract method to create an accounting invoice\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the invoice is created\n */\n abstract createInvoice(request: IInvoiceIntegrationRequest, loggedInUserId: bigint): Promise<IAccountingAPIResponse>;\n\n /**\n * Abstract method to create a recurring invoice\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the recurring invoice is created\n */\n abstract createRecurringInvoice(\n request: ICreateRecurringInvoiceRequest,\n capabilityIntegration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<ICreateRecurringInvoiceResponse>;\n\n /**\n * Abstract method to update an accounting invoice\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the invoice is updated\n */\n abstract updateInvoice(request: IInvoiceIntegrationRequest, loggedInUserId: bigint): Promise<IInvoiceResponse>;\n\n /**\n * Abstract method to delete an accounting invoice\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the invoice is deleted\n */\n abstract deleteInvoice(request: IInvoiceIntegrationRequest, loggedInUserId: bigint): Promise<IAccountingAPIResponse>;\n\n /**\n * Abstract method to download an accounting invoice\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the invoice is downloaded\n */\n\n abstract downloadInvoice(request: IInvoiceIntegrationRequest, loggedInUserId: bigint): Promise<ArrayBuffer>;\n\n /**\n * Abstract method to get an accounting invoice\n *\n * @param request - The invoice request\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise resolving to the invoice\n */\n abstract getInvoice(request: IInvoiceIntegrationRequest, loggedInUserId: bigint): Promise<IInvoiceResponse>;\n\n /**\n * Abstract method to get a recurring invoice by ID\n *\n * @param request - The recurring invoice request\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise resolving to the recurring invoice\n */\n abstract getRecurringInvoice(request: IGetRecurringInvoiceRequest, loggedInUserId: bigint): Promise<unknown>;\n\n /**\n * Creates a customer payment in Zoho Books\n * This marks an invoice as paid or partially paid\n *\n * @param request - Payment request containing customer payment details\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise resolving to payment creation response\n */\n\n abstract markInvoiceAsPaid(request: IInvoiceIntegrationRequest, loggedInUserId: bigint): Promise<IAccountingAPIResponse>;\n\n /**\n * Update the status of an existing invoice (e.g., Mark as paid).\n */\n abstract updateInvoiceStatus(request: IInvoiceIntegrationRequest, loggedInUserId: bigint): Promise<IAccountingAPIResponse>;\n\n abstract getInvoices(request: IGetInvoicesRequest, capabilityIntegration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IInvoicesResponse>;\n\n abstract getRecurringInvoices(\n request: IGetRecurringInvoicesRequest,\n capabilityIntegration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IRecurringInvoicesResponse>;\n\n abstract updateRecurringInvoice(\n request: IUpdateRecurringInvoiceRequest,\n capabilityIntegration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IUpdateRecurringInvoiceResponse>;\n\n abstract markInvoiceAsSent(invoiceId: string, capabilityIntegration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IAccountingAPIResponse>;\n\n abstract updateRecurringInvoiceStatus(\n request: IUpdateRecurringInvoiceStatusRequest,\n capabilityIntegration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IUpdateRecurringInvoiceResponse>;\n}\n","/**\n * Base abstract class for accounting chart of accounts (LOA) management operations\n * Provides a foundation for implementing chart of accounts management functionality\n * within accounting capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific chart of accounts management operations for different accounting systems\n */\nexport abstract class BaseAccountingLOAManagement {\n /**\n * Abstract method to list accounting chart of accounts\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the chart of accounts is listed\n */\n abstract listAccountingChartOfAccounts(): Promise<void>;\n}\n","/**\n * Base abstract class for accounting tax management operations\n * Provides a foundation for implementing tax management functionality\n * within accounting capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific tax management operations for different accounting systems\n */\nexport abstract class BaseAccountingTaxManagement {\n /**\n * Abstract method to list accounting taxes\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the taxes are listed\n */\n abstract listAccountingTaxes(): Promise<void>;\n}\n","/**\n * Base abstract class for payment operations\n * Provides a foundation for implementing payment functionality\n * within payment capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific payment operations for different payment systems\n */\nexport abstract class BasePayment {\n /**\n * Abstract method to create a payment setup intent\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the payment setup intent is created\n */\n abstract createPaymentSetupIntent(): Promise<void>;\n\n /**\n * Abstract method to confirm a payment setup intent\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the payment setup intent is confirmed\n */\n abstract confirmPaymentSetupIntent(): Promise<void>;\n\n /**\n * Abstract method to cancel a payment setup intent\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the payment setup intent is cancelled\n */\n abstract cancelPaymentSetupIntent(): Promise<void>;\n\n /**\n * Abstract method to create a payment ephemeral key\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the payment ephemeral key is created\n */\n abstract createPaymentEphemeralKey(): Promise<void>;\n}\n","/**\n * Base abstract class for payment method management operations\n * Provides a foundation for implementing payment method management functionality\n * within payment capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific payment method management operations for different payment systems\n */\nexport abstract class BasePaymentMethodManagement {\n /**\n * Abstract method to create a payment method\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the payment method is created\n */\n abstract createPaymentMethod(): Promise<void>;\n\n /**\n * Abstract method to attach a payment method to a customer\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the payment method is attached\n */\n abstract attachPaymentMethodToCustomer(): Promise<void>;\n\n /**\n * Abstract method to list payment methods for a customer\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the payment methods are listed\n */\n abstract listPaymentMethodForCustomer(): Promise<void>;\n\n /**\n * Abstract method to detach a payment method from a customer\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the payment method is detached\n */\n abstract detachPaymentMethodFromCustomer(): Promise<void>;\n}\n","/**\n * Base abstract class for payment user management operations\n * Provides a foundation for implementing user management functionality\n * within payment capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific user management operations for different payment systems\n */\nexport abstract class BasePaymentUserManagement {\n /**\n * Abstract method to list payment customers\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the customers are listed\n */\n abstract listPaymentCustomers(): Promise<void>;\n\n /**\n * Abstract method to create a new payment customer\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the customer is created\n */\n abstract createPaymentCustomer(): Promise<void>;\n\n /**\n * Abstract method to update an existing payment customer\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the customer is updated\n */\n abstract updatePaymentCustomer(): Promise<void>;\n\n /**\n * Abstract method to delete a payment customer\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the customer is deleted\n */\n abstract deletePaymentCustomer(): Promise<void>;\n\n /**\n * Abstract method to search for payment customers\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the search is completed\n */\n abstract searchPaymentCustomers(): Promise<void>;\n}\n","/**\n * Base abstract class for membership customer management operations\n * Provides a foundation for implementing customer management functionality\n * within membership capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific customer management operations for different membership systems\n */\nexport abstract class BaseMembershipCustomerManagement {\n /**\n * Abstract method to get all membership customers\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when all customers are retrieved\n */\n abstract getMembershipAllCustomers(): Promise<void>;\n\n /**\n * Abstract method to get a specific membership customer\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the customer is retrieved\n */\n abstract getMembershipCustomer(): Promise<void>;\n\n /**\n * Abstract method to create a new membership customer\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the customer is created\n */\n abstract createMembershipCustomer(): Promise<void>;\n\n /**\n * Abstract method to update an existing membership customer\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the customer is updated\n */\n abstract updateMembershipCustomer(): Promise<void>;\n}\n","/**\n * Base abstract class for membership management operations\n * Provides a foundation for implementing membership management functionality\n * within membership capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific membership management operations for different membership systems\n */\nexport abstract class BaseMembershipManagement {\n /**\n * Abstract method to get membership types\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the membership types are retrieved\n */\n abstract getMembershipTypes(): Promise<void>;\n\n /**\n * Abstract method to get a membership\n * Must be implemented by concrete classes\n *\n * @returns Promise resolving when the membership is retrieved\n */\n abstract getMembership(): Promise<void>;\n}\n","import type { CAPABILITY_CATEGORY_ENUM, CAPABILITY_TYPE_ENUM } from '@dv4resi/dvss-backend-module-datastore/dist/datastore/models/capability.model';\nimport { CONFIGURED_FOR_TYPE_ENUM } from '@dv4resi/dvss-backend-module-datastore/dist/datastore/models';\nimport type { CommonValidationDatabaseService } from '@dv4resi/dvss-backend-module-datastore';\nimport {\n AddAPIResponse,\n CustomException,\n GraphQLContext,\n LoggerService,\n MASK_STRATEGY_ENUM,\n maskValue,\n type SecretProvider,\n} from '@dv4resi/dvss-backend-module-utility';\nimport { Injectable, Optional } from '@nestjs/common';\nimport type {\n IAddCapabilityIntegration,\n IAddCapabilityIntegrationInput,\n IGetCapabilityIntegrationInput,\n IGetCapabilityIntegrationResult,\n IUpdateCapabilityIntegration,\n} from '../../../integration-common-utils';\nimport type { IntegrationConfigurationDao } from '../../../integration-common-utils/dao/integration-configuration.dao';\nimport type { IntegrationConfigSecureStorageService } from '../../../integration-common-utils/secure-storage/integration-config-secure-storage.service';\nimport type { IIntegrationConfigStructureMetadata } from '../../../integration-common-utils/secure-storage/types/field-metadata.types';\nimport type { ICapabilityIntegration } from '../../models/capability-integration.model';\nimport type {\n IGetCapabilityIntegrationsRequest,\n IGetCapabilityIntegrationsResponse,\n IUpdateCapabilityIntegrationRequest,\n IUpdateCapabilityIntegrationResponse,\n} from '../../models/integration-configuration.model';\n\nexport interface ISecureStorageWriteOptions {\n /** When true, encrypt sensitive config fields before DAO persist. Default false. */\n useSecureStorage?: boolean;\n /** KMS key id or alias required when useSecureStorage is true. */\n kmsKeyId?: string;\n}\n\n@Injectable()\nexport class BaseIntegrationConfiguration {\n protected readonly fileName: string = 'integration-configuration.base.ts';\n\n constructor(\n protected readonly integrationConfigurationDao: IntegrationConfigurationDao,\n protected readonly commonValidationDatabaseService: CommonValidationDatabaseService,\n protected readonly logger: LoggerService,\n @Optional() protected readonly secureStorage?: IntegrationConfigSecureStorageService,\n @Optional() protected readonly secretProvider?: SecretProvider,\n ) {}\n\n /**\n * Validates add-capability-integration input (project, property, parent, capability, provider, configuredFor).\n * Logic copied from project-ms CapabilityIntegrationService.validateAddCapabilityIntegrationInput.\n */\n private async validateAddCapabilityIntegrationInput(\n input: IAddCapabilityIntegrationInput,\n context: GraphQLContext,\n ): Promise<{\n capability: {\n id: bigint;\n type: CAPABILITY_TYPE_ENUM;\n category: CAPABILITY_CATEGORY_ENUM;\n providerId: bigint;\n configStructure?: unknown;\n };\n capabilityProvider: { id: bigint };\n }> {\n await this.commonValidationDatabaseService.getProject({\n projectId: input.projectId,\n });\n\n if (input.propertyId != null) {\n await this.commonValidationDatabaseService.getProperty({\n propertyId: input.propertyId,\n projectId: input.projectId,\n });\n }\n\n if (input.resourceMappings?.length) {\n for (const mapping of input.resourceMappings) {\n if (mapping.configuredForType === CONFIGURED_FOR_TYPE_ENUM.PROPERTY) {\n const propertyId = Number(mapping.configuredForId);\n await this.commonValidationDatabaseService.validatePropertyIds({\n propertyIds: [propertyId],\n projectId: input.projectId,\n });\n }\n }\n }\n\n if (input.parentId != null) {\n const parentIntegration = await this.integrationConfigurationDao.getCapabilityIntegration(\n { capabilityIntegrationId: input.parentId },\n context.loggedInUserId,\n );\n if (!parentIntegration) {\n throw new Error('Parent capability integration not found');\n }\n }\n\n const [capability, capabilityProvider] = await Promise.all([\n this.integrationConfigurationDao.getCapability({ capabilityId: input.capabilityId }, context.loggedInUserId),\n this.integrationConfigurationDao.getCapabilityProvider({ capabilityProviderId: input.capabilityProviderId }, context.loggedInUserId),\n ]);\n\n if (!capability) {\n throw new Error('Capability not found');\n }\n\n if (!capabilityProvider) {\n throw new Error('Capability provider not found');\n }\n\n if (capability.providerId !== capabilityProvider.id) {\n throw new Error(`Capability provider mismatch: capabilityId=${capability.id}, capabilityProviderId=${capability.providerId}`);\n }\n\n return {\n capability: {\n id: capability.id,\n type: capability.type,\n category: capability.category,\n providerId: capability.providerId,\n configStructure: capability.configStructure,\n },\n capabilityProvider: { id: capabilityProvider.id },\n };\n }\n\n /**\n * Add a capability integration (validate then persist via DAO).\n * Same name as project MS call: addCapabilityIntegration.\n */\n async addCapabilityIntegration(\n input: IAddCapabilityIntegrationInput,\n context: GraphQLContext,\n options: ISecureStorageWriteOptions = {},\n ): Promise<AddAPIResponse> {\n const { capability, capabilityProvider } = await this.validateAddCapabilityIntegrationInput(input, context);\n\n const securedConfig = await this.applySecureStorageForWrite(input.config, capability.configStructure, options, context.loggedInUserId);\n\n const addCapabilityIntegrationInput: IAddCapabilityIntegration = {\n ...input,\n config: securedConfig,\n providerId: capabilityProvider.id,\n createdBy: context.loggedInUserId,\n type: capability.type,\n category: capability.category,\n availableFor: input.availableFor,\n configuredFor: input.configuredFor,\n };\n\n const result = await this.integrationConfigurationDao.addCapabilityIntegration(addCapabilityIntegrationInput, context.loggedInUserId);\n\n if (!result || !result.id) {\n throw new Error('Failed to add capability integration');\n }\n\n return result;\n }\n\n /**\n * Update capability integration with config merging support.\n * Handles merging of integrationConfig and platformConfig from existing integration.\n */\n async updateCapabilityIntegration(\n request: IUpdateCapabilityIntegrationRequest,\n integration?: ICapabilityIntegration,\n loggedInUserId?: bigint,\n options: ISecureStorageWriteOptions = {},\n ): Promise<IUpdateCapabilityIntegrationResponse> {\n if (!loggedInUserId) {\n throw new Error('loggedInUserId is required');\n }\n\n this.validateIconAndNickName(request.updateData, loggedInUserId);\n\n if (request.updateData.resourceMappings?.length) {\n for (const mapping of request.updateData.resourceMappings) {\n if (mapping.configuredForType === CONFIGURED_FOR_TYPE_ENUM.PROPERTY) {\n if (!integration?.projectId) {\n throw new CustomException('BAD_REQUEST', 'integration.projectId is required to validate resourceMappings');\n }\n\n const propertyId = Number(mapping.configuredForId);\n\n await this.commonValidationDatabaseService.validatePropertyIds({\n propertyIds: [propertyId],\n projectId: integration.projectId,\n });\n }\n }\n }\n\n let configToUpdate: Record<string, unknown> | undefined;\n const updateData = request.updateData;\n const { resourceMappings } = updateData;\n\n if (updateData.config && integration?.config) {\n const existingConfig = integration.config as Record<string, unknown>;\n\n configToUpdate = {\n ...existingConfig,\n };\n\n const existingIntegrationConfig = (existingConfig.integrationConfig as Record<string, unknown> | undefined) || {};\n configToUpdate.integrationConfig = {\n ...existingIntegrationConfig,\n ...updateData.config.integrationConfig,\n };\n\n const existingPlatformConfig = (existingConfig.platformConfig as Record<string, unknown> | undefined) || {};\n configToUpdate.platformConfig = {\n ...existingPlatformConfig,\n ...updateData.config.platformConfig,\n };\n\n const existingAccountConfig = (existingConfig.accountConfig as Record<string, unknown> | undefined) || {};\n configToUpdate.accountConfig = {\n ...existingAccountConfig,\n ...updateData.config.accountConfig,\n };\n } else if (updateData.config) {\n configToUpdate = updateData.config as unknown as Record<string, unknown>;\n }\n\n if (configToUpdate && options.useSecureStorage) {\n const capabilityId = updateData.capabilityId ?? integration?.capabilityId;\n let configStructure: unknown;\n\n if (capabilityId != null) {\n const capability = await this.integrationConfigurationDao.getCapability({ capabilityId }, loggedInUserId);\n configStructure = capability?.configStructure;\n }\n\n configToUpdate = await this.applySecureStorageForWrite(configToUpdate, configStructure, options, loggedInUserId);\n }\n\n const updateDataForDao: IUpdateCapabilityIntegration = {\n nickname: updateData.nickname,\n icon: updateData.icon as unknown,\n config: configToUpdate as unknown,\n parentId: updateData.parentId,\n propertyId: updateData.propertyId,\n capabilityId: updateData.capabilityId,\n providerId: updateData.capabilityProviderId,\n subcategory: updateData.subcategory,\n capabilityIntegrationResourceId: updateData.capabilityIntegrationResourceId,\n groupId: updateData.groupId,\n status: updateData.status,\n availableFor: updateData.availableFor,\n updatedBy: loggedInUserId,\n };\n\n const updateResult = await this.integrationConfigurationDao.updateCapabilityIntegration(\n { id: request.id, updateData: updateDataForDao, projectId: integration?.projectId as number },\n loggedInUserId,\n );\n\n if (resourceMappings?.length) {\n await this.integrationConfigurationDao.syncCapabilityIntegrationResourceMappings(\n {\n capabilityIntegrationId: request.id,\n projectId: integration?.projectId as number,\n resourceMappings,\n },\n loggedInUserId,\n );\n }\n\n return updateResult;\n }\n\n /**\n * Validates icon and nickname. Can be overridden in subclasses for provider-specific validation.\n */\n protected validateIconAndNickName(updateData: IUpdateCapabilityIntegrationRequest['updateData'], loggedInUserId: bigint): void {\n if (updateData.nickname !== undefined && (updateData.nickname === '' || updateData.nickname.trim() === '')) {\n this.logger.error(loggedInUserId, this.validateIconAndNickName.name, this.fileName, 'Validation failed: nickname cannot be empty or null');\n throw new Error('Nickname cannot be empty');\n }\n\n if (updateData.icon && updateData.icon.meta && typeof updateData.icon.meta === 'object') {\n const meta = updateData.icon.meta as Record<string, unknown>;\n\n if (\n meta.iconName !== undefined &&\n (meta.iconName === null || meta.iconName === '' || (typeof meta.iconName === 'string' && meta.iconName.trim() === ''))\n ) {\n this.logger.error(loggedInUserId, this.validateIconAndNickName.name, this.fileName, 'Validation failed: iconName cannot be empty');\n throw new Error('Icon name cannot be empty');\n }\n }\n }\n\n async getCapabilityIntegrations(request: IGetCapabilityIntegrationsRequest, loggedInUserId: bigint): Promise<IGetCapabilityIntegrationsResponse> {\n return await this.integrationConfigurationDao.getCapabilityIntegrations(request, loggedInUserId);\n }\n\n async getCapabilityIntegration(input: IGetCapabilityIntegrationInput, context: GraphQLContext): Promise<IGetCapabilityIntegrationResult> {\n if (!input.projectId) {\n throw new Error('Project ID is required');\n }\n\n await this.commonValidationDatabaseService.getProject({\n projectId: input.projectId,\n });\n\n let integration: IGetCapabilityIntegrationResult | undefined;\n\n if (input.id) {\n integration = await this.integrationConfigurationDao.getCapabilityIntegrationById(\n {\n id: input.id,\n projectId: input.projectId,\n category: input.category,\n },\n context.loggedInUserId,\n );\n } else if (input.fetchBy) {\n integration = await this.integrationConfigurationDao.getCapabilityIntegrationByProvider(\n {\n projectId: input.projectId,\n category: input.fetchBy.category ?? input.category,\n configuredForType: input.fetchBy.configuredForType,\n configuredForId: BigInt(input.fetchBy.configuredForId),\n },\n context.loggedInUserId,\n );\n }\n\n if (!integration) {\n throw new Error('Capability integration not found');\n }\n\n return integration;\n }\n\n /**\n * When useSecureStorage is true: prepareForWrite on metadata-covered fields + encrypt accessToken if present.\n */\n protected async applySecureStorageForWrite(\n config: Record<string, unknown> | undefined,\n configStructure: unknown,\n options: ISecureStorageWriteOptions,\n loggedInUserId: bigint,\n ): Promise<Record<string, unknown> | undefined> {\n if (!options.useSecureStorage || !config) {\n return config;\n }\n\n if (!this.secureStorage || !this.secretProvider) {\n throw new CustomException(\n 'INTERNAL_ERROR',\n 'Secure storage is not configured.',\n 'Secure storage providers are required when useSecureStorage is true',\n );\n }\n\n if (!options.kmsKeyId) {\n throw new CustomException('BAD_REQUEST', 'Encryption key is required.', 'kmsKeyId is required when useSecureStorage is true');\n }\n\n const fieldMetadata = (configStructure && typeof configStructure === 'object' ? configStructure : {}) as IIntegrationConfigStructureMetadata;\n\n const accessDetails = config.accessDetails;\n const accessTokenPlain =\n accessDetails && typeof accessDetails === 'object' && !Array.isArray(accessDetails)\n ? (accessDetails as Record<string, unknown>).accessToken\n : undefined;\n const plaintextToken = typeof accessTokenPlain === 'string' ? accessTokenPlain : undefined;\n\n const encryptedBody = await this.secureStorage.prepareForWrite(\n {\n integrationConfig: (config.integrationConfig ?? {}) as Record<string, unknown>,\n },\n fieldMetadata,\n options.kmsKeyId,\n loggedInUserId,\n );\n\n let result: Record<string, unknown> = {\n ...config,\n ...encryptedBody,\n };\n\n if (plaintextToken) {\n const encrypted = await this.secretProvider.encrypt(plaintextToken, options.kmsKeyId);\n const masked = maskValue(plaintextToken, MASK_STRATEGY_ENUM.LAST_4);\n const details =\n accessDetails && typeof accessDetails === 'object' && !Array.isArray(accessDetails) ? { ...(accessDetails as Record<string, unknown>) } : {};\n\n details.accessToken = {\n encrypted,\n masked,\n isSensitive: true,\n };\n\n result = {\n ...result,\n accessDetails: details,\n };\n }\n\n return result;\n }\n}\n","import { IntegrationResourceManagementDao } from '../../../integration-common-utils/dao/integration-resource-management.dao';\nimport {\n IAddResourceToIntegrationInput,\n IAddResourceToIntegrationResponse,\n IRemoveResourceFromIntegrationRequest,\n IRemoveResourceFromIntegrationResponse,\n IUpdateOfferingIntegrationResourceConfigurationInput,\n IUpdateOfferingIntegrationResourceConfigurationResponse,\n} from '../../../integration-operation-skeletons/models/integration-resource-management.model';\nimport { GraphQLContext, LoggerService } from '@dv4resi/dvss-backend-module-utility';\nimport { CONFIGURED_FOR_TYPE_ENUM } from '@dv4resi/dvss-backend-module-datastore/dist/datastore/models';\n\n/**\n * Base abstract class for integration resource management operations.\n * Holds only inter-service implementation (DAO calls). Validation (config, mapping exists)\n * lives in provider wrappers (e.g. TrybeIntegrationResourceManagementService).\n * MS is responsible for getOffering, getIntegration, updateOffering, runAfterAddIfNeeded.\n */\nexport abstract class BaseIntegrationResourceManagement {\n private readonly fileName = 'integration-resource-management.base';\n\n constructor(\n protected readonly integrationResourceManagementDao: IntegrationResourceManagementDao,\n protected readonly logger: LoggerService,\n ) {}\n\n /**\n * Adds a resource (capability integration) to an offering integration via UIF.\n * Inter-service implementation only: performs DAO insert. Wrapper must validate\n * config and mapping-exists before calling; caller (MS) does getOffering, getIntegration,\n * updateOffering and runAfterAddIfNeeded.\n *\n * @param input - projectId, offeringId, capabilityIntegrationId, optional config\n * @param context - GraphQL context\n * @returns Promise resolving to { status, ids }\n */\n async addResourceToIntegration(input: IAddResourceToIntegrationInput, context: GraphQLContext): Promise<IAddResourceToIntegrationResponse> {\n this.logger.info(context.loggedInUserId, this.addResourceToIntegration.name, this.fileName, 'addResourceToIntegration called', {\n offeringId: input.offeringId.toString(),\n capabilityIntegrationId: input.capabilityIntegrationId.toString(),\n });\n\n const addResult = await this.integrationResourceManagementDao.addCapabilityIntegrationMapping(\n {\n projectId: input.projectId,\n capabilityIntegrationId: input.capabilityIntegrationId,\n configuredForId: input.offeringId,\n configuredForType: CONFIGURED_FOR_TYPE_ENUM.OFFERING,\n config: input.config,\n },\n context,\n );\n\n const result: IAddResourceToIntegrationResponse = {\n status: addResult.status,\n ids: addResult.ids,\n };\n\n this.logger.info(context.loggedInUserId, this.addResourceToIntegration.name, this.fileName, 'addResourceToIntegration completed', {\n status: result.status,\n idsCount: result.ids.length,\n });\n\n return result;\n }\n\n /**\n * Removes a resource from an offering integration.\n * Generic validation and DAO call; Trybe service adds mapping-exists check before calling.\n */\n async removeResourceFromIntegration(\n request: IRemoveResourceFromIntegrationRequest,\n context: GraphQLContext,\n ): Promise<IRemoveResourceFromIntegrationResponse> {\n const result = await this.integrationResourceManagementDao.removeCapabilityIntegrationMapping(\n {\n capabilityIntegrationId: request.capabilityIntegrationId,\n configuredForId: request.offeringId,\n configuredForType: CONFIGURED_FOR_TYPE_ENUM.OFFERING,\n },\n context,\n );\n\n return { status: result.status };\n }\n\n /**\n * Updates offering integration resource configuration (cap_integ_resource_mapping.config by id).\n * Inter-service implementation only: performs DAO update. Wrapper must validate config before calling\n * (e.g. Trybe validates via validateResourceMappingConfig). Caller (MS) does getOffering,\n * getIntegration, and runAfterUpdateIfNeeded (e.g. handleTrybeIntegration).\n *\n * @param input - id (resource mapping row id), config\n * @param context - GraphQL context\n * @returns Promise resolving to { status }\n */\n async updateOfferingIntegrationResourceConfiguration(\n input: IUpdateOfferingIntegrationResourceConfigurationInput,\n context: GraphQLContext,\n ): Promise<IUpdateOfferingIntegrationResourceConfigurationResponse> {\n this.logger.info(\n context.loggedInUserId,\n this.updateOfferingIntegrationResourceConfiguration.name,\n this.fileName,\n 'updateOfferingIntegrationResourceConfiguration called',\n { id: input.id.toString() },\n );\n\n const result = await this.integrationResourceManagementDao.updateCapabilityIntegrationConfiguration(\n {\n id: input.id,\n config: input.config,\n },\n context,\n );\n\n this.logger.info(\n context.loggedInUserId,\n this.updateOfferingIntegrationResourceConfiguration.name,\n this.fileName,\n 'updateOfferingIntegrationResourceConfiguration completed',\n { status: result.status },\n );\n\n return { status: result.status };\n }\n}\n","import {\n IDeleteDeviceInput,\n IDeleteDeviceResponse,\n IGetDeviceKeyInput,\n IGetDeviceKeyResponse,\n IGetDevicesInput,\n IGetDevicesResponse,\n IRegisterDeviceInput,\n IRegisterDeviceResponse,\n IUpdateDeviceCertificateInput,\n IUpdateDeviceCertificateResponse,\n} from '../../models/device-management.model';\nimport { IAdminCredentials, IConfiguration } from '../../models/customer-management.model';\n\n/**\n * Base abstract class for device management operations\n * Provides a foundation for implementing device management functionality\n * within capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific device management operations for different systems\n */\nexport abstract class BaseDeviceManagement {\n /**\n * Initializes the customer management service with configuration and credentials\n *\n * This method sets up the service by:\n * 1. Storing the configuration settings\n * 2. Authenticating with the identity server\n * 3. Creating an authenticated Axios instance\n * 4. Setting up authorization headers for subsequent requests\n *\n * @param configuration - system configuration\n * @param credentials - Optional admin credentials (uses config credentials if not provided)\n */\n abstract init(configuration: IConfiguration, credentials?: IAdminCredentials): Promise<void>;\n\n /**\n * Registers a new device with the access control system\n *\n * @param request - Device registration input\n * @param loggedInUserId - User ID for logging\n * @returns Promise resolving to the registered device\n */\n\n abstract registerAcsDevice(request: IRegisterDeviceInput, loggedInUserId: bigint): Promise<IRegisterDeviceResponse>;\n\n /**\n * Deregisters a device from the access control system\n *\n * @param request - Device deregistration input\n * @param loggedInUserId - User ID for logging\n * @returns Promise resolving to the deregistered device\n */\n\n abstract deregisterAcsDevice(request: IDeleteDeviceInput, loggedInUserId: bigint): Promise<IDeleteDeviceResponse>;\n\n /**\n * Retrieves devices from the access control system\n *\n * @param request - Device retrieval input\n * @param loggedInUserId - User ID for logging\n * @returns Promise resolving to the retrieved devices\n */\n\n abstract getDevices(request: IGetDevicesInput, loggedInUserId: bigint): Promise<IGetDevicesResponse>;\n\n /**\n * Update device certificate from the control system\n *\n * @param request\n * @param loggedInUserId\n * @returns Promise resolving the updated device certificates\n */\n\n abstract updateDeviceCertificate(request: IUpdateDeviceCertificateInput, loggedInUserId: bigint): Promise<IUpdateDeviceCertificateResponse>;\n\n /**\n * Retrieves the device key from the control system\n *\n * @param request - Device key retrieval input\n * @param loggedInUserId - User ID for logging\n * @returns Promise resolving the device key\n */\n\n abstract getDeviceKey(request: IGetDeviceKeyInput, loggedInUserId: bigint): Promise<IGetDeviceKeyResponse>;\n\n /**\n * Retrieves the device from the control system\n *\n * @param request - Device retrieval input\n * @param loggedInUserId - User ID for logging\n * @returns Promise resolving the device\n */\n\n abstract getDevice(request: IGetDeviceKeyInput, loggedInUserId: bigint): Promise<IRegisterDeviceResponse>;\n\n /**\n * Retrieves the device keys for a user from the control system\n *\n * @param request - User device keys retrieval input\n * @param loggedInUserId - User ID for logging\n * @returns Promise resolving the user device keys\n */\n\n abstract getSiteUserDeviceKeys(request: { userId: string }, loggedInUserId: bigint): Promise<Array<{ id: string; key_uid: string }>>;\n}\n","import { IGetAccessProfilesResponse } from '../../models/access-management.model';\nimport { IAdminCredentials, IConfiguration } from '../../models/customer-management.model';\nimport { IGetDevicesInput } from '../../models/device-management.model';\n\n/**\n * Base abstract class for access management operations\n * Provides a foundation for implementing access management functionality\n * within capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific access management operations for different systems\n */\nexport abstract class BaseAccessManagement {\n /**\n * Initializes the customer management service with configuration and credentials\n *\n * This method sets up the service by:\n * 1. Storing the configuration settings\n * 2. Authenticating with the identity server\n * 3. Creating an authenticated Axios instance\n * 4. Setting up authorization headers for subsequent requests\n *\n * @param configuration - system configuration\n * @param credentials - Optional admin credentials (uses config credentials if not provided)\n */\n abstract init(configuration: IConfiguration, credentials?: IAdminCredentials): Promise<void>;\n\n /**\n * Retrieves the access profiles from the access control system\n *\n * @param request - Access profiles retrieval input [Optional]\n * @param loggedInUserId - User ID for logging\n * @returns Promise resolving the access profiles\n */\n abstract getAccessProfiles(request?: IGetDevicesInput, loggedInUserId?: bigint): Promise<IGetAccessProfilesResponse>;\n}\n","import { ICapabilityIntegration, IAccountingAPIResponse } from '../../../../integration-common-utils';\nimport {\n GetCustomerActivitiesInput,\n IAccounts,\n IAvailableTaxes,\n IDownloadCustomerAccountingStatementRequest,\n IGetCustomerActivities,\n ITransactionNumberSeries,\n} from '../../../models/miscellaneous.model';\n\n/**\n * Base abstract class for accounting miscellaneous management operations\n * Provides a foundation for implementing miscellaneous management functionality\n * within accounting capabilities\n *\n * This class should be extended by concrete implementations that provide\n * specific miscellaneous management operations for different accounting systems\n */\nexport abstract class BaseAccountingMiscellaneousManagement {\n /**\n * Retrieve bank & cash accounts from the accounting system.\n *\n * @returns Promise resolving to an array of {@link IAccounts}\n */\n abstract getAccounts(integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IAccounts[]>;\n\n /**\n * Fetches taxes from Zoho Books API\n *\n * @param integration - The Zoho Books integration configuration\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise resolving to list of taxes\n */\n abstract getTaxes(integration: ICapabilityIntegration, loggedInUserId: bigint, page?: number, limit?: number): Promise<IAvailableTaxes[]>;\n\n /**\n * Retrieve transaction number series from the accounting system.\n *\n * @param integration - The accounting integration configuration\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise resolving to list of transaction number series groups\n */\n abstract getTransactionNumberSeries(integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<ITransactionNumberSeries[]>;\n\n abstract downloadCustomerAccountingStatement(\n request: IDownloadCustomerAccountingStatementRequest,\n capabilityIntegration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<ArrayBuffer>;\n\n /**\n * Fetches list of all active items from Zoho Books API\n *\n * @param integration - The Zoho Books integration configuration\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise resolving to list of taxes\n */\n abstract listItems(integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IAccountingAPIResponse>;\n\n abstract getCustomerActivities(\n input: GetCustomerActivitiesInput,\n capabilityIntegration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IGetCustomerActivities>;\n}\n","import type { ICapabilityIntegration } from '../../../integration-common-utils';\nimport type { IGetResourcesRequest, IGetResourcesResponse } from '../../models/resource-management.model';\n\n/**\n * Base abstract class for calendar resource discovery (rooms / resource mailboxes).\n * Provider packages (e.g. Microsoft Graph) extend this with concrete API calls.\n */\nexport abstract class BaseCalendarResourceManagement {\n /**\n * Discovers calendar resources from the provider (e.g. Exchange room mailboxes).\n */\n abstract getResources(request: IGetResourcesRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IGetResourcesResponse>;\n}\n","import type { ICapabilityIntegration } from '../../../integration-common-utils';\nimport type {\n IBookingEventRef,\n ICancelEventRequest,\n ICreateEventRequest,\n IDeleteEventRequest,\n IGetEventsRequest,\n IGetEventsResponse,\n IUpdateEventRequest,\n} from '../../models/booking-management.model';\n\n/**\n * Base abstract class for OUTBOUND calendar event / booking lifecycle operations\n * (DVSS → provider). Provider packages extend this to implement Graph, Google Calendar, etc.\n *\n * `getEvents` is the one read: a narrow calendarView lookup that backs editing a single\n * occurrence of a recurring series. There is no inbound (provider → DVSS) reconciliation here.\n */\nexport abstract class BaseCalendarBookingManagement {\n abstract createEvent(request: ICreateEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IBookingEventRef>;\n\n abstract updateEvent(request: IUpdateEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IBookingEventRef>;\n\n abstract cancelEvent(request: ICancelEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<void>;\n\n abstract deleteEvent(request: IDeleteEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<void>;\n\n abstract getEvents(request: IGetEventsRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IGetEventsResponse>;\n}\n","import type { ICapabilityIntegration } from '../../../integration-common-utils';\nimport type {\n IDeleteWebhookRequest,\n IRefreshWebhookRequest,\n IRefreshWebhookResponse,\n IRegisterWebhookRequest,\n IRegisterWebhookResponse,\n} from '../../models/webhook-management.model';\n\n/**\n * Base abstract class for calendar webhook / change-notification subscriptions.\n * Providers with expiring subscriptions (e.g. Microsoft Graph) implement register, refresh, and delete.\n */\nexport abstract class BaseCalendarWebhookManagement {\n abstract registerWebhook(request: IRegisterWebhookRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IRegisterWebhookResponse>;\n\n abstract refreshSubscription(\n request: IRefreshWebhookRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IRefreshWebhookResponse>;\n\n abstract deleteSubscription(request: IDeleteWebhookRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<void>;\n}\n","import { appConstants, schema } from '@dv4resi/dvss-backend-module-datastore';\nimport { LoggerService } from '@dv4resi/dvss-backend-module-utility';\nimport { Inject, Injectable } from '@nestjs/common';\nimport { and, eq, isNull } from 'drizzle-orm';\nimport type { MySql2Database } from 'drizzle-orm/mysql2';\nimport { IOfferingBookingOccurrence } from './models';\n\n/**\n * DAO for loading offering booking and related entities used when building\n */\n@Injectable()\nexport class IntegrationBookingDao {\n private readonly fileName = 'integration-booking.dao';\n\n constructor(\n @Inject(appConstants.DB_CONNECTION)\n private readonly conn: MySql2Database<typeof schema>,\n private readonly logger: LoggerService,\n ) {}\n\n async getOfferingBookingOccurrence(input: {\n offeringBookingOccurrenceId: bigint;\n loggedInUserId: bigint;\n offeringBookingId?: bigint;\n }): Promise<IOfferingBookingOccurrence | undefined> {\n this.logger.debug(\n input.loggedInUserId,\n this.getOfferingBookingOccurrence.name,\n this.fileName,\n 'Getting offering booking occurrence with input: ',\n input,\n );\n const conditions = [\n isNull(schema.offeringBookingOccurrence.deletedAt),\n eq(schema.offeringBookingOccurrence.id, input.offeringBookingOccurrenceId),\n isNull(schema.offeringBooking.deletedAt),\n isNull(schema.offering.deletedAt),\n ];\n if (input.offeringBookingId != null) {\n conditions.push(eq(schema.offeringBooking.id, input.offeringBookingId));\n }\n const result = await this.conn\n .select({\n offeringBookingOccurrence: schema.offeringBookingOccurrence,\n offering: schema.offering,\n offeringIntentId: schema.offeringBooking.offeringIntentId,\n })\n .from(schema.offeringBookingOccurrence)\n .innerJoin(schema.offeringBooking, eq(schema.offeringBookingOccurrence.offeringBookingId, schema.offeringBooking.id))\n .innerJoin(schema.offering, eq(schema.offeringBooking.offeringId, schema.offering.id))\n .where(and(...conditions))\n .limit(1);\n if (!result[0] || result[0].offeringIntentId == null) return undefined;\n return {\n offeringBookingOccurrence: result[0].offeringBookingOccurrence,\n offering: result[0].offering,\n offeringIntentId: result[0].offeringIntentId,\n };\n }\n /**\n * Fetches offering intent by id.\n */\n async getOfferingIntent(input: { offeringIntentId: bigint }): Promise<typeof schema.offeringIntent.$inferSelect | undefined> {\n const row = await this.conn.query.offeringIntent.findFirst({\n where: and(isNull(schema.offeringIntent.deletedAt), eq(schema.offeringIntent.id, input.offeringIntentId)),\n });\n return row ?? undefined;\n }\n}\n","import { appConstants, schema } from '@dv4resi/dvss-backend-module-datastore';\nimport { DEFAULT_TIMEZONE, LoggerService } from '@dv4resi/dvss-backend-module-utility';\nimport { Inject, Injectable } from '@nestjs/common';\nimport { and, eq, isNotNull, isNull } from 'drizzle-orm';\nimport type { MySql2Database } from 'drizzle-orm/mysql2';\n\n/**\n * Common DAO for integration utilities.\n * Provides shared database operations used across integrations.\n */\n@Injectable()\nexport class IntegrationCommonDao {\n private readonly fileName = 'integration-common.dao';\n\n constructor(\n @Inject(appConstants.DB_CONNECTION)\n private readonly conn: MySql2Database<typeof schema>,\n private readonly logger: LoggerService,\n ) {}\n\n /**\n * Gets timezone using userContext (first propertyId) with fallback to projectId\n * First tries to get timezone from user's first propertyId, then falls back to projectId\n * @param input - Object containing projectId and loggedInUserId\n * @returns Promise resolving to timezone string\n */\n async getTimezoneForRequest(input: { projectId?: number; loggedInUserId: bigint }): Promise<string> {\n const { projectId, loggedInUserId } = input;\n\n try {\n // First, try to get timezone from userContext (user's first propertyId)\n const userBehavior = await this.conn.query.userIdentityBehaviorMapping.findFirst({\n where: and(\n eq(schema.userIdentityBehaviorMapping.userIdentityId, loggedInUserId),\n isNotNull(schema.userIdentityBehaviorMapping.propertyId),\n isNull(schema.userIdentityBehaviorMapping.deletedAt),\n ),\n with: {\n property: true,\n },\n });\n\n if (userBehavior?.propertyId && userBehavior.property?.timezone) {\n this.logger.info(loggedInUserId, this.getTimezoneForRequest.name, this.fileName, 'Successfully fetched property timezone using userContext', {\n projectId,\n loggedInUserId,\n propertyId: userBehavior.propertyId,\n timezone: userBehavior.property.timezone,\n });\n return userBehavior.property.timezone;\n }\n\n // Fallback: use projectId to fetch properties and use the first propertyId to fetch timezone\n if (projectId) {\n const properties = await this.conn.query.property.findMany({\n where: and(eq(schema.property.projectId, projectId), isNull(schema.property.deletedAt)),\n limit: 1,\n });\n\n if (properties.length > 0 && properties[0].timezone) {\n this.logger.info(loggedInUserId, this.getTimezoneForRequest.name, this.fileName, 'Successfully fetched property timezone using projectId', {\n projectId,\n propertyId: properties[0].id,\n timezone: properties[0].timezone,\n });\n return properties[0].timezone;\n }\n }\n } catch (error: unknown) {\n this.logger.warn(loggedInUserId, this.getTimezoneForRequest.name, this.fileName, 'Error fetching property timezone, using default', {\n projectId,\n error,\n });\n }\n\n return DEFAULT_TIMEZONE;\n }\n}\n","import { appConstants, schema } from '@dv4resi/dvss-backend-module-datastore';\nimport { LoggerService } from '@dv4resi/dvss-backend-module-utility';\nimport { Inject, Injectable } from '@nestjs/common';\nimport { and, eq, isNull } from 'drizzle-orm';\nimport type { MySql2Database } from 'drizzle-orm/mysql2';\nimport { ISubCapability } from './models/integration-subcapability.model';\n\n@Injectable()\nexport class IntegrationSubcapabilityDao {\n private readonly fileName = 'integration-subcapability.dao';\n\n constructor(\n @Inject(appConstants.DB_CONNECTION)\n private readonly conn: MySql2Database<typeof schema>,\n private readonly logger: LoggerService,\n ) {}\n\n /**\n * Returns subcapability id for given capabilityId and subcapability name.\n * Enforces uniqueness: if more than one active row is found, throws an error.\n * If no active row is found, returns undefined (caller decides how to handle).\n */\n async getSubcapabilityId(input: { capabilityId: bigint; name: string }, loggedInUserId: bigint): Promise<bigint | undefined> {\n this.logger.info(loggedInUserId, this.getSubcapabilityId.name, this.fileName, 'IntegrationSubcapabilityDao -> getSubcapabilityId called', { input });\n\n try {\n const rows = await this.conn.query.subcapability.findMany({\n where: and(\n eq(schema.subcapability.capabilityId, input.capabilityId),\n eq(schema.subcapability.name, input.name),\n isNull(schema.subcapability.deletedAt),\n ),\n });\n\n if (rows.length === 0) {\n // Let caller decide how to surface \"not found\"\n this.logger.error(loggedInUserId, this.getSubcapabilityId.name, this.fileName, 'Subcapability not found for given capabilityId and name', {\n input,\n });\n return undefined;\n }\n\n return rows[0].id;\n } catch (error) {\n this.logger.error(loggedInUserId, this.getSubcapabilityId.name, this.fileName, 'Error in getSubcapabilityId', error, { input });\n throw error;\n }\n }\n\n async getSubcapabilities(input: { capabilityId: bigint }, loggedInUserId: bigint): Promise<ISubCapability[]> {\n this.logger.info(loggedInUserId, this.getSubcapabilities.name, this.fileName, 'IntegrationSubcapabilityDao -> getSubcapabilities called', { input });\n\n try {\n return await this.conn.query.subcapability.findMany({\n where: and(eq(schema.subcapability.capabilityId, input.capabilityId), isNull(schema.subcapability.deletedAt)),\n });\n } catch (error) {\n this.logger.error(loggedInUserId, this.getSubcapabilities.name, this.fileName, 'Error in getSubcapabilities', error, { input });\n throw error;\n }\n }\n}\n","import { schema } from '@dv4resi/dvss-backend-module-datastore';\nimport { CONFIGURED_FOR_TYPE_ENUM } from '@dv4resi/dvss-backend-module-datastore/dist/datastore/models';\nimport { CAPABILITY_INTEGRATION_STATUS_ENUM } from '@dv4resi/dvss-backend-module-datastore/dist/datastore/models/capability-integration.model';\nimport { and, eq, isNull } from 'drizzle-orm';\nimport type { MySql2Database } from 'drizzle-orm/mysql2';\n\nexport class IntegrationVisitorCredentialMappingDao {\n private readonly generateVisitorCredentialConfigKey = 'generateCredentialsForVisitor';\n private readonly capIntegResourceMappingOfficeVisitorType = CONFIGURED_FOR_TYPE_ENUM.OFFICE_VISITOR_CONFIGURATION;\n\n extractGenerateCredentialsForVisitorValue(config: unknown): boolean | undefined {\n if (!config || typeof config !== 'object') {\n return undefined;\n }\n\n const integrationConfig = (config as { integrationConfig?: Record<string, unknown> }).integrationConfig;\n const value = integrationConfig?.[this.generateVisitorCredentialConfigKey];\n\n return typeof value === 'boolean' ? value : undefined;\n }\n\n async syncVisitorCredentialMapping(input: {\n db: Pick<MySql2Database<typeof schema>, 'query' | 'insert' | 'update'>;\n capabilityIntegrationId: bigint;\n projectId: number;\n isGenerateCredentialsForVisitorEnabled: boolean | undefined;\n loggedInUserId: bigint;\n createOnly: boolean;\n }): Promise<void> {\n const isGenerateCredentialEnabled = Boolean(input.isGenerateCredentialsForVisitorEnabled);\n\n if (!isGenerateCredentialEnabled && input.createOnly) {\n return;\n }\n\n const officeVisitorConfigProfile = await input.db.query.officeVisitorConfigProfile.findFirst({\n where: and(eq(schema.officeVisitorConfigProfile.projectId, input.projectId), isNull(schema.officeVisitorConfigProfile.deletedAt)),\n });\n\n if (!officeVisitorConfigProfile) {\n return;\n }\n\n const capIntegResourceMapping = await input.db.query.capIntegResourceMapping.findFirst({\n where: and(\n eq(schema.capIntegResourceMapping.capabilityIntegrationId, input.capabilityIntegrationId),\n eq(schema.capIntegResourceMapping.configuredForType, this.capIntegResourceMappingOfficeVisitorType),\n eq(schema.capIntegResourceMapping.configuredForId, officeVisitorConfigProfile.id),\n isNull(schema.capIntegResourceMapping.deletedAt),\n ),\n });\n\n const currentConfig = capIntegResourceMapping?.config as { generateCredential?: unknown } | null | undefined;\n const isCurrentGenerateCredentialEnabled = currentConfig?.generateCredential === true;\n\n if (capIntegResourceMapping) {\n if (isCurrentGenerateCredentialEnabled !== isGenerateCredentialEnabled) {\n await input.db\n .update(schema.capIntegResourceMapping)\n .set({\n config: {\n generateCredential: isGenerateCredentialEnabled,\n },\n updatedAt: new Date(),\n updatedBy: input.loggedInUserId,\n })\n .where(eq(schema.capIntegResourceMapping.id, capIntegResourceMapping.id));\n }\n\n return;\n }\n\n if (!isGenerateCredentialEnabled) {\n return;\n }\n\n await input.db.insert(schema.capIntegResourceMapping).values({\n projectId: input.projectId,\n configuredForId: officeVisitorConfigProfile.id,\n configuredForType: this.capIntegResourceMappingOfficeVisitorType,\n capabilityIntegrationId: input.capabilityIntegrationId,\n config: {\n generateCredential: true,\n },\n createdBy: input.loggedInUserId,\n status: CAPABILITY_INTEGRATION_STATUS_ENUM.ACTIVE,\n });\n }\n}\n","import { appConstants, MAX_RECORDS_LENGTH, schema } from '@dv4resi/dvss-backend-module-datastore';\nimport { SORTING_ORDER_ENUM } from '@dv4resi/dvss-backend-module-datastore/dist/datastore/commons/common.enum';\nimport { CONFIGURED_FOR_TYPE_ENUM } from '@dv4resi/dvss-backend-module-datastore/dist/datastore/models';\nimport {\n CAP_INTEG_SUBCAPABILITY_MAPPING_STATUS_ENUM,\n CAPABILITY_INTEGRATION_STATUS_ENUM,\n} from '@dv4resi/dvss-backend-module-datastore/dist/datastore/models/capability-integration.model';\nimport {\n type ICapability,\n CAPABILITY_TYPE_ENUM,\n type CAPABILITY_CATEGORY_ENUM,\n} from '@dv4resi/dvss-backend-module-datastore/dist/datastore/models/capability.model';\nimport { LoggerService } from '@dv4resi/dvss-backend-module-utility';\nimport { Inject, Injectable } from '@nestjs/common';\nimport { and, asc, desc, eq, getTableColumns, inArray, isNotNull, isNull, or, type SQL, sql } from 'drizzle-orm';\nimport type { MySqlColumn } from 'drizzle-orm/mysql-core';\nimport type { MySql2Database } from 'drizzle-orm/mysql2';\n\nimport type { ICapabilityIntegration } from '../../integration-operation-skeletons/models/capability-integration.model';\nimport type {\n IGetCapabilityIntegrationsRequest,\n IGetCapabilityIntegrationsResponse,\n} from '../../integration-operation-skeletons/models/integration-configuration.model';\nimport {\n CapabilityIntegrationCategory,\n IAddCapabilityIntegration,\n IAddCapIntegResourceMapping,\n IUpdateCapabilityIntegration,\n type IGetCapabilityIntegrationResult,\n} from './models';\nimport { IntegrationSubcapabilityDao } from './integration-subcapability.dao';\nimport { IAddCapIntegSubcapabilityMapping } from './models/integration-subcapability.model';\nimport { IntegrationVisitorCredentialMappingDao } from './integration-visitor-credential-mapping.dao';\n\n/**\n * DAO for integration-configuration persistence (offering get/update).\n * Performs actual DB calls using datastore schema; conn is injected by the host app.\n */\n@Injectable()\nexport class IntegrationConfigurationDao {\n private readonly fileName = 'integration-configuration.dao';\n private readonly integrationVisitorCredentialMappingDao = new IntegrationVisitorCredentialMappingDao();\n\n constructor(\n @Inject(appConstants.DB_CONNECTION)\n private readonly conn: MySql2Database<typeof schema>,\n private readonly logger: LoggerService,\n private readonly integrationSubcapabilityDao: IntegrationSubcapabilityDao,\n ) {}\n\n async addCapabilityIntegration(input: IAddCapabilityIntegration, loggedInUserId: bigint): Promise<{ id: bigint } | undefined> {\n // Log the attempt to add a capability integration\n this.logger.info(loggedInUserId, this.addCapabilityIntegration.name, this.fileName, `CapabilityDaoService -> addCapabilityIntegration called`);\n\n try {\n // Run operations in a transaction\n return this.conn.transaction(async (tx) => {\n const { configuredFor, resourceMappings, ...capabilityIntegrationInsertInput } = input;\n\n // Insert the capability integration record and get its ID\n const [integrationResult] = await tx.insert(schema.capabilityIntegration).values(capabilityIntegrationInsertInput).$returningId();\n\n if (!integrationResult.id) {\n // rollback if insertion failed\n tx.rollback();\n return;\n }\n\n // Add mapping rows (resourceMappings takes precedence; configuredFor kept for backwards compatibility)\n if (resourceMappings?.length) {\n for (const mapping of resourceMappings) {\n const insertData: IAddCapIntegResourceMapping = {\n capabilityIntegrationId: integrationResult.id,\n configuredForId: mapping.configuredForId,\n configuredForType: mapping.configuredForType,\n status: CAPABILITY_INTEGRATION_STATUS_ENUM.ACTIVE,\n projectId: input.projectId,\n config: mapping.config ?? undefined,\n createdAt: new Date(),\n createdBy: loggedInUserId,\n };\n\n await tx.insert(schema.capIntegResourceMapping).values(insertData);\n }\n } else if (configuredFor) {\n const insertData: IAddCapIntegResourceMapping = {\n capabilityIntegrationId: integrationResult.id,\n configuredForId: configuredFor.configuredForId,\n configuredForType: configuredFor.configuredForType,\n status: CAPABILITY_INTEGRATION_STATUS_ENUM.ACTIVE,\n projectId: input.projectId,\n createdAt: new Date(),\n createdBy: loggedInUserId,\n };\n\n await tx.insert(schema.capIntegResourceMapping).values(insertData);\n }\n\n const subcapabilities = await this.integrationSubcapabilityDao.getSubcapabilities({ capabilityId: input.capabilityId }, loggedInUserId);\n\n this.logger.info(\n loggedInUserId,\n this.addCapabilityIntegration.name,\n this.fileName,\n `Subcapabilities ${subcapabilities.length} found for capabilityIntegrationId: ${integrationResult.id}`,\n );\n\n for (const subcapability of subcapabilities) {\n const insertData: IAddCapIntegSubcapabilityMapping = {\n capabilityIntegrationId: integrationResult.id,\n subcapabilityId: subcapability.id,\n projectId: input.projectId,\n createdAt: new Date(),\n createdBy: loggedInUserId,\n status: CAP_INTEG_SUBCAPABILITY_MAPPING_STATUS_ENUM.ACTIVE,\n };\n await tx.insert(schema.capIntegSubcapabilityMapping).values(insertData);\n }\n\n await this.integrationVisitorCredentialMappingDao.syncVisitorCredentialMapping({\n db: tx,\n capabilityIntegrationId: integrationResult.id,\n projectId: input.projectId,\n isGenerateCredentialsForVisitorEnabled: this.integrationVisitorCredentialMappingDao.extractGenerateCredentialsForVisitorValue(input.config),\n loggedInUserId,\n createOnly: true,\n });\n\n return { id: integrationResult.id };\n });\n } catch (error) {\n // Log and rethrow\n this.logger.error(loggedInUserId, this.addCapabilityIntegration.name, this.fileName, 'Error in addCapabilityIntegration', error, input);\n\n throw error;\n }\n }\n\n /**\n * Get capability by id (for add-capability-integration validation).\n * Copied from project-ms CapabilityDaoService.getCapability.\n */\n async getCapability(request: { capabilityId: bigint }, loggedInUserId: bigint): Promise<ICapability | undefined> {\n try {\n this.logger.info(loggedInUserId, this.getCapability.name, this.fileName, 'getCapability called', { request });\n\n return await this.conn.query.capability.findFirst({\n where: and(eq(schema.capability.id, request.capabilityId), isNull(schema.capability.deletedAt)),\n });\n } catch (error) {\n this.logger.error(loggedInUserId, this.getCapability.name, this.fileName, 'Error on getCapability', error, { request });\n\n throw error;\n }\n }\n\n /**\n * Get capability provider by id (for add-capability-integration validation).\n * Copied from project-ms CapabilityProviderDao.getCapabilityProvider.\n */\n async getCapabilityProvider(\n request: { capabilityProviderId: bigint },\n loggedInUserId: bigint,\n ): Promise<typeof schema.capabilityProvider.$inferSelect | undefined> {\n try {\n this.logger.info(loggedInUserId, this.getCapabilityProvider.name, this.fileName, 'getCapabilityProvider called', { request });\n\n return await this.conn.query.capabilityProvider.findFirst({\n where: and(eq(schema.capabilityProvider.id, request.capabilityProviderId), isNull(schema.capabilityProvider.deletedAt)),\n });\n } catch (error) {\n this.logger.error(loggedInUserId, this.getCapabilityProvider.name, this.fileName, 'Error on getCapabilityProvider', error, { request });\n\n throw error;\n }\n }\n\n /**\n * Updates capability integration in the database.\n * Copied from project-ms CapabilityIntegrationDao.updateCapabilityIntegration.\n *\n * @param input - Object containing the integration ID and update data\n * @param loggedInUserId - User ID for logging\n * @returns Promise that resolves to the update operation status\n */\n async updateCapabilityIntegration(\n input: {\n id: bigint;\n updateData: IUpdateCapabilityIntegration;\n projectId: number;\n },\n loggedInUserId: bigint,\n ): Promise<{ status: boolean }> {\n try {\n this.logger.info(loggedInUserId, this.updateCapabilityIntegration.name, this.fileName, 'Updating capability integration', { input });\n\n const response = await this.conn\n .update(schema.capabilityIntegration)\n .set({\n ...input.updateData,\n })\n .where(eq(schema.capabilityIntegration.id, input.id));\n\n const isGenerateCredentialsForVisitorEnabled = this.integrationVisitorCredentialMappingDao.extractGenerateCredentialsForVisitorValue(\n input.updateData.config,\n );\n if (typeof isGenerateCredentialsForVisitorEnabled === 'boolean') {\n await this.integrationVisitorCredentialMappingDao.syncVisitorCredentialMapping({\n db: this.conn,\n capabilityIntegrationId: input.id,\n projectId: input.projectId,\n isGenerateCredentialsForVisitorEnabled,\n loggedInUserId,\n createOnly: false,\n });\n }\n\n return {\n status: response[0].affectedRows > 0,\n };\n } catch (error) {\n this.logger.error(loggedInUserId, this.updateCapabilityIntegration.name, this.fileName, 'Error updating capability integration', error);\n\n throw error;\n }\n }\n\n async updateCapabilityIntegrationAccessDetails(\n capabilityIntegrationId: bigint,\n accessToken: string,\n expiresInSeconds: number,\n loggedInUserId: bigint,\n ): Promise<void> {\n try {\n this.logger.info(\n loggedInUserId,\n this.updateCapabilityIntegrationAccessDetails.name,\n this.fileName,\n 'Updating capability integration access details',\n { capabilityIntegrationId },\n );\n\n const expiryAtExpression = sql`DATE_FORMAT(UTC_TIMESTAMP() + INTERVAL ${expiresInSeconds} SECOND, '%Y-%m-%dT%H:%i:%sZ')`;\n\n await this.conn\n .update(schema.capabilityIntegration)\n .set({\n config: sql`\n JSON_SET(\n JSON_SET(\n COALESCE(${schema.capabilityIntegration.config}, JSON_OBJECT()),\n '$.accessDetails',\n COALESCE(JSON_EXTRACT(COALESCE(${schema.capabilityIntegration.config}, JSON_OBJECT()), '$.accessDetails'), JSON_OBJECT())\n ),\n '$.accessDetails.accessToken', ${accessToken},\n '$.accessDetails.expiryAt', ${expiryAtExpression}\n )\n `,\n updatedBy: loggedInUserId,\n })\n .where(and(eq(schema.capabilityIntegration.id, capabilityIntegrationId), isNull(schema.capabilityIntegration.deletedAt)));\n } catch (error) {\n this.logger.error(\n loggedInUserId,\n this.updateCapabilityIntegrationAccessDetails.name,\n this.fileName,\n 'Error updating capability integration access details',\n error,\n { capabilityIntegrationId },\n );\n\n throw error;\n }\n }\n\n /**\n * Replace cap_integ_resource_mapping rows for the given capabilityIntegrationId and configuredForTypes.\n * Upsert semantics: delete existing rows first, then insert the provided mappings.\n */\n async syncCapabilityIntegrationResourceMappings(\n input: {\n capabilityIntegrationId: bigint;\n projectId: number;\n resourceMappings: Array<{\n configuredForId: bigint;\n configuredForType: CONFIGURED_FOR_TYPE_ENUM;\n config?: typeof schema.capIntegResourceMapping.$inferSelect.config;\n }>;\n },\n loggedInUserId: bigint,\n ): Promise<{ status: boolean }> {\n try {\n if (input.resourceMappings.length === 0) {\n return { status: true };\n }\n\n const inputMap = new Map<string, (typeof input.resourceMappings)[number]>();\n for (const m of input.resourceMappings) {\n inputMap.set(`${m.configuredForId}:${m.configuredForType}`, m);\n }\n\n const inputKeys = new Set(inputMap.keys());\n\n return await this.conn.transaction(async (tx) => {\n const existing = await tx\n .select({\n id: schema.capIntegResourceMapping.id,\n configuredForId: schema.capIntegResourceMapping.configuredForId,\n configuredForType: schema.capIntegResourceMapping.configuredForType,\n })\n .from(schema.capIntegResourceMapping)\n .where(\n and(\n eq(schema.capIntegResourceMapping.capabilityIntegrationId, input.capabilityIntegrationId),\n eq(schema.capIntegResourceMapping.projectId, input.projectId),\n isNull(schema.capIntegResourceMapping.deletedAt),\n ),\n );\n\n const existingMap = new Map<string, (typeof existing)[number]>();\n for (const e of existing) {\n existingMap.set(`${e.configuredForId}:${e.configuredForType}`, e);\n }\n\n const toDeleteIds: bigint[] = [];\n for (const [key, value] of existingMap.entries()) {\n if (!inputKeys.has(key)) {\n toDeleteIds.push(value.id);\n }\n }\n\n const toInsert: IAddCapIntegResourceMapping[] = [];\n for (const [key, mapping] of inputMap.entries()) {\n if (!existingMap.has(key)) {\n toInsert.push({\n capabilityIntegrationId: input.capabilityIntegrationId,\n configuredForId: mapping.configuredForId,\n configuredForType: mapping.configuredForType,\n status: CAPABILITY_INTEGRATION_STATUS_ENUM.ACTIVE,\n projectId: input.projectId,\n config: mapping.config ?? undefined,\n createdAt: new Date(),\n createdBy: loggedInUserId,\n });\n }\n }\n\n if (toDeleteIds.length > 0) {\n await tx\n .update(schema.capIntegResourceMapping)\n .set({\n deletedAt: new Date(),\n deletedBy: loggedInUserId,\n })\n .where(inArray(schema.capIntegResourceMapping.id, toDeleteIds));\n }\n if (toInsert.length > 0) {\n await tx.insert(schema.capIntegResourceMapping).values(toInsert);\n }\n\n return { status: true };\n });\n } catch (error) {\n this.logger.error(\n loggedInUserId,\n this.syncCapabilityIntegrationResourceMappings.name,\n this.fileName,\n 'Error syncing capability integration resource mappings',\n error,\n input,\n );\n\n throw error;\n }\n }\n\n /**\n * Get capability integration by id (for parent validation when parentId is set).\n * Copied from project-ms CapabilityIntegrationDao.getCapabilityIntegration.\n */\n async getCapabilityIntegration(\n input: { capabilityIntegrationId: bigint },\n loggedInUserId: bigint,\n ): Promise<typeof schema.capabilityIntegration.$inferSelect | undefined> {\n try {\n this.logger.info(loggedInUserId, this.getCapabilityIntegration.name, this.fileName, 'getCapabilityIntegration called', input);\n\n return await this.conn.query.capabilityIntegration.findFirst({\n where: and(isNull(schema.capabilityIntegration.deletedAt), eq(schema.capabilityIntegration.id, input.capabilityIntegrationId)),\n });\n } catch (error) {\n this.logger.error(loggedInUserId, this.getCapabilityIntegration.name, this.fileName, 'Error on getCapabilityIntegration', error, input);\n\n throw error;\n }\n }\n\n /**\n * Retrieves capability integration by ID with resource mapping details.\n * Copied from project-ms CapabilityIntegrationDao.getCapabilityIntegrationById.\n */\n async getCapabilityIntegrationById(\n request: {\n id: bigint;\n projectId: number;\n category?: CAPABILITY_CATEGORY_ENUM;\n },\n loggedInUserId: bigint,\n ): Promise<IGetCapabilityIntegrationResult | undefined> {\n try {\n this.logger.info(loggedInUserId, this.getCapabilityIntegrationById.name, this.fileName, 'getCapabilityIntegrationById called', request);\n\n const conditions = [\n eq(schema.capabilityIntegration.id, request.id),\n eq(schema.capabilityIntegration.projectId, request.projectId),\n eq(schema.capabilityIntegration.type, CAPABILITY_TYPE_ENUM.INTEGRATION),\n eq(schema.capabilityIntegration.status, CAPABILITY_INTEGRATION_STATUS_ENUM.ACTIVE),\n isNull(schema.capabilityIntegration.deletedAt),\n isNull(schema.capability.deletedAt),\n ];\n\n if (request.category) {\n conditions.push(eq(schema.capabilityIntegration.category, request.category));\n }\n\n const response = await this.conn\n .select({\n ...getTableColumns(schema.capabilityIntegration),\n resourceMappingId: schema.capIntegResourceMapping.id,\n configuredForId: schema.capIntegResourceMapping.configuredForId,\n configuredForType: schema.capIntegResourceMapping.configuredForType,\n resourceMappingConfig: schema.capIntegResourceMapping.config,\n provider: schema.capability.providerIntegrationType,\n })\n .from(schema.capabilityIntegration)\n .innerJoin(schema.capability, eq(schema.capability.id, schema.capabilityIntegration.capabilityId))\n .leftJoin(\n schema.capIntegResourceMapping,\n and(\n eq(schema.capIntegResourceMapping.capabilityIntegrationId, schema.capabilityIntegration.id),\n eq(schema.capIntegResourceMapping.projectId, request.projectId),\n isNull(schema.capIntegResourceMapping.deletedAt),\n ),\n )\n .where(and(...conditions));\n\n return response[0] as unknown as IGetCapabilityIntegrationResult | undefined;\n } catch (error) {\n this.logger.error(loggedInUserId, this.getCapabilityIntegrationById.name, this.fileName, 'Error on getCapabilityIntegrationById', error, request);\n\n throw error;\n }\n }\n\n /**\n * Retrieves capability integration by provider type and resource mapping.\n * Copied from project-ms CapabilityIntegrationDao.getCapabilityIntegrationByProvider.\n */\n async getCapabilityIntegrationByProvider(\n request: {\n projectId: number;\n category?: CAPABILITY_CATEGORY_ENUM;\n configuredForType: CONFIGURED_FOR_TYPE_ENUM;\n configuredForId: bigint;\n },\n loggedInUserId: bigint,\n ): Promise<IGetCapabilityIntegrationResult | undefined> {\n try {\n this.logger.info(loggedInUserId, this.getCapabilityIntegrationByProvider.name, this.fileName, 'getCapabilityIntegrationByProvider called', request);\n\n const conditions = [\n isNull(schema.capability.deletedAt),\n eq(schema.capabilityIntegration.projectId, request.projectId),\n eq(schema.capabilityIntegration.type, CAPABILITY_TYPE_ENUM.INTEGRATION),\n eq(schema.capabilityIntegration.status, CAPABILITY_INTEGRATION_STATUS_ENUM.ACTIVE),\n isNull(schema.capabilityIntegration.deletedAt),\n eq(schema.capIntegResourceMapping.projectId, request.projectId),\n eq(schema.capIntegResourceMapping.configuredForType, request.configuredForType),\n eq(schema.capIntegResourceMapping.configuredForId, request.configuredForId),\n isNull(schema.capIntegResourceMapping.deletedAt),\n ];\n\n if (request.category) {\n conditions.push(eq(schema.capabilityIntegration.category, request.category));\n }\n\n const response = await this.conn\n .select({\n ...getTableColumns(schema.capabilityIntegration),\n resourceMappingId: schema.capIntegResourceMapping.id,\n configuredForId: schema.capIntegResourceMapping.configuredForId,\n configuredForType: schema.capIntegResourceMapping.configuredForType,\n resourceMappingConfig: schema.capIntegResourceMapping.config,\n provider: schema.capability.providerIntegrationType,\n })\n .from(schema.capabilityIntegration)\n .innerJoin(schema.capability, eq(schema.capability.id, schema.capabilityIntegration.capabilityId))\n .innerJoin(schema.capIntegResourceMapping, eq(schema.capIntegResourceMapping.capabilityIntegrationId, schema.capabilityIntegration.id))\n .where(and(...conditions));\n\n return response[0] as unknown as IGetCapabilityIntegrationResult | undefined;\n } catch (error) {\n this.logger.error(\n loggedInUserId,\n this.getCapabilityIntegrationByProvider.name,\n this.fileName,\n 'Error on getCapabilityIntegrationByProvider',\n error,\n request,\n );\n\n throw error;\n }\n }\n\n /**\n * Get capability integrations with pagination, filtering, sorting, and search.\n * Copied from project-ms CapabilityIntegrationDao.getCapabilityIntegrations.\n */\n async getCapabilityIntegrations(input: IGetCapabilityIntegrationsRequest, loggedInUserId: bigint): Promise<IGetCapabilityIntegrationsResponse> {\n try {\n this.logger.info(loggedInUserId, this.getCapabilityIntegrations.name, this.fileName, 'getCapabilityIntegrations called', input);\n\n const count = input.options?.count ?? MAX_RECORDS_LENGTH;\n const offset = ((input.options?.page ?? 1) - 1) * count;\n\n const sorting = input.options?.sorting;\n let sortBy: MySqlColumn = schema.capabilityIntegration.id;\n\n if (sorting?.by === 'CREATED_AT') {\n sortBy = schema.capabilityIntegration.createdAt;\n } else if (sorting?.by === 'UPDATED_AT') {\n sortBy = schema.capabilityIntegration.updatedAt;\n }\n\n const sortOrder: SQL = sorting?.order === SORTING_ORDER_ENUM.ASC ? asc(sortBy) : desc(sortBy);\n const searchTerm = input.options?.search;\n\n // Determine if we need capability table join (for search, provider filter)\n const shouldJoinCapability = Boolean(searchTerm) || Boolean(input.options?.filters?.some((filter) => filter.by === 'PROVIDER_INTEGRATION_TYPE'));\n\n // Build where conditions for data query\n const whereConditions: SQL[] = [eq(schema.capabilityIntegration.projectId, input.projectId), isNull(schema.capabilityIntegration.deletedAt)];\n\n if (input.category) {\n whereConditions.push(eq(schema.capabilityIntegration.category, input.category as CapabilityIntegrationCategory));\n }\n\n // Apply filters\n if (input.options?.filters && input.options.filters.length > 0) {\n this.applyFilters(whereConditions, input.options);\n }\n\n if (searchTerm) {\n const searchPattern = `%${searchTerm}%`;\n whereConditions.push(sql`(${schema.capabilityIntegration.nickname} LIKE ${searchPattern} OR ${schema.capability.name} LIKE ${searchPattern})`);\n }\n\n // Add capability deletedAt check if capability join is present\n if (shouldJoinCapability) {\n whereConditions.push(isNull(schema.capability.deletedAt));\n }\n\n // Filter out NULL mappings when propertyId is provided\n if (input.propertyId) {\n whereConditions.push(isNotNull(schema.capIntegResourceMapping.id));\n }\n\n // Build count query\n const countWhereConditions: SQL[] = [eq(schema.capabilityIntegration.projectId, input.projectId), isNull(schema.capabilityIntegration.deletedAt)];\n\n if (input.category) {\n countWhereConditions.push(eq(schema.capabilityIntegration.category, input.category as CapabilityIntegrationCategory));\n }\n\n if (input.options?.filters && input.options.filters.length > 0) {\n this.applyFilters(countWhereConditions, input.options);\n }\n\n if (searchTerm) {\n const searchPattern = `%${searchTerm}%`;\n countWhereConditions.push(\n sql`(${schema.capabilityIntegration.nickname} LIKE ${searchPattern} OR ${schema.capability.name} LIKE ${searchPattern})`,\n );\n }\n\n const countQueryBuilder = this.conn\n .select({\n count: sql`count(distinct ${schema.capabilityIntegration.id})`.as('count'),\n })\n .from(schema.capabilityIntegration);\n\n const countQueryWithJoins = shouldJoinCapability\n ? countQueryBuilder.leftJoin(schema.capability, eq(schema.capability.id, schema.capabilityIntegration.capabilityId))\n : countQueryBuilder;\n\n if (shouldJoinCapability) {\n countWhereConditions.push(isNull(schema.capability.deletedAt));\n }\n\n const countQueryWithPropertyJoin = input.propertyId\n ? countQueryWithJoins.leftJoin(\n schema.capIntegResourceMapping,\n and(\n eq(schema.capIntegResourceMapping.capabilityIntegrationId, schema.capabilityIntegration.id),\n eq(schema.capIntegResourceMapping.configuredForType, CONFIGURED_FOR_TYPE_ENUM.PROPERTY),\n eq(schema.capIntegResourceMapping.configuredForId, BigInt(input.propertyId)),\n isNull(schema.capIntegResourceMapping.deletedAt),\n ),\n )\n : countQueryWithJoins;\n\n if (input.propertyId) {\n countWhereConditions.push(isNotNull(schema.capIntegResourceMapping.id));\n }\n\n const countQuery = countQueryWithPropertyJoin.where(and(...countWhereConditions));\n\n // Build data query\n const baseQuery = this.conn\n .select({\n ...getTableColumns(schema.capabilityIntegration),\n provider: schema.capability.providerIntegrationType,\n })\n .from(schema.capabilityIntegration)\n .leftJoin(schema.capability, eq(schema.capability.id, schema.capabilityIntegration.capabilityId));\n\n const finalQuery = input.propertyId\n ? baseQuery\n .leftJoin(\n schema.capIntegResourceMapping,\n and(\n eq(schema.capIntegResourceMapping.capabilityIntegrationId, schema.capabilityIntegration.id),\n eq(schema.capIntegResourceMapping.configuredForType, CONFIGURED_FOR_TYPE_ENUM.PROPERTY),\n eq(schema.capIntegResourceMapping.configuredForId, BigInt(input.propertyId)),\n isNull(schema.capIntegResourceMapping.deletedAt),\n ),\n )\n .where(and(...whereConditions))\n : baseQuery.where(and(...whereConditions));\n\n // Execute queries in parallel\n const [{ count: totalCount }, records] = await Promise.all([\n countQuery.execute().then((result) => result[0]),\n finalQuery.limit(count).offset(offset).orderBy(sortOrder).execute(),\n ]);\n\n return {\n totalCount: Number(totalCount) || 0,\n records: records as unknown as ICapabilityIntegration[],\n };\n } catch (error) {\n this.logger.error(loggedInUserId, this.getCapabilityIntegrations.name, this.fileName, 'Error in getCapabilityIntegrations', error, input);\n\n throw error;\n }\n }\n\n /**\n * Applies filters to where conditions.\n */\n private applyFilters(whereConditions: SQL[], filters: IGetCapabilityIntegrationsRequest['options'] | undefined): void {\n if (!filters || !filters.filters) {\n return;\n }\n\n for (const filter of filters.filters) {\n const filterValues = filter.values;\n\n if (!filterValues || filterValues.length === 0) {\n continue;\n }\n\n switch (filter.by) {\n case 'PROVIDER_INTEGRATION_TYPE': {\n const valuePlaceholders = filterValues.map((value) => sql`${String(value)}`);\n const joinedValues = sql.join(valuePlaceholders, sql`, `);\n whereConditions.push(sql`${schema.capability.providerIntegrationType} IN (${joinedValues})`);\n break;\n }\n\n case 'CAPABILITY_INTEGRATION_TYPE': {\n const parentConditions: SQL[] = [];\n\n for (const value of filterValues) {\n const upperValue = String(value).toUpperCase();\n\n if (upperValue === 'PARENT') {\n parentConditions.push(isNull(schema.capabilityIntegration.parentId));\n } else if (upperValue === 'CHILD') {\n parentConditions.push(isNotNull(schema.capabilityIntegration.parentId));\n }\n }\n\n if (parentConditions.length === 1) {\n whereConditions.push(parentConditions[0]);\n } else if (parentConditions.length > 1) {\n const orCondition = or(...parentConditions);\n\n if (orCondition) {\n whereConditions.push(orCondition);\n }\n }\n break;\n }\n }\n }\n }\n}\n","import { appConstants, schema } from '@dv4resi/dvss-backend-module-datastore';\nimport { LoggerService, SYSTEM_USER_ID } from '@dv4resi/dvss-backend-module-utility';\nimport { Inject, Injectable } from '@nestjs/common';\nimport { and, eq, getTableColumns, isNull } from 'drizzle-orm';\nimport type { MySql2Database } from 'drizzle-orm/mysql2';\nimport { IAddServiceCommunicationTopic, IGetServiceCommunicationTopic } from './models/service-communication-topic.model';\n\n/**\n * DAO for on-prem service communication topics.\n * Performs DB operations on the `service_communication_topic` table using the shared datastore schema.\n */\n@Injectable()\nexport class IntegrationServiceCommunicationTopicDao {\n private readonly fileName = 'integration-service-communication-topic.dao';\n\n constructor(\n @Inject(appConstants.DB_CONNECTION)\n private readonly conn: MySql2Database<typeof schema>,\n private readonly logger: LoggerService,\n ) {}\n\n /**\n * Upserts a service communication topic for a given deployment + capability/subcapability/operation.\n * If a matching topic exists (by deploymentId + capability + subcapability + subcapabilityOperation),\n * it will be updated; otherwise a new row will be inserted.\n */\n async upsertTopic(input: IAddServiceCommunicationTopic, loggedInUserId = SYSTEM_USER_ID): Promise<{ status: boolean }> {\n this.logger.info(loggedInUserId, this.upsertTopic.name, this.fileName, 'IntegrationServiceCommunicationTopicDao -> upsertTopic called', { input });\n\n try {\n const existing = await this.conn.query.serviceCommunicationTopic.findFirst({\n where: and(\n eq(schema.serviceCommunicationTopic.deploymentId, input.deploymentId as bigint),\n eq(schema.serviceCommunicationTopic.projectId, input.projectId as number),\n isNull(schema.serviceCommunicationTopic.deletedAt),\n // capability / subcapability filters are optional\n ...(input.capability ? [eq(schema.serviceCommunicationTopic.capability, input.capability)] : []),\n ...(input.subcapability ? [eq(schema.serviceCommunicationTopic.subcapability, input.subcapability)] : []),\n eq(schema.serviceCommunicationTopic.subcapabilityOperation, input.subcapabilityOperation),\n ...(input.capabilityIntegrationId ? [eq(schema.serviceCommunicationTopic.capabilityIntegrationId, input.capabilityIntegrationId)] : []),\n ),\n });\n\n if (existing) {\n await this.conn\n .update(schema.serviceCommunicationTopic)\n .set({\n topicType: input.topicType,\n topicName: input.topicName,\n isUniversal: input.isUniversal ?? existing.isUniversal,\n shouldPublish: input.shouldPublish ?? existing.shouldPublish,\n shouldSubscribe: input.shouldSubscribe ?? existing.shouldSubscribe,\n updatedAt: new Date(),\n updatedBy: loggedInUserId,\n })\n .where(eq(schema.serviceCommunicationTopic.id, existing.id));\n\n return { status: true };\n }\n\n await this.conn.insert(schema.serviceCommunicationTopic).values({\n projectId: input.projectId,\n propertyId: input.propertyId,\n deploymentId: input.deploymentId,\n capability: input.capability,\n subcapability: input.subcapability,\n subcapabilityOperation: input.subcapabilityOperation,\n topicType: input.topicType,\n topicName: input.topicName,\n isUniversal: input.isUniversal ?? false,\n shouldPublish: input.shouldPublish ?? false,\n shouldSubscribe: input.shouldSubscribe ?? true,\n createdBy: loggedInUserId,\n capabilityIntegrationId: input.capabilityIntegrationId,\n });\n\n return { status: true };\n } catch (error) {\n this.logger.error(loggedInUserId, this.upsertTopic.name, this.fileName, 'Error in upsertTopic', error, { input });\n\n throw error;\n }\n }\n\n /**\n * Returns all service communication topics for a given integration.\n * NOTE: Currently filters by deploymentId using the provided integrationId;\n * once capabilityIntegrationId is available in the public typings, this can\n * be updated to filter by that column instead.\n */\n async getServiceCommunicationTopics(integrationId: bigint, loggedInUserId = SYSTEM_USER_ID): Promise<IGetServiceCommunicationTopic[]> {\n this.logger.info(\n loggedInUserId,\n this.getServiceCommunicationTopics.name,\n this.fileName,\n 'IntegrationServiceCommunicationTopicDao -> getServiceCommunicationTopics called',\n { integrationId },\n );\n\n try {\n const topics = await this.conn\n .select({\n ...getTableColumns(schema.serviceCommunicationTopic),\n subcapability: getTableColumns(schema.subcapability),\n })\n .from(schema.serviceCommunicationTopic)\n .innerJoin(schema.subcapability, eq(schema.subcapability.id, schema.serviceCommunicationTopic.subcapability))\n .where(and(eq(schema.serviceCommunicationTopic.capabilityIntegrationId, integrationId), isNull(schema.serviceCommunicationTopic.deletedAt)));\n\n return topics as IGetServiceCommunicationTopic[];\n } catch (error) {\n this.logger.error(loggedInUserId, this.getServiceCommunicationTopics.name, this.fileName, 'Error in getServiceCommunicationTopics', error, {\n integrationId,\n });\n throw error;\n }\n }\n}\n","import { appConstants, schema } from '@dv4resi/dvss-backend-module-datastore';\nimport type { CONFIGURED_FOR_TYPE_ENUM } from '@dv4resi/dvss-backend-module-datastore/dist/datastore/models';\nimport { CAPABILITY_INTEGRATION_STATUS_ENUM } from '@dv4resi/dvss-backend-module-datastore/dist/datastore/models/capability-integration.model';\nimport { GraphQLContext, LoggerService } from '@dv4resi/dvss-backend-module-utility';\nimport { Inject, Injectable } from '@nestjs/common';\nimport { and, eq, isNull } from 'drizzle-orm';\nimport type { MySql2Database } from 'drizzle-orm/mysql2';\nimport { IAddCapabilityIntegrationMappingResponse, ICapabilityIntegrationResourceMappingRow, IDeleteAPIResponse, IUpdateAPIResponse } from './models';\n\n/**\n * DAO for integration resource management (cap_integ_resource_mapping).\n * Provides checkMappingExists and removeCapabilityIntegrationMapping so UIF/callers\n * can validate and remove capability integration mappings without inter-service calls.\n */\n@Injectable()\nexport class IntegrationResourceManagementDao {\n private readonly fileName = 'integration-resource-management.dao';\n\n constructor(\n @Inject(appConstants.DB_CONNECTION)\n private readonly conn: MySql2Database<typeof schema>,\n private readonly logger: LoggerService,\n ) {}\n\n /**\n * Adds a capability integration resource mapping (insert into cap_integ_resource_mapping).\n * Replaces inter-service gRPC call to project-onboarding-ms for add configurations.\n *\n * @param input - projectId, capabilityIntegrationId, configuredForId, configuredForType, optional config\n * @param context - GraphQL context for loggedInUserId\n * @returns Promise resolving to { status: true, ids: [insertedId] } or { status: false, ids: [] }\n */\n async addCapabilityIntegrationMapping(\n input: {\n projectId: number;\n capabilityIntegrationId: bigint;\n configuredForId: bigint;\n configuredForType: CONFIGURED_FOR_TYPE_ENUM;\n config?: Record<string, unknown>;\n },\n context: GraphQLContext,\n ): Promise<IAddCapabilityIntegrationMappingResponse> {\n try {\n this.logger.info(context.loggedInUserId, this.addCapabilityIntegrationMapping.name, this.fileName, 'Adding capability integration mapping', input);\n\n const insertResult = await this.conn.insert(schema.capIntegResourceMapping).values({\n projectId: input.projectId,\n status: CAPABILITY_INTEGRATION_STATUS_ENUM.ACTIVE,\n capabilityIntegrationId: input.capabilityIntegrationId,\n configuredForId: input.configuredForId,\n configuredForType: input.configuredForType,\n config: input.config ?? null,\n createdBy: context.loggedInUserId,\n });\n\n const raw = insertResult as unknown as { insertId?: number | string }[];\n const insertedId = raw[0]?.insertId != null ? Number(raw[0].insertId) : 0;\n const isInserted = insertedId > 0;\n const ids = isInserted ? [BigInt(insertedId)] : [];\n\n this.logger.info(\n context.loggedInUserId,\n this.addCapabilityIntegrationMapping.name,\n this.fileName,\n `Mapping add ${isInserted ? 'successful' : 'failed'}`,\n { insertedId, status: isInserted },\n );\n\n return { status: isInserted, ids };\n } catch (error) {\n this.logger.error(\n context.loggedInUserId,\n this.addCapabilityIntegrationMapping.name,\n this.fileName,\n 'Error adding capability integration mapping',\n error,\n input,\n );\n throw error;\n }\n }\n\n /**\n * Checks if a capability integration resource mapping exists.\n * Validates that the mapping exists for the given capability integration, configured for ID and type.\n *\n * @param input - Input containing capability integration ID, configured for ID and type\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise that resolves to true if mapping exists, false otherwise\n */\n async checkMappingExists(\n input: {\n capabilityIntegrationId: bigint;\n configuredForId: bigint;\n configuredForType: CONFIGURED_FOR_TYPE_ENUM;\n },\n loggedInUserId: bigint,\n ): Promise<boolean> {\n try {\n this.logger.info(loggedInUserId, this.checkMappingExists.name, this.fileName, `${this.checkMappingExists.name} called`, input);\n\n const response = await this.conn\n .select({ id: schema.capIntegResourceMapping.id })\n .from(schema.capIntegResourceMapping)\n .where(\n and(\n eq(schema.capIntegResourceMapping.capabilityIntegrationId, input.capabilityIntegrationId),\n eq(schema.capIntegResourceMapping.configuredForId, input.configuredForId),\n eq(schema.capIntegResourceMapping.configuredForType, input.configuredForType),\n isNull(schema.capIntegResourceMapping.deletedAt),\n ),\n )\n .limit(1);\n\n return response.length > 0;\n } catch (error) {\n this.logger.error(loggedInUserId, this.checkMappingExists.name, this.fileName, 'Error in checkMappingExists', error, input);\n\n throw error;\n }\n }\n\n /**\n * Removes capability integration resource mapping (soft delete).\n * Sets deletedAt and deletedBy on the matching cap_integ_resource_mapping row.\n * Use this from UIF/callers instead of inter-service call to project-onboarding-ms.\n *\n * @param input - Delete parameters including capability integration ID, configured for ID and type\n * @param loggedInUserId - ID of the user performing the operation\n * @returns Promise resolving to { status: true } if any row was updated, { status: false } otherwise\n */\n async removeCapabilityIntegrationMapping(\n input: {\n capabilityIntegrationId: bigint;\n configuredForId: bigint;\n configuredForType: CONFIGURED_FOR_TYPE_ENUM;\n },\n context: GraphQLContext,\n ): Promise<IDeleteAPIResponse> {\n try {\n this.logger.info(\n context.loggedInUserId,\n this.removeCapabilityIntegrationMapping.name,\n this.fileName,\n 'Removing capability integration mapping',\n input,\n );\n\n // Build where conditions for the delete operation - match on capability_integration_id, configured_for_id, and configured_for_type\n const whereConditions = [\n isNull(schema.capIntegResourceMapping.deletedAt),\n eq(schema.capIntegResourceMapping.capabilityIntegrationId, input.capabilityIntegrationId),\n eq(schema.capIntegResourceMapping.configuredForId, input.configuredForId),\n eq(schema.capIntegResourceMapping.configuredForType, input.configuredForType),\n ];\n\n // Perform soft delete\n const deleteResult = await this.conn\n .update(schema.capIntegResourceMapping)\n .set({\n deletedAt: new Date(),\n deletedBy: context.loggedInUserId,\n })\n .where(and(...whereConditions));\n\n const isSuccess = deleteResult[0].affectedRows > 0;\n\n this.logger.info(\n context.loggedInUserId,\n this.removeCapabilityIntegrationMapping.name,\n this.fileName,\n `Mapping removal ${isSuccess ? 'successful' : 'failed - no matching records'}`,\n { affectedRows: deleteResult[0].affectedRows },\n );\n\n return { status: isSuccess };\n } catch (error) {\n this.logger.error(\n context.loggedInUserId,\n this.removeCapabilityIntegrationMapping.name,\n this.fileName,\n 'Error removing capability integration mapping',\n error,\n input,\n );\n\n throw error;\n }\n }\n\n /**\n * Gets a capability integration resource mapping by id (non-deleted only).\n * Use from UIF wrappers to validate mapping exists before update.\n *\n * @param id - cap_integ_resource_mapping.id\n * @param loggedInUserId - for logging\n * @returns The mapping row or undefined if not found\n */\n async getCapabilityIntegrationResourceMappingById(id: bigint, loggedInUserId: bigint): Promise<ICapabilityIntegrationResourceMappingRow | undefined> {\n try {\n this.logger.info(\n loggedInUserId,\n this.getCapabilityIntegrationResourceMappingById.name,\n this.fileName,\n `${this.getCapabilityIntegrationResourceMappingById.name} called`,\n { id: id.toString() },\n );\n\n const rows = await this.conn\n .select({\n id: schema.capIntegResourceMapping.id,\n capabilityIntegrationId: schema.capIntegResourceMapping.capabilityIntegrationId,\n configuredForId: schema.capIntegResourceMapping.configuredForId,\n configuredForType: schema.capIntegResourceMapping.configuredForType,\n })\n .from(schema.capIntegResourceMapping)\n .where(and(eq(schema.capIntegResourceMapping.id, id), isNull(schema.capIntegResourceMapping.deletedAt)))\n .limit(1);\n\n return rows[0];\n } catch (error) {\n this.logger.error(\n loggedInUserId,\n this.getCapabilityIntegrationResourceMappingById.name,\n this.fileName,\n 'Error in getCapabilityIntegrationResourceMappingById',\n error,\n { id: id.toString() },\n );\n throw error;\n }\n }\n\n /**\n * Updates capability integration resource mapping config by id.\n * Replaces inter-service gRPC call to project-onboarding-ms for update capability integration configuration.\n *\n * @param input - id (mapping row id), config (new config JSON)\n * @param context - GraphQL context for loggedInUserId\n * @returns Promise resolving to { status: true } if row was updated, { status: false } otherwise\n */\n async updateCapabilityIntegrationConfiguration(\n input: {\n id: bigint;\n config: Record<string, unknown>;\n },\n context: GraphQLContext,\n ): Promise<IUpdateAPIResponse> {\n try {\n this.logger.info(\n context.loggedInUserId,\n this.updateCapabilityIntegrationConfiguration.name,\n this.fileName,\n 'Updating capability integration resource mapping config',\n { id: input.id.toString() },\n );\n\n const updateResult = await this.conn\n .update(schema.capIntegResourceMapping)\n .set({\n config: input.config,\n updatedBy: context.loggedInUserId,\n })\n .where(and(eq(schema.capIntegResourceMapping.id, input.id), isNull(schema.capIntegResourceMapping.deletedAt)));\n\n const isSuccess = updateResult[0].affectedRows > 0;\n\n this.logger.info(\n context.loggedInUserId,\n this.updateCapabilityIntegrationConfiguration.name,\n this.fileName,\n `Mapping config update ${isSuccess ? 'successful' : 'failed - no matching records'}`,\n { affectedRows: updateResult[0].affectedRows },\n );\n\n return { status: isSuccess };\n } catch (error) {\n this.logger.error(\n context.loggedInUserId,\n this.updateCapabilityIntegrationConfiguration.name,\n this.fileName,\n 'Error updating capability integration resource mapping config',\n error,\n input,\n );\n\n throw error;\n }\n }\n}\n","import { appConstants, schema } from '@dv4resi/dvss-backend-module-datastore';\nimport { Inject, Injectable } from '@nestjs/common';\nimport type { MySql2Database } from 'drizzle-orm/mysql2';\n\n/**\n * DAO for integration user-management persistence.\n * Performs actual DB calls using datastore schema; conn is injected by the host app.\n */\n@Injectable()\nexport class IntegrationUserManagementDao {\n constructor(\n @Inject(appConstants.DB_CONNECTION)\n protected readonly conn: MySql2Database<typeof schema>,\n ) {}\n}\n","import { appConstants, schema } from '@dv4resi/dvss-backend-module-datastore';\nimport { IAddUpdateAPIStatusResponseBigInt } from '@dv4resi/dvss-backend-module-datastore/dist/datastore/models';\nimport { LoggerService, SYSTEM_USER_ID } from '@dv4resi/dvss-backend-module-utility';\nimport { Inject, Injectable } from '@nestjs/common';\nimport { and, eq, isNull } from 'drizzle-orm';\nimport type { MySql2Database } from 'drizzle-orm/mysql2';\n\nimport { IAddOnpremDeployment, IUpdateOnpremDeployment } from './models/integration-onprem-deloyment.model';\n\n/**\n * DAO for integration-configuration persistence (offering get/update).\n * Performs actual DB calls using datastore schema; conn is injected by the host app.\n */\n@Injectable()\nexport class IntegrationOnpremDeploymentDao {\n private readonly fileName = 'integration-onprem-deployment.dao';\n\n constructor(\n @Inject(appConstants.DB_CONNECTION)\n private readonly conn: MySql2Database<typeof schema>,\n private readonly logger: LoggerService,\n ) {}\n\n async addUpdateOnpremDeployment(input: IAddOnpremDeployment, loggedInUserId = SYSTEM_USER_ID): Promise<IAddUpdateAPIStatusResponseBigInt> {\n try {\n // Log the attempt to add a capability integration\n this.logger.info(\n loggedInUserId,\n this.addUpdateOnpremDeployment.name,\n this.fileName,\n `IntegrationOnpremDeploymentDao -> addUpdateOnpremDeployment called`,\n {\n input,\n },\n );\n\n //Check if entry exists by projectId and capabilityIntegrationId\n //If entry exists, update the entry\n //If entry does not exist, create a new entry\n const existingEntry = await this.conn.query.onPremDeployment.findFirst({\n where: and(\n eq(schema.onPremDeployment.projectId, input.projectId as number),\n eq(schema.onPremDeployment.capabilityIntegrationId, input.capabilityIntegrationId),\n ),\n });\n if (existingEntry) {\n await this.updateOnpremDeployment(existingEntry.id, input, loggedInUserId);\n\n return { status: true, id: existingEntry.id };\n }\n return this.addOnpremDeployment(input, loggedInUserId);\n } catch (error) {\n // Log and rethrow\n this.logger.error(loggedInUserId, this.addUpdateOnpremDeployment.name, this.fileName, 'Error in addCapabilityIntegration', error, { input });\n\n throw error;\n }\n }\n\n private async addOnpremDeployment(input: IAddOnpremDeployment, loggedInUserId = SYSTEM_USER_ID): Promise<IAddUpdateAPIStatusResponseBigInt> {\n try {\n const [insertedResult] = await this.conn.insert(schema.onPremDeployment).values(input).$returningId();\n\n return { status: true, id: BigInt(insertedResult.id) };\n } catch (error) {\n this.logger.error(loggedInUserId, this.addOnpremDeployment.name, this.fileName, 'Error in addOnpremDeployment', error, { input });\n throw error;\n }\n }\n\n private async updateOnpremDeployment(\n id: bigint,\n updateData: IUpdateOnpremDeployment,\n loggedInUserId = SYSTEM_USER_ID,\n ): Promise<IAddUpdateAPIStatusResponseBigInt> {\n try {\n const result = await this.conn.update(schema.onPremDeployment).set(updateData).where(eq(schema.onPremDeployment.id, id)).execute();\n return { status: result[0].affectedRows > 0, id };\n } catch (error) {\n this.logger.error(loggedInUserId, this.updateOnpremDeployment.name, this.fileName, 'Error in updateOnpremDeployment', error, { id, updateData });\n throw error;\n }\n }\n\n /**\n * Gets an on-prem deployment by capability integration id.\n * Used by Suprema integration to resolve deployment for a given integration.\n */\n async getOnpremDeployment(\n input: { integrationId: bigint; projectId: number },\n loggedInUserId = SYSTEM_USER_ID,\n ): Promise<typeof schema.onPremDeployment.$inferSelect | undefined> {\n try {\n this.logger.info(loggedInUserId, this.getOnpremDeployment.name, this.fileName, 'IntegrationOnpremDeploymentDao -> getOnpremDeployment called', {\n input,\n });\n\n return await this.conn.query.onPremDeployment.findFirst({\n where: and(\n eq(schema.onPremDeployment.projectId, input.projectId),\n eq(schema.onPremDeployment.capabilityIntegrationId, input.integrationId),\n isNull(schema.onPremDeployment.deletedAt),\n ),\n });\n } catch (error) {\n this.logger.error(loggedInUserId, this.getOnpremDeployment.name, this.fileName, 'Error in getOnpremDeployment', error, { input });\n throw error;\n }\n }\n}\n","import { ENV_PREFIX, OAUTH_TOKEN_CACHE_PREFIX, OAUTH_TOKEN_LOCK_PREFIX } from '@dv4resi/dvss-backend-module-datastore';\n\n/**\n * Replaces `{placeholder}` tokens in catalog URLs (e.g. `{tenantId}`).\n * Unknown placeholders are left unchanged.\n */\nexport function substituteUrlPlaceholders(url: string, params: Record<string, string> = {}): string {\n return url.replace(/\\{(\\w+)\\}/g, (matched, name: string) => params[name] ?? matched);\n}\n\nexport function hasPersistedIntegrationId(id?: bigint): id is bigint {\n return id != null && id !== BigInt(0);\n}\n\nexport function secondsUntil(expiresAt: Date, nowMs: number = Date.now()): number {\n return Math.max(0, Math.floor((expiresAt.getTime() - nowMs) / 1000));\n}\n\n/** Tokens within this window of expiry are treated as stale so callers refresh early. */\nexport const OAUTH_TOKEN_FRESHNESS_BUFFER_MS = 60_000;\n\nexport function isTokenFresh(expiresAt: Date, nowMs: number = Date.now()): boolean {\n return expiresAt.getTime() - OAUTH_TOKEN_FRESHNESS_BUFFER_MS > nowMs;\n}\n\nexport function getIntegrationConfigKmsKeyId(): string {\n return process.env.INTEGRATION_CONFIG_KMS_KEY_ID || '';\n}\n\nexport function delay(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n\n/** Exact Redis key for a cached OAuth access token (`{ENV}{oauthToken:}{id}`). */\nexport function getOauthTokenCacheKey(capabilityIntegrationId: bigint): string {\n return `${ENV_PREFIX}${OAUTH_TOKEN_CACHE_PREFIX}${capabilityIntegrationId.toString()}`;\n}\n\n/** Exact Redis key for the OAuth mint lock (`{ENV}{oauthTokenLock:}{id}`). */\nexport function getOauthTokenLockKey(capabilityIntegrationId: bigint): string {\n return `${ENV_PREFIX}${OAUTH_TOKEN_LOCK_PREFIX}${capabilityIntegrationId.toString()}`;\n}\n","import { RedisCacheStoreService } from '@dv4resi/dvss-backend-module-datastore';\nimport { Injectable } from '@nestjs/common';\n\nimport { getOauthTokenCacheKey, secondsUntil } from '../common/oauth.util';\nimport type { IOauthAccessToken } from '../models/oauth.model';\n\ninterface ICachedOauthToken {\n accessToken: string;\n tokenType: string;\n expiresAt: string;\n refreshToken?: string;\n}\n\n@Injectable()\nexport class OauthTokenCache {\n constructor(private readonly redisCacheStoreService: RedisCacheStoreService) {}\n\n async get(capabilityIntegrationId: bigint): Promise<IOauthAccessToken | undefined> {\n const cached = await this.redisCacheStoreService.get<ICachedOauthToken>(getOauthTokenCacheKey(capabilityIntegrationId));\n\n if (!cached?.accessToken || !cached.expiresAt) {\n return undefined;\n }\n\n return {\n accessToken: cached.accessToken,\n tokenType: cached.tokenType,\n expiresAt: new Date(cached.expiresAt),\n refreshToken: cached.refreshToken,\n };\n }\n\n async set(capabilityIntegrationId: bigint, token: IOauthAccessToken): Promise<void> {\n const ttlSeconds = secondsUntil(token.expiresAt);\n\n if (ttlSeconds <= 0) {\n return;\n }\n\n await this.redisCacheStoreService.set(\n getOauthTokenCacheKey(capabilityIntegrationId),\n {\n accessToken: token.accessToken,\n tokenType: token.tokenType,\n expiresAt: token.expiresAt.toISOString(),\n refreshToken: token.refreshToken,\n } satisfies ICachedOauthToken,\n ttlSeconds,\n );\n }\n\n async del(capabilityIntegrationId: bigint): Promise<void> {\n await this.redisCacheStoreService.del(getOauthTokenCacheKey(capabilityIntegrationId));\n }\n}\n","import { Injectable } from '@nestjs/common';\n\nimport type { IOauthAccessToken } from '../models/oauth.model';\nimport type { GrantHandler, IGrantMintRequest } from './grant-handler';\n\n@Injectable()\nexport class AuthorizationCodeGrantHandler implements GrantHandler {\n mint(request: IGrantMintRequest): Promise<IOauthAccessToken> {\n throw new Error(`NotImplemented: authorization_code grant is not supported (${request.tokenUrl})`);\n }\n}\n","export const OAUTH_GRANT_TYPE = {\n AUTHORIZATION_CODE: 'AUTHORIZATION_CODE',\n CLIENT_CREDENTIALS: 'CLIENT_CREDENTIALS',\n} as const;\n\nexport type OauthGrantType = (typeof OAUTH_GRANT_TYPE)[keyof typeof OAUTH_GRANT_TYPE];\n\nexport const OAUTH_RFC_GRANT_TYPE: Record<OauthGrantType, string> = {\n AUTHORIZATION_CODE: 'authorization_code',\n CLIENT_CREDENTIALS: 'client_credentials',\n};\n\nexport const OAUTH_DEFAULT_TOKEN_TYPE = 'Bearer';\n\nexport const OAUTH_TOKEN_HEADERS = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Accept: 'application/json',\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/x-www-form-urlencoded',\n};\n\nexport interface IOauthMintCredentials {\n tokenUrl: string;\n clientId: string;\n clientSecret: string;\n scope?: string;\n urlParams?: Record<string, string>;\n}\n\nexport interface IOauthAccessToken {\n accessToken: string;\n tokenType: string;\n expiresAt: Date;\n refreshToken?: string;\n metadata?: Record<string, unknown>;\n}\n\nexport interface IGetValidAccessTokenOptions {\n forceRefresh?: boolean;\n loggedInUserId?: bigint;\n credentials?: IOauthMintCredentials;\n capabilityId?: bigint;\n providerId?: bigint;\n}\n","import { LoggerService } from '@dv4resi/dvss-backend-module-utility';\nimport { HTTP_METHOD, type IValidatedCapabilityIntegration, TrafficGatewayService } from '@dvss/dvss-integration-libs';\nimport { Injectable } from '@nestjs/common';\n\nimport { OAUTH_DEFAULT_TOKEN_TYPE, OAUTH_RFC_GRANT_TYPE, OAUTH_TOKEN_HEADERS, type IOauthAccessToken } from '../models/oauth.model';\nimport type { GrantHandler, IGrantMintRequest } from './grant-handler';\n\ninterface IOauthTokenHttpResponse {\n access_token?: string;\n token_type?: string;\n expires_in?: number;\n refresh_token?: string;\n}\n\n@Injectable()\nexport class ClientCredentialsGrantHandler implements GrantHandler {\n private readonly fileName = 'client-credentials.handler';\n\n constructor(\n private readonly logger: LoggerService,\n private readonly trafficGatewayService: TrafficGatewayService,\n ) {}\n\n async mint(request: IGrantMintRequest): Promise<IOauthAccessToken> {\n const tokenUrl = new URL(request.tokenUrl);\n const body = new URLSearchParams({\n client_id: request.credentials.clientId,\n client_secret: request.credentials.clientSecret,\n grant_type: OAUTH_RFC_GRANT_TYPE.CLIENT_CREDENTIALS,\n });\n\n if (request.scope) {\n body.set('scope', request.scope);\n }\n\n const loggedInUserId = request.loggedInUserId;\n const integrationContext = {\n id: request.integration.id as bigint,\n capabilityId: request.integration.capabilityId,\n providerId: request.integration.providerId,\n projectId: request.integration.projectId,\n headers: OAUTH_TOKEN_HEADERS,\n config: {\n platformConfig: { authUrl: request.tokenUrl, baseUrl: tokenUrl.origin },\n integrationConfig: {},\n },\n } as unknown as IValidatedCapabilityIntegration;\n\n this.logger.info(loggedInUserId, this.mint.name, this.fileName, 'Minting OAuth access token with client_credentials');\n\n const response = await this.trafficGatewayService.executeIntegrationRequest<IOauthTokenHttpResponse, string>(\n {\n apiMethod: HTTP_METHOD.POST,\n baseUrl: tokenUrl.origin,\n url: `${tokenUrl.pathname}${tokenUrl.search}`,\n body: body.toString(),\n headers: OAUTH_TOKEN_HEADERS,\n },\n integrationContext,\n loggedInUserId,\n );\n\n if (!response.access_token) {\n throw new Error('OAuth token response is missing access_token');\n }\n\n const expiresInSeconds = response.expires_in ?? 0;\n\n return {\n accessToken: response.access_token,\n tokenType: response.token_type ?? OAUTH_DEFAULT_TOKEN_TYPE,\n expiresAt: new Date(Date.now() + expiresInSeconds * 1000),\n refreshToken: response.refresh_token,\n };\n }\n}\n","import { Injectable } from '@nestjs/common';\n\nimport { OAUTH_GRANT_TYPE, type OauthGrantType } from '../models/oauth.model';\nimport { AuthorizationCodeGrantHandler } from './authorization-code.handler';\nimport { ClientCredentialsGrantHandler } from './client-credentials.handler';\nimport type { GrantHandler } from './grant-handler';\n\n@Injectable()\nexport class GrantHandlerRegistry {\n constructor(\n private readonly clientCredentialsGrantHandler: ClientCredentialsGrantHandler,\n private readonly authorizationCodeGrantHandler: AuthorizationCodeGrantHandler,\n ) {}\n\n get(grantType: OauthGrantType): GrantHandler {\n if (grantType === OAUTH_GRANT_TYPE.CLIENT_CREDENTIALS) {\n return this.clientCredentialsGrantHandler;\n }\n\n return this.authorizationCodeGrantHandler;\n }\n\n resolvePreferredGrant(supportedGrantTypes: OauthGrantType[] | undefined): OauthGrantType {\n if (supportedGrantTypes?.includes(OAUTH_GRANT_TYPE.CLIENT_CREDENTIALS)) {\n return OAUTH_GRANT_TYPE.CLIENT_CREDENTIALS;\n }\n\n if (supportedGrantTypes?.length) {\n return supportedGrantTypes[0];\n }\n\n return OAUTH_GRANT_TYPE.CLIENT_CREDENTIALS;\n }\n}\n","import { appConstants, DATABASE_ERROR_NAMES, errorHandler, MODULE_NAME, schema } from '@dv4resi/dvss-backend-module-datastore';\nimport { LoggerService } from '@dv4resi/dvss-backend-module-utility';\nimport { Inject, Injectable } from '@nestjs/common';\nimport { and, eq, isNull } from 'drizzle-orm';\nimport type { MySql2Database } from 'drizzle-orm/mysql2';\n\nimport type { IOauthProvider } from './oauth.model';\n\n@Injectable()\nexport class OauthProviderDao {\n private readonly fileName = 'oauth-provider.dao';\n\n constructor(\n @Inject(appConstants.DB_CONNECTION)\n private readonly conn: MySql2Database<typeof schema>,\n private readonly logger: LoggerService,\n ) {}\n\n async findByCapabilityAndProvider(capabilityId: bigint, providerId: bigint, loggedInUserId: bigint): Promise<IOauthProvider | undefined> {\n this.logger.info(loggedInUserId, this.findByCapabilityAndProvider.name, this.fileName, 'Loading OAuth provider catalog row', {\n capabilityId,\n providerId,\n });\n\n try {\n const rows = await this.conn\n .select()\n .from(schema.integrationOauthProvider)\n .where(\n and(\n eq(schema.integrationOauthProvider.capabilityId, capabilityId),\n eq(schema.integrationOauthProvider.providerId, providerId),\n isNull(schema.integrationOauthProvider.deletedAt),\n ),\n );\n\n return rows[0];\n } catch (error) {\n throw errorHandler(\n loggedInUserId,\n this.findByCapabilityAndProvider.name,\n this.fileName,\n DATABASE_ERROR_NAMES.DATABASE_ERROR,\n MODULE_NAME.COMMON,\n error,\n { capabilityId, providerId },\n ) as Error;\n }\n }\n}\n","import { appConstants, DATABASE_ERROR_NAMES, errorHandler, MODULE_NAME, schema } from '@dv4resi/dvss-backend-module-datastore';\nimport { LoggerService } from '@dv4resi/dvss-backend-module-utility';\nimport { Inject, Injectable } from '@nestjs/common';\nimport { and, eq, isNull } from 'drizzle-orm';\nimport type { MySql2Database } from 'drizzle-orm/mysql2';\n\nimport type { IOauthToken, IUpsertOauthTokenInput } from './oauth.model';\n\n@Injectable()\nexport class OauthTokenDao {\n private readonly fileName = 'oauth-token.dao';\n\n constructor(\n @Inject(appConstants.DB_CONNECTION)\n private readonly conn: MySql2Database<typeof schema>,\n private readonly logger: LoggerService,\n ) {}\n\n async findByCapabilityIntegrationId(capabilityIntegrationId: bigint, loggedInUserId: bigint): Promise<IOauthToken | undefined> {\n this.logger.info(loggedInUserId, this.findByCapabilityIntegrationId.name, this.fileName, 'Loading OAuth token row', { capabilityIntegrationId });\n\n try {\n const rows = await this.conn\n .select()\n .from(schema.integrationOauthToken)\n .where(and(eq(schema.integrationOauthToken.capabilityIntegrationId, capabilityIntegrationId), isNull(schema.integrationOauthToken.deletedAt)));\n\n return rows[0];\n } catch (error) {\n throw errorHandler(\n loggedInUserId,\n this.findByCapabilityIntegrationId.name,\n this.fileName,\n DATABASE_ERROR_NAMES.DATABASE_ERROR,\n MODULE_NAME.COMMON,\n error,\n { capabilityIntegrationId },\n ) as Error;\n }\n }\n\n async upsert(input: IUpsertOauthTokenInput): Promise<void> {\n this.logger.info(input.loggedInUserId, this.upsert.name, this.fileName, 'Upserting OAuth token row', {\n capabilityIntegrationId: input.capabilityIntegrationId,\n });\n\n const existing = await this.findByCapabilityIntegrationId(input.capabilityIntegrationId, input.loggedInUserId);\n const now = new Date();\n\n try {\n if (existing) {\n await this.conn\n .update(schema.integrationOauthToken)\n .set({\n accessToken: input.accessToken,\n refreshToken: input.refreshToken ?? null,\n expiresAt: input.expiresAt,\n refreshExpiredAt: input.refreshExpiredAt ?? null,\n tokenMetadata: input.tokenMetadata ?? null,\n updatedAt: now,\n updatedBy: input.loggedInUserId,\n deletedAt: null,\n deletedBy: null,\n })\n .where(eq(schema.integrationOauthToken.id, existing.id));\n return;\n }\n\n await this.conn.insert(schema.integrationOauthToken).values({\n capabilityIntegrationId: input.capabilityIntegrationId,\n accessToken: input.accessToken,\n refreshToken: input.refreshToken ?? null,\n expiresAt: input.expiresAt,\n refreshExpiredAt: input.refreshExpiredAt ?? null,\n tokenMetadata: input.tokenMetadata ?? null,\n createdAt: now,\n createdBy: input.loggedInUserId,\n });\n } catch (error) {\n throw errorHandler(input.loggedInUserId, this.upsert.name, this.fileName, DATABASE_ERROR_NAMES.DATABASE_ERROR, MODULE_NAME.COMMON, error, {\n capabilityIntegrationId: input.capabilityIntegrationId,\n }) as Error;\n }\n }\n}\n","import { RedisCacheStoreService } from '@dv4resi/dvss-backend-module-datastore';\nimport { LoggerService, SECRET_PROVIDER, type SecretProvider, SYSTEM_USER_ID } from '@dv4resi/dvss-backend-module-utility';\nimport { Inject, Injectable, Optional } from '@nestjs/common';\nimport { randomUUID } from 'crypto';\n\nimport { OauthTokenCache } from '../cache/oauth-token-cache';\nimport {\n delay,\n getIntegrationConfigKmsKeyId,\n getOauthTokenLockKey,\n hasPersistedIntegrationId,\n isTokenFresh,\n substituteUrlPlaceholders,\n} from '../common/oauth.util';\nimport { GrantHandlerRegistry } from '../grants/grant-handler.registry';\nimport type { IGetValidAccessTokenOptions, IOauthAccessToken, IOauthMintCredentials, OauthGrantType } from '../models/oauth.model';\nimport { OauthProviderDao } from '../store/oauth-provider.dao';\nimport { OauthTokenDao } from '../store/oauth-token.dao';\n\n// SECRET_PROVIDER is undefined when tests mock utility without it.\n// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\nconst oauthSecretProviderToken = SECRET_PROVIDER ?? Symbol('SECRET_PROVIDER');\n\nconst OAUTH_LOCK_TTL_SECONDS = 30;\nconst OAUTH_LOCK_WAIT_MS = 100;\nconst OAUTH_LOCK_MAX_WAIT_MS = 10_000;\n\ninterface IMemorySession {\n token: string;\n tokenType: string;\n tokenExpiry: Date;\n refreshToken?: string;\n}\n\n@Injectable()\nexport class OauthTokenManager {\n private readonly fileName = 'oauth-token-manager';\n\n private readonly sessions = new Map<string, IMemorySession>();\n\n constructor(\n private readonly logger: LoggerService,\n private readonly tokenDao: OauthTokenDao,\n private readonly providerDao: OauthProviderDao,\n private readonly tokenCache: OauthTokenCache,\n private readonly redisCacheStoreService: RedisCacheStoreService,\n private readonly grantHandlerRegistry: GrantHandlerRegistry,\n @Optional() @Inject(oauthSecretProviderToken) private readonly secretProvider?: SecretProvider,\n ) {}\n\n async getValidAccessToken(capabilityIntegrationId: bigint | undefined, opts: IGetValidAccessTokenOptions = {}): Promise<IOauthAccessToken> {\n const loggedInUserId = opts.loggedInUserId ?? SYSTEM_USER_ID;\n const shouldForceRefresh = opts.forceRefresh === true;\n\n if (!shouldForceRefresh && hasPersistedIntegrationId(capabilityIntegrationId)) {\n const cached = await this.readCachedToken(capabilityIntegrationId, loggedInUserId);\n if (cached) {\n return cached;\n }\n }\n\n if (!hasPersistedIntegrationId(capabilityIntegrationId)) {\n return this.mintToken(undefined, opts, loggedInUserId);\n }\n\n return this.mintWithDistributedLock(capabilityIntegrationId, opts, loggedInUserId, shouldForceRefresh);\n }\n\n async storeToken(capabilityIntegrationId: bigint, token: IOauthAccessToken, loggedInUserId: bigint = SYSTEM_USER_ID): Promise<void> {\n await this.persistToken(capabilityIntegrationId, token, loggedInUserId);\n this.writeMemory(capabilityIntegrationId, token);\n await this.tokenCache.set(capabilityIntegrationId, token);\n }\n\n async invalidate(capabilityIntegrationId: bigint): Promise<void> {\n this.sessions.delete(capabilityIntegrationId.toString());\n await this.tokenCache.del(capabilityIntegrationId);\n }\n\n private async mintWithDistributedLock(\n capabilityIntegrationId: bigint,\n opts: IGetValidAccessTokenOptions,\n loggedInUserId: bigint,\n shouldForceRefresh: boolean,\n ): Promise<IOauthAccessToken> {\n const lockKey = getOauthTokenLockKey(capabilityIntegrationId);\n const deadline = Date.now() + OAUTH_LOCK_MAX_WAIT_MS;\n\n while (Date.now() < deadline) {\n if (!shouldForceRefresh) {\n const cached = await this.readCachedToken(capabilityIntegrationId, loggedInUserId);\n if (cached) {\n return cached;\n }\n }\n\n const ownerId = randomUUID();\n const isAcquired = await this.redisCacheStoreService.setIfAbsent(lockKey, ownerId, OAUTH_LOCK_TTL_SECONDS);\n\n if (isAcquired) {\n this.logger.info(loggedInUserId, this.mintWithDistributedLock.name, this.fileName, 'OAuth token lock acquired', {\n capabilityIntegrationId: capabilityIntegrationId.toString(),\n });\n\n try {\n if (!shouldForceRefresh) {\n const cached = await this.readCachedToken(capabilityIntegrationId, loggedInUserId);\n if (cached) {\n return cached;\n }\n }\n\n return await this.mintToken(capabilityIntegrationId, opts, loggedInUserId);\n } finally {\n await this.releaseLockIfOwner(lockKey, ownerId);\n }\n }\n\n const existingLock = await this.redisCacheStoreService.get<string>(lockKey);\n if (existingLock == null) {\n this.logger.warn(loggedInUserId, this.mintWithDistributedLock.name, this.fileName, 'OAuth token lock unavailable; minting without lock', {\n capabilityIntegrationId: capabilityIntegrationId.toString(),\n });\n\n if (!shouldForceRefresh) {\n const cached = await this.readCachedToken(capabilityIntegrationId, loggedInUserId);\n if (cached) {\n return cached;\n }\n }\n\n return this.mintToken(capabilityIntegrationId, opts, loggedInUserId);\n }\n\n this.logger.info(loggedInUserId, this.mintWithDistributedLock.name, this.fileName, 'OAuth token lock contention; waiting', {\n capabilityIntegrationId: capabilityIntegrationId.toString(),\n });\n\n await delay(OAUTH_LOCK_WAIT_MS);\n }\n\n this.logger.warn(loggedInUserId, this.mintWithDistributedLock.name, this.fileName, 'OAuth token lock wait timed out; minting without lock', {\n capabilityIntegrationId: capabilityIntegrationId.toString(),\n });\n\n if (!shouldForceRefresh) {\n const cached = await this.readCachedToken(capabilityIntegrationId, loggedInUserId);\n if (cached) {\n return cached;\n }\n }\n\n return this.mintToken(capabilityIntegrationId, opts, loggedInUserId);\n }\n\n private async releaseLockIfOwner(lockKey: string, ownerId: string): Promise<void> {\n const current = await this.redisCacheStoreService.get<string>(lockKey);\n if (current === ownerId) {\n await this.redisCacheStoreService.del(lockKey);\n }\n }\n\n private async readCachedToken(capabilityIntegrationId: bigint, loggedInUserId: bigint): Promise<IOauthAccessToken | undefined> {\n const memory = this.sessions.get(capabilityIntegrationId.toString());\n if (memory && isTokenFresh(memory.tokenExpiry)) {\n return {\n accessToken: memory.token,\n tokenType: memory.tokenType,\n expiresAt: memory.tokenExpiry,\n refreshToken: memory.refreshToken,\n };\n }\n\n const redisToken = await this.tokenCache.get(capabilityIntegrationId);\n if (redisToken && isTokenFresh(redisToken.expiresAt)) {\n this.writeMemory(capabilityIntegrationId, redisToken);\n return redisToken;\n }\n\n const row = await this.tokenDao.findByCapabilityIntegrationId(capabilityIntegrationId, loggedInUserId);\n if (!row || !isTokenFresh(row.expiresAt)) {\n return undefined;\n }\n\n const accessToken = await this.decryptToken(row.accessToken);\n const refreshToken = row.refreshToken ? await this.decryptToken(row.refreshToken) : undefined;\n const token: IOauthAccessToken = {\n accessToken,\n tokenType: (row.tokenMetadata?.tokenType as string | undefined) ?? 'Bearer',\n expiresAt: row.expiresAt,\n refreshToken,\n metadata: row.tokenMetadata ?? undefined,\n };\n\n this.writeMemory(capabilityIntegrationId, token);\n await this.tokenCache.set(capabilityIntegrationId, token);\n return token;\n }\n\n private async mintToken(\n capabilityIntegrationId: bigint | undefined,\n opts: IGetValidAccessTokenOptions,\n loggedInUserId: bigint,\n ): Promise<IOauthAccessToken> {\n if (!opts.credentials) {\n throw new Error('OAuth mint credentials are required when no valid cached token exists');\n }\n\n const { tokenUrl, scope, grantType } = await this.resolveMintContext(opts.credentials, opts, loggedInUserId);\n const handler = this.grantHandlerRegistry.get(grantType);\n\n this.logger.info(loggedInUserId, this.mintToken.name, this.fileName, 'Minting OAuth token', {\n capabilityIntegrationId: capabilityIntegrationId?.toString(),\n grantType,\n });\n\n try {\n const minted = await handler.mint({\n credentials: opts.credentials,\n tokenUrl,\n scope,\n integration: {\n id: capabilityIntegrationId,\n capabilityId: opts.capabilityId,\n providerId: opts.providerId,\n },\n loggedInUserId,\n });\n\n if (!minted.accessToken) {\n throw new Error('OAuth mint returned an empty access token');\n }\n\n if (hasPersistedIntegrationId(capabilityIntegrationId)) {\n await this.storeToken(capabilityIntegrationId, minted, loggedInUserId);\n }\n\n return minted;\n } catch (error) {\n this.logger.error(loggedInUserId, this.mintToken.name, this.fileName, 'OAuth token mint failed', error as Error);\n throw error;\n }\n }\n\n private async resolveMintContext(\n credentials: IOauthMintCredentials,\n opts: IGetValidAccessTokenOptions,\n loggedInUserId: bigint,\n ): Promise<{ tokenUrl: string; scope?: string; grantType: OauthGrantType }> {\n let tokenUrl = credentials.tokenUrl;\n let supportedGrantTypes: OauthGrantType[] | undefined;\n let defaultScopes: string[] | undefined;\n\n if (opts.capabilityId != null && opts.providerId != null) {\n const provider = await this.providerDao.findByCapabilityAndProvider(opts.capabilityId, opts.providerId, loggedInUserId);\n if (provider) {\n tokenUrl = substituteUrlPlaceholders(provider.tokenUrl, credentials.urlParams);\n supportedGrantTypes = provider.supportedGrantTypes as OauthGrantType[];\n defaultScopes = provider.defaultScopes;\n }\n }\n\n tokenUrl = substituteUrlPlaceholders(tokenUrl, credentials.urlParams);\n\n const scope = credentials.scope ?? (defaultScopes?.length ? defaultScopes.join(' ') : undefined);\n const grantType = this.grantHandlerRegistry.resolvePreferredGrant(supportedGrantTypes);\n\n return { tokenUrl, scope, grantType };\n }\n\n private async persistToken(capabilityIntegrationId: bigint, token: IOauthAccessToken, loggedInUserId: bigint): Promise<void> {\n const encryptedAccessToken = await this.encryptToken(token.accessToken);\n const encryptedRefreshToken = token.refreshToken ? await this.encryptToken(token.refreshToken) : undefined;\n\n await this.tokenDao.upsert({\n capabilityIntegrationId,\n accessToken: encryptedAccessToken,\n refreshToken: encryptedRefreshToken,\n expiresAt: token.expiresAt,\n tokenMetadata: {\n ...(token.metadata ?? {}),\n tokenType: token.tokenType,\n },\n loggedInUserId,\n });\n }\n\n private writeMemory(capabilityIntegrationId: bigint, token: IOauthAccessToken): void {\n this.sessions.set(capabilityIntegrationId.toString(), {\n token: token.accessToken,\n tokenType: token.tokenType,\n tokenExpiry: token.expiresAt,\n refreshToken: token.refreshToken,\n });\n }\n\n private async encryptToken(value: string): Promise<string> {\n const keyId = getIntegrationConfigKmsKeyId();\n if (!this.secretProvider || !keyId) {\n throw new Error('OAuth token persist requires SECRET_PROVIDER and INTEGRATION_CONFIG_KMS_KEY_ID');\n }\n\n return this.secretProvider.encrypt(value, keyId);\n }\n\n private async decryptToken(value: string): Promise<string> {\n const keyId = getIntegrationConfigKmsKeyId();\n if (!this.secretProvider || !keyId) {\n throw new Error('OAuth token decrypt requires SECRET_PROVIDER and INTEGRATION_CONFIG_KMS_KEY_ID');\n }\n\n return this.secretProvider.decrypt(value, keyId);\n }\n}\n","import { SYSTEM_USER_ID } from '@dv4resi/dvss-backend-module-utility';\nimport type { ICapabilityIntegration } from '@dvss/dvss-integration-libs';\nimport { Injectable } from '@nestjs/common';\n\nimport type { AuthProvider } from './auth-provider';\nimport type { IGetValidAccessTokenOptions, IOauthAccessToken, IOauthMintCredentials } from './models/oauth.model';\nimport { OauthTokenManager } from './token-manager/oauth-token-manager';\n\n@Injectable()\nexport class OAuth2Provider implements AuthProvider {\n constructor(private readonly tokenManager: OauthTokenManager) {}\n\n async getValidAccessToken(capabilityIntegrationId: bigint | undefined, opts: IGetValidAccessTokenOptions = {}): Promise<IOauthAccessToken> {\n return this.tokenManager.getValidAccessToken(capabilityIntegrationId, opts);\n }\n\n async getAuthenticationHeaders(capabilityIntegrationId: bigint, opts: IGetValidAccessTokenOptions = {}): Promise<Record<string, string>> {\n const token = await this.getValidAccessToken(capabilityIntegrationId, opts);\n return {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Authorization: `${token.tokenType} ${token.accessToken}`,\n };\n }\n\n async testIntegration(integration: ICapabilityIntegration, loggedInUserId: bigint, credentials: IOauthMintCredentials): Promise<boolean> {\n const token = await this.getValidAccessToken(integration.id, {\n forceRefresh: true,\n loggedInUserId,\n credentials,\n capabilityId: integration.capabilityId,\n providerId: integration.providerId,\n });\n\n if (!token.accessToken) {\n throw new Error('OAuth integration test failed: empty access token');\n }\n\n return true;\n }\n\n async storeToken(capabilityIntegrationId: bigint, token: IOauthAccessToken, loggedInUserId?: bigint): Promise<void> {\n await this.tokenManager.storeToken(capabilityIntegrationId, token, loggedInUserId ?? SYSTEM_USER_ID);\n }\n\n async invalidate(capabilityIntegrationId: bigint): Promise<void> {\n await this.tokenManager.invalidate(capabilityIntegrationId);\n }\n}\n","import { DatastoreModule } from '@dv4resi/dvss-backend-module-datastore';\nimport { LoggerModule } from '@dv4resi/dvss-backend-module-utility';\nimport { IntegrationLibsModule } from '@dvss/dvss-integration-libs';\nimport { Module } from '@nestjs/common';\n\nimport { OauthTokenCache } from './cache/oauth-token-cache';\nimport { AuthorizationCodeGrantHandler } from './grants/authorization-code.handler';\nimport { ClientCredentialsGrantHandler } from './grants/client-credentials.handler';\nimport { GrantHandlerRegistry } from './grants/grant-handler.registry';\nimport { OAuth2Provider } from './oauth2.provider';\nimport { OauthProviderDao } from './store/oauth-provider.dao';\nimport { OauthTokenDao } from './store/oauth-token.dao';\nimport { OauthTokenManager } from './token-manager/oauth-token-manager';\n\n@Module({\n imports: [IntegrationLibsModule, LoggerModule, DatastoreModule],\n providers: [\n OauthTokenDao,\n OauthProviderDao,\n OauthTokenCache,\n ClientCredentialsGrantHandler,\n AuthorizationCodeGrantHandler,\n GrantHandlerRegistry,\n OauthTokenManager,\n OAuth2Provider,\n ],\n exports: [OAuth2Provider, OauthTokenManager],\n})\nexport class IntegrationOauthModule {}\n","/**\n * Graph API path fragments used by Microsoft calendar capabilities.\n *\n * `mailboxEmail` is whichever mailbox the operation targets — the organizing user for\n * user-organized bookings, or the room itself for the legacy room-organizes flow. Graph\n * derives the event organizer from this mailbox, and event ids are scoped to it.\n */\nexport const MICROSOFT_GRAPH_PATHS = {\n rooms: '/places/microsoft.graph.room',\n userCalendarEvents: (mailboxEmail: string): string => `/users/${encodeURIComponent(mailboxEmail)}/calendar/events`,\n userCalendarEvent: (mailboxEmail: string, eventId: string): string =>\n `/users/${encodeURIComponent(mailboxEmail)}/calendar/events/${encodeURIComponent(eventId)}`,\n userCalendarView: (mailboxEmail: string, startDateTime: string, endDateTime: string): string =>\n `/users/${encodeURIComponent(mailboxEmail)}/calendarView?startDateTime=${encodeURIComponent(startDateTime)}&endDateTime=${encodeURIComponent(endDateTime)}`,\n subscriptions: '/subscriptions',\n subscription: (subscriptionId: string): string => `/subscriptions/${encodeURIComponent(subscriptionId)}`,\n} as const;\n\nexport const MICROSOFT_DEFAULT_GRAPH_BASE_URL = 'https://graph.microsoft.com/v1.0';\n\n/** Token endpoint template — runtime replaces `{tenantId}` (see auth.service). */\nexport const MICROSOFT_DEFAULT_AUTH_URL = 'https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token';\n","import { MICROSOFT_DEFAULT_AUTH_URL, MICROSOFT_DEFAULT_GRAPH_BASE_URL } from '../common/microsoft.constant';\nimport type { IMicrosoftConfig, IMicrosoftIntegrationConfig } from '../models';\n\nexport type MicrosoftIntegrationConfigInput = Pick<IMicrosoftIntegrationConfig, 'tenantId' | 'clientId' | 'clientSecret'>;\n\n/**\n * Build a full Microsoft integration config with platform URL defaults.\n * Persists authUrl with the real tenantId substituted (not a template placeholder).\n */\nexport function buildMicrosoftIntegrationConfig(integrationConfig: MicrosoftIntegrationConfigInput, existing?: Partial<IMicrosoftConfig>): IMicrosoftConfig {\n const existingBaseUrl = existing?.platformConfig?.baseUrl.trim();\n\n return {\n platformConfig: {\n authUrl: MICROSOFT_DEFAULT_AUTH_URL.replace('{tenantId}', integrationConfig.tenantId),\n baseUrl: existingBaseUrl || MICROSOFT_DEFAULT_GRAPH_BASE_URL,\n },\n integrationConfig: {\n tenantId: integrationConfig.tenantId,\n clientId: integrationConfig.clientId,\n clientSecret: integrationConfig.clientSecret,\n },\n };\n}\n","export const MICROSOFT_SECURE_STORAGE = 'MICROSOFT_INTEGRATION_CONFIG_SECURE_STORAGE';\n\nexport function getMicrosoftKmsKeyId(): string {\n return process.env.INTEGRATION_CONFIG_KMS_KEY_ID || '';\n}\n\nexport function looksLikeStoredSecureConfig(config: Record<string, unknown>): boolean {\n const integrationConfig = config.integrationConfig;\n\n if (typeof integrationConfig !== 'object' || integrationConfig === null || Array.isArray(integrationConfig)) {\n return false;\n }\n\n return Object.values(integrationConfig as Record<string, unknown>).some((value) => typeof value === 'object' && value !== null && 'isSensitive' in value);\n}\n","export const MICROSOFT_CLIENT_CREDENTIALS_GRANT_TYPE = 'client_credentials';\n\nexport const MICROSOFT_DEFAULT_GRAPH_SCOPE = 'https://graph.microsoft.com/.default';\n\nexport const MICROSOFT_DEFAULT_ACCESS_TOKEN_TYPE = 'Bearer';\n\nexport const MICROSOFT_DEFAULT_HEADERS = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Accept: 'application/json',\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/json',\n};\n\nexport const MICROSOFT_TOKEN_HEADERS = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Accept: 'application/json',\n // eslint-disable-next-line @typescript-eslint/naming-convention\n 'Content-Type': 'application/x-www-form-urlencoded',\n};\n","import { LoggerService, SYSTEM_USER_ID } from '@dv4resi/dvss-backend-module-utility';\nimport {\n BaseAuth,\n type ICapabilityIntegration,\n type IValidatedCapabilityIntegration,\n type IntegrationConfigSecureStorageService,\n} from '@dvss/dvss-integration-libs';\nimport { OAuth2Provider, type IOauthAccessToken, type IOauthMintCredentials, secondsUntil } from '@dvss/dvss-integration-oauth';\nimport { Inject, Injectable, Optional } from '@nestjs/common';\n\nimport { buildMicrosoftIntegrationConfig } from '../../common/build-microsoft-integration-config';\nimport { getMicrosoftKmsKeyId, looksLikeStoredSecureConfig, MICROSOFT_SECURE_STORAGE } from '../../common/microsoft-secure-storage';\nimport { MICROSOFT_DEFAULT_ACCESS_TOKEN_TYPE, MICROSOFT_DEFAULT_GRAPH_SCOPE } from '../../enum';\nimport type { IMicrosoftAccessToken, IMicrosoftConfig } from '../../models';\n\nfunction requireNonEmpty(value: unknown, fieldName: string): asserts value is string {\n if (value == null || (typeof value === 'string' && value.trim() === '')) {\n throw new Error(`Microsoft integration configuration: ${fieldName} is required`);\n }\n}\n\nfunction requireObject(value: unknown, fieldName: string): asserts value is Record<string, unknown> {\n if (value == null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`Microsoft integration configuration: ${fieldName} is required`);\n }\n}\n\n@Injectable()\nexport class MicrosoftAuthService implements BaseAuth {\n private readonly fileName = 'auth.service';\n\n constructor(\n private readonly logger: LoggerService,\n private readonly oauth2Provider: OAuth2Provider,\n @Optional() @Inject(MICROSOFT_SECURE_STORAGE) private readonly secureStorage?: IntegrationConfigSecureStorageService,\n ) {}\n\n /**\n * Validates Azure AD / Graph integration configuration.\n * Authorization headers are resolved on demand via OAuth2Provider (not from config.accessDetails).\n */\n validateConfig(integration: ICapabilityIntegration, loggedInUserId: bigint): IValidatedCapabilityIntegration {\n const config = this.parseAndValidateConfig(integration, loggedInUserId);\n\n return {\n ...integration,\n id: integration.id as bigint,\n config: config as unknown as IValidatedCapabilityIntegration['config'],\n headers: {},\n } as IValidatedCapabilityIntegration;\n }\n\n /**\n * Typed config validation used by API client and other capabilities.\n * Applies platform URL defaults when platformConfig is missing/incomplete.\n */\n parseAndValidateConfig(integration: ICapabilityIntegration | Omit<ICapabilityIntegration, 'id'>, loggedInUserId?: bigint): IMicrosoftConfig {\n this.logger.info(loggedInUserId ?? SYSTEM_USER_ID, this.parseAndValidateConfig.name, this.fileName, 'Validating Microsoft integration config');\n\n const raw = integration.config as Partial<IMicrosoftConfig> | undefined;\n\n if (!raw) {\n throw new Error('Microsoft integration config is required');\n }\n\n const integrationConfig = raw.integrationConfig;\n requireObject(integrationConfig, 'integrationConfig');\n requireNonEmpty(integrationConfig.tenantId, 'integrationConfig.tenantId');\n requireNonEmpty(integrationConfig.clientId, 'integrationConfig.clientId');\n requireNonEmpty(integrationConfig.clientSecret, 'integrationConfig.clientSecret');\n\n const config = buildMicrosoftIntegrationConfig(\n {\n tenantId: integrationConfig.tenantId,\n clientId: integrationConfig.clientId,\n clientSecret: integrationConfig.clientSecret,\n },\n raw,\n );\n\n requireNonEmpty(config.platformConfig.authUrl, 'platformConfig.authUrl');\n requireNonEmpty(config.platformConfig.baseUrl, 'platformConfig.baseUrl');\n\n return config;\n }\n\n /**\n * Decrypts stored secure-storage envelopes when present, then validates.\n * Does not mutate the caller's `integration.config`.\n */\n async resolvePlaintextConfig(integration: ICapabilityIntegration | Omit<ICapabilityIntegration, 'id'>, loggedInUserId?: bigint): Promise<IMicrosoftConfig> {\n const stored = (integration.config ?? {}) as Record<string, unknown>;\n const effectiveLoggedInUserId = loggedInUserId ?? SYSTEM_USER_ID;\n let configForParse: Record<string, unknown> = stored;\n\n if (looksLikeStoredSecureConfig(stored)) {\n if (!this.secureStorage) {\n throw new Error('Microsoft integration configuration: secure storage is required to decrypt stored credentials');\n }\n\n configForParse = (await this.secureStorage.prepareForBackend(stored, getMicrosoftKmsKeyId(), effectiveLoggedInUserId)) as Record<string, unknown>;\n }\n\n return this.parseAndValidateConfig(\n {\n ...integration,\n config: configForParse,\n },\n loggedInUserId,\n );\n }\n\n async getAccessToken(\n integration: ICapabilityIntegration | Omit<ICapabilityIntegration, 'id'>,\n loggedInUserId?: bigint,\n forceRefresh: boolean = false,\n ): Promise<IMicrosoftAccessToken> {\n const config = await this.resolvePlaintextConfig(integration, loggedInUserId);\n const token = await this.oauth2Provider.getValidAccessToken('id' in integration ? integration.id : undefined, {\n forceRefresh,\n loggedInUserId: loggedInUserId ?? SYSTEM_USER_ID,\n credentials: this.toMintCredentials(config),\n capabilityId: integration.capabilityId,\n providerId: integration.providerId,\n });\n\n return this.toMicrosoftAccessToken(token);\n }\n\n /**\n * Persists a previously minted token after capability_integration insert.\n */\n async persistMintedAccessToken(capabilityIntegrationId: bigint, token: IMicrosoftAccessToken, loggedInUserId: bigint): Promise<void> {\n if (token.expiresIn <= 0) {\n return;\n }\n\n await this.oauth2Provider.storeToken(\n capabilityIntegrationId,\n {\n accessToken: token.accessToken,\n tokenType: token.tokenType || MICROSOFT_DEFAULT_ACCESS_TOKEN_TYPE,\n expiresAt: new Date(Date.now() + token.expiresIn * 1000),\n },\n loggedInUserId,\n );\n }\n\n /**\n * BaseAuth contract — returns the access token string.\n */\n async fetchAccessToken(integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<string> {\n const token = await this.getAccessToken(integration, loggedInUserId);\n return token.accessToken;\n }\n\n /**\n * Tests connectivity by obtaining a client-credentials access token.\n */\n async testIntegration(integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<boolean> {\n this.logger.info(loggedInUserId, this.testIntegration.name, this.fileName, 'Testing Microsoft Graph integration');\n\n const config = await this.resolvePlaintextConfig(integration, loggedInUserId);\n const isSuccessful = await this.oauth2Provider.testIntegration(integration, loggedInUserId, this.toMintCredentials(config));\n\n this.logger.info(loggedInUserId, this.testIntegration.name, this.fileName, 'Microsoft Graph integration test successful');\n return isSuccessful;\n }\n\n toMintCredentials(config: IMicrosoftConfig): IOauthMintCredentials {\n return {\n tokenUrl: config.platformConfig.authUrl,\n clientId: config.integrationConfig.clientId,\n clientSecret: config.integrationConfig.clientSecret,\n scope: MICROSOFT_DEFAULT_GRAPH_SCOPE,\n urlParams: { tenantId: config.integrationConfig.tenantId },\n };\n }\n\n private toMicrosoftAccessToken(token: IOauthAccessToken): IMicrosoftAccessToken {\n return {\n accessToken: token.accessToken,\n tokenType: token.tokenType || MICROSOFT_DEFAULT_ACCESS_TOKEN_TYPE,\n expiresIn: secondsUntil(token.expiresAt),\n };\n }\n}\n","import { LoggerService, SYSTEM_USER_ID } from '@dv4resi/dvss-backend-module-utility';\nimport { HTTP_METHOD, type ICapabilityIntegration, type IValidatedCapabilityIntegration, TrafficGatewayService } from '@dvss/dvss-integration-libs';\nimport { OAuth2Provider } from '@dvss/dvss-integration-oauth';\nimport { Injectable } from '@nestjs/common';\n\nimport { MicrosoftAuthService } from '../capabilities/auth/auth.service';\nimport { MICROSOFT_DEFAULT_HEADERS } from '../enum';\n\nexport interface IMicrosoftApiCallRequest<TBody = unknown> {\n apiMethod: HTTP_METHOD;\n url: string;\n body?: TBody;\n headers?: Record<string, string>;\n responseType?: 'json' | 'text' | 'blob' | 'arraybuffer';\n}\n\n@Injectable()\nexport class MicrosoftApiClientService {\n private readonly fileName = 'microsoft-api-client.service';\n\n private readonly maxAuthRetryCount = 2;\n\n constructor(\n private readonly logger: LoggerService,\n private readonly authService: MicrosoftAuthService,\n private readonly oauth2Provider: OAuth2Provider,\n private readonly trafficGatewayService: TrafficGatewayService,\n ) {}\n\n async apiCall<TResponse = unknown, TBody = unknown>(\n request: IMicrosoftApiCallRequest<TBody>,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint = SYSTEM_USER_ID,\n ): Promise<TResponse> {\n return this.executeWithRetry(request, integration, loggedInUserId, 0);\n }\n\n private async executeWithRetry<TResponse = unknown, TBody = unknown>(\n request: IMicrosoftApiCallRequest<TBody>,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n retryCount: number,\n ): Promise<TResponse> {\n const config = await this.authService.resolvePlaintextConfig(integration, loggedInUserId);\n const authHeaders = await this.oauth2Provider.getAuthenticationHeaders(integration.id as bigint, {\n forceRefresh: retryCount > 0,\n loggedInUserId,\n credentials: this.authService.toMintCredentials(config),\n capabilityId: integration.capabilityId,\n providerId: integration.providerId,\n });\n const headers = {\n ...MICROSOFT_DEFAULT_HEADERS,\n ...(request.headers ?? {}),\n ...authHeaders,\n };\n\n const validatedIntegration = {\n ...integration,\n headers,\n } as IValidatedCapabilityIntegration;\n\n this.logger.info(loggedInUserId, this.apiCall.name, this.fileName, 'Microsoft Graph API call', {\n method: request.apiMethod,\n url: request.url,\n hasBody: request.body != null,\n });\n\n try {\n return await this.trafficGatewayService.executeIntegrationRequest<TResponse, TBody>(\n {\n apiMethod: request.apiMethod,\n baseUrl: config.platformConfig.baseUrl,\n url: request.url,\n body: request.body,\n headers,\n responseType: request.responseType,\n },\n validatedIntegration,\n loggedInUserId,\n );\n } catch (error) {\n if (!this.isUnauthorizedError(error) || retryCount >= this.maxAuthRetryCount) {\n throw error;\n }\n\n if (integration.id != null) {\n await this.oauth2Provider.invalidate(integration.id);\n }\n\n this.logger.info(loggedInUserId, this.executeWithRetry.name, this.fileName, 'Retrying Microsoft Graph API call after unauthorized response', {\n retryCount: retryCount + 1,\n url: request.url,\n });\n\n return this.executeWithRetry(request, integration, loggedInUserId, retryCount + 1);\n }\n }\n\n private isUnauthorizedError(error: unknown): boolean {\n const errorObject = error as {\n response?: {\n status?: number;\n };\n status?: number;\n };\n\n return errorObject.response?.status === 401 || errorObject.status === 401;\n }\n}\n","import {\n DAY_OF_WEEK,\n OFFERING_RESOURCE_TYPE,\n type IScheduleConfig,\n SCHEDULE_MONTHLY_UNIT,\n SCHEDULE_REPEAT_TYPE,\n} from '@dv4resi/dvss-backend-module-datastore/dist/datastore/models';\nimport {\n EVENT_INSTANCE_KIND,\n type IBookingEvent,\n type IBookingEventInstance,\n type IBookingEventRef,\n type IBookingItem,\n type IEventSyncMetadata,\n type IExcludedDateResult,\n} from '@dvss/dvss-integration-libs';\n\nimport type { IMicrosoftGraphAttendee, IMicrosoftGraphEvent, IMicrosoftGraphEventsResponse, IMicrosoftGraphRecurrence } from '../../models';\n\n/** Graph attendee type that books a room/equipment mailbox rather than inviting a person. */\nconst GRAPH_RESOURCE_ATTENDEE_TYPE = 'resource';\n\n/** DVSS weekday → Graph weekday string. */\nconst GRAPH_WEEKDAY: Readonly<Record<DAY_OF_WEEK, string>> = {\n [DAY_OF_WEEK.SUN]: 'sunday',\n [DAY_OF_WEEK.MON]: 'monday',\n [DAY_OF_WEEK.TUE]: 'tuesday',\n [DAY_OF_WEEK.WED]: 'wednesday',\n [DAY_OF_WEEK.THU]: 'thursday',\n [DAY_OF_WEEK.FRI]: 'friday',\n [DAY_OF_WEEK.SAT]: 'saturday',\n};\n\n/** DVSS nth-weekday ordinal → Graph relativeMonthly `index`. */\nconst GRAPH_MONTHLY_INDEX: Readonly<Record<SCHEDULE_MONTHLY_UNIT, string>> = {\n [SCHEDULE_MONTHLY_UNIT.FIRST]: 'first',\n [SCHEDULE_MONTHLY_UNIT.SECOND]: 'second',\n [SCHEDULE_MONTHLY_UNIT.THIRD]: 'third',\n [SCHEDULE_MONTHLY_UNIT.FOURTH]: 'fourth',\n [SCHEDULE_MONTHLY_UNIT.LAST]: 'last',\n};\n\n/** Graph event `type` → outbound-result instance kind. */\nconst GRAPH_TYPE_TO_INSTANCE_KIND: Readonly<Record<string, EVENT_INSTANCE_KIND>> = {\n singleInstance: EVENT_INSTANCE_KIND.SINGLE,\n seriesMaster: EVENT_INSTANCE_KIND.SERIES_MASTER,\n occurrence: EVENT_INSTANCE_KIND.OCCURRENCE,\n exception: EVENT_INSTANCE_KIND.EXCEPTION,\n};\n\n/**\n * Maps the system `IBookingEvent` (an `AddOfferingBookingInput`-shaped subset, values already\n * resolved to emails) to a Microsoft Graph event body. **Every key rename happens here.**\n * Booking-domain fields with no calendar meaning (`customFields`, `assets`, `preferences`, …)\n * are ignored.\n *\n * `options.targetMailbox` is the mailbox the event will be created/patched in (the organizer's,\n * or the room's). It is NOT added as an attendee — Graph derives the organizer from it.\n */\nexport function toGraphEvent(event: IBookingEvent | Partial<IBookingEvent>, options?: { targetMailbox?: string }): IMicrosoftGraphEvent {\n const graph: IMicrosoftGraphEvent = {};\n\n if (event.name !== undefined) {\n graph.subject = event.name;\n }\n const body = event.description ?? event.notes ?? undefined;\n if (body !== undefined) {\n graph.body = { contentType: 'text', content: body };\n }\n if (event.bookingStartDateLabel !== undefined) {\n graph.start = { dateTime: toGraphDateTime(event.bookingStartDateLabel, event.bookingStartTimeLabel, event.isFullDay), timeZone: event.timeZone ?? '' };\n }\n if (event.bookingEndDateLabel !== undefined) {\n graph.end = { dateTime: toGraphDateTime(event.bookingEndDateLabel, event.bookingEndTimeLabel, event.isFullDay), timeZone: event.timeZone ?? '' };\n }\n if (event.isFullDay !== undefined) {\n graph.isAllDay = event.isFullDay;\n }\n if (event.isRecurring && event.schedule) {\n // The recurrence range spans the whole series, while `booking*DateLabel` describe only the\n // first occurrence's slot — passing the latter as `range.endDate` ends the series on day one.\n // `seriesEndDateLabel` carries the real range end; the fallback keeps callers that never set\n // it (and single-day series) behaving as before.\n const recurrence = scheduleToGraphRecurrence(event.schedule, {\n startDate: event.bookingStartDateLabel,\n endDate: event.seriesEndDateLabel ?? event.bookingEndDateLabel,\n });\n if (recurrence) {\n graph.recurrence = recurrence;\n }\n }\n\n const attendees = buildGraphAttendees(event, options?.targetMailbox);\n if (attendees.length > 0) {\n graph.attendees = attendees;\n }\n\n // `organizer` is deliberately not written — Graph derives it from the request mailbox.\n\n return graph;\n}\n\n/**\n * The room mailbox(es) DVSS put on the event: `items[].externalId` for every item that books\n * a SPACE resource. Trimmed, deduped, non-empty.\n */\nexport function spaceMailboxesFromItems(items: IBookingItem[] | undefined): string[] {\n const out: string[] = [];\n const seen = new Set<string>();\n\n for (const item of items ?? []) {\n const isSpace = item.resources?.some((resource) => resource.resourceType === OFFERING_RESOURCE_TYPE.SPACE);\n const email = item.externalId?.trim();\n const key = email?.toLowerCase();\n\n if (isSpace && email && key && !seen.has(key)) {\n seen.add(key);\n out.push(email);\n }\n }\n\n return out;\n}\n\n/**\n * `requestedForIds` + `recipientIds` (people, resolved emails) → `required`;\n * the room mailboxes from `items[]` → `resource`. The `targetMailbox` (organizer / room the\n * event is created in) is skipped. Deduped by lowercased email.\n */\nfunction buildGraphAttendees(event: Partial<IBookingEvent>, targetMailbox: string | undefined): IMicrosoftGraphAttendee[] {\n const target = targetMailbox?.trim().toLowerCase();\n const seen = new Set<string>(target ? [target] : []);\n const attendees: IMicrosoftGraphAttendee[] = [];\n\n const add = (email: string | undefined, type: string): void => {\n const key = email?.trim().toLowerCase();\n if (!key || seen.has(key)) {\n return;\n }\n seen.add(key);\n attendees.push({ emailAddress: { address: email!.trim() }, type });\n };\n\n for (const email of [...(event.requestedForIds ?? []), ...(event.recipientIds ?? [])]) {\n add(email, 'required');\n }\n for (const email of spaceMailboxesFromItems(event.items)) {\n add(email, GRAPH_RESOURCE_ATTENDEE_TYPE);\n }\n\n return attendees;\n}\n\n/**\n * Translates a DVSS `IScheduleConfig` + the booking's date window into a Graph `recurrence`,\n * or `undefined` when the schedule can't be expressed as a single Graph rule (CUSTOM dates,\n * multiple month-days, a weekly pattern with no weekdays, or a missing window) — the caller\n * should have routed those to per-occurrence events.\n */\nexport function scheduleToGraphRecurrence(schedule: IScheduleConfig, window: { startDate?: string; endDate?: string }): IMicrosoftGraphRecurrence | undefined {\n if (!window.startDate || !window.endDate) {\n return undefined;\n }\n\n const range = { type: 'endDate', startDate: window.startDate, endDate: window.endDate };\n\n switch (schedule.repeat) {\n case SCHEDULE_REPEAT_TYPE.EVERY_DAY:\n return { pattern: { type: 'daily', interval: 1 }, range };\n\n case SCHEDULE_REPEAT_TYPE.EVERY_WEEK:\n if (!schedule.daysOfWeek?.length) {\n return undefined;\n }\n return {\n pattern: { type: 'weekly', interval: 1, daysOfWeek: schedule.daysOfWeek.map((day) => GRAPH_WEEKDAY[day]) },\n range,\n };\n\n case SCHEDULE_REPEAT_TYPE.EVERY_MONTH:\n if (schedule.datesOfMonth?.length === 1) {\n return { pattern: { type: 'absoluteMonthly', interval: 1, dayOfMonth: schedule.datesOfMonth[0] }, range };\n }\n if (schedule.monthlyUnit && schedule.daysOfWeek?.length) {\n return {\n pattern: {\n type: 'relativeMonthly',\n interval: 1,\n daysOfWeek: schedule.daysOfWeek.map((day) => GRAPH_WEEKDAY[day]),\n index: GRAPH_MONTHLY_INDEX[schedule.monthlyUnit],\n },\n range,\n };\n }\n return undefined;\n\n case SCHEDULE_REPEAT_TYPE.CUSTOM:\n default:\n return undefined;\n }\n}\n\n/**\n * Maps a Graph event (a create/patch response) to the slim outbound result the consumer persists.\n */\nexport function graphEventToRef(\n graph: IMicrosoftGraphEvent,\n options?: {\n organizerUserEmail?: string;\n resourceId?: string;\n syncMetadata?: IEventSyncMetadata;\n excludedDateResults?: IExcludedDateResult[];\n },\n): IBookingEventRef {\n return {\n id: graph.id,\n seriesId: graph.seriesMasterId,\n instanceKind: graph.type ? GRAPH_TYPE_TO_INSTANCE_KIND[graph.type] : undefined,\n syncMetadata: omitUndefined({\n ...options?.syncMetadata,\n externalEventId: graph.id ?? options?.syncMetadata?.externalEventId,\n organizerUserEmail: options?.organizerUserEmail ?? options?.syncMetadata?.organizerUserEmail,\n resourceId: options?.resourceId ?? options?.syncMetadata?.resourceId,\n excludedDateResults: options?.excludedDateResults ?? options?.syncMetadata?.excludedDateResults,\n }),\n };\n}\n\n/**\n * Maps a Graph calendarView response to the occurrence list that backs single-instance\n * series edits (id + local date + the series it belongs to).\n */\nexport function graphEventsToInstances(response: IMicrosoftGraphEventsResponse): IBookingEventInstance[] {\n return (response.value ?? [])\n .filter((graph): graph is IMicrosoftGraphEvent & { id: string; start: { dateTime: string } } => Boolean(graph.id && graph.start?.dateTime))\n .map((graph) => omitUndefined({ id: graph.id, startDateLabel: graph.start.dateTime.slice(0, 10), seriesId: graph.seriesMasterId }));\n}\n\n/**\n * Composes a Graph `dateTime` (local, no offset) from DVSS date + time labels.\n * Full-day / missing time → midnight. Accepts `HH:mm` or `HH:mm:ss`.\n */\nexport function toGraphDateTime(dateLabel: string, timeLabel: string | undefined, isFullDay: boolean | undefined): string {\n if (isFullDay || !timeLabel) {\n return `${dateLabel}T00:00:00`;\n }\n const parts = timeLabel.split(':');\n const hh = parts[0] ?? '00';\n const mm = parts[1] ?? '00';\n const ss = parts[2] ?? '00';\n return `${dateLabel}T${hh}:${mm}:${ss}`;\n}\n\nfunction omitUndefined<T extends Record<string, unknown>>(value: T): T {\n return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined)) as T;\n}\n","import { CustomException, LoggerService } from '@dv4resi/dvss-backend-module-utility';\nimport {\n BaseCalendarBookingManagement,\n HTTP_METHOD,\n type IBookingEventRef,\n type ICancelEventRequest,\n type ICapabilityIntegration,\n type ICreateEventRequest,\n type IDeleteEventRequest,\n type IExcludedDateResult,\n type IGetEventsRequest,\n type IGetEventsResponse,\n type IUpdateEventRequest,\n} from '@dvss/dvss-integration-libs';\nimport { Injectable } from '@nestjs/common';\n\nimport { MicrosoftApiClientService } from '../../adapter/microsoft-api-client.service';\nimport { MICROSOFT_GRAPH_PATHS } from '../../common';\nimport type { IMicrosoftGraphEvent, IMicrosoftGraphEventsResponse } from '../../models';\nimport { graphEventsToInstances, graphEventToRef, spaceMailboxesFromItems, toGraphEvent } from './booking-management.mapper';\n\n/**\n * Microsoft Graph calendar event lifecycle — OUTBOUND only.\n * Endpoints:\n * - POST | PATCH | DELETE /users/{mailboxEmail}/calendar/events[/{eventId}]\n * - GET /users/{mailboxEmail}/calendarView (single-instance-of-a-series lookup)\n *\n * The mailbox in the URL owns the event: Graph makes its owner the organizer. On create that\n * is the first requested-for person (`event.requestedForIds[0]`) when known, else the room in\n * `event.items[].externalId`. Later ops are mailbox-scoped and reuse the persisted\n * `organizerUserEmail`.\n */\n@Injectable()\nexport class MicrosoftCalendarBookingService extends BaseCalendarBookingManagement {\n private readonly fileName = 'booking-management.service';\n\n constructor(\n private readonly logger: LoggerService,\n private readonly microsoftApiClient: MicrosoftApiClientService,\n ) {\n super();\n }\n\n override async createEvent(request: ICreateEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IBookingEventRef> {\n try {\n const organizerEmail = request.event.requestedForIds?.[0];\n const roomEmail = spaceMailboxesFromItems(request.event.items)[0];\n const mailboxEmail = this.pickMailbox(organizerEmail, roomEmail);\n this.assertMailbox(mailboxEmail);\n\n this.logger.info(loggedInUserId, this.createEvent.name, this.fileName, 'Create Microsoft Graph calendar event', {\n mailboxEmail,\n subject: request.event.name,\n path: MICROSOFT_GRAPH_PATHS.userCalendarEvents(mailboxEmail),\n });\n\n const graphEvent = await this.microsoftApiClient.apiCall<IMicrosoftGraphEvent>(\n {\n apiMethod: HTTP_METHOD.POST,\n url: MICROSOFT_GRAPH_PATHS.userCalendarEvents(mailboxEmail),\n body: toGraphEvent(request.event, { targetMailbox: mailboxEmail }),\n },\n integration,\n loggedInUserId,\n );\n\n const excludedDateResults = await this.resolveSkipDatesIfAny(\n graphEvent.id,\n request.event.schedule?.skipDates,\n mailboxEmail,\n this.organizerUserMailbox(organizerEmail),\n integration,\n loggedInUserId,\n );\n\n const ref = graphEventToRef(graphEvent, {\n organizerUserEmail: this.organizerUserMailbox(organizerEmail),\n resourceId: roomEmail,\n syncMetadata: request.event.syncMetadata,\n excludedDateResults,\n });\n this.logger.info(loggedInUserId, this.createEvent.name, this.fileName, 'Created Microsoft Graph calendar event', { eventId: ref.id, mailboxEmail });\n return ref;\n } catch (error) {\n this.logger.error(loggedInUserId, this.createEvent.name, this.fileName, 'Error creating Microsoft Graph calendar event', error);\n throw error;\n }\n }\n\n override async updateEvent(request: IUpdateEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IBookingEventRef> {\n try {\n // Mailbox-scoped id — target the mailbox the event was created in (persisted by the caller).\n const mailboxEmail = this.pickMailbox(request.organizerUserEmail, request.resourceEmail);\n this.assertMailbox(mailboxEmail);\n this.assertEventId(request.eventId);\n\n this.logger.info(loggedInUserId, this.updateEvent.name, this.fileName, 'Update Microsoft Graph calendar event', {\n mailboxEmail,\n eventId: request.eventId,\n path: MICROSOFT_GRAPH_PATHS.userCalendarEvent(mailboxEmail, request.eventId),\n });\n\n const graphEvent = await this.microsoftApiClient.apiCall<IMicrosoftGraphEvent>(\n {\n apiMethod: HTTP_METHOD.PATCH,\n url: MICROSOFT_GRAPH_PATHS.userCalendarEvent(mailboxEmail, request.eventId),\n body: toGraphEvent(request.event, { targetMailbox: mailboxEmail }),\n },\n integration,\n loggedInUserId,\n );\n\n const excludedDateResults = await this.resolveSkipDatesIfAny(\n graphEvent.id ?? request.eventId,\n request.event.schedule?.skipDates,\n mailboxEmail,\n this.organizerUserMailbox(request.organizerUserEmail),\n integration,\n loggedInUserId,\n );\n\n const ref = graphEventToRef(graphEvent, {\n organizerUserEmail: this.organizerUserMailbox(request.organizerUserEmail),\n resourceId: request.resourceEmail,\n syncMetadata: request.event.syncMetadata,\n excludedDateResults,\n });\n this.logger.info(loggedInUserId, this.updateEvent.name, this.fileName, 'Updated Microsoft Graph calendar event', { eventId: ref.id, mailboxEmail });\n return ref;\n } catch (error) {\n this.logger.error(loggedInUserId, this.updateEvent.name, this.fileName, 'Error updating Microsoft Graph calendar event', error);\n throw error;\n }\n }\n\n override async cancelEvent(request: ICancelEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<void> {\n try {\n const mailboxEmail = this.pickMailbox(request.organizerUserEmail, request.resourceEmail);\n this.logger.info(loggedInUserId, this.cancelEvent.name, this.fileName, 'Cancel Microsoft Graph calendar event', {\n mailboxEmail,\n eventId: request.eventId,\n });\n await this.deleteGraphEvent(mailboxEmail, request.eventId, integration, loggedInUserId);\n } catch (error) {\n this.logger.error(loggedInUserId, this.cancelEvent.name, this.fileName, 'Error cancelling Microsoft Graph calendar event', error);\n throw error;\n }\n }\n\n override async deleteEvent(request: IDeleteEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<void> {\n try {\n const mailboxEmail = this.pickMailbox(request.organizerUserEmail, request.resourceEmail);\n this.logger.info(loggedInUserId, this.deleteEvent.name, this.fileName, 'Delete Microsoft Graph calendar event', {\n mailboxEmail,\n eventId: request.eventId,\n });\n await this.deleteGraphEvent(mailboxEmail, request.eventId, integration, loggedInUserId);\n } catch (error) {\n this.logger.error(loggedInUserId, this.deleteEvent.name, this.fileName, 'Error deleting Microsoft Graph calendar event', error);\n throw error;\n }\n }\n\n override async getEvents(request: IGetEventsRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IGetEventsResponse> {\n try {\n const mailboxEmail = this.pickMailbox(request.organizerUserEmail, request.resourceEmail);\n this.assertMailbox(mailboxEmail);\n const hasWindow = Boolean(request.startDateLabel && request.endDateLabel);\n const url = hasWindow\n ? MICROSOFT_GRAPH_PATHS.userCalendarView(mailboxEmail, `${request.startDateLabel}T00:00:00`, `${request.endDateLabel}T23:59:59`)\n : MICROSOFT_GRAPH_PATHS.userCalendarEvents(mailboxEmail);\n\n this.logger.info(loggedInUserId, this.getEvents.name, this.fileName, 'List Microsoft Graph calendar events', {\n mailboxEmail,\n path: url,\n hasTimeWindow: hasWindow,\n });\n\n const response = await this.microsoftApiClient.apiCall<IMicrosoftGraphEventsResponse>(\n { apiMethod: HTTP_METHOD.GET, url },\n integration,\n loggedInUserId,\n );\n const events = graphEventsToInstances(response);\n this.logger.info(loggedInUserId, this.getEvents.name, this.fileName, 'Listed Microsoft Graph calendar events', {\n mailboxEmail,\n count: events.length,\n });\n return { events };\n } catch (error) {\n this.logger.error(loggedInUserId, this.getEvents.name, this.fileName, 'Error listing Microsoft Graph calendar events', error);\n throw error;\n }\n }\n\n private async deleteGraphEvent(mailboxEmail: string, eventId: string, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<void> {\n this.assertMailbox(mailboxEmail);\n this.assertEventId(eventId);\n await this.microsoftApiClient.apiCall(\n { apiMethod: HTTP_METHOD.DELETE, url: MICROSOFT_GRAPH_PATHS.userCalendarEvent(mailboxEmail, eventId) },\n integration,\n loggedInUserId,\n );\n }\n\n /**\n * Graph always creates/updates a recurring series whole. For each date in\n * `schedule.skipDates` this finds the occurrence instance in the series just\n * created/updated and cancels it via the existing DELETE path. Best-effort per date — a\n * date that can't be resolved is reported `excluded: false`, not thrown.\n */\n private async resolveSkipDatesIfAny(\n seriesId: string | undefined,\n dates: string[] | undefined,\n mailboxEmail: string,\n organizerUserEmail: string | undefined,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IExcludedDateResult[] | undefined> {\n if (!dates?.length) {\n return undefined;\n }\n\n const results: IExcludedDateResult[] = [];\n\n for (const date of dates) {\n try {\n const instanceId = await this.findOccurrenceInstanceId(seriesId, date, mailboxEmail, integration, loggedInUserId);\n if (!instanceId) {\n this.logger.warn(loggedInUserId, this.resolveSkipDatesIfAny.name, this.fileName, 'Could not resolve skip-date occurrence', {\n seriesId,\n date,\n mailboxEmail,\n });\n results.push({ date, excluded: false });\n continue;\n }\n\n await this.cancelEvent({ eventId: instanceId, resourceEmail: mailboxEmail, organizerUserEmail }, integration, loggedInUserId);\n results.push({ date, eventId: instanceId, excluded: true });\n } catch (error) {\n this.logger.warn(loggedInUserId, this.resolveSkipDatesIfAny.name, this.fileName, 'Failed to cancel skip-date occurrence', {\n seriesId,\n date,\n mailboxEmail,\n error: error instanceof Error ? error.message : String(error),\n });\n results.push({ date, excluded: false });\n }\n }\n\n return results;\n }\n\n private async findOccurrenceInstanceId(\n seriesId: string | undefined,\n date: string,\n mailboxEmail: string,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<string | undefined> {\n const response = await this.microsoftApiClient.apiCall<IMicrosoftGraphEventsResponse>(\n { apiMethod: HTTP_METHOD.GET, url: MICROSOFT_GRAPH_PATHS.userCalendarView(mailboxEmail, `${date}T00:00:00`, `${date}T23:59:59`) },\n integration,\n loggedInUserId,\n );\n return (response.value ?? []).find((occurrence) => occurrence.seriesMasterId === seriesId)?.id;\n }\n\n /** Mailbox the Graph call targets: the organizing user if known, else the room. */\n private pickMailbox(organizerEmail: string | undefined, roomEmail: string | undefined): string {\n return this.organizerUserMailbox(organizerEmail) ?? roomEmail?.trim() ?? '';\n }\n\n /** The organizing user's mailbox, or undefined when the room ends up organizing. */\n private organizerUserMailbox(organizerEmail: string | undefined): string | undefined {\n return organizerEmail?.trim() || undefined;\n }\n\n private assertMailbox(mailboxEmail: string | undefined): void {\n if (!mailboxEmail?.trim()) {\n throw new CustomException('BAD_REQUEST', 'a requested-for or resource mailbox is required');\n }\n }\n\n private assertEventId(eventId: string | undefined): void {\n if (!eventId?.trim()) {\n throw new CustomException('BAD_REQUEST', 'eventId is required');\n }\n }\n}\n","import { LoggerService } from '@dv4resi/dvss-backend-module-utility';\nimport {\n BaseCalendarResourceManagement,\n HTTP_METHOD,\n type ICapabilityIntegration,\n type IGetResourcesRequest,\n type IGetResourcesResponse,\n type IResource,\n} from '@dvss/dvss-integration-libs';\nimport { Injectable } from '@nestjs/common';\n\nimport { MicrosoftApiClientService } from '../../adapter/microsoft-api-client.service';\nimport { MICROSOFT_GRAPH_PATHS } from '../../common';\nimport type { IMicrosoftGraphRoom, IMicrosoftGraphRoomsResponse } from '../../models';\n\n/**\n * Microsoft Graph room mailbox discovery.\n * Endpoint: GET /places/microsoft.graph.room\n */\n@Injectable()\nexport class MicrosoftCalendarResourceService extends BaseCalendarResourceManagement {\n private readonly fileName = 'resource-management.service';\n\n constructor(\n private readonly logger: LoggerService,\n private readonly microsoftApiClient: MicrosoftApiClientService,\n ) {\n super();\n }\n\n override async getResources(request: IGetResourcesRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IGetResourcesResponse> {\n this.logger.info(loggedInUserId, this.getResources.name, this.fileName, 'Fetching Microsoft Graph room mailboxes', {\n search: request.search,\n });\n\n const response = await this.microsoftApiClient.apiCall<IMicrosoftGraphRoomsResponse>(\n {\n apiMethod: HTTP_METHOD.GET,\n url: MICROSOFT_GRAPH_PATHS.rooms,\n },\n integration,\n loggedInUserId,\n );\n\n const resources = (response.value ?? [])\n .map((room) => this.mapRoom(room))\n .filter((room): room is IResource => room !== undefined)\n .filter((room) => {\n if (!request.search) {\n return true;\n }\n const needle = request.search.toLowerCase();\n return room.displayName?.toLowerCase().includes(needle) === true || room.id.toLowerCase().includes(needle);\n });\n\n return { resources };\n }\n\n private mapRoom(room: IMicrosoftGraphRoom): IResource | undefined {\n if (!room.emailAddress) {\n return undefined;\n }\n\n return {\n id: room.emailAddress,\n displayName: room.displayName,\n capacity: room.capacity,\n building: room.building,\n floorLabel: room.floorLabel,\n };\n }\n}\n","import { CustomException, LoggerService } from '@dv4resi/dvss-backend-module-utility';\nimport {\n BaseCalendarWebhookManagement,\n HTTP_METHOD,\n type ICapabilityIntegration,\n type IDeleteWebhookRequest,\n type IRefreshWebhookRequest,\n type IRefreshWebhookResponse,\n type IRegisterWebhookRequest,\n type IRegisterWebhookResponse,\n type IWebhookSubscription,\n} from '@dvss/dvss-integration-libs';\nimport { Injectable } from '@nestjs/common';\n\nimport { MicrosoftApiClientService } from '../../adapter/microsoft-api-client.service';\nimport { MICROSOFT_GRAPH_PATHS } from '../../common';\nimport type { IMicrosoftGraphSubscription } from '../../models';\n\nconst GRAPH_SUBSCRIPTION_KNOWN_KEYS = new Set(['id', 'resource', 'changeType', 'notificationUrl', 'expirationDateTime', 'clientState']);\n\n/**\n * Microsoft Graph change-notification subscriptions.\n * Caller supplies notificationUrl, resource, clientState, and expirationDateTime.\n * Persistence and the Graph validation handshake live outside this package.\n * Endpoints:\n * - POST /subscriptions\n * - PATCH /subscriptions/{id} (renewal)\n * - DELETE /subscriptions/{id}\n */\n@Injectable()\nexport class MicrosoftCalendarWebhookService extends BaseCalendarWebhookManagement {\n private readonly fileName = 'webhook-management.service';\n\n constructor(\n private readonly logger: LoggerService,\n private readonly microsoftApiClient: MicrosoftApiClientService,\n ) {\n super();\n }\n\n override async registerWebhook(\n request: IRegisterWebhookRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IRegisterWebhookResponse> {\n try {\n this.logger.info(loggedInUserId, this.registerWebhook.name, this.fileName, 'Register Microsoft Graph subscription', {\n resource: request.resource,\n path: MICROSOFT_GRAPH_PATHS.subscriptions,\n });\n this.assertRequired(request.resource, 'resource');\n this.assertRequired(request.notificationUrl, 'notificationUrl');\n this.assertRequired(request.expirationDateTime, 'expirationDateTime');\n if (request.changeTypes.length === 0) {\n throw new CustomException('BAD_REQUEST', 'changeTypes is required');\n }\n\n const graphSubscription = await this.microsoftApiClient.apiCall<IMicrosoftGraphSubscription>(\n {\n apiMethod: HTTP_METHOD.POST,\n url: MICROSOFT_GRAPH_PATHS.subscriptions,\n body: this.toGraphSubscription(request),\n },\n integration,\n loggedInUserId,\n );\n const subscription = this.fromGraphSubscription(graphSubscription);\n this.logger.info(loggedInUserId, this.registerWebhook.name, this.fileName, 'Registered Microsoft Graph subscription', {\n subscriptionId: subscription.id,\n resource: subscription.resource,\n });\n return { subscription };\n } catch (error) {\n this.logger.error(loggedInUserId, this.registerWebhook.name, this.fileName, 'Error registering Microsoft Graph subscription', error);\n throw error;\n }\n }\n\n override async refreshSubscription(\n request: IRefreshWebhookRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IRefreshWebhookResponse> {\n try {\n this.logger.info(loggedInUserId, this.refreshSubscription.name, this.fileName, 'Refresh Microsoft Graph subscription', {\n subscriptionId: request.subscriptionId,\n path: MICROSOFT_GRAPH_PATHS.subscription(request.subscriptionId),\n });\n this.assertRequired(request.subscriptionId, 'subscriptionId');\n this.assertRequired(request.expirationDateTime, 'expirationDateTime');\n\n const graphSubscription = await this.microsoftApiClient.apiCall<IMicrosoftGraphSubscription>(\n {\n apiMethod: HTTP_METHOD.PATCH,\n url: MICROSOFT_GRAPH_PATHS.subscription(request.subscriptionId),\n body: { expirationDateTime: request.expirationDateTime },\n },\n integration,\n loggedInUserId,\n );\n const subscription = this.fromGraphSubscription(graphSubscription);\n this.logger.info(loggedInUserId, this.refreshSubscription.name, this.fileName, 'Refreshed Microsoft Graph subscription', {\n subscriptionId: subscription.id,\n });\n return { subscription };\n } catch (error) {\n this.logger.error(loggedInUserId, this.refreshSubscription.name, this.fileName, 'Error refreshing Microsoft Graph subscription', error);\n throw error;\n }\n }\n\n override async deleteSubscription(request: IDeleteWebhookRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<void> {\n try {\n this.logger.info(loggedInUserId, this.deleteSubscription.name, this.fileName, 'Delete Microsoft Graph subscription', {\n subscriptionId: request.subscriptionId,\n path: MICROSOFT_GRAPH_PATHS.subscription(request.subscriptionId),\n });\n this.assertRequired(request.subscriptionId, 'subscriptionId');\n\n await this.microsoftApiClient.apiCall(\n {\n apiMethod: HTTP_METHOD.DELETE,\n url: MICROSOFT_GRAPH_PATHS.subscription(request.subscriptionId),\n },\n integration,\n loggedInUserId,\n );\n this.logger.info(loggedInUserId, this.deleteSubscription.name, this.fileName, 'Deleted Microsoft Graph subscription', {\n subscriptionId: request.subscriptionId,\n });\n } catch (error) {\n this.logger.error(loggedInUserId, this.deleteSubscription.name, this.fileName, 'Error deleting Microsoft Graph subscription', error);\n throw error;\n }\n }\n\n private toGraphSubscription(request: IRegisterWebhookRequest): IMicrosoftGraphSubscription {\n const graph: IMicrosoftGraphSubscription = {\n changeType: request.changeTypes.join(','),\n notificationUrl: request.notificationUrl,\n resource: request.resource,\n expirationDateTime: request.expirationDateTime,\n };\n if (request.clientState !== undefined) {\n graph.clientState = request.clientState;\n }\n return graph;\n }\n\n private fromGraphSubscription(graph: IMicrosoftGraphSubscription): IWebhookSubscription {\n const metadata = this.collectUnknownGraphFields(graph);\n return {\n id: graph.id,\n resource: graph.resource ?? '',\n changeTypes: (graph.changeType ?? '')\n .split(',')\n .map((changeType) => changeType.trim())\n .filter((changeType) => changeType.length > 0),\n notificationUrl: graph.notificationUrl ?? '',\n expirationDateTime: graph.expirationDateTime ?? '',\n clientState: graph.clientState,\n metadata,\n };\n }\n\n private collectUnknownGraphFields(graph: IMicrosoftGraphSubscription): Record<string, unknown> | undefined {\n const extras: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(graph as Record<string, unknown>)) {\n if (!GRAPH_SUBSCRIPTION_KNOWN_KEYS.has(key) && value !== undefined) {\n extras[key] = value;\n }\n }\n return Object.keys(extras).length > 0 ? extras : undefined;\n }\n\n private assertRequired(value: string | undefined, fieldName: string): void {\n if (!value?.trim()) {\n throw new CustomException('BAD_REQUEST', `${fieldName} is required`);\n }\n }\n}\n","import { CommonValidationDatabaseService } from '@dv4resi/dvss-backend-module-datastore';\nimport { type AddAPIResponse, type GraphQLContext, LoggerService, SECRET_PROVIDER, type SecretProvider } from '@dv4resi/dvss-backend-module-utility';\nimport {\n BaseIntegrationConfiguration,\n IntegrationConfigurationDao,\n IntegrationConfigSecureStorageService,\n type IAddCapabilityIntegrationInput,\n type ICapabilityIntegration,\n type IUpdateCapabilityIntegrationRequest,\n type IUpdateCapabilityIntegrationResponse,\n} from '@dvss/dvss-integration-libs';\nimport { Inject, Injectable, Optional } from '@nestjs/common';\n\nimport { buildMicrosoftIntegrationConfig } from '../../common/build-microsoft-integration-config';\nimport { getMicrosoftKmsKeyId, looksLikeStoredSecureConfig } from '../../common/microsoft-secure-storage';\nimport type { IMicrosoftConfig } from '../../models';\nimport { MicrosoftAuthService } from '../auth/auth.service';\n\nconst MICROSOFT_SECURE_STORAGE_OPTIONS = {\n useSecureStorage: true as const,\n get kmsKeyId(): string {\n return getMicrosoftKmsKeyId();\n },\n};\n\n@Injectable()\nexport class MicrosoftIntegrationConfigurationService extends BaseIntegrationConfiguration {\n constructor(\n integrationConfigurationDao: IntegrationConfigurationDao,\n commonValidationDatabaseService: CommonValidationDatabaseService,\n logger: LoggerService,\n private readonly microsoftAuthService: MicrosoftAuthService,\n @Optional() @Inject(IntegrationConfigSecureStorageService) secureStorage?: IntegrationConfigSecureStorageService,\n @Optional() @Inject(SECRET_PROVIDER) secretProvider?: SecretProvider,\n ) {\n super(integrationConfigurationDao, commonValidationDatabaseService, logger, secureStorage, secretProvider);\n }\n\n override async addCapabilityIntegration(input: IAddCapabilityIntegrationInput, context: GraphQLContext): Promise<AddAPIResponse> {\n const rawConfig = (input.config ?? {}) as Partial<IMicrosoftConfig>;\n const integrationConfig = rawConfig.integrationConfig;\n\n if (!integrationConfig?.tenantId || !integrationConfig.clientId || !integrationConfig.clientSecret) {\n throw new Error('Microsoft integrationConfig.tenantId, clientId, and clientSecret are required');\n }\n\n const microsoftConfig = buildMicrosoftIntegrationConfig(\n {\n tenantId: integrationConfig.tenantId,\n clientId: integrationConfig.clientId,\n clientSecret: integrationConfig.clientSecret,\n },\n rawConfig,\n );\n\n const token = await this.microsoftAuthService.getAccessToken(\n {\n config: microsoftConfig,\n capabilityId: input.capabilityId,\n providerId: input.capabilityProviderId,\n } as Omit<ICapabilityIntegration, 'id'>,\n context.loggedInUserId,\n true,\n );\n\n const result = await super.addCapabilityIntegration(\n {\n ...input,\n config: microsoftConfig as unknown as IAddCapabilityIntegrationInput['config'],\n },\n context,\n {\n useSecureStorage: MICROSOFT_SECURE_STORAGE_OPTIONS.useSecureStorage,\n kmsKeyId: MICROSOFT_SECURE_STORAGE_OPTIONS.kmsKeyId,\n },\n );\n\n await this.microsoftAuthService.persistMintedAccessToken(BigInt(result.id), token, context.loggedInUserId);\n\n return result;\n }\n\n override async updateCapabilityIntegration(\n request: IUpdateCapabilityIntegrationRequest,\n integration?: ICapabilityIntegration,\n loggedInUserId?: bigint,\n ): Promise<IUpdateCapabilityIntegrationResponse> {\n if (!request.updateData.config) {\n return super.updateCapabilityIntegration(request, integration, loggedInUserId);\n }\n\n const existingStored = (integration?.config ?? {}) as Record<string, unknown>;\n let existingConfig = existingStored as unknown as Partial<IMicrosoftConfig>;\n\n if (looksLikeStoredSecureConfig(existingStored) && this.secureStorage) {\n const keyId = MICROSOFT_SECURE_STORAGE_OPTIONS.kmsKeyId;\n existingConfig = (await this.secureStorage.prepareForBackend(existingStored, keyId, loggedInUserId)) as unknown as Partial<IMicrosoftConfig>;\n }\n\n const incomingConfig = request.updateData.config as unknown as Partial<IMicrosoftConfig>;\n\n const asString = (value: unknown): string => (typeof value === 'string' ? value : '');\n\n const mergedCredentials = {\n tenantId: asString(incomingConfig.integrationConfig?.tenantId) || asString(existingConfig.integrationConfig?.tenantId) || '',\n clientId: asString(incomingConfig.integrationConfig?.clientId) || asString(existingConfig.integrationConfig?.clientId) || '',\n clientSecret: asString(incomingConfig.integrationConfig?.clientSecret) || asString(existingConfig.integrationConfig?.clientSecret) || '',\n };\n\n const platformConfig = incomingConfig.platformConfig ?? existingConfig.platformConfig;\n const mergedConfig = buildMicrosoftIntegrationConfig(mergedCredentials, platformConfig ? { platformConfig } : undefined);\n\n await this.microsoftAuthService.getAccessToken(\n {\n id: request.id,\n config: mergedConfig,\n capabilityId: integration?.capabilityId,\n providerId: integration?.providerId,\n } as ICapabilityIntegration,\n loggedInUserId,\n true,\n );\n\n const updateRequest: IUpdateCapabilityIntegrationRequest = {\n ...request,\n updateData: {\n ...request.updateData,\n config: {\n ...request.updateData.config,\n ...mergedConfig,\n } as unknown as IUpdateCapabilityIntegrationRequest['updateData']['config'],\n },\n };\n\n const integrationForUpdate = integration\n ? ({\n ...integration,\n config: mergedConfig,\n } as ICapabilityIntegration)\n : integration;\n\n return super.updateCapabilityIntegration(updateRequest, integrationForUpdate, loggedInUserId, {\n useSecureStorage: MICROSOFT_SECURE_STORAGE_OPTIONS.useSecureStorage,\n kmsKeyId: MICROSOFT_SECURE_STORAGE_OPTIONS.kmsKeyId,\n });\n }\n}\n","import { CommonValidationDatabaseService, DatastoreModule } from '@dv4resi/dvss-backend-module-datastore';\nimport { LoggerModule } from '@dv4resi/dvss-backend-module-utility';\nimport {\n IntegrationConfigurationDao,\n IntegrationConfigSecureStorageService,\n IntegrationLibsModule,\n IntegrationSubcapabilityDao,\n} from '@dvss/dvss-integration-libs';\nimport { IntegrationOauthModule } from '@dvss/dvss-integration-oauth';\nimport { Module } from '@nestjs/common';\n\nimport { MicrosoftApiClientService } from './adapter/microsoft-api-client.service';\nimport { MicrosoftAuthService } from './capabilities/auth/auth.service';\nimport { MicrosoftCalendarBookingService } from './capabilities/booking-management/booking-management.service';\nimport { MicrosoftCalendarResourceService } from './capabilities/resource-management/resource-management.service';\nimport { MicrosoftCalendarWebhookService } from './capabilities/webhook-management/webhook-management.service';\nimport { MicrosoftIntegrationConfigurationService } from './capabilities/integration-configuration/integration-configuration.service';\nimport { MICROSOFT_SECURE_STORAGE } from './common/microsoft-secure-storage';\n\n@Module({\n imports: [IntegrationLibsModule, LoggerModule, DatastoreModule, IntegrationOauthModule],\n providers: [\n MicrosoftAuthService,\n MicrosoftApiClientService,\n MicrosoftIntegrationConfigurationService,\n MicrosoftCalendarResourceService,\n MicrosoftCalendarBookingService,\n MicrosoftCalendarWebhookService,\n IntegrationSubcapabilityDao,\n IntegrationConfigurationDao,\n CommonValidationDatabaseService,\n {\n provide: MICROSOFT_SECURE_STORAGE,\n useExisting: IntegrationConfigSecureStorageService,\n },\n ],\n exports: [\n MicrosoftAuthService,\n MicrosoftApiClientService,\n MicrosoftIntegrationConfigurationService,\n MicrosoftCalendarResourceService,\n MicrosoftCalendarBookingService,\n MicrosoftCalendarWebhookService,\n IntegrationSubcapabilityDao,\n IntegrationConfigurationDao,\n CommonValidationDatabaseService,\n IntegrationOauthModule,\n ],\n})\nexport class AppModule {}\n","import { Injectable } from '@nestjs/common';\n\n/**\n * Base helper for calendar-im provider routing.\n * Returns already-injected Nest provider instances (not ModuleRef.create).\n */\n@Injectable()\nexport abstract class AdapterFactoryService<TProvider extends string | number | symbol, TAdapter> {\n abstract readonly adapterMap: Partial<Record<TProvider, TAdapter>>;\n\n getAdapter(provider: TProvider): TAdapter {\n const adapter = this.adapterMap[provider];\n\n if (adapter === undefined) {\n throw new Error(`No calendar adapter found for provider: ${String(provider)}`);\n }\n\n return adapter;\n }\n}\n","/**\n * Calendar provider keys used by CalendarIntegrationManager adapter factories.\n * Values match CAPABILITY_PROVIDER_INTEGRATION_ENUM in datastore / utility.\n */\nexport enum CALENDAR_PROVIDER_ENUM {\n MICROSOFT_365 = 'MICROSOFT_365',\n}\n","import type { ICapabilityIntegration, IValidatedCapabilityIntegration } from '@dvss/dvss-integration-libs';\n\n/**\n * IM orchestration contract for calendar provider auth flows.\n */\nexport abstract class ICalendarAuthHandler {\n abstract validateConfig(integration: ICapabilityIntegration, loggedInUserId: bigint): IValidatedCapabilityIntegration;\n\n abstract testIntegration(integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<boolean>;\n\n abstract fetchAccessToken(integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<string>;\n}\n","import type { ICapabilityIntegration, IValidatedCapabilityIntegration } from '@dvss/dvss-integration-libs';\nimport { MicrosoftAuthService } from '@dvss/dvss-integration-microsoft';\nimport { Injectable } from '@nestjs/common';\n\nimport { ICalendarAuthHandler } from '../../handlers/calendar-auth.handler.interface';\n\n@Injectable()\nexport class MicrosoftCalendarAuthHandler extends ICalendarAuthHandler {\n constructor(private readonly microsoftAuthService: MicrosoftAuthService) {\n super();\n }\n\n override validateConfig(integration: ICapabilityIntegration, loggedInUserId: bigint): IValidatedCapabilityIntegration {\n return this.microsoftAuthService.validateConfig(integration, loggedInUserId);\n }\n\n override async testIntegration(integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<boolean> {\n return this.microsoftAuthService.testIntegration(integration, loggedInUserId);\n }\n\n override async fetchAccessToken(integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<string> {\n return this.microsoftAuthService.fetchAccessToken(integration, loggedInUserId);\n }\n}\n","import { Injectable } from '@nestjs/common';\n\nimport { AdapterFactoryService } from '../common/abstract/adapter-factory.service';\nimport { CALENDAR_PROVIDER_ENUM } from '../common/enum/calendar-provider.enum';\nimport { ICalendarAuthHandler } from '../handlers/calendar-auth.handler.interface';\nimport { MicrosoftCalendarAuthHandler } from '../providers/microsoft/microsoft-calendar-auth.handler';\n\n@Injectable()\nexport class CalendarAuthAdapterFactory extends AdapterFactoryService<CALENDAR_PROVIDER_ENUM, ICalendarAuthHandler> {\n readonly adapterMap: Partial<Record<CALENDAR_PROVIDER_ENUM, ICalendarAuthHandler>>;\n\n constructor(microsoftCalendarAuthHandler: MicrosoftCalendarAuthHandler) {\n super();\n this.adapterMap = {\n [CALENDAR_PROVIDER_ENUM.MICROSOFT_365]: microsoftCalendarAuthHandler,\n };\n }\n}\n","import type {\n IBookingEventRef,\n ICancelEventRequest,\n ICapabilityIntegration,\n ICreateEventRequest,\n IDeleteEventRequest,\n IGetEventsRequest,\n IGetEventsResponse,\n IUpdateEventRequest,\n} from '@dvss/dvss-integration-libs';\n\n/**\n * IM orchestration contract for OUTBOUND calendar booking flows (DVSS → provider).\n * Same shape for every provider. Implementations may invoke multiple vendor API calls inside\n * a single method. `getCalendarBookings` is the one read — a narrow calendarView lookup that\n * backs editing a single occurrence of a recurring series.\n */\nexport abstract class ICalendarBookingHandler {\n abstract addCalendarBooking(request: ICreateEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IBookingEventRef>;\n\n abstract updateCalendarBooking(request: IUpdateEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IBookingEventRef>;\n\n abstract cancelCalendarBooking(request: ICancelEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<void>;\n\n abstract deleteCalendarBooking(request: IDeleteEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<void>;\n\n abstract getCalendarBookings(request: IGetEventsRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IGetEventsResponse>;\n}\n","import type {\n IBookingEventRef,\n ICancelEventRequest,\n ICapabilityIntegration,\n ICreateEventRequest,\n IDeleteEventRequest,\n IGetEventsRequest,\n IGetEventsResponse,\n IUpdateEventRequest,\n} from '@dvss/dvss-integration-libs';\nimport { MicrosoftCalendarBookingService } from '@dvss/dvss-integration-microsoft';\nimport { Injectable } from '@nestjs/common';\n\nimport { ICalendarBookingHandler } from '../../handlers/calendar-booking.handler.interface';\n\n/**\n * Microsoft 365 orchestration for outbound calendar booking flows.\n * Calls microsoft-package atomic Graph ops in the order required for each flow.\n */\n@Injectable()\nexport class MicrosoftCalendarBookingHandler extends ICalendarBookingHandler {\n constructor(private readonly microsoftCalendarBookingService: MicrosoftCalendarBookingService) {\n super();\n }\n\n override async addCalendarBooking(request: ICreateEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IBookingEventRef> {\n // Orchestration seam: add further Graph calls here when a flow needs more than createEvent.\n return this.microsoftCalendarBookingService.createEvent(request, integration, loggedInUserId);\n }\n\n override async updateCalendarBooking(request: IUpdateEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IBookingEventRef> {\n return this.microsoftCalendarBookingService.updateEvent(request, integration, loggedInUserId);\n }\n\n override async cancelCalendarBooking(request: ICancelEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<void> {\n return this.microsoftCalendarBookingService.cancelEvent(request, integration, loggedInUserId);\n }\n\n override async deleteCalendarBooking(request: IDeleteEventRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<void> {\n return this.microsoftCalendarBookingService.deleteEvent(request, integration, loggedInUserId);\n }\n\n override async getCalendarBookings(request: IGetEventsRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IGetEventsResponse> {\n return this.microsoftCalendarBookingService.getEvents(request, integration, loggedInUserId);\n }\n}\n","import { Injectable } from '@nestjs/common';\n\nimport { AdapterFactoryService } from '../common/abstract/adapter-factory.service';\nimport { CALENDAR_PROVIDER_ENUM } from '../common/enum/calendar-provider.enum';\nimport { ICalendarBookingHandler } from '../handlers/calendar-booking.handler.interface';\nimport { MicrosoftCalendarBookingHandler } from '../providers/microsoft/microsoft-calendar-booking.handler';\n\n@Injectable()\nexport class CalendarBookingAdapterFactory extends AdapterFactoryService<CALENDAR_PROVIDER_ENUM, ICalendarBookingHandler> {\n readonly adapterMap: Partial<Record<CALENDAR_PROVIDER_ENUM, ICalendarBookingHandler>>;\n\n constructor(microsoftCalendarBookingHandler: MicrosoftCalendarBookingHandler) {\n super();\n this.adapterMap = {\n [CALENDAR_PROVIDER_ENUM.MICROSOFT_365]: microsoftCalendarBookingHandler,\n };\n }\n}\n","import type {\n IAddCapabilityIntegrationInput,\n ICapabilityIntegration,\n IGetCapabilityIntegrationInput,\n IGetCapabilityIntegrationResult,\n IGetCapabilityIntegrationsRequest,\n IGetCapabilityIntegrationsResponse,\n IUpdateCapabilityIntegrationRequest,\n IUpdateCapabilityIntegrationResponse,\n} from '@dvss/dvss-integration-libs';\nimport type { AddAPIResponse, GraphQLContext } from '@dv4resi/dvss-backend-module-utility';\n\n/**\n * IM orchestration contract for calendar capability-integration configuration flows.\n */\nexport abstract class ICalendarIntegrationConfigurationHandler {\n abstract addCapabilityIntegration(input: IAddCapabilityIntegrationInput, context: GraphQLContext): Promise<AddAPIResponse>;\n\n abstract updateCapabilityIntegration(\n request: IUpdateCapabilityIntegrationRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IUpdateCapabilityIntegrationResponse>;\n\n abstract getCapabilityIntegrations(request: IGetCapabilityIntegrationsRequest, loggedInUserId: bigint): Promise<IGetCapabilityIntegrationsResponse>;\n\n abstract getCapabilityIntegration(input: IGetCapabilityIntegrationInput, context: GraphQLContext): Promise<IGetCapabilityIntegrationResult>;\n}\n","import type {\n IAddCapabilityIntegrationInput,\n ICapabilityIntegration,\n IGetCapabilityIntegrationInput,\n IGetCapabilityIntegrationResult,\n IGetCapabilityIntegrationsRequest,\n IGetCapabilityIntegrationsResponse,\n IUpdateCapabilityIntegrationRequest,\n IUpdateCapabilityIntegrationResponse,\n} from '@dvss/dvss-integration-libs';\nimport { MicrosoftIntegrationConfigurationService } from '@dvss/dvss-integration-microsoft';\nimport type { AddAPIResponse, GraphQLContext } from '@dv4resi/dvss-backend-module-utility';\nimport { Injectable } from '@nestjs/common';\n\nimport { ICalendarIntegrationConfigurationHandler } from '../../handlers/calendar-integration-configuration.handler.interface';\n\n@Injectable()\nexport class MicrosoftCalendarIntegrationConfigurationHandler extends ICalendarIntegrationConfigurationHandler {\n constructor(private readonly microsoftIntegrationConfigurationService: MicrosoftIntegrationConfigurationService) {\n super();\n }\n\n override async addCapabilityIntegration(input: IAddCapabilityIntegrationInput, context: GraphQLContext): Promise<AddAPIResponse> {\n return this.microsoftIntegrationConfigurationService.addCapabilityIntegration(input, context);\n }\n\n override async updateCapabilityIntegration(\n request: IUpdateCapabilityIntegrationRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IUpdateCapabilityIntegrationResponse> {\n return this.microsoftIntegrationConfigurationService.updateCapabilityIntegration(request, integration, loggedInUserId);\n }\n\n override async getCapabilityIntegrations(request: IGetCapabilityIntegrationsRequest, loggedInUserId: bigint): Promise<IGetCapabilityIntegrationsResponse> {\n return this.microsoftIntegrationConfigurationService.getCapabilityIntegrations(request, loggedInUserId);\n }\n\n override async getCapabilityIntegration(input: IGetCapabilityIntegrationInput, context: GraphQLContext): Promise<IGetCapabilityIntegrationResult> {\n return this.microsoftIntegrationConfigurationService.getCapabilityIntegration(input, context);\n }\n}\n","import { Injectable } from '@nestjs/common';\n\nimport { AdapterFactoryService } from '../common/abstract/adapter-factory.service';\nimport { CALENDAR_PROVIDER_ENUM } from '../common/enum/calendar-provider.enum';\nimport { ICalendarIntegrationConfigurationHandler } from '../handlers/calendar-integration-configuration.handler.interface';\nimport { MicrosoftCalendarIntegrationConfigurationHandler } from '../providers/microsoft/microsoft-calendar-integration-configuration.handler';\n\n@Injectable()\nexport class CalendarIntegrationConfigurationAdapterFactory extends AdapterFactoryService<CALENDAR_PROVIDER_ENUM, ICalendarIntegrationConfigurationHandler> {\n readonly adapterMap: Partial<Record<CALENDAR_PROVIDER_ENUM, ICalendarIntegrationConfigurationHandler>>;\n\n constructor(microsoftCalendarIntegrationConfigurationHandler: MicrosoftCalendarIntegrationConfigurationHandler) {\n super();\n this.adapterMap = {\n [CALENDAR_PROVIDER_ENUM.MICROSOFT_365]: microsoftCalendarIntegrationConfigurationHandler,\n };\n }\n}\n","import type { ICapabilityIntegration, IGetResourcesRequest, IGetResourcesResponse } from '@dvss/dvss-integration-libs';\n\n/**\n * IM orchestration contract for calendar resource discovery flows.\n */\nexport abstract class ICalendarResourceHandler {\n abstract getCalendarResources(request: IGetResourcesRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<IGetResourcesResponse>;\n}\n","import type { ICapabilityIntegration, IGetResourcesRequest, IGetResourcesResponse } from '@dvss/dvss-integration-libs';\nimport { MicrosoftCalendarResourceService } from '@dvss/dvss-integration-microsoft';\nimport { Injectable } from '@nestjs/common';\n\nimport { ICalendarResourceHandler } from '../../handlers/calendar-resource.handler.interface';\n\n@Injectable()\nexport class MicrosoftCalendarResourceHandler extends ICalendarResourceHandler {\n constructor(private readonly microsoftCalendarResourceService: MicrosoftCalendarResourceService) {\n super();\n }\n\n override async getCalendarResources(\n request: IGetResourcesRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IGetResourcesResponse> {\n return this.microsoftCalendarResourceService.getResources(request, integration, loggedInUserId);\n }\n}\n","import { Injectable } from '@nestjs/common';\n\nimport { AdapterFactoryService } from '../common/abstract/adapter-factory.service';\nimport { CALENDAR_PROVIDER_ENUM } from '../common/enum/calendar-provider.enum';\nimport { ICalendarResourceHandler } from '../handlers/calendar-resource.handler.interface';\nimport { MicrosoftCalendarResourceHandler } from '../providers/microsoft/microsoft-calendar-resource.handler';\n\n@Injectable()\nexport class CalendarResourceAdapterFactory extends AdapterFactoryService<CALENDAR_PROVIDER_ENUM, ICalendarResourceHandler> {\n readonly adapterMap: Partial<Record<CALENDAR_PROVIDER_ENUM, ICalendarResourceHandler>>;\n\n constructor(microsoftCalendarResourceHandler: MicrosoftCalendarResourceHandler) {\n super();\n this.adapterMap = {\n [CALENDAR_PROVIDER_ENUM.MICROSOFT_365]: microsoftCalendarResourceHandler,\n };\n }\n}\n","import type {\n ICapabilityIntegration,\n IDeleteWebhookRequest,\n IRefreshWebhookRequest,\n IRefreshWebhookResponse,\n IRegisterWebhookRequest,\n IRegisterWebhookResponse,\n} from '@dvss/dvss-integration-libs';\n\n/**\n * IM orchestration contract for calendar webhook subscription flows.\n */\nexport abstract class ICalendarWebhookHandler {\n abstract registerCalendarWebhook(\n request: IRegisterWebhookRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IRegisterWebhookResponse>;\n\n abstract refreshCalendarWebhook(\n request: IRefreshWebhookRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IRefreshWebhookResponse>;\n\n abstract deleteCalendarWebhook(request: IDeleteWebhookRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<void>;\n}\n","import type {\n ICapabilityIntegration,\n IDeleteWebhookRequest,\n IRefreshWebhookRequest,\n IRefreshWebhookResponse,\n IRegisterWebhookRequest,\n IRegisterWebhookResponse,\n} from '@dvss/dvss-integration-libs';\nimport { MicrosoftCalendarWebhookService } from '@dvss/dvss-integration-microsoft';\nimport { Injectable } from '@nestjs/common';\n\nimport { ICalendarWebhookHandler } from '../../handlers/calendar-webhook.handler.interface';\n\n@Injectable()\nexport class MicrosoftCalendarWebhookHandler extends ICalendarWebhookHandler {\n constructor(private readonly microsoftCalendarWebhookService: MicrosoftCalendarWebhookService) {\n super();\n }\n\n override async registerCalendarWebhook(\n request: IRegisterWebhookRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IRegisterWebhookResponse> {\n return this.microsoftCalendarWebhookService.registerWebhook(request, integration, loggedInUserId);\n }\n\n override async refreshCalendarWebhook(\n request: IRefreshWebhookRequest,\n integration: ICapabilityIntegration,\n loggedInUserId: bigint,\n ): Promise<IRefreshWebhookResponse> {\n return this.microsoftCalendarWebhookService.refreshSubscription(request, integration, loggedInUserId);\n }\n\n override async deleteCalendarWebhook(request: IDeleteWebhookRequest, integration: ICapabilityIntegration, loggedInUserId: bigint): Promise<void> {\n return this.microsoftCalendarWebhookService.deleteSubscription(request, integration, loggedInUserId);\n }\n}\n","import { Injectable } from '@nestjs/common';\n\nimport { AdapterFactoryService } from '../common/abstract/adapter-factory.service';\nimport { CALENDAR_PROVIDER_ENUM } from '../common/enum/calendar-provider.enum';\nimport { ICalendarWebhookHandler } from '../handlers/calendar-webhook.handler.interface';\nimport { MicrosoftCalendarWebhookHandler } from '../providers/microsoft/microsoft-calendar-webhook.handler';\n\n@Injectable()\nexport class CalendarWebhookAdapterFactory extends AdapterFactoryService<CALENDAR_PROVIDER_ENUM, ICalendarWebhookHandler> {\n readonly adapterMap: Partial<Record<CALENDAR_PROVIDER_ENUM, ICalendarWebhookHandler>>;\n\n constructor(microsoftCalendarWebhookHandler: MicrosoftCalendarWebhookHandler) {\n super();\n this.adapterMap = {\n [CALENDAR_PROVIDER_ENUM.MICROSOFT_365]: microsoftCalendarWebhookHandler,\n };\n }\n}\n","import { Module } from '@nestjs/common';\nimport { IntegrationLibsModule } from '@dvss/dvss-integration-libs';\nimport { IntegrationMicrosoftModule } from '@dvss/dvss-integration-microsoft';\n\nimport { CalendarAuthAdapterFactory } from './adapters/calendar-auth.adapter.factory';\nimport { CalendarBookingAdapterFactory } from './adapters/calendar-booking.adapter.factory';\nimport { CalendarIntegrationConfigurationAdapterFactory } from './adapters/calendar-integration-configuration.adapter.factory';\nimport { CalendarResourceAdapterFactory } from './adapters/calendar-resource.adapter.factory';\nimport { CalendarWebhookAdapterFactory } from './adapters/calendar-webhook.adapter.factory';\nimport { MicrosoftCalendarAuthHandler } from './providers/microsoft/microsoft-calendar-auth.handler';\nimport { MicrosoftCalendarBookingHandler } from './providers/microsoft/microsoft-calendar-booking.handler';\nimport { MicrosoftCalendarIntegrationConfigurationHandler } from './providers/microsoft/microsoft-calendar-integration-configuration.handler';\nimport { MicrosoftCalendarResourceHandler } from './providers/microsoft/microsoft-calendar-resource.handler';\nimport { MicrosoftCalendarWebhookHandler } from './providers/microsoft/microsoft-calendar-webhook.handler';\n\nconst microsoftHandlers = [\n MicrosoftCalendarBookingHandler,\n MicrosoftCalendarResourceHandler,\n MicrosoftCalendarWebhookHandler,\n MicrosoftCalendarAuthHandler,\n MicrosoftCalendarIntegrationConfigurationHandler,\n];\n\nconst adapterFactories = [\n CalendarBookingAdapterFactory,\n CalendarResourceAdapterFactory,\n CalendarWebhookAdapterFactory,\n CalendarAuthAdapterFactory,\n CalendarIntegrationConfigurationAdapterFactory,\n];\n\n@Module({\n imports: [IntegrationLibsModule, IntegrationMicrosoftModule],\n providers: [...microsoftHandlers, ...adapterFactories],\n exports: [IntegrationLibsModule, IntegrationMicrosoftModule, ...microsoftHandlers, ...adapterFactories],\n})\nexport class AppModule {}\n"]}
|