diff --git a/packages/models-react/.prettierignore b/packages/models-react/.prettierignore new file mode 100644 index 00000000..eae16afd --- /dev/null +++ b/packages/models-react/.prettierignore @@ -0,0 +1,2 @@ +dist/ +CHANGELOG.md diff --git a/packages/models-react/.prettierrc.js b/packages/models-react/.prettierrc.js new file mode 100644 index 00000000..d289ee8d --- /dev/null +++ b/packages/models-react/.prettierrc.js @@ -0,0 +1,3 @@ +import config from "../../config/.prettierrc.js"; + +export default config; diff --git a/packages/models-react/README.md b/packages/models-react/README.md new file mode 100644 index 00000000..7b8bf331 --- /dev/null +++ b/packages/models-react/README.md @@ -0,0 +1,39 @@ +# @mittwald/api-models-react + +React bindings for [`@mittwald/api-models`](../models), the domain-model layer +over `@mittwald/api-client`. + +The core package is framework-agnostic and SSR-safe; everything React-specific +lives here. The dependency runs one way, react → core +([ADR-0002](../models/docs/adr/0002-agnostic-core-two-packages.md)). + +## Usage + +Every model has a matching Ghost — a Suspense-integrated, lazily resolving proxy +built with +[`@mittwald/react-ghostmaker`](https://github.com/mittwald/react-ghostmaker): + +```tsx +import { CustomerGhost, ProjectGhost } from "@mittwald/api-models-react"; + +const customer = CustomerGhost.ofId(customerId).use(); +const projects = ProjectGhost.query({ customer }).execute().use().items; +``` + +Call `.getCommon().use()` or `.getDetailed().use()` inside a component to get a +live instance. A resolved Ghost supports the underlying model's own instance +methods directly — there is nothing to unwrap. + +## Initialization + +Initialize the core package once at startup, as described in its +[README](../models/README.md#initialization). This package needs no separate +setup. + +## Peer dependencies + +`react` (`>=19.2`, as required by `@mittwald/react-ghostmaker`), +`@tanstack/react-query`, `@mittwald/api-client` and +`@mittwald/api-client-commons` are peers — the consumer provides them. The last +two are passed through from `@mittwald/api-models`, which declares them as peers +itself. diff --git a/packages/models-react/eslint.config.js b/packages/models-react/eslint.config.js new file mode 100644 index 00000000..f713aa51 --- /dev/null +++ b/packages/models-react/eslint.config.js @@ -0,0 +1,3 @@ +import baseConfig from "../../config/eslint.config.base.js"; + +export default baseConfig; diff --git a/packages/models-react/package.json b/packages/models-react/package.json new file mode 100644 index 00000000..938638e9 --- /dev/null +++ b/packages/models-react/package.json @@ -0,0 +1,69 @@ +{ + "name": "@mittwald/api-models-react", + "version": "4.493.1", + "author": "Mittwald CM Service GmbH & Co. KG ", + "type": "module", + "description": "React bindings for the mittwald API domain models", + "keywords": [ + "api", + "client", + "mittwald", + "models", + "react" + ], + "homepage": "https://developer.mittwald.de", + "repository": "github:mittwald/api-client-js", + "bugs": { + "url": "https://github.com/mittwald/api-client-js/issues" + }, + "license": "MIT", + "exports": { + ".": { + "types": "./dist/types/index.d.ts", + "import": "./dist/esm/index.js" + } + }, + "files": [ + "dist" + ], + "scripts": { + "build": "run build:clean && run tsc", + "build:clean": "rimraf dist", + "format": "run prettier --write '**/*.{ts,tsx,yaml,yml,json,md,mdx,js}'", + "lint": "run eslint .", + "test": "", + "test:compile": "run tsc --noEmit", + "test:unit": "run vitest run" + }, + "dependencies": { + "@mittwald/api-models": "workspace:^", + "@mittwald/react-async-proxy": "^0.0.12", + "@mittwald/react-ghostmaker": "^1.6.0", + "@sindresorhus/is": "^8.1.0", + "minimatch": "^10.2.5" + }, + "devDependencies": { + "@eslint/js": "^10.0.1", + "@mittwald/api-client": "workspace:^", + "@mittwald/api-client-commons": "workspace:^", + "@tanstack/react-query": "^5.102.8", + "@types/react": "^19.2.17", + "eslint": "^10.9.1", + "eslint-config-prettier": "^10.1.8", + "eslint-plugin-json": "^5.0.0", + "eslint-plugin-prettier": "^5.5.6", + "globals": "^17.11.0", + "prettier": "^3.9.6", + "react": "^19.2.7", + "rimraf": "^6.1.3", + "typescript": "^5.9.3", + "typescript-eslint": "^8.68.0", + "vitest": "^4.1.8" + }, + "peerDependencies": { + "@mittwald/api-client": "workspace:^", + "@mittwald/api-client-commons": "workspace:^", + "@tanstack/react-query": "^5", + "react": ">=19.2" + } +} diff --git a/packages/models-react/src/ReactCacheManager.ts b/packages/models-react/src/ReactCacheManager.ts new file mode 100644 index 00000000..7c1d02bb --- /dev/null +++ b/packages/models-react/src/ReactCacheManager.ts @@ -0,0 +1,91 @@ +import { getQueryContext } from "@mittwald/react-ghostmaker"; +import type { Query, QueryClient } from "@tanstack/react-query"; +import { Minimatch } from "minimatch"; + +type PathInvalidationHandler = (path: string) => void; + +export class ReactCacheManager { + public readonly queryClient: QueryClient; + + private readonly matcherCache = new Map(); + + private readonly idsOfPath = new Map>(); + private readonly pathsOfId = new Map>(); + private readonly onPathInvalidatedHandler = + new Set(); + + public constructor(queryClient: QueryClient) { + this.queryClient = queryClient; + this.subscribeToCacheEvents(); + } + + private subscribeToCacheEvents() { + this.queryClient.getQueryCache().subscribe((event) => { + if (event.type !== "updated") { + return; + } + const actionType = event.action.type; + if (actionType === "invalidate" || actionType === "fetch") { + this.handleQueryInvalidated(event.query); + } + }); + } + + private handleQueryInvalidated(query: Query) { + this.pathsOfId + .get(JSON.stringify(query.queryKey)) + ?.forEach((url) => this.callPathInvalidationHandlers(url)); + } + + private callPathInvalidationHandlers(path: string) { + this.onPathInvalidatedHandler.forEach((handler) => handler(path)); + } + + public onPathInvalidated(handler: PathInvalidationHandler) { + this.onPathInvalidatedHandler.add(handler); + return () => { + this.onPathInvalidatedHandler.delete(handler); + }; + } + + public refresh(path?: string) { + if (path) { + const minimatch = this.matcherCache.get(path) ?? new Minimatch(path); + this.matcherCache.set(path, minimatch); + + this.idsOfPath.forEach((ids, path) => { + if (minimatch.match(path)) { + ids.forEach((id) => { + if (id.includes("react-ghostmaker")) { + this.queryClient.invalidateQueries({ + queryKey: JSON.parse(id), + }); + } + }); + } + }); + } else { + this.queryClient.getQueryCache().clear(); + } + } + + public registerPath(path: string) { + const queryContext = getQueryContext(); + + const queryId = queryContext?.queryKey + ? JSON.stringify(queryContext.queryKey) + : undefined; + + if (!queryId) { + return; + } + + const thisUrlIds = this.idsOfPath.get(path) ?? new Set(); + thisUrlIds.add(queryId); + this.idsOfPath.set(path, thisUrlIds); + + const thisPathsOfId = this.pathsOfId.get(queryId) ?? new Set(); + thisPathsOfId.add(path); + this.pathsOfId.set(queryId, thisPathsOfId); + } +} diff --git a/packages/models-react/src/__snapshots__/publicApi.txt b/packages/models-react/src/__snapshots__/publicApi.txt new file mode 100644 index 00000000..4d502b44 --- /dev/null +++ b/packages/models-react/src/__snapshots__/publicApi.txt @@ -0,0 +1,157 @@ +ActivityGhost +ActivityListQueryGhost +AIModelGhost +AIModelListQueryGhost +AITokenStatisticsGhost +type AnyLeadGhost +ApiTokenGhost +ApiTokenListQueryGhost +AppGhost +AppInstallationGhost +AppInstallationListQueryGhost +AppListQueryGhost +AppVersionGhost +AppVersionListQueryGhost +ArticleGhost +ArticleListQueryGhost +AuthGhost +BackupGhost +BackupListQueryGhost +BackupScheduleGhost +BackupScheduleListQueryGhost +CertificateGhost +CertificateListQueryGhost +CertificateRequestGhost +CertificateRequestListQueryGhost +CityGhost +CityListQueryGhost +ContactVerificationGhost +ContactVerificationListQueryGhost +ContainerGhost +ContainerListQueryGhost +ContainerStackGhost +ContainerTemplateGhost +ContainerTemplateListQueryGhost +ContractArticleGhost +ContractGhost +ContractItemGhost +ContractListQueryGhost +ContributorExtensionGhost +ContributorExtensionListQueryGhost +ContributorGhost +ContributorIncomingInvoiceGhost +ContributorIncomingInvoiceListQueryGhost +ContributorListQueryGhost +ConversationGhost +ConversationListQueryGhost +ConversationMessageGhost +ConversationUserGhost +ConversationUserListQueryGhost +CronjobExecutionGhost +CronjobExecutionListQueryGhost +CronjobGhost +CronjobListQueryGhost +CustomerAIApiKeyGhost +CustomerAIPlanGhost +CustomerGhost +CustomerInviteGhost +CustomerInviteListQueryGhost +CustomerListQueryGhost +CustomerMembershipGhost +CustomerMembershipListQueryGhost +DeliveryBoxGhost +DeliveryBoxListQueryGhost +DnsZoneGhost +DnsZoneListQueryGhost +DomainGhost +DomainListQueryGhost +DomainMigrationGhost +DomainMigrationListQueryGhost +DomainOrderRequestGhost +ExtensionGhost +ExtensionInstanceContextGhost +ExtensionInstanceGhost +ExtensionInstanceListQueryGhost +ExtensionListQueryGhost +ExternalCertificateOrderRequestGhost +FeedbackGhost +FileGhost +FinderProfileGhost +FinderProfileListQueryGhost +FinderProfileRequestGhost +FinderProfileRequestListQueryGhost +HostingArticleGhost +HostingContractItemGhost +HostingOrderRequestGhost +IngressDomainListGhost +IngressDomainListItemGhost +IngressGhost +IngressListQueryGhost +InvoiceGhost +InvoiceListQueryGhost +InvoiceSettingsGhost +LeadFyndrGhost +LeadGhost +LeadListQueryGhost +LeadsExportGhost +LeadsExportListQueryGhost +LicenseGhost +LicenseListQueryGhost +LicenseOrderRequestGhost +MailAddressGhost +MailAddressListQueryGhost +MailRateLimitGhost +MailRateLimitListQueryGhost +MailSettingsGhost +MfaGhost +MySqlCharsetGhost +MySqlCharsetListQueryGhost +MySqlGhost +MySqlListQueryGhost +MySqlUserGhost +MySqlUserListQueryGhost +NewsletterGhost +NotificationsGhost +OrderGhost +OrderListQueryGhost +PerformanceGhost +PerformanceListQueryGhost +ProjectAIApiKeyGhost +ProjectAIPlanGhost +ProjectGhost +ProjectInviteGhost +ProjectInviteListQueryGhost +ProjectListQueryGhost +ProjectMembershipGhost +ProjectMembershipListQueryGhost +ProjectUsageMetricsGhost +RedisGhost +RedisListQueryGhost +RegistryGhost +RegistryListQueryGhost +ServerGhost +ServerListQueryGhost +ServerUsageMetricsGhost +SessionGhost +SessionListQueryGhost +SftpUserGhost +SftpUserListQueryGhost +SpotlightGhost +SshKeyGhost +SshKeyListQueryGhost +SshUserGhost +SshUserListQueryGhost +StorageMetricsGhost +SupportCodeGhost +SystemSoftwareGhost +SystemSoftwareListQueryGhost +SystemSoftwareVersionGhost +SystemSoftwareVersionListQueryGhost +TldGhost +TldListQueryGhost +TldPriceGhost +UnlockedLeadGhost +UnlockedLeadListQueryGhost +UserGhost +VolumeGhost +VolumeListQueryGhost \ No newline at end of file diff --git a/packages/models-react/src/index.ts b/packages/models-react/src/index.ts new file mode 100644 index 00000000..56165ca1 --- /dev/null +++ b/packages/models-react/src/index.ts @@ -0,0 +1 @@ +export * from "./models/index.js"; diff --git a/packages/models-react/src/models/AIApiKey.ts b/packages/models-react/src/models/AIApiKey.ts new file mode 100644 index 00000000..6a11d1a3 --- /dev/null +++ b/packages/models-react/src/models/AIApiKey.ts @@ -0,0 +1,17 @@ +import * as Models from "@mittwald/api-models"; +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; + +export const ProjectAIApiKeyGhost = makeGhost(Models.ProjectAIApiKey); +export type ProjectAIApiKeyGhost = MaybeReactGhost; + +export const ProjectAIPlanGhost = makeGhost(Models.ProjectAIPlan); +export type ProjectAIPlanGhost = MaybeReactGhost; + +export const CustomerAIApiKeyGhost = makeGhost(Models.CustomerAIApiKey); +export type CustomerAIApiKeyGhost = MaybeReactGhost; + +export const CustomerAIPlanGhost = makeGhost(Models.CustomerAIPlan); +export type CustomerAIPlanGhost = MaybeReactGhost; + +export const AITokenStatisticsGhost = makeGhost(Models.AITokenStatistics); +export type AITokenStatisticsGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/AIModel.ts b/packages/models-react/src/models/AIModel.ts new file mode 100644 index 00000000..66a2f047 --- /dev/null +++ b/packages/models-react/src/models/AIModel.ts @@ -0,0 +1,8 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const AIModelGhost = makeGhost(Models.AIModel); +export type AIModelGhost = MaybeReactGhost; + +export const AIModelListQueryGhost = makeGhost(Models.AIModelListQuery); +export type AIModelListQueryGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/Activity.ts b/packages/models-react/src/models/Activity.ts new file mode 100644 index 00000000..a7d3cd23 --- /dev/null +++ b/packages/models-react/src/models/Activity.ts @@ -0,0 +1,8 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const ActivityGhost = makeGhost(Models.Activity); +export type ActivityGhost = MaybeReactGhost; + +export const ActivityListQueryGhost = makeGhost(Models.ActivityListQuery); +export type ActivityListQueryGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/AnyLeadGhost.ts b/packages/models-react/src/models/AnyLeadGhost.ts new file mode 100644 index 00000000..b65b5eef --- /dev/null +++ b/packages/models-react/src/models/AnyLeadGhost.ts @@ -0,0 +1,4 @@ +import type { LeadGhost } from "./Lead.js"; +import type { UnlockedLeadGhost } from "./UnlockedLead.js"; + +export type AnyLeadGhost = LeadGhost | UnlockedLeadGhost; diff --git a/packages/models-react/src/models/ApiToken.ts b/packages/models-react/src/models/ApiToken.ts new file mode 100644 index 00000000..6ee100ee --- /dev/null +++ b/packages/models-react/src/models/ApiToken.ts @@ -0,0 +1,8 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const ApiTokenGhost = makeGhost(Models.ApiToken); +export type ApiTokenGhost = MaybeReactGhost; + +export const ApiTokenListQueryGhost = makeGhost(Models.ApiTokenListQuery); +export type ApiTokenListQueryGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/App.ts b/packages/models-react/src/models/App.ts new file mode 100644 index 00000000..8f859028 --- /dev/null +++ b/packages/models-react/src/models/App.ts @@ -0,0 +1,8 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const AppGhost = makeGhost(Models.App); +export type AppGhost = MaybeReactGhost; + +export const AppListQueryGhost = makeGhost(Models.AppListQuery); +export type AppListQueryGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/AppInstallation.ts b/packages/models-react/src/models/AppInstallation.ts new file mode 100644 index 00000000..04d20fc9 --- /dev/null +++ b/packages/models-react/src/models/AppInstallation.ts @@ -0,0 +1,11 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const AppInstallationGhost = makeGhost(Models.AppInstallation); +export type AppInstallationGhost = MaybeReactGhost; + +export const AppInstallationListQueryGhost = makeGhost( + Models.AppInstallationListQuery, +); +export type AppInstallationListQueryGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/AppVersion.ts b/packages/models-react/src/models/AppVersion.ts new file mode 100644 index 00000000..d421be90 --- /dev/null +++ b/packages/models-react/src/models/AppVersion.ts @@ -0,0 +1,9 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const AppVersionGhost = makeGhost(Models.AppVersion); +export type AppVersionGhost = MaybeReactGhost; + +export const AppVersionListQueryGhost = makeGhost(Models.AppVersionListQuery); +export type AppVersionListQueryGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/Article.ts b/packages/models-react/src/models/Article.ts new file mode 100644 index 00000000..ec98872c --- /dev/null +++ b/packages/models-react/src/models/Article.ts @@ -0,0 +1,8 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const ArticleGhost = makeGhost(Models.Article); +export type ArticleGhost = MaybeReactGhost; + +export const ArticleListQueryGhost = makeGhost(Models.ArticleListQuery); +export type ArticleListQueryGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/Auth.ts b/packages/models-react/src/models/Auth.ts new file mode 100644 index 00000000..920ed15d --- /dev/null +++ b/packages/models-react/src/models/Auth.ts @@ -0,0 +1,5 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const AuthGhost = makeGhost(Models.Auth); +export type AuthGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/Backup.ts b/packages/models-react/src/models/Backup.ts new file mode 100644 index 00000000..a31cb8c1 --- /dev/null +++ b/packages/models-react/src/models/Backup.ts @@ -0,0 +1,8 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const BackupGhost = makeGhost(Models.Backup); +export type BackupGhost = MaybeReactGhost; + +export const BackupListQueryGhost = makeGhost(Models.BackupListQuery); +export type BackupListQueryGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/BackupSchedule.ts b/packages/models-react/src/models/BackupSchedule.ts new file mode 100644 index 00000000..dfbf9e4b --- /dev/null +++ b/packages/models-react/src/models/BackupSchedule.ts @@ -0,0 +1,11 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const BackupScheduleGhost = makeGhost(Models.BackupSchedule); +export type BackupScheduleGhost = MaybeReactGhost; + +export const BackupScheduleListQueryGhost = makeGhost( + Models.BackupScheduleListQuery, +); +export type BackupScheduleListQueryGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/Certificate.ts b/packages/models-react/src/models/Certificate.ts new file mode 100644 index 00000000..4db11f9d --- /dev/null +++ b/packages/models-react/src/models/Certificate.ts @@ -0,0 +1,9 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const CertificateGhost = makeGhost(Models.Certificate); +export type CertificateGhost = MaybeReactGhost; + +export const CertificateListQueryGhost = makeGhost(Models.CertificateListQuery); +export type CertificateListQueryGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/CertificateRequest.ts b/packages/models-react/src/models/CertificateRequest.ts new file mode 100644 index 00000000..3849d8d5 --- /dev/null +++ b/packages/models-react/src/models/CertificateRequest.ts @@ -0,0 +1,12 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const CertificateRequestGhost = makeGhost(Models.CertificateRequest); +export type CertificateRequestGhost = + MaybeReactGhost; + +export const CertificateRequestListQueryGhost = makeGhost( + Models.CertificateRequestListQuery, +); +export type CertificateRequestListQueryGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/City.tsx b/packages/models-react/src/models/City.tsx new file mode 100644 index 00000000..49f72e59 --- /dev/null +++ b/packages/models-react/src/models/City.tsx @@ -0,0 +1,8 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const CityGhost = makeGhost(Models.City); +export type CityGhost = MaybeReactGhost; + +export const CityListQueryGhost = makeGhost(Models.CityListQuery); +export type CityListQueryGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/ContactVerification.ts b/packages/models-react/src/models/ContactVerification.ts new file mode 100644 index 00000000..0d599023 --- /dev/null +++ b/packages/models-react/src/models/ContactVerification.ts @@ -0,0 +1,12 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const ContactVerificationGhost = makeGhost(Models.ContactVerification); +export type ContactVerificationGhost = + MaybeReactGhost; + +export const ContactVerificationListQueryGhost = makeGhost( + Models.ContactVerificationListQuery, +); +export type ContactVerificationListQueryGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/Container.tsx b/packages/models-react/src/models/Container.tsx new file mode 100644 index 00000000..5570f4f7 --- /dev/null +++ b/packages/models-react/src/models/Container.tsx @@ -0,0 +1,12 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const ContainerGhost = makeGhost(Models.Container); +export type ContainerGhost = MaybeReactGhost; + +export const ContainerListQueryGhost = makeGhost(Models.ContainerListQuery); +export type ContainerListQueryGhost = + MaybeReactGhost; + +export const ContainerStackGhost = makeGhost(Models.ContainerStack); +export type ContainerStackGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/ContainerLog.tsx b/packages/models-react/src/models/ContainerLog.tsx new file mode 100644 index 00000000..efd0c64f --- /dev/null +++ b/packages/models-react/src/models/ContainerLog.tsx @@ -0,0 +1,5 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const ContainerLogGhost = makeGhost(Models.ContainerLog); +export type ContainerLogGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/ContainerTemplate.tsx b/packages/models-react/src/models/ContainerTemplate.tsx new file mode 100644 index 00000000..816ad7f0 --- /dev/null +++ b/packages/models-react/src/models/ContainerTemplate.tsx @@ -0,0 +1,11 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const ContainerTemplateGhost = makeGhost(Models.ContainerTemplate); +export type ContainerTemplateGhost = MaybeReactGhost; + +export const ContainerTemplateListQueryGhost = makeGhost( + Models.ContainerTemplateListQuery, +); +export type ContainerTemplateListQueryGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/Contract.ts b/packages/models-react/src/models/Contract.ts new file mode 100644 index 00000000..9a5399ae --- /dev/null +++ b/packages/models-react/src/models/Contract.ts @@ -0,0 +1,8 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const ContractGhost = makeGhost(Models.Contract); +export type ContractGhost = MaybeReactGhost; + +export const ContractListQueryGhost = makeGhost(Models.ContractListQuery); +export type ContractListQueryGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/ContractArticle.ts b/packages/models-react/src/models/ContractArticle.ts new file mode 100644 index 00000000..ea1cc7e7 --- /dev/null +++ b/packages/models-react/src/models/ContractArticle.ts @@ -0,0 +1,5 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const ContractArticleGhost = makeGhost(Models.ContractArticle); +export type ContractArticleGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/ContractItem.ts b/packages/models-react/src/models/ContractItem.ts new file mode 100644 index 00000000..1542aff7 --- /dev/null +++ b/packages/models-react/src/models/ContractItem.ts @@ -0,0 +1,5 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const ContractItemGhost = makeGhost(Models.ContractItem); +export type ContractItemGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/Contributor.ts b/packages/models-react/src/models/Contributor.ts new file mode 100644 index 00000000..4fa459b8 --- /dev/null +++ b/packages/models-react/src/models/Contributor.ts @@ -0,0 +1,9 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const ContributorGhost = makeGhost(Models.Contributor); +export type ContributorGhost = MaybeReactGhost; + +export const ContributorListQueryGhost = makeGhost(Models.ContributorListQuery); +export type ContributorListQueryGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/ContributorExtension.ts b/packages/models-react/src/models/ContributorExtension.ts new file mode 100644 index 00000000..9f2a233f --- /dev/null +++ b/packages/models-react/src/models/ContributorExtension.ts @@ -0,0 +1,12 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const ContributorExtensionGhost = makeGhost(Models.ContributorExtension); +export type ContributorExtensionGhost = + MaybeReactGhost; + +export const ContributorExtensionListQueryGhost = makeGhost( + Models.ContributorExtensionListQuery, +); +export type ContributorExtensionListQueryGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/ContributorIncomingInvoice.ts b/packages/models-react/src/models/ContributorIncomingInvoice.ts new file mode 100644 index 00000000..9bb03680 --- /dev/null +++ b/packages/models-react/src/models/ContributorIncomingInvoice.ts @@ -0,0 +1,14 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const ContributorIncomingInvoiceGhost = makeGhost( + Models.ContributorIncomingInvoice, +); +export type ContributorIncomingInvoiceGhost = + MaybeReactGhost; + +export const ContributorIncomingInvoiceListQueryGhost = makeGhost( + Models.ContributorIncomingInvoiceListQuery, +); +export type ContributorIncomingInvoiceListQueryGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/Conversation.tsx b/packages/models-react/src/models/Conversation.tsx new file mode 100644 index 00000000..71475900 --- /dev/null +++ b/packages/models-react/src/models/Conversation.tsx @@ -0,0 +1,11 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const ConversationGhost = makeGhost(Models.Conversation); +export type ConversationGhost = MaybeReactGhost; + +export const ConversationListQueryGhost = makeGhost( + Models.ConversationListQuery, +); +export type ConversationListQueryGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/ConversationMessage.tsx b/packages/models-react/src/models/ConversationMessage.tsx new file mode 100644 index 00000000..ab5be929 --- /dev/null +++ b/packages/models-react/src/models/ConversationMessage.tsx @@ -0,0 +1,6 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const ConversationMessageGhost = makeGhost(Models.ConversationMessage); +export type ConversationMessageGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/ConversationUser.tsx b/packages/models-react/src/models/ConversationUser.tsx new file mode 100644 index 00000000..4cd4b2ac --- /dev/null +++ b/packages/models-react/src/models/ConversationUser.tsx @@ -0,0 +1,11 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const ConversationUserGhost = makeGhost(Models.ConversationUser); +export type ConversationUserGhost = MaybeReactGhost; + +export const ConversationUserListQueryGhost = makeGhost( + Models.ConversationUserListQuery, +); +export type ConversationUserListQueryGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/Cronjob.tsx b/packages/models-react/src/models/Cronjob.tsx new file mode 100644 index 00000000..4e37db1f --- /dev/null +++ b/packages/models-react/src/models/Cronjob.tsx @@ -0,0 +1,8 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const CronjobGhost = makeGhost(Models.Cronjob); +export type CronjobGhost = MaybeReactGhost; + +export const CronjobListQueryGhost = makeGhost(Models.CronjobListQuery); +export type CronjobListQueryGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/CronjobExecution.ts b/packages/models-react/src/models/CronjobExecution.ts new file mode 100644 index 00000000..1e92759d --- /dev/null +++ b/packages/models-react/src/models/CronjobExecution.ts @@ -0,0 +1,11 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const CronjobExecutionGhost = makeGhost(Models.CronjobExecution); +export type CronjobExecutionGhost = MaybeReactGhost; + +export const CronjobExecutionListQueryGhost = makeGhost( + Models.CronjobExecutionListQuery, +); +export type CronjobExecutionListQueryGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/Customer.ts b/packages/models-react/src/models/Customer.ts new file mode 100644 index 00000000..d9e3405e --- /dev/null +++ b/packages/models-react/src/models/Customer.ts @@ -0,0 +1,8 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const CustomerGhost = makeGhost(Models.Customer); +export type CustomerGhost = MaybeReactGhost; + +export const CustomerListQueryGhost = makeGhost(Models.CustomerListQuery); +export type CustomerListQueryGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/Customer.tsx b/packages/models-react/src/models/Customer.tsx new file mode 100644 index 00000000..b5337ac3 --- /dev/null +++ b/packages/models-react/src/models/Customer.tsx @@ -0,0 +1,11 @@ +import { + makeGhost, + type MaybeReactAsyncProxy, +} from "@mittwald/react-async-proxy"; + +export const CustomerProxy = makeGhost(Models.Customer); +export type CustomerProxy = MaybeReactAsyncProxy; + +export const CustomerListQueryProxy = makeGhost(Models.CustomerListQuery); +export type CustomerListQueryProxy = + MaybeReactAsyncProxy; diff --git a/packages/models-react/src/models/CustomerInvite.ts b/packages/models-react/src/models/CustomerInvite.ts new file mode 100644 index 00000000..a3125fba --- /dev/null +++ b/packages/models-react/src/models/CustomerInvite.ts @@ -0,0 +1,11 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const CustomerInviteGhost = makeGhost(Models.CustomerInvite); +export type CustomerInviteGhost = MaybeReactGhost; + +export const CustomerInviteListQueryGhost = makeGhost( + Models.CustomerInviteListQuery, +); +export type CustomerInviteListQueryGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/CustomerMembership.ts b/packages/models-react/src/models/CustomerMembership.ts new file mode 100644 index 00000000..711a23b5 --- /dev/null +++ b/packages/models-react/src/models/CustomerMembership.ts @@ -0,0 +1,12 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const CustomerMembershipGhost = makeGhost(Models.CustomerMembership); +export type CustomerMembershipGhost = + MaybeReactGhost; + +export const CustomerMembershipListQueryGhost = makeGhost( + Models.CustomerMembershipListQuery, +); +export type CustomerMembershipListQueryGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/DeliveryBox.ts b/packages/models-react/src/models/DeliveryBox.ts new file mode 100644 index 00000000..bfb69e21 --- /dev/null +++ b/packages/models-react/src/models/DeliveryBox.ts @@ -0,0 +1,9 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const DeliveryBoxGhost = makeGhost(Models.DeliveryBox); +export type DeliveryBoxGhost = MaybeReactGhost; + +export const DeliveryBoxListQueryGhost = makeGhost(Models.DeliveryBoxListQuery); +export type DeliveryBoxListQueryGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/DnsZone.ts b/packages/models-react/src/models/DnsZone.ts new file mode 100644 index 00000000..5b9a82f3 --- /dev/null +++ b/packages/models-react/src/models/DnsZone.ts @@ -0,0 +1,8 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const DnsZoneGhost = makeGhost(Models.DnsZone); +export type DnsZoneGhost = MaybeReactGhost; + +export const DnsZoneListQueryGhost = makeGhost(Models.DnsZoneListQuery); +export type DnsZoneListQueryGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/Domain.ts b/packages/models-react/src/models/Domain.ts new file mode 100644 index 00000000..2a49651b --- /dev/null +++ b/packages/models-react/src/models/Domain.ts @@ -0,0 +1,8 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const DomainGhost = makeGhost(Models.Domain); +export type DomainGhost = MaybeReactGhost; + +export const DomainListQueryGhost = makeGhost(Models.DomainListQuery); +export type DomainListQueryGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/DomainMigration.ts b/packages/models-react/src/models/DomainMigration.ts new file mode 100644 index 00000000..c3948cac --- /dev/null +++ b/packages/models-react/src/models/DomainMigration.ts @@ -0,0 +1,11 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const DomainMigrationGhost = makeGhost(Models.DomainMigration); +export type DomainMigrationGhost = MaybeReactGhost; + +export const DomainMigrationListQueryGhost = makeGhost( + Models.DomainMigrationListQuery, +); +export type DomainMigrationListQueryGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/DomainOrderRequest.ts b/packages/models-react/src/models/DomainOrderRequest.ts new file mode 100644 index 00000000..6d026d61 --- /dev/null +++ b/packages/models-react/src/models/DomainOrderRequest.ts @@ -0,0 +1,6 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const DomainOrderRequestGhost = makeGhost(Models.DomainOrderRequest); +export type DomainOrderRequestGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/Extension.ts b/packages/models-react/src/models/Extension.ts new file mode 100644 index 00000000..cf380158 --- /dev/null +++ b/packages/models-react/src/models/Extension.ts @@ -0,0 +1,9 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const ExtensionGhost = makeGhost(Models.Extension); +export type ExtensionGhost = MaybeReactGhost; + +export const ExtensionListQueryGhost = makeGhost(Models.ExtensionListQuery); +export type ExtensionListQueryGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/ExtensionInstance.ts b/packages/models-react/src/models/ExtensionInstance.ts new file mode 100644 index 00000000..18d5da6c --- /dev/null +++ b/packages/models-react/src/models/ExtensionInstance.ts @@ -0,0 +1,11 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const ExtensionInstanceGhost = makeGhost(Models.ExtensionInstance); +export type ExtensionInstanceGhost = MaybeReactGhost; + +export const ExtensionInstanceListQueryGhost = makeGhost( + Models.ExtensionInstanceListQuery, +); +export type ExtensionInstanceListQueryGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/ExtensionInstanceContext.ts b/packages/models-react/src/models/ExtensionInstanceContext.ts new file mode 100644 index 00000000..70020bc9 --- /dev/null +++ b/packages/models-react/src/models/ExtensionInstanceContext.ts @@ -0,0 +1,8 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const ExtensionInstanceContextGhost = makeGhost( + Models.ExtensionInstanceContext, +); +export type ExtensionInstanceContextGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/ExternalCertificateOrderRequest.ts b/packages/models-react/src/models/ExternalCertificateOrderRequest.ts new file mode 100644 index 00000000..7791b6dc --- /dev/null +++ b/packages/models-react/src/models/ExternalCertificateOrderRequest.ts @@ -0,0 +1,8 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const ExternalCertificateOrderRequestGhost = makeGhost( + Models.ExternalCertificateOrderRequest, +); +export type ExternalCertificateOrderRequestGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/Feedback.ts b/packages/models-react/src/models/Feedback.ts new file mode 100644 index 00000000..df42d674 --- /dev/null +++ b/packages/models-react/src/models/Feedback.ts @@ -0,0 +1,5 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const FeedbackGhost = makeGhost(Models.Feedback); +export type FeedbackGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/File.ts b/packages/models-react/src/models/File.ts new file mode 100644 index 00000000..9b85695c --- /dev/null +++ b/packages/models-react/src/models/File.ts @@ -0,0 +1,5 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const FileGhost = makeGhost(Models.File); +export type FileGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/FinderProfile.ts b/packages/models-react/src/models/FinderProfile.ts new file mode 100644 index 00000000..91d0b285 --- /dev/null +++ b/packages/models-react/src/models/FinderProfile.ts @@ -0,0 +1,11 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const FinderProfileGhost = makeGhost(Models.FinderProfile); +export type FinderProfileGhost = MaybeReactGhost; + +export const FinderProfileListQueryGhost = makeGhost( + Models.FinderProfileListQuery, +); +export type FinderProfileListQueryGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/FinderProfileRequest.ts b/packages/models-react/src/models/FinderProfileRequest.ts new file mode 100644 index 00000000..b1b06dcd --- /dev/null +++ b/packages/models-react/src/models/FinderProfileRequest.ts @@ -0,0 +1,12 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const FinderProfileRequestGhost = makeGhost(Models.FinderProfileRequest); +export type FinderProfileRequestGhost = + MaybeReactGhost; + +export const FinderProfileRequestListQueryGhost = makeGhost( + Models.FinderProfileRequestListQuery, +); +export type FinderProfileRequestListQueryGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/HostingArticle.ts b/packages/models-react/src/models/HostingArticle.ts new file mode 100644 index 00000000..c0a726b5 --- /dev/null +++ b/packages/models-react/src/models/HostingArticle.ts @@ -0,0 +1,5 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const HostingArticleGhost = makeGhost(Models.HostingArticle); +export type HostingArticleGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/HostingContractItem.ts b/packages/models-react/src/models/HostingContractItem.ts new file mode 100644 index 00000000..c3c677a9 --- /dev/null +++ b/packages/models-react/src/models/HostingContractItem.ts @@ -0,0 +1,6 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const HostingContractItemGhost = makeGhost(Models.HostingContractItem); +export type HostingContractItemGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/HostingOrderRequest.ts b/packages/models-react/src/models/HostingOrderRequest.ts new file mode 100644 index 00000000..9b804fd3 --- /dev/null +++ b/packages/models-react/src/models/HostingOrderRequest.ts @@ -0,0 +1,6 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const HostingOrderRequestGhost = makeGhost(Models.HostingOrderRequest); +export type HostingOrderRequestGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/Ingress.ts b/packages/models-react/src/models/Ingress.ts new file mode 100644 index 00000000..1d01a576 --- /dev/null +++ b/packages/models-react/src/models/Ingress.ts @@ -0,0 +1,8 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const IngressGhost = makeGhost(Models.Ingress); +export type IngressGhost = MaybeReactGhost; + +export const IngressListQueryGhost = makeGhost(Models.IngressListQuery); +export type IngressListQueryGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/IngressDomainList.ts b/packages/models-react/src/models/IngressDomainList.ts new file mode 100644 index 00000000..26413b5a --- /dev/null +++ b/packages/models-react/src/models/IngressDomainList.ts @@ -0,0 +1,5 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const IngressDomainListGhost = makeGhost(Models.IngressDomainList); +export type IngressDomainListGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/IngressDomainListItem.ts b/packages/models-react/src/models/IngressDomainListItem.ts new file mode 100644 index 00000000..baa2cdb0 --- /dev/null +++ b/packages/models-react/src/models/IngressDomainListItem.ts @@ -0,0 +1,8 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const IngressDomainListItemGhost = makeGhost( + Models.IngressDomainListItem, +); +export type IngressDomainListItemGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/Invoice.ts b/packages/models-react/src/models/Invoice.ts new file mode 100644 index 00000000..75185af6 --- /dev/null +++ b/packages/models-react/src/models/Invoice.ts @@ -0,0 +1,8 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const InvoiceGhost = makeGhost(Models.Invoice); +export type InvoiceGhost = MaybeReactGhost; + +export const InvoiceListQueryGhost = makeGhost(Models.InvoiceListQuery); +export type InvoiceListQueryGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/InvoiceSettings.ts b/packages/models-react/src/models/InvoiceSettings.ts new file mode 100644 index 00000000..8205b5f6 --- /dev/null +++ b/packages/models-react/src/models/InvoiceSettings.ts @@ -0,0 +1,5 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const InvoiceSettingsGhost = makeGhost(Models.InvoiceSettings); +export type InvoiceSettingsGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/Lead.ts b/packages/models-react/src/models/Lead.ts new file mode 100644 index 00000000..aa8c47bf --- /dev/null +++ b/packages/models-react/src/models/Lead.ts @@ -0,0 +1,8 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const LeadGhost = makeGhost(Models.Lead); +export type LeadGhost = MaybeReactGhost; + +export const LeadListQueryGhost = makeGhost(Models.LeadListQuery); +export type LeadListQueryGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/LeadFyndr.ts b/packages/models-react/src/models/LeadFyndr.ts new file mode 100644 index 00000000..2dd3440d --- /dev/null +++ b/packages/models-react/src/models/LeadFyndr.ts @@ -0,0 +1,5 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const LeadFyndrGhost = makeGhost(Models.LeadFyndr); +export type LeadFyndrGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/LeadsExport.ts b/packages/models-react/src/models/LeadsExport.ts new file mode 100644 index 00000000..4ede07da --- /dev/null +++ b/packages/models-react/src/models/LeadsExport.ts @@ -0,0 +1,9 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const LeadsExportGhost = makeGhost(Models.LeadsExport); +export type LeadsExportGhost = MaybeReactGhost; + +export const LeadsExportListQueryGhost = makeGhost(Models.LeadsExportListQuery); +export type LeadsExportListQueryGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/License.ts b/packages/models-react/src/models/License.ts new file mode 100644 index 00000000..db69c985 --- /dev/null +++ b/packages/models-react/src/models/License.ts @@ -0,0 +1,8 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const LicenseGhost = makeGhost(Models.License); +export type LicenseGhost = MaybeReactGhost; + +export const LicenseListQueryGhost = makeGhost(Models.LicenseListQuery); +export type LicenseListQueryGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/LicenseOrderRequest.ts b/packages/models-react/src/models/LicenseOrderRequest.ts new file mode 100644 index 00000000..81f5b1dd --- /dev/null +++ b/packages/models-react/src/models/LicenseOrderRequest.ts @@ -0,0 +1,6 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const LicenseOrderRequestGhost = makeGhost(Models.LicenseOrderRequest); +export type LicenseOrderRequestGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/MailAddress.ts b/packages/models-react/src/models/MailAddress.ts new file mode 100644 index 00000000..27fe48df --- /dev/null +++ b/packages/models-react/src/models/MailAddress.ts @@ -0,0 +1,9 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const MailAddressGhost = makeGhost(Models.MailAddress); +export type MailAddressGhost = MaybeReactGhost; + +export const MailAddressListQueryGhost = makeGhost(Models.MailAddressListQuery); +export type MailAddressListQueryGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/MailRateLimit.ts b/packages/models-react/src/models/MailRateLimit.ts new file mode 100644 index 00000000..493c6532 --- /dev/null +++ b/packages/models-react/src/models/MailRateLimit.ts @@ -0,0 +1,11 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const MailRateLimitGhost = makeGhost(Models.MailRateLimit); +export type MailRateLimitGhost = MaybeReactGhost; + +export const MailRateLimitListQueryGhost = makeGhost( + Models.MailRateLimitListQuery, +); +export type MailRateLimitListQueryGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/MailSettings.ts b/packages/models-react/src/models/MailSettings.ts new file mode 100644 index 00000000..d112d008 --- /dev/null +++ b/packages/models-react/src/models/MailSettings.ts @@ -0,0 +1,5 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const MailSettingsGhost = makeGhost(Models.MailSettings); +export type MailSettingsGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/Metrics.ts b/packages/models-react/src/models/Metrics.ts new file mode 100644 index 00000000..79dbb264 --- /dev/null +++ b/packages/models-react/src/models/Metrics.ts @@ -0,0 +1,13 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const StorageMetricsGhost = makeGhost(Models.StorageMetrics); +export type StorageMetricsGhost = MaybeReactGhost; + +export const ProjectUsageMetricsGhost = makeGhost(Models.ProjectUsageMetrics); +export type ProjectUsageMetricsGhost = + MaybeReactGhost; + +export const ServerUsageMetricsGhost = makeGhost(Models.ServerUsageMetrics); +export type ServerUsageMetricsGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/Mfa.ts b/packages/models-react/src/models/Mfa.ts new file mode 100644 index 00000000..84778047 --- /dev/null +++ b/packages/models-react/src/models/Mfa.ts @@ -0,0 +1,5 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const MfaGhost = makeGhost(Models.Mfa); +export type MfaGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/MySql.ts b/packages/models-react/src/models/MySql.ts new file mode 100644 index 00000000..0cb0af29 --- /dev/null +++ b/packages/models-react/src/models/MySql.ts @@ -0,0 +1,8 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const MySqlGhost = makeGhost(Models.MySql); +export type MySqlGhost = MaybeReactGhost; + +export const MySqlListQueryGhost = makeGhost(Models.MySqlListQuery); +export type MySqlListQueryGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/MySqlCharset.ts b/packages/models-react/src/models/MySqlCharset.ts new file mode 100644 index 00000000..07a1fb42 --- /dev/null +++ b/packages/models-react/src/models/MySqlCharset.ts @@ -0,0 +1,11 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const MySqlCharsetGhost = makeGhost(Models.MySqlCharset); +export type MySqlCharsetGhost = MaybeReactGhost; + +export const MySqlCharsetListQueryGhost = makeGhost( + Models.MySqlCharsetListQuery, +); +export type MySqlCharsetListQueryGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/MySqlUser.ts b/packages/models-react/src/models/MySqlUser.ts new file mode 100644 index 00000000..53ec2fc7 --- /dev/null +++ b/packages/models-react/src/models/MySqlUser.ts @@ -0,0 +1,9 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const MySqlUserGhost = makeGhost(Models.MySqlUser); +export type MySqlUserGhost = MaybeReactGhost; + +export const MySqlUserListQueryGhost = makeGhost(Models.MySqlUserListQuery); +export type MySqlUserListQueryGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/Newsletter.ts b/packages/models-react/src/models/Newsletter.ts new file mode 100644 index 00000000..d50eb416 --- /dev/null +++ b/packages/models-react/src/models/Newsletter.ts @@ -0,0 +1,5 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const NewsletterGhost = makeGhost(Models.Newsletter); +export type NewsletterGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/Notifications.ts b/packages/models-react/src/models/Notifications.ts new file mode 100644 index 00000000..b8298ebb --- /dev/null +++ b/packages/models-react/src/models/Notifications.ts @@ -0,0 +1,5 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const NotificationsGhost = makeGhost(Models.Notifications); +export type NotificationsGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/Order.ts b/packages/models-react/src/models/Order.ts new file mode 100644 index 00000000..5588e8e3 --- /dev/null +++ b/packages/models-react/src/models/Order.ts @@ -0,0 +1,8 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const OrderGhost = makeGhost(Models.Order); +export type OrderGhost = MaybeReactGhost; + +export const OrderListQueryGhost = makeGhost(Models.OrderListQuery); +export type OrderListQueryGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/Performance.ts b/packages/models-react/src/models/Performance.ts new file mode 100644 index 00000000..df9110d9 --- /dev/null +++ b/packages/models-react/src/models/Performance.ts @@ -0,0 +1,9 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const PerformanceGhost = makeGhost(Models.Performance); +export type PerformanceGhost = MaybeReactGhost; + +export const PerformanceListQueryGhost = makeGhost(Models.PerformanceListQuery); +export type PerformanceListQueryGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/Project.ts b/packages/models-react/src/models/Project.ts new file mode 100644 index 00000000..59b37dde --- /dev/null +++ b/packages/models-react/src/models/Project.ts @@ -0,0 +1,8 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const ProjectGhost = makeGhost(Models.Project); +export type ProjectGhost = MaybeReactGhost; + +export const ProjectListQueryGhost = makeGhost(Models.ProjectListQuery); +export type ProjectListQueryGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/ProjectInvite.ts b/packages/models-react/src/models/ProjectInvite.ts new file mode 100644 index 00000000..2c2cd009 --- /dev/null +++ b/packages/models-react/src/models/ProjectInvite.ts @@ -0,0 +1,11 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const ProjectInviteGhost = makeGhost(Models.ProjectInvite); +export type ProjectInviteGhost = MaybeReactGhost; + +export const ProjectInviteListQueryGhost = makeGhost( + Models.ProjectInviteListQuery, +); +export type ProjectInviteListQueryGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/ProjectMembership.ts b/packages/models-react/src/models/ProjectMembership.ts new file mode 100644 index 00000000..15c2bd3a --- /dev/null +++ b/packages/models-react/src/models/ProjectMembership.ts @@ -0,0 +1,11 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const ProjectMembershipGhost = makeGhost(Models.ProjectMembership); +export type ProjectMembershipGhost = MaybeReactGhost; + +export const ProjectMembershipListQueryGhost = makeGhost( + Models.ProjectMembershipListQuery, +); +export type ProjectMembershipListQueryGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/Redis.ts b/packages/models-react/src/models/Redis.ts new file mode 100644 index 00000000..71f38bd8 --- /dev/null +++ b/packages/models-react/src/models/Redis.ts @@ -0,0 +1,8 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const RedisGhost = makeGhost(Models.Redis); +export type RedisGhost = MaybeReactGhost; + +export const RedisListQueryGhost = makeGhost(Models.RedisListQuery); +export type RedisListQueryGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/Registry.tsx b/packages/models-react/src/models/Registry.tsx new file mode 100644 index 00000000..9a617034 --- /dev/null +++ b/packages/models-react/src/models/Registry.tsx @@ -0,0 +1,8 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const RegistryGhost = makeGhost(Models.Registry); +export type RegistryGhost = MaybeReactGhost; + +export const RegistryListQueryGhost = makeGhost(Models.RegistryListQuery); +export type RegistryListQueryGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/Server.ts b/packages/models-react/src/models/Server.ts new file mode 100644 index 00000000..ae3c1b30 --- /dev/null +++ b/packages/models-react/src/models/Server.ts @@ -0,0 +1,8 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const ServerGhost = makeGhost(Models.Server); +export type ServerGhost = MaybeReactGhost; + +export const ServerListQueryGhost = makeGhost(Models.ServerListQuery); +export type ServerListQueryGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/Session.ts b/packages/models-react/src/models/Session.ts new file mode 100644 index 00000000..893ea397 --- /dev/null +++ b/packages/models-react/src/models/Session.ts @@ -0,0 +1,8 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const SessionGhost = makeGhost(Models.Session); +export type SessionGhost = MaybeReactGhost; + +export const SessionListQueryGhost = makeGhost(Models.SessionListQuery); +export type SessionListQueryGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/SftpUser.ts b/packages/models-react/src/models/SftpUser.ts new file mode 100644 index 00000000..b2ebcfd3 --- /dev/null +++ b/packages/models-react/src/models/SftpUser.ts @@ -0,0 +1,8 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const SftpUserGhost = makeGhost(Models.SftpUser); +export type SftpUserGhost = MaybeReactGhost; + +export const SftpUserListQueryGhost = makeGhost(Models.SftpUserListQuery); +export type SftpUserListQueryGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/Spotlight.ts b/packages/models-react/src/models/Spotlight.ts new file mode 100644 index 00000000..dcffd8f9 --- /dev/null +++ b/packages/models-react/src/models/Spotlight.ts @@ -0,0 +1,5 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const SpotlightGhost = makeGhost(Models.Spotlight); +export type SpotlightGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/SshKey.ts b/packages/models-react/src/models/SshKey.ts new file mode 100644 index 00000000..b27c0d16 --- /dev/null +++ b/packages/models-react/src/models/SshKey.ts @@ -0,0 +1,8 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const SshKeyGhost = makeGhost(Models.SshKey); +export type SshKeyGhost = MaybeReactGhost; + +export const SshKeyListQueryGhost = makeGhost(Models.SshKeyListQuery); +export type SshKeyListQueryGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/SshUser.ts b/packages/models-react/src/models/SshUser.ts new file mode 100644 index 00000000..8949eae9 --- /dev/null +++ b/packages/models-react/src/models/SshUser.ts @@ -0,0 +1,8 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const SshUserGhost = makeGhost(Models.SshUser); +export type SshUserGhost = MaybeReactGhost; + +export const SshUserListQueryGhost = makeGhost(Models.SshUserListQuery); +export type SshUserListQueryGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/SupportCode.ts b/packages/models-react/src/models/SupportCode.ts new file mode 100644 index 00000000..10130b33 --- /dev/null +++ b/packages/models-react/src/models/SupportCode.ts @@ -0,0 +1,5 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const SupportCodeGhost = makeGhost(Models.SupportCode); +export type SupportCodeGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/SystemSoftware.ts b/packages/models-react/src/models/SystemSoftware.ts new file mode 100644 index 00000000..2f7c70bc --- /dev/null +++ b/packages/models-react/src/models/SystemSoftware.ts @@ -0,0 +1,11 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const SystemSoftwareGhost = makeGhost(Models.SystemSoftware); +export type SystemSoftwareGhost = MaybeReactGhost; + +export const SystemSoftwareListQueryGhost = makeGhost( + Models.SystemSoftwareListQuery, +); +export type SystemSoftwareListQueryGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/SystemSoftwareVersion.ts b/packages/models-react/src/models/SystemSoftwareVersion.ts new file mode 100644 index 00000000..42957d86 --- /dev/null +++ b/packages/models-react/src/models/SystemSoftwareVersion.ts @@ -0,0 +1,14 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const SystemSoftwareVersionGhost = makeGhost( + Models.SystemSoftwareVersion, +); +export type SystemSoftwareVersionGhost = + MaybeReactGhost; + +export const SystemSoftwareVersionListQueryGhost = makeGhost( + Models.SystemSoftwareVersionListQuery, +); +export type SystemSoftwareVersionListQueryGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/Tld.ts b/packages/models-react/src/models/Tld.ts new file mode 100644 index 00000000..58515b69 --- /dev/null +++ b/packages/models-react/src/models/Tld.ts @@ -0,0 +1,11 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const TldGhost = makeGhost(Models.Tld); +export type TldGhost = MaybeReactGhost; + +export const TldPriceGhost = makeGhost(Models.TldPrice); +export type TldPriceGhost = MaybeReactGhost; + +export const TldListQueryGhost = makeGhost(Models.TldListQuery); +export type TldListQueryGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/UnlockedLead.ts b/packages/models-react/src/models/UnlockedLead.ts new file mode 100644 index 00000000..bbb07495 --- /dev/null +++ b/packages/models-react/src/models/UnlockedLead.ts @@ -0,0 +1,11 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const UnlockedLeadGhost = makeGhost(Models.UnlockedLead); +export type UnlockedLeadGhost = MaybeReactGhost; + +export const UnlockedLeadListQueryGhost = makeGhost( + Models.UnlockedLeadListQuery, +); +export type UnlockedLeadListQueryGhost = + MaybeReactGhost; diff --git a/packages/models-react/src/models/User.ts b/packages/models-react/src/models/User.ts new file mode 100644 index 00000000..00257f0c --- /dev/null +++ b/packages/models-react/src/models/User.ts @@ -0,0 +1,5 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const UserGhost = makeGhost(Models.User); +export type UserGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/Volume.tsx b/packages/models-react/src/models/Volume.tsx new file mode 100644 index 00000000..58a2068c --- /dev/null +++ b/packages/models-react/src/models/Volume.tsx @@ -0,0 +1,8 @@ +import { makeGhost, type MaybeReactGhost } from "@mittwald/react-ghostmaker"; +import * as Models from "@mittwald/api-models"; + +export const VolumeGhost = makeGhost(Models.Volume); +export type VolumeGhost = MaybeReactGhost; + +export const VolumeListQueryGhost = makeGhost(Models.VolumeListQuery); +export type VolumeListQueryGhost = MaybeReactGhost; diff --git a/packages/models-react/src/models/index.ts b/packages/models-react/src/models/index.ts new file mode 100644 index 00000000..ceb4fbdb --- /dev/null +++ b/packages/models-react/src/models/index.ts @@ -0,0 +1,90 @@ +import "./init.js"; + +export * from "./Activity.js"; +export * from "./AIApiKey.js"; +export * from "./AIModel.js"; +export * from "./AnyLeadGhost.js"; +export * from "./ApiToken.js"; +export * from "./App.js"; +export * from "./AppInstallation.js"; +export * from "./AppVersion.js"; +export * from "./Article.js"; +export * from "./Auth.js"; +export * from "./Backup.js"; +export * from "./BackupSchedule.js"; +export * from "./Certificate.js"; +export * from "./CertificateRequest.js"; +export * from "./City.js"; +export * from "./Container.js"; +export * from "./ContainerTemplate.js"; +export * from "./Contract.js"; +export * from "./ContractArticle.js"; +export * from "./ContractItem.js"; +export * from "./Contributor.js"; +export * from "./ContributorExtension.js"; +export * from "./ContributorIncomingInvoice.js"; +export * from "./Conversation.js"; +export * from "./ConversationMessage.js"; +export * from "./ConversationUser.js"; +export * from "./Cronjob.js"; +export * from "./CronjobExecution.js"; +export * from "./Customer.js"; +export * from "./CustomerInvite.js"; +export * from "./CustomerMembership.js"; +export * from "./DeliveryBox.js"; +export * from "./DnsZone.js"; +export * from "./Domain.js"; +export * from "./DomainOrderRequest.js"; +export * from "./Extension.js"; +export * from "./ExtensionInstance.js"; +export * from "./ExtensionInstanceContext.js"; +export * from "./ExternalCertificateOrderRequest.js"; +export * from "./Feedback.js"; +export * from "./File.js"; +export * from "./FinderProfile.js"; +export * from "./FinderProfileRequest.js"; +export * from "./HostingArticle.js"; +export * from "./HostingContractItem.js"; +export * from "./HostingOrderRequest.js"; +export * from "./Ingress.js"; +export * from "./IngressDomainList.js"; +export * from "./Invoice.js"; +export * from "./InvoiceSettings.js"; +export * from "./Lead.js"; +export * from "./LeadFyndr.js"; +export * from "./LeadsExport.js"; +export * from "./License.js"; +export * from "./LicenseOrderRequest.js"; +export * from "./MailAddress.js"; +export * from "./MailSettings.js"; +export * from "./Metrics.js"; +export * from "./Mfa.js"; +export * from "./MySql.js"; +export * from "./MySqlCharset.js"; +export * from "./MySqlUser.js"; +export * from "./Newsletter.js"; +export * from "./Notifications.js"; +export * from "./Order.js"; +export * from "./Performance.js"; +export * from "./Project.js"; +export * from "./ProjectInvite.js"; +export * from "./ProjectMembership.js"; +export * from "./Redis.js"; +export * from "./Registry.js"; +export * from "./Server.js"; +export * from "./Session.js"; +export * from "./SftpUser.js"; +export * from "./Spotlight.js"; +export * from "./SshKey.js"; +export * from "./SshUser.js"; +export * from "./SupportCode.js"; +export * from "./SystemSoftware.js"; +export * from "./SystemSoftwareVersion.js"; +export * from "./Tld.js"; +export * from "./UnlockedLead.js"; +export * from "./User.js"; +export * from "./Volume.js"; +export * from "./ContactVerification.js"; +export * from "./IngressDomainListItem.js"; +export * from "./DomainMigration.js"; +export * from "./MailRateLimit.js"; diff --git a/packages/models-react/src/models/init.ts b/packages/models-react/src/models/init.ts new file mode 100644 index 00000000..450be05f --- /dev/null +++ b/packages/models-react/src/models/init.ts @@ -0,0 +1,40 @@ +import { ghostMakerModel } from "@mittwald/react-ghostmaker"; +import is from "@sindresorhus/is"; +import { ListQueryModel, Money, ReferenceModel } from "@mittwald/api-models"; + +function isMoney(something: unknown): something is Money { + return ( + is.object(something) && + "getAmount" in something && + "getCurrency" in something && + is.function(something.getAmount) && + is.function(something.getCurrency) + ); +} + +ghostMakerModel((something) => { + if (!is.object(something)) { + return undefined; + } + + if (something instanceof ReferenceModel) { + return { + name: something.constructor.name, + getId: () => something.id, + }; + } + + if (something instanceof ListQueryModel) { + return { + name: something.constructor.name, + getId: () => something.queryId, + }; + } + + if (isMoney(something)) { + return { + name: "Money", + getId: () => `${something.getAmount()}${something.getCurrency()}`, + }; + } +}); diff --git a/packages/models-react/src/publicApi.test.ts b/packages/models-react/src/publicApi.test.ts new file mode 100644 index 00000000..10d5cdf8 --- /dev/null +++ b/packages/models-react/src/publicApi.test.ts @@ -0,0 +1,74 @@ +import { readFileSync } from "node:fs"; +import { dirname } from "node:path"; +import { fileURLToPath } from "node:url"; +import ts from "typescript"; +import { expect, it } from "vitest"; +import * as api from "./index.js"; + +/** + * Pins the public surface of the package — same contract and same mechanics as + * `@mittwald/api-models`' own `publicApi.test.ts`; see the comment there. + * + * This package's barrel is one `export *` per ghost, so a forgotten line means + * a model has no React binding a consumer can reach — `package.json#exports` + * only opens `"."`, so there is no deep-import fallback. + * + * Not covered: the shape behind each name. + */ + +const entryPath = fileURLToPath(new URL("./index.ts", import.meta.url)); + +const readCompilerOptions = (): ts.CompilerOptions => { + const configPath = ts.findConfigFile(dirname(entryPath), ts.sys.fileExists); + if (!configPath) throw new Error("tsconfig.json not found"); + const { config } = ts.readConfigFile(configPath, (p) => + readFileSync(p, "utf8"), + ); + const parsed = ts.parseJsonConfigFileContent( + config, + ts.sys, + dirname(configPath), + ); + return { ...parsed.options, noEmit: true }; +}; + +const readDeclaredExports = (): { values: string[]; types: string[] } => { + const program = ts.createProgram([entryPath], readCompilerOptions()); + const checker = program.getTypeChecker(); + const entry = program.getSourceFile(entryPath); + if (!entry) throw new Error(`${entryPath} is not part of the program`); + const entrySymbol = checker.getSymbolAtLocation(entry); + if (!entrySymbol) throw new Error(`${entryPath} has no module symbol`); + + const values: string[] = []; + const types: string[] = []; + for (const exported of checker.getExportsOfModule(entrySymbol)) { + const target = + exported.flags & ts.SymbolFlags.Alias + ? checker.getAliasedSymbol(exported) + : exported; + const bucket = target.flags & ts.SymbolFlags.Value ? values : types; + bucket.push(exported.getName()); + } + return { values: values.sort(), types: types.sort() }; +}; + +const declaredExports = readDeclaredExports(); + +it("exports exactly the declared values at runtime", () => { + expect(Object.keys(api).sort()).toEqual(declaredExports.values); +}); + +it("exports exactly the documented surface", async () => { + const { values, types } = declaredExports; + const surface = [ + ...values.map((name) => ({ name, line: name })), + ...types.map((name) => ({ name, line: `type ${name}` })), + ] + .sort((a, b) => a.name.localeCompare(b.name, "en")) + .map((entry) => entry.line); + + await expect(surface.join("\n")).toMatchFileSnapshot( + "./__snapshots__/publicApi.txt", + ); +}); diff --git a/packages/models-react/tsconfig.json b/packages/models-react/tsconfig.json new file mode 100644 index 00000000..594ab4c3 --- /dev/null +++ b/packages/models-react/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "declarationDir": "./dist/types", + "outDir": "./dist/esm", + "rootDir": "./src", + "jsx": "react-jsx", + "experimentalDecorators": true, + "emitDecoratorMetadata": true + }, + "exclude": ["**/*.test.ts", "**/*.test.tsx"], + "extends": "../../tsconfig.json", + "include": ["src/**/*.ts", "src/**/*.tsx"] +} diff --git a/packages/models-react/vitest.config.ts b/packages/models-react/vitest.config.ts new file mode 100644 index 00000000..3909966a --- /dev/null +++ b/packages/models-react/vitest.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + globals: true, + include: ["src/**/*.test.ts", "src/**/*.test.tsx"], + }, +}); diff --git a/packages/models/.prettierignore b/packages/models/.prettierignore index 849ddff3..eae16afd 100644 --- a/packages/models/.prettierignore +++ b/packages/models/.prettierignore @@ -1 +1,2 @@ dist/ +CHANGELOG.md diff --git a/packages/models/CHANGELOG.md b/packages/models/CHANGELOG.md index 3ee222e0..69f980e7 100644 --- a/packages/models/CHANGELOG.md +++ b/packages/models/CHANGELOG.md @@ -3,6 +3,10 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +> **Heads-up:** The release listed directly above this note replaces this +> package with a complete rewrite; see +> [Migration from 4.x](README.md#migration-from-4x). + # [4.503.0](https://github.com/mittwald/api-client-js/compare/4.502.0...4.503.0) (2026-10-18) **Note:** Version bump only for package @mittwald/api-models diff --git a/packages/models/CONTEXT.md b/packages/models/CONTEXT.md new file mode 100644 index 00000000..d5f092bf --- /dev/null +++ b/packages/models/CONTEXT.md @@ -0,0 +1,120 @@ +# @mittwald/api-models — Context + +The framework-agnostic domain-model layer over `@mittwald/api-client`. It wraps +the mittwald domain (servers, projects, domains, contracts …) in models with +behavior and is complemented by `@mittwald/api-models-react` for React bindings. + +The terms under **Domain** are derived from the code and should be treated as a +first, sharpenable draft. + +## Language + +### Model vocabulary + +**ReferenceModel**: A model that represents an entity by its `id` alone — +without loaded data. The base for "only the ID is known". _Avoid_: Stub, +Pointer, Ref + +**DataModel**: A model that carries the loaded raw data (`data`) of an entity. +_Avoid_: Entity, DTO, Record + +**ListDataModel**: Carries a (frozen) list of items together with a +`totalCount`. _Avoid_: Collection, Page + +**ListQueryModel**: A not-yet-executed query with a stable `queryId` (a hash of +the query). `.execute()` materializes it. _Avoid_: Filter, Search, Criteria + +**Common / Detailed / ListItem**: Variants of an entity `X`. `XCommon` = the +fields shared by the detail and list responses; `XDetailed` = the individually +loaded full view; `XListItem` = one element of a list response. _Avoid_: Full, +Summary, Partial + +**ListQuery / List**: `XListQuery` = the executable query (`.refine()`, +`.execute()`); `XList` = the materialized result (query + items + `totalCount`). + +**Behaviors**: The injectable implementation of a model's API access (an +interface plus an `api.ts`). Models never call `api-client` directly — only +through their behaviors. _Avoid_: Service, Repository, Gateway, Client + +**Aggregate**: A model's assignment to its cache/invalidation unit +(`AggregateMetaData`, `AggregateReference`), e.g. `project`. _Avoid_: Group, +Bucket + +### Domain + +**Customer**: An organization that owns servers and projects and is billed. +_Avoid_: Client, Account, Tenant + +> **Ubiquitous-language debt:** the product's ubiquitous language calls this +> concept **Organisation**, not "Customer". The `Customer*` naming here mirrors +> the `@mittwald/api-client` (backend) term and is kept as the public API. Treat +> `Customer` in this package as the technical alias of the domain term +> _Organisation_; a rename is deliberately deferred (public-API cost). + +**Project**: A working environment on a server that bundles apps, domains, +databases, etc. _Avoid_: Workspace, Site + +> **Aggregate composition:** `Project` (and `Customer`) is the composition hub +> of an aggregate hierarchy (`Customer` → `Project`/`Server` → backups, mail, +> databases, containers, domains, …). Parent↔child and peer contexts reference +> each other **by identity** (`X.ofId(id)` → `ReferenceModel`) or **by query** +> (`X.query(...)` → `ListQueryModel`), never by embedding loaded `data`. This +> produces module-level import cycles that carry no domain coupling and are +> **accepted**; the reference/`queryId` conventions and the import-cycle trap +> are in [docs/implementation-patterns.md](docs/implementation-patterns.md). + +**Server**: A managed hosting server (machine type, storage) owned by a +Customer. _Avoid_: Host, Machine, VM, Instance + +**Contract**: The billing contract / tariff behind a server or service. _Avoid_: +Subscription, Plan + +**App / AppInstallation**: An installable application and its concrete +installation within a Project. _Avoid_: Software, Package + +**Domain**: An internet domain. The surrounding concern is split into four +sibling contexts — `domain` (registration, handles, migration), `dns` +(`DnsZone`, records), `certificate` (TLS, ACME), and `ingress` (routing). +`dns`/`domain` stay directed; `certificate` and `ingress` reference each other +(an accepted lazy module cycle — see the import-cycle trap in +[docs/implementation-patterns.md](docs/implementation-patterns.md)). _Avoid_: +Hostname, URL + +**Ingress**: Routing of a hostname to a target within a Project. + +> **Ubiquitous-language debt:** in the product's ubiquitous language `Ingress` +> is **deprecated in favor of `Domain`**. The model is still present and used; +> new work should prefer the `domain` context where possible. Not yet marked +> `@deprecated` in code (would flag every current call site). _Avoid_: Route, +> VHost + +**Extension / Contributor**: A marketplace extension and the contributor that +provides it. _Avoid_: Plugin, Addon, Vendor + +**Fyndr / Lead**: The "Fyndr" lead-generation product. A `Lead` is a prospect; +an `UnlockedLead` is a lead that has been unlocked. _Avoid_: Finder (do not +confuse with the generic word), Prospect + +**Monitoring / Performance** (observability): Two distinct observability +subdomains — do not merge. `monitoring` = resource **usage/consumption** +(`UsageMetrics` CPU/memory time-series, `StorageMetrics`); its Prometheus-style +query primitive lives internally at `monitoring/lib/metrics` (not a public +context). `performance` = **web-performance** analysis (Lighthouse/TTFB, +screenshots). `status` (service status) is not part of this package; it belongs +to the consumer. _Avoid_: "metrics" as a standalone context; lumping +web-performance with usage. + +**Access / Credentials**: Credential-like models live with their **owning +aggregate**, by design, not in a single "credentials" context: `user/SshKey` + +`user/ApiToken` (personal, on the User), `access/SftpUser` + `access/SshUser` +(project access), `database/MySqlUser` (within a database). _Avoid_: a +cross-aggregate `credentials`/`access` bucket. + +**AI Hosting (scoped)**: The AI-hosting product, modelled per **scope** — +`Customer*` (billing/contract scope) and `Project*` (container/licence scope) +variants of `AIModel`, `AIApiKey`, `AIPlanOptions`. The scope split mirrors the +api-client's own `customer*`/`project*` endpoints and the app's scoped route +trees; it is deliberate, not duplication to abstract away. The identical +`*AIModel` family is deduped behind one factory; the diverging families stay +scope-specific. _Avoid_: forcing a single generic scope abstraction over the +diverging families. diff --git a/packages/models/README.md b/packages/models/README.md index 4c38ff8e..cbe9b53a 100644 --- a/packages/models/README.md +++ b/packages/models/README.md @@ -1,441 +1,97 @@ -# mittwald API models +# @mittwald/api-models -This package contains a collection of domain models for coherent interaction -with the mittwald API. +Framework-agnostic domain-model layer over `@mittwald/api-client`. Wraps the +mittwald domain in models with behavior; React bindings live in the sibling +package `@mittwald/api-models-react`. -## License +## Overview -Copyright (c) 2023 Mittwald CM Service GmbH & Co. KG and contributors +Two layers: -This project (and all NPM packages) therein is licensed under the MIT License; -see the [LICENSE](../../LICENSE) file for details. +- **`@mittwald/api-models`** — the agnostic core. +- **`@mittwald/api-models-react`** — thin React bindings (Ghosts). The + dependency runs **one-way**, react → core. -## Installing +### Building blocks -You can install this package from the regular NPM registry: +- **Base classes** (`base/`): `BaseModel` → `ReferenceModel` (identity via + `id`), plus `DataModel` / `ListDataModel` / `ListQueryModel`. Concrete + models get their data through the capability mixins `WithData()` / + `WithListData()`, so identity stays a single-inheritance chain and + native `instanceof` holds across it + ([ADR-0004](docs/adr/0004-mixin-functions-instead-of-polytype.md)). +- **Naming convention** per entity `X`: `X` (reference) · `XCommon` · + `XDetailed` · `XListItem` · `XListQuery` · `XList`. Data types in `types.ts` + come from `MittwaldAPIV2.*`. +- **Behaviors**: per model an interface (`behaviors/types.ts`) plus an API + implementation (`behaviors/api.ts`). Models never call `api-client` directly, + only through their behaviors. +- **Registry**: all behaviors hang off a central `config.behaviors`, populated + by `initApiModels` (see below). +- **Taxonomy**: ~35 domain-oriented top-level groups. The public contract is the + root barrel, not the folder structure + ([ADR-0003](docs/adr/0003-public-api-root-barrel.md)). -```shell -yarn add @mittwald/api-models -``` - -## Setup - -You will need to initialize an API client in order to operate with the models -provided by this package. Use the `api` global instance for initialization with -some methods. - -```typescript -import { api } from "@mittwald/api-models"; - -api.setupWithApiToken(process.env.MW_API_TOKEN); -``` - -## Examples - -- A **`Reference`** or `ReferenceModel` represents a certain model just by its - ID. -- A **`DetailedModel`** contains all the data of the resource. - -For a more detailed description refer to the section -[Type of models](#Type-of-models) - -```typescript -// Get a detailed project -const detailedProject = await Project.get("p-vka9t3"); - -// Create a project reference -const projectRef = Project.ofId("p-vka9t3"); - -// Get the detailed project from the reference -const anotherDetailedProject = await projectRef.getDetailed(); - -// Update project description -await detailedProject.updateDescription("My new description!"); - -// This method just needs the ID and a description and -// thus is also available on the reference -await projectRef.updateDescription("My new description!"); - -// Accessing the projects server reference -const server = project.server; - -// List all projects of this server -const serversProjects = await server.projects.execute(); - -// List all projects -const allProjects = await Project.query().execute(); - -// Iterate over project List Models -for (const project of serversProjects) { - await project.leave(); -} -``` - -## Usage in React - -This package also provides methods aligned to be used in React components. It -uses -[@mittwald/react-use-promise](https://www.npmjs.com/package/@mittwald/react-use-promise) -to encapsulate all asynchronous functions into AsyncResources. More details -about how to use AsyncResources see the package documentation. - -### Installation - -To use the React client you have to install the additional -`@mittwald/react-use-promise` package: - -```shell -yarn add @mittwald/react-use-promise -``` - -All asynchronous methods provide a `use`-method property. This method uses -[@mittwald/react-use-promise](https://www.npmjs.com/package/@mittwald/react-use-promise) -under the hood to "resolve" the promise in the "React way". - -```typescript -const detailedProject = Project.get.use("p-vka9t3"); - -// Create a project reference -const projectRef = Project.ofId("p-vka9t3"); - -// Get the detailed project from the reference -const anotherDetailedProject = projectRef.getDetailed.use(); - -// Accessing the projects server reference -const server = project.server; - -// List all projects of this server -const serversProjects = server.projects.execute.use(); - -// List all projects -const allProjects = Project.query().execute.use(); -``` - -## Immutability and state updates - -Most of all models provided by this package represent an associated counter-part -in the backend. When a model is loaded from the backend, the current state is -incorporated into the model instance. To keep it simple and predictable this -**state is immutable and does not change under any circumstances**. As a result -you must create a new instance to get an updated model and propagate it -throughout the runtime code. - -This also applies for operations initiated at client-side. For example when the -`updateDescription` method is called on a project, the project instance will -still have the old description. - -"Watching for changes" is not scope of this package and will be implemented in -future releases or other packages™️. - -## Contribute - -**As a general advice when contributing, be sure to look at the existing source -code and use it as a template!** - -Please consider the following conventions when adding or modifying models. - -### File structure - -Structure the models in meaningful directories. - -### Use the base classes - -Models should extend (or inherit) the correct base class. You can find the base -classes in `src/base`. The following classes are available. - -#### `DataModel` - -The DataModel is the foundation of all model classes that contain a set of -immutable generic data. - -#### `ReferenceModel` - -A ReferenceModel represents a certain model just by its ID. As the most basic -model operations often just need the ID and some input data (deleting, renaming, -...), Reference Models can avoid unnecessary API round trips. - -### Stick to the ubiquitous language - -When adding models or methods pay close attention to the (maybe existing) -language used in the respective domain. Talk to the responsible team if you are -uncertain. - -### Models as abstraction layer - -Models should cover the following aspects: - -- Coherent representation of the business logic -- Simple loading of models and their linked entities -- Methods to interact with the model in an intuitive way -- Preprocessing of the models raw data to increase DX -- Consistent API - -### Type of models - -#### Detailed vs. List Models - -The response type for some models often differs when loading single items or -lists. To reduce the amount of data, the list response type is usually a subset -of the comprehensive model. Add separate classes for the Detailed Model (name it -`[Model]Detailed`) and the List Model (name it `[Model]ListItem`). - -If both model share a common code base, you should add a Common Model (name it -`[Model]Common`). - -#### Reference Models - -A Reference Model represents a certain model just by its ID. As the most basic -model operations often just need the ID and some input data (deleting, renaming, -...), Reference Models can avoid unnecessary API round trips. These classes -should be used as a return type for newly created models or for linked models. - -To get the actual Detailed Model, Reference Models _must_ have a -`function getDetailed(): Promise` and -`function findDetailed(): Promise` method. - -Consider extending the Reference Model when implementing the Entry-Point Model. - -#### Query Models - -Querying models usually requires a query object – or short query. The query -mostly includes pagination settings like `limit`, `skip` or `page`. It may also -include filters like `fromDate` or `toDate`, and filters to other models like -`customerId`. - -A Query Model represents a specific query to a specific model and should include -the following methods: - -- `execute()`: executes the query and returns the respective List Model -- `refine(overrideQuery)`: creates a new Query Model with a refined query object -- `getTotalCount()`: gets the total count of the query (executes the query with - `limit: 0`) +Term definitions: see [CONTEXT.md](CONTEXT.md). -When a model supports queries, it should provide a static `query()` method to -create the respective Query Model. +## Initialization -When a model is used as a query parameters in a Query Model, the model should -have a property in its Reference Model for this Query Model. See the following -example: - -```typescript -class Server { - public readonly projects: ProjectsListQuery; - - public constructor(id: string) { - this.projects = new ProjectListQuery({ - server: this, - }); - } -} -``` - -#### List Models - -List Models are the result of a Query Model execution. A List Model includes - -- a list of the respective List Models, limited by the pagination configuration -- the available total count (useful to implement pagination or count data) - -List Models should extend their respective Query Model, because it might be -helpful to also call `refine()` on an already executed query. - -#### Implementation details - -When implementing shared functionality, like in the Common Models, you can use -the [`polytype`](https://www.npmjs.com/package/polytype) library to realize -dynamic multiple inheritance. Be sure to look at the existing source code for -implementation examples. - -#### Entry-Point Model - -Provide a single model (name it `[Model]`) as an entry point for all different -model types (detailed, query, ...). As a convention provide a default export for -this model. - -### Use the correct verbs - -#### `find` - -Entry-Point models should have a static `find` method. The find method returns -the detailed model or may return `undefined` if the model can not be found. - -#### `get` - -In addition to the `find` method Entry-Point models should have a static `get` -method. The get method should return the desired object or throw an -`ObjectNotFoundError`. You can use the `find` method and assert the existence -with the `assertObjectFound` function. - -#### `query` - -When a list of objects should be queried use a `query` method. It may support a -`query` parameter to filter the result by given criteria. - -#### `create` - -When a model should be created use a static `create` method. This method should -return a reference of the created resource. - -### Accessing "linked" models - -Most of the models are part of a larger model tree. Models should provide -properties to get the parent and child models, like `project.server`, -`server.projects` or `server.customer`. - -#### Use Reference Models resp. Entry-Point Models when possible! - -If a linked model provides a Reference Model or Entry-point Model, create it in -the model constructor, to avoid unnecessary API round trips. - -### Abstraction of model behaviors - -Models are usually backed by a set of behaviors, defining the basic model -interactions. In order to actually "use" the model, it must be initialized with -a concrete behavior implementation. This layer of abstraction removes -implementation specific code from the model, and also makes behaviors -exchangeable without any impact on the model itself - for example inside unit -tests. - -Consider using behaviors for: - -- API interactions -- Storing and loading local data -- Complex computations or logic (maybe supported by an external library) - -#### Encapsulate API interaction inside behaviors - -Encapsulate any API interaction inside the model behaviors to prevent strong -coupling of model and API-specific implementation. - -##### Don't 🥴 - -```typescript -class ProjectDetailed { - public static async find( - id: string, - ): Promise { - const response = await client.project.getProject({ - id, - }); - - if (response.status === 200) { - return new Project(response.data.id, response.data); - } - assertStatus(response, 403); - } -} -``` - -##### Do 😃 - -```typescript -class ProjectDetailed { - public static async find(id: string): Promise { - const data = await config.project.behaviors.find(id); - if (data !== undefined) { - return new Project(data.id, data); - } - } -} -``` - -#### How-to implement behaviors - -Place a `behaviors` folder inside the model that should look like this: - -``` -Project/ -├─ behaviors/ -│ ├─ index.ts -│ ├─ types.ts (behavior interface) -│ ├─ api.ts (behavior implementation) -│ ├─ inmem.ts (behavior implementation) - -``` - -##### Define `types.ts` first - -It is a good starting point to first implement the interface for the behavior. -The interface usually just defines methods used in the behavior. Like - -```ts -export interface ProjectBehaviors { - find: (id: string) => Promise; - updateDescription: (projectId: string, description: string) => Promise; -} -``` - -Then register the behavior in the global behavior configuration -`packages/models/src/config/config.ts`. - -##### Use the behaviors in the model - -If the behavior interface is defined, you can start implementing the model. You -can also first implement the concrete API behavior, to "proof" the behavior is -"working" with the real API. - -```ts -import { config } from "../../config/config.js"; - -class ProjectDetailed { - public static async find(id: string): Promise { - const data = await config.project.behaviors.find(id); - if (data !== undefined) { - return new Project(data.id, data); - } - } -} -``` - -##### Implement the API behavior - -The API behavior depends on an API client. You can implement the behavior as an -object factory, or a simple class implementing the interface. When using the -object factory, you do not have to redeclare the method parameter types. - -Do the implementation specific stuff, thus preparing and executing the request, -and finally processing the response. +The consumer passes its dependencies in once at startup: ```ts -import { ProjectBehaviors } from "./types.js"; -import { assertStatus, MittwaldAPIV2Client } from "@mittwald/api-client"; - -export const apiProjectBehaviors = ( - client: MittwaldAPIV2Client, -): ProjectBehaviors => ({ - find: async (id) => { - const response = await client.project.getProject({ - projectId: id, - }); +import { initApiModels } from "@mittwald/api-models"; - if (response.status === 200) { - return response.data; - } - assertStatus(response, 403); - }, +initApiModels({ + apiClient /*, defaultPaginationLimit?, usageMetricsUrl?, … */, }); ``` -### Prepare for React - -All asynchronous methods should provide a `use`-method property. This method -uses -[@mittwald/react-use-promise](https://www.npmjs.com/package/@mittwald/react-use-promise) -under the hood to "resolve" the promise in the "React way". - -To provide this feature to your _async_ model methods, wrap the actual method -with the `provideReact` enhancer. - -```ts -class ProjectDetailed { - public static find = provideReact( - async (id: string): Promise => { - const data = await config.behaviors.project.find(id); - - if (data !== undefined) { - return new ProjectDetailed(data); - } - }, - ); -} -``` +Details and rationale: [ADR-0001](docs/adr/0001-initialization.md). + +## Migration from 4.x + +This package was reimplemented from the ground up. Code written against the +earlier generation will not compile against it — treat the move as a rewrite, +not an upgrade. + +What changed: + +- **React bindings moved out.** The `./react` subpath is gone. Ghosts now live + in the sibling package `@mittwald/api-models-react`, which depends on this one + ([ADR-0002](docs/adr/0002-agnostic-core-two-packages.md)). +- **Initialization is mandatory.** Models no longer wire themselves up through a + side-effect import; the consumer calls `initApiModels({ apiClient, … })` once + at startup. Accessing a behavior before that fails with a clear error instead + of `undefined` at runtime ([ADR-0001](docs/adr/0001-initialization.md)). +- **`polytype` is gone.** Models are composed from plain mixin functions + ([ADR-0004](docs/adr/0004-mixin-functions-instead-of-polytype.md)). +- **The root entry point is the contract.** `package.json#exports` exposes only + `"."`; deep imports into package internals no longer resolve. The behaviors, + the `config` object and the internal `base` helpers are not part of the public + surface ([ADR-0003](docs/adr/0003-public-api-root-barrel.md)). +- **Model methods return data instead of touching the DOM.** Downloads hand back + a `Blob`/`ArrayBuffer` plus a filename; performing the download is the + consumer's job. + +The version number does not reflect this break: the package is released in +lockstep with `@mittwald/api-client`, so the rewrite ships as an ordinary minor. + +## Conventions & invariants + +- **The core stays agnostic.** No `react`, no DOM (`document`/`window`), no + mittwald policy in the core; such parts live in `models-react` or in the + consumer ([ADR-0002](docs/adr/0002-agnostic-core-two-packages.md)). +- **Immutability.** Model instances and their `data` are to be treated as + **immutable**. `data` is protected by a deep freeze in dev/test (not in + production, for performance). The instance itself is **not** frozen. +- **Folder naming**: behavior implementations live under `behaviors/` (plural). +- **No deep imports** into package internals; everything goes through the root. + +## Documentation + +- [CONTEXT.md](CONTEXT.md) — glossary / ubiquitous language +- [docs/implementation-patterns.md](docs/implementation-patterns.md) — recurring + code idioms (helpers, conventions) +- [docs/adr/](docs/adr/) — architecture decision records (ADRs) +- [docs/api-drift.md](docs/api-drift.md) — known deviations from the generated + OpenAPI spec diff --git a/packages/models/docs/adr/0001-initialization.md b/packages/models/docs/adr/0001-initialization.md new file mode 100644 index 00000000..34d9713f --- /dev/null +++ b/packages/models/docs/adr/0001-initialization.md @@ -0,0 +1,29 @@ +--- +status: accepted +--- + +# Initialization via `initApiModels` + +The models used to wire themselves up through a side-effect import +(`import "./config/behaviors/api"`) into a registry pre-filled with +`undefined as unknown as XBehaviors` — reaching into the consumer's globals and +failing at runtime (not compile time) when unwired. Instead, the consumer calls +an explicit `initApiModels({ apiClient, … })` once at startup, which populates +an encapsulated registry and fails clearly if a behavior is accessed before +init. The app-specific dependencies (`apiClient`, API URLs, optionally +`isEmployee`) are parameters of `initApiModels`. + +## Considered Options + +- **Global default via `initApiModels` (chosen).** The static entry points + (`Server.find`, `server.getContract()`) stay unchanged. Viable because auth is + cookie-based (`withCredentials`), so the `apiClient` carries no per-user + secret and a global singleton is not a client-side correctness bug. +- **Instance-based context (`createApiModels()`), no globals.** The cleanest DI + and true multi-client capability, but every static usage would move to + instance/context access, and there is no current need for multiple concurrent + clients. The instance-based hybrid (a global default _plus_ explicitly + instantiable clients) stays open as a later extension, without breaking the + default ergonomics. +- **Consumer supplies `behaviors`.** Maximum flexibility but boilerplate for the + common case. Rejected. diff --git a/packages/models/docs/adr/0002-agnostic-core-two-packages.md b/packages/models/docs/adr/0002-agnostic-core-two-packages.md new file mode 100644 index 00000000..3307375d --- /dev/null +++ b/packages/models/docs/adr/0002-agnostic-core-two-packages.md @@ -0,0 +1,33 @@ +--- +status: accepted +--- + +# `models` stays strictly agnostic; shipped as two packages + +The value of the `models`/`models-react` split stands or falls on the core being +**free of React, the DOM, and mittwald policy** — that is the only way it is +SSR-safe. We therefore decide: everything React/DOM/policy-specific lives in +`@mittwald/api-models-react` or in the consumer, never in the core. It ships as +**two separate packages** (`@mittwald/api-models`, `@mittwald/api-models-react`) +versioned in lockstep; the dependency runs one-way, react → core. + +## Consequences + +- Model methods with DOM side effects (file downloads via `document`/`window` in + `RecoveryCodes`, `Container`, `CronjobExecution`, `DnsZone`, + `ExtensionInstance`) **return data instead** (`Blob`/`ArrayBuffer`/string + + filename); the actual download is performed by a browser helper outside the + core. +- UI in the core (`fyndr/util/LeadUI.tsx` with `react`/`@tabler`) moves out. +- The `@mittwald.de` heuristic `isEmployee` is not hardcoded in the package: + primarily `data.isEmployee`, with a fallback injected via `initApiModels` when + needed. +- An ESLint guard in `packages/models/eslint.config.js` (`no-restricted-imports` + for `react`/`react-dom`/`@tabler/*`/`@mittwald/flow-react-components`, + `no-restricted-globals` for `document`/`window`) prevents regressions. +- Agnostic consumers (Node/CLI) get a react-free dependency tree. The core loads + `@mittwald/react-ghostmaker` (for the `@GhostMakerModel` decorator and + `getModelName`) only through its React-free entry + `@mittwald/react-ghostmaker/model`, where `react`/`@tanstack/react-query` are + optional peers. The ESLint guard forbids the ghostmaker main entry in the + core, since that one loads React. diff --git a/packages/models/docs/adr/0003-public-api-root-barrel.md b/packages/models/docs/adr/0003-public-api-root-barrel.md new file mode 100644 index 00000000..178a8fbc --- /dev/null +++ b/packages/models/docs/adr/0003-public-api-root-barrel.md @@ -0,0 +1,29 @@ +--- +status: accepted +--- + +# The public API is the curated root barrel; subpaths are gated + +Today the root `index.ts` re-exports everything via `export *` — including the +internal machinery (the `config` object, `base` helpers, behaviors) — and via +the wildcard aliases any internal path is importable. For a versioned package +this means: no encapsulation, a huge surface, and every internal rename is a +breaking change. We decide: the **public contract is the curated root entry +point**; internal machinery is not exported, and deep subpath imports are +**gated** via `package.json#exports`. + +## Consequences + +- Public: model classes, their data/query types, the base classes + (`ReferenceModel`, `DataModel`, `ListDataModel`, `ListQueryModel`, + `BaseModel`), `initApiModels`, the curated base helpers consumers rely on + (`registerDefaultOnBeforeRequestHandler`, `extractId`), a curated `common` + (`Money`, `Bytes`, `LocalizedText`), and `errors`. Internal: the `config` + object, the remaining `base` helpers (`validateResponse`, `assertObjectFound`, + `required`, `lazyGetter` …), and the behavior implementations. +- Because consumers effectively use only the root (778 root vs. 4 subpath + imports), the internal folder **taxonomy** can be reorganized later without + breaking consumers. The four existing deep-import leaks (article templates, + `container/lib/shellwords`, conversation types) are resolved. +- The raw `MittwaldAPIV2.*` type re-exports remain part of the surface; whether + to wrap them behind package-owned types is a known open question. diff --git a/packages/models/docs/adr/0004-mixin-functions-instead-of-polytype.md b/packages/models/docs/adr/0004-mixin-functions-instead-of-polytype.md new file mode 100644 index 00000000..b7ab30f7 --- /dev/null +++ b/packages/models/docs/adr/0004-mixin-functions-instead-of-polytype.md @@ -0,0 +1,53 @@ +--- +status: accepted +--- + +# Compose models with plain mixin functions instead of polytype + +Model composition currently rests on `polytype`'s `classes(...)` multiple +inheritance (272 composite classes). `polytype` is niche and forces a +`@lazyGetter` workaround for its "this in base constructors" limitation. We +evaluated `ts-mixer` (more widespread) but it **regresses native `instanceof`** +(requires `hasMixin`), which the core relies on heavily. We decide to compose +with the **plain TypeScript mixin-function pattern** — zero dependency: a linear +single-inheritance _identity_ chain (`BaseModel → ReferenceModel → …`) plus +generic _capability_ mixin functions (`WithData()`, `WithListData()`) for +the parts that only bolt on data. Validated by a throwaway PoC (plain +mixin-function composition across a 5-level `instanceof` chain); the PoC folder +has since been removed, its conclusions captured in this ADR. + +## Considered options + +- **polytype (status quo)** — preserves `instanceof`, but is niche and imposes + the `@lazyGetter` constructor workaround. +- **ts-mixer** — more widespread, and its `settings.initFunction` is cleaner + than `@lazyGetter`, but native `instanceof` returns `false` for mixed classes + (`hasMixin` required). The core uses `instanceof` pervasively (hundreds of + sites) — rejected. +- **Plain mixin functions (chosen)** — native `instanceof` across the whole + chain, zero dependency, the standard documented TS pattern. + +## Consequences + +- **Native `instanceof` is preserved.** It is only needed on the linear identity + chain; the PoC confirmed it across a 5-level chain (`ServerArticle` → + `HostingArticle` → `ArticleCommon` → `Article` → `ReferenceModel`), including + an `abstract` intermediate class. +- **The ghostmaker/polytype coupling dissolves.** `@mittwald/react-ghostmaker`'s + **main entry** resolves identity via the default prototype-chain walk — the + PoC resolved a `ServerArticle` four levels below the `@GhostMakerModel` + decorator. The `@mittwald/react-ghostmaker/polytype` import is dropped. +- **`@lazyGetter` can be removed** — normal constructors and getters work on a + normal prototype chain. +- **Standalone generic bases and generic mixins are separate primitives.** + `class DataModel extends WithData()(BaseModel)` does not compile (TS2562 + — a base-class expression cannot reference the class's own type parameter). + `DataModel` / `ListDataModel` stay plain generic classes; the mixin is + used only for the _combining_ case. +- **Ergonomic cost:** the capability mixin is a typed marker + (`declare readonly data: T`), so each concrete class still declares and + assigns its own field and threads arguments through `super()`; the `Ctor` + helper type uses `...args: any[]`. Mild, local, explicit. +- **Migration scope:** 272 `classes(...)` composites + 82 standalone + `extends DataModel<…>` sites. No `classes(...)` uses 3+ bases, so an identity + chain plus one capability mixin is structurally sufficient. diff --git a/packages/models/docs/adr/0005-model-testing-via-injected-behaviors.md b/packages/models/docs/adr/0005-model-testing-via-injected-behaviors.md new file mode 100644 index 00000000..03d9fe9e --- /dev/null +++ b/packages/models/docs/adr/0005-model-testing-via-injected-behaviors.md @@ -0,0 +1,61 @@ +--- +status: accepted +--- + +# Unit-test models by injecting fake behaviors into the registry + +Models reach the API only through their `behaviors` — an injectable per-domain +interface installed into the `config.behaviors` registry at startup by +`initApiModels`. We test model _logic_ (construction from data, derived getters, +guards, correct delegation) by installing fake behaviors into that same registry +and treating the `api.ts` mapping layer as the boundary rather than re-testing +it. Tests run under vitest in the default `node` environment — the agnostic core +needs no DOM. + +A small package-internal test helper is the seam: `installBehaviors(partial)` +writes partial fakes onto the registry's Proxy target and `resetBehaviors()` +clears it back to its fail-fast state, called from a per-test-file `afterEach` +so the module-singleton `config` cannot leak between tests. Fakes are hybrid: +inline `vi.fn` stubs returning fixture data by default, and a stateful in-memory +fake only where a flow spans several behavior calls (read-after-write, +list-after-mutation). Fixture data comes from lazily-added, typed builder +functions per `*Data` type (`buildXData(overrides?)`), since the `*Data` types +are compile-time-only OpenAPI derivations with no runtime examples to import. + +## Considered options + +- **Fake the `MittwaldAPIV2Client` and wire real behaviors via `initApiModels` + (rejected).** Highest fidelity, but forces reconstructing the client for every + method a model touches and tests the api-mapping layer we deliberately treat + as the boundary. +- **Direct `config.behaviors. = fake` assignment (rejected).** No + helper, but repetitive, easy to forget the reset, and reaches raw into the + internal `config`. +- **Inject via a helper against the Proxy registry (chosen).** Targets the seam + directly, gives isolation, and needs no api-client fake. +- **Pure in-memory fakes for all ~60 domains, or generating fixtures from the + OpenAPI spec (rejected for now).** Overkill for transform-level assertions and + heavy to build and maintain; kept as a later option if broad coverage is + pursued. + +## Consequences + +- **The `behaviors` seam is the single injection point** for tests — reinforcing + ADR-0001's registry design and CONTEXT.md's "models never call api-client + directly". +- **Scope for the pre-publish milestone** is the shared foundation (base + classes, the registry/init fail-fast contract, `extractId` / `required` / + `assertObjectFound`, aggregate references) plus one model per structural + pattern (reference + delegation, data + derived getters, list + + query/pagination, ghostmaker `instanceof` identity, `DownloadableFile`). Broad + per-domain coverage is deliberately left as follow-on work. +- **The test helper is written publish-ready under `testing/`** but its + `@mittwald/api-models/testing` export is deferred to the packaging step + (P0-4); until then it is imported only via relative paths from tests. +- **The ghostmaker identity path is a regression net** for the planned polytype + → mixin migration (ADR-0004). +- **Known friction:** `assertObjectFound` constructs `ObjectNotFoundError`, + which names the missing type via `getModelName` from the React-free + `@mittwald/react-ghostmaker/model` entry. That lookup only knows registered + ghost models, so tests of the error path mock it to name any class by its JS + name; the found path tests freely. diff --git a/packages/models/docs/api-drift.md b/packages/models/docs/api-drift.md new file mode 100644 index 00000000..2c7f30b6 --- /dev/null +++ b/packages/models/docs/api-drift.md @@ -0,0 +1,150 @@ +# API drift: `@mittwald/api-models` ↔ `@mittwald/api-client` + +**As of:** api-client `4.465.0`. + +Places where this package deviates from the generated OpenAPI spec. **Every row +is two-sided** — not automatically "the backend must fix it": either the spec +omits a status/field the endpoint really returns (→ extend the spec), or the +frontend works around behavior that is actually correct (→ drop the workaround +in this package). + +Most rows are **missing status codes**: the package handles a status that is not +in the spec's `responses`, currently bridged via `anyStatus*` (`… as any`, +`base/api/typeFixes.ts`). "Source" is the concrete `METHOD /route`, or a schema +path for pure-type drift. + +> **Resolved in the latest run:** nothing. `4.465.0` declares no additional +> status on any operation below — the literal-status `tsc` probe still fails on +> all 26 casts — `checkToken()` still does not exist, and `registeredAt` is +> still optional (already so in `4.463.0`, so the declaration is not new). Two +> bookkeeping changes: the `403` on +> `GET /v2/app-installations/{appInstallationId}` was the only cast without an +> `API-DRIFT` marker and now has one, and the `spotlight` rows below are listed +> for the first time. Resolved there: `4.465.0` ships `getSpotlightInfo`, +> `spotlightUsage` and `spotlightFeedback`, so the hand-written types and the +> `client.axios` transport are gone — and with them the `cache: false` the +> missing `onBeforeRequest` hook used to force. + +## app + +| Source | Frontend (api-models) | API spec (4.465.0) | Resolution | +| ----------------------------------------------- | ------------------------- | ------------------ | ----------------------------------------------------------------- | +| `GET /v2/app-installations/{appInstallationId}` | handles `403` (no access) | `404`, `429` | add `403` to spec — or drop handling in package if never returned | + +## auth + +| Source | Frontend (api-models) | API spec (4.465.0) | Resolution | +| ---------------------------------------------------------------------- | ------------------------------------------------------------------------ | ------------------------------------------ | ----------------------------------------------------------------------------------- | +| `POST /v2/authenticate` · `POST /v2/authenticate-mfa` | treats `403` as `invalidCredentials` | `200`, `202`, `204`, `400`, `408`, `429` | add `403` to spec if auth returns it — or drop the check in package | +| `PUT /v2/logout` | handles `401` | `204`, `400`, `429` | add `401` to spec — or drop in package | +| `GET /v2/users/{userId}` (`userId: "self"`, in `checkIsAuthenticated`) | accepts `401` | `200`, `403`, `404`, `412` | add `401` to spec — or drop in package | +| `GET /v2/users/{userId}` (self, as auth probe) — **behavioral** | probes auth via `getUser` self because no lightweight token check exists | no dedicated "token still valid?" endpoint | backend adds a `checkToken()` endpoint — or confirm the getUser probe as acceptable | + +## certificate + +| Source | Frontend (api-models) | API spec (4.465.0) | Resolution | +| -------------------------------------- | --------------------- | ------------------ | -------------------------------------- | +| `GET /v2/certificates/{certificateId}` | handles `403` | `404`, `429` | add `403` to spec — or drop in package | + +## contract + +| Source | Frontend (api-models) | API spec (4.465.0) | Resolution | +| --------------------------------------- | --------------------- | ------------------- | -------------------------------------- | +| `GET /v2/projects/{projectId}/contract` | handles `403` | `400`, `404`, `429` | add `403` to spec — or drop in package | +| `GET /v2/servers/{serverId}/contract` | handles `403` | `400`, `404`, `429` | add `403` to spec — or drop in package | +| `GET /v2/contracts/{contractId}` | handles `403` | `400`, `404`, `429` | add `403` to spec — or drop in package | + +## container + +| Source | Frontend (api-models) | API spec (4.465.0) | Resolution | +| ---------------------------------------------------------------------- | --------------------------------------------------------------------------------- | -------------------------- | ------------------------------------------------------------------------------------------- | +| `Components.Schemas.ContainerTemplate.help.alerts[].status` — **type** | narrows to `containerTemplateAlertStatuses`, unknown values fall back to `"info"` | `status: string` (no enum) | spec declares the enum — then derive `ContainerTemplateAlertStatus` from the generated type | + +## cronjob + +| Source | Frontend (api-models) | API spec (4.465.0) | Resolution | +| ------------------------------ | --------------------- | ------------------ | -------------------------------------- | +| `GET /v2/cronjobs/{cronjobId}` | handles `403` | `404`, `429` | add `403` to spec — or drop in package | + +## customer + +| Source | Frontend (api-models) | API spec (4.465.0) | Resolution | +| ------------------------------------------------- | ---------------------------- | ------------------- | -------------------------------------- | +| `GET /v2/customers/{customerId}/payment-method` | treats `403` as `"noAccess"` | `400`, `404`, `429` | add `403` to spec — or drop in package | +| `GET /v2/customer-invites/{customerInviteId}` | handles `403` | `404`, `429` | add `403` to spec — or drop in package | +| `GET /v2/customers/{customerId}/memberships` | handles `403` (in `findOwn`) | `404`, `429` | add `403` to spec — or drop in package | +| `GET /v2/customers/{customerId}/invoice-settings` | handles `403` | `400`, `404`, `429` | add `403` to spec — or drop in package | + +## database + +| Source | Frontend (api-models) | API spec (4.465.0) | Resolution | +| ------------------------------------------- | --------------------- | -------------------------- | -------------------------------------- | +| `GET /v2/mysql-databases/{mysqlDatabaseId}` | handles `403` | `400`, `404`, `429`, `500` | add `403` to spec — or drop in package | +| `GET /v2/redis-databases/{redisDatabaseId}` | handles `403` | `400`, `404`, `429`, `500` | add `403` to spec — or drop in package | + +## domain + +| Source | Frontend (api-models) | API spec (4.465.0) | Resolution | +| -------------------------------------------------- | ------------------------------------------------- | ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------- | +| `Domain.findByHostname` — **behavioral / routing** | `findByHostname` via `find(hostname)` is disabled | route invalidation does not work for shortId (hostname) lookups (not statically checkable) | backend/infra fix route invalidation for hostname lookups — or rethink the approach in package | + +## ingress + +| Source | Frontend (api-models) | API spec (4.465.0) | Resolution | +| ------------------------------- | --------------------- | ------------------ | -------------------------------------- | +| `GET /v2/ingresses/{ingressId}` | handles `403` | `404`, `429` | add `403` to spec — or drop in package | + +## marketplace + +| Source | Frontend (api-models) | API spec (4.465.0) | Resolution | +| ------------------------------------------------------------ | --------------------- | ------------------- | -------------------------------------- | +| `GET /v2/contributors/{contributorId}` | handles `403` | `404`, `429` | add `403` to spec — or drop in package | +| `GET /v2/extension-instances/{extensionInstanceId}/contract` | handles `403` | `400`, `404`, `429` | add `403` to spec — or drop in package | +| `GET /v2/customers/{customerId}/extension-orders` | handles `403` | `400`, `404`, `429` | add `403` to spec — or drop in package | + +## order + +| Source | Frontend (api-models) | API spec (4.465.0) | Resolution | +| -------------------------- | --------------------- | ------------------ | -------------------------------------- | +| `GET /v2/orders/{orderId}` | handles `404` | `200`, `429` | add `404` to spec — or drop in package | + +## performance + +| Source | Frontend (api-models) | API spec (4.465.0) | Resolution | +| ------------------------------------------------- | --------------------- | ------------------- | -------------------------------------- | +| `GET /v2/projects/{projectId}/straces/{straceId}` | handles `404` | `400`, `403`, `429` | add `404` to spec — or drop in package | + +## project + +| Source | Frontend (api-models) | API spec (4.465.0) | Resolution | +| ------------------------------------------- | --------------------- | ------------------ | -------------------------------------- | +| `GET /v2/projects/{projectId}` | handles `404` | `403`, `429` | add `404` to spec — or drop in package | +| `GET /v2/project-invites/{projectInviteId}` | handles `403` | `404`, `429` | add `403` to spec — or drop in package | + +## user + +| Source | Frontend (api-models) | API spec (4.465.0) | Resolution | +| --------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | -------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | +| `DELETE /v2/users/self` | handles `409` (last owner → `isLastOwner`) and `404` | `200`, `202`, `412`, `400`, `429` | add `409`/`404` to spec — or drop in package (a `response.data.originalStatus === 409` fallback already exists) | +| `GET /v2/users/{userId}` | handles `400` | `403`, `404`, `412` | add `400` to spec — or drop in package | +| `Components.Schemas.UserUser.registeredAt` (response of `GET /v2/users/{userId}`) | falls back to `DateTime.now()` when missing (else accounts look "new") | `registeredAt?` optional (presence not guaranteed) | backend returns `registeredAt` non-optional — or drop the fallback once the API is confirmed to return it | + +### user · spotlight + +| Source | Frontend (api-models) | API spec (4.465.0) | Resolution | +| -------------------------------------------------------------- | ---------------------------------------------------------------- | ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------- | +| `POST /v2/users/self/spotlights/{spotlightId}` · `/feedback` | omits `owner` from both request bodies, cast away on `/feedback` | `owner` declared on both, **required** on `/feedback` | drop `owner` from the service schema — or have the client send it again | +| `GET /v2/users/self/spotlights/{spotlightId}` — **behavioral** | expects `200` for an unknown record, as the spec declares | `200`, `429`; the service answers `403` for a record that does not exist | service returns the `200` null state its own spec declares — or the spec declares what it really returns | + +## Summary + +- **26 missing status codes** across 13 areas (bridged via `anyStatus*`), each + confirmed with the literal-status `tsc` probe against `4.465.0`. +- **4 behavioral/field deviations**: `auth` (checkToken endpoint), `container` + (alert status without enum), `domain` (findByHostname / route invalidation), + `user` (registeredAt). +- **`user · spotlight`**: an omitted `owner` (required in the generated feedback + type) and a `403` where the spec declares `200`. +- Notable: almost all missing codes are **`403` on protected `GET` detail + endpoints** — worth a bundled spec check whether `403` is generally absent + there. diff --git a/packages/models/docs/implementation-patterns.md b/packages/models/docs/implementation-patterns.md new file mode 100644 index 00000000..4bbfebb8 --- /dev/null +++ b/packages/models/docs/implementation-patterns.md @@ -0,0 +1,1073 @@ +# Implementation patterns + +Small, recurring code idioms used throughout `@mittwald/api-models`. This is a +contributor reference for the low-level building blocks — the _how_, not the +_why_ of the architecture. For the architecture and vocabulary see +[README.md](../README.md) and [CONTEXT.md](../CONTEXT.md); for the larger +decisions see [docs/adr/](adr/). + +When you add a model, reach for these idioms rather than reinventing them. Each +section gives the real signature, what it is for, and representative call sites. + +## `extractId` — accept an id **or** a model + +Most APIs need a bare id string, but callers usually already hold a model. +`extractId` normalizes "id string **or** reference" down to the id, so public +methods can take the ergonomic `ReferenceModel | string` shape without every +call site branching. The overloads preserve `undefined` when the input is +optional. + +```ts +export function extractId(from: ReferenceModel | string): string; +export function extractId( + from: ReferenceModel | string | undefined, +): string | undefined; +export function extractId(from?: ReferenceModel | string): string | undefined { + if (from === undefined) return; + if (typeof from === "string") return from; + return from.id; +} +``` + +Used in: `base/lib/extractId.ts`, `order/Order/Request/DomainOrderRequest.ts` +(`projectId: extractId(project)`), `app/AppInstallation/AppInstallation.ts`, +`mail/MailAddress/MailAddress.ts`. + +## `required(value)` — fail fast on missing values + +A thin wrapper over `tiny-invariant` that asserts a value is neither `null` nor +`undefined` and narrows the type. Use it to turn an optional into a non-optional +at the exact point where absence is a programming error, with a readable +message. + +```ts +export function required( + value: T | undefined | null, + valueType = "value", +): T { + invariant( + value !== undefined && value !== null, + `Expected ${valueType} not to be undefined`, + ); + return value; +} +``` + +Used in: `base/lib/required.ts`, `invoice/InvoiceItem/ServicePeriod.ts`, +`marketplace/ExtensionInstance/ExtensionInstanceContext.ts`. + +## `assertObjectFound` + `ObjectNotFoundError` — the find/get convention + +The package follows a **`find` returns `undefined` / `get` throws** convention. +`findX` performs the lookup and may return `undefined`; `getX` wraps it with +`assertObjectFound`, which throws a typed `ObjectNotFoundError` (carrying the +model type name and the reference) when nothing was found. This keeps the +optional-vs-throwing distinction uniform across every model. + +```ts +export default function assertObjectFound( + obj: T | undefined, + type: Class, + refIdOrObject: string | ReferenceModel, +): asserts obj is T { + /* throws ObjectNotFoundError when obj === undefined */ +} +``` + +```ts +// container/Container/Container.ts +public static async find(id: string, stackId: string) { + const data = await config.behaviors.container.find(id, stackId); + if (data) return new ContainerDetailed(data); +} + +public static async get(id: string, stackId: string) { + const container = await Container.find(id, stackId); + assertObjectFound(container, Container, id); + return container; +} +``` + +Used pervasively (~67 call sites): `base/lib/assertObjectFound.ts`, +`errors/ObjectNotFoundError.ts`, `container/Container/Container.ts`, +`server/Server/Server.ts`, `project/Project/Project.ts`. + +## `create()` — return a reference to the created resource + +The write-side counterpart to `find`/`get`. A static `create(...)` sends the +request through its behavior and returns a **reference** built from the id the +API echoes back (`new X(response.id)`), never the raw `*Data`. The caller gets +something it can immediately hydrate (`getDetailed()`) or act on, without a +second round-trip just to learn the id. + +```ts +// access/SshUser/SshUser.ts +public static async create(project: Project, data: SshUserCreateRequestData) { + const response = await config.behaviors.sshUser.create(project.id, data); + return new SshUser(response.id); // a reference, not `response` +} +``` + +Two deliberate departures — **not** inconsistencies — because the created +resource carries data that exists **only at creation time** and can never be +re-fetched from a reference: + +- **`ApiToken.create` returns the token secret `string`.** The plaintext token + is shown once and is never retrievable again, so the behavior is typed + `Promise` and the model passes it straight through + (`user/ApiToken/ApiToken.ts`; the create-token modal displays it once). +- **`LeadsExport.create` returns the generated export** + (`{ exportId, base64FileContent } | { errorType, … } | undefined`). It is + really an export _action_ whose file content and error discrimination are the + payload, not a resource you would later look up + (`fyndr/LeadsExport/LeadsExport.ts`). + +Operations with nothing meaningful to surface return `void` (`user/Feedback`, +`user/SshKey`, `fyndr/FinderProfileRequest`). Reserve the raw-payload shape for +these genuine "only available now" cases; otherwise return a reference. + +A model's **primary** creator is the bare `create()`; a second, differently +shaped way to create the same entity gets a descriptive name alongside it +(`MailAddress.create` for a mailbox + `MailAddress.createForward` for a +forward). `createXy` names are otherwise reserved for **relational** creators +that build a _different_ entity from a parent context (`Project.createMySql`, +`Project.createContainer`, …) and for sub-resource/action creators +(`Backup.createExport`, `Domain.createAuthCode`, `*.createUploadToken`) — those +never collapse to `create()`. + +Used in: `access/SshUser/SshUser.ts`, `database/Redis/Redis.ts`, +`app/AppInstallation/AppInstallation.ts`, +`project/ProjectInvite/ProjectInvite.ts` (reference); +`user/ApiToken/ApiToken.ts`, `fyndr/LeadsExport/LeadsExport.ts` (payload); +`user/Feedback/Feedback.ts` (void). + +## `assertInstanceOf` and the `BaseModel` type guards + +`BaseModel` exposes a trio of runtime type helpers built on `assertInstanceOf` +(itself a `tiny-invariant` wrapper). They let calling code narrow a reference to +a concrete subclass — `assertType` throws, `asType` throws-and-returns, +`isOfType` is a boolean type guard. This is the idiomatic way to go from a +`ReferenceModel` to, say, its `Detailed` variant. + +```ts +// base/models/BaseModel.ts +public assertType(type: T): asserts this is InstanceType { … } +public asType(type: T): InstanceType { this.assertType(type); return this; } +public isOfType(type: T): this is InstanceType { return this instanceof type; } +``` + +Used in: `base/models/BaseModel.ts`, `base/lib/assertInstanceOf.ts`. + +## Fail-fast behavior registry (Proxy) + `initApiModels` + +All model I/O runs through a single `config.behaviors` registry. It is a `Proxy` +over a null-prototype object: reading a behavior that has not been populated +throws a clear "not initialized" error instead of a confusing +`undefined is not a function` further down. `initApiModels({ apiClient })` fills +every slot with its API adapter at startup. This is what forces the "call +`initApiModels` before using any model" contract to fail loud and early. + +```ts +// config/config.ts +export const config: Config = { + defaultPaginationLimit: 50, + behaviors: new Proxy(Object.create(null), { + get(target, property, receiver) { + if (Reflect.has(target, property)) + return Reflect.get(target, property, receiver); + throw new Error( + `@mittwald/api-models is not initialized — call initApiModels({ apiClient }) ` + + `at startup before using any model (accessed behaviors.${String(property)})`, + ); + }, + }), +}; +``` + +```ts +// config/initApiModels.ts +config.behaviors.container = apiContainerBehaviors(apiClient); +config.behaviors.project = apiProjectBehaviors(apiClient); +// … one line per model +``` + +Used in: `config/config.ts`, `config/initApiModels.ts`. + +## Behavior adapter: `apiXBehaviors(client)` + `validateResponse` + +Every model declares a transport-neutral behavior interface +(`behaviors/types.ts`) and a matching API adapter `apiXBehaviors(client): X` +(`behaviors/api.ts`). Models call `config.behaviors.x.*`, never `api-client` +directly. Adapters assert the expected HTTP status with `validateResponse` +(which narrows the response type) and return raw `*Data`. List operations return +the uniform `QueryResponseData` envelope (`{ items, totalCount }`). + +```ts +// container/Container/behaviors/api.ts +export const apiContainerBehaviors = ( + client: MittwaldAPIV2Client, +): ContainerBehaviors => ({ + find: async (containerId, stackId) => { + const response = await client.container.getService({ + serviceId: containerId, + stackId, + }); + if (response.status === 200) return response.data; + validateResponse(response, [403, 404]); + }, + // … +}); +``` + +```ts +// base/models/types.ts +export interface QueryResponseData { + items: readonly T[]; + totalCount: number; +} +``` + +Used in: every `*/behaviors/api.ts` and `*/behaviors/types.ts`, +`base/api/validateResponse.ts`, `base/models/types.ts`. Rationale for the +injectable split: [ADR-0005](adr/0005-model-testing-via-injected-behaviors.md). + +## Reference identity: `@GhostMakerModel`, `ReferenceModel`, `ofId` + +A relation is represented cheaply by identity alone. `ReferenceModel` carries +just an `id`; `static ofId(id)` builds a reference **without any I/O**, so a +constructor can freely derive relations (`Project.ofId(data.projectId)`). +Hydration happens later via `getDetailed()` / `getCommon()`. Models are +decorated with `@GhostMakerModel` so `@mittwald/api-models-react` can resolve +identity for its Ghosts. + +```ts +// base/models/ReferenceModel.ts +@GhostMakerModel({ getId: (model) => model.id }) +export abstract class ReferenceModel extends BaseModel { + public readonly id: string; + public constructor(id: string) { + super(); + this.id = id; + } + public describe(): string { + return `${this.constructor.name}@${this.id}`; + } +} +``` + +```ts +// container/Container/Container.ts +public static ofId(id: string, stackId: string) { return new Container(id, stackId); } +``` + +Used across ~65 models: `base/models/ReferenceModel.ts`, +`project/Project/Project.ts`, `server/Server/Server.ts`. Note that a model may +expose a domain-specific factory instead of/alongside `ofId` (e.g. +`FinderProfile.ofCustomerId(id)`, `Container.ofId(id, stackId)`). + +## `Common` / `Detailed` / `ListItem` variants via capability mixins + +Per entity `X` there is a reference (`X`), the shared fields (`XCommon`), the +full single view (`XDetailed`), and one list element (`XListItem`). Identity is +a plain single-inheritance chain, so native `instanceof` holds across it +(`ContainerDetailed instanceof ContainerCommon instanceof Container instanceof ReferenceModel`); +methods use that multi-stage `instanceof` to decide whether a fetch is needed. +Data is bolted on with the zero-dependency capability mixins `WithData()` / +`WithListData()` (`base/models/mixins.ts`) — the move off `polytype` +while keeping `instanceof` is +[ADR-0004](adr/0004-mixin-functions-instead-of-polytype.md). + +```ts +// container/Container/Container.ts +export class ContainerCommon extends WithData< + ContainerListItemData | ContainerData +>()(Container) { + public override readonly data: ContainerListItemData | ContainerData; + public constructor(data: ContainerListItemData | ContainerData) { + super(data.id, data.stackId); // Container(id, stackId) — args threaded through directly + this.data = data; + /* …shared derived fields… */ + } +} + +// Detailed / ListItem extend Common directly and narrow `data` (no re-applied mixin): +export class ContainerDetailed extends ContainerCommon { + public override readonly data: ContainerData; + public constructor(data: ContainerData) { + super(data); + this.data = data; + } +} + +// Lists compose the query class with WithListData; items stay frozen: +export class ContainerList extends WithListData()(ContainerListQuery) { + public override readonly items: readonly ContainerListItem[]; + public override readonly totalCount: number; + public constructor( + project: Project, + query: ContainerListQueryData, + containers: ContainerListItem[], + totalCount: number, + ) { + super(project, query); + this.items = Object.freeze(containers); + this.totalCount = totalCount; + } +} + +// idempotent hydration driven by instanceof: +public async getCommon(): Promise { + return this instanceof ContainerCommon ? this : this.getDetailed(); +} +``` + +Used in every domain model, e.g. `container/Container/Container.ts`, +`server/Server/Server.ts`, `domain/Domain/Domain.ts`. + +### Traps that `tsc` does not catch + +1. **`DataModel` / `ListDataModel` are no longer nominal bases.** A composite is + `WithData()(X)`, not `extends DataModel`, so `x instanceof DataModel` is + always `false` — assert the observable payload (`x.data` / `x.items`) + instead. Standalone `extends DataModel` / `extends ListDataModel` + classes still exist and are unchanged; only the _combining_ case uses the + mixin. +2. **Re-declaring a mixin field clobbers the parent's assignment.** With + `useDefineForClassFields` (target ES2022), re-declaring `data` / `items` / + `totalCount` in a subclass emits a define-to-`undefined` that runs _after_ + `super()`. So any re-declared field that a parent constructor already assigns + must be re-assigned in this constructor (that is why `ContainerDetailed` + repeats `this.data = data`); conversely, never re-declare a field you do not + re-assign. +3. **Eager cross-model references in a constructor crash under import cycles.** + A field initialized to another model at construction time — e.g. + `Ingress.certificates = Certificate.query(...)` — evaluates during module + load. If the two models sit in a peer/parent module cycle and the reference + resolves **through the root barrel**, the other class can still be + `undefined` at that point (temporal dead zone), throwing at import time. Two + rules keep this safe: (a) reach the other model by a **deep import** + (`../../ingress/Ingress/Ingress`, not the barrel) so resolution doesn't wait + on the barrel's full evaluation, and (b) prefer **lazy** cross-model access + (a method that calls `Other.query()` when invoked) over an eager ctor field + wherever the ergonomics allow. Cross-aggregate references by identity + (`Other.ofId(id)`) are always safe — they touch only the id, not the other + class's statics. This is why `certificate ↔ ingress` is an accepted module + cycle: the eager `Ingress.certificates` ctor field deep-imports + `Certificate`, while `Certificate.linkedIngresses` (a lazy query getter) + deep-imports `Ingress`. + +## Derived values built in the constructor + +Wire data is primitive (ISO strings, byte counts, integer minor units). Models +convert these into rich value objects **once in the constructor** so consumers +always get typed values: `DateTime` (luxon) for timestamps, `Bytes` for sizes, +`Money` (dinero.js, pinned to EUR/de-DE) for amounts. + +```ts +this.statusSetAt = DateTime.fromISO(data.statusSetAt); // container/Container +this.storageUsage = Bytes.of(data.storageUsageInBytes, "bytes"); // database/Redis, database/MySql +this.totalGross = Money({ amount: data.totalGross ?? 0, currency: "EUR" }); // invoice/Invoice +``` + +`Bytes` and `Money` live in `common/` with their own arithmetic/formatting APIs +(`Bytes.of`, `.in(unit)`, `.text()`; `Money`, `ZeroMoney`). + +Used in: `common/Bytes.ts`, `common/Money.ts`, `invoice/Invoice/Invoice.ts`, +`database/Redis/Redis.ts`, `mail/MailAddress/MailAddress.ts`, +`server/Server/Server.ts`. + +## `DownloadableFile` — data-returning download descriptor + +The core is DOM-free ([ADR-0002](adr/0002-agnostic-core-two-packages.md)), so it +never triggers a browser download. Methods that produce a file return a plain +`{ filename, content }` descriptor; turning it into an actual download is the +consumer's job. + +```ts +// common/DownloadableFile.ts +export interface DownloadableFile { filename: string; content: string; } + +// container/Container/Container.ts +public async getLogDownload(): Promise { + const response = await config.behaviors.container.getLog(this.id, this.stackId); + return { filename: `${this.serviceName}.log`, content: response }; +} +``` + +Used in: `common/DownloadableFile.ts`, `container/Container/Container.ts`. + +## `AggregateMetaData` / `AggregateReference` — cache/invalidation identity + +Each model declares a +`static aggregateMetaData = new AggregateMetaData(domain, aggregate)`, its +stable identity for caching and invalidation. A polymorphic +`{ aggregate, domain, id, parent? }` payload is resolved back to the right +concrete reference by `resolveAggregateReference`, which matches on each model's +`aggregateMetaData` and returns `Model.ofId(id)`. Models also expose a +`findAggregate(id)` helper to build the payload. + +```ts +// common/AggregateMetaData.ts +export class AggregateMetaData { + public constructor(public readonly domain: string, public readonly aggregate: string) {} +} + +// container/Container/Container.ts +public static aggregateMetaData = new AggregateMetaData("container", "container"); + +// common/AggregateReference.ts +export function resolveAggregateReference(data: AggregateReferenceData): AggregateReference { + if (domain === Server.aggregateMetaData.domain && aggregate === Server.aggregateMetaData.aggregate) + return Server.ofId(id); + // … one branch per model +} +``` + +Used in: `common/AggregateMetaData.ts`, `common/AggregateReference.ts`, and +every model's `static aggregateMetaData`. + +## `ListQueryModel` — stable `queryId`, `.refine()`, `.execute()` + +A list is expressed as a **not-yet-executed** query. `ListQueryModel` hashes the +query object (`object-code`) together with its parent dependencies into a stable +`queryId` (via `joinedId`) — the same query always yields the same id, which is +what caching keys on. Before hashing, `normalizeQueryForHash` reduces any +`ReferenceModel` in the query to its `id`, so a query field typed +`Model | string` (see the next section) produces the **same** `queryId` whether +the caller passes a reference, a loaded model, or the bare id — the key is the +identity, never the model payload. (`object-code` ignores `toJSON`, so without +this a loaded model would hash its whole `data`.) `.refine()` returns a new +query with merged parameters; `.execute()` — declared `abstract` on the base — +materializes it into an `XList` (query + items + `totalCount`). Pagination +defaults to `config.defaultPaginationLimit`. Because every result carries a +`totalCount`, the base can offer `getTotalCount()` for free: it runs the query +and reads the count off the result. A model **overrides** it with +`refine({ limit: 1 })` (fetching a single-item page) wherever its list endpoint +is genuinely paginated — safe because a paginated mittwald endpoint always +returns the `x-pagination-totalcount` header, so `resolveTotalCount` reads the +real total regardless of page size. Whether an endpoint paginates is decided by +its generated query type: many are `{}` (no `limit`), and those correctly keep +the plain default. The one genuinely-paginated list still on the default is +`TldPrice`, whose behavior hardcodes `limit: 2000` and exposes no `refine`; +optimising it would need a model change first. + +```ts +// base/models/ListQueryModel.ts +@GhostMakerModel({ getId: (model) => model.queryId }) +export abstract class ListQueryModel { + public readonly queryId: string; + public constructor(query: TQuery, opts: Options = {}) { + this.query = query; + // normalizeQueryForHash: ReferenceModel -> id before hashing, so + // `Model | string` fields key on identity, not the loaded payload + this.queryId = joinedId( + ...(opts.dependencies ?? []), + hash(normalizeQueryForHash(query)), + ); + } + + // every list result has a totalCount, so execute is typed to guarantee it + public abstract execute( + options?: AxiosRequestConfig, + ): Promise<{ totalCount: number }>; + + public async getTotalCount(options?: AxiosRequestConfig): Promise { + const { totalCount } = await this.execute(options); + return totalCount; + } +} +``` + +```ts +// container/Container/Container.ts +public refine(query: ContainerListQueryData) { + return new ContainerListQuery(this.project, { ...this.query, ...query }); +} +public async execute(options?: AxiosRequestConfig) { + const { items, totalCount } = await config.behaviors.container.list(this.project.id, this.query, options); + return new ContainerList(this.project, this.query, items.map((c) => new ContainerListItem(c)), totalCount); +} +``` + +```ts +// order/Order/Order.ts — count without pulling the whole list +public async getTotalCount() { + const { totalCount } = await this.refine({ limit: 1 }).execute(); + return totalCount; +} +``` + +Used in: `base/models/ListQueryModel.ts`, `base/models/ListDataModel.ts`, +`container/Container/Container.ts`, and every `*ListQuery` / `*List`. + +## Query fields that reference another model accept `Model | string` + +Every field of a `*ListQueryModelData` that references **another model** — the +parent scope (`project`, `customer`, `database`, …) **and** any filter +(`certificate`, `ingress`, `stack`, `extension`, `appInstallation`, `container`, +…) — is typed `Model | string` and named after the model, **not** the raw +`xxxId`. The generated OpenAPI `xxxId` is `Omit`ted from the base query type and +re-mapped in `execute()` via `extractId`: + +```ts +export type XListQueryModelData = Omit & { + certificate?: Certificate | string; // import type — no runtime edge +}; +// execute() +behavior.list({ + ...omit(this.query, ["certificate"]), + certificateId: extractId(this.query.certificate), +}); +``` + +Referenced model types are imported **type-only**, so this adds no runtime +module edge. Callers may pass either a model or a bare id — and should **prefer +passing the model** where they already hold one (`query({ certificate })` over +`query({ certificate: certificate.id })`). This is cache-safe: `ListQueryModel` +(`normalizeQueryForHash`, previous section) reduces any `ReferenceModel` to its +id before hashing the `queryId`, so a reference, a loaded model, and a bare id +all produce the same key. The bare id stays accepted for the cases that only +have one (a route param, or when the value in hand is a different model that +merely shares the id — e.g. a `ContributorExtension` id passed where an +`Extension` is typed). + +Watch the mismatch case: pass `.id` (not the model) when the model you hold is +**not** the type the field expects. `tsc` catches this — a +`ContributorExtensionCommon` is not assignable to +`extension?: Extension | string` — so the field type is the guard. + +Used across every `*ListQuery`; the convention was swept package-wide +(compiler-resolved over all `*ListQueryModelData` types) so no filter field +still takes a raw id. + +## `*Data` types are OpenAPI derivations + +Model data types are never hand-written; they are aliased straight from the +generated `MittwaldAPIV2.*` namespace of `@mittwald/api-client`, keeping the +models in lock-step with the API contract. Drill into `Components.Schemas.*`, +`Operations.*.ResponseData`, or `Paths.*.Parameters.*` as needed. + +```ts +// container/Container/types.ts +export type ContainerData = + MittwaldAPIV2.Components.Schemas.ContainerServiceResponse; +export type ContainerListItemData = + MittwaldAPIV2.Operations.ContainerListServices.ResponseData[number]; +export type ContainerListQueryData = + MittwaldAPIV2.Paths.V2ProjectsProjectIdServices.Get.Parameters.Query; +``` + +Used in every `*/types.ts`, e.g. `container/Container/types.ts`, +`order/Order/types.ts`, `domain/Domain/types.ts`. + +## `// API-DRIFT:` markers — labelling deliberate spec deviations + +Because every `*Data` type is derived from `@mittwald/api-client`, the models +drift out of sync whenever that dependency is **bumped** and the generated +`MittwaldAPIV2.*` types change shape. Where we deliberately keep a workaround +for such drift, tag it in-code with a flat, greppable marker so it is +self-documenting and discoverable — `grep -rn "API-DRIFT" packages/models/src` +lists every open deviation: + +```ts +// API-DRIFT: (resolve: ) +``` + +Always state a **resolve** condition — the concrete backend/spec change that +makes the workaround unnecessary. Standalone markers: + +- `auth/Auth/behaviors/api.ts` — `checkIsAuthenticated` probes auth via + `getUser({ userId: "self" })` instead of `client.user.checkToken()`. +- `user/User/User.ts` — `registeredAt` falls back to `DateTime.now()` while + `/user/self` omits the field (wrongly making accounts look `isNew`). +- `domain/Domain/Domain.ts` — `findByHostname` via `find(hostname)` is disabled + because route invalidation does not work for shortId lookups. +- `container/Container/ContainerTemplate.ts` — `help.alerts[].status` is a plain + `string` in the spec; `toAlertStatus` narrows it to + `containerTemplateAlertStatuses` and falls back to `"info"`. + +Every `anyStatus*` cast (`base/api/typeFixes.ts`, see that section) is likewise +tagged with an `API-DRIFT` marker at its usage site, naming the operation whose +generated response type omits the status and the resolve condition (drop the +cast for the literal status once the client type declares it). The cast tokens +stay greppable on their own, but the marker records _why_ each one is needed. + +Every update of the generated `@mittwald/api-client` types is also the moment to +revisit the markers: **first fix the breaking changes the new types introduce**, +then resolve the `API-DRIFT` markers whose resolve condition now holds (removing +the resolved markers) and update [docs/api-drift.md](api-drift.md). Fixing the +breaking changes first is deliberate — it is what surfaces the drift in the +first place. + +## Small `lib/` helpers + +Shared low-level utilities under `lib/`, pulled in wherever the same tiny need +recurs: + +- **`replaceUrlTemplateValues(url, values)`** — fill `:key` URL placeholders, + sorting keys longest-first so overlapping names don't partially match + (`lib/replaceUrlTemplateValues.ts`, used e.g. in `file/File/File.ts`). +- **`joinedId(...parts)`** — `parts.join(".")` for composite/query ids + (`lib/joinedId.ts`, used by `base/models/ListQueryModel.ts`). +- **`arrayRemoveItem(items, pred)`** — in-place removal of the first match; + callers must ensure a match exists (`lib/arrayRemoveItem.ts`). +- **`generateRandomHexString` / `generateRandomBase64String` / + `generateRandomAlphanumericString`** — client-side token/name generation. The + hex and base64 variants use `crypto.getRandomValues`; the alphanumeric variant + uses `Math.random()` and is **not** cryptographically secure (`lib/`). + +--- + +# Subtler idioms + +The sections above cover the load-bearing patterns. The ones below are easy to +miss but recur across the package; get them wrong and things break quietly. + +## Per-model folder layout & barrel conventions + +A model lives in `group/Model/` with a fixed file layout. Follow it so the model +looks like every other one: + +``` +container/ # domain group + index.ts # group barrel: re-exports each model folder + Container/ + Container.ts # the model + its Common/Detailed/ListItem/Query/List + types.ts # *Data / *Query types, all MittwaldAPIV2.*-derived + index.ts # model barrel: export * from every file in the folder + behaviors/ + types.ts # the XBehaviors interface + api.ts # apiXBehaviors(client) adapter + ContainerStack.ts # sub-models get their own sibling file + ContainerPort.ts … +``` + +Invariants worth internalizing: + +- **The `index.ts` barrels only re-export** (`export * from "./Container";` …) — + no logic. The public contract is the **root** barrel, never a deep import + ([ADR-0003](adr/0003-public-api-root-barrel.md)). +- **A forgotten `export *` makes a model unreachable**, and nothing inside the + package notices — it imports the model by relative path and compiles fine. + `api-models/ghostmaker-model-exported` therefore checks that every + `@GhostMakerModel({ name })` class is reachable from `src/index.ts`. A model + that is deliberately internal opts out at the class with a reason: + `// eslint-disable-next-line api-models/ghostmaker-model-exported -- internal: `. +- **Naming is mechanical**: interface `XBehaviors`, adapter `apiXBehaviors`, + wire types `XData` / `XListItemData` / `XListQueryData`, model variants + `XCommon` / `XDetailed` / `XListItem`, query pair `XListQuery` / `XList`. +- **Folder is `behaviors/` (plural)**; a couple of older models use singular + `behavior/` (e.g. `fyndr/Lead`, `ai/*PlanOptions`) — match the folder you are + in, don't "fix" it in an unrelated change. + +## `internal.ts` — the internal-module pattern + +Some clusters are **cyclic by design**. In `article/Article/` the base class +`Article`/`ArticleCommon` (`Article.ts`), its subclasses (`articles/*` — +`HostingArticle`, `ServerArticle`, …), the factory that maps a template to a +subclass (`articles/articleFactory.ts`), and the attribute/modifier bases and +their subclasses all reference each other. There is no acyclic import order for +these files individually. + +The fix is the **internal-module pattern**: a single `internal.ts` barrel that +re-exports every file in the cluster, and **every cluster member imports the +other members from `./internal`, never from a sibling file directly**. The +barrel gives the runtime one well-defined evaluation order for the whole cycle. + +Two rules make it work — both easy to break silently: + +1. **The order of the `export *` lines is load-bearing.** The barrel is + evaluated top to bottom, so a base class must be exported **before** the + subclasses that `extends` it, and anything that imports subclasses at module + scope (e.g. `articleFactory`, which imports `ServerArticle` et al.) must come + **last**. Get it wrong and the barrel evaluates + `class ServerArticle extends HostingArticle` before `HostingArticle` exists — + a `TypeError: Class extends value undefined is not a constructor or null` at + import time, which takes out the entire cluster (and every test that touches + it). + +2. **Import cluster classes from `./internal`, not from the sibling file.** A + direct `import { Article } from "./Article"` (or `./ArticleModifier`, …) can + be the first thing to load the cluster, cold-loading `Article.ts` out of + order and tripping the same `Class extends value undefined`. This applies to + tests too: `Article.test.ts` imports `ArticleAttribute`/`ArticleModifier` + from `./internal`, not from their own files, precisely so it cannot pull a + base class in ahead of the barrel. A re-export is a way in as well: a + sub-barrel with `export * from "./Project"` hands the member out past the + cluster barrel just like a direct import, so it re-exports from `../internal` + by name instead (`project/Project/index.ts`). + `api-models/no-deep-cluster-imports` flags both — imports and + `export … from`. + +Because the order is deliberate and non-alphabetical, **no import/export sorting +may touch an `internal.ts` barrel**. No such rule is active in this package +today; if one is ever added, exclude every `internal.ts` from it (otherwise it +re-sorts the `export *` lines alphabetically and reintroduces bug 1). Keep the +blank-line groups as documentation of the tiers (bases → subclasses → factory → +attribute subclasses → modifier subclass) and hand-maintain them; do not let a +formatter reorder the file. + +### When a cluster actually needs an `internal.ts` + +Do **not** add an `internal.ts` to every cluster "to be uniform" — it is only +worth the hand-maintained ordering when the cluster has a genuine **load-time** +reference to a sibling that also sits inside an import cycle. The decision rule +is _load-time vs deferred_, not _"references a sibling at all"_: + +**Genuine load-time refs (these warrant `internal.ts`, they are unguarded):** + +- `class X extends ` — including the mixin form + `extends WithData()(Sibling)`. Evaluated when the class declaration runs; + if `Sibling` is not initialized yet you get `Class extends value undefined`. +- `static field = ` — e.g. `File`'s + `static inMemoryFile = new File(...)` reaching `FileMeta.ofFile`. Runs at + module load. +- An **eager constructor field** that touches another model's statics under a + cycle — see trap #3 in _Traps that `tsc` does not catch_ (deep-import + prefer + lazy). + +**Deferred / erased — these are safe and do NOT justify an `internal.ts`:** + +- A sibling value used **only inside method bodies** (`static get()`, + `findDetailed()`, …). Method bodies run at call time, not import time. +- `import type { … }` — fully erased, no runtime binding. +- `@GhostMakerModel` + a constructor parameter _typed_ as a sibling. This looks + dangerous but `emitDecoratorMetadata` is resilient here: a **union** param + type (`ContributorExtension | Extension`) degrades to `Object` (no ref at + all), and a **single-class** param type emits a `typeof`-**guarded** ref + (`typeof App !== "undefined" && App ? App : Object`) that falls back to + `Object` instead of throwing. Verify with a one-off + `ts.transpileModule(src, { emitDecoratorMetadata: true })` and grep the + `design:paramtypes` line before assuming a decorated model needs routing. + +Applying this rule, the only clusters that qualify today are the three that +already have an `internal.ts`: `article/Article` (`extends` chains + +`articleFactory` force-load), `file/File` (`File` static-init sentinel), and +`project` (eager `HardwareSpecs` ctor fields). `marketplace/Extension` _looks_ +like a candidate (cycle +`Extension → ExtensionPricePlan → ExtensionPricePlanVariant → Extension`, +`@GhostMakerModel`, ctor param typed `Extension`) but is safe: the param is a +union → `Object`, and every `Extension` value use is inside a method body. + +## Behavior-side response mapping & error translation + +Adapters (`behaviors/api.ts`) are the only place that touches `api-client`. The +mapping is uniform: + +- **Assert the status with `validateResponse(response, 200 | [403, 404] | …)`** + — it narrows the response union so `response.data` is typed. For "found or + not" lookups, return `data` on the success status and let `validateResponse` + accept the not-found status: + ```ts + if (response.status === 200) return response.data; + validateResponse(response, [403, 404]); // throws on anything else + ``` +- **List operations build the envelope by hand**, deriving the total via + `resolveTotalCount(response)`: + ```ts + return { items: response.data, totalCount: resolveTotalCount(response) }; + ``` + `resolveTotalCount` (`base/api/resolveTotalCount.ts`) is the **single source + of truth** for a list's total count: it prefers the `x-pagination-totalcount` + header and falls back to the returned page length, and — unlike the old + `extractTotalCountHeader`, which **throws** when the header is absent — it + never throws. A route that starts sending the header is picked up + automatically, with the page-length fallback until then, so no per-route audit + is needed. The total is derived **here, in the behavior layer**; models must + never compute it (no `this.totalCount = items.length` in a `*List` constructor + — take a `totalCount` parameter and pass through the value the behavior + returned). When the page items are nested inside the response rather than + being `response.data` itself, pass the count explicitly as the second argument + (e.g. `fyndr/Lead` / `fyndr/UnlockedLead`: + `resolveTotalCount(response, response.data.leads.length)`). + `extractTotalCountHeader` is no longer used anywhere in the package. +- **`400`-family validation errors become a `ValidationError`** via + `withResponseValidation` (used inside `validateResponse`). Gotcha: it wraps a + **synchronous** `try/catch` around the status assertion — it translates the + thrown `ApiClientError`, it does **not** await the network promise. Don't + expect it to catch a rejected fetch on its own. + +Used in: `base/api/validateResponse.ts`, `base/api/withResponseValidation.ts`, +every `*/behaviors/api.ts` (e.g. `container/Container/behaviors/api.ts`). + +## Error classes & conventions + +Three error shapes, and only one of them is an `Error`: + +- **`ObjectNotFoundError extends Error`** — thrown by `assertObjectFound`; + carries `type` (resolved via ghostmaker's `getModelName`) and `refName`, and + calls `Object.setPrototypeOf(this, ObjectNotFoundError.prototype)` so + `instanceof` survives transpilation to ES5 (`errors/ObjectNotFoundError.ts`). +- **`ValidationError`** — a **plain class, not an `Error`**. Holds + `errors: ValidationErrorObject[]` and is built with + `ValidationError.fromResponse(response, { pathMappings, typeMappings })`, + which returns `undefined` for non-validation responses. + `pathMappings`/`typeMappings` let a caller rename API field paths/types into + its own vocabulary via `performMappings` (`errors/ValidationError/`). +- **`FileUploadError`** — also a plain class; aggregates per-file `failures` + (`{ file, error }[]`) for a bulk upload (`errors/FileUploadError.ts`). + +Because `ValidationError`/`FileUploadError` are not `Error` subclasses, `catch` +blocks must test them with `instanceof`, not by reading `.message`. + +## `classifyFileUploadError` — message-substring rule table + +The upload API returns free-text messages; the model maps them to stable codes +with an ordered rule table (`code` + `test(message)`), matched against the +**lower-cased** message, returning the first hit. `getMaxUploadSizeInMB` pulls +the numeric limit out of the "exceeds the limit of N bytes" message. This is the +idiom for "turn an opaque server string into a UI-switchable code" — extend the +`rules` array rather than scattering `message.includes(...)` at call sites. + +```ts +// file/File/behaviors/classifyFileUploadError.ts +const rules: FileUploadErrorRule[] = [ + { code: "malwareInfected", test: (m) => m.includes("infected with malware") }, + { + code: "fileTooLarge", + test: (m) => m.includes("exceeds the limit of") && m.includes("bytes"), + }, + // … +]; +export const classifyFileUploadError = (message: string): string | undefined => + rules.find((rule) => rule.test(message.toLowerCase()))?.code; +``` + +## `withAxiosRequestConfig` + the `onBeforeRequest` handler registry + +Model methods thread an optional `AxiosRequestConfig` down to the adapter, which +passes it through `withAxiosRequestConfig(options)`. That merges the per-call +config onto the outgoing request **and** runs every globally registered +pre-request handler. Consumers hook in once at startup via +`registerDefaultOnBeforeRequestHandler` (a `Set`, so handlers stack); it is one +of the few things re-exported from the root barrel. + +```ts +// base/api/withModelRequestOptions.ts +export const withAxiosRequestConfig = ( + requestOptions: AxiosRequestConfig = {}, +): Commons.RequestOptions => ({ + onBeforeRequest: (config) => { + Object.assign(config.requestConfig, requestOptions); + executeDefaultOnBeforeRequestHandlers(config); + }, +}); +``` + +Used in: `base/api/withModelRequestOptions.ts`, `base/api/onBeforeRequest.ts`, +every list/detail adapter that accepts options (~27 sites). + +## `typeFixes` — `NNN as any` status-code escape hatch + +When the generated OpenAPI types omit a status the endpoint really returns, +adapters use the pre-cast constants from `base/api/typeFixes.ts` +(`anyStatus400`, `anyStatus403`, `anyStatus404`, `anyStatus409`, …) so +`validateResponse(response, anyStatus409)` type-checks. Treat every use as a +flag that the API spec and reality disagree — prefer fixing the spec, and don't +invent new `as any` casts inline; add/extend the constant. Every usage carries +an `API-DRIFT` marker (see that section) naming the operation and resolve +condition. + +```ts +export const anyStatus409 = 409 as any; +``` + +Used in: `base/api/typeFixes.ts`, e.g. `order/Order/behaviors/api.ts`, +`database/MySql/behaviors/api.ts`, `app/AppInstallation/behaviors/api.ts`. + +## Injected `AccessTokenProvider` — credentials stay out of the core + +Anything needing an authenticated URL or a short-lived token (avatars, invoice +PDFs, protected file downloads/uploads) takes an **optional injected** +`XAccessTokenProvider` rather than knowing how tokens are minted. The model +calls optional methods on it; the consumer supplies the implementation. This +keeps auth policy out of the agnostic core and makes the token flow testable. + +```ts +// file/FileAccessToken/FileAccessTokenProvider.ts +export interface FileAccessTokenProvider { + createUploadToken?: () => Promise; + getDownloadToken?: (fileId: string, requestConfig?: AxiosRequestConfig) => Promise; +} + +// project/Project/Project.ts — model exposes its own provider +public get fileAccessTokenProvider(): FileAccessTokenProvider { + return new ProjectAvatarAccessTokenProvider(this); +} +``` + +Recurs across ~10 models: `file/File/`, +`server/Server/ServerAvatarAccessTokenProvider.ts`, +`customer/Customer/CustomerAvatarAccessTokenProvider.ts`, +`invoice/Invoice/InvoicePdfAccessTokenProvider.ts`, +`marketplace/Contributor/*AccessTokenProvider.ts`. + +## Sentinel instance + guard (`File.inMemoryFile`) + +A shared "not a real, persisted entity" placeholder is exposed as a **static +singleton** and matched by identity, paired with a guard that fails fast when a +method needs a real id. Reuse the instance; don't test for the sentinel by id +string. + +```ts +// file/File/File.ts +public static inMemoryFile = new File("inmem"); +public get isInMemoryFile() { return this === File.inMemoryFile; } +public assertNotInMemoryFile() { invariant(!this.isInMemoryFile, "Expected not in-memory file"); } +``` + +Used in: `file/File/File.ts` (e.g. `url` getter and download flows call +`assertNotInMemoryFile()` first). + +## `DomFile` — the DOM touchpoint is aliased, not hidden + +The core is DOM-free ([ADR-0002](adr/0002-agnostic-core-two-packages.md)), but +uploads genuinely need the browser `File` type. Rather than sprinkle the global +`File` around, it is aliased once as `DomFile` (value **and** type) so the +single legitimate DOM dependency is explicit and greppable, and the model's own +class is also named `File` without collision. + +```ts +// file/File/types.ts +export const DomFile = File; // the browser global +export type DomFile = File; +``` + +Used in: `file/File/types.ts`, `file/File/File.ts` (`upload(file: DomFile, …)`), +`file/File/FileContent.ts`. + +## `LocalizedText` — process-global language with `de` fallback + +Localized API strings are wrapped in `LocalizedText`. The current language is a +**static on the class** (`LocalizedText.setLanguage(...)`), not per-instance, +and lookups fall back to `de` when the active language is missing. +`fromJsonString` parses leniently: invalid JSON or a bare string is treated as +`de` text rather than throwing. + +```ts +// common/LocalizedText.ts +const value = this.data[LocalizedText.language] ?? this.data[defaultLanguage]; // defaultLanguage = "de" +``` + +Gotchas: `setLanguage` mutates a process-global for every instance (and leaks +across tests if not reset); the fallback is specifically `de`, not "first +available"; and the lookup uses `if (!value)`, so an empty string `""` is +treated as _missing_ and falls back too. + +Used in: `common/LocalizedText.ts`. + +## Immutability enforcement is uneven — know which is which + +The README states model instances and their `data` are to be **treated** as +immutable. What is actually enforced today: + +- **`ListDataModel` shallow-freezes its `items`** with `Object.freeze` + (`base/models/ListDataModel.ts`); a few models freeze their own derived arrays + the same way (`domain/Ingress/Ingress.ts`, `user/Feedback/Feedback.ts`). +- **`DataModel.data` is _not_ frozen yet** — `base/models/DataModel.ts` carries + a `// todo: fix deep freeze`. So the deep-freeze the README describes is the + intended invariant, not a current runtime guarantee. +- **The instance itself is not frozen.** +- **Every instance property is `readonly`** (type-level; tsc-enforced) and there + is no mutable instance state anywhere — all fields are assigned once in the + declaring class's constructor, with no post-construction mutation in the + package. +- **The `*Article` facets are stateless lazy getters** — `HostingArticle` + (`hardwareSpecs`/`baseStorageAttribute`/`storageModifier`), `ServerArticle` + (`machineTypeSpecs`), `StorageArticle` (`bytes`): computed on access, never in + the constructor, holding **no cached state**. Laziness is load-bearing (not a + perf tweak): they use `getRequiredAttribute`/`getRequiredModifier`, which + **throw** when the attribute is absent, and the facets are only conditionally + valid per subtype (the code picks `machineTypeSpecs` vs `hardwareSpecs` via + `isOfType(ServerArticle)`). Eager ctor-init was tried and **breaks + construction** — the HostingOrderRequest flow builds a `HostingArticle` with + no `StorageArticleModifier` (verified: 5 vitest failures). So compute on + access. + +Practical rule: never mutate `data` or a frozen list; construct a new model +instead. Don't rely on a runtime error to catch an accidental `data` mutation. + +## Constructors are where wire data becomes domain data + +Value conversion, normalization, and relation-wiring happen **once in the +constructor**, never lazily at each getter. Recurring moves: `.trim()` string +fields, coalesce nullables with `?? 0` / `?? default` before wrapping, and +derive related references I/O-free with `.ofId`. + +```ts +// container/Container/Container.ts (ContainerCommon constructor) +this.description = data.description.trim(); +this.statusSetAt = DateTime.fromISO(data.statusSetAt); +this.cpuLimit = data.deploy?.resources?.limits?.cpus; // optional chaining, kept optional +this.project = Project.ofId(data.projectId); // relation without a fetch +``` + +Gotcha: **normalization is selective, not a global rule.** `.trim()` is applied +only in domains that need it — don't assume every API string is trimmed. And the +two nullable idioms are not interchangeable: `?? default` preserves `false`, +`0`, and `""`, whereas a truthiness check +(`data.avatarRefId ? File.ofId(...) : undefined`) discards them. Pick +deliberately. + +Used across every `*Common` constructor, e.g. +`container/Container/Container.ts`, `invoice/Invoice/Invoice.ts`, +`server/Server/Server.ts`. + +## `as const` tuples as runtime vocabulary + literal union + +Fixed vocabularies are declared **once** as an `as const` tuple and the literal +union is derived from it with `(typeof x)[number]`. The array is the runtime +allowlist and the type in one place, so they cannot drift apart. (The package +uses this rather than `satisfies` — outside of tests there are no `satisfies` +expressions under `packages/models/src`.) + +```ts +// invoice/Invoice/types.ts +export const invoiceStatusList = [ + "PAID", + "PARTIALLY_PAID", + "OVERPAID", + "NEW", + "CONFIRMED", + "DENIED", +] as const; +export type InvoiceStatus = NonNullable[number] & + (typeof invoiceStatusList)[number]; + +// common/LocalizedText.ts +const supportedLanguages = ["de", "en"] as const; +export type LocalizedTextLanguage = (typeof supportedLanguages)[number]; +``` + +When the generated field is a plain `string`, the tuple is also the narrowing +step: look the incoming value up in it at the mapping site instead of casting +with `as`, choose an explicit fallback for unknown values, and tag the spot with +an `API-DRIFT` marker (see that section): + +```ts +// container/Container/ContainerTemplate.ts +const toAlertStatus = (status: string): ContainerTemplateAlertStatus => + containerTemplateAlertStatuses.find((known) => known === status) ?? "info"; +``` + +Used in: `common/LocalizedText.ts`, `container/Container/types.ts`, +`invoice/Invoice/types.ts`, `marketplace/Extension/types.ts`. + +## Class member ordering: static → fields → constructor → methods + +Within a class, members follow a fixed group order: static members first, then +instance fields, then accessors, the constructor, and finally instance methods — +with **public before protected before private** inside each of those. The shape +of the object is declared before the behavior that operates on it. + +Within a group, members are sorted in **natural order** by name, so they read +`find*` before `get*`, `create` before `update`, etc. This means the +meaning-based pairing (`findDetailed` sitting next to `getDetailed`) is **not** +preserved — natural sort groups all `find*` together, then all `get*`. That is a +deliberate trade of "pairs read together" for a single deterministic order. + +No lint rule enforces this order in this package (`eslint.config.js` carries no +class-member sorting rule); it is a convention, kept by hand. Top-level +declaration order between classes is a separate concern: in the aggregate +families and the `internal.ts` clusters it is load-bearing, so no tool may sort +it — see the `internal.ts` section. diff --git a/packages/models/eslint-rules/ghostDecorator.js b/packages/models/eslint-rules/ghostDecorator.js new file mode 100644 index 00000000..9f3f7cb8 --- /dev/null +++ b/packages/models/eslint-rules/ghostDecorator.js @@ -0,0 +1,50 @@ +const GHOST_DECORATOR = "GhostMakerModel"; + +const propertyName = (key) => { + if (!key) return undefined; + if (key.type === "Identifier") return key.name; + if (key.type === "Literal" && typeof key.value === "string") return key.value; + return undefined; +}; + +/** + * The `name` of a class's `@GhostMakerModel({ name })` decorator as its string + * `Literal` node, so a rule can both read the name and report or fix it in + * place. + * + * Returns `undefined` when the class carries no such decorator, when the + * decorator has no `name` (the abstract bases `ReferenceModel`/`ListQueryModel` + * pass only `getId`), or when `name` is not a static string (the scoped-AI + * factory's `name: cfg.ghostName`) — nothing to check statically in any of + * these cases. + * + * @param {import("estree").Node & { decorators?: any[] }} classNode + * @returns {(import("estree").Literal & { value: string }) | undefined} + */ +const ghostNameLiteral = (classNode) => { + for (const decorator of classNode.decorators ?? []) { + const expr = decorator.expression; + if ( + !expr || + expr.type !== "CallExpression" || + expr.callee?.type !== "Identifier" || + expr.callee.name !== GHOST_DECORATOR + ) { + continue; + } + const arg = (expr.arguments ?? [])[0]; + if (!arg || arg.type !== "ObjectExpression") continue; + for (const prop of arg.properties ?? []) { + if (prop.type !== "Property") continue; + if (propertyName(prop.key) !== "name") continue; + const value = prop.value; + if (value?.type === "Literal" && typeof value.value === "string") { + return value; + } + return undefined; + } + } + return undefined; +}; + +module.exports = { ghostNameLiteral }; diff --git a/packages/models/eslint-rules/ghostmaker-model-exported.js b/packages/models/eslint-rules/ghostmaker-model-exported.js new file mode 100644 index 00000000..d265954e --- /dev/null +++ b/packages/models/eslint-rules/ghostmaker-model-exported.js @@ -0,0 +1,208 @@ +const { existsSync, readFileSync, statSync } = require("node:fs"); +const { dirname, join, relative, resolve } = require("node:path"); +const { ghostNameLiteral } = require("./ghostDecorator.js"); +const { readReExports } = require("./reExports.js"); +const { resolveModule } = require("./resolveModule.js"); + +/** + * Enforces that every `@GhostMakerModel({ name })` class is reachable through + * the package's root barrel (`src/index.ts`). + * + * `package.json#exports` opens only `"."` (see docs/adr/0003), so the root + * barrel is the entire public contract: a model that never makes it into a + * domain barrel is unreachable for consumers, with no deep-import fallback — + * and nothing else notices, because the package itself imports the model + * through relative paths and compiles fine. This is the cheapest mistake to + * make (build the model, forget the `export *`) and the most expensive to + * discover (in a consumer, after release). + * + * A model that is deliberately internal opts out at the class, with a reason: + * + * // eslint-disable-next-line api-models/ghostmaker-model-exported -- internal: + * + * @GhostMakerModel({ name: "SomeInternalModel" }) + * + * Intentionally NOT flagged: + * + * - Decorators without a static string `name` (the abstract bases + * `ReferenceModel`/`ListQueryModel`, and the scoped-AI factory's + * `name: cfg.ghostName`): a class expression built inside a factory has no + * exported binding of its own, and the abstract bases are not models. + */ + +/** Walks up from `startDir` to the directory holding the package manifest. */ +const findPackageRoot = (startDir) => { + let dir = startDir; + for (;;) { + if (existsSync(join(dir, "package.json"))) return dir; + const parent = dirname(dir); + if (parent === dir) return null; + dir = parent; + } +}; + +const mtimeOf = (file) => { + try { + return statSync(file).mtimeMs; + } catch { + return null; + } +}; + +const ALL = true; + +/** + * Walks the re-export graph out of `entry` and returns, per file, which of its + * names the package publishes: `ALL` for a file reached through an unbroken + * chain of `export *`, or the set of names pulled out of it by an `export { … } + * from`. + * + * Names have to be carried THROUGH intermediate barrels: several domains expose + * a hand-ordered `internal.ts` cluster with `export { A, B } from + * "./internal.js"`, and the classes themselves sit one `export *` further down. + * A traversal that stops at the named re-export declares those models + * unexported — the whole `article` and `project` clusters. Pushing the + * requested names down every `export *` of the barrel over-approximates (a name + * is attributed to all of the barrel's members, not just the one declaring it), + * which is harmless: members of one cluster cannot share an exported name + * anyway, or the barrel itself would be ambiguous. + * + * `barrels` collects the mtime of every file that carried a re-export, so the + * result can be invalidated without re-stating the whole tree. + */ +const readSurface = (entry) => { + const publicNames = new Map(); + const barrels = new Map(); + + const merge = (file, names) => { + const current = publicNames.get(file); + if (current === ALL) return false; + if (names === ALL) { + publicNames.set(file, ALL); + return true; + } + if (!current) { + publicNames.set(file, new Set(names)); + return true; + } + let grew = false; + for (const name of names) { + if (!current.has(name)) { + current.add(name); + grew = true; + } + } + return grew; + }; + + merge(entry, ALL); + const queue = [entry]; + + while (queue.length > 0) { + const file = queue.pop(); + const inherited = publicNames.get(file); + let src; + try { + src = readFileSync(file, "utf8"); + } catch { + continue; + } + if (!src.includes("from")) continue; + + let sawReExport = false; + for (const { spec, names } of readReExports(src)) { + if (!spec.startsWith(".")) continue; + const target = resolveModule(resolve(dirname(file), spec)); + if (!target) continue; + sawReExport = true; + + const carried = names === "*" ? inherited : new Set(names); + + if (merge(target, carried)) queue.push(target); + } + if (sawReExport) barrels.set(file, mtimeOf(file)); + } + + return { publicNames, barrels }; +}; + +const surfaceCache = new Map(); + +const getSurface = (packageRoot) => { + const cached = surfaceCache.get(packageRoot); + if (cached) { + let stale = false; + for (const [file, mtime] of cached.barrels) { + if (mtimeOf(file) !== mtime) { + stale = true; + break; + } + } + if (!stale) return cached; + } + const surface = readSurface(join(packageRoot, "src", "index.ts")); + surfaceCache.set(packageRoot, surface); + return surface; +}; + +/** @type {import("eslint").Rule.RuleModule} */ +const rule = { + meta: { + type: "problem", + docs: { + description: + "A @GhostMakerModel class must be reachable through the root barrel.", + }, + schema: [], + messages: { + notExportedFromModule: + 'Model "{{name}}" is not exported from its own module, so the barrel cannot re-export it. Write `export class {{name}}`.', + notInBarrel: + 'Model "{{name}}" is not reachable through the root barrel (src/index.ts). Add `export * from "./{{basename}}.js"` to {{barrel}} — package.json#exports only opens ".", so an unexported model has no deep-import fallback. If it is deliberately internal, disable this rule on the class with a reason.', + }, + }, + + create(context) { + const filename = context.filename ?? context.getFilename(); + const packageRoot = findPackageRoot(dirname(filename)); + if (!packageRoot) return {}; + + const check = (node) => { + if (!ghostNameLiteral(node)) return; + + if (node.type !== "ClassDeclaration" || !node.id) return; + if (node.parent?.type !== "ExportNamedDeclaration") { + context.report({ + node: node.id, + messageId: "notExportedFromModule", + data: { name: node.id.name }, + }); + return; + } + + const published = getSurface(packageRoot).publicNames.get(filename); + if (published === ALL || published?.has(node.id.name)) return; + + const basename = filename + .replace(/\.tsx?$/, "") + .split("/") + .pop(); + context.report({ + node: node.id, + messageId: "notInBarrel", + data: { + name: node.id.name, + basename, + barrel: relative(packageRoot, join(dirname(filename), "index.ts")), + }, + }); + }; + + return { + ClassDeclaration: check, + ClassExpression: check, + }; + }, +}; + +module.exports = rule; diff --git a/packages/models/eslint-rules/ghostmaker-name-matches-class.js b/packages/models/eslint-rules/ghostmaker-name-matches-class.js new file mode 100644 index 00000000..578cd51b --- /dev/null +++ b/packages/models/eslint-rules/ghostmaker-name-matches-class.js @@ -0,0 +1,61 @@ +const { ghostNameLiteral } = require("./ghostDecorator.js"); + +/** + * Enforces that a `@GhostMakerModel({ name: "..." })` decorator's static `name` + * exactly matches the name of the class it decorates. + * + * The ghost name is the identity under which `@mittwald/react-ghostmaker` + * resolves a model, so a stray/copy-pasted name silently points the resolution + * at the wrong model. Keeping `name` === class name is a mandatory pattern for + * every concrete model in the package. + * + * Intentionally NOT flagged (nothing to check statically): + * + * - Abstract base classes that pass only `getId` and no `name` (`ReferenceModel`, + * `ListQueryModel`) — no static name to compare. + * - A `name` whose value is not a string literal, e.g. the scoped-AI factory's + * `name: cfg.ghostName` — resolved at runtime, verified at its call sites. + */ + +/** @type {import("eslint").Rule.RuleModule} */ +const rule = { + meta: { + type: "problem", + fixable: "code", + docs: { + description: + "A @GhostMakerModel `name` must equal the decorated class name.", + }, + schema: [], + messages: { + nameMismatch: + 'GhostMakerModel name "{{name}}" must match the class name "{{className}}". The ghost name is the model\'s identity — keep them in sync.', + }, + }, + + create(context) { + const check = (node) => { + const className = node.id?.name; + if (!className) return; + + const value = ghostNameLiteral(node); + if (!value || value.value === className) return; + + context.report({ + node: value, + messageId: "nameMismatch", + data: { name: value.value, className }, + fix: value.range + ? (fixer) => fixer.replaceTextRange(value.range, `"${className}"`) + : undefined, + }); + }; + + return { + ClassDeclaration: check, + ClassExpression: check, + }; + }, +}; + +module.exports = rule; diff --git a/packages/models/eslint-rules/index.js b/packages/models/eslint-rules/index.js new file mode 100644 index 00000000..ada6f66a --- /dev/null +++ b/packages/models/eslint-rules/index.js @@ -0,0 +1,17 @@ +/** + * Local ESLint plugin for `@mittwald/api-models`. + * + * All three rules guard invariants the TypeScript compiler cannot see: the + * hand-ordered `internal.ts` barrels (load order), the ghost name of a model + * (runtime identity) and the reach of a model through the root barrel (the + * public contract). The first two may not be disabled — see + * docs/implementation-patterns.md. + */ + +module.exports = { + rules: { + "no-deep-cluster-imports": require("./no-deep-cluster-imports.js"), + "ghostmaker-name-matches-class": require("./ghostmaker-name-matches-class.js"), + "ghostmaker-model-exported": require("./ghostmaker-model-exported.js"), + }, +}; diff --git a/packages/models/eslint-rules/no-deep-cluster-imports.js b/packages/models/eslint-rules/no-deep-cluster-imports.js new file mode 100644 index 00000000..b10f2901 --- /dev/null +++ b/packages/models/eslint-rules/no-deep-cluster-imports.js @@ -0,0 +1,147 @@ +const { readFileSync, existsSync, statSync } = require("node:fs"); +const { dirname, join, relative, resolve } = require("node:path"); +const { JS_EXT_RE, SOURCE_EXTS, resolveModule } = require("./resolveModule.js"); +const { readReExports } = require("./reExports.js"); + +/** + * Enforces the internal-module pattern in packages that use `internal.ts` + * barrels: an import or re-export (`export … from`) of a cluster member (a + * module re-exported by some `internal.ts`) must go THROUGH that `internal.ts`, + * never via a deep sibling/member path. Keeping a single hand-ordered barrel as + * the only entry point is what makes the cluster robust against import + * reordering — a stray deep import can otherwise trigger "Class extends value + * undefined" / undefined-at-load crashes. + * + * See docs/implementation-patterns.md › "internal.ts — the internal-module + * pattern". + */ + +// Cache each internal.ts's member set, keyed by file path + mtime. +const clusterCache = new Map(); + +const readCluster = (internalFile) => { + const mtimeMs = statSync(internalFile).mtimeMs; + const cached = clusterCache.get(internalFile); + if (cached && cached.mtimeMs === mtimeMs) return cached.cluster; + + const dir = dirname(internalFile); + const src = readFileSync(internalFile, "utf8"); + const members = new Set(); + for (const { spec } of readReExports(src)) { + if (!spec.startsWith(".")) continue; + const resolved = resolveModule(resolve(dir, spec)); + if (resolved) members.add(resolved); + } + const cluster = { internalFile, members }; + clusterCache.set(internalFile, { mtimeMs, cluster }); + return cluster; +}; + +// Walk up from `startDir` collecting every ancestor `internal.ts`. +const findInternalFiles = (startDir) => { + const found = []; + let dir = startDir; + for (;;) { + for (const ext of SOURCE_EXTS) { + const candidate = join(dir, "internal" + ext); + if (existsSync(candidate)) found.push(candidate); + } + const parent = dirname(dir); + if (parent === dir) break; + dir = parent; + } + return found; +}; + +const toImportPath = (fromFile, targetInternal, originalSpec) => { + let rel = relative(dirname(fromFile), targetInternal).replace(/\\/g, "/"); + const emittedExt = JS_EXT_RE.exec(originalSpec); + rel = rel.replace(/\.(ts|tsx)$/, emittedExt ? emittedExt[0] : ""); + if (!rel.startsWith(".")) rel = "./" + rel; + return rel; +}; + +/** + * Whether swapping the specifier for the barrel keeps the statement's meaning, + * so it can be auto-fixed. Not for a `default` import or re-export: internal.ts + * forwards its members by name via `export *`, which drops default exports, so + * those have to become named by hand. Not for `export * from` either: pointed + * at the barrel it would re-export the whole cluster instead of the one + * module. + */ +const isPathSwapSafe = (node) => { + if (node.type === "ExportAllDeclaration") return false; + return !(node.specifiers ?? []).some( + (specifier) => + specifier.type === "ImportDefaultSpecifier" || + (specifier.type === "ImportSpecifier" && + specifier.imported?.name === "default") || + (specifier.type === "ExportSpecifier" && + specifier.local?.name === "default"), + ); +}; + +/** @type {import("eslint").Rule.RuleModule} */ +const rule = { + meta: { + type: "problem", + fixable: "code", + docs: { + description: + "Import and re-export cluster members through their internal.ts barrel, not via a deep sibling/member path.", + }, + schema: [], + messages: { + useInternal: + '{{kind}} "{{name}}" through the cluster barrel "{{internal}}" instead of the deep path "{{spec}}" (internal-module pattern — keeps load order robust).', + }, + }, + + create(context) { + const filename = context.filename ?? context.getFilename(); + + const check = (node) => { + if (!node.source) return; + const spec = node.source.value; + if (typeof spec !== "string" || !spec.startsWith(".")) return; + + const target = resolveModule(resolve(dirname(filename), spec)); + if (!target) return; + + for (const internalFile of findInternalFiles(dirname(target))) { + // The barrel itself is allowed to reference its members directly. + if (internalFile === filename) continue; + const { members } = readCluster(internalFile); + if (!members.has(target)) continue; + // Already importing via this internal.ts? (target would be the barrel) + if (target === internalFile) return; + + const internal = toImportPath(filename, internalFile, spec); + context.report({ + node, + messageId: "useInternal", + data: { + kind: node.type === "ImportDeclaration" ? "Import" : "Re-export", + name: spec.split("/").pop() ?? spec, + internal, + spec, + }, + fix: + isPathSwapSafe(node) && node.source.range + ? (fixer) => + fixer.replaceTextRange(node.source.range, `"${internal}"`) + : undefined, + }); + return; + } + }; + + return { + ImportDeclaration: check, + ExportNamedDeclaration: check, + ExportAllDeclaration: check, + }; + }, +}; + +module.exports = rule; diff --git a/packages/models/eslint-rules/package.json b/packages/models/eslint-rules/package.json new file mode 100644 index 00000000..97133687 --- /dev/null +++ b/packages/models/eslint-rules/package.json @@ -0,0 +1,9 @@ +{ + "name": "eslint-plugin-api-models", + "private": true, + "version": "0.0.0", + "type": "commonjs", + "description": "Local ESLint rules guarding @mittwald/api-models invariants", + "license": "MIT", + "main": "index.js" +} diff --git a/packages/models/eslint-rules/reExports.js b/packages/models/eslint-rules/reExports.js new file mode 100644 index 00000000..272f2d44 --- /dev/null +++ b/packages/models/eslint-rules/reExports.js @@ -0,0 +1,41 @@ +/** + * Reads the re-exports (`export * from`, `export { … } from`, each also as + * `export type`) out of a module's source text. Both the cluster rule and the + * public-surface rule walk barrels through this one parser, so they agree on + * what counts as a re-export. + * + * Comments are stripped first: a commented-out re-export must not count — that + * is exactly the edit these rules have to catch. + */ + +const stripComments = (src) => + src.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/[^\n]*/g, "$1"); + +const reExportRe = + /\bexport\s+(?:type\s+)?(\*|\{[^}]*\})\s+from\s+["']([^"']+)["']/g; + +const exportedNames = (clause) => + clause + .slice(1, -1) + .split(",") + .map((name) => + name + .trim() + .replace(/^type\s+/, "") + .split(/\s+as\s+/)[0] + .trim(), + ) + .filter(Boolean); + +/** + * @param {string} src + * @returns {{ spec: string; names: "*" | string[] }[]} Per re-export its + * specifier and either `"*"` or the names it pulls out of the target. + */ +const readReExports = (src) => + [...stripComments(src).matchAll(reExportRe)].map(([, clause, spec]) => ({ + spec, + names: clause === "*" ? "*" : exportedNames(clause), + })); + +module.exports = { readReExports }; diff --git a/packages/models/eslint-rules/resolveModule.js b/packages/models/eslint-rules/resolveModule.js new file mode 100644 index 00000000..45f6aff1 --- /dev/null +++ b/packages/models/eslint-rules/resolveModule.js @@ -0,0 +1,41 @@ +const { existsSync } = require("node:fs"); +const { join } = require("node:path"); + +const SOURCE_EXTS = [".ts", ".tsx"]; +const JS_EXT_RE = /\.(js|jsx|mjs|cjs)$/; + +/** + * Resolves a relative import/export specifier to the source file on disk. + * + * This package emits NodeNext ESM, so every relative specifier carries the + * EMITTED `.js` extension while the file on disk is the `.ts` source. Stripping + * that extension before trying `.ts`/`.tsx` is load-bearing: a resolver that + * naively appends looks for `Foo.js.ts`, never finds anything, and turns the + * calling rule into a silent no-op that looks green. + * + * @param {string} base Absolute path of the specifier, extension included. + * @returns {string | null} Absolute path of the source file, or null. + */ +const resolveModule = (base) => { + const candidates = [base]; + if (JS_EXT_RE.test(base)) candidates.push(base.replace(JS_EXT_RE, "")); + + for (const candidate of candidates) { + for (const ext of SOURCE_EXTS) { + if (existsSync(candidate + ext)) return candidate + ext; + } + } + for (const candidate of candidates) { + for (const ext of SOURCE_EXTS) { + const indexed = join(candidate, "index" + ext); + if (existsSync(indexed)) return indexed; + } + } + return null; +}; + +module.exports = { + JS_EXT_RE, + SOURCE_EXTS, + resolveModule, +}; diff --git a/packages/models/eslint.config.js b/packages/models/eslint.config.js index f713aa51..0b003a6d 100644 --- a/packages/models/eslint.config.js +++ b/packages/models/eslint.config.js @@ -1,3 +1,97 @@ +import apiModels from "eslint-plugin-api-models"; +import globals from "globals"; +import tseslint from "typescript-eslint"; import baseConfig from "../../config/eslint.config.base.js"; -export default baseConfig; +export default tseslint.config( + ...baseConfig, + { + plugins: { + "api-models": apiModels, + }, + rules: { + // Load-bearing guards for invariants tsc cannot see. Do not disable: the + // hand-ordered internal.ts barrels crash at runtime when bypassed, and a + // mismatching ghost name resolves silently to the wrong model. + // See docs/implementation-patterns.md. + "api-models/no-deep-cluster-imports": "error", + "api-models/ghostmaker-name-matches-class": "error", + // package.json#exports opens only ".", so a model missing from the root + // barrel is unreachable for consumers and nothing else notices. + "api-models/ghostmaker-model-exported": "error", + // The base model machinery is intentionally generic and uses `any` in type + // positions (`Class`, the type-level API fixes in base/api) where a + // concrete type is impossible. Relaxed package-wide rather than contorting + // the existing types; tighten later if desired. + "@typescript-eslint/no-explicit-any": "off", + // The core stays free of React, UI and the DOM (docs/adr/0002). React code + // belongs in @mittwald/api-models-react; downloads return data instead of + // touching `document`/`window`. + "no-restricted-imports": [ + "error", + { + paths: [ + { + name: "react", + message: + "The core is React-free (ADR-0002); React code belongs in @mittwald/api-models-react.", + }, + { + name: "react-dom", + message: + "The core is React-free (ADR-0002); React code belongs in @mittwald/api-models-react.", + }, + { + name: "@mittwald/flow-react-components", + message: + "The core carries no UI (ADR-0002); UI belongs in the consumer.", + }, + { + name: "@mittwald/react-ghostmaker", + message: + "The ghostmaker main entry loads React (ADR-0002); import from @mittwald/react-ghostmaker/model instead.", + }, + ], + patterns: [ + { + group: [ + "react/*", + "react-dom/*", + "@mittwald/flow-react-components/*", + "@tabler/*", + ], + message: "The core carries no React or UI (ADR-0002).", + }, + ], + }, + ], + "no-restricted-globals": [ + "error", + { + name: "document", + message: + "The core is DOM-free (ADR-0002); return data and let the consumer touch the DOM.", + }, + { + name: "window", + message: + "The core is DOM-free (ADR-0002); return data and let the consumer touch the DOM.", + }, + ], + }, + }, + { + // The local ESLint plugin is CommonJS (package.json "type": "commonjs"), + // so these files cannot be ESM like the rest of the package. + files: ["eslint-rules/**/*.js"], + languageOptions: { + sourceType: "commonjs", + globals: { + ...globals.node, + }, + }, + rules: { + "@typescript-eslint/no-require-imports": "off", + }, + }, +); diff --git a/packages/models/jest.config.js b/packages/models/jest.config.js deleted file mode 100644 index 82b56570..00000000 --- a/packages/models/jest.config.js +++ /dev/null @@ -1,15 +0,0 @@ -export default { - roots: ["src"], - preset: "ts-jest/presets/default-esm", - moduleNameMapper: { - "^(\\.{1,2}/.*)\\.js$": "$1", - }, - transform: { - "^.+\\.tsx?$": [ - "ts-jest", - { - useESM: true, - }, - ], - }, -}; diff --git a/packages/models/package.json b/packages/models/package.json index 8308bc81..30fd3268 100644 --- a/packages/models/package.json +++ b/packages/models/package.json @@ -21,10 +21,6 @@ ".": { "types": "./dist/types/index.d.ts", "import": "./dist/esm/index.js" - }, - "./react": { - "types": "./dist/types/react.d.ts", - "import": "./dist/esm/react.js" } }, "files": [ @@ -33,57 +29,59 @@ "scripts": { "build": "run build:clean && run tsc --project tsconfig.build.json", "build:clean": "rimraf dist", + "format": "run prettier --write '**/*.{ts,tsx,yaml,yml,json,md,mdx,js}'", "lint": "run eslint .", "test": "", "test:compile": "run tsc --noEmit", - "test:unit": "node --experimental-vm-modules $(yarn bin jest)" + "test:unit": "run vitest run" }, "dependencies": { - "@mittwald/api-client": "workspace:^", - "another-deep-freeze": "1.0.0", - "context": "^4.0.18", + "@internationalized/date": "^3.12.2", + "@mittwald/axios-cache-with-retry": "^1.0.0", + "@mittwald/react-ghostmaker": "^1.6.0", + "@sindresorhus/is": "^8.1.0", + "axios": "^1.15.2", + "convert": "^7.0.0", + "d3-array": "^3.2.4", "dinero.js": "^1.9.1", + "filesize-parser": "^1.5.1", + "jsonschema": "^1.5.0", + "luxon": "^3.7.2", + "minimatch": "^10.2.5", "object-code": "^2.0.0", - "polytype": "^0.17.0", - "type-fest": "^4.30.0" + "pretty-bytes": "^7.1.0", + "remeda": "^2.37.0", + "semver-compare": "^1.0.0", + "shellwords": "^1.1.1", + "slugify": "^1.6.9", + "tiny-invariant": "^1.3.3", + "tldts": "^7.4.2", + "tldts-core": "^7.4.2", + "type-fest": "^5.7.0", + "yaml": "^2.9.1", + "zod": "^4.4.3" }, "devDependencies": { "@eslint/js": "^10.0.1", - "@jest/globals": "^30.5.0", - "@mittwald/react-use-promise": "^4.3.0", - "@testing-library/dom": "^10.4.1", - "@testing-library/jest-dom": "^7.0.1", - "@testing-library/react": "^16.3.3", + "@types/d3-array": "^3.2.2", "@types/dinero.js": "^1.9.4", - "@types/jest": "^30.0.0", + "@types/filesize-parser": "^1.5.3", "@types/luxon": "^3.7.5", - "@types/react": "^18.3.31", - "@types/react-dom": "^18.3.7", + "@types/semver-compare": "^1.0.3", "eslint": "^10.9.1", "eslint-config-prettier": "^10.1.8", + "eslint-plugin-api-models": "portal:./eslint-rules", "eslint-plugin-json": "^5.0.0", "eslint-plugin-prettier": "^5.5.6", "globals": "^17.11.0", - "jest": "^30.5.0", - "jest-environment-jsdom": "^30.5.0", - "luxon": "^3.7.2", "prettier": "^3.9.6", - "react": "^18.3.1", - "react-dom": "^18.3.1", "rimraf": "^6.1.3", - "ts-jest": "^29.4.12", "typescript": "^5.9.3", - "typescript-eslint": "^8.68.0" + "typescript-eslint": "^8.68.0", + "vitest": "^4.1.8" }, "peerDependencies": { - "@mittwald/react-use-promise": "^2.6.0 || ^3.0.0 || ^4.0.0" - }, - "peerDependenciesMeta": { - "@mittwald/react-use-promise": { - "optional": true - }, - "react": { - "optional": true - } + "@mittwald/api-client": "workspace:^", + "@mittwald/api-client-commons": "workspace:^" } } diff --git a/packages/models/src/__snapshots__/publicApi.txt b/packages/models/src/__snapshots__/publicApi.txt new file mode 100644 index 00000000..ce76c4ae --- /dev/null +++ b/packages/models/src/__snapshots__/publicApi.txt @@ -0,0 +1,1395 @@ +type AccessTokenRetrievalKey +type ActionDataByName +Activity +ActivityAction +type ActivityActionData +type ActivityGenericActionData +ActivityList +ActivityListItem +type ActivityListItemData +ActivityListQuery +type ActivityListQueryData +type ActivityType +additionalCronInterpreters +additionalDataComparePrice +type Address +AggregateMetaData +type AggregateReference +AI_HOSTING_DEFAULT_RATE_LIMIT +AI_HOSTING_DOCUMENTATION_LINK +AI_HOSTING_ERROR_RESOLUTION_LINK +AI_HOSTING_INTRODUCTION_LINK +AI_HOSTING_LANDING_PAGE_LINK +AI_HOSTING_LLM_ENDPOINT +AI_HOSTING_MODELS_LINK +type AIBillingPeriodData +type AIBillingPeriodsData +type AIContainerType +aiContainerTypes +type AIDailyTokenUsageData +AIHostingArticle +AIHostingArticleTemplate +type AiHostingOrderData +type AiHostingOrderPreviewRequestData +AIHostingOrderRequest +AIModel +AIModelCommon +type AIModelData +AIModelDetailed +type AIModelLabel +AIModelList +AIModelListItem +type AIModelListItemData +AIModelListQuery +type AIModelListQueryData +type AIModelUsageData +AITokenStatistics +type AITokenUsageData +type AITokenUsageKeyData +type AITokenUsageRange +type AnyLeadCommon +ApiToken +ApiTokenCommon +type ApiTokenCreateRequestData +type ApiTokenData +ApiTokenDetailed +ApiTokenList +ApiTokenListItem +type ApiTokenListItemData +ApiTokenListQuery +type ApiTokenUpdateRequestData +App +AppCommon +AppCopyRequestedAction +type AppData +AppDatabaseLinkedAction +AppDatabaseUnlinkedAction +type AppDefaultCronjobData +AppDeletedAction +AppDescriptionSetAction +AppDetailed +AppFailedAction +AppId +AppInstallation +AppInstallationCommon +type AppInstallationCopyRequestData +type AppInstallationCreateRequestData +type AppInstallationData +AppInstallationDetailed +AppInstallationList +AppInstallationListItem +type AppInstallationListItemData +AppInstallationListQuery +type AppInstallationListQueryData +type AppInstallationListQueryModelData +AppInstallationRequestedAction +type AppInstallationSortOrder +type AppInstallationStagingCreateRequestData +type AppInstallationStagingDetachRequestData +type AppInstallationStatus +type AppInstallationUpdateRequestData +type AppLifecycle +AppLinkedDatabase +type AppLinkedDatabaseData +type AppLinkedDatabasePurpose +AppList +AppListItem +type AppListItemData +AppListQuery +type AppListQueryData +AppMainDatabaseChangedAction +type AppName +type AppPhase +type AppSavedUserInput +AppSystemSoftwareDeletedAction +AppSystemSoftwareSetAction +type AppUpdatePolicyData +type AppUserInputData +AppVersion +AppVersionCommon +type AppVersionData +AppVersionDetailed +AppVersionList +AppVersionListItem +type AppVersionListItemData +AppVersionListQuery +type AppVersionListQueryData +type AppVersionListQueryModelData +AppVersionSetAction +AppVersionUpdatedAction +type ARecordCustomListItem +type ARecordListItem +type ARecordManagedListItem +Article +type ArticleAttributeData +ArticleCommon +type ArticleData +ArticleDetailed +ArticleList +ArticleListItem +type ArticleListItemData +ArticleListQuery +type ArticleListQueryData +type ArticleListQueryModelData +type ArticleModifierData +type ArticleNames +type ArticleTagData +ArticleTagName +type ArticleTemplateData +type ArticleType +Auth +type AuthenticateMfaRequestData +Autoresponder +type AutoresponderData +type AutoresponderUpdateRequestData +Backup +BackupCommon +type BackupCreateExportRequestData +type BackupCreatePathRestoreRequestData +type BackupCreateRequestData +type BackupData +type BackupDbData +BackupDetailed +BackupExport +type BackupExportData +BackupList +BackupListItem +type BackupListItemData +BackupListQuery +type BackupListQueryData +type BackupListQueryModelData +BackupSchedule +BackupScheduleCommon +type BackupScheduleCreateRequestData +type BackupScheduleData +BackupScheduleDetailed +BackupScheduleList +BackupScheduleListItem +type BackupScheduleListItemData +BackupScheduleListQuery +type BackupScheduleListQueryData +type BackupScheduleUpdateRequestData +type BackupTocData +BaseModel +Bytes +type CaaRecordListItem +calculateRelocationPrices +Certificate +type CertificateCheckReplaceChanges +type CertificateCheckReplaceFieldChange +CertificateCheckReplaceResponse +type CertificateCheckReplaceResponseData +type CertificateCheckReplaceSliceChange +CertificateCommon +type CertificateData +CertificateDetailed +type CertificateDifferencesResolveResponse +type CertificateError +type CertificateErrorData +CertificateList +CertificateListItem +type CertificateListItemData +CertificateListQuery +type CertificateListQueryData +type CertificateListQueryModelData +CertificateRequest +type CertificateRequestCertificateData +CertificateRequestCommon +type CertificateRequestData +CertificateRequestDetailed +CertificateRequestList +CertificateRequestListItem +type CertificateRequestListItemData +CertificateRequestListQuery +type CertificateRequestListQueryData +type CertificateRequestListQueryModelData +type CertificateSettings +type CertificateType +CertificateTypes +type CheckReplaceChanges +type CitiesListItemData +type CitiesListQueryData +City +CityCommon +CityList +CityListItem +CityListQuery +type CnameRecordListItem +type CompleteOrderRequestData +type ConfirmMfaResponseData +ContactVerification +ContactVerificationAddressData +type ContactVerificationAddressDataData +ContactVerificationCommon +type ContactVerificationData +ContactVerificationDataBase +ContactVerificationDetailed +ContactVerificationEmailData +type ContactVerificationEmailDataData +ContactVerificationList +ContactVerificationListItem +type ContactVerificationListItemData +ContactVerificationListQuery +type ContactVerificationListQueryData +ContactVerificationNameData +type ContactVerificationNameDataData +type ContactVerificationStatus +type ContactVerificationTypeData +type ContactVerificationTypeDataData +contactVerificationTypeDataFactory +Container +type ContainerAccessibleListQueryData +type ContainerAddTemplateComponentData +containerCommandMaxLength +ContainerCommon +type ContainerData +type ContainerDeclareServiceData +ContainerDetailed +containerEnvKeyRegex +ContainerEnvVariable +type ContainerEnvVariableData +ContainerEnvVariableList +type ContainerEnvVariableListData +containerFilePathRegex +type ContainerImageFormValues +ContainerList +ContainerListItem +type ContainerListItemData +ContainerListQuery +type ContainerListQueryData +type ContainerListQueryModelData +ContainerLog +type ContainerLogChunk +type ContainerLogData +ContainerLogDetailed +containerMaxPort +containerMaxTextLength +type ContainerPatchServiceData +type ContainerPatchVolumeData +ContainerPort +type ContainerPortData +ContainerPortList +containerPortRegExp +type ContainerResourceLimitsData +containerServiceNameMaxLength +containerServiceNameRegex +ContainerStack +ContainerStackCommon +type ContainerStackCreateRequestData +type ContainerStackData +type ContainerStackDeclareRequestData +ContainerStackDetailed +ContainerStackList +ContainerStackListItem +type ContainerStackListItemData +ContainerStackListQuery +type ContainerStackListQueryData +type ContainerStackListQueryModelData +type ContainerStackPatchRequestData +type ContainerStackUpdateScheduleData +type ContainerStackUpdateSchedulePatchRequestData +type ContainerStateData +type ContainerStatus +ContainerTemplate +type ContainerTemplateAlertStatus +containerTemplateAlertStatuses +type ContainerTemplateApiData +containerTemplateCategories +type ContainerTemplateCategory +ContainerTemplateCommon +ContainerTemplateDetailed +type ContainerTemplateDomainData +type ContainerTemplateLicenseData +ContainerTemplateList +ContainerTemplateListItem +type ContainerTemplateListItemData +ContainerTemplateListQuery +type ContainerTemplateListQueryData +type ContainerTemplateTechnicalDetailData +type ContainerTemplateType +type ContainerTemplateUserInputsData +type ContainerTemplateUserInputValues +type ContainerUpdateData +ContainerUserInput +type ContainerUserInputData +ContainerVolumeRelation +type ContainerVolumeRelationData +type ContainerVolumeRelationFormValues +ContainerVolumeRelationList +Contract +type ContractAggregateReference +ContractArticle +type ContractArticleData +ContractCommon +type ContractData +ContractDetailed +ContractItem +ContractItemCommon +type ContractItemData +ContractItemDetailed +type ContractItemReferenceData +type ContractItemTerminationCreateRequestData +ContractList +ContractListItem +type ContractListItemData +ContractListQuery +type ContractListQueryData +type ContractListQueryModelData +ContractPartner +type ContractPartnerData +type ContractPartnerModelData +ContractTermination +type ContractTerminationCreateRequestData +Contributor +type ContributorBillingInformationData +ContributorCommon +type ContributorData +ContributorDetailed +ContributorExtension +ContributorExtensionCommon +type ContributorExtensionData +ContributorExtensionDetailed +ContributorExtensionList +ContributorExtensionListItem +type ContributorExtensionListItemData +ContributorExtensionListQuery +type ContributorExtensionListQueryData +type ContributorExtensionUpdatePricingRequestData +type ContributorExtensionUpdateRequestData +type ContributorImprint +ContributorIncomingInvoice +type ContributorIncomingInvoiceData +ContributorIncomingInvoiceListQuery +ContributorIncomingInvoicesList +ContributorList +type ContributorListIncomingInvoiceQueryData +ContributorListItem +type ContributorListItemData +ContributorListQuery +type ContributorListQueryData +type ContributorOnBehalfInvoiceData +ContributorOutgoingInvoice +type ContributorState +type ContributorUpdateRequestData +Conversation +type ConversationAggregateReference +ConversationCategory +type ConversationCategoryData +type ConversationCategoryListItemData +type ConversationCategoryReferenceType +ConversationCommon +type ConversationCreateMessageRequestData +type ConversationCreateMessageRequestModelData +type ConversationCreateRequest +type ConversationCreateRequestData +type ConversationData +ConversationDetailed +ConversationList +ConversationListItem +type ConversationListItemData +ConversationListQuery +type ConversationListQueryData +type ConversationMemberData +ConversationMessage +type ConversationMessageData +type ConversationMessageFileData +type ConversationMessageResponseData +type ConversationRelatedAggregateReference +ConversationServiceRequest +type ConversationServiceRequestData +type ConversationServiceRequestRelocationPayloadData +type ConversationShareableAggregateReference +type ConversationStatusRequestData +ConversationStatusUpdate +type ConversationUpdateRequestData +ConversationUser +type ConversationUserData +ConversationUserList +ConversationUserListQuery +createActivityAction +type CreateCertificateRequestSuccessResponse +type CreateOrderPreviewRequestData +type CreateOrderRequestData +Cronjob +type CronjobAppInstallationTarget +type CronjobCommandDestination +CronjobCommon +type CronjobContainerTarget +type CronjobContainerTargetResponse +type CronjobCreateRequestData +type CronjobData +CronjobDetailed +CronjobExecution +type CronjobExecutionAnalysisData +CronjobExecutionCommon +type CronjobExecutionData +CronjobExecutionDetailed +CronjobExecutionList +CronjobExecutionListItem +type CronjobExecutionListItemData +CronjobExecutionListQuery +type CronjobExecutionListQueryData +type CronjobExecutionStatus +type CronjobInterpreter +CronjobList +CronjobListItem +type CronjobListItemData +CronjobListQuery +type CronjobListQueryData +type CronjobListQueryModelData +type CronjobLogData +type CronjobUpdateRequestData +type CronjobUrlDestination +Customer +CustomerAIApiKey +CustomerAIApiKeyCommon +CustomerAIApiKeyDetailed +CustomerAIApiKeyList +CustomerAIApiKeyListItem +type CustomerAIApiKeyListItemData +CustomerAIApiKeyListQuery +type CustomerAIApiKeyListQueryData +type CustomerAIApiKeyRequestData +type CustomerAIApiKeyUpdateRequestData +CustomerAIModel +CustomerAIModelCommon +type CustomerAIModelData +CustomerAIModelList +CustomerAIModelListItem +type CustomerAIModelListItemData +CustomerAIModelListQuery +type CustomerAIModelListQueryData +type CustomerAIModelStatus +CustomerAIPlan +CustomerAIPlanCommon +type CustomerAIPlanData +CustomerAIPlanDetailed +type CustomerAIPlanKeys +type CustomerAIPlanLimit +CustomerAIPlanList +CustomerAIPlanListItem +CustomerAIPlanListQuery +type CustomerAIPlanListQueryData +type CustomerAIPlanTokens +type CustomerAIPlanTopUsage +CustomerCommon +type CustomerCreateRequestData +type CustomerData +CustomerDetailed +type CustomerExecutingUserRoles +type CustomerExpressInterestToContributeRequestData +CustomerInvite +CustomerInviteCommon +type CustomerInviteCreateRequestData +type CustomerInviteData +CustomerInviteDetailed +CustomerInviteList +CustomerInviteListItem +type CustomerInviteListItemData +CustomerInviteListQuery +type CustomerInviteListQueryData +CustomerList +CustomerListItem +type CustomerListItemData +CustomerListQuery +type CustomerListQueryData +CustomerMembership +CustomerMembershipCommon +type CustomerMembershipData +CustomerMembershipDetailed +CustomerMembershipList +CustomerMembershipListItem +type CustomerMembershipListItemData +CustomerMembershipListQuery +type CustomerMembershipListQueryData +type CustomerMembershipUpdateRequestData +type CustomerPaymentMethodData +type CustomerPermission +customerPermissions +type CustomerRole +type CustomerUpdateRequestData +type CustomerVatIdValidationState +DatabaseCreatedAction +DatabaseDeletedAction +DatabaseDescriptionSetAction +DatabaseMySqlUserAction +DatabaseMySqlUserCreatedAction +DatabaseMySqlUserDeletedAction +DatabaseMySqlUserPasswordSetAction +DatabaseMySqlUserUpdatedAction +type DatabaseType +DatabaseVersionSetAction +DataModel +DEFAULT_AI_CONTAINER_TYPE +defaultCronInterpreters +DeliveryBox +DeliveryBoxCommon +type DeliveryBoxData +DeliveryBoxDetailed +DeliveryBoxList +DeliveryBoxListItem +type DeliveryBoxListItemData +DeliveryBoxListQuery +type DeliveryBoxListQueryData +type DeliveryBoxListQueryModelData +DnsARecordSetAction +DnsARecordSetManagedAction +DnsCaaRecordSetAction +DnsCnameRecordSetAction +DnsMxRecordSetAction +DnsMxRecordSetManagedAction +DnsRecordAction +DnsRecordCaa +type DnsRecordCaaData +type DnsRecordCaaEntry +type DnsRecordCAARecord +DnsRecordCname +type DnsRecordCnameData +type DnsRecordCombinedA +DnsRecordCombinedABase +DnsRecordCombinedACustom +type DnsRecordCombinedACustomData +type DnsRecordCombinedAData +dnsRecordCombinedAFactory +DnsRecordCombinedAManaged +type DnsRecordCombinedAManagedData +DnsRecordCombinedAUnset +type DnsRecordCombinedAUnsetData +type DnsRecordMx +DnsRecordMxBase +DnsRecordMxCustom +type DnsRecordMxCustomData +type DnsRecordMxData +type DnsRecordMxEntry +dnsRecordMxFactory +DnsRecordMxManaged +type DnsRecordMxManagedData +type DnsRecordMXRecord +DnsRecordMxUnset +type DnsRecordMxUnsetData +DnsRecordSet +DnsRecordSetAction +type DnsRecordSetActionData +type DnsRecordSetData +DnsRecordSettings +type DnsRecordSettingsData +DnsRecordSrv +type DnsRecordSrvData +type DnsRecordSrvEntry +type DnsRecordSRVRecord +DnsRecordTxt +type DnsRecordTxtData +type DnsSrvRecord +DnsSrvRecordSetAction +DnsTxtRecordSetAction +type DnsUpdateMultipleRecordsRequest +type DnsUpdateMxRecordsRequest +type DnsValidationError +DnsZone +DnsZoneCommon +DnsZoneCreatedAction +type DnsZoneData +DnsZoneDeletedAction +DnsZoneDetailed +DnsZoneList +DnsZoneListItem +type DnsZoneListItemData +DnsZoneListQuery +type DnsZoneListQueryData +type DnsZoneListQueryModelData +DockerCompose +type DockerComposeData +dockerComposeSchema +type DockerComposeServiceData +DockerComposeValidationError +type DockerComposeValidationIssue +Domain +DomainArticleTemplate +DomainCommon +type DomainData +DomainDeletedAction +DomainDetailed +DomainHandle +DomainHandleReadable +DomainList +DomainListItem +type DomainListItemData +DomainListQuery +type DomainListQueryData +type DomainListQueryModelData +DomainMigration +DomainMigrationCommon +type DomainMigrationData +DomainMigrationDnsRecord +type DomainMigrationDnsRecordData +type DomainMigrationDnsRecordType +DomainMigrationDomain +type DomainMigrationDomainData +type DomainMigrationDomainState +DomainMigrationList +DomainMigrationListItem +type DomainMigrationListItemData +DomainMigrationListQuery +type DomainMigrationListQueryData +DomainOrderPreview +type DomainOrderPreviewData +type DomainOrderPreviewItem +type DomainOrderPreviewRequestData +type DomainOrderPreviewRequestModelData +DomainOrderRequest +type DomainOrderRequestData +type DomainOrderRequestModelData +DomainProcess +type DomainProcessData +type DomainRegistrableResponse +type DomainTransferableReasons +type DomainTransferableResponse +domainTransferPricePerDomain +DomFile +type DownloadableFile +emailInboxTransferPricePerInbox +type EmailOrigin +type EnrichedDbQueries +type EnrichedDbQuery +type EnrichedFileOp +type EnrichedFileOps +type EnrichedNetworkingOp +type EnrichedNetworkingOps +type ErrorApiData +type ExistingContainerInfo +type ExplicitAny +Extension +ExtensionAsset +type ExtensionAssetData +ExtensionCommon +type ExtensionData +ExtensionDetailed +ExtensionFreePricePlan +ExtensionInstance +type ExtensionInstanceChargeability +ExtensionInstanceCommon +type ExtensionInstanceConsentToScopesRequestData +ExtensionInstanceContext +ExtensionInstanceContract +type ExtensionInstanceContractData +ExtensionInstanceContractDetailed +type ExtensionInstanceContractStatus +type ExtensionInstanceCreateRequestData +type ExtensionInstanceData +ExtensionInstanceDetailed +ExtensionInstanceList +ExtensionInstanceListItem +type ExtensionInstanceListItemData +ExtensionInstanceListQuery +type ExtensionInstanceListQueryData +type ExtensionInstanceListQueryModelData +type ExtensionInstanceRetrievalKeyData +ExtensionList +ExtensionListItem +type ExtensionListItemData +ExtensionListQuery +type ExtensionListQueryData +ExtensionNotBookablePricePlan +type ExtensionOrderRequestData +ExtensionPricePlan +type ExtensionPricePlanData +ExtensionPricePlanVariant +ExtensionPricePlanVariantBase +type ExtensionPricePlanVariantBaseData +type ExtensionPricePlanVariantData +ExtensionPricePlanVariantDetailed +type ExtensionSecret +type ExtensionSessionTokenData +ExtensionSinglePricePlan +ExtensionVariantsPricePlan +extensionVariantsPricePlanFactory +type ExternalCertificateOrderData +ExternalCertificateOrderPreview +type ExternalCertificateOrderPreviewData +type ExternalCertificateOrderPreviewRequestData +type ExternalCertificateOrderPreviewRequestModelData +ExternalCertificateOrderRequest +type ExternalCertificateOrderRequestData +type ExternalCertificateOrderRequestModelData +type ExternalFrontend +extractId +Feedback +FeedbackCommon +type FeedbackCreateData +FeedbackListItem +type FeedbackListItemData +type FeedbackListQuery +type FeedbackPollStatus +FeePeriod +type FeePeriodData +File +type FileAccessTokenProvider +FileContent +FileContentDetailed +type FileDownloadResponseData +FileDownloadToken +type FileDownloadTokenData +FileMeta +type FileMetaData +FileMetaDetailed +type FileSystemDirectoriesData +type FileSystemDirectory +FileUploadError +type FileUploadFailure +type FileUploadResponseData +type FileUploadRules +FileUploadToken +type FileUploadTokenData +type FileUploadType +FinderProfile +FinderProfileCommon +type FinderProfileData +FinderProfileDetailed +FinderProfileList +FinderProfileListItem +type FinderProfileListItemData +type FinderProfileListModelQueryData +FinderProfileListQuery +type FinderProfilePlanOptions +FinderProfileRequest +FinderProfileRequestCommon +type FinderProfileRequestData +FinderProfileRequestDetailed +FinderProfileRequestList +FinderProfileRequestListItem +type FinderProfileRequestListItemData +type FinderProfileRequestListModelQueryData +FinderProfileRequestListQuery +type FinderProfileRequestRequestData +type FinderProfileRequestStatus +type FinderProfileTariffOptionsData +formatRamLimit +formatTokenUsage +type ForwardRequestData +FrontendFragment +type FrontendFragmentAnchor +frontendFragmentAnchors +type FrontendFragmentData +GenericAction +getArticleByName +getDnsRecordChangeType +type HandleData +type HandleField +type HandleReadableData +HardwareSpecs +hardwareSpecsSchema +HostingArticle +HostingContractItem +HostingOrderPreview +type HostingOrderPreviewData +HostingOrderRequest +type HostingOrderSpecs +ImageMeta +type ImageMetaData +type ImageMetaEnvData +type ImageMetaPortData +type ImageMetaVolumeData +Ingress +IngressAppInstallationTarget +type IngressAppInstallationTargetData +IngressCommon +IngressContainerTarget +type IngressContainerTargetData +type IngressData +IngressDeletedAction +IngressDetailed +IngressDomainList +IngressDomainListItem +type IngressDomainListItemData +IngressDomainListQuery +type IngressDomainListQueryData +IngressList +IngressListItem +type IngressListItemData +IngressListQuery +type IngressListQueryData +type IngressListQueryModelData +IngressPath +type IngressPathData +type IngressPathSettings +IngressRedirectTarget +type IngressRedirectTargetData +type IngressTarget +IngressTargetBase +type IngressTargetData +ingressTargetFactory +IngressUndefinedTarget +type IngressUndefinedTargetData +initApiModels +type InitApiModelsOptions +type InitMfaResponseData +InstalledSystemSoftware +type InstalledSystemSoftwareData +type InstalledSystemSoftwareQuery +Invoice +type InvoiceBankingInformation +InvoiceCancellation +InvoiceCommon +type InvoiceData +InvoiceDetailed +InvoiceItem +InvoiceItemGroup +InvoiceList +InvoiceListItem +type InvoiceListItemData +InvoiceListQuery +type InvoiceListQueryData +type InvoiceListQueryModelData +type InvoicePaymentSettings +InvoiceRecipient +type InvoiceRecipientData +InvoiceSettings +InvoiceSettingsCommon +type InvoiceSettingsData +InvoiceSettingsDetailed +type InvoiceSettingsStatus +type InvoiceSettingsUpdateRequestData +type InvoiceStatus +invoiceStatusList +isNewerVersion +isSensitiveEnvKey +isSystemSoftwareKey +isTranslatableValue +isValidationErrorsApiData +type KnownActionName +type KnownRegistryMeta +Lead +LeadCommon +type LeadCompanyData +type LeadData +LeadDetailed +type LeadFilterType +LeadFyndr +LeadFyndrArticleTemplate +LeadFyndrOrderPreview +type LeadFyndrOrderPreviewData +type LeadFyndrOrderPreviewRequestData +LeadFyndrOrderRequest +type LeadFyndrOrderRequestData +type LeadHosterInformationData +LeadList +LeadListItem +type LeadListItemData +LeadListQuery +type LeadListQueryData +type LeadMetricsData +LeadsExport +LeadsExportCommon +type LeadsExportData +LeadsExportDetailed +type LeadsExportExportableField +type LeadsExportExporter +LeadsExportList +LeadsExportListItem +type LeadsExportListItemData +LeadsExportListQuery +type LeadsExportListQueryData +type LeadsExportRequestData +type LeadTechnologyData +License +LicenseCommon +type LicenseData +LicenseDetailed +LicenseList +LicenseListItem +type LicenseListItemData +LicenseListQuery +type LicenseListQueryData +type LicenseMeta +LicenseOrderPreview +type LicenseOrderPreviewData +type LicenseOrderPreviewRequestData +LicenseOrderRequest +type LicenseOrderRequestData +ListDataModel +type ListMailAddressBackupQueryData +ListQueryModel +LocalizedText +type LocalizedTextData +type LocalizedTextLanguage +localizeTemplateText +LOCATION_DACH_ZIP_CODE +MachineTypeSpecs +MailAddress +MailAddressBackup +type MailAddressBackupData +MailAddressBackupList +MailAddressBackupListQuery +type MailAddressBackupListQueryModelData +MailAddressCommon +type MailAddressData +MailAddressDetailed +MailAddressList +MailAddressListItem +type MailAddressListItemData +MailAddressListQuery +type MailAddressListQueryData +type MailAddressListQueryModelData +type MailAddressRequestData +type MailAddressWithArchiveOrderPreview +type MailArchiveOrderData +type MailArchiveOrderPreviewData +type MailArchiveOrderPreviewRequestModelData +MailArchiveOrderRequest +type MailArchiveOrderRequestModelData +MailRateLimit +MailRateLimitCommon +type MailRateLimitData +MailRateLimitDetailed +MailRateLimitList +MailRateLimitListItem +type MailRateLimitListItemData +MailRateLimitListQuery +type MailRateLimitQueryData +MailSettings +type MailSettingsData +MailSettingsDetailed +type MarketplaceContext +type MarketplaceDetailedDescriptionsFormat +type MarketplaceExtendedSupportMeta +type MarketplaceExtensionDeprecation +type MarketplaceGenerateSecretResponse +type MarketplacePricePlanDetails +type MarketplaceSupportMeta +type MarketplaceWebhookType +type MarketplaceWebhookUrl +type MarketplaceWebhookUrls +maskedValuePlaceholder +maskSensitiveEnvValue +maskUrlCredentials +MetricsTimeRange +Mfa +MfaInit +MfaStatus +type MfaStatusData +Money +type MonitoringInterval +type MxRecordCustomListItem +type MxRecordListItem +type MxRecordManagedListItem +MySql +type MySqlCharacterSettings +MySqlCharset +MySqlCharsetList +MySqlCharsetListItem +type MySqlCharsetListItemData +MySqlCharsetListQuery +type MySqlCharsetListQueryData +type MySqlCharsetUpdateRequestData +MySqlCommon +type MySqlCopyRequestData +type MySqlCreateRequest +type MySqlCreateRequestData +type MySqlData +type MySqlDatabaseStatus +MySqlDetailed +MySqlList +MySqlListItem +type MySqlListItemData +MySqlListQuery +type MySqlListQueryData +type MySqlListQueryModelData +type MySqlPatchRequestData +MySqlUser +type MySqlUserAccessLevel +MySqlUserCommon +type MySqlUserCreateRequestData +type MySqlUserData +MySqlUserDetailed +MySqlUserList +MySqlUserListItem +type MySqlUserListItemData +MySqlUserListQuery +type MySqlUserListQueryData +type MySqlUserListQueryModelData +type MySqlUserUpdateRequestData +type MySqlVersionData +Newsletter +NewsletterInfo +type NewsletterInfoData +type NewsletterSubscribeData +NotificationCommon +NotificationList +NotificationListItem +type NotificationListItemData +NotificationListQuery +type NotificationListQueryData +type NotificationReadAllQueryData +Notifications +ObjectNotFoundError +type OpenCustomerExtensionOrderData +type OpenExtensionOrder +type OpenProjectExtensionOrderData +Order +type OrderAttributeConfigurationData +OrderCommon +type OrderData +OrderDetailed +type OrderDomainHandleField +OrderItem +type OrderItemData +OrderList +OrderListItem +type OrderListItemData +OrderListQuery +type OrderListQueryData +type OrderListQueryModelData +type OrderPreviewData +type OrderStatus +type OrderStatusApiData +type OrderTypeData +type OwnContributorData +OwnContributorDetailed +parseCpuLimit +type ParseDomainOptions +parseRamLimitToGb +Performance +PerformanceCommon +type PerformanceData +PerformanceDetailed +type PerformanceIdentifier +PerformanceList +PerformanceListItem +type PerformanceListItemData +PerformanceListQuery +type PerformanceListQueryData +PerformanceMetric +type PerformanceMetricData +PerformanceSubpageItem +type PerformanceSubpageItemData +PerformanceTtfbAnalysis +type PerformanceTtfbAnalysisData +PerformanceTtfbAnalysisDetailed +type PerformanceTtfbAnalysisScheduleData +type PerformanceTtfbAnalysisStraceData +type PerformanceTtfbAnalysisStraceDataDatabaseQueries +type PerformanceTtfbAnalysisStraceDataDbQueryStats +type PerformanceTtfbAnalysisStraceDataFileOps +type PerformanceTtfbAnalysisStraceDataFileOpStats +type PerformanceTtfbAnalysisStraceDataNetworkingOpStats +type PerformanceTtfbAnalysisStraceDataNetworkOps +PerformanceTtfbSummaryMetric +type PerformanceTtfbSummaryMetricData +PlanChange +type PlanChangePreviewRequestData +type PlanChangeRequestData +PricePlanEditingVariant +type PricePlanEditingVariantData +type ProcessState +type ProcessType +Project +ProjectAIApiKey +ProjectAIApiKeyCommon +ProjectAIApiKeyDetailed +ProjectAIApiKeyList +ProjectAIApiKeyListItem +type ProjectAIApiKeyListItemData +ProjectAIApiKeyListQuery +type ProjectAIApiKeyListQueryData +type ProjectAIApiKeyRequestData +type ProjectAIApiKeyUpdateRequestData +ProjectAIModel +ProjectAIModelCommon +type ProjectAIModelData +ProjectAIModelList +ProjectAIModelListItem +type ProjectAIModelListItemData +ProjectAIModelListQuery +type ProjectAIModelListQueryData +type ProjectAIModelStatus +ProjectAIPlan +ProjectAIPlanCommon +type ProjectAIPlanData +ProjectAIPlanDetailed +type ProjectAIPlanLicences +ProjectAIPlanList +ProjectAIPlanListItem +type ProjectAIPlanListItemData +ProjectAIPlanListQuery +type ProjectAIPlanListQueryData +ProjectCommon +type ProjectData +ProjectDetailed +type ProjectDisableReason +type ProjectFeature +ProjectInvite +ProjectInviteCommon +type ProjectInviteCreateRequestData +type ProjectInviteData +ProjectInviteDetailed +ProjectInviteList +ProjectInviteListItem +type ProjectInviteListItemData +ProjectInviteListQuery +type ProjectInviteListQueryData +ProjectListItem +type ProjectListItemData +ProjectListQuery +type ProjectListQueryData +type ProjectListQueryModelData +ProjectMembership +ProjectMembershipCommon +type ProjectMembershipData +ProjectMembershipDetailed +ProjectMembershipList +ProjectMembershipListItem +type ProjectMembershipListItemData +ProjectMembershipListQuery +type ProjectMembershipListQueryData +type ProjectMembershipUpdateRequestData +type ProjectOrderRequestData +type ProjectOrderRequestModelData +type ProjectPermission +projectPermissions +type ProjectRole +type ProjectStatus +ProjectUsageMetrics +ProSpaceArticleTemplate +RecommendedProjectsArticleAttribute +type RecordListItem +RecoveryCodes +Redis +RedisCommon +type RedisConfiguration +type RedisConfigurationUpdateRequestData +type RedisCreateRequestData +type RedisData +RedisDetailed +RedisList +RedisListItem +type RedisListItemData +RedisListQuery +type RedisListQueryData +type RedisListQueryModelData +type RedisMaxMemoryPolicy +type RedisPatchRequestData +type RedisVersionData +ReferenceModel +type RefreshSessionData +registerDefaultOnBeforeRequestHandler +Registration +Registry +RegistryCommon +type RegistryCreateRequestData +type RegistryData +RegistryDetailed +RegistryList +RegistryListItem +type RegistryListItemData +RegistryListQuery +type RegistryListQueryData +type RegistryListQueryModelData +type RegistryLoginType +type RegistryUpdateCredentialsRequestData +type RegistryUpdateRequestData +relocationArticles +type RelocationDomain +type RelocationMailInbox +type RelocationPricePosition +type RelocationPrices +RelocationRequest +type RelocationRequestApiData +type RelocationRequestData +type ResetMfaRecoveryResponseData +resolveAggregateReference +type Salutation +type SchedulePerformanceTtfbAnalysisData +Server +ServerArticle +ServerArticleTemplate +ServerCommon +ServerDetailed +ServerList +ServerListItem +ServerListQuery +type ServerOrderRequestData +type ServerOrderRequestModelData +type ServerProjectStatistics +ServerUsageMetrics +Session +SessionCommon +type SessionData +SessionDetailed +SessionList +SessionListItem +type SessionListItemData +SessionListQuery +SessionToken +type SessionTokenData +SftpUser +type SftpUserAccessLevel +SftpUserCommon +type SftpUserCreateRequestData +type SftpUserData +SftpUserDetailed +SftpUserList +SftpUserListItem +type SftpUserListItemData +SftpUserListQuery +type SftpUserListQueryData +type SftpUserListQueryModelData +type SftpUserUpdateRequestData +shellJoin +shellSplit +SpaceServerArticleTemplate +type SpamProtectionRequestData +Spotlight +type SpotlightDecision +type SpotlightFeedbackData +type SpotlightInteractionData +SpotlightState +type SpotlightStateData +type SrvRecordListItem +SshKey +SshKeyCommon +type SshKeyCreateData +type SshKeyData +SshKeyDetailed +SshKeyList +SshKeyListItem +type SshKeyListItemData +SshKeyListQuery +type SshKeyUpdateData +SshUser +SshUserCommon +type SshUserCreateRequestData +type SshUserData +SshUserDetailed +SshUserList +SshUserListItem +type SshUserListItemData +SshUserListQuery +type SshUserListQueryData +type SshUserListQueryModelData +type SshUserSshKey +type SshUserUpdateRequestData +StorageArticle +StorageArticleAttribute +StorageArticleModifier +StorageArticleTemplate +StorageMetrics +type StorageMetricsData +StorageMetricsDetailed +type StorageMetricsKind +StorageStatisticsCategory +type StorageStatisticsCategoryApiData +type StorageStatisticsCategoryKind +type StructuredLogLine +SupportCode +SupportCodeCommon +type SupportCodeData +SupportCodeDetailed +supportedDockerComposeServiceFields +supportedDockerComposeTopLevelFields +SystemSoftware +SystemSoftwareCommon +type SystemSoftwareData +type SystemSoftwareDependency +SystemSoftwareDetailed +SystemSoftwareFullNames +SystemSoftwareId +SystemSoftwareList +SystemSoftwareListItem +type SystemSoftwareListItemData +SystemSoftwareListQuery +type SystemSoftwareListQueryData +type SystemSoftwareName +SystemSoftwareVersion +SystemSoftwareVersionCommon +type SystemSoftwareVersionData +SystemSoftwareVersionDetailed +SystemSoftwareVersionList +SystemSoftwareVersionListItem +type SystemSoftwareVersionListItemData +SystemSoftwareVersionListQuery +type SystemSoftwareVersionListQueryData +type TariffChangePreviewData +TimeSeriesBin +TimeSeriesBins +Tld +TldCommon +type TldContactSchemas +type TldData +TldDetailed +TldList +TldListItem +type TldListItemData +TldListQuery +type TldListQueryData +TldPrice +TldPriceCommon +type TldPriceData +TldPriceList +TldPriceListItem +type TldPriceListItemData +TldPriceListQuery +type TldPriceListQueryData +type Tls +TlsAcme +type TlsAcmeData +TlsBase +TlsCertificate +type TlsCertificateData +type TlsData +tlsFactory +type TlsStatus +toPositiveLimit +type TransferAuthenticationData +translatable +tryResolveAggregateReference +type TxtRecordListItem +Typo3LicenseArticleTemplate +UnlockedLead +UnlockedLeadCommon +type UnlockedLeadCompanyData +type UnlockedLeadContactData +type UnlockedLeadData +UnlockedLeadDetailed +type UnlockedLeadHosterInformationData +UnlockedLeadList +UnlockedLeadListItem +type UnlockedLeadListItemData +UnlockedLeadListQuery +type UnlockedLeadListQueryData +type UnlockedLeadMetricsData +type UnlockedLeadSocialMediaData +type UpdatePricingResponseData +User +UserCommon +type UserConfirmPasswordResetRequestData +type UserData +type UserDeleteRequestData +UserDetailed +UserInput +type UserInputData +type UserUpdatePasswordRequestData +type UserUpdatePasswordResult +type UserUpdatePersonalInformationRequestData +type UserVerifyEmailRequestData +type UserVerifyPhoneNumberRequestData +ValidationError +type ValidationErrorFromApiResponseOptions +type ValidationErrorObject +type ValidationErrorObjectApiData +type ValidationErrorsApiData +type VerifyAddressRequest +Volume +VolumeCommon +type VolumeData +VolumeDetailed +VolumeList +VolumeListItem +type VolumeListItemData +VolumeListQuery +type VolumeListQueryData +type VolumeListQueryModelData +volumeNameRegExp +WebhostingArticle +WebhostingArticleTemplate +type WithTtfb +ZeroMoney \ No newline at end of file diff --git a/packages/models/src/access/SftpUser/SftpUser.test.ts b/packages/models/src/access/SftpUser/SftpUser.test.ts new file mode 100644 index 00000000..c5f1972d --- /dev/null +++ b/packages/models/src/access/SftpUser/SftpUser.test.ts @@ -0,0 +1,250 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; +import { DateTime } from "luxon"; + +import { buildSftpUserData } from "../../testing/builders/buildSftpUserData.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { Project } from "../../project/index.js"; +import { + SftpUserDetailed, + SftpUserListItem, + SftpUserList, + SftpUser, +} from "./SftpUser.js"; + +afterEach(resetBehaviors); + +describe("SftpUser reference and delegation", () => { + test("find delegates and returns a detailed user", async () => { + const find = vi.fn().mockResolvedValue(buildSftpUserData({ id: "sftp-1" })); + installBehaviors({ sftpUser: { find } }); + + const result = await SftpUser.find("sftp-1"); + + expect(find).toHaveBeenCalledWith("sftp-1"); + expect(result).toBeInstanceOf(SftpUserDetailed); + expect(result?.id).toBe("sftp-1"); + }); + + test("find returns undefined for a missing user", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ sftpUser: { find } }); + + expect(await SftpUser.find("missing")).toBeUndefined(); + expect(find).toHaveBeenCalledWith("missing"); + }); + + test("get returns a detailed user", async () => { + const find = vi.fn().mockResolvedValue(buildSftpUserData({ id: "sftp-2" })); + installBehaviors({ sftpUser: { find } }); + + const result = await SftpUser.get("sftp-2"); + + expect(find).toHaveBeenCalledWith("sftp-2"); + expect(result).toBeInstanceOf(SftpUserDetailed); + }); + + test("findDetailed delegates with the reference id", async () => { + const find = vi.fn().mockResolvedValue(buildSftpUserData({ id: "sftp-3" })); + installBehaviors({ sftpUser: { find } }); + + const result = await SftpUser.ofId("sftp-3").findDetailed(); + + expect(find).toHaveBeenCalledWith("sftp-3"); + expect(result).toBeInstanceOf(SftpUserDetailed); + }); + + test("create delegates with the project id and returns a reference", async () => { + const project = Project.ofId("project-id"); + const data = { + directories: ["/"] as [string, ...string[]], + authentication: { password: "secret" }, + accessLevel: "read" as const, + description: "new user", + }; + const create = vi.fn().mockResolvedValue({ id: "sftp-new" }); + installBehaviors({ sftpUser: { create } }); + + const result = await SftpUser.create(project, data); + + expect(create).toHaveBeenCalledWith("project-id", data); + expect(result).toBeInstanceOf(SftpUser); + expect(result.id).toBe("sftp-new"); + }); + + test("update and delete delegate with the reference id", async () => { + const update = vi.fn().mockResolvedValue(undefined); + const deleteBehavior = vi.fn().mockResolvedValue(undefined); + installBehaviors({ sftpUser: { delete: deleteBehavior, update } }); + const user = SftpUser.ofId("sftp-4"); + const data = { description: "updated" }; + + await user.update(data); + await user.delete(); + + expect(update).toHaveBeenCalledWith("sftp-4", data); + expect(deleteBehavior).toHaveBeenCalledWith("sftp-4"); + }); +}); + +describe("SftpUser data", () => { + test("derives access, key, directory, expiry, type, and project properties", () => { + const expiresAt = "2025-01-01T00:00:00.000Z"; + const user = new SftpUserDetailed( + buildSftpUserData({ + publicKeys: [{ key: "ssh-ed25519 AAA", comment: "laptop" }], + accessLevel: "full", + expiresAt, + }), + ); + + expect(user.hasFullAccess).toBe(true); + expect(user.hasPublicKeys).toBe(true); + expect(user.publicKeys).toHaveLength(1); + expect(user.directories).toEqual(["/"]); + expect(user.hasFullDirectoryAccess).toBe(true); + expect(user.expiresAt).toBeInstanceOf(DateTime); + expect(user.expiresAt?.toMillis()).toBe( + DateTime.fromISO(expiresAt).toMillis(), + ); + expect(user.type).toBe("SFTP"); + expect(user.project).toBeInstanceOf(Project); + expect(user.project.id).toBe("project-id"); + }); + + test("derives defaults and restricted access", () => { + const user = new SftpUserListItem( + buildSftpUserData({ + directories: ["/public"], + publicKeys: undefined, + expiresAt: undefined, + accessLevel: "read", + }), + ); + + expect(user.hasFullAccess).toBe(false); + expect(user.hasPublicKeys).toBeFalsy(); + expect(user.publicKeys).toEqual([]); + expect(user.hasFullDirectoryAccess).toBe(false); + expect(user.expiresAt).toBeUndefined(); + }); + + test("deleteSshKey updates the user without the matching key", async () => { + const update = vi.fn().mockResolvedValue(undefined); + installBehaviors({ sftpUser: { update } }); + const removed = { key: "ssh-ed25519 OLD", comment: "old" }; + const retained = { key: "ssh-ed25519 NEW", comment: "new" }; + const user = new SftpUserDetailed( + buildSftpUserData({ + publicKeys: [removed, retained], + id: "sftp-5", + }), + ); + + await user.deleteSshKey(removed); + + expect(update).toHaveBeenCalledWith("sftp-5", { publicKeys: [retained] }); + }); +}); + +describe("SftpUser list query", () => { + test("executes, materializes items, and preserves total count", async () => { + const project = Project.ofId("project-id"); + const query = { limit: 2, skip: 1 }; + const list = vi.fn().mockResolvedValue({ + items: [buildSftpUserData({ id: "sftp-6" })], + totalCount: 8, + }); + installBehaviors({ sftpUser: { list } }); + + const result = await SftpUser.query({ + project: project, + ...query, + }).execute(); + + expect(list).toHaveBeenCalledWith("project-id", query); + expect(result).toBeInstanceOf(SftpUserList); + expect(result.items[0]).toBeInstanceOf(SftpUserListItem); + expect(result.totalCount).toBe(8); + }); + + test("refine merges queries and getTotalCount returns the total", async () => { + const project = Project.ofId("project-id"); + const list = vi.fn().mockResolvedValue({ totalCount: 12, items: [] }); + installBehaviors({ sftpUser: { list } }); + const refined = SftpUser.query({ + project: project, + limit: 5, + }).refine({ skip: 10 }); + + expect(await refined.getTotalCount()).toBe(12); + // getTotalCount forces limit: 1 (only the count is needed), preserving skip + expect(list).toHaveBeenCalledWith("project-id", { limit: 1, skip: 10 }); + }); +}); + +describe("SftpUser common variant", () => { + test("findCommon on a reference delegates and returns the detailed variant", async () => { + const find = vi + .fn() + .mockResolvedValue(buildSftpUserData({ id: "sftp-c1" })); + installBehaviors({ sftpUser: { find } }); + + const result = await SftpUser.ofId("sftp-c1").findCommon(); + + expect(find).toHaveBeenCalledWith("sftp-c1"); + expect(result).toBeInstanceOf(SftpUserDetailed); + expect(result?.id).toBe("sftp-c1"); + }); + + test("findCommon on a reference returns undefined when not found", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ sftpUser: { find } }); + + expect(await SftpUser.ofId("missing").findCommon()).toBeUndefined(); + expect(find).toHaveBeenCalledWith("missing"); + }); + + test("getCommon on a reference delegates and returns the detailed variant", async () => { + const find = vi + .fn() + .mockResolvedValue(buildSftpUserData({ id: "sftp-c2" })); + installBehaviors({ sftpUser: { find } }); + + const result = await SftpUser.ofId("sftp-c2").getCommon(); + + expect(find).toHaveBeenCalledWith("sftp-c2"); + expect(result).toBeInstanceOf(SftpUserDetailed); + }); + + test("getCommon on a reference throws when not found", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ sftpUser: { find } }); + + await expect(SftpUser.ofId("missing").getCommon()).rejects.toThrow(); + }); + + test("findCommon on an already-materialized model returns it without a behavior call", async () => { + const find = vi.fn(); + installBehaviors({ sftpUser: { find } }); + const detailed = new SftpUserDetailed(buildSftpUserData({ id: "sftp-c3" })); + + const result = await detailed.findCommon(); + + expect(result).toBe(detailed); + expect(find).not.toHaveBeenCalled(); + }); + + test("getCommon on an already-materialized model returns it without a behavior call", async () => { + const find = vi.fn(); + installBehaviors({ sftpUser: { find } }); + const listItem = new SftpUserListItem(buildSftpUserData({ id: "sftp-c4" })); + + const result = await listItem.getCommon(); + + expect(result).toBe(listItem); + expect(find).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/models/src/access/SftpUser/SftpUser.ts b/packages/models/src/access/SftpUser/SftpUser.ts new file mode 100644 index 00000000..8bc0a6e1 --- /dev/null +++ b/packages/models/src/access/SftpUser/SftpUser.ts @@ -0,0 +1,197 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; +import { omit } from "remeda"; + +import type { SshUserSshKey } from "../SshUser/index.js"; +import type { + SftpUserListQueryModelData, + SftpUserCreateRequestData, + SftpUserUpdateRequestData, + SftpUserListItemData, + SftpUserAccessLevel, + SftpUserData, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { arrayRemoveItem } from "../../lib/arrayRemoveItem.js"; +import { Project } from "../../project/internal.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "SftpUser", +}) +export class SftpUser extends ReferenceModel { + public static async create( + project: Project, + data: SftpUserCreateRequestData, + ) { + const response = await config.behaviors.sftpUser.create(project.id, data); + + return new SftpUser(response.id); + } + + public static async find(id: string) { + const data = await config.behaviors.sftpUser.find(id); + if (data !== undefined) { + return new SftpUserDetailed(data); + } + } + + public static async get(id: string) { + const sftpUser = await this.find(id); + assertObjectFound(sftpUser, SftpUser, id); + return sftpUser; + } + + public static ofId(id: string) { + return new SftpUser(id); + } + + public static query(query: SftpUserListQueryModelData) { + return new SftpUserListQuery(query); + } + + public async delete() { + await config.behaviors.sftpUser.delete(this.id); + } + + public async findCommon(): Promise { + return this instanceof SftpUserCommon ? this : this.findDetailed(); + } + + public findDetailed(): Promise { + return SftpUser.find(this.id); + } + + public async getCommon(): Promise { + return this instanceof SftpUserCommon ? this : this.getDetailed(); + } + + public getDetailed(): Promise { + return SftpUser.get(this.id); + } + + public async update(data: SftpUserUpdateRequestData) { + return await config.behaviors.sftpUser.update(this.id, data); + } +} + +export class SftpUserCommon extends WithData< + SftpUserListItemData | SftpUserData +>()(SftpUser) { + public readonly accessLevel: SftpUserAccessLevel; + public readonly active: boolean; + public override readonly data: SftpUserListItemData | SftpUserData; + public readonly description: string; + public readonly directories?: string[]; + public readonly expiresAt?: DateTime; + public readonly hasFullAccess: boolean; + public readonly hasFullDirectoryAccess: boolean; + public readonly hasPassword?: boolean; + public readonly hasPublicKeys?: boolean; + public readonly project: Project; + public readonly publicKeys: SshUserSshKey[]; + public readonly type: "SFTP"; + public readonly userName: string; + + public constructor(data: SftpUserListItemData | SftpUserData) { + super(data.id); + this.data = data; + this.description = data.description; + this.userName = data.userName; + this.active = data.active ?? false; + this.accessLevel = data.accessLevel; + this.hasFullAccess = data.accessLevel === "full"; + this.expiresAt = data.expiresAt + ? DateTime.fromISO(data.expiresAt) + : undefined; + this.hasPassword = data.hasPassword; + this.hasPublicKeys = data.publicKeys && data.publicKeys.length > 0; + this.publicKeys = data.publicKeys ?? []; + this.directories = data.directories ?? ["/"]; + this.hasFullDirectoryAccess = + this.directories.length === 1 && this.directories[0] === "/"; + this.project = Project.ofId(data.projectId); + this.type = "SFTP"; + } + + public async deleteSshKey(sshKey: SshUserSshKey) { + const publicKeys = this.publicKeys; + + arrayRemoveItem( + publicKeys, + (k) => k.key === sshKey.key && k.comment === sshKey.comment, + ); + + await this.update({ publicKeys }); + } +} + +export class SftpUserDetailed extends SftpUserCommon { + public override readonly data: SftpUserData; + public constructor(data: SftpUserData) { + super(data); + this.data = data; + } +} + +export class SftpUserListItem extends SftpUserCommon { + public override readonly data: SftpUserListItemData; + public constructor(data: SftpUserListItemData) { + super(data); + this.data = data; + } +} + +export class SftpUserListQuery extends ListQueryModel { + public constructor(query: SftpUserListQueryModelData) { + super(query, { dependencies: [extractId(query.project)] }); + } + + public async execute() { + const { totalCount, items } = await config.behaviors.sftpUser.list( + extractId(this.query.project), + omit(this.query, ["project"]), + ); + return new SftpUserList( + this.query, + items.map((d) => new SftpUserListItem(d)), + totalCount, + ); + } + + public async getTotalCount() { + const { totalCount } = await this.refine({ limit: 1 }).execute(); + return totalCount; + } + + public refine(query: Partial = {}) { + return new SftpUserListQuery({ + ...this.query, + ...query, + }); + } +} + +export class SftpUserList extends WithListData()( + SftpUserListQuery, +) { + public override readonly items: readonly SftpUserListItem[]; + public override readonly totalCount: number; + public constructor( + query: SftpUserListQueryModelData, + sftpUsers: SftpUserListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(sftpUsers); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/access/SftpUser/behaviors/api.ts b/packages/models/src/access/SftpUser/behaviors/api.ts new file mode 100644 index 00000000..0a1d7a4d --- /dev/null +++ b/packages/models/src/access/SftpUser/behaviors/api.ts @@ -0,0 +1,78 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { SftpUserBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount } from "../../../base/index.js"; + +export const apiSftpUserBehaviors = ( + client: MittwaldAPIV2Client, +): SftpUserBehaviors => ({ + create: async (projectId, data) => { + const response = await client.sshsftpUser.sftpUserCreateSftpUser({ + projectId, + data, + }); + + validateResponse(response, 201, { + validationError: { + pathMappings: { + "*comment*": "sshKey", + "*key*": "sshKey", + }, + }, + }); + + return response.data; + }, + + update: async (sftpUserId, data) => { + const response = await client.sshsftpUser.sftpUserUpdateSftpUser({ + sftpUserId, + data, + }); + + validateResponse(response, 204, { + validationError: { + pathMappings: { + "*comment*": "sshKey", + "*key*": "sshKey", + }, + }, + }); + }, + + list: async (projectId, query) => { + const response = await client.sshsftpUser.sftpUserListSftpUsers({ + queryParameters: query, + projectId, + }); + + validateResponse(response, 200); + + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + find: async (sftpUserId) => { + const response = await client.sshsftpUser.sftpUserGetSftpUser({ + sftpUserId, + }); + + if (response.status === 200) { + return response.data; + } + + validateResponse(response, [403, 404]); + }, + + delete: async (sftpUserId) => { + const response = await client.sshsftpUser.sftpUserDeleteSftpUser({ + sftpUserId, + }); + + validateResponse(response, 204); + }, +}); diff --git a/packages/models/src/domain/Ingress/behaviors/index.ts b/packages/models/src/access/SftpUser/behaviors/index.ts similarity index 100% rename from packages/models/src/domain/Ingress/behaviors/index.ts rename to packages/models/src/access/SftpUser/behaviors/index.ts diff --git a/packages/models/src/access/SftpUser/behaviors/types.ts b/packages/models/src/access/SftpUser/behaviors/types.ts new file mode 100644 index 00000000..155bbfb9 --- /dev/null +++ b/packages/models/src/access/SftpUser/behaviors/types.ts @@ -0,0 +1,29 @@ +import type { QueryResponseData } from "../../../base/index.js"; +import type { + SftpUserCreateRequestData, + SftpUserUpdateRequestData, + SftpUserListQueryData, + SftpUserListItemData, + SftpUserData, +} from "../types.js"; + +export interface SftpUserBehaviors { + list: ( + projectId: string, + query?: SftpUserListQueryData, + ) => Promise>; + + create: ( + projectId: string, + data: SftpUserCreateRequestData, + ) => Promise<{ id: string }>; + + update: ( + sftpUserId: string, + data: SftpUserUpdateRequestData, + ) => Promise; + + find: (sftpUserId: string) => Promise; + + delete: (sftpUserId: string) => Promise; +} diff --git a/packages/models/src/access/SftpUser/index.ts b/packages/models/src/access/SftpUser/index.ts new file mode 100644 index 00000000..bf425273 --- /dev/null +++ b/packages/models/src/access/SftpUser/index.ts @@ -0,0 +1,2 @@ +export * from "./SftpUser.js"; +export * from "./types.js"; diff --git a/packages/models/src/access/SftpUser/types.ts b/packages/models/src/access/SftpUser/types.ts new file mode 100644 index 00000000..20da02c6 --- /dev/null +++ b/packages/models/src/access/SftpUser/types.ts @@ -0,0 +1,25 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import type { Project } from "../../project/index.js"; + +export type SftpUserData = + MittwaldAPIV2.Operations.SftpUserGetSftpUser.ResponseData; + +export type SftpUserListItemData = + MittwaldAPIV2.Operations.SftpUserListSftpUsers.ResponseData[number]; + +export type SftpUserListQueryData = + MittwaldAPIV2.Paths.V2ProjectsProjectIdSftpUsers.Get.Parameters.Query; + +export type SftpUserListQueryModelData = { + project: Project | string; +} & SftpUserListQueryData; + +export type SftpUserCreateRequestData = + MittwaldAPIV2.Paths.V2ProjectsProjectIdSftpUsers.Post.Parameters.RequestBody; + +export type SftpUserUpdateRequestData = + MittwaldAPIV2.Paths.V2SftpUsersSftpUserId.Patch.Parameters.RequestBody; + +export type SftpUserAccessLevel = + MittwaldAPIV2.Components.Schemas.SshuserAccessLevel; diff --git a/packages/models/src/access/SshUser/SshUser.test.ts b/packages/models/src/access/SshUser/SshUser.test.ts new file mode 100644 index 00000000..5c3577cf --- /dev/null +++ b/packages/models/src/access/SshUser/SshUser.test.ts @@ -0,0 +1,267 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; +import { DateTime } from "luxon"; + +import { buildProjectData } from "../../testing/builders/buildProjectData.js"; +import { buildSshUserData } from "../../testing/builders/buildSshUserData.js"; +import { buildUserData } from "../../testing/builders/buildUserData.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { Project } from "../../project/index.js"; +import { + SshUserDetailed, + SshUserListItem, + SshUserList, + SshUser, +} from "./SshUser.js"; + +afterEach(resetBehaviors); + +describe("SshUser reference and delegation", () => { + test("find delegates and returns a detailed user", async () => { + const find = vi.fn().mockResolvedValue(buildSshUserData({ id: "ssh-1" })); + installBehaviors({ sshUser: { find } }); + const result = await SshUser.find("ssh-1"); + expect(find).toHaveBeenCalledWith("ssh-1"); + expect(result).toBeInstanceOf(SshUserDetailed); + expect(result?.id).toBe("ssh-1"); + }); + + test("find returns undefined for a missing user", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ sshUser: { find } }); + expect(await SshUser.find("missing")).toBeUndefined(); + expect(find).toHaveBeenCalledWith("missing"); + }); + + test("get and findDetailed return detailed users", async () => { + const find = vi.fn().mockResolvedValue(buildSshUserData({ id: "ssh-2" })); + installBehaviors({ sshUser: { find } }); + expect(await SshUser.get("ssh-2")).toBeInstanceOf(SshUserDetailed); + expect(await SshUser.ofId("ssh-2").findDetailed()).toBeInstanceOf( + SshUserDetailed, + ); + expect(find).toHaveBeenNthCalledWith(1, "ssh-2"); + expect(find).toHaveBeenNthCalledWith(2, "ssh-2"); + }); + + test("create delegates and returns a reference", async () => { + const project = Project.ofId("project-id"); + const data = { + authentication: { password: "secret" }, + description: "new user", + }; + const create = vi.fn().mockResolvedValue({ id: "ssh-new" }); + installBehaviors({ sshUser: { create } }); + const result = await SshUser.create(project, data); + expect(create).toHaveBeenCalledWith("project-id", data); + expect(result).toBeInstanceOf(SshUser); + expect(result.id).toBe("ssh-new"); + }); + + test("update and delete delegate with the reference id", async () => { + const update = vi.fn().mockResolvedValue(undefined); + const deleteBehavior = vi.fn().mockResolvedValue(undefined); + installBehaviors({ sshUser: { delete: deleteBehavior, update } }); + const user = SshUser.ofId("ssh-3"); + const data = { description: "updated" }; + await user.update(data); + await user.delete(); + expect(update).toHaveBeenCalledWith("ssh-3", data); + expect(deleteBehavior).toHaveBeenCalledWith("ssh-3"); + }); +}); + +describe("SshUser data", () => { + test("derives key, expiry, default, type, and project properties", () => { + const expiresAt = "2025-01-01T00:00:00.000Z"; + const user = new SshUserDetailed( + buildSshUserData({ + publicKeys: [{ key: "ssh-ed25519 AAA", comment: "laptop" }], + id: "default", + expiresAt, + }), + ); + expect(user.hasPublicKeys).toBe(true); + expect(user.publicKeys).toHaveLength(1); + expect(user.expiresAt).toBeInstanceOf(DateTime); + expect(user.expiresAt?.toMillis()).toBe( + DateTime.fromISO(expiresAt).toMillis(), + ); + expect(user.isDefault).toBe(true); + expect(user.type).toBe("SSH"); + expect(user.project).toBeInstanceOf(Project); + expect(user.project.id).toBe("project-id"); + }); + + test("derives absent optional values", () => { + const user = new SshUserListItem( + buildSshUserData({ publicKeys: undefined, expiresAt: undefined }), + ); + expect(user.hasPublicKeys).toBeFalsy(); + expect(user.publicKeys).toEqual([]); + expect(user.expiresAt).toBeUndefined(); + expect(user.isDefault).toBeUndefined(); + }); + + test("deleteSshKey updates the user without the matching key", async () => { + const update = vi.fn().mockResolvedValue(undefined); + installBehaviors({ sshUser: { update } }); + const removed = { key: "ssh-ed25519 OLD", comment: "old" }; + const retained = { key: "ssh-ed25519 NEW", comment: "new" }; + const user = new SshUserDetailed( + buildSshUserData({ publicKeys: [removed, retained], id: "ssh-4" }), + ); + await user.deleteSshKey(removed); + expect(update).toHaveBeenCalledWith("ssh-4", { publicKeys: [retained] }); + }); +}); + +describe("SshUser list query", () => { + test("executes, materializes items, and derives total count", async () => { + const project = Project.ofId("project-id"); + const query = { limit: 2, skip: 1 }; + const list = vi.fn().mockResolvedValue({ + items: [ + buildSshUserData({ id: "ssh-5" }), + buildSshUserData({ id: "ssh-6" }), + ], + totalCount: 2, + }); + installBehaviors({ sshUser: { list } }); + const result = await SshUser.query({ + project: project, + ...query, + }).execute(); + expect(list).toHaveBeenCalledWith("project-id", query); + expect(result).toBeInstanceOf(SshUserList); + expect(result.items.every((item) => item instanceof SshUserListItem)).toBe( + true, + ); + expect(result.totalCount).toBe(2); + }); + + test("refine merges queries", async () => { + const list = vi.fn().mockResolvedValue({ items: [] }); + installBehaviors({ sshUser: { list } }); + await SshUser.query({ + project: Project.ofId("project-id"), + limit: 5, + }) + .refine({ skip: 10 }) + .execute(); + expect(list).toHaveBeenCalledWith("project-id", { limit: 5, skip: 10 }); + }); +}); + +describe("SshUser default user", () => { + test("getDefault builds a common user from the project and the current user", async () => { + const projectFind = vi.fn().mockResolvedValue( + buildProjectData({ + createdAt: "2024-02-02T00:00:00.000Z", + id: "project-7", + }), + ); + const userFind = vi + .fn() + .mockResolvedValue(buildUserData({ email: "ada@example.com" })); + installBehaviors({ + project: { find: projectFind }, + user: { find: userFind }, + }); + + const result = await SshUser.getDefault("project-7"); + + expect(projectFind).toHaveBeenCalledWith("project-7", undefined); + expect(userFind).toHaveBeenCalledWith("self", undefined); + expect(result).toBeInstanceOf(SshUser); + expect(result.userName).toBe("ada@example.com"); + expect(result.project.id).toBe("project-7"); + expect(result.id).toBe("default"); + expect(result.isDefault).toBe(true); + expect(result.description).toBe("mStudio Benutzer"); + expect(result.active).toBe(true); + expect(result.hasPassword).toBe(false); + expect(result.data.createdAt).toBe("2024-02-02T00:00:00.000Z"); + }); + + test("getDefault accepts a project reference", async () => { + const projectFind = vi + .fn() + .mockResolvedValue(buildProjectData({ id: "project-8" })); + installBehaviors({ + user: { + find: vi + .fn() + .mockResolvedValue(buildUserData({ email: "grace@example.com" })), + }, + project: { find: projectFind }, + }); + + const result = await SshUser.getDefault(Project.ofId("project-8")); + + expect(projectFind).toHaveBeenCalledWith("project-8", undefined); + expect(result.project.id).toBe("project-8"); + }); +}); + +describe("SshUser common variant", () => { + test("findCommon on a reference delegates and returns the detailed variant", async () => { + const find = vi.fn().mockResolvedValue(buildSshUserData({ id: "ssh-c1" })); + installBehaviors({ sshUser: { find } }); + + const result = await SshUser.ofId("ssh-c1").findCommon(); + + expect(find).toHaveBeenCalledWith("ssh-c1"); + expect(result).toBeInstanceOf(SshUserDetailed); + expect(result?.id).toBe("ssh-c1"); + }); + + test("findCommon on a reference returns undefined when not found", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ sshUser: { find } }); + + expect(await SshUser.ofId("missing").findCommon()).toBeUndefined(); + expect(find).toHaveBeenCalledWith("missing"); + }); + + test("getCommon on a reference delegates and returns the detailed variant", async () => { + const find = vi.fn().mockResolvedValue(buildSshUserData({ id: "ssh-c2" })); + installBehaviors({ sshUser: { find } }); + + const result = await SshUser.ofId("ssh-c2").getCommon(); + + expect(find).toHaveBeenCalledWith("ssh-c2"); + expect(result).toBeInstanceOf(SshUserDetailed); + }); + + test("getCommon on a reference throws when not found", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ sshUser: { find } }); + + await expect(SshUser.ofId("missing").getCommon()).rejects.toThrow(); + }); + + test("findCommon on an already-materialized model returns it without a behavior call", async () => { + const find = vi.fn(); + installBehaviors({ sshUser: { find } }); + const detailed = new SshUserDetailed(buildSshUserData({ id: "ssh-c3" })); + + const result = await detailed.findCommon(); + + expect(result).toBe(detailed); + expect(find).not.toHaveBeenCalled(); + }); + + test("getCommon on an already-materialized model returns it without a behavior call", async () => { + const find = vi.fn(); + installBehaviors({ sshUser: { find } }); + const listItem = new SshUserListItem(buildSshUserData({ id: "ssh-c4" })); + + const result = await listItem.getCommon(); + + expect(result).toBe(listItem); + expect(find).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/models/src/access/SshUser/SshUser.ts b/packages/models/src/access/SshUser/SshUser.ts new file mode 100644 index 00000000..b1ad87d5 --- /dev/null +++ b/packages/models/src/access/SshUser/SshUser.ts @@ -0,0 +1,208 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { assertString } from "@sindresorhus/is"; +import { DateTime } from "luxon"; +import { omit } from "remeda"; + +import type { + SshUserListQueryModelData, + SshUserCreateRequestData, + SshUserUpdateRequestData, + SshUserListItemData, + SshUserSshKey, + SshUserData, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { arrayRemoveItem } from "../../lib/arrayRemoveItem.js"; +import { Project } from "../../project/internal.js"; +import { config } from "../../config/index.js"; +import { User } from "../../user/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "SshUser", +}) +export class SshUser extends ReferenceModel { + public static async create(project: Project, data: SshUserCreateRequestData) { + const response = await config.behaviors.sshUser.create(project.id, data); + + return new SshUser(response.id); + } + + public static async find(id: string) { + const data = await config.behaviors.sshUser.find(id); + if (data !== undefined) { + return new SshUserDetailed(data); + } + } + + public static async get(id: string) { + const sshUser = await this.find(id); + assertObjectFound(sshUser, SshUser, id); + return sshUser; + } + + public static async getDefault( + project: Project | string, + ): Promise { + const projectDetailed = await Project.get(extractId(project)); + const user = await User.self.getCommon(); + + assertString(user.email); + + return new SshUserCommon({ + authUpdatedAt: projectDetailed.data.createdAt, + createdAt: projectDetailed.data.createdAt, + description: "mStudio Benutzer", + projectId: projectDetailed.id, + userName: user.email, + hasPassword: false, + id: "default", + active: true, + }); + } + + public static ofId(id: string) { + return new SshUser(id); + } + + public static query(query: SshUserListQueryModelData) { + return new SshUserListQuery(query); + } + + public async delete() { + await config.behaviors.sshUser.delete(this.id); + } + + public async findCommon(): Promise { + return this instanceof SshUserCommon ? this : this.findDetailed(); + } + + public findDetailed(): Promise { + return SshUser.find(this.id); + } + + public async getCommon(): Promise { + return this instanceof SshUserCommon ? this : this.getDetailed(); + } + + public getDetailed(): Promise { + return SshUser.get(this.id); + } + + public async update(data: SshUserUpdateRequestData) { + await config.behaviors.sshUser.update(this.id, data); + } +} + +export class SshUserCommon extends WithData< + SshUserListItemData | SshUserData +>()(SshUser) { + public readonly active: boolean; + public override readonly data: SshUserListItemData | SshUserData; + public readonly description: string; + public readonly expiresAt?: DateTime; + public readonly hasPassword?: boolean; + public readonly hasPublicKeys?: boolean; + public readonly isDefault?: boolean; + public readonly project: Project; + public readonly publicKeys: SshUserSshKey[]; + public readonly type: "SSH"; + public readonly userName: string; + + public constructor(data: SshUserListItemData | SshUserData) { + super(data.id); + this.data = data; + this.description = data.description; + this.userName = data.userName; + this.active = data.active ?? false; + this.expiresAt = data.expiresAt + ? DateTime.fromISO(data.expiresAt) + : undefined; + this.hasPassword = data.hasPassword; + this.hasPublicKeys = data.publicKeys && data.publicKeys.length > 0; + this.publicKeys = data.publicKeys ?? []; + this.project = Project.ofId(data.projectId); + this.type = "SSH"; + this.isDefault = data.id === "default" ? true : undefined; + } + + public async deleteSshKey(sshKey: SshUserSshKey) { + const publicKeys = this.publicKeys; + + arrayRemoveItem( + publicKeys, + (k) => k.key === sshKey.key && k.comment === sshKey.comment, + ); + + await this.update({ publicKeys }); + } +} + +export class SshUserDetailed extends SshUserCommon { + public override readonly data: SshUserData; + public constructor(data: SshUserData) { + super(data); + this.data = data; + } +} + +export class SshUserListItem extends SshUserCommon { + public override readonly data: SshUserListItemData; + public constructor(data: SshUserListItemData) { + super(data); + this.data = data; + } +} + +export class SshUserListQuery extends ListQueryModel { + public constructor(query: SshUserListQueryModelData) { + super(query, { dependencies: [extractId(query.project)] }); + } + + public async execute() { + const { totalCount, items } = await config.behaviors.sshUser.list( + extractId(this.query.project), + omit(this.query, ["project"]), + ); + return new SshUserList( + this.query, + items.map((d) => new SshUserListItem(d)), + totalCount, + ); + } + + public async getTotalCount() { + const { totalCount } = await this.refine({ limit: 1 }).execute(); + return totalCount; + } + + public refine(query: Partial = {}) { + return new SshUserListQuery({ + ...this.query, + ...query, + }); + } +} + +export class SshUserList extends WithListData()( + SshUserListQuery, +) { + public override readonly items: readonly SshUserListItem[]; + public override readonly totalCount: number; + public constructor( + query: SshUserListQueryModelData, + sshUsers: SshUserListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(sshUsers); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/access/SshUser/behaviors/api.ts b/packages/models/src/access/SshUser/behaviors/api.ts new file mode 100644 index 00000000..951107ed --- /dev/null +++ b/packages/models/src/access/SshUser/behaviors/api.ts @@ -0,0 +1,75 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { SshUserBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount } from "../../../base/index.js"; + +export const apiSshUserBehaviors = ( + client: MittwaldAPIV2Client, +): SshUserBehaviors => ({ + create: async (projectId, data) => { + const response = await client.sshsftpUser.sshUserCreateSshUser({ + projectId, + data, + }); + + validateResponse(response, 201, { + validationError: { + pathMappings: { + "*comment*": "sshKey", + "*key*": "sshKey", + }, + }, + }); + + return response.data; + }, + + update: async (sshUserId, data) => { + const response = await client.sshsftpUser.sshUserUpdateSshUser({ + sshUserId, + data, + }); + + validateResponse(response, 204, { + validationError: { + pathMappings: { + "*comment*": "sshKey", + "*key*": "sshKey", + }, + }, + }); + }, + + list: async (projectId, query) => { + const response = await client.sshsftpUser.sshUserListSshUsers({ + queryParameters: query, + projectId, + }); + + validateResponse(response, 200); + + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + find: async (sshUserId) => { + const response = await client.sshsftpUser.sshUserGetSshUser({ sshUserId }); + + if (response.status === 200) { + return response.data; + } + validateResponse(response, [403, 404]); + }, + + delete: async (sshUserId) => { + const response = await client.sshsftpUser.sshUserDeleteSshUser({ + sshUserId, + }); + + validateResponse(response, 204); + }, +}); diff --git a/packages/models/src/access/SshUser/behaviors/index.ts b/packages/models/src/access/SshUser/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/access/SshUser/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/access/SshUser/behaviors/types.ts b/packages/models/src/access/SshUser/behaviors/types.ts new file mode 100644 index 00000000..8d699d9e --- /dev/null +++ b/packages/models/src/access/SshUser/behaviors/types.ts @@ -0,0 +1,25 @@ +import type { + SshUserCreateRequestData, + SshUserUpdateRequestData, + SshUserListQueryData, + SshUserListItemData, + SshUserData, +} from "../types.js"; + +export interface SshUserBehaviors { + list: ( + projectId: string, + query?: SshUserListQueryData, + ) => Promise<{ items: SshUserListItemData[]; totalCount: number }>; + + create: ( + projectId: string, + data: SshUserCreateRequestData, + ) => Promise<{ id: string }>; + + update: (sshUserId: string, data: SshUserUpdateRequestData) => Promise; + + find: (sshUserId: string) => Promise; + + delete: (sshUserId: string) => Promise; +} diff --git a/packages/models/src/access/SshUser/index.ts b/packages/models/src/access/SshUser/index.ts new file mode 100644 index 00000000..d8a6d6de --- /dev/null +++ b/packages/models/src/access/SshUser/index.ts @@ -0,0 +1,2 @@ +export * from "./SshUser.js"; +export * from "./types.js"; diff --git a/packages/models/src/access/SshUser/types.ts b/packages/models/src/access/SshUser/types.ts new file mode 100644 index 00000000..ee5f08f4 --- /dev/null +++ b/packages/models/src/access/SshUser/types.ts @@ -0,0 +1,24 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import type { Project } from "../../project/index.js"; + +export type SshUserData = + MittwaldAPIV2.Operations.SshUserGetSshUser.ResponseData; + +export type SshUserListItemData = + MittwaldAPIV2.Operations.SshUserListSshUsers.ResponseData[number]; + +export type SshUserListQueryData = + MittwaldAPIV2.Paths.V2ProjectsProjectIdSshUsers.Get.Parameters.Query; + +export type SshUserListQueryModelData = { + project: Project | string; +} & SshUserListQueryData; + +export type SshUserCreateRequestData = + MittwaldAPIV2.Paths.V2ProjectsProjectIdSshUsers.Post.Parameters.RequestBody; + +export type SshUserUpdateRequestData = + MittwaldAPIV2.Paths.V2SshUsersSshUserId.Patch.Parameters.RequestBody; + +export type SshUserSshKey = MittwaldAPIV2.Components.Schemas.SshuserPublicKey; diff --git a/packages/models/src/access/index.ts b/packages/models/src/access/index.ts new file mode 100644 index 00000000..a14b67b9 --- /dev/null +++ b/packages/models/src/access/index.ts @@ -0,0 +1,2 @@ +export * from "./SftpUser/index.js"; +export * from "./SshUser/index.js"; diff --git a/packages/models/src/activity/Activity/Activity.test.ts b/packages/models/src/activity/Activity/Activity.test.ts new file mode 100644 index 00000000..e6f53529 --- /dev/null +++ b/packages/models/src/activity/Activity/Activity.test.ts @@ -0,0 +1,36 @@ +import { expect, test } from "vitest"; + +import type { ActivityListItemData } from "./types.js"; + +import { ActivityListItem } from "./Activity.js"; +import { Project } from "../../project/index.js"; + +const listItemData = (aggregate: { + aggregate: string; + domain: string; + id: string; +}): ActivityListItemData => + ({ + action: { name: "future.thing-happened", parameters: {}, changes: {} }, + dateTime: "2024-03-04T05:06:07.000Z", + aggregate, + }) as ActivityListItemData; + +test("resolves the aggregate reference to a model", () => { + const activity = new ActivityListItem( + Project.ofId("p-1"), + listItemData({ aggregate: "project", domain: "project", id: "p-1" }), + ); + + expect(activity.aggregate).toBeInstanceOf(Project); + expect(activity.aggregate?.id).toBe("p-1"); +}); + +test("keeps an unknown aggregate reference unresolved", () => { + const activity = new ActivityListItem( + Project.ofId("p-1"), + listItemData({ aggregate: "nope", domain: "nope", id: "x" }), + ); + + expect(activity.aggregate).toBeUndefined(); +}); diff --git a/packages/models/src/activity/Activity/Activity.ts b/packages/models/src/activity/Activity/Activity.ts new file mode 100644 index 00000000..1bc84931 --- /dev/null +++ b/packages/models/src/activity/Activity/Activity.ts @@ -0,0 +1,117 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; + +import type { ActivityListQueryData, ActivityListItemData } from "./types.js"; +import type { AggregateReference } from "../../common/index.js"; +import type { ActivityAction } from "./ActivityAction.js"; +import type { Project } from "../../project/index.js"; + +import { tryResolveAggregateReference } from "../../common/index.js"; +import { createActivityAction } from "./actionRegistry.js"; +import { Extension } from "../../marketplace/index.js"; +import { config } from "../../config/index.js"; +import { User } from "../../user/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "Activity", +}) +export class Activity extends ReferenceModel { + public static query(project: Project, query: ActivityListQueryData = {}) { + return new ActivityListQuery(project, query); + } +} + +export class ActivityListItem extends WithData()( + Activity, +) { + public readonly action: ActivityAction; + public readonly aggregate: AggregateReference | undefined; + public readonly dateTime: DateTime; + public readonly extension?: Extension; + public readonly impersonated: boolean; + public readonly project: Project; + public readonly user?: User; + + public constructor(project: Project, data: ActivityListItemData) { + const action = createActivityAction(data.action); + + // A log entry has no id, and timestamp, aggregate and action name alone are + // not unique (several records of one zone written in one request). + super( + [ + data.dateTime, + data.aggregate.id, + data.action.name, + action.displayName, + ].join("-"), + ); + + this.dateTime = DateTime.fromISO(data.dateTime); + + this.action = action; + + this.aggregate = tryResolveAggregateReference(data.aggregate); + this.user = + data.user && data.user.type === "user" + ? User.ofId(data.user.id) + : undefined; + this.extension = + data.user && data.user.type === "extension" + ? Extension.ofId(data.user.id) + : undefined; + this.impersonated = !!data.impersonator; + this.project = project; + } +} + +export class ActivityListQuery extends ListQueryModel { + public readonly project: Project; + + public constructor(project: Project, query: ActivityListQueryData = {}) { + super(query); + this.project = project; + } + + public async execute() { + const { totalCount, items } = await config.behaviors.activity.list( + extractId(this.project), + this.query, + ); + + return new ActivityList( + this.project, + this.query, + items.map((i) => new ActivityListItem(this.project, i)), + totalCount, + ); + } + + public refine(query: ActivityListQueryData) { + return new ActivityListQuery(this.project, { ...this.query, ...query }); + } +} + +export class ActivityList extends WithListData()( + ActivityListQuery, +) { + public override readonly items: readonly ActivityListItem[]; + public override readonly totalCount: number; + + public constructor( + project: Project, + query: ActivityListQueryData, + items: ActivityListItem[], + totalCount: number, + ) { + super(project, query); + this.items = Object.freeze(items); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/activity/Activity/ActivityAction.ts b/packages/models/src/activity/Activity/ActivityAction.ts new file mode 100644 index 00000000..d0140ab0 --- /dev/null +++ b/packages/models/src/activity/Activity/ActivityAction.ts @@ -0,0 +1,44 @@ +import type { ActivityActionData, ActivityType } from "./types.js"; + +import { DataModel } from "../../base/index.js"; + +type ChangesOf = T extends { changes: infer C } ? C : undefined; + +export abstract class ActivityAction< + T extends ActivityActionData = ActivityActionData, +> extends DataModel { + public readonly changes?: ChangesOf; + public displayName?: string; + /** Used when neither the aggregate nor `displayName` resolves. */ + public displayNameFallbackKey?: string; + /** `key.*` overrides for `changes` fields whose raw name is ambiguous. */ + public fieldLabels: Record = {}; + public hasWideChanges = false; + + /** Hidden when neither side carries a value. */ + public hideWhenEmptyFields: readonly string[] = []; + + public readonly name: T["name"]; + + /** Without the `activity.` prefix and without the `.short` suffix. */ + public titleKey: string; + + /** Beyond `{{displayName}}`; wrap in `translatable()` for a key to resolve. */ + public titleOptions: Record = {}; + + public type: ActivityType; + + public valuesAreCopyable = false; + + protected constructor(data: T) { + super(data); + + this.name = data.name; + + this.changes = + "changes" in data ? (data.changes as ChangesOf) : undefined; + + this.type = "info"; + this.titleKey = data.name; + } +} diff --git a/packages/models/src/activity/Activity/actionRegistry.test.ts b/packages/models/src/activity/Activity/actionRegistry.test.ts new file mode 100644 index 00000000..1c939299 --- /dev/null +++ b/packages/models/src/activity/Activity/actionRegistry.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, test } from "vitest"; + +import type { ActivityActionData } from "./types.js"; + +import { AppFailedAction, GenericAction } from "./actions/index.js"; +import { createActivityAction } from "./actionRegistry.js"; + +const actionData = (data: object): ActivityActionData => + data as ActivityActionData; + +describe("createActivityAction", () => { + test("resolves app.failed and names the reason when there is one", () => { + const withoutError = createActivityAction( + actionData({ + parameters: { appInstallation: { name: "my-shop" } }, + name: "app.failed", + changes: {}, + }), + ); + + expect(withoutError).toBeInstanceOf(AppFailedAction); + expect(withoutError.titleKey).toBe("app.failed"); + + const withError = createActivityAction( + actionData({ + parameters: { + appInstallation: { name: "my-shop" }, + error: { name: "out of disk space" }, + }, + name: "app.failed", + changes: {}, + }), + ); + + expect(withError.titleKey).toBe("app.failed.withError"); + expect(withError.titleOptions).toEqual({ error: "out of disk space" }); + }); + + test("falls back to the generic action for unknown names", () => { + const action = createActivityAction( + actionData({ + name: "future.thing-happened", + parameters: {}, + changes: {}, + }), + ); + + expect(action).toBeInstanceOf(GenericAction); + expect(action.titleKey).toBe("future.thing-happened"); + }); +}); diff --git a/packages/models/src/activity/Activity/actionRegistry.ts b/packages/models/src/activity/Activity/actionRegistry.ts new file mode 100644 index 00000000..ad6a0682 --- /dev/null +++ b/packages/models/src/activity/Activity/actionRegistry.ts @@ -0,0 +1,221 @@ +import type { ActivityAction } from "./ActivityAction.js"; +import type { + ActivityGenericActionData, + ActivityActionData, + ActionDataByName, + KnownActionName, +} from "./types.js"; + +import { + DatabaseMySqlUserPasswordSetAction, + AppInstallationRequestedAction, + AppSystemSoftwareDeletedAction, + DatabaseMySqlUserCreatedAction, + DatabaseMySqlUserDeletedAction, + DatabaseMySqlUserUpdatedAction, + AppMainDatabaseChangedAction, + DatabaseDescriptionSetAction, + DnsMxRecordSetManagedAction, + AppSystemSoftwareSetAction, + DnsARecordSetManagedAction, + AppDatabaseUnlinkedAction, + DatabaseVersionSetAction, + AppDatabaseLinkedAction, + AppDescriptionSetAction, + AppVersionUpdatedAction, + DnsCnameRecordSetAction, + AppCopyRequestedAction, + DatabaseCreatedAction, + DatabaseDeletedAction, + DnsCaaRecordSetAction, + DnsSrvRecordSetAction, + DnsTxtRecordSetAction, + DnsMxRecordSetAction, + DnsZoneCreatedAction, + DnsZoneDeletedAction, + IngressDeletedAction, + AppVersionSetAction, + DnsARecordSetAction, + DomainDeletedAction, + AppDeletedAction, + AppFailedAction, + GenericAction, +} from "./actions/index.js"; + +type ActionConstructor = new ( + data: ActionDataByName, +) => ActivityAction; + +/** + * `GenericAction` for names the schema knows but this package does not model + * yet. Their data does not have the generic schema shape, so it is taken as is + * – the same way `createActivityAction` hands unknown names to + * `GenericAction`. + */ +const UnmodelledAction = GenericAction as new ( + data: ActivityActionData, +) => ActivityAction; + +/** + * Not partial on purpose: a new name in the generated schema breaks compilation + * until it is handled – point it at `UnmodelledAction` to opt out visibly. A + * name only the API emits stays invisible until it shows up as a + * `GenericAction`. + */ +// Grouped by domain so the map reads like the API's action list; +// alphabetical within each group. +const actionRegistry: { + [TName in KnownActionName]: ActionConstructor; +} = { + // app + "app.copy-requested": AppCopyRequestedAction, + "app.database-linked": AppDatabaseLinkedAction, + "app.database-unlinked": AppDatabaseUnlinkedAction, + "app.deleted": AppDeletedAction, + "app.description-set": AppDescriptionSetAction, + "app.failed": AppFailedAction, + "app.installation-requested": AppInstallationRequestedAction, + "app.main-database-changed": AppMainDatabaseChangedAction, + "app.systemsoftware-deleted": AppSystemSoftwareDeletedAction, + "app.systemsoftware-set": AppSystemSoftwareSetAction, + "app.version-set": AppVersionSetAction, + "app.version-updated": AppVersionUpdatedAction, + + // container (not modelled yet) + "container.command-updated": UnmodelledAction, + "container.created": UnmodelledAction, + "container.deleted": UnmodelledAction, + "container.description-updated": UnmodelledAction, + "container.entrypoint-updated": UnmodelledAction, + "container.envs-updated": UnmodelledAction, + "container.image-pulled": UnmodelledAction, + "container.image-updated": UnmodelledAction, + "container.ports-updated": UnmodelledAction, + "container.recreated": UnmodelledAction, + "container.registry-created": UnmodelledAction, + "container.registry-credentials-updated": UnmodelledAction, + "container.registry-deleted": UnmodelledAction, + "container.registry-description-updated": UnmodelledAction, + "container.registry-uri-updated": UnmodelledAction, + "container.resources-updated": UnmodelledAction, + "container.restart-policy-updated": UnmodelledAction, + "container.restarted": UnmodelledAction, + "container.stack-created": UnmodelledAction, + "container.stack-deleted": UnmodelledAction, + "container.stack-description-updated": UnmodelledAction, + "container.stack-storage-updated": UnmodelledAction, + "container.stack-update-schedule-updated": UnmodelledAction, + "container.started": UnmodelledAction, + "container.stopped": UnmodelledAction, + "container.volume-created": UnmodelledAction, + "container.volume-deleted": UnmodelledAction, + "container.volumes-updated": UnmodelledAction, + + // cronjob (not modelled yet) + "cronjob.activated": UnmodelledAction, + "cronjob.alert-threshold-updated": UnmodelledAction, + "cronjob.command-updated": UnmodelledAction, + "cronjob.concurrency-policy-updated": UnmodelledAction, + "cronjob.created": UnmodelledAction, + "cronjob.deactivated": UnmodelledAction, + "cronjob.deleted": UnmodelledAction, + "cronjob.description-updated": UnmodelledAction, + "cronjob.execution-aborted": UnmodelledAction, + "cronjob.execution-triggered": UnmodelledAction, + "cronjob.interval-updated": UnmodelledAction, + "cronjob.notification-email-removed": UnmodelledAction, + "cronjob.notification-email-updated": UnmodelledAction, + "cronjob.service-reference-updated": UnmodelledAction, + "cronjob.target-updated": UnmodelledAction, + "cronjob.time-zone-updated": UnmodelledAction, + "cronjob.timeout-updated": UnmodelledAction, + + // database + "database.mysql-created": DatabaseCreatedAction, + "database.mysql-deleted": DatabaseDeletedAction, + "database.mysql-description-set": DatabaseDescriptionSetAction, + "database.mysql-version-set": DatabaseVersionSetAction, + "database.redis-created": DatabaseCreatedAction, + "database.redis-deleted": DatabaseDeletedAction, + "database.redis-description-set": DatabaseDescriptionSetAction, + "database.redis-version-set": DatabaseVersionSetAction, + + // database user + "database.mysql-user-created": DatabaseMySqlUserCreatedAction, + "database.mysql-user-deleted": DatabaseMySqlUserDeletedAction, + "database.mysql-user-password-set": DatabaseMySqlUserPasswordSetAction, + "database.mysql-user-updated": DatabaseMySqlUserUpdatedAction, + + // dns + "dns.a-record-set": DnsARecordSetAction, + "dns.a-record-set-managed": DnsARecordSetManagedAction, + "dns.caa-record-set": DnsCaaRecordSetAction, + "dns.cname-record-set": DnsCnameRecordSetAction, + "dns.domain-deleted": DomainDeletedAction, + "dns.ingress-deleted": IngressDeletedAction, + "dns.mx-record-set": DnsMxRecordSetAction, + "dns.mx-record-set-managed": DnsMxRecordSetManagedAction, + "dns.srv-record-set": DnsSrvRecordSetAction, + "dns.txt-record-set": DnsTxtRecordSetAction, + "dns.zone-created": DnsZoneCreatedAction, + "dns.zone-deleted": DnsZoneDeletedAction, + + // membership (not modelled yet) + "membership.invite-accepted": UnmodelledAction, + "membership.invite-created": UnmodelledAction, + "membership.invite-declined": UnmodelledAction, + "membership.invite-expired": UnmodelledAction, + "membership.invite-resent": UnmodelledAction, + "membership.invite-revoked": UnmodelledAction, + "membership.member-added": UnmodelledAction, + "membership.member-expired": UnmodelledAction, + "membership.member-expiry-updated": UnmodelledAction, + "membership.member-inherited": UnmodelledAction, + "membership.member-left": UnmodelledAction, + "membership.member-removed": UnmodelledAction, + "membership.member-role-updated": UnmodelledAction, + + // project (not modelled yet) + "project.created": UnmodelledAction, + "project.description-updated": UnmodelledAction, + + // sshuser (not modelled yet) + "sshuser.sftp-user-access-level-updated": UnmodelledAction, + "sshuser.sftp-user-activated": UnmodelledAction, + "sshuser.sftp-user-created": UnmodelledAction, + "sshuser.sftp-user-deactivated": UnmodelledAction, + "sshuser.sftp-user-deleted": UnmodelledAction, + "sshuser.sftp-user-description-updated": UnmodelledAction, + "sshuser.sftp-user-directories-updated": UnmodelledAction, + "sshuser.sftp-user-expired": UnmodelledAction, + "sshuser.sftp-user-expiry-updated": UnmodelledAction, + "sshuser.sftp-user-password-updated": UnmodelledAction, + "sshuser.sftp-user-public-keys-updated": UnmodelledAction, + "sshuser.ssh-user-activated": UnmodelledAction, + "sshuser.ssh-user-created": UnmodelledAction, + "sshuser.ssh-user-deactivated": UnmodelledAction, + "sshuser.ssh-user-deleted": UnmodelledAction, + "sshuser.ssh-user-description-updated": UnmodelledAction, + "sshuser.ssh-user-expired": UnmodelledAction, + "sshuser.ssh-user-expiry-updated": UnmodelledAction, + "sshuser.ssh-user-password-updated": UnmodelledAction, + "sshuser.ssh-user-public-keys-updated": UnmodelledAction, +}; + +const isKnownActionName = (name: string): name is KnownActionName => + name in actionRegistry; + +export const createActivityAction = ( + data: ActivityActionData, +): ActivityAction => { + if (!isKnownActionName(data.name)) { + return new GenericAction(data as ActivityGenericActionData); + } + + // The union of constructors is only callable with the intersection of their + // parameter types, so the name-to-class match cannot be expressed here. + const ActionClass: new (data: never) => ActivityAction = + actionRegistry[data.name]; + + return new ActionClass(data as never); +}; diff --git a/packages/models/src/activity/Activity/actions/AppCopyRequestedAction.ts b/packages/models/src/activity/Activity/actions/AppCopyRequestedAction.ts new file mode 100644 index 00000000..5b486bf5 --- /dev/null +++ b/packages/models/src/activity/Activity/actions/AppCopyRequestedAction.ts @@ -0,0 +1,21 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { ActivityAction } from "../ActivityAction.js"; + +type ActivityAppInstallationCopyRequested = + MittwaldAPIV2.Components.Schemas.ActivitylogAppInstallationCopyRequested; + +export class AppCopyRequestedAction extends ActivityAction { + public readonly parameters; + + constructor(data: ActivityAppInstallationCopyRequested) { + super(data); + + this.parameters = data.parameters; + this.displayName = data.parameters.appInstallation.name; + this.type = "copy"; + this.titleOptions = { + sourceAppInstallation: data.parameters.sourceAppInstallation.name, + }; + } +} diff --git a/packages/models/src/activity/Activity/actions/AppDatabaseLinkedAction.ts b/packages/models/src/activity/Activity/actions/AppDatabaseLinkedAction.ts new file mode 100644 index 00000000..3bd43394 --- /dev/null +++ b/packages/models/src/activity/Activity/actions/AppDatabaseLinkedAction.ts @@ -0,0 +1,19 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { ActivityAction } from "../ActivityAction.js"; + +type ActivityAppInstallationDatabaseLinked = + MittwaldAPIV2.Components.Schemas.ActivitylogAppInstallationDatabaseLinked; + +export class AppDatabaseLinkedAction extends ActivityAction { + public readonly parameters; + + constructor(data: ActivityAppInstallationDatabaseLinked) { + super(data); + + this.parameters = data.parameters; + this.displayName = data.parameters.appInstallation.name; + this.type = "edit"; + this.titleOptions = { database: data.parameters.database.name }; + } +} diff --git a/packages/models/src/activity/Activity/actions/AppDatabaseUnlinkedAction.ts b/packages/models/src/activity/Activity/actions/AppDatabaseUnlinkedAction.ts new file mode 100644 index 00000000..a19e3cef --- /dev/null +++ b/packages/models/src/activity/Activity/actions/AppDatabaseUnlinkedAction.ts @@ -0,0 +1,19 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { ActivityAction } from "../ActivityAction.js"; + +type ActivityAppInstallationDatabaseUnlinked = + MittwaldAPIV2.Components.Schemas.ActivitylogAppInstallationDatabaseUnlinked; + +export class AppDatabaseUnlinkedAction extends ActivityAction { + public readonly parameters; + + constructor(data: ActivityAppInstallationDatabaseUnlinked) { + super(data); + + this.parameters = data.parameters; + this.displayName = data.parameters.appInstallation.name; + this.type = "edit"; + this.titleOptions = { database: data.parameters.database.name }; + } +} diff --git a/packages/models/src/activity/Activity/actions/AppDeletedAction.ts b/packages/models/src/activity/Activity/actions/AppDeletedAction.ts new file mode 100644 index 00000000..949eae53 --- /dev/null +++ b/packages/models/src/activity/Activity/actions/AppDeletedAction.ts @@ -0,0 +1,18 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { ActivityAction } from "../ActivityAction.js"; + +type ActivityAppInstallationDeleted = + MittwaldAPIV2.Components.Schemas.ActivitylogAppInstallationDeleted; + +export class AppDeletedAction extends ActivityAction { + public readonly parameters; + + constructor(data: ActivityAppInstallationDeleted) { + super(data); + + this.parameters = data.parameters; + this.displayName = data.parameters.appInstallation.name; + this.type = "delete"; + } +} diff --git a/packages/models/src/activity/Activity/actions/AppDescriptionSetAction.ts b/packages/models/src/activity/Activity/actions/AppDescriptionSetAction.ts new file mode 100644 index 00000000..047de410 --- /dev/null +++ b/packages/models/src/activity/Activity/actions/AppDescriptionSetAction.ts @@ -0,0 +1,22 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { ActivityAction } from "../ActivityAction.js"; + +type ActivityAppInstallationDescriptionSet = + MittwaldAPIV2.Components.Schemas.ActivitylogAppInstallationDescriptionSet; + +export class AppDescriptionSetAction extends ActivityAction { + public readonly parameters; + + constructor(data: ActivityAppInstallationDescriptionSet) { + super(data); + + this.parameters = data.parameters; + this.displayName = data.parameters.appInstallation.name; + this.type = "edit"; + this.titleOptions = { + oldDescription: data.changes.before?.description, + description: data.changes.after?.description, + }; + } +} diff --git a/packages/models/src/activity/Activity/actions/AppFailedAction.ts b/packages/models/src/activity/Activity/actions/AppFailedAction.ts new file mode 100644 index 00000000..d1e2459d --- /dev/null +++ b/packages/models/src/activity/Activity/actions/AppFailedAction.ts @@ -0,0 +1,24 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { ActivityAction } from "../ActivityAction.js"; + +type ActivityAppInstallationFailed = + MittwaldAPIV2.Components.Schemas.ActivitylogAppInstallationFailed; + +export class AppFailedAction extends ActivityAction { + public readonly parameters; + + constructor(data: ActivityAppInstallationFailed) { + super(data); + + this.parameters = data.parameters; + this.displayName = data.parameters.appInstallation.name; + this.type = "fail"; + + // `changes` is empty, so the title is the only place the reason can surface. + if (data.parameters.error) { + this.titleKey = "app.failed.withError"; + this.titleOptions = { error: data.parameters.error.name }; + } + } +} diff --git a/packages/models/src/activity/Activity/actions/AppInstallationRequestedAction.ts b/packages/models/src/activity/Activity/actions/AppInstallationRequestedAction.ts new file mode 100644 index 00000000..66a073e8 --- /dev/null +++ b/packages/models/src/activity/Activity/actions/AppInstallationRequestedAction.ts @@ -0,0 +1,18 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { ActivityAction } from "../ActivityAction.js"; + +type ActivityAppInstallationRequested = + MittwaldAPIV2.Components.Schemas.ActivitylogAppInstallationRequested; + +export class AppInstallationRequestedAction extends ActivityAction { + public readonly parameters; + + constructor(data: ActivityAppInstallationRequested) { + super(data); + + this.parameters = data.parameters; + this.displayName = data.parameters.appInstallation.name; + this.type = "create"; + } +} diff --git a/packages/models/src/activity/Activity/actions/AppMainDatabaseChangedAction.ts b/packages/models/src/activity/Activity/actions/AppMainDatabaseChangedAction.ts new file mode 100644 index 00000000..bd7937bd --- /dev/null +++ b/packages/models/src/activity/Activity/actions/AppMainDatabaseChangedAction.ts @@ -0,0 +1,25 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { ActivityAction } from "../ActivityAction.js"; + +type ActivityAppInstallationMainDatabaseChanged = + MittwaldAPIV2.Components.Schemas.ActivitylogAppInstallationMainDatabaseChanged; + +const getMainDatabaseChangeType = ( + changes: ActivityAppInstallationMainDatabaseChanged["changes"], +): "changed" | "linked" => (changes.before.name ? "changed" : "linked"); + +export class AppMainDatabaseChangedAction extends ActivityAction { + public readonly parameters; + + constructor(data: ActivityAppInstallationMainDatabaseChanged) { + super(data); + + this.parameters = data.parameters; + this.displayName = data.parameters.appInstallation.name; + this.type = "edit"; + this.fieldLabels = { name: "databaseName" }; + this.titleOptions = { database: data.parameters.database.name }; + this.titleKey = `${data.name}.${getMainDatabaseChangeType(data.changes)}`; + } +} diff --git a/packages/models/src/activity/Activity/actions/AppSystemSoftwareDeletedAction.ts b/packages/models/src/activity/Activity/actions/AppSystemSoftwareDeletedAction.ts new file mode 100644 index 00000000..20d76d51 --- /dev/null +++ b/packages/models/src/activity/Activity/actions/AppSystemSoftwareDeletedAction.ts @@ -0,0 +1,22 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { SystemSoftwareFullNames } from "../../../app/index.js"; +import { ActivityAction } from "../ActivityAction.js"; + +type ActivityAppInstallationSystemSoftwareDeleted = + MittwaldAPIV2.Components.Schemas.ActivitylogAppInstallationDesiredSystemSoftwareDeleted; + +export class AppSystemSoftwareDeletedAction extends ActivityAction { + public readonly parameters; + + constructor(data: ActivityAppInstallationSystemSoftwareDeleted) { + super(data); + + this.parameters = data.parameters; + this.displayName = + SystemSoftwareFullNames[ + data.parameters.software.name as keyof typeof SystemSoftwareFullNames + ]; + this.type = "delete"; + } +} diff --git a/packages/models/src/activity/Activity/actions/AppSystemSoftwareSetAction.ts b/packages/models/src/activity/Activity/actions/AppSystemSoftwareSetAction.ts new file mode 100644 index 00000000..d28f5662 --- /dev/null +++ b/packages/models/src/activity/Activity/actions/AppSystemSoftwareSetAction.ts @@ -0,0 +1,32 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { SystemSoftwareFullNames } from "../../../app/index.js"; +import { ActivityAction } from "../ActivityAction.js"; + +type ActivityAppInstallationSystemSoftwareSet = + MittwaldAPIV2.Components.Schemas.ActivitylogAppInstallationDesiredSystemSoftwareSet; + +export class AppSystemSoftwareSetAction extends ActivityAction { + public readonly parameters; + + constructor(data: ActivityAppInstallationSystemSoftwareSet) { + super(data); + + this.parameters = data.parameters; + this.displayName = + SystemSoftwareFullNames[ + data.parameters.software.name as keyof typeof SystemSoftwareFullNames + ]; + + const oldVersion = data.changes.before?.softwareVersion; + + this.type = oldVersion ? "update" : "create"; + this.titleKey = oldVersion + ? "app.systemsoftware-set.changed" + : "app.systemsoftware-set.created"; + this.titleOptions = { + version: data.changes.after?.softwareVersion, + oldVersion, + }; + } +} diff --git a/packages/models/src/activity/Activity/actions/AppVersionSetAction.ts b/packages/models/src/activity/Activity/actions/AppVersionSetAction.ts new file mode 100644 index 00000000..fd34f3aa --- /dev/null +++ b/packages/models/src/activity/Activity/actions/AppVersionSetAction.ts @@ -0,0 +1,19 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { ActivityAction } from "../ActivityAction.js"; + +type ActivityAppInstallationAppVersionSet = + MittwaldAPIV2.Components.Schemas.ActivitylogAppInstallationAppVersionSet; + +export class AppVersionSetAction extends ActivityAction { + public readonly parameters; + + constructor(data: ActivityAppInstallationAppVersionSet) { + super(data); + + this.parameters = data.parameters; + this.displayName = data.parameters.appInstallation.name; + this.type = "create"; + this.titleOptions = { version: data.changes.after?.version }; + } +} diff --git a/packages/models/src/activity/Activity/actions/AppVersionUpdatedAction.ts b/packages/models/src/activity/Activity/actions/AppVersionUpdatedAction.ts new file mode 100644 index 00000000..02aad3b7 --- /dev/null +++ b/packages/models/src/activity/Activity/actions/AppVersionUpdatedAction.ts @@ -0,0 +1,19 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { ActivityAction } from "../ActivityAction.js"; + +type ActivityAppInstallationAppVersionUpdated = + MittwaldAPIV2.Components.Schemas.ActivitylogAppInstallationAppVersionSet; + +export class AppVersionUpdatedAction extends ActivityAction { + public readonly parameters; + + constructor(data: ActivityAppInstallationAppVersionUpdated) { + super(data); + + this.parameters = data.parameters; + this.displayName = data.parameters.appInstallation.name; + this.type = "update"; + this.titleOptions = { version: data.changes.after?.version }; + } +} diff --git a/packages/models/src/activity/Activity/actions/DatabaseCreatedAction.ts b/packages/models/src/activity/Activity/actions/DatabaseCreatedAction.ts new file mode 100644 index 00000000..1bd8803d --- /dev/null +++ b/packages/models/src/activity/Activity/actions/DatabaseCreatedAction.ts @@ -0,0 +1,19 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { ActivityAction } from "../ActivityAction.js"; + +type ActivityDatabaseCreated = + MittwaldAPIV2.Components.Schemas.ActivitylogDatabaseCreated; + +export class DatabaseCreatedAction extends ActivityAction { + public readonly parameters; + + constructor(data: ActivityDatabaseCreated) { + super(data); + + this.parameters = data.parameters; + this.displayName = data.parameters.description.name; + this.type = "create"; + this.fieldLabels = { name: "databaseName" }; + } +} diff --git a/packages/models/src/activity/Activity/actions/DatabaseDeletedAction.ts b/packages/models/src/activity/Activity/actions/DatabaseDeletedAction.ts new file mode 100644 index 00000000..0f7b2fe4 --- /dev/null +++ b/packages/models/src/activity/Activity/actions/DatabaseDeletedAction.ts @@ -0,0 +1,19 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { ActivityAction } from "../ActivityAction.js"; + +type ActivityDatabaseDeleted = + MittwaldAPIV2.Components.Schemas.ActivitylogDatabaseDeleted; + +export class DatabaseDeletedAction extends ActivityAction { + public readonly parameters; + + constructor(data: ActivityDatabaseDeleted) { + super(data); + + this.parameters = data.parameters; + this.displayName = data.parameters.description.name; + this.type = "delete"; + this.fieldLabels = { name: "databaseName" }; + } +} diff --git a/packages/models/src/activity/Activity/actions/DatabaseDescriptionSetAction.ts b/packages/models/src/activity/Activity/actions/DatabaseDescriptionSetAction.ts new file mode 100644 index 00000000..dd0683ea --- /dev/null +++ b/packages/models/src/activity/Activity/actions/DatabaseDescriptionSetAction.ts @@ -0,0 +1,23 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { ActivityAction } from "../ActivityAction.js"; + +type ActivityDatabaseDescriptionSet = + MittwaldAPIV2.Components.Schemas.ActivitylogDatabaseDescriptionSet; + +export class DatabaseDescriptionSetAction extends ActivityAction { + public readonly parameters; + + constructor(data: ActivityDatabaseDescriptionSet) { + super(data); + + this.parameters = data.parameters; + this.displayName = data.parameters.description.name; + this.type = "edit"; + this.fieldLabels = { name: "databaseName" }; + this.titleOptions = { + oldDescription: data.changes.before?.description, + description: data.changes.after?.description, + }; + } +} diff --git a/packages/models/src/activity/Activity/actions/DatabaseMySqlUserAction.ts b/packages/models/src/activity/Activity/actions/DatabaseMySqlUserAction.ts new file mode 100644 index 00000000..f9ff1c18 --- /dev/null +++ b/packages/models/src/activity/Activity/actions/DatabaseMySqlUserAction.ts @@ -0,0 +1,35 @@ +import type { ActivityActionData } from "../types.js"; + +import { ActivityAction } from "../ActivityAction.js"; +import { translatable } from "../types.js"; + +/** + * Every `database.mysql-user-*` action names the user through + * `parameters.description` – absent for the main user – and the database + * through `parameters.databaseDescription`. + */ +type DatabaseMySqlUserActionData = Extract< + ActivityActionData, + { name: `database.mysql-user-${string}` } +>; + +export abstract class DatabaseMySqlUserAction< + T extends DatabaseMySqlUserActionData = DatabaseMySqlUserActionData, +> extends ActivityAction { + public readonly parameters: T["parameters"]; + + protected constructor(data: T) { + super(data); + + this.parameters = data.parameters; + this.displayName = data.parameters.description.name; + + this.displayNameFallbackKey = "mainUser"; + this.titleOptions = { + user: this.displayName || translatable("mainUser"), + database: data.parameters.databaseDescription.name, + }; + this.fieldLabels = { name: "userName" }; + this.hideWhenEmptyFields = ["description"]; + } +} diff --git a/packages/models/src/activity/Activity/actions/DatabaseMySqlUserCreatedAction.ts b/packages/models/src/activity/Activity/actions/DatabaseMySqlUserCreatedAction.ts new file mode 100644 index 00000000..61f7ef9c --- /dev/null +++ b/packages/models/src/activity/Activity/actions/DatabaseMySqlUserCreatedAction.ts @@ -0,0 +1,14 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { DatabaseMySqlUserAction } from "./DatabaseMySqlUserAction.js"; + +type ActivityDatabaseMysqlUserCreated = + MittwaldAPIV2.Components.Schemas.ActivitylogDatabaseMysqlUserCreated; + +export class DatabaseMySqlUserCreatedAction extends DatabaseMySqlUserAction { + constructor(data: ActivityDatabaseMysqlUserCreated) { + super(data); + + this.type = "create"; + } +} diff --git a/packages/models/src/activity/Activity/actions/DatabaseMySqlUserDeletedAction.ts b/packages/models/src/activity/Activity/actions/DatabaseMySqlUserDeletedAction.ts new file mode 100644 index 00000000..10d5d7c1 --- /dev/null +++ b/packages/models/src/activity/Activity/actions/DatabaseMySqlUserDeletedAction.ts @@ -0,0 +1,14 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { DatabaseMySqlUserAction } from "./DatabaseMySqlUserAction.js"; + +type ActivityDatabaseMysqlUserDeleted = + MittwaldAPIV2.Components.Schemas.ActivitylogDatabaseMysqlUserDeleted; + +export class DatabaseMySqlUserDeletedAction extends DatabaseMySqlUserAction { + constructor(data: ActivityDatabaseMysqlUserDeleted) { + super(data); + + this.type = "delete"; + } +} diff --git a/packages/models/src/activity/Activity/actions/DatabaseMySqlUserPasswordSetAction.ts b/packages/models/src/activity/Activity/actions/DatabaseMySqlUserPasswordSetAction.ts new file mode 100644 index 00000000..1018fcc1 --- /dev/null +++ b/packages/models/src/activity/Activity/actions/DatabaseMySqlUserPasswordSetAction.ts @@ -0,0 +1,14 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { DatabaseMySqlUserAction } from "./DatabaseMySqlUserAction.js"; + +type ActivityDatabaseMysqlUserPasswordSet = + MittwaldAPIV2.Components.Schemas.ActivitylogDatabaseMysqlUserPasswordSet; + +export class DatabaseMySqlUserPasswordSetAction extends DatabaseMySqlUserAction { + constructor(data: ActivityDatabaseMysqlUserPasswordSet) { + super(data); + + this.type = "edit"; + } +} diff --git a/packages/models/src/activity/Activity/actions/DatabaseMySqlUserUpdatedAction.test.ts b/packages/models/src/activity/Activity/actions/DatabaseMySqlUserUpdatedAction.test.ts new file mode 100644 index 00000000..735cc27d --- /dev/null +++ b/packages/models/src/activity/Activity/actions/DatabaseMySqlUserUpdatedAction.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, test } from "vitest"; + +import type { ActivityActionData } from "../types.js"; + +import { createActivityAction } from "../actionRegistry.js"; + +const permissions = { + permissionsWrite: true, + externalAccess: false, + permissionsRead: true, +}; + +const updatedAction = (changes: object) => + createActivityAction({ + parameters: { + databaseDescription: { name: "my-db" }, + description: { name: "new-name" }, + }, + name: "database.mysql-user-updated", + changes, + } as unknown as ActivityActionData); + +describe("DatabaseMySqlUserUpdatedAction", () => { + test("uses the rename title when only the description changed", () => { + const action = updatedAction({ + before: { description: "old-name", ...permissions }, + after: { description: "new-name", ...permissions }, + }); + + expect(action.titleKey).toBe("database.mysql-user-updated.renamed"); + expect(action.titleOptions).toMatchObject({ + oldDescription: "old-name", + description: "new-name", + database: "my-db", + }); + }); + + test("falls back to the main user label as the old name", () => { + const action = updatedAction({ + after: { description: "new-name", ...permissions }, + before: { description: null, ...permissions }, + }); + + expect(action.titleOptions.oldDescription).toEqual({ + translationKey: "mainUser", + }); + }); + + test.each([ + [ + "a permission changed alongside the description", + { + after: { + description: "new-name", + ...permissions, + permissionsWrite: false, + }, + before: { description: "old-name", ...permissions }, + }, + ], + [ + "only a permission changed", + { + after: { description: "same", ...permissions, externalAccess: true }, + before: { description: "same", ...permissions }, + }, + ], + [ + "one side is missing", + { after: { description: "new-name", ...permissions } }, + ], + ])("keeps the generic title when %s", (_name, changes) => { + expect(updatedAction(changes).titleKey).toBe("database.mysql-user-updated"); + }); +}); diff --git a/packages/models/src/activity/Activity/actions/DatabaseMySqlUserUpdatedAction.ts b/packages/models/src/activity/Activity/actions/DatabaseMySqlUserUpdatedAction.ts new file mode 100644 index 00000000..93dd515a --- /dev/null +++ b/packages/models/src/activity/Activity/actions/DatabaseMySqlUserUpdatedAction.ts @@ -0,0 +1,47 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { DatabaseMySqlUserAction } from "./DatabaseMySqlUserAction.js"; +import { translatable } from "../types.js"; + +type ActivityDatabaseMysqlUserUpdated = + MittwaldAPIV2.Components.Schemas.ActivitylogDatabaseMysqlUserUpdated; + +type UserChanges = ActivityDatabaseMysqlUserUpdated["changes"]; + +/** A plain rename reads better as its own sentence, so it gets its own title. */ +const isDescriptionOnlyChange = (changes: UserChanges): boolean => { + const before = changes.before; + const after = changes.after; + + if (!before || !after) { + return false; + } + + const fields = new Set([...Object.keys(before), ...Object.keys(after)]); + + const changedFields = [...fields].filter( + (field) => + JSON.stringify(before[field as keyof typeof before]) !== + JSON.stringify(after[field as keyof typeof after]), + ); + + return changedFields.length === 1 && changedFields[0] === "description"; +}; + +export class DatabaseMySqlUserUpdatedAction extends DatabaseMySqlUserAction { + constructor(data: ActivityDatabaseMysqlUserUpdated) { + super(data); + + this.type = "edit"; + + if (isDescriptionOnlyChange(data.changes)) { + this.titleKey = `${data.name}.renamed`; + this.titleOptions = { + ...this.titleOptions, + oldDescription: + data.changes.before?.description || translatable("mainUser"), + description: data.changes.after?.description, + }; + } + } +} diff --git a/packages/models/src/activity/Activity/actions/DatabaseVersionSetAction.ts b/packages/models/src/activity/Activity/actions/DatabaseVersionSetAction.ts new file mode 100644 index 00000000..23ca1727 --- /dev/null +++ b/packages/models/src/activity/Activity/actions/DatabaseVersionSetAction.ts @@ -0,0 +1,21 @@ +import type { ActivityActionData } from "../types.js"; + +import { ActivityAction } from "../ActivityAction.js"; + +type ActivityDatabaseVersionSet = Extract< + ActivityActionData, + { name: `database.${string}-version-set` } +>; + +export class DatabaseVersionSetAction extends ActivityAction { + public readonly parameters; + + constructor(data: ActivityDatabaseVersionSet) { + super(data); + + this.parameters = data.parameters; + this.displayName = data.parameters.description.name; + this.type = "update"; + this.titleOptions = { version: data.changes.after?.version }; + } +} diff --git a/packages/models/src/activity/Activity/actions/DnsARecordSetAction.ts b/packages/models/src/activity/Activity/actions/DnsARecordSetAction.ts new file mode 100644 index 00000000..aa7b738e --- /dev/null +++ b/packages/models/src/activity/Activity/actions/DnsARecordSetAction.ts @@ -0,0 +1,8 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { DnsRecordSetAction } from "./DnsRecordSetAction.js"; + +type ActivityDnsARecordSet = + MittwaldAPIV2.Components.Schemas.ActivitylogDnsARecordSet; + +export class DnsARecordSetAction extends DnsRecordSetAction {} diff --git a/packages/models/src/activity/Activity/actions/DnsARecordSetManagedAction.ts b/packages/models/src/activity/Activity/actions/DnsARecordSetManagedAction.ts new file mode 100644 index 00000000..1d376084 --- /dev/null +++ b/packages/models/src/activity/Activity/actions/DnsARecordSetManagedAction.ts @@ -0,0 +1,8 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { DnsRecordAction } from "./DnsRecordAction.js"; + +type ActivityDnsARecordSetManaged = + MittwaldAPIV2.Components.Schemas.ActivitylogDnsARecordSetManaged; + +export class DnsARecordSetManagedAction extends DnsRecordAction {} diff --git a/packages/models/src/activity/Activity/actions/DnsCaaRecordSetAction.ts b/packages/models/src/activity/Activity/actions/DnsCaaRecordSetAction.ts new file mode 100644 index 00000000..a188f449 --- /dev/null +++ b/packages/models/src/activity/Activity/actions/DnsCaaRecordSetAction.ts @@ -0,0 +1,8 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { DnsRecordSetAction } from "./DnsRecordSetAction.js"; + +type ActivityDnsCaaRecordSet = + MittwaldAPIV2.Components.Schemas.ActivitylogDnsCaaRecordSet; + +export class DnsCaaRecordSetAction extends DnsRecordSetAction {} diff --git a/packages/models/src/activity/Activity/actions/DnsCnameRecordSetAction.ts b/packages/models/src/activity/Activity/actions/DnsCnameRecordSetAction.ts new file mode 100644 index 00000000..6d87286a --- /dev/null +++ b/packages/models/src/activity/Activity/actions/DnsCnameRecordSetAction.ts @@ -0,0 +1,8 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { DnsRecordSetAction } from "./DnsRecordSetAction.js"; + +type ActivityDnsCnameRecordSet = + MittwaldAPIV2.Components.Schemas.ActivitylogDnsCnameRecordSet; + +export class DnsCnameRecordSetAction extends DnsRecordSetAction {} diff --git a/packages/models/src/activity/Activity/actions/DnsMxRecordSetAction.ts b/packages/models/src/activity/Activity/actions/DnsMxRecordSetAction.ts new file mode 100644 index 00000000..4b74948b --- /dev/null +++ b/packages/models/src/activity/Activity/actions/DnsMxRecordSetAction.ts @@ -0,0 +1,8 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { DnsRecordSetAction } from "./DnsRecordSetAction.js"; + +type ActivityDnsMxRecordSet = + MittwaldAPIV2.Components.Schemas.ActivitylogDnsMxRecordSet; + +export class DnsMxRecordSetAction extends DnsRecordSetAction {} diff --git a/packages/models/src/activity/Activity/actions/DnsMxRecordSetManagedAction.ts b/packages/models/src/activity/Activity/actions/DnsMxRecordSetManagedAction.ts new file mode 100644 index 00000000..83f97619 --- /dev/null +++ b/packages/models/src/activity/Activity/actions/DnsMxRecordSetManagedAction.ts @@ -0,0 +1,8 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { DnsRecordAction } from "./DnsRecordAction.js"; + +type ActivityDnsMxRecordSetManaged = + MittwaldAPIV2.Components.Schemas.ActivitylogDnsMxRecordSetManaged; + +export class DnsMxRecordSetManagedAction extends DnsRecordAction {} diff --git a/packages/models/src/activity/Activity/actions/DnsRecordAction.ts b/packages/models/src/activity/Activity/actions/DnsRecordAction.ts new file mode 100644 index 00000000..97ac61d4 --- /dev/null +++ b/packages/models/src/activity/Activity/actions/DnsRecordAction.ts @@ -0,0 +1,31 @@ +import type { ActivityActionData } from "../types.js"; + +import { ActivityAction } from "../ActivityAction.js"; + +/** + * Both the custom (`dns.-record-set`) and the mittwald managed + * (`dns.-record-set-managed`) record set actions. The managed ones send + * the literal `"managed"` in `changes.after` and the replaced records in + * `changes.before` – differing shapes the generated schemas do not express. + */ +type DnsRecordActionData = Extract< + ActivityActionData, + { name: `dns.${string}-record-set-managed` | `dns.${string}-record-set` } +>; + +export abstract class DnsRecordAction< + T extends DnsRecordActionData = DnsRecordActionData, +> extends ActivityAction { + public readonly parameters: T["parameters"]; + + public constructor(data: T) { + super(data); + + this.parameters = data.parameters; + this.displayName = data.parameters.domain.name; + this.type = "edit"; + + this.valuesAreCopyable = true; + this.hasWideChanges = true; + } +} diff --git a/packages/models/src/activity/Activity/actions/DnsRecordSetAction.test.ts b/packages/models/src/activity/Activity/actions/DnsRecordSetAction.test.ts new file mode 100644 index 00000000..4a837c61 --- /dev/null +++ b/packages/models/src/activity/Activity/actions/DnsRecordSetAction.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, test } from "vitest"; + +import type { DnsRecordSetActionData } from "./DnsRecordSetAction.js"; + +import { DnsMxRecordSetAction } from "./DnsMxRecordSetAction.js"; +import { getDnsRecordChangeType } from "./DnsRecordSetAction.js"; + +const changesOf = (changes: object): DnsRecordSetActionData["changes"] => + changes as DnsRecordSetActionData["changes"]; + +describe("getDnsRecordChangeType", () => { + test("detects a created record set", () => { + expect( + getDnsRecordChangeType(changesOf({ after: { txt: ["v=spf1 -all"] } })), + ).toBe("created"); + }); + + test("detects a deleted record set", () => { + expect( + getDnsRecordChangeType(changesOf({ before: { txt: ["v=spf1 -all"] } })), + ).toBe("deleted"); + }); + + test("detects a changed record set", () => { + expect( + getDnsRecordChangeType( + changesOf({ before: { txt: ["a"] }, after: { txt: ["b"] } }), + ), + ).toBe("changed"); + }); + + test("treats empty values as an absent side", () => { + expect( + getDnsRecordChangeType( + changesOf({ before: { aaaaRecords: [], aRecords: [] }, after: {} }), + ), + ).toBe("changed"); + + expect( + getDnsRecordChangeType( + changesOf({ + after: { aRecords: ["127.0.0.1"] }, + before: { aRecords: [] }, + }), + ), + ).toBe("created"); + + expect( + getDnsRecordChangeType( + changesOf({ + before: { cname: "www.example.com" }, + after: { cname: "" }, + }), + ), + ).toBe("deleted"); + }); +}); + +describe("DnsRecordSetAction", () => { + test("derives activity type and title key from the change type", () => { + const action = new DnsMxRecordSetAction({ + parameters: { domain: { name: "example.com" } }, + changes: { before: { mx: [{}] } }, + name: "dns.mx-record-set", + } as never); + + expect(action.recordChangeType).toBe("deleted"); + expect(action.type).toBe("delete"); + expect(action.titleKey).toBe("dns.mx-record-set.deleted"); + expect(action.displayName).toBe("example.com"); + }); +}); diff --git a/packages/models/src/activity/Activity/actions/DnsRecordSetAction.ts b/packages/models/src/activity/Activity/actions/DnsRecordSetAction.ts new file mode 100644 index 00000000..c2faf44b --- /dev/null +++ b/packages/models/src/activity/Activity/actions/DnsRecordSetAction.ts @@ -0,0 +1,65 @@ +import type { ActivityActionData, ActivityType } from "../types.js"; + +import { DnsRecordAction } from "./DnsRecordAction.js"; + +/** + * Created, changed or deleted – the API tells them apart only by which side of + * `changes` carries values. + */ +type DnsRecordChangeType = "created" | "changed" | "deleted"; + +export type DnsRecordSetActionData = Extract< + ActivityActionData, + { name: `dns.${string}-record-set` } +>; + +const activityTypeByRecordChangeType: Record< + DnsRecordChangeType, + ActivityType +> = { + created: "create", + deleted: "delete", + changed: "edit", +}; + +const isEmptyRecordValue = (value: unknown): boolean => + value === undefined || + value === null || + value === "" || + (Array.isArray(value) && value.length === 0); + +const hasRecordValues = (side: unknown): boolean => + typeof side === "object" && + side !== null && + Object.values(side).some((value) => !isEmptyRecordValue(value)); + +export const getDnsRecordChangeType = ( + changes: DnsRecordSetActionData["changes"], +): DnsRecordChangeType => { + const hasBefore = hasRecordValues(changes.before); + const hasAfter = hasRecordValues(changes.after); + + if (hasBefore && !hasAfter) { + return "deleted"; + } + + if (!hasBefore && hasAfter) { + return "created"; + } + + return "changed"; +}; + +export abstract class DnsRecordSetAction< + T extends DnsRecordSetActionData = DnsRecordSetActionData, +> extends DnsRecordAction { + public readonly recordChangeType: DnsRecordChangeType; + + public constructor(data: T) { + super(data); + + this.recordChangeType = getDnsRecordChangeType(data.changes); + this.type = activityTypeByRecordChangeType[this.recordChangeType]; + this.titleKey = `${data.name}.${this.recordChangeType}`; + } +} diff --git a/packages/models/src/activity/Activity/actions/DnsSrvRecordSetAction.ts b/packages/models/src/activity/Activity/actions/DnsSrvRecordSetAction.ts new file mode 100644 index 00000000..9ec905f2 --- /dev/null +++ b/packages/models/src/activity/Activity/actions/DnsSrvRecordSetAction.ts @@ -0,0 +1,8 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { DnsRecordSetAction } from "./DnsRecordSetAction.js"; + +type ActivityDnsSrvRecordSet = + MittwaldAPIV2.Components.Schemas.ActivitylogDnsSrvRecordSet; + +export class DnsSrvRecordSetAction extends DnsRecordSetAction {} diff --git a/packages/models/src/activity/Activity/actions/DnsTxtRecordSetAction.ts b/packages/models/src/activity/Activity/actions/DnsTxtRecordSetAction.ts new file mode 100644 index 00000000..f8ef3fcc --- /dev/null +++ b/packages/models/src/activity/Activity/actions/DnsTxtRecordSetAction.ts @@ -0,0 +1,8 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { DnsRecordSetAction } from "./DnsRecordSetAction.js"; + +type ActivityDnsTxtRecordSet = + MittwaldAPIV2.Components.Schemas.ActivitylogDnsTxtRecordSet; + +export class DnsTxtRecordSetAction extends DnsRecordSetAction {} diff --git a/packages/models/src/activity/Activity/actions/DnsZoneCreatedAction.ts b/packages/models/src/activity/Activity/actions/DnsZoneCreatedAction.ts new file mode 100644 index 00000000..d0c92031 --- /dev/null +++ b/packages/models/src/activity/Activity/actions/DnsZoneCreatedAction.ts @@ -0,0 +1,18 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { ActivityAction } from "../ActivityAction.js"; + +type ActivityDnsZoneCreated = + MittwaldAPIV2.Components.Schemas.ActivitylogDnsZoneCreated; + +export class DnsZoneCreatedAction extends ActivityAction { + public readonly parameters; + + constructor(data: ActivityDnsZoneCreated) { + super(data); + + this.parameters = data.parameters; + this.displayName = data.parameters.domain.name; + this.type = "create"; + } +} diff --git a/packages/models/src/activity/Activity/actions/DnsZoneDeletedAction.ts b/packages/models/src/activity/Activity/actions/DnsZoneDeletedAction.ts new file mode 100644 index 00000000..049bb8f0 --- /dev/null +++ b/packages/models/src/activity/Activity/actions/DnsZoneDeletedAction.ts @@ -0,0 +1,18 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { ActivityAction } from "../ActivityAction.js"; + +type ActivityDnsZoneDeleted = + MittwaldAPIV2.Components.Schemas.ActivitylogDnsZoneDeleted; + +export class DnsZoneDeletedAction extends ActivityAction { + public readonly parameters; + + constructor(data: ActivityDnsZoneDeleted) { + super(data); + + this.parameters = data.parameters; + this.displayName = data.parameters.domain.name; + this.type = "delete"; + } +} diff --git a/packages/models/src/activity/Activity/actions/DomainDeletedAction.ts b/packages/models/src/activity/Activity/actions/DomainDeletedAction.ts new file mode 100644 index 00000000..c199af33 --- /dev/null +++ b/packages/models/src/activity/Activity/actions/DomainDeletedAction.ts @@ -0,0 +1,18 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { ActivityAction } from "../ActivityAction.js"; + +type ActivityDomainDeleted = + MittwaldAPIV2.Components.Schemas.ActivitylogDnsDomainDeleted; + +export class DomainDeletedAction extends ActivityAction { + public readonly parameters; + + constructor(data: ActivityDomainDeleted) { + super(data); + + this.parameters = data.parameters; + this.displayName = data.parameters.domain.name; + this.type = "delete"; + } +} diff --git a/packages/models/src/activity/Activity/actions/GenericAction.ts b/packages/models/src/activity/Activity/actions/GenericAction.ts new file mode 100644 index 00000000..4fcf0403 --- /dev/null +++ b/packages/models/src/activity/Activity/actions/GenericAction.ts @@ -0,0 +1,13 @@ +import type { ActivityGenericActionData } from "../types.js"; + +import { ActivityAction } from "../ActivityAction.js"; + +/** + * Fallback for names the registry does not know. Renders without a display name + * and without a title translation, so it is a stopgap, not a target. + */ +export class GenericAction extends ActivityAction { + constructor(data: ActivityGenericActionData) { + super(data); + } +} diff --git a/packages/models/src/activity/Activity/actions/IngressDeletedAction.ts b/packages/models/src/activity/Activity/actions/IngressDeletedAction.ts new file mode 100644 index 00000000..8438392f --- /dev/null +++ b/packages/models/src/activity/Activity/actions/IngressDeletedAction.ts @@ -0,0 +1,18 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { ActivityAction } from "../ActivityAction.js"; + +type ActivityIngressDeleted = + MittwaldAPIV2.Components.Schemas.ActivitylogDnsIngressDeleted; + +export class IngressDeletedAction extends ActivityAction { + public readonly parameters; + + constructor(data: ActivityIngressDeleted) { + super(data); + + this.parameters = data.parameters; + this.displayName = data.parameters.domain.name; + this.type = "delete"; + } +} diff --git a/packages/models/src/activity/Activity/actions/index.ts b/packages/models/src/activity/Activity/actions/index.ts new file mode 100644 index 00000000..8b83523f --- /dev/null +++ b/packages/models/src/activity/Activity/actions/index.ts @@ -0,0 +1,36 @@ +export * from "./AppCopyRequestedAction.js"; +export * from "./AppDatabaseLinkedAction.js"; +export * from "./AppDatabaseUnlinkedAction.js"; +export * from "./AppDeletedAction.js"; +export * from "./AppDescriptionSetAction.js"; +export * from "./AppFailedAction.js"; +export * from "./AppInstallationRequestedAction.js"; +export * from "./AppMainDatabaseChangedAction.js"; +export * from "./AppSystemSoftwareDeletedAction.js"; +export * from "./AppSystemSoftwareSetAction.js"; +export * from "./AppVersionSetAction.js"; +export * from "./AppVersionUpdatedAction.js"; +export * from "./DatabaseCreatedAction.js"; +export * from "./DatabaseDeletedAction.js"; +export * from "./DatabaseDescriptionSetAction.js"; +export * from "./DatabaseMySqlUserAction.js"; +export * from "./DatabaseMySqlUserCreatedAction.js"; +export * from "./DatabaseMySqlUserDeletedAction.js"; +export * from "./DatabaseMySqlUserPasswordSetAction.js"; +export * from "./DatabaseMySqlUserUpdatedAction.js"; +export * from "./DatabaseVersionSetAction.js"; +export * from "./DnsARecordSetAction.js"; +export * from "./DnsARecordSetManagedAction.js"; +export * from "./DnsCaaRecordSetAction.js"; +export * from "./DnsCnameRecordSetAction.js"; +export * from "./DnsMxRecordSetAction.js"; +export * from "./DnsMxRecordSetManagedAction.js"; +export * from "./DnsRecordAction.js"; +export * from "./DnsRecordSetAction.js"; +export * from "./DnsSrvRecordSetAction.js"; +export * from "./DnsTxtRecordSetAction.js"; +export * from "./DnsZoneCreatedAction.js"; +export * from "./DnsZoneDeletedAction.js"; +export * from "./DomainDeletedAction.js"; +export * from "./GenericAction.js"; +export * from "./IngressDeletedAction.js"; diff --git a/packages/models/src/activity/Activity/behaviors/api.ts b/packages/models/src/activity/Activity/behaviors/api.ts new file mode 100644 index 00000000..9e597e0c --- /dev/null +++ b/packages/models/src/activity/Activity/behaviors/api.ts @@ -0,0 +1,35 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; +import type { AxiosRequestConfig } from "axios"; + +import type { ActivityBehaviors } from "./types.js"; + +import { + withAxiosRequestConfig, + resolveTotalCount, + validateResponse, +} from "../../../base/index.js"; + +export const apiActivityBehaviors = ( + client: MittwaldAPIV2Client, +): ActivityBehaviors => ({ + list: async (projectId, query) => { + const response = await client.project.listProjectActivities( + { + queryParameters: query, + projectId, + }, + withAxiosRequestConfig({ + retryCache: { + cache: false, + }, + } as AxiosRequestConfig), + ); + + validateResponse(response, 200); + + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, +}); diff --git a/packages/models/src/activity/Activity/behaviors/index.ts b/packages/models/src/activity/Activity/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/activity/Activity/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/activity/Activity/behaviors/types.ts b/packages/models/src/activity/Activity/behaviors/types.ts new file mode 100644 index 00000000..2f73ad37 --- /dev/null +++ b/packages/models/src/activity/Activity/behaviors/types.ts @@ -0,0 +1,9 @@ +import type { ActivityListQueryData, ActivityListItemData } from "../types.js"; +import type { QueryResponseData } from "../../../base/index.js"; + +export interface ActivityBehaviors { + list: ( + projectId: string, + query?: ActivityListQueryData, + ) => Promise>; +} diff --git a/packages/models/src/activity/Activity/index.ts b/packages/models/src/activity/Activity/index.ts new file mode 100644 index 00000000..cd6fb6ef --- /dev/null +++ b/packages/models/src/activity/Activity/index.ts @@ -0,0 +1,5 @@ +export * from "./actionRegistry.js"; +export * from "./actions/index.js"; +export * from "./Activity.js"; +export * from "./ActivityAction.js"; +export * from "./types.js"; diff --git a/packages/models/src/activity/Activity/types.ts b/packages/models/src/activity/Activity/types.ts new file mode 100644 index 00000000..4cdc7206 --- /dev/null +++ b/packages/models/src/activity/Activity/types.ts @@ -0,0 +1,47 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type ActivityListItemData = + MittwaldAPIV2.Components.Schemas.ActivitylogLogEntry; + +export type ActivityGenericActionData = + MittwaldAPIV2.Components.Schemas.ActivitylogGenericAction; + +export type ActivityActionData = ActivityListItemData["action"]; + +export type ActivityListQueryData = + MittwaldAPIV2.Paths.V2ProjectsProjectIdActivities.Get.Parameters.Query; + +export type ActivityType = + "update" | "delete" | "create" | "copy" | "edit" | "fail" | "info"; + +/** A title placeholder that has to be translated rather than printed. */ +interface TranslatableValue { + translationKey: string; +} + +export const translatable = (translationKey: string): TranslatableValue => ({ + translationKey, +}); + +export const isTranslatableValue = ( + value: unknown, +): value is TranslatableValue => + typeof value === "object" && value !== null && "translationKey" in value; + +/** + * `ActivityActionData["name"]` alone is `string`: the generic fallback action + * types its name that way and widens the union. Dropping the member whose name + * did not narrow leaves the literal union the action registry needs. + */ +export type KnownActionName = T extends { + name: infer TName; +} + ? string extends TName + ? never + : TName + : never; + +export type ActionDataByName = Extract< + ActivityActionData, + { name: TName } +>; diff --git a/packages/models/src/activity/index.ts b/packages/models/src/activity/index.ts new file mode 100644 index 00000000..4b79fb3f --- /dev/null +++ b/packages/models/src/activity/index.ts @@ -0,0 +1 @@ +export * from "./Activity/index.js"; diff --git a/packages/models/src/ai/AIModel/AIModel.test.ts b/packages/models/src/ai/AIModel/AIModel.test.ts new file mode 100644 index 00000000..85cedb8e --- /dev/null +++ b/packages/models/src/ai/AIModel/AIModel.test.ts @@ -0,0 +1,57 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { buildAIModelData } from "../../testing/builders/buildAIModelData.js"; +import { ListQueryModel, ReferenceModel } from "../../base/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { + AIModelListQuery, + AIModelListItem, + AIModelList, + AIModel, +} from "./AIModel.js"; + +afterEach(resetBehaviors); + +describe("AIModel", () => { + it("delegates list queries and maps the result", async () => { + const data = buildAIModelData({ displayName: "GPT One", name: "gpt-1" }); + const list = vi.fn().mockResolvedValue({ items: [data], totalCount: 1 }); + installBehaviors({ aiModel: { list } }); + + const result = await AIModel.query().execute(); + + expect(list).toHaveBeenCalledWith({}); + expect(result).toBeInstanceOf(AIModelList); + expect(result.items[0]).toBeInstanceOf(AIModelListItem); + expect(result.items[0]).toMatchObject({ + displayName: "GPT One", + name: "gpt-1", + }); + expect(result.totalCount).toBe(1); + }); + + it("exposes model data through derived getters", () => { + const item = new AIModelListItem(buildAIModelData()); + + expect(item.documentationLink).toBe("https://docs.example.com/model"); + expect(item.termsOfServiceLink).toBe("https://tos.example.com/model"); + expect(item.tokenFactor).toBe(1); + expect(item.label).toBe("stable"); + }); + + it("preserves the model inheritance chains", () => { + const item = new AIModelListItem(buildAIModelData()); + const list = new AIModelList({}, [item], 1); + + expect(item).toBeInstanceOf(AIModelListItem); + expect(item).toBeInstanceOf(AIModel); + expect(item).toBeInstanceOf(ReferenceModel); + expect(item.data).toBeDefined(); + expect(list).toBeInstanceOf(AIModelListQuery); + expect(list).toBeInstanceOf(ListQueryModel); + expect(list.items).toBeDefined(); + }); +}); diff --git a/packages/models/src/ai/AIModel/AIModel.ts b/packages/models/src/ai/AIModel/AIModel.ts new file mode 100644 index 00000000..df3df27e --- /dev/null +++ b/packages/models/src/ai/AIModel/AIModel.ts @@ -0,0 +1,102 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; + +import type { + AIModelListQueryData, + AIModelListItemData, + AIModelLabel, + AIModelData, +} from "./types.js"; + +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "AIModel", +}) +export class AIModel extends ReferenceModel { + public constructor(id: string) { + super(id); + } + + public static query = () => { + return new AIModelListQuery(); + }; +} + +export class AIModelCommon extends WithData< + AIModelListItemData | AIModelData +>()(AIModel) { + public override readonly data: AIModelListItemData | AIModelData; + public readonly displayName: string; + public readonly documentationLink: string; + public readonly label?: AIModelLabel; + public readonly name: string; + public readonly termsOfServiceLink: string; + public readonly tokenFactor: number; + + public constructor(data: AIModelListItemData | AIModelData) { + super(data.name); + this.data = data; + this.name = data.name; + this.displayName = data.displayName; + this.documentationLink = data.docLink; + this.termsOfServiceLink = data.termsOfServiceLink; + this.tokenFactor = data.tokenFactor; + this.label = data.label; + } +} + +export class AIModelDetailed extends AIModelCommon { + public override readonly data: AIModelData; + public constructor(data: AIModelData) { + super(data); + this.data = data; + } +} + +export class AIModelListItem extends AIModelCommon { + public override readonly data: AIModelListItemData; + public constructor(data: AIModelListItemData) { + super(data); + this.data = data; + } +} + +export class AIModelListQuery extends ListQueryModel { + public constructor(query: AIModelListQueryData = {}) { + super(query); + } + + public async execute() { + const { totalCount, items } = await config.behaviors.aiModel.list( + this.query, + ); + + return new AIModelList( + this.query, + items.map((item) => new AIModelListItem(item)), + totalCount, + ); + } +} + +export class AIModelList extends WithListData()( + AIModelListQuery, +) { + public override readonly items: readonly AIModelListItem[]; + public override readonly totalCount: number; + public constructor( + query: AIModelListQueryData, + items: AIModelListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(items); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/ai/AIModel/behaviors/api.ts b/packages/models/src/ai/AIModel/behaviors/api.ts new file mode 100644 index 00000000..3a3cb261 --- /dev/null +++ b/packages/models/src/ai/AIModel/behaviors/api.ts @@ -0,0 +1,21 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { AIModelBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount } from "../../../base/index.js"; + +export const apiAIModelBehaviors = ( + client: MittwaldAPIV2Client, +): AIModelBehaviors => ({ + list: async () => { + const response = await client.aiHosting.getModels(); + + validateResponse(response, 200); + + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, +}); diff --git a/packages/models/src/ai/AIModel/behaviors/index.ts b/packages/models/src/ai/AIModel/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/ai/AIModel/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/ai/AIModel/behaviors/types.ts b/packages/models/src/ai/AIModel/behaviors/types.ts new file mode 100644 index 00000000..bf9bcfdb --- /dev/null +++ b/packages/models/src/ai/AIModel/behaviors/types.ts @@ -0,0 +1,7 @@ +import type { AIModelListQueryData, AIModelListItemData } from "../types.js"; + +export interface AIModelBehaviors { + list: ( + query?: AIModelListQueryData, + ) => Promise<{ items: AIModelListItemData[]; totalCount: number }>; +} diff --git a/packages/models/src/ai/AIModel/index.ts b/packages/models/src/ai/AIModel/index.ts new file mode 100644 index 00000000..70b41150 --- /dev/null +++ b/packages/models/src/ai/AIModel/index.ts @@ -0,0 +1,2 @@ +export * from "./AIModel.js"; +export * from "./types.js"; diff --git a/packages/models/src/ai/AIModel/types.ts b/packages/models/src/ai/AIModel/types.ts new file mode 100644 index 00000000..3409bccf --- /dev/null +++ b/packages/models/src/ai/AIModel/types.ts @@ -0,0 +1,12 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type AIModelData = + MittwaldAPIV2.Operations.AiHostingGetModels.ResponseData[number]; + +export type AIModelListItemData = AIModelData; + +export type AIModelLabel = + "legacy stable" | "experimental" | "preview" | "stable" | "lts"; + +// eslint-disable-next-line @typescript-eslint/no-empty-object-type +export interface AIModelListQueryData {} diff --git a/packages/models/src/ai/AITokenStatistics/AITokenStatistics.ts b/packages/models/src/ai/AITokenStatistics/AITokenStatistics.ts new file mode 100644 index 00000000..831e01c4 --- /dev/null +++ b/packages/models/src/ai/AITokenStatistics/AITokenStatistics.ts @@ -0,0 +1,55 @@ +import type { AxiosRequestConfig } from "axios"; + +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; + +import type { + AIBillingPeriodsData, + AITokenUsageRange, + AITokenUsageData, +} from "./types.js"; + +import { ReferenceModel } from "../../base/index.js"; +import { config } from "../../config/index.js"; + +/** + * Token statistics of a single AI-hosting plan. The billing periods and the + * usage numbers come from two separate endpoints: the periods tell you which + * timeframes exist, the usage route only answers for a timeframe you pass in. + */ +@GhostMakerModel({ + name: "AITokenStatistics", +}) +export class AITokenStatistics extends ReferenceModel { + public readonly customerId: string; + + public constructor(planId: string, customerId: string) { + super(planId); + this.customerId = customerId; + } + + public static ofPlan(customerId: string, planId: string) { + return new AITokenStatistics(planId, customerId); + } + + public async getBillingPeriods( + options?: AxiosRequestConfig, + ): Promise { + return config.behaviors.aiTokenStatistics.getBillingPeriods( + this.customerId, + this.id, + options, + ); + } + + public async getUsage( + range: AITokenUsageRange, + options?: AxiosRequestConfig, + ): Promise { + return config.behaviors.aiTokenStatistics.getUsage( + this.customerId, + this.id, + range, + options, + ); + } +} diff --git a/packages/models/src/ai/AITokenStatistics/behaviors/api.ts b/packages/models/src/ai/AITokenStatistics/behaviors/api.ts new file mode 100644 index 00000000..94adf5e5 --- /dev/null +++ b/packages/models/src/ai/AITokenStatistics/behaviors/api.ts @@ -0,0 +1,41 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { AITokenStatisticsBehaviors } from "./types.js"; + +import { + withAxiosRequestConfig, + validateResponse, +} from "../../../base/index.js"; + +export const apiAITokenStatisticsBehaviors = ( + client: MittwaldAPIV2Client, +): AITokenStatisticsBehaviors => ({ + getUsage: async (customerId, planId, range, options) => { + const response = await client.aiHosting.planGetUsageStats( + { + queryParameters: { + startDate: range.startDate, + endDate: range.endDate, + }, + customerId, + planId, + }, + withAxiosRequestConfig(options), + ); + + validateResponse(response, 200); + + return response.data; + }, + + getBillingPeriods: async (customerId, planId, options) => { + const response = await client.aiHosting.planGetBillingPeriods( + { customerId, planId }, + withAxiosRequestConfig(options), + ); + + validateResponse(response, 200); + + return response.data; + }, +}); diff --git a/packages/models/src/ai/AITokenStatistics/behaviors/index.ts b/packages/models/src/ai/AITokenStatistics/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/ai/AITokenStatistics/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/ai/AITokenStatistics/behaviors/types.ts b/packages/models/src/ai/AITokenStatistics/behaviors/types.ts new file mode 100644 index 00000000..0fd6dd57 --- /dev/null +++ b/packages/models/src/ai/AITokenStatistics/behaviors/types.ts @@ -0,0 +1,21 @@ +import type { AxiosRequestConfig } from "axios"; + +import type { + AIBillingPeriodsData, + AITokenUsageRange, + AITokenUsageData, +} from "../types.js"; + +export interface AITokenStatisticsBehaviors { + getUsage: ( + customerId: string, + planId: string, + range: AITokenUsageRange, + options?: AxiosRequestConfig, + ) => Promise; + getBillingPeriods: ( + customerId: string, + planId: string, + options?: AxiosRequestConfig, + ) => Promise; +} diff --git a/packages/models/src/ai/AITokenStatistics/index.ts b/packages/models/src/ai/AITokenStatistics/index.ts new file mode 100644 index 00000000..50e0e0ea --- /dev/null +++ b/packages/models/src/ai/AITokenStatistics/index.ts @@ -0,0 +1,2 @@ +export * from "./AITokenStatistics.js"; +export * from "./types.js"; diff --git a/packages/models/src/ai/AITokenStatistics/types.ts b/packages/models/src/ai/AITokenStatistics/types.ts new file mode 100644 index 00000000..e3b87f76 --- /dev/null +++ b/packages/models/src/ai/AITokenStatistics/types.ts @@ -0,0 +1,20 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type AIBillingPeriodsData = + MittwaldAPIV2.Operations.AiHostingPlanGetBillingPeriods.ResponseData; + +export type AIBillingPeriodData = AIBillingPeriodsData["periods"][number]; + +export type AITokenUsageData = + MittwaldAPIV2.Operations.AiHostingPlanGetUsageStats.ResponseData; + +export type AIDailyTokenUsageData = AITokenUsageData["daily"][number]; + +export type AITokenUsageKeyData = AITokenUsageData["keys"][number]; + +export type AIModelUsageData = AITokenUsageData["modelShare"][number]; + +export interface AITokenUsageRange { + startDate: string; + endDate: string; +} diff --git a/packages/models/src/ai/CustomerAIApiKey/CustomerAIApiKey.test.ts b/packages/models/src/ai/CustomerAIApiKey/CustomerAIApiKey.test.ts new file mode 100644 index 00000000..8317a2f6 --- /dev/null +++ b/packages/models/src/ai/CustomerAIApiKey/CustomerAIApiKey.test.ts @@ -0,0 +1,251 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { buildAIApiKeyData } from "../../testing/builders/buildAIApiKeyData.js"; +import { buildIngressData } from "../../testing/builders/buildIngressData.js"; +import { ReferenceModel } from "../../base/index.js"; +import { Customer } from "../../customer/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { + CustomerAIApiKeyDetailed, + CustomerAIApiKeyListItem, + CustomerAIApiKey, +} from "./CustomerAIApiKey.js"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +afterEach(resetBehaviors); + +describe("CustomerAIApiKey", () => { + it("finds and maps a detailed API key", async () => { + const find = vi.fn().mockResolvedValue(buildAIApiKeyData({ keyId: "k-1" })); + installBehaviors({ customerAiApiKey: { find } }); + + const result = await CustomerAIApiKey.find("c-1", "k-1"); + + expect(find).toHaveBeenCalledWith("c-1", "k-1"); + expect(result).toBeInstanceOf(CustomerAIApiKeyDetailed); + expect(result?.id).toBe("k-1"); + }); + + it("returns undefined when an API key is not found", async () => { + installBehaviors({ + customerAiApiKey: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + CustomerAIApiKey.find("c-1", "missing"), + ).resolves.toBeUndefined(); + }); + + it("throws when getting a missing API key", async () => { + installBehaviors({ + customerAiApiKey: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(CustomerAIApiKey.get("c-1", "missing")).rejects.toThrow(); + }); + + it("exposes related models and formatted token usage", () => { + const detailed = new CustomerAIApiKeyDetailed(buildAIApiKeyData()); + const withoutProject = new CustomerAIApiKeyDetailed( + buildAIApiKeyData({ projectId: undefined }), + ); + + expect(detailed.customer.id).toBe("customer-id"); + expect(typeof detailed.tokenUsage.formattedUsed).toBe("string"); + expect(detailed.project?.id).toBe("project-id"); + expect(withoutProject.project).toBeUndefined(); + }); + + it("delegates updates and deletion", async () => { + const update = vi.fn().mockResolvedValue(undefined); + const deleteBehavior = vi.fn().mockResolvedValue(undefined); + installBehaviors({ customerAiApiKey: { delete: deleteBehavior, update } }); + const detailed = new CustomerAIApiKeyDetailed(buildAIApiKeyData()); + + await detailed.updateName("new"); + await detailed.linkProject("p-9", true); + await detailed.delete(); + + expect(update).toHaveBeenCalledWith("customer-id", "key-id", { + name: "new", + }); + expect(update).toHaveBeenCalledWith("customer-id", "key-id", { + createWebuiContainer: true, + projectId: "p-9", + }); + expect(deleteBehavior).toHaveBeenCalledWith("customer-id", "key-id"); + }); + + it("creates an API key for a customer", async () => { + const create = vi.fn().mockResolvedValue({ id: "new-key" }); + installBehaviors({ customerAiApiKey: { create } }); + const requestData = { + planId: "plan-1", + name: "new key", + models: [], + }; + + const result = await CustomerAIApiKey.create( + Customer.ofId("c-1"), + requestData, + ); + + expect(create).toHaveBeenCalledWith("c-1", requestData); + expect(result).toBeInstanceOf(CustomerAIApiKey); + expect(result).toMatchObject({ customerId: "c-1", id: "new-key" }); + }); + + it("returns a detailed instance directly from common lookups", async () => { + const detailed = new CustomerAIApiKeyDetailed(buildAIApiKeyData()); + + await expect(detailed.getCommon()).resolves.toBe(detailed); + await expect(detailed.findCommon()).resolves.toBe(detailed); + }); + + it("preserves the list item inheritance chain", () => { + const item = new CustomerAIApiKeyListItem(buildAIApiKeyData()); + + expect(item).toBeInstanceOf(CustomerAIApiKeyListItem); + expect(item).toBeInstanceOf(CustomerAIApiKey); + expect(item).toBeInstanceOf(ReferenceModel); + expect(item.data).toBeDefined(); + }); +}); + +describe("CustomerAIApiKey container-related ingress", () => { + const containerMeta = { + containerId: "container-1", + status: "created" as const, + ingressId: "ingress-1", + stackId: "stack-1", + }; + + it("returns no related ingress without container metadata", async () => { + const detailed = new CustomerAIApiKeyDetailed( + buildAIApiKeyData({ containerMeta: undefined }), + ); + + await expect( + detailed.getContainerRelatedIngress(), + ).resolves.toBeUndefined(); + }); + + it("returns the ingress matching the container metadata ingress id", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildIngressData({ id: "ingress-1" })], + totalCount: 1, + }); + installBehaviors({ ingress: { list } }); + const detailed = new CustomerAIApiKeyDetailed( + buildAIApiKeyData({ containerMeta }), + ); + + const result = await detailed.getContainerRelatedIngress(); + + expect(list).toHaveBeenCalledWith({ projectId: "project-id" }, undefined); + expect(result?.id).toBe("ingress-1"); + }); + + it("falls back to the ingress targeting the container", async () => { + const list = vi.fn().mockResolvedValue({ + items: [ + buildIngressData({ + paths: [ + { + target: { + container: { portProtocol: "8080/TCP", id: "container-1" }, + }, + path: "/", + }, + ], + id: "ingress-2", + }), + ], + totalCount: 1, + }); + installBehaviors({ ingress: { list } }); + const detailed = new CustomerAIApiKeyDetailed( + buildAIApiKeyData({ + containerMeta: { ...containerMeta, ingressId: "missing" }, + }), + ); + + const result = await detailed.getContainerRelatedIngress(); + + expect(result?.id).toBe("ingress-2"); + }); + + it("returns undefined when no ingress matches", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildIngressData({ id: "other" })], + totalCount: 1, + }); + installBehaviors({ ingress: { list } }); + const detailed = new CustomerAIApiKeyDetailed( + buildAIApiKeyData({ + containerMeta: { + ...containerMeta, + containerId: "missing", + ingressId: "missing", + }, + }), + ); + + await expect( + detailed.getContainerRelatedIngress(), + ).resolves.toBeUndefined(); + }); +}); + +describe("CustomerAIApiKey common lookups", () => { + it("findCommon on a bare reference delegates to find and returns the detailed variant", async () => { + const find = vi.fn().mockResolvedValue(buildAIApiKeyData({ keyId: "k-1" })); + installBehaviors({ customerAiApiKey: { find } }); + + const result = await CustomerAIApiKey.ofId("c-1", "k-1").findCommon(); + + expect(find).toHaveBeenCalledWith("c-1", "k-1"); + expect(result).toBeInstanceOf(CustomerAIApiKeyDetailed); + expect(result?.id).toBe("k-1"); + }); + + it("getCommon on a bare reference returns the common variant when found", async () => { + const find = vi.fn().mockResolvedValue(buildAIApiKeyData({ keyId: "k-1" })); + installBehaviors({ customerAiApiKey: { find } }); + + const result = await CustomerAIApiKey.ofId("c-1", "k-1").getCommon(); + + expect(result).toBeInstanceOf(CustomerAIApiKeyDetailed); + expect(result.id).toBe("k-1"); + }); + + it("getCommon on a bare reference throws when the key is not found", async () => { + installBehaviors({ + customerAiApiKey: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + CustomerAIApiKey.ofId("c-1", "missing").getCommon(), + ).rejects.toThrow(); + }); + + it("does not refetch when an already-common model resolves its common variant", async () => { + const find = vi.fn(); + installBehaviors({ customerAiApiKey: { find } }); + const detailed = new CustomerAIApiKeyDetailed(buildAIApiKeyData()); + + await expect(detailed.findCommon()).resolves.toBe(detailed); + await expect(detailed.getCommon()).resolves.toBe(detailed); + expect(find).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/models/src/ai/CustomerAIApiKey/CustomerAIApiKey.ts b/packages/models/src/ai/CustomerAIApiKey/CustomerAIApiKey.ts new file mode 100644 index 00000000..3efda212 --- /dev/null +++ b/packages/models/src/ai/CustomerAIApiKey/CustomerAIApiKey.ts @@ -0,0 +1,258 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import invariant from "tiny-invariant"; + +import type { + AIApiKeyContainerMetaData, + AIApiKeyTokenUsageData, + AIApiKeyRateLimitData, + AIApiKeyData, +} from "../types.js"; +import type { + CustomerAIApiKeyListQueryData, + CustomerAIApiKeyListItemData, + CustomerAIApiKeyRequestData, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { Customer } from "../../customer/Customer/Customer.js"; +import { Project } from "../../project/internal.js"; +import { formatTokenUsage } from "../helper.js"; +import { Ingress } from "../../ingress/index.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "CustomerAIApiKey", +}) +export class CustomerAIApiKey extends ReferenceModel { + public readonly customerId: string; + + public constructor(licenceId: string, customerId: string) { + super(licenceId); + this.customerId = customerId; + } + + public static async create( + customer: Customer, + data: CustomerAIApiKeyRequestData, + ): Promise { + const response = await config.behaviors.customerAiApiKey.create( + customer.id, + data, + ); + if (response) { + return new CustomerAIApiKey(response.id, customer.id); + } + return undefined; + } + + public static async find(customerId: string, licenceId: string) { + const data = await config.behaviors.customerAiApiKey.find( + customerId, + licenceId, + ); + + if (data) { + return new CustomerAIApiKeyDetailed(data); + } + } + + public static async get(customerId: string, licenceId: string) { + const apiKey = await this.find(customerId, licenceId); + assertObjectFound(apiKey, CustomerAIApiKey, licenceId); + return apiKey; + } + + public static ofId(customerId: string, licenceId: string) { + return new CustomerAIApiKey(licenceId, customerId); + } + + public static query( + customer: Customer, + query: CustomerAIApiKeyListQueryData = {}, + ) { + return new CustomerAIApiKeyListQuery(customer, query); + } + + public async findCommon(): Promise { + return this instanceof CustomerAIApiKeyCommon ? this : this.findDetailed(); + } + + public async findDetailed(): Promise { + return CustomerAIApiKey.find(this.customerId, this.id); + } + + public async getCommon(): Promise { + return this instanceof CustomerAIApiKeyCommon ? this : this.getDetailed(); + } + + public async getDetailed(): Promise { + return CustomerAIApiKey.get(this.customerId, this.id); + } +} + +export class CustomerAIApiKeyCommon extends WithData< + CustomerAIApiKeyListItemData | AIApiKeyData +>()(CustomerAIApiKey) { + public readonly containerMeta?: AIApiKeyContainerMetaData; + public readonly customer: Customer; + public override readonly data: CustomerAIApiKeyListItemData | AIApiKeyData; + public readonly isBlocked: boolean; + public readonly key: string; + public readonly models: string[]; + public readonly name: string; + public readonly planId?: string; + public readonly project?: Project; + public readonly rateLimit: AIApiKeyRateLimitData; + + public readonly tokenUsage: AIApiKeyTokenUsageData; + + public constructor(data: CustomerAIApiKeyListItemData | AIApiKeyData) { + invariant(data.profileId, "profile id not found"); + super(data.keyId, data.profileId); + this.data = data; + this.customer = Customer.ofId(data.profileId); + this.key = data.key; + this.models = data.models; + this.name = data.name; + this.planId = data.planId; + this.containerMeta = data.containerMeta; + this.isBlocked = data.isBlocked; + this.rateLimit = data.rateLimit; + this.tokenUsage = { + ...data.tokenUsage, + formattedUsed: formatTokenUsage(data.tokenUsage.used), + }; + + this.project = data.projectId ? Project.ofId(data.projectId) : undefined; + } + + public async delete(): Promise { + await config.behaviors.customerAiApiKey.delete(this.customer.id, this.id); + } + + public async linkProject( + projectId: string, + createOpenWebUIContainer: boolean, + ): Promise { + await config.behaviors.customerAiApiKey.update(this.customer.id, this.id, { + createWebuiContainer: createOpenWebUIContainer, + projectId, + }); + } + + public async updateName(name: string): Promise { + await config.behaviors.customerAiApiKey.update(this.customer.id, this.id, { + name, + }); + } +} + +export class CustomerAIApiKeyDetailed extends CustomerAIApiKeyCommon { + public override readonly data: AIApiKeyData; + public constructor(data: AIApiKeyData) { + super(data); + this.data = data; + } + + public async getContainerRelatedIngress() { + const defaultIngressId = this.containerMeta?.ingressId; + + if (!defaultIngressId || !this.data.projectId) { + return undefined; + } + + const ingresses = ( + await Ingress.query({ + project: this.project?.id, + }).execute() + ).items; + + const defaultIngress = ingresses.find( + (ingress) => ingress.id === defaultIngressId, + ); + + if (defaultIngress) { + return defaultIngress; + } + + const ingressWithContainerId = ingresses.find((ingress) => + ingress.paths.some( + (path) => + path.target && + path.target.type === "container" && + path.target.data.container.id === this.containerMeta?.containerId, + ), + ); + + if (ingressWithContainerId) { + return ingressWithContainerId; + } + + return undefined; + } +} + +export class CustomerAIApiKeyListItem extends CustomerAIApiKeyCommon { + public override readonly data: CustomerAIApiKeyListItemData; + public constructor(data: CustomerAIApiKeyListItemData) { + super(data); + this.data = data; + } +} + +export class CustomerAIApiKeyListQuery extends ListQueryModel { + private readonly customer: Customer; + + public constructor( + customer: Customer, + query: CustomerAIApiKeyListQueryData = {}, + ) { + super(query); + this.customer = customer; + } + + public async execute() { + const { totalCount, items } = await config.behaviors.customerAiApiKey.list( + extractId(this.customer), + this.query, + ); + + return new CustomerAIApiKeyList( + this.customer, + this.query, + items.map((d) => new CustomerAIApiKeyListItem(d)), + totalCount, + ); + } + + public refine(query: CustomerAIApiKeyListQueryData) { + return new CustomerAIApiKeyListQuery(this.customer, { + ...this.query, + ...query, + }); + } +} + +export class CustomerAIApiKeyList extends WithListData()( + CustomerAIApiKeyListQuery, +) { + public override readonly items: readonly CustomerAIApiKeyListItem[]; + public override readonly totalCount: number; + public constructor( + customer: Customer, + query: CustomerAIApiKeyListQueryData, + apiKeys: CustomerAIApiKeyListItem[], + totalCount: number, + ) { + super(customer, query); + this.items = Object.freeze(apiKeys); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/ai/CustomerAIApiKey/behaviors/api.ts b/packages/models/src/ai/CustomerAIApiKey/behaviors/api.ts new file mode 100644 index 00000000..dc27742a --- /dev/null +++ b/packages/models/src/ai/CustomerAIApiKey/behaviors/api.ts @@ -0,0 +1,75 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { CustomerAIApiKeyBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount } from "../../../base/index.js"; +import { ValidationError } from "../../../errors/index.js"; + +export const apiCustomerAIApiKeyBehaviors = ( + client: MittwaldAPIV2Client, +): CustomerAIApiKeyBehaviors => ({ + find: async (customerId, apiKeyId) => { + const response = await client.aiHosting.customerGetKey({ + keyId: apiKeyId, + customerId, + }); + + if (response.status === 200) { + return response.data; + } + + const validationError = ValidationError.fromResponse(response); + // invalid uuid in URL + if ( + validationError && + validationError.errors.some( + (e) => e.path === "licenceId" || e.path === "licenseId", + ) + ) { + return; + } + + validateResponse(response, 404); + }, + list: async (customerId, query) => { + const response = await client.aiHosting.customerGetKeys({ + queryParameters: query, + customerId, + }); + + validateResponse(response, 200); + + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + create: async (customerId, data) => { + const response = await client.aiHosting.customerCreateKey({ + customerId, + data, + }); + + validateResponse(response, 201); + + return { id: response.data.keyId }; + }, + update: async (customerId, apiKeyId, data) => { + const response = await client.aiHosting.customerUpdateKey({ + keyId: apiKeyId, + customerId, + data, + }); + + validateResponse(response, 200); + }, + delete: async (customerId, apiKeyId) => { + const response = await client.aiHosting.customerDeleteKey({ + keyId: apiKeyId, + customerId, + }); + + validateResponse(response, 204); + }, +}); diff --git a/packages/models/src/ai/CustomerAIApiKey/behaviors/index.ts b/packages/models/src/ai/CustomerAIApiKey/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/ai/CustomerAIApiKey/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/ai/CustomerAIApiKey/behaviors/types.ts b/packages/models/src/ai/CustomerAIApiKey/behaviors/types.ts new file mode 100644 index 00000000..da299872 --- /dev/null +++ b/packages/models/src/ai/CustomerAIApiKey/behaviors/types.ts @@ -0,0 +1,28 @@ +import type { QueryResponseData } from "../../../base/index.js"; +import type { AIApiKeyData } from "../../types.js"; +import type { + CustomerAIApiKeyUpdateRequestData, + CustomerAIApiKeyListQueryData, + CustomerAIApiKeyRequestData, +} from "../types.js"; + +export interface CustomerAIApiKeyBehaviors { + update: ( + customerId: string, + apiKeyId: string, + data: Partial, + ) => Promise; + list: ( + customerId: string, + query: CustomerAIApiKeyListQueryData, + ) => Promise>; + create: ( + customerId: string, + data: CustomerAIApiKeyRequestData, + ) => Promise<{ id: string } | undefined>; + find: ( + customerId: string, + licenceId: string, + ) => Promise; + delete: (customerId: string, apiKeyId: string) => Promise; +} diff --git a/packages/models/src/ai/CustomerAIApiKey/index.ts b/packages/models/src/ai/CustomerAIApiKey/index.ts new file mode 100644 index 00000000..73143b91 --- /dev/null +++ b/packages/models/src/ai/CustomerAIApiKey/index.ts @@ -0,0 +1,2 @@ +export * from "./CustomerAIApiKey.js"; +export * from "./types.js"; diff --git a/packages/models/src/ai/CustomerAIApiKey/types.ts b/packages/models/src/ai/CustomerAIApiKey/types.ts new file mode 100644 index 00000000..18302e38 --- /dev/null +++ b/packages/models/src/ai/CustomerAIApiKey/types.ts @@ -0,0 +1,13 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type CustomerAIApiKeyListItemData = + MittwaldAPIV2.Operations.AiHostingCustomerGetKeys.ResponseData[number]; + +export type CustomerAIApiKeyListQueryData = + MittwaldAPIV2.Paths.V2CustomersCustomerIdAiHostingKeys.Get.Parameters.Query; + +export type CustomerAIApiKeyRequestData = + MittwaldAPIV2.Paths.V2CustomersCustomerIdAiHostingKeys.Post.Parameters.RequestBody; + +export type CustomerAIApiKeyUpdateRequestData = + MittwaldAPIV2.Paths.V2CustomersCustomerIdAiHostingKeysKeyId.Put.Parameters.RequestBody; diff --git a/packages/models/src/ai/CustomerAIModel/CustomerAIModel.test.ts b/packages/models/src/ai/CustomerAIModel/CustomerAIModel.test.ts new file mode 100644 index 00000000..1b6a48f2 --- /dev/null +++ b/packages/models/src/ai/CustomerAIModel/CustomerAIModel.test.ts @@ -0,0 +1,63 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { buildCustomerAIDetailedModelData } from "../../testing/builders/buildCustomerAIDetailedModelData.js"; +import { ReferenceModel } from "../../base/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { + CustomerAIModelListItem, + CustomerAIModelList, + CustomerAIModel, +} from "./CustomerAIModel.js"; + +afterEach(resetBehaviors); + +describe("CustomerAIModel", () => { + it("delegates list queries and maps the result", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildCustomerAIDetailedModelData()], + totalCount: 1, + }); + installBehaviors({ customerAIModel: { list } }); + + const result = await CustomerAIModel.query("customer-1").execute(); + + expect(list).toHaveBeenCalledWith("customer-1", {}); + expect(result).toBeInstanceOf(CustomerAIModelList); + expect(result.items[0]).toBeInstanceOf(CustomerAIModelListItem); + expect(result.totalCount).toBe(1); + }); + + it("exposes detailed model data through derived getters", () => { + const withoutRemoval = new CustomerAIModelListItem( + buildCustomerAIDetailedModelData({ replacesModelName: "gpt-old" }), + ); + const withRemoval = new CustomerAIModelListItem( + buildCustomerAIDetailedModelData({ + removalAt: "2025-01-01T00:00:00.000Z", + }), + ); + + expect(withoutRemoval.activeAt.isValid).toBe(true); + expect(withoutRemoval.removalAt).toBeUndefined(); + expect(withRemoval.removalAt?.isValid).toBe(true); + expect(withoutRemoval.status).toBe("active"); + expect(withoutRemoval.replacesModelName).toBe("gpt-old"); + expect(withoutRemoval.documentationLink).toBe( + "https://docs.example.com/detailed", + ); + }); + + it("preserves the model inheritance chain", () => { + const item = new CustomerAIModelListItem( + buildCustomerAIDetailedModelData(), + ); + + expect(item).toBeInstanceOf(CustomerAIModelListItem); + expect(item).toBeInstanceOf(CustomerAIModel); + expect(item).toBeInstanceOf(ReferenceModel); + expect(item.data).toBeDefined(); + }); +}); diff --git a/packages/models/src/ai/CustomerAIModel/CustomerAIModel.ts b/packages/models/src/ai/CustomerAIModel/CustomerAIModel.ts new file mode 100644 index 00000000..b9b4f862 --- /dev/null +++ b/packages/models/src/ai/CustomerAIModel/CustomerAIModel.ts @@ -0,0 +1,38 @@ +import type { + CustomerAIModelListQueryData, + CustomerAIModelData, +} from "./types.js"; + +import { makeScopedAIModelClasses } from "../lib/makeScopedAIModelClasses.js"; +import { config } from "../../config/index.js"; + +const classes = makeScopedAIModelClasses< + CustomerAIModelData, + CustomerAIModelListQueryData +>({ + resolveBehavior: () => config.behaviors.customerAIModel, + ghostName: "CustomerAIModel", +}); + +export const CustomerAIModel = classes.ScopedAIModel; +export type CustomerAIModel = InstanceType; + +export const CustomerAIModelCommon = classes.ScopedAIModelCommon; +export type CustomerAIModelCommon = InstanceType< + typeof classes.ScopedAIModelCommon +>; + +export const CustomerAIModelListItem = classes.ScopedAIModelListItem; +export type CustomerAIModelListItem = InstanceType< + typeof classes.ScopedAIModelListItem +>; + +export const CustomerAIModelListQuery = classes.ScopedAIModelListQuery; +export type CustomerAIModelListQuery = InstanceType< + typeof classes.ScopedAIModelListQuery +>; + +export const CustomerAIModelList = classes.ScopedAIModelList; +export type CustomerAIModelList = InstanceType< + typeof classes.ScopedAIModelList +>; diff --git a/packages/models/src/ai/CustomerAIModel/behaviors/api.ts b/packages/models/src/ai/CustomerAIModel/behaviors/api.ts new file mode 100644 index 00000000..dab199a7 --- /dev/null +++ b/packages/models/src/ai/CustomerAIModel/behaviors/api.ts @@ -0,0 +1,24 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { CustomerAIModelBehaviors } from "./types.js"; + +import { resolveTotalCount, validateResponse } from "../../../base/index.js"; + +export const apiCustomerAIModelBehaviors = ( + client: MittwaldAPIV2Client, +): CustomerAIModelBehaviors => ({ + list: async (customerId: string) => { + const response = await client.aiHosting.customerGetDetailedModels({ + customerId, + }); + if (response.status !== 200) { + validateResponse(response, 404); + return { totalCount: 0, items: [] }; + } + + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, +}); diff --git a/packages/models/src/ai/CustomerAIModel/behaviors/index.ts b/packages/models/src/ai/CustomerAIModel/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/ai/CustomerAIModel/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/ai/CustomerAIModel/behaviors/types.ts b/packages/models/src/ai/CustomerAIModel/behaviors/types.ts new file mode 100644 index 00000000..a744209c --- /dev/null +++ b/packages/models/src/ai/CustomerAIModel/behaviors/types.ts @@ -0,0 +1,11 @@ +import type { + CustomerAIModelListQueryData, + CustomerAIModelListItemData, +} from "../types.js"; + +export interface CustomerAIModelBehaviors { + list: ( + customerId: string, + query?: CustomerAIModelListQueryData, + ) => Promise<{ items: CustomerAIModelListItemData[]; totalCount: number }>; +} diff --git a/packages/models/src/ai/CustomerAIModel/index.ts b/packages/models/src/ai/CustomerAIModel/index.ts new file mode 100644 index 00000000..29a9d81b --- /dev/null +++ b/packages/models/src/ai/CustomerAIModel/index.ts @@ -0,0 +1,2 @@ +export * from "./CustomerAIModel.js"; +export * from "./types.js"; diff --git a/packages/models/src/ai/CustomerAIModel/types.ts b/packages/models/src/ai/CustomerAIModel/types.ts new file mode 100644 index 00000000..87d4be7b --- /dev/null +++ b/packages/models/src/ai/CustomerAIModel/types.ts @@ -0,0 +1,12 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type CustomerAIModelData = + MittwaldAPIV2.Operations.AiHostingCustomerGetDetailedModels.ResponseData[number]; + +export type CustomerAIModelListItemData = CustomerAIModelData; + +export type CustomerAIModelStatus = + MittwaldAPIV2.Components.Schemas.AihostingDetailedModelStatus; + +// eslint-disable-next-line @typescript-eslint/no-empty-object-type +export interface CustomerAIModelListQueryData {} diff --git a/packages/models/src/ai/CustomerAIPlan/CustomerAIPlan.test.ts b/packages/models/src/ai/CustomerAIPlan/CustomerAIPlan.test.ts new file mode 100644 index 00000000..0e83e9d6 --- /dev/null +++ b/packages/models/src/ai/CustomerAIPlan/CustomerAIPlan.test.ts @@ -0,0 +1,271 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { ContractDetailed } from "../../contract/index.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { ReferenceModel } from "../../base/index.js"; +import { Customer } from "../../customer/index.js"; +import { + CustomerAIPlanDetailed, + CustomerAIPlanListItem, + CustomerAIPlanCommon, + CustomerAIPlanList, + CustomerAIPlan, +} from "./CustomerAIPlan.js"; +import { + buildCustomerAIPlanData, + buildContractData, + installBehaviors, + resetBehaviors, +} from "../../testing/index.js"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +afterEach(resetBehaviors); + +describe("CustomerAIPlan", () => { + it("finds a plan by customer and plan id", async () => { + const find = vi.fn().mockResolvedValue(buildCustomerAIPlanData()); + installBehaviors({ customerAiPlan: { find } }); + + const result = await CustomerAIPlan.find("c-1", "plan-1"); + + expect(find).toHaveBeenCalledWith("c-1", "plan-1", undefined, undefined); + expect(result).toBeInstanceOf(CustomerAIPlanDetailed); + }); + + it("returns undefined when the plan is not found", async () => { + installBehaviors({ + customerAiPlan: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(CustomerAIPlan.find("c-1", "plan-1")).resolves.toBeUndefined(); + }); + + it("throws when getting a missing plan", async () => { + installBehaviors({ + customerAiPlan: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(CustomerAIPlan.get("c-1", "plan-1")).rejects.toThrow(); + }); + + it("exposes dates, usage values, and the customer", () => { + const detailed = new CustomerAIPlanDetailed(buildCustomerAIPlanData()); + + expect(detailed.nextTokenResetDate.isValid).toBe(true); + expect(typeof detailed.tokens.formattedUsed).toBe("string"); + expect(typeof detailed.tokens.formattedPlanLimit).toBe("string"); + expect(typeof detailed.topUsages[0]?.formattedTokenUsed).toBe("string"); + expect(detailed.customer.id).toBe("customer-id"); + expect(typeof detailed.modelTermsApprovalRequired).toBe("boolean"); + }); + + it("reports whether the plan has capacity", () => { + const withPlan = new CustomerAIPlanDetailed(buildCustomerAIPlanData()); + const withoutPlan = new CustomerAIPlanDetailed( + buildCustomerAIPlanData({ + rateLimit: { allowedRequestsPerUnit: 0, unit: "minute" }, + }), + ); + + expect(withPlan.hasPlan()).toBe(true); + expect(withoutPlan.hasPlan()).toBe(false); + }); + + it("delegates accepting model terms for a plan reference", async () => { + const acceptModelTerms = vi.fn().mockResolvedValue(undefined); + installBehaviors({ customerAiPlan: { acceptModelTerms } }); + + await CustomerAIPlan.ofId("c-1", "plan-1").acceptModelTerms(); + + expect(acceptModelTerms).toHaveBeenCalledWith("c-1"); + }); + + it("delegates accepting model terms for a bare customer id", async () => { + const acceptModelTerms = vi.fn().mockResolvedValue(undefined); + installBehaviors({ customerAiPlan: { acceptModelTerms } }); + + await CustomerAIPlan.acceptModelTermsForCustomer("c-1"); + + expect(acceptModelTerms).toHaveBeenCalledWith("c-1"); + }); + + it("delegates updating the plan name", async () => { + const updateName = vi.fn().mockResolvedValue(undefined); + installBehaviors({ customerAiPlan: { updateName } }); + + await CustomerAIPlan.ofId("c-1", "plan-1").updateName("new name"); + + expect(updateName).toHaveBeenCalledWith("c-1", "plan-1", "new name"); + }); + + it("returns undefined when no contract is found", async () => { + const findContract = vi.fn().mockResolvedValue(undefined); + installBehaviors({ customerAiPlan: { findContract } }); + const plan = CustomerAIPlan.ofId("c-1", "plan-1"); + + await expect(plan.findContract()).resolves.toBeUndefined(); + expect(findContract).toHaveBeenCalledWith("c-1", "plan-1", undefined); + }); + + it("returns a detailed contract when one is found", async () => { + const findContract = vi + .fn() + .mockResolvedValue(buildContractData({ contractId: "contract-9" })); + installBehaviors({ customerAiPlan: { findContract } }); + + const contract = await CustomerAIPlan.ofId("c-1", "plan-1").findContract(); + + expect(findContract).toHaveBeenCalledWith("c-1", "plan-1", undefined); + expect(contract).toBeInstanceOf(ContractDetailed); + expect(contract?.id).toBe("contract-9"); + }); + + it("gets the contract when one is found", async () => { + const findContract = vi + .fn() + .mockResolvedValue(buildContractData({ contractId: "contract-9" })); + installBehaviors({ customerAiPlan: { findContract } }); + + const contract = await CustomerAIPlan.ofId("c-1", "plan-1").getContract(); + + expect(contract).toBeInstanceOf(ContractDetailed); + expect(contract.id).toBe("contract-9"); + }); + + it("throws when getting a missing contract", async () => { + installBehaviors({ + customerAiPlan: { findContract: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + CustomerAIPlan.ofId("c-1", "plan-1").getContract(), + ).rejects.toThrow(); + }); + + it("preserves the detailed model inheritance chain", () => { + const detailed = new CustomerAIPlanDetailed(buildCustomerAIPlanData()); + + expect(detailed).toBeInstanceOf(CustomerAIPlanDetailed); + expect(detailed).toBeInstanceOf(CustomerAIPlanCommon); + expect(detailed).toBeInstanceOf(CustomerAIPlan); + expect(detailed).toBeInstanceOf(ReferenceModel); + expect(detailed.data).toBeDefined(); + }); + + it("defaults top usages to an empty array when the source omits them", () => { + const detailed = new CustomerAIPlanDetailed( + buildCustomerAIPlanData({ topUsages: undefined }), + ); + + expect(detailed.topUsages).toEqual([]); + }); + + it("wires aggregate metadata for cache invalidation", () => { + expect(CustomerAIPlan.aggregateMetaData).toBeInstanceOf(AggregateMetaData); + expect(CustomerAIPlan.aggregateMetaData.domain).toBe("llmlocksmith"); + expect(CustomerAIPlan.aggregateMetaData.aggregate).toBe("locksmithPlan"); + }); +}); + +describe("CustomerAIPlan common lookups and metadata", () => { + it("findCommon on a bare reference delegates to find and returns the detailed variant", async () => { + const find = vi.fn().mockResolvedValue(buildCustomerAIPlanData()); + installBehaviors({ customerAiPlan: { find } }); + + const result = await CustomerAIPlan.ofId( + "customer-id", + "plan-1", + ).findCommon(); + + expect(find).toHaveBeenCalledWith( + "customer-id", + "plan-1", + undefined, + undefined, + ); + expect(result).toBeInstanceOf(CustomerAIPlanDetailed); + expect(result).toBeInstanceOf(CustomerAIPlanCommon); + }); + + it("getCommon on a bare reference returns the common variant when found", async () => { + const find = vi.fn().mockResolvedValue(buildCustomerAIPlanData()); + installBehaviors({ customerAiPlan: { find } }); + + const result = await CustomerAIPlan.ofId( + "customer-id", + "plan-1", + ).getCommon(); + + expect(result).toBeInstanceOf(CustomerAIPlanCommon); + expect(result.customer.id).toBe("customer-id"); + }); + + it("getCommon on a bare reference throws when the plan is not found", async () => { + installBehaviors({ + customerAiPlan: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + CustomerAIPlan.ofId("customer-id", "missing").getCommon(), + ).rejects.toThrow(); + }); + + it("does not refetch when an already-common model resolves its common variant", async () => { + const find = vi.fn(); + installBehaviors({ customerAiPlan: { find } }); + const detailed = new CustomerAIPlanDetailed(buildCustomerAIPlanData()); + + await expect(detailed.findCommon()).resolves.toBe(detailed); + await expect(detailed.getCommon()).resolves.toBe(detailed); + expect(find).not.toHaveBeenCalled(); + }); +}); + +describe("CustomerAIPlan.query", () => { + it("lists plans for a customer id", async () => { + const list = vi.fn().mockResolvedValue({ + items: [ + buildCustomerAIPlanData({ planId: "plan-1" }), + buildCustomerAIPlanData({ planId: "plan-2" }), + ], + totalCount: 2, + }); + installBehaviors({ customerAiPlan: { list } }); + + const result = await CustomerAIPlan.query("customer-id").execute(); + + expect(list).toHaveBeenCalledWith("customer-id", {}, undefined); + expect(result).toBeInstanceOf(CustomerAIPlanList); + expect(result.items).toHaveLength(2); + expect(result.items[0]).toBeInstanceOf(CustomerAIPlanListItem); + expect(result.totalCount).toBe(2); + }); + + it("lists plans for a Customer instance by extracting its id", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 0, items: [] }); + installBehaviors({ customerAiPlan: { list } }); + + await CustomerAIPlan.query(Customer.ofId("customer-id")).execute(); + + expect(list).toHaveBeenCalledWith("customer-id", {}, undefined); + }); + + it("returns the total count without requiring callers to inspect the list", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildCustomerAIPlanData()], + totalCount: 1, + }); + installBehaviors({ customerAiPlan: { list } }); + + await expect( + CustomerAIPlan.query("customer-id").getTotalCount(), + ).resolves.toBe(1); + }); +}); diff --git a/packages/models/src/ai/CustomerAIPlan/CustomerAIPlan.ts b/packages/models/src/ai/CustomerAIPlan/CustomerAIPlan.ts new file mode 100644 index 00000000..7e3e593f --- /dev/null +++ b/packages/models/src/ai/CustomerAIPlan/CustomerAIPlan.ts @@ -0,0 +1,265 @@ +import type { AxiosRequestConfig } from "axios"; + +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; + +import type { + CustomerAIPlanListQueryData, + CustomerAIPlanTopUsage, + CustomerAIPlanTokens, + CustomerAIPlanLimit, + CustomerAIPlanData, + CustomerAIPlanKeys, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { AITokenStatistics } from "../AITokenStatistics/index.js"; +import { ContractDetailed } from "../../contract/index.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { formatTokenUsage } from "../helper.js"; +import { Customer } from "../../customer/index.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "CustomerAIPlan", +}) +export class CustomerAIPlan extends ReferenceModel { + public static aggregateMetaData = new AggregateMetaData( + "llmlocksmith", + "locksmithPlan", + ); + + public readonly customerId: string; + public readonly tokenStatistics: AITokenStatistics; + + public constructor(planId: string, customerId: string) { + super(planId); + this.customerId = customerId; + this.tokenStatistics = AITokenStatistics.ofPlan(customerId, planId); + } + + public static async acceptModelTermsForCustomer(customerId: string) { + await config.behaviors.customerAiPlan.acceptModelTerms(customerId); + } + + public static async declareProfileForCustomer(customerId: string) { + await config.behaviors.customerAiPlan.declareProfile(customerId); + } + + public static async find( + customerId: string, + planId: string, + topUsageCount?: number, + options?: AxiosRequestConfig, + ) { + const data = await config.behaviors.customerAiPlan.find( + customerId, + planId, + topUsageCount, + options, + ); + + if (data) { + return new CustomerAIPlanDetailed(data); + } + } + + public static async get( + customerId: string, + planId: string, + topUsageCount?: number, + options?: AxiosRequestConfig, + ) { + const plan = await this.find(customerId, planId, topUsageCount, options); + assertObjectFound(plan, CustomerAIPlan, planId); + return plan; + } + + public static ofId(customerId: string, planId: string) { + return new CustomerAIPlan(planId, customerId); + } + + public static query(customerId: Customer | string) { + return new CustomerAIPlanListQuery(extractId(customerId)); + } + + public async acceptModelTerms() { + await config.behaviors.customerAiPlan.acceptModelTerms(this.customerId); + } + + public async findCommon( + topUsageCount?: number, + options?: AxiosRequestConfig, + ): Promise { + return this instanceof CustomerAIPlanCommon + ? this + : this.findDetailed(topUsageCount, options); + } + + public async findContract(options?: AxiosRequestConfig) { + const data = await config.behaviors.customerAiPlan.findContract( + this.customerId, + this.id, + options, + ); + if (data) { + return new ContractDetailed(data); + } + } + + public async findDetailed( + topUsageCount?: number, + options?: AxiosRequestConfig, + ): Promise { + return CustomerAIPlan.find( + this.customerId, + this.id, + topUsageCount, + options, + ); + } + + public async getCommon( + topUsageCount?: number, + options?: AxiosRequestConfig, + ): Promise { + return this instanceof CustomerAIPlanCommon + ? this + : this.getDetailed(topUsageCount, options); + } + + public async getContract(options?: AxiosRequestConfig) { + const contract = await this.findContract(options); + assertObjectFound(contract, CustomerAIPlan, this); + return contract; + } + + public async getDetailed( + topUsageCount?: number, + options?: AxiosRequestConfig, + ): Promise { + return CustomerAIPlan.get(this.customerId, this.id, topUsageCount, options); + } + + public async updateName(name: string): Promise { + await config.behaviors.customerAiPlan.updateName( + this.customerId, + this.id, + name, + ); + } +} + +export class CustomerAIPlanCommon extends WithData()( + CustomerAIPlan, +) { + public readonly apiKeys: CustomerAIPlanKeys; + public readonly customer: Customer; + public override readonly data: CustomerAIPlanData; + public readonly description: string; + public readonly modelTermsApprovalRequired: boolean; + public readonly nextTokenResetDate: DateTime; + public readonly planId: string; + public readonly rateLimit: CustomerAIPlanLimit; + public readonly tokens: CustomerAIPlanTokens; + public readonly topUsages: CustomerAIPlanTopUsage; + + public constructor(data: CustomerAIPlanData) { + super(data.planId, data.customerId); + this.data = data; + + this.planId = data.planId; + this.description = data.description; + this.customer = Customer.ofId(data.customerId); + this.apiKeys = data.keys; + this.rateLimit = data.rateLimit; + this.tokens = { + ...data.tokens, + formattedPlanLimit: formatTokenUsage(data.tokens.planLimit, 0), + formattedUsed: formatTokenUsage(data.tokens.used), + }; + this.topUsages = (data.topUsages ?? []).map((item) => ({ + ...item, + formattedTokenUsed: formatTokenUsage(item.tokenUsed), + })); + this.nextTokenResetDate = DateTime.fromISO(data.nextTokenReset); + this.modelTermsApprovalRequired = data.modelTermsApprovalRequired; + } + + public hasPlan(): boolean { + return ( + this.rateLimit.allowedRequestsPerUnit > 0 && + this.tokens.planLimit > 0 && + (this.apiKeys.planLimit > 0 || this.apiKeys.planLimit === -1) + ); + } +} + +export class CustomerAIPlanDetailed extends CustomerAIPlanCommon { + public constructor(data: CustomerAIPlanData) { + super(data); + } +} + +export class CustomerAIPlanListItem extends CustomerAIPlanCommon { + public constructor(data: CustomerAIPlanData) { + super(data); + } +} + +export class CustomerAIPlanListQuery extends ListQueryModel { + private readonly customerId: string; + + public constructor( + customerId: string, + query: CustomerAIPlanListQueryData = {}, + ) { + super(query, { dependencies: [customerId] }); + this.customerId = customerId; + } + + public async execute(options?: AxiosRequestConfig) { + const result = await config.behaviors.customerAiPlan.list( + this.customerId, + this.query, + options, + ); + + return new CustomerAIPlanList( + this.customerId, + this.query, + result.items.map((item) => new CustomerAIPlanListItem(item)), + result.totalCount, + ); + } + + public override async getTotalCount(options?: AxiosRequestConfig) { + const list = await this.execute(options); + return list.totalCount; + } +} + +export class CustomerAIPlanList extends WithListData()( + CustomerAIPlanListQuery, +) { + public override readonly items: readonly CustomerAIPlanListItem[]; + public override readonly totalCount: number; + + public constructor( + customerId: string, + query: CustomerAIPlanListQueryData, + items: CustomerAIPlanListItem[], + totalCount: number, + ) { + super(customerId, query); + this.items = Object.freeze(items); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/ai/CustomerAIPlan/behavior/api.ts b/packages/models/src/ai/CustomerAIPlan/behavior/api.ts new file mode 100644 index 00000000..a9271340 --- /dev/null +++ b/packages/models/src/ai/CustomerAIPlan/behavior/api.ts @@ -0,0 +1,95 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { CustomerAIPlanBehavior } from "./types.js"; + +import { + withAxiosRequestConfig, + resolveTotalCount, + validateResponse, +} from "../../../base/index.js"; + +export const apiCustomerAIPlanBehaviors = ( + client: MittwaldAPIV2Client, +): CustomerAIPlanBehavior => ({ + list: async (customerId, _query, options) => { + const response = await client.aiHosting.customerGetPlans( + { customerId }, + withAxiosRequestConfig(options), + ); + + if (response.status !== 200) { + validateResponse(response, 404); + return { totalCount: 0, items: [] }; + } + + const { plans } = response.data; + return { + totalCount: resolveTotalCount(response, plans.length), + items: plans, + }; + }, + + find: async (customerId, planId, topUsageCount, options) => { + const response = await client.aiHosting.customerGetPlan( + { queryParameters: { topUsageCount }, customerId, planId }, + withAxiosRequestConfig(options), + ); + + if (response.status === 200) { + return response.data; + } + + validateResponse(response, 404); + }, + + findContract: async (customerId, planId, options) => { + const response = await client.contract.getDetailOfContractByAiHosting( + { aiHostingId: planId, customerId }, + withAxiosRequestConfig(options), + ); + + if (response.status === 200) { + return response.data; + } + + validateResponse(response, 404); + }, + + updateName: async (customerId, planId, name) => { + const response = await client.aiHosting.customerUpdatePlan({ + data: { description: name }, + customerId, + planId, + }); + + if (response.status === 204) { + return; + } + + validateResponse(response, 404); + }, + + acceptModelTerms: async (customerId) => { + const response = await client.aiHosting.customerAcceptModelTerms({ + customerId, + }); + + if (response.status === 204) { + return; + } + + validateResponse(response, 404); + }, + + declareProfile: async (customerId) => { + const response = await client.aiHosting.customerDeclareProfile({ + customerId, + }); + + if (response.status === 204) { + return; + } + + validateResponse(response, 404); + }, +}); diff --git a/packages/models/src/ai/CustomerAIPlan/behavior/types.ts b/packages/models/src/ai/CustomerAIPlan/behavior/types.ts new file mode 100644 index 00000000..bfaf523d --- /dev/null +++ b/packages/models/src/ai/CustomerAIPlan/behavior/types.ts @@ -0,0 +1,33 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; +import type { AxiosRequestConfig } from "axios"; + +import type { + CustomerAIPlanListQueryData, + CustomerAIPlanData, +} from "../types.js"; +import type { QueryResponseData } from "../../../base/index.js"; + +type ContractData = + MittwaldAPIV2.Operations.ContractGetDetailOfContractByAiHosting.ResponseData; + +export interface CustomerAIPlanBehavior { + list( + customerId: string, + query?: CustomerAIPlanListQueryData, + options?: AxiosRequestConfig, + ): Promise>; + find( + customerId: string, + planId: string, + topUsageCount?: number, + options?: AxiosRequestConfig, + ): Promise; + findContract( + customerId: string, + planId: string, + options?: AxiosRequestConfig, + ): Promise; + updateName(customerId: string, planId: string, name: string): Promise; + acceptModelTerms(customerId: string): Promise; + declareProfile(customerId: string): Promise; +} diff --git a/packages/models/src/ai/CustomerAIPlan/index.ts b/packages/models/src/ai/CustomerAIPlan/index.ts new file mode 100644 index 00000000..3ec1e121 --- /dev/null +++ b/packages/models/src/ai/CustomerAIPlan/index.ts @@ -0,0 +1,2 @@ +export * from "./CustomerAIPlan.js"; +export * from "./types.js"; diff --git a/packages/models/src/ai/CustomerAIPlan/types.ts b/packages/models/src/ai/CustomerAIPlan/types.ts new file mode 100644 index 00000000..8a73356c --- /dev/null +++ b/packages/models/src/ai/CustomerAIPlan/types.ts @@ -0,0 +1,18 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type CustomerAIPlanData = + MittwaldAPIV2.Operations.AiHostingCustomerGetPlan.ResponseData; + +export type CustomerAIPlanListQueryData = Record; + +export type CustomerAIPlanKeys = CustomerAIPlanData["keys"]; +export type CustomerAIPlanLimit = CustomerAIPlanData["rateLimit"]; +export type CustomerAIPlanTokens = { + formattedPlanLimit: string; + formattedUsed: string; +} & CustomerAIPlanData["tokens"]; + +type TopUsageItem = NonNullable[number] & { + formattedTokenUsed: string; +}; +export type CustomerAIPlanTopUsage = TopUsageItem[]; diff --git a/packages/models/src/ai/ProjectAIApiKey/ProjectAIApiKey.test.ts b/packages/models/src/ai/ProjectAIApiKey/ProjectAIApiKey.test.ts new file mode 100644 index 00000000..4b6d92d1 --- /dev/null +++ b/packages/models/src/ai/ProjectAIApiKey/ProjectAIApiKey.test.ts @@ -0,0 +1,264 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { buildAIApiKeyData } from "../../testing/builders/buildAIApiKeyData.js"; +import { buildIngressData } from "../../testing/builders/buildIngressData.js"; +import { ReferenceModel } from "../../base/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { Project } from "../../project/index.js"; +import { + AI_HOSTING_DEFAULT_RATE_LIMIT, + AI_HOSTING_DOCUMENTATION_LINK, + ProjectAIApiKeyDetailed, + ProjectAIApiKeyListItem, + ProjectAIApiKey, +} from "./ProjectAIApiKey.js"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +afterEach(resetBehaviors); + +describe("ProjectAIApiKey", () => { + it("exports the AI hosting defaults", () => { + expect(AI_HOSTING_DEFAULT_RATE_LIMIT).toBe(300); + expect(AI_HOSTING_DOCUMENTATION_LINK.startsWith("https://")).toBe(true); + }); + + it("finds and maps a detailed API key", async () => { + const find = vi.fn().mockResolvedValue(buildAIApiKeyData({ keyId: "k-1" })); + installBehaviors({ projectAiApiKey: { find } }); + + const result = await ProjectAIApiKey.find("p-1", "k-1"); + + expect(find).toHaveBeenCalledWith("p-1", "k-1"); + expect(result).toBeInstanceOf(ProjectAIApiKeyDetailed); + expect(result?.id).toBe("k-1"); + }); + + it("returns undefined when an API key is not found", async () => { + installBehaviors({ + projectAiApiKey: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + ProjectAIApiKey.find("p-1", "missing"), + ).resolves.toBeUndefined(); + }); + + it("throws when getting a missing API key", async () => { + installBehaviors({ + projectAiApiKey: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(ProjectAIApiKey.get("p-1", "missing")).rejects.toThrow(); + }); + + it("exposes related models and formatted token usage", () => { + const detailed = new ProjectAIApiKeyDetailed(buildAIApiKeyData()); + const withoutCustomer = new ProjectAIApiKeyDetailed( + buildAIApiKeyData({ profileId: undefined }), + ); + + expect(detailed.project.id).toBe("project-id"); + expect(detailed.customer?.id).toBe("customer-id"); + expect(withoutCustomer.customer).toBeUndefined(); + expect(typeof detailed.tokenUsage.formattedUsed).toBe("string"); + }); + + it("delegates updates, deletion, and container linking", async () => { + const update = vi.fn().mockResolvedValue(undefined); + const deleteBehavior = vi.fn().mockResolvedValue(undefined); + const linkContainer = vi.fn().mockResolvedValue(undefined); + installBehaviors({ + projectAiApiKey: { delete: deleteBehavior, linkContainer, update }, + }); + const detailed = new ProjectAIApiKeyDetailed(buildAIApiKeyData()); + const linkData = { + containerId: "container-1", + ingressId: "ingress-1", + stackId: "stack-1", + }; + + await detailed.updateName("new"); + await detailed.addContainer(); + await detailed.linkContainer(linkData); + await detailed.delete(); + + expect(update).toHaveBeenCalledWith("project-id", "key-id", { + name: "new", + }); + expect(update).toHaveBeenCalledWith("project-id", "key-id", { + createWebuiContainer: true, + }); + expect(linkContainer).toHaveBeenCalledWith( + "project-id", + "key-id", + linkData, + ); + expect(deleteBehavior).toHaveBeenCalledWith("project-id", "key-id"); + }); + + it("creates an API key for a project", async () => { + const create = vi.fn().mockResolvedValue({ id: "nk" }); + installBehaviors({ projectAiApiKey: { create } }); + const requestData = { + planId: "plan-1", + name: "new key", + models: [], + }; + + const result = await ProjectAIApiKey.create( + Project.ofId("p-1"), + requestData, + ); + + expect(create).toHaveBeenCalledWith("p-1", requestData); + expect(result).toBeInstanceOf(ProjectAIApiKey); + expect(result).toMatchObject({ projectId: "p-1", id: "nk" }); + }); + + it("returns no related ingress without container metadata", async () => { + const detailed = new ProjectAIApiKeyDetailed( + buildAIApiKeyData({ containerMeta: undefined }), + ); + + await expect( + detailed.getContainerRelatedIngress(), + ).resolves.toBeUndefined(); + }); + + it("preserves the list item inheritance chain", () => { + const item = new ProjectAIApiKeyListItem(buildAIApiKeyData()); + + expect(item).toBeInstanceOf(ProjectAIApiKeyListItem); + expect(item).toBeInstanceOf(ProjectAIApiKey); + expect(item).toBeInstanceOf(ReferenceModel); + expect(item.data).toBeDefined(); + }); +}); + +describe("ProjectAIApiKey container-related ingress", () => { + const containerMeta = { + containerId: "container-1", + status: "created" as const, + ingressId: "ingress-1", + stackId: "stack-1", + }; + + it("returns the ingress matching the container metadata ingress id", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildIngressData({ id: "ingress-1" })], + totalCount: 1, + }); + installBehaviors({ ingress: { list } }); + const detailed = new ProjectAIApiKeyDetailed( + buildAIApiKeyData({ containerMeta }), + ); + + const result = await detailed.getContainerRelatedIngress(); + + expect(list).toHaveBeenCalledWith({ projectId: "project-id" }, undefined); + expect(result?.id).toBe("ingress-1"); + }); + + it("falls back to the ingress targeting the container", async () => { + const list = vi.fn().mockResolvedValue({ + items: [ + buildIngressData({ + paths: [ + { + target: { + container: { portProtocol: "8080/TCP", id: "container-1" }, + }, + path: "/", + }, + ], + id: "ingress-2", + }), + ], + totalCount: 1, + }); + installBehaviors({ ingress: { list } }); + const detailed = new ProjectAIApiKeyDetailed( + buildAIApiKeyData({ + containerMeta: { ...containerMeta, ingressId: "missing" }, + }), + ); + + const result = await detailed.getContainerRelatedIngress(); + + expect(result?.id).toBe("ingress-2"); + }); + + it("returns undefined when no ingress matches", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildIngressData({ id: "other" })], + totalCount: 1, + }); + installBehaviors({ ingress: { list } }); + const detailed = new ProjectAIApiKeyDetailed( + buildAIApiKeyData({ + containerMeta: { + ...containerMeta, + containerId: "missing", + ingressId: "missing", + }, + }), + ); + + await expect( + detailed.getContainerRelatedIngress(), + ).resolves.toBeUndefined(); + }); +}); + +describe("ProjectAIApiKey common lookups", () => { + it("findCommon on a bare reference delegates to find and returns the detailed variant", async () => { + const find = vi.fn().mockResolvedValue(buildAIApiKeyData({ keyId: "k-1" })); + installBehaviors({ projectAiApiKey: { find } }); + + const result = await ProjectAIApiKey.ofId("p-1", "k-1").findCommon(); + + expect(find).toHaveBeenCalledWith("p-1", "k-1"); + expect(result).toBeInstanceOf(ProjectAIApiKeyDetailed); + expect(result?.id).toBe("k-1"); + }); + + it("getCommon on a bare reference returns the common variant when found", async () => { + const find = vi.fn().mockResolvedValue(buildAIApiKeyData({ keyId: "k-1" })); + installBehaviors({ projectAiApiKey: { find } }); + + const result = await ProjectAIApiKey.ofId("p-1", "k-1").getCommon(); + + expect(result).toBeInstanceOf(ProjectAIApiKeyDetailed); + expect(result.id).toBe("k-1"); + }); + + it("getCommon on a bare reference throws when the key is not found", async () => { + installBehaviors({ + projectAiApiKey: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + ProjectAIApiKey.ofId("p-1", "missing").getCommon(), + ).rejects.toThrow(); + }); + + it("does not refetch when an already-common model resolves its common variant", async () => { + const find = vi.fn(); + installBehaviors({ projectAiApiKey: { find } }); + const detailed = new ProjectAIApiKeyDetailed(buildAIApiKeyData()); + + await expect(detailed.findCommon()).resolves.toBe(detailed); + await expect(detailed.getCommon()).resolves.toBe(detailed); + expect(find).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/models/src/ai/ProjectAIApiKey/ProjectAIApiKey.ts b/packages/models/src/ai/ProjectAIApiKey/ProjectAIApiKey.ts new file mode 100644 index 00000000..f5d36098 --- /dev/null +++ b/packages/models/src/ai/ProjectAIApiKey/ProjectAIApiKey.ts @@ -0,0 +1,284 @@ +import type { AxiosRequestConfig } from "axios"; + +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import invariant from "tiny-invariant"; + +import type { AIContainerType } from "../aiContainerType.js"; +import type { + AIApiKeyContainerMetaData, + AIApiKeyTokenUsageData, + AIApiKeyRateLimitData, + AIApiKeyData, +} from "../types.js"; +import type { + ProjectAIApiKeyListQueryData, + ProjectAIApiKeyListItemData, + ProjectAIApiKeyRequestData, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { Customer } from "../../customer/Customer/Customer.js"; +import { Project } from "../../project/internal.js"; +import { formatTokenUsage } from "../helper.js"; +import { Ingress } from "../../ingress/index.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; + +export const AI_HOSTING_DOCUMENTATION_LINK = + "https://developer.mittwald.de/de/docs/v2/platform/aihosting/"; +export const AI_HOSTING_ERROR_RESOLUTION_LINK = + "https://developer.mittwald.de/de/docs/v2/platform/aihosting/api-endpoints/errors/"; +export const AI_HOSTING_INTRODUCTION_LINK = + "https://developer.mittwald.de/de/docs/v2/platform/aihosting/introduction/"; +export const AI_HOSTING_MODELS_LINK = + "https://developer.mittwald.de/de/docs/v2/platform/aihosting/models/"; +export const AI_HOSTING_LANDING_PAGE_LINK = + "https://www.mittwald.de/mstudio/ai-hosting"; +export const AI_HOSTING_LLM_ENDPOINT = "https://llm.aihosting.mittwald.de/v1"; +export const AI_HOSTING_DEFAULT_RATE_LIMIT = 300; + +@GhostMakerModel({ + name: "ProjectAIApiKey", +}) +export class ProjectAIApiKey extends ReferenceModel { + public readonly projectId: string; + + public constructor(licenceId: string, projectId: string) { + super(licenceId); + this.projectId = projectId; + } + + public static async create( + project: Project, + data: ProjectAIApiKeyRequestData, + ): Promise { + const response = await config.behaviors.projectAiApiKey.create( + project.id, + data, + ); + if (response) { + return new ProjectAIApiKey(response.id, project.id); + } + return undefined; + } + + public static async find(projectId: string, licenceId: string) { + const data = await config.behaviors.projectAiApiKey.find( + projectId, + licenceId, + ); + + if (data) { + return new ProjectAIApiKeyDetailed(data); + } + } + + public static async get(projectId: string, licenceId: string) { + const apiKey = await this.find(projectId, licenceId); + assertObjectFound(apiKey, ProjectAIApiKey, licenceId); + return apiKey; + } + + public static ofId(projectId: string, licenceId: string) { + return new ProjectAIApiKey(licenceId, projectId); + } + + public static query( + project: Project, + query: ProjectAIApiKeyListQueryData = {}, + ) { + return new ProjectAIApiKeyListQuery(project, query); + } + + public async findCommon(): Promise { + return this instanceof ProjectAIApiKeyCommon ? this : this.findDetailed(); + } + + public async findDetailed(): Promise { + return ProjectAIApiKey.find(this.projectId, this.id); + } + + public async getCommon(): Promise { + return this instanceof ProjectAIApiKeyCommon ? this : this.getDetailed(); + } + + public async getDetailed(): Promise { + return ProjectAIApiKey.get(this.projectId, this.id); + } +} + +export class ProjectAIApiKeyCommon extends WithData< + ProjectAIApiKeyListItemData | AIApiKeyData +>()(ProjectAIApiKey) { + public readonly containerMeta: AIApiKeyContainerMetaData | undefined; + public readonly customer: Customer | undefined; + public override readonly data: ProjectAIApiKeyListItemData | AIApiKeyData; + public readonly isBlocked: boolean; + public readonly key: string; + public readonly models: string[]; + public readonly name: string; + public readonly planId?: string; + public readonly project: Project; + public readonly rateLimit: AIApiKeyRateLimitData; + + public readonly tokenUsage: AIApiKeyTokenUsageData; + + public constructor(data: ProjectAIApiKeyListItemData | AIApiKeyData) { + invariant(data.projectId, "project id not found"); + super(data.keyId, data.projectId); + this.data = data; + this.project = Project.ofId(data.projectId); + this.key = data.key; + this.models = data.models; + this.name = data.name; + this.planId = data.planId; + this.containerMeta = data.containerMeta; + this.isBlocked = data.isBlocked; + this.rateLimit = data.rateLimit; + this.tokenUsage = { + ...data.tokenUsage, + formattedUsed: formatTokenUsage(data.tokenUsage.used), + }; + + this.customer = data.profileId ? Customer.ofId(data.profileId) : undefined; + } + + public async addContainer( + containerType: AIContainerType = "openwebui", + ): Promise { + await config.behaviors.projectAiApiKey.update(this.project.id, this.id, { + createWebuiContainer: containerType === "openwebui", + }); + } + + public async delete(): Promise { + await config.behaviors.projectAiApiKey.delete(this.project.id, this.id); + } + + public async linkContainer(data: { + containerId: string; + ingressId: string; + stackId: string; + }): Promise { + await config.behaviors.projectAiApiKey.linkContainer( + this.project.id, + this.id, + data, + ); + } + + public async updateName(name: string): Promise { + await config.behaviors.projectAiApiKey.update(this.project.id, this.id, { + name, + }); + } +} + +export class ProjectAIApiKeyDetailed extends ProjectAIApiKeyCommon { + public override readonly data: AIApiKeyData; + public constructor(data: AIApiKeyData) { + super(data); + this.data = data; + } + + public async getContainerRelatedIngress() { + const defaultIngressId = this.containerMeta?.ingressId; + + if (!defaultIngressId || !this.project) { + return undefined; + } + + const ingresses = ( + await Ingress.query({ + project: this.project, + }).execute() + ).items; + + const defaultIngress = ingresses.find( + (ingress) => ingress.id === defaultIngressId, + ); + + if (defaultIngress) { + return defaultIngress; + } + + const ingressWithContainerId = ingresses.find((ingress) => + ingress.paths.some( + (path) => + path.target && + path.target.type === "container" && + path.target.data.container.id === this.containerMeta?.containerId, + ), + ); + + if (ingressWithContainerId) { + return ingressWithContainerId; + } + + return undefined; + } +} + +export class ProjectAIApiKeyListItem extends ProjectAIApiKeyCommon { + public override readonly data: ProjectAIApiKeyListItemData; + public constructor(data: ProjectAIApiKeyListItemData) { + super(data); + this.data = data; + } +} + +export class ProjectAIApiKeyListQuery extends ListQueryModel { + private readonly project: Project; + + public constructor( + project: Project, + query: ProjectAIApiKeyListQueryData = {}, + ) { + super(query); + this.project = project; + } + + public async execute(options?: AxiosRequestConfig) { + const { totalCount, items } = await config.behaviors.projectAiApiKey.list( + extractId(this.project), + options, + ); + + return new ProjectAIApiKeyList( + this.project, + this.query, + items.map((d) => new ProjectAIApiKeyListItem(d)), + totalCount, + ); + } + + public refine(query: ProjectAIApiKeyListQueryData) { + return new ProjectAIApiKeyListQuery(this.project, { + ...this.query, + ...query, + }); + } +} + +export class ProjectAIApiKeyList extends WithListData()( + ProjectAIApiKeyListQuery, +) { + public override readonly items: readonly ProjectAIApiKeyListItem[]; + public override readonly totalCount: number; + public constructor( + project: Project, + query: ProjectAIApiKeyListQueryData, + apiKeys: ProjectAIApiKeyListItem[], + totalCount: number, + ) { + super(project, query); + this.items = Object.freeze(apiKeys); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/ai/ProjectAIApiKey/behaviors/api.ts b/packages/models/src/ai/ProjectAIApiKey/behaviors/api.ts new file mode 100644 index 00000000..98eba552 --- /dev/null +++ b/packages/models/src/ai/ProjectAIApiKey/behaviors/api.ts @@ -0,0 +1,90 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; +import type { AxiosRequestConfig } from "axios"; + +import type { ProjectAIApiKeyBehaviors } from "./types.js"; + +import { + withAxiosRequestConfig, + resolveTotalCount, +} from "../../../base/index.js"; +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { ValidationError } from "../../../errors/index.js"; + +export const apiProjectAIApiKeyBehaviors = ( + client: MittwaldAPIV2Client, +): ProjectAIApiKeyBehaviors => ({ + find: async (projectId, apiKeyId) => { + const response = await client.aiHosting.projectGetKey({ + keyId: apiKeyId, + projectId, + }); + + if (response.status === 200) { + return response.data; + } + + const validationError = ValidationError.fromResponse(response); + // invalid uuid in URL + if ( + validationError && + validationError.errors.some( + (e) => e.path === "licenceId" || e.path === "licenseId", + ) + ) { + return; + } + + validateResponse(response, 404); + }, + list: async (projectId, options?: AxiosRequestConfig) => { + const response = await client.aiHosting.projectGetKeys( + { + projectId, + }, + withAxiosRequestConfig(options), + ); + + validateResponse(response, 200); + + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + linkContainer: async (projectId, apiKeyId, data) => { + const response = await client.aiHosting.projectLinkContainer({ + keyId: apiKeyId, + projectId, + data, + }); + + validateResponse(response, 204); + }, + create: async (projectId, data) => { + const response = await client.aiHosting.projectCreateKey({ + projectId, + data, + }); + + validateResponse(response, 201); + + return { id: response.data.keyId }; + }, + update: async (projectId, apiKeyId, data) => { + const response = await client.aiHosting.projectUpdateKey({ + keyId: apiKeyId, + projectId, + data, + }); + + validateResponse(response, 200); + }, + delete: async (projectId, apiKeyId) => { + const response = await client.aiHosting.projectDeleteKey({ + keyId: apiKeyId, + projectId, + }); + + validateResponse(response, 204); + }, +}); diff --git a/packages/models/src/ai/ProjectAIApiKey/behaviors/index.ts b/packages/models/src/ai/ProjectAIApiKey/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/ai/ProjectAIApiKey/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/ai/ProjectAIApiKey/behaviors/types.ts b/packages/models/src/ai/ProjectAIApiKey/behaviors/types.ts new file mode 100644 index 00000000..8dd037cc --- /dev/null +++ b/packages/models/src/ai/ProjectAIApiKey/behaviors/types.ts @@ -0,0 +1,40 @@ +import type { AxiosRequestConfig } from "axios"; + +import type { QueryResponseData } from "../../../base/index.js"; +import type { AIApiKeyData } from "../../types.js"; +import type { + ProjectAIApiKeyUpdateRequestData, + ProjectAIApiKeyRequestData, +} from "../types.js"; + +export interface ProjectAIApiKeyLinkContainerData { + containerId: string; + ingressId: string; + stackId: string; +} + +export interface ProjectAIApiKeyBehaviors { + update: ( + projectId: string, + apiKeyId: string, + data: Partial, + ) => Promise; + linkContainer: ( + projectId: string, + apiKeyId: string, + data: ProjectAIApiKeyLinkContainerData, + ) => Promise; + create: ( + projectId: string, + data: ProjectAIApiKeyRequestData, + ) => Promise<{ id: string } | undefined>; + list: ( + projectId: string, + options?: AxiosRequestConfig, + ) => Promise>; + find: ( + projectId: string, + licenceId: string, + ) => Promise; + delete: (projectId: string, apiKeyId: string) => Promise; +} diff --git a/packages/models/src/ai/ProjectAIApiKey/index.ts b/packages/models/src/ai/ProjectAIApiKey/index.ts new file mode 100644 index 00000000..e45ccd01 --- /dev/null +++ b/packages/models/src/ai/ProjectAIApiKey/index.ts @@ -0,0 +1,2 @@ +export * from "./ProjectAIApiKey.js"; +export * from "./types.js"; diff --git a/packages/models/src/ai/ProjectAIApiKey/types.ts b/packages/models/src/ai/ProjectAIApiKey/types.ts new file mode 100644 index 00000000..cc9ebe1d --- /dev/null +++ b/packages/models/src/ai/ProjectAIApiKey/types.ts @@ -0,0 +1,13 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type ProjectAIApiKeyListItemData = + MittwaldAPIV2.Operations.AiHostingProjectGetKeys.ResponseData[number]; + +export type ProjectAIApiKeyListQueryData = + MittwaldAPIV2.Paths.V2CustomersCustomerIdAiHostingKeys.Get.Parameters.Query; + +export type ProjectAIApiKeyRequestData = + MittwaldAPIV2.Paths.V2CustomersCustomerIdAiHostingKeys.Post.Parameters.RequestBody; + +export type ProjectAIApiKeyUpdateRequestData = + MittwaldAPIV2.Paths.V2CustomersCustomerIdAiHostingKeysKeyId.Put.Parameters.RequestBody; diff --git a/packages/models/src/ai/ProjectAIModel/ProjectAIModel.test.ts b/packages/models/src/ai/ProjectAIModel/ProjectAIModel.test.ts new file mode 100644 index 00000000..7824277b --- /dev/null +++ b/packages/models/src/ai/ProjectAIModel/ProjectAIModel.test.ts @@ -0,0 +1,61 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { buildProjectAIDetailedModelData } from "../../testing/builders/buildProjectAIDetailedModelData.js"; +import { ReferenceModel } from "../../base/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { + ProjectAIModelListItem, + ProjectAIModelList, + ProjectAIModel, +} from "./ProjectAIModel.js"; + +afterEach(resetBehaviors); + +describe("ProjectAIModel", () => { + it("delegates list queries and maps the result", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildProjectAIDetailedModelData()], + totalCount: 1, + }); + installBehaviors({ projectAIModel: { list } }); + + const result = await ProjectAIModel.query("project-1").execute(); + + expect(list).toHaveBeenCalledWith("project-1", {}); + expect(result).toBeInstanceOf(ProjectAIModelList); + expect(result.items[0]).toBeInstanceOf(ProjectAIModelListItem); + expect(result.totalCount).toBe(1); + }); + + it("exposes detailed model data through derived getters", () => { + const withoutRemoval = new ProjectAIModelListItem( + buildProjectAIDetailedModelData({ replacesModelName: "gpt-old" }), + ); + const withRemoval = new ProjectAIModelListItem( + buildProjectAIDetailedModelData({ + removalAt: "2025-01-01T00:00:00.000Z", + }), + ); + + expect(withoutRemoval.activeAt.isValid).toBe(true); + expect(withoutRemoval.removalAt).toBeUndefined(); + expect(withRemoval.removalAt?.isValid).toBe(true); + expect(withoutRemoval.status).toBe("active"); + expect(withoutRemoval.replacesModelName).toBe("gpt-old"); + expect(withoutRemoval.documentationLink).toBe( + "https://docs.example.com/detailed", + ); + }); + + it("preserves the model inheritance chain", () => { + const item = new ProjectAIModelListItem(buildProjectAIDetailedModelData()); + + expect(item).toBeInstanceOf(ProjectAIModelListItem); + expect(item).toBeInstanceOf(ProjectAIModel); + expect(item).toBeInstanceOf(ReferenceModel); + expect(item.data).toBeDefined(); + }); +}); diff --git a/packages/models/src/ai/ProjectAIModel/ProjectAIModel.ts b/packages/models/src/ai/ProjectAIModel/ProjectAIModel.ts new file mode 100644 index 00000000..70f81e59 --- /dev/null +++ b/packages/models/src/ai/ProjectAIModel/ProjectAIModel.ts @@ -0,0 +1,36 @@ +import type { + ProjectAIModelListQueryData, + ProjectAIModelData, +} from "./types.js"; + +import { makeScopedAIModelClasses } from "../lib/makeScopedAIModelClasses.js"; +import { config } from "../../config/index.js"; + +const classes = makeScopedAIModelClasses< + ProjectAIModelData, + ProjectAIModelListQueryData +>({ + resolveBehavior: () => config.behaviors.projectAIModel, + ghostName: "ProjectAIModel", +}); + +export const ProjectAIModel = classes.ScopedAIModel; +export type ProjectAIModel = InstanceType; + +export const ProjectAIModelCommon = classes.ScopedAIModelCommon; +export type ProjectAIModelCommon = InstanceType< + typeof classes.ScopedAIModelCommon +>; + +export const ProjectAIModelListItem = classes.ScopedAIModelListItem; +export type ProjectAIModelListItem = InstanceType< + typeof classes.ScopedAIModelListItem +>; + +export const ProjectAIModelListQuery = classes.ScopedAIModelListQuery; +export type ProjectAIModelListQuery = InstanceType< + typeof classes.ScopedAIModelListQuery +>; + +export const ProjectAIModelList = classes.ScopedAIModelList; +export type ProjectAIModelList = InstanceType; diff --git a/packages/models/src/ai/ProjectAIModel/behaviors/api.ts b/packages/models/src/ai/ProjectAIModel/behaviors/api.ts new file mode 100644 index 00000000..76000b8f --- /dev/null +++ b/packages/models/src/ai/ProjectAIModel/behaviors/api.ts @@ -0,0 +1,24 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { ProjectAIModelBehaviors } from "./types.js"; + +import { resolveTotalCount, validateResponse } from "../../../base/index.js"; + +export const apiProjectAIModelBehaviors = ( + client: MittwaldAPIV2Client, +): ProjectAIModelBehaviors => ({ + list: async (projectId: string) => { + const response = await client.aiHosting.projectGetDetailedModels({ + projectId, + }); + if (response.status !== 200) { + validateResponse(response, 404); + return { totalCount: 0, items: [] }; + } + + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, +}); diff --git a/packages/models/src/ai/ProjectAIModel/behaviors/index.ts b/packages/models/src/ai/ProjectAIModel/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/ai/ProjectAIModel/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/ai/ProjectAIModel/behaviors/types.ts b/packages/models/src/ai/ProjectAIModel/behaviors/types.ts new file mode 100644 index 00000000..08dfde21 --- /dev/null +++ b/packages/models/src/ai/ProjectAIModel/behaviors/types.ts @@ -0,0 +1,11 @@ +import type { + ProjectAIModelListQueryData, + ProjectAIModelListItemData, +} from "../types.js"; + +export interface ProjectAIModelBehaviors { + list: ( + projectId: string, + query?: ProjectAIModelListQueryData, + ) => Promise<{ items: ProjectAIModelListItemData[]; totalCount: number }>; +} diff --git a/packages/models/src/ai/ProjectAIModel/index.ts b/packages/models/src/ai/ProjectAIModel/index.ts new file mode 100644 index 00000000..12a70449 --- /dev/null +++ b/packages/models/src/ai/ProjectAIModel/index.ts @@ -0,0 +1,2 @@ +export * from "./ProjectAIModel.js"; +export * from "./types.js"; diff --git a/packages/models/src/ai/ProjectAIModel/types.ts b/packages/models/src/ai/ProjectAIModel/types.ts new file mode 100644 index 00000000..965dd006 --- /dev/null +++ b/packages/models/src/ai/ProjectAIModel/types.ts @@ -0,0 +1,12 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type ProjectAIModelData = + MittwaldAPIV2.Operations.AiHostingProjectGetDetailedModels.ResponseData[number]; + +export type ProjectAIModelListItemData = ProjectAIModelData; + +export type ProjectAIModelStatus = + MittwaldAPIV2.Components.Schemas.AihostingDetailedModelStatus; + +// eslint-disable-next-line @typescript-eslint/no-empty-object-type +export interface ProjectAIModelListQueryData {} diff --git a/packages/models/src/ai/ProjectAIPlan/ProjectAIPlan.test.ts b/packages/models/src/ai/ProjectAIPlan/ProjectAIPlan.test.ts new file mode 100644 index 00000000..f840f34a --- /dev/null +++ b/packages/models/src/ai/ProjectAIPlan/ProjectAIPlan.test.ts @@ -0,0 +1,212 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { buildProjectAIPlanData } from "../../testing/builders/buildProjectAIPlanData.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { + ProjectAIPlanDetailed, + ProjectAIPlanListItem, + ProjectAIPlanCommon, + ProjectAIPlanList, + ProjectAIPlan, +} from "./ProjectAIPlan.js"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +afterEach(resetBehaviors); + +test("ofId creates a reference with the given plan id", () => { + const plan = ProjectAIPlan.ofId("project-123", "plan-1"); + + expect(plan).toBeInstanceOf(ProjectAIPlan); + expect(plan.id).toBe("plan-1"); + expect(plan.projectId).toBe("project-123"); +}); + +test("findByProject delegates to the behavior and maps returned data", async () => { + const options = { headers: { "x-test": "value" } }; + const data = buildProjectAIPlanData({ + keys: { planLimit: 500, available: 75, used: 25 }, + modelTermsApprovalRequired: true, + projectId: "project-123", + planId: "plan-1", + }); + const find = vi.fn().mockResolvedValue(data); + installBehaviors({ projectAiPlan: { find } }); + + const plan = await ProjectAIPlan.findByProject( + "project-123", + "plan-1", + options, + ); + + expect(find).toHaveBeenCalledOnce(); + expect(find).toHaveBeenCalledWith("project-123", "plan-1", options); + expect(plan).toBeInstanceOf(ProjectAIPlanDetailed); + expect(plan).toBeInstanceOf(ProjectAIPlanCommon); + expect(plan).toBeInstanceOf(ProjectAIPlan); + expect(plan).toMatchObject({ + modelTermsApprovalRequired: true, + apiKeys: data.keys, + id: "plan-1", + }); +}); + +test("findByProject returns undefined when the behavior finds no data", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ projectAiPlan: { find } }); + + await expect( + ProjectAIPlan.findByProject("project-123", "plan-1"), + ).resolves.toBeUndefined(); +}); + +test("getByProject returns the detailed model when found", async () => { + const data = buildProjectAIPlanData({ + projectId: "project-123", + planId: "plan-1", + }); + const find = vi.fn().mockResolvedValue(data); + installBehaviors({ projectAiPlan: { find } }); + + const plan = await ProjectAIPlan.getByProject("project-123", "plan-1"); + + expect(plan).toBeInstanceOf(ProjectAIPlanDetailed); + expect(plan.id).toBe("plan-1"); +}); + +test("findDetailed delegates using the reference ids", async () => { + const options = { headers: { "x-test": "value" } }; + const data = buildProjectAIPlanData({ projectId: "project-123" }); + const find = vi.fn().mockResolvedValue(data); + installBehaviors({ projectAiPlan: { find } }); + + const plan = await ProjectAIPlan.ofId("project-123", "plan-1").findDetailed( + options, + ); + + expect(find).toHaveBeenCalledWith("project-123", "plan-1", options); + expect(plan).toBeInstanceOf(ProjectAIPlanDetailed); +}); + +test("findCommon and getCommon return an existing common model without refetching", async () => { + const find = vi.fn(); + installBehaviors({ projectAiPlan: { find } }); + const plan = new ProjectAIPlanDetailed(buildProjectAIPlanData()); + + await expect(plan.findCommon()).resolves.toBe(plan); + await expect(plan.getCommon()).resolves.toBe(plan); + expect(find).not.toHaveBeenCalled(); +}); + +describe("hasPlan", () => { + test.each([ + { caseName: "positive plan limit", planLimit: 1000, expected: true }, + { caseName: "unlimited plan", expected: true, planLimit: -1 }, + { caseName: "zero plan limit", expected: false, planLimit: 0 }, + ])("returns $expected for a $caseName", ({ planLimit, expected }) => { + const plan = new ProjectAIPlanDetailed( + buildProjectAIPlanData({ + keys: { available: 100, planLimit, used: 0 }, + }), + ); + + expect(plan.hasPlan()).toBe(expected); + }); +}); + +describe("common lookups from a bare reference", () => { + test("findCommon on a bare reference delegates to find and returns the detailed variant", async () => { + const data = buildProjectAIPlanData({ + projectId: "project-123", + planId: "plan-1", + }); + const find = vi.fn().mockResolvedValue(data); + installBehaviors({ projectAiPlan: { find } }); + + const result = await ProjectAIPlan.ofId( + "project-123", + "plan-1", + ).findCommon(); + + expect(find).toHaveBeenCalledWith("project-123", "plan-1", undefined); + expect(result).toBeInstanceOf(ProjectAIPlanDetailed); + expect(result).toBeInstanceOf(ProjectAIPlanCommon); + expect(result?.id).toBe("plan-1"); + }); + + test("getCommon on a bare reference returns the common variant when found", async () => { + const data = buildProjectAIPlanData({ + projectId: "project-123", + planId: "plan-1", + }); + const find = vi.fn().mockResolvedValue(data); + installBehaviors({ projectAiPlan: { find } }); + + const result = await ProjectAIPlan.ofId( + "project-123", + "plan-1", + ).getCommon(); + + expect(result).toBeInstanceOf(ProjectAIPlanCommon); + expect(result.id).toBe("plan-1"); + }); + + test("getCommon on a bare reference throws when plan options are not found", async () => { + installBehaviors({ + projectAiPlan: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + ProjectAIPlan.ofId("project-123", "plan-1").getCommon(), + ).rejects.toThrow(); + }); +}); + +describe("query", () => { + test("execute maps the listed plans", async () => { + const list = vi.fn().mockResolvedValue({ + items: [ + { + ...buildProjectAIPlanData({ + description: "AI Hosting M", + projectId: "project-123", + }), + planId: "plan-1", + }, + ], + totalCount: 1, + }); + installBehaviors({ projectAiPlan: { list } }); + + const result = await ProjectAIPlan.query("project-123").execute(); + + expect(list).toHaveBeenCalledWith("project-123", {}, undefined); + expect(result).toBeInstanceOf(ProjectAIPlanList); + expect(result.items[0]).toBeInstanceOf(ProjectAIPlanListItem); + expect(result.items[0]).toMatchObject({ + description: "AI Hosting M", + planId: "plan-1", + }); + }); + + test("getTotalCount resolves the number of plans", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildProjectAIPlanData(), buildProjectAIPlanData()], + totalCount: 2, + }); + installBehaviors({ projectAiPlan: { list } }); + + await expect( + ProjectAIPlan.query("project-123").getTotalCount(), + ).resolves.toBe(2); + }); +}); diff --git a/packages/models/src/ai/ProjectAIPlan/ProjectAIPlan.ts b/packages/models/src/ai/ProjectAIPlan/ProjectAIPlan.ts new file mode 100644 index 00000000..508e4b90 --- /dev/null +++ b/packages/models/src/ai/ProjectAIPlan/ProjectAIPlan.ts @@ -0,0 +1,186 @@ +import type { AxiosRequestConfig } from "axios"; + +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; + +import type { + ProjectAIPlanListQueryData, + ProjectAIPlanListItemData, + ProjectAIPlanLicences, + ProjectAIPlanData, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { Project } from "../../project/internal.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "ProjectAIPlan", +}) +export class ProjectAIPlan extends ReferenceModel { + public readonly projectId: string; + + public constructor(planId: string, projectId: string) { + super(planId); + this.projectId = projectId; + } + + public static async findByProject( + projectId: string, + planId: string, + options?: AxiosRequestConfig, + ) { + const data = await config.behaviors.projectAiPlan.find( + projectId, + planId, + options, + ); + + if (data) { + return new ProjectAIPlanDetailed(data); + } + } + + public static async getByProject( + projectId: string, + planId: string, + options?: AxiosRequestConfig, + ) { + const plan = await this.findByProject(projectId, planId, options); + assertObjectFound(plan, ProjectAIPlan, planId); + return plan; + } + + public static ofId(projectId: string, planId: string) { + return new ProjectAIPlan(planId, projectId); + } + + public static query(project: Project | string) { + return new ProjectAIPlanListQuery(extractId(project)); + } + + public async findCommon( + options?: AxiosRequestConfig, + ): Promise { + return this instanceof ProjectAIPlanCommon + ? this + : this.findDetailed(options); + } + + public async findDetailed( + options?: AxiosRequestConfig, + ): Promise { + return ProjectAIPlan.findByProject(this.projectId, this.id, options); + } + + public async getCommon( + options?: AxiosRequestConfig, + ): Promise { + return this instanceof ProjectAIPlanCommon + ? this + : this.getDetailed(options); + } + + public async getDetailed( + options?: AxiosRequestConfig, + ): Promise { + return ProjectAIPlan.getByProject(this.projectId, this.id, options); + } +} + +export class ProjectAIPlanCommon extends WithData< + ProjectAIPlanListItemData | ProjectAIPlanData +>()(ProjectAIPlan) { + public readonly apiKeys: ProjectAIPlanLicences; + public override readonly data: ProjectAIPlanListItemData | ProjectAIPlanData; + public readonly description?: string; + public readonly modelTermsApprovalRequired: boolean; + public readonly planId: string; + public readonly project: Project; + + public constructor(data: ProjectAIPlanListItemData | ProjectAIPlanData) { + super(data.planId, data.projectId); + this.data = data; + + this.planId = data.planId; + this.project = Project.ofId(data.projectId); + this.description = data.description; + this.apiKeys = data.keys; + this.modelTermsApprovalRequired = data.modelTermsApprovalRequired; + } + + public hasPlan(): boolean { + return this.apiKeys.planLimit > 0 || this.apiKeys.planLimit === -1; + } +} + +export class ProjectAIPlanDetailed extends ProjectAIPlanCommon { + public constructor(data: ProjectAIPlanData) { + super(data); + } +} + +export class ProjectAIPlanListItem extends ProjectAIPlanCommon { + public override readonly data: ProjectAIPlanListItemData; + + public constructor(data: ProjectAIPlanListItemData) { + super(data); + this.data = data; + } +} + +export class ProjectAIPlanListQuery extends ListQueryModel { + private readonly projectId: string; + + public constructor( + projectId: string, + query: ProjectAIPlanListQueryData = {}, + ) { + super(query, { dependencies: [projectId] }); + this.projectId = projectId; + } + + public async execute(options?: AxiosRequestConfig) { + const result = await config.behaviors.projectAiPlan.list( + this.projectId, + this.query, + options, + ); + + return new ProjectAIPlanList( + this.projectId, + this.query, + result.items.map((item) => new ProjectAIPlanListItem(item)), + result.totalCount, + ); + } + + public override async getTotalCount(options?: AxiosRequestConfig) { + const list = await this.execute(options); + return list.totalCount; + } +} + +export class ProjectAIPlanList extends WithListData()( + ProjectAIPlanListQuery, +) { + public override readonly items: readonly ProjectAIPlanListItem[]; + public override readonly totalCount: number; + + public constructor( + projectId: string, + query: ProjectAIPlanListQueryData, + items: ProjectAIPlanListItem[], + totalCount: number, + ) { + super(projectId, query); + this.items = Object.freeze(items); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/ai/ProjectAIPlan/behavior/api.ts b/packages/models/src/ai/ProjectAIPlan/behavior/api.ts new file mode 100644 index 00000000..11cc9b36 --- /dev/null +++ b/packages/models/src/ai/ProjectAIPlan/behavior/api.ts @@ -0,0 +1,43 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; +import type { AxiosRequestConfig } from "axios"; + +import type { ProjectAIPlanBehavior } from "./types.js"; + +import { withAxiosRequestConfig } from "../../../base/api/withModelRequestOptions.js"; +import { resolveTotalCount } from "../../../base/api/resolveTotalCount.js"; +import { validateResponse } from "../../../base/api/validateResponse.js"; + +export const apiProjectAIPlanBehaviors = ( + client: MittwaldAPIV2Client, +): ProjectAIPlanBehavior => ({ + list: async (projectId, _query, options) => { + const response = await client.aiHosting.projectGetPlans( + { projectId }, + withAxiosRequestConfig(options), + ); + + if (response.status !== 200) { + validateResponse(response, 404); + return { totalCount: 0, items: [] }; + } + + const { plans } = response.data; + return { + totalCount: resolveTotalCount(response, plans.length), + items: plans, + }; + }, + + find: async (projectId, planId, options?: AxiosRequestConfig) => { + const response = await client.aiHosting.projectGetPlan( + { projectId, planId }, + withAxiosRequestConfig(options), + ); + + if (response.status === 200) { + return response.data; + } + + validateResponse(response, 404); + }, +}); diff --git a/packages/models/src/ai/ProjectAIPlan/behavior/index.ts b/packages/models/src/ai/ProjectAIPlan/behavior/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/ai/ProjectAIPlan/behavior/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/ai/ProjectAIPlan/behavior/types.ts b/packages/models/src/ai/ProjectAIPlan/behavior/types.ts new file mode 100644 index 00000000..809f3a46 --- /dev/null +++ b/packages/models/src/ai/ProjectAIPlan/behavior/types.ts @@ -0,0 +1,21 @@ +import type { AxiosRequestConfig } from "axios"; + +import type { QueryResponseData } from "../../../base/index.js"; +import type { + ProjectAIPlanListQueryData, + ProjectAIPlanListItemData, + ProjectAIPlanData, +} from "../types.js"; + +export interface ProjectAIPlanBehavior { + list: ( + projectId: string, + query?: ProjectAIPlanListQueryData, + options?: AxiosRequestConfig, + ) => Promise>; + find: ( + projectId: string, + planId: string, + options?: AxiosRequestConfig, + ) => Promise; +} diff --git a/packages/models/src/ai/ProjectAIPlan/index.ts b/packages/models/src/ai/ProjectAIPlan/index.ts new file mode 100644 index 00000000..3f105a97 --- /dev/null +++ b/packages/models/src/ai/ProjectAIPlan/index.ts @@ -0,0 +1,2 @@ +export * from "./ProjectAIPlan.js"; +export * from "./types.js"; diff --git a/packages/models/src/ai/ProjectAIPlan/types.ts b/packages/models/src/ai/ProjectAIPlan/types.ts new file mode 100644 index 00000000..8b127df1 --- /dev/null +++ b/packages/models/src/ai/ProjectAIPlan/types.ts @@ -0,0 +1,11 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type ProjectAIPlanData = + MittwaldAPIV2.Operations.AiHostingProjectGetPlan.ResponseData; + +export type ProjectAIPlanListItemData = + MittwaldAPIV2.Operations.AiHostingProjectGetPlans.ResponseData["plans"][number]; + +export type ProjectAIPlanListQueryData = Record; + +export type ProjectAIPlanLicences = ProjectAIPlanData["keys"]; diff --git a/packages/models/src/ai/aiContainerType.ts b/packages/models/src/ai/aiContainerType.ts new file mode 100644 index 00000000..da5cc6f5 --- /dev/null +++ b/packages/models/src/ai/aiContainerType.ts @@ -0,0 +1,9 @@ +export const aiContainerTypes = [ + "openwebui", + "anythingllm", + "librechat", +] as const; + +export type AIContainerType = (typeof aiContainerTypes)[number]; + +export const DEFAULT_AI_CONTAINER_TYPE: AIContainerType = "openwebui"; diff --git a/packages/models/src/ai/helper.test.ts b/packages/models/src/ai/helper.test.ts new file mode 100644 index 00000000..4bebd839 --- /dev/null +++ b/packages/models/src/ai/helper.test.ts @@ -0,0 +1,48 @@ +import { expect, test } from "vitest"; + +import { formatTokenUsage } from "./helper.js"; + +test("formatTokenUsage returns '0' for zero tokens", () => { + expect(formatTokenUsage(0)).toBe("0"); +}); + +test("formatTokenUsage formats millions correctly with default digits", () => { + expect(formatTokenUsage(1_000_000)).toBe("1,0"); + expect(formatTokenUsage(2_500_000)).toBe("2,5"); + expect(formatTokenUsage(10_000_000)).toBe("10,0"); +}); + +test("formatTokenUsage formats millions correctly with custom digits", () => { + expect(formatTokenUsage(1_234_567, 2)).toBe("1,23"); + expect(formatTokenUsage(1_234_567, 3)).toBe("1,235"); + expect(formatTokenUsage(5_000_000, 0)).toBe("5"); +}); + +test("formatTokenUsage shows '< threshold' for very small values", () => { + expect(formatTokenUsage(50_000)).toBe("< 0,1"); + expect(formatTokenUsage(1_000)).toBe("< 0,1"); + expect(formatTokenUsage(99_999)).toBe("< 0,1"); +}); + +test("formatTokenUsage shows '< threshold' with custom digits", () => { + expect(formatTokenUsage(5_000, 2)).toBe("< 0,01"); + expect(formatTokenUsage(999, 3)).toBe("< 0,001"); +}); + +test("formatTokenUsage handles threshold boundary correctly", () => { + expect(formatTokenUsage(100_000, 1)).toBe("0,1"); + expect(formatTokenUsage(99_999, 1)).toBe("< 0,1"); + + expect(formatTokenUsage(10_000, 2)).toBe("0,01"); + expect(formatTokenUsage(9_999, 2)).toBe("< 0,01"); +}); + +test("formatTokenUsage uses German number format", () => { + expect(formatTokenUsage(1_500_000)).toBe("1,5"); + expect(formatTokenUsage(123_456_789, 2)).toBe("123,46"); +}); + +test("formatTokenUsage handles large numbers", () => { + expect(formatTokenUsage(1_000_000_000, 1)).toBe("1.000,0"); + expect(formatTokenUsage(999_999_999, 2)).toBe("1.000,00"); +}); diff --git a/packages/models/src/ai/helper.ts b/packages/models/src/ai/helper.ts new file mode 100644 index 00000000..d15fcf71 --- /dev/null +++ b/packages/models/src/ai/helper.ts @@ -0,0 +1,18 @@ +export const formatTokenUsage = (tokens: number, digits = 1) => { + const value = tokens / 1_000_000; + const nf = new Intl.NumberFormat("de-DE", { + minimumFractionDigits: digits, + maximumFractionDigits: digits, + }); + + if (value === 0) { + return "0"; + } + + const threshold = Math.pow(10, -digits); // bei digits=1 -> 0.1 + if (value > 0 && value < threshold) { + return `< ${nf.format(threshold)}`; + } + + return nf.format(value); +}; diff --git a/packages/models/src/ai/index.ts b/packages/models/src/ai/index.ts new file mode 100644 index 00000000..ffd0c540 --- /dev/null +++ b/packages/models/src/ai/index.ts @@ -0,0 +1,10 @@ +export * from "./aiContainerType.js"; +export * from "./AIModel/index.js"; +export * from "./AITokenStatistics/index.js"; +export * from "./CustomerAIApiKey/index.js"; +export * from "./CustomerAIModel/index.js"; +export * from "./CustomerAIPlan/index.js"; +export * from "./helper.js"; +export * from "./ProjectAIApiKey/index.js"; +export * from "./ProjectAIModel/index.js"; +export * from "./ProjectAIPlan/index.js"; diff --git a/packages/models/src/ai/lib/makeScopedAIModelClasses.ts b/packages/models/src/ai/lib/makeScopedAIModelClasses.ts new file mode 100644 index 00000000..33cf07a9 --- /dev/null +++ b/packages/models/src/ai/lib/makeScopedAIModelClasses.ts @@ -0,0 +1,156 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; + +import type { AIModelLabel } from "../AIModel/index.js"; + +import { + ListQueryModel, + ReferenceModel, + WithListData, + WithData, +} from "../../base/index.js"; + +type AIDetailedModelStatus = + MittwaldAPIV2.Components.Schemas.AihostingDetailedModelStatus; + +/** + * The detailed-model shape shared by the customer- and project-scoped AI-model + * list endpoints (`aiHosting.{customer,project}GetDetailedModels`). Both scopes + * return the identical payload; only the endpoint differs. + */ +export interface ScopedAIDetailedModelData { + status: AIDetailedModelStatus; + termsOfServiceLink: string; + replacesModelName?: string; + label?: AIModelLabel; + displayName: string; + removalAt?: string; + activeAt: string; + docLink: string; + name: string; +} + +export interface ScopedAIModelListBehavior { + list: ( + scopeId: string, + query?: TQuery, + ) => Promise<{ totalCount: number; items: TData[] }>; +} + +/** + * Builds the identical `ReferenceModel → Common → ListItem` + `ListQuery → + * List` class family for a scoped AI-model context. `CustomerAIModel` and + * `ProjectAIModel` are 100 % identical apart from the ghost name and which + * scoped `list` behavior they call, so both are produced from this one factory. + * The generic keeps each scope's public data type. + */ +export const makeScopedAIModelClasses = < + TData extends ScopedAIDetailedModelData, + TQuery extends object, +>(cfg: { + resolveBehavior: () => ScopedAIModelListBehavior; + ghostName: string; +}) => { + @GhostMakerModel({ + name: cfg.ghostName, + }) + class ScopedAIModel extends ReferenceModel { + public constructor(id: string) { + super(id); + } + + public static query = (scopeId: string, query?: TQuery) => { + return new ScopedAIModelListQuery(scopeId, query); + }; + } + + class ScopedAIModelCommon extends WithData()(ScopedAIModel) { + public readonly activeAt: DateTime; + public override readonly data: TData; + public readonly displayName: string; + public readonly documentationLink: string; + public readonly label?: AIModelLabel; + public readonly name: string; + public readonly removalAt: DateTime | undefined; + public readonly replacesModelName: string | undefined; + public readonly status: AIDetailedModelStatus; + public readonly termsOfServiceLink: string; + + public constructor(data: TData) { + super(data.name); + this.data = data; + this.name = data.name; + this.displayName = data.displayName; + this.documentationLink = data.docLink; + this.termsOfServiceLink = data.termsOfServiceLink; + this.status = data.status; + this.activeAt = DateTime.fromISO(data.activeAt); + this.removalAt = data.removalAt + ? DateTime.fromISO(data.removalAt) + : undefined; + this.replacesModelName = data.replacesModelName; + this.label = data.label; + } + } + + class ScopedAIModelListItem extends ScopedAIModelCommon { + public override readonly data: TData; + public constructor(data: TData) { + super(data); + this.data = data; + } + } + + // The classes below are local to this factory, so declaration emit has to + // describe them as anonymous class types — which cannot carry private or + // protected members (TS4094). Both `query` (protected in `ListQueryModel`) + // and `scopeId` are therefore widened to public here. + class ScopedAIModelListQuery extends ListQueryModel { + declare public readonly query: TQuery; + public readonly scopeId: string; + public constructor(scopeId: string, query: TQuery = {} as TQuery) { + super(query); + this.scopeId = scopeId; + } + + public async execute() { + const { totalCount, items } = await cfg + .resolveBehavior() + .list(this.scopeId, this.query); + + return new ScopedAIModelList( + this.scopeId, + this.query, + items.map((item) => new ScopedAIModelListItem(item)), + totalCount, + ); + } + } + + class ScopedAIModelList extends WithListData()( + ScopedAIModelListQuery, + ) { + public override readonly items: readonly ScopedAIModelListItem[]; + public override readonly totalCount: number; + public constructor( + scopeId: string, + query: TQuery, + items: ScopedAIModelListItem[], + totalCount: number, + ) { + super(scopeId, query); + this.items = Object.freeze(items); + this.totalCount = totalCount; + } + } + + return { + ScopedAIModelListQuery, + ScopedAIModelListItem, + ScopedAIModelCommon, + ScopedAIModelList, + ScopedAIModel, + }; +}; diff --git a/packages/models/src/ai/types.ts b/packages/models/src/ai/types.ts new file mode 100644 index 00000000..3087ceea --- /dev/null +++ b/packages/models/src/ai/types.ts @@ -0,0 +1,9 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type AIApiKeyData = MittwaldAPIV2.Components.Schemas.AihostingKey; + +export type AIApiKeyContainerMetaData = AIApiKeyData["containerMeta"]; +export type AIApiKeyRateLimitData = AIApiKeyData["rateLimit"]; +export type AIApiKeyTokenUsageData = { + formattedUsed: string; +} & AIApiKeyData["tokenUsage"]; diff --git a/packages/models/src/app/App/App.test.ts b/packages/models/src/app/App/App.test.ts new file mode 100644 index 00000000..0b36f564 --- /dev/null +++ b/packages/models/src/app/App/App.test.ts @@ -0,0 +1,130 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { ObjectNotFoundError } from "../../errors/ObjectNotFoundError.js"; +import { buildAppData } from "../../testing/builders/buildAppData.js"; +import { ReferenceModel } from "../../base/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { AppListQuery, AppDetailed, AppListItem, AppList, App } from "./App.js"; + +afterEach(resetBehaviors); + +describe("App", () => { + test("find and get delegate and materialize detailed apps", async () => { + const find = vi.fn().mockResolvedValue(buildAppData({ id: "a-1" })); + installBehaviors({ app: { find } }); + + await expect(App.find("a-1")).resolves.toEqual( + expect.objectContaining({ id: "a-1" }), + ); + await expect(App.get("a-1")).resolves.toBeInstanceOf(AppDetailed); + expect(find).toHaveBeenCalledWith("a-1"); + }); + + test("find returns undefined and get throws when missing", async () => { + installBehaviors({ app: { find: vi.fn().mockResolvedValue(undefined) } }); + + await expect(App.find("missing")).resolves.toBeUndefined(); + await expect(App.get("missing")).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("findCommon and getCommon materialize a reference via the behavior", async () => { + const find = vi.fn().mockResolvedValue(buildAppData({ id: "a-1" })); + installBehaviors({ app: { find } }); + const reference = App.ofId("a-1"); + + await expect(reference.findCommon()).resolves.toBeInstanceOf(AppDetailed); + await expect(reference.getCommon()).resolves.toBeInstanceOf(AppDetailed); + expect(find).toHaveBeenCalledWith("a-1"); + }); + + test("findCommon resolves undefined and getCommon throws when missing", async () => { + installBehaviors({ app: { find: vi.fn().mockResolvedValue(undefined) } }); + const reference = App.ofId("missing"); + + await expect(reference.findCommon()).resolves.toBeUndefined(); + await expect(reference.getCommon()).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("findCommon and getCommon are idempotent for materialized apps", async () => { + const find = vi.fn(); + installBehaviors({ app: { find } }); + const detailed = new AppDetailed(buildAppData({ id: "a-1" })); + const listItem = new AppListItem(buildAppData({ id: "a-2" })); + + await expect(detailed.findCommon()).resolves.toBe(detailed); + await expect(detailed.getCommon()).resolves.toBe(detailed); + await expect(listItem.findCommon()).resolves.toBe(listItem); + await expect(listItem.getCommon()).resolves.toBe(listItem); + expect(find).not.toHaveBeenCalled(); + }); + + test("references find their detailed model", async () => { + const find = vi.fn().mockResolvedValue(buildAppData({ id: "a-1" })); + installBehaviors({ app: { find } }); + const app = App.ofId("a-1"); + + expect(app).toBeInstanceOf(App); + await expect(app.findDetailed()).resolves.toBeInstanceOf(AppDetailed); + expect(find).toHaveBeenCalledWith("a-1"); + }); + + test("exposes app classification and tags", () => { + const node = new AppListItem( + buildAppData({ tags: ["runtime"], name: "Node.js" }), + ); + const php = new AppListItem(buildAppData({ name: "PHP" })); + const wordpress = new AppListItem(buildAppData({ name: "WordPress" })); + + expect(node).toMatchObject({ + isCustomApp: true, + tags: ["runtime"], + isNodeApp: true, + }); + expect(php).toMatchObject({ isCustomApp: true, isNodeApp: false }); + expect(wordpress).toMatchObject({ isCustomApp: false, isPopular: true }); + }); + + test("query delegates and preserves pagination", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildAppData({ id: "a-1" })], + totalCount: 1, + }); + installBehaviors({ app: { list } }); + const query = App.query(); + + const result = await query.execute(); + + expect(result).toBeInstanceOf(AppList); + expect(result).toBeInstanceOf(AppListQuery); + expect(result.items[0]).toBeInstanceOf(AppListItem); + expect(result.totalCount).toBe(1); + expect(list).toHaveBeenCalledWith({}); + }); + + test("preserves ghostmaker composition chains", () => { + for (const app of [ + new AppListItem(buildAppData()), + new AppDetailed(buildAppData()), + ]) { + expect(app).toBeInstanceOf(App); + expect(app).toBeInstanceOf(ReferenceModel); + // ADR-0004: data is a capability mixin, not a nominal base. + expect(app.data).toBeDefined(); + } + }); +}); diff --git a/packages/models/src/app/App/App.ts b/packages/models/src/app/App/App.ts new file mode 100644 index 00000000..4ae5f65f --- /dev/null +++ b/packages/models/src/app/App/App.ts @@ -0,0 +1,155 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; + +import type { AppVersionListQuery } from "../index.js"; +import type { + AppListQueryData, + AppListItemData, + AppData, + AppName, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { config } from "../../config/index.js"; +import { AppVersion } from "../index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "App", +}) +export class App extends ReferenceModel { + public readonly recommendedVersions: AppVersionListQuery; + + public constructor(id: string) { + super(id); + this.recommendedVersions = AppVersion.query({ + recommended: true, + app: this, + }); + } + + public static async find(id: string) { + const data = await config.behaviors.app.find(id); + if (data) { + return new AppDetailed(data); + } + } + + public static async get(id: string) { + const app = await this.find(id); + assertObjectFound(app, App, id); + return app; + } + + public static ofId(id: string) { + return new App(id); + } + + public static query = (query: AppListQueryData = {}) => + new AppListQuery(query); + + public async findCommon(): Promise { + return this instanceof AppCommon ? this : this.findDetailed(); + } + + public async findDetailed(): Promise { + return App.find(this.id); + } + + public async getCommon(): Promise { + return this instanceof AppCommon ? this : this.getDetailed(); + } + + public async getDetailed(): Promise { + return App.get(this.id); + } +} + +export class AppCommon extends WithData()(App) { + public override readonly data: AppListItemData | AppData; + public readonly isCustomApp: boolean; + public readonly isNodeApp: boolean; + public readonly isPopular: boolean; + public readonly name: AppName; + public readonly tags: string[]; + public constructor(data: AppListItemData | AppData) { + super(data.id); + this.data = data; + this.name = data.name as AppName; + this.isNodeApp = this.name === "Node.js"; + this.isCustomApp = + this.isNodeApp || + this.name === "PHP" || + this.name === "Static Files" || + this.name === "Python" || + this.name === "PHP-Worker"; + this.tags = data.tags; + this.isPopular = + this.name === "WordPress" || + this.name === "TYPO3" || + this.name === "Shopware 6" || + this.name === "PHP"; + } +} + +export class AppDetailed extends AppCommon { + public override readonly data: AppData; + public constructor(data: AppData) { + super(data); + this.data = data; + } +} + +export class AppListItem extends AppCommon { + public override readonly data: AppListItemData; + public constructor(data: AppListItemData) { + super(data); + this.data = data; + } +} + +export class AppListQuery extends ListQueryModel { + public constructor(query: AppListQueryData = {}) { + super(query); + } + + public async execute() { + const { totalCount, items } = await config.behaviors.app.list(this.query); + + return new AppList( + this.query, + items.map((d) => new AppListItem(d)), + totalCount, + ); + } + + public async getTotalCount() { + const { totalCount } = await this.refine({ limit: 1 }).execute(); + return totalCount; + } + + public refine(query: AppListQueryData) { + return new AppListQuery({ + ...this.query, + ...query, + }); + } +} + +export class AppList extends WithListData()(AppListQuery) { + public override readonly items: readonly AppListItem[]; + public override readonly totalCount: number; + public constructor( + query: AppListQueryData, + apps: AppListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(apps); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/app/App/behaviors/api.ts b/packages/models/src/app/App/behaviors/api.ts new file mode 100644 index 00000000..be848a11 --- /dev/null +++ b/packages/models/src/app/App/behaviors/api.ts @@ -0,0 +1,27 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { AppBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount } from "../../../base/index.js"; + +export const apiAppBehaviors = (client: MittwaldAPIV2Client): AppBehaviors => ({ + list: async (query) => { + const response = await client.app.listApps({ queryParameters: query }); + + validateResponse(response, 200); + + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + find: async (appId) => { + const response = await client.app.getApp({ appId }); + if (response.status === 200) { + return response.data; + } + validateResponse(response, 404); + }, +}); diff --git a/packages/models/src/app/App/behaviors/index.ts b/packages/models/src/app/App/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/app/App/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/app/App/behaviors/types.ts b/packages/models/src/app/App/behaviors/types.ts new file mode 100644 index 00000000..434738f0 --- /dev/null +++ b/packages/models/src/app/App/behaviors/types.ts @@ -0,0 +1,8 @@ +import type { AppListQueryData, AppListItemData, AppData } from "../types.js"; + +export interface AppBehaviors { + list: ( + query?: AppListQueryData, + ) => Promise<{ items: AppListItemData[]; totalCount: number }>; + find: (appId: string) => Promise; +} diff --git a/packages/models/src/app/App/index.ts b/packages/models/src/app/App/index.ts new file mode 100644 index 00000000..7b7a729e --- /dev/null +++ b/packages/models/src/app/App/index.ts @@ -0,0 +1,2 @@ +export * from "./App.js"; +export * from "./types.js"; diff --git a/packages/models/src/app/App/types.ts b/packages/models/src/app/App/types.ts new file mode 100644 index 00000000..82116526 --- /dev/null +++ b/packages/models/src/app/App/types.ts @@ -0,0 +1,49 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type AppData = MittwaldAPIV2.Operations.AppGetApp.ResponseData; + +export type AppListItemData = + MittwaldAPIV2.Operations.AppListApps.ResponseData[number]; + +export type AppListQueryData = MittwaldAPIV2.Paths.V2Apps.Get.Parameters.Query; + +export type AppUpdatePolicyData = + MittwaldAPIV2.Components.Schemas.AppAppUpdatePolicy; + +export type AppName = + | "Roundcube Webmail" + | "Static Files" + | "Drupal Core" + | "PHP-Worker" + | "PrestaShop" + | "Shopware 5" + | "Shopware 6" + | "Drupal CMS" + | "Nextcloud" + | "WordPress" + | "Joomla!" + | "Node.js" + | "Contao" + | "Matomo" + | "Python" + | "TYPO3" + | "PHP"; + +export enum AppId { + staticFiles = "d20baefd-81d2-42aa-bfba-9a3220ae839b", + nextcloud = "0b97d59f-ee13-4f18-a1f6-53e1beaf2e70", + phpWorker = "fcac178a-e606-4460-a5fd-b3ad0ae7a3cc", + roundcube = "f37a8798-2785-4186-8d74-a98146bff3c3", + shopware5 = "a23acf9c-9298-4082-9e7d-25356f9976dc", + shopware6 = "12d54d05-7e55-4cf3-90c4-093516e0eaf8", + wordPress = "da3aa3ae-4b6b-4398-a4a8-ee8def827876", + drupalCms = "0548e45c-28cf-4da4-8827-246a67ba0b98", + contao = "4916ce3e-cba4-4d2e-9798-a8764aa14cf3", + drupal = "3d8a261a-3d6f-4e09-b68c-bfe90aece514", + joomla = "8d404bff-6d75-4833-9eed-1b83b0552585", + matomo = "91fa05e7-34f7-42e8-a8d3-a9c42abd5f8c", + nodejs = "3e7f920b-a711-4d2f-9871-661e1b41a2f0", + python = "be57d166-dae9-4480-bae2-da3f3c6f0a2e", + typo3 = "352971cc-b96a-4a26-8651-b08d7c8a7357", + php = "34220303-cb87-4592-8a95-2eb20a97b2ac", +} diff --git a/packages/models/src/app/AppInstallation/AppInstallation.test.ts b/packages/models/src/app/AppInstallation/AppInstallation.test.ts new file mode 100644 index 00000000..2b4169cb --- /dev/null +++ b/packages/models/src/app/AppInstallation/AppInstallation.test.ts @@ -0,0 +1,232 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { buildAppInstallationData } from "../../testing/builders/buildAppInstallationData.js"; +import { ObjectNotFoundError } from "../../errors/ObjectNotFoundError.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { ReferenceModel } from "../../base/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { Project } from "../../project/index.js"; +import { App } from "../App/index.js"; +import { + AppInstallationListQuery, + AppInstallationDetailed, + AppInstallationListItem, + AppInstallationList, + AppInstallation, +} from "./AppInstallation.js"; + +afterEach(resetBehaviors); + +describe("AppInstallation", () => { + test("create delegates and returns a reference", async () => { + const create = vi.fn().mockResolvedValue({ id: "ai-1" }); + installBehaviors({ appInstallation: { create } }); + const data = { + updatePolicy: "none" as const, + appVersionId: "v-1", + description: "site", + userInputs: [], + }; + + const result = await AppInstallation.create(Project.ofId("p-1"), data); + + expect(create).toHaveBeenCalledWith("p-1", data); + expect(result).toBeInstanceOf(AppInstallation); + expect(result.id).toBe("ai-1"); + }); + + test("find maps found and missing installations", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildAppInstallationData({ id: "ai-1" })) + .mockResolvedValueOnce(undefined); + installBehaviors({ appInstallation: { find } }); + + await expect(AppInstallation.find("ai-1")).resolves.toBeInstanceOf( + AppInstallationDetailed, + ); + await expect(AppInstallation.find("missing")).resolves.toBeUndefined(); + }); + + test("findCommon and getCommon materialize a reference via the behavior", async () => { + const find = vi + .fn() + .mockResolvedValue(buildAppInstallationData({ id: "ai-1" })); + installBehaviors({ appInstallation: { find } }); + const reference = AppInstallation.ofId("ai-1"); + + await expect(reference.findCommon()).resolves.toBeInstanceOf( + AppInstallationDetailed, + ); + await expect(reference.getCommon()).resolves.toBeInstanceOf( + AppInstallationDetailed, + ); + expect(find).toHaveBeenCalledWith("ai-1"); + }); + + test("findCommon resolves undefined and getCommon throws when missing", async () => { + installBehaviors({ + appInstallation: { find: vi.fn().mockResolvedValue(undefined) }, + }); + const reference = AppInstallation.ofId("missing"); + + await expect(reference.findCommon()).resolves.toBeUndefined(); + await expect(reference.getCommon()).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("findCommon and getCommon are idempotent for materialized installations", async () => { + const find = vi.fn(); + installBehaviors({ appInstallation: { find } }); + const detailed = new AppInstallationDetailed( + buildAppInstallationData({ id: "ai-1" }), + ); + const listItem = new AppInstallationListItem( + buildAppInstallationData({ id: "ai-2" }), + ); + + await expect(detailed.findCommon()).resolves.toBe(detailed); + await expect(detailed.getCommon()).resolves.toBe(detailed); + await expect(listItem.findCommon()).resolves.toBe(listItem); + await expect(listItem.getCommon()).resolves.toBe(listItem); + expect(find).not.toHaveBeenCalled(); + }); + + test("pins the aggregate metadata identity and reference", () => { + expect(AppInstallation.aggregateMetaData).toBeInstanceOf(AggregateMetaData); + expect(AppInstallation.aggregateMetaData).toMatchObject({ + aggregate: "appinstallation", + domain: "app", + }); + expect(AppInstallation.findAggregate("ai-1")).toEqual({ + aggregate: "appinstallation", + domain: "app", + id: "ai-1", + }); + expect(AppInstallation.findAggregate()).toBeUndefined(); + }); + + test("derives empty and absent installation fields when source data is missing", () => { + const installation = new AppInstallationDetailed( + buildAppInstallationData(), + ); + + expect(installation.installedSystemSoftware).toEqual([]); + expect(installation.linkedDatabases).toEqual([]); + expect(installation.userInputs).toEqual([]); + expect(installation.host).toBeUndefined(); + expect(installation.previousAppVersion).toBeUndefined(); + expect(installation.primaryDatabase).toBeUndefined(); + expect(installation.httpPort).toBeUndefined(); + expect(installation.entryPointUserInput).toBeUndefined(); + expect(installation.lastVersionChangedAt).toBeUndefined(); + expect(installation.lastVersionChangedBy).toBeUndefined(); + }); + + test("mutations delegate with correct arguments", async () => { + const update = vi.fn().mockResolvedValue(undefined); + const deleteBehavior = vi.fn().mockResolvedValue(undefined); + const copy = vi.fn().mockResolvedValue(undefined); + const unlinkDatabase = vi.fn().mockResolvedValue(undefined); + installBehaviors({ + appInstallation: { + delete: deleteBehavior, + unlinkDatabase, + update, + copy, + }, + }); + const installation = AppInstallation.ofId("ai-1"); + + await installation.update({ description: "x" }); + await installation.delete(); + await installation.copy({ targetProjectId: "p-2", description: "copy" }); + await installation.unlinkDatabase("db-1"); + + expect(update).toHaveBeenCalledWith("ai-1", { description: "x" }); + expect(deleteBehavior).toHaveBeenCalledWith("ai-1"); + expect(copy).toHaveBeenCalledWith("ai-1", { + targetProjectId: "p-2", + description: "copy", + }); + expect(unlinkDatabase).toHaveBeenCalledWith("ai-1", "db-1"); + }); + + test("exposes derived installation details", () => { + const installing = new AppInstallationDetailed( + buildAppInstallationData({ + phase: "installing", + appName: "Node.js", + appId: "app-x", + id: "ai-1", + }), + ); + const ready = new AppInstallationDetailed( + buildAppInstallationData({ phase: "ready" }), + ); + + expect(installing).toMatchObject({ + execCommand: "app exec ai-1", + primaryDatabase: undefined, + description: "my site", + installationPath: "/", + phase: "installing", + shortId: "abc123", + isNodeApp: true, + isBusy: true, + }); + expect(installing.app).toBeInstanceOf(App); + expect(installing.app.id).toBe("app-x"); + expect(ready.isBusy).toBe(false); + }); + + test("queries by project and preserves pagination", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildAppInstallationData({ id: "ai-1" })], + totalCount: 1, + }); + installBehaviors({ appInstallation: { list } }); + + const result = await AppInstallation.query({ + project: Project.ofId("p-1"), + }).execute(); + + expect(result).toBeInstanceOf(AppInstallationList); + expect(result.items[0]).toBeInstanceOf(AppInstallationListItem); + expect(result.totalCount).toBe(1); + expect(list).toHaveBeenCalledWith("p-1", {}); + }); + + test("queries all installations without a project", async () => { + const listForUser = vi.fn().mockResolvedValue({ totalCount: 0, items: [] }); + installBehaviors({ appInstallation: { listForUser } }); + const query = AppInstallation.query(); + + await query.execute(); + + expect(listForUser).toHaveBeenCalledWith({}); + }); + + test("preserves ghostmaker composition chains", () => { + const detailed = new AppInstallationDetailed(buildAppInstallationData()); + + expect(detailed).toBeInstanceOf(AppInstallation); + expect(detailed).toBeInstanceOf(ReferenceModel); + expect(detailed.data).toBeDefined(); + expect(new AppInstallationList({}, [], 0)).toBeInstanceOf( + AppInstallationListQuery, + ); + }); +}); diff --git a/packages/models/src/app/AppInstallation/AppInstallation.ts b/packages/models/src/app/AppInstallation/AppInstallation.ts index 7e28b1c9..c81dc4e7 100644 --- a/packages/models/src/app/AppInstallation/AppInstallation.ts +++ b/packages/models/src/app/AppInstallation/AppInstallation.ts @@ -1,158 +1,521 @@ -import { config } from "../../config/config.js"; -import { classes } from "polytype"; -import { DataModel } from "../../base/DataModel.js"; -import assertObjectFound from "../../base/assertObjectFound.js"; -import { ReferenceModel } from "../../base/ReferenceModel.js"; -import { - AsyncResourceVariant, - provideReact, -} from "../../react/provideReact.js"; -import { - AppInstallationData, +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import invariant from "tiny-invariant"; +import { DateTime } from "luxon"; +import { omit } from "remeda"; + +import type { MySqlDetailed, RedisDetailed } from "../../database/index.js"; +import type { IngressListItem, IngressPath } from "../../ingress/index.js"; +import type { AppUpdatePolicyData } from "../index.js"; +import type { + AppInstallationStagingCreateRequestData, + AppInstallationStagingDetachRequestData, + AppInstallationListQueryModelData, + AppInstallationCreateRequestData, + AppInstallationUpdateRequestData, + AppInstallationCopyRequestData, + InstalledSystemSoftwareQuery, AppInstallationListItemData, - AppInstallationListQueryData, + AppInstallationData, + AppSavedUserInput, + AppPhase, } from "./types.js"; -import { ListQueryModel } from "../../base/ListQueryModel.js"; -import { ListDataModel } from "../../base/ListDataModel.js"; -import { Project } from "../../project/index.js"; +import { + SystemSoftwareDetailed, + SystemSoftwareId, +} from "../SystemSoftware/index.js"; +import { InstalledSystemSoftware } from "../InstalledSystemSoftware/index.js"; +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { AppLinkedDatabase, AppVersion, AppId, App } from "../index.js"; +import { Project } from "../../project/internal.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { User } from "../../user/User/User.js"; +import { Cronjob } from "../../cronjob/index.js"; +// Not the ingress barrel: IngressTarget imports this module, so the barrel would +// be evaluated mid-cycle, and vitest's `export *` then drops the names of the +// modules still loading. +import { Ingress } from "../../ingress/Ingress/index.js"; +import { MySql } from "../../database/index.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "AppInstallation", +}) export class AppInstallation extends ReferenceModel { - public static find = provideReact( - async (id: string): Promise => { - const data = await config.behaviors.appInstallation.find(id); - if (data !== undefined) { - return new AppInstallationDetailed(data); - } - }, + public static aggregateMetaData = new AggregateMetaData( + "app", + "appinstallation", ); - public static get = provideReact( - async (id: string): Promise => { - const appInstallation = await this.find(id); - assertObjectFound(appInstallation, this, id); - return appInstallation; - }, - ); + public static async create( + project: Project, + data: AppInstallationCreateRequestData, + ) { + const response = await config.behaviors.appInstallation.create( + project.id, + data, + ); + + return new AppInstallation(response.id); + } + + public static async find(id: string) { + const data = await config.behaviors.appInstallation.find(id); + if (data) { + return new AppInstallationDetailed(data); + } + } - public static ofId(id: string): AppInstallation { + public static findAggregate(appInstallationId?: string) { + return appInstallationId + ? { id: appInstallationId, ...AppInstallation.aggregateMetaData } + : undefined; + } + + public static async get(id: string) { + const appInstallation = await this.find(id); + assertObjectFound(appInstallation, AppInstallation, id); + return appInstallation; + } + + public static ofId(id: string) { return new AppInstallation(id); } - public query(project: Project, query: AppInstallationListQueryData = {}) { - return new AppInstallationListQuery(project, query); + public static query(query: AppInstallationListQueryModelData = {}) { + return new AppInstallationListQuery(query); } - /** @deprecated: use query() or project.appInstallations */ - public static list = provideReact( - async ( - projectId: string, - query: AppInstallationListQueryData = {}, - ): Promise>> => { - return new AppInstallationListQuery(Project.ofId(projectId), query) - .execute() - .then((r) => r.items); - }, - ); + public async addSystemSoftware( + systemSoftwareId: string, + systemSoftwareVersionId: string, + updatePolicy?: AppUpdatePolicyData, + ) { + await this.update({ + systemSoftware: { + [systemSoftwareId]: { + systemSoftwareVersion: systemSoftwareVersionId, + updatePolicy: updatePolicy ?? "patchLevel", + }, + }, + }); + } - public getDetailed = provideReact( - () => AppInstallation.get(this.id), - [this.id], - ) as AsyncResourceVariant<() => Promise>; + public async copy(data: AppInstallationCopyRequestData) { + await config.behaviors.appInstallation.copy(this.id, data); + } - public findDetailed = provideReact( - () => AppInstallation.find(this.id), - [this.id], - ) as AsyncResourceVariant<() => Promise>; -} + public async createStaging(data: AppInstallationStagingCreateRequestData) { + return config.behaviors.appInstallation.createStaging(this.id, data); + } -// Common class for future extension -class AppInstallationCommon extends classes( - DataModel, - AppInstallation, -) { - public constructor(data: AppInstallationListItemData | AppInstallationData) { - super([data], [data.id]); + public async delete() { + await config.behaviors.appInstallation.delete(this.id); } -} -export class AppInstallationDetailed extends classes( - AppInstallationCommon, - DataModel, -) { - public constructor(data: AppInstallationData) { - super([data], [data]); + public async deleteSystemSoftware(systemSoftwareId: string) { + await this.update({ + systemSoftware: { + [systemSoftwareId]: {}, + }, + }); } -} -export class AppInstallationListItem extends classes( - AppInstallationCommon, - DataModel, -) { - public constructor(data: AppInstallationListItemData) { - super([data], [data]); + public async detachStaging(data: AppInstallationStagingDetachRequestData) { + return config.behaviors.appInstallation.detachStaging(this.id, data); } -} -export class AppInstallationListQuery extends ListQueryModel { - public readonly project: Project; + public async findCommon(): Promise { + return this instanceof AppInstallationCommon ? this : this.findDetailed(); + } - public constructor( - project: Project, - query: AppInstallationListQueryData = {}, + public async findDetailed(): Promise { + return AppInstallation.find(this.id); + } + + public async getCommon(): Promise { + return this instanceof AppInstallationCommon ? this : this.getDetailed(); + } + + public getDetailed(): Promise { + return AppInstallation.get(this.id); + } + + public async getInstalledSystemSoftware( + query?: InstalledSystemSoftwareQuery, ) { - super(query, { - dependencies: [project.id], - }); - this.project = project; + const data = + await config.behaviors.appInstallation.getInstalledSystemSoftware( + this.id, + query, + ); + return data.map((d) => new SystemSoftwareDetailed(d)); } - public refine(query: AppInstallationListQueryData) { - return new AppInstallationListQuery(this.project, { - ...this.query, - ...query, + public async goLive() { + return config.behaviors.appInstallation.goLive(this.id); + } + + public async linkDatabase(database: MySqlDetailed | RedisDetailed) { + const mainMySqlUser = + database instanceof MySql ? database.mainUser : undefined; + + await config.behaviors.appInstallation.update(this.id, { + databases: { + [database.id]: { + databaseUserIds: mainMySqlUser + ? { admin: mainMySqlUser.id } + : undefined, + purpose: "custom", + }, + }, }); } - public execute = provideReact(async () => { - const { items, totalCount } = await config.behaviors.appInstallation.list( - this.project.id, - { - limit: config.defaultPaginationLimit, - ...this.query, + public async unlinkDatabase(databaseId: string) { + await config.behaviors.appInstallation.unlinkDatabase(this.id, databaseId); + } + + public async update(data: AppInstallationUpdateRequestData) { + await config.behaviors.appInstallation.update(this.id, data); + } + + public async updateSystemSoftwareVersion( + systemSoftwareId: string, + systemSoftwareVersionId: string, + ) { + await this.update({ + systemSoftware: { + [systemSoftwareId]: { + systemSoftwareVersion: systemSoftwareVersionId, + }, }, + }); + } +} + +export class AppInstallationCommon extends WithData< + AppInstallationListItemData | AppInstallationData +>()(AppInstallation) { + public readonly app: App; + public readonly appName: string; + public readonly appVersion: AppVersion; + public readonly appVersionString: string; + public readonly customDocumentRoot?: string; + public override readonly data: + AppInstallationListItemData | AppInstallationData; + public readonly deletionRequested?: boolean; + public readonly description: string; + public readonly entryPointUserInput?: AppSavedUserInput; + public readonly execCommand: string; + public readonly host?: string; + public readonly httpPort?: number; + public readonly installationPath: string; + public readonly installedSystemSoftware: InstalledSystemSoftware[]; + public readonly isBusy: boolean; + public readonly isLocked: boolean; + public readonly isNodeApp: boolean; + public readonly isStagingInstallation: boolean; + public readonly lastError?: string; + public readonly lastVersionChangedAt?: DateTime; + public readonly lastVersionChangedBy?: User; + public readonly linkedDatabases: AppLinkedDatabase[]; + public readonly mainSystemSoftware?: InstalledSystemSoftware; + public readonly phase: AppPhase; + public readonly php?: InstalledSystemSoftware; + public readonly previousAppVersion?: AppVersion; + public readonly primaryDatabase?: AppLinkedDatabase; + public readonly project: Project; + public readonly projectDescription: string; + public readonly shortId: string; + public readonly sourceInstallation: AppInstallation | undefined; + public readonly updateAvailable: boolean; + public readonly userInputs: AppSavedUserInput[]; + + public constructor(data: AppInstallationListItemData | AppInstallationData) { + super(data.id); + this.data = data; + this.description = data.description; + this.execCommand = `app exec ${data.id}`; + this.app = App.ofId(data.appId); + this.appVersionString = data.appExternalVersion; + this.appName = data.appName; + this.isNodeApp = this.appName === "Node.js"; + this.project = Project.ofId(data.projectId!); + this.projectDescription = data.projectDescription; + this.phase = data.phase; + this.isBusy = data.phase === "upgrading" || data.phase === "installing"; + this.isLocked = Object.keys(data.lockedBy ?? {}).length > 0; + + this.isStagingInstallation = data.staging ?? false; + this.sourceInstallation = data.sourceAppInstallationId + ? AppInstallation.ofId(data.sourceAppInstallationId) + : undefined; + + this.host = data.userInputs?.find((u) => u.name === "host")?.value; + + this.installedSystemSoftware = data.systemSoftware + ? data.systemSoftware + .sort((a, b) => a.systemSoftwareId.localeCompare(b.systemSoftwareId)) + .map((s) => new InstalledSystemSoftware(s)) + : []; + this.installationPath = data.installationPath; + this.userInputs = data.userInputs ?? []; + this.linkedDatabases = data.linkedDatabases + ? data.linkedDatabases.map((d) => new AppLinkedDatabase(d)) + : []; + this.primaryDatabase = this.linkedDatabases.find((d) => d.isPrimary); + this.shortId = data.shortId; + this.customDocumentRoot = data.customDocumentRoot; + + this.entryPointUserInput = this.userInputs.find( + (u) => u.name === "entrypoint", + ); + this.deletionRequested = data.deletionRequested; + + const { lastChangedAt, lastChangeBy, previous, desired, current } = + data.appVersion; + this.appVersion = AppVersion.ofId(current ?? desired, this.app); + this.previousAppVersion = previous + ? AppVersion.ofId(previous, App.ofId(data.appId)) + : undefined; + this.lastVersionChangedAt = lastChangedAt + ? DateTime.fromISO(lastChangedAt) + : undefined; + this.lastVersionChangedBy = lastChangeBy + ? User.ofId(lastChangeBy) + : undefined; + + if (this.app.id === AppId.nodejs) { + this.mainSystemSoftware = this.installedSystemSoftware.find( + (i) => i.systemSoftware.id === SystemSoftwareId.node, + ); + } else if (this.app.id === AppId.python) { + this.mainSystemSoftware = this.installedSystemSoftware.find( + (i) => i.systemSoftware.id === SystemSoftwareId.python, + ); + } else if (this.app.id !== AppId.staticFiles) { + this.mainSystemSoftware = + this.installedSystemSoftware.find( + (i) => i.systemSoftware.id === SystemSoftwareId.php, + ) ?? + this.installedSystemSoftware.find( + (i) => i.systemSoftware.id === SystemSoftwareId.node, + ) ?? + this.installedSystemSoftware.find( + (i) => i.systemSoftware.id === SystemSoftwareId.python, + ); + } + + this.php = this.installedSystemSoftware.find( + (i) => i.systemSoftware.id === SystemSoftwareId.php, ); + this.lastError = data.lastError; + this.updateAvailable = data.updateAvailable; + this.httpPort = data.ports?.find((p) => p.name === "http")?.port; + } + + public async findMainSystemSoftware() { + if (this.app.id === AppId.staticFiles) { + return; + } else if (this.app.id === AppId.nodejs) { + return this.installedSystemSoftware.find( + (i) => i.systemSoftware.id === SystemSoftwareId.node, + ); + } else if (this.app.id === AppId.python) { + return this.installedSystemSoftware.find( + (i) => i.systemSoftware.id === SystemSoftwareId.python, + ); + } else { + return ( + this.installedSystemSoftware.find( + (i) => i.systemSoftware.id === SystemSoftwareId.php, + ) ?? + this.installedSystemSoftware.find( + (i) => i.systemSoftware.id === SystemSoftwareId.node, + ) ?? + this.installedSystemSoftware.find( + (i) => i.systemSoftware.id === SystemSoftwareId.python, + ) + ); + } + } + + public async findStagingInstallation() { + const appInstallations = await AppInstallation.query({ + project: this.project, + }).execute(); + + return appInstallations.items.find( + (appInstallation) => appInstallation.sourceInstallation?.id === this.id, + ); + } + + public async listCompatibleDatabases() { + const mySqlList = await MySql.query({ project: this.project }).execute(); + + const appVersionDetailed = await this.appVersion.getDetailed(); + + const allowedDatabaseVersions: string[] = + appVersionDetailed.data.databases?.map((d) => { + switch (d.version) { + case "91bbc8ea-9308-4b7f-88dc-1a2873d02c8c": + return "5.6"; + case "1be01968-784d-434c-aa05-2e64a51ced28": + return "5.7"; + case "37931c38-e05e-470b-9e22-a035ef9f383b": + return "8.0"; + case "3c7f71f7-27bb-41fc-99a5-c7ec6d24e1f7": + return "8.4"; + default: + return ""; + } + }) ?? []; + + return mySqlList.items.filter((d) => + allowedDatabaseVersions.includes(d.version), + ); + } + + // todo: Query parameter zum filtern nach Apps + public async listCronjobs() { + const cronjobList = await Cronjob.query({ + project: this.project, + }).execute(); + + return cronjobList.items.filter( + (i) => i.linkedAppInstallation?.id === this.id && i.targetType === "app", + ); + } + + public async listIngresses() { + const ingressList = await Ingress.query().execute(); + + return ingressList.items.filter( + (i) => + i.defaultPath.target?.type === "appInstallation" && + i.defaultPath.target.appInstallation.id === this.id, + ); + } + + public async listIngressesAndPaths() { + const ingressList = await Ingress.query().execute(); + + const ingressAndPathList: (IngressListItem | IngressPath)[] = []; + + ingressList.items.forEach((i) => { + if ( + i.defaultPath.target?.type === "appInstallation" && + i.defaultPath.target.appInstallation.id === this.id + ) { + ingressAndPathList.push(i); + } + + i.paths.forEach((p) => { + if ( + p.target?.type === "appInstallation" && + p.target.appInstallation.id === this.id && + p.path !== "/" + ) { + ingressAndPathList.push(p); + } + }); + }); + + return ingressAndPathList; + } + + public async replacePrimaryDatabase(mySql: MySqlDetailed) { + const oldDatabaseId = + this.linkedDatabases.find((d) => d.isPrimary)?.id ?? ""; + + invariant(mySql.mainUser, "my sql main user not found"); + + await config.behaviors.appInstallation.update(this.id, { + databases: { + [mySql.id]: { + databaseUserIds: { admin: mySql.mainUser.id }, + replacesDatabaseId: oldDatabaseId, + }, + }, + }); + } +} + +export class AppInstallationDetailed extends AppInstallationCommon { + public override readonly data: AppInstallationData; + + public constructor(data: AppInstallationData) { + super(data); + this.data = data; + } +} + +export class AppInstallationListItem extends AppInstallationCommon { + public override readonly data: AppInstallationListItemData; + + public constructor(data: AppInstallationListItemData) { + super(data); + this.data = data; + } +} + +export class AppInstallationListQuery extends ListQueryModel { + public async execute() { + const projectId = extractId(this.query.project); + + const { totalCount, items } = projectId + ? await config.behaviors.appInstallation.list( + projectId, + omit(this.query, ["project"]), + ) + : await config.behaviors.appInstallation.listForUser(this.query); return new AppInstallationList( - this.project, this.query, - items.map((d) => new AppInstallationListItem(d)), + items + .map((d) => new AppInstallationListItem(d)) + + .sort((a, b) => + this.query.sortOrder ? 0 : a.description.localeCompare(b.description), + ), totalCount, ); - }, [this.queryId]); + } - public getTotalCount = provideReact(async () => { + public async getTotalCount() { const { totalCount } = await this.refine({ limit: 1 }).execute(); return totalCount; - }, [this.queryId]); + } - public findOneAndOnly = provideReact(async () => { - const { items, totalCount } = await this.refine({ limit: 2 }).execute(); - if (totalCount === 1) { - return items[0]; - } - }, [this.queryId]); + public refine(query: AppInstallationListQueryModelData) { + return new AppInstallationListQuery({ + ...this.query, + ...query, + }); + } } -export class AppInstallationList extends classes( +export class AppInstallationList extends WithListData()( AppInstallationListQuery, - ListDataModel, ) { + public override readonly items: readonly AppInstallationListItem[]; + public override readonly totalCount: number; + public constructor( - project: Project, - query: AppInstallationListQueryData, + query: AppInstallationListQueryModelData, appInstallations: AppInstallationListItem[], totalCount: number, ) { - super([project, query], [appInstallations, totalCount]); + super(query); + this.items = Object.freeze(appInstallations); + this.totalCount = totalCount; } } diff --git a/packages/models/src/app/AppInstallation/behaviors/api.ts b/packages/models/src/app/AppInstallation/behaviors/api.ts index 62476402..0ce61d9c 100644 --- a/packages/models/src/app/AppInstallation/behaviors/api.ts +++ b/packages/models/src/app/AppInstallation/behaviors/api.ts @@ -1,23 +1,21 @@ -import { - assertStatus, - extractTotalCountHeader, - MittwaldAPIV2Client, -} from "@mittwald/api-client"; -import { assertOneOfStatus } from "@mittwald/api-client"; -import { AppInstallationBehaviors } from "./types.js"; +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { AppInstallationBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { anyStatus403 } from "../../../base/api/typeFixes.js"; +import { resolveTotalCount } from "../../../base/index.js"; export const apiAppInstallationBehaviors = ( client: MittwaldAPIV2Client, ): AppInstallationBehaviors => ({ - find: async (id) => { - const response = await client.app.getAppinstallation({ - appInstallationId: id, - }); - + find: async (appInstallationId) => { + const response = await client.app.getAppinstallation({ appInstallationId }); if (response.status === 200) { return response.data; } - assertOneOfStatus(response, [404]); + // API-DRIFT: getAppinstallation omits 403 in its generated response type, so anyStatus403 (403 as any) is passed (resolve: use the literal 403 once the client type declares it) + validateResponse(response, [404, anyStatus403]); }, list: async (projectId, query) => { @@ -25,10 +23,102 @@ export const apiAppInstallationBehaviors = ( queryParameters: query, projectId, }); - assertStatus(response, 200); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + listForUser: async (query) => { + const response = await client.app.listAppinstallationsForUser({ + queryParameters: query, + }); + validateResponse(response, 200); return { + totalCount: resolveTotalCount(response), items: response.data, - totalCount: extractTotalCountHeader(response), }; }, + + getInstalledSystemSoftware: async (appInstallationId, query) => { + const response = await client.app.getAppInstallationSystemSoftware({ + queryParameters: query, + appInstallationId, + }); + + validateResponse(response, 200); + + return response.data; + }, + + createStaging: async (appInstallationId, data) => { + const response = await client.app.requestAppinstallationStaging({ + appInstallationId, + data, + }); + validateResponse(response, 201); + return response.data; + }, + + detachStaging: async (appInstallationId, data) => { + const response = await client.app.detachAppinstallationStaging({ + appInstallationId, + data, + }); + validateResponse(response, 204); + }, + + unlinkDatabase: async (appInstallationId, databaseId) => { + const response = await client.app.unlinkDatabase({ + appInstallationId, + databaseId, + }); + + validateResponse(response, 204); + }, + + create: async (projectId, data) => { + const response = await client.app.requestAppinstallation({ + projectId, + data, + }); + + validateResponse(response, 201); + + return response.data; + }, + + copy: async (appInstallationId, data) => { + const response = await client.app.requestAppinstallationCopy({ + appInstallationId, + data, + }); + + validateResponse(response, 201); + }, + + update: async (appInstallationId, data) => { + const response = await client.app.patchAppinstallation({ + appInstallationId, + data, + }); + + validateResponse(response, 204); + }, + + goLive: async (appInstallationId) => { + const response = await client.app.promoteAppinstallationStaging({ + appInstallationId, + }); + validateResponse(response, 204); + }, + + delete: async (appInstallationId) => { + const response = await client.app.uninstallAppinstallation({ + appInstallationId, + }); + + validateResponse(response, 204); + }, }); diff --git a/packages/models/src/app/AppInstallation/behaviors/types.ts b/packages/models/src/app/AppInstallation/behaviors/types.ts index 7402f42e..53088f2d 100644 --- a/packages/models/src/app/AppInstallation/behaviors/types.ts +++ b/packages/models/src/app/AppInstallation/behaviors/types.ts @@ -1,14 +1,65 @@ -import { - AppInstallationData, - AppInstallationListItemData, +import type { SystemSoftwareData } from "../../SystemSoftware/index.js"; +import type { QueryResponseData } from "../../../base/index.js"; +import type { + AppInstallationStagingCreateRequestData, + AppInstallationStagingDetachRequestData, + AppInstallationCreateRequestData, + AppInstallationUpdateRequestData, + AppInstallationCopyRequestData, AppInstallationListQueryData, + InstalledSystemSoftwareQuery, + AppInstallationListItemData, + AppInstallationData, } from "../types.js"; -import { QueryResponseData } from "../../../base/index.js"; export interface AppInstallationBehaviors { - find: (id: string) => Promise; + getInstalledSystemSoftware: ( + appInstallationId: string, + query?: InstalledSystemSoftwareQuery, + ) => Promise; + list: ( projectId: string, query?: AppInstallationListQueryData, ) => Promise>; + + createStaging: ( + appInstallationId: string, + data: AppInstallationStagingCreateRequestData, + ) => Promise<{ id: string }>; + + listForUser: ( + query?: AppInstallationListQueryData, + ) => Promise>; + + detachStaging: ( + appInstallationId: string, + data: AppInstallationStagingDetachRequestData, + ) => Promise; + + create: ( + projectId: string, + data: AppInstallationCreateRequestData, + ) => Promise<{ id: string }>; + + update: ( + appInstallationId: string, + data: AppInstallationUpdateRequestData, + ) => Promise; + + copy: ( + appInstallationId: string, + data: AppInstallationCopyRequestData, + ) => Promise; + + unlinkDatabase: ( + appInstallationId: string, + databaseId: string, + ) => Promise; + + find: (appInstallationId: string) => Promise; + + goLive: (appInstallationId: string) => Promise; + + delete: (appInstallationId: string) => Promise; } diff --git a/packages/models/src/app/AppInstallation/types.ts b/packages/models/src/app/AppInstallation/types.ts index ea60f35e..fa374f9f 100644 --- a/packages/models/src/app/AppInstallation/types.ts +++ b/packages/models/src/app/AppInstallation/types.ts @@ -1,10 +1,45 @@ -import { MittwaldAPIV2 } from "@mittwald/api-client"; +import type { MittwaldAPIV2 } from "@mittwald/api-client"; -export type AppInstallationListQueryData = - MittwaldAPIV2.Paths.V2ProjectsProjectIdAppInstallations.Get.Parameters.Query; +import type { Project } from "../../project/index.js"; export type AppInstallationData = MittwaldAPIV2.Operations.AppGetAppinstallation.ResponseData; export type AppInstallationListItemData = MittwaldAPIV2.Operations.AppListAppinstallations.ResponseData[number]; + +export type AppInstallationListQueryData = + MittwaldAPIV2.Paths.V2ProjectsProjectIdAppInstallations.Get.Parameters.Query; + +export type AppInstallationListQueryModelData = { + project?: Project | string; +} & AppInstallationListQueryData; + +export type AppInstallationCreateRequestData = + MittwaldAPIV2.Paths.V2ProjectsProjectIdAppInstallations.Post.Parameters.RequestBody; + +export type AppInstallationUpdateRequestData = + MittwaldAPIV2.Paths.V2AppInstallationsAppInstallationId.Patch.Parameters.RequestBody; + +export type AppInstallationStatus = + MittwaldAPIV2.Operations.AppRetrieveStatus.ResponseData; + +export type AppInstallationCopyRequestData = + MittwaldAPIV2.Paths.V2AppInstallationsAppInstallationIdActionsCopy.Post.Parameters.RequestBody; + +export type AppInstallationStagingCreateRequestData = + MittwaldAPIV2.Paths.V2AppInstallationsAppInstallationIdActionsStaging.Post.Parameters.RequestBody; + +export type AppInstallationStagingDetachRequestData = + MittwaldAPIV2.Paths.V2AppInstallationsAppInstallationIdActionsDetachStaging.Post.Parameters.RequestBody; + +export type AppPhase = MittwaldAPIV2.Components.Schemas.AppPhase; + +export type AppSavedUserInput = + MittwaldAPIV2.Components.Schemas.AppSavedUserInput; + +export type InstalledSystemSoftwareQuery = + MittwaldAPIV2.Paths.V2AppInstallationsAppInstallationIdSystemSoftware.Get.Parameters.Query; + +export type AppInstallationSortOrder = + MittwaldAPIV2.Components.Schemas.AppAppInstallationSortOrder; diff --git a/packages/models/src/app/AppLinkedDatabase/AppLinkedDatabase.test.ts b/packages/models/src/app/AppLinkedDatabase/AppLinkedDatabase.test.ts new file mode 100644 index 00000000..b5867460 --- /dev/null +++ b/packages/models/src/app/AppLinkedDatabase/AppLinkedDatabase.test.ts @@ -0,0 +1,30 @@ +import { afterEach, describe, expect, test } from "vitest"; + +import { buildAppLinkedDatabaseData } from "../../testing/builders/buildAppLinkedDatabaseData.js"; +import { resetBehaviors } from "../../testing/installBehaviors.js"; +import { AppLinkedDatabase } from "./AppLinkedDatabase.js"; +import { MySql, Redis } from "../../database/index.js"; +import { DataModel } from "../../base/index.js"; + +afterEach(resetBehaviors); + +describe("AppLinkedDatabase", () => { + test("maps a primary mysql database", () => { + const linked = new AppLinkedDatabase(buildAppLinkedDatabaseData()); + + expect(linked.database).toBeInstanceOf(MySql); + expect(linked.database.id).toBe("db-id"); + expect(linked.id).toBe("db-id"); + expect(linked.isPrimary).toBe(true); + expect(linked).toBeInstanceOf(DataModel); + }); + + test("maps a custom redis database", () => { + const linked = new AppLinkedDatabase( + buildAppLinkedDatabaseData({ purpose: "custom", kind: "redis" }), + ); + + expect(linked.database).toBeInstanceOf(Redis); + expect(linked.isPrimary).toBe(false); + }); +}); diff --git a/packages/models/src/app/AppLinkedDatabase/AppLinkedDatabase.ts b/packages/models/src/app/AppLinkedDatabase/AppLinkedDatabase.ts new file mode 100644 index 00000000..74b9da53 --- /dev/null +++ b/packages/models/src/app/AppLinkedDatabase/AppLinkedDatabase.ts @@ -0,0 +1,21 @@ +import type { AppLinkedDatabaseData } from "./types.js"; + +import { MySql } from "../../database/MySql/MySql.js"; +import { Redis } from "../../database/Redis/Redis.js"; +import { DataModel } from "../../base/index.js"; + +export class AppLinkedDatabase extends DataModel { + public readonly database: MySql | Redis; + public readonly id: string; + public readonly isPrimary: boolean; + + public constructor(data: AppLinkedDatabaseData) { + super(data); + this.database = + data.kind === "redis" + ? Redis.ofId(data.databaseId) + : MySql.ofId(data.databaseId); + this.isPrimary = data.purpose === "primary"; + this.id = data.databaseId; + } +} diff --git a/packages/models/src/app/AppLinkedDatabase/index.ts b/packages/models/src/app/AppLinkedDatabase/index.ts new file mode 100644 index 00000000..84eccc11 --- /dev/null +++ b/packages/models/src/app/AppLinkedDatabase/index.ts @@ -0,0 +1,2 @@ +export * from "./AppLinkedDatabase.js"; +export * from "./types.js"; diff --git a/packages/models/src/app/AppLinkedDatabase/types.ts b/packages/models/src/app/AppLinkedDatabase/types.ts new file mode 100644 index 00000000..ec6a5bb3 --- /dev/null +++ b/packages/models/src/app/AppLinkedDatabase/types.ts @@ -0,0 +1,6 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type AppLinkedDatabaseData = + MittwaldAPIV2.Components.Schemas.AppLinkedDatabase; + +export type AppLinkedDatabasePurpose = AppLinkedDatabaseData["purpose"]; diff --git a/packages/models/src/app/AppVersion/AppVersion.test.ts b/packages/models/src/app/AppVersion/AppVersion.test.ts new file mode 100644 index 00000000..c35f6dae --- /dev/null +++ b/packages/models/src/app/AppVersion/AppVersion.test.ts @@ -0,0 +1,165 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { buildAppVersionData } from "../../testing/builders/buildAppVersionData.js"; +import { ObjectNotFoundError } from "../../errors/ObjectNotFoundError.js"; +import { ReferenceModel } from "../../base/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { App } from "../index.js"; +import { + AppVersionListQuery, + AppVersionDetailed, + AppVersionListItem, + AppVersionList, + AppVersion, +} from "./AppVersion.js"; + +afterEach(resetBehaviors); + +describe("AppVersion", () => { + const app = App.ofId("app-1"); + + test("find delegates and maps missing versions", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildAppVersionData({ id: "v1" })) + .mockResolvedValueOnce(undefined); + installBehaviors({ appVersion: { find } }); + + await expect(AppVersion.find("v1", app)).resolves.toBeInstanceOf( + AppVersionDetailed, + ); + await expect(AppVersion.find("missing", app)).resolves.toBeUndefined(); + expect(find).toHaveBeenNthCalledWith(1, "v1", "app-1"); + }); + + test("get throws for a missing version", async () => { + installBehaviors({ + appVersion: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(AppVersion.get("missing", app)).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("findCommon and getCommon materialize a reference via the behavior", async () => { + const find = vi.fn().mockResolvedValue(buildAppVersionData({ id: "v1" })); + installBehaviors({ appVersion: { find } }); + const reference = AppVersion.ofId("v1", app); + + await expect(reference.findCommon()).resolves.toBeInstanceOf( + AppVersionDetailed, + ); + await expect(reference.getCommon()).resolves.toBeInstanceOf( + AppVersionDetailed, + ); + expect(find).toHaveBeenNthCalledWith(1, "v1", "app-1"); + }); + + test("findCommon resolves undefined and getCommon throws when missing", async () => { + installBehaviors({ + appVersion: { find: vi.fn().mockResolvedValue(undefined) }, + }); + const reference = AppVersion.ofId("missing", app); + + await expect(reference.findCommon()).resolves.toBeUndefined(); + await expect(reference.getCommon()).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("findCommon and getCommon are idempotent for materialized versions", async () => { + const find = vi.fn(); + installBehaviors({ appVersion: { find } }); + const detailed = new AppVersionDetailed(buildAppVersionData({ id: "v1" })); + const listItem = new AppVersionListItem(buildAppVersionData({ id: "v2" })); + + await expect(detailed.findCommon()).resolves.toBe(detailed); + await expect(detailed.getCommon()).resolves.toBe(detailed); + await expect(listItem.findCommon()).resolves.toBe(listItem); + await expect(listItem.getCommon()).resolves.toBe(listItem); + expect(find).not.toHaveBeenCalled(); + }); + + test("derives empty user-input collections when source data is absent", () => { + const version = new AppVersionDetailed(buildAppVersionData()); + + expect(version.installationUserInputs).toEqual([]); + expect(version.installationUserInputSteps).toEqual([]); + expect(version.systemSoftwareDependencies).toEqual([]); + expect(version.backendPathTemplate).toBeUndefined(); + expect(version.defaultCronjobs).toBeUndefined(); + }); + + test("query reverses behavior items", async () => { + const list = vi.fn().mockResolvedValue({ + items: [ + buildAppVersionData({ id: "v1" }), + buildAppVersionData({ id: "v2" }), + ], + }); + installBehaviors({ appVersion: { list } }); + const query = AppVersion.query({ app: app }); + + const result = await query.execute(); + + expect(result).toBeInstanceOf(AppVersionList); + expect(result).toBeInstanceOf(AppVersionListQuery); + expect(result.items.map(({ id }) => id)).toEqual(["v2", "v1"]); + expect( + result.items.every((item) => item instanceof AppVersionListItem), + ).toBe(true); + expect(list).toHaveBeenCalledWith("app-1", {}); + }); + + test("exposes version details and compares internal versions", () => { + const detailed = new AppVersionDetailed( + buildAppVersionData({ externalVersion: "6.4.0", recommended: true }), + ); + const older = new AppVersionListItem( + buildAppVersionData({ internalVersion: "1.0.0" }), + ); + const newer = new AppVersionListItem( + buildAppVersionData({ internalVersion: "2.0.0" }), + ); + + expect(detailed).toMatchObject({ recommended: true, version: "6.4.0" }); + expect(Array.isArray(detailed.systemSoftwareDependencies)).toBe(true); + expect(older.compare(newer)).toBe(-1); + expect(newer.compare(older)).toBe(1); + }); + + test("lists update candidates", async () => { + const listUpdateCandidates = vi + .fn() + .mockResolvedValue([buildAppVersionData({ id: "v2" })]); + installBehaviors({ appVersion: { listUpdateCandidates } }); + + const result = await AppVersion.ofId("v1", app).listUpdateCandidates(); + + expect(listUpdateCandidates).toHaveBeenCalledWith("app-1", "v1"); + expect(result[0]).toBeInstanceOf(AppVersionListItem); + }); + + test("preserves ghostmaker composition chains", () => { + for (const version of [ + new AppVersionListItem(buildAppVersionData()), + new AppVersionDetailed(buildAppVersionData()), + ]) { + expect(version).toBeInstanceOf(AppVersion); + expect(version).toBeInstanceOf(ReferenceModel); + expect(version.data).toBeDefined(); + } + }); +}); diff --git a/packages/models/src/app/AppVersion/AppVersion.ts b/packages/models/src/app/AppVersion/AppVersion.ts new file mode 100644 index 00000000..e3283301 --- /dev/null +++ b/packages/models/src/app/AppVersion/AppVersion.ts @@ -0,0 +1,191 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import semverCompare from "semver-compare"; +import { omit } from "remeda"; + +import type { SystemSoftware } from "../SystemSoftware/index.js"; +import type { + AppVersionListQueryModelData, + SystemSoftwareDependency, + AppVersionListItemData, + AppDefaultCronjobData, + AppVersionData, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { UserInput } from "../UserInput/index.js"; +import { config } from "../../config/index.js"; +import { App } from "../index.js"; +import { + sortByPositionMeta, + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "AppVersion", +}) +export class AppVersion extends ReferenceModel { + public readonly app: App; + + public constructor(id: string, app: App) { + super(id); + this.app = app; + } + + public static async find(id: string, app: App) { + const data = await config.behaviors.appVersion.find(id, app.id); + if (data) { + return new AppVersionDetailed(data); + } + } + + public static async get(id: string, app: App) { + const appVersion = await this.find(id, app); + assertObjectFound(appVersion, AppVersion, id); + return appVersion; + } + + public static ofId(id: string, app: App) { + return new AppVersion(id, app); + } + + public static query(query: AppVersionListQueryModelData) { + return new AppVersionListQuery(query); + } + + public async findCommon(): Promise { + return this instanceof AppVersionCommon ? this : this.findDetailed(); + } + + public async findDetailed(): Promise { + return AppVersion.find(this.id, this.app); + } + + public async getCommon(): Promise { + return this instanceof AppVersionCommon ? this : this.getDetailed(); + } + + public async getDetailed(): Promise { + return AppVersion.get(this.id, this.app); + } + + public async listUpdateCandidates(): Promise { + const data = await config.behaviors.appVersion.listUpdateCandidates( + this.app.id, + this.id, + ); + + return data + .map((d) => new AppVersionListItem(d)) + .sort((a, b) => b.compare(a)); + } + + public async updateAvailable() { + return (await this.listUpdateCandidates()).length > 0; + } +} + +export class AppVersionCommon extends WithData< + AppVersionListItemData | AppVersionData +>()(AppVersion) { + public readonly backendPathTemplate?: string; + public override readonly data: AppVersionListItemData | AppVersionData; + public readonly defaultCronjobs?: AppDefaultCronjobData[]; + public readonly docRootUserEditable: boolean; + public readonly installationUserInputs: UserInput[]; + public readonly installationUserInputSteps: string[]; + public readonly recommended?: boolean; + public readonly systemSoftwareDependencies: SystemSoftwareDependency[]; + public readonly version: string; + + public constructor(data: AppVersionListItemData | AppVersionData) { + super(data.id, App.ofId(data.appId)); + this.data = data; + this.version = data.externalVersion; + this.installationUserInputs = data.userInputs + ? sortByPositionMeta(data.userInputs).map((u) => new UserInput(u)) + : []; + this.installationUserInputSteps = Array.from( + new Set(this.installationUserInputs.map((u) => u.step)).values(), + ); + this.docRootUserEditable = data.docRootUserEditable; + this.backendPathTemplate = data.backendPathTemplate; + this.systemSoftwareDependencies = data.systemSoftwareDependencies ?? []; + this.defaultCronjobs = data.defaultCronjobs; + this.recommended = data.recommended; + } + + public compare(other: AppVersionListItem): -1 | 0 | 1 { + return semverCompare(this.data.internalVersion, other.data.internalVersion); + } + + public isSystemSoftwareRequired(systemSoftware: SystemSoftware) { + return this.data.systemSoftwareDependencies?.find( + (d) => d.systemSoftwareId === systemSoftware.id, + ); + } +} + +export class AppVersionDetailed extends AppVersionCommon { + public override readonly data: AppVersionData; + + public constructor(data: AppVersionData) { + super(data); + this.data = data; + } +} + +export class AppVersionListItem extends AppVersionCommon { + public override readonly data: AppVersionListItemData; + + public constructor(data: AppVersionListItemData) { + super(data); + this.data = data; + } +} + +export class AppVersionListQuery extends ListQueryModel { + public constructor(query: AppVersionListQueryModelData) { + super(query, { dependencies: [extractId(query.app)] }); + } + + public async execute() { + const { totalCount, items } = await config.behaviors.appVersion.list( + extractId(this.query.app), + omit(this.query, ["app"]), + ); + + return new AppVersionList( + this.query, + items.reverse().map((d) => new AppVersionListItem(d)), + totalCount, + ); + } + + public refine(query: Partial = {}) { + return new AppVersionListQuery({ + ...this.query, + ...query, + }); + } +} + +export class AppVersionList extends WithListData()( + AppVersionListQuery, +) { + public override readonly items: readonly AppVersionListItem[]; + public override readonly totalCount: number; + + public constructor( + query: AppVersionListQueryModelData, + appVersions: AppVersionListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(appVersions); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/app/AppVersion/behaviors/api.ts b/packages/models/src/app/AppVersion/behaviors/api.ts new file mode 100644 index 00000000..b4de52b8 --- /dev/null +++ b/packages/models/src/app/AppVersion/behaviors/api.ts @@ -0,0 +1,43 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { AppVersionBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount } from "../../../base/index.js"; + +export const apiAppVersionBehaviors = ( + client: MittwaldAPIV2Client, +): AppVersionBehaviors => ({ + listUpdateCandidates: async (appId, baseAppVersionId) => { + const response = await client.app.listUpdateCandidatesForAppversion({ + queryParameters: { onlyRecommended: true }, + baseAppVersionId, + appId, + }); + validateResponse(response, 200); + return response.data; + }, + + list: async (appId, query) => { + const response = await client.app.listAppversions({ + queryParameters: query, + appId, + }); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + find: async (appVersionId, appId) => { + const response = await client.app.getAppversion({ + appVersionId, + appId, + }); + if (response.status === 200) { + return response.data; + } + validateResponse(response, 404); + }, +}); diff --git a/packages/models/src/app/AppVersion/behaviors/index.ts b/packages/models/src/app/AppVersion/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/app/AppVersion/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/app/AppVersion/behaviors/types.ts b/packages/models/src/app/AppVersion/behaviors/types.ts new file mode 100644 index 00000000..f2d3b896 --- /dev/null +++ b/packages/models/src/app/AppVersion/behaviors/types.ts @@ -0,0 +1,22 @@ +import type { + AppVersionListQueryData, + AppVersionListItemData, + AppVersionData, +} from "../types.js"; + +export interface AppVersionBehaviors { + list: ( + appId: string, + query?: AppVersionListQueryData, + ) => Promise<{ items: AppVersionListItemData[]; totalCount: number }>; + + listUpdateCandidates: ( + appId: string, + baseAppVersionId: string, + ) => Promise; + + find: ( + appVersionId: string, + appId: string, + ) => Promise; +} diff --git a/packages/models/src/app/AppVersion/index.ts b/packages/models/src/app/AppVersion/index.ts new file mode 100644 index 00000000..899fd0cc --- /dev/null +++ b/packages/models/src/app/AppVersion/index.ts @@ -0,0 +1,2 @@ +export * from "./AppVersion.js"; +export * from "./types.js"; diff --git a/packages/models/src/app/AppVersion/types.ts b/packages/models/src/app/AppVersion/types.ts new file mode 100644 index 00000000..7bba9fe1 --- /dev/null +++ b/packages/models/src/app/AppVersion/types.ts @@ -0,0 +1,22 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import type { App } from "../../index.js"; + +export type AppVersionData = + MittwaldAPIV2.Operations.AppGetAppversion.ResponseData; + +export type AppVersionListItemData = + MittwaldAPIV2.Operations.AppListAppversions.ResponseData[number]; + +export type AppVersionListQueryData = + MittwaldAPIV2.Paths.V2AppsAppIdVersions.Get.Parameters.Query; + +export type AppVersionListQueryModelData = { + app: string | App; +} & AppVersionListQueryData; + +export type AppDefaultCronjobData = + MittwaldAPIV2.Components.Schemas.AppDefaultCronjob; + +export type SystemSoftwareDependency = + MittwaldAPIV2.Components.Schemas.AppSystemSoftwareDependency; diff --git a/packages/models/src/app/InstalledSystemSoftware/InstalledSystemSoftware.test.ts b/packages/models/src/app/InstalledSystemSoftware/InstalledSystemSoftware.test.ts new file mode 100644 index 00000000..ae12459a --- /dev/null +++ b/packages/models/src/app/InstalledSystemSoftware/InstalledSystemSoftware.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, test } from "vitest"; +import { DateTime } from "luxon"; + +import { buildInstalledSystemSoftwareData } from "../../testing/builders/buildInstalledSystemSoftwareData.js"; +import { InstalledSystemSoftware } from "./InstalledSystemSoftware.js"; +import { SystemSoftwareVersion } from "../SystemSoftwareVersion/index.js"; +import { SystemSoftware } from "../SystemSoftware/index.js"; +import { DataModel } from "../../base/index.js"; + +describe("InstalledSystemSoftware", () => { + test("maps stable installed software", () => { + const installed = new InstalledSystemSoftware( + buildInstalledSystemSoftwareData(), + ); + + expect(installed).toBeInstanceOf(DataModel); + expect(installed).toMatchObject({ + updateAvailable: false, + isInstalling: false, + isUpdating: false, + version: "8.2", + id: "sys-id", + }); + expect(installed.systemSoftware).toBeInstanceOf(SystemSoftware); + expect(installed.systemSoftware.id).toBe("sys-id"); + expect(installed.systemSoftwareVersion).toBeInstanceOf( + SystemSoftwareVersion, + ); + expect(installed.previousSystemSoftwareVersion).toBeUndefined(); + }); + + test("detects updating and installing states", () => { + const updating = new InstalledSystemSoftware( + buildInstalledSystemSoftwareData({ + systemSoftwareVersion: { current: "v1", desired: "v2" }, + }), + ); + const installing = new InstalledSystemSoftware( + buildInstalledSystemSoftwareData({ + systemSoftwareVersion: { desired: "v1" }, + }), + ); + + expect(updating.isUpdating).toBe(true); + expect(installing.isInstalling).toBe(true); + }); + + test("maps previous version and last-change timestamp", () => { + const installed = new InstalledSystemSoftware( + buildInstalledSystemSoftwareData({ + systemSoftwareVersion: { + lastChangedAt: "2024-01-01T00:00:00.000Z", + previous: "v1", + current: "v2", + desired: "v2", + }, + }), + ); + + expect(installed.previousSystemSoftwareVersion).toBeInstanceOf( + SystemSoftwareVersion, + ); + expect(installed.lastVersionChangedAt).toBeInstanceOf(DateTime); + expect(installed.lastVersionChangedAt?.isValid).toBe(true); + }); +}); diff --git a/packages/models/src/app/InstalledSystemSoftware/InstalledSystemSoftware.ts b/packages/models/src/app/InstalledSystemSoftware/InstalledSystemSoftware.ts new file mode 100644 index 00000000..41105c3d --- /dev/null +++ b/packages/models/src/app/InstalledSystemSoftware/InstalledSystemSoftware.ts @@ -0,0 +1,65 @@ +import { DateTime } from "luxon"; + +import type { SystemSoftwareName } from "../SystemSoftware/index.js"; +import type { InstalledSystemSoftwareData } from "./types.js"; + +import { + SystemSoftwareFullNames, + SystemSoftware, +} from "../SystemSoftware/index.js"; +import { SystemSoftwareVersion } from "../SystemSoftwareVersion/index.js"; +import { User } from "../../user/User/User.js"; +import { DataModel } from "../../base/index.js"; + +export class InstalledSystemSoftware extends DataModel { + public readonly fullName: string; + public readonly id: string; + public readonly isInstalling: boolean; + public readonly isUpdating: boolean; + public readonly lastVersionChangedAt?: DateTime; + public readonly lastVersionChangedBy?: User; + public readonly name: string; + public readonly previousSystemSoftwareVersion?: SystemSoftwareVersion; + public readonly systemSoftware: SystemSoftware; + public readonly systemSoftwareVersion: SystemSoftwareVersion; + public readonly updateAvailable: boolean; + public readonly version: string; + + public constructor(data: InstalledSystemSoftwareData) { + super(data); + + this.id = data.systemSoftwareId; + this.name = data.name as SystemSoftwareName; + this.fullName = + SystemSoftwareFullNames[ + this.name as keyof typeof SystemSoftwareFullNames + ]; + this.version = data.externalVersion; + this.updateAvailable = data.updateAvailable; + + this.isUpdating = + !!data.systemSoftwareVersion.current && + data.systemSoftwareVersion.current !== data.systemSoftwareVersion.desired; + this.isInstalling = !data.systemSoftwareVersion.current; + this.systemSoftware = SystemSoftware.ofId(data.systemSoftwareId); + const { lastChangedAt, lastChangeBy, previous, desired } = + data.systemSoftwareVersion; + + this.systemSoftwareVersion = SystemSoftwareVersion.ofId( + desired, + SystemSoftware.ofId(data.systemSoftwareId), + ); + this.previousSystemSoftwareVersion = previous + ? SystemSoftwareVersion.ofId( + previous, + SystemSoftware.ofId(data.systemSoftwareId), + ) + : undefined; + this.lastVersionChangedAt = lastChangedAt + ? DateTime.fromISO(lastChangedAt) + : undefined; + this.lastVersionChangedBy = lastChangeBy + ? User.ofId(lastChangeBy) + : undefined; + } +} diff --git a/packages/models/src/app/InstalledSystemSoftware/index.ts b/packages/models/src/app/InstalledSystemSoftware/index.ts new file mode 100644 index 00000000..0bfd5166 --- /dev/null +++ b/packages/models/src/app/InstalledSystemSoftware/index.ts @@ -0,0 +1,2 @@ +export * from "./InstalledSystemSoftware.js"; +export * from "./types.js"; diff --git a/packages/models/src/app/InstalledSystemSoftware/types.ts b/packages/models/src/app/InstalledSystemSoftware/types.ts new file mode 100644 index 00000000..e7f83b9b --- /dev/null +++ b/packages/models/src/app/InstalledSystemSoftware/types.ts @@ -0,0 +1,4 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type InstalledSystemSoftwareData = + MittwaldAPIV2.Components.Schemas.AppInstalledSystemSoftware; diff --git a/packages/models/src/app/License/License.test.ts b/packages/models/src/app/License/License.test.ts new file mode 100644 index 00000000..7f7b3ab7 --- /dev/null +++ b/packages/models/src/app/License/License.test.ts @@ -0,0 +1,183 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import type { ContractData } from "../../contract/Contract/types.js"; + +import { buildLicenseData } from "../../testing/builders/buildLicenseData.js"; +import { ObjectNotFoundError } from "../../errors/ObjectNotFoundError.js"; +import { ContractDetailed } from "../../contract/index.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { ReferenceModel } from "../../base/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { Project } from "../../project/index.js"; +import { + LicenseListQuery, + LicenseDetailed, + LicenseListItem, + LicenseList, + License, +} from "./License.js"; + +afterEach(resetBehaviors); + +describe("License", () => { + test("find delegates and maps missing licenses", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildLicenseData({ id: "l-1" })) + .mockResolvedValueOnce(undefined); + installBehaviors({ license: { find } }); + + await expect(License.find("l-1")).resolves.toBeInstanceOf(LicenseDetailed); + await expect(License.find("missing")).resolves.toBeUndefined(); + expect(find).toHaveBeenNthCalledWith(1, "l-1"); + }); + + test("get throws for a missing license", async () => { + installBehaviors({ + license: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(License.get("missing")).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("findCommon and getCommon materialize a reference via the behavior", async () => { + const find = vi.fn().mockResolvedValue(buildLicenseData({ id: "l-1" })); + installBehaviors({ license: { find } }); + const reference = License.ofId("l-1"); + + await expect(reference.findCommon()).resolves.toBeInstanceOf( + LicenseDetailed, + ); + await expect(reference.getCommon()).resolves.toBeInstanceOf( + LicenseDetailed, + ); + expect(find).toHaveBeenCalledWith("l-1"); + }); + + test("findCommon resolves undefined and getCommon throws when missing", async () => { + installBehaviors({ + license: { find: vi.fn().mockResolvedValue(undefined) }, + }); + const reference = License.ofId("missing"); + + await expect(reference.findCommon()).resolves.toBeUndefined(); + await expect(reference.getCommon()).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("findCommon and getCommon are idempotent for materialized licenses", async () => { + const find = vi.fn(); + installBehaviors({ license: { find } }); + const detailed = new LicenseDetailed(buildLicenseData({ id: "l-1" })); + const listItem = new LicenseListItem(buildLicenseData({ id: "l-2" })); + + await expect(detailed.findCommon()).resolves.toBe(detailed); + await expect(detailed.getCommon()).resolves.toBe(detailed); + await expect(listItem.findCommon()).resolves.toBe(listItem); + await expect(listItem.getCommon()).resolves.toBe(listItem); + expect(find).not.toHaveBeenCalled(); + }); + + test("pins the aggregate metadata identity for cache invalidation", () => { + expect(License.aggregateMetaData).toBeInstanceOf(AggregateMetaData); + expect(License.aggregateMetaData).toMatchObject({ + aggregate: "licence", + domain: "licence", + }); + }); + + test("rotateKey delegates", async () => { + const rotateKey = vi.fn().mockResolvedValue(undefined); + installBehaviors({ license: { rotateKey } }); + + await License.ofId("l-1").rotateKey(); + + expect(rotateKey).toHaveBeenCalledWith("l-1"); + }); + + test("getContract materializes a detailed contract", async () => { + const contractData: ContractData = { + baseItem: { + totalPrice: { currency: "EUR", value: 10 }, + description: "Project contract", + contractPeriod: 12, + isActivated: true, + isBaseItem: true, + itemId: "item-1", + articles: [], + }, + contractNumber: "contract-number-1", + contractId: "contract-1", + customerId: "customer-1", + additionalItems: [], + }; + const getContract = vi.fn().mockResolvedValue(contractData); + installBehaviors({ license: { getContract } }); + + const result = await License.ofId("l-1").getContract(); + + expect(getContract).toHaveBeenCalledWith("l-1"); + expect(result).toBeInstanceOf(ContractDetailed); + }); + + test("exposes derived license details", () => { + const detailed = new LicenseDetailed( + buildLicenseData({ kind: "typo3-elts", description: "d" }), + ); + const external = new LicenseDetailed( + buildLicenseData({ keyReference: { externalKey: "external" } }), + ); + + expect(detailed).toMatchObject({ + kind: "typo3-elts", + key: "secret-key", + description: "d", + meta: {}, + }); + expect(detailed.aggregateReference).toBeInstanceOf(Project); + expect(detailed.aggregateReference.id).toBe("project-id"); + expect(external.key).toBe(""); + }); + + test("query delegates and preserves pagination", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildLicenseData({ id: "l-1" })], + totalCount: 1, + }); + installBehaviors({ license: { list } }); + const query = License.query(Project.ofId("p-1")); + + const result = await query.execute(); + + expect(result).toBeInstanceOf(LicenseList); + expect(result).toBeInstanceOf(LicenseListQuery); + expect(result.items[0]).toBeInstanceOf(LicenseListItem); + expect(result.totalCount).toBe(1); + expect(list).toHaveBeenCalledWith("p-1", {}); + }); + + test("preserves ghostmaker composition chains", () => { + for (const license of [ + new LicenseListItem(buildLicenseData()), + new LicenseDetailed(buildLicenseData()), + ]) { + expect(license).toBeInstanceOf(License); + expect(license).toBeInstanceOf(ReferenceModel); + expect(license.data).toBeDefined(); + } + }); +}); diff --git a/packages/models/src/app/License/License.ts b/packages/models/src/app/License/License.ts new file mode 100644 index 00000000..b4967158 --- /dev/null +++ b/packages/models/src/app/License/License.ts @@ -0,0 +1,177 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; + +import type { Project } from "../../project/index.js"; +import type { + LicenseListQueryData, + LicenseListItemData, + LicenseData, + LicenseMeta, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { ContractDetailed } from "../../contract/index.js"; +import { config } from "../../config/index.js"; +import { + resolveAggregateReference, + type AggregateReference, + AggregateMetaData, +} from "../../common/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "License", +}) +export class License extends ReferenceModel { + public static aggregateMetaData = new AggregateMetaData("licence", "licence"); + + public constructor(id: string) { + super(id); + } + + public static async find(id: string) { + const data = await config.behaviors.license.find(id); + if (data) { + return new LicenseDetailed(data); + } + } + + public static async get(id: string) { + const license = await this.find(id); + assertObjectFound(license, License, id); + return license; + } + + public static ofId(id: string) { + return new License(id); + } + + public static query = (project: Project, query: LicenseListQueryData = {}) => + new LicenseListQuery(project, query); + + public async findCommon(): Promise { + return this instanceof LicenseCommon ? this : this.findDetailed(); + } + + public async findDetailed(): Promise { + return License.find(this.id); + } + + public async getCommon(): Promise { + return this instanceof LicenseCommon ? this : this.getDetailed(); + } + + public async getContract() { + const response = await config.behaviors.license.getContract(this.id); + return new ContractDetailed(response); + } + + public async getDetailed(): Promise { + return License.get(this.id); + } + + public async rotateKey() { + return await config.behaviors.license.rotateKey(this.id); + } +} + +export class LicenseCommon extends WithData< + LicenseListItemData | LicenseData +>()(License) { + public readonly aggregateReference: AggregateReference; + public override readonly data: LicenseListItemData | LicenseData; + public readonly description: string; + public readonly key: string; + public readonly kind: string; + public readonly meta: LicenseMeta; + + public constructor(data: LicenseListItemData | LicenseData) { + super(data.id); + this.data = data; + this.description = data.description; + this.meta = data.meta; + this.kind = data.kind; + this.aggregateReference = resolveAggregateReference(data.reference); + this.key = + data.keyReference && "key" in data.keyReference + ? data.keyReference.key + : ""; + } +} + +export class LicenseDetailed extends LicenseCommon { + public override readonly data: LicenseData; + + public constructor(data: LicenseData) { + super(data); + this.data = data; + } +} + +export class LicenseListItem extends LicenseCommon { + public override readonly data: LicenseListItemData; + + public constructor(data: LicenseListItemData) { + super(data); + this.data = data; + } +} + +export class LicenseListQuery extends ListQueryModel { + public readonly project: Project; + + public constructor(project: Project, query: LicenseListQueryData = {}) { + super(query, { + dependencies: [project.id], + }); + this.project = project; + } + + public async execute() { + const { totalCount, items } = await config.behaviors.license.list( + this.project.id, + this.query, + ); + + return new LicenseList( + this.project, + this.query, + items.map((d) => new LicenseListItem(d)), + totalCount, + ); + } + + public async getTotalCount() { + const { totalCount } = await this.refine({ limit: 1 }).execute(); + return totalCount; + } + + public refine(query: LicenseListQueryData) { + return new LicenseListQuery(this.project, { + ...this.query, + ...query, + }); + } +} + +export class LicenseList extends WithListData()( + LicenseListQuery, +) { + public override readonly items: readonly LicenseListItem[]; + public override readonly totalCount: number; + + public constructor( + project: Project, + query: LicenseListQueryData, + licenses: LicenseListItem[], + totalCount: number, + ) { + super(project, query); + this.items = Object.freeze(licenses); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/app/License/behaviors/api.ts b/packages/models/src/app/License/behaviors/api.ts new file mode 100644 index 00000000..9a3cb685 --- /dev/null +++ b/packages/models/src/app/License/behaviors/api.ts @@ -0,0 +1,43 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { LicenseBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount } from "../../../base/index.js"; + +export const apiLicenseBehaviors = ( + client: MittwaldAPIV2Client, +): LicenseBehaviors => ({ + list: async (projectId, query) => { + const response = await client.license.listLicensesForProject({ + queryParameters: query, + projectId, + }); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + find: async (licenseId) => { + const response = await client.license.getLicense({ licenseId }); + if (response.status === 200) { + return response.data; + } + validateResponse(response, 403); + }, + + getContract: async (licenseId) => { + const response = await client.contract.getDetailOfContractByLicense({ + licenseId, + }); + validateResponse(response, 200); + return response.data; + }, + + rotateKey: async (licenseId) => { + const response = await client.license.rotateLicenseKey({ licenseId }); + validateResponse(response, 200); + }, +}); diff --git a/packages/models/src/app/License/behaviors/index.ts b/packages/models/src/app/License/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/app/License/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/app/License/behaviors/types.ts b/packages/models/src/app/License/behaviors/types.ts new file mode 100644 index 00000000..b7b699f2 --- /dev/null +++ b/packages/models/src/app/License/behaviors/types.ts @@ -0,0 +1,16 @@ +import type { ContractData } from "../../../contract/index.js"; +import type { + LicenseListQueryData, + LicenseListItemData, + LicenseData, +} from "../types.js"; + +export interface LicenseBehaviors { + list: ( + projectId: string, + query?: LicenseListQueryData, + ) => Promise<{ items: LicenseListItemData[]; totalCount: number }>; + find: (licenseId: string) => Promise; + getContract: (licenseId: string) => Promise; + rotateKey: (licenseId: string) => Promise; +} diff --git a/packages/models/src/app/License/index.ts b/packages/models/src/app/License/index.ts new file mode 100644 index 00000000..6ff07b31 --- /dev/null +++ b/packages/models/src/app/License/index.ts @@ -0,0 +1,2 @@ +export * from "./License.js"; +export * from "./types.js"; diff --git a/packages/models/src/app/License/types.ts b/packages/models/src/app/License/types.ts new file mode 100644 index 00000000..cd453edc --- /dev/null +++ b/packages/models/src/app/License/types.ts @@ -0,0 +1,12 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type LicenseData = + MittwaldAPIV2.Operations.LicenseGetLicense.ResponseData; + +export type LicenseListItemData = + MittwaldAPIV2.Operations.LicenseListLicensesForProject.ResponseData[number]; + +export type LicenseListQueryData = + MittwaldAPIV2.Paths.V2ProjectsProjectIdLicenses.Get.Parameters.Query; + +export type LicenseMeta = MittwaldAPIV2.Components.Schemas.LicenseMeta; diff --git a/packages/models/src/app/SystemSoftware/SystemSoftware.test.ts b/packages/models/src/app/SystemSoftware/SystemSoftware.test.ts new file mode 100644 index 00000000..9c8f8f7f --- /dev/null +++ b/packages/models/src/app/SystemSoftware/SystemSoftware.test.ts @@ -0,0 +1,182 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { ObjectNotFoundError } from "../../errors/ObjectNotFoundError.js"; +import { + buildSystemSoftwareListItemData, + buildSystemSoftwareData, +} from "../../testing/builders/buildSystemSoftwareData.js"; +import { ReferenceModel } from "../../base/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { + SystemSoftwareListQuery, + SystemSoftwareDetailed, + SystemSoftwareListItem, + SystemSoftwareList, + SystemSoftware, +} from "./SystemSoftware.js"; + +afterEach(resetBehaviors); + +describe("SystemSoftware reference and delegation", () => { + test("find delegates by id and returns a detailed model", async () => { + const find = vi + .fn() + .mockResolvedValue(buildSystemSoftwareData({ id: "ss-1" })); + installBehaviors({ systemSoftware: { find } }); + + const result = await SystemSoftware.find("ss-1"); + + expect(find).toHaveBeenCalledWith("ss-1"); + expect(result).toBeInstanceOf(SystemSoftwareDetailed); + expect(result?.id).toBe("ss-1"); + }); + + test("find returns undefined when the behavior finds nothing", async () => { + installBehaviors({ + systemSoftware: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(SystemSoftware.find("missing")).resolves.toBeUndefined(); + }); + + test("get returns a detailed model", async () => { + installBehaviors({ + systemSoftware: { + find: vi + .fn() + .mockResolvedValue(buildSystemSoftwareData({ id: "ss-1" })), + }, + }); + + await expect(SystemSoftware.get("ss-1")).resolves.toBeInstanceOf( + SystemSoftwareDetailed, + ); + }); + + test("ofId creates a reference whose findDetailed delegates by id", async () => { + const find = vi + .fn() + .mockResolvedValue(buildSystemSoftwareData({ id: "ss-1" })); + installBehaviors({ systemSoftware: { find } }); + + const reference = SystemSoftware.ofId("ss-1"); + const result = await reference.findDetailed(); + + expect(reference).toBeInstanceOf(SystemSoftware); + expect(find).toHaveBeenCalledWith("ss-1"); + expect(result).toBeInstanceOf(SystemSoftwareDetailed); + }); + + test("findCommon and getCommon materialize a reference via the behavior", async () => { + const find = vi + .fn() + .mockResolvedValue(buildSystemSoftwareData({ id: "ss-1" })); + installBehaviors({ systemSoftware: { find } }); + const reference = SystemSoftware.ofId("ss-1"); + + await expect(reference.findCommon()).resolves.toBeInstanceOf( + SystemSoftwareDetailed, + ); + await expect(reference.getCommon()).resolves.toBeInstanceOf( + SystemSoftwareDetailed, + ); + expect(find).toHaveBeenCalledWith("ss-1"); + }); + + test("findCommon resolves undefined and getCommon throws when missing", async () => { + installBehaviors({ + systemSoftware: { find: vi.fn().mockResolvedValue(undefined) }, + }); + const reference = SystemSoftware.ofId("missing"); + + await expect(reference.findCommon()).resolves.toBeUndefined(); + await expect(reference.getCommon()).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("findCommon and getCommon are idempotent for materialized system software", async () => { + const find = vi.fn(); + installBehaviors({ systemSoftware: { find } }); + const detailed = new SystemSoftwareDetailed( + buildSystemSoftwareData({ id: "ss-1" }), + ); + const listItem = new SystemSoftwareListItem( + buildSystemSoftwareListItemData({ id: "ss-2" }), + ); + + await expect(detailed.findCommon()).resolves.toBe(detailed); + await expect(detailed.getCommon()).resolves.toBe(detailed); + await expect(listItem.findCommon()).resolves.toBe(listItem); + await expect(listItem.getCommon()).resolves.toBe(listItem); + expect(find).not.toHaveBeenCalled(); + }); +}); + +describe("SystemSoftware data", () => { + test.each([ + ["php", "PHP"], + ["wp-cli", "WP-CLI"], + ] as const)("derives the full name for %s", (name, fullName) => { + const item = new SystemSoftwareListItem( + buildSystemSoftwareListItemData({ tags: [name], name }), + ); + const detailed = new SystemSoftwareDetailed( + buildSystemSoftwareData({ tags: [name], name }), + ); + + for (const model of [item, detailed]) { + expect(model.name).toBe(name); + expect(model.fullName).toBe(fullName); + expect(model.tags).toEqual([name]); + } + }); +}); + +describe("SystemSoftware list query", () => { + test("delegates the query and materializes list items", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildSystemSoftwareListItemData({ id: "ss-1" })], + }); + installBehaviors({ systemSoftware: { list } }); + + const query = SystemSoftware.query({ limit: 5 }); + const result = await query.execute(); + + expect(query).toBeInstanceOf(SystemSoftwareListQuery); + expect(list).toHaveBeenCalledWith({ limit: 5 }); + expect(result).toBeInstanceOf(SystemSoftwareList); + expect(result.items[0]).toBeInstanceOf(SystemSoftwareListItem); + }); + + test("refine merges query values", async () => { + const list = vi.fn().mockResolvedValue({ items: [] }); + installBehaviors({ systemSoftware: { list } }); + + await SystemSoftware.query({ limit: 5, skip: 1 }) + .refine({ skip: 2 }) + .execute(); + + expect(list).toHaveBeenCalledWith({ limit: 5, skip: 2 }); + }); +}); + +test("SystemSoftware list items preserve the model composition chain", () => { + const item = new SystemSoftwareListItem(buildSystemSoftwareListItemData()); + + expect(item).toBeInstanceOf(SystemSoftwareListItem); + expect(item).toBeInstanceOf(SystemSoftware); + expect(item).toBeInstanceOf(ReferenceModel); + expect(item.data).toBeDefined(); +}); diff --git a/packages/models/src/app/SystemSoftware/SystemSoftware.ts b/packages/models/src/app/SystemSoftware/SystemSoftware.ts new file mode 100644 index 00000000..627b3b78 --- /dev/null +++ b/packages/models/src/app/SystemSoftware/SystemSoftware.ts @@ -0,0 +1,158 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; + +import type { SystemSoftwareVersionListQuery } from "../SystemSoftwareVersion/index.js"; +import type { + SystemSoftwareListQueryData, + SystemSoftwareListItemData, + SystemSoftwareData, + SystemSoftwareName, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { SystemSoftwareVersion } from "../SystemSoftwareVersion/index.js"; +import { SystemSoftwareFullNames } from "./types.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "SystemSoftware", +}) +export class SystemSoftware extends ReferenceModel { + public readonly recommendedVersions: SystemSoftwareVersionListQuery; + + public constructor(id: string) { + super(id); + this.recommendedVersions = SystemSoftwareVersion.query(this, { + recommended: true, + }); + } + + public static async find(id: string) { + const data = await config.behaviors.systemSoftware.find(id); + + if (data) { + return new SystemSoftwareDetailed(data); + } + } + + public static async get(id: string) { + const systemSoftware = await this.find(id); + assertObjectFound(systemSoftware, SystemSoftware, id); + return systemSoftware; + } + + public static ofId(id: string) { + return new SystemSoftware(id); + } + + public static query(query: SystemSoftwareListQueryData = {}) { + return new SystemSoftwareListQuery(query); + } + + public async findCommon(): Promise { + return this instanceof SystemSoftwareCommon ? this : this.findDetailed(); + } + + public findDetailed(): Promise { + return SystemSoftware.find(this.id); + } + + public async getCommon(): Promise { + return this instanceof SystemSoftwareCommon ? this : this.getDetailed(); + } + + public async getDetailed(): Promise { + return SystemSoftware.get(this.id); + } +} + +export class SystemSoftwareCommon extends WithData< + SystemSoftwareListItemData | SystemSoftwareData +>()(SystemSoftware) { + public override readonly data: + SystemSoftwareListItemData | SystemSoftwareData; + public readonly fullName: string; + public readonly name: SystemSoftwareName; + public readonly tags: string[]; + + public constructor(data: SystemSoftwareListItemData | SystemSoftwareData) { + super(data.id); + this.data = data; + this.name = data.name as SystemSoftwareName; + this.fullName = + SystemSoftwareFullNames[ + this.name as keyof typeof SystemSoftwareFullNames + ]; + this.tags = data.tags; + } +} + +export class SystemSoftwareDetailed extends SystemSoftwareCommon { + public override readonly data: SystemSoftwareData; + + public constructor(data: SystemSoftwareData) { + super(data); + this.data = data; + } +} + +export class SystemSoftwareListItem extends SystemSoftwareCommon { + public override readonly data: SystemSoftwareListItemData; + + public constructor(data: SystemSoftwareListItemData) { + super(data); + this.data = data; + } +} + +export class SystemSoftwareListQuery extends ListQueryModel { + public constructor(query: SystemSoftwareListQueryData = {}) { + super(query); + } + + public async execute() { + const { totalCount, items } = await config.behaviors.systemSoftware.list( + this.query, + ); + + return new SystemSoftwareList( + this.query, + items.map((d) => new SystemSoftwareListItem(d)), + totalCount, + ); + } + + public async getTotalCount() { + const { totalCount } = await this.refine({ limit: 1 }).execute(); + return totalCount; + } + + public refine(query: SystemSoftwareListQueryData) { + return new SystemSoftwareListQuery({ + ...this.query, + ...query, + }); + } +} + +export class SystemSoftwareList extends WithListData()( + SystemSoftwareListQuery, +) { + public override readonly items: readonly SystemSoftwareListItem[]; + public override readonly totalCount: number; + + public constructor( + query: SystemSoftwareListQueryData, + systemSoftwares: SystemSoftwareListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(systemSoftwares); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/app/SystemSoftware/behaviors/api.ts b/packages/models/src/app/SystemSoftware/behaviors/api.ts new file mode 100644 index 00000000..75063f0c --- /dev/null +++ b/packages/models/src/app/SystemSoftware/behaviors/api.ts @@ -0,0 +1,31 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { SystemSoftwareBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount } from "../../../base/index.js"; + +export const apiSystemSoftwareBehaviors = ( + client: MittwaldAPIV2Client, +): SystemSoftwareBehaviors => ({ + list: async (query) => { + const response = await client.app.listSystemsoftwares({ + queryParameters: query, + }); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + find: async (systemSoftwareId) => { + const response = await client.app.getSystemsoftware({ + systemSoftwareId, + }); + if (response.status === 200) { + return response.data; + } + validateResponse(response, 404); + }, +}); diff --git a/packages/models/src/app/SystemSoftware/behaviors/index.ts b/packages/models/src/app/SystemSoftware/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/app/SystemSoftware/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/app/SystemSoftware/behaviors/types.ts b/packages/models/src/app/SystemSoftware/behaviors/types.ts new file mode 100644 index 00000000..b7d410e5 --- /dev/null +++ b/packages/models/src/app/SystemSoftware/behaviors/types.ts @@ -0,0 +1,13 @@ +import type { + SystemSoftwareListQueryData, + SystemSoftwareListItemData, + SystemSoftwareData, +} from "../types.js"; + +export interface SystemSoftwareBehaviors { + list: ( + query?: SystemSoftwareListQueryData, + ) => Promise<{ items: SystemSoftwareListItemData[]; totalCount: number }>; + + find: (systemSoftwareId: string) => Promise; +} diff --git a/packages/models/src/app/SystemSoftware/index.ts b/packages/models/src/app/SystemSoftware/index.ts new file mode 100644 index 00000000..cf9bdf17 --- /dev/null +++ b/packages/models/src/app/SystemSoftware/index.ts @@ -0,0 +1,2 @@ +export * from "./SystemSoftware.js"; +export * from "./types.js"; diff --git a/packages/models/src/app/SystemSoftware/types.ts b/packages/models/src/app/SystemSoftware/types.ts new file mode 100644 index 00000000..21b23d18 --- /dev/null +++ b/packages/models/src/app/SystemSoftware/types.ts @@ -0,0 +1,72 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type SystemSoftwareData = + MittwaldAPIV2.Operations.AppGetSystemsoftware.ResponseData; + +export type SystemSoftwareListItemData = + MittwaldAPIV2.Operations.AppListSystemsoftwares.ResponseData[number]; + +export type SystemSoftwareListQueryData = + MittwaldAPIV2.Paths.V2SystemSoftwares.Get.Parameters.Query; + +export type SystemSoftwareName = + | "redis-cli" + | "composer" + | "pdftools" + | "libvips" + | "python" + | "wp-cli" + | "mysql" + | "nano" + | "node" + | "perl" + | "webp" + | "php" + | "gs" + | "gm" + | "im" + | "mc"; + +export enum SystemSoftwareFullNames { + mc = "Midnight Commander", + "redis-cli" = "Redis CLI", + mysql = "MySQL Client", + pdftools = "PDF Tools", + composer = "Composer", + gm = "GraphicsMagick", + libvips = "libvips", + "wp-cli" = "WP-CLI", + gs = "Ghostscript", + im = "ImageMagick", + python = "Python", + node = "Node.js", + nano = "nano", + perl = "Perl", + webp = "WebP", + php = "PHP", +} + +export function isSystemSoftwareKey( + value: string, +): value is keyof typeof SystemSoftwareFullNames { + return value in SystemSoftwareFullNames; +} + +export enum SystemSoftwareId { + "redis-cli" = "218091c6-049b-4834-8fda-42dda74b7c78", + composer = "2390ee6c-0f09-4781-bb11-a9359c17a0d4", + pdftools = "55311bea-b9b9-40d0-9ffc-dd943a16a540", + "wp-cli" = "9c55807a-f3b4-49f4-8849-8c7923a1225f", + libvips = "46188c81-dadd-4997-b7b9-5e0cb95aabc9", + python = "5ff298ad-40c6-4a8a-a5b6-1ac1bf75c71c", + mysql = "e3668337-e473-4b01-a334-52ff042ede9d", + nano = "97ce8755-489d-474f-adc3-87b0384972e6", + node = "1d80c3ff-f932-424e-813a-17c49c0fb837", + perl = "8187e28c-dc32-4db2-8274-25372836ff2f", + webp = "ee8e2a45-8ac2-48cb-8838-f73eb7cc1431", + php = "c42293f3-c2df-40d9-a5c9-4fa2ffdc36aa", + gm = "b0b5880a-0fc0-413e-8e6a-308d1dc01179", + gs = "685cb377-c685-42b0-a598-142eee4c945a", + im = "e015b8f3-c0bd-43c3-a8bf-2865028bbb50", + mc = "f2e61269-aaeb-46a0-a720-ca00491fef47", +} diff --git a/packages/models/src/app/SystemSoftwareVersion/FeePeriod.ts b/packages/models/src/app/SystemSoftwareVersion/FeePeriod.ts new file mode 100644 index 00000000..9c857470 --- /dev/null +++ b/packages/models/src/app/SystemSoftwareVersion/FeePeriod.ts @@ -0,0 +1,21 @@ +import { DateTime } from "luxon"; + +import type { FeePeriodData } from "./types.js"; + +import { Money } from "../../common/index.js"; + +export class FeePeriod { + public readonly feeValidFrom?: DateTime; + public readonly feeValidUntil?: DateTime; + public readonly monthlyPrice: Money; + + public constructor(data: FeePeriodData) { + this.feeValidFrom = data.feeValidFrom + ? DateTime.fromISO(data.feeValidFrom) + : undefined; + this.feeValidUntil = data.feeValidUntil + ? DateTime.fromISO(data.feeValidUntil) + : undefined; + this.monthlyPrice = Money({ amount: data.monthlyPrice, currency: "EUR" }); + } +} diff --git a/packages/models/src/app/SystemSoftwareVersion/SystemSoftwareVersion.test.ts b/packages/models/src/app/SystemSoftwareVersion/SystemSoftwareVersion.test.ts new file mode 100644 index 00000000..b04cfc6d --- /dev/null +++ b/packages/models/src/app/SystemSoftwareVersion/SystemSoftwareVersion.test.ts @@ -0,0 +1,271 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; +import { DateTime } from "luxon"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { ObjectNotFoundError } from "../../errors/ObjectNotFoundError.js"; +import { + buildSystemSoftwareVersionListItemData, + buildSystemSoftwareVersionData, +} from "../../testing/builders/buildSystemSoftwareVersionData.js"; +import { SystemSoftware } from "../SystemSoftware/index.js"; +import { ReferenceModel } from "../../base/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { FeePeriod } from "./FeePeriod.js"; +import { + SystemSoftwareVersionDetailed, + SystemSoftwareVersionListItem, + SystemSoftwareVersionList, + SystemSoftwareVersion, +} from "./SystemSoftwareVersion.js"; + +afterEach(resetBehaviors); + +const systemSoftware = SystemSoftware.ofId("ss-1"); + +describe("SystemSoftwareVersion reference and delegation", () => { + test("find delegates with both ids and returns a detailed model", async () => { + const find = vi + .fn() + .mockResolvedValue(buildSystemSoftwareVersionData({ id: "version-1" })); + installBehaviors({ systemSoftwareVersion: { find } }); + + const result = await SystemSoftwareVersion.find( + "version-1", + systemSoftware, + ); + + expect(find).toHaveBeenCalledWith("version-1", "ss-1"); + expect(result).toBeInstanceOf(SystemSoftwareVersionDetailed); + expect(result?.id).toBe("version-1"); + }); + + test("find returns undefined when the behavior finds nothing", async () => { + installBehaviors({ + systemSoftwareVersion: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + SystemSoftwareVersion.find("missing", systemSoftware), + ).resolves.toBeUndefined(); + }); + + test("a reference delegates findDetailed with its ids", async () => { + const find = vi.fn().mockResolvedValue(buildSystemSoftwareVersionData()); + installBehaviors({ systemSoftwareVersion: { find } }); + + const reference = SystemSoftwareVersion.ofId("version-1", systemSoftware); + const result = await reference.findDetailed(); + + expect(reference).toBeInstanceOf(SystemSoftwareVersion); + expect(find).toHaveBeenCalledWith("version-1", "ss-1"); + expect(result).toBeInstanceOf(SystemSoftwareVersionDetailed); + }); + + test("findCommon and getCommon materialize a reference via the behavior", async () => { + const find = vi + .fn() + .mockResolvedValue(buildSystemSoftwareVersionData({ id: "version-1" })); + installBehaviors({ systemSoftwareVersion: { find } }); + const reference = SystemSoftwareVersion.ofId("version-1", systemSoftware); + + await expect(reference.findCommon()).resolves.toBeInstanceOf( + SystemSoftwareVersionDetailed, + ); + await expect(reference.getCommon()).resolves.toBeInstanceOf( + SystemSoftwareVersionDetailed, + ); + expect(find).toHaveBeenCalledWith("version-1", "ss-1"); + }); + + test("findCommon resolves undefined and getCommon throws when missing", async () => { + installBehaviors({ + systemSoftwareVersion: { find: vi.fn().mockResolvedValue(undefined) }, + }); + const reference = SystemSoftwareVersion.ofId("missing", systemSoftware); + + await expect(reference.findCommon()).resolves.toBeUndefined(); + await expect(reference.getCommon()).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("findCommon and getCommon are idempotent for materialized versions", async () => { + const find = vi.fn(); + installBehaviors({ systemSoftwareVersion: { find } }); + const detailed = new SystemSoftwareVersionDetailed( + buildSystemSoftwareVersionData({ id: "version-1" }), + systemSoftware, + ); + const listItem = new SystemSoftwareVersionListItem( + buildSystemSoftwareVersionListItemData({ id: "version-2" }), + systemSoftware, + ); + + await expect(detailed.findCommon()).resolves.toBe(detailed); + await expect(detailed.getCommon()).resolves.toBe(detailed); + await expect(listItem.findCommon()).resolves.toBe(listItem); + await expect(listItem.getCommon()).resolves.toBe(listItem); + expect(find).not.toHaveBeenCalled(); + }); +}); + +describe("SystemSoftwareVersion data and derived values", () => { + test("exposes the external version and parses the expiry date", () => { + const item = new SystemSoftwareVersionListItem( + buildSystemSoftwareVersionListItemData({ + expiryDate: "2030-04-15T00:00:00.000Z", + externalVersion: "8.4", + }), + systemSoftware, + ); + + expect(item.version).toBe("8.4"); + expect(item.expiryDate).toBeInstanceOf(DateTime); + expect(item.expiryDate?.toISODate()).toBe("2030-04-15"); + }); + + test("leaves expiryDate undefined when absent", () => { + const item = new SystemSoftwareVersionListItem( + buildSystemSoftwareVersionListItemData(), + systemSoftware, + ); + + expect(item.expiryDate).toBeUndefined(); + }); + + test("returns no fee period when the version carries no fee", () => { + const item = new SystemSoftwareVersionListItem( + buildSystemSoftwareVersionListItemData(), + systemSoftware, + ); + + expect(item.checkCurrentFee()).toBeUndefined(); + expect(item.checkImminentFee()).toBeUndefined(); + }); + + test("reports only imminent expiry dates", () => { + const imminent = DateTime.now().plus({ month: 1 }).toISO(); + const distant = DateTime.now().plus({ year: 5 }).toISO(); + + expect( + new SystemSoftwareVersionListItem( + buildSystemSoftwareVersionListItemData({ expiryDate: imminent }), + systemSoftware, + ).checkImminentExpiryDate(), + ).toBe(imminent); + expect( + new SystemSoftwareVersionListItem( + buildSystemSoftwareVersionListItemData({ expiryDate: distant }), + systemSoftware, + ).checkImminentExpiryDate(), + ).toBeUndefined(); + }); + + test("compares internal semantic versions", () => { + const newer = new SystemSoftwareVersionListItem( + buildSystemSoftwareVersionListItemData({ internalVersion: "8.3.0" }), + systemSoftware, + ); + const older = new SystemSoftwareVersionListItem( + buildSystemSoftwareVersionListItemData({ internalVersion: "8.2.0" }), + systemSoftware, + ); + + expect(newer.compare(older)).toBe(1); + expect(older.compare(newer)).toBe(-1); + expect(newer.compare(newer)).toBe(0); + }); + + test("returns the current fee period", () => { + const item = new SystemSoftwareVersionListItem( + buildSystemSoftwareVersionListItemData({ + fee: { + periods: [ + { + feeValidFrom: DateTime.now().minus({ month: 1 }).toISO(), + monthlyPrice: 1000, + }, + ], + }, + }), + systemSoftware, + ); + + const period = item.checkCurrentFee(); + expect(period).toBeInstanceOf(FeePeriod); + expect(period?.monthlyPrice).toBeDefined(); + }); + + test("returns an imminent future fee when there is no current fee", () => { + const item = new SystemSoftwareVersionListItem( + buildSystemSoftwareVersionListItemData({ + fee: { + periods: [ + { + feeValidFrom: DateTime.now().plus({ month: 3 }).toISO(), + monthlyPrice: 1200, + }, + ], + }, + }), + systemSoftware, + ); + + const period = item.checkImminentFee(); + expect(period).toBeInstanceOf(FeePeriod); + expect(period?.monthlyPrice).toBeDefined(); + }); +}); + +describe("SystemSoftwareVersion list query", () => { + test("delegates, materializes, and sorts versions descending", async () => { + const list = vi.fn().mockResolvedValue({ + items: ["8.2.0", "8.4.0", "8.3.0"].map((internalVersion) => + buildSystemSoftwareVersionListItemData({ + externalVersion: internalVersion, + internalVersion, + }), + ), + }); + installBehaviors({ systemSoftwareVersion: { list } }); + + const result = await SystemSoftwareVersion.query(systemSoftware, { + recommended: true, + }).execute(); + + expect(list).toHaveBeenCalledWith("ss-1", { recommended: true }); + expect(result).toBeInstanceOf(SystemSoftwareVersionList); + expect( + result.items.every( + (item) => item instanceof SystemSoftwareVersionListItem, + ), + ).toBe(true); + expect(result.items.map((item) => item.version)).toEqual([ + "8.4.0", + "8.3.0", + "8.2.0", + ]); + }); +}); + +test("SystemSoftwareVersion list items preserve the model composition chain", () => { + const item = new SystemSoftwareVersionListItem( + buildSystemSoftwareVersionListItemData(), + systemSoftware, + ); + + expect(item).toBeInstanceOf(SystemSoftwareVersionListItem); + expect(item).toBeInstanceOf(SystemSoftwareVersion); + expect(item).toBeInstanceOf(ReferenceModel); + expect(item.data).toBeDefined(); +}); diff --git a/packages/models/src/app/SystemSoftwareVersion/SystemSoftwareVersion.ts b/packages/models/src/app/SystemSoftwareVersion/SystemSoftwareVersion.ts new file mode 100644 index 00000000..bead7edf --- /dev/null +++ b/packages/models/src/app/SystemSoftwareVersion/SystemSoftwareVersion.ts @@ -0,0 +1,227 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import semverCompare from "semver-compare"; +import { DateTime } from "luxon"; + +import type { SystemSoftware } from "../SystemSoftware/index.js"; +import type { + SystemSoftwareVersionListQueryData, + SystemSoftwareVersionListItemData, + SystemSoftwareVersionData, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { FeePeriod } from "./FeePeriod.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "SystemSoftwareVersion", +}) +export class SystemSoftwareVersion extends ReferenceModel { + public readonly systemSoftware: SystemSoftware; + + public constructor(id: string, systemSoftware: SystemSoftware) { + super(id); + this.systemSoftware = systemSoftware; + } + + public static async find(id: string, systemSoftware: SystemSoftware) { + const data = await config.behaviors.systemSoftwareVersion.find( + id, + systemSoftware.id, + ); + if (data) { + return new SystemSoftwareVersionDetailed(data, systemSoftware); + } + } + + public static async get(id: string, systemSoftware: SystemSoftware) { + const systemSoftwareVersion = await this.find(id, systemSoftware); + assertObjectFound(systemSoftwareVersion, SystemSoftwareVersion, id); + return systemSoftwareVersion; + } + + public static ofId(id: string, systemSoftware: SystemSoftware) { + return new SystemSoftwareVersion(id, systemSoftware); + } + + public static query( + systemSoftware: SystemSoftware, + query: SystemSoftwareVersionListQueryData = {}, + ) { + return new SystemSoftwareVersionListQuery(systemSoftware, query); + } + + public async findCommon(): Promise { + return this instanceof SystemSoftwareVersionCommon + ? this + : this.findDetailed(); + } + + public async findDetailed(): Promise< + SystemSoftwareVersionDetailed | undefined + > { + return SystemSoftwareVersion.find(this.id, this.systemSoftware); + } + + public async getCommon(): Promise { + return this instanceof SystemSoftwareVersionCommon + ? this + : this.getDetailed(); + } + + public getDetailed(): Promise { + return SystemSoftwareVersion.get(this.id, this.systemSoftware); + } +} + +export class SystemSoftwareVersionCommon extends WithData< + SystemSoftwareVersionListItemData | SystemSoftwareVersionData +>()(SystemSoftwareVersion) { + public override readonly data: + SystemSoftwareVersionListItemData | SystemSoftwareVersionData; + public readonly expiryDate?: DateTime; + public readonly version: string; + public constructor( + data: SystemSoftwareVersionListItemData | SystemSoftwareVersionData, + systemSoftware: SystemSoftware, + ) { + super(data.id, systemSoftware); + this.data = data; + this.version = data.externalVersion; + this.expiryDate = data.expiryDate + ? DateTime.fromISO(data.expiryDate) + : undefined; + } + + public checkCurrentFee() { + if (this.data.fee && "periods" in this.data.fee) { + const period = this.data.fee.periods.find( + (period) => + period.feeValidFrom && + DateTime.fromISO(period.feeValidFrom) <= DateTime.now() && + (!period.feeValidUntil || + DateTime.fromISO(period.feeValidUntil) > DateTime.now()), + ); + if (period) { + return new FeePeriod(period); + } + } + } + + public checkImminentExpiryDate() { + if ( + this.data.expiryDate && + DateTime.fromISO(this.data.expiryDate) < DateTime.now().plus({ month: 6 }) + ) { + return this.data.expiryDate; + } + } + + public checkImminentFee() { + if ( + this.data.fee && + "periods" in this.data.fee && + !this.checkCurrentFee() + ) { + const period = this.data.fee.periods.find( + (period) => + period.feeValidFrom && + DateTime.fromISO(period.feeValidFrom) > DateTime.now() && + DateTime.fromISO(period.feeValidFrom) < + DateTime.now().plus({ month: 6 }), + ); + + if (period) { + return new FeePeriod(period); + } + } + } + + public compare(other: SystemSoftwareVersionListItem): -1 | 0 | 1 { + return semverCompare(this.data.internalVersion, other.data.internalVersion); + } +} + +export class SystemSoftwareVersionDetailed extends SystemSoftwareVersionCommon { + public override readonly data: SystemSoftwareVersionData; + + public constructor( + data: SystemSoftwareVersionData, + systemSoftware: SystemSoftware, + ) { + super(data, systemSoftware); + this.data = data; + } +} + +export class SystemSoftwareVersionListItem extends SystemSoftwareVersionCommon { + public override readonly data: SystemSoftwareVersionListItemData; + + public constructor( + data: SystemSoftwareVersionListItemData, + systemSoftware: SystemSoftware, + ) { + super(data, systemSoftware); + this.data = data; + } +} + +export class SystemSoftwareVersionListQuery extends ListQueryModel { + public readonly systemSoftware: SystemSoftware; + + public constructor( + systemSoftware: SystemSoftware, + query: SystemSoftwareVersionListQueryData, + ) { + super(query, { dependencies: [systemSoftware.id] }); + this.systemSoftware = systemSoftware; + } + + public async execute() { + const { totalCount, items } = + await config.behaviors.systemSoftwareVersion.list( + this.systemSoftware.id, + this.query, + ); + + return new SystemSoftwareVersionList( + this.systemSoftware, + this.query, + items + .map((d) => new SystemSoftwareVersionListItem(d, this.systemSoftware)) + .sort((a, b) => b.compare(a)), + totalCount, + ); + } + + public refine(query: SystemSoftwareVersionListQueryData) { + return new SystemSoftwareVersionListQuery(this.systemSoftware, { + ...this.query, + ...query, + }); + } +} + +export class SystemSoftwareVersionList extends WithListData()( + SystemSoftwareVersionListQuery, +) { + public override readonly items: readonly SystemSoftwareVersionListItem[]; + public override readonly totalCount: number; + + public constructor( + systemSoftware: SystemSoftware, + query: SystemSoftwareVersionListQueryData, + systemSoftwareVersions: SystemSoftwareVersionListItem[], + totalCount: number, + ) { + super(systemSoftware, query); + this.items = Object.freeze(systemSoftwareVersions); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/app/SystemSoftwareVersion/behaviors/api.ts b/packages/models/src/app/SystemSoftwareVersion/behaviors/api.ts new file mode 100644 index 00000000..9ef8c396 --- /dev/null +++ b/packages/models/src/app/SystemSoftwareVersion/behaviors/api.ts @@ -0,0 +1,36 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { SystemSoftwareVersionBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount } from "../../../base/index.js"; + +export const apiSystemSoftwareVersionBehaviors = ( + client: MittwaldAPIV2Client, +): SystemSoftwareVersionBehaviors => ({ + list: async (systemSoftwareId, query) => { + const response = await client.app.listSystemsoftwareversions({ + queryParameters: query, + systemSoftwareId, + }); + + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + find: async (systemSoftwareVersionId, systemSoftwareId) => { + const response = await client.app.getSystemsoftwareversion({ + systemSoftwareVersionId, + systemSoftwareId, + }); + + if (response.status === 200) { + return response.data; + } + + validateResponse(response, 404); + }, +}); diff --git a/packages/models/src/app/SystemSoftwareVersion/behaviors/index.ts b/packages/models/src/app/SystemSoftwareVersion/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/app/SystemSoftwareVersion/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/app/SystemSoftwareVersion/behaviors/types.ts b/packages/models/src/app/SystemSoftwareVersion/behaviors/types.ts new file mode 100644 index 00000000..de2e600b --- /dev/null +++ b/packages/models/src/app/SystemSoftwareVersion/behaviors/types.ts @@ -0,0 +1,20 @@ +import type { + SystemSoftwareVersionListQueryData, + SystemSoftwareVersionListItemData, + SystemSoftwareVersionData, +} from "../types.js"; + +export interface SystemSoftwareVersionBehaviors { + list: ( + systemSoftwareId: string, + query?: SystemSoftwareVersionListQueryData, + ) => Promise<{ + items: SystemSoftwareVersionListItemData[]; + totalCount: number; + }>; + + find: ( + systemSoftwareVersionId: string, + SystemSoftwareId: string, + ) => Promise; +} diff --git a/packages/models/src/app/SystemSoftwareVersion/index.ts b/packages/models/src/app/SystemSoftwareVersion/index.ts new file mode 100644 index 00000000..845187f2 --- /dev/null +++ b/packages/models/src/app/SystemSoftwareVersion/index.ts @@ -0,0 +1,3 @@ +export * from "./FeePeriod.js"; +export * from "./SystemSoftwareVersion.js"; +export * from "./types.js"; diff --git a/packages/models/src/app/SystemSoftwareVersion/types.ts b/packages/models/src/app/SystemSoftwareVersion/types.ts new file mode 100644 index 00000000..f97993ec --- /dev/null +++ b/packages/models/src/app/SystemSoftwareVersion/types.ts @@ -0,0 +1,13 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type SystemSoftwareVersionData = + MittwaldAPIV2.Operations.AppGetSystemsoftwareversion.ResponseData; + +export type SystemSoftwareVersionListItemData = + MittwaldAPIV2.Operations.AppListSystemsoftwareversions.ResponseData[number]; + +export type SystemSoftwareVersionListQueryData = + MittwaldAPIV2.Paths.V2SystemSoftwaresSystemSoftwareIdVersions.Get.Parameters.Query; + +export type FeePeriodData = + MittwaldAPIV2.Components.Schemas.FeePeriodBasedFeeStrategy["periods"][0]; diff --git a/packages/models/src/app/UserInput/UserInput.test.ts b/packages/models/src/app/UserInput/UserInput.test.ts new file mode 100644 index 00000000..25c4ef49 --- /dev/null +++ b/packages/models/src/app/UserInput/UserInput.test.ts @@ -0,0 +1,74 @@ +import { afterEach, expect, test } from "vitest"; + +import { buildAppUserInputData } from "../../testing/builders/buildAppUserInputData.js"; +import { resetBehaviors } from "../../testing/installBehaviors.js"; +import { UserInput } from "./UserInput.js"; +import { DataModel } from "../../base/index.js"; + +afterEach(resetBehaviors); + +test("exposes its input data", () => { + const input = new UserInput( + buildAppUserInputData({ + validationSchema: '{"type":"string"}', + defaultValue: "admin@example.com", + name: "admin-email", + dataSource: "users", + dataType: "text", + required: false, + format: "email", + }), + ); + + expect(input.name).toBe("admin-email"); + expect(input.dataType).toBe("text"); + expect(input.required).toBe(false); + expect(input.validationSchema).toBe('{"type":"string"}'); + expect(input.format).toBe("email"); + expect(input.dataSource).toBe("users"); + expect(input.defaultValue).toBe("admin@example.com"); +}); + +test("derives lifecycle and an explicit step", () => { + const input = new UserInput( + buildAppUserInputData({ + lifecycleConstraint: "installation", + positionMeta: { step: "database" }, + }), + ); + + expect(input.lifecycle).toBe("installation"); + expect(input.step).toBe("database"); +}); + +test("uses common as the default step", () => { + const input = new UserInput(buildAppUserInputData()); + + expect(input.step).toBe("common"); +}); + +test("exposes a password-rule validation schema", () => { + const input = new UserInput( + buildAppUserInputData({ + additionalValidationSchema: { kind: "password-rule", schema: "PW" }, + }), + ); + + expect(input.passwordValidationSchema).toBe("PW"); +}); + +test("does not expose other additional validation schemas", () => { + const absent = new UserInput(buildAppUserInputData()); + const other = new UserInput( + buildAppUserInputData({ + additionalValidationSchema: { schema: "OTHER" }, + }), + ); + + expect(absent.passwordValidationSchema).toBeUndefined(); + expect(other.passwordValidationSchema).toBeUndefined(); +}); + +test("is a DataModel", () => { + expect(new UserInput(buildAppUserInputData())).toBeInstanceOf(DataModel); +}); diff --git a/packages/models/src/app/UserInput/UserInput.ts b/packages/models/src/app/UserInput/UserInput.ts new file mode 100644 index 00000000..e7a1885c --- /dev/null +++ b/packages/models/src/app/UserInput/UserInput.ts @@ -0,0 +1,34 @@ +import type { UserInputData, AppLifecycle } from "./types.js"; + +import { DataModel } from "../../base/index.js"; + +export class UserInput extends DataModel { + public readonly dataSource?: string; + public readonly dataType: string; + public readonly defaultValue?: string; + public readonly format?: string; + public readonly lifecycle?: AppLifecycle; + public readonly name: string; + public readonly passwordValidationSchema?: string; + public readonly required: boolean; + public readonly step: string; + public readonly validationSchema: string; + + public constructor(data: UserInputData) { + super(data); + this.lifecycle = data.lifecycleConstraint; + this.step = data.positionMeta?.step ?? "common"; + this.name = data.name; + this.dataType = data.dataType; + this.format = data.format; + this.validationSchema = data.validationSchema; + this.passwordValidationSchema = + data.additionalValidationSchema && + data.additionalValidationSchema?.kind === "password-rule" + ? data.additionalValidationSchema?.schema + : undefined; + this.dataSource = data.dataSource; + this.required = data.required; + this.defaultValue = data.defaultValue; + } +} diff --git a/packages/models/src/app/UserInput/index.ts b/packages/models/src/app/UserInput/index.ts new file mode 100644 index 00000000..7864ab36 --- /dev/null +++ b/packages/models/src/app/UserInput/index.ts @@ -0,0 +1,2 @@ +export * from "./types.js"; +export * from "./UserInput.js"; diff --git a/packages/models/src/app/UserInput/types.ts b/packages/models/src/app/UserInput/types.ts new file mode 100644 index 00000000..fa1dd2ae --- /dev/null +++ b/packages/models/src/app/UserInput/types.ts @@ -0,0 +1,13 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type AppUserInputData = MittwaldAPIV2.Components.Schemas.AppUserInput; + +export type AppLifecycle = + MittwaldAPIV2.Components.Schemas.AppAppInstallationLifecycle; + +export type UserInputData = Omit< + AppUserInputData, + "lifecycleConstraint" | "step" +> & { + lifecycleConstraint?: AppLifecycle; +}; diff --git a/packages/models/src/app/index.ts b/packages/models/src/app/index.ts index 2eee1ff2..9962c5c9 100644 --- a/packages/models/src/app/index.ts +++ b/packages/models/src/app/index.ts @@ -1 +1,9 @@ +export * from "./App/index.js"; export * from "./AppInstallation/index.js"; +export * from "./AppLinkedDatabase/index.js"; +export * from "./AppVersion/index.js"; +export * from "./InstalledSystemSoftware/index.js"; +export * from "./License/index.js"; +export * from "./SystemSoftware/index.js"; +export * from "./SystemSoftwareVersion/index.js"; +export * from "./UserInput/index.js"; diff --git a/packages/models/src/article/Article/Article.test.ts b/packages/models/src/article/Article/Article.test.ts new file mode 100644 index 00000000..e51a774d --- /dev/null +++ b/packages/models/src/article/Article/Article.test.ts @@ -0,0 +1,459 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { ObjectNotFoundError } from "../../errors/ObjectNotFoundError.js"; +import { installBehaviors, resetBehaviors } from "../../testing/index.js"; +import { + buildArticleAttributeData, + buildArticleListItemData, + buildArticleModifierData, + buildArticleTemplateData, + buildArticleTagData, + buildArticleData, +} from "../../testing/builders/buildArticleData.js"; +import { config } from "../../config/config.js"; +import { ReferenceModel } from "../../base/index.js"; +import { + StorageArticleModifier, + CpuArticleAttribute, + AIHostingArticle, + ArticleAttribute, + ArticleListQuery, + ArticleDetailed, + ArticleListItem, + ArticleModifier, + ArticleCommon, + ArticleList, + Article, +} from "./internal.js"; + +afterEach(resetBehaviors); + +describe("Article reference", () => { + test("find delegates to the article behavior and materializes an article", async () => { + const find = vi + .fn() + .mockResolvedValue(buildArticleData({ articleId: "a-1" })); + installBehaviors({ article: { find } }); + + const result = await Article.find("a-1"); + + expect(find).toHaveBeenCalledWith("a-1"); + expect(result).toBeInstanceOf(ArticleCommon); + expect(result?.id).toBe("a-1"); + }); + + test("find returns undefined for a missing article", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ article: { find } }); + + expect(await Article.find("missing")).toBeUndefined(); + }); + + test("get returns a found article", async () => { + const find = vi + .fn() + .mockResolvedValue(buildArticleData({ articleId: "a-2" })); + installBehaviors({ article: { find } }); + + const result = await Article.get("a-2"); + + expect(result.id).toBe("a-2"); + }); + + test("get throws ObjectNotFoundError for a missing article", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ article: { find } }); + + await expect(Article.get("missing")).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("ofId creates a reference without calling a behavior", () => { + const find = vi.fn(); + installBehaviors({ article: { find } }); + + const article = Article.ofId("a-3"); + + expect(article).toBeInstanceOf(Article); + expect(article).toBeInstanceOf(ReferenceModel); + expect(article.id).toBe("a-3"); + expect(find).not.toHaveBeenCalled(); + }); +}); + +describe("Article data", () => { + test("maps common values, tags, and price", () => { + const article = new ArticleDetailed( + buildArticleData({ + tags: [buildArticleTagData({ name: "featured" })], + description: "A useful article", + name: "Useful", + price: 1234, + }), + ); + + expect(article.price.getAmount()).toBe(1234); + expect(article.name).toBe("Useful"); + expect(article.description).toBe("A useful article"); + expect(article.tags[0]?.name).toBe("featured"); + expect(article.getTag("featured")).toBe(article.tags[0]); + expect(article.hasTag("featured")).toBe(true); + expect(article.hasTag("missing")).toBe(false); + }); + + test("finds optional and required attributes by class", () => { + const article = new ArticleDetailed( + buildArticleData({ + attributes: [buildArticleAttributeData({ key: "cpu", value: "2" })], + }), + ); + + expect(article.getAttribute(CpuArticleAttribute)).toBeInstanceOf( + CpuArticleAttribute, + ); + expect(article.getRequiredAttribute(CpuArticleAttribute)).toBeInstanceOf( + CpuArticleAttribute, + ); + expect(article.getAttribute(ArticleAttribute)).toBeInstanceOf( + ArticleAttribute, + ); + expect(() => + article.getRequiredAttribute(class Missing extends ArticleAttribute {}), + ).toThrow("Required attribute not found"); + }); + + test("finds optional and required modifiers by class", () => { + const article = new ArticleDetailed( + buildArticleData({ + modifierArticles: [ + buildArticleModifierData({ articleId: "additional-storage" }), + ], + }), + ); + + expect(article.getModifier(StorageArticleModifier)).toBeInstanceOf( + StorageArticleModifier, + ); + expect(article.getRequiredModifier(StorageArticleModifier)).toBeInstanceOf( + StorageArticleModifier, + ); + expect(() => + article.getRequiredModifier(class Missing extends ArticleModifier {}), + ).toThrow("Required modifier not found"); + }); + + test("combines an attribute value and unit", () => { + expect( + new ArticleAttribute( + buildArticleAttributeData({ unit: "GiB", value: "4" }), + ).valueWithUnit, + ).toBe("4GiB"); + expect( + new ArticleAttribute(buildArticleAttributeData({ value: "4" })) + .valueWithUnit, + ).toBe("4"); + }); + + test.each([ + ["cpu", "cpu"], + ["vcpu", "vcpu"], + ] as const)("derives CPU data for %s", (key, type) => { + const attribute = new CpuArticleAttribute( + buildArticleAttributeData({ value: "2", key }), + ); + + expect(attribute.cpuCount).toBe(2); + expect(attribute.type).toBe(type); + }); + + test("derives AI Hosting limits from attributes", async () => { + const find = vi.fn().mockResolvedValue( + buildArticleData({ + attributes: [ + buildArticleAttributeData({ key: "monthlyTokens", value: "1000" }), + buildArticleAttributeData({ + key: "requestsPerMinute", + value: "60", + }), + ], + template: buildArticleTemplateData({ name: "AI-Hosting" }), + }), + ); + installBehaviors({ article: { find } }); + + const article = await Article.find("ai"); + + expect(article).toBeInstanceOf(AIHostingArticle); + expect((article as AIHostingArticle).getMonthlyTokens()).toBe(1000); + expect((article as AIHostingArticle).getRequestsPerMinute()).toBe(60); + }); + + test("materializes modifier limits and article references", () => { + const article = new ArticleDetailed( + buildArticleData({ + modifierArticles: [ + buildArticleModifierData({ + articleId: "modifier-a", + maxArticleCount: 3, + }), + ], + }), + ); + + expect(article.modifiers[0]?.maxCount).toBe(3); + expect(article.modifiers[0]?.article).toBeInstanceOf(Article); + expect(article.modifiers[0]?.article.id).toBe("modifier-a"); + }); +}); + +describe("Article list query", () => { + test("applies the default pagination limit", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildArticleListItemData()], + totalCount: 1, + }); + installBehaviors({ article: { list } }); + + const result = await Article.query().execute(); + + expect(result).toBeInstanceOf(ArticleList); + expect(result.items[0]).toBeInstanceOf(ArticleListItem); + expect(result.totalCount).toBe(1); + expect(list).toHaveBeenCalledWith( + expect.objectContaining({ limit: config.defaultPaginationLimit }), + ); + }); + + test("uses an explicit pagination limit", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 0, items: [] }); + installBehaviors({ article: { list } }); + + await Article.query({ limit: 5 }).execute(); + + expect(list).toHaveBeenCalledWith(expect.objectContaining({ limit: 5 })); + }); + + test("materializes items and total count", async () => { + const list = vi.fn().mockResolvedValue({ + items: [ + buildArticleListItemData({ articleId: "a-1" }), + buildArticleListItemData({ articleId: "a-2" }), + ], + totalCount: 7, + }); + installBehaviors({ article: { list } }); + + const result = await Article.query().execute(); + + expect(result.items.map(({ id }) => id)).toEqual(["a-1", "a-2"]); + expect(result.items.every((item) => item instanceof ArticleListItem)).toBe( + true, + ); + expect(result.totalCount).toBe(7); + }); + + test("returns the lowest-priced item", async () => { + const list = vi.fn().mockResolvedValue({ + items: [ + buildArticleListItemData({ articleId: "high", price: 2000 }), + buildArticleListItemData({ articleId: "low", price: 500 }), + ], + totalCount: 2, + }); + installBehaviors({ article: { list } }); + + const result = await Article.query().getLowestPrice(); + + expect(result?.id).toBe("low"); + expect(result?.price.getAmount()).toBe(500); + }); + + test("returns no lowest-priced item for an empty result", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 0, items: [] }); + installBehaviors({ article: { list } }); + + expect(await Article.query().getLowestPrice()).toBeUndefined(); + }); + + test("gets the total count", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 42, items: [] }); + installBehaviors({ article: { list } }); + + expect(await Article.query().getTotalCount()).toBe(42); + }); + + test("refine merges query parameters into a new query", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 0, items: [] }); + installBehaviors({ article: { list } }); + const original = Article.query({ limit: 10 }); + + const refined = original.refine({ templateNames: ["unknown"] }); + await refined.execute(); + + expect(refined).toBeInstanceOf(ArticleListQuery); + expect(refined).not.toBe(original); + expect(list).toHaveBeenCalledWith( + expect.objectContaining({ templateNames: ["unknown"], limit: 10 }), + ); + }); + + test("find returns the item matching a predicate", async () => { + const list = vi.fn().mockResolvedValue({ + items: [ + buildArticleListItemData({ articleId: "a-1" }), + buildArticleListItemData({ articleId: "a-2" }), + ], + totalCount: 2, + }); + installBehaviors({ article: { list } }); + + const result = await Article.query().find(({ id }) => id === "a-2"); + + expect(result?.id).toBe("a-2"); + }); +}); + +describe("Article common variant", () => { + test("getCommon on a reference delegates to the behavior and materializes the common variant", async () => { + const find = vi + .fn() + .mockResolvedValue(buildArticleData({ articleId: "a-1" })); + installBehaviors({ article: { find } }); + + const result = await Article.ofId("a-1").getCommon(); + + expect(find).toHaveBeenCalledWith("a-1"); + expect(result).toBeInstanceOf(ArticleCommon); + expect(result.id).toBe("a-1"); + }); + + test("getCommon on a reference throws ObjectNotFoundError when not found", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ article: { find } }); + + await expect(Article.ofId("missing").getCommon()).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("findCommon on a reference delegates and returns the common variant when found", async () => { + const find = vi + .fn() + .mockResolvedValue(buildArticleData({ articleId: "a-2" })); + installBehaviors({ article: { find } }); + + const result = await Article.ofId("a-2").findCommon(); + + expect(find).toHaveBeenCalledWith("a-2"); + expect(result).toBeInstanceOf(ArticleCommon); + expect(result?.id).toBe("a-2"); + }); + + test("findCommon on a reference throws ObjectNotFoundError when not found (delegates via get)", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ article: { find } }); + + await expect(Article.ofId("missing").findCommon()).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); +}); + +describe("Article variant idempotency", () => { + test("getCommon on an already-materialized common model returns itself without calling a behavior", async () => { + const find = vi.fn(); + installBehaviors({ article: { find } }); + const detailed = new ArticleDetailed( + buildArticleData({ articleId: "a-3" }), + ); + + const result = await detailed.getCommon(); + + expect(result).toBe(detailed); + expect(find).not.toHaveBeenCalled(); + }); + + test("findCommon on an already-materialized common model returns itself without calling a behavior", async () => { + const find = vi.fn(); + installBehaviors({ article: { find } }); + const detailed = new ArticleDetailed( + buildArticleData({ articleId: "a-3" }), + ); + + const result = await detailed.findCommon(); + + expect(result).toBe(detailed); + expect(find).not.toHaveBeenCalled(); + }); + + test("getCommon on a list item returns the list item itself without calling a behavior", async () => { + const find = vi.fn(); + installBehaviors({ article: { find } }); + const listItem = new ArticleListItem( + buildArticleListItemData({ articleId: "a-4" }), + ); + + expect(await listItem.getCommon()).toBe(listItem); + expect(find).not.toHaveBeenCalled(); + }); +}); + +describe("Article absent optional data", () => { + test("defaults derived collections to empty arrays when source data is absent", () => { + const article = new ArticleDetailed( + buildArticleData({ + modifierArticles: undefined, + attributes: undefined, + tags: undefined, + }), + ); + + expect(article.attributes).toEqual([]); + expect(article.modifiers).toEqual([]); + expect(article.tags).toEqual([]); + }); + + test("leaves optional scalar fields undefined when absent", () => { + const article = new ArticleDetailed( + buildArticleData({ + forcedInvoicingPeriodInMonth: undefined, + hasIndependentContractPeriod: undefined, + hideOnInvoice: undefined, + description: undefined, + }), + ); + + expect(article.description).toBeUndefined(); + expect(article.forcedInvoicingPeriodInMonth).toBeUndefined(); + expect(article.hideOnInvoice).toBeUndefined(); + expect(article.hasIndependentContractPeriod).toBeUndefined(); + }); + + test("returns undefined for an attribute type that is not present", () => { + const article = new ArticleDetailed(buildArticleData({ attributes: [] })); + + expect(article.getAttribute(CpuArticleAttribute)).toBeUndefined(); + }); + + test("returns undefined for a modifier type that is not present", () => { + const article = new ArticleDetailed( + buildArticleData({ modifierArticles: [] }), + ); + + expect(article.getModifier(StorageArticleModifier)).toBeUndefined(); + }); + + test("returns undefined for a tag that is not present", () => { + const article = new ArticleDetailed(buildArticleData({ tags: [] })); + + expect(article.getTag("missing")).toBeUndefined(); + }); +}); diff --git a/packages/models/src/article/Article/Article.ts b/packages/models/src/article/Article/Article.ts index 16615187..2e60ad8e 100644 --- a/packages/models/src/article/Article/Article.ts +++ b/packages/models/src/article/Article/Article.ts @@ -1,73 +1,166 @@ -import { ReferenceModel } from "../../base/ReferenceModel.js"; -import { - ArticleData, - ArticleListItemData, - ArticleListQueryData, +import type { Constructor } from "type-fest"; + +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import invariant from "tiny-invariant"; + +import type { ArticleListQueryModelData, + ArticleListItemData, + ArticleData, } from "./types.js"; -import { config } from "../../config/config.js"; -import { classes } from "polytype"; -import { DataModel } from "../../base/DataModel.js"; -import assertObjectFound from "../../base/assertObjectFound.js"; -import { provideReact } from "../../react/provideReact.js"; -import { ListQueryModel } from "../../base/ListQueryModel.js"; -import { ListDataModel } from "../../base/ListDataModel.js"; -import { Money } from "../../base/Money.js"; +import { articleAttributeFactory } from "./attributes/articleAttributeFactory.js"; +import { articleTemplateFactory } from "./templates/articleTemplateFactory.js"; +import { articleModifierFactory } from "./modifier/articleModifierFactory.js"; +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { ArticleTemplate } from "./ArticleTemplate.js"; +import { articleFactory } from "./internal.js"; +import { config } from "../../config/index.js"; +import { Money } from "../../common/index.js"; +import { + type ArticleAttribute, + type ArticleModifier, + type ArticleTagName, + ArticleTag, +} from "./internal.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "Article", +}) export class Article extends ReferenceModel { - public static ofId(id: string): Article { - return new Article(id); - } + public static async find(id: string) { + const data = await config.behaviors.article.find(id); - public static find = provideReact( - async (id: string): Promise => { - const data = await config.behaviors.article.find(id); + if (data) { + return articleFactory(new ArticleDetailed(data)); + } + } - if (data !== undefined) { - return new ArticleDetailed(data); - } - }, - ); + public static async get(id: string) { + const article = await Article.find(id); + assertObjectFound(article, Article, id); + return article; + } - public static get = provideReact( - async (id: string): Promise => { - const article = await this.find(id); - assertObjectFound(article, this, id); - return article; - }, - ); + public static ofId(id: string) { + return new Article(id); + } public static query(query: ArticleListQueryModelData = {}) { return new ArticleListQuery(query); } + + public async findCommon(): Promise { + return this instanceof ArticleCommon ? this : this.findDetailed(); + } + + public findDetailed(): Promise { + return Article.get(this.id); + } + + public async getCommon(): Promise { + return this instanceof ArticleCommon ? this : this.getDetailed(); + } + + public async getDetailed(): Promise { + return await Article.get(this.id); + } } -class ArticleCommon extends classes( - DataModel, - Article, -) { +export class ArticleCommon extends WithData< + ArticleListItemData | ArticleData +>()(Article) { + public readonly attributes: ArticleAttribute[]; + public readonly contractDurationInMonth: number; + public override readonly data: ArticleListItemData | ArticleData; + public readonly description?: string; + public readonly forcedInvoicingPeriodInMonth?: number; + public readonly hasIndependentContractPeriod?: boolean; + public readonly hideOnInvoice?: boolean; + public readonly modifiers: ArticleModifier[]; + public readonly name: string; + public readonly orderable: (ArticleListItemData | ArticleData)["orderable"]; public readonly price: Money; + public readonly tags: ArticleTag[]; + public readonly template: ArticleTemplate; + public constructor(data: ArticleListItemData | ArticleData) { - super([data]); + super(data.articleId); + this.data = data; + this.modifiers = + data.modifierArticles?.map((m) => articleModifierFactory(m)) ?? []; + this.attributes = + data.attributes?.map((attr) => articleAttributeFactory(attr)) ?? []; + this.tags = data.tags?.map((t) => new ArticleTag(t)) ?? []; this.price = Money({ amount: data.price, currency: "EUR" }); + this.description = data.description; + this.orderable = data.orderable; + this.name = data.name; + this.template = articleTemplateFactory(new ArticleTemplate(data.template)); + this.contractDurationInMonth = data.contractDurationInMonth; + this.forcedInvoicingPeriodInMonth = data.forcedInvoicingPeriodInMonth; + this.hideOnInvoice = data.hideOnInvoice; + this.hasIndependentContractPeriod = data.hasIndependentContractPeriod; + } + + public getAttribute( + type: Constructor, + ): T | undefined { + return this.attributes.find((attr) => attr instanceof type) as + T | undefined; + } + + public getModifier( + type: Constructor, + ): T | undefined { + return this.modifiers.find((attr) => attr instanceof type) as T | undefined; + } + + public getRequiredAttribute( + type: Constructor, + ): T { + const attribute = this.getAttribute(type); + invariant(!!attribute, `Required attribute not found: ${type.name}`); + return attribute; + } + + public getRequiredModifier( + type: Constructor, + ): T { + const modifier = this.getModifier(type); + invariant(!!modifier, `Required modifier not found: ${type.name}`); + return modifier; + } + + public getTag(name: ArticleTagName | string) { + return this.tags.find((tag) => tag.name === name); + } + + public hasTag(name: ArticleTagName | string) { + return !!this.getTag(name); } } -export class ArticleDetailed extends classes( - ArticleCommon, - DataModel, -) { +export class ArticleDetailed extends ArticleCommon { + public override readonly data: ArticleData; public constructor(data: ArticleData) { - super([data], [data]); + super(data); + this.data = data; } } -export class ArticleListItem extends classes( - ArticleCommon, - DataModel, -) { +export class ArticleListItem extends ArticleCommon { + public override readonly data: ArticleListItemData; public constructor(data: ArticleListItemData) { - super([data]); + super(data); + this.data = data; } } @@ -76,49 +169,64 @@ export class ArticleListQuery extends ListQueryModel super(query); } - public refine(query: ArticleListQueryModelData) { - return new ArticleListQuery({ - ...this.query, - ...query, - }); - } + public async execute() { + const { customer, ...query } = this.query; - public execute = provideReact(async () => { - const { ...query } = this.query; - const { items, totalCount } = await config.behaviors.article.list({ + const { totalCount, items } = await config.behaviors.article.list({ limit: config.defaultPaginationLimit, ...query, + customerId: extractId(customer), }); return new ArticleList( this.query, - items.map((d) => new ArticleListItem(d)), + items.map((d) => articleFactory(new ArticleListItem(d))), totalCount, ); - }, [this.queryId]); + } + + public readonly find = async ( + predicate: (item: ArticleListItem) => boolean, + ) => { + const { items } = await this.execute(); + return items.find(predicate); + }; + + public async getLowestPrice() { + const { totalCount, items } = await this.execute(); + + if (totalCount === 0) return undefined; - public getTotalCount = provideReact(async () => { + return [...items].sort( + (a, b) => a.price.getAmount() - b.price.getAmount(), + )[0]; + } + + public async getTotalCount() { const { totalCount } = await this.refine({ limit: 1 }).execute(); return totalCount; - }, [this.queryId]); + } - public findOneAndOnly = provideReact(async () => { - const { items, totalCount } = await this.refine({ limit: 1 }).execute(); - if (totalCount === 1) { - return items[0]; - } - }, [this.queryId]); + public refine(query: ArticleListQueryModelData) { + return new ArticleListQuery({ + ...this.query, + ...query, + }); + } } -export class ArticleList extends classes( +export class ArticleList extends WithListData()( ArticleListQuery, - ListDataModel, ) { + public override readonly items: readonly ArticleListItem[]; + public override readonly totalCount: number; public constructor( - query: ArticleListQueryData, + query: ArticleListQueryModelData, articles: ArticleListItem[], totalCount: number, ) { - super([query], [articles, totalCount]); + super(query); + this.items = Object.freeze(articles); + this.totalCount = totalCount; } } diff --git a/packages/models/src/article/Article/ArticleAttribute.ts b/packages/models/src/article/Article/ArticleAttribute.ts new file mode 100644 index 00000000..82ec81bc --- /dev/null +++ b/packages/models/src/article/Article/ArticleAttribute.ts @@ -0,0 +1,20 @@ +import type { ArticleAttributeData } from "./types.js"; + +import { DataModel } from "../../base/index.js"; + +export class ArticleAttribute extends DataModel { + public readonly key: string; + public readonly unit?: string; + public readonly value?: string; + public readonly valueWithUnit: string; + + public constructor(data: ArticleAttributeData) { + super(data); + this.key = data.key; + this.unit = data.unit; + this.value = data.value; + this.valueWithUnit = + (data.unit === undefined ? data.value : `${data.value}${data.unit}`) ?? + ""; + } +} diff --git a/packages/models/src/article/Article/ArticleModifier.ts b/packages/models/src/article/Article/ArticleModifier.ts new file mode 100644 index 00000000..7ff309bd --- /dev/null +++ b/packages/models/src/article/Article/ArticleModifier.ts @@ -0,0 +1,18 @@ +import type { ArticleModifierData } from "./types.js"; + +import { DataModel } from "../../base/index.js"; +import { Article } from "./internal.js"; + +export class ArticleModifier extends DataModel { + public readonly article: Article; + public readonly maxCount: number; + + public constructor(data: ArticleModifierData) { + super(data); + const { maxArticleCount, articleId } = data; + this.article = Article.ofId(articleId); + this.maxCount = maxArticleCount; + } +} + +export default ArticleModifier; diff --git a/packages/models/src/article/Article/ArticleTag.ts b/packages/models/src/article/Article/ArticleTag.ts new file mode 100644 index 00000000..42b528e2 --- /dev/null +++ b/packages/models/src/article/Article/ArticleTag.ts @@ -0,0 +1,28 @@ +import type { ArticleTagData } from "./types.js"; + +import { DataModel } from "../../base/index.js"; + +export enum ArticleTagName { + balancedOptimized = "balance-optimized", + ramOptimized = "ram-optimized", + cpuOptimized = "cpu-optimized", + proSpaceLite = "ps-basic", + dedicated = "dedicated", + proSpace = "ps-plus", + vServer = "vserver", +} + +export class ArticleTag extends DataModel { + public readonly description?: string; + public readonly hexColor?: string; + public readonly id: string; + public readonly name?: string; + + public constructor(data: ArticleTagData) { + super(data); + this.id = data.id; + this.name = data.name; + this.description = data.description; + this.hexColor = data.hexColor; + } +} diff --git a/packages/models/src/article/Article/ArticleTemplate.ts b/packages/models/src/article/Article/ArticleTemplate.ts new file mode 100644 index 00000000..d7c32756 --- /dev/null +++ b/packages/models/src/article/Article/ArticleTemplate.ts @@ -0,0 +1,14 @@ +import { type ArticleTemplateData } from "./types.js"; +import { DataModel } from "../../base/index.js"; + +export class ArticleTemplate extends DataModel { + public static readonly templateName: string = "unknown"; + public readonly id: string; + public readonly name: string; + + public constructor(data: ArticleTemplateData) { + super(data); + this.id = data.id; + this.name = data.name; + } +} diff --git a/packages/models/src/article/Article/articles/AIHostingArticle.ts b/packages/models/src/article/Article/articles/AIHostingArticle.ts new file mode 100644 index 00000000..91fa2bdc --- /dev/null +++ b/packages/models/src/article/Article/articles/AIHostingArticle.ts @@ -0,0 +1,33 @@ +import { AIHostingArticleTemplate } from "../templates/AIHostingArticleTemplate.js"; +import { ArticleCommon, Article } from "../internal.js"; + +export class AIHostingArticle extends ArticleCommon { + public static async getArticleWithLowestPrice() { + const articles = await this.getOrderableArticles().execute(); + + if (articles.items.length === 0) return undefined; + + return Array.from(articles.items).sort((a, b) => + a.price.lessThan(b.price) ? -1 : a.price.greaterThan(b.price) ? 1 : 0, + )[0]; + } + + public static getOrderableArticles() { + return Article.query({ + templateNames: [AIHostingArticleTemplate.templateName], + orderable: ["deprecated", "full"], + }); + } + + public getMonthlyTokens(): number { + const tokenLimit = + this.attributes.find((a) => a.key === "monthlyTokens")?.value ?? "0"; + return parseInt(tokenLimit, 10); + } + + public getRequestsPerMinute(): number { + const rpmLimit = + this.attributes.find((a) => a.key === "requestsPerMinute")?.value ?? "0"; + return parseInt(rpmLimit, 10); + } +} diff --git a/packages/models/src/article/Article/articles/HostingArticle.ts b/packages/models/src/article/Article/articles/HostingArticle.ts new file mode 100644 index 00000000..9cfc7187 --- /dev/null +++ b/packages/models/src/article/Article/articles/HostingArticle.ts @@ -0,0 +1,77 @@ +import invariant from "tiny-invariant"; + +import type { ArticleType } from "../types.js"; + +import { HardwareSpecs } from "../../../project/internal.js"; +import { Bytes } from "../../../common/index.js"; +import { + StorageArticleAttribute, + StorageArticleModifier, + ArticleCommon, + ServerArticle, + type Article, +} from "../internal.js"; + +export abstract class HostingArticle extends ArticleCommon { + public get baseStorageAttribute(): StorageArticleAttribute { + return this.getRequiredAttribute(StorageArticleAttribute); + } + + // Stateless lazy getters: computed on access (never in the constructor) + // because getRequired*() throws when the attribute is absent and these facets + // are only conditionally valid per article subtype. See implementation-patterns. + public get hardwareSpecs(): HardwareSpecs { + return HardwareSpecs.fromArticle(this); + } + + public get storageModifier(): StorageArticleModifier { + return this.getRequiredModifier(StorageArticleModifier); + } + + public static assert(article: Article): asserts article is HostingArticle { + invariant( + article instanceof HostingArticle, + "Expected article to be an instance of HostingArticle", + ); + } + + public getDefaultStorageOption( + articleType: ArticleType, + storageModifierBytes: Bytes, + ) { + const storageOptions = this.getStorageOptions(storageModifierBytes); + + if (articleType === "vServer" || articleType === "webhosting") { + return storageOptions[1]?.gib ?? storageOptions[0].gib; + } + + return storageOptions[0].gib; + } + + public getRecommendedStorageFromArticle(): string | undefined { + if (this.isOfType(ServerArticle)) { + return this.machineTypeSpecs.getRecommendedStorage(); + } + return this.hardwareSpecs.getRecommendedStorage(); + } + + public getStorageOptions(storageModifierBytes: Bytes): [Bytes, ...Bytes[]] { + const modifierBytes = this.getModifierBytes(); + + modifierBytes.forEach((gb) => { + invariant( + (gb - this.baseStorageAttribute.bytes.gib) % + storageModifierBytes.gib === + 0, + `must be a multiple of ${storageModifierBytes.gib}`, + ); + }); + + return [ + this.baseStorageAttribute.bytes, + ...modifierBytes.map((s) => Bytes.of(s, "GiB")), + ]; + } + + protected abstract getModifierBytes(): number[]; +} diff --git a/packages/models/src/article/Article/articles/ServerArticle.ts b/packages/models/src/article/Article/articles/ServerArticle.ts new file mode 100644 index 00000000..e1960cfe --- /dev/null +++ b/packages/models/src/article/Article/articles/ServerArticle.ts @@ -0,0 +1,66 @@ +import { SpaceServerArticleTemplate } from "../templates/SpaceServerArticleTemplate.js"; +import { ProSpaceArticleTemplate } from "../templates/ProSpaceArticleTemplate.js"; +import { ServerArticleTemplate } from "../templates/ServerArticleTemplate.js"; +import { MachineTypeSpecs } from "../../../project/internal.js"; +import { + RecommendedProjectsArticleAttribute, + ArticleTagName, + HostingArticle, + Article, +} from "../internal.js"; + +export class ServerArticle extends HostingArticle { + public get isProSpace(): boolean { + return this.template instanceof ProSpaceArticleTemplate; + } + + public get machineTypeSpecs(): MachineTypeSpecs { + return MachineTypeSpecs.fromArticle(this); + } + + public static readonly getOrderableArticles = ( + dedicated: boolean, + proSpace = false, + ) => { + const tags = dedicated + ? [ArticleTagName.dedicated] + : proSpace + ? [ArticleTagName.proSpace] + : [ArticleTagName.vServer]; + + return Article.query({ + templateNames: [ + (proSpace ? ProSpaceArticleTemplate : ServerArticleTemplate) + .templateName, + ], + orderable: ["deprecated", "full"], + ...{ tags }, + }); + }; + + public static readonly getRecommendedProjects = ( + article: ServerArticle, + ): string | undefined => { + return article.getAttribute(RecommendedProjectsArticleAttribute)?.value; + }; + + protected getModifierBytes(): number[] { + if (this.template instanceof ServerArticleTemplate) { + if (this.hasTag(ArticleTagName.dedicated)) { + return [300, 500, 850, 1500, 2000, 2500]; + } else { + return [100, 150, 300, 500, 850, 1500, 2000]; + } + } + + if (this.template instanceof SpaceServerArticleTemplate) { + return [100, 150, 300, 500, 850, 1500, 2000]; + } + + if (this.template instanceof ProSpaceArticleTemplate) { + return [40, 60, 100, 200, 300, 400, 500]; + } + + return []; + } +} diff --git a/packages/models/src/article/Article/articles/StorageArticle.ts b/packages/models/src/article/Article/articles/StorageArticle.ts new file mode 100644 index 00000000..5734f01b --- /dev/null +++ b/packages/models/src/article/Article/articles/StorageArticle.ts @@ -0,0 +1,21 @@ +import invariant from "tiny-invariant"; + +import type { Bytes } from "../../../common/index.js"; + +import { StorageArticleAttribute, ArticleCommon } from "../internal.js"; + +export class StorageArticle extends ArticleCommon { + public get bytes(): Bytes { + const storageAttribute = this.getAttribute(StorageArticleAttribute); + invariant(!!storageAttribute, "Storage attribute not found in article"); + return storageAttribute.bytes; + } + + public static refine(article: ArticleCommon) { + if (article.id.endsWith("-Storage")) { + return new StorageArticle(article.data); + } + } +} + +export default StorageArticle; diff --git a/packages/models/src/article/Article/articles/WebhostingArticle.ts b/packages/models/src/article/Article/articles/WebhostingArticle.ts new file mode 100644 index 00000000..93a60067 --- /dev/null +++ b/packages/models/src/article/Article/articles/WebhostingArticle.ts @@ -0,0 +1,25 @@ +import { WebhostingArticleTemplate } from "../templates/WebhostingArticleTemplate.js"; +import { HostingArticle, Article } from "../internal.js"; + +export class WebhostingArticle extends HostingArticle { + public static async getArticleWithLowestPrice() { + const articles = await this.getOrderableArticles().execute(); + + if (articles.items.length === 0) return undefined; + + return Array.from(articles.items).sort((a, b) => + a.price.lessThan(b.price) ? -1 : a.price.greaterThan(b.price) ? 1 : 0, + )[0]; + } + + public static getOrderableArticles() { + return Article.query({ + templateNames: [WebhostingArticleTemplate.templateName], + orderable: ["deprecated", "full"], + }); + } + + protected getModifierBytes(): number[] { + return [40, 60, 80, 100]; + } +} diff --git a/packages/models/src/article/Article/articles/articleFactory.ts b/packages/models/src/article/Article/articles/articleFactory.ts new file mode 100644 index 00000000..3052f430 --- /dev/null +++ b/packages/models/src/article/Article/articles/articleFactory.ts @@ -0,0 +1,40 @@ +import { SpaceServerArticleTemplate } from "../templates/SpaceServerArticleTemplate.js"; +import { WebhostingArticleTemplate } from "../templates/WebhostingArticleTemplate.js"; +import { AIHostingArticleTemplate } from "../templates/AIHostingArticleTemplate.js"; +import { ProSpaceArticleTemplate } from "../templates/ProSpaceArticleTemplate.js"; +import { StorageArticleTemplate } from "../templates/StorageArticleTemplate.js"; +import { ServerArticleTemplate } from "../templates/ServerArticleTemplate.js"; +import { + WebhostingArticle, + AIHostingArticle, + ServerArticle, +} from "../internal.js"; +import { + type ArticleCommon, + ArticleTagName, + StorageArticle, +} from "../internal.js"; + +export const articleFactory = (article: ArticleCommon) => { + if ( + article.template.name === ProSpaceArticleTemplate.templateName && + article.hasTag(ArticleTagName.proSpaceLite) + ) { + return new WebhostingArticle(article.data); + } + + switch (article.template.name) { + case SpaceServerArticleTemplate.templateName: + case ProSpaceArticleTemplate.templateName: + case ServerArticleTemplate.templateName: + return new ServerArticle(article.data); + case WebhostingArticleTemplate.templateName: + return new WebhostingArticle(article.data); + case AIHostingArticleTemplate.templateName: + return new AIHostingArticle(article.data); + case StorageArticleTemplate.templateName: + return new StorageArticle(article.data); + default: + return article; + } +}; diff --git a/packages/models/src/article/Article/attributes/CpuArticleAttribute.ts b/packages/models/src/article/Article/attributes/CpuArticleAttribute.ts new file mode 100644 index 00000000..8b666c51 --- /dev/null +++ b/packages/models/src/article/Article/attributes/CpuArticleAttribute.ts @@ -0,0 +1,27 @@ +import invariant from "tiny-invariant"; + +import type { ArticleAttributeData } from "../types.js"; + +import { ArticleAttribute } from "../internal.js"; + +export class CpuArticleAttribute extends ArticleAttribute { + public readonly cpuCount: number; + public readonly type: "vcpu" | "cpu"; + + public constructor(data: ArticleAttributeData) { + super(data); + this.cpuCount = this.constructCpu(); + this.type = data.key === "cpu" ? "cpu" : "vcpu"; + } + + private constructCpu(): number { + const cpuValue = parseInt(this.value ?? ""); + invariant( + !isNaN(cpuValue) && String(cpuValue) === this.value, + "CPU value must be a valid number", + ); + return cpuValue; + } +} + +export default CpuArticleAttribute; diff --git a/packages/models/src/article/Article/attributes/MachineTypeArticleAttribute.ts b/packages/models/src/article/Article/attributes/MachineTypeArticleAttribute.ts new file mode 100644 index 00000000..fbacb740 --- /dev/null +++ b/packages/models/src/article/Article/attributes/MachineTypeArticleAttribute.ts @@ -0,0 +1,20 @@ +import invariant from "tiny-invariant"; + +import type { ArticleAttributeData } from "../types.js"; + +import { ArticleAttribute } from "../internal.js"; + +export class MachineTypeArticleAttribute extends ArticleAttribute { + public readonly machineType: string; + + public constructor(data: ArticleAttributeData) { + super(data); + invariant( + data.value !== undefined, + "MachineTypeArticleAttribute requires a value", + ); + this.machineType = data.value; + } +} + +export default MachineTypeArticleAttribute; diff --git a/packages/models/src/article/Article/attributes/RamArticleAttribute.ts b/packages/models/src/article/Article/attributes/RamArticleAttribute.ts new file mode 100644 index 00000000..734f4d8e --- /dev/null +++ b/packages/models/src/article/Article/attributes/RamArticleAttribute.ts @@ -0,0 +1,15 @@ +import type { ArticleAttributeData } from "../types.js"; + +import { ArticleAttribute } from "../internal.js"; +import { Bytes } from "../../../common/index.js"; + +export class RamArticleAttribute extends ArticleAttribute { + public readonly bytes: Bytes; + + public constructor(data: ArticleAttributeData) { + super(data); + this.bytes = Bytes.parse(this.valueWithUnit); + } +} + +export default RamArticleAttribute; diff --git a/packages/models/src/article/Article/attributes/RecommendedProjectsArticleAttribute.ts b/packages/models/src/article/Article/attributes/RecommendedProjectsArticleAttribute.ts new file mode 100644 index 00000000..0ee7ee52 --- /dev/null +++ b/packages/models/src/article/Article/attributes/RecommendedProjectsArticleAttribute.ts @@ -0,0 +1,11 @@ +import type { ArticleAttributeData } from "../types.js"; + +import { ArticleAttribute } from "../internal.js"; + +export class RecommendedProjectsArticleAttribute extends ArticleAttribute { + public constructor(data: ArticleAttributeData) { + super(data); + } +} + +export default RecommendedProjectsArticleAttribute; diff --git a/packages/models/src/article/Article/attributes/StorageArticleAttribute.ts b/packages/models/src/article/Article/attributes/StorageArticleAttribute.ts new file mode 100644 index 00000000..abab9dff --- /dev/null +++ b/packages/models/src/article/Article/attributes/StorageArticleAttribute.ts @@ -0,0 +1,18 @@ +import invariant from "tiny-invariant"; + +import type { ArticleAttributeData } from "../types.js"; + +import { ArticleAttribute } from "../internal.js"; +import { Bytes } from "../../../common/index.js"; + +export class StorageArticleAttribute extends ArticleAttribute { + public readonly bytes: Bytes; + + public constructor(data: ArticleAttributeData) { + super(data); + invariant(!!this.unit, "Storage article attribute must have a unit"); + this.bytes = Bytes.parse(this.valueWithUnit); + } +} + +export default StorageArticleAttribute; diff --git a/packages/models/src/article/Article/attributes/TldAttribute.ts b/packages/models/src/article/Article/attributes/TldAttribute.ts new file mode 100644 index 00000000..d2f6cf7f --- /dev/null +++ b/packages/models/src/article/Article/attributes/TldAttribute.ts @@ -0,0 +1,16 @@ +import invariant from "tiny-invariant"; + +import type { ArticleAttributeData } from "../types.js"; + +import { ArticleAttribute } from "../internal.js"; + +export class TldAttribute extends ArticleAttribute { + public readonly tld: string; + + public constructor(data: ArticleAttributeData) { + super(data); + invariant(!!this.value, "TLD article attribute must have a value"); + this.tld = this.value; + } +} +export default TldAttribute; diff --git a/packages/models/src/article/Article/attributes/articleAttributeFactory.ts b/packages/models/src/article/Article/attributes/articleAttributeFactory.ts new file mode 100644 index 00000000..61a65965 --- /dev/null +++ b/packages/models/src/article/Article/attributes/articleAttributeFactory.ts @@ -0,0 +1,40 @@ +import type { ArticleAttributeData } from "../types.js"; + +import { TldAttribute } from "./TldAttribute.js"; +import { + RecommendedProjectsArticleAttribute, + MachineTypeArticleAttribute, + StorageArticleAttribute, + CpuArticleAttribute, + RamArticleAttribute, + ArticleAttribute, +} from "../internal.js"; + +export const articleAttributeFactory = ( + articleAttribute: ArticleAttributeData | ArticleAttribute, +) => { + const data = + articleAttribute instanceof ArticleAttribute + ? articleAttribute.data + : articleAttribute; + + switch (articleAttribute.key) { + case "recommended_projects": + return new RecommendedProjectsArticleAttribute(data); + case "spec.machine_type": + return new MachineTypeArticleAttribute(data); + case "machine_type": + return new MachineTypeArticleAttribute(data); + case "toplevel": + return new TldAttribute(data); + case "storage": + return new StorageArticleAttribute(data); + case "vcpu": + case "cpu": + return new CpuArticleAttribute(data); + case "ram": + return new RamArticleAttribute(data); + default: + return new ArticleAttribute(data); + } +}; diff --git a/packages/models/src/article/Article/behaviors/api.ts b/packages/models/src/article/Article/behaviors/api.ts index 73319d3e..d0f06602 100644 --- a/packages/models/src/article/Article/behaviors/api.ts +++ b/packages/models/src/article/Article/behaviors/api.ts @@ -1,32 +1,32 @@ -import { ArticleBehaviors } from "./types.js"; -import { - MittwaldAPIV2Client, - assertStatus, - extractTotalCountHeader, -} from "@mittwald/api-client"; +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { ArticleBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount } from "../../../base/index.js"; export const apiArticleBehaviors = ( client: MittwaldAPIV2Client, ): ArticleBehaviors => ({ - find: async (id) => { - const response = await client.article.getArticle({ - articleId: id, - }); - - if (response.status === 200) { - return response.data; - } - assertStatus(response, 404); - }, - list: async (query) => { const response = await client.article.listArticles({ queryParameters: query, }); - assertStatus(response, 200); + validateResponse(response, 200); return { + totalCount: resolveTotalCount(response), items: response.data, - totalCount: extractTotalCountHeader(response), }; }, + + find: async (articleId) => { + const response = await client.article.getArticle({ + articleId, + }); + + if (response.status === 200) { + return response.data; + } + validateResponse(response, 404); + }, }); diff --git a/packages/models/src/article/Article/behaviors/types.ts b/packages/models/src/article/Article/behaviors/types.ts index 10014226..8f35e26d 100644 --- a/packages/models/src/article/Article/behaviors/types.ts +++ b/packages/models/src/article/Article/behaviors/types.ts @@ -1,13 +1,13 @@ -import { - ArticleData, - ArticleListItemData, +import type { QueryResponseData } from "../../../base/index.js"; +import type { ArticleListQueryData, + ArticleListItemData, + ArticleData, } from "../types.js"; -import { QueryResponseData } from "../../../base/index.js"; export interface ArticleBehaviors { - find: (id: string) => Promise; list: ( query?: ArticleListQueryData, ) => Promise>; + find: (articleId: string) => Promise; } diff --git a/packages/models/src/article/Article/index.ts b/packages/models/src/article/Article/index.ts index 32549924..d429e984 100644 --- a/packages/models/src/article/Article/index.ts +++ b/packages/models/src/article/Article/index.ts @@ -1,2 +1,27 @@ -export * from "./Article.js"; +export { + AIHostingArticle, + Article, + ArticleCommon, + ArticleDetailed, + ArticleList, + ArticleListItem, + ArticleListQuery, + ArticleTagName, + HostingArticle, + RecommendedProjectsArticleAttribute, + ServerArticle, + StorageArticle, + StorageArticleAttribute, + StorageArticleModifier, + WebhostingArticle, +} from "./internal.js"; +export * from "./templates/AIHostingArticleTemplate.js"; +export * from "./templates/DomainArticleTemplate.js"; +export * from "./templates/LeadFyndrArticleTemplate.js"; +export * from "./templates/ProSpaceArticleTemplate.js"; +export * from "./templates/ServerArticleTemplate.js"; +export * from "./templates/SpaceServerArticleTemplate.js"; +export * from "./templates/StorageArticleTemplate.js"; +export * from "./templates/Typo3LicenseArticleTemplate.js"; +export * from "./templates/WebhostingArticleTemplate.js"; export * from "./types.js"; diff --git a/packages/models/src/article/Article/internal.ts b/packages/models/src/article/Article/internal.ts new file mode 100644 index 00000000..84967a55 --- /dev/null +++ b/packages/models/src/article/Article/internal.ts @@ -0,0 +1,26 @@ +// Hand-ordered internal-module barrel — do not reorder or alphabetize. +// See docs/implementation-patterns.md › "internal.ts — the internal-module pattern". +// +// Order is TOPOLOGICAL (a dependency must be listed before whatever extends it +// at load time). `Article.ts` force-loads the attribute/modifier factories at +// import time, whose classes `extends ArticleAttribute` / `extends +// ArticleModifier` — so those two bases MUST come before `Article`. The article +// subclasses `extends ArticleCommon`/`HostingArticle`, so they come after +// `Article` (and `HostingArticle` before the articles that extend it), with +// `articleFactory` (imports every article) last. +export * from "./ArticleAttribute.js"; +export * from "./attributes/CpuArticleAttribute.js"; +export * from "./attributes/MachineTypeArticleAttribute.js"; +export * from "./attributes/RamArticleAttribute.js"; +export * from "./attributes/RecommendedProjectsArticleAttribute.js"; +export * from "./attributes/StorageArticleAttribute.js"; +export * from "./ArticleModifier.js"; +export * from "./modifier/StorageArticleModifier.js"; +export * from "./ArticleTag.js"; +export * from "./Article.js"; +export * from "./articles/AIHostingArticle.js"; +export * from "./articles/HostingArticle.js"; +export * from "./articles/ServerArticle.js"; +export * from "./articles/StorageArticle.js"; +export * from "./articles/WebhostingArticle.js"; +export * from "./articles/articleFactory.js"; diff --git a/packages/models/src/article/Article/modifier/StorageArticleModifier.ts b/packages/models/src/article/Article/modifier/StorageArticleModifier.ts new file mode 100644 index 00000000..7def92d8 --- /dev/null +++ b/packages/models/src/article/Article/modifier/StorageArticleModifier.ts @@ -0,0 +1,16 @@ +import type { Bytes } from "../../../common/index.js"; + +import { ArticleModifier, StorageArticle } from "../internal.js"; + +export class StorageArticleModifier extends ArticleModifier { + public async getBytes() { + const article = await this.article.getCommon(); + return article.asType(StorageArticle).bytes; + } + + public getMaxBytes(storageModifierBytes: Bytes) { + return storageModifierBytes.multiply(this.maxCount); + } +} + +export default StorageArticleModifier; diff --git a/packages/models/src/article/Article/modifier/articleModifierFactory.ts b/packages/models/src/article/Article/modifier/articleModifierFactory.ts new file mode 100644 index 00000000..f61c2fba --- /dev/null +++ b/packages/models/src/article/Article/modifier/articleModifierFactory.ts @@ -0,0 +1,10 @@ +import type { ArticleModifierData } from "../types.js"; + +import { StorageArticleModifier, ArticleModifier } from "../internal.js"; + +export const articleModifierFactory = (data: ArticleModifierData) => { + if (data.articleId.toLowerCase().endsWith("-storage")) { + return new StorageArticleModifier(data); + } + return new ArticleModifier(data); +}; diff --git a/packages/models/src/article/Article/templates/AIHostingArticleTemplate.ts b/packages/models/src/article/Article/templates/AIHostingArticleTemplate.ts new file mode 100644 index 00000000..0a4a367c --- /dev/null +++ b/packages/models/src/article/Article/templates/AIHostingArticleTemplate.ts @@ -0,0 +1,5 @@ +import { ArticleTemplate } from "../ArticleTemplate.js"; + +export class AIHostingArticleTemplate extends ArticleTemplate { + public static readonly templateName = "AI-Hosting"; +} diff --git a/packages/models/src/article/Article/templates/DomainArticleTemplate.ts b/packages/models/src/article/Article/templates/DomainArticleTemplate.ts new file mode 100644 index 00000000..1b0d8c9f --- /dev/null +++ b/packages/models/src/article/Article/templates/DomainArticleTemplate.ts @@ -0,0 +1,5 @@ +import { ArticleTemplate } from "../ArticleTemplate.js"; + +export class DomainArticleTemplate extends ArticleTemplate { + public static readonly templateName = "domain"; +} diff --git a/packages/models/src/article/Article/templates/LeadFyndrArticleTemplate.ts b/packages/models/src/article/Article/templates/LeadFyndrArticleTemplate.ts new file mode 100644 index 00000000..6e5c2ed7 --- /dev/null +++ b/packages/models/src/article/Article/templates/LeadFyndrArticleTemplate.ts @@ -0,0 +1,5 @@ +import { ArticleTemplate } from "../ArticleTemplate.js"; + +export class LeadFyndrArticleTemplate extends ArticleTemplate { + public static readonly templateName = "LeadFyndr"; +} diff --git a/packages/models/src/article/Article/templates/MailArticleTemplate.ts b/packages/models/src/article/Article/templates/MailArticleTemplate.ts new file mode 100644 index 00000000..e8b92ba6 --- /dev/null +++ b/packages/models/src/article/Article/templates/MailArticleTemplate.ts @@ -0,0 +1,6 @@ +import { ArticleTemplate } from "../ArticleTemplate.js"; + +export class MailArticleTemplate extends ArticleTemplate { + public static readonly templateName = + "E-Mail-Archivierung GoBD-konform und revisionssicher"; +} diff --git a/packages/models/src/article/Article/templates/ProSpaceArticleTemplate.ts b/packages/models/src/article/Article/templates/ProSpaceArticleTemplate.ts new file mode 100644 index 00000000..8709d65a --- /dev/null +++ b/packages/models/src/article/Article/templates/ProSpaceArticleTemplate.ts @@ -0,0 +1,6 @@ +import { ArticleTemplate } from "../ArticleTemplate.js"; + +export class ProSpaceArticleTemplate extends ArticleTemplate { + public static readonly templateId = "fa357d31-57ce-43f9-8a06-c813544b905f"; + public static readonly templateName = "Pro-Space-Hosting"; +} diff --git a/packages/models/src/article/Article/templates/ServerArticleTemplate.ts b/packages/models/src/article/Article/templates/ServerArticleTemplate.ts new file mode 100644 index 00000000..dc3676b0 --- /dev/null +++ b/packages/models/src/article/Article/templates/ServerArticleTemplate.ts @@ -0,0 +1,6 @@ +import { ArticleTemplate } from "../ArticleTemplate.js"; + +export class ServerArticleTemplate extends ArticleTemplate { + public static readonly templateId = "75377469-8cb5-4d88-ab26-d82ff51e18c8"; + public static readonly templateName = "vServer"; +} diff --git a/packages/models/src/article/Article/templates/SpaceServerArticleTemplate.ts b/packages/models/src/article/Article/templates/SpaceServerArticleTemplate.ts new file mode 100644 index 00000000..53e7d03a --- /dev/null +++ b/packages/models/src/article/Article/templates/SpaceServerArticleTemplate.ts @@ -0,0 +1,6 @@ +import { ArticleTemplate } from "../ArticleTemplate.js"; + +export class SpaceServerArticleTemplate extends ArticleTemplate { + public static readonly templateId = "030ac9af-22be-4824-9671-4b388ee9b25f"; + public static readonly templateName = "Multi-Tec-Hosting"; +} diff --git a/packages/models/src/article/Article/templates/StorageArticleTemplate.ts b/packages/models/src/article/Article/templates/StorageArticleTemplate.ts new file mode 100644 index 00000000..69ec21c7 --- /dev/null +++ b/packages/models/src/article/Article/templates/StorageArticleTemplate.ts @@ -0,0 +1,6 @@ +import { ArticleTemplate } from "../ArticleTemplate.js"; + +export class StorageArticleTemplate extends ArticleTemplate { + public static readonly templateId = "054e27e4-d3ed-4ffc-a472-fbb74a6a2ec1"; + public static readonly templateName = "Speicher für Hosting aller Art"; +} diff --git a/packages/models/src/article/Article/templates/Typo3LicenseArticleTemplate.ts b/packages/models/src/article/Article/templates/Typo3LicenseArticleTemplate.ts new file mode 100644 index 00000000..9323fcf9 --- /dev/null +++ b/packages/models/src/article/Article/templates/Typo3LicenseArticleTemplate.ts @@ -0,0 +1,6 @@ +import { ArticleTemplate } from "../ArticleTemplate.js"; + +export class Typo3LicenseArticleTemplate extends ArticleTemplate { + public static readonly templateId = "249e32a6-d56b-4547-8966-0c6f240e6371"; + public static readonly templateName = "typo3_elts"; +} diff --git a/packages/models/src/article/Article/templates/WebhostingArticleTemplate.ts b/packages/models/src/article/Article/templates/WebhostingArticleTemplate.ts new file mode 100644 index 00000000..cb27f7e1 --- /dev/null +++ b/packages/models/src/article/Article/templates/WebhostingArticleTemplate.ts @@ -0,0 +1,6 @@ +import { ArticleTemplate } from "../ArticleTemplate.js"; + +export class WebhostingArticleTemplate extends ArticleTemplate { + public static readonly templateId = "ab32d264-4d97-4442-8a80-89ab8436718c"; + public static readonly templateName = "Webhosting"; +} diff --git a/packages/models/src/article/Article/templates/articleTemplateFactory.ts b/packages/models/src/article/Article/templates/articleTemplateFactory.ts new file mode 100644 index 00000000..73bbe527 --- /dev/null +++ b/packages/models/src/article/Article/templates/articleTemplateFactory.ts @@ -0,0 +1,30 @@ +import type { ArticleTemplate } from "../ArticleTemplate.js"; + +import { SpaceServerArticleTemplate } from "./SpaceServerArticleTemplate.js"; +import { WebhostingArticleTemplate } from "./WebhostingArticleTemplate.js"; +import { AIHostingArticleTemplate } from "./AIHostingArticleTemplate.js"; +import { ProSpaceArticleTemplate } from "./ProSpaceArticleTemplate.js"; +import { StorageArticleTemplate } from "./StorageArticleTemplate.js"; +import { ServerArticleTemplate } from "./ServerArticleTemplate.js"; +import { MailArticleTemplate } from "./MailArticleTemplate.js"; + +export const articleTemplateFactory = (template: ArticleTemplate) => { + switch (template.name) { + case SpaceServerArticleTemplate.templateName: + return new SpaceServerArticleTemplate(template.data); + case WebhostingArticleTemplate.templateName: + return new WebhostingArticleTemplate(template.data); + case AIHostingArticleTemplate.templateName: + return new AIHostingArticleTemplate(template.data); + case ProSpaceArticleTemplate.templateName: + return new ProSpaceArticleTemplate(template.data); + case StorageArticleTemplate.templateName: + return new StorageArticleTemplate(template.data); + case ServerArticleTemplate.templateName: + return new ServerArticleTemplate(template.data); + case MailArticleTemplate.templateName: + return new MailArticleTemplate(template.data); + default: + return template; + } +}; diff --git a/packages/models/src/article/Article/types.ts b/packages/models/src/article/Article/types.ts index 666ad155..f397a184 100644 --- a/packages/models/src/article/Article/types.ts +++ b/packages/models/src/article/Article/types.ts @@ -1,4 +1,6 @@ -import { MittwaldAPIV2 } from "@mittwald/api-client"; +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import type { Customer } from "../../customer/index.js"; export type ArticleListQueryData = MittwaldAPIV2.Paths.V2Articles.Get.Parameters.Query; @@ -9,4 +11,28 @@ export type ArticleData = export type ArticleListItemData = MittwaldAPIV2.Operations.ArticleListArticles.ResponseData[number]; -export type ArticleListQueryModelData = ArticleListQueryData; +export type ArticleListQueryModelData = Omit< + ArticleListQueryData, + "customerId" +> & { + customer?: Customer | string; +}; + +export type ArticleTagData = MittwaldAPIV2.Components.Schemas.ArticleArticleTag; + +export type ArticleAttributeData = + MittwaldAPIV2.Components.Schemas.ArticleArticleAttributes; + +export type ArticleModifierData = + MittwaldAPIV2.Components.Schemas.ArticleReadableModifierArticleOptions; + +export type ArticleTemplateData = + MittwaldAPIV2.Components.Schemas.ArticleArticleTemplate; + +export type ArticleType = + | "proSpaceDedicated" + | "dedicatedServer" + | "webhosting" + | "proSpace" + | "vServer" + | "ai"; diff --git a/packages/models/src/auth/Auth/Auth.ts b/packages/models/src/auth/Auth/Auth.ts new file mode 100644 index 00000000..2930df89 --- /dev/null +++ b/packages/models/src/auth/Auth/Auth.ts @@ -0,0 +1,36 @@ +import type { AxiosRequestConfig } from "axios"; + +import type { AuthenticateRequestData } from "./types.js"; + +import { SessionToken } from "../SessionToken/index.js"; +import { config } from "../../config/index.js"; + +export class Auth { + public static async checkIsAuthenticated(requestConfig?: AxiosRequestConfig) { + return await config.behaviors.auth.checkIsAuthenticated(requestConfig); + } + + public static async login( + data: AuthenticateRequestData, + ): Promise<"mfaRequired" | SessionToken>; + + public static async login( + data: AuthenticateRequestData & { cookieOnly: true }, + ): Promise; + + public static async login( + data: AuthenticateRequestData, + ): Promise<"mfaRequired" | SessionToken | void> { + const response = await config.behaviors.auth.authenticate(data); + + if (response === "mfaRequired" || response === undefined) { + return response; + } + + return new SessionToken(response); + } + + public static async logout(requestConfig?: AxiosRequestConfig) { + await config.behaviors.auth.logout(requestConfig); + } +} diff --git a/packages/models/src/auth/Auth/behaviors/api.ts b/packages/models/src/auth/Auth/behaviors/api.ts new file mode 100644 index 00000000..476430de --- /dev/null +++ b/packages/models/src/auth/Auth/behaviors/api.ts @@ -0,0 +1,108 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; +import type { AxiosRequestConfig } from "axios"; + +import type { AuthBehaviors } from "./types.js"; + +import { ValidationError } from "../../../errors/index.js"; +import { + withAxiosRequestConfig, + validateResponse, + anyStatus401, + anyStatus403, +} from "../../../base/index.js"; + +export const apiAuthBehaviors = ( + client: MittwaldAPIV2Client, +): AuthBehaviors => ({ + authenticate: async (data, requestOptions?: AxiosRequestConfig) => { + const { multiFactorCode, cookieOnly, ...bodyData } = data; + + const response = multiFactorCode + ? await client.user.authenticateMfa( + { + data: { + ...bodyData, + multiFactorCode, + }, + queryParameters: { + cookieOnly, + }, + }, + withAxiosRequestConfig(requestOptions), + ) + : await client.user.authenticate( + { + queryParameters: { + cookieOnly, + }, + data: bodyData, + }, + withAxiosRequestConfig(requestOptions), + ); + + if ( + response.status === 401 || + // API-DRIFT: user.authenticate omits 403 in its generated response type, so anyStatus403 (403 as any) is compared (resolve: use the literal 403 once the client type declares it) + response.status === anyStatus403 || + (response.data as { type?: string } | undefined)?.type === + "WrongEmailOrPassword" + ) { + throw new ValidationError({ + message: "invalidCredentials", + type: "invalidCredentials", + path: "root", + }); + } + + validateResponse(response, [200, 202, 204], { + validationError: { + typeMappings: { + custom: (e) => + e.message?.includes("code is not valid") + ? "mfaCodeInvalid" + : undefined, + }, + }, + }); + + if (response.status === 202) { + return "mfaRequired"; + } + + if (response.status === 204) { + return; + } + + return response.data; + }, + + checkIsAuthenticated: async (requestConfig) => { + // API-DRIFT: uses getUser({ userId: "self" }) as an auth probe instead of client.user.checkToken() (resolve: switch to checkToken() once the API is fixed) + const response = await client.user.getUser( + { + userId: "self", + }, + withAxiosRequestConfig(requestConfig), + ); + + // const response = await client.user.checkToken( + // {}, + // withAxiosRequestConfig(requestOptions), + // ); + + // API-DRIFT: user.getUser (auth probe) omits 401 in its generated response type, so anyStatus401 (401 as any) is passed (resolve: use the literal 401 once the client type declares it) + validateResponse(response, [200, anyStatus401, 412]); + + return response.status === 200; + }, + + logout: async (requestConfig) => { + const response = await client.user.logout( + {}, + withAxiosRequestConfig(requestConfig), + ); + + // API-DRIFT: user.logout omits 401 in its generated response type, so anyStatus401 (401 as any) is passed (resolve: use the literal 401 once the client type declares it) + validateResponse(response, [204, anyStatus401]); + }, +}); diff --git a/packages/models/src/auth/Auth/behaviors/index.ts b/packages/models/src/auth/Auth/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/auth/Auth/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/auth/Auth/behaviors/types.ts b/packages/models/src/auth/Auth/behaviors/types.ts new file mode 100644 index 00000000..77d3d347 --- /dev/null +++ b/packages/models/src/auth/Auth/behaviors/types.ts @@ -0,0 +1,16 @@ +import type { AxiosRequestConfig } from "axios"; + +import type { AuthenticateRequestData, AuthenticateData } from "../types.js"; + +export interface AuthBehaviors { + authenticate: ( + data: AuthenticateRequestData, + options?: AxiosRequestConfig, + ) => Promise; + + checkIsAuthenticated: ( + requestConfig?: AxiosRequestConfig, + ) => Promise; + + logout: (requestConfig?: AxiosRequestConfig) => Promise; +} diff --git a/packages/models/src/auth/Auth/index.ts b/packages/models/src/auth/Auth/index.ts new file mode 100644 index 00000000..3b70ef86 --- /dev/null +++ b/packages/models/src/auth/Auth/index.ts @@ -0,0 +1 @@ +export * from "./Auth.js"; diff --git a/packages/models/src/auth/Auth/types.ts b/packages/models/src/auth/Auth/types.ts new file mode 100644 index 00000000..e38f3e0f --- /dev/null +++ b/packages/models/src/auth/Auth/types.ts @@ -0,0 +1,20 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type AuthenticateData = + | MittwaldAPIV2.Paths.V2Authenticate.Post.Responses.$200.Content.ApplicationJson + | "mfaRequired"; + +export type AuthenticateRequestData = + MittwaldAPIV2.Paths.V2Authenticate.Post.Parameters.RequestBody & { + multiFactorCode?: string; + cookieOnly?: boolean; + }; + +export type RegisterRequestData = + MittwaldAPIV2.Paths.V2Register.Post.Parameters.RequestBody; + +export type VerifyRegistrationRequestData = + MittwaldAPIV2.Paths.V2VerifyRegistration.Post.Parameters.RequestBody; + +export type ResendVerificationEmailRequestData = + MittwaldAPIV2.Paths.V2UsersSelfCredentialsEmailActionsResendEmail.Post.Parameters.RequestBody; diff --git a/packages/models/src/auth/Mfa/Mfa.test.ts b/packages/models/src/auth/Mfa/Mfa.test.ts new file mode 100644 index 00000000..87095aae --- /dev/null +++ b/packages/models/src/auth/Mfa/Mfa.test.ts @@ -0,0 +1,145 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { buildSessionTokenData } from "../../testing/builders/buildSessionTokenData.js"; +import { buildMfaStatusData } from "../../testing/builders/buildMfaStatusData.js"; +import { buildMfaInitData } from "../../testing/builders/buildMfaInitData.js"; +import { installBehaviors, resetBehaviors } from "../../testing/index.js"; +import { RecoveryCodes } from "../RecoveryCodes/index.js"; +import { DataModel } from "../../base/index.js"; +import { MfaStatus, Mfa } from "./Mfa.js"; +import { MfaInit } from "./MfaInit.js"; + +afterEach(resetBehaviors); + +describe("Mfa.getStatus", () => { + test("maps confirmed status to an active MfaStatus", async () => { + const getStatus = vi + .fn() + .mockResolvedValue(buildMfaStatusData({ confirmed: true })); + installBehaviors({ mfa: { getStatus } }); + + const status = await Mfa.getStatus(); + + expect(status).toBeInstanceOf(MfaStatus); + expect(status.active).toBe(true); + }); + + test("maps unconfirmed status to an inactive MfaStatus", async () => { + const getStatus = vi + .fn() + .mockResolvedValue(buildMfaStatusData({ confirmed: false })); + installBehaviors({ mfa: { getStatus } }); + + const status = await Mfa.getStatus(); + + expect(status.active).toBe(false); + }); +}); + +describe("Mfa.confirm", () => { + test("returns joined recovery codes and forwards the code", async () => { + const confirm = vi + .fn() + .mockResolvedValue({ recoveryCodesList: ["a", "b"] }); + installBehaviors({ mfa: { confirm } }); + + const recoveryCodes = await Mfa.confirm("123456"); + + expect(recoveryCodes).toBeInstanceOf(RecoveryCodes); + expect(recoveryCodes.getDownload().content).toBe("a\nb"); + expect(confirm).toHaveBeenCalledWith("123456"); + }); +}); + +describe("Mfa.resetRecoveryCodes", () => { + test("returns fresh recovery codes and forwards the code", async () => { + const resetRecoveryCodes = vi + .fn() + .mockResolvedValue({ recoveryCodesList: ["x", "y", "z"] }); + installBehaviors({ mfa: { resetRecoveryCodes } }); + + const recoveryCodes = await Mfa.resetRecoveryCodes("654321"); + + expect(recoveryCodes).toBeInstanceOf(RecoveryCodes); + expect(recoveryCodes.getDownload().content).toBe("x\ny\nz"); + expect(resetRecoveryCodes).toHaveBeenCalledWith("654321"); + }); +}); + +describe("Mfa.disable", () => { + test("forwards the code and resolves without a value", async () => { + const disable = vi.fn().mockResolvedValue(undefined); + installBehaviors({ mfa: { disable } }); + + await expect(Mfa.disable("000111")).resolves.toBeUndefined(); + expect(disable).toHaveBeenCalledWith("000111"); + }); +}); + +describe("Mfa.authenticate", () => { + test("passes the request data through and returns the session token data", async () => { + const sessionTokenData = buildSessionTokenData(); + const authenticateMfa = vi.fn().mockResolvedValue(sessionTokenData); + installBehaviors({ mfa: { authenticateMfa } }); + + const requestData = { + email: "user@example.com", + multiFactorCode: "123456", + password: "secret", + }; + const result = await Mfa.authenticate(requestData); + + expect(result).toEqual(sessionTokenData); + expect(authenticateMfa).toHaveBeenCalledWith(requestData); + }); +}); + +describe("Mfa.init", () => { + test("returns an MfaInit with the secret extracted from the url", async () => { + const init = vi.fn().mockResolvedValue(buildMfaInitData()); + installBehaviors({ mfa: { init } }); + + const mfaInit = await Mfa.init(); + + expect(mfaInit).toBeInstanceOf(MfaInit); + expect(mfaInit.secret).toBe("THE-SECRET"); + expect(mfaInit.barcodeImageSrc.startsWith("data:image/jpg;base64, ")).toBe( + true, + ); + }); + + test("forwards the request config to the behavior", async () => { + const init = vi.fn().mockResolvedValue(buildMfaInitData()); + installBehaviors({ mfa: { init } }); + + const requestConfig = { timeout: 1000 }; + await Mfa.init(requestConfig); + + expect(init).toHaveBeenCalledWith(requestConfig); + }); +}); + +describe("MfaStatus construction", () => { + test("derives active from the confirmed flag", () => { + const status = new MfaStatus(buildMfaStatusData({ confirmed: false })); + + expect(status).toBeInstanceOf(DataModel); + expect(status.active).toBe(false); + }); +}); + +describe("MfaInit construction", () => { + test("falls back to an empty secret when the url has no secret param", () => { + const mfaInit = new MfaInit( + buildMfaInitData({ url: "otpauth://totp/mittwald" }), + ); + + expect(mfaInit.secret).toBe(""); + }); + + test("embeds the barcode as a base64 image data uri", () => { + const mfaInit = new MfaInit(buildMfaInitData({ barcode: "AAA" })); + + expect(mfaInit.barcodeImageSrc).toBe("data:image/jpg;base64, AAA"); + }); +}); diff --git a/packages/models/src/auth/Mfa/Mfa.ts b/packages/models/src/auth/Mfa/Mfa.ts new file mode 100644 index 00000000..f5a2e2c7 --- /dev/null +++ b/packages/models/src/auth/Mfa/Mfa.ts @@ -0,0 +1,54 @@ +import type { AxiosRequestConfig } from "axios"; + +import type { AuthenticateMfaRequestData, MfaStatusData } from "./types.js"; + +import { RecoveryCodes } from "../RecoveryCodes/index.js"; +import { DataModel } from "../../base/index.js"; +import { config } from "../../config/index.js"; +import { MfaInit } from "./MfaInit.js"; + +export class Mfa { + public static async authenticate(data: AuthenticateMfaRequestData) { + return await config.behaviors.mfa.authenticateMfa(data); + } + + public static async confirm(multiFactorCode: string) { + const response = await config.behaviors.mfa.confirm(multiFactorCode); + + return new RecoveryCodes({ + codes: response.recoveryCodesList, + }); + } + + public static async disable(multiFactorCode: string) { + return await config.behaviors.mfa.disable(multiFactorCode); + } + + public static async getStatus() { + const data = await config.behaviors.mfa.getStatus(); + return new MfaStatus(data); + } + + public static async init(requestConfig?: AxiosRequestConfig) { + const data = await config.behaviors.mfa.init(requestConfig); + return new MfaInit(data); + } + + public static async resetRecoveryCodes(multiFactorCode: string) { + const response = + await config.behaviors.mfa.resetRecoveryCodes(multiFactorCode); + + return new RecoveryCodes({ + codes: response.recoveryCodesList, + }); + } +} + +export class MfaStatus extends DataModel { + public readonly active: boolean; + + public constructor(data: MfaStatusData) { + super(data); + this.active = data.confirmed; + } +} diff --git a/packages/models/src/auth/Mfa/MfaInit.ts b/packages/models/src/auth/Mfa/MfaInit.ts new file mode 100644 index 00000000..daad21b3 --- /dev/null +++ b/packages/models/src/auth/Mfa/MfaInit.ts @@ -0,0 +1,14 @@ +import type { InitMfaResponseData } from "./types.js"; + +import { DataModel } from "../../base/index.js"; + +export class MfaInit extends DataModel { + public readonly barcodeImageSrc: string; + public readonly secret: string; + + public constructor(data: InitMfaResponseData) { + super(data); + this.secret = data.url.split("secret=")[1] ?? ""; + this.barcodeImageSrc = `data:image/jpg;base64, ${data.barcode}`; + } +} diff --git a/packages/models/src/auth/Mfa/behaviors/api.ts b/packages/models/src/auth/Mfa/behaviors/api.ts new file mode 100644 index 00000000..d636deac --- /dev/null +++ b/packages/models/src/auth/Mfa/behaviors/api.ts @@ -0,0 +1,67 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { MfaBehaviors } from "./types.js"; + +import { + withAxiosRequestConfig, + validateResponse, +} from "../../../base/index.js"; + +export const apiMfaBehaviors = (client: MittwaldAPIV2Client): MfaBehaviors => ({ + resetRecoveryCodes: async (multiFactorCode) => { + const response = await client.user.resetRecoverycodes({ + data: { multiFactorCode }, + }); + + validateResponse(response, 200); + + return response.data; + }, + + init: async (requestConfig) => { + const response = await client.user.initMfa( + {}, + withAxiosRequestConfig(requestConfig), + ); + + validateResponse(response, 200); + + return response.data; + }, + + confirm: async (multiFactorCode) => { + const response = await client.user.confirmMfa({ + data: { multiFactorCode }, + }); + + validateResponse(response, 200); + + return response.data; + }, + + authenticateMfa: async (data) => { + const response = await client.user.authenticateMfa({ + data, + }); + + validateResponse(response, 200); + + return response.data; + }, + + disable: async (multiFactorCode) => { + const response = await client.user.disableMfa({ + data: { multiFactorCode }, + }); + + validateResponse(response, 204); + }, + + getStatus: async () => { + const response = await client.user.getMfaStatus({}); + + validateResponse(response, 200); + + return response.data; + }, +}); diff --git a/packages/models/src/auth/Mfa/behaviors/index.ts b/packages/models/src/auth/Mfa/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/auth/Mfa/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/auth/Mfa/behaviors/types.ts b/packages/models/src/auth/Mfa/behaviors/types.ts new file mode 100644 index 00000000..4323847a --- /dev/null +++ b/packages/models/src/auth/Mfa/behaviors/types.ts @@ -0,0 +1,28 @@ +import type { AxiosRequestConfig } from "axios"; + +import type { SessionTokenData } from "../../SessionToken/types.js"; +import type { + ResetMfaRecoveryResponseData, + AuthenticateMfaRequestData, + ConfirmMfaResponseData, + InitMfaResponseData, + MfaStatusData, +} from "../types.js"; + +export interface MfaBehaviors { + resetRecoveryCodes: ( + multiFactorCode: string, + ) => Promise; + + authenticateMfa: ( + data: AuthenticateMfaRequestData, + ) => Promise; + + init: (requestConfig?: AxiosRequestConfig) => Promise; + + confirm: (multiFactorCode: string) => Promise; + + disable: (multiFactorCode: string) => Promise; + + getStatus: () => Promise; +} diff --git a/packages/models/src/auth/Mfa/index.ts b/packages/models/src/auth/Mfa/index.ts new file mode 100644 index 00000000..f295676d --- /dev/null +++ b/packages/models/src/auth/Mfa/index.ts @@ -0,0 +1,3 @@ +export * from "./Mfa.js"; +export * from "./MfaInit.js"; +export * from "./types.js"; diff --git a/packages/models/src/auth/Mfa/types.ts b/packages/models/src/auth/Mfa/types.ts new file mode 100644 index 00000000..72c45acb --- /dev/null +++ b/packages/models/src/auth/Mfa/types.ts @@ -0,0 +1,16 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type MfaStatusData = + MittwaldAPIV2.Operations.UserGetMfaStatus.ResponseData; + +export type ResetMfaRecoveryResponseData = + MittwaldAPIV2.Operations.UserResetRecoverycodes.ResponseData; + +export type ConfirmMfaResponseData = + MittwaldAPIV2.Operations.UserConfirmMfa.ResponseData; + +export type AuthenticateMfaRequestData = + MittwaldAPIV2.Paths.V2AuthenticateMfa.Post.Parameters.RequestBody; + +export type InitMfaResponseData = + MittwaldAPIV2.Operations.UserInitMfa.ResponseData; diff --git a/packages/models/src/auth/RecoveryCodes/RecoveryCodes.test.ts b/packages/models/src/auth/RecoveryCodes/RecoveryCodes.test.ts new file mode 100644 index 00000000..f1a82b1b --- /dev/null +++ b/packages/models/src/auth/RecoveryCodes/RecoveryCodes.test.ts @@ -0,0 +1,15 @@ +import { afterEach, expect, test } from "vitest"; + +import { buildRecoveryCodesData, resetBehaviors } from "../../testing/index.js"; +import { RecoveryCodes } from "./RecoveryCodes.js"; + +afterEach(resetBehaviors); + +test("provides recovery codes as a downloadable text file", () => { + const recoveryCodes = new RecoveryCodes(buildRecoveryCodesData()); + + expect(recoveryCodes.getDownload()).toEqual({ + filename: "mittwald-recovery-codes.txt", + content: "code-1\ncode-2\ncode-3", + }); +}); diff --git a/packages/models/src/auth/RecoveryCodes/RecoveryCodes.ts b/packages/models/src/auth/RecoveryCodes/RecoveryCodes.ts new file mode 100644 index 00000000..9473803b --- /dev/null +++ b/packages/models/src/auth/RecoveryCodes/RecoveryCodes.ts @@ -0,0 +1,17 @@ +import type { DownloadableFile } from "../../common/index.js"; +import type { RecoveryCodesData } from "./types.js"; + +import { DataModel } from "../../base/index.js"; + +export class RecoveryCodes extends DataModel { + public readonly codes: string; + + public constructor(data: RecoveryCodesData) { + super(data); + this.codes = data.codes.join("\n"); + } + + public getDownload(): DownloadableFile { + return { filename: "mittwald-recovery-codes.txt", content: this.codes }; + } +} diff --git a/packages/models/src/auth/RecoveryCodes/index.ts b/packages/models/src/auth/RecoveryCodes/index.ts new file mode 100644 index 00000000..81103f11 --- /dev/null +++ b/packages/models/src/auth/RecoveryCodes/index.ts @@ -0,0 +1 @@ +export * from "./RecoveryCodes.js"; diff --git a/packages/models/src/auth/RecoveryCodes/types.ts b/packages/models/src/auth/RecoveryCodes/types.ts new file mode 100644 index 00000000..1167ce57 --- /dev/null +++ b/packages/models/src/auth/RecoveryCodes/types.ts @@ -0,0 +1,3 @@ +export interface RecoveryCodesData { + codes: string[]; +} diff --git a/packages/models/src/auth/Registration/Registration.test.ts b/packages/models/src/auth/Registration/Registration.test.ts new file mode 100644 index 00000000..0ca5baa9 --- /dev/null +++ b/packages/models/src/auth/Registration/Registration.test.ts @@ -0,0 +1,59 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { buildRegisterRequestData } from "../../testing/builders/buildRegisterRequestData.js"; +import { installBehaviors, resetBehaviors } from "../../testing/index.js"; +import { Registration } from "./Registration.js"; +import { DataModel } from "../../base/index.js"; + +afterEach(resetBehaviors); + +describe("Registration.start", () => { + test("delegates to the behavior and returns a Registration", async () => { + const start = vi.fn().mockResolvedValue({ id: "user-123" }); + installBehaviors({ registration: { start } }); + const requestData = buildRegisterRequestData({ email: "a@b.de" }); + + const registration = await Registration.start(requestData); + + expect(registration).toBeInstanceOf(Registration); + expect(registration).toBeInstanceOf(DataModel); + expect(start).toHaveBeenCalledWith(requestData); + }); +}); + +describe("Registration.verify", () => { + test("verifies with the stored email/userId and the given token", async () => { + const verify = vi.fn().mockResolvedValue(undefined); + installBehaviors({ registration: { verify } }); + const registration = new Registration({ + ...buildRegisterRequestData({ email: "a@b.de" }), + userId: "user-123", + }); + + await registration.verify({ token: "tok" }); + + expect(verify).toHaveBeenCalledWith({ + userId: "user-123", + email: "a@b.de", + token: "tok", + }); + }); +}); + +describe("Registration.resendVerificationEmail", () => { + test("resends using the stored email and userId", async () => { + const resendVerificationEmail = vi.fn().mockResolvedValue(undefined); + installBehaviors({ registration: { resendVerificationEmail } }); + const registration = new Registration({ + ...buildRegisterRequestData({ email: "a@b.de" }), + userId: "user-123", + }); + + await registration.resendVerificationEmail(); + + expect(resendVerificationEmail).toHaveBeenCalledWith({ + userId: "user-123", + email: "a@b.de", + }); + }); +}); diff --git a/packages/models/src/auth/Registration/Registration.ts b/packages/models/src/auth/Registration/Registration.ts new file mode 100644 index 00000000..b1ea5ae3 --- /dev/null +++ b/packages/models/src/auth/Registration/Registration.ts @@ -0,0 +1,39 @@ +import type { + VerifyRegistrationModelData, + RegisterRequestData, +} from "./types.js"; + +import { DataModel } from "../../base/index.js"; +import { config } from "../../config/index.js"; + +interface Data extends RegisterRequestData { + userId: string; +} + +export class Registration extends DataModel { + public static async start(data: RegisterRequestData) { + const response = await config.behaviors.registration.start(data); + return new Registration({ + ...data, + userId: response.id, + }); + } + + public async resendVerificationEmail() { + const { userId, email } = this.data; + return await config.behaviors.registration.resendVerificationEmail({ + userId, + email, + }); + } + + public async verify(data: VerifyRegistrationModelData) { + const { userId, email } = this.data; + const { token } = data; + await config.behaviors.registration.verify({ + userId, + email, + token, + }); + } +} diff --git a/packages/models/src/auth/Registration/behaviors/api.ts b/packages/models/src/auth/Registration/behaviors/api.ts new file mode 100644 index 00000000..89424e97 --- /dev/null +++ b/packages/models/src/auth/Registration/behaviors/api.ts @@ -0,0 +1,38 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { RegistrationBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/index.js"; + +export const apiRegistrationBehaviors = ( + client: MittwaldAPIV2Client, +): RegistrationBehaviors => ({ + verify: async (data) => { + const response = await client.user.verifyRegistration({ data }); + + validateResponse(response, 200, { + validationError: { + typeMappings: { + "*": (e) => + e.message === "Wrong verification token" + ? "wrongVerificationToken" + : undefined, + }, + }, + }); + }, + + start: async (data) => { + const response = await client.user.register({ data }); + + validateResponse(response, 201); + + return { id: response.data.userId }; + }, + + resendVerificationEmail: async (data) => { + const response = await client.user.resendVerificationEmail({ data }); + + validateResponse(response, 204); + }, +}); diff --git a/packages/models/src/auth/Registration/behaviors/index.ts b/packages/models/src/auth/Registration/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/auth/Registration/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/auth/Registration/behaviors/types.ts b/packages/models/src/auth/Registration/behaviors/types.ts new file mode 100644 index 00000000..d415433b --- /dev/null +++ b/packages/models/src/auth/Registration/behaviors/types.ts @@ -0,0 +1,14 @@ +import type { + ResendVerificationEmailRequestData, + VerifyRegistrationRequestData, + RegisterRequestData, +} from "../types.js"; + +export interface RegistrationBehaviors { + resendVerificationEmail: ( + data: ResendVerificationEmailRequestData, + ) => Promise; + + verify: (data: VerifyRegistrationRequestData) => Promise; + start: (data: RegisterRequestData) => Promise<{ id: string }>; +} diff --git a/packages/models/src/auth/Registration/index.ts b/packages/models/src/auth/Registration/index.ts new file mode 100644 index 00000000..1b54cb37 --- /dev/null +++ b/packages/models/src/auth/Registration/index.ts @@ -0,0 +1 @@ +export * from "./Registration.js"; diff --git a/packages/models/src/auth/Registration/types.ts b/packages/models/src/auth/Registration/types.ts new file mode 100644 index 00000000..07c78a42 --- /dev/null +++ b/packages/models/src/auth/Registration/types.ts @@ -0,0 +1,14 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type RegisterRequestData = + MittwaldAPIV2.Paths.V2Register.Post.Parameters.RequestBody; + +export type VerifyRegistrationRequestData = + MittwaldAPIV2.Paths.V2VerifyRegistration.Post.Parameters.RequestBody; + +export interface VerifyRegistrationModelData { + token: string; +} + +export type ResendVerificationEmailRequestData = + MittwaldAPIV2.Paths.V2UsersSelfCredentialsEmailActionsResendEmail.Post.Parameters.RequestBody; diff --git a/packages/models/src/auth/SessionToken/SessionToken.test.ts b/packages/models/src/auth/SessionToken/SessionToken.test.ts new file mode 100644 index 00000000..454cab23 --- /dev/null +++ b/packages/models/src/auth/SessionToken/SessionToken.test.ts @@ -0,0 +1,48 @@ +import { afterEach, describe, expect, test } from "vitest"; +import { DateTime } from "luxon"; + +import { buildSessionTokenData } from "../../testing/builders/buildSessionTokenData.js"; +import { resetBehaviors } from "../../testing/index.js"; +import { SessionToken } from "./SessionToken.js"; +import { DataModel } from "../../base/index.js"; + +afterEach(resetBehaviors); + +describe("SessionToken construction", () => { + test("exposes token, refresh token and a parsed expiration date", () => { + const sessionToken = new SessionToken( + buildSessionTokenData({ + expires: "2099-01-01T00:00:00.000Z", + refreshToken: "r", + token: "t", + }), + ); + + expect(sessionToken).toBeInstanceOf(DataModel); + expect(sessionToken.token).toBe("t"); + expect(sessionToken.refreshToken).toBe("r"); + expect(sessionToken.expirationDate).toBeInstanceOf(DateTime); + expect(sessionToken.expirationDate.isValid).toBe(true); + expect(sessionToken.expirationDate.toUTC().toISO()).toBe( + "2099-01-01T00:00:00.000Z", + ); + }); +}); + +describe("SessionToken.isExpired", () => { + test("returns false when the expiration date is in the future", () => { + const sessionToken = new SessionToken( + buildSessionTokenData({ expires: "2099-01-01T00:00:00.000Z" }), + ); + + expect(sessionToken.isExpired()).toBe(false); + }); + + test("returns true when the expiration date is in the past", () => { + const sessionToken = new SessionToken( + buildSessionTokenData({ expires: "2000-01-01T00:00:00.000Z" }), + ); + + expect(sessionToken.isExpired()).toBe(true); + }); +}); diff --git a/packages/models/src/auth/SessionToken/SessionToken.ts b/packages/models/src/auth/SessionToken/SessionToken.ts new file mode 100644 index 00000000..d6b46a09 --- /dev/null +++ b/packages/models/src/auth/SessionToken/SessionToken.ts @@ -0,0 +1,22 @@ +import { DateTime } from "luxon"; + +import type { SessionTokenData } from "./types.js"; + +import { DataModel } from "../../base/index.js"; + +export class SessionToken extends DataModel { + public readonly expirationDate: DateTime; + public readonly refreshToken: string; + public readonly token: string; + + public constructor(data: SessionTokenData) { + super(data); + this.expirationDate = DateTime.fromISO(data.expires); + this.token = data.token; + this.refreshToken = data.refreshToken; + } + + public isExpired() { + return this.expirationDate < DateTime.now(); + } +} diff --git a/packages/models/src/auth/SessionToken/index.ts b/packages/models/src/auth/SessionToken/index.ts new file mode 100644 index 00000000..15f56362 --- /dev/null +++ b/packages/models/src/auth/SessionToken/index.ts @@ -0,0 +1 @@ +export * from "./SessionToken.js"; diff --git a/packages/models/src/auth/SessionToken/types.ts b/packages/models/src/auth/SessionToken/types.ts new file mode 100644 index 00000000..2871bbba --- /dev/null +++ b/packages/models/src/auth/SessionToken/types.ts @@ -0,0 +1,5 @@ +export interface SessionTokenData { + refreshToken: string; + expires: string; + token: string; +} diff --git a/packages/models/src/auth/index.ts b/packages/models/src/auth/index.ts new file mode 100644 index 00000000..0a0ef2a3 --- /dev/null +++ b/packages/models/src/auth/index.ts @@ -0,0 +1,5 @@ +export * from "./Auth/index.js"; +export * from "./Mfa/index.js"; +export * from "./RecoveryCodes/index.js"; +export * from "./Registration/index.js"; +export * from "./SessionToken/index.js"; diff --git a/packages/models/src/backup/Backup/Backup.test.ts b/packages/models/src/backup/Backup/Backup.test.ts new file mode 100644 index 00000000..54d5c2c0 --- /dev/null +++ b/packages/models/src/backup/Backup/Backup.test.ts @@ -0,0 +1,397 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; +import { DateTime } from "luxon"; + +import type { + BackupCreatePathRestoreRequestData, + BackupCreateExportRequestData, + BackupCreateRequestData, +} from "./types.js"; + +import { buildBackupExportData } from "../../testing/builders/buildBackupExportData.js"; +import { + BackupDetailed, + BackupListItem, + BackupList, + Backup, +} from "./Backup.js"; +import { buildBackupData } from "../../testing/builders/buildBackupData.js"; +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { BackupSchedule } from "../BackupSchedule/index.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { BackupExport } from "./BackupExport.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { Project } from "../../project/index.js"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +afterEach(resetBehaviors); + +describe("Backup lookup and creation", () => { + test("find delegates and returns a detailed backup", async () => { + const find = vi.fn().mockResolvedValue(buildBackupData({ id: "b-1" })); + installBehaviors({ backup: { find } }); + + const result = await Backup.find("b-1"); + + expect(find).toHaveBeenCalledWith("b-1"); + expect(result).toBeInstanceOf(BackupDetailed); + expect(result?.id).toBe("b-1"); + }); + + test("find returns undefined for a missing backup", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ backup: { find } }); + + expect(await Backup.find("missing")).toBeUndefined(); + }); + + test("get returns a detailed backup", async () => { + installBehaviors({ + backup: { + find: vi.fn().mockResolvedValue(buildBackupData({ id: "b-2" })), + }, + }); + + const result = await Backup.get("b-2"); + + expect(result).toBeInstanceOf(BackupDetailed); + expect(result.id).toBe("b-2"); + }); + + test("get throws ObjectNotFoundError for a missing backup", async () => { + installBehaviors({ + backup: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(Backup.get("missing")).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("create delegates and returns a backup reference", async () => { + const create = vi.fn().mockResolvedValue({ id: "created-id" }); + const data: BackupCreateRequestData = { + expirationTime: "2024-02-01T00:00:00.000Z", + description: "daily", + }; + const project = Project.ofId("p-1"); + installBehaviors({ backup: { create } }); + + const result = await Backup.create(project, data); + + expect(create).toHaveBeenCalledWith("p-1", data); + expect(result).toBeInstanceOf(Backup); + expect(result.id).toBe("created-id"); + }); +}); + +describe("Backup list query", () => { + test("materializes items and applies the default pagination limit", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildBackupData({ id: "b-1" })], + totalCount: 7, + }); + installBehaviors({ backup: { list } }); + + const result = await Backup.query({ + project: Project.ofId("p-1"), + }).execute(); + + expect(result).toBeInstanceOf(BackupList); + expect(result.items[0]).toBeInstanceOf(BackupListItem); + expect(result.totalCount).toBe(7); + expect(list).toHaveBeenCalledWith("p-1", {}); + }); + + test("passes through an explicit pagination limit", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 0, items: [] }); + installBehaviors({ backup: { list } }); + + await Backup.query({ + project: Project.ofId("p-1"), + limit: 5, + }).execute(); + + expect(list).toHaveBeenCalledWith( + "p-1", + expect.objectContaining({ limit: 5 }), + ); + }); + + test("getTotalCount returns the behavior total count", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 12, items: [] }); + installBehaviors({ backup: { list } }); + + const result = await Backup.query({ + project: Project.ofId("p-1"), + }).getTotalCount(); + + expect(result).toBe(12); + }); +}); + +describe("Backup common variant", () => { + test("findCommon on a reference delegates to findDetailed", async () => { + const find = vi.fn().mockResolvedValue(buildBackupData({ id: "b-1" })); + installBehaviors({ backup: { find } }); + + const result = await Backup.ofId("b-1").findCommon(); + + expect(find).toHaveBeenCalledWith("b-1"); + expect(result).toBeInstanceOf(BackupDetailed); + expect(result?.id).toBe("b-1"); + }); + + test("findCommon on a reference returns undefined when not found", async () => { + installBehaviors({ + backup: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + expect(await Backup.ofId("missing").findCommon()).toBeUndefined(); + }); + + test("getCommon on a reference delegates and returns the detailed variant", async () => { + const find = vi.fn().mockResolvedValue(buildBackupData({ id: "b-3" })); + installBehaviors({ backup: { find } }); + + const result = await Backup.ofId("b-3").getCommon(); + + expect(find).toHaveBeenCalledWith("b-3"); + expect(result).toBeInstanceOf(BackupDetailed); + expect(result.id).toBe("b-3"); + }); + + test("getCommon on a missing reference throws ObjectNotFoundError", async () => { + installBehaviors({ + backup: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(Backup.ofId("missing").getCommon()).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("findCommon and getCommon on a materialized model do not re-fetch", () => { + const find = vi.fn(); + installBehaviors({ backup: { find } }); + const item = new BackupListItem(buildBackupData({ id: "b-4" })); + + expect(item.findCommon()).toBe(item); + expect(item.getCommon()).toBe(item); + expect(find).not.toHaveBeenCalled(); + }); +}); + +describe("Backup aggregate metadata", () => { + test("carries the projectbackup aggregate identity", () => { + expect(Backup.aggregateMetaData).toBeInstanceOf(AggregateMetaData); + expect(Backup.aggregateMetaData.domain).toBe("backup"); + expect(Backup.aggregateMetaData.aggregate).toBe("projectbackup"); + }); +}); + +describe("Backup data", () => { + test("maps dates and derived values", () => { + const item = new BackupListItem( + buildBackupData({ + requestedAt: "2024-01-03T00:00:00.000Z", + createdAt: "2024-01-02T00:00:00.000Z", + expiresAt: "2024-01-04T00:00:00.000Z", + status: "Completed", + deletable: true, + }), + ); + + expect(item.createdAt).toBeInstanceOf(DateTime); + expect(item.createdAt?.isValid).toBe(true); + expect(item.requestedAt?.toUTC().toISO()).toBe("2024-01-03T00:00:00.000Z"); + expect(item.expiresAt).toBeInstanceOf(DateTime); + expect(item.isCompleted).toBe(true); + expect(item.isDeletable).toBe(true); + }); + + test("leaves absent dates undefined and maps non-completed status", () => { + const item = new BackupListItem( + buildBackupData({ + requestedAt: undefined, + createdAt: undefined, + expiresAt: undefined, + status: "Pending", + }), + ); + + expect(item.createdAt).toBeUndefined(); + expect(item.requestedAt).toBeUndefined(); + expect(item.expiresAt).toBeUndefined(); + expect(item.isCompleted).toBe(false); + }); + + test("maps schedule, export, and project references", () => { + const item = new BackupListItem( + buildBackupData({ + export: buildBackupExportData(), + projectId: "p-1", + parentId: "s-1", + }), + ); + + expect(item.schedule).toBeInstanceOf(BackupSchedule); + expect(item.schedule?.id).toBe("s-1"); + expect(item.export).toBeInstanceOf(BackupExport); + expect(item.project).toBeInstanceOf(Project); + expect(item.project.id).toBe("p-1"); + }); + + test("leaves absent schedule and export undefined", () => { + const item = new BackupListItem( + buildBackupData({ parentId: undefined, export: undefined }), + ); + + expect(item.schedule).toBeUndefined(); + expect(item.export).toBeUndefined(); + }); + + test("exposes restore details only while a restore is running", () => { + const running = new BackupListItem( + buildBackupData({ + restore: { + pathRestore: { + determinedTargetPath: "/a", + clearTargetPath: false, + sourcePaths: ["/a"], + }, + databaseRestores: [ + { databaseBackupDump: "dump-1", targetDatabaseId: "db-1" }, + ], + phase: "running", + }, + }), + ); + const completed = new BackupListItem( + buildBackupData({ + restore: { + pathRestore: { + determinedTargetPath: "/b", + clearTargetPath: false, + sourcePaths: ["/b"], + }, + databaseRestores: [ + { databaseBackupDump: "dump-2", targetDatabaseId: "db-2" }, + ], + phase: "completed", + }, + }), + ); + + expect(running.restoreInProgress).toBe(true); + expect(running.restorePaths).toEqual(["/a"]); + expect(running.restoreDatabases).toEqual(["dump-1"]); + expect(completed.restoreInProgress).toBe(false); + expect(completed.restorePaths).toBeUndefined(); + expect(completed.restoreDatabases).toBeUndefined(); + }); + + test("leaves restore details undefined when no restore is present", () => { + const item = new BackupListItem(buildBackupData({ restore: undefined })); + + expect(item.restoreInProgress).toBe(false); + expect(item.restorePaths).toBeUndefined(); + expect(item.restoreDatabases).toBeUndefined(); + }); + + test("leaves restore paths and databases undefined while running without them", () => { + const item = new BackupListItem( + buildBackupData({ restore: { phase: "running" } }), + ); + + expect(item.restoreInProgress).toBe(true); + expect(item.restorePaths).toBeUndefined(); + expect(item.restoreDatabases).toBeUndefined(); + }); + + test("findCommon and getCommon return an existing common model", () => { + const item = new BackupListItem(buildBackupData()); + + expect(item.findCommon()).toBe(item); + expect(item.getCommon()).toBe(item); + }); +}); + +describe("Backup export", () => { + test("maps completed export data", () => { + const result = new BackupExport( + buildBackupExportData({ + expiresAt: "2024-01-01T00:00:00.000Z", + downloadURL: "https://x", + phase: "Completed", + format: "zip", + }), + ); + + expect(result.isCompleted).toBe(true); + expect(result.isPending).toBe(false); + expect(result.downloadUrl).toBe("https://x"); + expect(result.format).toBe("zip"); + expect(result.expiresAt).toBeInstanceOf(DateTime); + }); + + test("maps a pending export", () => { + const result = new BackupExport( + buildBackupExportData({ phase: "Pending" }), + ); + + expect(result.isCompleted).toBe(false); + expect(result.isPending).toBe(true); + }); +}); + +describe("Backup mutations", () => { + test("delegates mutations to their behaviors", async () => { + const deleteBehavior = vi.fn().mockResolvedValue(undefined); + const updateDescription = vi.fn().mockResolvedValue(undefined); + const updateExpiryDate = vi.fn().mockResolvedValue(undefined); + const createExport = vi.fn().mockResolvedValue(undefined); + const createRestoreRequest = vi.fn().mockResolvedValue(undefined); + const exportData: BackupCreateExportRequestData = { format: "zip" }; + const restoreData: BackupCreatePathRestoreRequestData = { + pathRestore: { + clearTargetPath: false, + sourcePaths: ["/a"], + }, + }; + installBehaviors({ + backup: { + delete: deleteBehavior, + createRestoreRequest, + updateDescription, + updateExpiryDate, + createExport, + }, + }); + const backup = Backup.ofId("b-1"); + + await backup.delete(); + await backup.updateDescription("d"); + await backup.updateExpiryDate("2024-01-01T00:00:00.000Z"); + await backup.createExport(exportData); + await backup.createRestoreRequest(restoreData); + + expect(deleteBehavior).toHaveBeenCalledWith("b-1"); + expect(updateDescription).toHaveBeenCalledWith("b-1", "d"); + expect(updateExpiryDate).toHaveBeenCalledWith( + "b-1", + "2024-01-01T00:00:00.000Z", + ); + expect(createExport).toHaveBeenCalledWith("b-1", exportData); + expect(createRestoreRequest).toHaveBeenCalledWith("b-1", restoreData); + }); +}); diff --git a/packages/models/src/backup/Backup/Backup.ts b/packages/models/src/backup/Backup/Backup.ts new file mode 100644 index 00000000..cff90248 --- /dev/null +++ b/packages/models/src/backup/Backup/Backup.ts @@ -0,0 +1,217 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; +import { omit } from "remeda"; + +import type { + BackupCreatePathRestoreRequestData, + BackupCreateExportRequestData, + BackupListQueryModelData, + BackupCreateRequestData, + BackupListItemData, + BackupData, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { BackupSchedule } from "../BackupSchedule/index.js"; +import { Project } from "../../project/internal.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { BackupExport } from "./BackupExport.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "Backup", +}) +export class Backup extends ReferenceModel { + public static aggregateMetaData = new AggregateMetaData( + "backup", + "projectbackup", + ); + + public static async create(project: Project, data: BackupCreateRequestData) { + const { id } = await config.behaviors.backup.create(project.id, data); + return new Backup(id); + } + + public static async find(id: string) { + const data = await config.behaviors.backup.find(id); + if (data) { + return new BackupDetailed(data); + } + } + + public static async get(id: string) { + const backup = await Backup.find(id); + assertObjectFound(backup, Backup, id); + return backup; + } + + public static ofId(id: string) { + return new Backup(id); + } + + public static query(query: BackupListQueryModelData) { + return new BackupListQuery(query); + } + + public async createExport(data: BackupCreateExportRequestData) { + await config.behaviors.backup.createExport(this.id, data); + } + + public async createRestoreRequest(data: BackupCreatePathRestoreRequestData) { + await config.behaviors.backup.createRestoreRequest(this.id, data); + } + + public async delete() { + await config.behaviors.backup.delete(this.id); + } + + public findCommon(): Promise | BackupCommon { + return this instanceof BackupCommon ? this : this.findDetailed(); + } + + public findDetailed(): Promise { + return Backup.find(this.id); + } + + public getCommon(): Promise | BackupCommon { + return this instanceof BackupCommon ? this : this.getDetailed(); + } + + public getDetailed(): Promise { + return Backup.get(this.id); + } + + public async updateDescription(description?: string) { + await config.behaviors.backup.updateDescription(this.id, description); + } + + public async updateExpiryDate(expiryDate?: string) { + await config.behaviors.backup.updateExpiryDate(this.id, expiryDate); + } +} + +export class BackupCommon extends WithData()( + Backup, +) { + public readonly createdAt?: DateTime; + public override readonly data: BackupListItemData | BackupData; + public readonly description?: string; + public readonly expiresAt?: DateTime; + public readonly export?: BackupExport; + public readonly isCompleted: boolean; + public readonly isDeletable: boolean; + public readonly project: Project; + public readonly requestedAt?: DateTime; + public readonly restoreDatabases?: string[]; + public readonly restoreInProgress: boolean; + public readonly restorePaths?: string[]; + public readonly schedule?: BackupSchedule; + + public constructor(data: BackupListItemData | BackupData) { + super(data.id); + this.data = data; + this.createdAt = data.createdAt + ? DateTime.fromISO(data.createdAt) + : undefined; + this.requestedAt = data.requestedAt + ? DateTime.fromISO(data.requestedAt) + : undefined; + this.expiresAt = data.expiresAt + ? DateTime.fromISO(data.expiresAt) + : undefined; + this.description = data.description; + this.isDeletable = data.deletable; + this.export = data.export ? new BackupExport(data.export) : undefined; + this.isCompleted = data.status === "Completed"; + this.schedule = data.parentId + ? BackupSchedule.ofId(data.parentId) + : undefined; + this.project = Project.ofId(data.projectId); + this.restoreInProgress = data.restore?.phase === "running"; + this.restorePaths = + this.restoreInProgress && data.restore?.pathRestore + ? data.restore.pathRestore.sourcePaths + : undefined; + this.restoreDatabases = + this.restoreInProgress && data.restore?.databaseRestores + ? data.restore.databaseRestores.map((r) => r.databaseBackupDump) + : undefined; + } + + public readonly findDatabaseBackups = async () => { + return await config.behaviors.backup.findDatabaseBackups(this.id); + }; + + public readonly findToc = async (directory: string) => { + return await config.behaviors.backup.findToc(this.id, directory); + }; +} + +export class BackupDetailed extends BackupCommon { + public override readonly data: BackupData; + public constructor(data: BackupData) { + super(data); + this.data = data; + } +} + +export class BackupListItem extends BackupCommon { + public override readonly data: BackupListItemData; + public constructor(data: BackupListItemData) { + super(data); + this.data = data; + } +} + +export class BackupListQuery extends ListQueryModel { + public constructor(query: BackupListQueryModelData) { + super(query, { dependencies: [extractId(query.project)] }); + } + + public async execute() { + const { totalCount, items } = await config.behaviors.backup.list( + extractId(this.query.project), + omit(this.query, ["project"]), + ); + return new BackupList( + this.query, + items.map((d) => new BackupListItem(d)), + totalCount, + ); + } + + public async getTotalCount() { + const { totalCount } = await this.refine({ limit: 1 }).execute(); + return totalCount; + } + + public refine(query: Partial = {}) { + return new BackupListQuery({ + ...this.query, + ...query, + }); + } +} + +export class BackupList extends WithListData()( + BackupListQuery, +) { + public override readonly items: readonly BackupListItem[]; + public override readonly totalCount: number; + public constructor( + query: BackupListQueryModelData, + backups: BackupListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(backups); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/backup/Backup/BackupExport.ts b/packages/models/src/backup/Backup/BackupExport.ts new file mode 100644 index 00000000..9a35fa9f --- /dev/null +++ b/packages/models/src/backup/Backup/BackupExport.ts @@ -0,0 +1,24 @@ +import { DateTime } from "luxon"; + +import type { BackupExportData } from "./types.js"; + +import { DataModel } from "../../base/index.js"; + +export class BackupExport extends DataModel { + public readonly downloadUrl?: string; + public readonly expiresAt?: DateTime; + public readonly format?: string; + public readonly isCompleted: boolean; + public readonly isPending: boolean; + + public constructor(data: BackupExportData) { + super(data); + this.isCompleted = data.phase === "Completed"; + this.isPending = !this.isCompleted; + this.expiresAt = data.expiresAt + ? DateTime.fromISO(data.expiresAt) + : undefined; + this.downloadUrl = data.downloadURL; + this.format = data.format; + } +} diff --git a/packages/models/src/backup/Backup/behaviors/api.ts b/packages/models/src/backup/Backup/behaviors/api.ts new file mode 100644 index 00000000..0304ab3d --- /dev/null +++ b/packages/models/src/backup/Backup/behaviors/api.ts @@ -0,0 +1,99 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { BackupBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount } from "../../../base/index.js"; + +export const apiBackupBehaviors = ( + client: MittwaldAPIV2Client, +): BackupBehaviors => ({ + list: async (projectId, query) => { + const response = await client.backup.listProjectBackups({ + queryParameters: query, + projectId, + }); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + findToc: async (projectBackupId, directory) => { + const response = await client.backup.getProjectBackupDirectories({ + queryParameters: { directory }, + projectBackupId, + }); + + if (response.status === 200) { + return response.data; + } + }, + + updateExpiryDate: async (projectBackupId, expiryDate) => { + const response = await client.backup.updateProjectBackup({ + data: { expirationTime: expiryDate }, + projectBackupId, + }); + validateResponse(response, 204); + }, + + find: async (projectBackupId) => { + const response = await client.backup.getProjectBackup({ projectBackupId }); + if (response.status === 200) { + return response.data; + } + validateResponse(response, [404, 403]); + }, + + findDatabaseBackups: async (projectBackupId) => { + const response = await client.backup.getProjectBackupDatabaseDumps({ + projectBackupId, + }); + + if (response.status === 200) { + return response.data; + } + }, + + updateDescription: async (projectBackupId, description) => { + const response = await client.backup.updateProjectBackup({ + data: { description }, + projectBackupId, + }); + validateResponse(response, 204); + }, + + createRestoreRequest: async (projectBackupId, data) => { + const response = await client.backup.requestProjectBackupRestore({ + projectBackupId, + data, + }); + validateResponse(response, 204); + }, + + create: async (projectId, data) => { + const response = await client.backup.createProjectBackup({ + projectId, + data, + }); + validateResponse(response, 201); + return response.data; + }, + + createExport: async (projectBackupId, data) => { + const response = await client.backup.createProjectBackupExport({ + projectBackupId, + data, + }); + validateResponse(response, 204); + }, + + delete: async (projectBackupId) => { + const response = await client.backup.deleteProjectBackup({ + projectBackupId, + }); + validateResponse(response, 204); + }, +}); diff --git a/packages/models/src/backup/Backup/behaviors/index.ts b/packages/models/src/backup/Backup/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/backup/Backup/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/backup/Backup/behaviors/types.ts b/packages/models/src/backup/Backup/behaviors/types.ts new file mode 100644 index 00000000..072a51b2 --- /dev/null +++ b/packages/models/src/backup/Backup/behaviors/types.ts @@ -0,0 +1,56 @@ +import type { QueryResponseData } from "../../../base/index.js"; +import type { + BackupCreatePathRestoreRequestData, + BackupCreateExportRequestData, + BackupCreateRequestData, + BackupListQueryData, + BackupListItemData, + BackupTocData, + BackupDbData, + BackupData, +} from "../types.js"; + +export interface BackupBehaviors { + createRestoreRequest: ( + projectBackupId: string, + data: BackupCreatePathRestoreRequestData, + ) => Promise; + + list: ( + projectId: string, + query?: BackupListQueryData, + ) => Promise>; + + createExport: ( + projectBackupId: string, + data: BackupCreateExportRequestData, + ) => Promise; + + findToc: ( + projectBackupId: string, + directory: string, + ) => Promise; + + create: ( + projectId: string, + data: BackupCreateRequestData, + ) => Promise<{ id: string }>; + + updateDescription: ( + projectBackupId: string, + description?: string, + ) => Promise; + + updateExpiryDate: ( + projectBackupId: string, + expiryDate?: string, + ) => Promise; + + findDatabaseBackups: ( + projectBackupId: string, + ) => Promise; + + find: (projectBackupId: string) => Promise; + + delete: (projectBackupId: string) => Promise; +} diff --git a/packages/models/src/backup/Backup/index.ts b/packages/models/src/backup/Backup/index.ts new file mode 100644 index 00000000..1760d756 --- /dev/null +++ b/packages/models/src/backup/Backup/index.ts @@ -0,0 +1,3 @@ +export * from "./Backup.js"; +export * from "./BackupExport.js"; +export * from "./types.js"; diff --git a/packages/models/src/backup/Backup/types.ts b/packages/models/src/backup/Backup/types.ts new file mode 100644 index 00000000..0144e4a0 --- /dev/null +++ b/packages/models/src/backup/Backup/types.ts @@ -0,0 +1,34 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import type { Project } from "../../project/index.js"; + +export type BackupData = + MittwaldAPIV2.Operations.BackupGetProjectBackup.ResponseData; + +export type BackupListItemData = + MittwaldAPIV2.Operations.BackupListProjectBackups.ResponseData[number]; + +export type BackupListQueryData = + MittwaldAPIV2.Paths.V2ProjectsProjectIdBackups.Get.Parameters.Query; + +export type BackupListQueryModelData = { + project: Project | string; +} & BackupListQueryData; + +export type BackupCreateRequestData = + MittwaldAPIV2.Paths.V2ProjectsProjectIdBackups.Post.Parameters.RequestBody; + +export type BackupCreateExportRequestData = + MittwaldAPIV2.Paths.V2ProjectBackupsProjectBackupIdExport.Post.Parameters.RequestBody; + +export type BackupExportData = + MittwaldAPIV2.Components.Schemas.BackupProjectBackupExport; + +export type BackupCreatePathRestoreRequestData = + MittwaldAPIV2.Paths.V2ProjectBackupsProjectBackupIdRestore.Post.Parameters.RequestBody; + +export type BackupTocData = + MittwaldAPIV2.Operations.BackupGetProjectBackupDirectories.ResponseData; + +export type BackupDbData = + MittwaldAPIV2.Operations.BackupGetProjectBackupDatabaseDumps.ResponseData; diff --git a/packages/models/src/backup/BackupSchedule/BackupSchedule.test.ts b/packages/models/src/backup/BackupSchedule/BackupSchedule.test.ts new file mode 100644 index 00000000..14b61f66 --- /dev/null +++ b/packages/models/src/backup/BackupSchedule/BackupSchedule.test.ts @@ -0,0 +1,238 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +import type { + BackupScheduleCreateRequestData, + BackupScheduleUpdateRequestData, +} from "./types.js"; + +import { buildBackupScheduleData } from "../../testing/builders/buildBackupScheduleData.js"; +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { Project } from "../../project/index.js"; +import { + BackupScheduleDetailed, + BackupScheduleListItem, + BackupScheduleList, + BackupSchedule, +} from "./BackupSchedule.js"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +afterEach(resetBehaviors); + +describe("BackupSchedule lookup and creation", () => { + test("find delegates and returns a detailed schedule", async () => { + const find = vi + .fn() + .mockResolvedValue(buildBackupScheduleData({ id: "s-1" })); + installBehaviors({ backupSchedule: { find } }); + + const result = await BackupSchedule.find("s-1"); + + expect(find).toHaveBeenCalledWith("s-1"); + expect(result).toBeInstanceOf(BackupScheduleDetailed); + expect(result?.id).toBe("s-1"); + }); + + test("find returns undefined for a missing schedule", async () => { + installBehaviors({ + backupSchedule: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + expect(await BackupSchedule.find("missing")).toBeUndefined(); + }); + + test("get returns a detailed schedule", async () => { + installBehaviors({ + backupSchedule: { + find: vi.fn().mockResolvedValue(buildBackupScheduleData({ id: "s-2" })), + }, + }); + + const result = await BackupSchedule.get("s-2"); + + expect(result).toBeInstanceOf(BackupScheduleDetailed); + expect(result.id).toBe("s-2"); + }); + + test("get throws ObjectNotFoundError for a missing schedule", async () => { + installBehaviors({ + backupSchedule: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(BackupSchedule.get("missing")).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("create delegates and returns a schedule reference", async () => { + const create = vi + .fn() + .mockResolvedValue(buildBackupScheduleData({ id: "created-id" })); + const data: BackupScheduleCreateRequestData = { + description: "nightly", + schedule: "0 3 * * *", + ttl: "P7D", + }; + installBehaviors({ backupSchedule: { create } }); + + const result = await BackupSchedule.create(Project.ofId("p-1"), data); + + expect(create).toHaveBeenCalledWith("p-1", data); + expect(result).toBeInstanceOf(BackupSchedule); + expect(result.id).toBe("created-id"); + }); +}); + +describe("BackupSchedule list query", () => { + test("materializes items and derives total count", async () => { + const list = vi.fn().mockResolvedValue({ + items: [ + buildBackupScheduleData({ id: "s-1" }), + buildBackupScheduleData({ id: "s-2" }), + ], + totalCount: 2, + }); + installBehaviors({ backupSchedule: { list } }); + + const result = await BackupSchedule.query(Project.ofId("p-1")).execute(); + + expect(result).toBeInstanceOf(BackupScheduleList); + expect(result.items).toHaveLength(2); + expect(result.items[0]).toBeInstanceOf(BackupScheduleListItem); + expect(result.totalCount).toBe(2); + expect(list).toHaveBeenCalledWith("p-1", expect.any(Object)); + }); +}); + +describe("BackupSchedule common variant", () => { + test("findCommon on a reference delegates to findDetailed", async () => { + const find = vi + .fn() + .mockResolvedValue(buildBackupScheduleData({ id: "s-1" })); + installBehaviors({ backupSchedule: { find } }); + + const result = await BackupSchedule.ofId("s-1").findCommon(); + + expect(find).toHaveBeenCalledWith("s-1"); + expect(result).toBeInstanceOf(BackupScheduleDetailed); + expect(result?.id).toBe("s-1"); + }); + + test("findCommon on a reference resolves undefined when not found", async () => { + installBehaviors({ + backupSchedule: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + BackupSchedule.ofId("missing").findCommon(), + ).resolves.toBeUndefined(); + }); + + test("getCommon on a reference delegates and returns the detailed variant", async () => { + const find = vi + .fn() + .mockResolvedValue(buildBackupScheduleData({ id: "s-3" })); + installBehaviors({ backupSchedule: { find } }); + + const result = await BackupSchedule.ofId("s-3").getCommon(); + + expect(find).toHaveBeenCalledWith("s-3"); + expect(result).toBeInstanceOf(BackupScheduleDetailed); + expect(result.id).toBe("s-3"); + }); + + test("getCommon on a missing reference rejects with ObjectNotFoundError", async () => { + installBehaviors({ + backupSchedule: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + BackupSchedule.ofId("missing").getCommon(), + ).rejects.toBeInstanceOf(ObjectNotFoundError); + }); + + test("findCommon and getCommon on a materialized model do not re-fetch", async () => { + const find = vi.fn(); + installBehaviors({ backupSchedule: { find } }); + const item = new BackupScheduleListItem( + buildBackupScheduleData({ id: "s-4" }), + ); + + await expect(item.findCommon()).resolves.toBe(item); + await expect(item.getCommon()).resolves.toBe(item); + expect(find).not.toHaveBeenCalled(); + }); +}); + +describe("BackupSchedule data", () => { + test("maps data and project reference", () => { + const item = new BackupScheduleListItem( + buildBackupScheduleData({ + description: "nightly", + schedule: "0 4 * * *", + isSystemBackup: true, + projectId: "p-1", + ttl: "P7D", + }), + ); + + expect(item.description).toBe("nightly"); + expect(item.ttl).toBe("P7D"); + expect(item.schedule).toBe("0 4 * * *"); + expect(item.isSystemBackup).toBe(true); + expect(item.project).toBeInstanceOf(Project); + expect(item.project.id).toBe("p-1"); + }); + + test("leaves absent optional fields undefined", () => { + const item = new BackupScheduleListItem( + buildBackupScheduleData({ + description: undefined, + schedule: undefined, + ttl: undefined, + }), + ); + + expect(item.description).toBeUndefined(); + expect(item.ttl).toBeUndefined(); + expect(item.schedule).toBeUndefined(); + }); + + test("findCommon and getCommon resolve to an existing common model", async () => { + const item = new BackupScheduleListItem(buildBackupScheduleData()); + + await expect(item.findCommon()).resolves.toBe(item); + await expect(item.getCommon()).resolves.toBe(item); + }); +}); + +describe("BackupSchedule mutations", () => { + test("update delegates with id and data", async () => { + const update = vi.fn().mockResolvedValue(undefined); + const data: BackupScheduleUpdateRequestData = { description: "updated" }; + installBehaviors({ backupSchedule: { update } }); + + await BackupSchedule.ofId("s-1").update(data); + + expect(update).toHaveBeenCalledWith("s-1", data); + }); + + test("delete delegates with the id", async () => { + const deleteBehavior = vi.fn().mockResolvedValue(undefined); + installBehaviors({ backupSchedule: { delete: deleteBehavior } }); + + await BackupSchedule.ofId("s-1").delete(); + + expect(deleteBehavior).toHaveBeenCalledWith("s-1"); + }); +}); diff --git a/packages/models/src/backup/BackupSchedule/BackupSchedule.ts b/packages/models/src/backup/BackupSchedule/BackupSchedule.ts new file mode 100644 index 00000000..29505ebc --- /dev/null +++ b/packages/models/src/backup/BackupSchedule/BackupSchedule.ts @@ -0,0 +1,173 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; + +import type { + BackupScheduleCreateRequestData, + BackupScheduleUpdateRequestData, + BackupScheduleListQueryData, + BackupScheduleListItemData, + BackupScheduleData, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { Project } from "../../project/internal.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "BackupSchedule", +}) +export class BackupSchedule extends ReferenceModel { + public static async create( + project: Project, + data: BackupScheduleCreateRequestData, + ) { + const response = await config.behaviors.backupSchedule.create( + project.id, + data, + ); + + return new BackupSchedule(response.id); + } + + public static async find(id: string) { + const data = await config.behaviors.backupSchedule.find(id); + if (data) { + return new BackupScheduleDetailed(data); + } + } + + public static async get(id: string) { + const schedule = await BackupSchedule.find(id); + assertObjectFound(schedule, BackupSchedule, id); + return schedule; + } + + public static ofId(id: string) { + return new BackupSchedule(id); + } + + public static query( + project: Project, + query: BackupScheduleListQueryData = {}, + ) { + return new BackupScheduleListQuery(project, query); + } + + public async delete() { + await config.behaviors.backupSchedule.delete(this.id); + } + + public async findCommon(): Promise { + return this instanceof BackupScheduleCommon ? this : this.findDetailed(); + } + + public findDetailed(): Promise { + return BackupSchedule.find(this.id); + } + + public async getCommon(): Promise { + return this instanceof BackupScheduleCommon ? this : this.getDetailed(); + } + + public getDetailed(): Promise { + return BackupSchedule.get(this.id); + } + + public async update(data: BackupScheduleUpdateRequestData) { + return await config.behaviors.backupSchedule.update(this.id, data); + } +} + +export class BackupScheduleCommon extends WithData< + BackupScheduleListItemData | BackupScheduleData +>()(BackupSchedule) { + public override readonly data: + BackupScheduleListItemData | BackupScheduleData; + public readonly description?: string; + public readonly isSystemBackup: boolean; + public readonly project: Project; + public readonly schedule?: string; + public readonly ttl?: string; + + public constructor(data: BackupScheduleListItemData | BackupScheduleData) { + super(data.id); + this.data = data; + this.description = data.description; + this.ttl = data.ttl; + this.schedule = data.schedule; + this.isSystemBackup = data.isSystemBackup; + this.project = Project.ofId(data.projectId); + } +} + +export class BackupScheduleDetailed extends BackupScheduleCommon { + public override readonly data: BackupScheduleData; + public constructor(data: BackupScheduleData) { + super(data); + this.data = data; + } +} + +export class BackupScheduleListItem extends BackupScheduleCommon { + public override readonly data: BackupScheduleListItemData; + public constructor(data: BackupScheduleListItemData) { + super(data); + this.data = data; + } +} + +export class BackupScheduleListQuery extends ListQueryModel { + public readonly project: Project; + + public constructor( + project: Project, + query: BackupScheduleListQueryData = {}, + ) { + super(query, { + dependencies: [project.id], + }); + this.project = project; + } + + public async execute() { + const { totalCount, items } = await config.behaviors.backupSchedule.list( + this.project.id, + this.query, + ); + return new BackupScheduleList( + this.project, + this.query, + items.map((d) => new BackupScheduleListItem(d)), + totalCount, + ); + } + + public refine(query: BackupScheduleListQueryData) { + return new BackupScheduleListQuery(this.project, { + ...this.query, + ...query, + }); + } +} + +export class BackupScheduleList extends WithListData()( + BackupScheduleListQuery, +) { + public override readonly items: readonly BackupScheduleListItem[]; + public override readonly totalCount: number; + public constructor( + project: Project, + query: BackupScheduleListQueryData, + schedules: BackupScheduleListItem[], + totalCount: number, + ) { + super(project, query); + this.items = Object.freeze(schedules); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/backup/BackupSchedule/behaviors/api.ts b/packages/models/src/backup/BackupSchedule/behaviors/api.ts new file mode 100644 index 00000000..9f228973 --- /dev/null +++ b/packages/models/src/backup/BackupSchedule/behaviors/api.ts @@ -0,0 +1,57 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { BackupScheduleBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount } from "../../../base/index.js"; + +export const apiBackupScheduleBehaviors = ( + client: MittwaldAPIV2Client, +): BackupScheduleBehaviors => ({ + find: async (projectBackupScheduleId) => { + const response = await client.backup.getProjectBackupSchedule({ + projectBackupScheduleId, + }); + if (response.status === 200) { + return response.data; + } + validateResponse(response, [403, 404]); + }, + + list: async (projectId) => { + const response = await client.backup.listProjectBackupSchedules({ + projectId, + }); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + update: async (projectBackupScheduleId, data) => { + const response = await client.backup.updateProjectBackupSchedule({ + projectBackupScheduleId, + data, + }); + + validateResponse(response, 204); + }, + + create: async (projectId, data) => { + const response = await client.backup.createProjectBackupSchedule({ + projectId, + data, + }); + + validateResponse(response, 201); + return response.data; + }, + + delete: async (projectBackupScheduleId) => { + const response = await client.backup.deleteProjectBackupSchedule({ + projectBackupScheduleId, + }); + validateResponse(response, 204); + }, +}); diff --git a/packages/models/src/backup/BackupSchedule/behaviors/index.ts b/packages/models/src/backup/BackupSchedule/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/backup/BackupSchedule/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/backup/BackupSchedule/behaviors/types.ts b/packages/models/src/backup/BackupSchedule/behaviors/types.ts new file mode 100644 index 00000000..71a075ba --- /dev/null +++ b/packages/models/src/backup/BackupSchedule/behaviors/types.ts @@ -0,0 +1,30 @@ +import type { + BackupScheduleCreateRequestData, + BackupScheduleUpdateRequestData, + BackupScheduleListQueryData, + BackupScheduleListItemData, + BackupScheduleData, +} from "../types.js"; + +export interface BackupScheduleBehaviors { + list: ( + projectId: string, + query?: BackupScheduleListQueryData, + ) => Promise<{ items: BackupScheduleListItemData[]; totalCount: number }>; + + create: ( + projectId: string, + data: BackupScheduleCreateRequestData, + ) => Promise; + + update: ( + projectBackupScheduleId: string, + data: BackupScheduleUpdateRequestData, + ) => Promise; + + find: ( + projectBackupScheduleId: string, + ) => Promise; + + delete: (projectBackupScheduleId: string) => Promise; +} diff --git a/packages/models/src/backup/BackupSchedule/index.ts b/packages/models/src/backup/BackupSchedule/index.ts new file mode 100644 index 00000000..e956749a --- /dev/null +++ b/packages/models/src/backup/BackupSchedule/index.ts @@ -0,0 +1,2 @@ +export * from "./BackupSchedule.js"; +export * from "./types.js"; diff --git a/packages/models/src/backup/BackupSchedule/types.ts b/packages/models/src/backup/BackupSchedule/types.ts new file mode 100644 index 00000000..315ec38a --- /dev/null +++ b/packages/models/src/backup/BackupSchedule/types.ts @@ -0,0 +1,16 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type BackupScheduleData = + MittwaldAPIV2.Operations.BackupGetProjectBackupSchedule.ResponseData; + +export type BackupScheduleListItemData = + MittwaldAPIV2.Operations.BackupListProjectBackupSchedules.ResponseData[number]; + +export type BackupScheduleListQueryData = + MittwaldAPIV2.Paths.V2ProjectsProjectIdBackupSchedules.Get.Parameters.Query; + +export type BackupScheduleCreateRequestData = + MittwaldAPIV2.Paths.V2ProjectsProjectIdBackupSchedules.Post.Parameters.RequestBody; + +export type BackupScheduleUpdateRequestData = + MittwaldAPIV2.Paths.V2ProjectBackupSchedulesProjectBackupScheduleId.Patch.Parameters.RequestBody; diff --git a/packages/models/src/backup/index.ts b/packages/models/src/backup/index.ts new file mode 100644 index 00000000..393b007f --- /dev/null +++ b/packages/models/src/backup/index.ts @@ -0,0 +1,2 @@ +export * from "./Backup/index.js"; +export * from "./BackupSchedule/index.js"; diff --git a/packages/models/src/base/DataModel.ts b/packages/models/src/base/DataModel.ts deleted file mode 100644 index 29ddd7e0..00000000 --- a/packages/models/src/base/DataModel.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { ReadonlyDeep } from "type-fest"; -import deepFreeze from "../lib/deepFreeze.js"; - -export class DataModel { - public readonly data: ReadonlyDeep; - - public constructor(data: T) { - this.data = deepFreeze(data); - } -} diff --git a/packages/models/src/base/ListQueryModel.ts b/packages/models/src/base/ListQueryModel.ts deleted file mode 100644 index 0a33ee22..00000000 --- a/packages/models/src/base/ListQueryModel.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { hash } from "object-code"; -import { joinedId } from "../lib/joinedId.js"; - -interface Options { - dependencies?: string[]; -} - -export abstract class ListQueryModel { - protected readonly query: TQuery; - public readonly queryId: string; - - public constructor(query: TQuery, opts: Options = {}) { - const { dependencies = [] } = opts; - this.query = query; - this.queryId = joinedId(hash(query), ...dependencies); - } -} diff --git a/packages/models/src/base/ReferenceModel.ts b/packages/models/src/base/ReferenceModel.ts deleted file mode 100644 index 30f8054b..00000000 --- a/packages/models/src/base/ReferenceModel.ts +++ /dev/null @@ -1,11 +0,0 @@ -export abstract class ReferenceModel { - public readonly id: string; - - public constructor(id: string) { - this.id = id; - } - - public describe(): string { - return `${this.constructor.name}@${this.id}`; - } -} diff --git a/packages/models/src/base/api/getModelRequestOptions.ts b/packages/models/src/base/api/getModelRequestOptions.ts new file mode 100644 index 00000000..f3c09edb --- /dev/null +++ b/packages/models/src/base/api/getModelRequestOptions.ts @@ -0,0 +1,4 @@ +import type { AxiosRequestConfig } from "axios"; + +export const getAxiosRequestConfig = (request: AxiosRequestConfig) => + request as AxiosRequestConfig; diff --git a/packages/models/src/base/api/onBeforeRequest.ts b/packages/models/src/base/api/onBeforeRequest.ts new file mode 100644 index 00000000..78b8dc52 --- /dev/null +++ b/packages/models/src/base/api/onBeforeRequest.ts @@ -0,0 +1,20 @@ +import type { ApiClientRequest } from "./types.js"; + +export type OnBeforeRequestHandler = (request: ApiClientRequest) => void; + +const defaultOnBeforeRequestHandler = new Set(); + +export const registerDefaultOnBeforeRequestHandler = ( + handler: OnBeforeRequestHandler, +): OnBeforeRequestHandler => { + defaultOnBeforeRequestHandler.add(handler); + return handler; +}; + +export const executeDefaultOnBeforeRequestHandlers = ( + config: ApiClientRequest, +): void => { + defaultOnBeforeRequestHandler.forEach((handler) => { + handler(config); + }); +}; diff --git a/packages/models/src/base/api/resolveTotalCount.test.ts b/packages/models/src/base/api/resolveTotalCount.test.ts new file mode 100644 index 00000000..132d147f --- /dev/null +++ b/packages/models/src/base/api/resolveTotalCount.test.ts @@ -0,0 +1,54 @@ +import { type AxiosResponse, AxiosHeaders } from "axios"; +import { describe, expect, test } from "vitest"; + +import { resolveTotalCount } from "./resolveTotalCount.js"; + +const responseWith = ( + data: unknown[], + headers?: Record, +): AxiosResponse => + ({ + headers: headers ? new AxiosHeaders(headers) : {}, + config: {} as never, + statusText: "OK", + status: 200, + data, + }) as AxiosResponse; + +describe("resolveTotalCount", () => { + test("uses the x-pagination-totalcount header when present", () => { + const response = responseWith([1, 2], { "x-pagination-totalcount": "57" }); + expect(resolveTotalCount(response)).toBe(57); + }); + + test("falls back to the page length when the header is absent", () => { + const response = responseWith([1, 2, 3], {}); + expect(resolveTotalCount(response)).toBe(3); + }); + + test("falls back to the page length when headers are not AxiosHeaders", () => { + const response = responseWith([1, 2, 3, 4]); + expect(resolveTotalCount(response)).toBe(4); + }); + + test("falls back to the page length for a non-numeric header", () => { + const response = responseWith([1], { "x-pagination-totalcount": "n/a" }); + expect(resolveTotalCount(response)).toBe(1); + }); + + test("uses an explicit fallbackCount for a nested-list response", () => { + const response = { + data: { leads: [1, 2, 3] }, + config: {} as never, + statusText: "OK", + status: 200, + headers: {}, + } as AxiosResponse<{ leads: number[] }>; + expect(resolveTotalCount(response, response.data.leads.length)).toBe(3); + }); + + test("prefers the header even when a fallbackCount is given", () => { + const response = responseWith([1, 2], { "x-pagination-totalcount": "99" }); + expect(resolveTotalCount(response, 2)).toBe(99); + }); +}); diff --git a/packages/models/src/base/api/resolveTotalCount.ts b/packages/models/src/base/api/resolveTotalCount.ts new file mode 100644 index 00000000..92be22a9 --- /dev/null +++ b/packages/models/src/base/api/resolveTotalCount.ts @@ -0,0 +1,37 @@ +import { type AxiosResponse, AxiosHeaders } from "axios"; + +const HEADER_NAME = "x-pagination-totalcount"; + +/** + * The single source of truth for a list response's total count. + * + * Returns the `x-pagination-totalcount` header when the API sends it, otherwise + * `fallbackCount` — which defaults to the number of items on the returned page + * (`response.data.length`). Unlike `extractTotalCountHeader` (which throws when + * the header is absent), this never throws: a route that starts sending the + * header is picked up automatically, with the page-length fallback until then. + * + * Pass `fallbackCount` explicitly when the page items are not `response.data` + * itself but nested inside it (e.g. `response.data.leads.length`). Total counts + * are derived here, in the behavior layer; models must not compute them. + */ +export const resolveTotalCount = ( + response: AxiosResponse, + fallbackCount: number = Array.isArray(response.data) + ? response.data.length + : 0, +): number => { + const header = + response.headers instanceof AxiosHeaders + ? response.headers.get(HEADER_NAME) + : undefined; + + if (typeof header === "string") { + const parsed = Number(header); + if (Number.isFinite(parsed)) { + return parsed; + } + } + + return fallbackCount; +}; diff --git a/packages/models/src/base/api/typeFixes.ts b/packages/models/src/base/api/typeFixes.ts new file mode 100644 index 00000000..27956bb3 --- /dev/null +++ b/packages/models/src/base/api/typeFixes.ts @@ -0,0 +1,5 @@ +export const anyStatus400 = 400 as any; +export const anyStatus401 = 401 as any; +export const anyStatus403 = 403 as any; +export const anyStatus404 = 404 as any; +export const anyStatus409 = 409 as any; diff --git a/packages/models/src/base/api/types.ts b/packages/models/src/base/api/types.ts new file mode 100644 index 00000000..d4d8eb1a --- /dev/null +++ b/packages/models/src/base/api/types.ts @@ -0,0 +1,6 @@ +import type { AnyResponse } from "@mittwald/api-client-commons"; +import type { Commons } from "@mittwald/api-client"; + +export type ApiClientRequest = Commons.Request; + +export type ApiClientResponse = AnyResponse; diff --git a/packages/models/src/base/api/validateResponse.ts b/packages/models/src/base/api/validateResponse.ts new file mode 100644 index 00000000..23929988 --- /dev/null +++ b/packages/models/src/base/api/validateResponse.ts @@ -0,0 +1,29 @@ +import type { Commons } from "@mittwald/api-client"; + +import { assertOneOfStatus, assertStatus } from "@mittwald/api-client"; + +import { + type ResponseValidationOptions, + withResponseValidation, +} from "./withResponseValidation.js"; + +export function validateResponse< + T extends Commons.Response, + S extends T["status"], +>( + response: T, + status: S[] | S, + options?: ResponseValidationOptions, +): asserts response is { + status: S; +} & T { + const assertionWithValidation = withResponseValidation(() => { + if (Array.isArray(status)) { + assertOneOfStatus(response, status); + } else { + assertStatus(response, status); + } + }, options); + + assertionWithValidation(); +} diff --git a/packages/models/src/base/api/withModelRequestOptions.ts b/packages/models/src/base/api/withModelRequestOptions.ts new file mode 100644 index 00000000..e1bc723b --- /dev/null +++ b/packages/models/src/base/api/withModelRequestOptions.ts @@ -0,0 +1,20 @@ +import type { Commons } from "@mittwald/api-client"; +import type { AxiosRequestConfig } from "axios"; + +// Loads the `declare module "axios"` augmentation that contributes the +// `retryCache` request option consumed by this package's call sites. +import type {} from "@mittwald/axios-cache-with-retry"; + +import { executeDefaultOnBeforeRequestHandlers } from "../../base/api/onBeforeRequest.js"; + +export const withAxiosRequestConfig = ( + requestOptions: AxiosRequestConfig = {}, +): Commons.RequestOptions => { + return { + onBeforeRequest: (config) => { + const requestConfig = config.requestConfig; + Object.assign(requestConfig, requestOptions); + executeDefaultOnBeforeRequestHandlers(config); + }, + }; +}; diff --git a/packages/models/src/base/api/withResponseValidation.ts b/packages/models/src/base/api/withResponseValidation.ts new file mode 100644 index 00000000..4c13ebf3 --- /dev/null +++ b/packages/models/src/base/api/withResponseValidation.ts @@ -0,0 +1,39 @@ +import { Commons } from "@mittwald/api-client"; + +import { + type ValidationErrorFromApiResponseOptions, + type ValidationErrorObject, + ValidationError, +} from "../../errors/index.js"; + +type AnyFn = (...args: unknown[]) => unknown; + +export interface ResponseValidationOptions { + validationError?: ValidationErrorFromApiResponseOptions; +} + +const mapError = (error: unknown, options: ResponseValidationOptions) => { + if (error instanceof Commons.ApiClientError && error.response) { + const validationError = ValidationError.fromResponse( + error.response as Commons.AnyResponse, + options.validationError, + ); + + if (validationError) { + throw validationError; + } + } + throw error; +}; + +export const withResponseValidation = ( + fn: T, + options: ResponseValidationOptions = {}, +): T => + ((...args) => { + try { + return fn(...args); + } catch (error) { + mapError(error, options); + } + }) as T; diff --git a/packages/models/src/base/assertObjectFound.ts b/packages/models/src/base/assertObjectFound.ts deleted file mode 100644 index 182e08fd..00000000 --- a/packages/models/src/base/assertObjectFound.ts +++ /dev/null @@ -1,18 +0,0 @@ -import ObjectNotFoundError from "../errors/ObjectNotFoundError.js"; -import { Constructor } from "type-fest"; -import { ReferenceModel } from "./ReferenceModel.js"; - -export default function assertObjectFound( - obj: T | undefined, - theClass: Constructor, - refIdOrObject: string | ReferenceModel, -): asserts obj is T { - if (obj === undefined) { - const refName = - typeof refIdOrObject === "string" - ? refIdOrObject - : refIdOrObject.toString(); - - throw new ObjectNotFoundError(theClass.name, refName); - } -} diff --git a/packages/models/src/base/index.ts b/packages/models/src/base/index.ts index 2b4dde37..eacb8995 100644 --- a/packages/models/src/base/index.ts +++ b/packages/models/src/base/index.ts @@ -1,6 +1,17 @@ -export * from "./assertObjectFound.js"; -export * from "./DataModel.js"; -export * from "./ReferenceModel.js"; -export * from "./ListDataModel.js"; -export * from "./ListQueryModel.js"; -export * from "./types.js"; +export * from "./api/getModelRequestOptions.js"; +export * from "./api/onBeforeRequest.js"; +export * from "./api/resolveTotalCount.js"; +export * from "./api/typeFixes.js"; +export * from "./api/types.js"; +export * from "./api/validateResponse.js"; +export * from "./api/withModelRequestOptions.js"; +export * from "./lib/assertObjectFound.js"; +export * from "./lib/extractId.js"; +export * from "./lib/required.js"; +export * from "./lib/sortByPositionMeta.js"; +export * from "./models/DataModel.js"; +export * from "./models/ListDataModel.js"; +export * from "./models/ListQueryModel.js"; +export * from "./models/mixins.js"; +export * from "./models/ReferenceModel.js"; +export * from "./models/types.js"; diff --git a/packages/models/src/base/lib/assertInstanceOf.ts b/packages/models/src/base/lib/assertInstanceOf.ts new file mode 100644 index 00000000..37fa9907 --- /dev/null +++ b/packages/models/src/base/lib/assertInstanceOf.ts @@ -0,0 +1,14 @@ +import type { AbstractClass } from "type-fest"; +import type { Class } from "@sindresorhus/is"; + +import invariant from "tiny-invariant"; + +export function assertInstanceOf | Class>( + instance: InstanceType, + type: T, +): asserts instance is InstanceType { + invariant( + instance instanceof type, + `Expected value which is \`${type.name}\`, received value of type \`${instance.constructor.name}\`.`, + ); +} diff --git a/packages/models/src/base/lib/assertObjectFound.test.ts b/packages/models/src/base/lib/assertObjectFound.test.ts new file mode 100644 index 00000000..5694bd6c --- /dev/null +++ b/packages/models/src/base/lib/assertObjectFound.test.ts @@ -0,0 +1,62 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, expect, test, vi } from "vitest"; + +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { resetBehaviors } from "../../testing/index.js"; +import { Project } from "../../project/index.js"; + +// Names any class by its JS name, so ObjectNotFoundError's type does not depend on the ghost registry. +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import assertObjectFound from "./assertObjectFound.js"; + +afterEach(resetBehaviors); + +class Foo {} + +test("returns normally and narrows a defined value", () => { + const value: { name: string } | undefined = { name: "found" }; + + assertObjectFound(value, Foo, "abc"); + + expect(value.name).toBe("found"); +}); + +test("throws an ObjectNotFoundError containing the type and string reference", () => { + try { + assertObjectFound(undefined, Foo, "abc"); + } catch (error) { + expect(error).toBeInstanceOf(ObjectNotFoundError); + expect(error).toMatchObject({ + name: "ObjectNotFoundError", + refName: "abc", + type: "Foo", + }); + expect(error).toHaveProperty( + "message", + expect.stringMatching(/Foo@abc not found/), + ); + return; + } + + throw new Error("Expected assertObjectFound to throw"); +}); + +test("uses a reference model string representation as the reference name", () => { + const project = Project.ofId("p-1"); + + try { + assertObjectFound(undefined, Foo, project); + } catch (error) { + expect(error).toBeInstanceOf(ObjectNotFoundError); + expect(error).toHaveProperty("refName", project.toString()); + return; + } + + throw new Error("Expected assertObjectFound to throw"); +}); diff --git a/packages/models/src/base/lib/assertObjectFound.ts b/packages/models/src/base/lib/assertObjectFound.ts new file mode 100644 index 00000000..37725138 --- /dev/null +++ b/packages/models/src/base/lib/assertObjectFound.ts @@ -0,0 +1,20 @@ +import type { Class } from "type-fest"; + +import type { ReferenceModel } from "../models/ReferenceModel.js"; + +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; + +export default function assertObjectFound( + obj: T | undefined, + type: Class, + refIdOrObject: ReferenceModel | string, +): asserts obj is T { + if (obj === undefined) { + const refName = + typeof refIdOrObject === "string" + ? refIdOrObject + : refIdOrObject.toString(); + + throw new ObjectNotFoundError(type, refName); + } +} diff --git a/packages/models/src/base/lib/extractId.test.ts b/packages/models/src/base/lib/extractId.test.ts new file mode 100644 index 00000000..e7991869 --- /dev/null +++ b/packages/models/src/base/lib/extractId.test.ts @@ -0,0 +1,19 @@ +import { afterEach, expect, test } from "vitest"; + +import { resetBehaviors } from "../../testing/index.js"; +import { Project } from "../../project/index.js"; +import { extractId } from "./extractId.js"; + +afterEach(resetBehaviors); + +test("returns a string reference unchanged", () => { + expect(extractId("abc")).toBe("abc"); +}); + +test("returns the id of a reference model", () => { + expect(extractId(Project.ofId("p-1"))).toBe("p-1"); +}); + +test("returns undefined for an undefined reference", () => { + expect(extractId(undefined)).toBeUndefined(); +}); diff --git a/packages/models/src/base/lib/extractId.ts b/packages/models/src/base/lib/extractId.ts new file mode 100644 index 00000000..03344fda --- /dev/null +++ b/packages/models/src/base/lib/extractId.ts @@ -0,0 +1,17 @@ +import type { ReferenceModel } from "../models/ReferenceModel.js"; + +export function extractId(from: ReferenceModel | string): string; + +export function extractId( + from: ReferenceModel | string | undefined, +): string | undefined; + +export function extractId(from?: ReferenceModel | string): string | undefined { + if (from === undefined) { + return; + } + if (typeof from === "string") { + return from; + } + return from.id; +} diff --git a/packages/models/src/base/lib/required.test.ts b/packages/models/src/base/lib/required.test.ts new file mode 100644 index 00000000..fbb49b80 --- /dev/null +++ b/packages/models/src/base/lib/required.test.ts @@ -0,0 +1,24 @@ +import { afterEach, expect, test } from "vitest"; + +import { resetBehaviors } from "../../testing/index.js"; +import { required } from "./required.js"; + +afterEach(resetBehaviors); + +test("returns present values unchanged", () => { + expect(required(0)).toBe(0); + expect(required("")).toBe(""); + expect(required(false)).toBe(false); +}); + +test("throws for undefined", () => { + expect(() => required(undefined)).toThrowError(/value/); +}); + +test("throws for null", () => { + expect(() => required(null)).toThrowError(/value/); +}); + +test("includes the value type in the error message", () => { + expect(() => required(undefined, "projectId")).toThrowError(/projectId/); +}); diff --git a/packages/models/src/base/lib/required.ts b/packages/models/src/base/lib/required.ts new file mode 100644 index 00000000..abba077b --- /dev/null +++ b/packages/models/src/base/lib/required.ts @@ -0,0 +1,12 @@ +import invariant from "tiny-invariant"; + +export function required( + value: T | undefined | null, + valueType = "value", +): T { + invariant( + value !== undefined && value !== null, + `Expected ${valueType} not to be undefined`, + ); + return value; +} diff --git a/packages/models/src/base/lib/sortByPositionMeta.ts b/packages/models/src/base/lib/sortByPositionMeta.ts new file mode 100644 index 00000000..d8500572 --- /dev/null +++ b/packages/models/src/base/lib/sortByPositionMeta.ts @@ -0,0 +1,20 @@ +interface WithPositionMeta { + positionMeta?: { + index?: number; + step?: string; + }; +} + +export function sortByPositionMeta( + items: T[], + commonStep = "common", +): T[] { + return [...items].sort((a, b) => { + const aIsCommon = (a.positionMeta?.step ?? commonStep) === commonStep; + const bIsCommon = (b.positionMeta?.step ?? commonStep) === commonStep; + if (aIsCommon !== bIsCommon) { + return aIsCommon ? -1 : 1; + } + return (a.positionMeta?.index ?? 0) - (b.positionMeta?.index ?? 0); + }); +} diff --git a/packages/models/src/base/models/BaseModel.ts b/packages/models/src/base/models/BaseModel.ts new file mode 100644 index 00000000..22f17bb1 --- /dev/null +++ b/packages/models/src/base/models/BaseModel.ts @@ -0,0 +1,24 @@ +import type { AbstractClass, Class } from "type-fest"; + +import { assertInstanceOf } from "../lib/assertInstanceOf.js"; + +export abstract class BaseModel { + public assertType | Class>( + type: T, + ): asserts this is InstanceType { + assertInstanceOf(this, type); + } + + public asType | Class>( + type: T, + ): InstanceType { + this.assertType(type); + return this; + } + + public isOfType | Class>( + type: T, + ): this is InstanceType { + return this instanceof type; + } +} diff --git a/packages/models/src/base/models/DataModel.test.ts b/packages/models/src/base/models/DataModel.test.ts new file mode 100644 index 00000000..4a61f74b --- /dev/null +++ b/packages/models/src/base/models/DataModel.test.ts @@ -0,0 +1,17 @@ +import { afterEach, describe, expect, test } from "vitest"; + +import { buildContainerData, resetBehaviors } from "../../testing/index.js"; +import { DataModel } from "./DataModel.js"; + +afterEach(resetBehaviors); + +describe("DataModel", () => { + test("carries the supplied data", () => { + const data = buildContainerData(); + + const model = new DataModel(data); + + expect(model.data).toBe(data); + expect(model.data).toEqual(data); + }); +}); diff --git a/packages/models/src/base/models/DataModel.ts b/packages/models/src/base/models/DataModel.ts new file mode 100644 index 00000000..f1804a93 --- /dev/null +++ b/packages/models/src/base/models/DataModel.ts @@ -0,0 +1,8 @@ +// todo: fix deep freeze +export class DataModel { + public readonly data: T; + + public constructor(data: T) { + this.data = data; + } +} diff --git a/packages/models/src/base/models/ListDataModel.test.ts b/packages/models/src/base/models/ListDataModel.test.ts new file mode 100644 index 00000000..a9e4163e --- /dev/null +++ b/packages/models/src/base/models/ListDataModel.test.ts @@ -0,0 +1,27 @@ +import { afterEach, describe, expect, test } from "vitest"; + +import { buildContainerData, resetBehaviors } from "../../testing/index.js"; +import { ListDataModel } from "./ListDataModel.js"; + +afterEach(resetBehaviors); + +describe("ListDataModel", () => { + test("carries the supplied items and total count", () => { + const items = [buildContainerData()]; + + const model = new ListDataModel(items, 3); + + expect(model.items).toEqual(items); + expect(model.totalCount).toBe(3); + }); + + test("freezes its items", () => { + const items = [buildContainerData()]; + const model = new ListDataModel(items, 1); + + expect(Object.isFrozen(model.items)).toBe(true); + expect(() => + (model.items as typeof items).push(buildContainerData()), + ).toThrow(); + }); +}); diff --git a/packages/models/src/base/ListDataModel.ts b/packages/models/src/base/models/ListDataModel.ts similarity index 100% rename from packages/models/src/base/ListDataModel.ts rename to packages/models/src/base/models/ListDataModel.ts diff --git a/packages/models/src/base/models/ListQueryModel.test.ts b/packages/models/src/base/models/ListQueryModel.test.ts new file mode 100644 index 00000000..f5d92ff9 --- /dev/null +++ b/packages/models/src/base/models/ListQueryModel.test.ts @@ -0,0 +1,73 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; + +import type { + ContainerListQueryData, + ContainerListItemData, +} from "../../container/Container/types.js"; + +import { ListQueryModel } from "./ListQueryModel.js"; +import { ListDataModel } from "./ListDataModel.js"; +import { config } from "../../config/config.js"; +import { + buildContainerData, + installBehaviors, + resetBehaviors, +} from "../../testing/index.js"; + +afterEach(resetBehaviors); + +class TestContainerListQuery extends ListQueryModel { + public constructor( + private readonly projectId: string, + query: ContainerListQueryData = {}, + ) { + super(query, { dependencies: [projectId] }); + } + + public async execute(): Promise> { + const { totalCount, items } = await config.behaviors.container.list( + this.projectId, + this.query, + ); + + return new ListDataModel([...items], totalCount); + } +} + +describe("ListQueryModel", () => { + test("creates a stable query id from dependencies and query structure", () => { + const first = new TestContainerListQuery("project-id", { + limit: 20, + page: 1, + }); + const equal = new TestContainerListQuery("project-id", { + limit: 20, + page: 1, + }); + const different = new TestContainerListQuery("project-id", { + limit: 20, + page: 2, + }); + + expect(first.queryId).toEqual(expect.any(String)); + expect(first.queryId).not.toHaveLength(0); + expect(equal.queryId).toBe(first.queryId); + expect(different.queryId).not.toBe(first.queryId); + }); + + test("delegates execution to the container behavior and materializes its result", async () => { + const query: ContainerListQueryData = { limit: 20, page: 1 }; + const items = [buildContainerData()]; + const list = vi.fn().mockResolvedValue({ totalCount: 7, items }); + installBehaviors({ container: { list } }); + + const result = await new TestContainerListQuery( + "project-id", + query, + ).execute(); + + expect(list).toHaveBeenCalledWith("project-id", query); + expect(result.items).toEqual(items); + expect(result.totalCount).toBe(7); + }); +}); diff --git a/packages/models/src/base/models/ListQueryModel.ts b/packages/models/src/base/models/ListQueryModel.ts new file mode 100644 index 00000000..233aabc1 --- /dev/null +++ b/packages/models/src/base/models/ListQueryModel.ts @@ -0,0 +1,70 @@ +import type { AxiosRequestConfig } from "axios"; + +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { hash } from "object-code"; + +import { ReferenceModel } from "./ReferenceModel.js"; +import { joinedId } from "../../lib/joinedId.js"; + +interface Options { + dependencies?: string[]; +} + +/** + * Reduce any model reference in a query to its id before hashing, so a field + * typed `Model | string` yields the same `queryId` whether the caller passes a + * model (a reference or a loaded model) or the bare id. Without this, hashing a + * loaded model would key the query on its whole payload instead of its + * identity. Shallow by design: query model-references are top-level fields. + */ +const normalizeQueryForHash = (query: unknown): unknown => { + if (query === null || typeof query !== "object" || Array.isArray(query)) { + return query; + } + return Object.fromEntries( + Object.entries(query as Record).map(([key, value]) => [ + key, + value instanceof ReferenceModel ? value.id : value, + ]), + ); +}; + +@GhostMakerModel({ + getId: (model) => model.queryId, +}) +export abstract class ListQueryModel { + public readonly queryId: string; + protected readonly query: TQuery; + + public constructor(query: TQuery, opts: Options = {}) { + const { dependencies = [] } = opts; + this.query = query; + this.queryId = joinedId( + ...dependencies, + hash(normalizeQueryForHash(query)), + ); + } + + /** + * Materialize the query into its list result (which always carries a + * `totalCount`). Implemented per model; the optional request config is + * threaded through to the behavior where the model supports it. + */ + public abstract execute( + options?: AxiosRequestConfig, + ): Promise<{ totalCount: number }>; + + /** + * Resolve just the total number of matching items. The default runs the query + * and reads `totalCount` off the result. A model may override this to + * `refine({ limit: 1 })` first — fetching a single-item page instead of the + * default one — but only where its query accepts a `limit` **and** the + * endpoint reports the total independently of the page size (otherwise + * `resolveTotalCount` would fall back to the page length and report `1`). Not + * every limit-capable model overrides; the rest use this default. + */ + public async getTotalCount(options?: AxiosRequestConfig): Promise { + const { totalCount } = await this.execute(options); + return totalCount; + } +} diff --git a/packages/models/src/base/models/ReferenceModel.test.ts b/packages/models/src/base/models/ReferenceModel.test.ts new file mode 100644 index 00000000..ac9dabe4 --- /dev/null +++ b/packages/models/src/base/models/ReferenceModel.test.ts @@ -0,0 +1,17 @@ +import { afterEach, describe, expect, test } from "vitest"; + +import { ReferenceModel } from "./ReferenceModel.js"; +import { resetBehaviors } from "../../testing/index.js"; + +afterEach(resetBehaviors); + +class TestReference extends ReferenceModel {} + +describe("ReferenceModel", () => { + test("constructs a reference from an id", () => { + const reference = new TestReference("reference-id"); + + expect(reference.id).toBe("reference-id"); + expect(reference.describe()).toBe("TestReference@reference-id"); + }); +}); diff --git a/packages/models/src/base/models/ReferenceModel.ts b/packages/models/src/base/models/ReferenceModel.ts new file mode 100644 index 00000000..29542ca5 --- /dev/null +++ b/packages/models/src/base/models/ReferenceModel.ts @@ -0,0 +1,19 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; + +import { BaseModel } from "./BaseModel.js"; + +@GhostMakerModel({ + getId: (model) => model.id, +}) +export abstract class ReferenceModel extends BaseModel { + public readonly id: string; + + public constructor(id: string) { + super(); + this.id = id; + } + + public describe(): string { + return `${this.constructor.name}@${this.id}`; + } +} diff --git a/packages/models/src/base/models/mixins.ts b/packages/models/src/base/models/mixins.ts new file mode 100644 index 00000000..82af59aa --- /dev/null +++ b/packages/models/src/base/models/mixins.ts @@ -0,0 +1,49 @@ +/** + * Zero-dependency capability mixins (ADR-0004). They bolt a data payload onto + * an identity-chain base (a {@link BaseModel}/{@link ReferenceModel} subclass) + * while preserving native `instanceof` across the whole prototype chain. + * + * Each mixin only contributes a typed marker (`declare readonly …`); the + * concrete class re-declares and assigns its own field(s) and threads the base + * constructor arguments through `super(...)`. See + * `docs/adr/0004-mixin-functions-instead-of-polytype.md`. + */ + +// A base-class expression a mixin can extend. `...args: any[]` is required so the +// mixin can sit in front of bases with differing constructor signatures. +export type Ctor = new (...args: any[]) => T; + +/** + * Bolt a readonly `data: TData` onto `Base`. + * + * @example + * export class TldCommon extends WithData()(Tld) { + * public override readonly data: TldData; + * public constructor(data: TldData) { + * super(data.tld); + * this.data = data; + * } + * } + */ +export function WithData() { + return function (Base: TBase) { + abstract class WithDataModel extends Base { + declare readonly data: TData; + } + return WithDataModel; + }; +} + +/** + * Bolt readonly `items`/`totalCount` onto `Base` (the list counterpart of + * {@link WithData}). Mirrors the shape of `ListDataModel`. + */ +export function WithListData() { + return function (Base: TBase) { + abstract class WithListDataModel extends Base { + declare readonly items: readonly TItem[]; + declare readonly totalCount: number; + } + return WithListDataModel; + }; +} diff --git a/packages/models/src/base/types.ts b/packages/models/src/base/models/types.ts similarity index 57% rename from packages/models/src/base/types.ts rename to packages/models/src/base/models/types.ts index 7d8988d8..eb7f3a91 100644 --- a/packages/models/src/base/types.ts +++ b/packages/models/src/base/models/types.ts @@ -1,8 +1,8 @@ -import { DataModel } from "./DataModel.js"; +import type { DataModel } from "./DataModel.js"; export type DataType = T extends DataModel ? TData : never; -export type QueryResponseData = { +export interface QueryResponseData { items: readonly T[]; totalCount: number; -}; +} diff --git a/packages/models/src/certificate/Certificate/Certificate.test.ts b/packages/models/src/certificate/Certificate/Certificate.test.ts new file mode 100644 index 00000000..95f737ce --- /dev/null +++ b/packages/models/src/certificate/Certificate/Certificate.test.ts @@ -0,0 +1,200 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { buildCertificateCheckReplaceResponseData } from "../../testing/builders/buildCertificateCheckReplaceResponseData.js"; +import { CertificateCheckReplaceResponse } from "../CertificateCheckReplaceResponse/index.js"; +import { buildCertificateData } from "../../testing/builders/buildCertificateData.js"; +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { ReferenceModel } from "../../base/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { + CertificateDetailed, + CertificateListItem, + CertificateCommon, + CertificateList, + Certificate, +} from "./Certificate.js"; + +afterEach(resetBehaviors); + +describe("Certificate", () => { + test("aggregateMetaData carries the ssl/certificate identity", () => { + expect(Certificate.aggregateMetaData).toBeInstanceOf(AggregateMetaData); + expect(Certificate.aggregateMetaData.domain).toBe("ssl"); + expect(Certificate.aggregateMetaData.aggregate).toBe("certificate"); + }); + + test("findCommon delegates to a detailed variant for a reference", async () => { + const find = vi.fn().mockResolvedValue(buildCertificateData({ id: "c-1" })); + installBehaviors({ certificate: { find } }); + + const common = await Certificate.ofId("c-1").findCommon(); + + expect(common).toBeInstanceOf(CertificateCommon); + expect(find).toHaveBeenCalledWith("c-1"); + }); + + test("getCommon throws for a missing reference", async () => { + installBehaviors({ + certificate: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(Certificate.ofId("c-1").getCommon()).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("getCommon/findCommon are idempotent on materialized models", async () => { + const find = vi.fn(); + installBehaviors({ certificate: { find } }); + const detailed = new CertificateDetailed(buildCertificateData()); + const item = new CertificateListItem(buildCertificateData()); + + expect(await detailed.getCommon()).toBe(detailed); + expect(await detailed.findCommon()).toBe(detailed); + expect(await item.getCommon()).toBe(item); + expect(await item.findCommon()).toBe(item); + expect(find).not.toHaveBeenCalled(); + }); + + test("omits optional status and validity data when absent", () => { + const certificate = new CertificateDetailed(buildCertificateData()); + + expect(certificate.getStatus()).toBeUndefined(); + expect(certificate.certificateOrder).toBeUndefined(); + expect(certificate.validTo).toBeUndefined(); + }); + + test("find delegates and returns a detailed certificate", async () => { + const find = vi.fn().mockResolvedValue(buildCertificateData({ id: "c-1" })); + installBehaviors({ certificate: { find } }); + + const result = await Certificate.find("c-1"); + + expect(find).toHaveBeenCalledWith("c-1"); + expect(result).toBeInstanceOf(CertificateDetailed); + expect(result?.id).toBe("c-1"); + }); + + test("find returns undefined when the certificate is missing", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ certificate: { find } }); + + expect(await Certificate.find("missing")).toBeUndefined(); + }); + + test("get returns a detailed certificate when found", async () => { + const find = vi.fn().mockResolvedValue(buildCertificateData({ id: "c-2" })); + installBehaviors({ certificate: { find } }); + + const result = await Certificate.get("c-2"); + + expect(result).toBeInstanceOf(CertificateDetailed); + expect(result.id).toBe("c-2"); + }); + + test("get throws ObjectNotFoundError when missing", async () => { + installBehaviors({ + certificate: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(Certificate.get("missing")).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("ofId creates a certificate reference", () => { + const certificate = Certificate.ofId("c-ref"); + + expect(certificate).toBeInstanceOf(Certificate); + expect(certificate.id).toBe("c-ref"); + }); + + test("exposes names and hostname compatibility", () => { + const exact = new CertificateDetailed( + buildCertificateData({ + dnsNames: ["api.example.com"], + commonName: "example.com", + }), + ); + const wildcard = new CertificateDetailed( + buildCertificateData({ commonName: "*.example.com", dnsNames: [] }), + ); + const dnsFallback = new CertificateDetailed( + buildCertificateData({ + dnsNames: ["fallback.example.com"], + commonName: undefined, + }), + ); + const empty = new CertificateDetailed( + buildCertificateData({ commonName: undefined, dnsNames: undefined }), + ); + + expect(exact.displayName).toBe("example.com"); + expect(exact.dnsNames).toEqual(["api.example.com"]); + expect(dnsFallback.displayName).toBe("fallback.example.com"); + expect(empty.displayName).toBe(""); + expect(wildcard.isWildcard()).toBe(true); + expect(exact.isCompatibleWithHostname("example.com")).toBe(true); + expect(wildcard.isCompatibleWithHostname("www.example.com")).toBe(true); + expect(wildcard.isCompatibleWithHostname("unrelated.test")).toBe(false); + }); + + test("query delegates and materializes a certificate list", async () => { + const query = vi.fn().mockResolvedValue({ + items: [buildCertificateData({ id: "c-list" })], + totalCount: 4, + }); + installBehaviors({ certificate: { query } }); + + const result = await Certificate.query().execute(); + + expect(query).toHaveBeenCalledWith({ projectId: undefined }); + expect(result).toBeInstanceOf(CertificateList); + expect(result.items[0]).toBeInstanceOf(CertificateListItem); + expect(result.items[0]?.id).toBe("c-list"); + expect(result.totalCount).toBe(4); + }); + + test("checkReplace delegates and materializes the response", async () => { + const checkReplace = vi + .fn() + .mockResolvedValue(buildCertificateCheckReplaceResponseData()); + installBehaviors({ certificate: { checkReplace } }); + + const result = await Certificate.ofId("c-1").checkReplace( + "certificate", + "private-key", + "ca", + ); + + expect(checkReplace).toHaveBeenCalledWith( + "c-1", + "certificate", + "private-key", + "ca", + ); + expect(result).toBeInstanceOf(CertificateCheckReplaceResponse); + }); + + test("preserves the list item identity chain", () => { + const item = new CertificateListItem(buildCertificateData()); + + expect(item).toBeInstanceOf(CertificateListItem); + expect(item).toBeInstanceOf(CertificateCommon); + expect(item).toBeInstanceOf(Certificate); + expect(item).toBeInstanceOf(ReferenceModel); + expect(item.data).toBeDefined(); + }); +}); diff --git a/packages/models/src/certificate/Certificate/Certificate.ts b/packages/models/src/certificate/Certificate/Certificate.ts new file mode 100644 index 00000000..569c45c1 --- /dev/null +++ b/packages/models/src/certificate/Certificate/Certificate.ts @@ -0,0 +1,277 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; +import { omit } from "remeda"; + +import type { + CertificateListQueryModelData, + CertificateListItemData, + CertificateData, + CertificateType, +} from "./types.js"; + +import { CertificateCheckReplaceResponse } from "../CertificateCheckReplaceResponse/index.js"; +import { CertificateContact } from "../CertificateContact/CertificateContact.js"; +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { CertificateRequest } from "../CertificateRequest/index.js"; +import { DnsCertificateSpec } from "../DnsCertificateSpec/index.js"; +import { Ingress } from "../../ingress/Ingress/Ingress.js"; +import { Project } from "../../project/internal.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { Order } from "../../order/Order/Order.js"; +import { CertificateTypes } from "./types.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "Certificate", +}) +export class Certificate extends ReferenceModel { + public static aggregateMetaData = new AggregateMetaData("ssl", "certificate"); + + public static async find(id: string) { + const data = await config.behaviors.certificate.find(id); + if (data) { + return new CertificateDetailed(data); + } + } + + public static async get(id: string) { + const certificate = await this.find(id); + assertObjectFound(certificate, Certificate, id); + return certificate; + } + + public static ofId(id: string) { + return new Certificate(id); + } + + public static query(query: CertificateListQueryModelData = {}) { + return new CertificateListQuery(query); + } + + public async checkReplace( + certificate: string, + privateKey: string, + certificateAuthority?: string, + ): Promise { + const response = await config.behaviors.certificate.checkReplace( + this.id, + certificate, + privateKey, + certificateAuthority, + ); + return new CertificateCheckReplaceResponse(response); + } + + public async delete() { + await config.behaviors.certificate.delete(this.id); + } + + public async findCommon(): Promise { + return this instanceof CertificateCommon ? this : this.findDetailed(); + } + + public async findDetailed(): Promise { + return Certificate.find(this.id); + } + + public async getCommon(): Promise { + return this instanceof CertificateCommon ? this : this.getDetailed(); + } + + public async getDetailed(): Promise { + return Certificate.get(this.id); + } + + public async replace( + certificate: string, + privateKey: string, + certificateAuthority?: string, + ) { + await config.behaviors.certificate.replace( + this.id, + certificate, + privateKey, + certificateAuthority, + ); + } +} + +export class CertificateCommon extends WithData()( + Certificate, +) { + public readonly caBundle?: string; + public readonly certificate?: string; + public readonly certificateOrder?: Order; + public readonly certificateRequest: CertificateRequest; + public readonly certificateType: CertificateType; + public readonly commonName?: string; + public readonly contact?: CertificateContact; + public override readonly data: CertificateData; + public readonly displayName: string; + public readonly dnsCertSpec?: DnsCertificateSpec; + public readonly dnsNames: string[]; + public readonly isExpired: boolean; + public readonly issuer?: string; + public readonly lastExpirationThresholdHit?: number; + public readonly project: Project; + public readonly validFrom?: DateTime; + public readonly validTo?: DateTime; + /** + * The ingresses that reference this certificate. A lazy query getter (not an + * eager ctor field), so the accepted `certificate ↔ ingress` module cycle + * carries no import-time hazard — see the import-cycle trap in + * docs/implementation-patterns.md. + */ + public get linkedIngresses() { + return Ingress.query({ certificate: this }); + } + + public constructor(data: CertificateData) { + super(data.id); + this.data = data; + this.caBundle = data.caBundle; + this.certificate = data.certificate; + if (data.certificateOrderId) { + this.certificateOrder = Order.ofId(data.certificateOrderId); + } + this.certificateRequest = CertificateRequest.ofId( + data.certificateRequestId, + ); + this.certificateType = data.certificateType; + this.commonName = data.commonName; + if (data.contact) { + this.contact = new CertificateContact(data.contact); + } + this.dnsNames = data.dnsNames ?? []; + this.isExpired = data.isExpired ?? false; + this.issuer = data.issuer; + this.lastExpirationThresholdHit = data.lastExpirationThresholdHit; + this.project = Project.ofId(data.projectId); + if (data.validFrom) { + this.validFrom = DateTime.fromISO(data.validFrom); + } + if (data.validTo) { + this.validTo = DateTime.fromISO(data.validTo); + } + this.displayName = this.commonName ?? this.dnsNames[0] ?? ""; + if (data.dnsCertSpec) { + this.dnsCertSpec = new DnsCertificateSpec(data.dnsCertSpec); + } + } + + public expired() { + return ( + this.isExpired || (this.validTo && this.validTo.diffNow("days").days <= 0) + ); + } + + public expiresSoon() { + return this.validTo && this.validTo?.diffNow("months").months <= 1; + } + + public getStatus() { + if (this.certificateType === CertificateTypes.DNS) { + if (this.dnsCertSpec?.status) { + return this.dnsCertSpec.status.status; + } + } + } + + public readonly isCompatibleWithHostname = (hostname: string) => { + const itemsToCheck = this.dnsNames; + if (this.commonName) { + itemsToCheck.push(this.commonName); + } + + for (const item of itemsToCheck) { + if (item === hostname) { + return true; + } + if (item.startsWith("*.")) { + const hostnameParts = hostname.split("."); + if ( + hostnameParts.slice(1, hostnameParts.length).join(".") === + item.replace("*.", "") + ) { + return true; + } + } + } + return false; + }; + + public isWildcard() { + return this.displayName.startsWith("*."); + } + + /** + * The ingresses in this certificate's project that are compatible with it. A + * lazy delegator to the ingress-side query; part of the accepted `certificate + * ↔ ingress` module cycle (lazy, deep import). + */ + public async listCompatibleIngresses() { + return Ingress.listCompatibleWithCertificate(this); + } +} + +export class CertificateDetailed extends CertificateCommon { + public constructor(data: CertificateData) { + super(data); + } +} + +export class CertificateListQuery extends ListQueryModel { + public constructor(query: CertificateListQueryModelData = {}) { + super(query); + } + + public async execute() { + const { totalCount, items } = await config.behaviors.certificate.query({ + ...omit(this.query, ["project", "ingress"]), + projectId: extractId(this.query.project), + ingressId: extractId(this.query.ingress), + }); + return new CertificateList( + this.query, + items.map((c) => new CertificateListItem(c)), + totalCount, + ); + } + + public refine(query: CertificateListQueryModelData = {}) { + return new CertificateListQuery({ ...this.query, ...query }); + } +} + +export class CertificateListItem extends CertificateCommon { + public constructor(data: CertificateListItemData) { + super(data); + } +} + +export class CertificateList extends WithListData()( + CertificateListQuery, +) { + public override readonly items: readonly CertificateListItem[]; + public override readonly totalCount: number; + public constructor( + query: CertificateListQueryModelData, + certificates: CertificateListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(certificates); + this.totalCount = totalCount; + } + + public getItemsCompatibleWithHostname(hostname: string) { + return this.items.filter((i) => i.isCompatibleWithHostname(hostname)); + } +} diff --git a/packages/models/src/certificate/Certificate/behaviors/api.ts b/packages/models/src/certificate/Certificate/behaviors/api.ts new file mode 100644 index 00000000..38c5d67e --- /dev/null +++ b/packages/models/src/certificate/Certificate/behaviors/api.ts @@ -0,0 +1,69 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { CertificateBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount, anyStatus403 } from "../../../base/index.js"; + +export const apiCertificateBehaviors = ( + client: MittwaldAPIV2Client, +): CertificateBehaviors => ({ + checkReplace: async ( + certificateId, + certificateData, + privateKey, + certificateAuthority, + ) => { + const certificate = certificateAuthority + ? [certificateData, certificateAuthority].join("\n") + : certificateData; + + const response = await client.domain.sslCheckReplaceCertificate({ + data: { certificate, privateKey }, + certificateId, + }); + validateResponse(response, 200); + return response.data; + }, + find: async (certificateId) => { + const response = await client.domain.sslGetCertificate({ + certificateId, + }); + if (response.status === 200) { + return response.data; + } + // API-DRIFT: sslGetCertificate omits 403 in its generated response type, so anyStatus403 (403 as any) is passed (resolve: use the literal 403 once the client type declares it) + validateResponse(response, [anyStatus403, 404]); + }, + replace: async ( + certificateId, + certificateData, + privateKey, + certificateAuthority, + ) => { + const certificate = certificateAuthority + ? [certificateData, certificateAuthority].join("\n") + : certificateData; + const response = await client.domain.sslReplaceCertificate({ + data: { certificate, privateKey }, + certificateId, + }); + validateResponse(response, 204); + }, + query: async (query = {}) => { + const response = await client.domain.sslListCertificates({ + queryParameters: query, + }); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + delete: async (certificateId) => { + const response = await client.domain.sslDeleteCertificate({ + certificateId, + }); + validateResponse(response, 204); + }, +}); diff --git a/packages/models/src/certificate/Certificate/behaviors/index.ts b/packages/models/src/certificate/Certificate/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/certificate/Certificate/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/certificate/Certificate/behaviors/types.ts b/packages/models/src/certificate/Certificate/behaviors/types.ts new file mode 100644 index 00000000..29bb1b7b --- /dev/null +++ b/packages/models/src/certificate/Certificate/behaviors/types.ts @@ -0,0 +1,27 @@ +import type { CertificateCheckReplaceResponseData } from "../../CertificateCheckReplaceResponse/index.js"; +import type { QueryResponseData } from "../../../base/index.js"; +import type { + CertificateListQueryData, + CertificateListItemData, + CertificateData, +} from "../types.js"; + +export interface CertificateBehaviors { + checkReplace: ( + certificateId: string, + certificate: string, + privateKey: string, + certificateAuthority?: string, + ) => Promise; + replace: ( + certificateId: string, + certificate: string, + privateKey: string, + certificateAuthority?: string, + ) => Promise; + query: ( + query?: CertificateListQueryData, + ) => Promise>; + find: (certificateId: string) => Promise; + delete: (certificateId: string) => Promise; +} diff --git a/packages/models/src/certificate/Certificate/index.ts b/packages/models/src/certificate/Certificate/index.ts new file mode 100644 index 00000000..bdaf6ebe --- /dev/null +++ b/packages/models/src/certificate/Certificate/index.ts @@ -0,0 +1,2 @@ +export * from "./Certificate.js"; +export * from "./types.js"; diff --git a/packages/models/src/certificate/Certificate/types.ts b/packages/models/src/certificate/Certificate/types.ts new file mode 100644 index 00000000..8df81a32 --- /dev/null +++ b/packages/models/src/certificate/Certificate/types.ts @@ -0,0 +1,31 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import type { Ingress } from "../../ingress/Ingress/Ingress.js"; +import type { Project } from "../../project/index.js"; + +export type CertificateData = + MittwaldAPIV2.Operations.SslGetCertificate.ResponseData; + +export type CertificateListQueryData = + MittwaldAPIV2.Paths.V2Certificates.Get.Parameters.Query; + +export type CertificateListQueryModelData = Omit< + CertificateListQueryData, + "projectId" | "ingressId" +> & { + project?: Project | string; + ingress?: Ingress | string; +}; + +export type CertificateListItemData = + MittwaldAPIV2.Operations.SslListCertificates.ResponseData[number]; + +export type CertificateType = + MittwaldAPIV2.Components.Schemas.SslCertificateType; + +export enum CertificateTypes { + DNS = 3, + EXTERNAL = 2, + INTERNAL = 1, + UNSPECIFIED = 0, +} diff --git a/packages/models/src/certificate/CertificateCheckReplaceResponse/CertificateCheckReplaceResponse.test.ts b/packages/models/src/certificate/CertificateCheckReplaceResponse/CertificateCheckReplaceResponse.test.ts new file mode 100644 index 00000000..c256fcc8 --- /dev/null +++ b/packages/models/src/certificate/CertificateCheckReplaceResponse/CertificateCheckReplaceResponse.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, test } from "vitest"; + +import { buildCertificateCheckReplaceResponseData } from "../../testing/builders/buildCertificateCheckReplaceResponseData.js"; +import { CertificateCheckReplaceResponse } from "./CertificateCheckReplaceResponse.js"; + +describe("CertificateCheckReplaceResponse", () => { + test("copies response data and defaults errors", () => { + const changes = { + commonName: { oldValue: "old.example.com", newValue: "new.example.com" }, + }; + const response = new CertificateCheckReplaceResponse( + buildCertificateCheckReplaceResponseData({ + isReplaceable: false, + changes, + }), + ); + + expect(response.isReplaceable).toBe(false); + expect(response.changes).toEqual(changes); + expect(response.errors).toEqual([]); + }); + + test("combines added DNS names and includes the new common name by default", () => { + const response = new CertificateCheckReplaceResponse( + buildCertificateCheckReplaceResponseData({ + changes: { + dnsNames: { + addedValues: ["added.example.com"], + values: ["current.example.com"], + removedValues: [], + }, + commonName: { + oldValue: "old.example.com", + newValue: "new.example.com", + }, + }, + }), + ); + + expect(response.getAddedDnsNames()).toEqual([ + "added.example.com", + "current.example.com", + "new.example.com", + ]); + expect(response.getAddedDnsNames(false)).toEqual([ + "added.example.com", + "current.example.com", + ]); + }); + + test("returns removed DNS names or an empty array", () => { + const response = new CertificateCheckReplaceResponse( + buildCertificateCheckReplaceResponseData({ + changes: { + dnsNames: { + removedValues: ["removed.example.com"], + addedValues: [], + values: [], + }, + }, + }), + ); + + expect(response.getRemovedDnsNames()).toEqual(["removed.example.com"]); + expect( + new CertificateCheckReplaceResponse( + buildCertificateCheckReplaceResponseData(), + ).getRemovedDnsNames(), + ).toEqual([]); + }); +}); diff --git a/packages/models/src/certificate/CertificateCheckReplaceResponse/CertificateCheckReplaceResponse.ts b/packages/models/src/certificate/CertificateCheckReplaceResponse/CertificateCheckReplaceResponse.ts new file mode 100644 index 00000000..44438127 --- /dev/null +++ b/packages/models/src/certificate/CertificateCheckReplaceResponse/CertificateCheckReplaceResponse.ts @@ -0,0 +1,130 @@ +import type { + CertificateDetailed, + CertificateListItem, +} from "../Certificate/index.js"; +import type { IngressListItem } from "../../ingress/Ingress/index.js"; +import type { + CertificateDifferencesResolveResponse, + CertificateCheckReplaceResponseData, + CertificateCheckReplaceChanges, + CertificateErrorData, +} from "./types.js"; + +import { DataModel } from "../../base/index.js"; + +export class CertificateCheckReplaceResponse extends DataModel { + public readonly changes?: CertificateCheckReplaceChanges; + public readonly errors: CertificateErrorData[]; + public readonly isReplaceable: boolean; + public constructor(data: CertificateCheckReplaceResponseData) { + super(data); + this.isReplaceable = data.isReplaceable; + this.changes = data.changes; + this.errors = data.errors ?? []; + } + + public getAddedDnsNames(incldeCommonName = true): string[] { + const hostnames = [ + ...(this.changes?.dnsNames?.addedValues ?? []), + ...(this.changes?.dnsNames?.values ?? []), + ]; + if (incldeCommonName && this.changes?.commonName?.newValue) { + hostnames.push(this.changes?.commonName?.newValue); + } + return hostnames; + } + + public getRemovedDnsNames(): string[] { + return this.changes?.dnsNames?.removedValues ?? []; + } + + public resolveCertificateChanges( + oldCertificate: CertificateDetailed | CertificateListItem, + newCompatibleIngresses: IngressListItem[], + oldCompatibleIngresses: IngressListItem[], + ): CertificateDifferencesResolveResponse { + const addedHostnames = this.getAddedDnsNames(); + const newHostnames = addedHostnames + .filter((i, index, array) => array.indexOf(i) === index) + .filter((i) => + newCompatibleIngresses.find((ingress) => ingress.hostname === i), + ); + + const oldIngresses = oldCompatibleIngresses + .filter( + (i) => + i.tls.type === "certificate" && + i.tls.certificate.id === oldCertificate.id, + ) + .filter((i) => !this.hostnameMatchesWildcard(i.hostname, newHostnames)); + + if (!this.changes?.dnsNames) { + const hostnames = oldIngresses.map((i) => i.hostname); + newHostnames.push(...hostnames); + } + + const removedOldIngresses = !this.changes?.dnsNames + ? [] + : oldIngresses.map((ingress) => ingress.hostname); + + const removedOldCommonName = !this.changes?.commonName + ? [] + : [this.changes.commonName.oldValue]; + + const removedDnsNames = this.getRemovedDnsNames(); + + const removedHostnames = [ + ...removedOldIngresses, + ...removedOldCommonName, + ...removedDnsNames, + ].filter((i, pos, array) => array.indexOf(i) === pos); + + const ingressWillReceiveCertificate = newCompatibleIngresses.filter( + (i) => + this.hostnameMatchesWildcard(i.hostname, newHostnames) && + ((i.tls.type === "certificate" && + i.tls.certificate.id === oldCertificate.id) || + i.tls.type === "acme"), + ); + + const ingressWillBeDowngradedToLetsEncrypt = [ + ...newCompatibleIngresses, + ...oldIngresses, + ] + .filter( + (i) => + this.hostnameMatchesWildcard(i.hostname, removedHostnames) && + i.tls.type === "certificate" && + i.tls.certificate.id === oldCertificate.id, + ) + .filter( + (ingress, pos, array): ingress is IngressListItem => + array.findIndex((i) => i.hostname === ingress.hostname) === pos, + ); + + const removed = ingressWillBeDowngradedToLetsEncrypt.map((i) => i.hostname); + const added = ingressWillReceiveCertificate.map((i) => i.hostname); + return { removed, added }; + } + + private hostnameMatchesWildcard( + hostname: string, + wildcards: string[], + ): boolean { + for (const wildcard of wildcards) { + if (hostname === wildcard) { + return true; + } + if (wildcard.startsWith("*.")) { + const hostnameParts = hostname.split("."); + if ( + hostnameParts.slice(1, hostnameParts.length).join(".") === + wildcard.replace("*.", "") + ) { + return true; + } + } + } + return false; + } +} diff --git a/packages/models/src/certificate/CertificateCheckReplaceResponse/index.ts b/packages/models/src/certificate/CertificateCheckReplaceResponse/index.ts new file mode 100644 index 00000000..d9cb12a2 --- /dev/null +++ b/packages/models/src/certificate/CertificateCheckReplaceResponse/index.ts @@ -0,0 +1,2 @@ +export * from "./CertificateCheckReplaceResponse.js"; +export * from "./types.js"; diff --git a/packages/models/src/certificate/CertificateCheckReplaceResponse/types.ts b/packages/models/src/certificate/CertificateCheckReplaceResponse/types.ts new file mode 100644 index 00000000..1fbe9197 --- /dev/null +++ b/packages/models/src/certificate/CertificateCheckReplaceResponse/types.ts @@ -0,0 +1,21 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type CertificateCheckReplaceResponseData = + MittwaldAPIV2.Components.Schemas.SslCheckReplaceCertificateResponse; + +export type CertificateCheckReplaceChanges = + MittwaldAPIV2.Components.Schemas.SslCheckReplaceChanges; + +export type CertificateCheckReplaceFieldChange = + MittwaldAPIV2.Components.Schemas.SslCheckReplaceFieldChange; + +export type CertificateCheckReplaceSliceChange = + MittwaldAPIV2.Components.Schemas.SslCheckReplaceSliceChange; + +export type CertificateErrorData = + MittwaldAPIV2.Components.Schemas.SslCertificateError; + +export interface CertificateDifferencesResolveResponse { + removed: string[]; + added: string[]; +} diff --git a/packages/models/src/certificate/CertificateContact/CertificateContact.test.ts b/packages/models/src/certificate/CertificateContact/CertificateContact.test.ts new file mode 100644 index 00000000..7a9298be --- /dev/null +++ b/packages/models/src/certificate/CertificateContact/CertificateContact.test.ts @@ -0,0 +1,15 @@ +import { expect, test } from "vitest"; + +import { buildCertificateContactData } from "../../testing/builders/buildCertificateContactData.js"; +import { CertificateContact } from "./CertificateContact.js"; + +test("copies certificate contact fields", () => { + const data = buildCertificateContactData(); + const contact = new CertificateContact(data); + + expect(contact.city).toBe(data.city); + expect(contact.company).toBe(data.company); + expect(contact.country).toBe(data.country); + expect(contact.organizationalUnit).toBe(data.organizationalUnit); + expect(contact.state).toBe(data.state); +}); diff --git a/packages/models/src/certificate/CertificateContact/CertificateContact.ts b/packages/models/src/certificate/CertificateContact/CertificateContact.ts new file mode 100644 index 00000000..bae0a194 --- /dev/null +++ b/packages/models/src/certificate/CertificateContact/CertificateContact.ts @@ -0,0 +1,19 @@ +import type { CertificateContactData } from "./types.js"; + +import { DataModel } from "../../base/index.js"; + +export class CertificateContact extends DataModel { + public readonly city?: string; + public readonly company?: string; + public readonly country?: string; + public readonly organizationalUnit?: string; + public readonly state?: string; + public constructor(data: CertificateContactData) { + super(data); + this.city = data.city; + this.company = data.company; + this.country = data.country; + this.organizationalUnit = data.organizationalUnit; + this.state = data.state; + } +} diff --git a/packages/models/src/certificate/CertificateContact/index.ts b/packages/models/src/certificate/CertificateContact/index.ts new file mode 100644 index 00000000..e69de29b diff --git a/packages/models/src/certificate/CertificateContact/types.ts b/packages/models/src/certificate/CertificateContact/types.ts new file mode 100644 index 00000000..3ae4f1a1 --- /dev/null +++ b/packages/models/src/certificate/CertificateContact/types.ts @@ -0,0 +1,4 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type CertificateContactData = + MittwaldAPIV2.Components.Schemas.SslContact; diff --git a/packages/models/src/certificate/CertificateRequest/CertificateRequest.test.ts b/packages/models/src/certificate/CertificateRequest/CertificateRequest.test.ts new file mode 100644 index 00000000..d897d385 --- /dev/null +++ b/packages/models/src/certificate/CertificateRequest/CertificateRequest.test.ts @@ -0,0 +1,185 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; +import { DateTime } from "luxon"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { buildCertificateRequestData } from "../../testing/builders/buildCertificateRequestData.js"; +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { ReferenceModel } from "../../base/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { + CertificateRequestDetailed, + CertificateRequestListItem, + CertificateRequestCommon, + CertificateRequestList, + CertificateRequest, +} from "./CertificateRequest.js"; + +afterEach(resetBehaviors); + +describe("CertificateRequest", () => { + test("findCommon delegates to a detailed variant for a reference", async () => { + const find = vi + .fn() + .mockResolvedValue(buildCertificateRequestData({ id: "cr-1" })); + installBehaviors({ certificateRequest: { find } }); + + const common = await CertificateRequest.ofId("cr-1").findCommon(); + + expect(common).toBeInstanceOf(CertificateRequestCommon); + expect(find).toHaveBeenCalledWith("cr-1"); + }); + + test("getCommon throws for a missing reference", async () => { + installBehaviors({ + certificateRequest: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + CertificateRequest.ofId("cr-1").getCommon(), + ).rejects.toBeInstanceOf(ObjectNotFoundError); + }); + + test("getCommon/findCommon are idempotent on materialized models", async () => { + const find = vi.fn(); + installBehaviors({ certificateRequest: { find } }); + const detailed = new CertificateRequestDetailed( + buildCertificateRequestData(), + ); + const item = new CertificateRequestListItem(buildCertificateRequestData()); + + expect(await detailed.getCommon()).toBe(detailed); + expect(await detailed.findCommon()).toBe(detailed); + expect(await item.getCommon()).toBe(item); + expect(await item.findCommon()).toBe(item); + expect(find).not.toHaveBeenCalled(); + }); + + test("omits optional request data when absent", () => { + const request = new CertificateRequestDetailed( + buildCertificateRequestData({ + commonName: undefined, + projectId: undefined, + validFrom: undefined, + dnsNames: undefined, + validTo: undefined, + }), + ); + + expect(request.project).toBeUndefined(); + expect(request.commonName).toBeUndefined(); + expect(request.dnsNames).toEqual([]); + expect(request.validFrom).toBeUndefined(); + expect(request.validTo).toBeUndefined(); + }); + + test("find delegates and returns a detailed request", async () => { + const find = vi + .fn() + .mockResolvedValue(buildCertificateRequestData({ id: "cr-1" })); + installBehaviors({ certificateRequest: { find } }); + + const result = await CertificateRequest.find("cr-1"); + + expect(find).toHaveBeenCalledWith("cr-1"); + expect(result).toBeInstanceOf(CertificateRequestDetailed); + expect(result?.id).toBe("cr-1"); + }); + + test("find returns undefined when the request is missing", async () => { + installBehaviors({ + certificateRequest: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + expect(await CertificateRequest.find("missing")).toBeUndefined(); + }); + + test("get throws ObjectNotFoundError when missing", async () => { + installBehaviors({ + certificateRequest: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(CertificateRequest.get("missing")).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("ofId creates a request reference", () => { + const request = CertificateRequest.ofId("cr-ref"); + + expect(request).toBeInstanceOf(CertificateRequest); + expect(request.id).toBe("cr-ref"); + }); + + test("create delegates and returns a request reference", async () => { + const create = vi.fn().mockResolvedValue({ id: "created-id" }); + installBehaviors({ certificateRequest: { create } }); + + const result = await CertificateRequest.create( + "project-id", + "certificate", + "private-key", + "ca", + ); + + expect(create).toHaveBeenCalledWith( + "project-id", + "certificate", + "private-key", + "ca", + ); + expect(result).toBeInstanceOf(CertificateRequest); + expect(result.id).toBe("created-id"); + }); + + test("query delegates and materializes a request list", async () => { + const query = vi.fn().mockResolvedValue({ + items: [buildCertificateRequestData({ id: "cr-list" })], + totalCount: 3, + }); + installBehaviors({ certificateRequest: { query } }); + + const result = await CertificateRequest.query().execute(); + + expect(query).toHaveBeenCalledWith({ projectId: undefined }); + expect(result).toBeInstanceOf(CertificateRequestList); + expect(result.items[0]).toBeInstanceOf(CertificateRequestListItem); + expect(result.items[0]?.id).toBe("cr-list"); + expect(result.totalCount).toBe(3); + }); + + test("exposes common request data", () => { + const request = new CertificateRequestDetailed( + buildCertificateRequestData({ + dnsNames: ["one.example.com", "two.example.com"], + commonName: "cert.example.com", + isCompleted: true, + }), + ); + + expect(request.dnsNames).toEqual(["one.example.com", "two.example.com"]); + expect(request.commonName).toBe("cert.example.com"); + expect(request.isCompleted).toBe(true); + expect(request.createdAt).toBeInstanceOf(DateTime); + expect(request.createdAt.isValid).toBe(true); + }); + + test("preserves the list item identity chain", () => { + const item = new CertificateRequestListItem(buildCertificateRequestData()); + + expect(item).toBeInstanceOf(CertificateRequestListItem); + expect(item).toBeInstanceOf(CertificateRequestCommon); + expect(item).toBeInstanceOf(CertificateRequest); + expect(item).toBeInstanceOf(ReferenceModel); + expect(item.data).toBeDefined(); + }); +}); diff --git a/packages/models/src/certificate/CertificateRequest/CertificateRequest.ts b/packages/models/src/certificate/CertificateRequest/CertificateRequest.ts new file mode 100644 index 00000000..32dc5e84 --- /dev/null +++ b/packages/models/src/certificate/CertificateRequest/CertificateRequest.ts @@ -0,0 +1,185 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; +import { omit } from "remeda"; + +import type { CertificateType } from "../Certificate/index.js"; +import type { + CertificateRequestListQueryModelData, + CertificateRequestCertificateData, + CertificateRequestListItemData, + CertificateRequestData, +} from "./types.js"; + +import { CertificateContact } from "../CertificateContact/CertificateContact.js"; +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { Project } from "../../project/internal.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "CertificateRequest", +}) +export class CertificateRequest extends ReferenceModel { + public static async create( + projectId: string, + certificate: string, + privateKey: string, + certificateAuthority?: string, + ) { + const { id } = await config.behaviors.certificateRequest.create( + projectId, + certificate, + privateKey, + certificateAuthority, + ); + return new CertificateRequest(id); + } + + public static async createDnsCertificate( + project: Project, + commonName: string, + ) { + return await config.behaviors.certificateRequest.createDnsCertificate( + commonName, + project.id, + ); + } + + public static async find(id: string) { + const data = await config.behaviors.certificateRequest.find(id); + if (data) { + return new CertificateRequestDetailed(data); + } + } + + public static async get(id: string) { + const certificateRequest = await this.find(id); + assertObjectFound(certificateRequest, CertificateRequest, id); + return certificateRequest; + } + + public static ofId(certificateRequestId: string) { + return new CertificateRequest(certificateRequestId); + } + + public static query(query: CertificateRequestListQueryModelData = {}) { + return new CertificateRequestListQuery(query); + } + public async delete() { + await config.behaviors.certificateRequest.delete(this.id); + } + + public async findCommon(): Promise { + return this instanceof CertificateRequestCommon + ? this + : this.findDetailed(); + } + + public findDetailed(): Promise { + return CertificateRequest.find(this.id); + } + + public async getCommon(): Promise { + return this instanceof CertificateRequestCommon ? this : this.getDetailed(); + } + + public getDetailed(): Promise { + return CertificateRequest.get(this.id); + } +} + +export class CertificateRequestCommon extends WithData()( + CertificateRequest, +) { + public readonly certificateData: CertificateRequestCertificateData; + public readonly certificateType: CertificateType; + public readonly commonName?: string; + public readonly contact?: CertificateContact; + public readonly createdAt: DateTime; + public override readonly data: CertificateRequestData; + public readonly dnsNames: string[]; + public readonly isCompleted: boolean; + public readonly issuer?: string; + public readonly project?: Project; + public readonly validFrom?: DateTime; + public readonly validTo?: DateTime; + public constructor(data: CertificateRequestData) { + super(data.id); + this.data = data; + this.certificateData = data.certificateData; + this.certificateType = data.certificateType; + this.commonName = data.commonName; + this.contact = data.contact + ? new CertificateContact(data.contact) + : undefined; + this.createdAt = DateTime.fromISO(data.createdAt); + this.dnsNames = data.dnsNames ?? []; + this.isCompleted = data.isCompleted; + this.issuer = data.issuer; + if (data.projectId) { + this.project = Project.ofId(data.projectId); + } + this.validFrom = data.validFrom + ? DateTime.fromISO(data.validFrom) + : undefined; + this.validTo = data.validTo ? DateTime.fromISO(data.validTo) : undefined; + } +} + +export class CertificateRequestDetailed extends CertificateRequestCommon { + public constructor(data: CertificateRequestData) { + super(data); + } +} + +export class CertificateRequestListItem extends CertificateRequestCommon { + public constructor(data: CertificateRequestListItemData) { + super(data); + } +} + +export class CertificateRequestListQuery extends ListQueryModel { + public constructor(query: CertificateRequestListQueryModelData = {}) { + super(query); + } + + public async execute() { + const { totalCount, items } = + await config.behaviors.certificateRequest.query({ + ...omit(this.query, ["project", "ingress"]), + projectId: extractId(this.query.project), + ingressId: extractId(this.query.ingress), + }); + return new CertificateRequestList( + this.query, + items.map((r) => new CertificateRequestListItem(r)), + totalCount, + ); + } + + public refine(query: CertificateRequestListQueryModelData = {}) { + return new CertificateRequestListQuery(query); + } +} + +export class CertificateRequestList extends WithListData()( + CertificateRequestListQuery, +) { + public override readonly items: readonly CertificateRequestListItem[]; + public override readonly totalCount: number; + public constructor( + query: CertificateRequestListQueryModelData, + certificateRequests: CertificateRequestListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(certificateRequests); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/certificate/CertificateRequest/behaviors/api.ts b/packages/models/src/certificate/CertificateRequest/behaviors/api.ts new file mode 100644 index 00000000..c1a4d2b7 --- /dev/null +++ b/packages/models/src/certificate/CertificateRequest/behaviors/api.ts @@ -0,0 +1,92 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { CertificateRequestBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount } from "../../../base/index.js"; +import { ValidationError } from "../../../errors/index.js"; + +export const apiCertificateRequestBehaviors = ( + client: MittwaldAPIV2Client, +): CertificateRequestBehaviors => ({ + createDnsCertificate: async (commonName, projectId) => { + const data = { commonName, projectId }; + const response = await client.domain.sslCreateCertificateRequest({ + data, + }); + if (response.status === 409) { + throw new ValidationError({ + message: "certificateAlreadyExists", + type: "certificateAlreadyExists", + path: "domain", + }); + } + + if (response.status === 400) { + if ( + typeof response.data.message === "string" && + response.data.message.toLowerCase().includes("does not match pattern") + ) { + throw new ValidationError({ + message: "invalidDomain", + type: "invalidDomain", + path: "domain", + }); + } + } + validateResponse(response, 201); + return response.data; + }, + create: async ( + projectId, + certificateData, + privateKey, + certificateAuthority, + ) => { + const certificate = certificateAuthority + ? [certificateData, certificateAuthority].join("\n") + : certificateData; + const data = { certificate, privateKey, projectId }; + const response = await client.domain.sslCreateCertificateRequest({ data }); + + if (response.status === 400 && typeof response.data.message === "string") { + const field = response.data.message.includes("private_key") + ? "privateKey" + : "certificate"; + + throw new ValidationError({ + message: response.data.message, + type: response.data.message, + path: field, + }); + } + + validateResponse(response, 201); + return response.data; + }, + query: async (query = {}) => { + const response = await client.domain.sslListCertificateRequests({ + queryParameters: query, + }); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + find: async (certificateRequestId) => { + const response = await client.domain.sslGetCertificateRequest({ + certificateRequestId, + }); + if (response.status === 200) { + return response.data; + } + validateResponse(response, [404]); + }, + delete: async (certificateRequestId) => { + const response = await client.domain.sslDeleteCertificateRequest({ + certificateRequestId, + }); + validateResponse(response, 204); + }, +}); diff --git a/packages/models/src/certificate/CertificateRequest/behaviors/index.ts b/packages/models/src/certificate/CertificateRequest/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/certificate/CertificateRequest/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/certificate/CertificateRequest/behaviors/types.ts b/packages/models/src/certificate/CertificateRequest/behaviors/types.ts new file mode 100644 index 00000000..98877d55 --- /dev/null +++ b/packages/models/src/certificate/CertificateRequest/behaviors/types.ts @@ -0,0 +1,27 @@ +import type { QueryResponseData } from "../../../base/index.js"; +import type { + CreateCertificateRequestSuccessResponse, + CertificateRequestListQueryData, + CertificateRequestListItemData, + CertificateRequestData, +} from "../types.js"; + +export interface CertificateRequestBehaviors { + create: ( + projectId: string, + certificate: string, + privateKey: string, + certificateAuthority?: string, + ) => Promise; + createDnsCertificate: ( + commonName: string, + projectId: string, + ) => Promise; + query: ( + query?: CertificateRequestListQueryData, + ) => Promise>; + find: ( + certificateRequestId: string, + ) => Promise; + delete: (certificateRequestId: string) => Promise; +} diff --git a/packages/models/src/certificate/CertificateRequest/index.ts b/packages/models/src/certificate/CertificateRequest/index.ts new file mode 100644 index 00000000..456e152d --- /dev/null +++ b/packages/models/src/certificate/CertificateRequest/index.ts @@ -0,0 +1,2 @@ +export * from "./CertificateRequest.js"; +export * from "./types.js"; diff --git a/packages/models/src/certificate/CertificateRequest/types.ts b/packages/models/src/certificate/CertificateRequest/types.ts new file mode 100644 index 00000000..a04b7cff --- /dev/null +++ b/packages/models/src/certificate/CertificateRequest/types.ts @@ -0,0 +1,34 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import type { Ingress } from "../../ingress/Ingress/Ingress.js"; +import type { Project } from "../../project/index.js"; + +export type CertificateRequestData = + MittwaldAPIV2.Operations.SslGetCertificateRequest.ResponseData; + +export type CertificateRequestListQueryData = + MittwaldAPIV2.Paths.V2CertificateRequests.Get.Parameters.Query; + +export type CertificateRequestListQueryModelData = Omit< + CertificateRequestListQueryData, + "projectId" | "ingressId" +> & { + project?: Project | string; + ingress?: Ingress | string; +}; + +export type CertificateRequestListItemData = + MittwaldAPIV2.Operations.SslListCertificateRequests.ResponseData[number]; + +export type CheckReplaceChanges = + MittwaldAPIV2.Components.Schemas.SslCheckReplaceChanges; + +export type CertificateError = + MittwaldAPIV2.Components.Schemas.SslCertificateError; + +export type CertificateRequestCertificateData = + MittwaldAPIV2.Components.Schemas.SslCertificateData; + +export interface CreateCertificateRequestSuccessResponse { + id: string; +} diff --git a/packages/models/src/certificate/DnsCertificateSpec/DnsCertificateSpec.test.ts b/packages/models/src/certificate/DnsCertificateSpec/DnsCertificateSpec.test.ts new file mode 100644 index 00000000..74e08066 --- /dev/null +++ b/packages/models/src/certificate/DnsCertificateSpec/DnsCertificateSpec.test.ts @@ -0,0 +1,35 @@ +import { beforeEach, afterEach, describe, expect, test } from "vitest"; + +import { buildDnsCertificateStatusData } from "../../testing/builders/buildDnsCertificateStatusData.js"; +import { buildDnsCertificateSpecData } from "../../testing/builders/buildDnsCertificateSpecData.js"; +import { DnsCertificateStatus } from "../DnsCertificateStatus/index.js"; +import { DnsCertificateSpec } from "./DnsCertificateSpecData.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; + +beforeEach(() => installBehaviors({})); +afterEach(resetBehaviors); + +describe("DnsCertificateSpec", () => { + test("constructs without a status", () => { + const spec = new DnsCertificateSpec( + buildDnsCertificateSpecData({ status: undefined }), + ); + + expect(spec.cnameTarget).toBe("cname.example.com"); + expect(spec.status).toBeUndefined(); + }); + + test("constructs its status model", () => { + const spec = new DnsCertificateSpec( + buildDnsCertificateSpecData({ + status: buildDnsCertificateStatusData(), + }), + ); + + expect(spec.status).toBeInstanceOf(DnsCertificateStatus); + expect(spec.status?.status).toBe("ready"); + }); +}); diff --git a/packages/models/src/certificate/DnsCertificateSpec/DnsCertificateSpecData.ts b/packages/models/src/certificate/DnsCertificateSpec/DnsCertificateSpecData.ts new file mode 100644 index 00000000..fd1c7d1c --- /dev/null +++ b/packages/models/src/certificate/DnsCertificateSpec/DnsCertificateSpecData.ts @@ -0,0 +1,17 @@ +import type { DnsCertificateSpecData } from "./types.js"; + +import { DnsCertificateStatus } from "../DnsCertificateStatus/index.js"; +import { DataModel } from "../../base/index.js"; + +export class DnsCertificateSpec extends DataModel { + public readonly cnameTarget?: string; + public readonly status?: DnsCertificateStatus; + + public constructor(data: DnsCertificateSpecData) { + super(data); + this.cnameTarget = data.cnameTarget; + if (data.status) { + this.status = new DnsCertificateStatus(data.status); + } + } +} diff --git a/packages/models/src/certificate/DnsCertificateSpec/index.ts b/packages/models/src/certificate/DnsCertificateSpec/index.ts new file mode 100644 index 00000000..38552353 --- /dev/null +++ b/packages/models/src/certificate/DnsCertificateSpec/index.ts @@ -0,0 +1,2 @@ +export * from "./DnsCertificateSpecData.js"; +export * from "./types.js"; diff --git a/packages/models/src/certificate/DnsCertificateSpec/types.ts b/packages/models/src/certificate/DnsCertificateSpec/types.ts new file mode 100644 index 00000000..8c7178f6 --- /dev/null +++ b/packages/models/src/certificate/DnsCertificateSpec/types.ts @@ -0,0 +1,5 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type DnsCertificateSpecData = NonNullable< + MittwaldAPIV2.Components.Schemas.SslCertificate["dnsCertSpec"] +>; diff --git a/packages/models/src/certificate/DnsCertificateStatus/DnsCertificateStatus.test.ts b/packages/models/src/certificate/DnsCertificateStatus/DnsCertificateStatus.test.ts new file mode 100644 index 00000000..81d4a089 --- /dev/null +++ b/packages/models/src/certificate/DnsCertificateStatus/DnsCertificateStatus.test.ts @@ -0,0 +1,29 @@ +import { beforeEach, afterEach, describe, expect, test } from "vitest"; + +import { buildDnsCertificateStatusData } from "../../testing/builders/buildDnsCertificateStatusData.js"; +import { DnsCertificateStatus } from "./DnsCertificateStatus.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; + +beforeEach(() => installBehaviors({})); +afterEach(resetBehaviors); + +describe("DnsCertificateStatus", () => { + test("constructs without an update timestamp", () => { + const status = new DnsCertificateStatus( + buildDnsCertificateStatusData({ updatedAt: undefined }), + ); + + expect(status.status).toBe("ready"); + expect(status.message).toBe("all good"); + expect(status.updatedAt).toBeUndefined(); + }); + + test("converts the update timestamp to a DateTime", () => { + const status = new DnsCertificateStatus(buildDnsCertificateStatusData()); + + expect(status.updatedAt?.toISODate()).toBe("2024-05-01"); + }); +}); diff --git a/packages/models/src/certificate/DnsCertificateStatus/DnsCertificateStatus.ts b/packages/models/src/certificate/DnsCertificateStatus/DnsCertificateStatus.ts new file mode 100644 index 00000000..874b8b30 --- /dev/null +++ b/packages/models/src/certificate/DnsCertificateStatus/DnsCertificateStatus.ts @@ -0,0 +1,23 @@ +import { DateTime } from "luxon"; + +import type { + DnsCertificateStatusData, + ProjectCertificateStatus, +} from "./types.js"; + +import { DataModel } from "../../base/index.js"; + +export class DnsCertificateStatus extends DataModel { + public readonly message?: string; + public readonly status?: ProjectCertificateStatus; + public readonly updatedAt?: DateTime; + + public constructor(data: DnsCertificateStatusData) { + super(data); + this.status = data.status; + this.message = data.message; + if (data.updatedAt) { + this.updatedAt = DateTime.fromISO(data.updatedAt); + } + } +} diff --git a/packages/models/src/certificate/DnsCertificateStatus/index.ts b/packages/models/src/certificate/DnsCertificateStatus/index.ts new file mode 100644 index 00000000..44952d9b --- /dev/null +++ b/packages/models/src/certificate/DnsCertificateStatus/index.ts @@ -0,0 +1,2 @@ +export * from "./DnsCertificateStatus.js"; +export * from "./types.js"; diff --git a/packages/models/src/certificate/DnsCertificateStatus/types.ts b/packages/models/src/certificate/DnsCertificateStatus/types.ts new file mode 100644 index 00000000..f9f4a8db --- /dev/null +++ b/packages/models/src/certificate/DnsCertificateStatus/types.ts @@ -0,0 +1,7 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type DnsCertificateStatusData = + MittwaldAPIV2.Components.Schemas.SslDNSCertStatus; + +export type ProjectCertificateStatus = + MittwaldAPIV2.Components.Schemas.SslProjectCertificateStatus; diff --git a/packages/models/src/certificate/Tls/Tls.test.ts b/packages/models/src/certificate/Tls/Tls.test.ts new file mode 100644 index 00000000..a966d790 --- /dev/null +++ b/packages/models/src/certificate/Tls/Tls.test.ts @@ -0,0 +1,120 @@ +import { afterEach, describe, expect, test } from "vitest"; +import { DateTime } from "luxon"; + +import { buildTlsCertificateData } from "../../testing/builders/buildTlsCertificateData.js"; +import { buildTlsAcmeData } from "../../testing/builders/buildTlsAcmeData.js"; +import { resetBehaviors } from "../../testing/installBehaviors.js"; +import { TlsCertificate, tlsFactory, TlsAcme } from "./Tls.js"; +import { Certificate } from "../Certificate/index.js"; +import { DataModel } from "../../base/index.js"; + +afterEach(resetBehaviors); + +describe("TlsCertificate", () => { + test("constructs a certificate TLS model", () => { + const data = buildTlsCertificateData({ + certificateId: "custom-certificate-id", + }); + + const tls = new TlsCertificate(data); + + expect(tls.type).toBe("certificate"); + expect(tls.certificate).toBeInstanceOf(Certificate); + expect(tls.certificate.id).toBe(data.certificateId); + expect(tls).toBeInstanceOf(DataModel); + }); +}); + +describe("TlsAcme", () => { + test("constructs an ACME TLS model with a request deadline", () => { + const requestDeadline = "2998-12-31T23:00:00.000Z"; + const data = buildTlsAcmeData({ + isCreated: true, + requestDeadline, + acme: false, + }); + + const tls = new TlsAcme(data); + + expect(tls.type).toBe("acme"); + expect(tls.acme).toBe(data.acme); + expect(tls.isCreated).toBe(data.isCreated); + expect(DateTime.isDateTime(tls.requestDeadline)).toBe(true); + expect(tls.requestDeadline?.toMillis()).toBe( + DateTime.fromISO(requestDeadline).toMillis(), + ); + expect(tls).toBeInstanceOf(DataModel); + }); + + test("constructs an ACME TLS model without a request deadline", () => { + const tls = new TlsAcme(buildTlsAcmeData({ requestDeadline: undefined })); + + expect(tls.requestDeadline).toBeUndefined(); + }); + + describe("getStatus", () => { + test("returns undefined when ACME setup is created", () => { + const tls = new TlsAcme(buildTlsAcmeData({ isCreated: true })); + + expect(tls.getStatus()).toBeUndefined(); + }); + + test("returns disabled when ACME is disabled", () => { + const tls = new TlsAcme( + buildTlsAcmeData({ isCreated: false, acme: false }), + ); + + expect(tls.getStatus()).toBe("disabled"); + }); + + test("returns exceeded when there is no request deadline", () => { + const tls = new TlsAcme( + buildTlsAcmeData({ + requestDeadline: undefined, + isCreated: false, + acme: true, + }), + ); + + expect(tls.getStatus()).toBe("exceeded"); + }); + + test("returns exceeded when the request deadline is in the past", () => { + const tls = new TlsAcme( + buildTlsAcmeData({ + requestDeadline: "2000-01-01T00:00:00.000Z", + isCreated: false, + acme: true, + }), + ); + + expect(tls.getStatus()).toBe("exceeded"); + }); + + test("returns running when the request deadline is in the future", () => { + const tls = new TlsAcme( + buildTlsAcmeData({ + requestDeadline: "2999-01-01T00:00:00.000Z", + isCreated: false, + acme: true, + }), + ); + + expect(tls.getStatus()).toBe("running"); + }); + }); +}); + +describe("tlsFactory", () => { + test("returns a TlsCertificate for certificate data", () => { + const tls = tlsFactory(buildTlsCertificateData()); + + expect(tls).toBeInstanceOf(TlsCertificate); + }); + + test("returns a TlsAcme for data without a certificate ID", () => { + const tls = tlsFactory(buildTlsAcmeData()); + + expect(tls).toBeInstanceOf(TlsAcme); + }); +}); diff --git a/packages/models/src/certificate/Tls/Tls.ts b/packages/models/src/certificate/Tls/Tls.ts new file mode 100644 index 00000000..66fbed20 --- /dev/null +++ b/packages/models/src/certificate/Tls/Tls.ts @@ -0,0 +1,69 @@ +import { DateTime } from "luxon"; + +import type { + TlsCertificateData, + TlsAcmeData, + TlsStatus, + TlsData, +} from "./types.js"; + +import { Certificate } from "../Certificate/index.js"; +import { DataModel } from "../../base/index.js"; + +export abstract class TlsBase extends DataModel { + public constructor(data: T) { + super(data); + } +} + +export class TlsCertificate extends TlsBase { + public readonly certificate: Certificate; + public readonly type = "certificate"; + + public constructor(data: TlsCertificateData) { + super(data); + this.certificate = Certificate.ofId(data.certificateId); + } +} + +export class TlsAcme extends TlsBase { + public readonly acme: boolean; + public readonly isCreated: boolean; + public readonly requestDeadline: DateTime | undefined; + public readonly type = "acme"; + public constructor(data: TlsAcmeData) { + super(data); + this.acme = data.acme; + this.isCreated = data.isCreated; + this.requestDeadline = data.requestDeadline + ? DateTime.fromISO(data.requestDeadline) + : undefined; + } + + public getStatus(): TlsStatus | undefined { + if (this.isCreated) { + return undefined; + } + if (!this.acme) { + return "disabled"; + } + if (!this.requestDeadline) { + return "exceeded"; + } + const deadlineExceeded = + DateTime.now().toMillis() > this.requestDeadline.toMillis(); + if (deadlineExceeded) { + return "exceeded"; + } + return "running"; + } +} + +export type Tls = TlsCertificate | TlsAcme; + +export const tlsFactory = (data: TlsData): Tls => { + if ("certificateId" in data) { + return new TlsCertificate(data); + } + return new TlsAcme(data); +}; diff --git a/packages/models/src/certificate/Tls/index.ts b/packages/models/src/certificate/Tls/index.ts new file mode 100644 index 00000000..6af89413 --- /dev/null +++ b/packages/models/src/certificate/Tls/index.ts @@ -0,0 +1,2 @@ +export * from "./Tls.js"; +export * from "./types.js"; diff --git a/packages/models/src/certificate/Tls/types.ts b/packages/models/src/certificate/Tls/types.ts new file mode 100644 index 00000000..36d7058a --- /dev/null +++ b/packages/models/src/certificate/Tls/types.ts @@ -0,0 +1,9 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type TlsAcmeData = MittwaldAPIV2.Components.Schemas.IngressTlsAcme; +export type TlsCertificateData = + MittwaldAPIV2.Components.Schemas.IngressTlsCertificate; + +export type TlsData = TlsCertificateData | TlsAcmeData; + +export type TlsStatus = "exceeded" | "disabled" | "running"; diff --git a/packages/models/src/certificate/index.ts b/packages/models/src/certificate/index.ts new file mode 100644 index 00000000..aeadde31 --- /dev/null +++ b/packages/models/src/certificate/index.ts @@ -0,0 +1,4 @@ +export * from "./Certificate/index.js"; +export * from "./CertificateCheckReplaceResponse/index.js"; +export * from "./CertificateRequest/index.js"; +export * from "./Tls/index.js"; diff --git a/packages/models/src/common/AggregateMetaData.test.ts b/packages/models/src/common/AggregateMetaData.test.ts new file mode 100644 index 00000000..d2199713 --- /dev/null +++ b/packages/models/src/common/AggregateMetaData.test.ts @@ -0,0 +1,33 @@ +import { afterEach, expect, test } from "vitest"; + +import { AggregateMetaData } from "./AggregateMetaData.js"; +import { resetBehaviors } from "../testing/index.js"; +import { Container } from "../container/index.js"; +import { Project } from "../project/index.js"; + +afterEach(resetBehaviors); + +test("exposes its domain and aggregate", () => { + const metadata = new AggregateMetaData("project", "billing"); + + expect(metadata.domain).toBe("project"); + expect(metadata.aggregate).toBe("billing"); +}); + +test("models expose aggregate metadata", () => { + expect(Project.aggregateMetaData).toBeInstanceOf(AggregateMetaData); + expect(Project.aggregateMetaData.domain).not.toBe(""); + expect(Project.aggregateMetaData.aggregate).not.toBe(""); +}); + +test("Container.findAggregate returns an aggregate reference descriptor", () => { + expect(Container.findAggregate("c-1")).toEqual({ + aggregate: Container.aggregateMetaData.aggregate, + domain: Container.aggregateMetaData.domain, + id: "c-1", + }); +}); + +test("Container.findAggregate returns undefined without an id", () => { + expect(Container.findAggregate(undefined)).toBeUndefined(); +}); diff --git a/packages/models/src/common/AggregateMetaData.ts b/packages/models/src/common/AggregateMetaData.ts new file mode 100644 index 00000000..30617b01 --- /dev/null +++ b/packages/models/src/common/AggregateMetaData.ts @@ -0,0 +1,9 @@ +export class AggregateMetaData { + public readonly aggregate: string; + public readonly domain: string; + + public constructor(domain: string, aggregate: string) { + this.domain = domain; + this.aggregate = aggregate; + } +} diff --git a/packages/models/src/common/AggregateReference.test.ts b/packages/models/src/common/AggregateReference.test.ts new file mode 100644 index 00000000..5c3068ef --- /dev/null +++ b/packages/models/src/common/AggregateReference.test.ts @@ -0,0 +1,86 @@ +import { afterEach, expect, test } from "vitest"; + +import { resetBehaviors } from "../testing/index.js"; +import { Container } from "../container/index.js"; +import { Customer } from "../customer/index.js"; +import { Project } from "../project/index.js"; +import { Server } from "../server/index.js"; +import { + tryResolveAggregateReference, + resolveAggregateReference, +} from "./AggregateReference.js"; + +afterEach(resetBehaviors); + +test("resolves a project reference", () => { + const project = resolveAggregateReference({ + aggregate: Project.aggregateMetaData.aggregate, + domain: Project.aggregateMetaData.domain, + id: "p-1", + }); + + expect(project).toBeInstanceOf(Project); + expect(project.id).toBe("p-1"); +}); + +test("resolves a server reference", () => { + const server = resolveAggregateReference({ + aggregate: Server.aggregateMetaData.aggregate, + domain: Server.aggregateMetaData.domain, + id: "s-1", + }); + + expect(server).toBeInstanceOf(Server); + expect(server.id).toBe("s-1"); +}); + +test("resolves a customer reference", () => { + const customer = resolveAggregateReference({ + aggregate: Customer.aggregateMetaData.aggregate, + domain: Customer.aggregateMetaData.domain, + id: "cu-1", + }); + + expect(customer).toBeInstanceOf(Customer); + expect(customer.id).toBe("cu-1"); +}); + +test("resolves a container reference using its parent id", () => { + const container = resolveAggregateReference({ + parent: { + aggregate: Container.aggregateMetaData.aggregate, + domain: Container.aggregateMetaData.domain, + id: "st-1", + }, + aggregate: Container.aggregateMetaData.aggregate, + domain: Container.aggregateMetaData.domain, + id: "c-1", + }); + + expect(container).toBeInstanceOf(Container); + if (!(container instanceof Container)) { + throw new Error("Expected a Container reference"); + } + expect(container.id).toBe("c-1"); + expect(container.stackId).toBe("st-1"); +}); + +test("throws for an unknown aggregate mapping", () => { + expect(() => + resolveAggregateReference({ + aggregate: "nope", + domain: "nope", + id: "x", + }), + ).toThrowError(/not found/); +}); + +test("returns undefined for an unknown aggregate mapping", () => { + expect( + tryResolveAggregateReference({ + aggregate: "nope", + domain: "nope", + id: "x", + }), + ).toBeUndefined(); +}); diff --git a/packages/models/src/common/AggregateReference.ts b/packages/models/src/common/AggregateReference.ts new file mode 100644 index 00000000..fc8aebe3 --- /dev/null +++ b/packages/models/src/common/AggregateReference.ts @@ -0,0 +1,272 @@ +import { FinderProfileRequest, FinderProfile } from "../fyndr/index.js"; +import { ExtensionInstance, Extension } from "../marketplace/index.js"; +import { CustomerInvite, Customer } from "../customer/index.js"; +import { MySqlUser, MySql, Redis } from "../database/index.js"; +import { ProjectInvite, Project } from "../project/index.js"; +import { Container, Registry } from "../container/index.js"; +import { AppInstallation, License } from "../app/index.js"; +import { Conversation } from "../conversation/index.js"; +import { Certificate } from "../certificate/index.js"; +import { CustomerAIPlan } from "../ai/index.js"; +import { MailAddress } from "../mail/index.js"; +import { Ingress } from "../ingress/index.js"; +import { Invoice } from "../invoice/index.js"; +import { Backup } from "../backup/index.js"; +import { Domain } from "../domain/index.js"; +import { Server } from "../server/index.js"; +import { DnsZone } from "../dns/index.js"; +import { Order } from "../order/index.js"; +import { User } from "../user/index.js"; + +interface AggregateReferenceData { + parent?: AggregateReferenceData; + aggregate: string; + domain: string; + id: string; +} +export type AggregateReference = + | FinderProfileRequest + | ExtensionInstance + | AppInstallation + | CustomerInvite + | CustomerAIPlan + | ProjectInvite + | FinderProfile + | Conversation + | MailAddress + | Certificate + | Container + | Extension + | MySqlUser + | Customer + | Registry + | Project + | Ingress + | Invoice + | License + | DnsZone + | Server + | Backup + | Domain + | Order + | MySql + | Redis + | User; + +export function tryResolveAggregateReference( + data: AggregateReferenceData, +): AggregateReference | undefined { + const { aggregate, domain, parent, id } = data; + + if ( + domain === Server.aggregateMetaData.domain && + aggregate === Server.aggregateMetaData.aggregate + ) { + return Server.ofId(id); + } + + if ( + domain === Customer.aggregateMetaData.domain && + aggregate === Customer.aggregateMetaData.aggregate + ) { + return Customer.ofId(id); + } + + if ( + domain === Project.aggregateMetaData.domain && + aggregate === Project.aggregateMetaData.aggregate + ) { + return Project.ofId(id); + } + + if ( + domain === AppInstallation.aggregateMetaData.domain && + aggregate === AppInstallation.aggregateMetaData.aggregate + ) { + return AppInstallation.ofId(id); + } + + if ( + domain === ExtensionInstance.aggregateMetaData.domain && + aggregate === ExtensionInstance.aggregateMetaData.aggregate + ) { + return ExtensionInstance.ofId(id); + } + + if ( + domain === User.aggregateMetaData.domain && + aggregate === User.aggregateMetaData.aggregate + ) { + return User.ofId(id); + } + + if ( + domain === Backup.aggregateMetaData.domain && + aggregate === Backup.aggregateMetaData.aggregate + ) { + return Backup.ofId(id); + } + + if ( + domain === ProjectInvite.aggregateMetaData.domain && + aggregate === ProjectInvite.aggregateMetaData.aggregate + ) { + return ProjectInvite.ofId(id); + } + + if ( + domain === CustomerInvite.aggregateMetaData.domain && + aggregate === CustomerInvite.aggregateMetaData.aggregate + ) { + return CustomerInvite.ofId(id); + } + + if ( + domain === MailAddress.aggregateMetaData.domain && + aggregate === MailAddress.aggregateMetaData.aggregate + ) { + return MailAddress.ofId(id); + } + + if ( + domain === Domain.aggregateMetaData.domain && + aggregate === Domain.aggregateMetaData.aggregate + ) { + return Domain.ofId(id); + } + + if ( + domain === Certificate.aggregateMetaData.domain && + aggregate === Certificate.aggregateMetaData.aggregate + ) { + return Certificate.ofId(id); + } + + if ( + domain === Ingress.aggregateMetaData.domain && + aggregate === Ingress.aggregateMetaData.aggregate + ) { + return Ingress.ofId(id); + } + + if ( + domain === Conversation.aggregateMetaData.domain && + aggregate === Conversation.aggregateMetaData.aggregate + ) { + return Conversation.ofId(id); + } + + if ( + domain === Order.aggregateMetaData.domain && + aggregate === Order.aggregateMetaData.aggregate + ) { + return Order.ofId(id); + } + + if ( + domain === Invoice.aggregateMetaData.domain && + aggregate === Invoice.aggregateMetaData.aggregate + ) { + return Invoice.ofId(id); + } + + if ( + domain === Registry.aggregateMetaData.domain && + aggregate === Registry.aggregateMetaData.aggregate + ) { + return Registry.ofId(id); + } + + if ( + domain === FinderProfile.aggregateMetaData.domain && + aggregate === FinderProfile.aggregateMetaData.aggregate + ) { + return FinderProfile.ofCustomerId(id); + } + + if ( + domain === FinderProfileRequest.aggregateMetaData.domain && + aggregate === FinderProfileRequest.aggregateMetaData.aggregate + ) { + return FinderProfileRequest.ofCustomer(id); + } + + if ( + domain === CustomerAIPlan.aggregateMetaData.domain && + aggregate === CustomerAIPlan.aggregateMetaData.aggregate + ) { + return CustomerAIPlan.ofId(parent?.id ?? id, id); + } + + // Legacy aggregate name from before a customer could have multiple AI + // plans. Persisted activities/notifications may still reference it. + if (domain === "llmlocksmith" && aggregate === "locksmithProfile") { + return CustomerAIPlan.ofId(parent?.id ?? id, id); + } + + if ( + domain === Container.aggregateMetaData.domain && + aggregate === Container.aggregateMetaData.aggregate && + parent?.id !== undefined + ) { + return Container.ofId(id, parent.id); + } + + if ( + domain === License.aggregateMetaData.domain && + aggregate === License.aggregateMetaData.aggregate + ) { + return License.ofId(id); + } + + if ( + domain === Extension.aggregateMetaData.domain && + aggregate === Extension.aggregateMetaData.aggregate + ) { + return Extension.ofId(id); + } + + if ( + domain === MySql.aggregateMetaData.domain && + aggregate === MySql.aggregateMetaData.aggregate + ) { + return MySql.ofId(id); + } + + if ( + domain === Redis.aggregateMetaData.domain && + aggregate === Redis.aggregateMetaData.aggregate + ) { + return Redis.ofId(id); + } + + if ( + domain === MySqlUser.aggregateMetaData.domain && + aggregate === MySqlUser.aggregateMetaData.aggregate + ) { + return MySqlUser.ofId(id); + } + + if ( + domain === DnsZone.aggregateMetaData.domain && + aggregate === DnsZone.aggregateMetaData.aggregate + ) { + return DnsZone.ofId(id); + } + + return undefined; +} + +export function resolveAggregateReference( + data: AggregateReferenceData, +): AggregateReference { + const reference = tryResolveAggregateReference(data); + + if (!reference) { + throw new Error( + `aggregate with domain "${data.domain}" and aggregate "${data.aggregate}" not found`, + ); + } + + return reference; +} diff --git a/packages/models/src/common/Bytes.ts b/packages/models/src/common/Bytes.ts new file mode 100644 index 00000000..6b664039 --- /dev/null +++ b/packages/models/src/common/Bytes.ts @@ -0,0 +1,64 @@ +import type { Data } from "convert"; + +import filesizeParser from "filesize-parser"; +import prettyBytes from "pretty-bytes"; +import convert from "convert"; + +export class Bytes { + public readonly gib: number; + public readonly value: number; + + public constructor(bytes: number) { + this.value = bytes; + this.gib = this.in("GiB"); + } + + public static of(amount: number, unit: string | Data): Bytes { + return new Bytes(convert(amount, unit as Data).to("bytes")); + } + + public static parse(asString: string): Bytes { + return new Bytes(filesizeParser(asString)); + } + + public add(other: Bytes): Bytes { + return new Bytes(this.value + other.value); + } + + public equals(other: Bytes) { + return this.value === other.value; + } + + public in(unit: Data, digits?: number): number { + const converted = convert(this.value, "bytes").to(unit); + if (!digits) { + return converted; + } + return Math.round(converted * 10 ** digits) / 10 ** digits; + } + + public isDifferent(other: Bytes) { + return !this.equals(other); + } + + public isGreaterThan(other: Bytes): boolean { + return this.value > other.value; + } + + public multiply(by: number): Bytes { + return new Bytes(this.value * by); + } + + public percentOf(other: Bytes): string { + return `${((100 / other.value) * this.value).toFixed(1).replace(".", ",")} %`; + } + + public text(options: { binary?: boolean } = {}): string { + const { binary = true } = options; + + return prettyBytes(this.value, { + binary: binary, + locale: "de", + }); + } +} diff --git a/packages/models/src/common/DownloadableFile.ts b/packages/models/src/common/DownloadableFile.ts new file mode 100644 index 00000000..edf22eb9 --- /dev/null +++ b/packages/models/src/common/DownloadableFile.ts @@ -0,0 +1,4 @@ +export interface DownloadableFile { + filename: string; + content: string; +} diff --git a/packages/models/src/common/LocalizedText.ts b/packages/models/src/common/LocalizedText.ts new file mode 100644 index 00000000..0a496fca --- /dev/null +++ b/packages/models/src/common/LocalizedText.ts @@ -0,0 +1,61 @@ +const supportedLanguages = ["de", "en"] as const; +export type LocalizedTextLanguage = (typeof supportedLanguages)[number]; + +export type LocalizedTextData = Partial>; + +const defaultLanguage = "de" as const; + +type GetTextFn = ( + ...args: T extends string ? [] : [key: keyof T] +) => string | undefined; + +export class LocalizedText { + private static language: LocalizedTextLanguage = defaultLanguage; + private readonly data: LocalizedTextData; + + public constructor(data?: LocalizedTextData) { + this.data = data ?? {}; + } + + public static fromJsonString(json: string) { + try { + const parsed = JSON.parse(json); + + if (typeof parsed === "object" && parsed !== null) { + return new LocalizedText(parsed); + } + } catch { + // parsing failed + } + + return new LocalizedText({ [defaultLanguage]: json }); + } + + public static setLanguage(language: LocalizedTextLanguage) { + if (!supportedLanguages.includes(language)) { + throw new Error( + `Unsupported language: ${language}. Supported languages are: ${supportedLanguages.join( + ", ", + )}`, + ); + } + LocalizedText.language = language; + } + + public readonly getText: GetTextFn = (...args) => { + const key = args[0]; + + const value = + this.data[LocalizedText.language] ?? this.data[defaultLanguage]; + + if (!value) { + return undefined; + } + + if (typeof value === "string") { + return value; + } + + return String(value[key as keyof T]); + }; +} diff --git a/packages/models/src/base/Money.ts b/packages/models/src/common/Money.ts similarity index 80% rename from packages/models/src/base/Money.ts rename to packages/models/src/common/Money.ts index 4d8eda63..2068b504 100644 --- a/packages/models/src/base/Money.ts +++ b/packages/models/src/common/Money.ts @@ -5,4 +5,6 @@ Money.defaultCurrency = "EUR"; Money.defaultPrecision = 2; Money.globalLocale = "de-DE"; +export const ZeroMoney = Money({ amount: 0 }); + export type Money = ReturnType; diff --git a/packages/models/src/common/index.ts b/packages/models/src/common/index.ts new file mode 100644 index 00000000..a6b20545 --- /dev/null +++ b/packages/models/src/common/index.ts @@ -0,0 +1,6 @@ +export * from "./AggregateMetaData.js"; +export * from "./AggregateReference.js"; +export * from "./Bytes.js"; +export * from "./DownloadableFile.js"; +export * from "./LocalizedText.js"; +export * from "./Money.js"; diff --git a/packages/models/src/config/behaviors/api.ts b/packages/models/src/config/behaviors/api.ts deleted file mode 100644 index 39907682..00000000 --- a/packages/models/src/config/behaviors/api.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { MittwaldAPIV2Client } from "@mittwald/api-client"; -import { config } from "../config.js"; -import { apiProjectBehaviors } from "../../project/Project/behaviors/index.js"; -import { apiServerBehaviors } from "../../server/Server/behaviors/index.js"; -import { apiCustomerBehaviors } from "../../customer/Customer/behaviors/index.js"; -import { apiIngressBehaviors } from "../../domain/Ingress/behaviors/index.js"; -import { apiAppInstallationBehaviors } from "../../app/AppInstallation/behaviors/index.js"; -import { addUrlTagToProvideReactCache } from "../../react/asyncResourceInvalidation.js"; -import { apiArticleBehaviors } from "../../article/Article/behaviors/index.js"; -import { apiContractBehaviors } from "../../contract/Contract/behaviors/index.js"; -import { apiContractItemBehaviors } from "../../contract/ContractItem/behaviors/index.js"; -import { apiContributorBehaviors } from "../../marketplace/Contributor/behaviors/api.js"; - -class ApiSetupState { - private _client: MittwaldAPIV2Client | undefined; - - public setupWithClient(client: MittwaldAPIV2Client) { - if (this._client !== undefined) { - throw new Error( - "API already setup. If you want to operate on the API client use api.client.", - ); - } - this._client = client; - this._client.defaultRequestOptions.onBeforeRequest = - addUrlTagToProvideReactCache; - - config.behaviors.article = apiArticleBehaviors(client); - config.behaviors.project = apiProjectBehaviors(client); - config.behaviors.server = apiServerBehaviors(client); - config.behaviors.customer = apiCustomerBehaviors(client); - config.behaviors.ingress = apiIngressBehaviors(client); - config.behaviors.appInstallation = apiAppInstallationBehaviors(client); - config.behaviors.contract = apiContractBehaviors(client); - config.behaviors.contributor = apiContributorBehaviors(client); - config.behaviors.contractItem = apiContractItemBehaviors(client); - } - - public setupWithApiToken(apiToken: string) { - return this.setupWithClient(MittwaldAPIV2Client.newWithToken(apiToken)); - } - - public setupUnauthenticated() { - return this.setupWithClient(MittwaldAPIV2Client.newUnauthenticated()); - } - - public get client(): MittwaldAPIV2Client { - if (!this._client) { - throw new Error("Could not get client. Behavior not initialized."); - } - return this._client; - } - - public get defaults(): (typeof this.client)["axios"]["defaults"] { - return this.client.axios.defaults; - } - - public get interceptors(): (typeof this.client)["axios"]["interceptors"] { - return this.client.axios.interceptors; - } -} - -export const api = new ApiSetupState(); diff --git a/packages/models/src/config/behaviors/index.ts b/packages/models/src/config/behaviors/index.ts deleted file mode 100644 index e4fa9cd3..00000000 --- a/packages/models/src/config/behaviors/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./api.js"; diff --git a/packages/models/src/config/config.ts b/packages/models/src/config/config.ts index 6e555f86..c0b4dd11 100644 --- a/packages/models/src/config/config.ts +++ b/packages/models/src/config/config.ts @@ -1,39 +1,189 @@ -import { ProjectBehaviors } from "../project/Project/behaviors/index.js"; -import { ServerBehaviors } from "../server/Server/behaviors/index.js"; -import { CustomerBehaviors } from "../customer/Customer/behaviors/index.js"; -import { IngressBehaviors } from "../domain/Ingress/behaviors/index.js"; -import { ContractBehaviors } from "../contract/Contract/behaviors/index.js"; -import { AppInstallationBehaviors } from "../app/AppInstallation/behaviors/index.js"; -import { ContractItemBehaviors } from "../contract/ContractItem/behaviors/index.js"; -import { ArticleBehaviors } from "../article/Article/behaviors/index.js"; -import type { ContributorBehaviors } from "../marketplace/Contributor/behaviors/types.js"; +import type { PerformanceTtfbAnalysisBehaviors } from "../performance/PerformanceTtfbAnalysis/behaviors/index.js"; +import type { ContributorExtensionBehaviors } from "../marketplace/ContributorExtension/behaviors/index.js"; +import type { CertificateRequestBehaviors } from "../certificate/CertificateRequest/behaviors/index.js"; +import type { SystemSoftwareVersionBehaviors } from "../app/SystemSoftwareVersion/behaviors/index.js"; +import type { FinderProfileRequestBehaviors } from "../fyndr/FinderProfileRequest/behaviors/index.js"; +import type { ExtensionInstanceBehaviors } from "../marketplace/ExtensionInstance/behaviors/index.js"; +import type { CustomerMembershipBehaviors } from "../customer/CustomerMembership/behaviors/index.js"; +import type { ContactVerificationBehaviors } from "../domain/ContactVerification/behaviors/index.js"; +import type { ProjectMembershipBehaviors } from "../project/ProjectMembership/behaviors/index.js"; +import type { UsageMetricsBehaviors } from "../monitoring/UsageMetrics/behaviors/types.js"; +import type { CronjobExecutionBehaviors } from "../cronjob/CronjobExecution/behaviors/index.js"; +import type { InvoiceSettingsBehaviors } from "../customer/InvoiceSettings/behaviors/index.js"; +import type { StorageMetricsBehaviors } from "../monitoring/StorageMetrics/behaviors/index.js"; +import type { NotificationBehaviors } from "../notifications/Notifications/behaviors/index.js"; +import type { RelocationBehaviors } from "../relocation/RelocationRequest/behaviors/index.js"; +import type { ConversationBehaviors } from "../conversation/Conversation/behaviors/index.js"; +import type { CustomerInviteBehaviors } from "../customer/CustomerInvite/behaviors/index.js"; +import type { DomainMigrationBehaviors } from "../domain/DomainMigration/behaviors/index.js"; +import type { AITokenStatisticsBehaviors } from "../ai/AITokenStatistics/behaviors/index.js"; +import type { CustomerAIApiKeyBehaviors } from "../ai/CustomerAIApiKey/behaviors/index.js"; +import type { BackupScheduleBehaviors } from "../backup/BackupSchedule/behaviors/index.js"; +import type { CustomerAIPlanBehavior } from "../ai/CustomerAIPlan/behavior/types.js"; +import type { AppInstallationBehaviors } from "../app/AppInstallation/behaviors/index.js"; +import type { CertificateBehaviors } from "../certificate/Certificate/behaviors/index.js"; +import type { ContributorBehaviors } from "../marketplace/Contributor/behaviors/index.js"; +import type { PerformanceBehaviors } from "../performance/Performance/behaviors/index.js"; +import type { ProjectInviteBehaviors } from "../project/ProjectInvite/behaviors/index.js"; +import type { CustomerAIModelBehaviors } from "../ai/CustomerAIModel/behaviors/index.js"; +import type { ProjectAIApiKeyBehaviors } from "../ai/ProjectAIApiKey/behaviors/index.js"; +import type { ContractItemBehaviors } from "../contract/ContractItem/behaviors/index.js"; +import type { SystemSoftwareBehaviors } from "../app/SystemSoftware/behaviors/index.js"; +import type { FinderProfileBehaviors } from "../fyndr/FinderProfile/behaviors/index.js"; +import type { ProjectAIModelBehaviors } from "../ai/ProjectAIModel/behaviors/index.js"; +import type { MailRateLimitBehaviors } from "../mail/MailRateLimit/behaviors/index.js"; +import type { NewsletterBehaviors } from "../newsletter/Newsletter/behaviors/index.js"; +import type { ExtensionBehaviors } from "../marketplace/Extension/behaviors/index.js"; +import type { RegistrationBehaviors } from "../auth/Registration/behaviors/index.js"; +import type { UnlockedLeadBehaviors } from "../fyndr/UnlockedLead/behavior/index.js"; +import type { MailSettingsBehaviors } from "../mail/MailSettings/behaviors/index.js"; +import type { ContainerBehaviors } from "../container/Container/behaviors/index.js"; +import type { ProjectAIPlanBehavior } from "../ai/ProjectAIPlan/behavior/index.js"; +import type { MySqlUserBehaviors } from "../database/MySqlUser/behaviors/index.js"; +import type { DeliveryBoxBehaviors } from "../mail/DeliveryBox/behaviors/index.js"; +import type { MailAddressBehaviors } from "../mail/MailAddress/behaviors/index.js"; +import type { SupportCodeBehaviors } from "../user/SupportCode/behaviors/index.js"; +import type { RegistryBehaviors } from "../container/Registry/behaviors/index.js"; +import type { LeadsExportBehavior } from "../fyndr/LeadsExport/behavior/index.js"; +import type { ContractBehaviors } from "../contract/Contract/behaviors/index.js"; +import type { CustomerBehaviors } from "../customer/Customer/behaviors/index.js"; +import type { ActivityBehaviors } from "../activity/Activity/behaviors/index.js"; +import type { AppVersionBehaviors } from "../app/AppVersion/behaviors/index.js"; +import type { SftpUserBehaviors } from "../access/SftpUser/behaviors/index.js"; +import type { SpotlightBehaviors } from "../user/Spotlight/behaviors/index.js"; +import type { ArticleBehaviors } from "../article/Article/behaviors/index.js"; +import type { VolumeBehaviors } from "../container/Volume/behaviors/index.js"; +import type { CronjobBehaviors } from "../cronjob/Cronjob/behaviors/index.js"; +import type { IngressBehaviors } from "../ingress/Ingress/behaviors/index.js"; +import type { InvoiceBehaviors } from "../invoice/Invoice/behaviors/index.js"; +import type { ProjectBehaviors } from "../project/Project/behaviors/index.js"; +import type { SshUserBehaviors } from "../access/SshUser/behaviors/index.js"; +import type { ApiTokenBehaviors } from "../user/ApiToken/behaviors/index.js"; +import type { FeedbackBehaviors } from "../user/Feedback/behaviors/index.js"; +import type { AuthBehaviors } from "../auth/Auth/behaviors/types.js"; +import type { BackupBehaviors } from "../backup/Backup/behaviors/index.js"; +import type { MySqlBehaviors } from "../database/MySql/behaviors/index.js"; +import type { RedisBehaviors } from "../database/Redis/behaviors/index.js"; +import type { DomainBehaviors } from "../domain/Domain/behaviors/index.js"; +import type { ServerBehaviors } from "../server/Server/behaviors/index.js"; +import type { SessionBehaviors } from "../user/Session/behaviors/index.js"; +import type { LicenseBehaviors } from "../app/License/behaviors/index.js"; +import type { DnsZoneBehaviors } from "../dns/DnsZone/behaviors/index.js"; +import type { AIModelBehaviors } from "../ai/AIModel/behaviors/index.js"; +import type { SshKeyBehaviors } from "../user/SshKey/behaviors/index.js"; +import type { OrderBehaviors } from "../order/Order/behaviors/index.js"; +import type { TldBehaviors } from "../domain/Tld/behaviors/index.js"; +import type { FileBehaviors } from "../file/File/behaviors/index.js"; +import type { CityBehaviors } from "../fyndr/City/behavior/index.js"; +import type { LeadBehaviors } from "../fyndr/Lead/behavior/index.js"; +import type { UserBehaviors } from "../user/User/behaviors/index.js"; +import type { MfaBehaviors } from "../auth/Mfa/behaviors/index.js"; +import type { AppBehaviors } from "../app/App/behaviors/index.js"; +import type { UserCommon } from "../user/User/User.js"; + +export interface Behaviors { + performanceTtfbAnalysis: PerformanceTtfbAnalysisBehaviors; + systemSoftwareVersion: SystemSoftwareVersionBehaviors; + contributorExtension: ContributorExtensionBehaviors; + finderProfileRequest: FinderProfileRequestBehaviors; + contactVerification: ContactVerificationBehaviors; + certificateRequest: CertificateRequestBehaviors; + customerMembership: CustomerMembershipBehaviors; + extensionInstance: ExtensionInstanceBehaviors; + projectMembership: ProjectMembershipBehaviors; + aiTokenStatistics: AITokenStatisticsBehaviors; + cronjobExecution: CronjobExecutionBehaviors; + customerAiApiKey: CustomerAIApiKeyBehaviors; + appInstallation: AppInstallationBehaviors; + invoiceSettings: InvoiceSettingsBehaviors; + customerAIModel: CustomerAIModelBehaviors; + projectAiApiKey: ProjectAIApiKeyBehaviors; + domainMigration: DomainMigrationBehaviors; + backupSchedule: BackupScheduleBehaviors; + customerInvite: CustomerInviteBehaviors; + storageMetrics: StorageMetricsBehaviors; + systemSoftware: SystemSoftwareBehaviors; + projectAIModel: ProjectAIModelBehaviors; + customerAiPlan: CustomerAIPlanBehavior; + projectInvite: ProjectInviteBehaviors; + finderProfile: FinderProfileBehaviors; + mailRateLimit: MailRateLimitBehaviors; + projectAiPlan: ProjectAIPlanBehavior; + contractItem: ContractItemBehaviors; + conversation: ConversationBehaviors; + mailSettings: MailSettingsBehaviors; + notification: NotificationBehaviors; + registration: RegistrationBehaviors; + usageMetrics: UsageMetricsBehaviors; + unlockedLead: UnlockedLeadBehaviors; + certificate: CertificateBehaviors; + contributor: ContributorBehaviors; + deliveryBox: DeliveryBoxBehaviors; + mailAddress: MailAddressBehaviors; + performance: PerformanceBehaviors; + supportCode: SupportCodeBehaviors; + leadsExport: LeadsExportBehavior; + appVersion: AppVersionBehaviors; + newsletter: NewsletterBehaviors; + relocation: RelocationBehaviors; + spotlight: SpotlightBehaviors; + container: ContainerBehaviors; + extension: ExtensionBehaviors; + mySqlUser: MySqlUserBehaviors; + activity: ActivityBehaviors; + apiToken: ApiTokenBehaviors; + contract: ContractBehaviors; + customer: CustomerBehaviors; + feedback: FeedbackBehaviors; + registry: RegistryBehaviors; + sftpUser: SftpUserBehaviors; + article: ArticleBehaviors; + cronjob: CronjobBehaviors; + dnsZone: DnsZoneBehaviors; + ingress: IngressBehaviors; + invoice: InvoiceBehaviors; + project: ProjectBehaviors; + session: SessionBehaviors; + sshUser: SshUserBehaviors; + aiModel: AIModelBehaviors; + license: LicenseBehaviors; + backup: BackupBehaviors; + domain: DomainBehaviors; + server: ServerBehaviors; + sshKey: SshKeyBehaviors; + volume: VolumeBehaviors; + mySql: MySqlBehaviors; + order: OrderBehaviors; + redis: RedisBehaviors; + auth: AuthBehaviors; + file: FileBehaviors; + user: UserBehaviors; + lead: LeadBehaviors; + city: CityBehaviors; + app: AppBehaviors; + mfa: MfaBehaviors; + tld: TldBehaviors; +} interface Config { + isEmployee?: (user: UserCommon) => boolean; defaultPaginationLimit: number; - behaviors: { - contract: ContractBehaviors; - contributor: ContributorBehaviors; - contractItem: ContractItemBehaviors; - article: ArticleBehaviors; - project: ProjectBehaviors; - server: ServerBehaviors; - customer: CustomerBehaviors; - ingress: IngressBehaviors; - appInstallation: AppInstallationBehaviors; - }; + locale: () => "de" | "en"; + behaviors: Behaviors; } export const config: Config = { + behaviors: new Proxy(Object.create(null), { + get(target, property, receiver) { + if (Reflect.has(target, property)) { + return Reflect.get(target, property, receiver); + } + + throw new Error( + `@mittwald/api-models is not initialized — call initApiModels({ apiClient }) at startup before using any model (accessed behaviors.${String(property)})`, + ); + }, + }), defaultPaginationLimit: 50, - behaviors: { - contract: undefined as unknown as ContractBehaviors, - contractItem: undefined as unknown as ContractItemBehaviors, - contributor: undefined as unknown as ContributorBehaviors, - article: undefined as unknown as ArticleBehaviors, - project: undefined as unknown as ProjectBehaviors, - server: undefined as unknown as ServerBehaviors, - customer: undefined as unknown as CustomerBehaviors, - ingress: undefined as unknown as IngressBehaviors, - appInstallation: undefined as unknown as AppInstallationBehaviors, - }, + locale: () => "de", }; diff --git a/packages/models/src/config/index.ts b/packages/models/src/config/index.ts index f121b6bd..d1bc97e8 100644 --- a/packages/models/src/config/index.ts +++ b/packages/models/src/config/index.ts @@ -1 +1 @@ -export * from "./behaviors/index.js"; +export * from "./config.js"; diff --git a/packages/models/src/config/initApiModels.ts b/packages/models/src/config/initApiModels.ts new file mode 100644 index 00000000..7a573707 --- /dev/null +++ b/packages/models/src/config/initApiModels.ts @@ -0,0 +1,196 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { UserCommon } from "../user/User/User.js"; + +import { apiPerformanceTtfbAnalysisBehaviors } from "../performance/PerformanceTtfbAnalysis/behaviors/index.js"; +import { apiContributorExtensionBehaviors } from "../marketplace/ContributorExtension/behaviors/index.js"; +import { apiCertificateRequestBehaviors } from "../certificate/CertificateRequest/behaviors/index.js"; +import { apiSystemSoftwareVersionBehaviors } from "../app/SystemSoftwareVersion/behaviors/index.js"; +import { apiFinderProfileRequestBehaviors } from "../fyndr/FinderProfileRequest/behaviors/index.js"; +import { apiExtensionInstanceBehaviors } from "../marketplace/ExtensionInstance/behaviors/index.js"; +import { apiCustomerMembershipBehaviors } from "../customer/CustomerMembership/behaviors/index.js"; +import { apiContactVerificationBehaviors } from "../domain/ContactVerification/behaviors/index.js"; +import { apiProjectMembershipBehaviors } from "../project/ProjectMembership/behaviors/index.js"; +import { apiCronjobExecutionBehaviors } from "../cronjob/CronjobExecution/behaviors/index.js"; +import { apiInvoiceSettingsBehaviors } from "../customer/InvoiceSettings/behaviors/index.js"; +import { apiStorageMetricsBehaviors } from "../monitoring/StorageMetrics/behaviors/index.js"; +import { apiUsageMetricsBehaviors } from "../monitoring/UsageMetrics/behaviors/api.js"; +import { apiNotificationBehaviors } from "../notifications/Notifications/behaviors/index.js"; +import { apiRelocationBehaviors } from "../relocation/RelocationRequest/behaviors/index.js"; +import { apiAITokenStatisticsBehaviors } from "../ai/AITokenStatistics/behaviors/index.js"; +import { apiConversationBehaviors } from "../conversation/Conversation/behaviors/index.js"; +import { apiCustomerInviteBehaviors } from "../customer/CustomerInvite/behaviors/index.js"; +import { apiDomainMigrationBehavior } from "../domain/DomainMigration/behaviors/index.js"; +import { apiCustomerAIApiKeyBehaviors } from "../ai/CustomerAIApiKey/behaviors/index.js"; +import { apiBackupScheduleBehaviors } from "../backup/BackupSchedule/behaviors/index.js"; +import { apiCustomerAIPlanBehaviors } from "../ai/CustomerAIPlan/behavior/api.js"; +import { apiAppInstallationBehaviors } from "../app/AppInstallation/behaviors/index.js"; +import { apiCertificateBehaviors } from "../certificate/Certificate/behaviors/index.js"; +import { apiContributorBehaviors } from "../marketplace/Contributor/behaviors/index.js"; +import { apiPerformanceBehaviors } from "../performance/Performance/behaviors/index.js"; +import { apiProjectInviteBehaviors } from "../project/ProjectInvite/behaviors/index.js"; +import { apiCustomerAIModelBehaviors } from "../ai/CustomerAIModel/behaviors/index.js"; +import { apiProjectAIApiKeyBehaviors } from "../ai/ProjectAIApiKey/behaviors/index.js"; +import { apiContractItemBehaviors } from "../contract/ContractItem/behaviors/index.js"; +import { apiSystemSoftwareBehaviors } from "../app/SystemSoftware/behaviors/index.js"; +import { apiFinderProfileBehaviors } from "../fyndr/FinderProfile/behaviors/index.js"; +import { apiProjectAIModelBehaviors } from "../ai/ProjectAIModel/behaviors/index.js"; +import { apiMailRateLimitBehaviors } from "../mail/MailRateLimit/behaviors/index.js"; +import { apiNewsletterBehaviors } from "../newsletter/Newsletter/behaviors/index.js"; +import { apiExtensionBehaviors } from "../marketplace/Extension/behaviors/index.js"; +import { apiRegistrationBehaviors } from "../auth/Registration/behaviors/index.js"; +import { apiUnlockedLeadBehaviors } from "../fyndr/UnlockedLead/behavior/index.js"; +import { apiMailSettingsBehaviors } from "../mail/MailSettings/behaviors/index.js"; +import { apiProjectAIPlanBehaviors } from "../ai/ProjectAIPlan/behavior/index.js"; +import { apiContainerBehaviors } from "../container/Container/behaviors/index.js"; +import { apiMySqlUserBehaviors } from "../database/MySqlUser/behaviors/index.js"; +import { apiDeliveryBoxBehaviors } from "../mail/DeliveryBox/behaviors/index.js"; +import { apiMailAddressBehaviors } from "../mail/MailAddress/behaviors/index.js"; +import { apiSupportCodeBehaviors } from "../user/SupportCode/behaviors/index.js"; +import { apiRegistryBehaviors } from "../container/Registry/behaviors/index.js"; +import { apiLeadsExportBehavior } from "../fyndr/LeadsExport/behavior/index.js"; +import { apiContractBehaviors } from "../contract/Contract/behaviors/index.js"; +import { apiCustomerBehaviors } from "../customer/Customer/behaviors/index.js"; +import { apiActivityBehaviors } from "../activity/Activity/behaviors/index.js"; +import { apiAppVersionBehaviors } from "../app/AppVersion/behaviors/index.js"; +import { apiSpotlightBehaviors } from "../user/Spotlight/behaviors/index.js"; +import { apiSftpUserBehaviors } from "../access/SftpUser/behaviors/index.js"; +import { apiArticleBehaviors } from "../article/Article/behaviors/index.js"; +import { apiVolumeBehaviors } from "../container/Volume/behaviors/index.js"; +import { apiCronjobBehaviors } from "../cronjob/Cronjob/behaviors/index.js"; +import { apiIngressBehaviors } from "../ingress/Ingress/behaviors/index.js"; +import { apiInvoiceBehaviors } from "../invoice/Invoice/behaviors/index.js"; +import { apiProjectBehaviors } from "../project/Project/behaviors/index.js"; +import { apiSshUserBehaviors } from "../access/SshUser/behaviors/index.js"; +import { apiApiTokenBehaviors } from "../user/ApiToken/behaviors/index.js"; +import { apiFeedbackBehaviors } from "../user/Feedback/behaviors/index.js"; +import { apiBackupBehaviors } from "../backup/Backup/behaviors/index.js"; +import { apiMySqlBehaviors } from "../database/MySql/behaviors/index.js"; +import { apiRedisBehaviors } from "../database/Redis/behaviors/index.js"; +import { apiDomainBehaviors } from "../domain/Domain/behaviors/index.js"; +import { apiServerBehaviors } from "../server/Server/behaviors/index.js"; +import { apiSessionBehaviors } from "../user/Session/behaviors/index.js"; +import { apiLicenseBehaviors } from "../app/License/behaviors/index.js"; +import { apiDnsZoneBehaviors } from "../dns/DnsZone/behaviors/index.js"; +import { apiAIModelBehaviors } from "../ai/AIModel/behaviors/index.js"; +import { apiSshKeyBehaviors } from "../user/SshKey/behaviors/index.js"; +import { apiOrderBehaviors } from "../order/Order/behaviors/index.js"; +import { apiAuthBehaviors } from "../auth/Auth/behaviors/index.js"; +import { apiTldBehaviors } from "../domain/Tld/behaviors/index.js"; +import { apiFileBehaviors } from "../file/File/behaviors/index.js"; +import { apiLeadBehaviors } from "../fyndr/Lead/behavior/index.js"; +import { apiUserBehaviors } from "../user/User/behaviors/index.js"; +import { apiCityBehavior } from "../fyndr/City/behavior/index.js"; +import { apiMfaBehaviors } from "../auth/Mfa/behaviors/index.js"; +import { apiAppBehaviors } from "../app/App/behaviors/index.js"; +import { config } from "./config.js"; + +export interface InitApiModelsOptions { + isEmployee?: (user: UserCommon) => boolean; + defaultPaginationLimit?: number; + apiClient: MittwaldAPIV2Client; + locale?: () => "de" | "en"; + usageMetricsUrl?: string; +} + +export function initApiModels(options: InitApiModelsOptions): void { + const { apiClient } = options; + + config.defaultPaginationLimit = options.defaultPaginationLimit ?? 50; + config.isEmployee = options.isEmployee; + config.behaviors.activity = apiActivityBehaviors(apiClient); + config.behaviors.apiToken = apiApiTokenBehaviors(apiClient); + config.behaviors.app = apiAppBehaviors(apiClient); + config.behaviors.appInstallation = apiAppInstallationBehaviors(apiClient); + config.behaviors.appVersion = apiAppVersionBehaviors(apiClient); + config.behaviors.article = apiArticleBehaviors(apiClient); + config.behaviors.auth = apiAuthBehaviors(apiClient); + config.behaviors.backup = apiBackupBehaviors(apiClient); + config.behaviors.backupSchedule = apiBackupScheduleBehaviors(apiClient); + config.behaviors.certificate = apiCertificateBehaviors(apiClient); + config.behaviors.certificateRequest = + apiCertificateRequestBehaviors(apiClient); + config.behaviors.container = apiContainerBehaviors(apiClient); + config.behaviors.contract = apiContractBehaviors(apiClient); + config.behaviors.contractItem = apiContractItemBehaviors(apiClient); + config.behaviors.contributor = apiContributorBehaviors(apiClient); + config.behaviors.contributorExtension = + apiContributorExtensionBehaviors(apiClient); + config.behaviors.conversation = apiConversationBehaviors(apiClient); + config.behaviors.cronjob = apiCronjobBehaviors(apiClient); + config.behaviors.cronjobExecution = apiCronjobExecutionBehaviors(apiClient); + config.behaviors.customer = apiCustomerBehaviors(apiClient); + config.behaviors.customerInvite = apiCustomerInviteBehaviors(apiClient); + config.behaviors.customerMembership = + apiCustomerMembershipBehaviors(apiClient); + config.behaviors.deliveryBox = apiDeliveryBoxBehaviors(apiClient); + config.behaviors.dnsZone = apiDnsZoneBehaviors(apiClient); + config.behaviors.domain = apiDomainBehaviors(apiClient); + config.behaviors.extension = apiExtensionBehaviors(apiClient); + config.behaviors.extensionInstance = apiExtensionInstanceBehaviors(apiClient); + config.behaviors.feedback = apiFeedbackBehaviors(apiClient); + config.behaviors.file = apiFileBehaviors(apiClient); + config.behaviors.ingress = apiIngressBehaviors(apiClient); + config.behaviors.invoice = apiInvoiceBehaviors(apiClient); + config.behaviors.invoiceSettings = apiInvoiceSettingsBehaviors(apiClient); + config.behaviors.mailAddress = apiMailAddressBehaviors(apiClient); + config.behaviors.mailSettings = apiMailSettingsBehaviors(apiClient); + config.behaviors.mfa = apiMfaBehaviors(apiClient); + config.behaviors.mySql = apiMySqlBehaviors(apiClient); + config.behaviors.mySqlUser = apiMySqlUserBehaviors(apiClient); + config.behaviors.newsletter = apiNewsletterBehaviors(apiClient); + config.behaviors.notification = apiNotificationBehaviors(apiClient); + config.behaviors.order = apiOrderBehaviors(apiClient); + config.behaviors.performance = apiPerformanceBehaviors(apiClient); + config.behaviors.performanceTtfbAnalysis = + apiPerformanceTtfbAnalysisBehaviors(apiClient); + config.behaviors.project = apiProjectBehaviors(apiClient); + config.behaviors.projectInvite = apiProjectInviteBehaviors(apiClient); + config.behaviors.projectMembership = apiProjectMembershipBehaviors(apiClient); + config.behaviors.redis = apiRedisBehaviors(apiClient); + config.behaviors.registration = apiRegistrationBehaviors(apiClient); + config.behaviors.registry = apiRegistryBehaviors(apiClient); + config.behaviors.relocation = apiRelocationBehaviors(apiClient); + config.behaviors.server = apiServerBehaviors(apiClient); + config.behaviors.session = apiSessionBehaviors(apiClient); + config.behaviors.sftpUser = apiSftpUserBehaviors(apiClient); + config.behaviors.spotlight = apiSpotlightBehaviors(apiClient); + config.behaviors.sshKey = apiSshKeyBehaviors(apiClient); + config.behaviors.sshUser = apiSshUserBehaviors(apiClient); + config.behaviors.storageMetrics = apiStorageMetricsBehaviors(apiClient); + config.behaviors.supportCode = apiSupportCodeBehaviors(apiClient); + config.behaviors.systemSoftware = apiSystemSoftwareBehaviors(apiClient); + config.behaviors.systemSoftwareVersion = + apiSystemSoftwareVersionBehaviors(apiClient); + config.behaviors.tld = apiTldBehaviors(apiClient); + config.behaviors.user = apiUserBehaviors(apiClient); + config.behaviors.volume = apiVolumeBehaviors(apiClient); + config.behaviors.finderProfile = apiFinderProfileBehaviors(apiClient); + config.behaviors.finderProfileRequest = + apiFinderProfileRequestBehaviors(apiClient); + config.behaviors.lead = apiLeadBehaviors(apiClient); + config.behaviors.leadsExport = apiLeadsExportBehavior(apiClient); + config.behaviors.unlockedLead = apiUnlockedLeadBehaviors(apiClient); + config.behaviors.city = apiCityBehavior(apiClient); + config.behaviors.aiModel = apiAIModelBehaviors(apiClient); + config.behaviors.customerAIModel = apiCustomerAIModelBehaviors(apiClient); + config.behaviors.projectAIModel = apiProjectAIModelBehaviors(apiClient); + config.behaviors.projectAiApiKey = apiProjectAIApiKeyBehaviors(apiClient); + config.behaviors.customerAiApiKey = apiCustomerAIApiKeyBehaviors(apiClient); + config.behaviors.projectAiPlan = apiProjectAIPlanBehaviors(apiClient); + config.behaviors.customerAiPlan = apiCustomerAIPlanBehaviors(apiClient); + config.behaviors.aiTokenStatistics = apiAITokenStatisticsBehaviors(apiClient); + config.behaviors.license = apiLicenseBehaviors(apiClient); + config.behaviors.usageMetrics = apiUsageMetricsBehaviors( + apiClient, + options.usageMetricsUrl ?? "", + ); + config.behaviors.contactVerification = + apiContactVerificationBehaviors(apiClient); + config.behaviors.domainMigration = apiDomainMigrationBehavior(apiClient); + config.behaviors.mailRateLimit = apiMailRateLimitBehaviors(apiClient); + + if (options.locale) { + config.locale = options.locale; + } +} diff --git a/packages/models/src/container/Container/Container.test.ts b/packages/models/src/container/Container/Container.test.ts new file mode 100644 index 00000000..e92db0af --- /dev/null +++ b/packages/models/src/container/Container/Container.test.ts @@ -0,0 +1,198 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { ContainerDetailed, ContainerCommon, Container } from "./Container.js"; +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { + buildContainerData, + installBehaviors, + resetBehaviors, +} from "../../testing/index.js"; + +afterEach(resetBehaviors); + +describe("Container", () => { + test("find delegates to the container behavior and returns a detailed container", async () => { + const find = vi + .fn() + .mockResolvedValue(buildContainerData({ stackId: "s-1", id: "c-1" })); + installBehaviors({ container: { find } }); + + const result = await Container.find("c-1", "s-1"); + + expect(find).toHaveBeenCalledWith("c-1", "s-1"); + expect(result).toBeInstanceOf(ContainerDetailed); + expect(result?.id).toBe("c-1"); + }); + + test("find maps a missing container to undefined", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ container: { find } }); + + const result = await Container.find("missing", "s-1"); + + expect(find).toHaveBeenCalledWith("missing", "s-1"); + expect(result).toBeUndefined(); + }); + + test("get delegates to the container behavior and returns a detailed container", async () => { + const find = vi + .fn() + .mockResolvedValue(buildContainerData({ stackId: "s-2", id: "c-2" })); + installBehaviors({ container: { find } }); + + const result = await Container.get("c-2", "s-2"); + + expect(find).toHaveBeenCalledWith("c-2", "s-2"); + expect(result).toBeInstanceOf(ContainerDetailed); + expect(result.id).toBe("c-2"); + }); + + test("get rejects with ObjectNotFoundError when the container is missing", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ container: { find } }); + + await expect(Container.get("missing", "s-1")).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("findDetailed delegates with the reference identifiers", async () => { + const ref = Container.ofId("c-3", "s-3"); + const find = vi + .fn() + .mockResolvedValue(buildContainerData({ stackId: "s-3", id: "c-3" })); + installBehaviors({ container: { find } }); + + const result = await ref.findDetailed(); + + expect(find).toHaveBeenCalledWith("c-3", "s-3"); + expect(result).toBeInstanceOf(ContainerDetailed); + expect(result?.id).toBe("c-3"); + }); + + test("findCommon delegates to find and returns a detailed container for a bare reference", async () => { + const find = vi + .fn() + .mockResolvedValue(buildContainerData({ stackId: "s-4", id: "c-4" })); + installBehaviors({ container: { find } }); + const ref = Container.ofId("c-4", "s-4"); + + const result = await ref.findCommon(); + + expect(find).toHaveBeenCalledWith("c-4", "s-4"); + expect(result).toBeInstanceOf(ContainerDetailed); + expect(result).toBeInstanceOf(ContainerCommon); + expect(result?.id).toBe("c-4"); + }); + + test("findCommon maps a missing container to undefined for a bare reference", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ container: { find } }); + + await expect( + Container.ofId("m", "s").findCommon(), + ).resolves.toBeUndefined(); + expect(find).toHaveBeenCalledWith("m", "s"); + }); + + test("getCommon rejects with ObjectNotFoundError for a missing bare reference", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ container: { find } }); + + await expect(Container.ofId("m", "s").getCommon()).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("findCommon and getCommon reuse an already materialized container without re-fetching", async () => { + const find = vi + .fn() + .mockResolvedValue(buildContainerData({ stackId: "s-5", id: "c-5" })); + installBehaviors({ container: { find } }); + const detailed = await Container.get("c-5", "s-5"); + find.mockClear(); + + expect(detailed).toBeInstanceOf(ContainerCommon); + await expect(detailed.findCommon()).resolves.toBe(detailed); + await expect(detailed.getCommon()).resolves.toBe(detailed); + expect(find).not.toHaveBeenCalled(); + }); + + test("aggregateMetaData identifies the container aggregate", () => { + expect(Container.aggregateMetaData).toBeInstanceOf(AggregateMetaData); + expect(Container.aggregateMetaData.domain).toBe("container"); + expect(Container.aggregateMetaData.aggregate).toBe("container"); + }); + + test("cpuLimit and ramLimit are undefined when deploy resource limits are absent", async () => { + const find = vi + .fn() + .mockResolvedValue(buildContainerData({ stackId: "s-6", id: "c-6" })); + installBehaviors({ container: { find } }); + + const container = await Container.get("c-6", "s-6"); + + expect(container.cpuLimit).toBeUndefined(); + expect(container.ramLimit).toBeUndefined(); + }); + + test.each([ + { status: "running", expected: true }, + { status: "error", expected: true }, + { status: "stopped", expected: false }, + { status: "creating", expected: false }, + { status: "starting", expected: false }, + { status: "stopping", expected: false }, + { status: undefined, expected: false }, + ] as const)( + "canRestart returns $expected when the status is $status", + ({ expected, status }) => { + const container = new ContainerCommon(buildContainerData({ status })); + + expect(container.canRestart()).toBe(expected); + }, + ); + + test.each([ + { status: "stopped", expected: true }, + { status: "running", expected: false }, + { status: "error", expected: false }, + { status: "creating", expected: false }, + { status: "starting", expected: false }, + { status: "stopping", expected: false }, + { status: undefined, expected: false }, + ] as const)( + "canStart returns $expected when the status is $status", + ({ expected, status }) => { + const container = new ContainerCommon(buildContainerData({ status })); + + expect(container.canStart()).toBe(expected); + }, + ); + + test.each([ + { status: "stopped", expected: false }, + { status: "running", expected: true }, + { status: "error", expected: true }, + { status: "creating", expected: true }, + { status: "starting", expected: true }, + { status: "stopping", expected: true }, + { status: undefined, expected: true }, + ] as const)( + "canStop returns $expected when the status is $status", + ({ expected, status }) => { + const container = new ContainerCommon(buildContainerData({ status })); + + expect(container.canStop()).toBe(expected); + }, + ); +}); diff --git a/packages/models/src/container/Container/Container.ts b/packages/models/src/container/Container/Container.ts new file mode 100644 index 00000000..91cce04a --- /dev/null +++ b/packages/models/src/container/Container/Container.ts @@ -0,0 +1,535 @@ +import type { AxiosRequestConfig } from "axios"; + +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { omit, pick } from "remeda"; +import { DateTime } from "luxon"; +import slugify from "slugify"; + +import type { ContainerVolumeRelationList } from "./ContainerVolumeRelation.js"; +import type { ContainerEnvVariableList } from "./ContainerEnvVariable.js"; +import type { ContainerPortList } from "./ContainerPort.js"; +import type { + ContainerStackPatchRequestData, + ContainerListQueryModelData, + ContainerResourceLimitsData, + ContainerListItemData, + ContainerUpdateData, + ContainerStatus, + ContainerData, +} from "./types.js"; + +import { + type DownloadableFile, + AggregateMetaData, +} from "../../common/index.js"; +import { ContainerVolumeRelation } from "./ContainerVolumeRelation.js"; +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { ContainerTemplate } from "./ContainerTemplate.js"; +import { ContainerStack } from "./ContainerStack.js"; +import { ContainerState } from "./ContainerState.js"; +import { Project } from "../../project/internal.js"; +import { shellSplit } from "../lib/shellwords.js"; +import { Cronjob } from "../../cronjob/index.js"; +import { ImageMeta } from "./ImageMeta.js"; +import { config } from "../../config/index.js"; +import { Volume } from "../Volume/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "Container", +}) +export class Container extends ReferenceModel { + public static aggregateMetaData = new AggregateMetaData( + "container", + "container", + ); + + public readonly stackId: string; + + public constructor(id: string, stackId: string) { + super(id); + this.stackId = stackId; + } + + public static async create( + stackId: string, + data: ContainerStackPatchRequestData, + ) { + const response = await config.behaviors.container.create(stackId, data); + + return new Container(response.id, stackId); + } + + public static async find(id: string, stackId: string) { + const data = await config.behaviors.container.find(id, stackId); + if (data) { + return new ContainerDetailed(data); + } + } + + public static findAggregate(containerId?: string) { + return containerId + ? { id: containerId, ...Container.aggregateMetaData } + : undefined; + } + + public static generateServiceName(description: string) { + return slugify(description, { + strict: true, + lower: true, + }); + } + + public static async get(id: string, stackId: string) { + const container = await Container.find(id, stackId); + assertObjectFound(container, Container, id); + return container; + } + + public static async getImageMeta( + imageRef: string, + projectId: string, + generateAiData?: boolean, + language?: string, + ): Promise { + const result = await config.behaviors.container.getImageMeta( + imageRef, + projectId, + generateAiData, + language, + ); + + if (typeof result !== "string" && "isAiAvailable" in result) { + return new ImageMeta(result, imageRef); + } + return result; + } + + public static ofId(id: string, stackId: string) { + return new Container(id, stackId); + } + + public static query(query: ContainerListQueryModelData = {}) { + return new ContainerListQuery(query); + } + + public async findCommon(): Promise { + return this instanceof ContainerCommon ? this : this.findDetailed(); + } + + public async findDetailed(): Promise { + return Container.find(this.id, this.stackId); + } + + public async getCommon(): Promise { + return this instanceof ContainerCommon ? this : this.getDetailed(); + } + + public getDetailed(): Promise { + return Container.get(this.id, this.stackId); + } + + public async pullImage() { + await config.behaviors.container.pullImage(this.id, this.stackId); + } + + public async recreate() { + await config.behaviors.container.recreate(this.id, this.stackId); + } + + public async restart() { + await config.behaviors.container.restart(this.id, this.stackId); + } + + public async start() { + await config.behaviors.container.start(this.id, this.stackId); + } + + public async stop() { + await config.behaviors.container.stop(this.id, this.stackId); + } +} + +export class ContainerCommon extends WithData< + ContainerListItemData | ContainerData +>()(Container) { + public readonly command?: string; + public readonly cpuLimit?: string; + public override readonly data: ContainerListItemData | ContainerData; + public readonly deployedState: ContainerState; + public readonly description: string; + public readonly entrypoint?: string; + public readonly message?: string; + public readonly pendingState: ContainerState; + public readonly project: Project; + public readonly ramLimit?: string; + public readonly recreateRequired?: boolean; + public readonly serviceName: string; + public readonly shortId: string; + public readonly stack: ContainerStack; + public readonly status?: ContainerStatus; + public readonly statusSetAt?: DateTime; + public readonly template?: ContainerTemplate; + + public constructor(data: ContainerListItemData | ContainerData) { + super(data.id, data.stackId); + this.data = data; + this.shortId = data.shortId; + this.description = data.description.trim(); + this.serviceName = data.serviceName.trim(); + this.deployedState = new ContainerState(data.deployedState); + this.pendingState = new ContainerState(data.pendingState); + this.status = data.status; + this.statusSetAt = DateTime.fromISO(data.statusSetAt); + this.message = data.message; + this.recreateRequired = data.requiresRecreate; + this.cpuLimit = data.deploy?.resources?.limits?.cpus; + this.ramLimit = data.deploy?.resources?.limits?.memory; + this.project = Project.ofId(data.projectId); + this.stack = ContainerStack.ofId(data.stackId); + this.template = data.templateId + ? new ContainerTemplate(data.templateId) + : undefined; + } + + public canRestart(): boolean { + return this.status === "running" || this.status === "error"; + } + + public canStart(): boolean { + return this.status === "stopped"; + } + + public canStop(): boolean { + return this.status !== "stopped"; + } + + public async delete() { + await config.behaviors.container.delete(this.serviceName, this.stackId); + } + + public async getLogDownload(): Promise { + const response = await config.behaviors.container.getLog( + this.id, + this.stackId, + ); + return { filename: `${this.serviceName}.log`, content: response }; + } + + public async listCronjobs() { + const cronjobList = await Cronjob.query({ + project: this.project, + }).execute(); + + return cronjobList.items.filter( + (cronjob) => + cronjob.targetType === "container" && + cronjob.linkedContainer?.id === this.shortId && + cronjob.linkedContainer?.stackId === this.stackId, + ); + } + + public async resetToDeployedState() { + await config.behaviors.container.updateStack(this.stackId, { + services: { + [this.serviceName]: { + entrypoint: shellSplit(this.deployedState.entrypoint ?? ""), + command: shellSplit(this.deployedState.command ?? ""), + volumes: this.deployedState.volumes.toStringArray(), + envs: this.deployedState.envs.toApiDataObject(), + ports: this.deployedState.ports.toStringArray(), + image: this.deployedState.imageReference, + }, + }, + }); + } + + public async rotateImagePullWebhook() { + return await config.behaviors.container.rotateImagePullWebhook( + this.id, + this.stackId, + ); + } + + public async update( + data: ContainerUpdateData, + ): Promise { + const response = await config.behaviors.container.updateStack( + this.stackId, + { + services: { + [this.serviceName]: { + description: data.description, + image: data.image, + }, + }, + }, + ); + + const containerData = response.services?.find( + (s) => s.serviceName === this.serviceName, + ); + + return containerData ? new ContainerDetailed(containerData) : undefined; + } + + public async updateCommand( + command: string, + custom?: boolean, + ): Promise { + const result = await config.behaviors.container.updateStack(this.stackId, { + services: { + [this.serviceName]: { + command: + command.trim() !== this.command?.trim() && custom + ? shellSplit(command) + : [], + }, + }, + }); + + const containerData = result.services?.find( + (s) => s.serviceName === this.serviceName, + ); + + return containerData ? new ContainerDetailed(containerData) : undefined; + } + + public async updateEntrypoint( + entrypoint: string, + custom?: boolean, + ): Promise { + const result = await config.behaviors.container.updateStack(this.stackId, { + services: { + [this.serviceName]: { + entrypoint: + entrypoint.trim() !== this.entrypoint?.trim() && custom + ? shellSplit(entrypoint) + : [], + }, + }, + }); + + const containerData = result.services?.find( + (s) => s.serviceName === this.serviceName, + ); + + return containerData ? new ContainerDetailed(containerData) : undefined; + } + + public async updateEnvs( + envList: ContainerEnvVariableList, + ): Promise { + const result = await config.behaviors.container.updateStack(this.stackId, { + services: { + [this.serviceName]: { + envs: envList.toApiDataObject(), + }, + }, + }); + + const containerData = result.services?.find( + (s) => s.serviceName === this.serviceName, + ); + + return containerData ? new ContainerDetailed(containerData) : undefined; + } + + public async updatePorts( + portList: ContainerPortList, + ): Promise { + const result = await config.behaviors.container.updateStack(this.stackId, { + services: { + [this.serviceName]: { + ports: portList.toStringArray(), + }, + }, + }); + + const containerData = result.services?.find( + (s) => s.serviceName === this.serviceName, + ); + + return containerData ? new ContainerDetailed(containerData) : undefined; + } + + public async updateResourceLimits( + limits: ContainerResourceLimitsData, + ): Promise { + const hasCpuLimit = limits.cpuLimit != null; + const hasRamLimit = limits.ramLimit != null; + + const result = await config.behaviors.container.updateStack(this.stackId, { + services: { + [this.serviceName]: { + deploy: { + resources: + hasCpuLimit || hasRamLimit + ? { + limits: { + memory: limits.ramLimit, + cpus: limits.cpuLimit, + }, + } + : {}, + }, + }, + }, + }); + + const containerData = result.services?.find( + (s) => s.serviceName === this.serviceName, + ); + + return containerData ? new ContainerDetailed(containerData) : undefined; + } + + public async updateVolumes( + volumes: ContainerVolumeRelationList, + ): Promise { + const newVolumes = volumes.items + .filter((v) => v.volumeCreationRequired) + .map( + (v) => + new ContainerVolumeRelation( + v.data.replace( + "createNewVolume", + Volume.generateRandomName( + `${this.serviceName}${v.containerPath?.toLowerCase().split("/").join("-")}`, + ), + ), + ), + ); + const existingVolumesAndProjectPaths = volumes.items + .filter((v) => !v.volumeCreationRequired) + .map((v) => v.data); + + const result = await config.behaviors.container.updateStack(this.stackId, { + volumes: + newVolumes.length > 0 + ? newVolumes.reduce( + (prev: Record, curr) => { + if (!curr.volume) { + return prev; + } + prev[curr.volume] = { name: curr.volume }; + return prev; + }, + {}, + ) + : {}, + services: { + [this.serviceName]: { + volumes: [ + ...newVolumes.map((v) => v.data), + ...existingVolumesAndProjectPaths, + ], + }, + }, + }); + + const containerData = result.services?.find( + (s) => s.serviceName === this.serviceName, + ); + + return containerData ? new ContainerDetailed(containerData) : undefined; + } +} + +export class ContainerDetailed extends ContainerCommon { + public override readonly data: ContainerData; + public readonly project: Project; + + public constructor(data: ContainerData) { + super(data); + this.data = data; + this.project = Project.ofId(data.projectId); + } +} + +export class ContainerListItem extends ContainerCommon { + public override readonly data: ContainerListItemData; + public constructor(data: ContainerListItemData) { + super(data); + this.data = data; + } +} + +export class ContainerListQuery extends ListQueryModel { + public constructor(query: ContainerListQueryModelData = {}) { + const projectId = extractId(query.project); + super(query, projectId ? { dependencies: [projectId] } : undefined); + } + + public async checkServiceNameIsAvailable(serviceName: string) { + const result = await this.refine({ + searchTerm: serviceName, + limit: 10, + }).execute(); + + return !result.items.some((c) => c.serviceName === serviceName); + } + + public async execute(options?: AxiosRequestConfig) { + const projectId = extractId(this.query.project); + const { totalCount, items } = projectId + ? await config.behaviors.container.list( + projectId, + { + ...omit(this.query, ["project", "stack"]), + stackId: extractId(this.query.stack), + }, + options, + ) + : await config.behaviors.container.listAccessible( + pick(this.query, [ + "searchTerm", + "sortOrder", + "limit", + "skip", + "page", + ]), + options, + ); + + return new ContainerList( + this.query, + items.map((c) => new ContainerListItem(c)), + totalCount, + ); + } + + public async getTotalCount() { + const { totalCount } = await this.refine({ limit: 1 }).execute(); + return totalCount; + } + + public refine(query: Partial = {}) { + return new ContainerListQuery({ + ...this.query, + ...query, + }); + } +} + +export class ContainerList extends WithListData()( + ContainerListQuery, +) { + public override readonly items: readonly ContainerListItem[]; + public override readonly totalCount: number; + public constructor( + query: ContainerListQueryModelData, + containers: ContainerListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(containers); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/container/Container/ContainerEnvVariable.ts b/packages/models/src/container/Container/ContainerEnvVariable.ts new file mode 100644 index 00000000..d93aecd0 --- /dev/null +++ b/packages/models/src/container/Container/ContainerEnvVariable.ts @@ -0,0 +1,83 @@ +import type { + ContainerEnvVariableListData, + ContainerEnvVariableData, +} from "./types.js"; + +import { ListDataModel, DataModel } from "../../base/index.js"; + +export class ContainerEnvVariable extends DataModel { + public readonly key: string; + public readonly value: string; + + public constructor(data: ContainerEnvVariableData) { + super(data); + this.key = data.key.trim(); + this.value = data.value.trim(); + } + + public toString(): string { + return this.key || this.value + ? `${this.key ? this.key : ""}=${this.value ? this.value : ""}` + : ""; + } +} + +export class ContainerEnvVariableList extends ListDataModel { + public readonly data: ContainerEnvVariableListData; + + public constructor(envs: ContainerEnvVariableListData) { + const envArray = []; + for (const [key, value] of Object.entries(envs)) { + envArray.push(new ContainerEnvVariable({ value, key })); + } + super(envArray, envArray.length); + this.data = envs; + } + + public static fromText(text: string): ContainerEnvVariableList { + const envs = text + .split("\n") + .filter((line) => line !== "" && !line.startsWith("#")) + .reduce((prev, curr) => { + // eslint-disable-next-line prefer-const + let [key, value] = curr.split(/=(.*)/s); + if (!key || !value) { + return prev; + } + + const commentIndex = value.indexOf(" # "); + if ( + commentIndex && + commentIndex > -1 && + !value.includes('"') && + !value.includes("'") + ) { + value = value.substring(0, commentIndex).trim(); + } + + return { ...prev, [key]: value.replace(/['"]/g, "") }; + }, {}); + + return new ContainerEnvVariableList(envs); + } + + public static fromVariables( + variables: ContainerEnvVariable[], + ): ContainerEnvVariableList { + return new ContainerEnvVariableList( + variables.reduce((prev, curr) => { + return Object.assign(prev, { [curr.key]: curr.value }); + }, {}), + ); + } + + public toApiDataObject(): ContainerEnvVariableListData { + return this.items.reduce((prev, curr) => { + return Object.assign(prev, { [curr.key]: curr.value }); + }, {}); + } + + public toString(): string { + return this.items.map((v) => v.toString()).join("\n"); + } +} diff --git a/packages/models/src/container/Container/ContainerLog.ts b/packages/models/src/container/Container/ContainerLog.ts new file mode 100644 index 00000000..a787942b --- /dev/null +++ b/packages/models/src/container/Container/ContainerLog.ts @@ -0,0 +1,53 @@ +import type { AxiosRequestConfig } from "axios"; + +import { DateTime } from "luxon"; + +import type { ContainerLogChunk, ContainerLogData } from "./types.js"; +import type { Container } from "./Container.js"; + +import { WithData } from "../../base/index.js"; +import { config } from "../../config/index.js"; + +export class ContainerLog { + public static async get(container: Container) { + const data = await config.behaviors.container.getLog( + container.id, + container.stackId, + ); + return new ContainerLogDetailed(data, container); + } + + public static async getChunk( + container: Container, + range: string, + requestOptions?: AxiosRequestConfig, + ): Promise { + return config.behaviors.container.getLogChunk( + container.id, + container.stackId, + range, + requestOptions, + ); + } +} + +class ContainerLogCommon extends WithData()(ContainerLog) { + public readonly container: Container; + public readonly content: string; + public override readonly data: ContainerLogData; + public readonly lastRefresh: DateTime; + + public constructor(data: ContainerLogData, container: Container) { + super(); + this.data = data; + this.content = data; + this.lastRefresh = DateTime.now(); + this.container = container; + } +} + +export class ContainerLogDetailed extends ContainerLogCommon { + public constructor(data: ContainerLogData, container: Container) { + super(data, container); + } +} diff --git a/packages/models/src/container/Container/ContainerPort.ts b/packages/models/src/container/Container/ContainerPort.ts new file mode 100644 index 00000000..0baedb09 --- /dev/null +++ b/packages/models/src/container/Container/ContainerPort.ts @@ -0,0 +1,104 @@ +import invariant from "tiny-invariant"; + +import { type ContainerPortData, containerMaxPort } from "./types.js"; +import { ListDataModel, DataModel } from "../../base/index.js"; + +const parsePortOrRange = (portStr: string) => { + const [start, end] = portStr.split("-"); + invariant(start, "Invalid container port definition!"); + return { + end: end ? parseInt(end) : undefined, + start: parseInt(start), + }; +}; + +export class ContainerPort extends DataModel { + public readonly external: number; + public readonly externalRangeEnd?: number; + public readonly internal: number; + public readonly internalRangeEnd?: number; + public readonly isRange: boolean; + public readonly protocol?: string; + + public constructor(data: ContainerPortData) { + super(data); + const [portString, protocol] = data.split("/"); + invariant(portString, "Invalid container port definition!"); + const [internalPart, externalPart] = portString.split(":"); + invariant(internalPart, "Invalid container port definition!"); + + const internal = parsePortOrRange(internalPart); + const external = externalPart ? parsePortOrRange(externalPart) : internal; + + this.internal = internal.start; + this.internalRangeEnd = internal.end; + this.external = external.start; + this.externalRangeEnd = external.end; + this.isRange = internal.end !== undefined && external.end !== undefined; + this.protocol = protocol?.trim() ?? "tcp"; + } + + /** The API doesn't support port mapping yet — ports must be equal. */ + public static hasEqualMapping(port: string): boolean { + const portObj = new ContainerPort(port); + return ( + portObj.internal === portObj.external && + portObj.internalRangeEnd === portObj.externalRangeEnd + ); + } + + public static validatePort(port: string): boolean { + const portObj = new ContainerPort(port); + const validPortOrRange = (portStart: number, portRangeEnd?: number) => + portStart > 0 && + portStart <= containerMaxPort && + (portRangeEnd === undefined || + (portRangeEnd > 0 && + portRangeEnd <= containerMaxPort && + portRangeEnd >= portStart)); + const internalLength = + (portObj.internalRangeEnd ?? portObj.internal) - portObj.internal; + const externalLength = + (portObj.externalRangeEnd ?? portObj.external) - portObj.external; + + return ( + validPortOrRange(portObj.internal, portObj.internalRangeEnd) && + validPortOrRange(portObj.external, portObj.externalRangeEnd) && + (!portObj.isRange || internalLength === externalLength) + ); + } + + public toString(externalOnly?: boolean): string { + const internalStr = + this.internalRangeEnd !== undefined + ? `${this.internal}-${this.internalRangeEnd}` + : `${this.internal}`; + const externalStr = + this.externalRangeEnd !== undefined + ? `${this.external}-${this.externalRangeEnd}` + : `${this.external}`; + const protocol = this.protocol ? `/${this.protocol}` : ""; + + if (externalOnly || internalStr === externalStr) { + return `${externalStr}${protocol}`; + } + return `${internalStr}:${externalStr}${protocol}`; + } +} + +export class ContainerPortList extends ListDataModel { + public constructor(ports: ContainerPortData[]) { + super( + ports.map((p) => new ContainerPort(p)), + ports.length, + ); + } + + public static fromPorts(ports: ContainerPort[]): ContainerPortList { + return new ContainerPortList(ports.map((p) => p.toString())); + } + + public toStringArray(): string[] { + return this.items.map((p) => p.toString()); + } +} diff --git a/packages/models/src/container/Container/ContainerStack.ts b/packages/models/src/container/Container/ContainerStack.ts new file mode 100644 index 00000000..d251a1a4 --- /dev/null +++ b/packages/models/src/container/Container/ContainerStack.ts @@ -0,0 +1,259 @@ +import type { AxiosRequestConfig } from "axios"; + +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { omit } from "remeda"; + +import type { + ContainerStackListQueryModelData, + ContainerStackUpdateScheduleData, + ContainerTemplateUserInputValues, + ContainerStackDeclareRequestData, + ContainerStackCreateRequestData, + ContainerStackPatchRequestData, + ContainerStackListItemData, + ContainerStackData, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { ContainerTemplate } from "./ContainerTemplate.js"; +import { Project } from "../../project/internal.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { ContainerListItem } from "./Container.js"; +import { VolumeListItem } from "../Volume/index.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "ContainerStack", +}) +export class ContainerStack extends ReferenceModel { + public static aggregateMetaData = new AggregateMetaData("container", "stack"); + + public constructor(id: string) { + super(id); + } + + public static async create( + project: Project, + data: ContainerStackCreateRequestData, + ) { + const response = await config.behaviors.container.createStack( + data, + project.id, + ); + + return new ContainerStackDetailed(response); + } + + public static async find(id: string, options?: AxiosRequestConfig) { + const data = await config.behaviors.container.findStack(id, options); + if (data) { + return new ContainerStackDetailed(data); + } + } + + public static findAggregate(stackId?: string) { + return stackId + ? { id: stackId, ...ContainerStack.aggregateMetaData } + : undefined; + } + + public static async get(id: string, options?: AxiosRequestConfig) { + const stack = await ContainerStack.find(id, options); + assertObjectFound(stack, ContainerStack, id); + return stack; + } + + public static ofId(id: string) { + return new ContainerStack(id); + } + + public static query(query: ContainerStackListQueryModelData = {}) { + return new ContainerStackListQuery(query); + } + + public async addTemplateComponent( + templateId: string, + userInputs?: ContainerTemplateUserInputValues, + ) { + await config.behaviors.container.addTemplateComponent(this.id, { + templateConfig: { templateId, userInputs }, + }); + } + + public async clearUpdateSchedule() { + await config.behaviors.container.updateStackUpdateSchedule(this.id, null); + } + + public async delete() { + return await config.behaviors.container.deleteStack(this.id); + } + + public async findCommon(): Promise { + return this instanceof ContainerStackCommon ? this : this.findDetailed(); + } + + public async findDetailed(): Promise { + return ContainerStack.find(this.id); + } + + public async getCommon(): Promise { + return this instanceof ContainerStackCommon ? this : this.getDetailed(); + } + + public getDetailed( + options?: AxiosRequestConfig, + ): Promise { + return ContainerStack.get(this.id, options); + } + + public async setUpdateSchedule(data: ContainerStackUpdateScheduleData) { + const payload: ContainerStackUpdateScheduleData = { + timezone: data.timezone, + cron: data.cron, + }; + await config.behaviors.container.updateStackUpdateSchedule( + this.id, + payload, + ); + } +} + +export class ContainerStackCommon extends WithData< + ContainerStackListItemData | ContainerStackData +>()(ContainerStack) { + public readonly containers: ContainerListItem[]; + public override readonly data: + ContainerStackListItemData | ContainerStackData; + public readonly description: string; + public readonly disabled: boolean; + public readonly isDefaultStack: boolean; + public readonly project: Project; + public readonly shortId: string; + public readonly template?: ContainerTemplate; + public readonly updateSchedule?: ContainerStackUpdateScheduleData; + public readonly volumes: VolumeListItem[]; + + public constructor(data: ContainerStackListItemData | ContainerStackData) { + super(data.id); + this.data = data; + this.description = data.description; + this.isDefaultStack = data.description === "default"; + this.shortId = data.prefix; + this.disabled = data.disabled; + this.project = Project.ofId(data.projectId); + this.containers = data.services?.map((s) => new ContainerListItem(s)) ?? []; + this.volumes = data.volumes?.map((v) => new VolumeListItem(v)) ?? []; + this.template = data.templateId + ? new ContainerTemplate(data.templateId) + : undefined; + this.updateSchedule = data.updateSchedule ?? undefined; + } + + public async declare( + data: ContainerStackDeclareRequestData, + ): Promise { + const response = await config.behaviors.container.declareStack( + this.id, + data, + ); + + return response ? new ContainerStackDetailed(response) : undefined; + } + + public async update( + data: ContainerStackPatchRequestData, + ): Promise { + const response = await config.behaviors.container.updateStack( + this.id, + data, + ); + + return response ? new ContainerStackDetailed(response) : undefined; + } + + public async updateDescription(description: string): Promise { + return await config.behaviors.container.updateStackDescription( + this.id, + description, + ); + } +} + +export class ContainerStackDetailed extends ContainerStackCommon { + public override readonly data: ContainerStackData; + public readonly project: Project; + + public constructor(data: ContainerStackData) { + super(data); + this.data = data; + this.project = Project.ofId(data.projectId); + } +} + +export class ContainerStackListItem extends ContainerStackCommon { + public override readonly data: ContainerStackListItemData; + public constructor(data: ContainerStackListItemData) { + super(data); + this.data = data; + } +} + +export class ContainerStackListQuery extends ListQueryModel { + public constructor(query: ContainerStackListQueryModelData = {}) { + const projectId = extractId(query.project); + super(query, projectId ? { dependencies: [projectId] } : undefined); + } + + public async execute() { + const projectId = extractId(this.query.project); + const { totalCount, items } = projectId + ? await config.behaviors.container.listStacksOfProject( + projectId, + omit(this.query, ["project"]), + ) + : await config.behaviors.container.listStacks( + omit(this.query, ["project"]), + ); + + return new ContainerStackList( + this.query, + items.map((c) => new ContainerStackListItem(c)), + totalCount, + ); + } + + public async getTotalCount() { + const { totalCount } = await this.refine({ limit: 1 }).execute(); + return totalCount; + } + + public refine(query: Partial = {}) { + return new ContainerStackListQuery({ + ...this.query, + ...query, + }); + } +} + +export class ContainerStackList extends WithListData()( + ContainerStackListQuery, +) { + public override readonly items: readonly ContainerStackListItem[]; + public override readonly totalCount: number; + public constructor( + query: ContainerStackListQueryModelData, + containers: ContainerStackListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(containers); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/container/Container/ContainerState.ts b/packages/models/src/container/Container/ContainerState.ts new file mode 100644 index 00000000..872d44e6 --- /dev/null +++ b/packages/models/src/container/Container/ContainerState.ts @@ -0,0 +1,34 @@ +import type { ContainerStateData } from "./types.js"; + +import { + ContainerVolumeRelationList, + ContainerEnvVariableList, +} from "./index.js"; +import { ContainerPortList } from "./ContainerPort.js"; +import { shellJoin } from "../lib/shellwords.js"; +import { DataModel } from "../../base/index.js"; + +export class ContainerState extends DataModel { + public readonly command?: string; + public readonly entrypoint?: string; + public readonly envs: ContainerEnvVariableList; + public readonly imageDigest?: string; + public readonly imageReference: string; + public readonly ports: ContainerPortList; + public readonly shortDigest?: string; + public readonly volumes: ContainerVolumeRelationList; + + public constructor(data: ContainerStateData) { + super(data); + this.imageReference = data.image.trim(); + this.imageDigest = data.imageDigest + ? data.imageDigest.split(":")[1] + : undefined; + this.shortDigest = this.imageDigest?.substring(0, 12); + this.envs = new ContainerEnvVariableList(data.envs ?? {}); + this.volumes = new ContainerVolumeRelationList(data.volumes ?? []); + this.ports = new ContainerPortList(data.ports ?? []); + this.entrypoint = shellJoin(data.entrypoint ?? []); + this.command = shellJoin(data.command ?? []); + } +} diff --git a/packages/models/src/container/Container/ContainerTemplate.ts b/packages/models/src/container/Container/ContainerTemplate.ts new file mode 100644 index 00000000..28d0d2c6 --- /dev/null +++ b/packages/models/src/container/Container/ContainerTemplate.ts @@ -0,0 +1,296 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; + +import type { ContainerListItem } from "./Container.js"; +import type { Project } from "../../project/index.js"; +import type { + ContainerTemplateTechnicalDetailData, + ContainerTemplateUserInputValues, + ContainerTemplateUserInputsData, + ContainerTemplateListQueryData, + ContainerTemplateListItemData, + ContainerTemplateAlertStatus, + ContainerTemplateLicenseData, + ContainerTemplateDomainData, + ContainerTemplateCategory, + ContainerTemplateApiData, + ContainerTemplateType, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { maskSensitiveEnvValue } from "../lib/sensitiveEnvKeys.js"; +import { containerTemplateAlertStatuses } from "./types.js"; +import { ContainerStack } from "./ContainerStack.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { config } from "../../config/index.js"; +import { + sortByPositionMeta, + ListQueryModel, + ReferenceModel, + WithListData, + WithData, +} from "../../base/index.js"; + +export function localizeTemplateText( + value: Record<"de" | "en", string>, +): string { + return value[config.locale()] ?? value.de; +} + +// API-DRIFT: help.alerts[].status is a plain string in the spec, although templates only use a closed set of statuses; values outside containerTemplateAlertStatuses fall back to "info" (resolve: derive ContainerTemplateAlertStatus from the generated type once the spec declares the enum) +const toAlertStatus = (status: string): ContainerTemplateAlertStatus => + containerTemplateAlertStatuses.find((known) => known === status) ?? "info"; + +const hostnamePattern = /\$\{([^.]+)\.hostname\}/g; +const envPattern = /\$\{([^.]+)\.env\.(\w+)\}/g; +const domainPattern = /\$\{domain\.(\w+)\}/g; +const unresolvedPlaceholderPattern = /\$\{[^}]+\}/; + +const resolveTechnicalDetailValue = ( + value: string, + containers: ContainerListItem[], + domains: Record, + mask: boolean, +): string => + value + .replace(hostnamePattern, (match, serviceName) => { + const container = containers.find((c) => c.serviceName === serviceName); + return container ? container.serviceName : match; + }) + .replace(envPattern, (match, serviceName, envKey) => { + const container = containers.find((c) => c.serviceName === serviceName); + const envValue = container?.pendingState.envs.data[envKey]; + if (envValue === undefined) return match; + return mask ? maskSensitiveEnvValue(envKey, envValue) : envValue; + }) + .replace(domainPattern, (match, purpose) => domains[purpose] ?? match); + +@GhostMakerModel({ + name: "ContainerTemplate", +}) +export class ContainerTemplate extends ReferenceModel { + public static aggregateMetaData = new AggregateMetaData( + "container", + "template", + ); + + public constructor(id: string) { + super(id); + } + + public static async find(id: string) { + const data = await config.behaviors.container.findTemplate(id); + if (data) { + return new ContainerTemplateDetailed(data); + } + } + + public static findAggregate(templateId?: string) { + return templateId + ? { id: templateId, ...ContainerTemplate.aggregateMetaData } + : undefined; + } + + public static async get(id: string) { + const template = await ContainerTemplate.find(id); + assertObjectFound(template, ContainerTemplate, id); + return template; + } + + public static ofId(id: string) { + return new ContainerTemplate(id); + } + + public static query(query: ContainerTemplateListQueryData = {}) { + return new ContainerTemplateListQuery(query); + } + + public async findCommon(): Promise { + return this instanceof ContainerTemplateCommon ? this : this.findDetailed(); + } + + public async findDetailed(): Promise { + return ContainerTemplate.find(this.id); + } + + public async getCommon(): Promise { + return this instanceof ContainerTemplateCommon ? this : this.getDetailed(); + } + + public getDetailed(): Promise { + return ContainerTemplate.get(this.id); + } +} + +export class ContainerTemplateCommon extends WithData< + ContainerTemplateListItemData | ContainerTemplateApiData +>()(ContainerTemplate) { + public readonly categories: ContainerTemplateCategory[]; + public override readonly data: + ContainerTemplateListItemData | ContainerTemplateApiData; + public readonly developer: string; + public readonly domains: ContainerTemplateDomainData; + public readonly icon: string; + public readonly license?: ContainerTemplateLicenseData; + public readonly manifestVersion: string; + public readonly repository?: string; + public readonly support?: string; + public readonly technicalDetails: ContainerTemplateTechnicalDetailData; + public readonly type: ContainerTemplateType; + public readonly userInputs: ContainerTemplateUserInputsData; + public readonly version: string; + public readonly website?: string; + + get alerts() { + return (this.data.help?.alerts ?? []).map((alert) => ({ + linkText: alert.linkText + ? localizeTemplateText(alert.linkText) + : undefined, + link: alert.link ? localizeTemplateText(alert.link) : undefined, + status: toAlertStatus(alert.status), + heading: localizeTemplateText(alert.heading), + content: localizeTemplateText(alert.content), + })); + } + + get description(): string { + return localizeTemplateText(this.data.description); + } + + get name(): string { + return localizeTemplateText(this.data.name); + } + + get screenshots() { + return (this.data.screenshots ?? []).map((screenshot) => ({ + text: localizeTemplateText(screenshot.text), + screenshot: screenshot.screenshot, + background: screenshot.bg, + })); + } + + get tagline(): string { + return localizeTemplateText(this.data.tagline); + } + + public constructor( + data: ContainerTemplateListItemData | ContainerTemplateApiData, + ) { + super(data.id); + this.data = data; + this.categories = data.categories as ContainerTemplateCategory[]; + this.developer = data.developer; + this.domains = data.domains; + this.icon = data.iconUrl; + this.license = data.license; + this.manifestVersion = data.manifestVersion; + this.repository = data.repository; + this.userInputs = data.userInputs + ? sortByPositionMeta(data.userInputs) + : undefined; + this.version = data.version; + this.website = data.website; + this.support = data.supportLink; + this.technicalDetails = data.help?.technicalDetails; + this.type = data.type; + } + + public async createStack( + project: Project, + data: { + userInputs?: ContainerTemplateUserInputValues; + description: string; + }, + ) { + return ContainerStack.create(project, { + templateConfig: { userInputs: data.userInputs, templateId: this.id }, + description: data.description, + }); + } + + public resolveTechnicalDetails( + containers: ContainerListItem[], + domains: Record = {}, + ) { + return (this.technicalDetails ?? []) + .map((detail) => ({ + displayValue: resolveTechnicalDetailValue( + detail.value, + containers, + domains, + true, + ), + copyValue: resolveTechnicalDetailValue( + detail.value, + containers, + domains, + false, + ), + label: localizeTemplateText(detail.key), + })) + .filter(({ copyValue }) => !unresolvedPlaceholderPattern.test(copyValue)); + } +} + +export class ContainerTemplateDetailed extends ContainerTemplateCommon { + public override readonly data: ContainerTemplateApiData; + + public constructor(data: ContainerTemplateApiData) { + super(data); + this.data = data; + } +} + +export class ContainerTemplateListItem extends ContainerTemplateCommon { + public override readonly data: ContainerTemplateListItemData; + + public constructor(data: ContainerTemplateListItemData) { + super(data); + this.data = data; + } +} + +export class ContainerTemplateListQuery extends ListQueryModel { + public constructor(query: ContainerTemplateListQueryData = {}) { + super(query); + } + + public async execute() { + const { totalCount, items } = + await config.behaviors.container.listTemplates(this.query); + + return new ContainerTemplateList( + this.query, + items.map((c) => new ContainerTemplateListItem(c)), + totalCount, + ); + } + + public async getTotalCount() { + const { totalCount } = await this.refine({ limit: 1 }).execute(); + return totalCount; + } + + public refine(query: Partial = {}) { + return new ContainerTemplateListQuery({ + ...this.query, + ...query, + }); + } +} + +export class ContainerTemplateList extends WithListData()( + ContainerTemplateListQuery, +) { + public override readonly items: readonly ContainerTemplateListItem[]; + public override readonly totalCount: number; + + public constructor( + query: ContainerTemplateListQueryData, + containers: ContainerTemplateListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(containers); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/container/Container/ContainerUserInput.ts b/packages/models/src/container/Container/ContainerUserInput.ts new file mode 100644 index 00000000..4d33af25 --- /dev/null +++ b/packages/models/src/container/Container/ContainerUserInput.ts @@ -0,0 +1,32 @@ +import type { Schema } from "jsonschema"; + +import type { ContainerUserInputData } from "./types.js"; + +import { DataModel } from "../../base/index.js"; + +export class ContainerUserInput extends DataModel { + public readonly dataSource?: string; + public readonly defaultValue?: string; + public readonly label?: Record<"de" | "en", string>; + public readonly name: string; + public readonly required: boolean; + public readonly schema: Schema; + public readonly step: string; + public readonly validationSchema: string; + + public get format(): string | undefined { + return this.schema.format; + } + + public constructor(data: ContainerUserInputData, schema: Schema) { + super(data); + this.name = data.name; + this.required = data.required; + this.defaultValue = data.defaultValue; + this.dataSource = data.dataSource; + this.validationSchema = data.validationSchema ?? "{}"; + this.schema = schema; + this.label = data.label; + this.step = data.positionMeta?.step ?? "common"; + } +} diff --git a/packages/models/src/container/Container/ContainerVolumeRelation.ts b/packages/models/src/container/Container/ContainerVolumeRelation.ts new file mode 100644 index 00000000..17beda2a --- /dev/null +++ b/packages/models/src/container/Container/ContainerVolumeRelation.ts @@ -0,0 +1,74 @@ +import type { + ContainerVolumeRelationFormValues, + ContainerVolumeRelationData, + ImageMetaVolumeData, +} from "./types.js"; + +import { ListDataModel, DataModel } from "../../base/index.js"; + +export class ContainerVolumeRelation extends DataModel { + public readonly combinedName?: string; + public readonly containerPath?: string; + public readonly projectPath?: string; + public readonly type?: "directory" | "volume"; + public readonly volume?: string; + public readonly volumeCreationRequired: boolean; + + public constructor(data: ContainerVolumeRelationData) { + super(data); + const [prefix, suffix] = data.split(":"); + const type = + prefix && prefix.startsWith("/") && suffix ? "directory" : "volume"; + this.type = type; + this.volume = + type === "volume" && suffix?.trim() ? prefix?.trim() : undefined; + this.projectPath = + type === "directory" && suffix?.trim() ? prefix?.trim() : "/"; + this.containerPath = suffix?.trim() ?? prefix?.trim(); + this.combinedName = + this.type === "directory" + ? `${this.projectPath}-${this.containerPath}` + : `${this.volume}-${this.containerPath}`; + this.volumeCreationRequired = + this.volume === "createNewVolume" && this.type === "volume"; + } + + public static fromFormValues( + values: ContainerVolumeRelationFormValues, + ): ContainerVolumeRelation { + return new ContainerVolumeRelation( + values.type === "volume" + ? `${values.volume.trim()}:${values.containerPath.trim()}` + : `${values.projectPath.trim()}:${values.containerPath.trim()}`, + ); + } +} + +export class ContainerVolumeRelationList extends ListDataModel { + public constructor(relations: ContainerVolumeRelationData[]) { + super( + relations.map((r) => new ContainerVolumeRelation(r)), + relations.length, + ); + } + + public static fromImageMeta( + meta: ImageMetaVolumeData[], + ): ContainerVolumeRelationList { + return ContainerVolumeRelationList.fromRelations( + meta.map( + (m) => new ContainerVolumeRelation(`createNewVolume:${m.volume}`), + ), + ); + } + + public static fromRelations( + relations: ContainerVolumeRelation[], + ): ContainerVolumeRelationList { + return new ContainerVolumeRelationList(relations.map((r) => r.data)); + } + + public toStringArray(): string[] { + return this.items.map((v) => v.data); + } +} diff --git a/packages/models/src/container/Container/DockerCompose.ts b/packages/models/src/container/Container/DockerCompose.ts new file mode 100644 index 00000000..ee157e67 --- /dev/null +++ b/packages/models/src/container/Container/DockerCompose.ts @@ -0,0 +1,597 @@ +import type { ErrorCode as YamlErrorCode } from "yaml"; +import type { z } from "zod"; + +import { YAMLParseError, stringify, parse } from "yaml"; + +import type { ContainerStackCommon } from "./ContainerStack.js"; +import type { ContainerListItem } from "./Container.js"; +import type { VolumeListItem } from "../Volume/index.js"; +import type { + DockerComposeServiceData, + DockerComposeData, +} from "./DockerComposeSchema.js"; +import type { + ContainerStackDeclareRequestData, + ContainerDeclareServiceData, +} from "./types.js"; + +import { + containerServiceNameMaxLength, + containerMaxTextLength, +} from "./types.js"; +import { ContainerVolumeRelation } from "./ContainerVolumeRelation.js"; +import { ContainerEnvVariableList } from "./ContainerEnvVariable.js"; +import { shellSplit } from "../lib/shellwords.js"; +import { Container } from "./Container.js"; +import { + containerCommandMaxLength, + dockerComposeSchema, +} from "./DockerComposeSchema.js"; + +const getServiceVolumes = (container: ContainerListItem): string[] => + container.pendingState.volumes.items + .filter((relation) => relation.containerPath) + .map((relation) => relation.data); + +const getServiceEnvironment = ( + container: ContainerListItem, +): Record | undefined => { + const envs = container.pendingState.envs; + + return envs.items.length > 0 ? envs.toApiDataObject() : undefined; +}; + +const getServiceDeploy = (container: ContainerListItem) => { + if (!container.cpuLimit && !container.ramLimit) { + return undefined; + } + + return { + resources: { + limits: { + ...(container.cpuLimit ? { cpus: container.cpuLimit } : {}), + ...(container.ramLimit ? { memory: container.ramLimit } : {}), + }, + }, + }; +}; + +const getService = (container: ContainerListItem) => { + const ports = container.pendingState.ports.items.map((port) => + port.toString(), + ); + const volumes = getServiceVolumes(container); + const environment = getServiceEnvironment(container); + const deploy = getServiceDeploy(container); + + return { + image: container.pendingState.imageReference, + ...(container.pendingState.command + ? { command: container.pendingState.command } + : {}), + ...(container.pendingState.entrypoint + ? { entrypoint: container.pendingState.entrypoint } + : {}), + ...(environment ? { environment } : {}), + ...(ports.length > 0 ? { ports } : {}), + ...(volumes.length > 0 ? { volumes } : {}), + ...(deploy ? { deploy } : {}), + }; +}; + +const getVolumes = ( + volumes: VolumeListItem[], +): Record> | undefined => + volumes.length > 0 + ? Object.fromEntries(volumes.map((volume) => [volume.name, {}])) + : undefined; + +export interface DockerComposeValidationIssue { + params?: Record; + key: string; +} + +export class DockerComposeValidationError extends Error { + public readonly issues: readonly DockerComposeValidationIssue[]; + + public constructor(issues: readonly DockerComposeValidationIssue[]) { + super( + `Invalid docker-compose YAML: ${issues.map((issue) => issue.key).join(", ")}`, + ); + this.issues = issues; + } +} + +/** + * Unwraps an `invalid_union` issue to whichever branch isn't a generic type + * mismatch. + */ +const resolveUnionIssue = (issue: z.core.$ZodIssue): z.core.$ZodIssue => { + if (issue.code !== "invalid_union") { + return issue; + } + + const candidates = issue.errors.flat(); + const specific = + candidates.find((nested) => nested.code !== "invalid_type") ?? + candidates[0]; + + return specific + ? { ...specific, path: [...issue.path, ...specific.path] } + : issue; +}; + +/** + * Maps `yaml`'s error codes to German messages — its own `error.message` is + * English-only. + */ +const YAML_SYNTAX_ERROR_KEYS: Partial> = { + UNEXPECTED_TOKEN: "dockerComposeEditor.yaml.syntaxError.unexpectedToken", + BAD_SCALAR_START: "dockerComposeEditor.yaml.syntaxError.badScalarStart", + DUPLICATE_KEY: "dockerComposeEditor.yaml.syntaxError.duplicateKey", + MULTIPLE_DOCS: "dockerComposeEditor.yaml.syntaxError.multipleDocs", + TAB_AS_INDENT: "dockerComposeEditor.yaml.syntaxError.tabAsIndent", + BAD_DQ_ESCAPE: "dockerComposeEditor.yaml.syntaxError.badDqEscape", + MISSING_CHAR: "dockerComposeEditor.yaml.syntaxError.missingChar", + BAD_INDENT: "dockerComposeEditor.yaml.syntaxError.badIndent", +}; + +const formatYamlParseError = ( + error: YAMLParseError, +): DockerComposeValidationIssue => { + const [start] = error.linePos ?? []; + + return { + key: + YAML_SYNTAX_ERROR_KEYS[error.code] ?? + "dockerComposeEditor.yaml.syntaxErrorGeneric", + params: { + column: start?.col ?? 1, + line: start?.line ?? 1, + code: error.code, + }, + }; +}; + +const serviceNameFromPath = (issue: z.core.$ZodIssue): unknown => issue.path[1]; + +/** Maps each segment's issue reason to a message, per segment. */ +const SEGMENT_ISSUE_RULES: Record< + string, + { + byReason: Record< + string, + (issue: z.core.$ZodIssueCustom) => DockerComposeValidationIssue + >; + customFallback: ( + issue: z.core.$ZodIssueCustom, + ) => DockerComposeValidationIssue; + nonCustomFallback: ( + issue: z.core.$ZodIssue, + ) => DockerComposeValidationIssue; + } +> = { + environment: { + byReason: { + duplicateEnvKey: (issue) => ({ + params: { + service: serviceNameFromPath(issue), + key: issue.params?.envKey, + }, + key: "dockerComposeEditor.yaml.duplicateEnvKey", + }), + invalidEnvValue: (issue) => ({ + params: { + service: serviceNameFromPath(issue), + key: issue.params?.envKey, + }, + key: "dockerComposeEditor.yaml.invalidEnvValue", + }), + invalidEnvKey: (issue) => ({ + params: { service: serviceNameFromPath(issue) }, + key: "dockerComposeEditor.yaml.invalidEnvKey", + }), + }, + customFallback: (issue) => ({ + params: { + service: serviceNameFromPath(issue), + key: issue.params?.envKey, + }, + key: "dockerComposeEditor.yaml.invalidEnvValue", + }), + nonCustomFallback: (issue) => ({ + params: { service: serviceNameFromPath(issue), key: undefined }, + key: "dockerComposeEditor.yaml.invalidEnvValue", + }), + }, + volumes: { + byReason: { + relativeBindMount: (issue) => ({ + key: "dockerComposeEditor.yaml.relativeBindMountNotSupported", + params: { service: serviceNameFromPath(issue) }, + }), + unsupportedMountMode: (issue) => ({ + key: "dockerComposeEditor.yaml.volumeModeNotSupported", + params: { service: serviceNameFromPath(issue) }, + }), + duplicateVolumePath: (issue) => ({ + key: "dockerComposeEditor.yaml.duplicateVolumePath", + params: { service: serviceNameFromPath(issue) }, + }), + }, + customFallback: (issue) => ({ + key: "dockerComposeEditor.yaml.invalidVolumeMountPath", + params: { service: serviceNameFromPath(issue) }, + }), + nonCustomFallback: (issue) => ({ + params: { service: serviceNameFromPath(issue) }, + key: "dockerComposeEditor.yaml.emptyVolume", + }), + }, + ports: { + byReason: { + mappingNotSupported: (issue) => ({ + key: "dockerComposeEditor.yaml.portMappingNotSupported", + params: { service: serviceNameFromPath(issue) }, + }), + duplicatePort: (issue) => ({ + params: { service: serviceNameFromPath(issue) }, + key: "dockerComposeEditor.yaml.duplicatePort", + }), + invalidFormat: (issue) => ({ + params: { service: serviceNameFromPath(issue) }, + key: "dockerComposeEditor.yaml.invalidPort", + }), + }, + customFallback: (issue) => ({ + key: "dockerComposeEditor.yaml.portMappingNotSupported", + params: { service: serviceNameFromPath(issue) }, + }), + nonCustomFallback: (issue) => ({ + params: { service: serviceNameFromPath(issue) }, + key: "dockerComposeEditor.yaml.emptyPort", + }), + }, +}; + +const resolveSegmentIssue = ( + segment: unknown, + issue: z.core.$ZodIssue, +): DockerComposeValidationIssue | undefined => { + const rules = + typeof segment === "string" ? SEGMENT_ISSUE_RULES[segment] : undefined; + if (!rules) { + return undefined; + } + + if (issue.code !== "custom") { + return rules.nonCustomFallback(issue); + } + + const reason = + typeof issue.params?.reason === "string" ? issue.params.reason : undefined; + const rule = reason ? rules.byReason[reason] : undefined; + + return rule ? rule(issue) : rules.customFallback(issue); +}; + +const formatDockerComposeIssue = ( + rawIssue: z.core.$ZodIssue, +): DockerComposeValidationIssue => { + const issue = resolveUnionIssue(rawIssue); + const path = issue.path.join("."); + const parentSegment = issue.path[issue.path.length - 2]; + + if (issue.code === "unrecognized_keys") { + const field = issue.keys[0] ?? ""; + + return path + ? { + key: "dockerComposeEditor.yaml.unsupportedField", + params: { field, path }, + } + : { + key: "dockerComposeEditor.yaml.unsupportedTopLevelField", + params: { field }, + }; + } + + if (issue.path.length === 0) { + return { key: "dockerComposeEditor.yaml.emptyDocument" }; + } + + if (path === "services") { + return { key: "dockerComposeEditor.yaml.missingServices" }; + } + + if (issue.code === "invalid_key" && parentSegment === "environment") { + return { + key: "dockerComposeEditor.yaml.invalidEnvKey", + params: { service: issue.path[1] }, + }; + } + + if (issue.code === "invalid_key") { + const isServiceKey = issue.path[0] === "services"; + const name = issue.path[1]; + const codes = issue.issues.map((nested) => nested.code); + + if (codes.includes("too_small")) { + return { + key: isServiceKey + ? "dockerComposeEditor.yaml.emptyServiceName" + : "dockerComposeEditor.yaml.emptyVolumeName", + }; + } + + if (codes.includes("too_big")) { + return { + params: { + maxLength: isServiceKey + ? containerServiceNameMaxLength + : containerMaxTextLength, + name, + }, + key: isServiceKey + ? "dockerComposeEditor.yaml.serviceNameTooLong" + : "dockerComposeEditor.yaml.volumeNameTooLong", + }; + } + + return { + key: isServiceKey + ? "dockerComposeEditor.yaml.invalidServiceName" + : "dockerComposeEditor.yaml.invalidVolumeName", + params: { name }, + }; + } + + if (path.endsWith(".image")) { + return { + key: "dockerComposeEditor.yaml.imageRequired", + params: { service: issue.path[1] }, + }; + } + + if (path.endsWith(".command") || path.endsWith(".entrypoint")) { + const field = path.endsWith(".command") ? "command" : "entrypoint"; + const isTooLong = + issue.code === "custom" && issue.params?.reason === "tooLong"; + + return { + key: isTooLong + ? `dockerComposeEditor.yaml.${field}TooLong` + : `dockerComposeEditor.yaml.${field}Required`, + params: { + service: issue.path[1], + ...(isTooLong ? { maxLength: containerCommandMaxLength } : {}), + }, + }; + } + + if (parentSegment === "limits" && issue.code === "custom") { + return { + key: + issue.params?.reason === "invalidCpuLimit" + ? "dockerComposeEditor.yaml.invalidCpuLimit" + : "dockerComposeEditor.yaml.invalidMemoryLimit", + params: { service: issue.path[1] }, + }; + } + + const segmentIssue = resolveSegmentIssue(parentSegment, issue); + if (segmentIssue) { + return segmentIssue; + } + + return { key: "dockerComposeEditor.yaml.fieldInvalid", params: { path } }; +}; + +const toArgArray = (value: string[] | string): string[] => + Array.isArray(value) ? value : shellSplit(value); + +const toEnvironmentRecord = ( + environment: DockerComposeServiceData["environment"], +): Record | undefined => { + if (!environment) { + return undefined; + } + + if (Array.isArray(environment)) { + return ContainerEnvVariableList.fromText( + environment.join("\n"), + ).toApiDataObject(); + } + + return Object.fromEntries( + Object.entries(environment).map(([key, value]) => [key, String(value)]), + ); +}; + +const buildServiceDeclaration = ( + service: DockerComposeServiceData, + description: string, +): ContainerDeclareServiceData => { + const environment = toEnvironmentRecord(service.environment); + + return { + image: service.image, + description, + ...(service.command ? { command: toArgArray(service.command) } : {}), + ...(service.entrypoint + ? { entrypoint: toArgArray(service.entrypoint) } + : {}), + ...(environment ? { environment } : {}), + ...(service.ports ? { ports: service.ports } : {}), + ...(service.volumes ? { volumes: service.volumes } : {}), + ...(service.deploy ? { deploy: service.deploy } : {}), + }; +}; + +export interface ExistingContainerInfo { + serviceName: string; + description: string; + image: string; +} + +export class DockerCompose { + private constructor(private readonly data: DockerComposeData) {} + + public static fromStack( + stack: Pick, + ): DockerCompose { + const services = Object.fromEntries( + stack.containers.map((container) => [ + container.serviceName, + getService(container), + ]), + ); + const volumes = getVolumes(stack.volumes); + + return new DockerCompose({ + services, + ...(volumes ? { volumes } : {}), + }); + } + + /** + * @throws {DockerComposeValidationError} If `yamlText` is not valid YAML, or + * not compatible with the supported docker-compose subset. + */ + public static parse(yamlText: string): DockerCompose { + let parsed: unknown; + + try { + parsed = parse(yamlText, { merge: true }); + } catch (error) { + throw new DockerComposeValidationError([ + error instanceof YAMLParseError + ? formatYamlParseError(error) + : { + params: { + message: error instanceof Error ? error.message : String(error), + }, + key: "dockerComposeEditor.yaml.invalidSyntax", + }, + ]); + } + + const result = dockerComposeSchema.safeParse(parsed); + if (result.success) { + return new DockerCompose(result.data); + } + + throw new DockerComposeValidationError( + result.error.issues.length > 0 + ? result.error.issues.map(formatDockerComposeIssue) + : [ + { + key: "dockerComposeEditor.yaml.fieldInvalid", + params: { path: "" }, + }, + ], + ); + } + + /** + * Validates each changed service's image, like `ImageReferenceField`; stops + * at the first invalid one. + */ + public async findInvalidImage( + existingContainers: readonly ExistingContainerInfo[], + projectId: string, + language?: string, + ): Promise<{ service: string; reason: string } | undefined> { + const imageByServiceName = new Map( + existingContainers.map((container) => [ + container.serviceName, + container.image, + ]), + ); + + for (const [serviceName, service] of Object.entries(this.data.services)) { + if (imageByServiceName.get(serviceName) === service.image) { + continue; + } + + const imageMeta = await Container.getImageMeta( + service.image, + projectId, + undefined, + language, + ); + + if (typeof imageMeta === "string") { + return { service: serviceName, reason: imageMeta }; + } + } + + return undefined; + } + + public getUndeclaredVolumeReferences( + existingVolumeNames: readonly string[], + ): string[] { + const declaredVolumeNames = new Set([ + ...Object.keys(this.data.volumes ?? {}), + ...existingVolumeNames, + ]); + + const referencedVolumeNames = new Set( + Object.values(this.data.services) + .flatMap((service) => service.volumes ?? []) + .map((mount) => new ContainerVolumeRelation(mount)) + .filter((relation) => relation.type === "volume") + .map((relation) => relation.volume) + .filter((name): name is string => !!name), + ); + + return [...referencedVolumeNames].filter( + (name) => !declaredVolumeNames.has(name), + ); + } + + /** + * Maps to the stack's declarative PUT payload — an omitted service is + * deleted, an omitted volume is detached. Descriptions are carried over from + * `existingContainers` since compose has no such field. + */ + public toStackDeclareRequest( + existingContainers: readonly Pick< + ExistingContainerInfo, + "serviceName" | "description" + >[], + ): ContainerStackDeclareRequestData { + const descriptionByServiceName = new Map( + existingContainers.map((container) => [ + container.serviceName, + container.description, + ]), + ); + + const services = Object.fromEntries( + Object.entries(this.data.services).map(([key, service]) => [ + key, + buildServiceDeclaration( + service, + descriptionByServiceName.get(key) ?? key, + ), + ]), + ); + + const volumes = this.data.volumes + ? Object.fromEntries( + Object.keys(this.data.volumes).map((key) => [key, { name: key }]), + ) + : undefined; + + return { + services, + ...(volumes ? { volumes } : {}), + }; + } + + public toYaml(): string { + return stringify(this.data); + } +} diff --git a/packages/models/src/container/Container/DockerComposeSchema.ts b/packages/models/src/container/Container/DockerComposeSchema.ts new file mode 100644 index 00000000..d1b5702d --- /dev/null +++ b/packages/models/src/container/Container/DockerComposeSchema.ts @@ -0,0 +1,356 @@ +import { z } from "zod"; + +import { ContainerVolumeRelation } from "./ContainerVolumeRelation.js"; +import { parseRamLimitToGb, parseCpuLimit } from "./resourceLimits.js"; +import { ContainerPort } from "./ContainerPort.js"; +import { volumeNameRegExp } from "../Volume/index.js"; +import { + containerServiceNameMaxLength, + containerServiceNameRegex, + containerFilePathRegex, + containerMaxTextLength, + containerEnvKeyRegex, + containerPortRegExp, +} from "./types.js"; + +export const containerCommandMaxLength = 8000; + +const commandLength = (value: string[] | string): number => + Array.isArray(value) ? value.join(" ").length : value.length; + +/** Omitting the field means "use the image's default"; an empty value doesn't. */ +const dockerComposeCommandSchema = z + .union([z.string(), z.array(z.string())]) + .superRefine((value, ctx) => { + const length = commandLength(value); + + if (length === 0) { + ctx.addIssue({ params: { reason: "required" }, code: "custom" }); + return; + } + + if (length > containerCommandMaxLength) { + ctx.addIssue({ params: { reason: "tooLong" }, code: "custom" }); + } + }); + +/** + * Format must pass first — `ContainerPort`'s constructor throws on a malformed + * value. + */ +const isValidPortFormat = (port: string): boolean => + containerPortRegExp.test(port) && ContainerPort.validatePort(port); + +const nonEmptyPortSchema = z.preprocess( + (value) => (typeof value === "number" ? String(value) : value), + z + .string() + .min(1) + .superRefine((port, ctx) => { + if (!isValidPortFormat(port)) { + ctx.addIssue({ params: { reason: "invalidFormat" }, code: "custom" }); + return; + } + if (!ContainerPort.hasEqualMapping(port)) { + ctx.addIssue({ + params: { reason: "mappingNotSupported" }, + code: "custom", + }); + } + }), +); + +/** Rejects duplicate ports, matching the manual "add port" form. */ +const dockerComposePortsSchema = z + .array(nonEmptyPortSchema) + .superRefine((ports, ctx) => { + const seen = new Set(); + + ports.forEach((port, index) => { + if (!isValidPortFormat(port)) { + return; + } + + const normalized = new ContainerPort(port).toString(); + if (seen.has(normalized)) { + ctx.addIssue({ + params: { reason: "duplicatePort" }, + code: "custom", + path: [index], + }); + return; + } + seen.add(normalized); + }); + }); + +/** Compose reserves `x-*` keys for user extensions — ignored, not errored on. */ +const stripExtensionFields = (value: unknown): unknown => + typeof value === "object" && value !== null && !Array.isArray(value) + ? Object.fromEntries( + Object.entries(value).filter(([key]) => !key.startsWith("x-")), + ) + : value; + +/** Valid but unused top-level fields — dropped like `x-*` extensions. */ +const TOP_LEVEL_IGNORED_KEYS = new Set(["version", "name"]); + +const stripIgnoredTopLevelFields = (value: unknown): unknown => { + const withoutExtensions = stripExtensionFields(value); + + return typeof withoutExtensions === "object" && + withoutExtensions !== null && + !Array.isArray(withoutExtensions) + ? Object.fromEntries( + Object.entries(withoutExtensions).filter( + ([key]) => !TOP_LEVEL_IGNORED_KEYS.has(key), + ), + ) + : withoutExtensions; +}; + +const isValidEnvKey = (key: string): boolean => + key.length > 0 && + key.length <= containerMaxTextLength && + containerEnvKeyRegex.test(key); + +const isValidEnvValue = (value: string): boolean => + value.trim().length > 0 && value.length <= containerMaxTextLength; + +/** + * List-form entries aren't keyed like the map form, so each is checked + * individually. + */ +const dockerComposeEnvListEntrySchema = z + .string() + .min(1) + .superRefine((entry, ctx) => { + const [key = "", value = ""] = entry.split(/=(.*)/s); + + if (!isValidEnvKey(key)) { + ctx.addIssue({ params: { reason: "invalidEnvKey" }, code: "custom" }); + return; + } + + if (!isValidEnvValue(value)) { + ctx.addIssue({ + params: { reason: "invalidEnvValue", envKey: key }, + code: "custom", + }); + } + }); + +const dockerComposeEnvListSchema = z + .array(dockerComposeEnvListEntrySchema) + .superRefine((entries, ctx) => { + const seenKeys = new Set(); + + entries.forEach((entry, index) => { + const [key = ""] = entry.split(/=(.*)/s); + + if (seenKeys.has(key)) { + ctx.addIssue({ + params: { reason: "duplicateEnvKey", envKey: key }, + code: "custom", + path: [index], + }); + } + seenKeys.add(key); + }); + }); + +const dockerComposeEnvMapSchema = z + .record( + z.string().min(1).max(containerMaxTextLength).regex(containerEnvKeyRegex), + z.union([z.string(), z.number(), z.boolean(), z.null()]), + ) + .superRefine((entries, ctx) => { + Object.entries(entries).forEach(([key, value]) => { + const stringValue = + typeof value === "string" ? value : String(value ?? ""); + + if ( + (typeof value === "string" || value === null) && + !isValidEnvValue(stringValue) + ) { + ctx.addIssue({ + params: { reason: "invalidEnvValue", envKey: key }, + code: "custom", + path: [key], + }); + } + }); + }); + +const dockerComposeEnvironmentSchema = z.union([ + dockerComposeEnvMapSchema, + dockerComposeEnvListSchema, +]); + +/** + * Only the container-facing half of `:` has a format to + * check. + */ +const isValidVolumeMount = (mount: string): boolean => { + const relation = new ContainerVolumeRelation(mount); + + if ( + !relation.containerPath || + relation.containerPath.length > containerMaxTextLength || + !containerFilePathRegex.test(relation.containerPath) + ) { + return false; + } + + return ( + relation.type !== "directory" || + (relation.projectPath?.length ?? 0) <= containerMaxTextLength + ); +}; + +const isRelativeBindMountSource = (source: string): boolean => + !source.startsWith("/") && + (source === "." || source === ".." || source.includes("/")); + +/** Rejects mount-mode suffixes like `:ro` — the API has no mode of its own. */ +const hasUnsupportedMountMode = (mount: string): boolean => + mount.split(":").length > 2; + +const dockerComposeVolumeMountSchema = z + .string() + .min(1) + .superRefine((mount, ctx) => { + const [source = ""] = mount.split(":"); + + if (isRelativeBindMountSource(source)) { + ctx.addIssue({ params: { reason: "relativeBindMount" }, code: "custom" }); + return; + } + + if (hasUnsupportedMountMode(mount)) { + ctx.addIssue({ + params: { reason: "unsupportedMountMode" }, + code: "custom", + }); + return; + } + + if (!isValidVolumeMount(mount)) { + ctx.addIssue({ code: "custom" }); + } + }); + +/** Rejects a second mount at the same container path, matching the manual modal. */ +const dockerComposeVolumesSchema = z + .array(dockerComposeVolumeMountSchema) + .superRefine((mounts, ctx) => { + const seenPaths = new Set(); + + mounts.forEach((mount, index) => { + const { containerPath } = new ContainerVolumeRelation(mount); + if (!containerPath) { + return; + } + + if (seenPaths.has(containerPath)) { + ctx.addIssue({ + params: { reason: "duplicateVolumePath" }, + code: "custom", + path: [index], + }); + return; + } + seenPaths.add(containerPath); + }); + }); + +/** Reuses the manual "Edit Resource Limits" modal's own parsers. */ +const dockerComposeDeployLimitsSchema = z + .object({ + memory: z.union([z.string(), z.number()]).transform(String).optional(), + cpus: z.union([z.string(), z.number()]).transform(String).optional(), + }) + .strict() + .superRefine((limits, ctx) => { + if (limits.cpus !== undefined && parseCpuLimit(limits.cpus) === undefined) { + ctx.addIssue({ + params: { reason: "invalidCpuLimit" }, + code: "custom", + path: ["cpus"], + }); + } + + if ( + limits.memory !== undefined && + parseRamLimitToGb(limits.memory) === undefined + ) { + ctx.addIssue({ + params: { reason: "invalidMemoryLimit" }, + path: ["memory"], + code: "custom", + }); + } + }); + +const dockerComposeDeploySchema = z + .object({ + resources: z + .object({ limits: dockerComposeDeployLimitsSchema.optional() }) + .strict() + .optional(), + }) + .strict(); + +const dockerComposeServiceObjectSchema = z + .object({ + environment: dockerComposeEnvironmentSchema.optional(), + entrypoint: dockerComposeCommandSchema.optional(), + command: dockerComposeCommandSchema.optional(), + volumes: dockerComposeVolumesSchema.optional(), + deploy: dockerComposeDeploySchema.optional(), + ports: dockerComposePortsSchema.optional(), + image: z.string().min(1), + }) + .strict(); + +const dockerComposeServiceSchema = z.preprocess( + stripExtensionFields, + dockerComposeServiceObjectSchema, +); + +const dockerComposeObjectSchema = z + .object({ + services: z.record( + z + .string() + .min(1) + .max(containerServiceNameMaxLength) + .regex(containerServiceNameRegex), + dockerComposeServiceSchema, + ), + volumes: z + .record( + z.string().min(1).max(containerMaxTextLength).regex(volumeNameRegExp), + z.unknown(), + ) + .optional(), + }) + .strict(); + +export const dockerComposeSchema = z.preprocess( + stripIgnoredTopLevelFields, + dockerComposeObjectSchema, +); + +export const supportedDockerComposeTopLevelFields = Object.keys( + dockerComposeObjectSchema.shape, +).sort(); + +export const supportedDockerComposeServiceFields = Object.keys( + dockerComposeServiceObjectSchema.shape, +).sort(); + +export type DockerComposeData = z.infer; +export type DockerComposeServiceData = z.infer< + typeof dockerComposeServiceSchema +>; diff --git a/packages/models/src/container/Container/ImageMeta.ts b/packages/models/src/container/Container/ImageMeta.ts new file mode 100644 index 00000000..300c779a --- /dev/null +++ b/packages/models/src/container/Container/ImageMeta.ts @@ -0,0 +1,30 @@ +import type { + ImageMetaVolumeData, + ImageMetaPortData, + ImageMetaEnvData, + ImageMetaData, +} from "./types.js"; + +import { shellJoin } from "../lib/shellwords.js"; +import { DataModel } from "../../base/index.js"; + +export class ImageMeta extends DataModel { + public readonly command?: string; + public readonly entrypoint?: string; + public readonly envs?: ImageMetaEnvData[]; + public readonly imageRef: string; + public readonly needsAiGeneration: boolean; + public readonly ports?: ImageMetaPortData[]; + public readonly volumes?: ImageMetaVolumeData[]; + + public constructor(data: ImageMetaData, imageRef: string) { + super(data); + this.imageRef = imageRef; + this.command = shellJoin(data.command ?? []); + this.entrypoint = shellJoin(data.entrypoint ?? []); + this.envs = data.env; + this.ports = data.exposedPorts; + this.volumes = data.volumes; + this.needsAiGeneration = data.isAiAvailable && !data.hasAiGeneratedData; + } +} diff --git a/packages/models/src/container/Container/behaviors/api.ts b/packages/models/src/container/Container/behaviors/api.ts new file mode 100644 index 00000000..8f539fa3 --- /dev/null +++ b/packages/models/src/container/Container/behaviors/api.ts @@ -0,0 +1,349 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; +import type { AxiosRequestConfig } from "axios"; + +import type { ContainerBehaviors } from "./types.js"; +import type { + ContainerStackUpdateSchedulePatchRequestData, + ContainerStackPatchRequestData, +} from "../types.js"; + +import { + withAxiosRequestConfig, + resolveTotalCount, + validateResponse, +} from "../../../base/index.js"; + +const resolveTemplateAssetUrls = < + T extends { + screenshots?: { screenshot: string; bg: string }[]; + iconUrl: string; + }, +>( + client: MittwaldAPIV2Client, + template: T, +): T => ({ + ...template, + screenshots: template.screenshots?.map((screenshot) => ({ + ...screenshot, + screenshot: client.axios.getUri({ url: screenshot.screenshot }), + bg: client.axios.getUri({ url: screenshot.bg }), + })), + iconUrl: client.axios.getUri({ url: template.iconUrl }), +}); + +export const apiContainerBehaviors = ( + client: MittwaldAPIV2Client, +): ContainerBehaviors => ({ + getImageMeta: async (imageRef, projectId, generateAiData, language) => { + const acceptLanguage = + language === "en" || language === "de" ? language : undefined; + + const response = await client.container.getContainerImageConfig({ + queryParameters: { + useCredentialsForProjectId: projectId, + imageReference: imageRef, + generateAiData, + }, + headers: acceptLanguage + ? { "Accept-Language": acceptLanguage } + : undefined, + }); + + if (response.status !== 200) { + if (response.status === 403) { + return "noImageAccess"; + } else if (response.status === 429) { + return "rateLimitReached"; + } else if (response.status >= 400 && response.status < 500) { + if (typeof response.data.message === "string") { + if (response.data.message.endsWith("'linux/amd64' platform")) { + return "invalidImageArchitecture"; + } + if (response.data.message.endsWith("is not reachable")) { + return "registryNotReachable"; + } + if (response.data.message.endsWith("does not host a registry")) { + return "noRegistryHosted"; + } + if ( + response.data.message.endsWith("unsupported with schema 1 manifest") + ) { + return "unsupportedManifest"; + } + if (response.data.message.endsWith("does not exist")) { + return "imageRefNotFound"; + } + } + } + + return "invalidImageRef"; + } + + validateResponse(response, 200); + return response.data; + }, + + getLogChunk: async (containerId, stackId, range, requestOptions) => { + const response = await client.container.getServiceLogs( + { + headers: { Range: range }, + serviceId: containerId, + stackId, + }, + withAxiosRequestConfig(requestOptions), + ); + + return { + contentRange: response.headers["content-range"] as string | undefined, + content: typeof response.data === "string" ? response.data : "", + status: response.status, + }; + }, + + list: async (projectId, queryParameters, options?: AxiosRequestConfig) => { + const response = await client.container.listServices( + { + queryParameters, + projectId, + }, + withAxiosRequestConfig(options), + ); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + listAccessible: async (queryParameters, options?: AxiosRequestConfig) => { + const response = await client.container.listAccessibleServices( + { + queryParameters, + }, + withAxiosRequestConfig(options), + ); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + updateStackUpdateSchedule: async (stackId, updateSchedule) => { + const data: ContainerStackUpdateSchedulePatchRequestData = { + updateSchedule, + }; + + const response = await client.container.updateStack({ + data: data as ContainerStackPatchRequestData, + stackId, + }); + + validateResponse(response, 200); + return response.data; + }, + + listTemplates: async (queryParameters) => { + const response = await client.container.listTemplates({ + queryParameters, + }); + validateResponse(response, 200); + return { + items: response.data.map((template) => + resolveTemplateAssetUrls(client, template), + ), + totalCount: resolveTotalCount(response), + }; + }, + + findStack: async (stackId, options?: AxiosRequestConfig) => { + const response = await client.container.getStack( + { + stackId, + }, + withAxiosRequestConfig(options), + ); + if (response.status === 200) { + return response.data; + } + validateResponse(response, 403); + }, + + listStacksOfProject: async (projectId, queryParameters) => { + const response = await client.container.listStacks({ + queryParameters, + projectId, + }); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + listStacks: async (queryParameters) => { + const response = await client.container.listSelfStacks({ + queryParameters, + }); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + rotateImagePullWebhook: async (containerId, stackId) => { + const response = await client.container.rotatePullImageWebhookForService({ + serviceId: containerId, + stackId, + }); + validateResponse(response, 200); + return response.data.webhookUrl; + }, + + find: async (containerId, stackId) => { + const response = await client.container.getService({ + serviceId: containerId, + stackId, + }); + if (response.status === 200) { + return response.data; + } + validateResponse(response, [403, 404]); + }, + + findTemplate: async (templateId) => { + const response = await client.container.getTemplate({ + templateId, + }); + + if (response.status === 200) { + return resolveTemplateAssetUrls(client, response.data); + } + validateResponse(response, 404); + }, + + getLog: async (containerId, stackId) => { + const response = await client.container.getServiceLogs({ + queryParameters: { tail: 10000 }, + serviceId: containerId, + stackId, + }); + validateResponse(response, 200); + return response.data; + }, + + delete: async (serviceName, stackId) => { + const response = await client.container.updateStack({ + data: { services: { [serviceName]: {} } }, + stackId, + }); + validateResponse(response, 200); + }, + + updateStackDescription: async (stackId, description) => { + const response = await client.container.updateStack({ + data: { description }, + stackId, + }); + + validateResponse(response, 200); + }, + + pullImage: async (containerId, stackId) => { + const response = await client.container.pullImageForService({ + serviceId: containerId, + stackId, + }); + validateResponse(response, 204); + }, + + declareStack: async (stackId, data) => { + const response = await client.container.declareStack({ + stackId, + data, + }); + + validateResponse(response, 200); + return response.data; + }, + + updateStack: async (stackId, data) => { + const response = await client.container.updateStack({ + stackId, + data, + }); + + validateResponse(response, 200); + return response.data; + }, + + recreate: async (containerId, stackId) => { + const response = await client.container.recreateService({ + serviceId: containerId, + stackId, + }); + validateResponse(response, 204); + }, + + restart: async (containerId, stackId) => { + const response = await client.container.restartService({ + serviceId: containerId, + stackId, + }); + validateResponse(response, 204); + }, + + create: async (stackId, data) => { + const response = await client.container.updateStack({ + stackId, + data, + }); + + validateResponse(response, 200); + return response.data; + }, + + start: async (containerId, stackId) => { + const response = await client.container.startService({ + serviceId: containerId, + stackId, + }); + validateResponse(response, 204); + }, + + addTemplateComponent: async (stackId, data) => { + const response = await client.container.addTemplateComponent({ + stackId, + data, + }); + validateResponse(response, 204); + }, + + stop: async (containerId, stackId) => { + const response = await client.container.stopService({ + serviceId: containerId, + stackId, + }); + validateResponse(response, 204); + }, + + createStack: async (data, projectId) => { + const response = await client.container.createStack({ projectId, data }); + validateResponse(response, 201); + return response.data; + }, + + getStack: async (stackId) => { + const response = await client.container.getStack({ + stackId, + }); + validateResponse(response, 200); + return response.data; + }, + + deleteStack: async (stackId) => { + const response = await client.container.deleteStack({ stackId }); + validateResponse(response, 204); + }, +}); diff --git a/packages/models/src/container/Container/behaviors/index.ts b/packages/models/src/container/Container/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/container/Container/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/container/Container/behaviors/types.ts b/packages/models/src/container/Container/behaviors/types.ts new file mode 100644 index 00000000..b201fdc8 --- /dev/null +++ b/packages/models/src/container/Container/behaviors/types.ts @@ -0,0 +1,132 @@ +import type { AxiosRequestConfig } from "axios"; + +import type { QueryResponseData } from "../../../base/index.js"; +import type { + ContainerStackUpdateSchedulePatchRequestData, + ContainerAddTemplateComponentData, + ContainerAccessibleListQueryData, + ContainerStackDeclareRequestData, + ContainerStackCreateRequestData, + ContainerStackPatchRequestData, + ContainerTemplateListQueryData, + ContainerTemplateListItemData, + ContainerStackListItemData, + ContainerTemplateApiData, + ContainerListQueryData, + ContainerListItemData, + ContainerStackData, + ContainerLogChunk, + ContainerData, + ImageMetaData, +} from "../types.js"; + +export interface ContainerBehaviors { + updateStackUpdateSchedule: ( + stackId: string, + updateSchedule: ContainerStackUpdateSchedulePatchRequestData["updateSchedule"], + ) => Promise; + list: ( + projectId: string, + query?: ContainerListQueryData, + options?: AxiosRequestConfig, + ) => Promise>; + + listAccessible: ( + query?: ContainerAccessibleListQueryData, + options?: AxiosRequestConfig, + ) => Promise>; + + getLogChunk: ( + containerId: string, + stackId: string, + range: string, + requestOptions?: AxiosRequestConfig, + ) => Promise; + + getImageMeta: ( + imageRef: string, + projectId: string, + generateAiData?: boolean, + language?: string, + ) => Promise; + + listStacksOfProject: ( + projectId: string, + query?: ContainerListQueryData, + ) => Promise>; + + listTemplates: ( + query?: ContainerTemplateListQueryData, + ) => Promise>; + + createStack: ( + data: ContainerStackCreateRequestData, + projectId: string, + ) => Promise; + + declareStack: ( + stackId: string, + data: ContainerStackDeclareRequestData, + ) => Promise; + + findStack: ( + stackId: string, + options?: AxiosRequestConfig, + ) => Promise; + + updateStack: ( + stackId: string, + data: ContainerStackPatchRequestData, + ) => Promise; + + listStacks: ( + query?: ContainerListQueryData, + ) => Promise>; + + addTemplateComponent: ( + stackId: string, + data: ContainerAddTemplateComponentData, + ) => Promise; + + create: ( + stackId: string, + data: ContainerStackPatchRequestData, + ) => Promise<{ id: string }>; + + find: ( + containerId: string, + stackId: string, + ) => Promise; + + rotateImagePullWebhook: ( + containerId: string, + stackId: string, + ) => Promise; + + updateStackDescription: ( + stackId: string, + description: string, + ) => Promise; + + findTemplate: ( + templateId: string, + ) => Promise; + + pullImage: (containerId: string, stackId: string) => Promise; + + recreate: (containerId: string, stackId: string) => Promise; + + getLog: (containerId: string, stackId: string) => Promise; + + restart: (containerId: string, stackId: string) => Promise; + + delete: (serviceName: string, stackId: string) => Promise; + + start: (containerId: string, stackId: string) => Promise; + + stop: (containerId: string, stackId: string) => Promise; + + getStack: (stackId: string) => Promise; + + deleteStack: (stackId: string) => Promise; +} diff --git a/packages/models/src/container/Container/index.ts b/packages/models/src/container/Container/index.ts new file mode 100644 index 00000000..a78e3fa5 --- /dev/null +++ b/packages/models/src/container/Container/index.ts @@ -0,0 +1,13 @@ +export * from "./Container.js"; +export * from "./ContainerEnvVariable.js"; +export * from "./ContainerLog.js"; +export * from "./ContainerPort.js"; +export * from "./ContainerStack.js"; +export * from "./ContainerTemplate.js"; +export * from "./ContainerUserInput.js"; +export * from "./ContainerVolumeRelation.js"; +export * from "./DockerCompose.js"; +export * from "./DockerComposeSchema.js"; +export * from "./ImageMeta.js"; +export * from "./resourceLimits.js"; +export * from "./types.js"; diff --git a/packages/models/src/container/Container/resourceLimits.ts b/packages/models/src/container/Container/resourceLimits.ts new file mode 100644 index 00000000..514a3bc8 --- /dev/null +++ b/packages/models/src/container/Container/resourceLimits.ts @@ -0,0 +1,45 @@ +import { Bytes } from "../../common/index.js"; + +export const toPositiveLimit = (value?: number): number | undefined => { + return typeof value === "number" && Number.isFinite(value) && value > 0 + ? value + : undefined; +}; + +export const parseCpuLimit = ( + cpuLimit?: string | number, +): number | undefined => { + if (!cpuLimit) { + return undefined; + } + + const normalized = String(cpuLimit).trim().replace(",", "."); + return toPositiveLimit(Number.parseFloat(normalized)); +}; + +export const parseRamLimitToGb = ( + ramLimit?: string | number, +): number | undefined => { + if (!ramLimit) { + return undefined; + } + + const normalized = String(ramLimit).trim(); + + try { + return toPositiveLimit(Bytes.parse(normalized).in("GiB")); + } catch { + return toPositiveLimit(Number.parseFloat(normalized)); + } +}; + +export const formatRamLimit = (ramLimitInGb?: number): string | undefined => { + const limit = toPositiveLimit(ramLimitInGb); + + if (limit === undefined) { + return undefined; + } + + const limitInMb = Math.round(Bytes.of(limit, "GiB").in("MiB")); + return limitInMb > 0 ? `${limitInMb}mb` : undefined; +}; diff --git a/packages/models/src/container/Container/types.ts b/packages/models/src/container/Container/types.ts new file mode 100644 index 00000000..2b6ca9d8 --- /dev/null +++ b/packages/models/src/container/Container/types.ts @@ -0,0 +1,182 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import type { ContainerStack } from "./ContainerStack.js"; +import type { Project } from "../../project/index.js"; + +export type ContainerData = + MittwaldAPIV2.Components.Schemas.ContainerServiceResponse; + +export type ContainerStackData = + MittwaldAPIV2.Components.Schemas.ContainerStackResponse; + +export type ContainerStackCreateRequestData = + MittwaldAPIV2.Paths.V2ProjectsProjectIdStacks.Post.Parameters.RequestBody; + +export type ContainerAddTemplateComponentData = + MittwaldAPIV2.Components.Schemas.ContainerAddTemplateComponent; + +// Same generated shape as ContainerCreateStack["templateConfig"]["userInputs"] - +// both API operations accept an identical { name; value }[] payload. +export type ContainerTemplateUserInputValues = + ContainerAddTemplateComponentData["templateConfig"]["userInputs"]; + +export type ContainerListItemData = + MittwaldAPIV2.Operations.ContainerListServices.ResponseData[number]; + +export type ContainerStackListItemData = ContainerStackData; + +export type ContainerListQueryData = + MittwaldAPIV2.Paths.V2ProjectsProjectIdServices.Get.Parameters.Query; + +export type ContainerAccessibleListQueryData = + MittwaldAPIV2.Paths.V2Services.Get.Parameters.Query; + +export type ContainerListQueryModelData = { + stack?: ContainerStack | string; + project?: Project | string; +} & Omit; + +export type ContainerStackListQueryData = + MittwaldAPIV2.Paths.V2Stacks.Get.Parameters.Query; + +export type ContainerStackListQueryModelData = { + project?: Project | string; +} & ContainerStackListQueryData; + +export type ContainerStackPatchRequestData = + MittwaldAPIV2.Paths.V2StacksStackId.Patch.Parameters.RequestBody; + +export type ContainerStackDeclareRequestData = + MittwaldAPIV2.Paths.V2StacksStackId.Put.Parameters.RequestBody; + +export type ContainerStackUpdateScheduleData = NonNullable< + ContainerStackPatchRequestData["updateSchedule"] +>; + +export type ContainerStackUpdateSchedulePatchRequestData = { + updateSchedule?: ContainerStackUpdateScheduleData | null; +} & Omit; + +export type ContainerPatchServiceData = + MittwaldAPIV2.Components.Schemas.ContainerServiceRequest; + +export type ContainerPatchVolumeData = + MittwaldAPIV2.Components.Schemas.ContainerVolumeRequest; + +export type ContainerDeclareServiceData = + MittwaldAPIV2.Components.Schemas.ContainerServiceDeclareRequest; + +export type ContainerTemplateApiData = + MittwaldAPIV2.Components.Schemas.ContainerTemplate; + +export type ContainerTemplateListQueryData = + MittwaldAPIV2.Paths.V2ContainerTemplates.Get.Parameters.Query; + +export type ContainerTemplateListItemData = + MittwaldAPIV2.Operations.ContainerListTemplates.ResponseData[number]; + +export const containerTemplateCategories = [ + "productivity", + "development", + "ai", + "security", + "monitoring", + "communication", + "media", +] as const; + +export type ContainerTemplateCategory = + (typeof containerTemplateCategories)[number]; + +export type ContainerTemplateDomainData = ContainerTemplateApiData["domains"]; +export type ContainerTemplateLicenseData = ContainerTemplateApiData["license"]; +export type ContainerTemplateType = ContainerTemplateApiData["type"]; + +export type ContainerTemplateTechnicalDetailData = NonNullable< + ContainerTemplateApiData["help"] +>["technicalDetails"]; + +export const containerTemplateAlertStatuses = [ + "info", + "success", + "warning", + "danger", + "unavailable", +] as const; + +export type ContainerTemplateAlertStatus = + (typeof containerTemplateAlertStatuses)[number]; + +export type ContainerStatus = + MittwaldAPIV2.Components.Schemas.ContainerServiceStatus; + +export type ContainerLogData = + MittwaldAPIV2.Operations.ContainerGetServiceLogs.ResponseData[number]; + +export interface ContainerLogChunk { + contentRange?: string; + content: string; + status: number; +} + +export interface ContainerUpdateData { + description?: string; + image?: string; +} + +export interface ContainerResourceLimitsData { + cpuLimit?: string; + ramLimit?: string; +} + +export type ContainerVolumeRelationData = string; + +export type ContainerPortData = string; + +export interface ContainerEnvVariableData { + value: string; + key: string; +} + +export type ImageMetaEnvData = + MittwaldAPIV2.Components.Schemas.ContainerContainerImageConfigEnv; + +export type ImageMetaPortData = + MittwaldAPIV2.Components.Schemas.ContainerContainerImageConfigExposedPort; + +export type ImageMetaVolumeData = + MittwaldAPIV2.Components.Schemas.ContainerContainerImageConfigVolume; + +export type ContainerStateData = + MittwaldAPIV2.Components.Schemas.ContainerServiceState; + +export type ContainerEnvVariableListData = Record; + +export type ImageMetaData = + MittwaldAPIV2.Components.Schemas.ContainerContainerImageConfig; + +export interface ContainerVolumeRelationFormValues { + type: "directory" | "volume"; + containerPath: string; + projectPath: string; + volume: string; +} + +export interface ContainerImageFormValues { + imageReference: string; +} + +export type ContainerTemplateUserInputsData = + ContainerTemplateApiData["userInputs"]; + +export type ContainerUserInputData = + NonNullable[number]; + +export const containerPortRegExp = + /^([0-9]+(-[0-9]+)?(:[0-9]+(-[0-9]+)?)?)?(\/(tcp|udp))?$/; +export const containerFilePathRegex = /^\/[a-z,A-Z/\-_.0-9]+/; +export const containerServiceNameRegex = /^[a-zA-Z0-9][a-zA-Z0-9_.-]+$/; +export const containerEnvKeyRegex = /^[a-zA-Z_][a-zA-Z0-9_.]*$/; +export const containerMaxPort = 65535; +export const containerServiceNameMaxLength = 63; +export const containerMaxTextLength = 800; diff --git a/packages/models/src/container/Registry/Registry.test.ts b/packages/models/src/container/Registry/Registry.test.ts new file mode 100644 index 00000000..2fb94a88 --- /dev/null +++ b/packages/models/src/container/Registry/Registry.test.ts @@ -0,0 +1,308 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { buildRegistryData } from "../../testing/builders/buildRegistryData.js"; +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { installBehaviors, resetBehaviors } from "../../testing/index.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { Project } from "../../project/index.js"; +import { + RegistryListQuery, + RegistryDetailed, + RegistryListItem, + RegistryList, + Registry, +} from "./Registry.js"; + +afterEach(resetBehaviors); + +describe("Registry", () => { + test("find delegates to the behavior and returns a detailed registry", async () => { + const find = vi.fn().mockResolvedValue(buildRegistryData({ id: "r-1" })); + installBehaviors({ registry: { find } }); + + const result = await Registry.find("r-1"); + + expect(find).toHaveBeenCalledWith("r-1"); + expect(result).toBeInstanceOf(RegistryDetailed); + expect(result?.id).toBe("r-1"); + }); + + test("find returns undefined when the registry is missing", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ registry: { find } }); + + await expect(Registry.find("missing")).resolves.toBeUndefined(); + expect(find).toHaveBeenCalledWith("missing"); + }); + + test("findCommon delegates to find and returns a detailed registry for a bare reference", async () => { + const find = vi.fn().mockResolvedValue(buildRegistryData({ id: "r-c" })); + installBehaviors({ registry: { find } }); + + const result = await Registry.ofId("r-c").findCommon(); + + expect(find).toHaveBeenCalledWith("r-c"); + expect(result).toBeInstanceOf(RegistryDetailed); + expect(result?.id).toBe("r-c"); + }); + + test("findCommon maps a missing registry to undefined for a bare reference", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ registry: { find } }); + + await expect( + Registry.ofId("missing").findCommon(), + ).resolves.toBeUndefined(); + expect(find).toHaveBeenCalledWith("missing"); + }); + + test("getCommon rejects with ObjectNotFoundError for a missing bare reference", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ registry: { find } }); + + await expect(Registry.ofId("missing").getCommon()).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("get returns a detailed registry", async () => { + const find = vi.fn().mockResolvedValue(buildRegistryData({ id: "r-2" })); + installBehaviors({ registry: { find } }); + + const result = await Registry.get("r-2"); + + expect(result).toBeInstanceOf(RegistryDetailed); + expect(result.id).toBe("r-2"); + }); + + test("get rejects with ObjectNotFoundError when the registry is missing", async () => { + installBehaviors({ + registry: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(Registry.get("missing")).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("findDetailed and getDetailed delegate with the reference id", async () => { + const find = vi.fn().mockResolvedValue(buildRegistryData({ id: "r-3" })); + installBehaviors({ registry: { find } }); + const registry = Registry.ofId("r-3"); + + await expect(registry.findDetailed()).resolves.toBeInstanceOf( + RegistryDetailed, + ); + await expect(registry.getDetailed()).resolves.toBeInstanceOf( + RegistryDetailed, + ); + expect(find).toHaveBeenNthCalledWith(1, "r-3"); + expect(find).toHaveBeenNthCalledWith(2, "r-3"); + }); + + test("findCommon and getCommon reuse an already detailed instance", async () => { + const find = vi.fn().mockResolvedValue(buildRegistryData()); + installBehaviors({ registry: { find } }); + const detailed = await Registry.get("registry-id"); + find.mockClear(); + + await expect(detailed.findCommon()).resolves.toBe(detailed); + await expect(detailed.getCommon()).resolves.toBe(detailed); + expect(find).not.toHaveBeenCalled(); + }); + + test("aggregateMetaData identifies the registry aggregate", () => { + expect(Registry.aggregateMetaData).toBeInstanceOf(AggregateMetaData); + expect(Registry.aggregateMetaData.domain).toBe("container"); + expect(Registry.aggregateMetaData.aggregate).toBe("registry"); + }); + + test("create sends password credentials and returns the response reference", async () => { + const create = vi.fn().mockResolvedValue({ id: "r-created" }); + installBehaviors({ registry: { create } }); + const project = Project.ofId("p-1"); + + const result = await Registry.create( + project, + { + credentials: { password: "secret", username: "alice" }, + description: "private registry", + uri: "private.example.com", + }, + "password", + ); + + expect(create).toHaveBeenCalledWith("p-1", { + credentials: { password: "secret", username: "alice" }, + description: "private registry", + uri: "private.example.com", + }); + expect(result).toBeInstanceOf(Registry); + expect(result.id).toBe("r-created"); + }); + + test("create omits credentials for anonymous login", async () => { + const create = vi.fn().mockResolvedValue({ id: "r-created" }); + installBehaviors({ registry: { create } }); + + await Registry.create( + Project.ofId("p-1"), + { + credentials: { username: "ignored", password: "ignored" }, + description: "public registry", + uri: "public.example.com", + }, + "anonymous", + ); + + expect(create).toHaveBeenCalledWith("p-1", { + description: "public registry", + uri: "public.example.com", + credentials: undefined, + }); + }); + + test("update delegates uri and description", async () => { + const update = vi.fn().mockResolvedValue(undefined); + installBehaviors({ registry: { update } }); + + await Registry.ofId("r-1").update({ + uri: "new.example.com", + description: "updated", + }); + + expect(update).toHaveBeenCalledWith("r-1", { + uri: "new.example.com", + description: "updated", + }); + }); + + test("updateCredentials sends password credentials", async () => { + const update = vi.fn().mockResolvedValue(undefined); + installBehaviors({ registry: { update } }); + + await Registry.ofId("r-1").updateCredentials( + { password: "secret", username: "alice" }, + "password", + ); + + expect(update).toHaveBeenCalledWith("r-1", { + credentials: { password: "secret", username: "alice" }, + }); + }); + + test("updateCredentials clears credentials for anonymous login", async () => { + const update = vi.fn().mockResolvedValue(undefined); + installBehaviors({ registry: { update } }); + + await Registry.ofId("r-1").updateCredentials( + { username: "ignored", password: "ignored" }, + "anonymous", + ); + + expect(update).toHaveBeenCalledWith("r-1", { credentials: null }); + }); + + test("delete delegates to the behavior", async () => { + const deleteRegistry = vi.fn().mockResolvedValue(undefined); + installBehaviors({ registry: { delete: deleteRegistry } }); + + await Registry.ofId("r-1").delete(); + + expect(deleteRegistry).toHaveBeenCalledWith("r-1"); + }); + + test("query executes with the project and materializes list items", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildRegistryData({ id: "r-1" })], + totalCount: 7, + }); + installBehaviors({ registry: { list } }); + const query = Registry.query({ + project: Project.ofId("p-1"), + limit: 5, + }); + + const result = await query.execute(); + + expect(query).toBeInstanceOf(RegistryListQuery); + expect(list).toHaveBeenCalledWith("p-1", { limit: 5 }); + expect(result).toBeInstanceOf(RegistryList); + expect(result.items).toHaveLength(1); + expect(result.items[0]).toBeInstanceOf(RegistryListItem); + expect(result.totalCount).toBe(7); + }); + + test("refine merges query values", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 0, items: [] }); + installBehaviors({ registry: { list } }); + + await Registry.query({ project: Project.ofId("p-1"), limit: 10 }) + .refine({ page: 2 }) + .execute(); + + expect(list).toHaveBeenCalledWith("p-1", { limit: 10, page: 2 }); + }); + + test("getTotalCount refines the query with limit one", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 12, items: [] }); + installBehaviors({ registry: { list } }); + + await expect( + Registry.query({ + project: Project.ofId("p-1"), + page: 3, + }).getTotalCount(), + ).resolves.toBe(12); + expect(list).toHaveBeenCalledWith("p-1", { limit: 1, page: 3 }); + }); + + test("exposes derived properties for detailed and list item data", async () => { + const passwordData = buildRegistryData({ + credentials: { username: "alice", valid: false }, + description: "description", + uri: "registry.test", + projectId: "p-data", + }); + const find = vi.fn().mockResolvedValue(passwordData); + const list = vi.fn().mockResolvedValue({ + items: [ + passwordData, + buildRegistryData({ credentials: undefined, id: "anonymous" }), + ], + totalCount: 2, + }); + installBehaviors({ registry: { find, list } }); + + const detailed = await Registry.get(passwordData.id); + const result = await Registry.query({ + project: Project.ofId("p-1"), + }).execute(); + const passwordItem = result.items[0]; + const anonymousItem = result.items[1]; + + for (const registry of [detailed, passwordItem]) { + expect(registry.description).toBe("description"); + expect(registry.uri).toBe("registry.test"); + expect(registry.username).toBe("alice"); + expect(registry.loginType).toBe("password"); + expect(registry.validCredentials).toBe(false); + expect(registry.project.id).toBe("p-data"); + } + expect(anonymousItem.loginType).toBe("anonymous"); + expect(anonymousItem.username).toBeUndefined(); + expect(anonymousItem.validCredentials).toBeUndefined(); + }); + + test("ofId creates a Registry instance", () => { + expect(Registry.ofId("r-1")).toBeInstanceOf(Registry); + }); +}); diff --git a/packages/models/src/container/Registry/Registry.ts b/packages/models/src/container/Registry/Registry.ts new file mode 100644 index 00000000..42a4532c --- /dev/null +++ b/packages/models/src/container/Registry/Registry.ts @@ -0,0 +1,210 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { omit } from "remeda"; + +import type { + RegistryUpdateCredentialsRequestData, + RegistryListQueryModelData, + RegistryCreateRequestData, + RegistryUpdateRequestData, + RegistryListItemData, + RegistryLoginType, + RegistryData, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { Project } from "../../project/internal.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "Registry", +}) +export class Registry extends ReferenceModel { + public static aggregateMetaData = new AggregateMetaData( + "container", + "registry", + ); + + public constructor(id: string) { + super(id); + } + + public static async create( + project: Project, + data: RegistryCreateRequestData, + loginType: RegistryLoginType, + ) { + const credentials = + loginType === "password" && data.credentials + ? { + username: data.credentials.username, + password: data.credentials.password, + } + : undefined; + + const response = await config.behaviors.registry.create(project.id, { + description: data.description, + uri: data.uri, + credentials, + }); + + return new Registry(response.id); + } + + public static async find(id: string) { + const data = await config.behaviors.registry.find(id); + if (data !== undefined) { + return new RegistryDetailed(data); + } + } + + public static async get(id: string) { + const registry = await Registry.find(id); + assertObjectFound(registry, Registry, id); + return registry; + } + + public static ofId(id: string) { + return new Registry(id); + } + + public static query(query: RegistryListQueryModelData) { + return new RegistryListQuery(query); + } + + public async delete() { + await config.behaviors.registry.delete(this.id); + } + + public async findCommon(): Promise { + return this instanceof RegistryCommon ? this : this.findDetailed(); + } + + public async findDetailed(): Promise { + return Registry.find(this.id); + } + + public async getCommon(): Promise { + return this instanceof RegistryCommon ? this : this.getDetailed(); + } + + public async getDetailed(): Promise { + return Registry.get(this.id); + } + + public async update(data: RegistryUpdateRequestData) { + return await config.behaviors.registry.update(this.id, { + description: data.description, + uri: data.uri, + }); + } + + public async updateCredentials( + data: RegistryUpdateCredentialsRequestData, + loginType: RegistryLoginType, + ) { + const credentials = + loginType === "password" + ? { + username: data.username, + password: data.password, + } + : undefined; + + await config.behaviors.registry.update(this.id, { + credentials: credentials ?? (null as any), + }); + } +} + +export class RegistryCommon extends WithData< + RegistryListItemData | RegistryData +>()(Registry) { + public override readonly data: RegistryListItemData | RegistryData; + public readonly description: string; + public readonly loginType: RegistryLoginType; + public readonly project: Project; + public readonly uri: string; + public readonly username?: string; + public readonly validCredentials?: boolean; + + public constructor(data: RegistryListItemData | RegistryData) { + super(data.id); + this.data = data; + this.description = data.description; + this.uri = data.uri; + this.username = data.credentials?.username; + this.loginType = data.credentials ? "password" : "anonymous"; + this.project = Project.ofId(data.projectId); + this.validCredentials = data.credentials?.valid; + } +} + +export class RegistryDetailed extends RegistryCommon { + public override readonly data: RegistryData; + public constructor(data: RegistryData) { + super(data); + this.data = data; + } +} + +export class RegistryListItem extends RegistryCommon { + public override readonly data: RegistryListItemData; + public constructor(data: RegistryListItemData) { + super(data); + this.data = data; + } +} + +export class RegistryListQuery extends ListQueryModel { + public constructor(query: RegistryListQueryModelData) { + super(query, { dependencies: [extractId(query.project)] }); + } + + public async execute() { + const { totalCount, items } = await config.behaviors.registry.list( + extractId(this.query.project), + omit(this.query, ["project"]), + ); + return new RegistryList( + this.query, + items.map((r) => new RegistryListItem(r)), + totalCount, + ); + } + + public async getTotalCount() { + const { totalCount } = await this.refine({ limit: 1 }).execute(); + return totalCount; + } + + public refine(query: Partial = {}) { + return new RegistryListQuery({ + ...this.query, + ...query, + }); + } +} + +export class RegistryList extends WithListData()( + RegistryListQuery, +) { + public override readonly items: readonly RegistryListItem[]; + public override readonly totalCount: number; + public constructor( + query: RegistryListQueryModelData, + registries: RegistryListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(registries); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/container/Registry/behaviors/api.ts b/packages/models/src/container/Registry/behaviors/api.ts new file mode 100644 index 00000000..d64d4519 --- /dev/null +++ b/packages/models/src/container/Registry/behaviors/api.ts @@ -0,0 +1,59 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { RegistryBehaviors } from "./types.js"; + +import { resolveTotalCount, validateResponse } from "../../../base/index.js"; + +export const apiRegistryBehaviors = ( + client: MittwaldAPIV2Client, +): RegistryBehaviors => ({ + create: async (projectId, data) => { + const response = await client.container.createRegistry({ projectId, data }); + + validateResponse(response, 201, { + validationError: { + pathMappings: { + "*.credentials": ["username", "password"], + }, + }, + }); + + return response.data; + }, + + list: async (projectId, queryParameters) => { + const response = await client.container.listRegistries({ + queryParameters, + projectId, + }); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + find: async (registryId) => { + const response = await client.container.getRegistry({ registryId }); + if (response.status === 200) { + return response.data; + } + validateResponse(response, 403); + }, + + update: async (registryId, data) => { + const response = await client.container.updateRegistry({ + registryId, + data, + }); + + validateResponse(response, 204); + }, + + delete: async (registryId) => { + const response = await client.container.deleteRegistry({ + registryId, + }); + validateResponse(response, 204); + }, +}); diff --git a/packages/models/src/container/Registry/behaviors/index.ts b/packages/models/src/container/Registry/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/container/Registry/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/container/Registry/behaviors/types.ts b/packages/models/src/container/Registry/behaviors/types.ts new file mode 100644 index 00000000..3572d0d9 --- /dev/null +++ b/packages/models/src/container/Registry/behaviors/types.ts @@ -0,0 +1,29 @@ +import type { QueryResponseData } from "../../../base/index.js"; +import type { + RegistryCreateRequestData, + RegistryUpdateRequestData, + RegistryListQueryData, + RegistryListItemData, + RegistryData, +} from "../types.js"; + +export interface RegistryBehaviors { + list: ( + projectId: string, + query?: RegistryListQueryData, + ) => Promise>; + + create: ( + projectId: string, + data: RegistryCreateRequestData, + ) => Promise<{ id: string }>; + + update: ( + registryId: string, + data: RegistryUpdateRequestData, + ) => Promise; + + find: (registryId: string) => Promise; + + delete: (registryId: string) => Promise; +} diff --git a/packages/models/src/container/Registry/index.ts b/packages/models/src/container/Registry/index.ts new file mode 100644 index 00000000..290b28e6 --- /dev/null +++ b/packages/models/src/container/Registry/index.ts @@ -0,0 +1,2 @@ +export * from "./Registry.js"; +export * from "./types.js"; diff --git a/packages/models/src/container/Registry/types.ts b/packages/models/src/container/Registry/types.ts new file mode 100644 index 00000000..62ee9677 --- /dev/null +++ b/packages/models/src/container/Registry/types.ts @@ -0,0 +1,31 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import type { Project } from "../../project/index.js"; + +export type RegistryData = MittwaldAPIV2.Components.Schemas.ContainerRegistry; + +export type RegistryListItemData = + MittwaldAPIV2.Operations.ContainerListRegistries.ResponseData[number]; + +export type RegistryListQueryData = + MittwaldAPIV2.Paths.V2ProjectsProjectIdRegistries.Get.Parameters.Query; + +export type RegistryListQueryModelData = { + project: Project | string; +} & RegistryListQueryData; + +export type RegistryCreateRequestData = + MittwaldAPIV2.Components.Schemas.ContainerCreateRegistry; + +export type RegistryUpdateRequestData = + MittwaldAPIV2.Components.Schemas.ContainerUpdateRegistry; + +export type RegistryUpdateCredentialsRequestData = + MittwaldAPIV2.Components.Schemas.ContainerSetRegistryCredentials; + +export type RegistryLoginType = "anonymous" | "password"; + +export interface KnownRegistryMeta { + helpLink: string; + scope: string; +} diff --git a/packages/models/src/container/Volume/Volume.test.ts b/packages/models/src/container/Volume/Volume.test.ts new file mode 100644 index 00000000..f5dc27c5 --- /dev/null +++ b/packages/models/src/container/Volume/Volume.test.ts @@ -0,0 +1,249 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { buildVolumeData } from "../../testing/builders/buildVolumeData.js"; +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { installBehaviors, resetBehaviors } from "../../testing/index.js"; +import { volumeNameRegExp } from "./types.js"; +import { Container } from "../Container/index.js"; +import { Project } from "../../project/index.js"; +import { Bytes } from "../../common/index.js"; +import { + VolumeListQuery, + VolumeDetailed, + VolumeListItem, + VolumeList, + Volume, +} from "./Volume.js"; + +afterEach(resetBehaviors); + +describe("Volume", () => { + test("find delegates to the behavior and returns a detailed volume", async () => { + const find = vi + .fn() + .mockResolvedValue(buildVolumeData({ stackId: "s-1", id: "v-1" })); + installBehaviors({ volume: { find } }); + + const result = await Volume.find("v-1", "s-1"); + + expect(find).toHaveBeenCalledWith("v-1", "s-1"); + expect(result).toBeInstanceOf(VolumeDetailed); + expect(result?.id).toBe("v-1"); + }); + + test("find returns undefined when the volume is missing", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ volume: { find } }); + + await expect(Volume.find("missing", "s-1")).resolves.toBeUndefined(); + expect(find).toHaveBeenCalledWith("missing", "s-1"); + }); + + test("findCommon delegates to find and returns a detailed volume for a bare reference", async () => { + const find = vi + .fn() + .mockResolvedValue(buildVolumeData({ stackId: "s-c", id: "v-c" })); + installBehaviors({ volume: { find } }); + + const result = await Volume.ofId("v-c", "s-c").findCommon(); + + expect(find).toHaveBeenCalledWith("v-c", "s-c"); + expect(result).toBeInstanceOf(VolumeDetailed); + expect(result?.id).toBe("v-c"); + }); + + test("findCommon maps a missing volume to undefined for a bare reference", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ volume: { find } }); + + await expect(Volume.ofId("m", "s").findCommon()).resolves.toBeUndefined(); + expect(find).toHaveBeenCalledWith("m", "s"); + }); + + test("getCommon rejects with ObjectNotFoundError for a missing bare reference", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ volume: { find } }); + + await expect(Volume.ofId("m", "s").getCommon()).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("get returns a detailed volume", async () => { + const find = vi + .fn() + .mockResolvedValue(buildVolumeData({ stackId: "s-2", id: "v-2" })); + installBehaviors({ volume: { find } }); + + const result = await Volume.get("v-2", "s-2"); + + expect(result).toBeInstanceOf(VolumeDetailed); + expect(result.id).toBe("v-2"); + }); + + test("get rejects with ObjectNotFoundError when the volume is missing", async () => { + installBehaviors({ + volume: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(Volume.get("missing", "s-1")).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("ofId keeps the stack id", () => { + const volume = Volume.ofId("v-1", "s-1"); + + expect(volume).toBeInstanceOf(Volume); + expect(volume.stackId).toBe("s-1"); + }); + + test("findDetailed and getDetailed delegate with id and stack id", async () => { + const find = vi + .fn() + .mockResolvedValue(buildVolumeData({ stackId: "s-3", id: "v-3" })); + installBehaviors({ volume: { find } }); + const volume = Volume.ofId("v-3", "s-3"); + + await expect(volume.findDetailed()).resolves.toBeInstanceOf(VolumeDetailed); + await expect(volume.getDetailed()).resolves.toBeInstanceOf(VolumeDetailed); + expect(find).toHaveBeenNthCalledWith(1, "v-3", "s-3"); + expect(find).toHaveBeenNthCalledWith(2, "v-3", "s-3"); + }); + + test("findCommon and getCommon reuse an already materialized volume without re-fetching", async () => { + const find = vi + .fn() + .mockResolvedValue(buildVolumeData({ stackId: "s-r", id: "v-r" })); + installBehaviors({ volume: { find } }); + const detailed = await Volume.get("v-r", "s-r"); + find.mockClear(); + + await expect(detailed.findCommon()).resolves.toBe(detailed); + await expect(detailed.getCommon()).resolves.toBe(detailed); + expect(find).not.toHaveBeenCalled(); + }); + + test("create delegates and returns a reference with the stack id", async () => { + const create = vi.fn().mockResolvedValue({ id: "v-created" }); + installBehaviors({ volume: { create } }); + + const result = await Volume.create("cache", "s-1"); + + expect(create).toHaveBeenCalledWith("s-1", "cache"); + expect(result).toBeInstanceOf(Volume); + expect(result.id).toBe("v-created"); + expect(result.stackId).toBe("s-1"); + }); + + test("delete delegates with id and stack id", async () => { + const deleteVolume = vi.fn().mockResolvedValue(undefined); + installBehaviors({ volume: { delete: deleteVolume } }); + + await Volume.ofId("v-1", "s-1").delete(); + + expect(deleteVolume).toHaveBeenCalledWith("v-1", "s-1"); + }); + + test("generateRandomName appends four valid characters", () => { + const initial = "volume"; + const result = Volume.generateRandomName(initial); + + expect(result).toMatch(volumeNameRegExp); + expect(result.startsWith(`${initial}-`)).toBe(true); + expect(result).toHaveLength(initial.length + 5); + }); + + test("query executes with the project and materializes list items", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildVolumeData({ id: "v-1" })], + totalCount: 7, + }); + installBehaviors({ volume: { list } }); + const query = Volume.query({ + project: Project.ofId("p-1"), + limit: 5, + }); + + const result = await query.execute(); + + expect(query).toBeInstanceOf(VolumeListQuery); + expect(list).toHaveBeenCalledWith("p-1", { limit: 5 }); + expect(result).toBeInstanceOf(VolumeList); + expect(result.items).toHaveLength(1); + expect(result.items[0]).toBeInstanceOf(VolumeListItem); + expect(result.totalCount).toBe(7); + }); + + test("refine merges query values", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 0, items: [] }); + installBehaviors({ volume: { list } }); + + await Volume.query({ project: Project.ofId("p-1"), limit: 10 }) + .refine({ page: 2 }) + .execute(); + + expect(list).toHaveBeenCalledWith("p-1", { limit: 10, page: 2 }); + }); + + test("getTotalCount refines the query with limit one", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 12, items: [] }); + installBehaviors({ volume: { list } }); + + await expect( + Volume.query({ + project: Project.ofId("p-1"), + page: 3, + }).getTotalCount(), + ).resolves.toBe(12); + expect(list).toHaveBeenCalledWith("p-1", { limit: 1, page: 3 }); + }); + + test("exposes derived properties and linked containers", async () => { + const data = buildVolumeData({ + linkedServices: ["container-a", "container-b"], + storageUsageInBytes: 2048, + name: "data-volume", + stackId: "s-data", + orphaned: true, + id: "v-data", + }); + installBehaviors({ volume: { find: vi.fn().mockResolvedValue(data) } }); + + const volume = await Volume.get("v-data", "s-data"); + + expect(volume.name).toBe("data-volume"); + expect(volume.storageUsageInBytes).toBe(2048); + expect(volume.storageUsage).toBeInstanceOf(Bytes); + expect(volume.orphaned).toBe(true); + expect(volume.stack.id).toBe("s-data"); + expect(volume.linkedContainers).toHaveLength(2); + expect( + volume.linkedContainers.every((item) => item instanceof Container), + ).toBe(true); + expect(volume.linkedContainers.map((item) => item.id)).toEqual([ + "container-a", + "container-b", + ]); + expect( + volume.linkedContainers.every((item) => item.stackId === "s-data"), + ).toBe(true); + }); + + test("linkedContainers is empty when linkedServices is absent", async () => { + const data = buildVolumeData({ linkedServices: undefined }); + installBehaviors({ volume: { find: vi.fn().mockResolvedValue(data) } }); + + const volume = await Volume.get(data.id, data.stackId); + + expect(volume.linkedContainers).toEqual([]); + }); +}); diff --git a/packages/models/src/container/Volume/Volume.ts b/packages/models/src/container/Volume/Volume.ts new file mode 100644 index 00000000..210869e6 --- /dev/null +++ b/packages/models/src/container/Volume/Volume.ts @@ -0,0 +1,175 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { omit } from "remeda"; + +import type { + VolumeListQueryModelData, + VolumeListItemData, + VolumeData, +} from "./types.js"; + +import { generateRandomAlphanumericString } from "../../lib/generateRandomAlphanumericString.js"; +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { ContainerStack, Container } from "../Container/index.js"; +import { config } from "../../config/index.js"; +import { Bytes } from "../../common/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "Volume", +}) +export class Volume extends ReferenceModel { + public readonly stackId: string; + + public constructor(id: string, stackId: string) { + super(id); + this.stackId = stackId; + } + + public static async create(name: string, stackId: string) { + const targetStackId = stackId; + const response = await config.behaviors.volume.create(targetStackId, name); + + return new Volume(response.id, targetStackId); + } + + public static async find(id: string, stackId: string) { + const data = await config.behaviors.volume.find(id, stackId); + if (data) { + return new VolumeDetailed(data); + } + } + + public static generateRandomName(initialName: string): string { + const suffix = generateRandomAlphanumericString(4); + return `${initialName}-${suffix}`; + } + + public static async get(id: string, stackId: string) { + const volume = await Volume.find(id, stackId); + assertObjectFound(volume, Volume, id); + return volume; + } + + public static ofId(id: string, stackId: string) { + return new Volume(id, stackId); + } + + public static query(query: VolumeListQueryModelData) { + return new VolumeListQuery(query); + } + + public async delete() { + await config.behaviors.volume.delete(this.id, this.stackId); + } + + public async findCommon(): Promise { + return this instanceof VolumeCommon ? this : this.findDetailed(); + } + + public async findDetailed(): Promise { + return Volume.find(this.id, this.stackId); + } + + public async getCommon(): Promise { + return this instanceof VolumeCommon ? this : this.getDetailed(); + } + + public async getDetailed(): Promise { + return Volume.get(this.id, this.stackId); + } +} + +export class VolumeCommon extends WithData()( + Volume, +) { + public override readonly data: VolumeListItemData | VolumeData; + public readonly linkedContainers: Container[]; + public readonly name: string; + public readonly orphaned: boolean; + public readonly stack: ContainerStack; + public readonly storageUsage: Bytes; + public readonly storageUsageInBytes: number; + + public constructor(data: VolumeListItemData | VolumeData) { + super(data.id, data.stackId); + this.data = data; + this.name = data.name; + this.linkedContainers = + data.linkedServices?.map((s) => Container.ofId(s, data.stackId)) ?? []; + this.storageUsage = Bytes.of(data.storageUsageInBytes, "bytes"); + this.storageUsageInBytes = data.storageUsageInBytes; + this.orphaned = data.orphaned; + this.stack = ContainerStack.ofId(data.stackId); + } +} + +export class VolumeDetailed extends VolumeCommon { + public override readonly data: VolumeData; + public constructor(data: VolumeData) { + super(data); + this.data = data; + } +} + +export class VolumeListItem extends VolumeCommon { + public override readonly data: VolumeListItemData; + public constructor(data: VolumeListItemData) { + super(data); + this.data = data; + } +} + +export class VolumeListQuery extends ListQueryModel { + public constructor(query: VolumeListQueryModelData) { + super(query, { dependencies: [extractId(query.project)] }); + } + + public async execute() { + const { totalCount, items } = await config.behaviors.volume.list( + extractId(this.query.project), + { + ...omit(this.query, ["project", "stack"]), + stackId: extractId(this.query.stack), + }, + ); + return new VolumeList( + this.query, + items.map((v) => new VolumeListItem(v)), + totalCount, + ); + } + + public async getTotalCount() { + const { totalCount } = await this.refine({ limit: 1 }).execute(); + return totalCount; + } + + public refine(query: Partial = {}) { + return new VolumeListQuery({ + ...this.query, + ...query, + }); + } +} + +export class VolumeList extends WithListData()( + VolumeListQuery, +) { + public override readonly items: readonly VolumeListItem[]; + public override readonly totalCount: number; + public constructor( + query: VolumeListQueryModelData, + volumes: VolumeListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(volumes); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/container/Volume/behaviors/api.ts b/packages/models/src/container/Volume/behaviors/api.ts new file mode 100644 index 00000000..1ee5627b --- /dev/null +++ b/packages/models/src/container/Volume/behaviors/api.ts @@ -0,0 +1,48 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { VolumeBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount } from "../../../base/index.js"; + +export const apiVolumeBehaviors = ( + client: MittwaldAPIV2Client, +): VolumeBehaviors => ({ + list: async (projectId, queryParameters) => { + const response = await client.container.listVolumes({ + queryParameters, + projectId, + }); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + create: async (stackId, name) => { + const response = await client.container.updateStack({ + data: { volumes: { [name]: { name } } }, + stackId, + }); + + validateResponse(response, 200); + return response.data; + }, + + find: async (volumeId, stackId) => { + const response = await client.container.getVolume({ volumeId, stackId }); + if (response.status === 200) { + return response.data; + } + validateResponse(response, 404); + }, + + delete: async (volumeId, stackId) => { + const response = await client.container.deleteVolume({ + volumeId, + stackId, + }); + validateResponse(response, 204); + }, +}); diff --git a/packages/models/src/container/Volume/behaviors/index.ts b/packages/models/src/container/Volume/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/container/Volume/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/container/Volume/behaviors/types.ts b/packages/models/src/container/Volume/behaviors/types.ts new file mode 100644 index 00000000..4298264c --- /dev/null +++ b/packages/models/src/container/Volume/behaviors/types.ts @@ -0,0 +1,19 @@ +import type { QueryResponseData } from "../../../base/index.js"; +import type { + VolumeListQueryData, + VolumeListItemData, + VolumeData, +} from "../types.js"; + +export interface VolumeBehaviors { + list: ( + projectId: string, + query?: VolumeListQueryData, + ) => Promise>; + + find: (volumeId: string, stackId: string) => Promise; + + create: (stackId: string, name: string) => Promise<{ id: string }>; + + delete: (volumeId: string, stackId: string) => Promise; +} diff --git a/packages/models/src/container/Volume/index.ts b/packages/models/src/container/Volume/index.ts new file mode 100644 index 00000000..10185339 --- /dev/null +++ b/packages/models/src/container/Volume/index.ts @@ -0,0 +1,2 @@ +export * from "./types.js"; +export * from "./Volume.js"; diff --git a/packages/models/src/container/Volume/types.ts b/packages/models/src/container/Volume/types.ts new file mode 100644 index 00000000..8bba6956 --- /dev/null +++ b/packages/models/src/container/Volume/types.ts @@ -0,0 +1,20 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import type { ContainerStack } from "../Container/ContainerStack.js"; +import type { Project } from "../../project/index.js"; + +export type VolumeData = + MittwaldAPIV2.Components.Schemas.ContainerVolumeResponse; + +export type VolumeListItemData = + MittwaldAPIV2.Operations.ContainerListVolumes.ResponseData[number]; + +export type VolumeListQueryData = + MittwaldAPIV2.Paths.V2ProjectsProjectIdVolumes.Get.Parameters.Query; + +export type VolumeListQueryModelData = { + stack?: ContainerStack | string; + project: Project | string; +} & Omit; + +export const volumeNameRegExp = /^[a-zA-Z0-9][a-zA-Z0-9_.-]+$/; diff --git a/packages/models/src/container/index.ts b/packages/models/src/container/index.ts new file mode 100644 index 00000000..8ca607ab --- /dev/null +++ b/packages/models/src/container/index.ts @@ -0,0 +1,5 @@ +export * from "./Container/index.js"; +export * from "./lib/sensitiveEnvKeys.js"; +export * from "./lib/shellwords.js"; +export * from "./Registry/index.js"; +export * from "./Volume/index.js"; diff --git a/packages/models/src/container/lib/sensitiveEnvKeys.test.ts b/packages/models/src/container/lib/sensitiveEnvKeys.test.ts new file mode 100644 index 00000000..0a3af7db --- /dev/null +++ b/packages/models/src/container/lib/sensitiveEnvKeys.test.ts @@ -0,0 +1,225 @@ +import { expect, test } from "vitest"; + +import { + maskedValuePlaceholder, + maskSensitiveEnvValue, + maskUrlCredentials, + isSensitiveEnvKey, +} from "./sensitiveEnvKeys.js"; + +test("isSensitiveEnvKey identifies sensitive environment keys", () => { + const sensitiveKeys = [ + "PASSWORD", + "DB_PASSWORD", + "MYSQL_PASSWD", + "admin_pass", + "PASSPHRASE", + "JWT_SECRET", + "CLIENT_SECRET", + "AUTH_TOKEN", + "auth_token", + "API_KEY", + "api-key", + "apiKey", + "APIKEY", + "AWS_ACCESS_KEY_ID", + "SSH_PRIVATE_KEY", + "GOOGLE_APPLICATION_CREDENTIALS", + "HASH_SALT", + "SENTRY_DSN", + ]; + + sensitiveKeys.forEach((key) => { + expect(isSensitiveEnvKey(key)).toBeTruthy(); + }); +}); + +test("isSensitiveEnvKey leaves harmless environment keys visible", () => { + const harmlessKeys = [ + "PWD", + "GIT_AUTHOR_NAME", + "AUTH_URL", + "KEYCLOAK_URL", + "PORT", + "NODE_ENV", + "DEBUG", + "DATABASE_URL", + "USE_TLS", + "USERNAME", + ]; + + harmlessKeys.forEach((key) => { + expect(isSensitiveEnvKey(key)).toBeFalsy(); + }); +}); + +test("isSensitiveEnvKey preserves descriptor word boundaries for non-corpus collision keys", () => { + ["USER_PASSWORD", "USERPASS", "USER_TOKEN", "REQUIRED_TOKEN"].forEach( + (key) => { + expect(isSensitiveEnvKey(key)).toBeTruthy(); + }, + ); +}); + +test("isSensitiveEnvKey masks all real keys covered by the trailing-key rule", () => { + const trailingKeySecrets = [ + "APP_KEY", + "CREDS_KEY", + "ENCRYPTION_KEY", + "MEILI_MASTER_KEY", + "N8N_ENCRYPTION_KEY", + "PWPUSH_MASTER_KEY", + "SIG_KEY", + ]; + + trailingKeySecrets.forEach((key) => { + expect(isSensitiveEnvKey(key)).toBeTruthy(); + }); +}); + +test("isSensitiveEnvKey masks LICENSE_KEY as an authorization credential", () => { + expect(isSensitiveEnvKey("LICENSE_KEY")).toBeTruthy(); +}); + +test("isSensitiveEnvKey does not treat non-trailing or descriptor key references as secrets", () => { + ["KEYBOARD_LAYOUT", "PUBLIC_KEY_PATH"].forEach((key) => { + expect(isSensitiveEnvKey(key)).toBeFalsy(); + }); +}); + +test("isSensitiveEnvKey masks SMTP_PWD but keeps the working-directory PWD visible", () => { + expect(isSensitiveEnvKey("SMTP_PWD")).toBeTruthy(); + expect(isSensitiveEnvKey("PWD")).toBeFalsy(); +}); + +test("isSensitiveEnvKey masks the real CREDS_IV credential material", () => { + expect(isSensitiveEnvKey("CREDS_IV")).toBeTruthy(); +}); + +[ + ["SECRETKEY_PATH", "/root/.flowise"], + ["SECRETKEY_STORAGE_TYPE", "local"], + ["GENERIC_OPEN_AI_MODEL_TOKEN_LIMIT", "131072"], + ["NEXT_PUBLIC_CREDENTIALS_ENABLED", "true"], + ["ALLOW_PASSWORD_RESET", "true"], +].forEach(([key, realValue]) => { + test(`isSensitiveEnvKey keeps descriptor ${key}=${realValue} visible`, () => { + expect(isSensitiveEnvKey(key)).toBeFalsy(); + }); +}); + +test("isSensitiveEnvKey descriptor exclusions never unmask confirmed secret-bearing keys", () => { + const confirmedSecretKeys = [ + "ADMIN_PASSWORD", + "ADMIN_TOKEN", + "APP_SECRET", + "AUTH_SECRET", + "AUTH_TOKEN", + "FLOWISE_SECRETKEY_OVERWRITE", + "JWT_SECRET", + "SECRET", + "SECRET_KEY", + "SECRET_KEY_BASE", + "SECRET_PASSWORD", + "POSTGRES_PASSWORD", + "MARIADB_ROOT_PASSWORD", + "LISTMONK_db__password", + "MM_EMAILSETTINGS_SMTPPASSWORD", + "OPENPROJECT_SMTP__PASSWORD", + "QDRANT__SERVICE__API_KEY", + "SIG_SALT", + "MEMOS_DSN", + "TOKEN_HASH_SECRET", + "OPENAI_API_KEY", + "RAG_OPENAI_API_KEY", + ]; + + confirmedSecretKeys.forEach((key) => { + expect(isSensitiveEnvKey(key)).toBeTruthy(); + }); +}); + +test("isSensitiveEnvKey masks BYPASS_* as an accepted false positive of the pass keyword", () => { + expect(isSensitiveEnvKey("BYPASS_CACHE")).toBeTruthy(); +}); + +test("isSensitiveEnvKey records known auth-pair limitations as currently visible", () => { + ["MP_SMTP_AUTH", "MP_UI_AUTH", "CREATE_SUPERUSER"].forEach((key) => { + expect(isSensitiveEnvKey(key)).toBeFalsy(); + }); +}); + +test("maskUrlCredentials masks only a URL password", () => { + const masked = maskUrlCredentials( + "postgres://appuser:s3cr3t@db.example.com:5432/appdb", + ); + + expect(masked).toBe( + `postgres://appuser:${maskedValuePlaceholder}@db.example.com:5432/appdb`, + ); + expect(masked).not.toContain("s3cr3t"); +}); + +test("maskUrlCredentials masks a password with an empty username", () => { + expect(maskUrlCredentials("redis://:supersecret@redis:6379")).toBe( + `redis://:${maskedValuePlaceholder}@redis:6379`, + ); +}); + +test("maskUrlCredentials preserves paths and queries after masking", () => { + const urls = [ + [ + "mongodb://librechat:s3cr3t@mongodb:27017/L?authSource=admin", + `mongodb://librechat:${maskedValuePlaceholder}@mongodb:27017/L?authSource=admin`, + ], + [ + "smtp://box:s3cr3t@mail.agenturserver.de?encryption=tls", + `smtp://box:${maskedValuePlaceholder}@mail.agenturserver.de?encryption=tls`, + ], + [ + "mysql://kimai:s3cr3t@database/kimai?charset=utf8mb4", + `mysql://kimai:${maskedValuePlaceholder}@database/kimai?charset=utf8mb4`, + ], + ]; + + urls.forEach(([value, expected]) => { + expect(maskUrlCredentials(value)).toBe(expected); + }); +}); + +test("maskUrlCredentials leaves a credential-free URL unchanged", () => { + const credentialFreeUrls = [ + "redis://redis:6379", + "https://example.com/path", + "http://user@example.com/x", + ]; + + credentialFreeUrls.forEach((url) => { + expect(maskUrlCredentials(url)).toBe(url); + }); +}); + +test("maskUrlCredentials leaves a plain non-URL value unchanged", () => { + expect(maskUrlCredentials("8080")).toBe("8080"); +}); + +test("maskSensitiveEnvValue masks a sensitive key regardless of its value", () => { + expect(maskSensitiveEnvValue("JWT_SECRET", "visible-value")).toBe( + maskedValuePlaceholder, + ); +}); + +test("maskSensitiveEnvValue masks URL credentials for a non-sensitive key", () => { + expect( + maskSensitiveEnvValue( + "DATABASE_URL", + "postgres://appuser:s3cr3t@db.example.com:5432/appdb", + ), + ).toBe( + `postgres://appuser:${maskedValuePlaceholder}@db.example.com:5432/appdb`, + ); +}); + +test("maskSensitiveEnvValue leaves a harmless key and value unchanged", () => { + expect(maskSensitiveEnvValue("PORT", "8080")).toBe("8080"); +}); diff --git a/packages/models/src/container/lib/sensitiveEnvKeys.ts b/packages/models/src/container/lib/sensitiveEnvKeys.ts new file mode 100644 index 00000000..de279512 --- /dev/null +++ b/packages/models/src/container/lib/sensitiveEnvKeys.ts @@ -0,0 +1,107 @@ +/** + * Sensitive environment-key rules: + * + * - `pass` covers password material such as `ADMIN_PASSWORD`; `BYPASS_CACHE` is a + * known accepted false positive. + * - `secret` covers secret material such as `APP_SECRET`. + * - `token` covers token material such as `ADMIN_TOKEN`. + * - `apikey` covers API keys such as `OPENAI_API_KEY`. + * - `accesskey` covers `AWS_ACCESS_KEY_ID`. + * - `privatekey` covers private keys such as `SSH_PRIVATE_KEY`. + * - `credential` covers credential references such as + * `GOOGLE_APPLICATION_CREDENTIALS`. + * - `pwd` covers password abbreviations such as `SMTP_PWD`. + * - `creds` covers credential material such as `CREDS_IV`. + * - `salt` covers hashing and crypto material such as `SIG_SALT`. + * - `dsn` covers secret-bearing connection strings such as `MEMOS_DSN`. + * - Trailing whole-token `key` covers key material such as `APP_KEY`. + * - Descriptor suffixes match only the final whole token. + * - Descriptor prefixes match only the first whole token. + * - `use` is omitted because it collides with secret-bearing `USER_*` keys. + * - Bare `key` stays omitted because it would match `KEYCLOAK_URL` and + * `KEYBOARD_LAYOUT`; only trailing `key` is sensitive. + * - Bare `auth` stays omitted because harmless keys such as `MAIL_SMTP_AUTH`, + * `WEBUI_AUTH`, and `SMTP_AUTHENTICATION` make it too broad. + * - Exact `PWD` stays visible because it is the standard working-directory + * variable. + * - Known accepted misses are `MP_SMTP_AUTH`, `MP_UI_AUTH`, and + * `CREATE_SUPERUSER`; their `user:password` values cannot be inferred safely + * from their keys. + */ +const sensitiveEnvKeywords = [ + "pass", + "secret", + "token", + "apikey", + "accesskey", + "privatekey", + "credential", + "pwd", + "creds", + "salt", + "dsn", +] as const; + +const sensitiveEnvSuffixes = ["key"] as const; + +const descriptorEnvSuffixes = [ + "path", + "file", + "type", + "limit", + "enabled", + "disabled", + "required", +] as const; + +const descriptorEnvPrefixes = [ + "allow", + "enable", + "disable", + "require", + "skip", +] as const; + +export const maskedValuePlaceholder = "•••••••••"; + +const normalizeEnvKey = (key: string): string => + key.toLowerCase().replace(/[^a-z0-9]/g, ""); + +const envKeyTokens = (key: string): string[] => + key + .replace(/([a-z0-9])([A-Z])/g, "$1 $2") + .toLowerCase() + .split(/[^a-z0-9]+/) + .filter(Boolean); + +export const isSensitiveEnvKey = (key: string): boolean => { + const normalizedKey = normalizeEnvKey(key); + const tokens = envKeyTokens(key); + const firstToken = tokens.at(0); + const lastToken = tokens.at(-1); + + if ( + descriptorEnvSuffixes.some((suffix) => lastToken === suffix) || + descriptorEnvPrefixes.some((prefix) => firstToken === prefix) + ) { + return false; + } + + if (normalizedKey === "pwd") { + return false; + } + + return ( + sensitiveEnvKeywords.some((keyword) => normalizedKey.includes(keyword)) || + sensitiveEnvSuffixes.some((suffix) => lastToken === suffix) + ); +}; + +export const maskUrlCredentials = (value: string): string => + value.replace( + /(:\/\/[^:/?#]*:)([^@/?#]+)(@)/, + `$1${maskedValuePlaceholder}$3`, + ); + +export const maskSensitiveEnvValue = (key: string, value: string): string => + isSensitiveEnvKey(key) ? maskedValuePlaceholder : maskUrlCredentials(value); diff --git a/packages/models/src/container/lib/shellwords.ts b/packages/models/src/container/lib/shellwords.ts new file mode 100644 index 00000000..235da5f8 --- /dev/null +++ b/packages/models/src/container/lib/shellwords.ts @@ -0,0 +1,14 @@ +import { split as shellwordsSplit } from "shellwords"; + +export const shellSplit = (words: string): string[] => { + return shellwordsSplit(words.trim()); +}; + +export const shellJoin = (words: string[]): string => { + return words + .map((word) => { + return /\s/.test(word) ? `"${word}"` : word; + }) + .join(" ") + .trim(); +}; diff --git a/packages/models/src/contract/Contract/Contract.test.ts b/packages/models/src/contract/Contract/Contract.test.ts new file mode 100644 index 00000000..4b0593ed --- /dev/null +++ b/packages/models/src/contract/Contract/Contract.test.ts @@ -0,0 +1,267 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { buildContractArticleData } from "../../testing/builders/buildContractArticleData.js"; +import { buildContractItemData } from "../../testing/builders/buildContractItemData.js"; +import { buildContractData } from "../../testing/builders/buildContractData.js"; +import { + ContractItemDetailed, + ContractItemCommon, +} from "../ContractItem/index.js"; +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { installBehaviors, resetBehaviors } from "../../testing/index.js"; +import { ReferenceModel } from "../../base/index.js"; +import { Customer } from "../../customer/index.js"; +import { + ContractListQuery, + ContractDetailed, + ContractListItem, + ContractCommon, + ContractList, + Contract, +} from "./Contract.js"; + +afterEach(resetBehaviors); + +describe("Contract", () => { + test("creates a reference", () => { + const contract = Contract.ofId("c-1"); + + expect(contract).toBeInstanceOf(Contract); + expect(contract.id).toBe("c-1"); + }); + + test("find delegates and constructs a detailed contract from returned data", async () => { + const find = vi + .fn() + .mockResolvedValue(buildContractData({ contractId: "data-id" })); + installBehaviors({ contract: { find } }); + + const contract = await Contract.find("requested-id"); + + expect(find).toHaveBeenCalledWith("requested-id"); + expect(contract).toBeInstanceOf(ContractDetailed); + expect(contract?.id).toBe("data-id"); + }); + + test("find returns undefined for missing data", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ contract: { find } }); + + await expect(Contract.find("missing")).resolves.toBeUndefined(); + }); + + test.each([ + ["project", "findByProject", "project-1", ["project-1", undefined]], + ["server", "findByServer", "server-1", ["server-1"]], + ] as const)("finds a contract by %s", async (_, method, id, expectedArgs) => { + const behavior = vi.fn().mockResolvedValue(buildContractData()); + installBehaviors({ contract: { [method]: behavior } }); + + const contract = await Contract[method](id); + + expect(behavior).toHaveBeenCalledWith(...expectedArgs); + expect(contract).toBeInstanceOf(ContractDetailed); + }); + + test("terminate and cancelTermination delegate with the contract id", async () => { + const terminate = vi.fn().mockResolvedValue(undefined); + const cancelTermination = vi.fn().mockResolvedValue(undefined); + installBehaviors({ contract: { cancelTermination, terminate } }); + const contract = Contract.ofId("contract-1"); + const data: Parameters[0] = {}; + + await contract.terminate(data); + await contract.cancelTermination(); + + expect(terminate).toHaveBeenCalledWith("contract-1", data); + expect(cancelTermination).toHaveBeenCalledWith("contract-1"); + }); + + test("constructs data and derived contract values", () => { + const domainItem = buildContractItemData({ + articles: [buildContractArticleData({ name: "Domain example.com" })], + totalPrice: { currency: "EUR", value: 250 }, + itemId: "domain-item", + isBaseItem: false, + }); + const otherItem = buildContractItemData({ + articles: [buildContractArticleData({ name: "Mailbox" })], + totalPrice: { currency: "EUR", value: 750 }, + itemId: "mail-item", + isBaseItem: false, + }); + const contract = new ContractDetailed( + buildContractData({ additionalItems: [domainItem, otherItem] }), + ); + + expect(contract.customer).toBeInstanceOf(Customer); + expect(contract.customer.id).toBe("customer-id"); + expect(contract.additionalItems).toHaveLength(2); + expect(contract.additionalItems[0]).toBeInstanceOf(ContractItemCommon); + expect(contract.additionalItemsTotalPrice.getAmount()).toBe(1000); + expect(contract.domainItemsCount).toBe(1); + expect(contract.baseItem).toBeInstanceOf(ContractItemDetailed); + expect(contract.description).toBe(contract.baseItem.description); + expect(contract.period).toBe(contract.baseItem.contractPeriod); + }); + + test("query executes, paginates, and maps list items", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildContractData()], + totalCount: 7, + }); + installBehaviors({ contract: { list } }); + const customer = Customer.ofId("customer-id"); + const query = Contract.query({ customer: customer, limit: 2 }); + + const result = await query.execute(); + const refined = query.refine({ page: 3 }); + await refined.execute(); + + expect(query).toBeInstanceOf(ContractListQuery); + expect(list).toHaveBeenCalledWith("customer-id", { limit: 2 }); + expect(result).toBeInstanceOf(ContractList); + expect(result.items[0]).toBeInstanceOf(ContractListItem); + expect(result.totalCount).toBe(7); + expect(refined).toBeInstanceOf(ContractListQuery); + expect(refined).not.toBe(query); + expect(list).toHaveBeenLastCalledWith("customer-id", { + limit: 2, + page: 3, + }); + }); + + test("getTotalCount requests and returns the total count", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 11, items: [] }); + installBehaviors({ contract: { list } }); + + const count = await Contract.query({ + customer: Customer.ofId("customer-id"), + limit: 2, + }).getTotalCount(); + + expect(count).toBe(11); + expect(list).toHaveBeenCalledWith("customer-id", { limit: 1 }); + }); + + test("list items retain the complete model identity chain", () => { + const item = new ContractListItem(buildContractData()); + + expect(item).toBeInstanceOf(ContractListItem); + expect(item).toBeInstanceOf(ContractCommon); + expect(item).toBeInstanceOf(Contract); + expect(item).toBeInstanceOf(ReferenceModel); + expect(item.data).toBeDefined(); + }); + + test("get rejects with ObjectNotFoundError for missing data", async () => { + installBehaviors({ + contract: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(Contract.get("missing")).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + test("getCommon on a reference delegates to the detail behavior and returns the common variant", async () => { + const find = vi + .fn() + .mockResolvedValue(buildContractData({ contractId: "data-id" })); + installBehaviors({ contract: { find } }); + + const common = await Contract.ofId("ref-id").getCommon(); + + expect(find).toHaveBeenCalledWith("ref-id"); + expect(common).toBeInstanceOf(ContractDetailed); + expect(common).toBeInstanceOf(ContractCommon); + expect(common.id).toBe("data-id"); + }); + + test("findCommon on a reference delegates to the detail behavior and returns the common variant", async () => { + const find = vi + .fn() + .mockResolvedValue(buildContractData({ contractId: "data-id" })); + installBehaviors({ contract: { find } }); + + const common = await Contract.ofId("ref-id").findCommon(); + + expect(find).toHaveBeenCalledWith("ref-id"); + expect(common).toBeInstanceOf(ContractDetailed); + expect(common?.id).toBe("data-id"); + }); + + test("getCommon rejects with ObjectNotFoundError when the reference cannot be resolved", async () => { + installBehaviors({ + contract: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(Contract.ofId("missing").getCommon()).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("findCommon on a reference rejects when the contract cannot be resolved", async () => { + // findCommon delegates to findDetailed -> Contract.get, which throws + // ObjectNotFoundError rather than resolving to undefined. + installBehaviors({ + contract: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(Contract.ofId("missing").findCommon()).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("getCommon on a materialized contract returns itself without invoking any behavior", async () => { + const find = vi.fn(); + installBehaviors({ contract: { find } }); + const contract = new ContractDetailed(buildContractData()); + + const common = await contract.getCommon(); + + expect(common).toBe(contract); + expect(find).not.toHaveBeenCalled(); + }); + + test("findCommon on a materialized list item returns itself without invoking any behavior", async () => { + const find = vi.fn(); + installBehaviors({ contract: { find } }); + const item = new ContractListItem(buildContractData()); + + const common = await item.findCommon(); + + expect(common).toBe(item); + expect(find).not.toHaveBeenCalled(); + }); + + test("omits derived optional values when the source omits them", () => { + const contract = new ContractDetailed(buildContractData()); + + expect(contract.termination).toBeUndefined(); + expect(contract.planChange).toBeUndefined(); + expect(contract.nextPossibleDowngradeDate).toBeUndefined(); + expect(contract.nextPossibleUpgradeDate).toBeUndefined(); + expect(contract.nextPossibleTerminationDate).toBeUndefined(); + expect(contract.aggregateReference).toBeUndefined(); + expect(contract.activationDate).toBeUndefined(); + expect(contract.freeTrialUntil).toBeUndefined(); + expect(contract.freeTrialDaysRemaining).toBeUndefined(); + expect(contract.hostingDescription).toBeUndefined(); + }); + + test("has no additional items and a zero domain count when none are provided", () => { + const contract = new ContractDetailed(buildContractData()); + + expect(contract.additionalItems).toEqual([]); + expect(contract.additionalItemsTotalPrice.getAmount()).toBe(0); + expect(contract.domainItemsCount).toBe(0); + }); +}); diff --git a/packages/models/src/contract/Contract/Contract.ts b/packages/models/src/contract/Contract/Contract.ts index 919ddb11..76022c6c 100644 --- a/packages/models/src/contract/Contract/Contract.ts +++ b/packages/models/src/contract/Contract/Contract.ts @@ -1,128 +1,281 @@ +import type { AxiosRequestConfig } from "axios"; + +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; +import { omit } from "remeda"; + +import type { + ContractTerminationCreateRequestData, + ContractListQueryModelData, + ContractListItemData, + ContractData, +} from "./types.js"; + +import { ContractItemReference } from "../ContractItem/ContractItemReference.js"; +import { + ContractItemDetailed, + ContractItemCommon, +} from "../ContractItem/index.js"; +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { ContractTermination } from "../ContractTermination/index.js"; +import { Customer } from "../../customer/Customer/Customer.js"; +import { PlanChange } from "../PlanChange/index.js"; +import { config } from "../../config/index.js"; +import { Money } from "../../common/index.js"; import { - DataModel, - ListDataModel, ListQueryModel, ReferenceModel, + WithListData, + extractId, + WithData, } from "../../base/index.js"; -import { provideReact } from "../../react/index.js"; -import { config } from "../../config/config.js"; -import { classes } from "polytype"; -import assertObjectFound from "../../base/assertObjectFound.js"; -import { - ContractData, - ContractListItemData, - ContractListQueryData, - ContractListQueryModelData, -} from "./types.js"; +@GhostMakerModel({ + name: "Contract", +}) export class Contract extends ReferenceModel { - public static ofId(id: string): Contract { - return new Contract(id); + public static async find(id: string) { + const data = await config.behaviors.contract.find(id); + if (data) { + return new ContractDetailed(data); + } + } + + public static async findByProject( + projectId: string, + requestConfig?: AxiosRequestConfig, + ) { + const data = await config.behaviors.contract.findByProject( + projectId, + requestConfig, + ); + if (data) { + return new ContractDetailed(data); + } } - public static find = provideReact( - async (id: string): Promise => { - const data = await config.behaviors.contract.find(id); - if (data !== undefined) { - return new ContractDetailed(data); - } - }, - ); + public static async findByServer(serverId: string) { + const data = await config.behaviors.contract.findByServer(serverId); + if (data) { + return new ContractDetailed(data); + } + } + + public static async get(id: string) { + const contract = await this.find(id); + assertObjectFound(contract, Contract, id); + return contract; + } + + public static async getByProject(projectId: string) { + const contract = await this.findByProject(projectId); + assertObjectFound(contract, Contract, projectId); + return contract; + } + + public static async getByServer(serverId: string) { + const contract = await this.findByServer(serverId); + assertObjectFound(contract, Contract, serverId); + return contract; + } + + public static ofId(id: string) { + return new Contract(id); + } public static query(query: ContractListQueryModelData) { return new ContractListQuery(query); } - public static get = provideReact( - async (id: string): Promise => { - const customer = await this.find(id); - assertObjectFound(customer, this, id); - return customer; - }, - ); + public async cancelTermination() { + await config.behaviors.contract.cancelTermination(this.id); + } + + public async findCommon(): Promise { + return this instanceof ContractCommon ? this : this.findDetailed(); + } + + public async findDetailed(): Promise { + return Contract.get(this.id); + } + + public async getCommon(): Promise { + return this instanceof ContractCommon ? this : this.getDetailed(); + } + + public async getDetailed(): Promise { + return Contract.get(this.id); + } + + public async terminate(data: ContractTerminationCreateRequestData) { + await config.behaviors.contract.terminate(this.id, data); + } } -class ContractCommon extends classes( - DataModel, - Contract, -) { +export class ContractCommon extends WithData< + ContractListItemData | ContractData +>()(Contract) { + public readonly activationDate?: DateTime; + public readonly additionalItems: ContractItemCommon[]; + public readonly additionalItemsTotalPrice: Money; + public readonly aggregateReference?: ContractItemReference; + public readonly baseItem: ContractItemDetailed; + public readonly customer: Customer; + public override readonly data: ContractListItemData | ContractData; + public readonly description: string; + public readonly domainItemsCount: number; + public readonly freeTrialDaysRemaining?: number; + public readonly freeTrialUntil?: DateTime; + public readonly hostingDescription?: string; + public readonly hostingShortId?: string; + public readonly nextPossibleDowngradeDate?: DateTime; + public readonly nextPossibleTerminationDate?: DateTime; + public readonly nextPossibleUpgradeDate?: DateTime; + public readonly period?: number; + public readonly plan?: string; + public readonly planChange?: PlanChange; + public readonly termination?: ContractTermination; + public constructor(data: ContractListItemData | ContractData) { - super([data], [data.customerId]); + super(data.contractId); + this.data = data; + if (data.termination) { + this.termination = new ContractTermination(data.termination); + } + this.customer = Customer.ofId(data.customerId); + this.additionalItems = data.additionalItems + ? data.additionalItems.map((i) => new ContractItemCommon(this, i)) + : []; + this.additionalItemsTotalPrice = this.additionalItems.reduce( + (total, item) => { + return total.add(item.totalPrice); + }, + Money({ currency: "EUR", amount: 0 }), + ); + this.domainItemsCount = this.additionalItems.filter((i) => + i.articleName.toLowerCase().includes("domain"), + ).length; + this.baseItem = new ContractItemDetailed(this, data.baseItem); + this.plan = this.baseItem.baseArticle?.name; + if (data.baseItem.tariffChange) { + this.planChange = new PlanChange( + this.baseItem, + data.baseItem.tariffChange, + ); + } + this.description = data.baseItem.description; + this.hostingDescription = /"(.*?)"/.exec(this.description)?.[1]; + const descriptionParts = this.description.split(":")[0]?.split(" "); + if (descriptionParts) { + this.hostingShortId = descriptionParts[descriptionParts.length - 1]; + } + + if (data.baseItem.nextPossibleDowngradeDate) { + this.nextPossibleDowngradeDate = DateTime.fromISO( + data.baseItem.nextPossibleDowngradeDate, + { zone: "utc" }, + ); + } + if (data.baseItem.nextPossibleUpgradeDate) { + this.nextPossibleUpgradeDate = DateTime.fromISO( + data.baseItem.nextPossibleUpgradeDate, + { zone: "utc" }, + ); + } + if (data.baseItem.nextPossibleTerminationDate) { + this.nextPossibleTerminationDate = DateTime.fromISO( + data.baseItem.nextPossibleTerminationDate, + { zone: "utc" }, + ); + } + + this.aggregateReference = data.baseItem.aggregateReference + ? new ContractItemReference( + data.baseItem.aggregateReference, + data.customerId, + ) + : undefined; + if (data.baseItem.activationDate) { + this.activationDate = DateTime.fromISO(data.baseItem.activationDate); + } + this.freeTrialUntil = + data.baseItem.isInFreeTrial && + this.activationDate && + this.activationDate.diff(DateTime.now()).toMillis() > 0 + ? this.activationDate + : undefined; + if (this.freeTrialUntil) { + this.freeTrialDaysRemaining = Math.ceil( + this.freeTrialUntil.diff(DateTime.now(), ["days"]).days, + ); + } + this.period = this.baseItem.contractPeriod; + } + + public async cancelPlanChange() { + await config.behaviors.contract.cancelPlanChange(this.id, this.baseItem.id); } } -export class ContractDetailed extends classes( - ContractCommon, - DataModel, -) { +export class ContractDetailed extends ContractCommon { + public override readonly data: ContractData; public constructor(data: ContractData) { - super([data], [data]); + super(data); + this.data = data; } } -export class ContractListItem extends classes( - ContractCommon, - DataModel, -) { +export class ContractListItem extends ContractCommon { + public override readonly data: ContractListItemData; public constructor(data: ContractListItemData) { - super([data], [data]); + super(data); + this.data = data; } } export class ContractListQuery extends ListQueryModel { public constructor(query: ContractListQueryModelData) { - super(query); - } - - public refine(query: ContractListQueryData) { - return new ContractListQuery({ - ...this.query, - ...query, - }); + super(query, { dependencies: [extractId(query.customer)] }); } - public execute = provideReact(async () => { - const { customer, ...query } = this.query; - - const customerId = customer.id; - const request = { - customerId: customerId, - queryParameters: { - limit: config.defaultPaginationLimit, - ...query, - }, - }; - const { items, totalCount } = await config.behaviors.contract.list(request); + public async execute() { + const { totalCount, items } = await config.behaviors.contract.list( + extractId(this.query.customer), + omit(this.query, ["customer"]), + ); return new ContractList( this.query, items.map((d) => new ContractListItem(d)), totalCount, ); - }, [this.queryId]); + } - public getTotalCount = provideReact(async () => { + public async getTotalCount() { const { totalCount } = await this.refine({ limit: 1 }).execute(); return totalCount; - }, [this.queryId]); + } - public findOneAndOnly = provideReact(async () => { - const { items, totalCount } = await this.refine({ limit: 1 }).execute(); - if (totalCount === 1) { - return items[0]; - } - }, [this.queryId]); + public refine(query: Partial = {}) { + return new ContractListQuery({ + ...this.query, + ...query, + }); + } } -export class ContractList extends classes( +export class ContractList extends WithListData()( ContractListQuery, - ListDataModel, ) { + public override readonly items: readonly ContractListItem[]; + public override readonly totalCount: number; public constructor( query: ContractListQueryModelData, contracts: ContractListItem[], totalCount: number, ) { - super([query], [contracts, totalCount]); + super(query); + this.items = Object.freeze(contracts); + this.totalCount = totalCount; } } diff --git a/packages/models/src/contract/Contract/behaviors/api.ts b/packages/models/src/contract/Contract/behaviors/api.ts index 03d6f4bc..26e495b6 100644 --- a/packages/models/src/contract/Contract/behaviors/api.ts +++ b/packages/models/src/contract/Contract/behaviors/api.ts @@ -1,30 +1,89 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { ContractBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; import { - assertStatus, - MittwaldAPIV2Client, - extractTotalCountHeader, -} from "@mittwald/api-client"; -import { ContractBehaviors } from "./types.js"; + withAxiosRequestConfig, + resolveTotalCount, + anyStatus403, +} from "../../../base/index.js"; export const apiContractBehaviors = ( client: MittwaldAPIV2Client, ): ContractBehaviors => ({ - find: async (id) => { - const response = await client.contract.getDetailOfContract({ - contractId: id, + findByProject: async (projectId, requestConfig) => { + const response = await client.contract.getDetailOfContractByProject( + { + projectId, + }, + withAxiosRequestConfig(requestConfig), + ); + + if (response.status === 200) { + return response.data; + } + // API-DRIFT: getDetailOfContractByProject omits 403 in its generated response type, so anyStatus403 (403 as any) is passed (resolve: use the literal 403 once the client type declares it) + validateResponse(response, [404, anyStatus403]); + }, + + findByServer: async (serverId) => { + const response = await client.contract.getDetailOfContractByServer({ + serverId, }); if (response.status === 200) { return response.data; } - assertStatus(response, 404); + // API-DRIFT: getDetailOfContractByServer omits 403 in its generated response type, so anyStatus403 (403 as any) is passed (resolve: use the literal 403 once the client type declares it) + validateResponse(response, [404, anyStatus403]); + }, + + find: async (contractId) => { + const response = await client.contract.getDetailOfContract({ contractId }); + + if (response.status === 200) { + return response.data; + } + // API-DRIFT: getDetailOfContract omits 403 in its generated response type, so anyStatus403 (403 as any) is passed (resolve: use the literal 403 once the client type declares it) + validateResponse(response, [anyStatus403, 404]); }, - list: async (request) => { - const response = await client.contract.listContracts(request); - assertStatus(response, 200); + list: async (customerId, query) => { + const response = await client.contract.listContracts({ + queryParameters: query, + customerId, + }); + validateResponse(response, 200); return { + totalCount: resolveTotalCount(response), items: response.data, - totalCount: extractTotalCountHeader(response), }; }, + + cancelPlanChange: async (contractId, contractItemId) => { + const response = await client.contract.cancelContractTariffChange({ + contractItemId, + contractId, + }); + + validateResponse(response, 200); + }, + + terminate: async (contractId, data) => { + const response = await client.contract.terminateContract({ + contractId, + data, + }); + + validateResponse(response, 201); + }, + + cancelTermination: async (contractId) => { + const response = await client.contract.cancelContractTermination({ + contractId, + }); + + validateResponse(response, 200); + }, }); diff --git a/packages/models/src/contract/Contract/behaviors/types.ts b/packages/models/src/contract/Contract/behaviors/types.ts index 1b12abc7..950e7189 100644 --- a/packages/models/src/contract/Contract/behaviors/types.ts +++ b/packages/models/src/contract/Contract/behaviors/types.ts @@ -1,14 +1,34 @@ -import { - ContractData, - ContractListItemData, +import type { AxiosRequestConfig } from "axios"; + +import type { QueryResponseData } from "../../../base/index.js"; +import type { + ContractTerminationCreateRequestData, ContractListQueryData, + ContractListItemData, + ContractData, } from "../types.js"; -import { QueryResponseData } from "../../../base/index.js"; export interface ContractBehaviors { - find: (id: string) => Promise; - list: (request: { - customerId: string; - queryParameters?: ContractListQueryData; - }) => Promise>; + list: ( + customerId: string, + query?: ContractListQueryData, + ) => Promise>; + findByProject: ( + projectId: string, + requestConfig?: AxiosRequestConfig, + ) => Promise; + terminate: ( + contractId: string, + data: ContractTerminationCreateRequestData, + ) => Promise; + + cancelPlanChange: ( + contractId: string, + contractItemId: string, + ) => Promise; + + findByServer: (serverId: string) => Promise; + find: (contractId: string) => Promise; + + cancelTermination: (contractId: string) => Promise; } diff --git a/packages/models/src/contract/Contract/types.ts b/packages/models/src/contract/Contract/types.ts index 3bbd3abb..d6e339b9 100644 --- a/packages/models/src/contract/Contract/types.ts +++ b/packages/models/src/contract/Contract/types.ts @@ -1,18 +1,22 @@ -import { MittwaldAPIV2 } from "@mittwald/api-client"; -import { Customer } from "../../customer/index.js"; +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import type { Customer } from "../../customer/index.js"; export type ContractListQueryData = - MittwaldAPIV2.Paths.V2ContractsContractId.Get.Parameters.Query; + MittwaldAPIV2.Paths.V2CustomersCustomerIdContracts.Get.Parameters.Query; -export type ContractListQueryModelData = Omit< - ContractListQueryData, - "customerId" -> & { - customer: Customer; -}; +export type ContractListQueryModelData = { + customer: Customer | string; +} & ContractListQueryData; export type ContractData = MittwaldAPIV2.Operations.ContractGetDetailOfContract.ResponseData; export type ContractListItemData = MittwaldAPIV2.Operations.ContractListContracts.ResponseData[number]; + +export type ContractTerminationCreateRequestData = + MittwaldAPIV2.Paths.V2ContractsContractIdTermination.Post.Parameters.RequestBody; + +export type ContractAggregateReference = + MittwaldAPIV2.Components.Schemas.ContractAggregateReference; diff --git a/packages/models/src/contract/ContractArticle/ContractArticle.test.ts b/packages/models/src/contract/ContractArticle/ContractArticle.test.ts new file mode 100644 index 00000000..48bfd4f0 --- /dev/null +++ b/packages/models/src/contract/ContractArticle/ContractArticle.test.ts @@ -0,0 +1,34 @@ +import { afterEach, describe, expect, test } from "vitest"; + +import { buildContractArticleData } from "../../testing/builders/buildContractArticleData.js"; +import { ContractArticle } from "./ContractArticle.js"; +import { resetBehaviors } from "../../testing/index.js"; +import { Article } from "../../article/index.js"; + +afterEach(resetBehaviors); + +describe("ContractArticle", () => { + test("constructs article data and derived prices", () => { + const data = buildContractArticleData({ + unitPrice: { currency: "EUR", value: 1000 }, + articleTemplateId: "template-1", + description: "Description", + name: "Article name", + id: "article-1", + amount: 3, + }); + + const article = new ContractArticle(data); + + expect(article.id).toBe(data.id); + expect(article.articleTemplateId).toBe(data.articleTemplateId); + expect(article.amount).toBe(data.amount); + expect(article.name).toBe(data.name); + expect(article.description).toBe(data.description); + expect(article.article).toBeInstanceOf(Article); + expect(article.article.id).toBe(data.id); + expect(article.unitPrice.getAmount()).toBe(1000); + expect(article.totalPrice.getAmount()).toBe(3000); + expect(article.displayName).toBe("Article name (Description)"); + }); +}); diff --git a/packages/models/src/contract/ContractArticle/ContractArticle.ts b/packages/models/src/contract/ContractArticle/ContractArticle.ts new file mode 100644 index 00000000..a39a0845 --- /dev/null +++ b/packages/models/src/contract/ContractArticle/ContractArticle.ts @@ -0,0 +1,38 @@ +import type { ContractArticleData } from "./types.js"; + +import { StorageArticle, Article } from "../../article/index.js"; +import { DataModel } from "../../base/index.js"; +import { Money } from "../../common/index.js"; + +export class ContractArticle extends DataModel { + public readonly amount: number; + public readonly article: Article; + public readonly articleTemplateId: string; + public readonly description?: string; + public readonly displayName: string; + public readonly id: string; + public readonly name: string; + public readonly totalPrice: Money; + public readonly unitPrice: Money; + + public constructor(data: ContractArticleData) { + super(data); + + this.id = data.id; + this.article = Article.ofId(data.id); + this.articleTemplateId = data.articleTemplateId; + this.unitPrice = Money({ amount: data.unitPrice.value, currency: "EUR" }); + this.totalPrice = this.unitPrice.multiply(data.amount); + this.amount = data.amount; + this.name = data.name; + this.description = data.description; + this.displayName = `${data.name} (${data.description})`; + } + + public async getTotalBytes() { + const article = await Article.get(this.article.id); + if (article instanceof StorageArticle) { + return article.bytes.multiply(this.amount); + } + } +} diff --git a/packages/models/src/contract/ContractArticle/index.ts b/packages/models/src/contract/ContractArticle/index.ts new file mode 100644 index 00000000..f2c5ff8f --- /dev/null +++ b/packages/models/src/contract/ContractArticle/index.ts @@ -0,0 +1,2 @@ +export * from "./ContractArticle.js"; +export * from "./types.js"; diff --git a/packages/models/src/contract/ContractArticle/types.ts b/packages/models/src/contract/ContractArticle/types.ts new file mode 100644 index 00000000..08d94790 --- /dev/null +++ b/packages/models/src/contract/ContractArticle/types.ts @@ -0,0 +1,4 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type ContractArticleData = + MittwaldAPIV2.Components.Schemas.ContractArticle; diff --git a/packages/models/src/contract/ContractItem/ContractItem.test.ts b/packages/models/src/contract/ContractItem/ContractItem.test.ts new file mode 100644 index 00000000..ee1c276a --- /dev/null +++ b/packages/models/src/contract/ContractItem/ContractItem.test.ts @@ -0,0 +1,160 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { buildContractArticleData } from "../../testing/builders/buildContractArticleData.js"; +import { buildContractItemData } from "../../testing/builders/buildContractItemData.js"; +import { buildPlanChangeData } from "../../testing/builders/buildPlanChangeData.js"; +import { buildContractData } from "../../testing/builders/buildContractData.js"; +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { installBehaviors, resetBehaviors } from "../../testing/index.js"; +import { ContractArticle } from "../ContractArticle/index.js"; +import { ContractDetailed } from "../Contract/index.js"; +import { ReferenceModel } from "../../base/index.js"; +import { PlanChange } from "../PlanChange/index.js"; +import { + ContractItemDetailed, + ContractItemCommon, + ContractItem, +} from "./ContractItem.js"; + +afterEach(resetBehaviors); + +function buildContract() { + return new ContractDetailed(buildContractData()); +} + +describe("ContractItem", () => { + test("creates a reference associated with its contract", () => { + const contract = buildContract(); + const item = ContractItem.ofId(contract, "item-1"); + + expect(item).toBeInstanceOf(ContractItem); + expect(item.id).toBe("item-1"); + expect(item.contract).toBe(contract); + }); + + test("find delegates and constructs a detailed item", async () => { + const contract = buildContract(); + const find = vi + .fn() + .mockResolvedValue(buildContractItemData({ itemId: "data-id" })); + installBehaviors({ contractItem: { find } }); + + const item = await ContractItem.find(contract, "requested-id"); + + expect(find).toHaveBeenCalledWith(contract.id, "requested-id"); + expect(item).toBeInstanceOf(ContractItemDetailed); + expect(item?.id).toBe("data-id"); + }); + + test("find returns undefined for missing data", async () => { + const contract = buildContract(); + installBehaviors({ + contractItem: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + ContractItem.find(contract, "missing"), + ).resolves.toBeUndefined(); + }); + + test("mutations delegate with contract and item ids", async () => { + const terminate = vi.fn().mockResolvedValue(undefined); + const cancelTermination = vi.fn().mockResolvedValue(undefined); + const cancelTariffChange = vi.fn().mockResolvedValue(undefined); + installBehaviors({ + contractItem: { cancelTariffChange, cancelTermination, terminate }, + }); + const item = ContractItem.ofId(buildContract(), "item-1"); + const data: Parameters[0] = {}; + + await item.terminate(data); + await item.cancelTermination(); + await item.cancelPlanChange(); + + expect(terminate).toHaveBeenCalledWith("contract-id", "item-1", data); + expect(cancelTermination).toHaveBeenCalledWith("contract-id", "item-1"); + expect(cancelTariffChange).toHaveBeenCalledWith("contract-id", "item-1"); + }); + + test("constructs data and derived item values", () => { + const contract = buildContract(); + const data = buildContractItemData({ + articles: [ + buildContractArticleData({ + articleTemplateId: "matching", + name: "First", + }), + buildContractArticleData({ + articleTemplateId: "other", + name: "Second", + }), + ], + totalPrice: { currency: "EUR", value: 250 }, + tariffChange: buildPlanChangeData(), + description: "Detailed item", + contractPeriod: 24, + isActivated: false, + isBaseItem: false, + itemId: "item-2", + }); + + const item = new ContractItemDetailed(contract, data); + + expect(item.totalPrice.getAmount()).toBe(250); + expect(item.totalYearlyPrice.getAmount()).toBe(3000); + expect(item.articles).toHaveLength(2); + expect(item.articles[0]).toBeInstanceOf(ContractArticle); + expect(item.baseArticle).toBeInstanceOf(ContractArticle); + expect(item.baseArticle?.name).toBe("First"); + expect(item.articleName).toBe("First"); + expect(item.isActivated).toBe(data.isActivated); + expect(item.isBaseItem).toBe(data.isBaseItem); + expect(item.description).toBe(data.description); + expect(item.itemId).toBe(data.itemId); + expect(item.contractPeriod).toBe(data.contractPeriod); + expect(item.planChange).toBeInstanceOf(PlanChange); + expect(item.findArticlesOfTemplate({ templateId: "matching" })).toEqual([ + item.articles[0], + ]); + }); + + test("has no plan change when tariffChange is absent", () => { + const item = new ContractItemDetailed( + buildContract(), + buildContractItemData(), + ); + + expect(item.planChange).toBeUndefined(); + }); + + test("detailed items retain the complete model identity chain", () => { + const item = new ContractItemDetailed( + buildContract(), + buildContractItemData(), + ); + + expect(item).toBeInstanceOf(ContractItemDetailed); + expect(item).toBeInstanceOf(ContractItemCommon); + expect(item).toBeInstanceOf(ContractItem); + expect(item).toBeInstanceOf(ReferenceModel); + expect(item.data).toBeDefined(); + }); + + test("get rejects with ObjectNotFoundError for missing data", async () => { + installBehaviors({ + contractItem: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + ContractItem.get(buildContract(), "missing"), + ).rejects.toBeInstanceOf(ObjectNotFoundError); + }); +}); diff --git a/packages/models/src/contract/ContractItem/ContractItem.ts b/packages/models/src/contract/ContractItem/ContractItem.ts index d4fc7729..06e8bbbb 100644 --- a/packages/models/src/contract/ContractItem/ContractItem.ts +++ b/packages/models/src/contract/ContractItem/ContractItem.ts @@ -1,54 +1,209 @@ -import { classes } from "polytype"; -import { ContractItemData } from "./types.js"; -import { DataModel, ReferenceModel } from "../../base/index.js"; -import { provideReact } from "../../react/index.js"; -import { config } from "../../config/config.js"; -import assertObjectFound from "../../base/assertObjectFound.js"; +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; +import type { PlanChangeRequestData } from "../../order/index.js"; +import type { ContractCommon } from "../Contract/index.js"; +import type { + ContractItemTerminationCreateRequestData, + ContractItemData, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { ContractItemReference } from "./ContractItemReference.js"; +import { ContractTermination } from "../ContractTermination/index.js"; +import { ReferenceModel, WithData } from "../../base/index.js"; +import { ContractArticle } from "../ContractArticle/index.js"; +import { Project } from "../../project/internal.js"; +import { PlanChange } from "../PlanChange/index.js"; +import { config } from "../../config/index.js"; +import { Money } from "../../common/index.js"; +import { Order } from "../../order/index.js"; + +@GhostMakerModel({ + name: "ContractItem", +}) export class ContractItem extends ReferenceModel { - public static ofId(contractId: string, id: string): ContractItem { - return new ContractItem(contractId, id); - } - - public static find = provideReact( - async ( - contractId: string, - contractItemId: string, - ): Promise => { - const data = await config.behaviors.contractItem.find( - contractId, - contractItemId, - ); - if (data !== undefined) { - return new ContractItemDetailed(contractId, data); - } - }, - ); - - public static get = provideReact( - async ( - contractId: string, - contractItemId: string, - ): Promise => { - const item = await this.find(contractId, contractItemId); - assertObjectFound(item, this, contractItemId); - return item; - }, - ); - - public readonly contractId: string; - - public constructor(contractId: string, id: string) { + public readonly contract: ContractCommon; + + public constructor(contract: ContractCommon, id: string) { super(id); - this.contractId = contractId; + this.contract = contract; + } + + public static async find(contract: ContractCommon, contractItemId: string) { + const data = await config.behaviors.contractItem.find( + contract.id, + contractItemId, + ); + if (data) { + return new ContractItemDetailed(contract, data); + } + } + + public static async get(contract: ContractCommon, contractItemId: string) { + const item = await this.find(contract, contractItemId); + assertObjectFound(item, ContractItem, contractItemId); + return item; + } + + public static ofId(contract: ContractCommon, id: string) { + return new ContractItem(contract, id); + } + + public async cancelPlanChange() { + await config.behaviors.contractItem.cancelTariffChange( + this.contract.id, + this.id, + ); + } + + public async cancelTermination() { + await config.behaviors.contractItem.cancelTermination( + this.contract.id, + this.id, + ); + } + + public async createPlanChange(data: PlanChangeRequestData) { + await Order.changePlan(data); + } + + public async findDetailed(): Promise { + return ContractItem.get(this.contract, this.id); + } + + public async getDetailed(): Promise { + return ContractItem.get(this.contract, this.id); + } + + public async terminate(data: ContractItemTerminationCreateRequestData) { + await config.behaviors.contractItem.terminate( + this.contract.id, + this.id, + data, + ); } } -export class ContractItemDetailed extends classes( - DataModel, +export class ContractItemCommon extends WithData()( ContractItem, ) { - public constructor(contractId: string, data: ContractItemData) { - super([data], [contractId, data.itemId]); + public readonly activationDate?: DateTime; + public readonly aggregateReference?: ContractItemReference; + public readonly articleName: string; + public readonly articles: ContractArticle[]; + public readonly baseArticle?: ContractArticle; + public readonly contractPeriod?: number; + public override readonly data: ContractItemData; + public readonly description: string; + public readonly freeTrialDays?: number; + public readonly freeTrialUntil?: DateTime; + public readonly invoiceStop?: DateTime; + public readonly invoicingPeriod?: number; + public readonly isActivated: boolean; + public readonly isBaseItem: boolean; + public readonly itemId: string; + public readonly nextPossibleDowngradeDate?: DateTime; + public readonly nextPossibleTerminationDate?: DateTime; + public readonly nextPossibleUpgradeDate?: DateTime; + public readonly orderDate?: DateTime; + public readonly planChange?: PlanChange; + public readonly project?: Project; + public readonly termination?: ContractTermination; + public readonly totalPrice: Money; + public readonly totalYearlyPrice: Money; + + public constructor(contract: ContractCommon, data: ContractItemData) { + super(contract, data.itemId); + this.data = data; + this.description = data.description; + this.itemId = data.itemId; + this.isActivated = data.isActivated; + this.project = data.groupByProjectId + ? Project.ofId(data.groupByProjectId) + : undefined; + this.isBaseItem = data.isBaseItem; + this.aggregateReference = data.aggregateReference + ? new ContractItemReference(data.aggregateReference, contract.customer.id) + : undefined; + this.totalPrice = Money({ + amount: data.totalPrice.value, + currency: "EUR", + }); + this.totalYearlyPrice = Money({ + amount: this.totalPrice.getAmount() * 12, + currency: "EUR", + }); + this.freeTrialDays = data.freeTrialDays; + if (data.activationDate) { + this.activationDate = DateTime.fromISO(data.activationDate); + } + if (data.nextPossibleDowngradeDate) { + this.nextPossibleDowngradeDate = DateTime.fromISO( + data.nextPossibleDowngradeDate, + ); + } + if (data.nextPossibleTerminationDate) { + this.nextPossibleTerminationDate = DateTime.fromISO( + data.nextPossibleTerminationDate, + ); + } + if (data.nextPossibleUpgradeDate) { + this.nextPossibleUpgradeDate = DateTime.fromISO( + data.nextPossibleUpgradeDate, + ); + } + if (data.orderDate) { + this.orderDate = DateTime.fromISO(data.orderDate); + } + if (data.invoiceStop) { + this.invoiceStop = DateTime.fromISO(data.invoiceStop); + } + if (data.termination) { + this.termination = new ContractTermination(data.termination); + } + if (data.tariffChange) { + this.planChange = new PlanChange(this, data.tariffChange); + } + if (data.contractPeriod) { + this.contractPeriod = data.contractPeriod; + } + if (data.invoicingPeriod) { + this.invoicingPeriod = data.invoicingPeriod; + } + this.freeTrialUntil = + data.isInFreeTrial && + this.activationDate && + this.activationDate.diff(DateTime.now()).toMillis() > 0 + ? this.activationDate + : undefined; + this.articles = data.articles.map( + (articleData) => new ContractArticle(articleData), + ); + this.baseArticle = this.articles[0]; + this.articleName = this.articles[0]?.name ?? ""; + } + + public findArticlesOfTemplate(template: { templateId?: string }) { + return this.articles.filter( + (article) => article.articleTemplateId === template.templateId, + ); + } +} + +export class ContractItemDetailed extends ContractItemCommon { + public readonly articles: ContractArticle[]; + public readonly planChange?: PlanChange; + + public constructor(contract: ContractCommon, data: ContractItemData) { + super(contract, data); + + this.articles = data.articles.map( + (articleData) => new ContractArticle(articleData), + ); + + this.planChange = data.tariffChange + ? new PlanChange(this, data.tariffChange) + : undefined; } } diff --git a/packages/models/src/contract/ContractItem/ContractItemReference.ts b/packages/models/src/contract/ContractItem/ContractItemReference.ts new file mode 100644 index 00000000..c2f297c7 --- /dev/null +++ b/packages/models/src/contract/ContractItem/ContractItemReference.ts @@ -0,0 +1,61 @@ +import type { ContractItemReferenceData } from "./types.js"; + +import { CustomerAIPlan } from "../../ai/CustomerAIPlan/CustomerAIPlan.js"; +import { Certificate } from "../../certificate/Certificate/Certificate.js"; +import { MailAddress } from "../../mail/MailAddress/MailAddress.js"; +import { License } from "../../app/License/License.js"; +import { Domain } from "../../domain/Domain/Domain.js"; +import { Server } from "../../server/Server/Server.js"; +import { Project } from "../../project/internal.js"; +import { DataModel } from "../../base/index.js"; + +export class ContractItemReference extends DataModel { + public readonly aiPlan?: CustomerAIPlan; + public readonly certificate?: Certificate; + public readonly domain?: Domain; + public readonly license?: License; + public readonly mailAddress?: MailAddress; + public readonly project?: Project; + public readonly server?: Server; + + public constructor(data: ContractItemReferenceData, customerId: string) { + super(data); + const { aggregate, domain, id } = data; + if ( + domain.includes(Server.aggregateMetaData.domain) && + aggregate === Server.aggregateMetaData.aggregate + ) { + this.server = Server.ofId(id); + } else if ( + domain.includes(Project.aggregateMetaData.domain) && + aggregate.includes(Project.aggregateMetaData.aggregate) + ) { + this.project = Project.ofId(id); + } else if ( + domain.includes(Domain.aggregateMetaData.domain) && + aggregate.includes(Domain.aggregateMetaData.aggregate) + ) { + this.domain = Domain.ofId(id); + } else if ( + domain.includes(Certificate.aggregateMetaData.domain) && + aggregate === Certificate.aggregateMetaData.aggregate + ) { + this.certificate = Certificate.ofId(id); + } else if ( + domain.includes(MailAddress.aggregateMetaData.domain) && + aggregate === MailAddress.aggregateMetaData.aggregate + ) { + this.mailAddress = MailAddress.ofId(id); + } else if ( + domain.includes(CustomerAIPlan.aggregateMetaData.domain) && + aggregate === CustomerAIPlan.aggregateMetaData.aggregate.toLowerCase() + ) { + this.aiPlan = CustomerAIPlan.ofId(customerId, id); + } else if ( + domain.includes(License.aggregateMetaData.domain) && + aggregate === License.aggregateMetaData.aggregate + ) { + this.license = License.ofId(id); + } + } +} diff --git a/packages/models/src/contract/ContractItem/HostingContractItem.ts b/packages/models/src/contract/ContractItem/HostingContractItem.ts new file mode 100644 index 00000000..e9de74e5 --- /dev/null +++ b/packages/models/src/contract/ContractItem/HostingContractItem.ts @@ -0,0 +1,42 @@ +import type { ContractItemDetailed } from "./ContractItem.js"; + +import { StorageArticleTemplate } from "../../article/Article/templates/StorageArticleTemplate.js"; +import { HostingArticle } from "../../article/Article/internal.js"; +import { type Money, ZeroMoney } from "../../common/index.js"; +import { ReferenceModel } from "../../base/index.js"; + +export class HostingContractItem extends ReferenceModel { + public readonly contractItem: ContractItemDetailed; + public readonly storagePrice: Money; + + protected constructor(contractItem: ContractItemDetailed) { + super(contractItem.id); + this.contractItem = contractItem; + this.storagePrice = this.contractItem + .findArticlesOfTemplate(StorageArticleTemplate) + .reduce((acc, a) => acc.add(a.totalPrice), ZeroMoney); + } + + public static fromContractItem(contractItem: ContractItemDetailed) { + return new HostingContractItem(contractItem); + } + + public async getHostingArticle() { + const article = await this.contractItem.baseArticle!.article.getDetailed(); + return article.asType(HostingArticle); + } + + public async getStorage() { + const article = await this.getHostingArticle(); + + const storageModifierBytes = await article.storageModifier.getBytes(); + + const additionalStorageArticlesCount = this.contractItem + .findArticlesOfTemplate(StorageArticleTemplate) + .reduce((acc, a) => acc + a.amount, 0); + + return storageModifierBytes + .multiply(additionalStorageArticlesCount) + .add(article.baseStorageAttribute.bytes); + } +} diff --git a/packages/models/src/contract/ContractItem/behaviors/api.ts b/packages/models/src/contract/ContractItem/behaviors/api.ts index 9ed8b91d..f9d34066 100644 --- a/packages/models/src/contract/ContractItem/behaviors/api.ts +++ b/packages/models/src/contract/ContractItem/behaviors/api.ts @@ -1,18 +1,46 @@ -import { assertStatus, MittwaldAPIV2Client } from "@mittwald/api-client"; -import { ContractItemBehaviors } from "./types.js"; +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { ContractItemBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; export const apiContractItemBehaviors = ( client: MittwaldAPIV2Client, ): ContractItemBehaviors => ({ find: async (contractId, contractItemId) => { const response = await client.contract.getDetailOfContractItem({ - contractId, contractItemId, + contractId, }); if (response.status === 200) { return response.data; } - assertStatus(response, 404); + validateResponse(response, 404); + }, + + terminate: async (contractId, contractItemId, data) => { + const response = await client.contract.terminateContractItem({ + contractItemId, + contractId, + data, + }); + validateResponse(response, 201); + }, + + cancelTermination: async (contractId, contractItemId) => { + const response = await client.contract.cancelContractItemTermination({ + contractItemId, + contractId, + }); + validateResponse(response, 200); + }, + + cancelTariffChange: async (contractId, contractItemId) => { + const response = await client.contract.cancelContractTariffChange({ + contractItemId, + contractId, + }); + validateResponse(response, 200); }, }); diff --git a/packages/models/src/contract/ContractItem/behaviors/types.ts b/packages/models/src/contract/ContractItem/behaviors/types.ts index cb50cc08..8b5d53c1 100644 --- a/packages/models/src/contract/ContractItem/behaviors/types.ts +++ b/packages/models/src/contract/ContractItem/behaviors/types.ts @@ -1,8 +1,27 @@ -import { ContractItemData } from "../types.js"; +import type { + ContractItemTerminationCreateRequestData, + ContractItemData, +} from "../types.js"; export interface ContractItemBehaviors { + terminate: ( + contractId: string, + contractItemId: string, + data: ContractItemTerminationCreateRequestData, + ) => Promise; + find: ( contractId: string, contractItemId: string, ) => Promise; + + cancelTariffChange: ( + contractId: string, + contractItemId: string, + ) => Promise; + + cancelTermination: ( + contractId: string, + contractItemId: string, + ) => Promise; } diff --git a/packages/models/src/contract/ContractItem/index.ts b/packages/models/src/contract/ContractItem/index.ts index e41367b6..246ad32e 100644 --- a/packages/models/src/contract/ContractItem/index.ts +++ b/packages/models/src/contract/ContractItem/index.ts @@ -1,2 +1,3 @@ export * from "./ContractItem.js"; +export * from "./HostingContractItem.js"; export * from "./types.js"; diff --git a/packages/models/src/contract/ContractItem/types.ts b/packages/models/src/contract/ContractItem/types.ts index bd2b259a..c824f6ef 100644 --- a/packages/models/src/contract/ContractItem/types.ts +++ b/packages/models/src/contract/ContractItem/types.ts @@ -1,4 +1,11 @@ -import { MittwaldAPIV2 } from "@mittwald/api-client"; +import type { MittwaldAPIV2 } from "@mittwald/api-client"; export type ContractItemData = - MittwaldAPIV2.Operations.ContractGetDetailOfContractItem.ResponseData; + MittwaldAPIV2.Components.Schemas.ContractContractItem; + +export type ContractItemReferenceData = NonNullable< + MittwaldAPIV2.Components.Schemas.ContractContractItem["aggregateReference"] +>; + +export type ContractItemTerminationCreateRequestData = + MittwaldAPIV2.Operations.ContractTerminateContractItem.RequestData; diff --git a/packages/models/src/contract/ContractTermination/ContractTermination.ts b/packages/models/src/contract/ContractTermination/ContractTermination.ts new file mode 100644 index 00000000..49c395bf --- /dev/null +++ b/packages/models/src/contract/ContractTermination/ContractTermination.ts @@ -0,0 +1,22 @@ +import { DateTime } from "luxon"; + +import type { ContractTerminationData } from "./types.js"; + +import { DataModel } from "../../base/index.js"; +import { User } from "../../user/index.js"; + +export class ContractTermination extends DataModel { + public readonly cancellationForbidden?: boolean; + public readonly scheduledByUser?: User; + public readonly targetDate: DateTime; + + public constructor(data: ContractTerminationData) { + super(data); + if (data.scheduledByUserId) { + this.scheduledByUser = User.ofId(data.scheduledByUserId); + } + + this.cancellationForbidden = data.cancellationForbidden; + this.targetDate = DateTime.fromISO(data.targetDate); + } +} diff --git a/packages/models/src/contract/ContractTermination/index.ts b/packages/models/src/contract/ContractTermination/index.ts new file mode 100644 index 00000000..c50f474f --- /dev/null +++ b/packages/models/src/contract/ContractTermination/index.ts @@ -0,0 +1 @@ +export * from "./ContractTermination.js"; diff --git a/packages/models/src/contract/ContractTermination/types.ts b/packages/models/src/contract/ContractTermination/types.ts new file mode 100644 index 00000000..175d282a --- /dev/null +++ b/packages/models/src/contract/ContractTermination/types.ts @@ -0,0 +1,4 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type ContractTerminationData = + MittwaldAPIV2.Components.Schemas.ContractTermination; diff --git a/packages/models/src/contract/PlanChange/PlanChange.test.ts b/packages/models/src/contract/PlanChange/PlanChange.test.ts new file mode 100644 index 00000000..45d5bb35 --- /dev/null +++ b/packages/models/src/contract/PlanChange/PlanChange.test.ts @@ -0,0 +1,58 @@ +import { afterEach, describe, expect, test } from "vitest"; +import { DateTime } from "luxon"; + +import { buildContractArticleData } from "../../testing/builders/buildContractArticleData.js"; +import { buildContractItemData } from "../../testing/builders/buildContractItemData.js"; +import { buildPlanChangeData } from "../../testing/builders/buildPlanChangeData.js"; +import { buildContractData } from "../../testing/builders/buildContractData.js"; +import { ContractItemDetailed } from "../ContractItem/index.js"; +import { ContractArticle } from "../ContractArticle/index.js"; +import { resetBehaviors } from "../../testing/index.js"; +import { ContractDetailed } from "../Contract/index.js"; +import { PlanChange } from "./PlanChange.js"; +import { User } from "../../user/index.js"; + +afterEach(resetBehaviors); + +describe("PlanChange", () => { + test("constructs data and derived article values", () => { + const contract = new ContractDetailed(buildContractData()); + const item = new ContractItemDetailed(contract, buildContractItemData()); + const data = buildPlanChangeData({ + newArticles: [ + buildContractArticleData({ + unitPrice: { currency: "EUR", value: 500 }, + amount: 2, + }), + buildContractArticleData({ + unitPrice: { currency: "EUR", value: 750 }, + amount: 1, + }), + ], + scheduledByUserId: "user-id", + isForced: true, + }); + + const planChange = new PlanChange(item, data); + + expect(planChange.contractItem).toBe(item); + expect(planChange.targetDate.toMillis()).toBe( + DateTime.fromISO(data.targetDate).toMillis(), + ); + expect(planChange.articles).toHaveLength(2); + expect(planChange.articles[0]).toBeInstanceOf(ContractArticle); + expect(planChange.totalPrice.getAmount()).toBe(1750); + expect(planChange.isForced).toBe(true); + expect(planChange.scheduledByUser).toBeInstanceOf(User); + expect(planChange.scheduledByUser?.id).toBe("user-id"); + }); + + test("has no scheduled user when no user id is supplied", () => { + const contract = new ContractDetailed(buildContractData()); + const item = new ContractItemDetailed(contract, buildContractItemData()); + + const planChange = new PlanChange(item, buildPlanChangeData()); + + expect(planChange.scheduledByUser).toBeUndefined(); + }); +}); diff --git a/packages/models/src/contract/PlanChange/PlanChange.ts b/packages/models/src/contract/PlanChange/PlanChange.ts new file mode 100644 index 00000000..ad9a03ef --- /dev/null +++ b/packages/models/src/contract/PlanChange/PlanChange.ts @@ -0,0 +1,35 @@ +import { DateTime } from "luxon"; + +import type { ContractItemCommon } from "../ContractItem/index.js"; +import type { PlanChangeData } from "./types.js"; + +import { ContractArticle } from "../ContractArticle/index.js"; +import { type Money, ZeroMoney } from "../../common/index.js"; +import { User } from "../../user/User/User.js"; +import { DataModel } from "../../base/index.js"; + +export class PlanChange extends DataModel { + public readonly articles: ContractArticle[]; + public readonly contractItem: ContractItemCommon; + public readonly isForced?: boolean; + public readonly scheduledByUser?: User; + public readonly targetDate: DateTime; + public readonly totalPrice: Money; + + public constructor(contractItem: ContractItemCommon, data: PlanChangeData) { + super(data); + this.contractItem = contractItem; + if (data.scheduledByUserId) { + this.scheduledByUser = User.ofId(data.scheduledByUserId); + } + this.targetDate = DateTime.fromISO(data.targetDate); + this.isForced = data.isForced; + this.articles = data.newArticles.map( + (article) => new ContractArticle(article), + ); + + this.totalPrice = this.articles.reduce((acc, article) => { + return acc.add(article.totalPrice); + }, ZeroMoney); + } +} diff --git a/packages/models/src/contract/PlanChange/index.ts b/packages/models/src/contract/PlanChange/index.ts new file mode 100644 index 00000000..93981bbd --- /dev/null +++ b/packages/models/src/contract/PlanChange/index.ts @@ -0,0 +1 @@ +export * from "./PlanChange.js"; diff --git a/packages/models/src/contract/PlanChange/types.ts b/packages/models/src/contract/PlanChange/types.ts new file mode 100644 index 00000000..eda63307 --- /dev/null +++ b/packages/models/src/contract/PlanChange/types.ts @@ -0,0 +1,4 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type PlanChangeData = + MittwaldAPIV2.Components.Schemas.ContractTariffChange; diff --git a/packages/models/src/contract/index.ts b/packages/models/src/contract/index.ts index e0c81bef..5d98cff9 100644 --- a/packages/models/src/contract/index.ts +++ b/packages/models/src/contract/index.ts @@ -1,2 +1,5 @@ export * from "./Contract/index.js"; +export * from "./ContractArticle/index.js"; export * from "./ContractItem/index.js"; +export * from "./ContractTermination/index.js"; +export * from "./PlanChange/index.js"; diff --git a/packages/models/src/conversation/Conversation/Conversation.test.ts b/packages/models/src/conversation/Conversation/Conversation.test.ts new file mode 100644 index 00000000..7dc99d0f --- /dev/null +++ b/packages/models/src/conversation/Conversation/Conversation.test.ts @@ -0,0 +1,310 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { AggregateMetaData } from "../../common/index.js"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { buildConversationCategoryData } from "../../testing/builders/buildConversationCategoryData.js"; +import { buildConversationListItemData } from "../../testing/builders/buildConversationListItemData.js"; +import { buildConversationUserData } from "../../testing/builders/buildConversationUserData.js"; +import { buildConversationData } from "../../testing/builders/buildConversationData.js"; +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { installBehaviors, resetBehaviors } from "../../testing/index.js"; +import { ConversationCategory } from "../ConversationCategory/index.js"; +import { ListQueryModel, ReferenceModel } from "../../base/index.js"; +import { ConversationUser } from "../ConversationUser/index.js"; +import { + ConversationListQuery, + ConversationDetailed, + ConversationListItem, + ConversationList, + Conversation, +} from "./Conversation.js"; + +afterEach(resetBehaviors); + +describe("Conversation lookup and mutations", () => { + test("find delegates and materializes a detailed conversation", async () => { + const find = vi + .fn() + .mockResolvedValue(buildConversationData({ conversationId: "c-1" })); + installBehaviors({ conversation: { find } }); + + const result = await Conversation.find("c-1"); + + expect(find).toHaveBeenCalledWith("c-1"); + expect(result).toBeInstanceOf(ConversationDetailed); + expect(result?.id).toBe("c-1"); + }); + + test("find returns undefined when the conversation is missing", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ conversation: { find } }); + + await expect(Conversation.find("missing")).resolves.toBeUndefined(); + }); + + test("get returns a detailed conversation or throws ObjectNotFoundError", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildConversationData({ conversationId: "c-1" })) + .mockResolvedValueOnce(undefined); + installBehaviors({ conversation: { find } }); + + await expect(Conversation.get("c-1")).resolves.toBeInstanceOf( + ConversationDetailed, + ); + await expect(Conversation.get("missing")).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("create delegates and returns a conversation reference", async () => { + const create = vi.fn().mockResolvedValue({ id: "conv-1" }); + installBehaviors({ conversation: { create } }); + const data = { visibility: "private" as const, title: "Help" }; + + const result = await Conversation.create(data); + + expect(create).toHaveBeenCalledWith(data); + expect(result).toBeInstanceOf(Conversation); + expect(result.id).toBe("conv-1"); + }); + + test("updateTitle, updateCategory, and close delegate", async () => { + const update = vi.fn().mockResolvedValue(undefined); + const setConversationStatus = vi.fn().mockResolvedValue(undefined); + installBehaviors({ conversation: { setConversationStatus, update } }); + const conversation = Conversation.ofId("c-1"); + + await conversation.updateTitle("New title"); + await conversation.updateCategory("cat-1"); + await conversation.close(); + + expect(update).toHaveBeenNthCalledWith(1, "c-1", { title: "New title" }); + expect(update).toHaveBeenNthCalledWith(2, "c-1", { categoryId: "cat-1" }); + expect(setConversationStatus).toHaveBeenCalledWith("c-1", "closed"); + }); +}); + +describe("Conversation data and lists", () => { + test.each([ + ["closed", false], + ["open", true], + ] as const)("derives isOpen from %s status", (status, isOpen) => { + const conversation = new ConversationDetailed( + buildConversationData({ title: "Title", status }), + ); + + expect(conversation.title).toBe("Title"); + expect(conversation.isOpen).toBe(isOpen); + expect(conversation.shortId).toBe("CONV-1"); + expect(conversation.mainUser).toBeInstanceOf(ConversationUser); + expect(conversation.createdAt.isValid).toBe(true); + expect(conversation.isPrivat).toBe(true); + }); + + test("query materializes list items and passes the query through", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildConversationListItemData({ conversationId: "c-1" })], + totalCount: 3, + }); + installBehaviors({ conversation: { list } }); + + const result = await Conversation.query().execute(); + + expect(result).toBeInstanceOf(ConversationList); + expect(result.items[0]).toBeInstanceOf(ConversationListItem); + expect(result.totalCount).toBe(3); + expect(list).toHaveBeenCalledWith({}); + }); + + test("refine merges into the query passed to the behavior", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 0, items: [] }); + installBehaviors({ conversation: { list } }); + + await Conversation.query({ limit: 5 }) + .refine({ fullTextSearch: "hello" }) + .execute(); + + expect(list).toHaveBeenCalledWith({ fullTextSearch: "hello", limit: 5 }); + }); + + test("preserves ghostmaker identity", async () => { + const item = new ConversationListItem(buildConversationListItemData()); + expect(item).toBeInstanceOf(ConversationListItem); + expect(item).toBeInstanceOf(Conversation); + expect(item).toBeInstanceOf(ReferenceModel); + expect(item.data).toBeDefined(); + + const list = vi.fn().mockResolvedValue({ totalCount: 0, items: [] }); + installBehaviors({ conversation: { list } }); + const result = await Conversation.query().execute(); + expect(result).toBeInstanceOf(ConversationListQuery); + expect(result).toBeInstanceOf(ListQueryModel); + expect(result.items).toBeDefined(); + }); + + test("lists categories and members through behaviors", async () => { + const listCategories = vi + .fn() + .mockResolvedValue([buildConversationCategoryData()]); + const getMembers = vi.fn().mockResolvedValue([buildConversationUserData()]); + installBehaviors({ conversation: { listCategories, getMembers } }); + + const categories = await Conversation.listCategories(); + const members = await Conversation.ofId("c-1").listMembers(); + + expect(listCategories).toHaveBeenCalledWith(); + expect(categories[0]).toBeInstanceOf(ConversationCategory); + expect(getMembers).toHaveBeenCalledWith("c-1"); + expect(members[0]).toBeInstanceOf(ConversationUser); + }); +}); + +describe("Conversation.findCommon / getCommon", () => { + test("findCommon delegates to the behavior for a bare reference and materializes the common variant", async () => { + const find = vi + .fn() + .mockResolvedValue(buildConversationData({ conversationId: "c-1" })); + installBehaviors({ conversation: { find } }); + + const result = await Conversation.ofId("c-1").findCommon(); + + expect(find).toHaveBeenCalledWith("c-1"); + expect(result).toBeInstanceOf(ConversationDetailed); + expect(result?.id).toBe("c-1"); + }); + + test("findCommon returns undefined for a bare reference when the conversation is missing", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ conversation: { find } }); + + await expect( + Conversation.ofId("missing").findCommon(), + ).resolves.toBeUndefined(); + }); + + test("getCommon delegates for a bare reference and throws ObjectNotFoundError when missing", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildConversationData({ conversationId: "c-1" })) + .mockResolvedValueOnce(undefined); + installBehaviors({ conversation: { find } }); + + await expect(Conversation.ofId("c-1").getCommon()).resolves.toBeInstanceOf( + ConversationDetailed, + ); + await expect( + Conversation.ofId("missing").getCommon(), + ).rejects.toBeInstanceOf(ObjectNotFoundError); + }); +}); + +describe("Conversation common idempotency", () => { + test("findCommon on an already materialized detailed conversation returns itself without hitting the behavior", async () => { + const find = vi.fn(); + installBehaviors({ conversation: { find } }); + const detailed = new ConversationDetailed( + buildConversationData({ conversationId: "c-1" }), + ); + + const result = await detailed.findCommon(); + + expect(result).toBe(detailed); + expect(find).not.toHaveBeenCalled(); + }); + + test("getCommon on an already materialized detailed conversation returns itself without hitting the behavior", async () => { + const find = vi.fn(); + installBehaviors({ conversation: { find } }); + const detailed = new ConversationDetailed( + buildConversationData({ conversationId: "c-1" }), + ); + + const result = await detailed.getCommon(); + + expect(result).toBe(detailed); + expect(find).not.toHaveBeenCalled(); + }); + + test("findCommon on a list item returns itself without hitting the behavior", async () => { + const find = vi.fn(); + installBehaviors({ conversation: { find } }); + const item = new ConversationListItem( + buildConversationListItemData({ conversationId: "c-1" }), + ); + + const result = await item.findCommon(); + + expect(result).toBe(item); + expect(find).not.toHaveBeenCalled(); + }); + + test("getDetailed re-fetches through the behavior even on a materialized conversation", async () => { + const find = vi + .fn() + .mockResolvedValue(buildConversationData({ conversationId: "c-1" })); + installBehaviors({ conversation: { find } }); + const detailed = new ConversationDetailed( + buildConversationData({ conversationId: "c-1" }), + ); + + const refreshed = await detailed.getDetailed(); + + expect(find).toHaveBeenCalledWith("c-1"); + expect(refreshed).toBeInstanceOf(ConversationDetailed); + expect(refreshed).not.toBe(detailed); + }); +}); + +describe("Conversation aggregate metadata and absent optionals", () => { + test("aggregateMetaData pins the conversation domain and aggregate", () => { + expect(Conversation.aggregateMetaData).toBeInstanceOf(AggregateMetaData); + expect(Conversation.aggregateMetaData.domain).toBe("conversation"); + expect(Conversation.aggregateMetaData.aggregate).toBe("conversation"); + }); + + test("derived optional getters are undefined when the source data omits them", () => { + const conversation = new ConversationDetailed(buildConversationData()); + + expect(conversation.createdBy).toBeUndefined(); + expect(conversation.relation).toBeUndefined(); + expect(conversation.lastMessageAt).toBeUndefined(); + expect(conversation.lastMessageBy).toBeUndefined(); + expect(conversation.category).toBeUndefined(); + expect(conversation.sharedWith).toBeUndefined(); + expect(conversation.isPrivat).toBe(true); + }); + + test("derived optional getters materialize when the source data provides them", () => { + const conversation = new ConversationDetailed( + buildConversationData({ + lastMessage: { + createdBy: buildConversationUserData({ userId: "author" }), + createdAt: "2024-02-02T00:00:00.000Z", + }, + sharedWith: { + aggregate: "project", + domain: "project", + id: "p-1", + }, + createdBy: buildConversationUserData({ userId: "creator" }), + category: buildConversationCategoryData(), + }), + ); + + expect(conversation.createdBy).toBeInstanceOf(ConversationUser); + expect(conversation.lastMessageAt?.isValid).toBe(true); + expect(conversation.lastMessageBy).toBeInstanceOf(ConversationUser); + expect(conversation.category).toBeInstanceOf(ConversationCategory); + expect(conversation.sharedWith).toBeDefined(); + expect(conversation.isPrivat).toBe(false); + }); +}); diff --git a/packages/models/src/conversation/Conversation/Conversation.ts b/packages/models/src/conversation/Conversation/Conversation.ts new file mode 100644 index 00000000..08c30754 --- /dev/null +++ b/packages/models/src/conversation/Conversation/Conversation.ts @@ -0,0 +1,321 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; + +import type { ConversationUserListQuery as ConversationUserListQueryType } from "../ConversationUser/index.js"; +import type { ConversationCategoryReferenceType } from "../ConversationCategory/index.js"; +import type { FileAccessTokenProvider, DomFile } from "../../file/index.js"; +import type { + ConversationCreateMessageRequestModelData, + ConversationShareableAggregateReference, + ConversationRelatedAggregateReference, + ConversationAggregateReference, + ConversationCreateRequest, + ConversationListQueryData, + ConversationListItemData, + ConversationData, +} from "./types.js"; + +import { ConversationMessageFileAttachmentAccessTokenProvider } from "../ConversationMessage/ConversationMessageFileAttachmentAccessTokenProvider.js"; +import { ConversationServiceRequest } from "../ConversationServiceRequest/index.js"; +import { ConversationStatusUpdate } from "../ConversationStatusUpdate/index.js"; +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { ConversationCategory } from "../ConversationCategory/index.js"; +import { ConversationMessage } from "../ConversationMessage/index.js"; +import { FileUploadError } from "../../errors/index.js"; +import { config } from "../../config/index.js"; +import { File } from "../../file/index.js"; +import { User } from "../../user/index.js"; +import { + ConversationUserListQuery, + ConversationUser, +} from "../ConversationUser/index.js"; +import { + tryResolveAggregateReference, + type AggregateReference, + AggregateMetaData, +} from "../../common/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "Conversation", +}) +export class Conversation extends ReferenceModel { + public static aggregateMetaData = new AggregateMetaData( + "conversation", + "conversation", + ); + public readonly fileAccessTokenProvider: FileAccessTokenProvider; + + public readonly users: ConversationUserListQueryType; + + public constructor(id: string) { + super(id); + this.fileAccessTokenProvider = + new ConversationMessageFileAttachmentAccessTokenProvider(this); + this.users = new ConversationUserListQuery(this); + } + + public static async create(data: ConversationCreateRequest) { + const response = await config.behaviors.conversation.create({ + ...data, + sharedWith: data.sharedWith as ConversationShareableAggregateReference, + relatedTo: data.relatedTo as ConversationRelatedAggregateReference, + }); + + return Conversation.ofId(response.id); + } + + public static async find(id: string) { + const data = await config.behaviors.conversation.find(id); + if (data) { + return new ConversationDetailed(data); + } + } + + public static async get(id: string) { + const conversation = await Conversation.find(id); + assertObjectFound(conversation, Conversation, id); + return conversation; + } + + public static async listCategories() { + const response = await config.behaviors.conversation.listCategories(); + return response.map((c) => new ConversationCategory(c)); + } + + public static async listRelatedCategories( + relationType: ConversationCategoryReferenceType[number], + ) { + const categories = await Conversation.listCategories(); + return categories.filter((c) => + c.data.referenceType.find((t) => t === relationType), + ); + } + + public static ofId(id: string) { + return new Conversation(id); + } + + public static query(query: ConversationListQueryData = {}) { + return new ConversationListQuery(query); + } + + public async close() { + await config.behaviors.conversation.setConversationStatus( + this.id, + "closed", + ); + } + + public async createMessage( + data: ConversationCreateMessageRequestModelData, + onProgress?: (file: DomFile, percent: number) => void, + ) { + const { files, ...restData } = data; + + const uploadedFiles = files + ? await this.uploadFiles(files, onProgress) + : []; + + await config.behaviors.conversation.createMessage(this.id, { + ...restData, + fileIds: uploadedFiles.map((f) => f.id), + }); + } + + public async findCommon(): Promise { + return this instanceof ConversationCommon ? this : this.findDetailed(); + } + + public async findDetailed(): Promise { + return Conversation.find(this.id); + } + + public async getCommon(): Promise { + return this instanceof ConversationCommon ? this : this.getDetailed(); + } + + public async getDetailed(): Promise { + return Conversation.get(this.id); + } + + public async listMembers() { + const data = await config.behaviors.conversation.getMembers(this.id); + return data.map((d) => new ConversationUser(d)); + } + + public async listMessages() { + const data = await config.behaviors.conversation.listMessages(this.id); + return data.map((d) => + d.type === "STATUS_UPDATE" + ? new ConversationStatusUpdate(d) + : d.type === "SERVICE_REQUEST" + ? new ConversationServiceRequest(d) + : new ConversationMessage(d), + ); + } + + public async updateCategory(categoryId: string) { + await config.behaviors.conversation.update(this.id, { categoryId }); + } + + public async updateRelation(relatedTo: ConversationAggregateReference) { + await config.behaviors.conversation.update(this.id, { + relatedTo: relatedTo as ConversationRelatedAggregateReference, + }); + } + + public async updateTitle(title: string) { + await config.behaviors.conversation.update(this.id, { title }); + } + + public async uploadFiles( + files: ArrayLike | null, + onProgress?: (file: DomFile, percent: number) => void, + ) { + const entries = Array.from(files ?? []); + const results = await Promise.allSettled( + entries.map((f) => + File.upload(f, this.fileAccessTokenProvider, undefined, (percent) => + onProgress?.(f, percent), + ), + ), + ); + + const failures = results.flatMap((result, index) => + result.status === "rejected" + ? [{ file: entries[index], error: result.reason }] + : [], + ); + + if (failures.length > 0) { + throw new FileUploadError(failures); + } + + return results.map((result) => { + if (result.status === "fulfilled") { + return result.value; + } + + throw result.reason; + }); + } +} + +export class ConversationCommon extends WithData< + ConversationListItemData | ConversationData +>()(Conversation) { + public readonly category?: ConversationCategory; + public readonly createdAt: DateTime; + public readonly createdBy?: ConversationUser; + public override readonly data: ConversationListItemData | ConversationData; + public readonly isOpen: boolean; + public readonly isPrivat: boolean; + public readonly lastMessageAt?: DateTime; + public readonly lastMessageBy?: ConversationUser; + public readonly mainUser: ConversationUser; + public readonly relation?: AggregateReference; + public readonly sharedWith?: AggregateReference; + public readonly shortId: string; + public readonly title: string; + + public constructor(data: ConversationListItemData | ConversationData) { + super(data.conversationId); + this.data = data; + this.title = data.title; + this.mainUser = new ConversationUser(data.mainUser); + this.relation = data.relatedTo + ? tryResolveAggregateReference({ + ...data.relatedTo, + parent: data.relations?.[0], + }) + : undefined; + this.createdAt = DateTime.fromISO(data.createdAt); + if (data.createdBy) { + this.createdBy = new ConversationUser(data.createdBy); + } + if (data.lastMessage) { + this.lastMessageAt = DateTime.fromISO(data.lastMessage.createdAt); + } + if (data.lastMessage?.createdBy) { + this.lastMessageBy = new ConversationUser(data.lastMessage.createdBy); + } + this.category = data.category + ? new ConversationCategory(data.category) + : undefined; + this.isOpen = data.status !== "closed"; + this.sharedWith = data.sharedWith + ? tryResolveAggregateReference(data.sharedWith) + : undefined; + this.shortId = data.shortId; + this.isPrivat = + !data.sharedWith || + data.sharedWith.aggregate === User.aggregateMetaData.aggregate; + } +} + +export class ConversationDetailed extends ConversationCommon { + public override readonly data: ConversationData; + public constructor(data: ConversationData) { + super(data); + this.data = data; + } +} + +export class ConversationListItem extends ConversationCommon { + public override readonly data: ConversationListItemData; + public constructor(data: ConversationListItemData) { + super(data); + this.data = data; + } +} + +export class ConversationListQuery extends ListQueryModel { + public constructor(query: ConversationListQueryData = {}) { + super(query); + } + + public async execute() { + const { totalCount, items } = await config.behaviors.conversation.list( + this.query, + ); + return new ConversationList( + this.query, + items.map((d) => new ConversationListItem(d)), + totalCount, + ); + } + + public async getTotalCount() { + const { totalCount } = await this.refine({ limit: 1 }).execute(); + return totalCount; + } + + public refine(query: ConversationListQueryData) { + return new ConversationListQuery({ + ...this.query, + ...query, + }); + } +} + +export class ConversationList extends WithListData()( + ConversationListQuery, +) { + public override readonly items: readonly ConversationListItem[]; + public override readonly totalCount: number; + public constructor( + query: ConversationListQueryData, + conversations: ConversationListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(conversations); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/conversation/Conversation/behaviors/api.ts b/packages/models/src/conversation/Conversation/behaviors/api.ts new file mode 100644 index 00000000..79348883 --- /dev/null +++ b/packages/models/src/conversation/Conversation/behaviors/api.ts @@ -0,0 +1,143 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { ConversationBehaviors } from "./types.js"; + +import { + withAxiosRequestConfig, + resolveTotalCount, +} from "../../../base/index.js"; +import { validateResponse } from "../../../base/api/validateResponse.js"; + +export const apiConversationBehaviors = ( + client: MittwaldAPIV2Client, +): ConversationBehaviors => ({ + createFileUploadToken: async (conversationId) => { + const response = await client.conversation.requestFileUpload( + { + conversationId, + }, + withAxiosRequestConfig({ + retryCache: { + dedupe: false, + cache: false, + }, + }), + ); + validateResponse(response, 201); + + return { + token: response.data.uploadToken, + rules: response.data.rules, + }; + }, + + createMessage: async (conversationId, data) => { + const response = await client.conversation.createMessage({ + conversationId, + data, + }); + validateResponse(response, 201, { + validationError: { + typeMappings: { + minimum: "messageOrFileRequired", + }, + pathMappings: { + fileIds: "files", + }, + }, + }); + }, + + getFileDownloadToken: async (fileId, conversationId, requestConfig) => { + const response = await client.conversation.getFileAccessToken( + { + conversationId, + fileId, + }, + withAxiosRequestConfig(requestConfig), + ); + validateResponse(response, 200); + + return response.data; + }, + + list: async (query) => { + const response = await client.conversation.listConversations({ + queryParameters: query, + }); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + updateMessage: async (conversationId, messageId, content) => { + const response = await client.conversation.updateMessage({ + data: { messageContent: content }, + conversationId, + messageId, + }); + validateResponse(response, 200); + }, + + find: async (conversationId) => { + const response = await client.conversation.getConversation({ + conversationId, + }); + if (response.status === 200) { + return response.data; + } + validateResponse(response, [403, 404]); + }, + + setConversationStatus: async (conversationId, status) => { + const response = await client.conversation.setConversationStatus({ + data: { status }, + conversationId, + }); + validateResponse(response, 200); + }, + + listMessages: async (conversationId) => { + const response = await client.conversation.listMessagesByConversation({ + conversationId, + }); + validateResponse(response, 200); + + return response.data; + }, + + getMembers: async (conversationId) => { + const response = await client.conversation.getConversationMembers({ + conversationId, + }); + + validateResponse(response, 200); + + return response.data; + }, + + create: async (data) => { + const response = await client.conversation.createConversation({ + data, + }); + validateResponse(response, 201); + return { id: response.data.conversationId }; + }, + + update: async (conversationId, data) => { + const response = await client.conversation.updateConversation({ + conversationId, + data, + }); + validateResponse(response, 200); + }, + + listCategories: async () => { + const response = await client.conversation.listCategories(); + validateResponse(response, 200); + + return response.data; + }, +}); diff --git a/packages/models/src/conversation/Conversation/behaviors/index.ts b/packages/models/src/conversation/Conversation/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/conversation/Conversation/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/conversation/Conversation/behaviors/types.ts b/packages/models/src/conversation/Conversation/behaviors/types.ts new file mode 100644 index 00000000..93926c0d --- /dev/null +++ b/packages/models/src/conversation/Conversation/behaviors/types.ts @@ -0,0 +1,54 @@ +import type { AxiosRequestConfig } from "axios"; + +import type { ConversationCategoryListItemData } from "../../ConversationCategory/types.js"; +import type { + FileDownloadTokenData, + FileUploadTokenData, +} from "../../../file/index.js"; +import type { ConversationMemberData } from "../../ConversationUser/types.js"; +import type { QueryResponseData } from "../../../base/index.js"; +import type { + ConversationCreateMessageRequestData, + ConversationMessageResponseData, + ConversationCreateRequestData, + ConversationStatusRequestData, + ConversationUpdateRequestData, + ConversationListQueryData, + ConversationListItemData, + ConversationData, +} from "../types.js"; + +export interface ConversationBehaviors { + getFileDownloadToken: ( + fileId: string, + conversationId: string, + requestConfig?: AxiosRequestConfig, + ) => Promise; + setConversationStatus: ( + conversationId: string, + status: ConversationStatusRequestData, + ) => Promise; + createMessage: ( + conversationId: string, + data: ConversationCreateMessageRequestData, + ) => Promise; + updateMessage: ( + conversationId: string, + messageId: string, + content: string, + ) => Promise; + list: ( + query?: ConversationListQueryData, + ) => Promise>; + listMessages: ( + conversationId: string, + ) => Promise; + createFileUploadToken: ( + conversationId: string, + ) => Promise; + update: (id: string, data: ConversationUpdateRequestData) => Promise; + getMembers: (conversationId: string) => Promise; + create: (data: ConversationCreateRequestData) => Promise<{ id: string }>; + find: (conversationId: string) => Promise; + listCategories: () => Promise; +} diff --git a/packages/models/src/conversation/Conversation/index.ts b/packages/models/src/conversation/Conversation/index.ts new file mode 100644 index 00000000..7fe876c6 --- /dev/null +++ b/packages/models/src/conversation/Conversation/index.ts @@ -0,0 +1,2 @@ +export * from "./Conversation.js"; +export * from "./types.js"; diff --git a/packages/models/src/conversation/Conversation/types.ts b/packages/models/src/conversation/Conversation/types.ts new file mode 100644 index 00000000..957d8902 --- /dev/null +++ b/packages/models/src/conversation/Conversation/types.ts @@ -0,0 +1,48 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import type { DomFile } from "../../file/index.js"; + +export type ConversationData = + MittwaldAPIV2.Operations.ConversationGetConversation.ResponseData; + +export type ConversationListItemData = + MittwaldAPIV2.Operations.ConversationListConversations.ResponseData[number]; + +export type ConversationCreateRequestData = + MittwaldAPIV2.Paths.V2Conversations.Post.Parameters.RequestBody; + +export type ConversationAggregateReference = + MittwaldAPIV2.Components.Schemas.ConversationAggregateReference; + +export type ConversationCreateRequest = { + sharedWith?: ConversationAggregateReference; + relatedTo?: ConversationAggregateReference; +} & Omit; + +export type ConversationShareableAggregateReference = + MittwaldAPIV2.Components.Schemas.ConversationShareableAggregateReference; + +export type ConversationRelatedAggregateReference = + MittwaldAPIV2.Components.Schemas.ConversationRelatedAggregateReference; + +export type ConversationUpdateRequestData = + MittwaldAPIV2.Paths.V2ConversationsConversationId.Put.Parameters.RequestBody; + +export type ConversationCreateMessageRequestData = + MittwaldAPIV2.Paths.V2ConversationsConversationIdMessages.Post.Parameters.RequestBody; + +export type ConversationCreateMessageRequestModelData = Omit< + ConversationCreateMessageRequestData, + "fileIds" +> & { + files?: ArrayLike | null; +}; + +export type ConversationListQueryData = + MittwaldAPIV2.Paths.V2Conversations.Get.Parameters.Query; + +export type ConversationStatusRequestData = + MittwaldAPIV2.Paths.V2ConversationsConversationIdStatus.Put.Parameters.RequestBody["status"]; + +export type ConversationMessageResponseData = + MittwaldAPIV2.Operations.ConversationListMessagesByConversation.ResponseData[number]; diff --git a/packages/models/src/conversation/ConversationCategory/ConversationCategory.test.ts b/packages/models/src/conversation/ConversationCategory/ConversationCategory.test.ts new file mode 100644 index 00000000..53fa1c15 --- /dev/null +++ b/packages/models/src/conversation/ConversationCategory/ConversationCategory.test.ts @@ -0,0 +1,31 @@ +import { afterEach, describe, expect, test } from "vitest"; + +import { buildConversationCategoryData } from "../../testing/builders/buildConversationCategoryData.js"; +import { ConversationCategory } from "./ConversationCategory.js"; +import { resetBehaviors } from "../../testing/index.js"; +import { DataModel } from "../../base/index.js"; + +afterEach(resetBehaviors); + +describe("ConversationCategory", () => { + test("maps category data", () => { + const category = new ConversationCategory( + buildConversationCategoryData({ + referenceType: ["extensionInstance"], + categoryId: "cat-1", + name: "Apps", + }), + ); + + expect(category.id).toBe("cat-1"); + expect(category.name).toBe("Apps"); + expect(category.referenceType).toEqual(["extensionInstance"]); + expect(category).toBeInstanceOf(DataModel); + }); + + test("exposes stable category identifiers", () => { + expect(ConversationCategory.appCategoryId).toEqual(expect.any(String)); + expect(ConversationCategory.appCategoryId).not.toHaveLength(0); + expect(ConversationCategory.generalCategoryId).not.toHaveLength(0); + }); +}); diff --git a/packages/models/src/conversation/ConversationCategory/ConversationCategory.ts b/packages/models/src/conversation/ConversationCategory/ConversationCategory.ts new file mode 100644 index 00000000..104c3506 --- /dev/null +++ b/packages/models/src/conversation/ConversationCategory/ConversationCategory.ts @@ -0,0 +1,44 @@ +import type { + ConversationCategoryReferenceType, + ConversationCategoryData, +} from "./types.js"; + +import { DataModel } from "../../base/index.js"; + +export class ConversationCategory extends DataModel { + public static readonly aiHostingCategoryId = + "0e3c0ace-869c-4869-9462-18dd190c9bea"; + public static readonly appCategoryId = "b1c735fd-185b-4e50-bb68-36daf6778c85"; + public static readonly articleCategoryId = + "d011822d-9411-440f-a659-6a39d7ed8203"; + public static readonly containerCategoryId = + "3a15b987-0f7f-4167-a2f7-eb6960d418f2"; + public static readonly databaseCategoryId = + "359b512b-1775-4f7d-8832-c64e78a94e1a"; + public static readonly domainCategoryId = + "43181e29-0268-4570-9dca-e5988b1d33bf"; + public static readonly extensionCategoryId = + "1b761a9d-cc93-41fd-becb-8858f7a67d10"; + public static readonly generalCategoryId = + "44bf568f-fb45-4b89-b810-bf558535b09d"; + public static readonly invoiceCategoryId = + "a678478b-8377-4c63-a596-7602fc5c136f"; + public static readonly leadFyndrCategoryId = + "5fa4c7e4-dfaa-4d81-9e99-54554fb74819"; + public static readonly mailCategoryId = + "b6ba8b8e-b137-4430-950b-10a40a239e0c"; + public static readonly relocationCategoryId = + "6014d6a6-75dc-43f6-8086-755436b9dfe4"; + public static readonly sshCategoryId = "9e86970d-3fc5-4395-901c-cb1db3571939"; + + public readonly id: string; + public readonly name: string; + public readonly referenceType: ConversationCategoryReferenceType; + + public constructor(data: ConversationCategoryData) { + super(data); + this.id = data.categoryId; + this.name = data.name; + this.referenceType = data.referenceType; + } +} diff --git a/packages/models/src/conversation/ConversationCategory/index.ts b/packages/models/src/conversation/ConversationCategory/index.ts new file mode 100644 index 00000000..54f556a2 --- /dev/null +++ b/packages/models/src/conversation/ConversationCategory/index.ts @@ -0,0 +1,2 @@ +export * from "./ConversationCategory.js"; +export * from "./types.js"; diff --git a/packages/models/src/conversation/ConversationCategory/types.ts b/packages/models/src/conversation/ConversationCategory/types.ts new file mode 100644 index 00000000..d65c82ef --- /dev/null +++ b/packages/models/src/conversation/ConversationCategory/types.ts @@ -0,0 +1,10 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type ConversationCategoryListItemData = + MittwaldAPIV2.Operations.ConversationListCategories.ResponseData[number]; + +export type ConversationCategoryData = + MittwaldAPIV2.Components.Schemas.ConversationCategory; + +export type ConversationCategoryReferenceType = + MittwaldAPIV2.Components.Schemas.ConversationCategoryReferenceType; diff --git a/packages/models/src/conversation/ConversationMessage/ConversationMessage.test.ts b/packages/models/src/conversation/ConversationMessage/ConversationMessage.test.ts new file mode 100644 index 00000000..aab0df45 --- /dev/null +++ b/packages/models/src/conversation/ConversationMessage/ConversationMessage.test.ts @@ -0,0 +1,70 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { buildConversationMessageData } from "../../testing/builders/buildConversationMessageData.js"; +import { buildConversationUserData } from "../../testing/builders/buildConversationUserData.js"; +import { installBehaviors, resetBehaviors } from "../../testing/index.js"; +import { ConversationMessage } from "./ConversationMessage.js"; +import { ConversationUser } from "../ConversationUser/index.js"; +import { File } from "../../file/File/internal.js"; +import { DataModel } from "../../base/index.js"; + +afterEach(resetBehaviors); + +describe("ConversationMessage", () => { + test("maps message data and its creator", () => { + const message = new ConversationMessage( + buildConversationMessageData({ + createdBy: buildConversationUserData(), + conversationId: "c-1", + messageContent: "Hi", + messageId: "m-1", + }), + ); + + expect(message.id).toBe("m-1"); + expect(message.content).toBe("Hi"); + expect(message.createdAt.isValid).toBe(true); + expect(message.conversation.id).toBe("c-1"); + expect(message.createdBy).toBeInstanceOf(ConversationUser); + expect(message).toBeInstanceOf(DataModel); + }); + + test("leaves an absent creator undefined", () => { + expect( + new ConversationMessage( + buildConversationMessageData({ createdBy: undefined }), + ).createdBy, + ).toBeUndefined(); + }); + + test("maps only uploaded files and defaults to an empty list", () => { + const message = new ConversationMessage( + buildConversationMessageData({ + files: [ + { status: "uploaded", id: "f-1", name: "a", type: "x" }, + { status: "requested", id: "f-2" }, + ], + }), + ); + + expect(message.files).toHaveLength(1); + expect(message.files[0]).toBeInstanceOf(File); + expect( + new ConversationMessage( + buildConversationMessageData({ files: undefined }), + ).files, + ).toEqual([]); + }); + + test("update delegates with conversation and message identifiers", async () => { + const updateMessage = vi.fn().mockResolvedValue(undefined); + installBehaviors({ conversation: { updateMessage } }); + const message = new ConversationMessage( + buildConversationMessageData({ conversationId: "c-1", messageId: "m-1" }), + ); + + await message.update("Updated"); + + expect(updateMessage).toHaveBeenCalledWith("c-1", "m-1", "Updated"); + }); +}); diff --git a/packages/models/src/conversation/ConversationMessage/ConversationMessage.ts b/packages/models/src/conversation/ConversationMessage/ConversationMessage.ts new file mode 100644 index 00000000..74e3e907 --- /dev/null +++ b/packages/models/src/conversation/ConversationMessage/ConversationMessage.ts @@ -0,0 +1,52 @@ +import { DateTime } from "luxon"; + +import type { + ConversationMessageFileData, + ConversationMessageData, +} from "./types.js"; + +import { ConversationUser } from "../ConversationUser/index.js"; +import { File } from "../../file/File/internal.js"; +import { Conversation } from "../Conversation/index.js"; +import { DataModel } from "../../base/index.js"; +import { config } from "../../config/index.js"; + +export class ConversationMessage extends DataModel { + public readonly content?: string; + public readonly conversation: Conversation; + public readonly createdAt: DateTime; + public readonly createdBy?: ConversationUser; + public readonly files: File[] = []; + public readonly id: string; + + public constructor(data: ConversationMessageData) { + super(data); + this.id = data.messageId; + this.conversation = Conversation.ofId(data.conversationId); + this.createdAt = DateTime.fromISO(data.createdAt); + this.createdBy = data.createdBy + ? new ConversationUser(data.createdBy) + : undefined; + this.files = + data.files + ?.filter( + (f): f is ConversationMessageFileData => f.status === "uploaded", + ) + .map( + (f) => new File(f.id, this.conversation.fileAccessTokenProvider), + ) ?? []; + this.content = data.messageContent; + } + + public static async getUploadRules() { + return File.getUploadRules("conversation"); + } + + public async update(content: string) { + await config.behaviors.conversation.updateMessage( + this.data.conversationId, + this.id, + content, + ); + } +} diff --git a/packages/models/src/conversation/ConversationMessage/ConversationMessageFileAttachmentAccessTokenProvider.ts b/packages/models/src/conversation/ConversationMessage/ConversationMessageFileAttachmentAccessTokenProvider.ts new file mode 100644 index 00000000..0e61c3a5 --- /dev/null +++ b/packages/models/src/conversation/ConversationMessage/ConversationMessageFileAttachmentAccessTokenProvider.ts @@ -0,0 +1,28 @@ +import type { AxiosRequestConfig } from "axios"; + +import type { FileAccessTokenProvider } from "../../file/index.js"; +import type { Conversation } from "../Conversation/index.js"; + +import { config } from "../../config/index.js"; + +export class ConversationMessageFileAttachmentAccessTokenProvider implements FileAccessTokenProvider { + public readonly conversation: Conversation; + + public constructor(message: Conversation) { + this.conversation = message; + } + + public createUploadToken() { + return config.behaviors.conversation.createFileUploadToken( + this.conversation.id, + ); + } + + public getDownloadToken(fileId: string, requestConfig?: AxiosRequestConfig) { + return config.behaviors.conversation.getFileDownloadToken( + fileId, + this.conversation.id, + requestConfig, + ); + } +} diff --git a/packages/models/src/conversation/ConversationMessage/index.ts b/packages/models/src/conversation/ConversationMessage/index.ts new file mode 100644 index 00000000..1b710a5a --- /dev/null +++ b/packages/models/src/conversation/ConversationMessage/index.ts @@ -0,0 +1,2 @@ +export * from "./ConversationMessage.js"; +export * from "./types.js"; diff --git a/packages/models/src/conversation/ConversationMessage/types.ts b/packages/models/src/conversation/ConversationMessage/types.ts new file mode 100644 index 00000000..e2eba769 --- /dev/null +++ b/packages/models/src/conversation/ConversationMessage/types.ts @@ -0,0 +1,7 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type ConversationMessageData = + MittwaldAPIV2.Components.Schemas.ConversationMessage; + +export type ConversationMessageFileData = + MittwaldAPIV2.Components.Schemas.ConversationUploadedFile; diff --git a/packages/models/src/conversation/ConversationServiceRequest/ConversationServiceRequest.ts b/packages/models/src/conversation/ConversationServiceRequest/ConversationServiceRequest.ts new file mode 100644 index 00000000..4da2c07e --- /dev/null +++ b/packages/models/src/conversation/ConversationServiceRequest/ConversationServiceRequest.ts @@ -0,0 +1,30 @@ +import { DateTime } from "luxon"; + +import type { + ConversationServiceRequestRelocationPayloadData, + ConversationServiceRequestData, +} from "./types.js"; + +import { Conversation } from "../Conversation/index.js"; +import { DataModel } from "../../base/index.js"; + +export class ConversationServiceRequest extends DataModel { + public readonly conversation: Conversation; + public readonly createdAt: DateTime; + public readonly payload: ConversationServiceRequestData["meta"]; + public readonly type: ConversationServiceRequestData["messageContent"]; + + public constructor(data: ConversationServiceRequestData) { + super(data); + this.conversation = Conversation.ofId(data.conversationId); + this.createdAt = DateTime.fromISO(data.createdAt); + this.type = data.messageContent; + this.payload = data.meta; + } + + public isRelocationRequest(): this is { + payload: ConversationServiceRequestRelocationPayloadData; + } & ConversationServiceRequest { + return this.type === "relocation"; + } +} diff --git a/packages/models/src/conversation/ConversationServiceRequest/index.ts b/packages/models/src/conversation/ConversationServiceRequest/index.ts new file mode 100644 index 00000000..e3ed8ad3 --- /dev/null +++ b/packages/models/src/conversation/ConversationServiceRequest/index.ts @@ -0,0 +1,2 @@ +export * from "./ConversationServiceRequest.js"; +export * from "./types.js"; diff --git a/packages/models/src/conversation/ConversationServiceRequest/types.ts b/packages/models/src/conversation/ConversationServiceRequest/types.ts new file mode 100644 index 00000000..189ed82b --- /dev/null +++ b/packages/models/src/conversation/ConversationServiceRequest/types.ts @@ -0,0 +1,6 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; +export type ConversationServiceRequestData = + MittwaldAPIV2.Components.Schemas.ConversationServiceRequest; + +export type ConversationServiceRequestRelocationPayloadData = + MittwaldAPIV2.Components.Schemas.ConversationServiceRequestRelocationPayload; diff --git a/packages/models/src/conversation/ConversationStatusUpdate/ConversationStatusUpdate.ts b/packages/models/src/conversation/ConversationStatusUpdate/ConversationStatusUpdate.ts new file mode 100644 index 00000000..6d16dffc --- /dev/null +++ b/packages/models/src/conversation/ConversationStatusUpdate/ConversationStatusUpdate.ts @@ -0,0 +1,24 @@ +import { DateTime } from "luxon"; + +import type { ConversationStatusUpdateData } from "./types.js"; + +import { ConversationUser } from "../ConversationUser/index.js"; +import { Conversation } from "../Conversation/index.js"; +import { DataModel } from "../../base/index.js"; + +export class ConversationStatusUpdate extends DataModel { + public readonly content: string; + public readonly conversation: Conversation; + public readonly createdAt: DateTime; + public readonly user?: ConversationUser; + + public constructor(data: ConversationStatusUpdateData) { + super(data); + this.conversation = Conversation.ofId(data.conversationId); + this.createdAt = DateTime.fromISO(data.createdAt); + this.user = data.meta?.user + ? new ConversationUser(data.meta.user) + : undefined; + this.content = data.messageContent; + } +} diff --git a/packages/models/src/conversation/ConversationStatusUpdate/index.ts b/packages/models/src/conversation/ConversationStatusUpdate/index.ts new file mode 100644 index 00000000..400cdb80 --- /dev/null +++ b/packages/models/src/conversation/ConversationStatusUpdate/index.ts @@ -0,0 +1 @@ +export * from "./ConversationStatusUpdate.js"; diff --git a/packages/models/src/conversation/ConversationStatusUpdate/types.ts b/packages/models/src/conversation/ConversationStatusUpdate/types.ts new file mode 100644 index 00000000..7adbeb41 --- /dev/null +++ b/packages/models/src/conversation/ConversationStatusUpdate/types.ts @@ -0,0 +1,4 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type ConversationStatusUpdateData = + MittwaldAPIV2.Components.Schemas.ConversationStatusUpdate; diff --git a/packages/models/src/conversation/ConversationUser/ConversationUser.test.ts b/packages/models/src/conversation/ConversationUser/ConversationUser.test.ts new file mode 100644 index 00000000..14f54622 --- /dev/null +++ b/packages/models/src/conversation/ConversationUser/ConversationUser.test.ts @@ -0,0 +1,70 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { buildConversationUserData } from "../../testing/builders/buildConversationUserData.js"; +import { installBehaviors, resetBehaviors } from "../../testing/index.js"; +import { Conversation } from "../Conversation/index.js"; +import { ReferenceModel } from "../../base/index.js"; +import { File } from "../../file/index.js"; +import { + ConversationUserListQuery, + ConversationUserList, + ConversationUser, +} from "./ConversationUser.js"; + +afterEach(resetBehaviors); + +describe("ConversationUser", () => { + test("maps user data and avatar", () => { + const user = new ConversationUser( + buildConversationUserData({ + avatarRefId: "f-1", + clearName: "Jane", + isEmployee: true, + userId: "u-1", + }), + ); + + expect(user.id).toBe("u-1"); + expect(user.clearName).toBe("Jane"); + expect(user.isEmployee).toBe(true); + expect(user.avatar).toBeInstanceOf(File); + expect(user.data).toBeDefined(); + expect(user).toBeInstanceOf(ReferenceModel); + }); + + test("leaves an absent avatar undefined", () => { + expect( + new ConversationUser( + buildConversationUserData({ avatarRefId: undefined }), + ).avatar, + ).toBeUndefined(); + }); + + test("executes the conversation user list query", async () => { + const getMembers = vi + .fn() + .mockResolvedValue([buildConversationUserData({ userId: "u-1" })]); + installBehaviors({ conversation: { getMembers } }); + const query = Conversation.ofId("c-1").users; + + const result = await query.execute(); + + expect(query).toBeInstanceOf(ConversationUserListQuery); + expect(result).toBeInstanceOf(ConversationUserList); + expect(result.items).toBeDefined(); + expect(result.items[0]).toBeInstanceOf(ConversationUser); + expect(result.totalCount).toBe(1); + expect(getMembers).toHaveBeenCalledWith("c-1"); + }); + + test("includes reports whether a user is present", async () => { + const getMembers = vi + .fn() + .mockResolvedValue([buildConversationUserData({ userId: "u-1" })]); + installBehaviors({ conversation: { getMembers } }); + const query = Conversation.ofId("c-1").users; + + await expect(query.includes("u-1")).resolves.toBe(true); + await expect(query.includes("u-2")).resolves.toBe(false); + }); +}); diff --git a/packages/models/src/conversation/ConversationUser/ConversationUser.ts b/packages/models/src/conversation/ConversationUser/ConversationUser.ts new file mode 100644 index 00000000..0d9903ad --- /dev/null +++ b/packages/models/src/conversation/ConversationUser/ConversationUser.ts @@ -0,0 +1,72 @@ +import type { Conversation } from "../Conversation/index.js"; +import type { ConversationUserData } from "./types.js"; +import type { User } from "../../user/index.js"; + +import { File } from "../../file/File/internal.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + type Ctor, + extractId, + WithData, +} from "../../base/index.js"; + +export class ConversationUser extends WithData()( + ReferenceModel as Ctor, +) { + public readonly avatar?: File; + public readonly clearName?: string; + public override readonly data: ConversationUserData; + public readonly isEmployee?: boolean; + + public constructor(data: ConversationUserData) { + super(data.userId); + this.data = data; + this.clearName = data.clearName; + this.avatar = data.avatarRefId ? File.ofId(data.avatarRefId) : undefined; + this.isEmployee = data.isEmployee; + } +} + +export class ConversationUserListQuery extends ListQueryModel { + private readonly conversation: Conversation; + + public constructor(conversation: Conversation) { + super(null, { dependencies: [conversation.id] }); + this.conversation = conversation; + } + + public async execute() { + const response = await config.behaviors.conversation.getMembers( + this.conversation.id, + ); + return new ConversationUserList( + this.conversation, + response.map((m) => new ConversationUser(m)), + response.length, + ); + } + + public async includes(otherUser: ConversationUser | string | User) { + const { items } = await this.execute(); + return items.some((u) => u.id === extractId(otherUser)); + } +} + +export class ConversationUserList extends WithListData()( + ConversationUserListQuery, +) { + public override readonly items: readonly ConversationUser[]; + public override readonly totalCount: number; + public constructor( + conversation: Conversation, + users: ConversationUser[], + totalCount: number, + ) { + super(conversation); + this.items = Object.freeze(users); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/conversation/ConversationUser/index.ts b/packages/models/src/conversation/ConversationUser/index.ts new file mode 100644 index 00000000..02f43487 --- /dev/null +++ b/packages/models/src/conversation/ConversationUser/index.ts @@ -0,0 +1,2 @@ +export * from "./ConversationUser.js"; +export * from "./types.js"; diff --git a/packages/models/src/conversation/ConversationUser/types.ts b/packages/models/src/conversation/ConversationUser/types.ts new file mode 100644 index 00000000..9a185610 --- /dev/null +++ b/packages/models/src/conversation/ConversationUser/types.ts @@ -0,0 +1,7 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type ConversationUserData = + MittwaldAPIV2.Components.Schemas.ConversationUser; + +export type ConversationMemberData = + MittwaldAPIV2.Operations.ConversationGetConversationMembers.ResponseData[number]; diff --git a/packages/models/src/conversation/index.ts b/packages/models/src/conversation/index.ts new file mode 100644 index 00000000..769482d3 --- /dev/null +++ b/packages/models/src/conversation/index.ts @@ -0,0 +1,6 @@ +export * from "./Conversation/index.js"; +export * from "./ConversationCategory/index.js"; +export * from "./ConversationMessage/index.js"; +export * from "./ConversationServiceRequest/index.js"; +export * from "./ConversationStatusUpdate/index.js"; +export * from "./ConversationUser/index.js"; diff --git a/packages/models/src/cronjob/Cronjob/Cronjob.test.ts b/packages/models/src/cronjob/Cronjob/Cronjob.test.ts new file mode 100644 index 00000000..236a6a67 --- /dev/null +++ b/packages/models/src/cronjob/Cronjob/Cronjob.test.ts @@ -0,0 +1,416 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +// Names any class by its JS name, so ObjectNotFoundError's type does not depend on the ghost registry. +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { CronjobExecutionListQuery } from "../CronjobExecution/index.js"; +import { + buildCronjobListItemData, + buildCronjobData, +} from "../../testing/builders/buildCronjobData.js"; +import { AppInstallation } from "../../app/index.js"; +import { Container } from "../../container/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { Project } from "../../project/index.js"; +import { + CronjobDetailed, + CronjobListItem, + CronjobList, + Cronjob, +} from "./Cronjob.js"; + +afterEach(resetBehaviors); + +const project = Project.ofId("project-id"); + +describe("Cronjob reference + delegation", () => { + test("find delegates to the cronjob behavior and returns a detailed cronjob", async () => { + const find = vi.fn().mockResolvedValue(buildCronjobData({ id: "c-1" })); + installBehaviors({ cronjob: { find } }); + + const result = await Cronjob.find("c-1"); + + expect(find).toHaveBeenCalledWith("c-1"); + expect(result).toBeInstanceOf(CronjobDetailed); + expect(result?.id).toBe("c-1"); + }); + + test("find maps a missing cronjob to undefined", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ cronjob: { find } }); + + const result = await Cronjob.find("missing"); + + expect(result).toBeUndefined(); + }); + + test("get returns a detailed cronjob when found", async () => { + const find = vi.fn().mockResolvedValue(buildCronjobData({ id: "c-2" })); + installBehaviors({ cronjob: { find } }); + + const result = await Cronjob.get("c-2"); + + expect(result).toBeInstanceOf(CronjobDetailed); + expect(result.id).toBe("c-2"); + }); + + test("get throws ObjectNotFoundError when the cronjob is missing", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ cronjob: { find } }); + + await expect(Cronjob.get("missing")).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("findDetailed delegates with the reference id", async () => { + const ref = Cronjob.ofId("c-3"); + const find = vi.fn().mockResolvedValue(buildCronjobData({ id: "c-3" })); + installBehaviors({ cronjob: { find } }); + + const result = await ref.findDetailed(); + + expect(find).toHaveBeenCalledWith("c-3"); + expect(result?.id).toBe("c-3"); + }); + + test("create delegates with the project id and returns a cronjob reference", async () => { + const create = vi.fn().mockResolvedValue({ id: "created-1" }); + installBehaviors({ cronjob: { create } }); + + const data = { + interval: "*/5 * * * *", + description: "new", + timeout: 3600, + active: true, + }; + const result = await Cronjob.create(project, data); + + expect(create).toHaveBeenCalledWith("project-id", data); + expect(result).toBeInstanceOf(Cronjob); + expect(result.id).toBe("created-1"); + }); + + test("getTimeZones returns the behavior value", async () => { + const getTimeZones = vi.fn().mockResolvedValue(["Europe/Berlin", "UTC"]); + installBehaviors({ cronjob: { getTimeZones } }); + + const result = await Cronjob.getTimeZones(); + + expect(result).toEqual(["Europe/Berlin", "UTC"]); + }); + + test("update, delete and trigger delegate with the reference id", async () => { + const update = vi.fn().mockResolvedValue(undefined); + const del = vi.fn().mockResolvedValue(undefined); + const trigger = vi.fn().mockResolvedValue(undefined); + installBehaviors({ + cronjob: { delete: del, trigger, update }, + }); + + const ref = Cronjob.ofId("c-4"); + await ref.update({ description: "changed" }); + await ref.delete(); + await ref.trigger(); + + expect(update).toHaveBeenCalledWith("c-4", { description: "changed" }); + expect(del).toHaveBeenCalledWith("c-4"); + expect(trigger).toHaveBeenCalledWith("c-4"); + }); +}); + +describe("Cronjob data + derived getters", () => { + test("copies simple fields through from the data", () => { + const item = new CronjobListItem( + buildCronjobListItemData({ + failedExecutionAlertThreshold: 3, + timeZone: "Europe/Berlin", + email: "ops@example.com", + description: "backup", + interval: "0 * * * *", + active: false, + timeout: 120, + }), + ); + + expect(item.description).toBe("backup"); + expect(item.active).toBe(false); + expect(item.interval).toBe("0 * * * *"); + expect(item.timeout).toBe(120); + expect(item.email).toBe("ops@example.com"); + expect(item.timeZone).toBe("Europe/Berlin"); + expect(item.failedExecutionAlertThreshold).toBe(3); + expect(item.project.id).toBe("project-id"); + }); + + test("derives a url cronjob from a url destination", () => { + const item = new CronjobListItem( + buildCronjobListItemData({ + destination: { url: "https://example.com/hook" }, + }), + ); + + expect(item.targetType).toBe("app"); + expect(item.type).toBe("url"); + expect(item.url).toBe("https://example.com/hook"); + expect(item.command).toBeUndefined(); + }); + + test("derives a command cronjob and remaps the legacy bash interpreter", () => { + const item = new CronjobListItem( + buildCronjobListItemData({ + destination: { + interpreter: "/bin/bash", + path: "/scripts/run.sh", + parameters: "-x", + }, + }), + ); + + expect(item.type).toBe("command"); + expect(item.command).toEqual({ + interpreter: "/usr/bin/bash", + path: "/scripts/run.sh", + parameters: "-x", + }); + expect(item.url).toBeUndefined(); + }); + + test("derives a container target with command text and linked container", () => { + const item = new CronjobListItem( + buildCronjobListItemData({ + target: { + serviceShortId: "svc-1", + command: "echo hi", + stackId: "stack-1", + }, + }), + ); + + expect(item.targetType).toBe("container"); + expect(item.commandText).toBe("echo hi"); + expect(item.linkedContainer).toBeInstanceOf(Container); + expect(item.linkedContainer?.id).toBe("svc-1"); + expect(item.type).toBeUndefined(); + }); + + test("links the app installation from the appId when no target is present", () => { + const item = new CronjobListItem( + buildCronjobListItemData({ appId: "app-42" }), + ); + + expect(item.targetType).toBe("app"); + expect(item.linkedAppInstallation).toBeDefined(); + expect(item.linkedAppInstallation?.id).toBe("app-42"); + expect(item.linkedContainer).toBeUndefined(); + }); + + test("leaves target derivations undefined when no destination, target or app link is present", () => { + const item = new CronjobListItem( + buildCronjobListItemData({ + timeZone: undefined, + appId: undefined, + email: undefined, + }), + ); + + expect(item.type).toBeUndefined(); + expect(item.url).toBeUndefined(); + expect(item.command).toBeUndefined(); + expect(item.commandText).toBeUndefined(); + expect(item.linkedAppInstallation).toBeUndefined(); + expect(item.linkedContainer).toBeUndefined(); + expect(item.latestExecution).toBeUndefined(); + expect(item.email).toBeUndefined(); + expect(item.timeZone).toBeUndefined(); + }); + + test("exposes an executions list query and a latest execution", () => { + const item = new CronjobListItem( + buildCronjobListItemData({ + latestExecution: { + cronjobId: "cronjob-id", + status: "Complete", + successful: true, + id: "exec-9", + }, + }), + ); + + expect(item.executions).toBeInstanceOf(CronjobExecutionListQuery); + expect(item.latestExecution?.id).toBe("exec-9"); + }); +}); + +describe("Cronjob list query pagination", () => { + test("execute always includes service cronjobs by default", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildCronjobListItemData({ id: "c-1" })], + totalCount: 1, + }); + installBehaviors({ cronjob: { list } }); + + const result = await Cronjob.query({ project: project }).execute(); + + expect(result).toBeInstanceOf(CronjobList); + expect(result.items).toHaveLength(1); + expect(result.items[0]).toBeInstanceOf(CronjobListItem); + expect(result.totalCount).toBe(1); + expect(list).toHaveBeenCalledWith( + "project-id", + expect.objectContaining({ includeServiceCronjobs: true }), + ); + }); + + test("passes an explicit query through to the behavior", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 0, items: [] }); + installBehaviors({ cronjob: { list } }); + + await Cronjob.query({ project: project, limit: 5 }).execute(); + + expect(list).toHaveBeenCalledWith( + "project-id", + expect.objectContaining({ limit: 5 }), + ); + }); + + test("getTotalCount refines the query to a single item", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 42, items: [] }); + installBehaviors({ cronjob: { list } }); + + const total = await Cronjob.query({ project: project }).getTotalCount(); + + expect(total).toBe(42); + expect(list).toHaveBeenCalledWith( + "project-id", + expect.objectContaining({ limit: 1 }), + ); + }); + + test("refine merges the new query onto the existing one", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 0, items: [] }); + installBehaviors({ cronjob: { list } }); + + await Cronjob.query({ project: project, limit: 2 }) + .refine({ skip: 4 }) + .execute(); + + expect(list).toHaveBeenCalledWith( + "project-id", + expect.objectContaining({ limit: 2, skip: 4 }), + ); + }); +}); + +describe("Cronjob.getInterpreters", () => { + test("returns only the default interpreters when no matching software is installed", async () => { + const getInstalledSystemSoftware = vi.fn().mockResolvedValue([]); + installBehaviors({ appInstallation: { getInstalledSystemSoftware } }); + + const appInstallation = AppInstallation.ofId("app-inst-id"); + + const interpreters = await Cronjob.getInterpreters(appInstallation); + + expect(getInstalledSystemSoftware).toHaveBeenCalledWith("app-inst-id", { + tagFilter: "interpreter", + }); + expect(interpreters.map((i) => i.name)).toEqual(["Bash"]); + }); + + test("adds an additional interpreter when the matching software is installed", async () => { + const getInstalledSystemSoftware = vi + .fn() + .mockResolvedValue([{ tags: ["interpreter"], name: "php", id: "s-1" }]); + installBehaviors({ appInstallation: { getInstalledSystemSoftware } }); + + const appInstallation = AppInstallation.ofId("app-inst-id"); + + const interpreters = await Cronjob.getInterpreters(appInstallation); + const names = interpreters.map((i) => i.name); + + expect(names).toContain("Bash"); + expect(names).toContain("PHP"); + expect(names).not.toContain("Python"); + }); +}); + +describe("Cronjob common variant + idempotency", () => { + test("findCommon on a reference delegates to findDetailed and returns the common variant", async () => { + const find = vi + .fn() + .mockResolvedValue(buildCronjobData({ id: "c-common-1" })); + installBehaviors({ cronjob: { find } }); + + const result = await Cronjob.ofId("c-common-1").findCommon(); + + expect(find).toHaveBeenCalledWith("c-common-1"); + expect(result).toBeInstanceOf(CronjobDetailed); + expect(result?.id).toBe("c-common-1"); + }); + + test("findCommon on a reference maps a missing cronjob to undefined", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ cronjob: { find } }); + + const result = await Cronjob.ofId("missing").findCommon(); + + expect(result).toBeUndefined(); + }); + + test("getCommon on a reference returns the common variant when found", async () => { + const find = vi + .fn() + .mockResolvedValue(buildCronjobData({ id: "c-common-2" })); + installBehaviors({ cronjob: { find } }); + + const result = await Cronjob.ofId("c-common-2").getCommon(); + + expect(result).toBeInstanceOf(CronjobDetailed); + expect(result.id).toBe("c-common-2"); + }); + + test("getCommon on a reference throws ObjectNotFoundError when missing", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ cronjob: { find } }); + + await expect(Cronjob.ofId("missing").getCommon()).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("findCommon on an already materialized list item returns itself without a behavior call", async () => { + const find = vi.fn(); + installBehaviors({ cronjob: { find } }); + + const item = new CronjobListItem( + buildCronjobListItemData({ id: "c-common-3" }), + ); + const result = await item.findCommon(); + + expect(result).toBe(item); + expect(find).not.toHaveBeenCalled(); + }); + + test("getCommon on an already detailed cronjob returns itself without a behavior call", async () => { + const find = vi.fn(); + installBehaviors({ cronjob: { find } }); + + const detailed = new CronjobDetailed( + buildCronjobData({ id: "c-common-4" }), + ); + const result = await detailed.getCommon(); + + expect(result).toBe(detailed); + expect(find).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/models/src/cronjob/Cronjob/Cronjob.ts b/packages/models/src/cronjob/Cronjob/Cronjob.ts new file mode 100644 index 00000000..f429dae8 --- /dev/null +++ b/packages/models/src/cronjob/Cronjob/Cronjob.ts @@ -0,0 +1,272 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import invariant from "tiny-invariant"; +import { omit } from "remeda"; + +import type { CronjobExecutionListQuery } from "../CronjobExecution/index.js"; +import type { + CronjobContainerTargetResponse, + CronjobAppInstallationTarget, + CronjobCommandDestination, + CronjobListQueryModelData, + CronjobCreateRequestData, + CronjobUpdateRequestData, + CronjobListItemData, + CronjobData, +} from "./types.js"; + +import { + additionalCronInterpreters, + defaultCronInterpreters, +} from "./types.js"; +import { AppInstallation } from "../../app/AppInstallation/AppInstallation.js"; +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { Container } from "../../container/Container/Container.js"; +import { Project } from "../../project/internal.js"; +import { config } from "../../config/index.js"; +import { + CronjobExecutionDetailed, + CronjobExecution, +} from "../CronjobExecution/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "Cronjob", +}) +export class Cronjob extends ReferenceModel { + public static readonly defaultTimeout = 3600; + public static readonly maxTimeout = 86400; + public static readonly minTimeout = 1; + public readonly executions: CronjobExecutionListQuery; + + public constructor(id: string) { + super(id); + this.executions = CronjobExecution.query(this); + } + + public static async create(project: Project, data: CronjobCreateRequestData) { + const result = await config.behaviors.cronjob.create(project.id, data); + + return new Cronjob(result.id); + } + + public static async find(id: string) { + const data = await config.behaviors.cronjob.find(id); + if (data !== undefined) { + return new CronjobDetailed(data); + } + } + + public static async get(id: string) { + const cronjob = await this.find(id); + assertObjectFound(cronjob, Cronjob, id); + return cronjob; + } + + public static async getInterpreters(appInstallation: AppInstallation) { + const systemSoftwares = await appInstallation.getInstalledSystemSoftware({ + tagFilter: "interpreter", + }); + + return [ + ...defaultCronInterpreters, + ...additionalCronInterpreters.filter((i) => + systemSoftwares.find((s) => i.name.toLowerCase() === s.name), + ), + ]; + } + + public static async getTimeZones() { + return await config.behaviors.cronjob.getTimeZones(); + } + + public static ofId(id: string) { + return new Cronjob(id); + } + + public static query(query: CronjobListQueryModelData) { + return new CronjobListQuery(query); + } + + public async delete() { + await config.behaviors.cronjob.delete(this.id); + } + + public findCommon(): Promise | CronjobCommon { + return this instanceof CronjobCommon ? this : this.findDetailed(); + } + + public findDetailed(): Promise { + return Cronjob.find(this.id); + } + + public getCommon(): Promise | CronjobCommon { + return this instanceof CronjobCommon ? this : this.getDetailed(); + } + + public getDetailed(): Promise { + return Cronjob.get(this.id); + } + + public async trigger() { + await config.behaviors.cronjob.trigger(this.id); + } + + public async update(data: CronjobUpdateRequestData) { + await config.behaviors.cronjob.update(this.id, data); + } +} + +export class CronjobCommon extends WithData< + CronjobListItemData | CronjobData +>()(Cronjob) { + public readonly active: boolean; + public readonly command?: CronjobCommandDestination; + public readonly commandText?: string; + public override readonly data: CronjobListItemData | CronjobData; + public readonly description: string; + public readonly email?: string; + public readonly failedExecutionAlertThreshold: number; + public readonly interval: string; + public readonly latestExecution?: CronjobExecutionDetailed; + public readonly linkedAppInstallation?: AppInstallation; + public readonly linkedContainer?: Container; + public readonly project: Project; + public readonly targetType: "container" | "app"; + public readonly timeout: number; + public readonly timeZone?: string; + public readonly type?: "command" | "url"; + public readonly url?: string; + + public constructor(data: CronjobListItemData | CronjobData) { + super(data.id); + this.data = data; + this.description = data.description; + this.active = data.active; + + const target = data.target; + const appTarget = + target && "appInstallationId" in target + ? (target as CronjobAppInstallationTarget) + : undefined; + const containerTarget = + target && "serviceShortId" in target + ? (target as CronjobContainerTargetResponse) + : undefined; + const appInstallationId = + appTarget?.appInstallationId ?? data.appInstallationId ?? data.appId; + + this.targetType = containerTarget ? "container" : "app"; + + if (containerTarget) { + this.commandText = containerTarget.command; + } else { + const destination = appTarget?.destination ?? data.destination; + this.type = destination + ? "path" in destination + ? "command" + : "url" + : undefined; + this.url = + destination && "url" in destination ? destination.url : undefined; + this.command = + destination && "path" in destination + ? { + interpreter: + destination.interpreter === "/bin/bash" + ? "/usr/bin/bash" + : destination.interpreter, + parameters: destination.parameters, + path: destination.path, + } + : undefined; + } + + this.interval = data.interval; + this.linkedAppInstallation = appInstallationId + ? AppInstallation.ofId(appInstallationId) + : undefined; + this.linkedContainer = containerTarget + ? Container.ofId(containerTarget.serviceShortId, containerTarget.stackId) + : undefined; + this.timeout = data.timeout; + this.email = data.email; + this.timeZone = data.timeZone; + this.failedExecutionAlertThreshold = data.failedExecutionAlertThreshold; + this.latestExecution = data.latestExecution + ? new CronjobExecutionDetailed(data.latestExecution, this) + : undefined; + invariant(data.projectId, `project missing in cronjob ${data.id}`); + this.project = Project.ofId(data.projectId); + } +} + +export class CronjobDetailed extends CronjobCommon { + public override readonly data: CronjobData; + public constructor(data: CronjobData) { + super(data); + this.data = data; + } +} + +export class CronjobListItem extends CronjobCommon { + public override readonly data: CronjobListItemData; + public constructor(data: CronjobListItemData) { + super(data); + this.data = data; + } +} + +export class CronjobListQuery extends ListQueryModel { + public constructor(query: CronjobListQueryModelData) { + super( + { includeServiceCronjobs: true, ...query }, + { dependencies: [extractId(query.project)] }, + ); + } + + public async execute() { + const { totalCount, items } = await config.behaviors.cronjob.list( + extractId(this.query.project), + omit(this.query, ["project"]), + ); + return new CronjobList( + this.query, + items.map((d) => new CronjobListItem(d)), + totalCount, + ); + } + + public async getTotalCount() { + const { totalCount } = await this.refine({ limit: 1 }).execute(); + return totalCount; + } + + public refine(query: Partial = {}) { + return new CronjobListQuery({ + ...this.query, + ...query, + }); + } +} + +export class CronjobList extends WithListData()( + CronjobListQuery, +) { + public override readonly items: readonly CronjobListItem[]; + public override readonly totalCount: number; + public constructor( + query: CronjobListQueryModelData, + cronjobs: CronjobListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(cronjobs); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/cronjob/Cronjob/behaviors/api.ts b/packages/models/src/cronjob/Cronjob/behaviors/api.ts new file mode 100644 index 00000000..c18cea02 --- /dev/null +++ b/packages/models/src/cronjob/Cronjob/behaviors/api.ts @@ -0,0 +1,75 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { CronjobBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { anyStatus403 } from "../../../base/api/typeFixes.js"; +import { resolveTotalCount } from "../../../base/index.js"; + +export const apiCronjobBehaviors = ( + client: MittwaldAPIV2Client, +): CronjobBehaviors => ({ + find: async (cronjobId) => { + const response = await client.cronjob.getCronjob({ cronjobId }); + + if (response.status === 200) { + return response.data; + } + // API-DRIFT: getCronjob omits 403 in its generated response type, so anyStatus403 (403 as any) is passed (resolve: use the literal 403 once the client type declares it) + validateResponse(response, [404, anyStatus403]); + }, + + list: async (projectId, query) => { + const response = await client.cronjob.listCronjobs({ + queryParameters: query, + projectId, + }); + + validateResponse(response, 200); + + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + create: async (projectId, data) => { + const response = await client.cronjob.createCronjob({ + projectId, + data, + }); + + validateResponse(response, 201); + + return response.data; + }, + + update: async (cronjobId, data) => { + const response = await client.cronjob.updateCronjob({ + cronjobId, + data, + }); + + validateResponse(response, 204); + }, + + getTimeZones: async () => { + const response = await client.misc.ellaneousListTimeZones(); + + validateResponse(response, 200); + + return response.data; + }, + + trigger: async (cronjobId) => { + const response = await client.cronjob.createExecution({ cronjobId }); + + validateResponse(response, 201); + }, + + delete: async (cronjobId) => { + const response = await client.cronjob.deleteCronjob({ cronjobId }); + + validateResponse(response, 204); + }, +}); diff --git a/packages/models/src/cronjob/Cronjob/behaviors/index.ts b/packages/models/src/cronjob/Cronjob/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/cronjob/Cronjob/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/cronjob/Cronjob/behaviors/types.ts b/packages/models/src/cronjob/Cronjob/behaviors/types.ts new file mode 100644 index 00000000..45426a2b --- /dev/null +++ b/packages/models/src/cronjob/Cronjob/behaviors/types.ts @@ -0,0 +1,30 @@ +import type { QueryResponseData } from "../../../base/index.js"; +import type { + CronjobCreateRequestData, + CronjobUpdateRequestData, + CronjobListQueryData, + CronjobListItemData, + CronjobData, +} from "../types.js"; + +export interface CronjobBehaviors { + list: ( + projectId: string, + query?: CronjobListQueryData, + ) => Promise>; + + create: ( + projectId: string, + data: CronjobCreateRequestData, + ) => Promise<{ id: string }>; + + update: (cronjobId: string, data: CronjobUpdateRequestData) => Promise; + + find: (cronjobId: string) => Promise; + + trigger: (cronjobId: string) => Promise; + + delete: (cronjobId: string) => Promise; + + getTimeZones: () => Promise; +} diff --git a/packages/models/src/cronjob/Cronjob/index.ts b/packages/models/src/cronjob/Cronjob/index.ts new file mode 100644 index 00000000..00a61fe0 --- /dev/null +++ b/packages/models/src/cronjob/Cronjob/index.ts @@ -0,0 +1,2 @@ +export * from "./Cronjob.js"; +export * from "./types.js"; diff --git a/packages/models/src/cronjob/Cronjob/types.ts b/packages/models/src/cronjob/Cronjob/types.ts new file mode 100644 index 00000000..940f7733 --- /dev/null +++ b/packages/models/src/cronjob/Cronjob/types.ts @@ -0,0 +1,70 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import type { Project } from "../../project/index.js"; + +export type CronjobData = + MittwaldAPIV2.Operations.CronjobGetCronjob.ResponseData; + +export type CronjobListItemData = + MittwaldAPIV2.Operations.CronjobListCronjobs.ResponseData[number]; + +export type CronjobListQueryData = + MittwaldAPIV2.Paths.V2ProjectsProjectIdCronjobs.Get.Parameters.Query; + +export type CronjobListQueryModelData = { + project: Project | string; +} & CronjobListQueryData; + +export type CronjobCreateRequestData = + MittwaldAPIV2.Components.Schemas.CronjobCronjobRequest; + +export type CronjobUpdateRequestData = + MittwaldAPIV2.Paths.V2CronjobsCronjobId.Patch.Parameters.RequestBody; + +export type CronjobUrlDestination = + MittwaldAPIV2.Components.Schemas.CronjobCronjobUrl; + +export type CronjobCommandDestination = + MittwaldAPIV2.Components.Schemas.CronjobCronjobCommand; + +export type CronjobAppInstallationTarget = + MittwaldAPIV2.Components.Schemas.CronjobAppInstallationTarget; + +export type CronjobContainerTarget = + MittwaldAPIV2.Components.Schemas.CronjobServiceTarget; + +export type CronjobContainerTargetResponse = + MittwaldAPIV2.Components.Schemas.CronjobServiceTargetResponse; + +export interface CronjobInterpreter { + extensions: string[]; + path: string; + name: string; +} + +/* interpreters available in every appInstallation */ +export const defaultCronInterpreters: CronjobInterpreter[] = [ + { + path: "/usr/bin/bash", + extensions: [".sh"], + name: "Bash", + }, +]; + +/* interpreters that have to be available within the appInstallation to be listed */ +export const additionalCronInterpreters: CronjobInterpreter[] = [ + { + extensions: [".php", ".phtml"], + path: "/usr/bin/php", + name: "PHP", + }, + { + path: "/usr/local/bin/python", + extensions: [".py"], + name: "Python", + }, +]; + +export type CronjobLogData = + | MittwaldAPIV2.Operations.ProjectFileSystemGetFileContent.ResponseData + | { message: string }; diff --git a/packages/models/src/cronjob/CronjobExecution/CronjobExecution.test.ts b/packages/models/src/cronjob/CronjobExecution/CronjobExecution.test.ts new file mode 100644 index 00000000..7300cd20 --- /dev/null +++ b/packages/models/src/cronjob/CronjobExecution/CronjobExecution.test.ts @@ -0,0 +1,456 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; +import { DateTime } from "luxon"; + +// Names any class by its JS name, so ObjectNotFoundError's type does not depend on the ghost registry. +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { + buildCronjobExecutionListItemData, + buildCronjobExecutionData, +} from "../../testing/builders/buildCronjobExecutionData.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { Cronjob } from "../Cronjob/index.js"; +import { + CronjobExecutionDetailed, + CronjobExecutionListItem, + CronjobExecutionList, + CronjobExecution, +} from "./CronjobExecution.js"; + +afterEach(resetBehaviors); + +const cronjob = Cronjob.ofId("cronjob-id"); + +describe("CronjobExecution reference + delegation", () => { + test("find delegates with the execution and cronjob ids and returns a detailed execution", async () => { + const find = vi + .fn() + .mockResolvedValue(buildCronjobExecutionData({ id: "e-1" })); + installBehaviors({ cronjobExecution: { find } }); + + const result = await CronjobExecution.find("e-1", cronjob); + + expect(find).toHaveBeenCalledWith("e-1", "cronjob-id"); + expect(result).toBeInstanceOf(CronjobExecutionDetailed); + expect(result?.id).toBe("e-1"); + }); + + test("find maps a missing execution to undefined", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ cronjobExecution: { find } }); + + const result = await CronjobExecution.find("missing", cronjob); + + expect(result).toBeUndefined(); + }); + + test("get throws ObjectNotFoundError when the execution is missing", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ cronjobExecution: { find } }); + + await expect( + CronjobExecution.get("missing", cronjob), + ).rejects.toBeInstanceOf(ObjectNotFoundError); + }); + + test("findDetailed delegates with the reference ids", async () => { + const ref = CronjobExecution.ofId("e-3", cronjob); + const find = vi + .fn() + .mockResolvedValue(buildCronjobExecutionData({ id: "e-3" })); + installBehaviors({ cronjobExecution: { find } }); + + const result = await ref.findDetailed(); + + expect(find).toHaveBeenCalledWith("e-3", "cronjob-id"); + expect(result?.id).toBe("e-3"); + }); + + test("getExecutionAnalysis delegates with the ids, language and request config", async () => { + const getExecutionAnalysis = vi + .fn() + .mockResolvedValue({ message: "all good" }); + installBehaviors({ cronjobExecution: { getExecutionAnalysis } }); + + const execution = new CronjobExecutionDetailed( + buildCronjobExecutionData({ id: "e-4" }), + cronjob, + ); + const requestConfig = { timeout: 1000 }; + const result = await execution.getExecutionAnalysis("de", requestConfig); + + expect(getExecutionAnalysis).toHaveBeenCalledWith( + "e-4", + "cronjob-id", + "de", + requestConfig, + ); + expect(result).toEqual({ message: "all good" }); + }); +}); + +describe("CronjobExecution data + derived getters", () => { + test("isRunning reflects the running and pending statuses", () => { + const running = new CronjobExecutionDetailed( + buildCronjobExecutionData({ status: "Running" }), + cronjob, + ); + const pending = new CronjobExecutionDetailed( + buildCronjobExecutionData({ status: "Pending" }), + cronjob, + ); + const complete = new CronjobExecutionDetailed( + buildCronjobExecutionData({ status: "Complete" }), + cronjob, + ); + + expect(running.isRunning).toBe(true); + expect(pending.isRunning).toBe(true); + expect(complete.isRunning).toBe(false); + }); + + test("durationInSeconds floors the millisecond duration", () => { + const execution = new CronjobExecutionDetailed( + buildCronjobExecutionData({ durationInMilliseconds: 5500 }), + cronjob, + ); + + expect(execution.durationInSeconds).toBe(5); + }); + + test("durationInSeconds is undefined when no duration is present", () => { + const execution = new CronjobExecutionDetailed( + buildCronjobExecutionData({ durationInMilliseconds: undefined }), + cronjob, + ); + + expect(execution.durationInSeconds).toBeUndefined(); + }); + + test("start is parsed into a luxon DateTime and undefined when absent", () => { + const withStart = new CronjobExecutionDetailed( + buildCronjobExecutionData({ start: "2024-01-01T00:00:00.000Z" }), + cronjob, + ); + const withoutStart = new CronjobExecutionDetailed( + buildCronjobExecutionData({ start: undefined }), + cronjob, + ); + + expect(withStart.start).toBeInstanceOf(DateTime); + expect(withStart.start?.toMillis()).toBe( + DateTime.fromISO("2024-01-01T00:00:00.000Z", { zone: "utc" }).toMillis(), + ); + expect(withoutStart.start).toBeUndefined(); + }); + + test("triggeredBy resolves to a user reference only when an id is present", () => { + const withUser = new CronjobExecutionDetailed( + buildCronjobExecutionData({ triggeredBy: { id: "user-7" } }), + cronjob, + ); + const withoutUser = new CronjobExecutionDetailed( + buildCronjobExecutionData({ triggeredBy: {} }), + cronjob, + ); + + expect(withUser.triggeredBy?.id).toBe("user-7"); + expect(withoutUser.triggeredBy).toBeUndefined(); + }); + + test("passes status, successful, exitCode and logPath through", () => { + const execution = new CronjobExecutionDetailed( + buildCronjobExecutionData({ + logPath: "/logs/failed.log", + successful: false, + status: "Failed", + exitCode: 137, + }), + cronjob, + ); + + expect(execution.status).toBe("Failed"); + expect(execution.successful).toBe(false); + expect(execution.exitCode).toBe(137); + expect(execution.logPath).toBe("/logs/failed.log"); + }); +}); + +describe("CronjobExecution log handling", () => { + test("findLog returns undefined when there is no log path", async () => { + const findLog = vi.fn(); + installBehaviors({ cronjobExecution: { findLog } }); + + const execution = new CronjobExecutionDetailed( + buildCronjobExecutionData({ logPath: undefined }), + cronjob, + ); + const result = await execution.findLog("project-id"); + + expect(result).toBeUndefined(); + expect(findLog).not.toHaveBeenCalled(); + }); + + test("findStructuredLog returns undefined when there is no log path", async () => { + const findLog = vi.fn(); + installBehaviors({ cronjobExecution: { findLog } }); + + const execution = new CronjobExecutionDetailed( + buildCronjobExecutionData({ logPath: undefined }), + cronjob, + ); + const result = await execution.findStructuredLog("project-id"); + + expect(result).toBeUndefined(); + expect(findLog).not.toHaveBeenCalled(); + }); + + test("findLog returns the message of an object response", async () => { + const findLog = vi.fn().mockResolvedValue({ message: "object log" }); + installBehaviors({ cronjobExecution: { findLog } }); + + const execution = new CronjobExecutionDetailed( + buildCronjobExecutionData(), + cronjob, + ); + const result = await execution.findLog("project-id"); + + expect(findLog).toHaveBeenCalledWith("project-id", "/logs/exec.log"); + expect(result).toBe("object log"); + }); + + test("findLog extracts and joins message fields from a structured string", async () => { + const findLog = vi + .fn() + .mockResolvedValue('{"message":"alpha"}\n{"message":"beta"}'); + installBehaviors({ cronjobExecution: { findLog } }); + + const execution = new CronjobExecutionDetailed( + buildCronjobExecutionData(), + cronjob, + ); + const result = await execution.findLog("project-id"); + + expect(result).toBe("alpha\nbeta"); + }); + + test("findLog returns a plain string log as-is", async () => { + const findLog = vi.fn().mockResolvedValue("plain log output"); + installBehaviors({ cronjobExecution: { findLog } }); + + const execution = new CronjobExecutionDetailed( + buildCronjobExecutionData(), + cronjob, + ); + const result = await execution.findLog("project-id"); + + expect(result).toBe("plain log output"); + }); + + test("findStructuredLog parses lines and maps the stream and time prefix", async () => { + const findLog = vi + .fn() + .mockResolvedValue( + '{"message":"line one","dev":"stdout","time":"12:00"}\n' + + '{"message":"line two","dev":"stderr"}\n' + + "not json", + ); + installBehaviors({ cronjobExecution: { findLog } }); + + const execution = new CronjobExecutionDetailed( + buildCronjobExecutionData(), + cronjob, + ); + const result = await execution.findStructuredLog("project-id"); + + expect(result).toEqual([ + { message: "12:00 line one", stream: "stdout" }, + { message: "line two", stream: "stderr" }, + ]); + }); + + test("findStructuredLog returns undefined for an empty response", async () => { + const findLog = vi.fn().mockResolvedValue(undefined); + installBehaviors({ cronjobExecution: { findLog } }); + + const execution = new CronjobExecutionDetailed( + buildCronjobExecutionData(), + cronjob, + ); + const result = await execution.findStructuredLog("project-id"); + + expect(result).toBeUndefined(); + }); + + test("getLogDownload wraps the log into a downloadable file", async () => { + const findLog = vi.fn().mockResolvedValue("downloadable log"); + installBehaviors({ cronjobExecution: { findLog } }); + + const execution = new CronjobExecutionDetailed( + buildCronjobExecutionData(), + cronjob, + ); + const result = await execution.getLogDownload("project-id"); + + expect(result).toEqual({ + content: "downloadable log", + filename: "cronjob.log", + }); + }); + + test("getLogDownload returns undefined when there is no log", async () => { + const findLog = vi.fn().mockResolvedValue(undefined); + installBehaviors({ cronjobExecution: { findLog } }); + + const execution = new CronjobExecutionDetailed( + buildCronjobExecutionData(), + cronjob, + ); + const result = await execution.getLogDownload("project-id"); + + expect(result).toBeUndefined(); + }); +}); + +describe("CronjobExecution list query pagination", () => { + test("execute materializes list items and total count", async () => { + const list = vi.fn().mockResolvedValue({ + items: [ + buildCronjobExecutionData({ id: "e-1" }), + buildCronjobExecutionData({ id: "e-2" }), + ], + totalCount: 5, + }); + installBehaviors({ cronjobExecution: { list } }); + + const result = await CronjobExecution.query(cronjob).execute(); + + expect(result).toBeInstanceOf(CronjobExecutionList); + expect(result.items).toHaveLength(2); + expect(result.items[0]).toBeInstanceOf(CronjobExecutionListItem); + expect(result.totalCount).toBe(5); + expect(list).toHaveBeenCalledWith("cronjob-id", expect.anything()); + }); + + test("passes an explicit query through to the behavior", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 0, items: [] }); + installBehaviors({ cronjobExecution: { list } }); + + await CronjobExecution.query(cronjob, { limit: 3 }).execute(); + + expect(list).toHaveBeenCalledWith( + "cronjob-id", + expect.objectContaining({ limit: 3 }), + ); + }); + + test("getTotalCount refines the query to a single item", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 9, items: [] }); + installBehaviors({ cronjobExecution: { list } }); + + const total = await CronjobExecution.query(cronjob).getTotalCount(); + + expect(total).toBe(9); + expect(list).toHaveBeenCalledWith( + "cronjob-id", + expect.objectContaining({ limit: 1 }), + ); + }); + + test("refine merges the new query onto the existing one", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 0, items: [] }); + installBehaviors({ cronjobExecution: { list } }); + + await CronjobExecution.query(cronjob, { limit: 2 }) + .refine({ sortOrder: "newestFirst" }) + .execute(); + + expect(list).toHaveBeenCalledWith( + "cronjob-id", + expect.objectContaining({ sortOrder: "newestFirst", limit: 2 }), + ); + }); +}); + +describe("CronjobExecution common variant + idempotency", () => { + test("findCommon on a reference delegates to findDetailed and returns the common variant", async () => { + const find = vi + .fn() + .mockResolvedValue(buildCronjobExecutionData({ id: "ec-1" })); + installBehaviors({ cronjobExecution: { find } }); + + const result = await CronjobExecution.ofId("ec-1", cronjob).findCommon(); + + expect(find).toHaveBeenCalledWith("ec-1", "cronjob-id"); + expect(result).toBeInstanceOf(CronjobExecutionDetailed); + expect(result?.id).toBe("ec-1"); + }); + + test("findCommon on a reference maps a missing execution to undefined", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ cronjobExecution: { find } }); + + const result = await CronjobExecution.ofId("missing", cronjob).findCommon(); + + expect(result).toBeUndefined(); + }); + + test("getCommon on a reference returns the common variant when found", async () => { + const find = vi + .fn() + .mockResolvedValue(buildCronjobExecutionData({ id: "ec-2" })); + installBehaviors({ cronjobExecution: { find } }); + + const result = await CronjobExecution.ofId("ec-2", cronjob).getCommon(); + + expect(result).toBeInstanceOf(CronjobExecutionDetailed); + expect(result.id).toBe("ec-2"); + }); + + test("getCommon on a reference throws ObjectNotFoundError when missing", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ cronjobExecution: { find } }); + + await expect( + CronjobExecution.ofId("missing", cronjob).getCommon(), + ).rejects.toBeInstanceOf(ObjectNotFoundError); + }); + + test("findCommon on an already materialized list item returns itself without a behavior call", async () => { + const find = vi.fn(); + installBehaviors({ cronjobExecution: { find } }); + + const item = new CronjobExecutionListItem( + buildCronjobExecutionListItemData({ id: "ec-3" }), + cronjob, + ); + const result = await item.findCommon(); + + expect(result).toBe(item); + expect(find).not.toHaveBeenCalled(); + }); + + test("getCommon on an already detailed execution returns itself without a behavior call", async () => { + const find = vi.fn(); + installBehaviors({ cronjobExecution: { find } }); + + const detailed = new CronjobExecutionDetailed( + buildCronjobExecutionData({ id: "ec-4" }), + cronjob, + ); + const result = await detailed.getCommon(); + + expect(result).toBe(detailed); + expect(find).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/models/src/cronjob/CronjobExecution/CronjobExecution.ts b/packages/models/src/cronjob/CronjobExecution/CronjobExecution.ts new file mode 100644 index 00000000..c2a45eb2 --- /dev/null +++ b/packages/models/src/cronjob/CronjobExecution/CronjobExecution.ts @@ -0,0 +1,307 @@ +import type { AxiosRequestConfig } from "axios"; + +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; + +import type { DownloadableFile } from "../../common/index.js"; +import type { Cronjob } from "../Cronjob/index.js"; +import type { + CronjobExecutionListQueryData, + CronjobExecutionListItemData, + CronjobExecutionStatus, + CronjobExecutionData, + StructuredLogLine, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { User } from "../../user/User/User.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + WithData, +} from "../../base/index.js"; + +const messageExtractionRegex = /"message"\s*:\s*"((?:\\.|[^"\\])*)"/g; + +@GhostMakerModel({ + name: "CronjobExecution", +}) +export class CronjobExecution extends ReferenceModel { + public readonly cronjob: Cronjob; + + public constructor(id: string, cronjob: Cronjob) { + super(id); + this.cronjob = cronjob; + } + public static async find(id: string, cronjob: Cronjob) { + const data = await config.behaviors.cronjobExecution.find(id, cronjob.id); + if (data !== undefined) { + return new CronjobExecutionDetailed(data, cronjob); + } + } + + public static async get(id: string, cronjob: Cronjob) { + const cronjobExecution = await this.find(id, cronjob); + assertObjectFound(cronjobExecution, CronjobExecution, id); + return cronjobExecution; + } + + public static ofId(id: string, cronjob: Cronjob) { + return new CronjobExecution(id, cronjob); + } + + public static query( + cronjob: Cronjob, + query: CronjobExecutionListQueryData = {}, + ) { + return new CronjobExecutionListQuery(cronjob, query); + } + + public async findCommon(): Promise { + return this instanceof CronjobExecutionCommon ? this : this.findDetailed(); + } + + public findDetailed(): Promise { + return CronjobExecution.find(this.id, this.cronjob); + } + + public async getCommon(): Promise { + return this instanceof CronjobExecutionCommon ? this : this.getDetailed(); + } + + public getDetailed(): Promise { + return CronjobExecution.get(this.id, this.cronjob); + } +} + +export class CronjobExecutionCommon extends WithData< + CronjobExecutionListItemData | CronjobExecutionData +>()(CronjobExecution) { + public override readonly data: + CronjobExecutionListItemData | CronjobExecutionData; + public readonly durationInSeconds?: number; + public readonly exitCode?: number; + public readonly isRunning: boolean; + public readonly logPath?: string; + public readonly start?: DateTime; + public readonly status: CronjobExecutionStatus; + public readonly successful: boolean; + public readonly triggeredBy?: User; + + public constructor( + data: CronjobExecutionListItemData | CronjobExecutionData, + cronjob: Cronjob, + ) { + super(data.id, cronjob); + this.data = data; + this.status = data.status; + this.isRunning = data.status === "Running" || data.status === "Pending"; + this.start = data.start + ? DateTime.fromISO(data.start, { zone: "utc" }) + : undefined; + this.exitCode = data.exitCode; + this.successful = data.successful; + this.durationInSeconds = + data.durationInMilliseconds !== undefined + ? Math.floor(data.durationInMilliseconds / 1000) + : undefined; + this.triggeredBy = data.triggeredBy?.id + ? User.ofId(data.triggeredBy.id) + : undefined; + this.logPath = data.logPath; + } + + public async findLog(projectId: string) { + if (!this.logPath) { + return; + } + + const response = await config.behaviors.cronjobExecution.findLog( + projectId, + this.logPath, + ); + + let finalLog: string | undefined; + + if (typeof response === "object" && "message" in response) { + finalLog = response.message as string; + } else if (response && messageExtractionRegex.test(response)) { + messageExtractionRegex.lastIndex = 0; + const messages = Array.from( + response.matchAll(messageExtractionRegex), + (m) => m[1], + ); + finalLog = messages.join("\n"); + } else { + finalLog = response; + } + return finalLog; + } + + public async findStructuredLog( + projectId: string, + ): Promise { + if (!this.logPath) { + return undefined; + } + + const response = await config.behaviors.cronjobExecution.findLog( + projectId, + this.logPath, + ); + + if (!response) { + return undefined; + } + + if (typeof response === "object") { + const parsedLine = this.parseLogLine(JSON.stringify(response)); + return parsedLine ? [parsedLine] : undefined; + } + + if (typeof response !== "string") { + return undefined; + } + + try { + const lines = response.trim().split("\n"); + const parsedLines: StructuredLogLine[] = []; + + for (const line of lines) { + const trimmedLine = line.trim(); + if (!trimmedLine) continue; + + const parsedLine = this.parseLogLine(trimmedLine); + if (parsedLine) { + parsedLines.push(parsedLine); + } + } + + return parsedLines.length > 0 ? parsedLines : undefined; + } catch { + return undefined; + } + } + + public async getExecutionAnalysis( + language?: "de" | "en", + requestConfig?: AxiosRequestConfig, + ) { + return await config.behaviors.cronjobExecution.getExecutionAnalysis( + this.id, + this.cronjob.id, + language, + requestConfig, + ); + } + + public async getLogDownload( + projectId: string, + ): Promise { + const log = await this.findLog(projectId); + if (!log) { + return undefined; + } + return { filename: "cronjob.log", content: log }; + } + + private parseLogLine(line: string): StructuredLogLine | null { + try { + const parsed = JSON.parse(line); + + if ( + !parsed || + typeof parsed.message !== "string" || + typeof parsed.dev !== "string" + ) { + return null; + } + + const message = + typeof parsed.time === "string" + ? `${parsed.time} ${parsed.message}` + : parsed.message; + + return { + stream: parsed.dev === "stderr" ? "stderr" : "stdout", + message, + }; + } catch { + return null; + } + } +} + +export class CronjobExecutionDetailed extends CronjobExecutionCommon { + public override readonly data: CronjobExecutionData; + public constructor(data: CronjobExecutionData, cronjob: Cronjob) { + super(data, cronjob); + this.data = data; + } +} + +export class CronjobExecutionListItem extends CronjobExecutionCommon { + public override readonly data: CronjobExecutionListItemData; + public constructor(data: CronjobExecutionListItemData, cronjob: Cronjob) { + super(data, cronjob); + this.data = data; + } +} + +export class CronjobExecutionListQuery extends ListQueryModel { + public readonly cronjob: Cronjob; + + public constructor( + cronjob: Cronjob, + query: CronjobExecutionListQueryData = {}, + ) { + super(query, { + dependencies: [cronjob.id], + }); + this.cronjob = cronjob; + } + + public async execute() { + const { totalCount, items } = await config.behaviors.cronjobExecution.list( + this.cronjob.id, + this.query, + ); + return new CronjobExecutionList( + this.cronjob, + this.query, + items.map((d) => new CronjobExecutionListItem(d, this.cronjob)), + totalCount, + ); + } + + public async getTotalCount() { + const { totalCount } = await this.refine({ limit: 1 }).execute(); + return totalCount; + } + + public refine(query: CronjobExecutionListQueryData) { + return new CronjobExecutionListQuery(this.cronjob, { + ...this.query, + ...query, + }); + } +} + +export class CronjobExecutionList extends WithListData()( + CronjobExecutionListQuery, +) { + public override readonly items: readonly CronjobExecutionListItem[]; + public override readonly totalCount: number; + public constructor( + cronjob: Cronjob, + query: CronjobExecutionListQueryData, + cronjobExecutions: CronjobExecutionListItem[], + totalCount: number, + ) { + super(cronjob, query); + this.items = Object.freeze(cronjobExecutions); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/cronjob/CronjobExecution/behaviors/api.ts b/packages/models/src/cronjob/CronjobExecution/behaviors/api.ts new file mode 100644 index 00000000..00a6e64a --- /dev/null +++ b/packages/models/src/cronjob/CronjobExecution/behaviors/api.ts @@ -0,0 +1,71 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { CronjobExecutionBehaviors } from "./types.js"; + +import { + withAxiosRequestConfig, + resolveTotalCount, +} from "../../../base/index.js"; +import { validateResponse } from "../../../base/api/validateResponse.js"; + +export const apiCronjobExecutionBehaviors = ( + client: MittwaldAPIV2Client, +): CronjobExecutionBehaviors => ({ + getExecutionAnalysis: async ( + executionId, + cronjobId, + language, + requestConfig, + ) => { + const response = await client.cronjob.getExecutionAnalysis( + { + headers: language ? { "Accept-Language": language } : undefined, + executionId, + cronjobId, + }, + withAxiosRequestConfig(requestConfig), + ); + + validateResponse(response, 200); + + return response.data; + }, + + list: async (cronjobId, query) => { + const response = await client.cronjob.listExecutions({ + queryParameters: query, + cronjobId, + }); + + validateResponse(response, 200); + + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + findLog: async (projectId, logPath) => { + const response = await client.projectFileSystem.getFileContent({ + queryParameters: { file: logPath }, + projectId, + }); + + if (response.status === 200) { + return response.data; + } + validateResponse(response, 404); + }, + + find: async (executionId, cronjobId) => { + const response = await client.cronjob.getExecution({ + executionId, + cronjobId, + }); + + if (response.status === 200) { + return response.data; + } + validateResponse(response, 404); + }, +}); diff --git a/packages/models/src/cronjob/CronjobExecution/behaviors/index.ts b/packages/models/src/cronjob/CronjobExecution/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/cronjob/CronjobExecution/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/cronjob/CronjobExecution/behaviors/types.ts b/packages/models/src/cronjob/CronjobExecution/behaviors/types.ts new file mode 100644 index 00000000..1de9d5ac --- /dev/null +++ b/packages/models/src/cronjob/CronjobExecution/behaviors/types.ts @@ -0,0 +1,34 @@ +import type { AxiosRequestConfig } from "axios"; + +import type { CronjobLogData } from "../../Cronjob/types.js"; +import type { QueryResponseData } from "../../../base/index.js"; +import type { + CronjobExecutionListQueryData, + CronjobExecutionAnalysisData, + CronjobExecutionListItemData, + CronjobExecutionData, +} from "../types.js"; + +export interface CronjobExecutionBehaviors { + getExecutionAnalysis: ( + executionId: string, + cronjobId: string, + language?: "de" | "en", + requestConfig?: AxiosRequestConfig, + ) => Promise; + + list: ( + cronjobId: string, + query?: CronjobExecutionListQueryData, + ) => Promise>; + + find: ( + executionId: string, + cronjobId: string, + ) => Promise; + + findLog: ( + projectId: string, + logPath: string, + ) => Promise; +} diff --git a/packages/models/src/cronjob/CronjobExecution/index.ts b/packages/models/src/cronjob/CronjobExecution/index.ts new file mode 100644 index 00000000..a67b7535 --- /dev/null +++ b/packages/models/src/cronjob/CronjobExecution/index.ts @@ -0,0 +1,2 @@ +export * from "./CronjobExecution.js"; +export * from "./types.js"; diff --git a/packages/models/src/cronjob/CronjobExecution/types.ts b/packages/models/src/cronjob/CronjobExecution/types.ts new file mode 100644 index 00000000..1443c876 --- /dev/null +++ b/packages/models/src/cronjob/CronjobExecution/types.ts @@ -0,0 +1,20 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type CronjobExecutionData = + MittwaldAPIV2.Operations.CronjobGetExecution.ResponseData; + +export type CronjobExecutionListItemData = + MittwaldAPIV2.Operations.CronjobListExecutions.ResponseData[number]; + +export type CronjobExecutionListQueryData = + MittwaldAPIV2.Paths.V2CronjobsCronjobIdExecutions.Get.Parameters.Query; + +export type CronjobExecutionStatus = CronjobExecutionData["status"]; + +export type CronjobExecutionAnalysisData = + MittwaldAPIV2.Components.Schemas.CronjobCronjobExecutionAnalysis; + +export interface StructuredLogLine { + stream: "stdout" | "stderr"; + message: string; +} diff --git a/packages/models/src/cronjob/index.ts b/packages/models/src/cronjob/index.ts new file mode 100644 index 00000000..e711c318 --- /dev/null +++ b/packages/models/src/cronjob/index.ts @@ -0,0 +1,2 @@ +export * from "./Cronjob/index.js"; +export * from "./CronjobExecution/index.js"; diff --git a/packages/models/src/customer/ContractPartner/ContractPartner.test.ts b/packages/models/src/customer/ContractPartner/ContractPartner.test.ts new file mode 100644 index 00000000..f751ef54 --- /dev/null +++ b/packages/models/src/customer/ContractPartner/ContractPartner.test.ts @@ -0,0 +1,52 @@ +import { afterEach, describe, expect, test } from "vitest"; + +import { buildContractPartnerData } from "../../testing/builders/buildContractPartnerData.js"; +import { resetBehaviors } from "../../testing/installBehaviors.js"; +import { ContractPartner } from "./ContractPartner.js"; + +afterEach(resetBehaviors); + +describe("ContractPartner", () => { + test("exposes contact data and derived values", () => { + const data = buildContractPartnerData(); + const partner = new ContractPartner(data); + + expect(partner.fullName).toBe("Ada Lovelace"); + expect(partner.phoneNumber).toBe("+49 431 123456"); + expect(partner.address).toBe(data.address); + expect(partner.salutation).toBe(data.salutation); + expect(partner.emailAddress).toBe(data.emailAddress); + expect(partner.company).toBe(data.company); + expect(partner.leitwegId).toBe(data.leitwegId); + }); + + test("exposes the purchase order reference", () => { + const partner = new ContractPartner( + buildContractPartnerData({ + purchaseOrderReference: "PO-12345", + leitwegId: undefined, + }), + ); + + expect(partner.purchaseOrderReference).toBe("PO-12345"); + }); + + test("leaves full name undefined when either name is missing", () => { + const partner = new ContractPartner( + buildContractPartnerData({ firstName: undefined }), + ); + + expect(partner.fullName).toBeUndefined(); + }); + + test.each([undefined, []])( + "leaves phone number undefined for %j phone numbers", + (phoneNumbers) => { + const partner = new ContractPartner( + buildContractPartnerData({ phoneNumbers }), + ); + + expect(partner.phoneNumber).toBeUndefined(); + }, + ); +}); diff --git a/packages/models/src/customer/ContractPartner/ContractPartner.ts b/packages/models/src/customer/ContractPartner/ContractPartner.ts new file mode 100644 index 00000000..0d743e3a --- /dev/null +++ b/packages/models/src/customer/ContractPartner/ContractPartner.ts @@ -0,0 +1,35 @@ +import type { ContractPartnerData, Salutation, Address } from "./types.js"; + +import { DataModel } from "../../base/index.js"; + +export class ContractPartner extends DataModel { + public readonly address: Address; + public readonly company?: string; + public readonly emailAddress?: string; + public readonly firstName?: string; + public readonly fullName?: string; + public readonly lastName?: string; + public readonly leitwegId?: string; + public readonly phoneNumber?: string; + public readonly purchaseOrderReference?: string; + public readonly salutation?: Salutation; + public readonly title?: string; + public readonly useFormalTerm?: boolean; + public constructor(data: ContractPartnerData) { + super(data); + this.firstName = data.firstName; + this.lastName = data.lastName; + if (data.firstName && data.lastName) { + this.fullName = `${data.firstName} ${data.lastName}`; + } + this.phoneNumber = data.phoneNumbers?.[0]; + this.address = data.address; + this.salutation = data.salutation; + this.title = data.title; + this.useFormalTerm = data.useFormalTerm; + this.emailAddress = data.emailAddress; + this.company = data.company; + this.leitwegId = data.leitwegId; + this.purchaseOrderReference = data.purchaseOrderReference; + } +} diff --git a/packages/models/src/customer/ContractPartner/index.ts b/packages/models/src/customer/ContractPartner/index.ts new file mode 100644 index 00000000..7ea6ab2b --- /dev/null +++ b/packages/models/src/customer/ContractPartner/index.ts @@ -0,0 +1,2 @@ +export * from "./ContractPartner.js"; +export * from "./types.js"; diff --git a/packages/models/src/customer/ContractPartner/types.ts b/packages/models/src/customer/ContractPartner/types.ts new file mode 100644 index 00000000..5827e84b --- /dev/null +++ b/packages/models/src/customer/ContractPartner/types.ts @@ -0,0 +1,8 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type ContractPartnerData = + MittwaldAPIV2.Components.Schemas.CustomerContact; + +export type Address = MittwaldAPIV2.Components.Schemas.CommonsAddress; + +export type Salutation = MittwaldAPIV2.Components.Schemas.CommonsSalutation; diff --git a/packages/models/src/customer/Customer/Customer.test.ts b/packages/models/src/customer/Customer/Customer.test.ts new file mode 100644 index 00000000..9a77716c --- /dev/null +++ b/packages/models/src/customer/Customer/Customer.test.ts @@ -0,0 +1,296 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; +import { DateTime } from "luxon"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { buildContractPartnerData } from "../../testing/builders/buildContractPartnerData.js"; +import { customerPermissions } from "../customerPermissions.js"; +import { ContractPartner } from "../ContractPartner/index.js"; +import { + buildCustomerListItemData, + buildCustomerData, +} from "../../testing/builders/buildCustomerData.js"; +import { config } from "../../config/config.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { + CustomerDetailed, + CustomerListItem, + CustomerList, + Customer, +} from "./Customer.js"; + +afterEach(resetBehaviors); + +describe("Customer delegation", () => { + test("find returns a detailed customer", async () => { + const find = vi.fn().mockResolvedValue(buildCustomerData()); + installBehaviors({ customer: { find } }); + + const result = await Customer.find("customer-id"); + + expect(find).toHaveBeenCalledWith("customer-id", undefined); + expect(result).toBeInstanceOf(CustomerDetailed); + }); + + test("find returns undefined for a missing customer", async () => { + installBehaviors({ + customer: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(Customer.find("missing")).resolves.toBeUndefined(); + }); + + test("create delegates and returns a reference", async () => { + const create = vi.fn().mockResolvedValue({ id: "created-id" }); + installBehaviors({ customer: { create } }); + + const result = await Customer.create({ name: "Created" }); + + expect(create).toHaveBeenCalledWith( + expect.objectContaining({ name: "Created" }), + ); + expect(result).toBeInstanceOf(Customer); + expect(result.id).toBe("created-id"); + }); + + test("create maps an owner phone number to the API shape", async () => { + const create = vi.fn().mockResolvedValue({ id: "created-id" }); + installBehaviors({ customer: { create } }); + const owner = { + address: buildContractPartnerData().address, + salutation: "other" as const, + phoneNumber: "+49 111", + }; + + await Customer.create({ name: "Created", owner }); + + expect(create).toHaveBeenCalledWith( + expect.objectContaining({ + owner: expect.objectContaining({ phoneNumbers: ["+49 111"] }), + }), + ); + }); + + test("update delegates with the customer id", async () => { + const update = vi.fn().mockResolvedValue(undefined); + installBehaviors({ customer: { update } }); + + await Customer.ofId("customer-id").update({ name: "Updated" }); + + expect(update).toHaveBeenCalledWith( + "customer-id", + expect.objectContaining({ name: "Updated" }), + ); + }); + + test("renaming preserves the contract partner Leitweg ID", async () => { + const update = vi.fn().mockResolvedValue(undefined); + installBehaviors({ customer: { update } }); + const customer = new CustomerDetailed( + buildCustomerData({ owner: buildContractPartnerData() }), + ); + + await customer.updateName("Renamed"); + + expect(update).toHaveBeenCalledWith( + "customer-id", + expect.objectContaining({ + owner: expect.objectContaining({ leitwegId: "04011000-12345-67" }), + }), + ); + }); + + test("renaming preserves the purchase order reference", async () => { + const update = vi.fn().mockResolvedValue(undefined); + installBehaviors({ customer: { update } }); + const customer = new CustomerDetailed( + buildCustomerData({ + owner: buildContractPartnerData({ + purchaseOrderReference: "PO-12345", + leitwegId: undefined, + }), + }), + ); + + await customer.updateName("Renamed"); + + expect(update).toHaveBeenCalledWith( + "customer-id", + expect.objectContaining({ + owner: expect.objectContaining({ + purchaseOrderReference: "PO-12345", + }), + }), + ); + }); + + test("delete delegates with the customer id", async () => { + const deleteBehavior = vi.fn().mockResolvedValue(undefined); + installBehaviors({ customer: { delete: deleteBehavior } }); + + await Customer.ofId("customer-id").delete(); + + expect(deleteBehavior).toHaveBeenCalledWith("customer-id"); + }); +}); + +describe("Customer common variant", () => { + test("findCommon on a reference delegates to find and returns a common variant", async () => { + const find = vi.fn().mockResolvedValue(buildCustomerData()); + installBehaviors({ customer: { find } }); + + const result = await Customer.ofId("customer-id").findCommon(); + + expect(find).toHaveBeenCalledWith("customer-id", undefined); + expect(result).toBeInstanceOf(CustomerDetailed); + }); + + test("findCommon resolves undefined when the reference is not found", async () => { + installBehaviors({ + customer: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + Customer.ofId("missing").findCommon(), + ).resolves.toBeUndefined(); + }); + + test("getCommon on a reference delegates and returns a common variant", async () => { + const find = vi.fn().mockResolvedValue(buildCustomerData()); + installBehaviors({ customer: { find } }); + + const result = await Customer.ofId("customer-id").getCommon(); + + expect(result).toBeInstanceOf(CustomerDetailed); + }); + + test("getCommon rejects when the reference is not found", async () => { + installBehaviors({ + customer: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(Customer.ofId("missing").getCommon()).rejects.toThrow(); + }); + + test("findCommon on an already materialized model returns itself without another call", async () => { + const find = vi.fn(); + installBehaviors({ customer: { find } }); + const detailed = new CustomerDetailed(buildCustomerData()); + + const result = await detailed.findCommon(); + + expect(result).toBe(detailed); + expect(find).not.toHaveBeenCalled(); + }); + + test("getCommon on an already materialized model returns itself without another call", async () => { + const find = vi.fn(); + installBehaviors({ customer: { find } }); + const detailed = new CustomerDetailed(buildCustomerData()); + + const result = await detailed.getCommon(); + + expect(result).toBe(detailed); + expect(find).not.toHaveBeenCalled(); + }); + + test("leaves avatar, suspension and deletion locks undefined when absent", () => { + const customer = new CustomerDetailed(buildCustomerData()); + + expect(customer.avatar).toBeUndefined(); + expect(customer.suspendedSince).toBeUndefined(); + expect(customer.deletionProhibitedBy).toBeUndefined(); + }); +}); + +describe("Customer aggregate metadata", () => { + test("carries the customer aggregate identity", () => { + expect(Customer.aggregateMetaData).toEqual( + expect.objectContaining({ aggregate: "customer", domain: "customer" }), + ); + }); + + test("findAggregate wires the id into the aggregate metadata", () => { + expect(Customer.findAggregate("customer-id")).toEqual({ + aggregate: "customer", + domain: "customer", + id: "customer-id", + }); + expect(Customer.findAggregate()).toBeUndefined(); + }); +}); + +describe("Customer data", () => { + test("exposes derived customer values", () => { + const owner = buildContractPartnerData(); + const customer = new CustomerDetailed( + buildCustomerData({ + activeSuspension: { createdAt: "2024-02-01T00:00:00.000Z" }, + levelOfUndeliverableDunningNotice: "first", + executingUserRoles: ["owner"], + name: "Named", + owner, + }), + ); + + expect(customer.name).toBe("Named"); + expect(customer.contractPartner).toBeInstanceOf(ContractPartner); + expect(customer.ownRole).toBe("owner"); + expect(customer.undeliverableDunningNotice).toBe(true); + expect(customer.suspendedSince).toBeInstanceOf(DateTime); + }); + + test("uses fallbacks when optional derived data is absent", () => { + const customer = new CustomerDetailed(buildCustomerData()); + + expect(customer.contractPartner).toBeUndefined(); + expect(customer.ownRole).toBe("notset"); + expect(customer.undeliverableDunningNotice).toBe(false); + }); + + test("checks permissions against the customer's role", () => { + expect(customerPermissions.deleteCustomer).toEqual(["owner"]); + const owner = new CustomerDetailed( + buildCustomerData({ executingUserRoles: ["owner"] }), + ); + const member = new CustomerDetailed( + buildCustomerData({ executingUserRoles: ["member"] }), + ); + + expect(owner.hasPermission("deleteCustomer")).toBe(true); + expect(member.hasPermission("deleteCustomer")).toBe(false); + }); +}); + +describe("Customer list query", () => { + test("applies pagination, sorts items, and materializes the list", async () => { + const list = vi.fn().mockResolvedValue({ + items: [ + buildCustomerListItemData({ customerId: "c-2", name: "Zeta" }), + buildCustomerListItemData({ customerId: "c-1", name: "Alpha" }), + ], + totalCount: 2, + }); + installBehaviors({ customer: { list } }); + + const result = await Customer.query().execute(); + + expect(result).toBeInstanceOf(CustomerList); + expect(result.items.every((item) => item instanceof CustomerListItem)).toBe( + true, + ); + expect(result.items.map((item) => item.name)).toEqual(["Alpha", "Zeta"]); + expect(list).toHaveBeenCalledWith( + expect.objectContaining({ limit: config.defaultPaginationLimit }), + ); + }); +}); diff --git a/packages/models/src/customer/Customer/Customer.ts b/packages/models/src/customer/Customer/Customer.ts index 508be00f..e33682ba 100644 --- a/packages/models/src/customer/Customer/Customer.ts +++ b/packages/models/src/customer/Customer/Customer.ts @@ -1,110 +1,404 @@ -import { config } from "../../config/config.js"; -import { classes } from "polytype"; -import { DataModel } from "../../base/DataModel.js"; -import assertObjectFound from "../../base/assertObjectFound.js"; -import { ReferenceModel } from "../../base/ReferenceModel.js"; -import { - AsyncResourceVariant, - provideReact, -} from "../../react/provideReact.js"; -import { - CustomerData, - CustomerListItemData, +import type { AxiosRequestConfig } from "axios"; + +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; + +import type { ProjectListQuery as ProjectListQueryType } from "../../project/index.js"; +import type { ExtensionInstanceListQuery } from "../../marketplace/index.js"; +import type { CustomerPermission } from "../customerPermissions.js"; +import type { ContractListQuery } from "../../contract/index.js"; +import type { InvoiceListQuery } from "../../invoice/index.js"; +import type { ServerListQuery } from "../../server/index.js"; +import type { OrderListQuery } from "../../order/index.js"; +import type { + CustomerMembershipListQuery, + CustomerRole, +} from "../CustomerMembership/index.js"; +import type { + CustomerInviteCreateRequestData, + CustomerInviteListQuery, +} from "../CustomerInvite/index.js"; +import type { + CustomerAIModelListQuery, + CustomerAIPlanListQuery, +} from "../../ai/index.js"; +import type { + CustomerExpressInterestToContributeRequestData, + CustomerVatIdValidationState, + CustomerExecutingUserRoles, + ContractPartnerModelData, CustomerListQueryData, - CustomerUpdateRequestData, + CustomerListItemData, + CustomerData, } from "./types.js"; -import { ListQueryModel } from "../../base/ListQueryModel.js"; -import { ListDataModel } from "../../base/ListDataModel.js"; -import { ServerListQuery } from "../../server/index.js"; -import { ProjectListQuery } from "../../project/index.js"; +import { ExtensionInstance } from "../../marketplace/ExtensionInstance/ExtensionInstance.js"; +import { CustomerAvatarAccessTokenProvider } from "./CustomerAvatarAccessTokenProvider.js"; +import { CustomerAIModel } from "../../ai/CustomerAIModel/CustomerAIModel.js"; +import { CustomerAIPlan } from "../../ai/CustomerAIPlan/CustomerAIPlan.js"; +import { + type FileAccessTokenProvider, + type DomFile, +} from "../../file/index.js"; +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { customerPermissions } from "../customerPermissions.js"; +import { Contract } from "../../contract/Contract/Contract.js"; +import { CustomerMembership } from "../CustomerMembership/index.js"; +import { ProjectListQuery } from "../../project/internal.js"; +import { Invoice } from "../../invoice/Invoice/Invoice.js"; +import { ContractPartner } from "../ContractPartner/index.js"; +import { InvoiceSettings } from "../InvoiceSettings/index.js"; +import { Server } from "../../server/Server/Server.js"; +import { CustomerInvite } from "../CustomerInvite/index.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { Contributor } from "../../marketplace/index.js"; +import { Order } from "../../order/Order/Order.js"; +import { File } from "../../file/File/internal.js"; +import { config } from "../../config/index.js"; +import { User } from "../../user/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "Customer", +}) export class Customer extends ReferenceModel { + public static aggregateMetaData = new AggregateMetaData( + "customer", + "customer", + ); + public readonly aiModelsQuery: CustomerAIModelListQuery; + public readonly aiPlans: CustomerAIPlanListQuery; + + public readonly contracts: ContractListQuery; + + public readonly extensionInstances: ExtensionInstanceListQuery; + + public readonly fileAccessTokenProvider: FileAccessTokenProvider; + public readonly invites: CustomerInviteListQuery; + + public readonly invoices: InvoiceListQuery; + + public readonly invoiceSettings: InvoiceSettings; + + public readonly memberships: CustomerMembershipListQuery; + public readonly orders: OrderListQuery; + public readonly projects: ProjectListQueryType; + public readonly servers: ServerListQuery; - public readonly projects: ProjectListQuery; public constructor(id: string) { super(id); - this.servers = new ServerListQuery({ - customer: this, - }); + this.fileAccessTokenProvider = new CustomerAvatarAccessTokenProvider(this); this.projects = new ProjectListQuery({ customer: this, }); + this.invites = CustomerInvite.query(this); + this.memberships = CustomerMembership.query(this); + this.contracts = Contract.query({ customer: this }); + this.invoices = Invoice.query({ customer: this }); + this.orders = Order.query({ customer: this }); + this.servers = Server.query({ customer: id }); + this.invoiceSettings = InvoiceSettings.ofCustomerId(id); + this.extensionInstances = ExtensionInstance.query({ customer: id }); + this.aiPlans = CustomerAIPlan.query(this.id); + this.aiModelsQuery = CustomerAIModel.query(this.id); } - public static ofId(id: string): Customer { - return new Customer(id); + public static async create(data: { + owner?: ContractPartnerModelData; + vatId?: string; + name: string; + }) { + const { vatId, owner, name } = data; + + const response = await config.behaviors.customer.create({ + owner: owner + ? { + ...owner, + phoneNumbers: owner.phoneNumber ? [owner.phoneNumber] : undefined, + } + : undefined, + vatId: vatId ?? undefined, + name, + }); + + return new Customer(response.id); } - public static find = provideReact( - async (id: string): Promise => { - const data = await config.behaviors.customer.find(id); - if (data !== undefined) { - return new CustomerDetailed(data); - } - }, - ); + public static async find(id: string, options?: AxiosRequestConfig) { + const data = await config.behaviors.customer.find(id, options); + if (data) { + return new CustomerDetailed(data); + } + } + + public static findAggregate(customerId?: string) { + return customerId + ? { id: customerId, ...Customer.aggregateMetaData } + : undefined; + } + + public static async get(id: string, options?: AxiosRequestConfig) { + const customer = await this.find(id, options); + assertObjectFound(customer, Customer, id); + return customer; + } + + public static ofId(id: string) { + return new Customer(id); + } public static query(query: CustomerListQueryData = {}) { return new CustomerListQuery(query); } - /** @deprecated Use query() */ - public static list = provideReact( - async ( - query: CustomerListQueryData = {}, - ): Promise>> => - new CustomerListQuery(query).execute().then((res) => res.items), - ); + public async delete() { + await config.behaviors.customer.delete(this.id); + } - public static get = provideReact( - async (id: string): Promise => { - const customer = await this.find(id); - assertObjectFound(customer, this, id); - return customer; - }, - ); + public async expressInterestToContribute( + customerData: CustomerExpressInterestToContributeRequestData, + ) { + const response = + await config.behaviors.customer.expressInterestToContribute( + this.id, + customerData, + ); + + return response; + } + + public async findCommon( + options?: AxiosRequestConfig, + ): Promise { + return this instanceof CustomerCommon ? this : this.findDetailed(options); + } + + public async findContributor() { + return Contributor.find(this.id); + } + + public async findDetailed( + options?: AxiosRequestConfig, + ): Promise { + return Customer.find(this.id, options); + } - public getDetailed = provideReact( - () => Customer.get(this.id), - [this.id], - ) as AsyncResourceVariant<() => Promise>; + public async findOpenExtensionOrders() { + return await ExtensionInstance.listOpenOrders(this); + } + + public async findPaymentMethod() { + return config.behaviors.customer.findMarketplacePaymentMethod(this.id); + } + + public async getAvatarUploadRules() { + return File.getUploadRules("avatar"); + } + + public async getBillingPortalLink() { + return await config.behaviors.customer.getBillingPortalLink(this.id); + } + + public async getCommon( + options?: AxiosRequestConfig, + ): Promise { + return this instanceof CustomerCommon ? this : this.getDetailed(options); + } + + public async getDetailed( + options?: AxiosRequestConfig, + ): Promise { + return Customer.get(this.id, options); + } + + public async getOwnMembership() { + return await CustomerMembership.getOwn(this); + } - public findDetailed = provideReact( - () => Customer.find(this.id), - [this.id], - ) as AsyncResourceVariant<() => Promise>; + public async inviteMember(data: CustomerInviteCreateRequestData) { + return CustomerInvite.create(this, data); + } - public async update(data: CustomerUpdateRequestData): Promise { - await config.behaviors.customer.update(this.id, data); + public async isBankrupt(options?: AxiosRequestConfig) { + const invoiceSettings = await this.invoiceSettings.findDetailed({ + ...options, + retryCache: { + retry: false, + }, + }); + return !!invoiceSettings?.isBankrupt; + } + + public async removeAvatar() { + await config.behaviors.customer.removeAvatar(this.id); + } + + public async requestAvatarUpload(): Promise { + const response = await config.behaviors.customer.createAvatarUploadToken( + this.id, + ); + + return response.token; + } + + public async suggestReward(suggestion: string) { + await config.behaviors.customer.createRecommendationSuggestion( + this.id, + suggestion, + ); + } + + public async update(data: { + owner?: ContractPartnerModelData; + vatId?: string; + name: string; + }) { + const { vatId, owner, name } = data; + + await config.behaviors.customer.update(this.id, { + owner: owner + ? { + ...owner, + phoneNumbers: owner.phoneNumber ? [owner.phoneNumber] : undefined, + } + : undefined, + vatId, + name, + }); + } + + public async updatePaymentMethod( + contextId: string, + currentUrl: string, + variantKey?: string, + ) { + const returnUrl = new URL(currentUrl); + returnUrl.searchParams.set("paymentDataFilled", ""); + returnUrl.searchParams.set("contextId", contextId); + if (variantKey) { + returnUrl.searchParams.set("variantKey", variantKey); + } + + return await config.behaviors.customer.updateMarketplacePaymentMethod( + this.id, + returnUrl.toString(), + ); + } + + public async uploadAvatar(file: DomFile) { + await File.upload(file, this.fileAccessTokenProvider); } } -// Common class for future extension -class CustomerCommon extends classes( - DataModel, - Customer, -) { +export class CustomerCommon extends WithData< + CustomerListItemData | CustomerData +>()(Customer) { + public readonly avatar?: File; + public readonly avatarRefId?: string; + public readonly contractPartner?: ContractPartner; + public readonly creationDate?: string; + public readonly customerNumber?: string; + public override readonly data: CustomerListItemData | CustomerData; + public readonly deletionProhibitedBy?: string[]; + public readonly executingUserRoles?: CustomerExecutingUserRoles[]; + public readonly isAllowedToPlaceOrders: boolean; + public readonly isBanned?: boolean; + public readonly isInDefaultOfPayment?: boolean; + public readonly isPublicSector?: boolean; + public readonly memberCount: number; + public readonly name: string; + public readonly ownRole: CustomerRole; + public readonly projectCount: number; + public readonly suspendedSince?: DateTime; + public readonly undeliverableDunningNotice?: boolean; + public readonly vatId?: string; + public readonly vatIdValidationState?: CustomerVatIdValidationState; + + public get isEligible(): boolean { + return !this.isBanned && this.isAllowedToPlaceOrders; + } + public constructor(data: CustomerListItemData | CustomerData) { - super([data], [data.customerId]); + super(data.customerId); + this.data = data; + this.name = data.name; + if (data.owner) { + this.contractPartner = new ContractPartner(data.owner); + this.isPublicSector = !!data.owner.leitwegId; + } + this.avatar = data.avatarRefId ? File.ofId(data.avatarRefId) : undefined; + this.vatId = data.vatId; + this.isBanned = data.isBanned; + if (data.activeSuspension) { + this.suspendedSince = DateTime.fromISO(data.activeSuspension?.createdAt); + } + this.creationDate = data.creationDate; + this.memberCount = data.memberCount; + this.projectCount = data.projectCount; + this.vatIdValidationState = data.vatIdValidationState; + this.executingUserRoles = data.executingUserRoles; + this.avatarRefId = data.avatarRefId; + this.customerNumber = data.customerNumber; + this.isInDefaultOfPayment = data.isInDefaultOfPayment; + this.ownRole = data.executingUserRoles?.[0] ?? "notset"; + this.isAllowedToPlaceOrders = data.isAllowedToPlaceOrders ?? true; + this.undeliverableDunningNotice = !!data.levelOfUndeliverableDunningNotice; + this.deletionProhibitedBy = data.deletionProhibitedBy; + } + + public hasPermission(permission: CustomerPermission) { + return customerPermissions[permission].includes(this.ownRole); + } + + public async updateContractPartner(data: { + owner: ContractPartnerModelData; + vatId?: string; + }) { + const { owner, vatId } = data; + + return await this.update({ name: this.name, vatId, owner }); + } + + public async updateName(name: string) { + return await this.update({ + owner: this.contractPartner + ? { + purchaseOrderReference: this.contractPartner.purchaseOrderReference, + salutation: this.contractPartner.salutation ?? "other", + emailAddress: this.contractPartner.emailAddress, + phoneNumber: this.contractPartner.phoneNumber, + address: { ...this.contractPartner.address }, + firstName: this.contractPartner.firstName, + leitwegId: this.contractPartner.leitwegId, + lastName: this.contractPartner.lastName, + company: this.contractPartner.company, + } + : undefined, + vatId: this.vatId, + name, + }); } } -export class CustomerDetailed extends classes( - CustomerCommon, - DataModel, -) { +export class CustomerDetailed extends CustomerCommon { + public override readonly data: CustomerData; public constructor(data: CustomerData) { - super([data], [data]); + super(data); + this.data = data; } } -export class CustomerListItem extends classes( - CustomerCommon, - DataModel, -) { +export class CustomerListItem extends CustomerCommon { + public override readonly data: CustomerListItemData; public constructor(data: CustomerListItemData) { - super([data], [data]); + super(data); + this.data = data; } } @@ -113,48 +407,86 @@ export class CustomerListQuery extends ListQueryModel { super(query); } - public refine(query: CustomerListQueryData) { - return new CustomerListQuery({ - ...this.query, - ...query, - }); - } - - public execute = provideReact(async () => { - const { items, totalCount } = await config.behaviors.customer.list({ + public async execute() { + const { totalCount, items } = await config.behaviors.customer.list({ limit: config.defaultPaginationLimit, ...this.query, }); return new CustomerList( this.query, - items.map((d) => new CustomerListItem(d)), + items + .map((d) => new CustomerListItem(d)) + .sort((a, b) => a.name.localeCompare(b.name)), totalCount, ); - }, [this.queryId]); + } - public getTotalCount = provideReact(async () => { + public async getTotalCount() { const { totalCount } = await this.refine({ limit: 1 }).execute(); return totalCount; - }, [this.queryId]); + } + + public async hasAnyCustomerWhereIsLastOwner(): Promise { + const currentUser = await User.self.getCommon(); + const limit = config.defaultPaginationLimit; + + const currentUserIsLastOwner = async ( + customer: CustomerListItem, + ): Promise => { + if (!customer.executingUserRoles?.includes("owner")) { + return false; + } - public findOneAndOnly = provideReact(async () => { - const { items, totalCount } = await this.refine({ limit: 2 }).execute(); - if (totalCount === 1) { - return items[0]; + const { items: memberships } = await customer.memberships.execute(); + const ownMembership = memberships.find( + (membership) => membership.user.id === currentUser.id, + ); + + return ( + !!ownMembership && + !!CustomerMembership.memberIsLastOwner(memberships, ownMembership) + ); + }; + + for (let skip = 0; ; skip += limit) { + const customerList = await this.refine({ + limit, + skip, + }).execute(); + + for (const customer of customerList.items) { + if (await currentUserIsLastOwner(customer)) { + return true; + } + } + + if (skip + customerList.items.length >= customerList.totalCount) { + return false; + } } - }, [this.queryId]); + } + + public refine(query: CustomerListQueryData) { + return new CustomerListQuery({ + ...this.query, + ...query, + }); + } } -export class CustomerList extends classes( +export class CustomerList extends WithListData()( CustomerListQuery, - ListDataModel, ) { + public override readonly items: readonly CustomerListItem[]; + public override readonly totalCount: number; public constructor( query: CustomerListQueryData, customers: CustomerListItem[], totalCount: number, ) { - super([query], [customers, totalCount]); + super(query); + this.items = Object.freeze(customers); + this.totalCount = totalCount; } } diff --git a/packages/models/src/customer/Customer/CustomerAvatarAccessTokenProvider.ts b/packages/models/src/customer/Customer/CustomerAvatarAccessTokenProvider.ts new file mode 100644 index 00000000..1140ce08 --- /dev/null +++ b/packages/models/src/customer/Customer/CustomerAvatarAccessTokenProvider.ts @@ -0,0 +1,16 @@ +import type { FileAccessTokenProvider } from "../../file/index.js"; +import type { Customer } from "./Customer.js"; + +import { config } from "../../config/index.js"; + +export class CustomerAvatarAccessTokenProvider implements FileAccessTokenProvider { + public readonly customer: Customer; + + public constructor(customer: Customer) { + this.customer = customer; + } + + public createUploadToken() { + return config.behaviors.customer.createAvatarUploadToken(this.customer.id); + } +} diff --git a/packages/models/src/customer/Customer/behaviors/api.ts b/packages/models/src/customer/Customer/behaviors/api.ts index a1eb4cb5..5b861a7d 100644 --- a/packages/models/src/customer/Customer/behaviors/api.ts +++ b/packages/models/src/customer/Customer/behaviors/api.ts @@ -1,41 +1,159 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; +import type { AxiosRequestConfig } from "axios"; + +import type { CustomerCreateRequestData } from "../types.js"; +import type { CustomerBehaviors } from "./types.js"; + import { - assertStatus, - MittwaldAPIV2Client, - extractTotalCountHeader, -} from "@mittwald/api-client"; -import { assertOneOfStatus } from "@mittwald/api-client"; -import { CustomerBehaviors } from "./types.js"; + withAxiosRequestConfig, + resolveTotalCount, +} from "../../../base/index.js"; +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { anyStatus403 } from "../../../base/api/typeFixes.js"; export const apiCustomerBehaviors = ( client: MittwaldAPIV2Client, ): CustomerBehaviors => ({ - find: async (id) => { - const response = await client.customer.getCustomer({ - customerId: id, + findMarketplacePaymentMethod: async (customerId) => { + const response = await client.marketplace.customerGetPaymentMethod({ + customerId, + }); + + if (response.status === 200) { + return response.data; + } + + // API-DRIFT: customerGetPaymentMethod omits 403 in its generated response type, so anyStatus403 (403 as any) is compared (resolve: use the literal 403 once the client type declares it) + if (response.status === anyStatus403) { + return "noAccess"; + } + + validateResponse(response, 404); + }, + + create: async (data: CustomerCreateRequestData) => { + const response = await client.customer.createCustomer({ + data, }); + validateResponse(response, 201, { + validationError: { + pathMappings: { + "owner.phoneNumbers": "owner.phoneNumber", + "address.zip": "owner.address.zip", + }, + }, + }); + return { id: response.data.customerId }; + }, + + update: async (customerId, data) => { + const response = await client.customer.updateCustomer({ + data: { ...data, customerId }, + customerId, + }); + + validateResponse(response, 200, { + validationError: { + pathMappings: { + "owner.phoneNumbers": "owner.phoneNumber", + "address.zip": "owner.address.zip", + }, + }, + }); + }, + + getBillingPortalLink: async (customerId) => { + const response = + await client.marketplace.contributorGetCustomerBillingPortalLink({ + customerId, + }); + + if (response.status === 404) { + return undefined; + } + + validateResponse(response, 200); + + return response.data.url; + }, + + find: async (customerId, options?: AxiosRequestConfig) => { + const response = await client.customer.getCustomer( + { customerId }, + withAxiosRequestConfig(options), + ); + if (response.status === 200) { return response.data; } - assertOneOfStatus(response, [404]); + validateResponse(response, [403, 404, 401]); + }, + + updateMarketplacePaymentMethod: async (customerId, customReturnUrl) => { + const response = await client.marketplace.customerUpdatePaymentMethod({ + data: { customReturnUrl }, + customerId, + }); + + validateResponse(response, 200); + + return response.data.url; + }, + + createAvatarUploadToken: async (customerId) => { + const response = await client.customer.requestAvatarUpload({ + customerId, + }); + validateResponse(response, 200); + return { + token: response.data.refId, + rules: response.data.rules, + }; + }, + + expressInterestToContribute: async (customerId, data) => { + const response = + await client.marketplace.contributorExpressInterestToContribute({ + customerId, + data, + }); + + validateResponse(response, 201); + + return response.data; }, list: async (query) => { const response = await client.customer.listCustomers({ queryParameters: query, }); - assertStatus(response, 200); + validateResponse(response, 200); return { + totalCount: resolveTotalCount(response), items: response.data, - totalCount: extractTotalCountHeader(response), }; }, - update: async (id, data) => { - const response = await client.customer.updateCustomer({ - customerId: id, - data, + createRecommendationSuggestion: async (customerId, suggestion) => { + const response = await client.customer.createRecommendationSuggestion({ + data: { suggestion }, + customerId, }); - assertStatus(response, 200); + + validateResponse(response, 201); + }, + + delete: async (customerId) => { + const response = await client.customer.deleteCustomer({ + customerId, + }); + validateResponse(response, 200); + }, + + removeAvatar: async (customerId) => { + const response = await client.customer.removeAvatar({ customerId }); + + validateResponse(response, 204); }, }); diff --git a/packages/models/src/customer/Customer/behaviors/types.ts b/packages/models/src/customer/Customer/behaviors/types.ts index 7ae8169c..6e81f51b 100644 --- a/packages/models/src/customer/Customer/behaviors/types.ts +++ b/packages/models/src/customer/Customer/behaviors/types.ts @@ -1,15 +1,53 @@ -import { +import type { AxiosRequestConfig } from "axios"; + +import type { FileUploadTokenData } from "../../../index.js"; +import type { QueryResponseData } from "../../../base/index.js"; +import type { + CustomerExpressInterestToContributeRequestData, + CustomerCreateRequestData, + CustomerPaymentMethodData, + CustomerUpdateRequestData, + CustomerListQueryData, CustomerListItemData, CustomerData, - CustomerListQueryData, - CustomerUpdateRequestData, } from "../types.js"; -import { QueryResponseData } from "../../../base/index.js"; export interface CustomerBehaviors { - find: (id: string) => Promise; + expressInterestToContribute: ( + customerId: string, + data: CustomerExpressInterestToContributeRequestData, + ) => Promise<{ id: string }>; + findMarketplacePaymentMethod: ( + customerId: string, + ) => Promise; + updateMarketplacePaymentMethod: ( + customerId: string, + customReturnUrl?: string, + ) => Promise; + find: ( + customerId: string, + options?: AxiosRequestConfig, + ) => Promise; + createRecommendationSuggestion: ( + customerId: string, + suggestion: string, + ) => Promise; + list: ( query?: CustomerListQueryData, ) => Promise>; - update: (id: string, data: CustomerUpdateRequestData) => Promise; + + update: ( + customerId: string, + data: CustomerUpdateRequestData, + ) => Promise; + + createAvatarUploadToken: (customerId: string) => Promise; + + getBillingPortalLink: (customerId: string) => Promise; + + create: (data: CustomerCreateRequestData) => Promise<{ id: string }>; + removeAvatar: (customerId: string) => Promise; + + delete: (customerId: string) => Promise; } diff --git a/packages/models/src/customer/Customer/types.ts b/packages/models/src/customer/Customer/types.ts index 56034576..e82cb7cb 100644 --- a/packages/models/src/customer/Customer/types.ts +++ b/packages/models/src/customer/Customer/types.ts @@ -1,4 +1,6 @@ -import { MittwaldAPIV2 } from "@mittwald/api-client"; +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import type { ContractPartnerData } from "../ContractPartner/index.js"; export type CustomerListQueryData = MittwaldAPIV2.Paths.V2Customers.Get.Parameters.Query; @@ -9,5 +11,30 @@ export type CustomerData = export type CustomerListItemData = MittwaldAPIV2.Operations.CustomerListCustomers.ResponseData[number]; -export type CustomerUpdateRequestData = - MittwaldAPIV2.Paths.V2CustomersCustomerId.Put.Parameters.RequestBody; +export type CustomerCreateRequestData = + MittwaldAPIV2.Paths.V2Customers.Post.Parameters.RequestBody; + +export type CustomerUpdateRequestData = Omit< + MittwaldAPIV2.Paths.V2CustomersCustomerId.Put.Parameters.RequestBody, + "customerId" +>; + +export type CustomerExpressInterestToContributeRequestData = + MittwaldAPIV2.Operations.ContributorExpressInterestToContribute.RequestData; + +export type ContractPartnerModelData = Omit< + ContractPartnerData, + "phoneNumbers" +> & { + phoneNumber?: string; +}; + +export type CustomerExecutingUserRoles = + MittwaldAPIV2.Components.Schemas.CustomerRole; + +export type CustomerVatIdValidationState = NonNullable< + MittwaldAPIV2.Components.Schemas.CustomerCustomer["vatIdValidationState"] +>; + +export type CustomerPaymentMethodData = + MittwaldAPIV2.Operations.MarketplaceCustomerGetPaymentMethod.ResponseData; diff --git a/packages/models/src/customer/CustomerInvite/CustomerInvite.test.ts b/packages/models/src/customer/CustomerInvite/CustomerInvite.test.ts new file mode 100644 index 00000000..c2d1e261 --- /dev/null +++ b/packages/models/src/customer/CustomerInvite/CustomerInvite.test.ts @@ -0,0 +1,203 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { + buildCustomerInviteListItemData, + buildCustomerInviteData, +} from "../../testing/builders/buildCustomerInviteData.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { Customer } from "../Customer/index.js"; +import { + CustomerInviteListQuery, + CustomerInviteDetailed, + CustomerInviteListItem, + CustomerInviteList, + CustomerInvite, +} from "./CustomerInvite.js"; + +afterEach(resetBehaviors); + +describe("CustomerInvite delegation", () => { + test("find returns a detailed invite", async () => { + const find = vi.fn().mockResolvedValue(buildCustomerInviteData()); + installBehaviors({ customerInvite: { find } }); + + const result = await CustomerInvite.find("invite-id"); + + expect(find).toHaveBeenCalledWith("invite-id"); + expect(result).toBeInstanceOf(CustomerInviteDetailed); + }); + + test("find returns undefined for a missing invite", async () => { + installBehaviors({ + customerInvite: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(CustomerInvite.find("missing")).resolves.toBeUndefined(); + }); + + test("get rejects for a missing invite", async () => { + installBehaviors({ + customerInvite: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(CustomerInvite.get("missing")).rejects.toThrow(); + }); + + test("create delegates with the customer id", async () => { + const create = vi.fn().mockResolvedValue({ id: "created-id" }); + installBehaviors({ customerInvite: { create } }); + const data = { + mailAddress: "invitee@example.com", + role: "member" as const, + message: "Join us", + }; + + const result = await CustomerInvite.create( + Customer.ofId("customer-id"), + data, + ); + + expect(create).toHaveBeenCalledWith("customer-id", data); + expect(result).toBeInstanceOf(CustomerInvite); + expect(result.id).toBe("created-id"); + }); + + test("delete delegates with the invite id", async () => { + const deleteBehavior = vi.fn().mockResolvedValue(undefined); + installBehaviors({ customerInvite: { delete: deleteBehavior } }); + + await CustomerInvite.ofId("invite-id").delete(); + + expect(deleteBehavior).toHaveBeenCalledWith("invite-id"); + }); + + test("acceptWithToken resolves and accepts the invite", async () => { + const getByToken = vi.fn().mockResolvedValue({ id: "invite-id" }); + const accept = vi.fn().mockResolvedValue(undefined); + installBehaviors({ customerInvite: { getByToken, accept } }); + + await CustomerInvite.acceptWithToken("token"); + + expect(getByToken).toHaveBeenCalledWith("token"); + expect(accept).toHaveBeenCalledWith("invite-id", "token"); + }); +}); + +describe("CustomerInvite common variant", () => { + test("findCommon on a reference delegates to find and returns a detailed invite", async () => { + const find = vi.fn().mockResolvedValue(buildCustomerInviteData()); + installBehaviors({ customerInvite: { find } }); + + const result = await CustomerInvite.ofId("invite-id").findCommon(); + + expect(find).toHaveBeenCalledWith("invite-id"); + expect(result).toBeInstanceOf(CustomerInviteDetailed); + }); + + test("findCommon resolves undefined when the reference is not found", async () => { + installBehaviors({ + customerInvite: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + CustomerInvite.ofId("missing").findCommon(), + ).resolves.toBeUndefined(); + }); + + test("getCommon rejects when the reference is not found", async () => { + installBehaviors({ + customerInvite: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(CustomerInvite.ofId("missing").getCommon()).rejects.toThrow(); + }); + + test("findCommon on an already materialized model returns itself without another call", async () => { + const find = vi.fn(); + installBehaviors({ customerInvite: { find } }); + const detailed = new CustomerInviteDetailed(buildCustomerInviteData()); + + const result = await detailed.findCommon(); + + expect(result).toBe(detailed); + expect(find).not.toHaveBeenCalled(); + }); + + test("getCommon on an already materialized model returns itself without another call", async () => { + const find = vi.fn(); + installBehaviors({ customerInvite: { find } }); + const detailed = new CustomerInviteDetailed(buildCustomerInviteData()); + + const result = await detailed.getCommon(); + + expect(result).toBe(detailed); + expect(find).not.toHaveBeenCalled(); + }); +}); + +describe("CustomerInvite aggregate metadata", () => { + test("carries the customer-invite aggregate identity", () => { + expect(CustomerInvite.aggregateMetaData).toEqual( + expect.objectContaining({ + aggregate: "customerinvite", + domain: "membership", + }), + ); + }); +}); + +describe("CustomerInvite data", () => { + test("leaves the message undefined when absent", () => { + const invite = new CustomerInviteDetailed( + buildCustomerInviteData({ message: undefined }), + ); + + expect(invite.message).toBeUndefined(); + }); +}); + +describe("CustomerInvite lists", () => { + test("listIncoming materializes list items", async () => { + installBehaviors({ + customerInvite: { + listIncoming: vi.fn().mockResolvedValue({ + items: [buildCustomerInviteListItemData()], + }), + }, + }); + + const result = await CustomerInvite.listIncoming(); + + expect(result).toHaveLength(1); + expect(result[0]).toBeInstanceOf(CustomerInviteListItem); + }); + + test("query delegates and materializes a list", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildCustomerInviteListItemData({ id: "i-1" })], + totalCount: 1, + }); + installBehaviors({ customerInvite: { list } }); + const customer = Customer.ofId("customer-id"); + const query = CustomerInvite.query(customer); + + const result = await query.execute(); + + expect(result).toBeInstanceOf(CustomerInviteList); + expect(result).toBeInstanceOf(CustomerInviteListQuery); + expect(result.items[0]).toBeInstanceOf(CustomerInviteListItem); + expect(list).toHaveBeenCalledWith("customer-id", {}); + expect(result.totalCount).toBe(1); + }); +}); diff --git a/packages/models/src/customer/CustomerInvite/CustomerInvite.ts b/packages/models/src/customer/CustomerInvite/CustomerInvite.ts new file mode 100644 index 00000000..66bef549 --- /dev/null +++ b/packages/models/src/customer/CustomerInvite/CustomerInvite.ts @@ -0,0 +1,203 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; + +import type { CustomerRole } from "../CustomerMembership/index.js"; +import type { + CustomerInviteCreateRequestData, + CustomerInviteListQueryData, + CustomerInviteListItemData, + CustomerInviteData, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { User } from "../../user/User/User.js"; +import { Customer } from "../Customer/index.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "CustomerInvite", +}) +export class CustomerInvite extends ReferenceModel { + public static aggregateMetaData = new AggregateMetaData( + "membership", + "customerinvite", + ); + + public static async acceptWithToken(invitationToken: string) { + const invite = + await config.behaviors.customerInvite.getByToken(invitationToken); + + await config.behaviors.customerInvite.accept(invite.id, invitationToken); + } + + public static async create( + customer: Customer, + data: CustomerInviteCreateRequestData, + ) { + const response = await config.behaviors.customerInvite.create( + customer.id, + data, + ); + + return new CustomerInvite(response.id); + } + + public static async find(id: string) { + const data = await config.behaviors.customerInvite.find(id); + if (data) { + return new CustomerInviteDetailed(data); + } + } + + public static async get(id: string) { + const customerInvite = await this.find(id); + assertObjectFound(customerInvite, CustomerInvite, id); + return customerInvite; + } + + public static async listIncoming() { + const data = await config.behaviors.customerInvite.listIncoming(); + + return data.items.map((i) => new CustomerInviteListItem(i)); + } + + public static ofId(id: string) { + return new CustomerInvite(id); + } + + public static query( + customer: Customer, + query: CustomerInviteListQueryData = {}, + ) { + return new CustomerInviteListQuery(customer, query); + } + + public async decline() { + await config.behaviors.customerInvite.decline(this.id); + } + + public async delete() { + await config.behaviors.customerInvite.delete(this.id); + } + + public async findCommon(): Promise { + return this instanceof CustomerInviteCommon ? this : this.findDetailed(); + } + + public async findDetailed(): Promise { + return CustomerInvite.find(this.id); + } + + public async getCommon(): Promise { + return this instanceof CustomerInviteCommon ? this : this.getDetailed(); + } + + public getDetailed(): Promise { + return CustomerInvite.get(this.id); + } +} + +export class CustomerInviteCommon extends WithData< + CustomerInviteListItemData | CustomerInviteData +>()(CustomerInvite) { + public readonly customer: Customer; + public readonly customerName: string; + public override readonly data: + CustomerInviteListItemData | CustomerInviteData; + public readonly invitedBy: User; + public readonly mailAddress: string; + public readonly message?: string; + public readonly role: CustomerRole; + + public constructor(data: CustomerInviteListItemData | CustomerInviteData) { + super(data.id); + this.data = data; + this.role = data.role; + this.mailAddress = data.mailAddress; + this.customerName = data.customerName; + this.invitedBy = User.ofId(data.information.invitedBy); + this.message = data.message; + this.customer = Customer.ofId(data.customerId); + } + + public async accept() { + await config.behaviors.customerInvite.accept(this.id); + } +} + +export class CustomerInviteDetailed extends CustomerInviteCommon { + public override readonly data: CustomerInviteData; + public constructor(data: CustomerInviteData) { + super(data); + this.data = data; + } +} + +export class CustomerInviteListItem extends CustomerInviteCommon { + public override readonly data: CustomerInviteListItemData; + public constructor(data: CustomerInviteListItemData) { + super(data); + this.data = data; + } +} + +export class CustomerInviteListQuery extends ListQueryModel { + public readonly customer: Customer; + + public constructor( + customer: Customer, + query: CustomerInviteListQueryData = {}, + ) { + super(query, { dependencies: [customer.id] }); + this.customer = customer; + } + + public async execute() { + const { totalCount, items } = await config.behaviors.customerInvite.list( + this.customer.id, + this.query, + ); + + return new CustomerInviteList( + this.customer, + this.query, + items.map((d) => new CustomerInviteListItem(d)), + totalCount, + ); + } + + public async getTotalCount() { + const { totalCount } = await this.refine({ limit: 1 }).execute(); + return totalCount; + } + + public refine(query: CustomerInviteListQueryData) { + return new CustomerInviteListQuery(this.customer, { + ...this.query, + ...query, + }); + } +} + +export class CustomerInviteList extends WithListData()( + CustomerInviteListQuery, +) { + public override readonly items: readonly CustomerInviteListItem[]; + public override readonly totalCount: number; + public constructor( + customer: Customer, + query: CustomerInviteListQueryData, + invites: CustomerInviteListItem[], + totalCount: number, + ) { + super(customer, query); + this.items = Object.freeze(invites); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/customer/CustomerInvite/behaviors/api.ts b/packages/models/src/customer/CustomerInvite/behaviors/api.ts new file mode 100644 index 00000000..3e18d372 --- /dev/null +++ b/packages/models/src/customer/CustomerInvite/behaviors/api.ts @@ -0,0 +1,118 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { CustomerInviteBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { anyStatus403 } from "../../../base/api/typeFixes.js"; +import { resolveTotalCount } from "../../../base/index.js"; +import { ValidationError } from "../../../errors/index.js"; + +export const apiCustomerInviteBehaviors = ( + client: MittwaldAPIV2Client, +): CustomerInviteBehaviors => ({ + create: async (customerId, data) => { + const response = await client.customer.createCustomerInvite({ + customerId, + data, + }); + + if (response.status === 409) { + const message = + response.data.message && typeof response.data.message === "string" + ? response.data.message + : undefined; + + if (message?.includes("already exists")) { + throw new ValidationError({ + message: "inviteAlreadyExists", + type: "inviteAlreadyExists", + path: "mailAddress", + }); + } + if (message?.includes("already member")) { + throw new ValidationError({ + message: "alreadyMember", + type: "alreadyMember", + path: "mailAddress", + }); + } + } + + validateResponse(response, 201, { + validationError: { + pathMappings: { + mail_address: "mailAddress", + }, + }, + }); + return response.data; + }, + + find: async (customerInviteId) => { + const response = await client.customer.getCustomerInvite({ + customerInviteId, + }); + if (response.status === 200) { + return response.data; + } + // API-DRIFT: getCustomerInvite omits 403 in its generated response type, so anyStatus403 (403 as any) is passed (resolve: use the literal 403 once the client type declares it) + validateResponse(response, [anyStatus403, 404]); + }, + + list: async (customerId, query) => { + const response = await client.customer.listInvitesForCustomer({ + queryParameters: query, + customerId, + }); + + validateResponse(response, 200); + + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + getByToken: async (invitationToken) => { + const response = await client.customer.getCustomerTokenInvite({ + headers: { token: invitationToken }, + }); + validateResponse(response, 200); + + return response.data; + }, + + accept: async (customerInviteId, invitationToken) => { + const response = await client.customer.acceptCustomerInvite({ + data: { invitationToken }, + customerInviteId, + }); + validateResponse(response, 204); + }, + + listIncoming: async (query) => { + const response = await client.customer.listCustomerInvites({ + queryParameters: query, + }); + + validateResponse(response, 200); + + return { + items: response.data, + }; + }, + + decline: async (customerInviteId) => { + const response = await client.customer.declineCustomerInvite({ + customerInviteId, + }); + validateResponse(response, 204); + }, + + delete: async (customerInviteId) => { + const response = await client.customer.deleteCustomerInvite({ + customerInviteId, + }); + validateResponse(response, 204); + }, +}); diff --git a/packages/models/src/customer/CustomerInvite/behaviors/index.ts b/packages/models/src/customer/CustomerInvite/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/customer/CustomerInvite/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/customer/CustomerInvite/behaviors/types.ts b/packages/models/src/customer/CustomerInvite/behaviors/types.ts new file mode 100644 index 00000000..ee9a6603 --- /dev/null +++ b/packages/models/src/customer/CustomerInvite/behaviors/types.ts @@ -0,0 +1,32 @@ +import type { + CustomerInviteCreateRequestData, + CustomerInviteListQueryData, + CustomerInviteListItemData, + CustomerInviteData, +} from "../types.js"; + +export interface CustomerInviteBehaviors { + list: ( + customerId: string, + query?: CustomerInviteListQueryData, + ) => Promise<{ items: CustomerInviteListItemData[]; totalCount: number }>; + + listIncoming: ( + query?: CustomerInviteListQueryData, + ) => Promise<{ items: CustomerInviteListItemData[] }>; + + create: ( + customerId: string, + data: CustomerInviteCreateRequestData, + ) => Promise<{ id: string }>; + + accept: (customerInviteId: string, invitationToken?: string) => Promise; + + find: (customerInviteId: string) => Promise; + + getByToken: (token: string) => Promise<{ id: string }>; + + decline: (customerInviteId: string) => Promise; + + delete: (customerInviteId: string) => Promise; +} diff --git a/packages/models/src/customer/CustomerInvite/index.ts b/packages/models/src/customer/CustomerInvite/index.ts new file mode 100644 index 00000000..a9248626 --- /dev/null +++ b/packages/models/src/customer/CustomerInvite/index.ts @@ -0,0 +1,2 @@ +export * from "./CustomerInvite.js"; +export * from "./types.js"; diff --git a/packages/models/src/customer/CustomerInvite/types.ts b/packages/models/src/customer/CustomerInvite/types.ts new file mode 100644 index 00000000..138be79b --- /dev/null +++ b/packages/models/src/customer/CustomerInvite/types.ts @@ -0,0 +1,13 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type CustomerInviteData = + MittwaldAPIV2.Operations.CustomerGetCustomerInvite.ResponseData; + +export type CustomerInviteListItemData = + MittwaldAPIV2.Operations.CustomerListCustomerInvites.ResponseData[number]; + +export type CustomerInviteListQueryData = + MittwaldAPIV2.Paths.V2CustomersCustomerIdInvites.Get.Parameters.Query; + +export type CustomerInviteCreateRequestData = + MittwaldAPIV2.Paths.V2CustomersCustomerIdInvites.Post.Parameters.RequestBody; diff --git a/packages/models/src/customer/CustomerMembership/CustomerMembership.test.ts b/packages/models/src/customer/CustomerMembership/CustomerMembership.test.ts new file mode 100644 index 00000000..2e6c051e --- /dev/null +++ b/packages/models/src/customer/CustomerMembership/CustomerMembership.test.ts @@ -0,0 +1,240 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; +import { DateTime } from "luxon"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { + buildCustomerMembershipListItemData, + buildCustomerMembershipData, +} from "../../testing/builders/buildCustomerMembershipData.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { Customer } from "../Customer/index.js"; +import { User } from "../../user/index.js"; +import { + CustomerMembershipListQuery, + CustomerMembershipDetailed, + CustomerMembershipListItem, + CustomerMembershipList, + CustomerMembership, +} from "./CustomerMembership.js"; + +afterEach(resetBehaviors); + +const item = ( + overrides?: Parameters[0], +) => + new CustomerMembershipListItem( + buildCustomerMembershipListItemData(overrides), + ); + +describe("CustomerMembership delegation", () => { + test("find returns a detailed membership", async () => { + const find = vi.fn().mockResolvedValue(buildCustomerMembershipData()); + installBehaviors({ customerMembership: { find } }); + + const result = await CustomerMembership.find("membership-id"); + + expect(find).toHaveBeenCalledWith("membership-id", undefined); + expect(result).toBeInstanceOf(CustomerMembershipDetailed); + }); + + test("find returns undefined for a missing membership", async () => { + installBehaviors({ + customerMembership: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(CustomerMembership.find("missing")).resolves.toBeUndefined(); + }); + + test("remove delegates with the membership id", async () => { + const remove = vi.fn().mockResolvedValue(undefined); + installBehaviors({ customerMembership: { remove } }); + + await CustomerMembership.ofId("membership-id").remove(); + + expect(remove).toHaveBeenCalledWith("membership-id"); + }); +}); + +describe("CustomerMembership common variant", () => { + test("findCommon on a reference delegates to find and returns a detailed membership", async () => { + const find = vi.fn().mockResolvedValue(buildCustomerMembershipData()); + installBehaviors({ customerMembership: { find } }); + + const result = await CustomerMembership.ofId("membership-id").findCommon(); + + expect(find).toHaveBeenCalledWith("membership-id", undefined); + expect(result).toBeInstanceOf(CustomerMembershipDetailed); + }); + + test("findCommon resolves undefined when the reference is not found", async () => { + installBehaviors({ + customerMembership: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + CustomerMembership.ofId("missing").findCommon(), + ).resolves.toBeUndefined(); + }); + + test("getCommon rejects when the reference is not found", async () => { + installBehaviors({ + customerMembership: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + CustomerMembership.ofId("missing").getCommon(), + ).rejects.toThrow(); + }); + + test("findCommon on an already materialized model returns itself without another call", async () => { + const find = vi.fn(); + installBehaviors({ customerMembership: { find } }); + const listItem = item(); + + const result = await listItem.findCommon(); + + expect(result).toBe(listItem); + expect(find).not.toHaveBeenCalled(); + }); + + test("getCommon on an already materialized model returns itself without another call", async () => { + const find = vi.fn(); + installBehaviors({ customerMembership: { find } }); + const listItem = item(); + + const result = await listItem.getCommon(); + + expect(result).toBe(listItem); + expect(find).not.toHaveBeenCalled(); + }); + + test("leaves the avatar undefined when no avatar ref is present", () => { + expect(item().avatar).toBeUndefined(); + }); +}); + +describe("CustomerMembership list query", () => { + test("delegates and materializes list data", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildCustomerMembershipListItemData({ id: "m-1" })], + totalCount: 1, + }); + installBehaviors({ customerMembership: { list } }); + const query = CustomerMembership.query(Customer.ofId("customer-id")); + + const result = await query.execute(); + + expect(result).toBeInstanceOf(CustomerMembershipList); + expect(result).toBeInstanceOf(CustomerMembershipListQuery); + expect(result.items[0]).toBeInstanceOf(CustomerMembershipListItem); + expect(result.totalCount).toBe(1); + expect(list).toHaveBeenCalledWith("customer-id", {}); + }); +}); + +describe("CustomerMembership data", () => { + test("exposes derived values", () => { + const membership = item({ + expiresAt: "2024-03-01T00:00:00.000Z", + userId: "user-2", + role: "owner", + }); + + expect(membership.fullName).toBe("Grace Hopper"); + expect(membership.role).toBe("owner"); + expect(membership.expiresAt).toBeInstanceOf(DateTime); + expect(membership.user).toBeInstanceOf(User); + expect(membership.user.id).toBe("user-2"); + }); + + test("leaves expiresAt undefined when absent", () => { + expect(item().expiresAt).toBeUndefined(); + }); +}); + +describe("CustomerMembership guards", () => { + test("identifies the last active owner", () => { + const owner = item({ role: "owner", id: "owner" }); + + expect(CustomerMembership.memberIsLastOwner([owner], owner)).toBe(true); + expect( + CustomerMembership.memberIsLastOwner( + [owner, item({ role: "owner", id: "other" })], + owner, + ), + ).toBe(false); + expect( + CustomerMembership.memberIsLastOwner([item()], item()), + ).toBeUndefined(); + const expiringOwner = item({ + expiresAt: "2024-03-01T00:00:00.000Z", + id: "expiring", + role: "owner", + }); + expect( + CustomerMembership.memberIsLastOwner([expiringOwner], expiringOwner), + ).toBeUndefined(); + }); + + test("identifies the own membership", () => { + const own = item({ id: "own" }); + + expect(CustomerMembership.memberIsOwnMember(own, item({ id: "own" }))).toBe( + true, + ); + expect( + CustomerMembership.memberIsOwnMember(own, item({ id: "other" })), + ).toBe(false); + }); + + test("allows an owner to edit and remove another non-last owner", () => { + const own = item({ role: "owner", id: "own" }); + const other = item({ role: "owner", id: "other" }); + const list = [own, other]; + + expect(CustomerMembership.canEditMember(own, other, list)).toBe(true); + expect(CustomerMembership.canRemoveMember(own, other, list)).toBe(true); + }); + + test("prevents editing and removal without the required conditions", () => { + const own = item({ role: "owner", id: "own" }); + const lastOwner = item({ role: "owner", id: "last" }); + const member = item({ role: "member", id: "member" }); + + expect( + CustomerMembership.canEditMember(member, lastOwner, [lastOwner]), + ).toBe(false); + expect(CustomerMembership.canRemoveMember(own, own, [own, lastOwner])).toBe( + false, + ); + expect(CustomerMembership.canEditMember(own, lastOwner, [lastOwner])).toBe( + false, + ); + expect( + CustomerMembership.canRemoveMember(own, lastOwner, [lastOwner]), + ).toBe(false); + }); + + test("allows the own member to leave when not the last owner", () => { + const own = item({ role: "owner", id: "own" }); + const other = item({ role: "owner", id: "other" }); + + expect(CustomerMembership.canLeaveCustomer(own, own, [own, other])).toBe( + true, + ); + expect(CustomerMembership.canLeaveCustomer(own, other, [own, other])).toBe( + false, + ); + expect(CustomerMembership.canLeaveCustomer(own, own, [own])).toBe(false); + }); +}); diff --git a/packages/models/src/customer/CustomerMembership/CustomerMembership.ts b/packages/models/src/customer/CustomerMembership/CustomerMembership.ts new file mode 100644 index 00000000..209afbbd --- /dev/null +++ b/packages/models/src/customer/CustomerMembership/CustomerMembership.ts @@ -0,0 +1,272 @@ +import type { AxiosRequestConfig } from "axios"; + +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; + +import type { + CustomerMembershipListQueryData, + CustomerMembershipListItemData, + CustomerMembershipData, + CustomerRole, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { File } from "../../file/File/internal.js"; +import { User } from "../../user/User/User.js"; +import { Customer } from "../Customer/index.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "CustomerMembership", +}) +export class CustomerMembership extends ReferenceModel { + public static canEditMember( + ownMember: CustomerMembershipListItem, + member: CustomerMembershipListItem, + memberList: readonly CustomerMembershipListItem[], + ) { + return ( + ownMember.role === "owner" && + !CustomerMembership.memberIsOwnMember(ownMember, member) && + !CustomerMembership.memberIsLastOwner(memberList, member) + ); + } + + public static canLeaveCustomer( + ownMember: CustomerMembershipListItem, + member: CustomerMembershipListItem, + memberList: readonly CustomerMembershipListItem[], + ) { + return ( + CustomerMembership.memberIsOwnMember(ownMember, member) && + !CustomerMembership.memberIsLastOwner(memberList, member) + ); + } + + public static canRemoveMember( + ownMember: CustomerMembershipListItem, + member: CustomerMembershipListItem, + memberList: readonly CustomerMembershipListItem[], + ) { + return ( + ownMember.role === "owner" && + !CustomerMembership.memberIsOwnMember(ownMember, member) && + !CustomerMembership.memberIsLastOwner(memberList, member) + ); + } + + public static async find(id: string, options?: AxiosRequestConfig) { + const data = await config.behaviors.customerMembership.find(id, options); + if (data) { + return new CustomerMembershipDetailed(data); + } + } + + public static async findOwn(customer: Customer) { + const ownUser = await User.self.getCommon(); + const data = await config.behaviors.customerMembership.findOwn( + customer.id, + ownUser.id, + ); + if (data) { + return new CustomerMembershipListItem(data); + } + } + + public static async get(id: string, options?: AxiosRequestConfig) { + const customerMembership = await this.find(id, options); + assertObjectFound(customerMembership, CustomerMembership, id); + return customerMembership; + } + + public static async getOwn(customer: Customer) { + const membership = await this.findOwn(customer); + assertObjectFound(membership, CustomerMembership, customer.id); + return membership; + } + + public static memberIsLastOwner( + memberList: readonly CustomerMembershipListItem[], + member: CustomerMembershipListItem, + ): boolean | undefined { + if (member.role !== "owner" || member.expiresAt) { + return; + } + + const otherActiveOwners = memberList.filter( + (m) => m.id !== member.id && m.role === "owner" && !m.expiresAt, + ); + + return otherActiveOwners.length === 0; + } + + public static memberIsOwnMember( + ownMember: CustomerMembershipListItem, + member: CustomerMembershipListItem, + ) { + return ownMember.id === member.id; + } + + public static ofId(id: string) { + return new CustomerMembership(id); + } + + public static query( + customer: Customer, + query: CustomerMembershipListQueryData = {}, + ) { + return new CustomerMembershipListQuery(customer, query); + } + + public async findCommon( + options?: AxiosRequestConfig, + ): Promise { + return this instanceof CustomerMembershipCommon + ? this + : this.findDetailed(options); + } + + public async findDetailed( + options?: AxiosRequestConfig, + ): Promise { + return CustomerMembership.find(this.id, options); + } + + public async getCommon( + options?: AxiosRequestConfig, + ): Promise { + return this instanceof CustomerMembershipCommon + ? this + : this.getDetailed(options); + } + + public async getDetailed( + options?: AxiosRequestConfig, + ): Promise { + return CustomerMembership.get(this.id, options); + } + + public async remove() { + await config.behaviors.customerMembership.remove(this.id); + } +} + +export class CustomerMembershipCommon extends WithData< + CustomerMembershipListItemData | CustomerMembershipData +>()(CustomerMembership) { + public readonly avatar?: File; + public readonly customer: Customer; + public override readonly data: + CustomerMembershipListItemData | CustomerMembershipData; + public readonly expiresAt?: DateTime; + public readonly fullName: string; + public readonly role: CustomerRole; + public readonly user: User; + + public constructor( + data: CustomerMembershipListItemData | CustomerMembershipData, + ) { + super(data.id); + this.data = data; + this.user = User.ofId(data.userId); + this.role = data.role; + if (data.expiresAt) { + this.expiresAt = DateTime.fromISO(data.expiresAt); + } + this.fullName = `${data.firstName} ${data.lastName}`; + this.avatar = data.avatarRef ? File.ofId(data.avatarRef) : undefined; + this.customer = Customer.ofId(data.customerId); + } + + public async updateExpirationDate(expiresAt: string | null) { + await config.behaviors.customerMembership.update(this.id, { + expiresAt: expiresAt as string | undefined, + role: this.role, + }); + } + + public async updateRole(role: CustomerRole) { + await config.behaviors.customerMembership.update(this.id, { + expiresAt: this.data.expiresAt, + role, + }); + } +} + +export class CustomerMembershipDetailed extends CustomerMembershipCommon { + public override readonly data: CustomerMembershipData; + public constructor(data: CustomerMembershipData) { + super(data); + this.data = data; + } +} + +export class CustomerMembershipListItem extends CustomerMembershipCommon { + public override readonly data: CustomerMembershipListItemData; + public constructor(data: CustomerMembershipListItemData) { + super(data); + this.data = data; + } +} + +export class CustomerMembershipListQuery extends ListQueryModel { + public readonly customer: Customer; + + public constructor( + customer: Customer, + query: CustomerMembershipListQueryData = {}, + ) { + super(query, { dependencies: [customer.id] }); + this.customer = customer; + } + + public async execute() { + const { totalCount, items } = + await config.behaviors.customerMembership.list( + this.customer.id, + this.query, + ); + + return new CustomerMembershipList( + this.customer, + this.query, + items.map((d) => new CustomerMembershipListItem(d)), + totalCount, + ); + } + + public async getTotalCount() { + const { totalCount } = await this.refine({ limit: 1 }).execute(); + return totalCount; + } + + public refine(query: CustomerMembershipListQueryData) { + return new CustomerMembershipListQuery(this.customer, { + ...this.query, + ...query, + }); + } +} + +export class CustomerMembershipList extends WithListData()( + CustomerMembershipListQuery, +) { + public override readonly items: readonly CustomerMembershipListItem[]; + public override readonly totalCount: number; + public constructor( + customer: Customer, + query: CustomerMembershipListQueryData, + memberships: CustomerMembershipListItem[], + totalCount: number, + ) { + super(customer, query); + this.items = Object.freeze(memberships); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/customer/CustomerMembership/behaviors/api.ts b/packages/models/src/customer/CustomerMembership/behaviors/api.ts new file mode 100644 index 00000000..b72e8805 --- /dev/null +++ b/packages/models/src/customer/CustomerMembership/behaviors/api.ts @@ -0,0 +1,67 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { CustomerMembershipBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { + withAxiosRequestConfig, + resolveTotalCount, + anyStatus403, +} from "../../../base/index.js"; + +export const apiCustomerMembershipBehaviors = ( + client: MittwaldAPIV2Client, +): CustomerMembershipBehaviors => ({ + findOwn: async (customerId, userId) => { + const response = await client.customer.listMembershipsForCustomer({ + customerId, + }); + if (response.status === 200) { + return response.data.find((m) => m.userId === userId); + } + // API-DRIFT: listMembershipsForCustomer omits 403 in its generated response type, so anyStatus403 (403 as any) is passed (resolve: use the literal 403 once the client type declares it) + validateResponse(response, [anyStatus403, 404]); + }, + + find: async (customerMembershipId, options) => { + const response = await client.customer.getCustomerMembership( + { + customerMembershipId, + }, + withAxiosRequestConfig(options), + ); + if (response.status === 200) { + return response.data; + } + validateResponse(response, 404); + }, + + list: async (customerId, query) => { + const response = await client.customer.listMembershipsForCustomer({ + queryParameters: query, + customerId, + }); + + validateResponse(response, 200); + + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + update: async (customerMembershipId, data) => { + const response = await client.customer.updateCustomerMembership({ + customerMembershipId, + data, + }); + validateResponse(response, 204); + }, + + remove: async (customerMembershipId) => { + const response = await client.customer.deleteCustomerMembership({ + customerMembershipId, + }); + validateResponse(response, 204); + }, +}); diff --git a/packages/models/src/customer/CustomerMembership/behaviors/index.ts b/packages/models/src/customer/CustomerMembership/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/customer/CustomerMembership/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/customer/CustomerMembership/behaviors/types.ts b/packages/models/src/customer/CustomerMembership/behaviors/types.ts new file mode 100644 index 00000000..083a1fee --- /dev/null +++ b/packages/models/src/customer/CustomerMembership/behaviors/types.ts @@ -0,0 +1,33 @@ +import type { AxiosRequestConfig } from "axios"; + +import type { QueryResponseData } from "../../../base/index.js"; +import type { + CustomerMembershipUpdateRequestData, + CustomerMembershipListQueryData, + CustomerMembershipListItemData, + CustomerMembershipData, +} from "../types.js"; + +export interface CustomerMembershipBehaviors { + list: ( + customerId: string, + query?: CustomerMembershipListQueryData, + ) => Promise>; + + find: ( + customerMembershipId: string, + options?: AxiosRequestConfig, + ) => Promise; + + findOwn: ( + customerId: string, + userId: string, + ) => Promise; + + update: ( + customerMembershipId: string, + data: CustomerMembershipUpdateRequestData, + ) => Promise; + + remove: (customerMembershipId: string) => Promise; +} diff --git a/packages/models/src/customer/CustomerMembership/index.ts b/packages/models/src/customer/CustomerMembership/index.ts new file mode 100644 index 00000000..8004c6a1 --- /dev/null +++ b/packages/models/src/customer/CustomerMembership/index.ts @@ -0,0 +1,2 @@ +export * from "./CustomerMembership.js"; +export * from "./types.js"; diff --git a/packages/models/src/customer/CustomerMembership/types.ts b/packages/models/src/customer/CustomerMembership/types.ts new file mode 100644 index 00000000..6a11a6cc --- /dev/null +++ b/packages/models/src/customer/CustomerMembership/types.ts @@ -0,0 +1,16 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type CustomerMembershipData = + MittwaldAPIV2.Operations.CustomerGetCustomerMembership.ResponseData; + +export type CustomerMembershipListItemData = + MittwaldAPIV2.Operations.CustomerListCustomerMemberships.ResponseData[number]; + +export type CustomerMembershipListQueryData = + MittwaldAPIV2.Paths.V2CustomersCustomerIdMemberships.Get.Parameters.Query; + +export type CustomerRole = + MittwaldAPIV2.Components.Schemas.MembershipCustomerRoles; + +export type CustomerMembershipUpdateRequestData = + MittwaldAPIV2.Paths.V2CustomerMembershipsCustomerMembershipId.Patch.Parameters.RequestBody; diff --git a/packages/models/src/customer/InvoiceSettings/InvoiceSettings.test.ts b/packages/models/src/customer/InvoiceSettings/InvoiceSettings.test.ts new file mode 100644 index 00000000..624e1c29 --- /dev/null +++ b/packages/models/src/customer/InvoiceSettings/InvoiceSettings.test.ts @@ -0,0 +1,174 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; +import { DateTime } from "luxon"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { buildInvoiceSettingsData } from "../../testing/builders/buildInvoiceSettingsData.js"; +import { InvoiceSettingsDetailed, InvoiceSettings } from "./InvoiceSettings.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; + +afterEach(resetBehaviors); + +describe("InvoiceSettings delegation", () => { + test("find returns detailed invoice settings", async () => { + const find = vi.fn().mockResolvedValue(buildInvoiceSettingsData()); + installBehaviors({ invoiceSettings: { find } }); + + const result = await InvoiceSettings.find("customer-id"); + + expect(find).toHaveBeenCalledWith("customer-id", undefined); + expect(result).toBeInstanceOf(InvoiceSettingsDetailed); + }); + + test("find returns undefined for missing invoice settings", async () => { + installBehaviors({ + invoiceSettings: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(InvoiceSettings.find("missing")).resolves.toBeUndefined(); + }); + + test("update delegates with the customer id", async () => { + const update = vi.fn().mockResolvedValue(undefined); + installBehaviors({ invoiceSettings: { update } }); + const data = { + paymentSettings: { method: "invoice" as const }, + additionalEmailRecipients: [], + invoicePeriod: 1, + }; + + await InvoiceSettings.ofCustomerId("customer-id").update(data); + + expect(update).toHaveBeenCalledWith("customer-id", data); + }); +}); + +describe("InvoiceSettings common variant", () => { + test("findCommon on a reference delegates to find and returns detailed settings", async () => { + const find = vi.fn().mockResolvedValue(buildInvoiceSettingsData()); + installBehaviors({ invoiceSettings: { find } }); + + const result = + await InvoiceSettings.ofCustomerId("customer-id").findCommon(); + + expect(find).toHaveBeenCalledWith("customer-id", undefined); + expect(result).toBeInstanceOf(InvoiceSettingsDetailed); + }); + + test("findCommon resolves undefined when the reference is not found", async () => { + installBehaviors({ + invoiceSettings: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + InvoiceSettings.ofCustomerId("missing").findCommon(), + ).resolves.toBeUndefined(); + }); + + test("getCommon rejects when the reference is not found", async () => { + installBehaviors({ + invoiceSettings: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + InvoiceSettings.ofCustomerId("missing").getCommon(), + ).rejects.toThrow(); + }); + + test("findCommon on already materialized settings returns itself without another call", async () => { + const find = vi.fn(); + installBehaviors({ invoiceSettings: { find } }); + const detailed = new InvoiceSettingsDetailed(buildInvoiceSettingsData()); + + const result = await detailed.findCommon(); + + expect(result).toBe(detailed); + expect(find).not.toHaveBeenCalled(); + }); + + test("getCommon on already materialized settings returns itself without another call", async () => { + const find = vi.fn(); + installBehaviors({ invoiceSettings: { find } }); + const detailed = new InvoiceSettingsDetailed(buildInvoiceSettingsData()); + + const result = await detailed.getCommon(); + + expect(result).toBe(detailed); + expect(find).not.toHaveBeenCalled(); + }); + + test("leaves optional derived values undefined when their source data is absent", () => { + const settings = new InvoiceSettingsDetailed(buildInvoiceSettingsData()); + + expect(settings.recipient).toBeUndefined(); + expect(settings.debitPaymentStopUntil).toBeUndefined(); + expect(settings.targetDay).toBeUndefined(); + }); +}); + +describe("InvoiceSettings data", () => { + test("exposes payment settings", () => { + const settings = new InvoiceSettingsDetailed(buildInvoiceSettingsData()); + + expect(settings.invoicePeriod).toBe(1); + expect(settings.paymentMethod).toBe("invoice"); + expect(settings.paymentSettings).toEqual({ method: "invoice" }); + expect(settings.additionalEmailRecipients).toEqual([]); + }); + + test("applies defaults for missing optional payment data", () => { + const settings = new InvoiceSettingsDetailed( + buildInvoiceSettingsData({ + additionalEmailRecipients: undefined, + paymentSettings: undefined, + invoicePeriod: undefined, + }), + ); + + expect(settings.invoicePeriod).toBe(1); + expect(settings.paymentSettings).toEqual({ method: "invoice" }); + expect(settings.paymentMethod).toBeUndefined(); + expect(settings.additionalEmailRecipients).toEqual([]); + }); + + test("derives status flags", () => { + const status = (type: "notReachable" | "bankrupt") => ({ + severity: "error" as const, + message: "", + type, + }); + + expect( + new InvoiceSettingsDetailed( + buildInvoiceSettingsData({ status: [status("bankrupt")] }), + ).isBankrupt, + ).toBe(true); + expect( + new InvoiceSettingsDetailed( + buildInvoiceSettingsData({ status: [status("notReachable")] }), + ).hasInvalidMail, + ).toBe(true); + const clear = new InvoiceSettingsDetailed(buildInvoiceSettingsData()); + expect(clear.isBankrupt).toBe(false); + expect(clear.hasInvalidMail).toBe(false); + }); + + test("parses the debit payment stop date", () => { + const settings = new InvoiceSettingsDetailed( + buildInvoiceSettingsData({ + debitPaymentStopUntil: "2024-04-01T00:00:00.000Z", + }), + ); + + expect(settings.debitPaymentStopUntil).toBeInstanceOf(DateTime); + }); +}); diff --git a/packages/models/src/customer/InvoiceSettings/InvoiceSettings.ts b/packages/models/src/customer/InvoiceSettings/InvoiceSettings.ts new file mode 100644 index 00000000..91fdf8ad --- /dev/null +++ b/packages/models/src/customer/InvoiceSettings/InvoiceSettings.ts @@ -0,0 +1,199 @@ +import type { AxiosRequestConfig } from "axios"; + +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; + +import type { InvoiceRecipientData } from "../../invoice/index.js"; +import type { + InvoiceSettingsUpdateRequestData, + InvoiceBankingInformation, + InvoicePaymentSettings, + InvoiceSettingsStatus, + InvoiceSettingsData, +} from "./types.js"; + +import { InvoiceRecipient } from "../../invoice/InvoiceRecipient/InvoiceRecipient.js"; +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { ReferenceModel, WithData } from "../../base/index.js"; +import { config } from "../../config/index.js"; + +@GhostMakerModel({ + name: "InvoiceSettings", +}) +export class InvoiceSettings extends ReferenceModel { + public static async find(id: string, options?: AxiosRequestConfig) { + const data = await config.behaviors.invoiceSettings.find(id, options); + if (data) { + return new InvoiceSettingsDetailed(data); + } + } + + public static async get(id: string, options?: AxiosRequestConfig) { + const invoiceSettings = await this.find(id, options); + assertObjectFound(invoiceSettings, InvoiceSettings, id); + return invoiceSettings; + } + + public static ofCustomerId(customerId: string) { + return new InvoiceSettings(customerId); + } + + public async findCommon( + options?: AxiosRequestConfig, + ): Promise { + return this instanceof InvoiceSettingsCommon + ? this + : this.findDetailed(options); + } + + public async findDetailed( + options?: AxiosRequestConfig, + ): Promise { + return InvoiceSettings.find(this.id, options); + } + + public async getCommon( + options?: AxiosRequestConfig, + ): Promise { + return this instanceof InvoiceSettingsCommon + ? this + : this.getDetailed(options); + } + + public async getDetailed( + options?: AxiosRequestConfig, + ): Promise { + return InvoiceSettings.get(this.id, options); + } + + public async update(data: InvoiceSettingsUpdateRequestData) { + return await config.behaviors.invoiceSettings.update(this.id, data); + } +} + +export class InvoiceSettingsCommon extends WithData()( + InvoiceSettings, +) { + public readonly additionalEmailRecipients: string[]; + public override readonly data: InvoiceSettingsData; + public readonly debitPaymentStopUntil?: DateTime; + public readonly hasInvalidMail: boolean; + public readonly id: string; + public readonly invoicePeriod: number; + public readonly isBankrupt: boolean; + public readonly lastBankingInformation?: InvoiceBankingInformation; + public readonly paymentMethod?: string; + public readonly paymentSettings: InvoicePaymentSettings; + public readonly printedInvoices?: boolean; + public readonly recipient?: InvoiceRecipient; + public readonly recipientSameAsOwner?: boolean; + public readonly status?: InvoiceSettingsStatus[]; + public readonly targetDay?: number; + + public constructor(data: InvoiceSettingsData) { + super(data.id); + this.data = data; + this.id = data.id; + if (data.recipient) { + this.recipient = new InvoiceRecipient(data.recipient); + } + this.status = data.status; + this.invoicePeriod = data.invoicePeriod ?? 1; + this.paymentSettings = data.paymentSettings ?? { method: "invoice" }; + this.additionalEmailRecipients = data.additionalEmailRecipients ?? []; + this.lastBankingInformation = data.lastBankingInformation; + this.printedInvoices = data.printedInvoices; + this.recipientSameAsOwner = data.recipientSameAsOwner; + this.targetDay = data.targetDay; + this.paymentMethod = data.paymentSettings?.method; + if (data.debitPaymentStopUntil) { + this.debitPaymentStopUntil = DateTime.fromISO(data.debitPaymentStopUntil); + } + + this.hasInvalidMail = !!this.status?.some((s) => s.type === "notReachable"); + this.isBankrupt = !!this.status?.some((s) => s.type === "bankrupt"); + } + + public async addAdditionalRecipient(mailAddress: string) { + return await this.update({ + additionalEmailRecipients: [ + ...this.additionalEmailRecipients, + mailAddress, + ], + recipient: this.data.recipient as InvoiceRecipientData, + recipientSameAsOwner: this.recipientSameAsOwner, + paymentSettings: this.paymentSettings, + printedInvoices: this.printedInvoices, + invoicePeriod: this.invoicePeriod, + }); + } + + public async removeAdditionalRecipient(mailAddress: string) { + await this.update({ + additionalEmailRecipients: this.additionalEmailRecipients.filter( + (a) => a !== mailAddress, + ), + recipient: this.data.recipient as InvoiceRecipientData, + recipientSameAsOwner: this.recipientSameAsOwner, + paymentSettings: this.paymentSettings, + printedInvoices: this.printedInvoices, + invoicePeriod: this.invoicePeriod, + }); + } + + public async update( + data: InvoiceSettingsUpdateRequestData, + options?: AxiosRequestConfig, + ) { + return await config.behaviors.invoiceSettings.update( + this.id, + data, + options, + ); + } + + public async updatePaymentSettings( + paymentSettings: InvoicePaymentSettings, + invoicePeriod: number, + options?: AxiosRequestConfig, + ) { + return await this.update( + { + paymentSettings: + paymentSettings.method === "invoice" + ? { method: paymentSettings.method } + : paymentSettings, + additionalEmailRecipients: this.additionalEmailRecipients, + recipient: this.data.recipient as InvoiceRecipientData, + recipientSameAsOwner: this.recipientSameAsOwner, + printedInvoices: this.printedInvoices, + invoicePeriod, + }, + options, + ); + } + + public async updateRecipient( + recipient: InvoiceRecipientData, + recipientSameAsOwner: boolean, + options?: AxiosRequestConfig, + ) { + return await this.update( + { + additionalEmailRecipients: this.additionalEmailRecipients, + paymentSettings: this.paymentSettings, + printedInvoices: this.printedInvoices, + invoicePeriod: this.invoicePeriod, + recipientSameAsOwner, + recipient, + }, + options, + ); + } +} + +export class InvoiceSettingsDetailed extends InvoiceSettingsCommon { + public constructor(data: InvoiceSettingsData) { + super(data); + } +} diff --git a/packages/models/src/customer/InvoiceSettings/behaviors/api.ts b/packages/models/src/customer/InvoiceSettings/behaviors/api.ts new file mode 100644 index 00000000..4acc5a54 --- /dev/null +++ b/packages/models/src/customer/InvoiceSettings/behaviors/api.ts @@ -0,0 +1,35 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; +import type { AxiosRequestConfig } from "axios"; + +import type { InvoiceSettingsBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { withAxiosRequestConfig } from "../../../base/index.js"; +import { anyStatus403 } from "../../../base/api/typeFixes.js"; + +export const apiInvoiceSettingsBehaviors = ( + client: MittwaldAPIV2Client, +): InvoiceSettingsBehaviors => ({ + find: async (customerId, config?: AxiosRequestConfig) => { + const response = await client.contract.invoiceGetDetailOfInvoiceSettings( + { customerId }, + withAxiosRequestConfig(config), + ); + + if (response.status === 200) { + return response.data; + } + + // API-DRIFT: invoiceGetDetailOfInvoiceSettings omits 403 in its generated response type, so anyStatus403 (403 as any) is passed (resolve: use the literal 403 once the client type declares it) + validateResponse(response, [404, anyStatus403]); + }, + + update: async (customerId, data, config?: AxiosRequestConfig) => { + const response = await client.contract.invoiceUpdateInvoiceSettings( + { customerId, data }, + withAxiosRequestConfig(config), + ); + + validateResponse(response, 200); + }, +}); diff --git a/packages/models/src/customer/InvoiceSettings/behaviors/index.ts b/packages/models/src/customer/InvoiceSettings/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/customer/InvoiceSettings/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/customer/InvoiceSettings/behaviors/types.ts b/packages/models/src/customer/InvoiceSettings/behaviors/types.ts new file mode 100644 index 00000000..8fc7571d --- /dev/null +++ b/packages/models/src/customer/InvoiceSettings/behaviors/types.ts @@ -0,0 +1,19 @@ +import type { AxiosRequestConfig } from "axios"; + +import type { + InvoiceSettingsUpdateRequestData, + InvoiceSettingsData, +} from "../types.js"; + +export interface InvoiceSettingsBehaviors { + update: ( + customerId: string, + data: InvoiceSettingsUpdateRequestData, + options?: AxiosRequestConfig, + ) => Promise; + + find: ( + customerId: string, + options?: AxiosRequestConfig, + ) => Promise; +} diff --git a/packages/models/src/customer/InvoiceSettings/index.ts b/packages/models/src/customer/InvoiceSettings/index.ts new file mode 100644 index 00000000..c868b5ba --- /dev/null +++ b/packages/models/src/customer/InvoiceSettings/index.ts @@ -0,0 +1,2 @@ +export * from "./InvoiceSettings.js"; +export * from "./types.js"; diff --git a/packages/models/src/customer/InvoiceSettings/types.ts b/packages/models/src/customer/InvoiceSettings/types.ts new file mode 100644 index 00000000..d269d4d8 --- /dev/null +++ b/packages/models/src/customer/InvoiceSettings/types.ts @@ -0,0 +1,16 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type InvoiceSettingsData = + MittwaldAPIV2.Operations.InvoiceGetDetailOfInvoiceSettings.ResponseData; + +export type InvoiceSettingsUpdateRequestData = + MittwaldAPIV2.Paths.V2CustomersCustomerIdInvoiceSettings.Put.Parameters.RequestBody; + +export type InvoiceSettingsStatus = + MittwaldAPIV2.Components.Schemas.InvoiceInvoiceSettingsStatus; + +export type InvoicePaymentSettings = + MittwaldAPIV2.Components.Schemas.InvoicePaymentSettings; + +export type InvoiceBankingInformation = + MittwaldAPIV2.Components.Schemas.InvoiceBankingInformation; diff --git a/packages/models/src/customer/customerPermissions.ts b/packages/models/src/customer/customerPermissions.ts new file mode 100644 index 00000000..5427b05a --- /dev/null +++ b/packages/models/src/customer/customerPermissions.ts @@ -0,0 +1,44 @@ +import type { CustomerRole } from "./CustomerMembership/index.js"; + +export type CustomerPermission = + | "accessContributorEditing" + | "accessContractPartner" + | "accessInvoiceSettings" + | "editContractPartner" + | "editInvoiceSettings" + | "accessConversations" + | "accessExtensionDev" + | "accessContributor" + | "accessExtension" + | "editContributor" + | "accessAiHosting" + | "deleteCustomer" + | "accessInvoices" + | "accessHosting" + | "accessInvites" + | "editCustomer" + | "accessOrders" + | "editHosting" + | "editMember"; + +export const customerPermissions: Record = { + accessContractPartner: ["owner", "member", "accountant"], + accessExtension: ["owner", "member", "accountant"], + accessInvoiceSettings: ["owner", "accountant"], + editContractPartner: ["owner", "accountant"], + editInvoiceSettings: ["owner", "accountant"], + accessConversations: ["owner", "accountant"], + accessContributor: ["owner", "accountant"], + accessInvoices: ["owner", "accountant"], + accessExtensionDev: ["owner", "member"], + accessAiHosting: ["owner", "member"], + accessContributorEditing: ["owner"], + accessHosting: ["owner", "member"], + accessOrders: ["owner", "member"], + editHosting: ["owner", "member"], + editContributor: ["owner"], + deleteCustomer: ["owner"], + accessInvites: ["owner"], + editCustomer: ["owner"], + editMember: ["owner"], +}; diff --git a/packages/models/src/customer/index.ts b/packages/models/src/customer/index.ts index 8fbc082e..39f775a8 100644 --- a/packages/models/src/customer/index.ts +++ b/packages/models/src/customer/index.ts @@ -1 +1,6 @@ +export * from "./ContractPartner/index.js"; export * from "./Customer/index.js"; +export * from "./CustomerInvite/index.js"; +export * from "./CustomerMembership/index.js"; +export * from "./customerPermissions.js"; +export * from "./InvoiceSettings/index.js"; diff --git a/packages/models/src/database/MySql/MySql.test.ts b/packages/models/src/database/MySql/MySql.test.ts new file mode 100644 index 00000000..bf0cd521 --- /dev/null +++ b/packages/models/src/database/MySql/MySql.test.ts @@ -0,0 +1,223 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { buildMySqlCharsetListItemData } from "../../testing/builders/buildMySqlCharsetListItemData.js"; +import { buildMySqlDatabaseData } from "../../testing/builders/buildMySqlDatabaseData.js"; +import { buildMySqlVersionData } from "../../testing/builders/buildMySqlVersionData.js"; +import { ListQueryModel, ReferenceModel } from "../../base/index.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { Project } from "../../project/index.js"; +import { + MySqlCharsetListItem, + MySqlCharsetList, + MySqlCharset, +} from "./MySqlCharset.js"; +import { + MySqlListQuery, + MySqlDetailed, + MySqlListItem, + MySqlCommon, + MySqlList, + MySql, +} from "./MySql.js"; + +afterEach(resetBehaviors); + +describe("MySql", () => { + test("find delegates and maps found and missing databases", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildMySqlDatabaseData({ id: "db-1" })) + .mockResolvedValueOnce(undefined); + installBehaviors({ mySql: { find } }); + + const found = await MySql.find("db-1"); + const missing = await MySql.find("missing"); + + expect(find).toHaveBeenNthCalledWith(1, "db-1"); + expect(find).toHaveBeenNthCalledWith(2, "missing"); + expect(found).toBeInstanceOf(MySqlDetailed); + expect(found?.id).toBe("db-1"); + expect(missing).toBeUndefined(); + }); + + test("get returns a detailed database or throws when it is missing", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildMySqlDatabaseData({ id: "db-1" })) + .mockResolvedValueOnce(undefined); + installBehaviors({ mySql: { find } }); + + await expect(MySql.get("db-1")).resolves.toBeInstanceOf(MySqlDetailed); + await expect(MySql.get("missing")).rejects.toThrow(); + }); + + test("create delegates with the API request shape", async () => { + const create = vi.fn().mockResolvedValue({ id: "db-new" }); + installBehaviors({ mySql: { create } }); + + const result = await MySql.create(Project.ofId("p-1"), { + description: "created database", + password: "secret", + version: "8.0", + }); + + expect(create).toHaveBeenCalledWith("p-1", { + database: { description: "created database", version: "8.0" }, + user: { accessLevel: "full", password: "secret" }, + }); + expect(result).toBeInstanceOf(MySql); + expect(result.id).toBe("db-new"); + }); + + test("listVersions excludes disabled versions and sorts descending", async () => { + const listVersions = vi + .fn() + .mockResolvedValue([ + buildMySqlVersionData({ disabled: true, number: "1.0" }), + buildMySqlVersionData({ number: "5.7", name: "5.7", id: "v-57" }), + buildMySqlVersionData({ number: "8.0", name: "8.0", id: "v-80" }), + ]); + installBehaviors({ mySql: { listVersions } }); + + const versions = await MySql.listVersions(); + + expect(versions.map(({ number }) => number)).toEqual(["8.0", "5.7"]); + await expect(MySql.getLatestVersion()).resolves.toMatchObject({ + number: "8.0", + }); + }); + + test("exposes derived database data", () => { + const database = new MySqlDetailed( + buildMySqlDatabaseData({ + finalizers: ["app:installation:app-installation-id"], + storageUsageInBytes: 4096, + name: "db_user_abc123", + }), + ); + const withoutFinalizers = new MySqlDetailed(buildMySqlDatabaseData()); + + expect(database.type).toBe("MySQL"); + expect(database.shortId).toBe("abc123"); + expect(database.storageUsage.value).toBe(4096); + expect(database.linkedAppInstallations).toHaveLength(1); + expect(database.linkedAppInstallations[0]?.id).toBe("app-installation-id"); + expect(withoutFinalizers.linkedAppInstallations).toEqual([]); + expect(withoutFinalizers.mainUser).toBeUndefined(); + }); + + test("query returns a sorted, paginated list with ghostmaker identities", async () => { + const list = vi.fn().mockResolvedValue({ + items: [ + buildMySqlDatabaseData({ description: "b", id: "db-b" }), + buildMySqlDatabaseData({ description: "a", id: "db-a" }), + ], + totalCount: 5, + }); + installBehaviors({ mySql: { list } }); + const query = MySql.query({ project: Project.ofId("p-1") }); + + const result = await query.execute(); + + expect(result).toBeInstanceOf(MySqlList); + expect(result).toBeInstanceOf(MySqlListQuery); + expect(result).toBeInstanceOf(ListQueryModel); + expect(result.items).toBeDefined(); + expect(result.items.map(({ description }) => description)).toEqual([ + "a", + "b", + ]); + expect(result.items.every((item) => item instanceof MySqlListItem)).toBe( + true, + ); + expect(result.totalCount).toBe(5); + await expect(query.getTotalCount()).resolves.toBe(5); + }); + + test("list items preserve their reference and data identities", () => { + const item = new MySqlListItem(buildMySqlDatabaseData()); + + expect(item).toBeInstanceOf(MySqlListItem); + expect(item).toBeInstanceOf(MySqlCommon); + expect(item).toBeInstanceOf(MySql); + expect(item).toBeInstanceOf(ReferenceModel); + expect(item.data).toBeDefined(); + }); + + test("aggregateMetaData pins the cache identity", () => { + expect(MySql.aggregateMetaData).toBeInstanceOf(AggregateMetaData); + expect(MySql.aggregateMetaData.domain).toBe("database"); + expect(MySql.aggregateMetaData.aggregate).toBe("mysqldb"); + }); + + test("findCommon delegates to the detailed variant on a bare reference", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildMySqlDatabaseData({ id: "db-1" })) + .mockResolvedValueOnce(undefined); + installBehaviors({ mySql: { find } }); + + const found = await MySql.ofId("db-1").findCommon(); + const missing = await MySql.ofId("missing").findCommon(); + + expect(find).toHaveBeenNthCalledWith(1, "db-1"); + expect(found).toBeInstanceOf(MySqlDetailed); + expect(found?.id).toBe("db-1"); + expect(missing).toBeUndefined(); + }); + + test("getCommon resolves on a bare reference and throws when missing", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildMySqlDatabaseData({ id: "db-1" })) + .mockResolvedValueOnce(undefined); + installBehaviors({ mySql: { find } }); + + await expect(MySql.ofId("db-1").getCommon()).resolves.toBeInstanceOf( + MySqlDetailed, + ); + await expect(MySql.ofId("missing").getCommon()).rejects.toThrow(); + }); + + test("findCommon/getCommon on a materialized model return it without another behavior call", () => { + const find = vi.fn(); + installBehaviors({ mySql: { find } }); + const detailed = new MySqlDetailed(buildMySqlDatabaseData({ id: "db-1" })); + const item = new MySqlListItem(buildMySqlDatabaseData({ id: "db-2" })); + + expect(detailed.findCommon()).toBe(detailed); + expect(detailed.getCommon()).toBe(detailed); + expect(item.findCommon()).toBe(item); + expect(item.getCommon()).toBe(item); + expect(find).not.toHaveBeenCalled(); + }); +}); + +describe("MySqlCharset", () => { + test("query returns charset list items", async () => { + const listCharsets = vi.fn().mockResolvedValue({ + items: [buildMySqlCharsetListItemData({ name: "utf8mb4" })], + totalCount: 1, + }); + installBehaviors({ mySql: { listCharsets } }); + + const result = await MySqlCharset.query().execute(); + + expect(result).toBeInstanceOf(MySqlCharsetList); + expect(result.items[0]).toBeInstanceOf(MySqlCharsetListItem); + expect(result.items[0]?.name).toBe("utf8mb4"); + expect(result.items[0]?.collations).toEqual(["utf8mb4_general_ci"]); + }); +}); diff --git a/packages/models/src/database/MySql/MySql.ts b/packages/models/src/database/MySql/MySql.ts new file mode 100644 index 00000000..cd255ebc --- /dev/null +++ b/packages/models/src/database/MySql/MySql.ts @@ -0,0 +1,251 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import semverCompare from "semver-compare"; +import { omit } from "remeda"; + +import type { DatabaseType } from "../types.js"; +import type { + MySqlUserCreateRequestData, + MySqlUserListQuery, +} from "../MySqlUser/index.js"; +import type { + MySqlCharsetUpdateRequestData, + MySqlListQueryModelData, + MySqlCharacterSettings, + MySqlDatabaseStatus, + MySqlCreateRequest, + MySqlListItemData, + MySqlData, +} from "./types.js"; + +import { AppInstallation } from "../../app/AppInstallation/AppInstallation.js"; +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { MySqlUserDetailed, MySqlUser } from "../MySqlUser/index.js"; +import { AggregateMetaData, Bytes } from "../../common/index.js"; +import { Project } from "../../project/internal.js"; +import { isNewerVersion } from "../lib.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "MySql", +}) +export class MySql extends ReferenceModel { + public static aggregateMetaData = new AggregateMetaData( + "database", + "mysqldb", + ); + + public readonly mySqlUsers: MySqlUserListQuery; + + public constructor(id: string) { + super(id); + this.mySqlUsers = MySqlUser.query({ database: this }); + } + + public static async create(project: Project, data: MySqlCreateRequest) { + const response = await config.behaviors.mySql.create(project.id, { + database: { + description: data.description, + version: data.version, + }, + user: { password: data.password, accessLevel: "full" }, + }); + + return new MySql(response.id); + } + + public static async find(id: string) { + const data = await config.behaviors.mySql.find(id); + if (data !== undefined) { + return new MySqlDetailed(data); + } + } + + public static async get(id: string) { + const database = await this.find(id); + assertObjectFound(database, MySql, id); + return database; + } + + public static async getLatestVersion() { + const versions = await MySql.listVersions(); + return versions[0]; + } + + public static async listVersions() { + const versions = await config.behaviors.mySql.listVersions(); + return versions + .filter((d) => !d.disabled) + .sort((a, b) => semverCompare(b.number, a.number)); + } + + public static ofId(id: string) { + return new MySql(id); + } + + public static query(query: MySqlListQueryModelData) { + return new MySqlListQuery(query); + } + + public async copy(description: string, password: string) { + await config.behaviors.mySql.copyDatabase(this.id, { + user: { accessLevel: "full", password }, + description, + }); + } + + public async createUser(data: MySqlUserCreateRequestData) { + return MySqlUser.create(this, data); + } + + public async delete() { + await config.behaviors.mySql.delete(this.id); + } + + public findCommon(): Promise | MySqlCommon { + return this instanceof MySqlCommon ? this : this.findDetailed(); + } + + public findDetailed(): Promise { + return MySql.find(this.id); + } + + public getCommon(): Promise | MySqlCommon { + return this instanceof MySqlCommon ? this : this.getDetailed(); + } + + public getDetailed(): Promise { + return MySql.get(this.id); + } + + public async updateDefaultCharacterSettings( + data: MySqlCharsetUpdateRequestData, + ) { + await config.behaviors.mySql.updateDefaultCharset(this.id, data); + } + + public async updateDescription(description: string) { + await config.behaviors.mySql.updateDescription(this.id, description); + } + + public async updateVersion(version: string) { + await config.behaviors.mySql.updateVersion(this.id, version); + } +} + +export class MySqlCommon extends WithData()( + MySql, +) { + public readonly characterSettings: MySqlCharacterSettings; + public override readonly data: MySqlListItemData | MySqlData; + public readonly description: string; + public readonly externalHostname: string; + public readonly hostname: string; + public readonly linkedAppInstallations: AppInstallation[]; + public readonly mainUser?: MySqlUserDetailed; + public readonly name: string; + public readonly project: Project; + public readonly shortId: string; + public readonly status: MySqlDatabaseStatus; + public readonly storageUsage: Bytes; + public readonly type: DatabaseType; + public readonly version: string; + + public constructor(data: MySqlListItemData | MySqlData) { + super(data.id); + this.data = data; + this.name = data.name; + this.description = data.description; + this.shortId = data.name.substring(data.name.lastIndexOf("_") + 1); + this.version = data.version; + this.type = "MySQL"; + this.storageUsage = Bytes.of(data.storageUsageInBytes, "bytes"); + + this.linkedAppInstallations = + data.finalizers?.map((f) => + AppInstallation.ofId(f.split(":")?.[2] ?? ""), + ) ?? []; + + this.hostname = data.hostname; + this.externalHostname = data.externalHostname; + this.mainUser = data.mainUser + ? new MySqlUserDetailed(data.mainUser) + : undefined; + this.characterSettings = data.characterSettings; + this.project = Project.ofId(data.projectId); + this.status = data.status; + } + + public async getAvailableVersionUpdate() { + const latestVersion = await MySql.getLatestVersion(); + return latestVersion && isNewerVersion(this.version, latestVersion) + ? latestVersion + : undefined; + } +} + +export class MySqlDetailed extends MySqlCommon { + public override readonly data: MySqlData; + + public constructor(data: MySqlData) { + super(data); + this.data = data; + } +} + +export class MySqlListItem extends MySqlCommon { + public override readonly data: MySqlListItemData; + + public constructor(data: MySqlListItemData) { + super(data); + this.data = data; + } +} + +export class MySqlListQuery extends ListQueryModel { + public constructor(query: MySqlListQueryModelData) { + super(query, { dependencies: [extractId(query.project)] }); + } + + public async execute() { + const { totalCount, items } = await config.behaviors.mySql.list( + extractId(this.query.project), + omit(this.query, ["project"]), + ); + return new MySqlList( + this.query, + items + .map((d) => new MySqlListItem(d)) + .sort((a, b) => a.description.localeCompare(b.description)), + totalCount, + ); + } + + public refine(query: Partial = {}) { + return new MySqlListQuery({ + ...this.query, + ...query, + }); + } +} + +export class MySqlList extends WithListData()(MySqlListQuery) { + public override readonly items: readonly MySqlListItem[]; + public override readonly totalCount: number; + + public constructor( + query: MySqlListQueryModelData, + databases: MySqlListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(databases); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/database/MySql/MySqlCharset.ts b/packages/models/src/database/MySql/MySqlCharset.ts new file mode 100644 index 00000000..00c67a56 --- /dev/null +++ b/packages/models/src/database/MySql/MySqlCharset.ts @@ -0,0 +1,58 @@ +import type { + MySqlCharsetListQueryData, + MySqlCharsetListItemData, + MySqlListQueryData, +} from "./types.js"; + +import { ListQueryModel, WithListData, DataModel } from "../../base/index.js"; +import { config } from "../../config/index.js"; + +export class MySqlCharset { + public static query(query: MySqlCharsetListQueryData = {}) { + return new MySqlCharsetListQuery(query); + } +} + +export class MySqlCharsetListItem extends DataModel { + public readonly collations: string[]; + public readonly name: string; + public constructor(data: MySqlCharsetListItemData) { + super(data); + this.name = data.name; + this.collations = data.collations; + } +} + +export class MySqlCharsetListQuery extends ListQueryModel { + public constructor(query: MySqlListQueryData = {}) { + super(query); + } + + public async execute() { + const { totalCount, items } = await config.behaviors.mySql.listCharsets( + this.query, + ); + return new MySqlCharsetList( + this.query, + items.map((d) => new MySqlCharsetListItem(d)), + totalCount, + ); + } +} + +export class MySqlCharsetList extends WithListData()( + MySqlCharsetListQuery, +) { + public override readonly items: readonly MySqlCharsetListItem[]; + public override readonly totalCount: number; + + public constructor( + query: MySqlListQueryData, + charsets: MySqlCharsetListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(charsets); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/database/MySql/behaviors/api.ts b/packages/models/src/database/MySql/behaviors/api.ts new file mode 100644 index 00000000..639e8201 --- /dev/null +++ b/packages/models/src/database/MySql/behaviors/api.ts @@ -0,0 +1,105 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { MySqlBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { anyStatus403 } from "../../../base/api/typeFixes.js"; +import { resolveTotalCount } from "../../../base/index.js"; + +export const apiMySqlBehaviors = ( + client: MittwaldAPIV2Client, +): MySqlBehaviors => ({ + find: async (mysqlDatabaseId) => { + const response = await client.database.getMysqlDatabase({ + mysqlDatabaseId, + }); + if (response.status === 200) { + return response.data; + } + // API-DRIFT: getMysqlDatabase omits 403 in its generated response type, so anyStatus403 (403 as any) is passed (resolve: use the literal 403 once the client type declares it) + validateResponse(response, [anyStatus403, 404]); + }, + + create: async (projectId, data) => { + const response = await client.database.createMysqlDatabase({ + projectId, + data, + }); + + validateResponse(response, 201, { + validationError: { + pathMappings: { + "*password*": "password", + }, + }, + }); + return response.data; + }, + + listCharsets: async (query) => { + const response = await client.database.listMysqlCharsets({ + queryParameters: query, + }); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + list: async (projectId) => { + const response = await client.database.listMysqlDatabases({ + projectId, + }); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + updateDefaultCharset: async (mysqlDatabaseId, data) => { + const response = await client.database.patchMysqlDatabase({ + data: { characterSettings: data }, + mysqlDatabaseId, + }); + validateResponse(response, 204); + }, + + updateDescription: async (mysqlDatabaseId, description) => { + const response = await client.database.patchMysqlDatabase({ + data: { description }, + mysqlDatabaseId, + }); + validateResponse(response, 204); + }, + + updateVersion: async (mysqlDatabaseId, version) => { + const response = await client.database.patchMysqlDatabase({ + data: { version }, + mysqlDatabaseId, + }); + validateResponse(response, 204); + }, + + copyDatabase: async (mysqlDatabaseId, data) => { + const response = await client.database.copyMysqlDatabase({ + mysqlDatabaseId, + data, + }); + validateResponse(response, 201); + }, + + delete: async (mysqlDatabaseId) => { + const response = await client.database.deleteMysqlDatabase({ + mysqlDatabaseId, + }); + validateResponse(response, 204); + }, + + listVersions: async () => { + const response = await client.database.listMysqlVersions(); + validateResponse(response, 200); + return response.data; + }, +}); diff --git a/packages/models/src/database/MySql/behaviors/index.ts b/packages/models/src/database/MySql/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/database/MySql/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/database/MySql/behaviors/types.ts b/packages/models/src/database/MySql/behaviors/types.ts new file mode 100644 index 00000000..dc876d12 --- /dev/null +++ b/packages/models/src/database/MySql/behaviors/types.ts @@ -0,0 +1,52 @@ +import type { QueryResponseData } from "../../../base/index.js"; +import type { + MySqlCharsetUpdateRequestData, + MySqlCharsetListQueryData, + MySqlCharsetListItemData, + MySqlCreateRequestData, + MySqlCopyRequestData, + MySqlListQueryData, + MySqlListItemData, + MySqlVersionData, + MySqlData, +} from "../types.js"; + +export interface MySqlBehaviors { + listCharsets: (query?: MySqlCharsetListQueryData) => Promise<{ + items: MySqlCharsetListItemData[]; + totalCount: number; + }>; + + list: ( + projectId: string, + query?: MySqlListQueryData, + ) => Promise>; + + updateDefaultCharset: ( + mysqlDatabaseId: string, + data: MySqlCharsetUpdateRequestData, + ) => Promise; + + create: ( + projectId: string, + data: MySqlCreateRequestData, + ) => Promise<{ id: string }>; + + copyDatabase: ( + mysqlDatabaseId: string, + data: MySqlCopyRequestData, + ) => Promise; + + updateDescription: ( + mysqlDatabaseId: string, + description: string, + ) => Promise; + + updateVersion: (mysqlDatabaseId: string, version: string) => Promise; + + find: (mysqlDatabaseId: string) => Promise; + + delete: (mysqlDatabaseId: string) => Promise; + + listVersions: () => Promise; +} diff --git a/packages/models/src/database/MySql/index.ts b/packages/models/src/database/MySql/index.ts new file mode 100644 index 00000000..915d4e5b --- /dev/null +++ b/packages/models/src/database/MySql/index.ts @@ -0,0 +1,3 @@ +export * from "./MySql.js"; +export * from "./MySqlCharset.js"; +export * from "./types.js"; diff --git a/packages/models/src/database/MySql/types.ts b/packages/models/src/database/MySql/types.ts new file mode 100644 index 00000000..ab12b415 --- /dev/null +++ b/packages/models/src/database/MySql/types.ts @@ -0,0 +1,49 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import type { Project } from "../../project/index.js"; + +export type MySqlData = + MittwaldAPIV2.Operations.DatabaseGetMysqlDatabase.ResponseData; + +export type MySqlListItemData = + MittwaldAPIV2.Operations.DatabaseListMysqlDatabases.ResponseData[number]; + +export type MySqlListQueryData = + MittwaldAPIV2.Paths.V2ProjectsProjectIdMysqlDatabases.Get.Parameters.Query; + +export type MySqlListQueryModelData = { + project: Project | string; +} & MySqlListQueryData; + +export type MySqlCreateRequestData = + MittwaldAPIV2.Paths.V2ProjectsProjectIdMysqlDatabases.Post.Parameters.RequestBody; + +export interface MySqlCreateRequest { + description: string; + password: string; + version: string; +} + +export type MySqlVersionData = + MittwaldAPIV2.Operations.DatabaseListMysqlVersions.ResponseData; + +export type MySqlPatchRequestData = + MittwaldAPIV2.Paths.V2MysqlDatabasesMysqlDatabaseId.Patch.Parameters.RequestBody; + +export type MySqlCharsetListQueryData = + MittwaldAPIV2.Paths.V2MysqlCharsets.Get.Parameters.Query; + +export type MySqlCharsetListItemData = + MittwaldAPIV2.Operations.DatabaseListMysqlCharsets.ResponseData[number]; + +export type MySqlCharsetUpdateRequestData = + MySqlPatchRequestData["characterSettings"]; + +export type MySqlCharacterSettings = + MittwaldAPIV2.Components.Schemas.DatabaseCharacterSettings; + +export type MySqlCopyRequestData = + MittwaldAPIV2.Paths.V2MysqlDatabasesMysqlDatabaseIdActionsCopy.Post.Parameters.RequestBody; + +export type MySqlDatabaseStatus = + MittwaldAPIV2.Components.Schemas.DatabaseDatabaseStatus; diff --git a/packages/models/src/database/MySqlUser/MySqlUser.test.ts b/packages/models/src/database/MySqlUser/MySqlUser.test.ts new file mode 100644 index 00000000..12e204de --- /dev/null +++ b/packages/models/src/database/MySqlUser/MySqlUser.test.ts @@ -0,0 +1,176 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { buildMySqlUserData } from "../../testing/builders/buildMySqlUserData.js"; +import { ListQueryModel, ReferenceModel } from "../../base/index.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { MySql } from "../MySql/index.js"; +import { + MySqlUserListQuery, + MySqlUserDetailed, + MySqlUserListItem, + MySqlUserList, + MySqlUser, +} from "./MySqlUser.js"; + +afterEach(resetBehaviors); + +describe("MySqlUser", () => { + test("find delegates and maps found and missing users", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildMySqlUserData({ id: "u-1" })) + .mockResolvedValueOnce(undefined); + installBehaviors({ mySqlUser: { find } }); + + const found = await MySqlUser.find("u-1"); + const missing = await MySqlUser.find("missing"); + + expect(find).toHaveBeenNthCalledWith(1, "u-1"); + expect(found).toBeInstanceOf(MySqlUserDetailed); + expect(found?.id).toBe("u-1"); + expect(missing).toBeUndefined(); + }); + + test("get throws when the user is missing", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ mySqlUser: { find } }); + + await expect(MySqlUser.get("missing")).rejects.toThrow(); + }); + + test("create delegates and returns a reference", async () => { + const create = vi.fn().mockResolvedValue({ id: "u-new" }); + installBehaviors({ mySqlUser: { create } }); + const data = { + accessLevel: "full" as const, + description: "created user", + databaseId: "db-1", + password: "secret", + }; + + const result = await MySqlUser.create(MySql.ofId("db-1"), data); + + expect(create).toHaveBeenCalledWith("db-1", data); + expect(result).toBeInstanceOf(MySqlUser); + expect(result.id).toBe("u-new"); + }); + + test("getPhpMyAdminUrl delegates and returns the URL", async () => { + const getPhpMyAdminUrl = vi + .fn() + .mockResolvedValue("https://phpmyadmin.example.com"); + installBehaviors({ mySqlUser: { getPhpMyAdminUrl } }); + + const result = await MySqlUser.ofId("u-1").getPhpMyAdminUrl(); + + expect(getPhpMyAdminUrl).toHaveBeenCalledWith("u-1"); + expect(result).toBe("https://phpmyadmin.example.com"); + }); + + test("exposes derived user data", () => { + const ready = new MySqlUserDetailed( + buildMySqlUserData({ + accessLevel: "readonly", + description: undefined, + externalAccess: true, + databaseId: "db-1", + status: "ready", + mainUser: true, + }), + ); + const pending = new MySqlUserDetailed( + buildMySqlUserData({ status: "pending" }), + ); + + expect(ready.isReady).toBe(true); + expect(pending.isReady).toBe(false); + expect(ready.description).toBe(""); + expect(ready.database).toBeInstanceOf(MySql); + expect(ready.database.id).toBe("db-1"); + expect(ready.mainUser).toBe(true); + expect(ready.accessLevel).toBe("readonly"); + expect(ready.externalAccess).toBe(true); + }); + + test("query returns list items with ghostmaker identities", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildMySqlUserData({ id: "u-1" })], + }); + installBehaviors({ mySqlUser: { list } }); + + const result = await MySqlUser.query({ + database: MySql.ofId("db-1"), + }).execute(); + + expect(result).toBeInstanceOf(MySqlUserList); + expect(result).toBeInstanceOf(MySqlUserListQuery); + expect(result).toBeInstanceOf(ListQueryModel); + expect(result.items).toBeDefined(); + expect(result.items[0]).toBeInstanceOf(MySqlUserListItem); + + const item = result.items[0]; + expect(item).toBeInstanceOf(MySqlUser); + expect(item).toBeInstanceOf(ReferenceModel); + expect(item.data).toBeDefined(); + }); + + test("aggregateMetaData pins the cache identity", () => { + expect(MySqlUser.aggregateMetaData).toBeInstanceOf(AggregateMetaData); + expect(MySqlUser.aggregateMetaData.domain).toBe("database"); + expect(MySqlUser.aggregateMetaData.aggregate).toBe("mysqluser"); + }); + + test("findCommon delegates to the detailed variant on a bare reference", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildMySqlUserData({ id: "u-1" })) + .mockResolvedValueOnce(undefined); + installBehaviors({ mySqlUser: { find } }); + + const found = await MySqlUser.ofId("u-1").findCommon(); + const missing = await MySqlUser.ofId("missing").findCommon(); + + expect(find).toHaveBeenNthCalledWith(1, "u-1"); + expect(found).toBeInstanceOf(MySqlUserDetailed); + expect(found?.id).toBe("u-1"); + expect(missing).toBeUndefined(); + }); + + test("getCommon resolves on a bare reference and throws when missing", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildMySqlUserData({ id: "u-1" })) + .mockResolvedValueOnce(undefined); + installBehaviors({ mySqlUser: { find } }); + + await expect(MySqlUser.ofId("u-1").getCommon()).resolves.toBeInstanceOf( + MySqlUserDetailed, + ); + await expect(MySqlUser.ofId("missing").getCommon()).rejects.toThrow(); + }); + + test("findCommon/getCommon on a materialized model return it without another behavior call", () => { + const find = vi.fn(); + installBehaviors({ mySqlUser: { find } }); + const detailed = new MySqlUserDetailed(buildMySqlUserData({ id: "u-1" })); + const item = new MySqlUserListItem(buildMySqlUserData({ id: "u-2" })); + + expect(detailed.findCommon()).toBe(detailed); + expect(detailed.getCommon()).toBe(detailed); + expect(item.findCommon()).toBe(item); + expect(item.getCommon()).toBe(item); + expect(find).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/models/src/database/MySqlUser/MySqlUser.ts b/packages/models/src/database/MySqlUser/MySqlUser.ts new file mode 100644 index 00000000..bfcb5150 --- /dev/null +++ b/packages/models/src/database/MySqlUser/MySqlUser.ts @@ -0,0 +1,177 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { omit } from "remeda"; + +import type { + MySqlUserListQueryModelData, + MySqlUserCreateRequestData, + MySqlUserUpdateRequestData, + MySqlUserListItemData, + MySqlUserAccessLevel, + MySqlUserData, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { config } from "../../config/index.js"; +import { MySql } from "../MySql/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "MySqlUser", +}) +export class MySqlUser extends ReferenceModel { + public static aggregateMetaData = new AggregateMetaData( + "database", + "mysqluser", + ); + + public static async create(mySql: MySql, data: MySqlUserCreateRequestData) { + const response = await config.behaviors.mySqlUser.create(mySql.id, data); + + return new MySqlUser(response.id); + } + + public static async find(id: string) { + const data = await config.behaviors.mySqlUser.find(id); + if (data !== undefined) { + return new MySqlUserDetailed(data); + } + } + + public static async get(id: string) { + const databaseUser = await this.find(id); + assertObjectFound(databaseUser, MySqlUser, id); + return databaseUser; + } + + public static ofId(id: string) { + return new MySqlUser(id); + } + + public static query(query: MySqlUserListQueryModelData) { + return new MySqlUserListQuery(query); + } + + public async delete() { + await config.behaviors.mySqlUser.delete(this.id); + } + + public findCommon(): Promise | MySqlUserCommon { + return this instanceof MySqlUserCommon ? this : this.findDetailed(); + } + + public findDetailed(): Promise { + return MySqlUser.find(this.id); + } + + public getCommon(): Promise | MySqlUserCommon { + return this instanceof MySqlUserCommon ? this : this.getDetailed(); + } + + public getDetailed(): Promise { + return MySqlUser.get(this.id); + } + + public async getPhpMyAdminUrl() { + return await config.behaviors.mySqlUser.getPhpMyAdminUrl(this.id); + } + + public async update(data: MySqlUserUpdateRequestData) { + await config.behaviors.mySqlUser.update(this.id, data); + } + + public async updatePassword(password: string) { + await config.behaviors.mySqlUser.updatePassword(this.id, password); + } +} + +export class MySqlUserCommon extends WithData< + MySqlUserListItemData | MySqlUserData +>()(MySqlUser) { + public readonly accessLevel: MySqlUserAccessLevel; + public override readonly data: MySqlUserListItemData | MySqlUserData; + public readonly database: MySql; + public readonly description: string; + public readonly externalAccess: boolean; + public readonly isReady: boolean; + public readonly mainUser: boolean; + public readonly name: string; + + public constructor(data: MySqlUserListItemData | MySqlUserData) { + super(data.id); + this.data = data; + this.name = data.name; + this.mainUser = data.mainUser; + this.description = data.description ?? ""; + this.accessLevel = data.accessLevel; + this.externalAccess = data.externalAccess; + this.isReady = data.status === "ready"; + this.database = MySql.ofId(data.databaseId); + } +} + +export class MySqlUserDetailed extends MySqlUserCommon { + public override readonly data: MySqlUserData; + + public constructor(data: MySqlUserData) { + super(data); + this.data = data; + } +} + +export class MySqlUserListItem extends MySqlUserCommon { + public override readonly data: MySqlUserListItemData; + + public constructor(data: MySqlUserListItemData) { + super(data); + this.data = data; + } +} + +export class MySqlUserListQuery extends ListQueryModel { + public constructor(query: MySqlUserListQueryModelData) { + super(query, { dependencies: [extractId(query.database)] }); + } + + public async execute() { + const { totalCount, items } = await config.behaviors.mySqlUser.list( + extractId(this.query.database), + omit(this.query, ["database"]), + ); + return new MySqlUserList( + this.query, + items.map((d) => new MySqlUserListItem(d)), + totalCount, + ); + } + + public refine(query: Partial = {}) { + return new MySqlUserListQuery({ + ...this.query, + ...query, + }); + } +} + +export class MySqlUserList extends WithListData()( + MySqlUserListQuery, +) { + public override readonly items: readonly MySqlUserListItem[]; + public override readonly totalCount: number; + + public constructor( + query: MySqlUserListQueryModelData, + mySqlUsers: MySqlUserListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(mySqlUsers); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/database/MySqlUser/behaviors/api.ts b/packages/models/src/database/MySqlUser/behaviors/api.ts new file mode 100644 index 00000000..3e12232a --- /dev/null +++ b/packages/models/src/database/MySqlUser/behaviors/api.ts @@ -0,0 +1,73 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { MySqlUserBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount } from "../../../base/index.js"; + +export const apiMySqlUserBehaviors = ( + client: MittwaldAPIV2Client, +): MySqlUserBehaviors => ({ + list: async (databaseId) => { + const response = await client.database.listMysqlUsers({ + mysqlDatabaseId: databaseId, + }); + + validateResponse(response, 200); + + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + create: async (mySqlDatabaseId, data) => { + const response = await client.database.createMysqlUser({ + mysqlDatabaseId: mySqlDatabaseId, + data, + }); + + validateResponse(response, 201); + return response.data; + }, + + find: async (mysqlUserId) => { + const response = await client.database.getMysqlUser({ mysqlUserId }); + + if (response.status === 200) { + return response.data; + } + validateResponse(response, 404); + }, + + getPhpMyAdminUrl: async (mysqlUserId) => { + const response = await client.database.getMysqlUserPhpMyAdminUrl({ + mysqlUserId, + }); + + validateResponse(response, 200); + + return response.data.url; + }, + + updatePassword: async (mysqlUserId, password) => { + const response = await client.database.updateMysqlUser({ + data: { password }, + mysqlUserId, + }); + validateResponse(response, 204); + }, + + update: async (mysqlUserId, data) => { + const response = await client.database.updateMysqlUser({ + mysqlUserId, + data, + }); + validateResponse(response, 204); + }, + + delete: async (mysqlUserId) => { + const response = await client.database.deleteMysqlUser({ mysqlUserId }); + validateResponse(response, 204); + }, +}); diff --git a/packages/models/src/database/MySqlUser/behaviors/index.ts b/packages/models/src/database/MySqlUser/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/database/MySqlUser/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/database/MySqlUser/behaviors/types.ts b/packages/models/src/database/MySqlUser/behaviors/types.ts new file mode 100644 index 00000000..d343c0cf --- /dev/null +++ b/packages/models/src/database/MySqlUser/behaviors/types.ts @@ -0,0 +1,32 @@ +import type { + MySqlUserCreateRequestData, + MySqlUserUpdateRequestData, + MySqlUserListQueryData, + MySqlUserListItemData, + MySqlUserData, +} from "../types.js"; + +export interface MySqlUserBehaviors { + list: ( + databaseId: string, + query?: MySqlUserListQueryData, + ) => Promise<{ items: MySqlUserListItemData[]; totalCount: number }>; + + create: ( + mySqlDatabaseId: string, + data: MySqlUserCreateRequestData, + ) => Promise<{ id: string }>; + + update: ( + mysqlUserId: string, + data: MySqlUserUpdateRequestData, + ) => Promise; + + updatePassword: (mysqlUserId: string, password: string) => Promise; + + find: (mysqlUserId: string) => Promise; + + getPhpMyAdminUrl: (mysqlUserId: string) => Promise; + + delete: (mysqlUserId: string) => Promise; +} diff --git a/packages/models/src/database/MySqlUser/index.ts b/packages/models/src/database/MySqlUser/index.ts new file mode 100644 index 00000000..376701d6 --- /dev/null +++ b/packages/models/src/database/MySqlUser/index.ts @@ -0,0 +1,2 @@ +export * from "./MySqlUser.js"; +export * from "./types.js"; diff --git a/packages/models/src/database/MySqlUser/types.ts b/packages/models/src/database/MySqlUser/types.ts new file mode 100644 index 00000000..e8057597 --- /dev/null +++ b/packages/models/src/database/MySqlUser/types.ts @@ -0,0 +1,24 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import type { MySql } from "../MySql/index.js"; + +export type MySqlUserData = + MittwaldAPIV2.Operations.DatabaseGetMysqlUser.ResponseData; + +export type MySqlUserListItemData = + MittwaldAPIV2.Operations.DatabaseListMysqlUsers.ResponseData[number]; + +export type MySqlUserListQueryData = + MittwaldAPIV2.Paths.V2MysqlDatabasesMysqlDatabaseIdUsers.Get.Parameters.Query; + +export type MySqlUserListQueryModelData = { + database: string | MySql; +} & MySqlUserListQueryData; + +export type MySqlUserCreateRequestData = + MittwaldAPIV2.Paths.V2MysqlDatabasesMysqlDatabaseIdUsers.Post.Parameters.RequestBody; + +export type MySqlUserAccessLevel = MySqlUserData["accessLevel"]; + +export type MySqlUserUpdateRequestData = + MittwaldAPIV2.Paths.V2MysqlUsersMysqlUserId.Patch.Parameters.RequestBody; diff --git a/packages/models/src/database/Redis/Redis.test.ts b/packages/models/src/database/Redis/Redis.test.ts new file mode 100644 index 00000000..a9854e0d --- /dev/null +++ b/packages/models/src/database/Redis/Redis.test.ts @@ -0,0 +1,218 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { buildRedisDatabaseData } from "../../testing/builders/buildRedisDatabaseData.js"; +import { buildRedisVersionData } from "../../testing/builders/buildRedisVersionData.js"; +import { ListQueryModel, ReferenceModel } from "../../base/index.js"; +import { AggregateMetaData, Bytes } from "../../common/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { Project } from "../../project/index.js"; +import { + RedisListQuery, + RedisDetailed, + RedisListItem, + RedisList, + Redis, +} from "./Redis.js"; + +afterEach(resetBehaviors); + +describe("Redis", () => { + test("find delegates and maps found and missing databases", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildRedisDatabaseData({ id: "redis-1" })) + .mockResolvedValueOnce(undefined); + installBehaviors({ redis: { find } }); + + const found = await Redis.find("redis-1"); + const missing = await Redis.find("missing"); + + expect(find).toHaveBeenNthCalledWith(1, "redis-1"); + expect(found).toBeInstanceOf(RedisDetailed); + expect(found?.id).toBe("redis-1"); + expect(missing).toBeUndefined(); + }); + + test("get returns a detailed database or throws when it is missing", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildRedisDatabaseData({ id: "redis-1" })) + .mockResolvedValueOnce(undefined); + installBehaviors({ redis: { find } }); + + await expect(Redis.get("redis-1")).resolves.toBeInstanceOf(RedisDetailed); + await expect(Redis.get("missing")).rejects.toThrow(); + }); + + test("create delegates and returns a reference", async () => { + const create = vi.fn().mockResolvedValue({ id: "redis-new" }); + installBehaviors({ redis: { create } }); + const data = { + description: "created redis", + version: "7.0", + }; + + const result = await Redis.create(Project.ofId("p-1"), data); + + expect(create).toHaveBeenCalledWith("p-1", data); + expect(result).toBeInstanceOf(Redis); + expect(result.id).toBe("redis-new"); + }); + + test("listVersions delegates, excludes disabled versions, and sorts descending", async () => { + const listVersions = vi + .fn() + .mockResolvedValue([ + buildRedisVersionData({ disabled: true, number: "1.0" }), + buildRedisVersionData({ number: "6.0", name: "6.0", id: "v-60" }), + buildRedisVersionData({ number: "7.0", name: "7.0", id: "v-70" }), + ]); + installBehaviors({ redis: { listVersions } }); + const project = Project.ofId("p-1"); + + const versions = await Redis.listVersions(project); + + expect(listVersions).toHaveBeenCalledWith("p-1"); + expect(versions.map(({ number }) => number)).toEqual(["7.0", "6.0"]); + await expect(Redis.getLatestVersion(project)).resolves.toMatchObject({ + number: "7.0", + }); + }); + + test("exposes derived database data", () => { + const database = new RedisDetailed( + buildRedisDatabaseData({ + configuration: { + maxMemoryPolicy: "noeviction", + maxMemory: "536870912", + additionalFlags: [], + persistent: true, + }, + finalizers: ["app:installation:app-installation-id"], + storageUsageInBytes: 4096, + }), + ); + const withoutConfiguration = new RedisDetailed( + buildRedisDatabaseData({ configuration: undefined }), + ); + const withoutFinalizers = new RedisDetailed(buildRedisDatabaseData()); + + expect(database.type).toBe("Redis"); + expect(database.connectionString).toBe("redis://redis.example.com:6379"); + expect(database.configuration?.persistent).toBe(true); + expect(database.configuration?.maxMemory).toBeInstanceOf(Bytes); + expect(database.configuration?.maxMemory?.value).toBe(512 * 1024 * 1024); + expect(database.configuration?.maxMemoryPolicy).toBe("noeviction"); + expect(withoutConfiguration.configuration).toBeUndefined(); + expect(database.linkedAppInstallations[0]?.id).toBe("app-installation-id"); + expect(withoutFinalizers.linkedAppInstallations).toEqual([]); + expect(database.storageUsage.value).toBe(4096); + }); + + test("query returns a sorted, paginated list with ghostmaker identities", async () => { + const list = vi.fn().mockResolvedValue({ + items: [ + buildRedisDatabaseData({ description: "b", id: "redis-b" }), + buildRedisDatabaseData({ description: "a", id: "redis-a" }), + ], + totalCount: 3, + }); + installBehaviors({ redis: { list } }); + const query = Redis.query({ project: Project.ofId("p-1") }); + + const result = await query.execute(); + + expect(result).toBeInstanceOf(RedisList); + expect(result).toBeInstanceOf(RedisListQuery); + expect(result).toBeInstanceOf(ListQueryModel); + expect(result.items).toBeDefined(); + expect(result.items.map(({ description }) => description)).toEqual([ + "a", + "b", + ]); + expect(result.items.every((item) => item instanceof RedisListItem)).toBe( + true, + ); + expect(result.totalCount).toBe(3); + await expect(query.getTotalCount()).resolves.toBe(3); + + const item = result.items[0]; + expect(item).toBeInstanceOf(Redis); + expect(item).toBeInstanceOf(ReferenceModel); + expect(item.data).toBeDefined(); + }); + + test("aggregateMetaData pins the cache identity", () => { + expect(Redis.aggregateMetaData).toBeInstanceOf(AggregateMetaData); + expect(Redis.aggregateMetaData.domain).toBe("database"); + expect(Redis.aggregateMetaData.aggregate).toBe("redisdb"); + }); + + test("findCommon delegates to the detailed variant on a bare reference", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildRedisDatabaseData({ id: "redis-1" })) + .mockResolvedValueOnce(undefined); + installBehaviors({ redis: { find } }); + + const found = await Redis.ofId("redis-1").findCommon(); + const missing = await Redis.ofId("missing").findCommon(); + + expect(find).toHaveBeenNthCalledWith(1, "redis-1"); + expect(found).toBeInstanceOf(RedisDetailed); + expect(found?.id).toBe("redis-1"); + expect(missing).toBeUndefined(); + }); + + test("getCommon resolves on a bare reference and throws when missing", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildRedisDatabaseData({ id: "redis-1" })) + .mockResolvedValueOnce(undefined); + installBehaviors({ redis: { find } }); + + await expect(Redis.ofId("redis-1").getCommon()).resolves.toBeInstanceOf( + RedisDetailed, + ); + await expect(Redis.ofId("missing").getCommon()).rejects.toThrow(); + }); + + test("findCommon/getCommon on a materialized model return it without another behavior call", () => { + const find = vi.fn(); + installBehaviors({ redis: { find } }); + const detailed = new RedisDetailed( + buildRedisDatabaseData({ id: "redis-1" }), + ); + const item = new RedisListItem(buildRedisDatabaseData({ id: "redis-2" })); + + expect(detailed.findCommon()).toBe(detailed); + expect(detailed.getCommon()).toBe(detailed); + expect(item.findCommon()).toBe(item); + expect(item.getCommon()).toBe(item); + expect(find).not.toHaveBeenCalled(); + }); + + test("configuration derives optional fields defensively when absent", () => { + const withPartialConfiguration = new RedisDetailed( + buildRedisDatabaseData({ configuration: {} }), + ); + + expect(withPartialConfiguration.configuration).toBeDefined(); + expect(withPartialConfiguration.configuration?.maxMemory).toBeUndefined(); + expect( + withPartialConfiguration.configuration?.maxMemoryPolicy, + ).toBeUndefined(); + expect(withPartialConfiguration.configuration?.persistent).toBe(false); + }); +}); diff --git a/packages/models/src/database/Redis/Redis.ts b/packages/models/src/database/Redis/Redis.ts new file mode 100644 index 00000000..dff1d906 --- /dev/null +++ b/packages/models/src/database/Redis/Redis.ts @@ -0,0 +1,221 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import semverCompare from "semver-compare"; +import { omit } from "remeda"; + +import type { DatabaseType } from "../types.js"; +import type { + RedisConfigurationUpdateRequestData, + RedisListQueryModelData, + RedisCreateRequestData, + RedisMaxMemoryPolicy, + RedisConfiguration, + RedisListItemData, + RedisData, +} from "./types.js"; + +import { AppInstallation } from "../../app/AppInstallation/AppInstallation.js"; +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { AggregateMetaData, Bytes } from "../../common/index.js"; +import { Project } from "../../project/internal.js"; +import { isNewerVersion } from "../lib.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "Redis", +}) +export class Redis extends ReferenceModel { + public static aggregateMetaData = new AggregateMetaData( + "database", + "redisdb", + ); + public static async create(project: Project, data: RedisCreateRequestData) { + const { id } = await config.behaviors.redis.create(project.id, data); + return new Redis(id); + } + + public static async find(id: string) { + const data = await config.behaviors.redis.find(id); + if (data !== undefined) { + return new RedisDetailed(data); + } + } + + public static async get(id: string) { + const database = await this.find(id); + assertObjectFound(database, Redis, id); + return database; + } + + public static async getLatestVersion(project: Project) { + const versions = await Redis.listVersions(project); + return versions[0]; + } + + public static async listVersions(project: Project) { + const versions = await config.behaviors.redis.listVersions(project.id); + + return versions + .filter((v) => !v.disabled) + .sort((a, b) => semverCompare(b.number, a.number)); + } + + public static ofId(id: string) { + return new Redis(id); + } + + public static query(query: RedisListQueryModelData) { + return new RedisListQuery(query); + } + + public async delete() { + await config.behaviors.redis.delete(this.id); + } + + public findCommon(): Promise | RedisCommon { + return this instanceof RedisCommon ? this : this.findDetailed(); + } + + public findDetailed(): Promise { + return Redis.find(this.id); + } + + public getCommon(): Promise | RedisCommon { + return this instanceof RedisCommon ? this : this.getDetailed(); + } + + public getDetailed(): Promise { + return Redis.get(this.id); + } + + public async updateConfiguration(data: RedisConfigurationUpdateRequestData) { + await config.behaviors.redis.updateConfiguration(this.id, data); + } + + public async updateDescription(description: string) { + await config.behaviors.redis.updateDescription(this.id, description); + } + + public async updateVersion(version: string) { + await config.behaviors.redis.updateVersion(this.id, version); + } +} + +export class RedisCommon extends WithData()( + Redis, +) { + public readonly configuration?: RedisConfiguration; + public readonly connectionString: string; + public override readonly data: RedisListItemData | RedisData; + public readonly description: string; + public readonly hostname: string; + public readonly linkedAppInstallations: AppInstallation[]; + public readonly name: string; + public readonly port: number; + public readonly project: Project; + public readonly storageUsage: Bytes; + public readonly type: DatabaseType; + public readonly version: string; + + public constructor(data: RedisListItemData | RedisData) { + super(data.id); + this.data = data; + this.name = data.name; + this.description = data.description; + this.version = data.version; + this.type = "Redis"; + this.storageUsage = Bytes.of(data.storageUsageInBytes, "bytes"); + if (data.configuration) { + this.configuration = { + maxMemory: data.configuration.maxMemory + ? Bytes.of(parseInt(data.configuration.maxMemory), "bytes") + : undefined, + maxMemoryPolicy: data.configuration.maxMemoryPolicy as + RedisMaxMemoryPolicy | undefined, + persistent: !!data.configuration.persistent, + }; + } + this.hostname = data.hostname; + this.port = data.port; + this.connectionString = `redis://${data.hostname}:${data.port}`; + + this.linkedAppInstallations = + data.finalizers?.map((f) => + AppInstallation.ofId(f.split(":")?.[2] ?? ""), + ) ?? []; + this.project = Project.ofId(data.projectId); + } + + public async getAvailableVersionUpdate() { + const latestVersion = await Redis.getLatestVersion(this.project); + return latestVersion && isNewerVersion(this.version, latestVersion) + ? latestVersion + : undefined; + } +} + +export class RedisDetailed extends RedisCommon { + public override readonly data: RedisData; + + public constructor(data: RedisData) { + super(data); + this.data = data; + } +} + +export class RedisListItem extends RedisCommon { + public override readonly data: RedisListItemData; + + public constructor(data: RedisListItemData) { + super(data); + this.data = data; + } +} + +export class RedisListQuery extends ListQueryModel { + public constructor(query: RedisListQueryModelData) { + super(query, { dependencies: [extractId(query.project)] }); + } + + public async execute() { + const { totalCount, items } = await config.behaviors.redis.list( + extractId(this.query.project), + omit(this.query, ["project"]), + ); + return new RedisList( + this.query, + items + .map((d) => new RedisListItem(d)) + .sort((a, b) => a.description.localeCompare(b.description)), + totalCount, + ); + } + + public refine(query: Partial = {}) { + return new RedisListQuery({ + ...this.query, + ...query, + }); + } +} + +export class RedisList extends WithListData()(RedisListQuery) { + public override readonly items: readonly RedisListItem[]; + public override readonly totalCount: number; + + public constructor( + query: RedisListQueryModelData, + databases: RedisListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(databases); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/database/Redis/behaviors/api.ts b/packages/models/src/database/Redis/behaviors/api.ts new file mode 100644 index 00000000..2957f1e3 --- /dev/null +++ b/packages/models/src/database/Redis/behaviors/api.ts @@ -0,0 +1,80 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { RedisBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount, anyStatus403 } from "../../../base/index.js"; + +export const apiRedisBehaviors = ( + client: MittwaldAPIV2Client, +): RedisBehaviors => ({ + find: async (redisDatabaseId) => { + const response = await client.database.getRedisDatabase({ + redisDatabaseId, + }); + if (response.status === 200) { + return response.data; + } + // API-DRIFT: getRedisDatabase omits 403 in its generated response type, so anyStatus403 (403 as any) is passed (resolve: use the literal 403 once the client type declares it) + validateResponse(response, [anyStatus403, 404]); + }, + + list: async (projectId) => { + const response = await client.database.listRedisDatabases({ + projectId, + }); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + updateConfiguration: async (redisDatabaseId, data) => { + const response = await client.database.patchRedisDatabase({ + data: { configuration: data }, + redisDatabaseId, + }); + validateResponse(response, 204); + }, + + updateDescription: async (redisDatabaseId, description) => { + const response = await client.database.patchRedisDatabase({ + data: { description }, + redisDatabaseId, + }); + validateResponse(response, 204); + }, + + updateVersion: async (redisDatabaseId, version) => { + const response = await client.database.patchRedisDatabase({ + data: { version }, + redisDatabaseId, + }); + validateResponse(response, 204); + }, + + listVersions: async (projectId) => { + const response = await client.database.listRedisVersions({ + queryParameters: { projectId }, + }); + validateResponse(response, 200); + return response.data; + }, + + create: async (projectId, data) => { + const response = await client.database.createRedisDatabase({ + projectId, + data, + }); + validateResponse(response, 201); + return response.data; + }, + + delete: async (redisDatabaseId) => { + const response = await client.database.deleteRedisDatabase({ + redisDatabaseId, + }); + validateResponse(response, 204); + }, +}); diff --git a/packages/models/src/database/Redis/behaviors/index.ts b/packages/models/src/database/Redis/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/database/Redis/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/database/Redis/behaviors/types.ts b/packages/models/src/database/Redis/behaviors/types.ts new file mode 100644 index 00000000..0a9b22d5 --- /dev/null +++ b/packages/models/src/database/Redis/behaviors/types.ts @@ -0,0 +1,39 @@ +import type { QueryResponseData } from "../../../base/index.js"; +import type { + RedisConfigurationUpdateRequestData, + RedisCreateRequestData, + RedisListQueryData, + RedisListItemData, + RedisVersionData, + RedisData, +} from "../types.js"; + +export interface RedisBehaviors { + updateConfiguration: ( + redisDatabaseId: string, + data: RedisConfigurationUpdateRequestData, + ) => Promise; + + list: ( + projectId: string, + query?: RedisListQueryData, + ) => Promise>; + + create: ( + projectId: string, + data: RedisCreateRequestData, + ) => Promise<{ id: string }>; + + updateDescription: ( + redisDatabaseId: string, + description: string, + ) => Promise; + + updateVersion: (redisDatabaseId: string, version: string) => Promise; + + find: (redisDatabaseId: string) => Promise; + + listVersions: (projectId: string) => Promise; + + delete: (redisDatabaseId: string) => Promise; +} diff --git a/packages/models/src/database/Redis/index.ts b/packages/models/src/database/Redis/index.ts new file mode 100644 index 00000000..b7912fd1 --- /dev/null +++ b/packages/models/src/database/Redis/index.ts @@ -0,0 +1,2 @@ +export * from "./Redis.js"; +export * from "./types.js"; diff --git a/packages/models/src/database/Redis/types.ts b/packages/models/src/database/Redis/types.ts new file mode 100644 index 00000000..b0301cfd --- /dev/null +++ b/packages/models/src/database/Redis/types.ts @@ -0,0 +1,45 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import type { Project } from "../../project/index.js"; +import type { Bytes } from "../../common/index.js"; + +export type RedisData = + MittwaldAPIV2.Operations.DatabaseGetRedisDatabase.ResponseData; + +export type RedisListItemData = + MittwaldAPIV2.Operations.DatabaseListRedisDatabases.ResponseData[number]; + +export type RedisListQueryData = + MittwaldAPIV2.Paths.V2ProjectsProjectIdRedisDatabases.Get.Parameters.Query; + +export type RedisListQueryModelData = { + project: Project | string; +} & RedisListQueryData; + +export type RedisCreateRequestData = + MittwaldAPIV2.Paths.V2ProjectsProjectIdRedisDatabases.Post.Parameters.RequestBody; + +export type RedisPatchRequestData = + MittwaldAPIV2.Paths.V2RedisDatabasesRedisDatabaseId.Patch.Parameters.RequestBody; + +export type RedisVersionData = + MittwaldAPIV2.Operations.DatabaseListRedisVersions.ResponseData; + +export interface RedisConfiguration { + maxMemoryPolicy?: RedisMaxMemoryPolicy; + persistent: boolean; + maxMemory?: Bytes; +} + +export type RedisMaxMemoryPolicy = + | "volatile-random" + | "allkeys-random" + | "volatile-lru" + | "volatile-lfu" + | "volatile-ttl" + | "allkeys-lru" + | "allkeys-lfu" + | "noeviction"; + +export type RedisConfigurationUpdateRequestData = + RedisPatchRequestData["configuration"]; diff --git a/packages/models/src/database/index.ts b/packages/models/src/database/index.ts new file mode 100644 index 00000000..c4a58d71 --- /dev/null +++ b/packages/models/src/database/index.ts @@ -0,0 +1,5 @@ +export * from "./lib.js"; +export * from "./MySql/index.js"; +export * from "./MySqlUser/index.js"; +export * from "./Redis/index.js"; +export * from "./types.js"; diff --git a/packages/models/src/database/lib.ts b/packages/models/src/database/lib.ts new file mode 100644 index 00000000..0f586e22 --- /dev/null +++ b/packages/models/src/database/lib.ts @@ -0,0 +1,6 @@ +import semverCompare from "semver-compare"; + +export const isNewerVersion = ( + currentVersion: string, + version: T, +): boolean => semverCompare(version.number, currentVersion) > 0; diff --git a/packages/models/src/database/types.ts b/packages/models/src/database/types.ts new file mode 100644 index 00000000..2bf6e8dd --- /dev/null +++ b/packages/models/src/database/types.ts @@ -0,0 +1 @@ +export type DatabaseType = "Redis" | "MySQL"; diff --git a/packages/models/src/dns/DnsRecordCaa/DnsRecordCaa.test.ts b/packages/models/src/dns/DnsRecordCaa/DnsRecordCaa.test.ts new file mode 100644 index 00000000..b74683e6 --- /dev/null +++ b/packages/models/src/dns/DnsRecordCaa/DnsRecordCaa.test.ts @@ -0,0 +1,76 @@ +import { beforeEach, afterEach, describe, expect, test, vi } from "vitest"; + +import type { DnsZoneCommon } from "../DnsZone/index.js"; + +import { + buildDnsRecordCaaComponentData, + buildDnsRecordCaaEntry, +} from "../../testing/builders/buildDnsRecordCaaData.js"; +import { DnsRecordCaa } from "./DnsRecordCaa.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; + +beforeEach(() => installBehaviors({})); +afterEach(resetBehaviors); + +describe("DnsRecordCaa", () => { + test("represents an unset record", () => { + const dnsZone = {} as unknown as DnsZoneCommon; + const record = new DnsRecordCaa(dnsZone, {}); + + expect(record.records).toBeUndefined(); + expect(record.getTtl()).toBe("auto"); + expect(record.asList()).toEqual([]); + expect(record.isEmpty()).toBe(true); + }); + + test("maps a component record to its observable values", () => { + const dnsZone = {} as unknown as DnsZoneCommon; + const record = new DnsRecordCaa(dnsZone, buildDnsRecordCaaComponentData()); + + expect(record.getTtl()).toBe(3600); + expect(record.asList()).toEqual([ + { + value: "letsencrypt.org", + recordType: "caa", + tag: "issue", + flags: 0, + }, + ]); + expect(record.isEmpty()).toBe(false); + }); + + test("delegates adding a record", async () => { + const setCaaRecord = vi.fn(); + const existingRecord = buildDnsRecordCaaEntry(); + const dnsZone = { + recordSet: { caa: { records: [existingRecord] } }, + setCaaRecord, + } as unknown as DnsZoneCommon; + const record = new DnsRecordCaa( + dnsZone, + buildDnsRecordCaaComponentData({ records: [existingRecord] }), + ); + const newRecord = buildDnsRecordCaaEntry({ value: "example.com" }); + + await record.addRecord(newRecord); + + expect(setCaaRecord).toHaveBeenCalledOnce(); + expect(setCaaRecord).toHaveBeenCalledWith( + [existingRecord, newRecord], + undefined, + ); + }); + + test("delegates clearing the record", async () => { + const setCaaRecord = vi.fn(); + const dnsZone = { setCaaRecord } as unknown as DnsZoneCommon; + const record = new DnsRecordCaa(dnsZone, {}); + + await record.setEmpty(); + + expect(setCaaRecord).toHaveBeenCalledWith([]); + }); +}); diff --git a/packages/models/src/dns/DnsRecordCaa/DnsRecordCaa.ts b/packages/models/src/dns/DnsRecordCaa/DnsRecordCaa.ts new file mode 100644 index 00000000..811b1e90 --- /dev/null +++ b/packages/models/src/dns/DnsRecordCaa/DnsRecordCaa.ts @@ -0,0 +1,83 @@ +import type { DnsRecordSettingsData } from "../DnsRecordSettings/index.js"; +import type { DnsZoneCommon } from "../DnsZone/index.js"; +import type { + CaaRecordListItem, + DnsRecordCaaEntry, + DnsRecordCaaData, +} from "./types.js"; + +import { DnsRecordSettings } from "../DnsRecordSettings/index.js"; +import { DataModel } from "../../base/index.js"; + +export class DnsRecordCaa extends DataModel { + public readonly dnsZone: DnsZoneCommon; + public readonly records?: DnsRecordCaaEntry[]; + public readonly settings?: DnsRecordSettings; + public constructor(dnsZone: DnsZoneCommon, data: DnsRecordCaaData) { + super(data); + this.dnsZone = dnsZone; + if ("records" in data) { + this.records = data.records; + this.settings = new DnsRecordSettings(data.settings); + } + } + + public async addRecord( + newRecord: DnsRecordCaaEntry, + settings?: DnsRecordSettingsData, + ) { + return await this.dnsZone.setCaaRecord( + [...(this.records ?? []), newRecord], + settings, + ); + } + + public asList(): CaaRecordListItem[] { + if (!this.records) { + return []; + } + return this.records.map((i) => { + return { + recordType: "caa", + ...i, + }; + }); + } + + public getTtl(): number | "auto" { + if (this.settings) { + return this.settings.ttl; + } + return "auto"; + } + + public isEmpty(): boolean { + return (this.records ?? []).length === 0; + } + + public async removeRecord(record: DnsRecordCaaEntry) { + await this.dnsZone.setCaaRecord( + (this.records ?? []).filter((i) => !this.areRecordsEqual(record, i)), + ); + } + + public async setEmpty() { + return await this.dnsZone.setCaaRecord([]); + } + + public async updateRecord( + oldRecord: DnsRecordCaaEntry, + newRecord: DnsRecordCaaEntry, + settings?: DnsRecordSettingsData, + ) { + const existingItems = this.dnsZone.recordSet.caa.records ?? []; + const update = existingItems.map((i) => + this.areRecordsEqual(oldRecord, i) ? newRecord : i, + ); + return await this.dnsZone.setCaaRecord(update, settings); + } + + private areRecordsEqual(a: DnsRecordCaaEntry, b: DnsRecordCaaEntry): boolean { + return a.tag === b.tag && a.flags === b.flags && a.value === b.value; + } +} diff --git a/packages/models/src/dns/DnsRecordCaa/index.ts b/packages/models/src/dns/DnsRecordCaa/index.ts new file mode 100644 index 00000000..036bca2d --- /dev/null +++ b/packages/models/src/dns/DnsRecordCaa/index.ts @@ -0,0 +1,2 @@ +export * from "./DnsRecordCaa.js"; +export * from "./types.js"; diff --git a/packages/models/src/dns/DnsRecordCaa/types.ts b/packages/models/src/dns/DnsRecordCaa/types.ts new file mode 100644 index 00000000..4a658ee9 --- /dev/null +++ b/packages/models/src/dns/DnsRecordCaa/types.ts @@ -0,0 +1,8 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type DnsRecordCaaData = MittwaldAPIV2.Components.Schemas.DnsRecordCAA; + +export type DnsRecordCaaEntry = + MittwaldAPIV2.Components.Schemas.DnsRecordCAARecord; + +export type CaaRecordListItem = { recordType: "caa" } & DnsRecordCaaEntry; diff --git a/packages/models/src/dns/DnsRecordCname/DnsRecordCname.test.ts b/packages/models/src/dns/DnsRecordCname/DnsRecordCname.test.ts new file mode 100644 index 00000000..350892b3 --- /dev/null +++ b/packages/models/src/dns/DnsRecordCname/DnsRecordCname.test.ts @@ -0,0 +1,50 @@ +import { beforeEach, afterEach, describe, expect, test, vi } from "vitest"; + +import type { DnsZoneCommon } from "../DnsZone/index.js"; + +import { buildDnsRecordCnameComponentData } from "../../testing/builders/buildDnsRecordCnameData.js"; +import { DnsRecordCname } from "./DnsRecordCname.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; + +beforeEach(() => installBehaviors({})); +afterEach(resetBehaviors); + +describe("DnsRecordCname", () => { + test("represents an unset record", () => { + const dnsZone = {} as unknown as DnsZoneCommon; + const record = new DnsRecordCname(dnsZone, {}); + + expect(record.fqdn).toBeUndefined(); + expect(record.getTtl()).toBe("auto"); + expect(record.asList()).toEqual([]); + expect(record.isEmpty()).toBe(true); + }); + + test("maps a component record to its observable values", () => { + const dnsZone = {} as unknown as DnsZoneCommon; + const record = new DnsRecordCname( + dnsZone, + buildDnsRecordCnameComponentData(), + ); + + expect(record.fqdn).toBe("target.example.com"); + expect(record.getTtl()).toBe(300); + expect(record.asList()).toEqual([ + { fqdn: "target.example.com", recordType: "cname" }, + ]); + expect(record.isEmpty()).toBe(false); + }); + + test("delegates clearing the record", async () => { + const removeCname = vi.fn(); + const dnsZone = { removeCname } as unknown as DnsZoneCommon; + const record = new DnsRecordCname(dnsZone, {}); + + await record.setEmpty(); + + expect(removeCname).toHaveBeenCalledOnce(); + }); +}); diff --git a/packages/models/src/dns/DnsRecordCname/DnsRecordCname.ts b/packages/models/src/dns/DnsRecordCname/DnsRecordCname.ts new file mode 100644 index 00000000..c6903e42 --- /dev/null +++ b/packages/models/src/dns/DnsRecordCname/DnsRecordCname.ts @@ -0,0 +1,45 @@ +import type { CnameRecordListItem, DnsRecordCnameData } from "./types.js"; +import type { DnsZoneCommon } from "../DnsZone/index.js"; + +import { DnsRecordSettings } from "../DnsRecordSettings/index.js"; +import { DataModel } from "../../base/index.js"; + +export class DnsRecordCname extends DataModel { + public readonly dnsZone: DnsZoneCommon; + public readonly fqdn?: string; + public readonly settings?: DnsRecordSettings; + public constructor(dnsZone: DnsZoneCommon, data: DnsRecordCnameData) { + super(data); + this.dnsZone = dnsZone; + if ("fqdn" in data) { + this.fqdn = data.fqdn; + this.settings = new DnsRecordSettings(data.settings); + } + } + public asList(): CnameRecordListItem[] { + if (this.fqdn) { + return [ + { + recordType: "cname", + fqdn: this.fqdn, + }, + ]; + } + return []; + } + + public getTtl(): number | "auto" { + if (this.settings) { + return this.settings.ttl; + } + return "auto"; + } + + public isEmpty() { + return this.fqdn === undefined; + } + + public async setEmpty() { + await this.dnsZone.removeCname(); + } +} diff --git a/packages/models/src/dns/DnsRecordCname/index.ts b/packages/models/src/dns/DnsRecordCname/index.ts new file mode 100644 index 00000000..076d5a6c --- /dev/null +++ b/packages/models/src/dns/DnsRecordCname/index.ts @@ -0,0 +1,2 @@ +export * from "./DnsRecordCname.js"; +export * from "./types.js"; diff --git a/packages/models/src/dns/DnsRecordCname/types.ts b/packages/models/src/dns/DnsRecordCname/types.ts new file mode 100644 index 00000000..851f2227 --- /dev/null +++ b/packages/models/src/dns/DnsRecordCname/types.ts @@ -0,0 +1,9 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type DnsRecordCnameData = + MittwaldAPIV2.Components.Schemas.DnsRecordCNAME; + +export interface CnameRecordListItem { + recordType: "cname"; + fqdn: string; +} diff --git a/packages/models/src/dns/DnsRecordCombinedA/DnsRecordCombinedA.test.ts b/packages/models/src/dns/DnsRecordCombinedA/DnsRecordCombinedA.test.ts new file mode 100644 index 00000000..14d483b7 --- /dev/null +++ b/packages/models/src/dns/DnsRecordCombinedA/DnsRecordCombinedA.test.ts @@ -0,0 +1,106 @@ +import { beforeEach, afterEach, describe, expect, test, vi } from "vitest"; + +import type { DnsZoneCommon } from "../DnsZone/index.js"; + +import { + buildDnsRecordCombinedAManagedData, + buildDnsRecordCombinedACustomData, + buildDnsRecordCombinedAUnsetData, +} from "../../testing/builders/buildDnsRecordCombinedAData.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { + dnsRecordCombinedAFactory, + DnsRecordCombinedAManaged, + DnsRecordCombinedACustom, + DnsRecordCombinedAUnset, +} from "./DnsRecordCombinedA.js"; + +beforeEach(() => installBehaviors({})); +afterEach(resetBehaviors); + +describe("dnsRecordCombinedAFactory", () => { + test("constructs a custom record", () => { + const dnsZone = {} as unknown as DnsZoneCommon; + const record = dnsRecordCombinedAFactory( + dnsZone, + buildDnsRecordCombinedACustomData(), + ); + + expect(record).toBeInstanceOf(DnsRecordCombinedACustom); + expect(record.type).toBe("custom"); + expect(record.getTtl()).toBe(600); + expect(record.asList()).toEqual([ + { + recordType: "a", + type: "custom", + ip: "1.2.3.4", + isIpV6: false, + }, + { + ip: "2001:db8::1", + recordType: "a", + type: "custom", + isIpV6: true, + }, + ]); + expect(record.isEmpty()).toBe(false); + expect(record.hasIpAddress("1.2.3.4")).toBe(true); + expect(record.hasIpAddress("9.9.9.9")).toBe(false); + }); + + test("constructs a managed record", () => { + const dnsZone = {} as unknown as DnsZoneCommon; + const record = dnsRecordCombinedAFactory( + dnsZone, + buildDnsRecordCombinedAManagedData(), + ); + + expect(record).toBeInstanceOf(DnsRecordCombinedAManaged); + if (!(record instanceof DnsRecordCombinedAManaged)) { + throw new Error("Expected a managed record"); + } + expect(record.type).toBe("managed"); + expect(record.getTtl()).toBe("auto"); + expect(record.asList()).toEqual([{ type: "managed", recordType: "a" }]); + expect(record.isEmpty()).toBe(false); + expect(record.hasIpAddress()).toBe(false); + expect(record.managedBy.id).toBe("ingress-1"); + }); + + test("constructs an unset record", () => { + const dnsZone = {} as unknown as DnsZoneCommon; + const record = dnsRecordCombinedAFactory( + dnsZone, + buildDnsRecordCombinedAUnsetData(), + ); + + expect(record).toBeInstanceOf(DnsRecordCombinedAUnset); + if (!(record instanceof DnsRecordCombinedAUnset)) { + throw new Error("Expected an unset record"); + } + expect(record.type).toBe("unset"); + expect(record.getTtl()).toBe("auto"); + expect(record.asList()).toEqual([]); + expect(record.isEmpty()).toBe(true); + expect(record.hasIpAddress()).toBe(false); + }); + + test("delegates clearing a custom record", async () => { + const setCustomARecord = vi.fn(); + const dnsZone = { + recordSet: { combinedA: { type: "custom", aaaa: [], a: [] } }, + setCustomARecord, + } as unknown as DnsZoneCommon; + const record = dnsRecordCombinedAFactory( + dnsZone, + buildDnsRecordCombinedACustomData(), + ); + + await record.setEmpty(); + + expect(setCustomARecord).toHaveBeenCalledWith([], []); + }); +}); diff --git a/packages/models/src/dns/DnsRecordCombinedA/DnsRecordCombinedA.ts b/packages/models/src/dns/DnsRecordCombinedA/DnsRecordCombinedA.ts new file mode 100644 index 00000000..eb602ffe --- /dev/null +++ b/packages/models/src/dns/DnsRecordCombinedA/DnsRecordCombinedA.ts @@ -0,0 +1,227 @@ +import type { DnsZoneCommon } from "../DnsZone/index.js"; +import type { + DnsRecordCombinedAManagedData, + DnsRecordCombinedACustomData, + DnsRecordCombinedAUnsetData, + DnsRecordCombinedAData, + ARecordCustomListItem, + ARecordListItem, +} from "./types.js"; + +import { Ingress } from "../../ingress/Ingress/index.js"; +import { DataModel } from "../../base/index.js"; +import { + type DnsRecordSettingsData, + DnsRecordSettings, +} from "../DnsRecordSettings/index.js"; + +export abstract class DnsRecordCombinedABase< + T extends DnsRecordCombinedAData, +> extends DataModel { + public readonly dnsZone: DnsZoneCommon; + public constructor(dnsZone: DnsZoneCommon, data: T) { + super(data); + this.dnsZone = dnsZone; + } + + public async addEntry( + type: "aaaa" | "a", + entry: string, + settings?: DnsRecordSettingsData, + ) { + const record = this.dnsZone.recordSet.combinedA; + const existingARecords = record.type === "custom" ? record.a : []; + const existingAaaaRecords = record.type === "custom" ? record.aaaa : []; + + if (type === "a") { + return await this.dnsZone.setCustomARecord( + [...existingARecords, entry], + existingAaaaRecords, + settings, + ); + } + return await this.dnsZone.setCustomARecord( + existingARecords, + [...existingAaaaRecords, entry], + settings, + ); + } + + public async removeEntry(type: "aaaa" | "a", entry: string) { + const record = this.dnsZone.recordSet.combinedA; + if (record.type !== "custom") { + return; + } + if (type === "aaaa") { + return await this.dnsZone.setCustomARecord( + record.a, + record.aaaa.filter((i) => i !== entry), + record.settings.data, + ); + } + return await this.dnsZone.setCustomARecord( + record.a.filter((i) => i !== entry), + record.aaaa, + record.settings.data, + ); + } + + public async setEmpty() { + return await this.dnsZone.setCustomARecord([], []); + } + + public async setManaged() { + await this.dnsZone.setRecordManaged("a"); + } + + public async updateEntry( + oldType: "aaaa" | "a", + oldEntry: string, + newType: "aaaa" | "a", + newEntry: string, + settings?: DnsRecordSettingsData, + ) { + const record = this.dnsZone.recordSet.combinedA; + if (record.type !== "custom") { + return; + } + + if (oldType === newType) { + const a = + newType === "a" + ? record.a.map((i) => (i === oldEntry ? newEntry : i)) + : record.a; + const aaaa = + newType === "aaaa" + ? record.aaaa.map((i) => (i === oldEntry ? newEntry : i)) + : record.aaaa; + return await this.dnsZone.setCustomARecord(a, aaaa, settings); + } + + if (newType === "aaaa") { + const a = record.a.filter((i) => i !== oldEntry); + const aaaa = [...record.aaaa, newEntry]; + return await this.dnsZone.setCustomARecord(a, aaaa, settings); + } + const a = [...record.a, newEntry]; + const aaaa = record.aaaa.filter((i) => i !== oldEntry); + return await this.dnsZone.setCustomARecord(a, aaaa, settings); + } +} + +export class DnsRecordCombinedAManaged extends DnsRecordCombinedABase { + public readonly managedBy: Ingress; + public readonly type = "managed"; + public constructor( + dnsZone: DnsZoneCommon, + data: DnsRecordCombinedAManagedData, + ) { + super(dnsZone, data); + this.managedBy = Ingress.ofId(data.managedBy.ingressId); + } + + public asList(): ARecordListItem[] { + return [{ type: "managed", recordType: "a" }]; + } + + public getTtl(): number | "auto" { + return "auto"; + } + + public hasIpAddress() { + return false; + } + + public isEmpty(): boolean { + return false; + } +} + +export class DnsRecordCombinedACustom extends DnsRecordCombinedABase { + public readonly a: string[]; + + public readonly aaaa: string[]; + public readonly settings: DnsRecordSettings; + public readonly type = "custom"; + + public constructor( + dnsZone: DnsZoneCommon, + data: DnsRecordCombinedACustomData, + ) { + super(dnsZone, data); + this.a = data.a; + this.aaaa = data.aaaa; + this.settings = new DnsRecordSettings(data.settings); + } + + public asList(): ARecordListItem[] { + const a: ARecordCustomListItem[] = this.a.map((i) => ({ + recordType: "a", + type: "custom", + isIpV6: false, + ip: i, + })); + + const aaaa: ARecordCustomListItem[] = this.aaaa.map((i) => ({ + recordType: "a", + type: "custom", + isIpV6: true, + ip: i, + })); + + return [...a, ...aaaa]; + } + + public getTtl(): number | "auto" { + return this.settings.ttl; + } + public hasIpAddress(ip: string) { + return [...this.a, ...this.aaaa].includes(ip); + } + public isEmpty(): boolean { + return this.a.length === 0 && this.aaaa.length === 0; + } +} + +export class DnsRecordCombinedAUnset extends DnsRecordCombinedABase { + public readonly type = "unset"; + public constructor( + dnsZone: DnsZoneCommon, + data: DnsRecordCombinedAUnsetData, + ) { + super(dnsZone, data); + } + + public asList(): ARecordListItem[] { + return []; + } + + public getTtl(): number | "auto" { + return "auto"; + } + + public hasIpAddress() { + return false; + } + public isEmpty(): boolean { + return true; + } +} + +export type DnsRecordCombinedA = + | DnsRecordCombinedAManaged + | DnsRecordCombinedACustom + | DnsRecordCombinedAUnset; + +export const dnsRecordCombinedAFactory = ( + dnsZone: DnsZoneCommon, + data: DnsRecordCombinedAData, +): DnsRecordCombinedA => { + if ("a" in data) { + return new DnsRecordCombinedACustom(dnsZone, data); + } + if ("managedBy" in data) { + return new DnsRecordCombinedAManaged(dnsZone, data); + } + return new DnsRecordCombinedAUnset(dnsZone, data); +}; diff --git a/packages/models/src/dns/DnsRecordCombinedA/index.ts b/packages/models/src/dns/DnsRecordCombinedA/index.ts new file mode 100644 index 00000000..97e2f786 --- /dev/null +++ b/packages/models/src/dns/DnsRecordCombinedA/index.ts @@ -0,0 +1,2 @@ +export * from "./DnsRecordCombinedA.js"; +export * from "./types.js"; diff --git a/packages/models/src/dns/DnsRecordCombinedA/types.ts b/packages/models/src/dns/DnsRecordCombinedA/types.ts new file mode 100644 index 00000000..b5a15e59 --- /dev/null +++ b/packages/models/src/dns/DnsRecordCombinedA/types.ts @@ -0,0 +1,27 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type DnsRecordCombinedACustomData = + MittwaldAPIV2.Components.Schemas.DnsCombinedACustom; +export type DnsRecordCombinedAManagedData = + MittwaldAPIV2.Components.Schemas.DnsCombinedAManaged; +export type DnsRecordCombinedAUnsetData = + MittwaldAPIV2.Components.Schemas.DnsRecordUnset; + +export type DnsRecordCombinedAData = + | DnsRecordCombinedAManagedData + | DnsRecordCombinedACustomData + | DnsRecordCombinedAUnsetData; + +export interface ARecordManagedListItem { + recordType: "a"; + type: "managed"; +} + +export interface ARecordCustomListItem { + recordType: "a"; + isIpV6: boolean; + type: "custom"; + ip: string; +} + +export type ARecordListItem = ARecordManagedListItem | ARecordCustomListItem; diff --git a/packages/models/src/dns/DnsRecordMx/DnsRecordMx.test.ts b/packages/models/src/dns/DnsRecordMx/DnsRecordMx.test.ts new file mode 100644 index 00000000..43eef693 --- /dev/null +++ b/packages/models/src/dns/DnsRecordMx/DnsRecordMx.test.ts @@ -0,0 +1,97 @@ +import { beforeEach, afterEach, describe, expect, test, vi } from "vitest"; + +import type { DnsZoneCommon } from "../DnsZone/index.js"; + +import { + buildDnsRecordMxManagedData, + buildDnsRecordMxCustomData, + buildDnsRecordMxUnsetData, + buildDnsRecordMxEntry, +} from "../../testing/builders/buildDnsRecordMxData.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { + dnsRecordMxFactory, + DnsRecordMxManaged, + DnsRecordMxCustom, + DnsRecordMxUnset, +} from "./DnsRecordMx.js"; + +beforeEach(() => installBehaviors({})); +afterEach(resetBehaviors); + +describe("dnsRecordMxFactory", () => { + test("constructs a custom record", () => { + const dnsZone = {} as unknown as DnsZoneCommon; + const record = dnsRecordMxFactory(dnsZone, buildDnsRecordMxCustomData()); + + expect(record).toBeInstanceOf(DnsRecordMxCustom); + expect(record.type).toBe("custom"); + expect(record.getTtl()).toBe(900); + expect(record.asList()).toEqual([ + { + fqdn: "mx.example.com", + recordType: "mx", + type: "custom", + priority: 10, + }, + ]); + expect(record.isEmpty()).toBe(false); + }); + + test("constructs a managed record", () => { + const dnsZone = {} as unknown as DnsZoneCommon; + const record = dnsRecordMxFactory(dnsZone, buildDnsRecordMxManagedData()); + + expect(record).toBeInstanceOf(DnsRecordMxManaged); + expect(record.type).toBe("managed"); + expect(record.getTtl()).toBe("auto"); + expect(record.asList()).toHaveLength(4); + expect(record.asList()[0]).toEqual({ + fqdn: "mx1.agenturserver.de", + recordType: "mx", + type: "managed", + priority: 10, + }); + expect(record.isEmpty()).toBe(false); + }); + + test("constructs an unset record", () => { + const dnsZone = {} as unknown as DnsZoneCommon; + const record = dnsRecordMxFactory(dnsZone, buildDnsRecordMxUnsetData()); + + expect(record).toBeInstanceOf(DnsRecordMxUnset); + expect(record.type).toBe("unset"); + expect(record.getTtl()).toBe("auto"); + expect(record.asList()).toEqual([]); + expect(record.isEmpty()).toBe(true); + }); + + test("delegates adding an entry to a custom record", async () => { + const setCustomMxRecord = vi.fn(); + const existingEntry = buildDnsRecordMxEntry(); + const dnsZone = { + recordSet: { + mx: { records: [existingEntry], type: "custom" }, + }, + setCustomMxRecord, + } as unknown as DnsZoneCommon; + const record = dnsRecordMxFactory( + dnsZone, + buildDnsRecordMxCustomData({ records: [existingEntry] }), + ); + const newEntry = buildDnsRecordMxEntry({ + fqdn: "mx2.example.com", + priority: 20, + }); + + await record.addEntry(newEntry); + + expect(setCustomMxRecord).toHaveBeenCalledWith( + [newEntry, existingEntry], + undefined, + ); + }); +}); diff --git a/packages/models/src/dns/DnsRecordMx/DnsRecordMx.ts b/packages/models/src/dns/DnsRecordMx/DnsRecordMx.ts new file mode 100644 index 00000000..349d70f2 --- /dev/null +++ b/packages/models/src/dns/DnsRecordMx/DnsRecordMx.ts @@ -0,0 +1,166 @@ +import type { DnsZoneCommon } from "../DnsZone/index.js"; +import type { + DnsRecordMxManagedData, + DnsRecordMxCustomData, + DnsRecordMxUnsetData, + DnsRecordMxEntry, + MxRecordListItem, + DnsRecordMxData, +} from "./types.js"; + +import { DataModel } from "../../base/index.js"; +import { DnsZone } from "../DnsZone/index.js"; +import { + type DnsRecordSettingsData, + DnsRecordSettings, +} from "../DnsRecordSettings/index.js"; + +export abstract class DnsRecordMxBase< + T extends DnsRecordMxData, +> extends DataModel { + public readonly dnsZone: DnsZoneCommon; + public constructor(dnsZone: DnsZoneCommon, data: T) { + super(data); + this.dnsZone = dnsZone; + } + + public async addEntry( + entry: DnsRecordMxEntry, + settings?: DnsRecordSettingsData, + ) { + const existingItems = + this.dnsZone.recordSet.mx.type === "custom" + ? this.dnsZone.recordSet.mx.records + : []; + return await this.dnsZone.setCustomMxRecord( + [entry, ...existingItems], + settings, + ); + } + + public async removeEntry(entry: DnsRecordMxEntry) { + const { mx } = this.dnsZone.recordSet; + + const existingItems = mx.type === "custom" ? mx.records : []; + + if (mx.type === "custom" && mx.settings && mx.records) { + const updated = existingItems.filter( + (i) => i.priority !== entry.priority && i.fqdn !== entry.fqdn, + ); + await this.dnsZone.setCustomMxRecord(updated, mx.settings.data); + } + } + + public async setEmpty() { + return await this.dnsZone.setCustomMxRecord([]); + } + + public async setManaged() { + await this.dnsZone.setRecordManaged("mx"); + } + + public async updateEntry( + entry: DnsRecordMxEntry, + newEntry: DnsRecordMxEntry, + settings?: DnsRecordSettingsData, + ) { + const existingItems = + this.dnsZone.recordSet.mx.type === "custom" + ? this.dnsZone.recordSet.mx.records + : []; + if ( + existingItems.length < 1 || + this.dnsZone.recordSet.mx.type !== "custom" + ) { + return; + } + const updatedArray = this.dnsZone.recordSet.mx.records.map((i) => + i.priority === entry.priority && i.fqdn === entry.fqdn ? newEntry : i, + ); + return await this.dnsZone.setCustomMxRecord(updatedArray, settings); + } +} + +export class DnsRecordMxManaged extends DnsRecordMxBase { + public readonly type = "managed"; + + public constructor(dnsZone: DnsZoneCommon, data: DnsRecordMxManagedData) { + super(dnsZone, data); + } + + public asList(): MxRecordListItem[] { + return DnsZone.mittwaldMxRecords.map((i) => ({ + ...i, + recordType: "mx", + type: "managed", + })); + } + + public getTtl(): number | "auto" { + return "auto"; + } + + public isEmpty(): boolean { + return false; + } +} + +export class DnsRecordMxCustom extends DnsRecordMxBase { + public readonly records: DnsRecordMxEntry[]; + public readonly settings: DnsRecordSettings; + public readonly type = "custom"; + public constructor(dnsZone: DnsZoneCommon, data: DnsRecordMxCustomData) { + super(dnsZone, data); + this.records = data.records; + this.settings = new DnsRecordSettings(data.settings); + } + + public asList(): MxRecordListItem[] { + return this.records.map((i) => { + return { recordType: "mx", type: "custom", ...i }; + }); + } + + public getTtl(): number | "auto" { + return this.settings.ttl; + } + + public isEmpty(): boolean { + return this.records.length === 0; + } +} + +export class DnsRecordMxUnset extends DnsRecordMxBase { + public readonly type = "unset"; + public constructor(dnsZone: DnsZoneCommon, data: DnsRecordMxUnsetData) { + super(dnsZone, data); + } + + public asList(): MxRecordListItem[] { + return []; + } + + public getTtl(): number | "auto" { + return "auto"; + } + + public isEmpty(): boolean { + return true; + } +} + +export type DnsRecordMx = + DnsRecordMxManaged | DnsRecordMxCustom | DnsRecordMxUnset; + +export const dnsRecordMxFactory = ( + dnsZone: DnsZoneCommon, + data: DnsRecordMxData, +): DnsRecordMx => { + if ("records" in data) { + return new DnsRecordMxCustom(dnsZone, data); + } + if ("managed" in data) { + return new DnsRecordMxManaged(dnsZone, data); + } + return new DnsRecordMxUnset(dnsZone, data); +}; diff --git a/packages/models/src/dns/DnsRecordMx/index.ts b/packages/models/src/dns/DnsRecordMx/index.ts new file mode 100644 index 00000000..8cf8b9cf --- /dev/null +++ b/packages/models/src/dns/DnsRecordMx/index.ts @@ -0,0 +1,2 @@ +export * from "./DnsRecordMx.js"; +export * from "./types.js"; diff --git a/packages/models/src/dns/DnsRecordMx/types.ts b/packages/models/src/dns/DnsRecordMx/types.ts new file mode 100644 index 00000000..8bca79fb --- /dev/null +++ b/packages/models/src/dns/DnsRecordMx/types.ts @@ -0,0 +1,26 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type DnsRecordMxManagedData = + MittwaldAPIV2.Components.Schemas.DnsRecordMXManaged; +export type DnsRecordMxCustomData = + MittwaldAPIV2.Components.Schemas.DnsRecordMXCustom; +export type DnsRecordMxUnsetData = + MittwaldAPIV2.Components.Schemas.DnsRecordUnset; + +export type DnsRecordMxData = + DnsRecordMxManagedData | DnsRecordMxCustomData | DnsRecordMxUnsetData; + +export type DnsRecordMxEntry = + MittwaldAPIV2.Components.Schemas.DnsRecordMXRecord; + +export type MxRecordCustomListItem = { + recordType: "mx"; + type: "custom"; +} & DnsRecordMxEntry; + +export type MxRecordManagedListItem = { + recordType: "mx"; + type: "managed"; +} & DnsRecordMxEntry; + +export type MxRecordListItem = MxRecordManagedListItem | MxRecordCustomListItem; diff --git a/packages/models/src/dns/DnsRecordSet/DnsRecordSet.test.ts b/packages/models/src/dns/DnsRecordSet/DnsRecordSet.test.ts new file mode 100644 index 00000000..c04dd11a --- /dev/null +++ b/packages/models/src/dns/DnsRecordSet/DnsRecordSet.test.ts @@ -0,0 +1,85 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { buildDnsRecordSrvComponentData } from "../../testing/builders/buildDnsRecordSrvComponentData.js"; +import { buildDnsRecordTxtComponentData } from "../../testing/builders/buildDnsRecordTxtComponentData.js"; +import { buildDnsRecordCnameComponentData } from "../../testing/builders/buildDnsRecordCnameData.js"; +import { buildDnsZoneData } from "../../testing/builders/buildDnsZoneData.js"; +import { DnsZoneCommon } from "../DnsZone/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; + +afterEach(resetBehaviors); + +describe("DnsRecordSet", () => { + test("aggregates records and reports counts", () => { + const recordSet = new DnsZoneCommon( + buildDnsZoneData({ + recordSet: { + srv: buildDnsRecordSrvComponentData(), + txt: buildDnsRecordTxtComponentData(), + }, + }), + ).recordSet; + + expect(recordSet.asList()).toEqual([ + { entry: "v=spf1 ~all", recordType: "txt" }, + expect.objectContaining({ fqdn: "srv.example.com", recordType: "srv" }), + ]); + expect(recordSet.getRecordCount("srv")).toBe(1); + expect(recordSet.getRecordCount("txt")).toBe(1); + expect(recordSet.getRecordCount("combinedA")).toBe(0); + // `cname` is constructed unconditionally, so the count must reflect whether + // a CNAME is actually set rather than whether the instance exists. + expect(recordSet.getRecordCount("cname")).toBe(0); + }); + + test("counts a CNAME record only when one is actually set", () => { + const withoutCname = new DnsZoneCommon(buildDnsZoneData()).recordSet; + expect(withoutCname.getRecordCount("cname")).toBe(0); + + const withCname = new DnsZoneCommon( + buildDnsZoneData({ + recordSet: { cname: buildDnsRecordCnameComponentData() }, + }), + ).recordSet; + expect(withCname.getRecordCount("cname")).toBe(1); + }); + + test("clears only non-empty record components", async () => { + const zone = new DnsZoneCommon( + buildDnsZoneData({ + recordSet: { + srv: buildDnsRecordSrvComponentData(), + txt: buildDnsRecordTxtComponentData(), + }, + }), + ); + const setSrvRecord = vi.fn().mockResolvedValue(undefined); + const setTxtRecord = vi.fn().mockResolvedValue(undefined); + const setARecord = vi.fn(); + const setMxRecord = vi.fn(); + const removeCname = vi.fn(); + const setCaaRecord = vi.fn(); + installBehaviors({ + dnsZone: { + setSrvRecord, + setTxtRecord, + setCaaRecord, + setMxRecord, + removeCname, + setARecord, + }, + }); + + await zone.recordSet.clearRecords(); + + expect(setSrvRecord).toHaveBeenCalledOnce(); + expect(setTxtRecord).toHaveBeenCalledOnce(); + expect(setARecord).not.toHaveBeenCalled(); + expect(setMxRecord).not.toHaveBeenCalled(); + expect(removeCname).not.toHaveBeenCalled(); + expect(setCaaRecord).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/models/src/dns/DnsRecordSet/DnsRecordSet.ts b/packages/models/src/dns/DnsRecordSet/DnsRecordSet.ts new file mode 100644 index 00000000..a5980a38 --- /dev/null +++ b/packages/models/src/dns/DnsRecordSet/DnsRecordSet.ts @@ -0,0 +1,76 @@ +import type { DnsRecordCombinedA } from "../DnsRecordCombinedA/index.js"; +import type { DnsRecordSetData, RecordListItem } from "./types.js"; +import type { DnsZoneCommon, DnsZone } from "../DnsZone/index.js"; +import type { DnsRecordMx } from "../DnsRecordMx/index.js"; + +import { dnsRecordCombinedAFactory } from "../DnsRecordCombinedA/index.js"; +import { dnsRecordMxFactory } from "../DnsRecordMx/index.js"; +import { DnsRecordCname } from "../DnsRecordCname/index.js"; +import { DnsRecordCaa } from "../DnsRecordCaa/index.js"; +import { DnsRecordSrv } from "../DnsRecordSrv/index.js"; +import { DnsRecordTxt } from "../DnsRecordTxt/index.js"; +import { DataModel } from "../../base/index.js"; + +export class DnsRecordSet extends DataModel { + public readonly caa: DnsRecordCaa; + + public readonly cname: DnsRecordCname; + public readonly combinedA: DnsRecordCombinedA; + public readonly mx: DnsRecordMx; + public readonly srv: DnsRecordSrv; + public readonly txt: DnsRecordTxt; + public readonly zone: DnsZone; + public constructor(zone: DnsZoneCommon, data: DnsRecordSetData) { + super(data); + this.zone = zone; + this.combinedA = dnsRecordCombinedAFactory(zone, data.combinedARecords); + this.mx = dnsRecordMxFactory(zone, data.mx); + this.srv = new DnsRecordSrv(zone, data.srv); + this.txt = new DnsRecordTxt(zone, data.txt); + this.cname = new DnsRecordCname(zone, data.cname); + this.caa = new DnsRecordCaa(zone, data.caa); + } + + public asList(): RecordListItem[] { + return [ + ...this.combinedA.asList(), + ...this.mx.asList(), + ...this.txt.asList(), + ...this.srv.asList(), + ...this.cname.asList(), + ...this.caa.asList(), + ]; + } + + public async clearRecords(): Promise { + const records = [ + this.combinedA, + this.mx, + this.srv, + this.txt, + this.cname, + this.caa, + ].filter((i) => !i.isEmpty()); + + await Promise.all(records.map((i) => i.setEmpty())); + } + + public getRecordCount( + record: "combinedA" | "cname" | "txt" | "srv" | "caa" | "mx", + ): number { + switch (record) { + case "combinedA": + return this.combinedA.asList().length; + case "cname": + return this.cname.asList().length; + case "txt": + return (this.txt.entries ?? []).length; + case "srv": + return (this.srv.records ?? []).length; + case "caa": + return (this.caa.records ?? []).length; + case "mx": + return this.mx.asList().length; + } + } +} diff --git a/packages/models/src/dns/DnsRecordSet/index.ts b/packages/models/src/dns/DnsRecordSet/index.ts new file mode 100644 index 00000000..1824f36b --- /dev/null +++ b/packages/models/src/dns/DnsRecordSet/index.ts @@ -0,0 +1,2 @@ +export * from "./DnsRecordSet.js"; +export * from "./types.js"; diff --git a/packages/models/src/dns/DnsRecordSet/types.ts b/packages/models/src/dns/DnsRecordSet/types.ts new file mode 100644 index 00000000..d9b4e525 --- /dev/null +++ b/packages/models/src/dns/DnsRecordSet/types.ts @@ -0,0 +1,41 @@ +import type { + CaaRecordListItem, + DnsRecordCaaData, +} from "../DnsRecordCaa/index.js"; +import type { + SrvRecordListItem, + DnsRecordSrvData, +} from "../DnsRecordSrv/index.js"; +import type { + TxtRecordListItem, + DnsRecordTxtData, +} from "../DnsRecordTxt/index.js"; +import type { + MxRecordListItem, + DnsRecordMxData, +} from "../DnsRecordMx/index.js"; +import type { + DnsRecordCombinedAData, + ARecordListItem, +} from "../DnsRecordCombinedA/index.js"; +import type { + CnameRecordListItem, + DnsRecordCnameData, +} from "../DnsRecordCname/index.js"; + +export interface DnsRecordSetData { + combinedARecords: DnsRecordCombinedAData; + cname: DnsRecordCnameData; + srv: DnsRecordSrvData; + txt: DnsRecordTxtData; + caa: DnsRecordCaaData; + mx: DnsRecordMxData; +} + +export type RecordListItem = + | CnameRecordListItem + | TxtRecordListItem + | SrvRecordListItem + | CaaRecordListItem + | MxRecordListItem + | ARecordListItem; diff --git a/packages/models/src/dns/DnsRecordSettings/DnsRecordSettings.test.ts b/packages/models/src/dns/DnsRecordSettings/DnsRecordSettings.test.ts new file mode 100644 index 00000000..baa96f26 --- /dev/null +++ b/packages/models/src/dns/DnsRecordSettings/DnsRecordSettings.test.ts @@ -0,0 +1,17 @@ +import { afterEach, describe, expect, test } from "vitest"; + +import { buildDnsRecordSettingsData } from "../../testing/builders/buildDnsRecordSettingsData.js"; +import { resetBehaviors } from "../../testing/installBehaviors.js"; +import { DnsRecordSettings } from "./DnsRecordSettings.js"; + +afterEach(resetBehaviors); + +describe("DnsRecordSettings", () => { + test.each([ + [buildDnsRecordSettingsData(), 3600], + [buildDnsRecordSettingsData({ ttl: { auto: true } }), "auto"], + [buildDnsRecordSettingsData({ ttl: undefined }), "auto"], + ])("derives the TTL", (data, expected) => { + expect(new DnsRecordSettings(data).ttl).toBe(expected); + }); +}); diff --git a/packages/models/src/dns/DnsRecordSettings/DnsRecordSettings.ts b/packages/models/src/dns/DnsRecordSettings/DnsRecordSettings.ts new file mode 100644 index 00000000..d06dfcb0 --- /dev/null +++ b/packages/models/src/dns/DnsRecordSettings/DnsRecordSettings.ts @@ -0,0 +1,15 @@ +import type { DnsRecordSettingsData } from "./types.js"; + +import { DataModel } from "../../base/index.js"; + +export class DnsRecordSettings extends DataModel { + public readonly ttl: number | "auto"; + public constructor(data: DnsRecordSettingsData) { + super(data); + if (data.ttl !== undefined && "seconds" in data.ttl) { + this.ttl = data.ttl.seconds; + } else { + this.ttl = "auto"; + } + } +} diff --git a/packages/models/src/dns/DnsRecordSettings/index.ts b/packages/models/src/dns/DnsRecordSettings/index.ts new file mode 100644 index 00000000..871d0b64 --- /dev/null +++ b/packages/models/src/dns/DnsRecordSettings/index.ts @@ -0,0 +1,2 @@ +export * from "./DnsRecordSettings.js"; +export * from "./types.js"; diff --git a/packages/models/src/dns/DnsRecordSettings/types.ts b/packages/models/src/dns/DnsRecordSettings/types.ts new file mode 100644 index 00000000..27f56682 --- /dev/null +++ b/packages/models/src/dns/DnsRecordSettings/types.ts @@ -0,0 +1,4 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type DnsRecordSettingsData = + MittwaldAPIV2.Components.Schemas.DnsRecordSettings; diff --git a/packages/models/src/dns/DnsRecordSrv/DnsRecordSrv.test.ts b/packages/models/src/dns/DnsRecordSrv/DnsRecordSrv.test.ts new file mode 100644 index 00000000..26e4a5e4 --- /dev/null +++ b/packages/models/src/dns/DnsRecordSrv/DnsRecordSrv.test.ts @@ -0,0 +1,61 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { buildDnsRecordSrvComponentData } from "../../testing/builders/buildDnsRecordSrvComponentData.js"; +import { buildDnsZoneData } from "../../testing/builders/buildDnsZoneData.js"; +import { DnsZoneCommon } from "../DnsZone/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; + +afterEach(resetBehaviors); + +describe("DnsRecordSrv", () => { + test("materializes component data and derived values", () => { + const zone = new DnsZoneCommon( + buildDnsZoneData({ + recordSet: { srv: buildDnsRecordSrvComponentData() }, + }), + ); + const record = zone.recordSet.srv; + + expect(record.records).toHaveLength(1); + expect(record.getTtl()).toBe(3600); + expect(record.asList()).toEqual([ + expect.objectContaining({ fqdn: "srv.example.com", recordType: "srv" }), + ]); + expect(record.isEmpty()).toBe(false); + }); + + test("materializes unset data as empty", () => { + const record = new DnsZoneCommon(buildDnsZoneData()).recordSet.srv; + + expect(record.records).toBeUndefined(); + expect(record.settings).toBeUndefined(); + expect(record.getTtl()).toBe("auto"); + expect(record.asList()).toEqual([]); + expect(record.isEmpty()).toBe(true); + }); + + test("delegates additions and clearing to the zone behavior", async () => { + const existing = buildDnsRecordSrvComponentData(); + const zone = new DnsZoneCommon( + buildDnsZoneData({ recordSet: { srv: existing } }), + ); + const setSrvRecord = vi.fn().mockResolvedValue(undefined); + installBehaviors({ dnsZone: { setSrvRecord } }); + const entry = { fqdn: "new.example.com", port: 8443 }; + + await zone.recordSet.srv.addEntry(entry); + expect(setSrvRecord).toHaveBeenCalledWith( + zone.id, + [entry, ...existing.records], + { ttl: { auto: true } }, + ); + + await zone.recordSet.srv.setEmpty(); + expect(setSrvRecord).toHaveBeenLastCalledWith(zone.id, [], { + ttl: { auto: true }, + }); + }); +}); diff --git a/packages/models/src/dns/DnsRecordSrv/DnsRecordSrv.ts b/packages/models/src/dns/DnsRecordSrv/DnsRecordSrv.ts new file mode 100644 index 00000000..8ddeae70 --- /dev/null +++ b/packages/models/src/dns/DnsRecordSrv/DnsRecordSrv.ts @@ -0,0 +1,103 @@ +import type { DnsZoneCommon } from "../DnsZone/index.js"; +import type { + DnsRecordSrvEntry, + SrvRecordListItem, + DnsRecordSrvData, +} from "./types.js"; + +import { DataModel } from "../../base/index.js"; +import { + type DnsRecordSettingsData, + DnsRecordSettings, +} from "../DnsRecordSettings/index.js"; + +export class DnsRecordSrv extends DataModel { + public readonly dnsZone: DnsZoneCommon; + public readonly records?: DnsRecordSrvEntry[]; + public readonly settings?: DnsRecordSettings; + + public constructor(dnsZone: DnsZoneCommon, data: DnsRecordSrvData) { + super(data); + this.dnsZone = dnsZone; + if ("records" in data) { + this.records = data.records; + this.settings = new DnsRecordSettings(data.settings); + } + } + + public async addEntry( + newEntry: DnsRecordSrvEntry, + settings?: DnsRecordSettingsData, + ) { + const existingItems = this.dnsZone.recordSet.srv.records ?? []; + return await this.dnsZone.setSrvRecord( + [newEntry, ...existingItems], + settings, + ); + } + + public asList(): SrvRecordListItem[] { + if (!this.records) { + return []; + } + return this.records.map((i) => { + return { + recordType: "srv", + ...i, + }; + }); + } + + public getTtl(): number | "auto" { + if (this.settings) { + return this.settings.ttl; + } + return "auto"; + } + public isEmpty(): boolean { + return (this.records ?? []).length === 0; + } + + public async removeEntry(entry: DnsRecordSrvEntry) { + if ( + this.dnsZone.recordSet.srv.records && + this.dnsZone.recordSet.srv.settings + ) { + const update = (this.dnsZone.recordSet.srv.records ?? []).filter( + (i) => !this.areEntriesEqual(entry, i), + ); + await this.dnsZone.setSrvRecord( + update, + this.dnsZone.recordSet.srv.settings.data, + ); + } + } + + public async setEmpty() { + return await this.dnsZone.setSrvRecord([]); + } + + public async updateEntry( + oldEntry: DnsRecordSrvEntry, + newEntry: DnsRecordSrvEntry, + settings?: DnsRecordSettingsData, + ) { + const existingItems = this.dnsZone.recordSet.srv.records ?? []; + if (existingItems.length < 1) { + return; + } + const update = existingItems.map((i) => + this.areEntriesEqual(i, oldEntry) ? newEntry : i, + ); + return await this.dnsZone.setSrvRecord(update, settings); + } + + private areEntriesEqual(a: DnsRecordSrvEntry, b: DnsRecordSrvEntry): boolean { + return ( + a.port === b.port && + a.fqdn === b.fqdn && + a.weight === b.weight && + a.priority === b.priority + ); + } +} diff --git a/packages/models/src/dns/DnsRecordSrv/index.ts b/packages/models/src/dns/DnsRecordSrv/index.ts new file mode 100644 index 00000000..a99e7420 --- /dev/null +++ b/packages/models/src/dns/DnsRecordSrv/index.ts @@ -0,0 +1,2 @@ +export * from "./DnsRecordSrv.js"; +export * from "./types.js"; diff --git a/packages/models/src/dns/DnsRecordSrv/types.ts b/packages/models/src/dns/DnsRecordSrv/types.ts new file mode 100644 index 00000000..a2045ee0 --- /dev/null +++ b/packages/models/src/dns/DnsRecordSrv/types.ts @@ -0,0 +1,8 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type DnsRecordSrvData = MittwaldAPIV2.Components.Schemas.DnsRecordSRV; + +export type DnsRecordSrvEntry = + MittwaldAPIV2.Components.Schemas.DnsRecordSRVRecord; + +export type SrvRecordListItem = { recordType: "srv" } & DnsRecordSrvEntry; diff --git a/packages/models/src/dns/DnsRecordTxt/DnsRecordTxt.test.ts b/packages/models/src/dns/DnsRecordTxt/DnsRecordTxt.test.ts new file mode 100644 index 00000000..235028ce --- /dev/null +++ b/packages/models/src/dns/DnsRecordTxt/DnsRecordTxt.test.ts @@ -0,0 +1,59 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { buildDnsRecordTxtComponentData } from "../../testing/builders/buildDnsRecordTxtComponentData.js"; +import { buildDnsZoneData } from "../../testing/builders/buildDnsZoneData.js"; +import { DnsZoneCommon } from "../DnsZone/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; + +afterEach(resetBehaviors); + +describe("DnsRecordTxt", () => { + test("materializes component data and derived values", () => { + const zone = new DnsZoneCommon( + buildDnsZoneData({ + recordSet: { txt: buildDnsRecordTxtComponentData() }, + }), + ); + const record = zone.recordSet.txt; + + expect(record.getTtl()).toBe(3600); + expect(record.asList()).toEqual([ + { entry: "v=spf1 ~all", recordType: "txt" }, + ]); + expect(record.isEmpty()).toBe(false); + }); + + test("materializes unset data as empty", () => { + const record = new DnsZoneCommon(buildDnsZoneData()).recordSet.txt; + + expect(record.entries).toBeUndefined(); + expect(record.settings).toBeUndefined(); + expect(record.getTtl()).toBe("auto"); + expect(record.asList()).toEqual([]); + expect(record.isEmpty()).toBe(true); + }); + + test("delegates additions and clearing to the zone behavior", async () => { + const existing = buildDnsRecordTxtComponentData(); + const zone = new DnsZoneCommon( + buildDnsZoneData({ recordSet: { txt: existing } }), + ); + const setTxtRecord = vi.fn().mockResolvedValue(undefined); + installBehaviors({ dnsZone: { setTxtRecord } }); + + await zone.recordSet.txt.addEntry("new-entry"); + expect(setTxtRecord).toHaveBeenCalledWith( + zone.id, + ["new-entry", ...existing.entries], + { ttl: { auto: true } }, + ); + + await zone.recordSet.txt.setEmpty(); + expect(setTxtRecord).toHaveBeenLastCalledWith(zone.id, [], { + ttl: { auto: true }, + }); + }); +}); diff --git a/packages/models/src/dns/DnsRecordTxt/DnsRecordTxt.ts b/packages/models/src/dns/DnsRecordTxt/DnsRecordTxt.ts new file mode 100644 index 00000000..65db9f92 --- /dev/null +++ b/packages/models/src/dns/DnsRecordTxt/DnsRecordTxt.ts @@ -0,0 +1,74 @@ +import type { TxtRecordListItem, DnsRecordTxtData } from "./types.js"; +import type { DnsZoneCommon } from "../DnsZone/index.js"; + +import { DataModel } from "../../base/index.js"; +import { + type DnsRecordSettingsData, + DnsRecordSettings, +} from "../DnsRecordSettings/index.js"; + +export class DnsRecordTxt extends DataModel { + public readonly dnsZone: DnsZoneCommon; + public readonly entries?: string[]; + public readonly settings?: DnsRecordSettings; + public constructor(dnsZone: DnsZoneCommon, data: DnsRecordTxtData) { + super(data); + this.dnsZone = dnsZone; + if ("entries" in data) { + this.entries = data.entries; + this.settings = new DnsRecordSettings(data.settings); + } + } + + public async addEntry(entry: string, settings?: DnsRecordSettingsData) { + const existingEntries = this.dnsZone.recordSet.txt.entries ?? []; + return await this.dnsZone.setTxtRecord( + [entry, ...existingEntries], + settings, + ); + } + + public asList(): TxtRecordListItem[] { + if (!this.entries) { + return []; + } + return this.entries.map((i) => ({ recordType: "txt", entry: i })); + } + + public getTtl(): number | "auto" { + if (this.settings) { + return this.settings.ttl; + } + return "auto"; + } + + public isEmpty(): boolean { + return (this.entries ?? []).length === 0; + } + + public async removeEntry(entry: string) { + const existingItems = this.dnsZone.recordSet.txt.entries ?? []; + if ( + this.dnsZone.recordSet.txt.entries && + this.dnsZone.recordSet.txt.settings + ) { + await this.dnsZone.setTxtRecord( + existingItems.filter((i) => i !== entry), + this.dnsZone.recordSet.txt.settings.data, + ); + } + } + + public async setEmpty() { + return await this.dnsZone.setTxtRecord([]); + } + public async updateEntry( + entry: string, + newEntry: string, + settings?: DnsRecordSettingsData, + ) { + const existingItems = this.dnsZone.recordSet.txt.entries ?? []; + const update = existingItems.map((i) => (i === entry ? newEntry : i)); + return await this.dnsZone.setTxtRecord(update, settings); + } +} diff --git a/packages/models/src/dns/DnsRecordTxt/DnsRecordTxtList.ts b/packages/models/src/dns/DnsRecordTxt/DnsRecordTxtList.ts new file mode 100644 index 00000000..e69de29b diff --git a/packages/models/src/dns/DnsRecordTxt/index.ts b/packages/models/src/dns/DnsRecordTxt/index.ts new file mode 100644 index 00000000..5f741aa8 --- /dev/null +++ b/packages/models/src/dns/DnsRecordTxt/index.ts @@ -0,0 +1,2 @@ +export * from "./DnsRecordTxt.js"; +export * from "./types.js"; diff --git a/packages/models/src/dns/DnsRecordTxt/types.ts b/packages/models/src/dns/DnsRecordTxt/types.ts new file mode 100644 index 00000000..4ce6306c --- /dev/null +++ b/packages/models/src/dns/DnsRecordTxt/types.ts @@ -0,0 +1,8 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type DnsRecordTxtData = MittwaldAPIV2.Components.Schemas.DnsRecordTXT; + +export interface TxtRecordListItem { + recordType: "txt"; + entry: string; +} diff --git a/packages/models/src/dns/DnsZone/DnsZone.test.ts b/packages/models/src/dns/DnsZone/DnsZone.test.ts new file mode 100644 index 00000000..1e2ad8f0 --- /dev/null +++ b/packages/models/src/dns/DnsZone/DnsZone.test.ts @@ -0,0 +1,313 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { buildDomainMigrationDnsRecordData } from "../../testing/builders/buildDomainMigrationDnsRecordData.js"; +import { buildDomainMigrationDomainData } from "../../testing/builders/buildDomainMigrationDomainData.js"; +import { buildDnsRecordCombinedACustomData } from "../../testing/builders/buildDnsRecordCombinedAData.js"; +import { buildDomainMigrationData } from "../../testing/builders/buildDomainMigrationData.js"; +import { buildDnsZoneData } from "../../testing/builders/buildDnsZoneData.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { DomainMigration } from "../../domain/index.js"; +import { ReferenceModel } from "../../base/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { Project } from "../../project/index.js"; +import { + DnsZoneDetailed, + DnsZoneListItem, + DnsZoneCommon, + DnsZoneList, + DnsZone, +} from "./DnsZone.js"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? type.name : undefined, +})); + +afterEach(resetBehaviors); + +describe("DnsZone aggregate + common variant", () => { + test("aggregateMetaData carries the dns/zone identity", () => { + expect(DnsZone.aggregateMetaData).toBeInstanceOf(AggregateMetaData); + expect(DnsZone.aggregateMetaData.domain).toBe("dns"); + expect(DnsZone.aggregateMetaData.aggregate).toBe("zone"); + }); + + test("findCommon delegates to a detailed variant for a reference", async () => { + const find = vi.fn().mockResolvedValue(buildDnsZoneData({ id: "z-1" })); + installBehaviors({ dnsZone: { find } }); + + const common = await DnsZone.ofId("z-1").findCommon(); + + expect(common).toBeInstanceOf(DnsZoneCommon); + expect(find).toHaveBeenCalledWith("z-1"); + }); + + test("getCommon throws for a missing reference", async () => { + installBehaviors({ + dnsZone: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(DnsZone.ofId("z-1").getCommon()).rejects.toThrow(); + }); + + test("getCommon/findCommon are idempotent on materialized models", async () => { + const find = vi.fn(); + installBehaviors({ dnsZone: { find } }); + const detailed = new DnsZoneDetailed(buildDnsZoneData()); + const item = new DnsZoneListItem(buildDnsZoneData()); + + expect(await detailed.getCommon()).toBe(detailed); + expect(await detailed.findCommon()).toBe(detailed); + expect(await item.getCommon()).toBe(item); + expect(await item.findCommon()).toBe(item); + expect(find).not.toHaveBeenCalled(); + }); + + test("reports no CNAME when optional CNAME data is absent", () => { + const zone = new DnsZoneCommon(buildDnsZoneData()); + + expect(zone.hasCname()).toBe(false); + }); +}); + +describe("DnsZone migration A-record", () => { + test("finds a succeeded migration A-record in the zone", async () => { + const queryByProjectId = vi.fn().mockResolvedValue({ + items: [ + buildDomainMigrationData({ + domains: [ + buildDomainMigrationDomainData({ + coabData: { + dnsRecords: [ + buildDomainMigrationDnsRecordData({ + value: "1.2.3.4", + type: "A", + }), + ], + }, + domain: "example.com", + state: "succeeded", + }), + ], + }), + ], + totalCount: 1, + }); + installBehaviors({ domainMigration: { queryByProjectId } }); + const migrations = + await DomainMigration.queryByProjectId("project-1").execute(); + const zone = new DnsZoneCommon( + buildDnsZoneData({ + recordSet: { + combinedARecords: buildDnsRecordCombinedACustomData({ + a: ["1.2.3.4"], + }), + }, + }), + ); + + expect(zone.findMigrationARecordIp(migrations)).toBe("1.2.3.4"); + expect(zone.hasARecordOfMigration(migrations)).toBe(true); + }); + + test("ignores a pending migration A-record in the zone", async () => { + const queryByProjectId = vi.fn().mockResolvedValue({ + items: [ + buildDomainMigrationData({ + domains: [ + buildDomainMigrationDomainData({ + coabData: { + dnsRecords: [ + buildDomainMigrationDnsRecordData({ + value: "1.2.3.4", + type: "A", + }), + ], + }, + domain: "example.com", + state: "pending", + }), + ], + }), + ], + totalCount: 1, + }); + installBehaviors({ domainMigration: { queryByProjectId } }); + const migrations = + await DomainMigration.queryByProjectId("project-1").execute(); + const zone = new DnsZoneCommon( + buildDnsZoneData({ + recordSet: { + combinedARecords: buildDnsRecordCombinedACustomData({ + a: ["1.2.3.4"], + }), + }, + }), + ); + + expect(zone.findMigrationARecordIp(migrations)).toBeUndefined(); + expect(zone.hasARecordOfMigration(migrations)).toBe(false); + }); + + test("ignores a migration A-record absent from the zone", async () => { + const queryByProjectId = vi.fn().mockResolvedValue({ + items: [ + buildDomainMigrationData({ + domains: [ + buildDomainMigrationDomainData({ + coabData: { + dnsRecords: [ + buildDomainMigrationDnsRecordData({ + value: "1.2.3.4", + type: "A", + }), + ], + }, + domain: "example.com", + state: "succeeded", + }), + ], + }), + ], + totalCount: 1, + }); + installBehaviors({ domainMigration: { queryByProjectId } }); + const migrations = + await DomainMigration.queryByProjectId("project-1").execute(); + const zone = new DnsZoneCommon( + buildDnsZoneData({ + recordSet: { + combinedARecords: buildDnsRecordCombinedACustomData({ + a: ["5.6.7.8"], + }), + }, + }), + ); + + expect(zone.findMigrationARecordIp(migrations)).toBeUndefined(); + expect(zone.hasARecordOfMigration(migrations)).toBe(false); + }); + + test("ignores an absent migration domain", async () => { + const queryByProjectId = vi.fn().mockResolvedValue({ + items: [ + buildDomainMigrationData({ + domains: [ + buildDomainMigrationDomainData({ + coabData: { + dnsRecords: [ + buildDomainMigrationDnsRecordData({ + value: "1.2.3.4", + type: "A", + }), + ], + }, + domain: "other.com", + state: "succeeded", + }), + ], + }), + ], + totalCount: 1, + }); + installBehaviors({ domainMigration: { queryByProjectId } }); + const migrations = + await DomainMigration.queryByProjectId("project-1").execute(); + const zone = new DnsZoneCommon( + buildDnsZoneData({ + recordSet: { + combinedARecords: buildDnsRecordCombinedACustomData({ + a: ["1.2.3.4"], + }), + }, + }), + ); + + expect(zone.findMigrationARecordIp(migrations)).toBeUndefined(); + expect(zone.hasARecordOfMigration(migrations)).toBe(false); + }); +}); + +describe("DnsZone reference and delegation", () => { + test("creates a reference", () => { + const zone = DnsZone.ofId("z-1"); + expect(zone).toBeInstanceOf(DnsZone); + expect(zone).toBeInstanceOf(ReferenceModel); + expect(zone.id).toBe("z-1"); + }); + + test("find materializes detailed data and preserves undefined", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildDnsZoneData({ id: "z-1" })) + .mockResolvedValueOnce(undefined); + installBehaviors({ dnsZone: { find } }); + + const found = await DnsZone.find("z-1"); + expect(found).toBeInstanceOf(DnsZoneDetailed); + expect(found).toBeInstanceOf(DnsZoneCommon); + expect(found?.domain).toBe("example.com"); + expect(await DnsZone.find("missing")).toBeUndefined(); + }); + + test("get throws when the zone is missing", async () => { + installBehaviors({ + dnsZone: { find: vi.fn().mockResolvedValue(undefined) }, + }); + await expect(DnsZone.get("missing")).rejects.toThrow(); + }); + + test("creates a zone reference through the behavior", async () => { + const create = vi.fn().mockResolvedValue({ id: "new-zone" }); + installBehaviors({ dnsZone: { create } }); + + const result = await DnsZone.create("p-1", "_autoconfig.example.com"); + expect(result).toBeInstanceOf(DnsZone); + expect(result.id).toBe("new-zone"); + expect(create).toHaveBeenCalledWith("p-1", "_autoconfig.example.com"); + }); + + test("returns a downloadable zone file", async () => { + const getZoneFile = vi.fn().mockResolvedValue("file-content"); + installBehaviors({ dnsZone: { getZoneFile } }); + const zone = new DnsZoneCommon(buildDnsZoneData()); + + await expect(zone.getZoneFileDownload()).resolves.toEqual({ + filename: "example.com.txt", + content: "file-content", + }); + expect(getZoneFile).toHaveBeenCalledWith(zone.id); + }); +}); + +describe("DnsZone query", () => { + test("materializes and filters query results", async () => { + const query = vi.fn().mockResolvedValue({ + items: [ + buildDnsZoneData({ domain: "a.example.com" }), + buildDnsZoneData({ domain: "b.other.com" }), + ], + totalCount: 2, + }); + installBehaviors({ dnsZone: { query } }); + const project = Project.ofId("p-1"); + + const result = await DnsZone.query({ project: project }).execute(); + expect(result).toBeInstanceOf(DnsZoneList); + expect(result.items).toHaveLength(2); + expect(result.items[0]).toBeInstanceOf(DnsZoneListItem); + expect(result.totalCount).toBe(2); + + const filtered = await DnsZone.query({ + domain: "other.com", + project: project, + }).execute(); + expect(filtered.items.map((item) => item.domain)).toEqual(["b.other.com"]); + }); +}); diff --git a/packages/models/src/dns/DnsZone/DnsZone.ts b/packages/models/src/dns/DnsZone/DnsZone.ts new file mode 100644 index 00000000..aa03b790 --- /dev/null +++ b/packages/models/src/dns/DnsZone/DnsZone.ts @@ -0,0 +1,302 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; + +import type { DomainMigrationList } from "../../domain/DomainMigration/index.js"; +import type { DnsRecordSettingsData } from "../DnsRecordSettings/index.js"; +import type { DnsRecordCaaEntry } from "../DnsRecordCaa/index.js"; +import type { DnsRecordMxEntry } from "../DnsRecordMx/index.js"; +import type { + DnsUpdateMultipleRecordsRequest, + DnsZoneListQueryModelData, + DnsZoneListItemData, + DnsSrvRecord, + DnsZoneData, +} from "./types.js"; + +import { + type DownloadableFile, + AggregateMetaData, +} from "../../common/index.js"; +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { DnsRecordSet } from "../DnsRecordSet/index.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "DnsZone", +}) +export class DnsZone extends ReferenceModel { + public static aggregateMetaData = new AggregateMetaData("dns", "zone"); + + public static autoDnsSettings: DnsRecordSettingsData = { + ttl: { auto: true }, + }; + public static dkim = + "v=DKIM1; k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC3U8kqa4SiUlO5WBe8DwVPhhLNooNNe8VLEJ+9PbDHVeEw0O6mY2O6AvcqbnSeBO5Ac9Ix0RQzxe9krqSgWDR84IvROW/u4kMxELn+Q+Jy2QXYASbVWnYs4T6p1yIqBEgRfWDFnNtmRDvNFCAcRv2VkA0ykkRMq3u9E6FZTLMnGQIDAQAB"; + public static dkim2048 = + "v=DKIM1; k=rsa; p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1BM9Prf00dhyP0i/fH0/k01oMSafqpl7biZMPjz/zxRJn+1YgSdeXt84NR3wZ5w+HWhtR27p1IEjchu179VOOyZ+xOte4owM+6FO7BVGnr/5IAlmRnC4fMvSeePdwun9fBExfkOroxwdEM4Y1+BqaSnpMT2xV6a2hRklymFzDkNQdmKrtm2AWSqg44iiMt3buEtZ0/y5SSBNd41zJYsp7UdPO2fgzF+C5gJrpyKhTWGB9ELLK83cd2Vdb8N+CC1Oh62eybgsMt2iBmxgnYAwp1LdTuxxNFYT2gEOFGL5KE01WM0L0+KALhwDQBcGcSC7Eup855OI/v8F4YDTZ3NCgQIDAQAB"; + + public static mittwaldMxRecords: DnsRecordMxEntry[] = [ + { fqdn: "mx1.agenturserver.de", priority: 10 }, + { fqdn: "mx2.agenturserver.de", priority: 20 }, + { fqdn: "mx3.agenturserver.de", priority: 30 }, + { fqdn: "mx4.agenturserver.de", priority: 40 }, + ]; + + public static spf = "v=spf1 include:agenturserver.de ~all"; + + public static async create(projectId: string, name: string) { + const result = await config.behaviors.dnsZone.create(projectId, name); + + return DnsZone.ofId(result.id); + } + + public static async find(id: string) { + const data = await config.behaviors.dnsZone.find(id); + if (data) { + return new DnsZoneDetailed(data); + } + } + + public static async get(id: string) { + const zone = await this.find(id); + assertObjectFound(zone, DnsZone, id); + return zone; + } + + public static getDkim2048Hostname = (hostname: string) => + `agenturserver2048._domainkey.${hostname}`; + + public static getDkimHostname = (hostname: string) => + `agenturserver._domainkey.${hostname}`; + + public static ofId(id: string) { + return new DnsZone(id); + } + + public static query(query: DnsZoneListQueryModelData) { + return new DnsZoneListQuery(query); + } + + public async delete() { + await config.behaviors.dnsZone.delete(this.id); + } + + public async findCommon(): Promise { + return this instanceof DnsZoneCommon ? this : this.findDetailed(); + } + + public findDetailed(): Promise { + return DnsZone.find(this.id); + } + + public async getCommon(): Promise { + return this instanceof DnsZoneCommon ? this : this.getDetailed(); + } + public getDetailed(): Promise { + return DnsZone.get(this.id); + } + + public async removeCname() { + await config.behaviors.dnsZone.removeCname(this.id); + } + + public async setCaaRecord( + records: DnsRecordCaaEntry[], + settings?: DnsRecordSettingsData, + ) { + return await config.behaviors.dnsZone.setCaaRecord( + this.id, + records, + settings ?? DnsZone.autoDnsSettings, + ); + } + + public async setCname(fqdn?: string, settings?: DnsRecordSettingsData) { + await config.behaviors.dnsZone.setCname( + this.id, + fqdn, + settings ?? DnsZone.autoDnsSettings, + ); + } + + public async setCustomARecord( + a: string[], + aaaa: string[], + settings?: DnsRecordSettingsData, + ) { + return await config.behaviors.dnsZone.setARecord( + this.id, + a, + aaaa, + settings ?? DnsZone.autoDnsSettings, + ); + } + + public async setCustomMxRecord( + records: DnsRecordMxEntry[], + settings?: DnsRecordSettingsData, + ) { + return await config.behaviors.dnsZone.setMxRecord( + this.id, + records, + settings ?? DnsZone.autoDnsSettings, + ); + } + + public async setRecordManaged(record: "mx" | "a") { + await config.behaviors.dnsZone.setRecordManaged(this.id, record); + } + + public async setSrvRecord( + entries: DnsSrvRecord[], + settings?: DnsRecordSettingsData, + ) { + return await config.behaviors.dnsZone.setSrvRecord( + this.id, + entries, + settings ?? DnsZone.autoDnsSettings, + ); + } + + public async setTxtRecord( + entries: string[], + settings?: DnsRecordSettingsData, + ) { + return await config.behaviors.dnsZone.setTxtRecord( + this.id, + entries, + settings ?? DnsZone.autoDnsSettings, + ); + } + + public async updateDnsRecords( + update: DnsUpdateMultipleRecordsRequest, + settings?: DnsRecordSettingsData, + ) { + const { cname, aaaa, txt, srv, caa, mx, a } = update; + const dnsSettings = settings ?? DnsZone.autoDnsSettings; + + if (a.length > 0 || aaaa.length > 0) { + await this.setCustomARecord(a, aaaa, dnsSettings); + } + + if (mx.data.length > 0 && !mx.managed) { + await this.setCustomMxRecord(mx.data, dnsSettings); + } + if (mx.managed) await this.setRecordManaged("mx"); + + if (txt.length > 0) await this.setTxtRecord(txt, dnsSettings); + if (srv.length > 0) await this.setSrvRecord(srv, dnsSettings); + if (cname) await this.setCname(cname, dnsSettings); + if (caa.length > 0) await this.setCaaRecord(caa, dnsSettings); + } +} + +export class DnsZoneCommon extends WithData()(DnsZone) { + public override readonly data: DnsZoneData; + public readonly domain: string; + public readonly recordSet: DnsRecordSet; + public constructor(data: DnsZoneData) { + super(data.id); + this.data = data; + this.domain = data.domain; + this.recordSet = new DnsRecordSet(this, data.recordSet); + } + public findMigrationARecordIp( + migrations: DomainMigrationList, + ): string | undefined { + const ip = migrations + .findSucceededMigrationDomain(this.domain) + ?.findFirstARecord()?.value; + + return ip !== undefined && this.recordSet.combinedA.hasIpAddress(ip) + ? ip + : undefined; + } + + public async getZoneFileDownload(): Promise { + const response = await config.behaviors.dnsZone.getZoneFile(this.id); + return { filename: `${this.domain}.txt`, content: response }; + } + + public hasARecordOfMigration(migrations: DomainMigrationList): boolean { + return this.findMigrationARecordIp(migrations) !== undefined; + } + + public hasCname() { + return this.recordSet.cname.fqdn !== undefined; + } +} + +export class DnsZoneDetailed extends DnsZoneCommon { + public constructor(data: DnsZoneData) { + super(data); + } +} + +export class DnsZoneListQuery extends ListQueryModel { + public constructor(query: DnsZoneListQueryModelData) { + super(query, { dependencies: [extractId(query.project)] }); + } + + public async execute() { + const { domain } = this.query; + const { totalCount, items } = await config.behaviors.dnsZone.query( + extractId(this.query.project), + ); + // List Zones does not support a domain query parameter, so filtering is needed + const zones = domain + ? items.filter((i) => i.domain.endsWith(domain)) + : items; + return new DnsZoneList( + this.query, + zones.map((z) => new DnsZoneListItem(z)), + totalCount, + ); + } + + public refine(query: Partial = {}) { + return new DnsZoneListQuery({ + ...this.query, + ...query, + }); + } +} + +export class DnsZoneListItem extends DnsZoneCommon { + public override readonly data: DnsZoneListItemData; + public constructor(data: DnsZoneListItemData) { + super(data); + this.data = data; + } +} + +export class DnsZoneList extends WithListData()( + DnsZoneListQuery, +) { + public override readonly items: readonly DnsZoneListItem[]; + public override readonly totalCount: number; + public constructor( + query: DnsZoneListQueryModelData, + zones: DnsZoneListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(zones); + this.totalCount = totalCount; + } + + public findByHostname(hostname: string) { + return this.items.find((i) => i.domain === hostname); + } + + public hasARecordOfMigration(migrations: DomainMigrationList): boolean { + return this.items.some((i) => i.hasARecordOfMigration(migrations)); + } +} diff --git a/packages/models/src/dns/DnsZone/behaviors/api.ts b/packages/models/src/dns/DnsZone/behaviors/api.ts new file mode 100644 index 00000000..7ba6706b --- /dev/null +++ b/packages/models/src/dns/DnsZone/behaviors/api.ts @@ -0,0 +1,183 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { DnsZoneBehaviors } from "./types.js"; +import type { + DnsRecordCAARecord, + DnsRecordSRVRecord, + DnsRecordMXRecord, +} from "../../../domain/Domain/index.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount } from "../../../base/index.js"; + +export const apiDnsZoneBehaviors = ( + client: MittwaldAPIV2Client, +): DnsZoneBehaviors => ({ + setCaaRecord: async (dnsZoneId, records, settings) => { + if (records.length === 0) { + const response = await client.domain.dnsUpdateRecordSet({ + recordSet: "caa", + data: undefined, + dnsZoneId, + }); + + validateResponse(response, 204); + return; + } + const response = await client.domain.dnsUpdateRecordSet({ + data: { + records: records as [DnsRecordCAARecord, ...DnsRecordCAARecord[]], + settings, + }, + recordSet: "caa", + dnsZoneId, + }); + + validateResponse(response, 204, { + validationError: { pathMappings: { "*": "root" } }, + }); + }, + setSrvRecord: async (dnsZoneId, records, settings) => { + if (records.length === 0) { + const response = await client.domain.dnsUpdateRecordSet({ + recordSet: "srv", + data: undefined, + dnsZoneId, + }); + validateResponse(response, 204); + return; + } + const response = await client.domain.dnsUpdateRecordSet({ + data: { + records: records as [DnsRecordSRVRecord, ...DnsRecordSRVRecord[]], + settings, + }, + recordSet: "srv", + dnsZoneId, + }); + + validateResponse(response, 204, { + validationError: { pathMappings: { "*": "root" } }, + }); + }, + setTxtRecord: async (dnsZoneId, entries, settings) => { + if (entries.length === 0) { + const response = await client.domain.dnsUpdateRecordSet({ + recordSet: "txt", + dnsZoneId, + }); + validateResponse(response, 204); + return; + } + + const response = await client.domain.dnsUpdateRecordSet({ + data: { settings, entries }, + recordSet: "txt", + dnsZoneId, + }); + validateResponse(response, 204, { + validationError: { pathMappings: { "*": "root" } }, + }); + }, + setCname: async (dnsZoneId, fqdn, settings) => { + if (fqdn && settings) { + const response = await client.domain.dnsUpdateRecordSet({ + data: { settings, fqdn }, + recordSet: "cname", + dnsZoneId, + }); + validateResponse(response, 204); + return; + } + const response = await client.domain.dnsUpdateRecordSet({ + recordSet: "cname", + data: undefined, + dnsZoneId, + }); + validateResponse(response, 204); + }, + setMxRecord: async (dnsZoneId, records, settings) => { + const response = await client.domain.dnsUpdateRecordSet({ + data: + records.length > 0 + ? { + records: records as [DnsRecordMXRecord, ...DnsRecordMXRecord[]], + settings, + } + : undefined, + recordSet: "mx", + dnsZoneId, + }); + + validateResponse(response, 204, { + validationError: { pathMappings: { "*": "root" } }, + }); + }, + setARecord: async (dnsZoneId, a, aaaa, settings) => { + const response = await client.domain.dnsUpdateRecordSet({ + data: a.length > 0 || aaaa.length > 0 ? { settings, aaaa, a } : undefined, + recordSet: "a", + dnsZoneId, + }); + + validateResponse(response, 204, { + validationError: { pathMappings: { "*": "root" } }, + }); + }, + + query: async (projectId) => { + const response = await client.domain.dnsListDnsZones({ + projectId, + }); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + create: async (projectId, name) => { + const response = await client.domain.dnsCreateProjectDnsZone({ + data: { name }, + projectId, + }); + + validateResponse(response, 201); + return { + id: response.data.id, + }; + }, + find: async (dnsZoneId) => { + const response = await client.domain.dnsGetDnsZone({ dnsZoneId }); + + if (response.status === 200) { + return response.data; + } + validateResponse(response, [400]); + }, + + removeCname: async (dnsZoneId) => { + const response = await client.domain.dnsUpdateRecordSet({ + recordSet: "cname", + data: undefined, + dnsZoneId, + }); + validateResponse(response, 204); + }, + setRecordManaged: async (dnsZoneId, recordSet) => { + const response = await client.domain.dnsSetRecordSetManaged({ + recordSet, + dnsZoneId, + }); + validateResponse(response, 200); + }, + getZoneFile: async (dnsZoneId) => { + const response = await client.domain.dnsGetZoneFile({ dnsZoneId }); + validateResponse(response, 200); + return response.data; + }, + delete: async (dnsZoneId) => { + const response = await client.domain.dnsDeleteDnsZone({ dnsZoneId }); + validateResponse(response, 204); + }, +}); diff --git a/packages/models/src/dns/DnsZone/behaviors/index.ts b/packages/models/src/dns/DnsZone/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/dns/DnsZone/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/dns/DnsZone/behaviors/types.ts b/packages/models/src/dns/DnsZone/behaviors/types.ts new file mode 100644 index 00000000..f0aaab53 --- /dev/null +++ b/packages/models/src/dns/DnsZone/behaviors/types.ts @@ -0,0 +1,51 @@ +import type { + DnsZoneListItemData, + DnsSrvRecord, + DnsZoneData, +} from "../types.js"; +import type { DnsRecordSettingsData } from "../../DnsRecordSettings/index.js"; +import type { DnsRecordCaaEntry } from "../../DnsRecordCaa/index.js"; +import type { DnsRecordMxEntry } from "../../DnsRecordMx/index.js"; +import type { QueryResponseData } from "../../../base/index.js"; + +export interface DnsZoneBehaviors { + setARecord: ( + dnsZoneId: string, + a: string[], + aaaa: string[], + settings: DnsRecordSettingsData, + ) => Promise; + setMxRecord: ( + dnsZoneId: string, + records: DnsRecordMxEntry[], + settings: DnsRecordSettingsData, + ) => Promise; + + setCaaRecord: ( + dnsZoneId: string, + items: DnsRecordCaaEntry[], + settings: DnsRecordSettingsData, + ) => Promise; + setSrvRecord: ( + dnsZoneId: string, + entries: DnsSrvRecord[], + settings: DnsRecordSettingsData, + ) => Promise; + setTxtRecord: ( + dnsZoneId: string, + entries: string[], + settings: DnsRecordSettingsData, + ) => Promise; + setCname: ( + dnsZoneId: string, + fqdn?: string, + settings?: DnsRecordSettingsData, + ) => Promise; + query: (projectId: string) => Promise>; + setRecordManaged: (dnsZoneId: string, recordSet: "mx" | "a") => Promise; + create: (projectId: string, name: string) => Promise<{ id: string }>; + find: (dnsZoneId: string) => Promise; + getZoneFile: (zoneId: string) => Promise; + removeCname: (zoneId: string) => Promise; + delete: (zoneId: string) => Promise; +} diff --git a/packages/models/src/dns/DnsZone/index.ts b/packages/models/src/dns/DnsZone/index.ts new file mode 100644 index 00000000..a3e3e48c --- /dev/null +++ b/packages/models/src/dns/DnsZone/index.ts @@ -0,0 +1,2 @@ +export * from "./DnsZone.js"; +export * from "./types.js"; diff --git a/packages/models/src/dns/DnsZone/types.ts b/packages/models/src/dns/DnsZone/types.ts new file mode 100644 index 00000000..555887c2 --- /dev/null +++ b/packages/models/src/dns/DnsZone/types.ts @@ -0,0 +1,37 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import type { DnsRecordCaaEntry } from "../DnsRecordCaa/index.js"; +import type { DnsRecordSrvEntry } from "../DnsRecordSrv/index.js"; +import type { DnsRecordMxEntry } from "../DnsRecordMx/index.js"; +import type { Project } from "../../project/index.js"; + +export type DnsZoneListQueryData = + MittwaldAPIV2.Paths.V2ProjectsProjectIdDnsZones.Get.Parameters.Query & { + domain?: string; + }; + +export type DnsZoneListQueryModelData = { + project: Project | string; +} & DnsZoneListQueryData; + +export type DnsZoneData = MittwaldAPIV2.Operations.DnsGetDnsZone.ResponseData; + +export type DnsZoneListItemData = + MittwaldAPIV2.Operations.DnsListDnsZones.ResponseData[number]; + +export type DnsSrvRecord = MittwaldAPIV2.Components.Schemas.DnsRecordSRVRecord; + +export interface DnsUpdateMxRecordsRequest { + data: DnsRecordMxEntry[]; + managed: boolean; +} + +export interface DnsUpdateMultipleRecordsRequest { + mx: DnsUpdateMxRecordsRequest; + cname: string | undefined; + srv: DnsRecordSrvEntry[]; + caa: DnsRecordCaaEntry[]; + aaaa: string[]; + txt: string[]; + a: string[]; +} diff --git a/packages/models/src/dns/index.ts b/packages/models/src/dns/index.ts new file mode 100644 index 00000000..9b4cdda0 --- /dev/null +++ b/packages/models/src/dns/index.ts @@ -0,0 +1,9 @@ +export * from "./DnsRecordCaa/index.js"; +export * from "./DnsRecordCname/index.js"; +export * from "./DnsRecordCombinedA/index.js"; +export * from "./DnsRecordMx/index.js"; +export * from "./DnsRecordSet/index.js"; +export * from "./DnsRecordSettings/index.js"; +export * from "./DnsRecordSrv/index.js"; +export * from "./DnsRecordTxt/index.js"; +export * from "./DnsZone/index.js"; diff --git a/packages/models/src/domain/ContactVerification/ContactVerification.test.ts b/packages/models/src/domain/ContactVerification/ContactVerification.test.ts new file mode 100644 index 00000000..35fa7545 --- /dev/null +++ b/packages/models/src/domain/ContactVerification/ContactVerification.test.ts @@ -0,0 +1,170 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { buildContactVerificationData } from "../../testing/builders/buildContactVerificationData.js"; +import { ReferenceModel } from "../../base/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { + ContactVerificationDetailed, + ContactVerificationListItem, + ContactVerificationCommon, + ContactVerificationList, + ContactVerification, +} from "./ContactVerification.js"; + +afterEach(resetBehaviors); + +describe("ContactVerification", () => { + test("findCommon delegates to a detailed variant for a reference", async () => { + const find = vi + .fn() + .mockResolvedValue(buildContactVerificationData({ id: "cv-1" })); + installBehaviors({ contactVerification: { find } }); + + const common = await ContactVerification.ofId("cv-1").findCommon(); + + expect(common).toBeInstanceOf(ContactVerificationCommon); + expect(find).toHaveBeenCalledWith("cv-1"); + }); + + test("getCommon throws for a missing reference", async () => { + installBehaviors({ + contactVerification: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + ContactVerification.ofId("cv-1").getCommon(), + ).rejects.toThrow(); + }); + + test("getCommon/findCommon are idempotent on materialized models", async () => { + const find = vi.fn(); + installBehaviors({ contactVerification: { find } }); + const detailed = new ContactVerificationDetailed( + buildContactVerificationData(), + ); + const item = new ContactVerificationListItem( + buildContactVerificationData(), + ); + + expect(await detailed.getCommon()).toBe(detailed); + expect(await detailed.findCommon()).toBe(detailed); + expect(await item.getCommon()).toBe(item); + expect(await item.findCommon()).toBe(item); + expect(find).not.toHaveBeenCalled(); + }); + + test("find delegates and returns a detailed verification", async () => { + const find = vi + .fn() + .mockResolvedValue(buildContactVerificationData({ id: "cv-1" })); + installBehaviors({ contactVerification: { find } }); + + const result = await ContactVerification.find("cv-1"); + + expect(find).toHaveBeenCalledWith("cv-1"); + expect(result).toBeInstanceOf(ContactVerificationDetailed); + expect(result?.id).toBe("cv-1"); + }); + + test("find returns undefined when the verification is missing", async () => { + installBehaviors({ + contactVerification: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + expect(await ContactVerification.find("missing")).toBeUndefined(); + }); + + test("ofId creates a verification reference", () => { + const verification = ContactVerification.ofId("cv-ref"); + + expect(verification).toBeInstanceOf(ContactVerification); + expect(verification.id).toBe("cv-ref"); + }); + + test("query delegates and materializes a verification list", async () => { + const query = vi.fn().mockResolvedValue({ + items: [buildContactVerificationData({ id: "cv-list" })], + totalCount: 2, + }); + installBehaviors({ contactVerification: { query } }); + + const result = await ContactVerification.query().execute(); + + expect(query).toHaveBeenCalledWith({}); + expect(result).toBeInstanceOf(ContactVerificationList); + expect(result.items[0]).toBeInstanceOf(ContactVerificationListItem); + expect(result.items[0]?.id).toBe("cv-list"); + expect(result.totalCount).toBe(2); + }); + + test("checks one or several statuses", () => { + const verification = new ContactVerificationDetailed( + buildContactVerificationData({ status: "pending" }), + ); + + expect(verification.hasStatus("pending")).toBe(true); + expect(verification.hasStatus("completed")).toBe(false); + expect(verification.hasStatus(["created", "pending"])).toBe(true); + }); + + test("creates typed verification data", () => { + const verification = new ContactVerificationDetailed( + buildContactVerificationData(), + ); + + expect(verification.typeData.type).toBe("email"); + }); + + test("findByEmail finds an email case-insensitively", async () => { + const matching = buildContactVerificationData({ + typeData: { value: "Foo@Example.com", type: "email" }, + id: "matching", + }); + const query = vi.fn().mockResolvedValue({ + items: [ + buildContactVerificationData({ + typeData: { value: "other@example.com", type: "email" }, + id: "other", + }), + matching, + ], + totalCount: 2, + }); + installBehaviors({ contactVerification: { query } }); + + const result = await ContactVerification.findByEmail("foo@example.com"); + + expect(query).toHaveBeenCalledWith({ + value: "foo@example.com", + type: "email", + }); + expect(result?.id).toBe("matching"); + }); + + test("resendVerificationMail delegates for email verifications", async () => { + const resendVerificationEmail = vi.fn().mockResolvedValue(undefined); + installBehaviors({ contactVerification: { resendVerificationEmail } }); + const verification = new ContactVerificationDetailed( + buildContactVerificationData({ id: "cv-email" }), + ); + + await verification.resendVerificationMail(); + + expect(resendVerificationEmail).toHaveBeenCalledWith("cv-email"); + }); + + test("preserves the list item identity chain", () => { + const item = new ContactVerificationListItem( + buildContactVerificationData(), + ); + + expect(item).toBeInstanceOf(ContactVerificationListItem); + expect(item).toBeInstanceOf(ContactVerificationCommon); + expect(item).toBeInstanceOf(ContactVerification); + expect(item).toBeInstanceOf(ReferenceModel); + expect(item.data).toBeDefined(); + }); +}); diff --git a/packages/models/src/domain/ContactVerification/ContactVerification.ts b/packages/models/src/domain/ContactVerification/ContactVerification.ts new file mode 100644 index 00000000..d5777c97 --- /dev/null +++ b/packages/models/src/domain/ContactVerification/ContactVerification.ts @@ -0,0 +1,162 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { isArray } from "remeda"; + +import type { ContactVerificationTypeData } from "../ContactVerificationTypeData/index.js"; +import type { + ContactVerificationListQueryData, + ContactVerificationStatus, + ContactVerificationData, +} from "./types.js"; + +import { contactVerificationTypeDataFactory } from "../ContactVerificationTypeData/index.js"; +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "ContactVerification", +}) +export class ContactVerification extends ReferenceModel { + public static async find(contactVerificationId: string) { + const data = await config.behaviors.contactVerification.find( + contactVerificationId, + ); + if (data) { + return new ContactVerificationDetailed(data); + } + } + + public static async findByEmail(email: string) { + const { items } = await ContactVerification.query({ + type: "email", + value: email, + }).execute(); + + return items.find( + (i) => + i.typeData.type === "email" && + i.typeData.value.toLowerCase() === email.toLowerCase(), + ); + } + + public static async get(contactVerificationId: string) { + const contactVerification = await this.find(contactVerificationId); + assertObjectFound( + contactVerification, + ContactVerification, + contactVerificationId, + ); + return contactVerification; + } + + public static ofId(id: string) { + return new ContactVerification(id); + } + + public static query(query: ContactVerificationListQueryData = {}) { + return new ContactVerificationListQuery(query); + } + + public async findCommon(): Promise { + return this instanceof ContactVerificationCommon + ? this + : this.findDetailed(); + } + + public async findDetailed(): Promise< + ContactVerificationDetailed | undefined + > { + return await ContactVerification.find(this.id); + } + + public async getCommon(): Promise { + return this instanceof ContactVerificationCommon + ? this + : this.getDetailed(); + } + + public async getDetailed(): Promise { + return await ContactVerification.get(this.id); + } +} + +export class ContactVerificationCommon extends WithData()( + ContactVerification, +) { + public override readonly data: ContactVerificationData; + public readonly status: ContactVerificationStatus; + public readonly typeData: ContactVerificationTypeData; + public constructor(data: ContactVerificationData) { + super(data.id); + this.data = data; + this.status = data.status; + this.typeData = contactVerificationTypeDataFactory(data.typeData); + } + + public hasStatus( + status: ContactVerificationStatus[] | ContactVerificationStatus, + ) { + return (isArray(status) ? status : [status]).includes(this.status); + } + + public async resendVerificationMail() { + if (this.typeData.type === "email") { + await config.behaviors.contactVerification.resendVerificationEmail( + this.id, + ); + } + } +} + +export class ContactVerificationDetailed extends ContactVerificationCommon { + public constructor(data: ContactVerificationData) { + super(data); + } +} + +export class ContactVerificationListQuery extends ListQueryModel { + public constructor(query: ContactVerificationListQueryData) { + super(query); + } + public async execute() { + const { totalCount, items } = + await config.behaviors.contactVerification.query(this.query); + + return new ContactVerificationList( + this.query, + items.map((i) => new ContactVerificationListItem(i)), + totalCount, + ); + } + + public refine(query: ContactVerificationListQueryData = {}) { + return new ContactVerificationListQuery({ ...this.query, ...query }); + } +} + +export class ContactVerificationListItem extends ContactVerificationCommon { + public constructor(data: ContactVerificationData) { + super(data); + } +} + +export class ContactVerificationList extends WithListData()( + ContactVerificationListQuery, +) { + public override readonly items: readonly ContactVerificationListItem[]; + public override readonly totalCount: number; + public constructor( + query: ContactVerificationListQueryData, + items: ContactVerificationListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(items); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/domain/ContactVerification/behaviors/api.ts b/packages/models/src/domain/ContactVerification/behaviors/api.ts new file mode 100644 index 00000000..aaabbb4f --- /dev/null +++ b/packages/models/src/domain/ContactVerification/behaviors/api.ts @@ -0,0 +1,64 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { ContactVerificationBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount } from "../../../base/index.js"; +import { ValidationError } from "../../../errors/index.js"; + +const resolveResendEmailError = (message: string): string => { + const lowercaseMessage = message?.toLowerCase(); + + if (lowercaseMessage.includes("mail send failed")) { + return "mailSendFailed"; + } + if (lowercaseMessage.includes("can only be sent once every")) { + return "resendCooldown"; + } + if (lowercaseMessage.includes("already verified")) { + return "alreadyVerified"; + } + return "default"; +}; + +export const apiContactVerificationBehaviors = ( + client: MittwaldAPIV2Client, +): ContactVerificationBehaviors => ({ + resendVerificationEmail: async (contactVerificationId: string) => { + const response = await client.domain.resendContactVerificationEmail({ + contactVerificationId, + }); + if (response.status === 412) { + const message = + typeof response.data.message === "string" + ? response.data.message.toLowerCase() + : undefined; + const type = message ? resolveResendEmailError(message) : "default"; + + throw new ValidationError({ + path: "contactVerification", + message: type, + type, + }); + } + + validateResponse(response, 204); + }, + find: async (contactVerificationId: string) => { + const response = await client.domain.getContactVerification({ + contactVerificationId, + }); + + if (response.status === 200) { + return response.data; + } + validateResponse(response, [404]); + }, + query: async (query = {}) => { + const response = await client.domain.listContactVerifications({ + queryParameters: query, + }); + validateResponse(response, 200); + return { totalCount: resolveTotalCount(response), items: response.data }; + }, +}); diff --git a/packages/models/src/domain/ContactVerification/behaviors/index.ts b/packages/models/src/domain/ContactVerification/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/domain/ContactVerification/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/domain/ContactVerification/behaviors/types.ts b/packages/models/src/domain/ContactVerification/behaviors/types.ts new file mode 100644 index 00000000..c179a991 --- /dev/null +++ b/packages/models/src/domain/ContactVerification/behaviors/types.ts @@ -0,0 +1,16 @@ +import type { QueryResponseData } from "../../../base/index.js"; +import type { + ContactVerificationListQueryData, + ContactVerificationListItemData, + ContactVerificationData, +} from "../types.js"; + +export interface ContactVerificationBehaviors { + query: ( + query?: ContactVerificationListQueryData, + ) => Promise>; + find: ( + contactVerificationId: string, + ) => Promise; + resendVerificationEmail: (contactVerificationId: string) => Promise; +} diff --git a/packages/models/src/domain/ContactVerification/index.ts b/packages/models/src/domain/ContactVerification/index.ts new file mode 100644 index 00000000..0fc5b0f3 --- /dev/null +++ b/packages/models/src/domain/ContactVerification/index.ts @@ -0,0 +1,2 @@ +export * from "./ContactVerification.js"; +export * from "./types.js"; diff --git a/packages/models/src/domain/ContactVerification/types.ts b/packages/models/src/domain/ContactVerification/types.ts new file mode 100644 index 00000000..4e114c0c --- /dev/null +++ b/packages/models/src/domain/ContactVerification/types.ts @@ -0,0 +1,13 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type ContactVerificationData = + MittwaldAPIV2.Components.Schemas.DomainContactVerification; + +export type ContactVerificationStatus = + MittwaldAPIV2.Components.Schemas.DomainContactVerificationStatus; + +export type ContactVerificationListQueryData = + MittwaldAPIV2.Paths.V2ContactVerifications.Get.Parameters.Query; + +export type ContactVerificationListItemData = + MittwaldAPIV2.Operations.DomainListContactVerifications.ResponseData[number]; diff --git a/packages/models/src/domain/ContactVerificationTypeData/ContactVerificationTypeData.test.ts b/packages/models/src/domain/ContactVerificationTypeData/ContactVerificationTypeData.test.ts new file mode 100644 index 00000000..c4c83d2d --- /dev/null +++ b/packages/models/src/domain/ContactVerificationTypeData/ContactVerificationTypeData.test.ts @@ -0,0 +1,84 @@ +import { describe, expect, test } from "vitest"; +import { DateTime } from "luxon"; + +import type { ContactVerificationEmailDataData } from "./types.js"; + +import { + contactVerificationTypeDataFactory, + ContactVerificationAddressData, + ContactVerificationEmailData, + ContactVerificationNameData, +} from "./ContactVerificationTypeData.js"; + +describe("contactVerificationTypeDataFactory", () => { + test("creates address data", () => { + const result = contactVerificationTypeDataFactory({ + type: "address", + value: "x", + }); + + expect(result).toBeInstanceOf(ContactVerificationAddressData); + expect(result.type).toBe("address"); + expect(result.value).toBe("x"); + }); + + test("creates name data", () => { + const result = contactVerificationTypeDataFactory({ + type: "name", + value: "y", + }); + + expect(result).toBeInstanceOf(ContactVerificationNameData); + expect(result.type).toBe("name"); + expect(result.value).toBe("y"); + }); + + test("creates email data", () => { + const result = contactVerificationTypeDataFactory({ + value: "z@e.com", + type: "email", + }); + + expect(result).toBeInstanceOf(ContactVerificationEmailData); + expect(result.type).toBe("email"); + expect(result.value).toBe("z@e.com"); + }); +}); + +describe("ContactVerificationEmailData", () => { + const buildEmailData = ( + overrides: Partial = {}, + ): ContactVerificationEmailDataData => ({ + value: "user@example.com", + type: "email", + ...overrides, + }); + + test("allows resending when no email has been sent", () => { + const email = new ContactVerificationEmailData(buildEmailData()); + + expect(email.isEmailResendAllowed()).toBe(true); + }); + + test("recognizes an expired verification deadline", () => { + const email = new ContactVerificationEmailData( + buildEmailData({ + emailVerificationDeadline: DateTime.now().minus({ hour: 1 }).toISO(), + }), + ); + + expect(email.hasDeadlineExpired()).toBe(true); + }); + + test("disallows a recent resend before the deadline", () => { + const email = new ContactVerificationEmailData( + buildEmailData({ + emailVerificationDeadline: DateTime.now().plus({ hour: 1 }).toISO(), + lastEmailSentDate: DateTime.now().toISO(), + }), + ); + + expect(email.hasDeadlineExpired()).toBe(false); + expect(email.isEmailResendAllowed()).toBe(false); + }); +}); diff --git a/packages/models/src/domain/ContactVerificationTypeData/ContactVerificationTypeData.ts b/packages/models/src/domain/ContactVerificationTypeData/ContactVerificationTypeData.ts new file mode 100644 index 00000000..fb117762 --- /dev/null +++ b/packages/models/src/domain/ContactVerificationTypeData/ContactVerificationTypeData.ts @@ -0,0 +1,86 @@ +import type { DurationLike } from "luxon"; + +import { DateTime } from "luxon"; + +import type { + ContactVerificationAddressDataData, + ContactVerificationEmailDataData, + ContactVerificationNameDataData, + ContactVerificationTypeDataData, +} from "./types.js"; + +import { DataModel } from "../../base/index.js"; + +export abstract class ContactVerificationDataBase< + T extends ContactVerificationTypeDataData, +> extends DataModel { + public readonly value: string; + public constructor(data: T) { + super(data); + this.value = data.value; + } +} + +export class ContactVerificationAddressData extends ContactVerificationDataBase { + public readonly type = "address"; + public constructor(data: ContactVerificationAddressDataData) { + super(data); + } +} + +export class ContactVerificationNameData extends ContactVerificationDataBase { + public readonly type = "name"; + public constructor(data: ContactVerificationNameDataData) { + super(data); + } +} + +export class ContactVerificationEmailData extends ContactVerificationDataBase { + public readonly emailVerificationDeadline?: DateTime; + public readonly lastEmailSentDate?: DateTime; + public readonly type = "email"; + public constructor(data: ContactVerificationEmailDataData) { + super(data); + if (data.emailVerificationDeadline) { + this.emailVerificationDeadline = DateTime.fromISO( + data.emailVerificationDeadline, + ); + } + if (data.lastEmailSentDate) { + this.lastEmailSentDate = DateTime.fromISO(data.lastEmailSentDate); + } + } + + public hasDeadlineExpired() { + if (!this.emailVerificationDeadline) { + return true; + } + return this.emailVerificationDeadline < DateTime.now(); + } + + public isEmailResendAllowed() { + if (!this.lastEmailSentDate || this.hasDeadlineExpired()) { + return true; + } + // The email can only be resent if this duration has passed since the last email was sent + const resendInterval: DurationLike = { minute: 15 }; + return this.lastEmailSentDate <= DateTime.now().minus(resendInterval); + } +} + +export type ContactVerificationTypeData = + | ContactVerificationAddressData + | ContactVerificationEmailData + | ContactVerificationNameData; + +export const contactVerificationTypeDataFactory = ( + data: ContactVerificationTypeDataData, +): ContactVerificationTypeData => { + if (data.type === "address") { + return new ContactVerificationAddressData(data); + } + if (data.type === "name") { + return new ContactVerificationNameData(data); + } + return new ContactVerificationEmailData(data); +}; diff --git a/packages/models/src/domain/ContactVerificationTypeData/index.ts b/packages/models/src/domain/ContactVerificationTypeData/index.ts new file mode 100644 index 00000000..ba6bbc00 --- /dev/null +++ b/packages/models/src/domain/ContactVerificationTypeData/index.ts @@ -0,0 +1,2 @@ +export * from "./ContactVerificationTypeData.js"; +export * from "./types.js"; diff --git a/packages/models/src/domain/ContactVerificationTypeData/types.ts b/packages/models/src/domain/ContactVerificationTypeData/types.ts new file mode 100644 index 00000000..1a74d9a4 --- /dev/null +++ b/packages/models/src/domain/ContactVerificationTypeData/types.ts @@ -0,0 +1,15 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type ContactVerificationAddressDataData = + MittwaldAPIV2.Components.Schemas.DomainContactVerificationAddressData; + +export type ContactVerificationEmailDataData = + MittwaldAPIV2.Components.Schemas.DomainContactVerificationEmailData; + +export type ContactVerificationNameDataData = + MittwaldAPIV2.Components.Schemas.DomainContactVerificationNameData; + +export type ContactVerificationTypeDataData = + | ContactVerificationAddressDataData + | ContactVerificationEmailDataData + | ContactVerificationNameDataData; diff --git a/packages/models/src/domain/Domain/Domain.test.ts b/packages/models/src/domain/Domain/Domain.test.ts new file mode 100644 index 00000000..4eda1767 --- /dev/null +++ b/packages/models/src/domain/Domain/Domain.test.ts @@ -0,0 +1,174 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { buildDomainListItemData } from "../../testing/builders/buildDomainListItemData.js"; +import { buildDomainDomainData } from "../../testing/builders/buildDomainDomainData.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { ReferenceModel } from "../../base/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { + DomainDetailed, + DomainListItem, + DomainCommon, + DomainList, + Domain, +} from "./Domain.js"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? type.name : undefined, +})); + +afterEach(resetBehaviors); + +describe("Domain aggregate + common variant", () => { + test("aggregateMetaData carries the domain/domain identity", () => { + expect(Domain.aggregateMetaData).toBeInstanceOf(AggregateMetaData); + expect(Domain.aggregateMetaData.domain).toBe("domain"); + expect(Domain.aggregateMetaData.aggregate).toBe("domain"); + }); + + test("findCommon delegates to a detailed variant for a reference", async () => { + const find = vi.fn().mockResolvedValue(buildDomainDomainData()); + installBehaviors({ domain: { find } }); + + const common = await Domain.ofId("d-1").findCommon(); + + expect(common).toBeInstanceOf(DomainCommon); + expect(find).toHaveBeenCalledWith("d-1"); + }); + + test("getCommon throws for a missing reference", async () => { + installBehaviors({ + domain: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(Domain.ofId("d-1").getCommon()).rejects.toThrow(); + }); + + test("getCommon/findCommon are idempotent on materialized models", async () => { + const find = vi.fn(); + installBehaviors({ domain: { find } }); + const detailed = new DomainDetailed(buildDomainDomainData()); + const item = new DomainListItem(buildDomainListItemData()); + + expect(await detailed.getCommon()).toBe(detailed); + expect(await detailed.findCommon()).toBe(detailed); + expect(await item.getCommon()).toBe(item); + expect(find).not.toHaveBeenCalled(); + }); + + test("omits optional owner/admin data when absent", () => { + const domain = new DomainDetailed(buildDomainDomainData()); + + expect(domain.adminC).toBeUndefined(); + expect(domain.scheduledDeletionDate).toBeUndefined(); + }); +}); + +describe("Domain reference and delegation", () => { + test("creates a reference", () => { + const domain = Domain.ofId("d-1"); + expect(domain).toBeInstanceOf(Domain); + expect(domain).toBeInstanceOf(ReferenceModel); + expect(domain.id).toBe("d-1"); + }); + + test("find materializes detailed data and preserves undefined", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildDomainDomainData()) + .mockResolvedValueOnce(undefined); + installBehaviors({ domain: { find } }); + + const found = await Domain.find("domain-id"); + expect(found).toBeInstanceOf(DomainDetailed); + expect(found).toBeInstanceOf(DomainCommon); + expect(await Domain.find("missing")).toBeUndefined(); + }); + + test("get throws when the domain is missing", async () => { + installBehaviors({ + domain: { find: vi.fn().mockResolvedValue(undefined) }, + }); + await expect(Domain.get("missing")).rejects.toThrow(); + }); + + test("delegates instance operations", async () => { + const deleteDomain = vi.fn().mockResolvedValue(undefined); + const updateNameservers = vi.fn().mockResolvedValue(undefined); + const createAuthCode = vi.fn().mockResolvedValue({ + expirationDate: "2030-01-01T00:00:00.000Z", + authCode: "abc", + }); + installBehaviors({ + domain: { delete: deleteDomain, updateNameservers, createAuthCode }, + }); + const domain = Domain.ofId("d-1"); + + await domain.delete(); + expect(deleteDomain).toHaveBeenCalledWith("d-1", undefined, undefined); + await domain.updateNameservers(["ns.example.com"]); + expect(updateNameservers).toHaveBeenCalledWith("d-1", ["ns.example.com"]); + const authCode = await domain.createAuthCode(); + expect(authCode.authCode).toBe("abc"); + expect(authCode.expirationDate?.isValid).toBe(true); + }); + + test("delegates static lookups and normalizes suggestions", async () => { + const getSuggestions = vi.fn().mockResolvedValue(["EXAMPLE.COM"]); + const response = { registrable: true }; + const checkDomainRegistrable = vi.fn().mockResolvedValue(response); + installBehaviors({ domain: { checkDomainRegistrable, getSuggestions } }); + + await expect(Domain.suggestDomains("x")).resolves.toEqual(["example.com"]); + await expect(Domain.checkRegistrability("x.com")).resolves.toBe(response); + expect(checkDomainRegistrable).toHaveBeenCalledWith("x.com"); + }); +}); + +describe("Domain derived values", () => { + test("derives nameserver and process state", () => { + const domain = new DomainDetailed( + buildDomainDomainData({ + processes: [ + { + lastUpdate: "2024-01-01T00:00:00.000Z", + processType: "REGISTER", + transactionId: "t1", + state: "FAILED", + }, + ], + nameservers: ["custom.ns.com", "ns01.agenturserver.de"], + usesDefaultNameserver: true, + }), + ); + + expect(domain.getCustomNameservers()).toEqual(["custom.ns.com"]); + expect(domain.hasMittwaldNameservers()).toBe(true); + expect(domain.hasProcessOfType("REGISTER")).toBe(true); + expect(domain.isFailedRegistration()).toBe(true); + expect(domain.hasProcessState("FAILED")).toBe(true); + }); +}); + +describe("Domain query", () => { + test("materializes list behavior results", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildDomainDomainData({ domain: "a.com" })], + totalCount: 1, + }); + installBehaviors({ domain: { list } }); + + const result = await Domain.query().execute(); + expect(result).toBeInstanceOf(DomainList); + expect(result.items[0]).toBeInstanceOf(DomainListItem); + expect(result.items[0]?.domain).toBe("a.com"); + expect(result.totalCount).toBe(1); + }); +}); diff --git a/packages/models/src/domain/Domain/Domain.ts b/packages/models/src/domain/Domain/Domain.ts new file mode 100644 index 00000000..d142dee0 --- /dev/null +++ b/packages/models/src/domain/Domain/Domain.ts @@ -0,0 +1,423 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; +import { omit } from "remeda"; + +import type { ProcessState, ProcessType } from "../DomainProcess/index.js"; +import type { HandleField } from "../DomainHandle/index.js"; +import type { + DomainListQueryModelData, + DomainOrderPreviewItem, + VerifyAddressRequest, + DomainListItemData, + DomainData, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { DomainHandleReadable } from "../DomainHandleReadable/index.js"; +import { ContactVerification } from "../ContactVerification/index.js"; +import { ContractDetailed } from "../../contract/index.js"; +import { DomainProcess } from "../DomainProcess/index.js"; +import { Project } from "../../project/internal.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { DomainOrderRequest } from "../../order/index.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "Domain", +}) +export class Domain extends ReferenceModel { + public static aggregateMetaData = new AggregateMetaData("domain", "domain"); + + public static defaultNameservers = [ + "ns01.agenturserver.de", + "ns01.agenturserver.it", + "ns01.agenturserver.co", + ]; + + public static async checkRegistrability(domain: string) { + return await config.behaviors.domain.checkDomainRegistrable(domain); + } + + // API-DRIFT: findByHostname via find(hostname) is disabled because route invalidation does not work for shortId (hostname) lookups (resolve: re-enable the commented block once route invalidation works) + // public static async findByHostname (hostname: string) { + // try { + // return await this.find(hostname); + // } catch { + // return undefined; + // } + // } + + public static async checkTransferability(domain: string, authCode?: string) { + const transferable = await config.behaviors.domain.checkDomainTransferable( + domain, + authCode, + ); + if ("transferable" in transferable) { + return { domain, ...transferable }; + } + return transferable; + } + + public static async find(id: string) { + const data = await config.behaviors.domain.find(id); + if (data) { + return new DomainDetailed(data); + } + } + + public static async findByHostname(hostname: string) { + const domains = await this.query({ + domainSearchName: hostname, + }).execute(); + return domains.items.find((i) => i.domain === hostname); + } + + public static async get(id: string) { + const domain = await this.find(id); + assertObjectFound(domain, Domain, id); + return domain; + } + + public static ofId(id: string) { + return new Domain(id); + } + + public static async previewDomainOrder( + project: Project, + domain: string, + authCode?: string, + ) { + const preview = DomainOrderRequest.create({ authCode, project, domain }); + return await preview.getPreview(); + } + + public static async previewMultipleDomainOrders( + project: Project, + domains: DomainOrderPreviewItem[], + ) { + return await Promise.all( + domains.map(({ authCode, domain }) => + Domain.previewDomainOrder(project, domain, authCode), + ), + ); + } + + public static query = (query: DomainListQueryModelData = {}) => { + return new DomainListQuery(query); + }; + + public static async queryUniqueDomainContacts( + query: DomainListQueryModelData = {}, + ) { + const domains = await this.query(query).execute(); + const contacts: DomainListItem[] = []; + for (const domain of domains.items) { + const name = + domain.ownerC.current.organization ?? domain.ownerC.current.name; + const hashAlreadyAdded = !!contacts.find( + (i) => i.contactHash === domain.contactHash, + ); + if (!hashAlreadyAdded && !!name) { + contacts.push(domain); + } + } + return contacts; + } + + public static async suggestDomains( + prompt: string, + amount?: number, + tlds?: string[], + ) { + const domains = await config.behaviors.domain.getSuggestions( + prompt, + amount, + tlds, + ); + return domains.map((i) => i.toLowerCase()); + } + + public static async verifyAddress( + address: VerifyAddressRequest, + ): Promise { + return await config.behaviors.domain.verifyAddress(address); + } + + public static async verifyCompany(name: string): Promise { + return await config.behaviors.domain.verifyCompany(name); + } + + public async abortDomainDeclaration() { + await config.behaviors.domain.abortDomainDeclaration(this.id); + } + + public async cancelScheduledDeletion() { + return await config.behaviors.domain.cancelScheduledDeletion(this.id); + } + + public async createAuthCode() { + const response = await config.behaviors.domain.createAuthCode(this.id); + + const { authCode } = response; + + const expirationDate = response.expirationDate + ? DateTime.fromISO(response.expirationDate) + : undefined; + + return { expirationDate, authCode }; + } + + public async delete(transit?: boolean, deleteIngresses?: boolean) { + await config.behaviors.domain.delete(this.id, transit, deleteIngresses); + } + + public async findCommon(): Promise { + return this instanceof DomainCommon ? this : this.findDetailed(); + } + + public async findDetailed(): Promise { + return Domain.find(this.id); + } + + public async getCommon(): Promise { + return this instanceof DomainCommon ? this : this.getDetailed(); + } + + public async getContract() { + const response = await config.behaviors.domain.getDomainContract(this.id); + return new ContractDetailed(response); + } + + public async getDetailed(): Promise { + return Domain.get(this.id); + } + + public async resendEmail() { + await config.behaviors.domain.resendEmail(this.id); + } + + public async scheduleDeletion(date: DateTime, deleteIngresses?: boolean) { + return await config.behaviors.domain.createScheduledDeletion( + this.id, + date, + deleteIngresses, + ); + } + + public async setNameserversManaged() { + await config.behaviors.domain.updateNameservers( + this.id, + Domain.defaultNameservers, + ); + } + + public async updateAuthCode(authCode: string) { + return await config.behaviors.domain.updateAuthCode(this.id, authCode); + } + + public async updateNameservers(nameservers: string[]) { + await config.behaviors.domain.updateNameservers(this.id, nameservers); + } + + public async updateOwnerContact( + contact: HandleField[], + avoidEmailConfirmation?: boolean, + ) { + await config.behaviors.domain.updateOwnerContact( + this.id, + contact, + avoidEmailConfirmation, + ); + } + + public async updateProject(project: Project): Promise { + return await config.behaviors.domain.updateProjectId(this.id, project.id); + } +} + +export class DomainCommon extends WithData()(Domain) { + public readonly adminC?: DomainHandleReadable; + public readonly connected: boolean; + public readonly contactHash?: string; + public override readonly data: DomainData; + public readonly deleted: boolean; + public readonly domain: string; + public readonly nameservers: string[]; + public readonly ownerC: DomainHandleReadable; + public readonly processes: DomainProcess[]; + public readonly project: Project; + public readonly scheduledDeletionDate?: DateTime; + public readonly transferInAuthCode?: string; + public readonly usesDefaultNameserver: boolean; + + public constructor(data: DomainData) { + super(data.domainId); + this.data = data; + this.domain = data.domain; + this.project = Project.ofId(data.projectId); + this.deleted = data.deleted; + this.connected = data.connected; + this.nameservers = data.nameservers; + this.ownerC = new DomainHandleReadable(data.handles.ownerC); + if (data.handles.adminC) { + this.adminC = new DomainHandleReadable(data.handles.adminC); + } + this.usesDefaultNameserver = data.usesDefaultNameserver; + this.processes = data.processes + ? data.processes.map((i) => new DomainProcess(i)) + : []; + this.contactHash = data.contactHash; + this.transferInAuthCode = data.transferInAuthCode; + if (data.scheduledDeletionDate) { + this.scheduledDeletionDate = DateTime.fromISO(data.scheduledDeletionDate); + } + } + + public async findEmailContactVerification() { + const email = this.ownerC.current.email; + if (!email) { + return undefined; + } + return await ContactVerification.findByEmail(email); + } + + public getCustomNameservers(): string[] { + return this.nameservers.filter( + (i) => !Domain.defaultNameservers.includes(i), + ); + } + + public getFirstProcessOfState(state: ProcessState) { + return this.processes.find((i) => i.state === state); + } + + public getNameserverChangeStatus(): "running" | "failed" | undefined { + if (this.hasProcessWithStateAndType("REQUESTED", "UPDATE")) { + return "running"; + } + if (this.hasProcessWithStateAndType("FAILED", "UPDATE")) { + return "failed"; + } + } + + public hasAuthCodeMismatchError() { + return this.processes.some((i) => + i.error && i.state === "FAILED" + ? i.error.includes("AuthCodeMismatchError") || + i.error.includes("ErrWrongAuthCode") || + i.error.includes("AuthInfo does not match") + : false, + ); + } + + public hasDeclareRequestedProcess() { + return this.hasProcessOfType("DECLARE_REQUESTED"); + } + + public hasMittwaldNameservers(): boolean { + return ( + this.usesDefaultNameserver || + this.nameservers.every((i) => Domain.defaultNameservers.includes(i)) + ); + } + + public hasProcessOfType(type: ProcessType) { + return this.processes.some((i) => i.processType === type); + } + + public hasProcessState(state: ProcessState) { + return this.processes.some((i) => i.state === state); + } + + public hasProcessWithStateAndType(state: ProcessState, type: ProcessType) { + return this.processes.some( + (i) => i.processType === type && i.state === state, + ); + } + + public hasRunningMoveProcess() { + return ( + this.hasProcessWithStateAndType("REQUESTED", "DECLARE_REQUESTED") && + this.hasProcessWithStateAndType("REQUESTED", "TRANSFER") + ); + } + + public isFailedRegistration() { + return ( + this.hasProcessWithStateAndType("FAILED", "DECLARE_REQUESTED") || + this.hasProcessWithStateAndType("FAILED", "REGISTER") + ); + } + + public isFailedTransfer() { + return this.hasProcessWithStateAndType("FAILED", "TRANSFER"); + } +} + +export class DomainDetailed extends DomainCommon { + public constructor(data: DomainData) { + super(data); + } +} + +export class DomainListItem extends DomainCommon { + public override readonly data: DomainListItemData; + public constructor(data: DomainListItemData) { + super(data); + this.data = data; + } +} + +export class DomainListQuery extends ListQueryModel { + public constructor(data: DomainListQueryModelData = {}) { + super(data); + } + + public async execute() { + const { totalCount, items } = await config.behaviors.domain.list({ + ...omit(this.query, ["project"]), + projectId: extractId(this.query.project), + }); + + return new DomainList( + this.query, + items.map((d) => new DomainListItem(d)), + totalCount, + ); + } + + public async getTotalCount() { + const { totalCount } = await this.refine({ limit: 1 }).execute(); + return totalCount; + } + + public refine(query: DomainListQueryModelData) { + return new DomainListQuery({ + ...this.query, + ...query, + }); + } +} + +export class DomainList extends WithListData()( + DomainListQuery, +) { + public override readonly items: readonly DomainListItem[]; + public override readonly totalCount: number; + public constructor( + query: DomainListQueryModelData, + domains: DomainListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(domains); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/domain/Domain/behaviors/api.ts b/packages/models/src/domain/Domain/behaviors/api.ts new file mode 100644 index 00000000..d9c96a8c --- /dev/null +++ b/packages/models/src/domain/Domain/behaviors/api.ts @@ -0,0 +1,228 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { DomainTransferableReasons } from "../types.js"; +import type { HandleField } from "../../DomainHandle/index.js"; +import type { DomainBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount } from "../../../base/index.js"; +import { ValidationError } from "../../../errors/index.js"; + +export const apiDomainBehaviors = ( + client: MittwaldAPIV2Client, +): DomainBehaviors => ({ + checkDomainTransferable: async (domain, authCode) => { + const response = await client.domain.checkDomainTransferability({ + data: { authCode, domain }, + }); + if (response.status === 412) { + const message = + typeof response.data.message === "string" + ? response.data.message + : undefined; + if (message?.toLowerCase().includes("declaration in progress")) { + throw new ValidationError({ + message: "domainDeclarationInProgress", + type: "domainDeclarationInProgress", + path: "domain", + }); + } + if ( + message?.includes("ErrServerConnection") && + message.includes("RegistrarError") + ) { + throw new ValidationError({ + message: "registrarConnectionFailed", + type: "registrarConnectionFailed", + path: "domain", + }); + } + if (message?.toLowerCase().includes("changes are not allowed")) { + throw new ValidationError({ + message: "domainHasRunningProcess", + type: "domainHasRunningProcess", + path: "domain", + }); + } + throw new ValidationError({ + message: "domainNotTransferable", + type: "domainNotTransferable", + path: "domain", + }); + } + validateResponse(response, 200); + + return { + reasons: response.data.reasons as DomainTransferableReasons, + transferable: response.data.transferable as boolean, + }; + }, + checkDomainRegistrable: async (domain) => { + const response = await client.domain.checkDomainRegistrability({ + data: { domain }, + }); + if (response.status === 400) { + return { + tldAvailable: false, + invalidDomain: true, + registrable: false, + isPremium: false, + domain, + }; + } + validateResponse(response, 200); + return { + invalidDomain: false, + tldAvailable: true, + domain, + ...response.data, + }; + }, + updateNameservers: async (domainId, nameservers) => { + const [first, second] = nameservers.slice(0, 2); + const remaining = nameservers.slice(2); + + const response = await client.domain.updateDomainNameservers({ + data: { + nameservers: [first ?? "", second ?? "", ...remaining], + }, + domainId, + }); + + validateResponse(response, 204); + }, + updateOwnerContact: async ( + domainId, + handleFields, + avoidEmailConfirmation, + ) => { + const response = await client.domain.updateDomainContact({ + data: { + contact: handleFields as [HandleField, ...HandleField[]], + avoidEmailConfirmation, + }, + contact: "owner", + domainId, + }); + validateResponse(response, 200); + }, + createScheduledDeletion: async (domainId, date, deleteIngresses) => { + const deletionDate = date.toISO(); + if (deletionDate === null) { + return; + } + const response = await client.domain.createScheduledDeletion({ + data: { deleteIngresses, deletionDate }, + domainId, + }); + + validateResponse(response, 204); + }, + updateAuthCode: async (domainId, authCode) => { + const response = await client.domain.updateDomainAuthCode({ + data: { authCode }, + domainId, + }); + validateResponse(response, 200); + return { + transactionId: response.data.transactionId as string, + isAsync: response.data.isAsync as boolean, + }; + }, + getSuggestions: async (prompt, domainCount, tlds) => { + const response = await client.domain.suggest({ + queryParameters: { + domainCount: domainCount ?? 6, + tlds: tlds ?? [], + prompt, + }, + }); + validateResponse(response, 200); + return response.data.domains; + }, + list: async (query = {}) => { + const response = await client.domain.listDomains({ + queryParameters: query, + }); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + getLatestScreenshot: async (domainName) => { + const response = await client.domain.getLatestScreenshot({ + queryParameters: { + domainName, + }, + }); + validateResponse(response, 200); + return response.data; + }, + delete: async (domainId, transit, deleteIngresses) => { + const response = await client.domain.deleteDomain({ + queryParameters: { deleteIngresses, transit }, + domainId, + }); + validateResponse(response, 200); + }, + updateProjectId: async (domainId, projectId) => { + const response = await client.domain.updateDomainProjectId({ + data: { + projectId, + }, + domainId, + }); + validateResponse(response, 204); + }, + find: async (domainId) => { + const response = await client.domain.getDomain({ domainId }); + if (response.status === 200) { + return response.data; + } + validateResponse(response, [404, 403]); + }, + verifyAddress: async (address) => { + const response = await client.misc.verificationVerifyAddress({ + data: address, + }); + validateResponse(response, 200); + return response.data.exists; + }, + getDomainContract: async (domainId) => { + const response = await client.contract.getDetailOfContractByDomain({ + domainId, + }); + validateResponse(response, 200); + return response.data; + }, + verifyCompany: async (name) => { + const response = await client.misc.verificationVerifyCompany({ + data: { name }, + }); + validateResponse(response, 200); + return response.data.exists; + }, + createAuthCode: async (domainId) => { + const response = await client.domain.createDomainAuthCode({ domainId }); + + validateResponse(response, 201); + return response.data; + }, + cancelScheduledDeletion: async (domainId) => { + const response = await client.domain.cancelScheduledDeletion({ + domainId, + }); + validateResponse(response, 204); + }, + abortDomainDeclaration: async (domainId) => { + const response = await client.domain.abortDomainDeclaration({ + domainId, + }); + validateResponse(response, 204); + }, + resendEmail: async (domainId) => { + const response = await client.domain.resendDomainEmail({ domainId }); + validateResponse(response, 204); + }, +}); diff --git a/packages/models/src/domain/Domain/behaviors/index.ts b/packages/models/src/domain/Domain/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/domain/Domain/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/domain/Domain/behaviors/types.ts b/packages/models/src/domain/Domain/behaviors/types.ts new file mode 100644 index 00000000..4da39bfd --- /dev/null +++ b/packages/models/src/domain/Domain/behaviors/types.ts @@ -0,0 +1,65 @@ +import type { DateTime } from "luxon"; + +import type { QueryResponseData } from "../../../base/index.js"; +import type { ContractData } from "../../../contract/index.js"; +import type { HandleField } from "../../DomainHandle/index.js"; +import type { + DomainTransferableResponse, + DomainRegistrableResponse, + VerifyAddressRequest, + DomainListQueryData, + DomainListItemData, + DomainData, +} from "../types.js"; + +export interface DomainBehaviors { + updateOwnerContact: ( + domainId: string, + handleFields: HandleField[], + avoidEmailConfirmation?: boolean, + ) => Promise; + updateAuthCode: ( + domainId: string, + authCode: string, + ) => Promise<{ transactionId: string; isAsync: boolean }>; + + createScheduledDeletion: ( + domainId: string, + date: DateTime, + deleteIngresses?: boolean, + ) => Promise; + checkDomainTransferable: ( + domain: string, + authCode?: string, + ) => Promise; + getSuggestions: ( + prompt: string, + domainCount?: number, + tlds?: string[], + ) => Promise; + + delete: ( + domainId: string, + transit?: boolean, + deleteIngresses?: boolean, + ) => Promise; + createAuthCode: ( + domainId: string, + ) => Promise<{ expirationDate?: string; authCode: string }>; + list: ( + query?: DomainListQueryData, + ) => Promise>; + checkDomainRegistrable: ( + domain: string, + ) => Promise; + updateNameservers: (domainId: string, nameservers: string[]) => Promise; + getLatestScreenshot: (domainName: string) => Promise<{ reference?: string }>; + updateProjectId: (domainId: string, projectId: string) => Promise; + verifyAddress: (address: VerifyAddressRequest) => Promise; + getDomainContract: (domainId: string) => Promise; + cancelScheduledDeletion: (domainId: string) => Promise; + abortDomainDeclaration: (domainId: string) => Promise; + find: (id: string) => Promise; + verifyCompany: (name: string) => Promise; + resendEmail: (domainId: string) => Promise; +} diff --git a/packages/models/src/domain/Domain/index.ts b/packages/models/src/domain/Domain/index.ts new file mode 100644 index 00000000..4ac75b76 --- /dev/null +++ b/packages/models/src/domain/Domain/index.ts @@ -0,0 +1,2 @@ +export * from "./Domain.js"; +export * from "./types.js"; diff --git a/packages/models/src/domain/Domain/types.ts b/packages/models/src/domain/Domain/types.ts new file mode 100644 index 00000000..727f5c53 --- /dev/null +++ b/packages/models/src/domain/Domain/types.ts @@ -0,0 +1,58 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import type { Project } from "../../project/index.js"; + +export type DomainListQueryData = + MittwaldAPIV2.Paths.V2Domains.Get.Parameters.Query; + +export type DomainListQueryModelData = Omit< + DomainListQueryData, + "projectId" +> & { + project?: Project | string; +}; + +export type DomainData = MittwaldAPIV2.Operations.DomainGetDomain.ResponseData; + +export type DomainListItemData = + MittwaldAPIV2.Operations.DomainListDomains.ResponseData[number]; + +export interface DomainRegistrableResponse { + invalidDomain: boolean; + tldAvailable: boolean; + registrable: boolean; + isPremium: boolean; + domain: string; +} + +export interface DomainTransferableReasons { + domainDoesNotExist: boolean; + domainAgeTooSmall: boolean; + wrongAuthCode: boolean; + transferLock: boolean; +} + +export interface DomainTransferableResponse { + reasons: DomainTransferableReasons; + transferable: boolean; +} + +export type DnsRecordMXRecord = + MittwaldAPIV2.Components.Schemas.DnsRecordMXRecord; + +export type DnsRecordSRVRecord = + MittwaldAPIV2.Components.Schemas.DnsRecordSRVRecord; + +export type DnsRecordCAARecord = + MittwaldAPIV2.Components.Schemas.DnsRecordCAARecord; + +export type OrderDomainHandleField = + MittwaldAPIV2.Components.Schemas.OrderDomainHandleField; + +export interface DomainOrderPreviewItem { + authCode?: string; + domain: string; +} + +export type VerifyAddressRequest = + MittwaldAPIV2.Paths.V2ActionsVerifyAddress.Post.Parameters.RequestBody; diff --git a/packages/models/src/domain/DomainHandle/DomainHandle.test.ts b/packages/models/src/domain/DomainHandle/DomainHandle.test.ts new file mode 100644 index 00000000..327b0741 --- /dev/null +++ b/packages/models/src/domain/DomainHandle/DomainHandle.test.ts @@ -0,0 +1,95 @@ +import { afterEach, describe, expect, test } from "vitest"; + +import { buildDomainHandleFieldData } from "../../testing/builders/buildDomainHandleFieldData.js"; +import { buildDomainHandleData } from "../../testing/builders/buildDomainHandleData.js"; +import { resetBehaviors } from "../../testing/installBehaviors.js"; +import { DomainHandle } from "./DomainHandle.js"; +import { DataModel } from "../../base/index.js"; + +afterEach(resetBehaviors); + +describe("DomainHandle", () => { + test("constructs from data and exposes derived fields", () => { + const data = buildDomainHandleData(); + const handle = new DomainHandle(data); + + expect(handle).toBeInstanceOf(DomainHandle); + expect(handle).toBeInstanceOf(DataModel); + expect(handle.handleRef).toBe(data.handleRef); + for (const name of [ + "name", + "organization", + "email", + "street", + "city", + "zip", + "country", + "phone", + ] as const) { + expect(handle[name]).toBe( + data.handleFields?.find((field) => field.name === name)?.value, + ); + } + }); + + test("defaults missing fields and derived values", () => { + const handle = new DomainHandle({}); + + expect(handle.fields).toEqual([]); + expect(handle.name).toBeUndefined(); + expect(handle.organization).toBeUndefined(); + expect(handle.email).toBeUndefined(); + expect(handle.street).toBeUndefined(); + expect(handle.city).toBeUndefined(); + expect(handle.zip).toBeUndefined(); + expect(handle.country).toBeUndefined(); + expect(handle.phone).toBeUndefined(); + }); + + test("gets a field value by name", () => { + const handle = new DomainHandle(buildDomainHandleData()); + + expect(handle.getFieldValue("email")).toBe("owner@example.com"); + expect(handle.getFieldValue("missing")).toBeUndefined(); + }); + + test("returns all fields as a record", () => { + const data = buildDomainHandleData(); + const handle = new DomainHandle(data); + + expect(handle.getAsRecord()).toEqual( + Object.fromEntries( + (data.handleFields ?? []).map(({ value, name }) => [name, value]), + ), + ); + }); + + test("returns only additional, non-excluded fields", () => { + const handle = new DomainHandle( + buildDomainHandleData({ + handleFields: [ + buildDomainHandleFieldData({ value: "Owner", name: "name" }), + buildDomainHandleFieldData({ value: "123", name: "fax" }), + buildDomainHandleFieldData({ name: "department", value: "Sales" }), + ], + }), + ); + + expect(handle.getAdditionalFields(["department"])).toEqual([ + buildDomainHandleFieldData({ value: "123", name: "fax" }), + ]); + }); + + test("constructs from handle fields", () => { + const fields = [ + buildDomainHandleFieldData({ value: "Other Owner", name: "name" }), + buildDomainHandleFieldData({ value: "other@example.com", name: "email" }), + ]; + + const handle = DomainHandle.fromHandleFields(fields); + + expect(handle.fields).toBe(fields); + expect(handle.name).toBe("Other Owner"); + expect(handle.email).toBe("other@example.com"); + }); +}); diff --git a/packages/models/src/domain/DomainHandle/DomainHandle.ts b/packages/models/src/domain/DomainHandle/DomainHandle.ts new file mode 100644 index 00000000..6862fa8a --- /dev/null +++ b/packages/models/src/domain/DomainHandle/DomainHandle.ts @@ -0,0 +1,54 @@ +import type { HandleField, HandleData } from "./types.js"; + +import { DataModel } from "../../base/index.js"; + +export class DomainHandle extends DataModel { + public readonly city?: string; + public readonly country?: string; + public readonly email?: string; + public readonly fields: HandleField[]; + public readonly handleRef?: string; + public readonly name?: string; + public readonly organization?: string; + public readonly phone?: string; + public readonly street?: string; + public readonly zip?: string; + + public constructor(data: HandleData) { + super(data); + this.handleRef = data.handleRef; + this.fields = data.handleFields ?? []; + this.name = this.getFieldValue("name"); + this.organization = this.getFieldValue("organization"); + this.email = this.getFieldValue("email"); + this.street = this.getFieldValue("street"); + this.city = this.getFieldValue("city"); + this.zip = this.getFieldValue("zip"); + this.country = this.getFieldValue("country"); + this.phone = this.getFieldValue("phone"); + } + + public static fromHandleFields(fields: HandleField[]): DomainHandle { + return new DomainHandle({ + handleFields: fields, + }); + } + + public getAdditionalFields(exclude: string[] = []): HandleField[] { + return this.fields.filter( + (i) => !(i.name in this) && !exclude.includes(i.name), + ); + } + + public getAsRecord(): Record { + const record: Record = {}; + this.fields.forEach((i) => { + record[i.name] = i.value; + }); + return record; + } + + public getFieldValue(name: string) { + return this.fields.find((i) => i.name === name)?.value; + } +} diff --git a/packages/models/src/domain/DomainHandle/index.ts b/packages/models/src/domain/DomainHandle/index.ts new file mode 100644 index 00000000..ff4410a3 --- /dev/null +++ b/packages/models/src/domain/DomainHandle/index.ts @@ -0,0 +1,2 @@ +export * from "./DomainHandle.js"; +export * from "./types.js"; diff --git a/packages/models/src/domain/DomainHandle/types.ts b/packages/models/src/domain/DomainHandle/types.ts new file mode 100644 index 00000000..2461e99f --- /dev/null +++ b/packages/models/src/domain/DomainHandle/types.ts @@ -0,0 +1,5 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type HandleData = MittwaldAPIV2.Components.Schemas.DomainHandleData; + +export type HandleField = MittwaldAPIV2.Components.Schemas.DomainHandleField; diff --git a/packages/models/src/domain/DomainHandleReadable/DomainHandleReadable.test.ts b/packages/models/src/domain/DomainHandleReadable/DomainHandleReadable.test.ts new file mode 100644 index 00000000..98da6e8a --- /dev/null +++ b/packages/models/src/domain/DomainHandleReadable/DomainHandleReadable.test.ts @@ -0,0 +1,39 @@ +import { afterEach, describe, expect, test } from "vitest"; + +import { buildDomainHandleReadableData } from "../../testing/builders/buildDomainHandleReadableData.js"; +import { buildDomainHandleData } from "../../testing/builders/buildDomainHandleData.js"; +import { resetBehaviors } from "../../testing/installBehaviors.js"; +import { DomainHandleReadable } from "./DomainHandleReadable.js"; +import { DomainHandle } from "../DomainHandle/index.js"; + +afterEach(resetBehaviors); + +describe("DomainHandleReadable", () => { + test("constructs current as a DomainHandle", () => { + const data = buildDomainHandleReadableData(); + const readable = new DomainHandleReadable(data); + + expect(readable.current).toBeInstanceOf(DomainHandle); + expect(readable.current.handleRef).toBe(data.current.handleRef); + }); + + test("leaves desired undefined when absent", () => { + const readable = new DomainHandleReadable( + buildDomainHandleReadableData({ desired: undefined }), + ); + + expect(readable.desired).toBeUndefined(); + }); + + test("constructs a distinct desired DomainHandle when present", () => { + const readable = new DomainHandleReadable( + buildDomainHandleReadableData({ + desired: buildDomainHandleData({ handleRef: "handle-2" }), + }), + ); + + expect(readable.desired).toBeInstanceOf(DomainHandle); + expect(readable.current.handleRef).toBe("handle-1"); + expect(readable.desired?.handleRef).toBe("handle-2"); + }); +}); diff --git a/packages/models/src/domain/DomainHandleReadable/DomainHandleReadable.ts b/packages/models/src/domain/DomainHandleReadable/DomainHandleReadable.ts new file mode 100644 index 00000000..f9581d22 --- /dev/null +++ b/packages/models/src/domain/DomainHandleReadable/DomainHandleReadable.ts @@ -0,0 +1,16 @@ +import type { HandleReadableData } from "./types.js"; + +import { DomainHandle } from "../DomainHandle/index.js"; +import { DataModel } from "../../base/index.js"; + +export class DomainHandleReadable extends DataModel { + public readonly current: DomainHandle; + public readonly desired?: DomainHandle; + public constructor(data: HandleReadableData) { + super(data); + this.current = new DomainHandle(data.current); + if (data.desired) { + this.desired = new DomainHandle(data.desired); + } + } +} diff --git a/packages/models/src/domain/DomainHandleReadable/index.ts b/packages/models/src/domain/DomainHandleReadable/index.ts new file mode 100644 index 00000000..76f752bb --- /dev/null +++ b/packages/models/src/domain/DomainHandleReadable/index.ts @@ -0,0 +1,2 @@ +export * from "./DomainHandleReadable.js"; +export * from "./types.js"; diff --git a/packages/models/src/domain/DomainHandleReadable/types.ts b/packages/models/src/domain/DomainHandleReadable/types.ts new file mode 100644 index 00000000..f744ff40 --- /dev/null +++ b/packages/models/src/domain/DomainHandleReadable/types.ts @@ -0,0 +1,4 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type HandleReadableData = + MittwaldAPIV2.Components.Schemas.DomainHandleReadable; diff --git a/packages/models/src/domain/DomainMigration/DomainMigration.test.ts b/packages/models/src/domain/DomainMigration/DomainMigration.test.ts new file mode 100644 index 00000000..668b9cc7 --- /dev/null +++ b/packages/models/src/domain/DomainMigration/DomainMigration.test.ts @@ -0,0 +1,291 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; +import { DateTime } from "luxon"; + +import { buildDomainMigrationDnsRecordData } from "../../testing/builders/buildDomainMigrationDnsRecordData.js"; +import { buildDomainMigrationDomainData } from "../../testing/builders/buildDomainMigrationDomainData.js"; +import { buildDomainMigrationData } from "../../testing/builders/buildDomainMigrationData.js"; +import { DomainMigrationDomain } from "../DomainMigrationDomain/index.js"; +import { ListQueryModel } from "../../base/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { + DomainMigrationListQuery, + DomainMigrationListItem, + DomainMigrationList, + DomainMigration, +} from "./DomainMigration.js"; + +afterEach(resetBehaviors); + +describe("DomainMigration list query", () => { + test("creates a project-scoped list query", () => { + const query = DomainMigration.queryByProjectId("project-1"); + + expect(query).toBeInstanceOf(DomainMigrationListQuery); + expect(query).toBeInstanceOf(ListQueryModel); + }); + + test("delegates execution and materializes the returned list", async () => { + const queryByProjectId = vi.fn().mockResolvedValue({ + items: [buildDomainMigrationData({ id: "m-1" })], + totalCount: 1, + }); + installBehaviors({ domainMigration: { queryByProjectId } }); + + const result = + await DomainMigration.queryByProjectId("project-1").execute(); + + expect(queryByProjectId).toHaveBeenCalledWith("project-1"); + expect(result).toBeInstanceOf(DomainMigrationList); + expect(result.items).toHaveLength(1); + expect(result.items[0]).toBeInstanceOf(DomainMigrationListItem); + expect(result.totalCount).toBe(1); + }); +}); + +describe("DomainMigrationListItem", () => { + test("finds included domains", () => { + const item = new DomainMigrationListItem( + buildDomainMigrationData({ + domains: [buildDomainMigrationDomainData({ domain: "a.com" })], + }), + ); + + expect(item.includesDomain("a.com")).toBe(true); + expect(item.includesDomain("b.com")).toBe(false); + expect(item.findDomain("a.com")).toBeInstanceOf(DomainMigrationDomain); + expect(item.findDomain("a.com")?.domain).toBe("a.com"); + expect(item.findDomain("b.com")).toBeUndefined(); + }); + + test("returns the first unique A-record value across domains", () => { + const item = new DomainMigrationListItem( + buildDomainMigrationData({ + domains: [ + buildDomainMigrationDomainData({ + coabData: { + dnsRecords: [ + buildDomainMigrationDnsRecordData({ + value: "9.9.9.9", + type: "A", + }), + ], + }, + domain: "a.com", + }), + ], + }), + ); + + expect(item.findFirstARecord()).toBe("9.9.9.9"); + }); + + test("leaves finishedAt undefined when absent", () => { + const item = new DomainMigrationListItem(buildDomainMigrationData()); + + expect(item.finishedAt).toBeUndefined(); + }); + + test("converts finishedAt to a Luxon DateTime", () => { + const item = new DomainMigrationListItem( + buildDomainMigrationData({ finishedAt: "2024-02-01T00:00:00.000Z" }), + ); + + expect(DateTime.isDateTime(item.finishedAt)).toBe(true); + expect(item.finishedAt?.toMillis()).toBe( + DateTime.fromISO("2024-02-01T00:00:00.000Z").toMillis(), + ); + }); +}); + +describe("DomainMigrationList", () => { + test("finds a succeeded migration domain", async () => { + const queryByProjectId = vi.fn().mockResolvedValue({ + items: [ + buildDomainMigrationData({ + domains: [ + buildDomainMigrationDomainData({ + state: "succeeded", + domain: "a.com", + }), + ], + }), + ], + totalCount: 1, + }); + installBehaviors({ domainMigration: { queryByProjectId } }); + const list = await DomainMigration.queryByProjectId("project-1").execute(); + + expect(list.findSucceededMigrationDomain("a.com")?.domain).toBe("a.com"); + expect(list.findSucceededMigrationDomain("a.com")?.state).toBe("succeeded"); + }); + + test("does not find a pending migration domain as succeeded", async () => { + const queryByProjectId = vi.fn().mockResolvedValue({ + items: [ + buildDomainMigrationData({ + domains: [ + buildDomainMigrationDomainData({ + state: "pending", + domain: "a.com", + }), + ], + }), + ], + totalCount: 1, + }); + installBehaviors({ domainMigration: { queryByProjectId } }); + const list = await DomainMigration.queryByProjectId("project-1").execute(); + + expect(list.findSucceededMigrationDomain("a.com")).toBeUndefined(); + }); + + test("does not find a failed migration domain as succeeded", async () => { + const queryByProjectId = vi.fn().mockResolvedValue({ + items: [ + buildDomainMigrationData({ + domains: [ + buildDomainMigrationDomainData({ + domain: "a.com", + state: "failed", + }), + ], + }), + ], + totalCount: 1, + }); + installBehaviors({ domainMigration: { queryByProjectId } }); + const list = await DomainMigration.queryByProjectId("project-1").execute(); + + expect(list.findSucceededMigrationDomain("a.com")).toBeUndefined(); + }); + + test("finds a succeeded retry after a failed migration", async () => { + const failed = buildDomainMigrationDomainData({ + domain: "a.com", + state: "failed", + }); + const succeeded = buildDomainMigrationDomainData({ + state: "succeeded", + domain: "a.com", + }); + const queryByProjectId = vi.fn().mockResolvedValue({ + items: [ + buildDomainMigrationData({ domains: [failed] }), + buildDomainMigrationData({ domains: [succeeded] }), + ], + totalCount: 2, + }); + installBehaviors({ domainMigration: { queryByProjectId } }); + const list = await DomainMigration.queryByProjectId("project-1").execute(); + + expect(list.findSucceededMigrationDomain("a.com")?.state).toBe("succeeded"); + }); + + test("does not find a migration domain that is absent", async () => { + const queryByProjectId = vi.fn().mockResolvedValue({ + items: [ + buildDomainMigrationData({ + domains: [ + buildDomainMigrationDomainData({ + state: "succeeded", + domain: "a.com", + }), + ], + }), + ], + totalCount: 1, + }); + installBehaviors({ domainMigration: { queryByProjectId } }); + const list = await DomainMigration.queryByProjectId("project-1").execute(); + + expect(list.findSucceededMigrationDomain("b.com")).toBeUndefined(); + }); + + test("detects pending migrations", async () => { + const queryByProjectId = vi + .fn() + .mockResolvedValueOnce({ + items: [buildDomainMigrationData({ finishedAt: undefined })], + totalCount: 1, + }) + .mockResolvedValueOnce({ + items: [ + buildDomainMigrationData({ + finishedAt: "2024-01-01T00:00:00.000Z", + }), + ], + totalCount: 1, + }); + installBehaviors({ domainMigration: { queryByProjectId } }); + + const pending = + await DomainMigration.queryByProjectId("project-1").execute(); + const finished = + await DomainMigration.queryByProjectId("project-1").execute(); + + expect(pending.hasPendingMigration()).toBe(true); + expect(finished.hasPendingMigration()).toBe(false); + }); + + test("returns the most recent finished migration", async () => { + const queryByProjectId = vi.fn().mockResolvedValue({ + items: [ + buildDomainMigrationData({ + finishedAt: "2024-03-01T00:00:00.000Z", + id: "later", + }), + buildDomainMigrationData({ + finishedAt: "2024-01-01T00:00:00.000Z", + id: "earlier", + }), + buildDomainMigrationData({ finishedAt: undefined, id: "unfinished" }), + ], + totalCount: 3, + }); + installBehaviors({ domainMigration: { queryByProjectId } }); + const list = await DomainMigration.queryByProjectId("project-1").execute(); + + expect(list.findMostRecentFinishedMigration()?.id).toBe("later"); + }); + + test("returns the most recent finished migration regardless of item order", async () => { + const queryByProjectId = vi.fn().mockResolvedValue({ + items: [ + buildDomainMigrationData({ + finishedAt: "2024-01-01T00:00:00.000Z", + id: "earlier", + }), + buildDomainMigrationData({ + finishedAt: "2024-03-01T00:00:00.000Z", + id: "later", + }), + buildDomainMigrationData({ finishedAt: undefined, id: "unfinished" }), + ], + totalCount: 3, + }); + installBehaviors({ domainMigration: { queryByProjectId } }); + const list = await DomainMigration.queryByProjectId("project-1").execute(); + + expect(list.findMostRecentFinishedMigration()?.id).toBe("later"); + }); + + test("finds a migration by domain", async () => { + const queryByProjectId = vi.fn().mockResolvedValue({ + items: [ + buildDomainMigrationData({ + domains: [buildDomainMigrationDomainData({ domain: "a.com" })], + id: "matching", + }), + ], + totalCount: 1, + }); + installBehaviors({ domainMigration: { queryByProjectId } }); + const list = await DomainMigration.queryByProjectId("project-1").execute(); + + expect(list.findMigrationByDomain("a.com")?.id).toBe("matching"); + expect(list.findMigrationByDomain("b.com")).toBeUndefined(); + }); +}); diff --git a/packages/models/src/domain/DomainMigration/DomainMigration.ts b/packages/models/src/domain/DomainMigration/DomainMigration.ts new file mode 100644 index 00000000..7fbefe37 --- /dev/null +++ b/packages/models/src/domain/DomainMigration/DomainMigration.ts @@ -0,0 +1,151 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; + +import type { + DomainMigrationListQueryData, + DomainMigrationListItemData, + DomainMigrationData, +} from "./types.js"; + +import { DomainMigrationDomain } from "../DomainMigrationDomain/index.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "DomainMigration", +}) +export class DomainMigration extends ReferenceModel { + public constructor(id: string) { + super(id); + } + + public static queryByProjectId = (projectId: string) => { + return new DomainMigrationListQuery(projectId); + }; +} + +export class DomainMigrationCommon extends WithData< + DomainMigrationListItemData | DomainMigrationData +>()(DomainMigration) { + public override readonly data: + DomainMigrationListItemData | DomainMigrationData; + public readonly domains: DomainMigrationDomain[]; + public readonly finishedAt?: DateTime; + public constructor(data: DomainMigrationListItemData | DomainMigrationData) { + super(data.id); + this.data = data; + this.domains = data.domains.map((i) => new DomainMigrationDomain(i)); + if (data.finishedAt) { + this.finishedAt = DateTime.fromISO(data.finishedAt); + } + } + + public findDomain(domain: string) { + return this.domains.find((d) => d.domain === domain); + } + + public findFirstARecord(): string | undefined { + const allARecords = this.domains + .flatMap((d) => d.dnsRecords) + .filter((r) => r.type === "A") + .map((i) => i.value); + + const uniqueRecords = [...new Set(allARecords)]; + return uniqueRecords[0]; + } + + public includesDomain(domain: string) { + return this.domains.some((d) => d.domain === domain); + } +} + +export class DomainMigrationListItem extends DomainMigrationCommon { + public override readonly data: DomainMigrationListItemData; + public constructor(data: DomainMigrationListItemData) { + super(data); + this.data = data; + } +} + +export class DomainMigrationListQuery extends ListQueryModel { + private readonly projectId: string; + + public constructor( + projectId: string, + query: DomainMigrationListQueryData = {}, + ) { + super(query); + this.projectId = projectId; + } + + public async execute() { + const { totalCount, items } = + await config.behaviors.domainMigration.queryByProjectId(this.projectId); + return new DomainMigrationList( + this.projectId, + this.query, + items.map((i) => new DomainMigrationListItem(i)), + totalCount, + ); + } +} + +export class DomainMigrationList extends WithListData()( + DomainMigrationListQuery, +) { + public override readonly items: readonly DomainMigrationListItem[]; + public override readonly totalCount: number; + public constructor( + projectId: string, + query: DomainMigrationListQueryData, + items: DomainMigrationListItem[], + totalCount: number, + ) { + super(projectId, query); + this.items = Object.freeze(items); + this.totalCount = totalCount; + } + + public findMigrationByDomain( + domain: string, + ): DomainMigrationListItem | undefined { + return this.items.find((i) => i.includesDomain(domain)); + } + + public findMostRecentFinishedMigration(): + DomainMigrationListItem | undefined { + let migration: DomainMigrationListItem | undefined = undefined; + + for (const i of this.items) { + if (!i.finishedAt) { + continue; + } + if (!migration || !migration.finishedAt) { + migration = i; + continue; + } + if (migration.finishedAt.diff(i.finishedAt).toMillis() < 0) { + migration = i; + } + } + + return migration; + } + + public findSucceededMigrationDomain( + domain: string, + ): DomainMigrationDomain | undefined { + return this.items + .flatMap((i) => i.domains) + .find((d) => d.domain === domain && d.state === "succeeded"); + } + + public hasPendingMigration() { + return this.items.some((i) => !i.finishedAt); + } +} diff --git a/packages/models/src/domain/DomainMigration/behaviors/api.ts b/packages/models/src/domain/DomainMigration/behaviors/api.ts new file mode 100644 index 00000000..84a475e8 --- /dev/null +++ b/packages/models/src/domain/DomainMigration/behaviors/api.ts @@ -0,0 +1,21 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { DomainMigrationBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount } from "../../../base/index.js"; +export const apiDomainMigrationBehavior = ( + client: MittwaldAPIV2Client, +): DomainMigrationBehaviors => ({ + queryByProjectId: async (projectId) => { + const response = await client.domain.migrationListMigrationsByProjectId({ + projectId, + }); + validateResponse(response, 200); + + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, +}); diff --git a/packages/models/src/domain/DomainMigration/behaviors/index.ts b/packages/models/src/domain/DomainMigration/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/domain/DomainMigration/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/domain/DomainMigration/behaviors/types.ts b/packages/models/src/domain/DomainMigration/behaviors/types.ts new file mode 100644 index 00000000..70c9fb02 --- /dev/null +++ b/packages/models/src/domain/DomainMigration/behaviors/types.ts @@ -0,0 +1,8 @@ +import type { DomainMigrationListItemData } from "../types.js"; +import type { QueryResponseData } from "../../../base/index.js"; + +export interface DomainMigrationBehaviors { + queryByProjectId: ( + projectId: string, + ) => Promise>; +} diff --git a/packages/models/src/domain/DomainMigration/index.ts b/packages/models/src/domain/DomainMigration/index.ts new file mode 100644 index 00000000..711794f1 --- /dev/null +++ b/packages/models/src/domain/DomainMigration/index.ts @@ -0,0 +1,2 @@ +export * from "./DomainMigration.js"; +export * from "./types.js"; diff --git a/packages/models/src/domain/DomainMigration/types.ts b/packages/models/src/domain/DomainMigration/types.ts new file mode 100644 index 00000000..7d5da0ce --- /dev/null +++ b/packages/models/src/domain/DomainMigration/types.ts @@ -0,0 +1,9 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type DomainMigrationData = + MittwaldAPIV2.Components.Schemas.DomainmigrationMigration; + +export type DomainMigrationListQueryData = + MittwaldAPIV2.Paths.V2ProjectsProjectIdDomainMigrations.Get.Parameters.Query; +export type DomainMigrationListItemData = + MittwaldAPIV2.Operations.DomainMigrationListMigrationsByProjectId.ResponseData[number]; diff --git a/packages/models/src/domain/DomainMigrationDnsRecord/DomainMigrationDnsRecord.test.ts b/packages/models/src/domain/DomainMigrationDnsRecord/DomainMigrationDnsRecord.test.ts new file mode 100644 index 00000000..b1a0e28d --- /dev/null +++ b/packages/models/src/domain/DomainMigrationDnsRecord/DomainMigrationDnsRecord.test.ts @@ -0,0 +1,25 @@ +import { afterEach, describe, expect, test } from "vitest"; + +import { buildDomainMigrationDnsRecordData } from "../../testing/builders/buildDomainMigrationDnsRecordData.js"; +import { DomainMigrationDnsRecord } from "./DomainMigrationDnsRecord.js"; +import { resetBehaviors } from "../../testing/installBehaviors.js"; +import { DataModel } from "../../base/index.js"; + +afterEach(resetBehaviors); + +describe("DomainMigrationDnsRecord", () => { + test("constructs from data and exposes its values", () => { + const data = buildDomainMigrationDnsRecordData({ + value: "2001:db8::1", + type: "AAAA", + ttl: 7200, + }); + const record = new DomainMigrationDnsRecord(data); + + expect(record).toBeInstanceOf(DomainMigrationDnsRecord); + expect(record).toBeInstanceOf(DataModel); + expect(record.type).toBe(data.type); + expect(record.value).toBe(data.value); + expect(record.ttl).toBe(data.ttl); + }); +}); diff --git a/packages/models/src/domain/DomainMigrationDnsRecord/DomainMigrationDnsRecord.ts b/packages/models/src/domain/DomainMigrationDnsRecord/DomainMigrationDnsRecord.ts new file mode 100644 index 00000000..9b6d1cd3 --- /dev/null +++ b/packages/models/src/domain/DomainMigrationDnsRecord/DomainMigrationDnsRecord.ts @@ -0,0 +1,18 @@ +import type { + DomainMigrationDnsRecordData, + DomainMigrationDnsRecordType, +} from "./types.js"; + +import { DataModel } from "../../base/index.js"; + +export class DomainMigrationDnsRecord extends DataModel { + public readonly ttl: number; + public readonly type: DomainMigrationDnsRecordType; + public readonly value: string; + public constructor(data: DomainMigrationDnsRecordData) { + super(data); + this.type = data.type; + this.value = data.value; + this.ttl = data.ttl; + } +} diff --git a/packages/models/src/domain/DomainMigrationDnsRecord/index.ts b/packages/models/src/domain/DomainMigrationDnsRecord/index.ts new file mode 100644 index 00000000..5db297ce --- /dev/null +++ b/packages/models/src/domain/DomainMigrationDnsRecord/index.ts @@ -0,0 +1,2 @@ +export * from "./DomainMigrationDnsRecord.js"; +export * from "./types.js"; diff --git a/packages/models/src/domain/DomainMigrationDnsRecord/types.ts b/packages/models/src/domain/DomainMigrationDnsRecord/types.ts new file mode 100644 index 00000000..55d06b56 --- /dev/null +++ b/packages/models/src/domain/DomainMigrationDnsRecord/types.ts @@ -0,0 +1,6 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type DomainMigrationDnsRecordData = + MittwaldAPIV2.Components.Schemas.DomainmigrationDNSRecord; +export type DomainMigrationDnsRecordType = + MittwaldAPIV2.Components.Schemas.DomainmigrationDNSRecordType; diff --git a/packages/models/src/domain/DomainMigrationDomain/DomainMigrationDomain.test.ts b/packages/models/src/domain/DomainMigrationDomain/DomainMigrationDomain.test.ts new file mode 100644 index 00000000..ea019dee --- /dev/null +++ b/packages/models/src/domain/DomainMigrationDomain/DomainMigrationDomain.test.ts @@ -0,0 +1,68 @@ +import { afterEach, describe, expect, test } from "vitest"; + +import { buildDomainMigrationDnsRecordData } from "../../testing/builders/buildDomainMigrationDnsRecordData.js"; +import { buildDomainMigrationDomainData } from "../../testing/builders/buildDomainMigrationDomainData.js"; +import { DomainMigrationDnsRecord } from "../DomainMigrationDnsRecord/index.js"; +import { resetBehaviors } from "../../testing/installBehaviors.js"; +import { DomainMigrationDomain } from "./DomainMigrationDomain.js"; + +afterEach(resetBehaviors); + +describe("DomainMigrationDomain", () => { + test("constructs from data", () => { + const data = buildDomainMigrationDomainData(); + const domain = new DomainMigrationDomain(data); + + expect(domain.domain).toBe(data.domain); + expect(domain.domainId).toBe(data.domainId); + expect(domain.state).toBe(data.state); + }); + + test("maps DNS data to DomainMigrationDnsRecord instances", () => { + const domain = new DomainMigrationDomain(buildDomainMigrationDomainData()); + + expect(domain.dnsRecords).toHaveLength(1); + expect(domain.dnsRecords[0]).toBeInstanceOf(DomainMigrationDnsRecord); + }); + + test("defaults DNS records to an empty array without coabData", () => { + const domain = new DomainMigrationDomain( + buildDomainMigrationDomainData({ coabData: undefined }), + ); + + expect(domain.dnsRecords).toEqual([]); + }); + + test("finds the first A record", () => { + const aRecord = buildDomainMigrationDnsRecordData({ + value: "9.9.9.9", + type: "A", + }); + const domain = new DomainMigrationDomain( + buildDomainMigrationDomainData({ + coabData: { + dnsRecords: [ + buildDomainMigrationDnsRecordData({ value: "text", type: "TXT" }), + aRecord, + ], + }, + }), + ); + + expect(domain.findFirstARecord()?.value).toBe(aRecord.value); + }); + + test("returns undefined without an A record", () => { + const domain = new DomainMigrationDomain( + buildDomainMigrationDomainData({ + coabData: { + dnsRecords: [ + buildDomainMigrationDnsRecordData({ value: "text", type: "TXT" }), + ], + }, + }), + ); + + expect(domain.findFirstARecord()).toBeUndefined(); + }); +}); diff --git a/packages/models/src/domain/DomainMigrationDomain/DomainMigrationDomain.ts b/packages/models/src/domain/DomainMigrationDomain/DomainMigrationDomain.ts new file mode 100644 index 00000000..7e7c165b --- /dev/null +++ b/packages/models/src/domain/DomainMigrationDomain/DomainMigrationDomain.ts @@ -0,0 +1,28 @@ +import type { + DomainMigrationDomainState, + DomainMigrationDomainData, +} from "./types.js"; + +import { DomainMigrationDnsRecord } from "../DomainMigrationDnsRecord/index.js"; +import { DataModel } from "../../base/index.js"; + +export class DomainMigrationDomain extends DataModel { + public readonly dnsRecords: DomainMigrationDnsRecord[]; + public readonly domain: string; + public readonly domainId: string; + public readonly state: DomainMigrationDomainState; + + public constructor(data: DomainMigrationDomainData) { + super(data); + this.domainId = data.domainId; + this.domain = data.domain; + this.state = data.state; + this.dnsRecords = (data.coabData?.dnsRecords ?? []).map( + (i) => new DomainMigrationDnsRecord(i), + ); + } + + public findFirstARecord() { + return this.dnsRecords.find((i) => i.type === "A"); + } +} diff --git a/packages/models/src/domain/DomainMigrationDomain/index.ts b/packages/models/src/domain/DomainMigrationDomain/index.ts new file mode 100644 index 00000000..67d70e64 --- /dev/null +++ b/packages/models/src/domain/DomainMigrationDomain/index.ts @@ -0,0 +1,2 @@ +export * from "./DomainMigrationDomain.js"; +export * from "./types.js"; diff --git a/packages/models/src/domain/DomainMigrationDomain/types.ts b/packages/models/src/domain/DomainMigrationDomain/types.ts new file mode 100644 index 00000000..a45cc81e --- /dev/null +++ b/packages/models/src/domain/DomainMigrationDomain/types.ts @@ -0,0 +1,5 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type DomainMigrationDomainData = + MittwaldAPIV2.Components.Schemas.DomainmigrationMigration["domains"][number]; +export type DomainMigrationDomainState = DomainMigrationDomainData["state"]; diff --git a/packages/models/src/domain/DomainProcess/DomainProcess.test.ts b/packages/models/src/domain/DomainProcess/DomainProcess.test.ts new file mode 100644 index 00000000..6018827a --- /dev/null +++ b/packages/models/src/domain/DomainProcess/DomainProcess.test.ts @@ -0,0 +1,45 @@ +import { afterEach, describe, expect, test } from "vitest"; +import { DateTime } from "luxon"; + +import { buildDomainProcessData } from "../../testing/builders/buildDomainProcessData.js"; +import { resetBehaviors } from "../../testing/installBehaviors.js"; +import { DomainProcess } from "./DomainProcess.js"; + +afterEach(resetBehaviors); + +describe("DomainProcess", () => { + test("constructs from data and exposes its values", () => { + const data = buildDomainProcessData({ + statusCode: "PROCESSING", + error: "Example error", + status: "processing", + }); + const process = new DomainProcess(data); + + expect(process.processType).toBe(data.processType); + expect(process.state).toBe(data.state); + expect(process.transactionId).toBe(data.transactionId); + expect(process.status).toBe(data.status); + expect(process.statusCode).toBe(data.statusCode); + expect(process.error).toBe(data.error); + }); + + test("leaves optional values undefined when omitted", () => { + const process = new DomainProcess(buildDomainProcessData()); + + expect(process.error).toBeUndefined(); + expect(process.status).toBeUndefined(); + expect(process.statusCode).toBeUndefined(); + }); + + test("converts lastUpdate to a Luxon DateTime", () => { + const data = buildDomainProcessData(); + const process = new DomainProcess(data); + + expect(DateTime.isDateTime(process.lastUpdate)).toBe(true); + expect(process.lastUpdate.isValid).toBe(true); + expect(process.lastUpdate.toMillis()).toBe( + DateTime.fromISO(data.lastUpdate).toMillis(), + ); + }); +}); diff --git a/packages/models/src/domain/DomainProcess/DomainProcess.ts b/packages/models/src/domain/DomainProcess/DomainProcess.ts new file mode 100644 index 00000000..d0327484 --- /dev/null +++ b/packages/models/src/domain/DomainProcess/DomainProcess.ts @@ -0,0 +1,25 @@ +import { DateTime } from "luxon"; + +import type { DomainProcessData, ProcessState, ProcessType } from "./types.js"; + +import { DataModel } from "../../base/index.js"; + +export class DomainProcess extends DataModel { + public readonly error?: string; + public readonly lastUpdate: DateTime; + public readonly processType: ProcessType; + public readonly state: ProcessState; + public readonly status?: string; + public readonly statusCode?: string; + public readonly transactionId: string; + public constructor(data: DomainProcessData) { + super(data); + this.error = data.error; + this.lastUpdate = DateTime.fromISO(data.lastUpdate); + this.processType = data.processType; + this.state = data.state; + this.status = data.status; + this.statusCode = data.statusCode; + this.transactionId = data.transactionId; + } +} diff --git a/packages/models/src/domain/DomainProcess/index.ts b/packages/models/src/domain/DomainProcess/index.ts new file mode 100644 index 00000000..4c6ea7df --- /dev/null +++ b/packages/models/src/domain/DomainProcess/index.ts @@ -0,0 +1,2 @@ +export * from "./DomainProcess.js"; +export * from "./types.js"; diff --git a/packages/models/src/domain/DomainProcess/types.ts b/packages/models/src/domain/DomainProcess/types.ts new file mode 100644 index 00000000..e367f0b3 --- /dev/null +++ b/packages/models/src/domain/DomainProcess/types.ts @@ -0,0 +1,7 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type DomainProcessData = MittwaldAPIV2.Components.Schemas.DomainProcess; + +export type ProcessType = MittwaldAPIV2.Components.Schemas.DomainProcessType; + +export type ProcessState = MittwaldAPIV2.Components.Schemas.DomainProcessState; diff --git a/packages/models/src/domain/Ingress/Ingress.ts b/packages/models/src/domain/Ingress/Ingress.ts deleted file mode 100644 index 74ab2227..00000000 --- a/packages/models/src/domain/Ingress/Ingress.ts +++ /dev/null @@ -1,170 +0,0 @@ -import { config } from "../../config/config.js"; -import { classes } from "polytype"; -import { DataModel } from "../../base/DataModel.js"; -import assertObjectFound from "../../base/assertObjectFound.js"; -import { ReferenceModel } from "../../base/ReferenceModel.js"; -import { - AsyncResourceVariant, - provideReact, -} from "../../react/provideReact.js"; -import { - IngressData, - IngressListItemData, - IngressListQueryData, - IngressListQueryModelData, -} from "./types.js"; -import { IngressPath } from "../IngressPath/IngressPath.js"; -import { ListQueryModel } from "../../base/ListQueryModel.js"; -import { ListDataModel } from "../../base/ListDataModel.js"; - -export class Ingress extends ReferenceModel { - public static ofId(id: string): Ingress { - return new Ingress(id); - } - - public static ofHostname(hostname: string): Ingress { - return Ingress.ofId(hostname); - } - - /** @deprecated: use query() or project.ingresses */ - public static list = provideReact( - async ( - query: IngressListQueryData = {}, - ): Promise>> => - new IngressListQuery(query).execute().then((r) => r.items), - ); - - public static find = provideReact( - async (id: string): Promise => { - const data = await config.behaviors.ingress.find(id); - if (data !== undefined) { - return new IngressDetailed(data); - } - }, - ); - - public static get = provideReact( - async (id: string): Promise => { - const ingress = await this.find(id); - assertObjectFound(ingress, this, id); - return ingress; - }, - ); - - public getDetailed = provideReact( - () => Ingress.get(this.id), - [this.id], - ) as AsyncResourceVariant<() => Promise>; - - public findDetailed = provideReact( - () => Ingress.find(this.id), - [this.id], - ) as AsyncResourceVariant<() => Promise>; -} - -export class IngressCommon extends classes( - DataModel, - Ingress, -) { - public readonly baseUrl: string; - public readonly paths: ReadonlyArray; - public readonly defaultPath: IngressPath; - - public constructor(data: IngressListItemData | IngressData) { - super([data], [data.id]); - this.baseUrl = `https://${data.hostname}`; - this.paths = Object.freeze(data.paths.map((p) => new IngressPath(this, p))); - - const defaultPath = this.paths.find((p) => p.path === "/"); - if (defaultPath === undefined) { - throw new Error(`Ingress ${this.describe()} has no default path.`); - } - this.defaultPath = defaultPath; - } -} - -export class IngressDetailed extends classes( - IngressCommon, - DataModel, -) { - public constructor(data: IngressData) { - super([data], [data]); - } -} - -export class IngressListItem extends classes( - IngressCommon, - DataModel, -) { - public constructor(data: IngressListItemData) { - super([data], [data]); - } -} - -export class IngressListQuery extends ListQueryModel { - public constructor(query: IngressListQueryModelData = {}) { - super(query); - } - - public refine(query: IngressListQueryModelData = {}) { - return new IngressListQuery({ - ...this.query, - ...query, - }); - } - - public execute = provideReact(async () => { - const { project, ...query } = this.query; - const { items, totalCount } = await config.behaviors.ingress.list({ - /** @todo: use this code when pagination is supported by API */ - // limit: config.defaultPaginationLimit, - ...query, - projectId: project?.id, - }); - - return new IngressList( - this.query, - items.map((d) => new IngressListItem(d)), - totalCount, - ); - }, [this.queryId]); - - public getTotalCount = provideReact(async () => { - /** @todo: use this code when pagination is supported by API */ - // const { totalCount } = await this.refine({ limit: 1 }).execute(); - // return totalCount; - const { items } = await this.refine({}).execute(); - return items.length; - }, [this.queryId]); - - public findOneAndOnly = provideReact(async () => { - /** @todo: use this code when pagination is supported by API */ - // const { items, totalCount } = await this.refine({ limit: 2 }).execute(); - // if (totalCount === 1) { - // return items[0]; - // } - const { items, totalCount } = await this.refine({}).execute(); - if (totalCount === 1) { - return items[0]; - } - }, [this.queryId]); -} - -export class IngressList extends classes( - IngressListQuery, - ListDataModel, -) { - public constructor( - query: IngressListQueryModelData, - ingresses: IngressListItem[], - totalCount: number, - ) { - super([query], [ingresses, totalCount]); - } - - public getDefault() { - const defaultIngress = this.items.find((i) => i.data.isDefault); - assertObjectFound(defaultIngress, IngressListItem, "IngressList"); - return defaultIngress; - } -} diff --git a/packages/models/src/domain/Ingress/behaviors/api.ts b/packages/models/src/domain/Ingress/behaviors/api.ts deleted file mode 100644 index f1f85c9b..00000000 --- a/packages/models/src/domain/Ingress/behaviors/api.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { assertStatus, MittwaldAPIV2Client } from "@mittwald/api-client"; -import { IngressBehaviors } from "./types.js"; -import { assertOneOfStatus } from "@mittwald/api-client"; - -export const apiIngressBehaviors = ( - client: MittwaldAPIV2Client, -): IngressBehaviors => ({ - find: async (id) => { - const response = await client.domain.ingressGetIngress({ - ingressId: id, - }); - - if (response.status === 200) { - return response.data; - } - assertOneOfStatus(response, [404]); - }, - - list: async (query = {}) => { - const response = await client.domain.ingressListIngresses({ - queryParameters: query, - }); - assertStatus(response, 200); - return { - items: response.data, - totalCount: response.data.length, - /** @todo: use this code when pagination is supported by API */ - // totalCount: extractTotalCountHeader(response), - }; - }, -}); diff --git a/packages/models/src/domain/Ingress/behaviors/types.ts b/packages/models/src/domain/Ingress/behaviors/types.ts deleted file mode 100644 index 0e64eece..00000000 --- a/packages/models/src/domain/Ingress/behaviors/types.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { - IngressListItemData, - IngressData, - IngressListQueryData, -} from "../types.js"; -import { QueryResponseData } from "../../../base/index.js"; - -export interface IngressBehaviors { - find: (id: string) => Promise; - list: ( - query?: IngressListQueryData, - ) => Promise>; -} diff --git a/packages/models/src/domain/Ingress/types.ts b/packages/models/src/domain/Ingress/types.ts deleted file mode 100644 index 6295e261..00000000 --- a/packages/models/src/domain/Ingress/types.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { MittwaldAPIV2 } from "@mittwald/api-client"; -import { Project } from "../../project/index.js"; - -export type IngressListQueryData = - MittwaldAPIV2.Paths.V2Ingresses.Get.Parameters.Query; - -export type IngressListQueryModelData = Omit< - IngressListQueryData, - "projectId" -> & { - project?: Project; -}; - -export type IngressData = - MittwaldAPIV2.Operations.IngressGetIngress.ResponseData; - -export type IngressListItemData = - MittwaldAPIV2.Operations.IngressListIngresses.ResponseData[number]; diff --git a/packages/models/src/domain/IngressPath/IngressPath.test.ts b/packages/models/src/domain/IngressPath/IngressPath.test.ts deleted file mode 100644 index f55461d2..00000000 --- a/packages/models/src/domain/IngressPath/IngressPath.test.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { IngressTargetData } from "../IngressTarget/index.js"; -import { IngressPath } from "./IngressPath.js"; -import { IngressData, IngressDetailed } from "../Ingress/index.js"; -import { IngressPathData } from "./types.js"; - -const ingressData: Partial = { - id: "abc", - paths: [], -}; - -const corruptIngressTargetData = {} as IngressTargetData; - -const ingressPathData: Partial = { - path: "/", - target: corruptIngressTargetData, -}; - -test("Creating IngressPath with corrupt IngressTarget throws error", () => { - expect(() => { - new IngressPath( - new IngressDetailed(ingressData as IngressData), - ingressPathData as IngressPathData, - ); - }).toThrow("Ingress IngressDetailed@abc has no default path."); -}); diff --git a/packages/models/src/domain/IngressPath/IngressPath.ts b/packages/models/src/domain/IngressPath/IngressPath.ts deleted file mode 100644 index 69732828..00000000 --- a/packages/models/src/domain/IngressPath/IngressPath.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { DataModel } from "../../base/DataModel.js"; -import { IngressPathData } from "./types.js"; -import { IngressCommon, Ingress } from "../Ingress/index.js"; -import { - IngressTarget, - ingressTargetFactory, -} from "../IngressTarget/IngressTarget.js"; - -export class IngressPath extends DataModel { - public readonly ingress: Ingress; - public readonly path: string; - public readonly url: URL; - public readonly target: IngressTarget; - - public constructor(ingress: IngressCommon, data: IngressPathData) { - super(data); - this.ingress = ingress; - this.path = data.path; - this.url = new URL(data.path, ingress.baseUrl); - this.target = ingressTargetFactory(this, data.target); - } -} diff --git a/packages/models/src/domain/Tld/Tld.test.ts b/packages/models/src/domain/Tld/Tld.test.ts new file mode 100644 index 00000000..fff9ac64 --- /dev/null +++ b/packages/models/src/domain/Tld/Tld.test.ts @@ -0,0 +1,136 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { buildTldData } from "../../testing/builders/buildTldData.js"; +import { ReferenceModel } from "../../base/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { TldDetailed, TldListItem, TldCommon, TldList, Tld } from "./Tld.js"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (t: unknown) => + typeof t === "function" ? (t as { name?: string }).name : undefined, +})); + +afterEach(resetBehaviors); + +describe("Tld", () => { + test("findCommon delegates to a detailed variant for a reference", async () => { + const query = vi.fn().mockResolvedValue({ + items: [buildTldData({ tld: "de" })], + totalCount: 1, + }); + installBehaviors({ tld: { query } }); + + const common = await Tld.ofTld("de").findCommon(); + + expect(common).toBeInstanceOf(TldCommon); + expect(query).toHaveBeenCalled(); + }); + + test("getCommon throws for a missing reference", async () => { + installBehaviors({ + tld: { + query: vi.fn().mockResolvedValue({ totalCount: 0, items: [] }), + }, + }); + + await expect(Tld.ofTld("de").getCommon()).rejects.toThrow(); + }); + + test("getCommon/findCommon are idempotent on materialized models", async () => { + const query = vi.fn(); + installBehaviors({ tld: { query } }); + const detailed = new TldDetailed(buildTldData()); + const item = new TldListItem(buildTldData()); + + expect(await detailed.getCommon()).toBe(detailed); + expect(await detailed.findCommon()).toBe(detailed); + expect(await item.getCommon()).toBe(item); + expect(await item.findCommon()).toBe(item); + expect(query).not.toHaveBeenCalled(); + }); + + test("find queries and returns the matching detailed TLD", async () => { + const query = vi.fn().mockResolvedValue({ + items: [buildTldData({ tld: "de" })], + totalCount: 1, + }); + installBehaviors({ tld: { query } }); + + const tld = await Tld.find("de"); + + expect(query).toHaveBeenCalledWith({}); + expect(tld).toBeInstanceOf(TldDetailed); + expect(tld?.id).toBe("de"); + expect(await Tld.find("com")).toBeUndefined(); + }); + + test("get throws when the TLD is missing", async () => { + const query = vi.fn().mockResolvedValue({ totalCount: 0, items: [] }); + installBehaviors({ tld: { query } }); + + await expect(Tld.get("missing")).rejects.toThrow(); + }); + + test("getContactSchemas delegates with the TLD id", async () => { + const schemas = { jsonSchemaOwnerC: {} }; + const getContactSchemas = vi.fn().mockResolvedValue(schemas); + installBehaviors({ tld: { getContactSchemas } }); + + const result = await Tld.ofTld("de").getContactSchemas(); + + expect(getContactSchemas).toHaveBeenCalledWith("de"); + expect(result).toBe(schemas); + }); + + test("query materializes pagination data and supports membership checks", async () => { + const query = vi.fn().mockResolvedValue({ + items: [buildTldData({ tld: "de" }), buildTldData({ tld: "com" })], + totalCount: 2, + }); + installBehaviors({ tld: { query } }); + + const list = await Tld.query().execute(); + + expect(query).toHaveBeenCalledWith({}); + expect(list).toBeInstanceOf(TldList); + expect(list.items).toHaveLength(2); + expect(list.items[0]).toBeInstanceOf(TldListItem); + expect(list.totalCount).toBe(2); + expect(list.includesTld("de")).toBe(true); + expect(list.includesTld("xyz")).toBe(false); + }); + + test("exposes derived TLD properties", () => { + const tld = new TldListItem( + buildTldData({ + transferAuthentication: "email", + rgpDays: 42, + tld: "com", + irtp: true, + }), + ); + + expect(tld.tld).toBe("com"); + expect(tld.irtp).toBe(true); + expect(tld.rgpDays).toBe(42); + expect(tld.transferAuthentication).toBe("email"); + }); + + test("preserves the ghostmaker identity chain", () => { + const tld = new TldListItem(buildTldData()); + + expect(tld).toBeInstanceOf(TldListItem); + expect(tld).toBeInstanceOf(TldCommon); + expect(tld).toBeInstanceOf(Tld); + expect(tld).toBeInstanceOf(ReferenceModel); + // ADR-0004: data is a capability mixin, not a nominal base — assert the + // observable payload instead of `instanceof DataModel`. + expect(tld.data).toBeDefined(); + }); +}); diff --git a/packages/models/src/domain/Tld/Tld.ts b/packages/models/src/domain/Tld/Tld.ts new file mode 100644 index 00000000..f770ad7d --- /dev/null +++ b/packages/models/src/domain/Tld/Tld.ts @@ -0,0 +1,140 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; + +import type { + TransferAuthenticationData, + TldListQueryData, + TldListItemData, + TldData, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "Tld", +}) +export class Tld extends ReferenceModel { + public static async find(tld: string) { + const data = await config.behaviors.tld.query({}); + const item = data.items.find((i) => i.tld === tld); + if (item) { + return new TldDetailed(item); + } + } + + public static async get(tld: string) { + const item = await Tld.find(tld); + assertObjectFound(item, Tld, tld); + return item; + } + + public static async getContactSchemasForTld(tld: string) { + return await config.behaviors.tld.getContactSchemas(tld); + } + + public static ofTld(tld: string) { + return new Tld(tld); + } + + public static query = (query: TldListQueryData = {}) => { + return new TldListQuery(query); + }; + + public async findCommon(): Promise { + return this instanceof TldCommon ? this : this.findDetailed(); + } + + public async findDetailed(): Promise { + return Tld.find(this.id); + } + + public async getCommon(): Promise { + return this instanceof TldCommon ? this : this.getDetailed(); + } + + public async getContactSchemas() { + return await config.behaviors.tld.getContactSchemas(this.id); + } + + public async getDetailed(): Promise { + return Tld.get(this.id); + } +} + +export class TldCommon extends WithData()(Tld) { + public override readonly data: TldData; + public readonly irtp: boolean; + public readonly rgpDays: number; + public readonly tld: string; + public readonly transferAuthentication: TransferAuthenticationData; + public constructor(data: TldData) { + super(data.tld); + this.data = data; + this.tld = data.tld; + this.irtp = data.irtp; + this.rgpDays = data.rgpDays; + this.transferAuthentication = data.transferAuthentication; + } +} + +export class TldDetailed extends TldCommon { + public constructor(data: TldData) { + super(data); + } +} + +export class TldListItem extends TldCommon { + public constructor(data: TldListItemData) { + super(data); + } +} + +export class TldListQuery extends ListQueryModel { + public constructor(query: TldListQueryData = {}) { + super(query); + } + + public async execute() { + const { ...query } = this.query; + const { totalCount, items } = await config.behaviors.tld.query({ + ...query, + }); + + return new TldList( + this.query, + items.map((t) => new TldListItem(t)), + totalCount, + ); + } + + public refine(query: TldListQueryData) { + return new TldListQuery({ + ...this.query, + ...query, + }); + } +} + +export class TldList extends WithListData()(TldListQuery) { + public override readonly items: readonly TldListItem[]; + public override readonly totalCount: number; + public constructor( + data: TldListQueryData, + tlds: TldListItem[], + totalCount: number, + ) { + super(data); + this.items = Object.freeze(tlds); + this.totalCount = totalCount; + } + + public includesTld(tld: string) { + return this.items.some((i) => i.tld === tld); + } +} diff --git a/packages/models/src/domain/Tld/TldPrice.ts b/packages/models/src/domain/Tld/TldPrice.ts new file mode 100644 index 00000000..67c92dda --- /dev/null +++ b/packages/models/src/domain/Tld/TldPrice.ts @@ -0,0 +1,131 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; + +import type { TldPriceListQueryData, TldPriceData } from "./types.js"; + +import { config } from "../../config/index.js"; +import { Money } from "../../common/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "TldPrice", +}) +export class TldPrice extends ReferenceModel { + public static query = (query: TldPriceListQueryData = {}) => { + return new TldPriceListQuery(query); + }; +} + +export class TldPriceListQuery extends ListQueryModel { + public constructor(query: TldPriceListQueryData = {}) { + super(query); + } + + public async execute() { + const { ...query } = this.query; + const { totalCount, items } = await config.behaviors.tld.queryPrices({ + ...query, + }); + + return new TldPriceList( + this.query, + items.map((t) => new TldPriceListItem(t)), + totalCount, + ); + } +} + +export class TldPriceCommon extends WithData()(TldPrice) { + public readonly contractDurationInMonth: number; + public override readonly data: TldPriceData; + public readonly description?: string; + public readonly name?: string; + public readonly price?: Money; + public readonly tld: string; + public constructor(data: TldPriceData) { + super(data.articleId); + this.data = data; + + const topLevelAttr = ( + data.attributes as { value: string; key: string }[] | undefined + )?.find((a) => a.key === "toplevel"); + + this.tld = topLevelAttr?.value ?? ""; + if (data.price) { + this.price = Money({ amount: data.price, currency: "EUR" }); + } + this.name = data.name; + this.description = data.description; + this.contractDurationInMonth = data.contractDurationInMonth; + } +} + +export class TldPriceListItem extends TldPriceCommon { + public constructor(data: TldPriceData) { + super(data); + } +} + +export class TldPriceList extends WithListData()( + TldPriceListQuery, +) { + private static readonly SORTED_PRIO_TLDS = [ + "de", + "com", + "at", + "eu", + "net", + "info", + "org", + "ch", + "biz", + "shop", + ]; + public override readonly items: readonly TldPriceListItem[]; + public override readonly totalCount: number; + + public constructor( + data: TldPriceListQueryData, + tlds: TldPriceListItem[], + totalCount: number, + ) { + super(data); + this.items = Object.freeze(tlds); + this.totalCount = totalCount; + } + + public readonly findByTld = (tld: string) => { + if (tld === "") { + return undefined; + } + return this.items.find((i) => i.tld === tld); + }; + + public readonly sort = () => { + const sortedItems = [...this.items].sort((left, right) => { + const leftIndex = TldPriceList.SORTED_PRIO_TLDS.indexOf(left.tld ?? ""); + const rightIndex = TldPriceList.SORTED_PRIO_TLDS.indexOf(right.tld ?? ""); + + const leftIsPrio = leftIndex !== -1; + const rightIsPrio = rightIndex !== -1; + + // Priority TLDs first + if (leftIsPrio && !rightIsPrio) return -1; + if (!leftIsPrio && rightIsPrio) return 1; + + // Priority: sort by priority order + if (leftIsPrio && rightIsPrio) return leftIndex - rightIndex; + + // Non-priority: sort alphabetically + const leftTld = left.tld ?? ""; + const rightTld = right.tld ?? ""; + return leftTld.localeCompare(rightTld); + }); + + return new TldPriceList(this.query, sortedItems, this.totalCount); + }; +} diff --git a/packages/models/src/domain/Tld/behaviors/api.ts b/packages/models/src/domain/Tld/behaviors/api.ts new file mode 100644 index 00000000..9ec25c90 --- /dev/null +++ b/packages/models/src/domain/Tld/behaviors/api.ts @@ -0,0 +1,41 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; +import type { Schema as SchemaObject } from "jsonschema"; + +import type { TldBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount } from "../../../base/index.js"; + +export const apiTldBehaviors = (client: MittwaldAPIV2Client): TldBehaviors => ({ + getContactSchemas: async (tld) => { + const response = await client.domain.listTldContactSchemas({ tld }); + validateResponse(response, 200); + const { jsonSchemaOwnerC, jsonSchemaAdminC } = response.data; + return { + jsonSchemaAdminC: jsonSchemaAdminC as SchemaObject | undefined, + jsonSchemaOwnerC: jsonSchemaOwnerC as SchemaObject, + }; + }, + queryPrices: async () => { + const response = await client.article.listArticles({ + queryParameters: { + templateNames: ["domain"], + orderable: ["full"], + limit: 2000, + }, + }); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + query: async () => { + const response = await client.domain.listTlds(); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, +}); diff --git a/packages/models/src/domain/Tld/behaviors/index.ts b/packages/models/src/domain/Tld/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/domain/Tld/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/domain/Tld/behaviors/types.ts b/packages/models/src/domain/Tld/behaviors/types.ts new file mode 100644 index 00000000..974552e9 --- /dev/null +++ b/packages/models/src/domain/Tld/behaviors/types.ts @@ -0,0 +1,18 @@ +import type { QueryResponseData } from "../../../base/index.js"; +import type { + TldPriceListQueryData, + TldPriceListItemData, + TldContactSchemas, + TldListQueryData, + TldListItemData, +} from "../types.js"; + +export interface TldBehaviors { + queryPrices: ( + query?: TldPriceListQueryData, + ) => Promise>; + query: ( + query?: TldListQueryData, + ) => Promise>; + getContactSchemas: (tld: string) => Promise; +} diff --git a/packages/models/src/domain/Tld/index.ts b/packages/models/src/domain/Tld/index.ts new file mode 100644 index 00000000..f970627b --- /dev/null +++ b/packages/models/src/domain/Tld/index.ts @@ -0,0 +1,3 @@ +export * from "./Tld.js"; +export * from "./TldPrice.js"; +export * from "./types.js"; diff --git a/packages/models/src/domain/Tld/types.ts b/packages/models/src/domain/Tld/types.ts new file mode 100644 index 00000000..e9701800 --- /dev/null +++ b/packages/models/src/domain/Tld/types.ts @@ -0,0 +1,27 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; +import type { Schema as SchemaObject } from "jsonschema"; + +export type TldData = MittwaldAPIV2.Components.Schemas.DomainTopLevel; + +export type TldListItemData = + MittwaldAPIV2.Operations.DomainListTlds.ResponseData[number]; + +export type TldListQueryData = + MittwaldAPIV2.Paths.V2DomainTlds.Get.Parameters.Query; + +export type TldPriceData = + MittwaldAPIV2.Components.Schemas.ArticleReadableArticle; + +export type TldPriceListItemData = + MittwaldAPIV2.Operations.ArticleListArticles.ResponseData[number]; + +export type TldPriceListQueryData = + MittwaldAPIV2.Paths.V2Articles.Get.Parameters.Query; + +export type TransferAuthenticationData = + MittwaldAPIV2.Components.Schemas.DomainTransferAuthentication; + +export interface TldContactSchemas { + jsonSchemaAdminC?: SchemaObject; + jsonSchemaOwnerC: SchemaObject; +} diff --git a/packages/models/src/domain/index.ts b/packages/models/src/domain/index.ts index b92ce4b7..e8a09aa5 100644 --- a/packages/models/src/domain/index.ts +++ b/packages/models/src/domain/index.ts @@ -1 +1,10 @@ -export * from "./Ingress/index.js"; +export * from "./ContactVerification/index.js"; +export * from "./ContactVerificationTypeData/index.js"; +export * from "./Domain/index.js"; +export * from "./DomainHandle/index.js"; +export * from "./DomainHandleReadable/index.js"; +export * from "./DomainMigration/index.js"; +export * from "./DomainMigrationDnsRecord/index.js"; +export * from "./DomainMigrationDomain/index.js"; +export * from "./DomainProcess/index.js"; +export * from "./Tld/index.js"; diff --git a/packages/models/src/errors/FileUploadError.ts b/packages/models/src/errors/FileUploadError.ts new file mode 100644 index 00000000..6d812aa4 --- /dev/null +++ b/packages/models/src/errors/FileUploadError.ts @@ -0,0 +1,14 @@ +import type { DomFile } from "../file/index.js"; + +export interface FileUploadFailure { + error: unknown; + file: DomFile; +} + +export class FileUploadError { + public readonly failures: FileUploadFailure[]; + + public constructor(failures: FileUploadFailure[]) { + this.failures = failures; + } +} diff --git a/packages/models/src/errors/ObjectNotFoundError.ts b/packages/models/src/errors/ObjectNotFoundError.ts index 56b0b344..81c9ac63 100644 --- a/packages/models/src/errors/ObjectNotFoundError.ts +++ b/packages/models/src/errors/ObjectNotFoundError.ts @@ -1,7 +1,22 @@ -export default class ObjectNotFoundError extends Error { - public constructor(type: string, refName: string) { - super(`${type}@${refName} not found`); +import type { Class } from "type-fest"; + +import { getModelName } from "@mittwald/react-ghostmaker/model"; + +export class ObjectNotFoundError extends Error { + public readonly refName: string; + public readonly type: string; + + public constructor(type: Class, refName: string) { + const typeString = + typeof type === "string" ? type : (getModelName(type) ?? "UnknownType"); + + super(`${typeString}@${refName} not found`); this.name = "ObjectNotFoundError"; + this.type = typeString; + this.refName = refName; + Object.setPrototypeOf(this, ObjectNotFoundError.prototype); } } + +export default ObjectNotFoundError; diff --git a/packages/models/src/errors/ValidationError/ValidationError.ts b/packages/models/src/errors/ValidationError/ValidationError.ts new file mode 100644 index 00000000..17fcfd10 --- /dev/null +++ b/packages/models/src/errors/ValidationError/ValidationError.ts @@ -0,0 +1,57 @@ +import type { ApiClientResponse } from "../../base/index.js"; + +import { performMappings } from "./mapping/performMappings.js"; +import { + type ValidationErrorFromApiResponseOptions, + type ValidationErrorObjectApiData, + type ValidationErrorObject, + isValidationErrorsApiData, +} from "./types.js"; + +export class ValidationError { + public readonly errors: ValidationErrorObject[] = []; + + public constructor(errors: ValidationErrorObject[] | ValidationErrorObject) { + this.errors = Array.isArray(errors) ? errors : [errors]; + } + + public static fromResponse( + response: ApiClientResponse, + options: ValidationErrorFromApiResponseOptions = {}, + ): ValidationError | undefined { + if (response.status < 400 || !isValidationErrorsApiData(response.data)) { + return; + } + + const { pathMappings = {}, typeMappings = {} } = options; + + const errors = response.data.validationErrors + .map(this.mapValidationErrorObject) + .flatMap((errorObject) => + performMappings(errorObject, { + mappings: pathMappings, + property: "path", + }).flatMap((errorObject) => + performMappings(errorObject, { + mappings: typeMappings, + property: "type", + }), + ), + ) + .filter((e) => !!e); + + return new ValidationError(errors); + } + + private static mapValidationErrorObject( + data: ValidationErrorObjectApiData, + ): ValidationErrorObject { + // map context to params for better compatibility with existing ValidationErrorObject + const { context, ...restData } = data; + + return { + ...restData, + params: context, + }; + } +} diff --git a/packages/models/src/errors/ValidationError/index.ts b/packages/models/src/errors/ValidationError/index.ts new file mode 100644 index 00000000..617c7bca --- /dev/null +++ b/packages/models/src/errors/ValidationError/index.ts @@ -0,0 +1,2 @@ +export * from "./types.js"; +export * from "./ValidationError.js"; diff --git a/packages/models/src/errors/ValidationError/mapping/performMappings.ts b/packages/models/src/errors/ValidationError/mapping/performMappings.ts new file mode 100644 index 00000000..dadde500 --- /dev/null +++ b/packages/models/src/errors/ValidationError/mapping/performMappings.ts @@ -0,0 +1,42 @@ +import { minimatch } from "minimatch"; + +import type { ValidationErrorMapping, MappingReturn } from "./types.js"; + +interface Options { + mappings: ValidationErrorMapping; + property: keyof T; +} + +export const performMappings = (source: T, options: Options) => { + const { property, mappings } = options; + + let mappedValue: MappingReturn | undefined; + + for (const [key, val] of Object.entries(mappings)) { + if (mappedValue) { + break; + } + const sourceValue = String(source[property]); + const matching = minimatch(sourceValue, key); + if (matching) { + if (typeof val === "function") { + mappedValue = val(source); + } else { + mappedValue = val; + } + } + } + + if (mappedValue) { + const mappedValueList = Array.isArray(mappedValue) + ? mappedValue + : [mappedValue]; + + return mappedValueList.map((mappedProperty) => ({ + ...source, + [property]: mappedProperty, + })); + } + + return [source]; +}; diff --git a/packages/models/src/errors/ValidationError/mapping/types.ts b/packages/models/src/errors/ValidationError/mapping/types.ts new file mode 100644 index 00000000..603d530c --- /dev/null +++ b/packages/models/src/errors/ValidationError/mapping/types.ts @@ -0,0 +1,6 @@ +export type MappingReturn = string[] | string; + +export type ValidationErrorMapping = Record< + string, + ((error: T) => MappingReturn | undefined) | MappingReturn +>; diff --git a/packages/models/src/errors/ValidationError/types.ts b/packages/models/src/errors/ValidationError/types.ts new file mode 100644 index 00000000..85fb1d5f --- /dev/null +++ b/packages/models/src/errors/ValidationError/types.ts @@ -0,0 +1,43 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import type { ValidationErrorMapping } from "./mapping/types.js"; + +export type ErrorApiData = MittwaldAPIV2.Components.Schemas.CommonsError; + +type ValidationErrorParams = Record; +type ValidationErrorMeta = Record; + +// @todo: use enum with only allowed types +type ValidationErrorType = string; + +export type ValidationErrorObjectApiData = + MittwaldAPIV2.Components.Schemas.CommonsValidationErrorSchema; + +export type ValidationErrorsApiData = + MittwaldAPIV2.Components.Schemas.CommonsValidationErrors; + +export interface ValidationErrorObject { + params?: ValidationErrorParams; + meta?: ValidationErrorMeta; + type: ValidationErrorType; + message?: string; + path: string; +} + +export const isValidationErrorsApiData = ( + data: unknown, +): data is ValidationErrorsApiData => { + return ( + typeof data === "object" && + data !== null && + "validationErrors" in data && + Array.isArray(data.validationErrors) && + "type" in data && + data.type === "ValidationError" + ); +}; + +export interface ValidationErrorFromApiResponseOptions { + pathMappings?: ValidationErrorMapping; + typeMappings?: ValidationErrorMapping; +} diff --git a/packages/models/src/errors/index.ts b/packages/models/src/errors/index.ts new file mode 100644 index 00000000..27a157bb --- /dev/null +++ b/packages/models/src/errors/index.ts @@ -0,0 +1,3 @@ +export * from "./FileUploadError.js"; +export * from "./ObjectNotFoundError.js"; +export * from "./ValidationError/index.js"; diff --git a/packages/models/src/file/File/File.test.ts b/packages/models/src/file/File/File.test.ts new file mode 100644 index 00000000..72eed17c --- /dev/null +++ b/packages/models/src/file/File/File.test.ts @@ -0,0 +1,314 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { buildFileDownloadTokenData } from "../../testing/builders/buildFileDownloadTokenData.js"; +import { buildFileUploadRulesData } from "../../testing/builders/buildFileUploadRulesData.js"; +import { buildFileUploadTokenData } from "../../testing/builders/buildFileUploadTokenData.js"; +import { buildFileMetaData } from "../../testing/builders/buildFileMetaData.js"; +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { FileDownloadToken } from "../FileAccessToken/index.js"; +import { ReferenceModel } from "../../base/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { Bytes } from "../../common/index.js"; +import { + FileContentDetailed, + FileMetaDetailed, + FileContent, + FileMeta, + File, +} from "./internal.js"; + +afterEach(resetBehaviors); + +describe("File", () => { + test("constructs its metadata and content references", () => { + const file = File.ofId("f-1"); + + expect(file.id).toBe("f-1"); + expect(file.metaData).toBeInstanceOf(FileMeta); + expect(file.content).toBeInstanceOf(FileContent); + }); + + test("reports whether it is protected", () => { + expect(File.ofId("f-1").isProtected).toBe(false); + expect( + File.ofId("f-1", { + getDownloadToken: vi + .fn() + .mockResolvedValue(buildFileDownloadTokenData()), + }).isProtected, + ).toBe(true); + }); + + test("identifies and guards the in-memory file", () => { + expect(File.inMemoryFile.isInMemoryFile).toBe(true); + expect(File.ofId("f-1").isInMemoryFile).toBe(false); + expect(() => File.inMemoryFile.assertNotInMemoryFile()).toThrow(); + }); + + test("builds the public URL", () => { + const buildUrl = vi.fn().mockReturnValue("https://x/f-1"); + installBehaviors({ file: { buildUrl } }); + + expect(File.ofId("f-1").url).toBe("https://x/f-1"); + expect(buildUrl).toHaveBeenCalledWith("f-1"); + }); + + test("does not expose a direct URL for protected or in-memory files", () => { + const protectedFile = File.ofId("f-1", { + getDownloadToken: vi.fn().mockResolvedValue(buildFileDownloadTokenData()), + }); + + expect(() => protectedFile.url).toThrow(); + expect(() => File.inMemoryFile.url).toThrow(); + }); + + test("builds download link props with an access token", async () => { + const tokenData = buildFileDownloadTokenData({ accessToken: "tok" }); + const getDownloadToken = vi.fn().mockResolvedValue(tokenData); + const findMetaData = vi + .fn() + .mockResolvedValue(buildFileMetaData({ name: "report.txt", id: "f-1" })); + const buildUrl = vi.fn().mockReturnValue("https://x/f-1"); + installBehaviors({ file: { findMetaData, buildUrl } }); + + const result = await File.ofId("f-1", { + getDownloadToken, + }).getFileLinkProps(); + + expect(result).toEqual({ + download: "report.txt", + href: "https://x/f-1", + target: "_blank", + token: "tok", + }); + expect(getDownloadToken).toHaveBeenCalledWith("f-1", undefined); + expect(findMetaData).toHaveBeenCalledWith("f-1", "tok", undefined); + expect(buildUrl).toHaveBeenCalledWith("f-1", "report.txt", "tok"); + }); + + test("finds a download token when a provider is available", async () => { + const getDownloadToken = vi + .fn() + .mockResolvedValue(buildFileDownloadTokenData({ accessToken: "tok" })); + + const token = await File.ofId("f-1", { + getDownloadToken, + }).findDownloadToken(); + + expect(token).toBeInstanceOf(FileDownloadToken); + expect(token?.token).toBe("tok"); + expect(getDownloadToken).toHaveBeenCalledWith("f-1", undefined); + }); + + test("does not find a download token without a provider", async () => { + await expect(File.ofId("f-1").findDownloadToken()).resolves.toBeUndefined(); + }); + + test("uploads a file with a regular upload token", async () => { + const tokenData = buildFileUploadTokenData({ token: "up-token" }); + const createUploadToken = vi.fn().mockResolvedValue(tokenData); + const upload = vi.fn().mockResolvedValue(buildFileMetaData({ id: "up-1" })); + installBehaviors({ file: { upload } }); + const domFile = new globalThis.File(["data"], "test.txt"); + + const result = await File.upload(domFile, { createUploadToken }); + + expect(result).toBeInstanceOf(FileMetaDetailed); + expect(result.id).toBe("up-1"); + expect(createUploadToken).toHaveBeenCalledWith(); + expect(upload).toHaveBeenCalledWith(domFile, "up-token", undefined); + }); + + test("uploads an image with an asset upload token", async () => { + const createAssetUploadToken = vi + .fn() + .mockResolvedValue(buildFileUploadTokenData({ token: "asset-token" })); + const upload = vi + .fn() + .mockResolvedValue(buildFileMetaData({ id: "asset-1" })); + installBehaviors({ file: { upload } }); + const domFile = new globalThis.File(["image"], "image.png"); + + const result = await File.upload( + domFile, + { createAssetUploadToken }, + "image", + ); + + expect(result).toBeInstanceOf(FileMetaDetailed); + expect(result.id).toBe("asset-1"); + expect(createAssetUploadToken).toHaveBeenCalledWith("image"); + expect(upload).toHaveBeenCalledWith(domFile, "asset-token", undefined); + }); + + test("adds a Bytes value to upload rules", async () => { + const getUploadRules = vi + .fn() + .mockResolvedValue(buildFileUploadRulesData({ maxSizeInBytes: 1_024 })); + installBehaviors({ file: { getUploadRules } }); + + const result = await File.getUploadRules("avatar"); + + expect(result.maxSize).toBeInstanceOf(Bytes); + expect(result.maxSize.value).toBe(1_024); + expect(getUploadRules).toHaveBeenCalledWith("avatar"); + }); +}); + +describe("FileMeta", () => { + test("finds detailed metadata and exposes derived fields", async () => { + const data = buildFileMetaData({ + mimeType: "image/jpeg", + name: "photo.jpg", + }); + const findMetaData = vi.fn().mockResolvedValue(data); + installBehaviors({ file: { findMetaData } }); + + const result = await FileMeta.find(File.ofId("f-1")); + + expect(result).toBeInstanceOf(FileMetaDetailed); + expect(result?.name).toBe("photo.jpg"); + expect(result?.mimeType).toBe("image/jpeg"); + expect(findMetaData).toHaveBeenCalledWith("f-1", undefined, undefined); + }); + + test("returns undefined when metadata is not found", async () => { + const findMetaData = vi.fn().mockResolvedValue(undefined); + installBehaviors({ file: { findMetaData } }); + + await expect(FileMeta.find(File.ofId("missing"))).resolves.toBeUndefined(); + }); + + test("throws ObjectNotFoundError when metadata is not found", async () => { + const findMetaData = vi.fn().mockResolvedValue(undefined); + installBehaviors({ file: { findMetaData } }); + + await expect(FileMeta.get(File.ofId("missing"))).rejects.toThrow( + ObjectNotFoundError, + ); + }); + + test("preserves all model identities and returns itself as common metadata", async () => { + const detailed = new FileMetaDetailed( + File.ofId("f-1"), + buildFileMetaData({ id: "f-1" }), + ); + + expect(detailed).toBeInstanceOf(FileMeta); + expect(detailed).toBeInstanceOf(ReferenceModel); + expect(detailed.data).toBeDefined(); + await expect(detailed.findCommon()).resolves.toBe(detailed); + await expect(detailed.getCommon()).resolves.toBe(detailed); + }); + + test("findCommon delegates to a detailed lookup for reference metadata", async () => { + const findMetaData = vi + .fn() + .mockResolvedValue(buildFileMetaData({ name: "doc.txt", id: "f-1" })); + installBehaviors({ file: { findMetaData } }); + + const result = await File.ofId("f-1").metaData.findCommon(); + + expect(result).toBeInstanceOf(FileMetaDetailed); + expect(result?.name).toBe("doc.txt"); + expect(findMetaData).toHaveBeenCalledWith("f-1", undefined, undefined); + }); + + test("findCommon resolves undefined when reference metadata is not found", async () => { + const findMetaData = vi.fn().mockResolvedValue(undefined); + installBehaviors({ file: { findMetaData } }); + + await expect( + File.ofId("missing").metaData.findCommon(), + ).resolves.toBeUndefined(); + }); + + test("getCommon delegates to a detailed lookup for reference metadata", async () => { + const findMetaData = vi + .fn() + .mockResolvedValue(buildFileMetaData({ id: "f-1" })); + installBehaviors({ file: { findMetaData } }); + + const result = await File.ofId("f-1").metaData.getCommon(); + + expect(result).toBeInstanceOf(FileMetaDetailed); + expect(findMetaData).toHaveBeenCalledWith("f-1", undefined, undefined); + }); + + test("getCommon throws ObjectNotFoundError when reference metadata is not found", async () => { + const findMetaData = vi.fn().mockResolvedValue(undefined); + installBehaviors({ file: { findMetaData } }); + + await expect(File.ofId("missing").metaData.getCommon()).rejects.toThrow( + ObjectNotFoundError, + ); + }); + + test("does not re-fetch when common variants are requested on already-detailed metadata", async () => { + const findMetaData = vi.fn().mockResolvedValue(buildFileMetaData()); + installBehaviors({ file: { findMetaData } }); + + const detailed = new FileMetaDetailed( + File.ofId("f-1"), + buildFileMetaData({ id: "f-1" }), + ); + + await expect(detailed.findCommon()).resolves.toBe(detailed); + await expect(detailed.getCommon()).resolves.toBe(detailed); + expect(findMetaData).not.toHaveBeenCalled(); + }); + + test("falls back to the deprecated type field when mimeType is absent", () => { + const detailed = new FileMetaDetailed( + File.ofId("f-1"), + buildFileMetaData({ type: "application/pdf", mimeType: undefined }), + ); + + expect(detailed.mimeType).toBe("application/pdf"); + }); +}); + +describe("FileContent", () => { + test("creates detailed content from base64", () => { + const result = FileContent.ofBase64({ + base64: btoa("hello"), + type: "text/plain", + name: "h.txt", + }); + + expect(result).toBeInstanceOf(FileContentDetailed); + expect(result.name).toBe("h.txt"); + expect(result.blob).toBeInstanceOf(Blob); + expect(result.objectUrl).toEqual(expect.any(String)); + expect(result.data).toBeInstanceOf(globalThis.File); + expect(result.data.name).toBe("h.txt"); + }); + + test("downloads detailed content using its metadata", async () => { + const findMetaData = vi + .fn() + .mockResolvedValue(buildFileMetaData({ name: "data.txt" })); + const buffer = new TextEncoder().encode("data").buffer; + const download = vi.fn().mockResolvedValue(buffer); + installBehaviors({ file: { findMetaData, download } }); + + const result = await FileContent.get(File.ofId("f-1")); + + expect(result).toBeInstanceOf(FileContentDetailed); + expect(result.name).toBe("data.txt"); + expect(result.blob).toBeInstanceOf(Blob); + expect(findMetaData).toHaveBeenCalledWith("f-1", undefined, undefined); + expect(download).toHaveBeenCalledWith("f-1", undefined); + }); +}); diff --git a/packages/models/src/file/File/File.ts b/packages/models/src/file/File/File.ts new file mode 100644 index 00000000..69271de2 --- /dev/null +++ b/packages/models/src/file/File/File.ts @@ -0,0 +1,122 @@ +import type { AxiosRequestConfig } from "axios"; + +import invariant from "tiny-invariant"; + +import type { FileAccessTokenProvider } from "../FileAccessToken/index.js"; +import type { FileUploadType, DomFile } from "./types.js"; + +import { FileMetaDetailed, FileContent, FileMeta } from "./internal.js"; +import { FileDownloadToken } from "../FileAccessToken/index.js"; +import { ReferenceModel } from "../../base/index.js"; +import { config } from "../../config/index.js"; +import { Bytes } from "../../common/index.js"; + +export class File extends ReferenceModel { + public static inMemoryFile = new File("inmem"); + public readonly accessTokenProvider?: FileAccessTokenProvider; + public readonly content: FileContent; + public readonly metaData: FileMeta; + + public get isInMemoryFile() { + return this === File.inMemoryFile; + } + + public get isProtected() { + return !!this.accessTokenProvider?.getDownloadToken; + } + + public get url() { + invariant( + !this.isProtected, + "This file is protected. Use getProtectedUrl().", + ); + this.assertNotInMemoryFile(); + return config.behaviors.file.buildUrl(this.id); + } + + public constructor( + id: string, + accessTokenProvider?: FileAccessTokenProvider, + ) { + super(id); + this.metaData = FileMeta.ofFile(this); + this.content = FileContent.ofFile(this); + this.accessTokenProvider = accessTokenProvider; + } + + public static async getUploadRules(type: FileUploadType) { + const rules = await config.behaviors.file.getUploadRules(type); + + return { ...rules, maxSize: Bytes.of(rules.maxSizeInBytes, "bytes") }; + } + + public static ofId( + id: string, + accessTokenProvider?: FileAccessTokenProvider, + ) { + return new File(id, accessTokenProvider); + } + + public static async upload( + file: DomFile, + accessTokenProvider: FileAccessTokenProvider, + assetType?: "image" | "video", + onProgress?: (percent: number) => void, + ) { + let uploadToken; + if (assetType) { + uploadToken = + await accessTokenProvider.createAssetUploadToken?.(assetType); + } else { + uploadToken = await accessTokenProvider.createUploadToken?.(); + } + invariant(!!uploadToken, "Could not upload file without upload token"); + + const response = await config.behaviors.file.upload( + file, + uploadToken.token, + onProgress, + ); + + const fileModel = new File(response.id, accessTokenProvider); + return new FileMetaDetailed(fileModel, response); + } + + public assertNotInMemoryFile() { + invariant(!this.isInMemoryFile, "Expected not in-memory file"); + } + + public async findDownloadToken(requestConfig?: AxiosRequestConfig) { + this.assertNotInMemoryFile(); + const tokenData = await this.accessTokenProvider?.getDownloadToken?.( + this.id, + requestConfig, + ); + if (tokenData) { + return new FileDownloadToken(tokenData); + } + } + + public async getFileLinkProps(requestConfig?: AxiosRequestConfig) { + this.assertNotInMemoryFile(); + + const metaData = await this.metaData.getDetailed(requestConfig); + + const token = metaData.token + ? { token: metaData.token } + : await this.findDownloadToken(requestConfig); + + const href = config.behaviors.file.buildUrl( + metaData.id, + metaData.name, + token?.token, + ); + + return { + download: metaData.name, + token: token?.token, + target: "_blank", + href, + }; + } +} diff --git a/packages/models/src/file/File/FileContent.ts b/packages/models/src/file/File/FileContent.ts new file mode 100644 index 00000000..e124cb11 --- /dev/null +++ b/packages/models/src/file/File/FileContent.ts @@ -0,0 +1,109 @@ +import type { AxiosRequestConfig } from "axios"; + +import { ReferenceModel } from "../../base/index.js"; +import { config } from "../../config/index.js"; +import { File } from "./internal.js"; +import { DomFile } from "./types.js"; + +interface Base64InitObject { + base64: string; + type: string; + name: string; +} + +export class FileContent extends ReferenceModel { + public readonly file: File; + + public constructor(file: File) { + super(file.id); + this.file = file; + } + + public static async find(file: File, requestConfig?: AxiosRequestConfig) { + const downloadToken = await file.findDownloadToken(requestConfig); + const meta = await file.metaData.findDetailed(requestConfig); + + if (!meta) { + return; + } + + const arrayBuffer = await config.behaviors.file.download( + file.id, + downloadToken?.token, + ); + + return new FileContentDetailed(file, { + blob: new Blob([arrayBuffer], { + type: meta.mimeType, + }), + name: meta.name, + }); + } + + public static async get(file: File, requestConfig?: AxiosRequestConfig) { + const downloadToken = await file.findDownloadToken(requestConfig); + const meta = await file.metaData.getDetailed(requestConfig); + + const arrayBuffer = await config.behaviors.file.download( + file.id, + downloadToken?.token, + ); + + return new FileContentDetailed(file, { + blob: new Blob([arrayBuffer], { + type: meta.mimeType, + }), + name: meta.name, + }); + } + + public static ofBase64(init: Base64InitObject) { + const { base64, type, name } = init; + + const byteArray = Uint8Array.from( + atob(base64) + .split("") + .map((char) => char.charCodeAt(0)), + ); + + return new FileContentDetailed(File.inMemoryFile, { + blob: new Blob([byteArray], { + type, + }), + name, + }); + } + + public static ofFile(file: File) { + return new FileContent(file); + } + + public async findDetailed(requestConfig?: AxiosRequestConfig) { + return FileContent.find(this.file, requestConfig); + } + + public async getDetailed(requestConfig?: AxiosRequestConfig) { + return FileContent.get(this.file, requestConfig); + } +} + +interface FileContentDetailedInitObject { + name: string; + blob: Blob; +} + +export class FileContentDetailed extends FileContent { + public readonly blob: Blob; + public readonly data: DomFile; + public readonly name: string; + public readonly objectUrl: string; + + public constructor(file: File, init: FileContentDetailedInitObject) { + super(file); + + this.name = init.name; + this.blob = init.blob; + this.data = new DomFile([init.blob], init.name); + this.objectUrl = URL.createObjectURL(this.blob); + } +} diff --git a/packages/models/src/file/File/FileMeta.ts b/packages/models/src/file/File/FileMeta.ts new file mode 100644 index 00000000..f7ddc4cf --- /dev/null +++ b/packages/models/src/file/File/FileMeta.ts @@ -0,0 +1,74 @@ +import type { AxiosRequestConfig } from "axios"; + +import type { FileMetaData } from "./types.js"; +import type { File } from "./internal.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { ReferenceModel, WithData } from "../../base/index.js"; +import { config } from "../../config/index.js"; + +export class FileMeta extends ReferenceModel { + public readonly file: File; + + public constructor(file: File) { + super(file.id); + file.assertNotInMemoryFile(); + this.file = file; + } + + public static async find(file: File, requestConfig?: AxiosRequestConfig) { + const downloadToken = await file.findDownloadToken(requestConfig); + const tokenString = downloadToken?.token; + + const data = await config.behaviors.file.findMetaData( + file.id, + tokenString, + requestConfig, + ); + + if (data !== undefined) { + return new FileMetaDetailed(file, data, tokenString); + } + } + + public static async get(file: File, requestConfig?: AxiosRequestConfig) { + const fileMeta = await FileMeta.find(file, requestConfig); + assertObjectFound(fileMeta, FileMeta, file.id); + return fileMeta; + } + + public static ofFile(file: File): FileMeta { + return new FileMeta(file); + } + + public async findCommon(): Promise { + return this instanceof FileMetaDetailed ? this : this.findDetailed(); + } + + public findDetailed(requestConfig?: AxiosRequestConfig) { + return FileMeta.find(this.file, requestConfig); + } + + public async getCommon(): Promise { + return this instanceof FileMetaDetailed ? this : this.getDetailed(); + } + + public getDetailed(requestConfig?: AxiosRequestConfig) { + return FileMeta.get(this.file, requestConfig); + } +} + +export class FileMetaDetailed extends WithData()(FileMeta) { + public override readonly data: FileMetaData; + public readonly mimeType: string; + public readonly name: string; + public readonly token?: string; + + public constructor(file: File, data: FileMetaData, token?: string) { + super(file); + this.data = data; + this.mimeType = data.mimeType ?? data.type; + this.name = data.name; + this.token = token; + } +} diff --git a/packages/models/src/file/File/behaviors/api.ts b/packages/models/src/file/File/behaviors/api.ts new file mode 100644 index 00000000..32c15851 --- /dev/null +++ b/packages/models/src/file/File/behaviors/api.ts @@ -0,0 +1,135 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; +import type { Writable } from "type-fest"; + +import type { FileBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { withAxiosRequestConfig } from "../../../base/index.js"; +import { ValidationError } from "../../../errors/index.js"; +import { + classifyFileUploadError, + getMaxUploadSizeInMB, +} from "./classifyFileUploadError.js"; + +export const apiFileBehaviors = ( + client: MittwaldAPIV2Client, +): FileBehaviors => ({ + upload: async (file, token, onProgress) => { + const uploadFormData = new FormData(); + uploadFormData.append("file", file); + + const response = await client.file.createFile( + { + headers: { + Token: token, + }, + data: uploadFormData as never, + }, + { + onBeforeRequest: (req) => { + const writableRequest = req as Writable; + writableRequest.requestConfig = { + ...req.requestConfig, + onUploadProgress: (event) => { + if (onProgress && event.total) { + onProgress(Math.round((event.loaded / event.total) * 100)); + } + }, + }; + }, + }, + ); + + if ( + response.status === 400 || + response.status === 406 || + response.status === 422 || + response.status === 429 + ) { + const message = + "message" in response.data && typeof response.data.message === "string" + ? response.data.message + : undefined; + + const code = message ? classifyFileUploadError(message) : undefined; + const maxSizeInMB = + code === "fileTooLarge" && message + ? getMaxUploadSizeInMB(message) + : undefined; + + throw new ValidationError({ + type: + code ?? + (typeof response.data.type === "string" + ? response.data.type + : "unknown"), + path: "files", + ...(message !== undefined ? { message } : {}), + ...(maxSizeInMB ? { meta: { maxSizeInMB } } : {}), + }); + } + + validateResponse(response, 201); + + return response.data; + }, + + download: async (fileId, token) => { + const response = await client.file.getFile( + { + headers: { Token: token }, + fileId, + }, + { + onBeforeRequest: (req) => { + const writableRequest = req as Writable; + writableRequest.requestConfig = { + ...req.requestConfig, + // prevent Axios from returning binary content as text + responseType: "arraybuffer", + }; + }, + }, + ); + + validateResponse(response, 200); + return response.data as unknown as ArrayBuffer; + }, + + findMetaData: async (fileId, token, requestConfig) => { + const response = await client.file.getFileMeta( + { + headers: { + Token: token, + }, + fileId, + }, + withAxiosRequestConfig(requestConfig), + ); + + if (response.status === 200) { + return response.data; + } + validateResponse(response, 404); + }, + + buildUrl: (refId, name, token) => { + const path = name ? `/v2/files/${refId}/${name}` : `/v2/files/${refId}`; + return client.axios.getUri({ + params: { + token, + }, + url: path, + }); + }, + + getUploadRules: async (fileUploadType) => { + const response = await client.file.getFileUploadTypeRules({ + fileUploadType, + }); + + validateResponse(response, 200); + + return response.data; + }, +}); diff --git a/packages/models/src/file/File/behaviors/classifyFileUploadError.test.ts b/packages/models/src/file/File/behaviors/classifyFileUploadError.test.ts new file mode 100644 index 00000000..1726f00a --- /dev/null +++ b/packages/models/src/file/File/behaviors/classifyFileUploadError.test.ts @@ -0,0 +1,77 @@ +import { expect, test } from "vitest"; + +import { + classifyFileUploadError, + getMaxUploadSizeInMB, +} from "./classifyFileUploadError.js"; + +test.each([ + [ + "malwareInfected", + "Your file is infected with malware, reason: Eicar-Test-Signature.", + ], + [ + "fileTypeMismatch", + "Your zip archive's file 'corrupt.jpeg' is corrupt, the file type text/rtf with the extension .rtf does not match to the file extension .jpeg.", + ], + [ + "mimeTypeNotAllowed", + "File type application/x-msdownload is not allowed, allowed are image/png, image/jpeg.", + ], + ["unsafeContent", "Your file 'document.pdf' contains unsafe content."], + [ + "fileNameTooLong", + "Your file name length of 300 characters exceeds the limit of 255 characters.", + ], + [ + "fileTooLarge", + "Your file size 10485761 bytes exceeds the limit of 10485760 bytes.", + ], + [ + "fileExtensionMissing", + "Your zip archive's file 'README' has no extension.", + ], + ["zipEmpty", "Your zip archive is empty."], + ["zipPasswordProtected", "Your zip archive cannot be password protected."], + [ + "imageDimensions", + "Your image height is too small, expected 200px, given 100px.", + ], + ["fileCorrupt", "Your file is corrupt."], + ["uploadTokenInvalid", "Your token has expired, please request a new one."], + ["tooManyRequests", "Too many requests, see rate limit headers."], +])("classifies %s", (code, message) => { + expect(classifyFileUploadError(message)).toBe(code); +}); + +test("classifies corrupt-by-type messages before plain corrupt messages", () => { + expect( + classifyFileUploadError( + "Your file avatar.jpg is corrupt, the file type text/plain with the extension .txt does not match to the file extension .jpg.", + ), + ).toBe("fileTypeMismatch"); + + expect(classifyFileUploadError("Your file is corrupt.")).toBe("fileCorrupt"); +}); + +test("returns undefined for unrelated messages", () => { + expect(classifyFileUploadError("Something unexpected happened.")).toBe( + undefined, + ); +}); + +test("extracts the maximum upload size in MB from the limit message", () => { + expect( + getMaxUploadSizeInMB( + "Your file size 16000000 bytes exceeds the limit of 10000000 bytes.", + ), + ).toBe("10"); + expect( + getMaxUploadSizeInMB( + "Your file size 16000000 bytes exceeds the limit of 10500000 bytes.", + ), + ).toBe("10.5"); + expect(getMaxUploadSizeInMB("Something unexpected happened.")).toBe( + undefined, + ); +}); diff --git a/packages/models/src/file/File/behaviors/classifyFileUploadError.ts b/packages/models/src/file/File/behaviors/classifyFileUploadError.ts new file mode 100644 index 00000000..16ad83b9 --- /dev/null +++ b/packages/models/src/file/File/behaviors/classifyFileUploadError.ts @@ -0,0 +1,92 @@ +type FileUploadErrorRule = { + test: (message: string) => boolean; + code: string; +}; + +const includesAny = (message: string, fragments: string[]): boolean => + fragments.some((fragment) => message.includes(fragment)); + +const rules: FileUploadErrorRule[] = [ + { + test: (message) => message.includes("infected with malware"), + code: "malwareInfected", + }, + { + test: (message) => message.includes("does not match to the file extension"), + code: "fileTypeMismatch", + }, + { + test: (message) => message.includes("is not allowed, allowed"), + code: "mimeTypeNotAllowed", + }, + { + test: (message) => message.includes("contains unsafe content"), + code: "unsafeContent", + }, + { + test: (message) => message.includes("file name length"), + code: "fileNameTooLong", + }, + { + test: (message) => + message.includes("exceeds the limit of") && message.includes("bytes"), + code: "fileTooLarge", + }, + { + test: (message) => + includesAny(message, ["file extension is required", "has no extension"]), + code: "fileExtensionMissing", + }, + { + test: (message) => message.includes("zip archive is empty"), + code: "zipEmpty", + }, + { + test: (message) => message.includes("password protected"), + code: "zipPasswordProtected", + }, + { + test: (message) => includesAny(message, ["image height", "image width"]), + code: "imageDimensions", + }, + { + test: (message) => message.includes("is corrupt"), + code: "fileCorrupt", + }, + { + test: (message) => + message.includes("token") && + includesAny(message, [ + "invalid", + "expired", + "already used", + "does not exist", + ]), + code: "uploadTokenInvalid", + }, + { + test: (message) => + includesAny(message, ["too many requests", "upload attempts exceeded"]), + code: "tooManyRequests", + }, +]; + +export const classifyFileUploadError = ( + message: string, +): string | undefined => { + const lowercasedMessage = message.toLowerCase(); + + return rules.find((rule) => rule.test(lowercasedMessage))?.code; +}; + +export const getMaxUploadSizeInMB = (message: string): string | undefined => { + const match = message.match(/exceeds the limit of (\d+) bytes/i); + + if (!match) { + return undefined; + } + + const sizeInMB = Number(match[1]) / 1_000_000; + + return sizeInMB % 1 === 0 ? sizeInMB.toFixed(0) : sizeInMB.toFixed(1); +}; diff --git a/packages/models/src/file/File/behaviors/index.ts b/packages/models/src/file/File/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/file/File/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/file/File/behaviors/types.ts b/packages/models/src/file/File/behaviors/types.ts new file mode 100644 index 00000000..99b1373e --- /dev/null +++ b/packages/models/src/file/File/behaviors/types.ts @@ -0,0 +1,28 @@ +import type { AxiosRequestConfig } from "axios"; + +import type { + FileUploadResponseData, + FileUploadRules, + FileUploadType, + FileMetaData, +} from "../types.js"; + +export interface FileBehaviors { + findMetaData( + fileId: string, + token?: string, + requestConfig?: AxiosRequestConfig, + ): Promise; + + upload( + file: File, + token: string, + onProgress?: (percent: number) => void, + ): Promise; + + buildUrl(refId: string, name?: string, token?: string): string; + + download(fileId: string, token?: string): Promise; + + getUploadRules(type: FileUploadType): Promise; +} diff --git a/packages/models/src/file/File/index.ts b/packages/models/src/file/File/index.ts new file mode 100644 index 00000000..1d071121 --- /dev/null +++ b/packages/models/src/file/File/index.ts @@ -0,0 +1,2 @@ +export * from "./internal.js"; +export * from "./types.js"; diff --git a/packages/models/src/file/File/internal.ts b/packages/models/src/file/File/internal.ts new file mode 100644 index 00000000..2e85531b --- /dev/null +++ b/packages/models/src/file/File/internal.ts @@ -0,0 +1,11 @@ +// Hand-ordered internal-module barrel — do not reorder or alphabetize. +// See docs/implementation-patterns.md › "internal.ts — the internal-module pattern". +// +// `File` runs `new File("inmem")` in a static initializer at load time, which +// calls `FileMeta.ofFile()` / `FileContent.ofFile()`. Those two must therefore +// be fully evaluated *before* `File`, so they are exported first. Cluster +// members import each other via this barrel (never via a direct sibling path) +// so this order — not import-statement order — decides evaluation. +export * from "./FileMeta.js"; +export * from "./FileContent.js"; +export * from "./File.js"; diff --git a/packages/models/src/file/File/types.ts b/packages/models/src/file/File/types.ts new file mode 100644 index 00000000..6bc5b9fc --- /dev/null +++ b/packages/models/src/file/File/types.ts @@ -0,0 +1,20 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type FileDownloadResponseData = + MittwaldAPIV2.Operations.FileGetFile.ResponseData; + +export type FileUploadResponseData = + MittwaldAPIV2.Paths.V2Files.Post.Responses.$201.Content.ApplicationJson; + +export type FileMetaData = + MittwaldAPIV2.Operations.FileGetFileMeta.ResponseData; + +export const DomFile = File; + +export type DomFile = File; + +export type FileUploadType = + MittwaldAPIV2.Paths.V2FileUploadTypesFileUploadTypeRules.Get.Parameters.Path["fileUploadType"]; + +export type FileUploadRules = + MittwaldAPIV2.Operations.FileGetFileUploadTypeRules.ResponseData; diff --git a/packages/models/src/file/FileAccessToken/FileAccessToken.test.ts b/packages/models/src/file/FileAccessToken/FileAccessToken.test.ts new file mode 100644 index 00000000..3cb52c3c --- /dev/null +++ b/packages/models/src/file/FileAccessToken/FileAccessToken.test.ts @@ -0,0 +1,57 @@ +import { afterEach, describe, expect, test } from "vitest"; +import { DateTime } from "luxon"; + +import { buildFileDownloadTokenData } from "../../testing/builders/buildFileDownloadTokenData.js"; +import { buildFileUploadTokenData } from "../../testing/builders/buildFileUploadTokenData.js"; +import { resetBehaviors } from "../../testing/installBehaviors.js"; +import { FileDownloadToken } from "./FileDownloadToken.js"; +import { FileUploadToken } from "./FileUploadToken.js"; +import { DataModel } from "../../base/index.js"; + +afterEach(resetBehaviors); + +describe("FileDownloadToken", () => { + test("exposes its token and parsed expiry", () => { + const token = new FileDownloadToken( + buildFileDownloadTokenData({ + expiresAt: "2099-01-01T00:00:00.000Z", + accessToken: "tok", + }), + ); + + expect(token.token).toBe("tok"); + expect(token.expiresAt).toBeInstanceOf(DateTime); + expect(token.expiresAt.isValid).toBe(true); + }); + + test("returns true for a future expiry", () => { + const token = new FileDownloadToken( + buildFileDownloadTokenData({ + expiresAt: DateTime.now().plus({ days: 1 }).toISO(), + }), + ); + + expect(token.checkIsExpired()).toBe(true); + }); + + test("returns false for a past expiry", () => { + const token = new FileDownloadToken( + buildFileDownloadTokenData({ + expiresAt: DateTime.now().minus({ days: 1 }).toISO(), + }), + ); + + expect(token.checkIsExpired()).toBe(false); + }); +}); + +describe("FileUploadToken", () => { + test("exposes the token and original data", () => { + const data = buildFileUploadTokenData({ token: "up" }); + const token = new FileUploadToken(data); + + expect(token).toBeInstanceOf(DataModel); + expect(token.token).toBe("up"); + expect(token.data).toBe(data); + }); +}); diff --git a/packages/models/src/file/FileAccessToken/FileAccessTokenProvider.ts b/packages/models/src/file/FileAccessToken/FileAccessTokenProvider.ts new file mode 100644 index 00000000..7c524e20 --- /dev/null +++ b/packages/models/src/file/FileAccessToken/FileAccessTokenProvider.ts @@ -0,0 +1,14 @@ +import type { AxiosRequestConfig } from "axios"; + +import type { FileDownloadTokenData, FileUploadTokenData } from "./types.js"; + +export interface FileAccessTokenProvider { + getDownloadToken?: ( + fileId: string, + requestConfig?: AxiosRequestConfig, + ) => Promise; + createAssetUploadToken?: ( + assetType: "image" | "video", + ) => Promise; + createUploadToken?: () => Promise; +} diff --git a/packages/models/src/file/FileAccessToken/FileDownloadToken.ts b/packages/models/src/file/FileAccessToken/FileDownloadToken.ts new file mode 100644 index 00000000..e5031f43 --- /dev/null +++ b/packages/models/src/file/FileAccessToken/FileDownloadToken.ts @@ -0,0 +1,20 @@ +import { DateTime } from "luxon"; + +import type { FileDownloadTokenData } from "./types.js"; + +import { DataModel } from "../../base/index.js"; + +export class FileDownloadToken extends DataModel { + public readonly expiresAt: DateTime; + public readonly token: string; + + public constructor(data: FileDownloadTokenData) { + super(data); + this.token = data.accessToken; + this.expiresAt = DateTime.fromISO(data.expiresAt); + } + + public checkIsExpired() { + return this.expiresAt > DateTime.now(); + } +} diff --git a/packages/models/src/file/FileAccessToken/FileUploadToken.ts b/packages/models/src/file/FileAccessToken/FileUploadToken.ts new file mode 100644 index 00000000..28164ce9 --- /dev/null +++ b/packages/models/src/file/FileAccessToken/FileUploadToken.ts @@ -0,0 +1,12 @@ +import type { FileUploadTokenData } from "./types.js"; + +import { DataModel } from "../../base/index.js"; + +export class FileUploadToken extends DataModel { + public readonly token: string; + + public constructor(data: FileUploadTokenData) { + super(data); + this.token = data.token; + } +} diff --git a/packages/models/src/file/FileAccessToken/index.ts b/packages/models/src/file/FileAccessToken/index.ts new file mode 100644 index 00000000..73afd775 --- /dev/null +++ b/packages/models/src/file/FileAccessToken/index.ts @@ -0,0 +1,4 @@ +export * from "./FileAccessTokenProvider.js"; +export * from "./FileDownloadToken.js"; +export * from "./FileUploadToken.js"; +export * from "./types.js"; diff --git a/packages/models/src/file/FileAccessToken/types.ts b/packages/models/src/file/FileAccessToken/types.ts new file mode 100644 index 00000000..a655ecbb --- /dev/null +++ b/packages/models/src/file/FileAccessToken/types.ts @@ -0,0 +1,19 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export interface FileUploadTokenData { + rules: Omit< + MittwaldAPIV2.Components.Schemas.FileFileUploadRules, + | "maxSizeInBytes" + | "maxNameLength" + | "maxSizeInKb" + | "maxSizeInKB" + | "extensions" + | "fileTypes" + >; + token: string; +} + +export interface FileDownloadTokenData { + accessToken: string; + expiresAt: string; +} diff --git a/packages/models/src/file/index.ts b/packages/models/src/file/index.ts new file mode 100644 index 00000000..ab2e81f2 --- /dev/null +++ b/packages/models/src/file/index.ts @@ -0,0 +1,2 @@ +export * from "./File/index.js"; +export * from "./FileAccessToken/index.js"; diff --git a/packages/models/src/fyndr/City/City.test.ts b/packages/models/src/fyndr/City/City.test.ts new file mode 100644 index 00000000..db05ef06 --- /dev/null +++ b/packages/models/src/fyndr/City/City.test.ts @@ -0,0 +1,42 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { buildCityData } from "../../testing/builders/buildCityData.js"; +import { CityListItem, CityList, City } from "./City.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; + +afterEach(resetBehaviors); + +describe("City", () => { + test("queries cities and maps list items", async () => { + const query = { input: "Kiel" }; + const list = vi.fn().mockResolvedValue({ + items: [buildCityData()], + totalCount: 7, + }); + installBehaviors({ city: { list } }); + + const result = await City.query(query).execute(); + + expect(list).toHaveBeenCalledWith(query); + expect(result).toBeInstanceOf(CityList); + expect(result.totalCount).toBe(7); + expect(result.items[0]).toBeInstanceOf(CityListItem); + expect(result.items[0]).toMatchObject({ + zipCode: "24103", + country: "DE", + city: "Kiel", + }); + }); + + test("refine merges additional query fields", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 0, items: [] }); + installBehaviors({ city: { list } }); + + await City.query({ input: "Ki" }).refine({ input: "Kiel" }).execute(); + + expect(list).toHaveBeenCalledWith({ input: "Kiel" }); + }); +}); diff --git a/packages/models/src/fyndr/City/City.ts b/packages/models/src/fyndr/City/City.ts new file mode 100644 index 00000000..ad091f98 --- /dev/null +++ b/packages/models/src/fyndr/City/City.ts @@ -0,0 +1,66 @@ +import type { CitiesListQueryData, CitiesListItemData } from "./types.js"; + +import { ListQueryModel, WithListData, DataModel } from "../../base/index.js"; +import { config } from "../../config/config.js"; + +export const LOCATION_DACH_ZIP_CODE = "DACH-RAUM"; + +export class City { + public static query(query: CitiesListQueryData) { + return new CityListQuery(query); + } +} + +export class CityCommon extends DataModel { + public readonly city: string; + public readonly country: string; + public readonly zipCode: string; + + public constructor(data: CitiesListItemData) { + super(data); + + this.city = data.city; + this.zipCode = data.postCode; + this.country = data.country; + } +} + +export class CityListItem extends CityCommon { + public constructor(data: CitiesListItemData) { + super(data); + } +} + +export class CityListQuery extends ListQueryModel { + public constructor(query: CitiesListQueryData) { + super(query); + } + + public async execute() { + const { totalCount, items } = await config.behaviors.city.list(this.query); + return new CityList( + this.query, + items.map((item) => new CityListItem(item)), + totalCount, + ); + } + + public refine(query: CitiesListQueryData) { + return new CityListQuery({ ...this.query, ...query }); + } +} + +export class CityList extends WithListData()(CityListQuery) { + public override readonly items: readonly CityListItem[]; + public override readonly totalCount: number; + + public constructor( + query: CitiesListQueryData, + cities: CityListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(cities); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/fyndr/City/behavior/api.ts b/packages/models/src/fyndr/City/behavior/api.ts new file mode 100644 index 00000000..b8fc953f --- /dev/null +++ b/packages/models/src/fyndr/City/behavior/api.ts @@ -0,0 +1,22 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { CityBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; + +export const apiCityBehavior = ( + client: MittwaldAPIV2Client, +): CityBehaviors => ({ + list: async (query) => { + const response = await client.leadFyndr.leadfyndrGetCities({ + queryParameters: query, + }); + + validateResponse(response, 200); + + return { + totalCount: response.data.length, + items: response.data, + }; + }, +}); diff --git a/packages/models/src/fyndr/City/behavior/index.ts b/packages/models/src/fyndr/City/behavior/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/fyndr/City/behavior/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/fyndr/City/behavior/types.ts b/packages/models/src/fyndr/City/behavior/types.ts new file mode 100644 index 00000000..2b1ee71c --- /dev/null +++ b/packages/models/src/fyndr/City/behavior/types.ts @@ -0,0 +1,8 @@ +import type { CitiesListQueryData, CitiesListItemData } from "../types.js"; +import type { QueryResponseData } from "../../../base/index.js"; + +export interface CityBehaviors { + list: ( + query: CitiesListQueryData, + ) => Promise>; +} diff --git a/packages/models/src/fyndr/City/index.ts b/packages/models/src/fyndr/City/index.ts new file mode 100644 index 00000000..2f56a0e9 --- /dev/null +++ b/packages/models/src/fyndr/City/index.ts @@ -0,0 +1,2 @@ +export * from "./City.js"; +export * from "./types.js"; diff --git a/packages/models/src/fyndr/City/types.ts b/packages/models/src/fyndr/City/types.ts new file mode 100644 index 00000000..9b512e90 --- /dev/null +++ b/packages/models/src/fyndr/City/types.ts @@ -0,0 +1,7 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type CitiesListItemData = + MittwaldAPIV2.Operations.LeadfyndrGetCities.ResponseData[number]; + +export type CitiesListQueryData = + MittwaldAPIV2.Paths.V2Cities.Get.Parameters.Query; diff --git a/packages/models/src/fyndr/FinderProfile/FinderProfile.test.ts b/packages/models/src/fyndr/FinderProfile/FinderProfile.test.ts new file mode 100644 index 00000000..cd408b9a --- /dev/null +++ b/packages/models/src/fyndr/FinderProfile/FinderProfile.test.ts @@ -0,0 +1,173 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { buildFinderProfileData } from "../../testing/builders/buildFinderProfileData.js"; +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { + FinderProfileDetailed, + FinderProfileList, + FinderProfile, +} from "./FinderProfile.js"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? type.name : undefined, +})); + +afterEach(resetBehaviors); + +describe("FinderProfile", () => { + test("find delegates with options and maps missing data", async () => { + const options = { retryCache: false }; + const find = vi + .fn() + .mockResolvedValueOnce(buildFinderProfileData()) + .mockResolvedValueOnce(undefined); + installBehaviors({ finderProfile: { find } }); + + expect(await FinderProfile.find("c-1", options)).toBeInstanceOf( + FinderProfileDetailed, + ); + expect(find).toHaveBeenCalledWith("c-1", options); + expect(await FinderProfile.find("missing")).toBeUndefined(); + }); + + test("get returns detailed data and rejects when missing", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildFinderProfileData()) + .mockResolvedValueOnce(undefined); + installBehaviors({ finderProfile: { find } }); + + expect(await FinderProfile.get("c-1")).toBeInstanceOf( + FinderProfileDetailed, + ); + await expect(FinderProfile.get("missing")).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("exposes profile data through derived getters", () => { + const tariff = buildFinderProfileData().tariff; + const enabled = new FinderProfileDetailed( + buildFinderProfileData({ tariff }), + ); + const disabled = new FinderProfileDetailed( + buildFinderProfileData({ + disabledOn: "2024-03-01T00:00:00.000Z", + domain: "https://example.org", + }), + ); + + expect(enabled.url).toBe("https://example.com"); + expect(enabled.approvedAt?.toUTC().toISO()).toBe( + "2024-01-01T00:00:00.000Z", + ); + expect(enabled.plan).toBe(tariff); + expect(enabled.unlockContingentRenewalDate?.toUTC().toISO()).toBe( + "2024-06-01T00:00:00.000Z", + ); + expect(enabled.isDisabled).toBe(false); + expect(enabled.disabledAt).toBeUndefined(); + expect(enabled.hasAccess()).toBe(true); + expect(enabled.customer.id).toBe("c-1"); + expect(disabled.url).toBe("https://example.org"); + expect(disabled.isDisabled).toBe(true); + expect(disabled.disabledAt?.toUTC().toISO()).toBe( + "2024-03-01T00:00:00.000Z", + ); + expect(disabled.hasAccess()).toBe(false); + }); + + test("getContract delegates and preserves undefined", async () => { + const findContract = vi.fn().mockResolvedValue(undefined); + installBehaviors({ finderProfile: { findContract } }); + + expect(await FinderProfile.ofCustomer("c-1").getContract()).toBeUndefined(); + expect(findContract).toHaveBeenCalledWith("c-1"); + }); + + test("preserves identity and queries the list behavior", async () => { + const list = vi + .fn() + .mockResolvedValue({ items: [buildFinderProfileData()], totalCount: 8 }); + installBehaviors({ finderProfile: { list } }); + + const result = await FinderProfile.query().execute(); + + expect(FinderProfile.ofCustomer("c-1").id).toBe("c-1"); + expect(result).toBeInstanceOf(FinderProfileList); + expect(result.items[0]).toBeInstanceOf(FinderProfile); + expect(new FinderProfileDetailed(buildFinderProfileData())).toBeInstanceOf( + FinderProfile, + ); + expect(list).toHaveBeenCalledWith(); + }); + + test("findCommon delegates to find and maps the common variant, undefined when missing", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildFinderProfileData()) + .mockResolvedValueOnce(undefined); + installBehaviors({ finderProfile: { find } }); + + expect(await FinderProfile.ofCustomer("c-1").findCommon()).toBeInstanceOf( + FinderProfileDetailed, + ); + expect(find).toHaveBeenCalledWith("c-1", undefined); + expect(await FinderProfile.ofCustomer("c-2").findCommon()).toBeUndefined(); + }); + + test("getCommon returns the common variant and rejects when missing", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildFinderProfileData()) + .mockResolvedValueOnce(undefined); + installBehaviors({ finderProfile: { find } }); + + expect(await FinderProfile.ofCustomer("c-1").getCommon()).toBeInstanceOf( + FinderProfileDetailed, + ); + await expect( + FinderProfile.ofCustomer("missing").getCommon(), + ).rejects.toBeInstanceOf(ObjectNotFoundError); + }); + + test("getCommon and findCommon are idempotent on a materialized profile", async () => { + const find = vi.fn(); + installBehaviors({ finderProfile: { find } }); + const detailed = new FinderProfileDetailed(buildFinderProfileData()); + + expect(await detailed.getCommon()).toBe(detailed); + expect(await detailed.findCommon()).toBe(detailed); + expect(find).not.toHaveBeenCalled(); + }); + + test("aggregateMetaData pins the cache identity", () => { + expect(FinderProfile.aggregateMetaData).toBeInstanceOf(AggregateMetaData); + expect(FinderProfile.aggregateMetaData.domain).toBe("leadfinder"); + expect(FinderProfile.aggregateMetaData.aggregate).toBe("finderprofile"); + }); + + test("derived dates fall back to undefined when source fields are absent", () => { + const profile = new FinderProfileDetailed( + buildFinderProfileData({ + tariff: { + reservation: { tariffLimit: 0, available: 0, used: 0 }, + unlocked: { tariffLimit: 0, available: 0, used: 0 }, + }, + approvedOn: undefined, + }), + ); + + expect(profile.approvedAt).toBeUndefined(); + expect(profile.unlockContingentRenewalDate).toBeUndefined(); + }); +}); diff --git a/packages/models/src/fyndr/FinderProfile/FinderProfile.ts b/packages/models/src/fyndr/FinderProfile/FinderProfile.ts new file mode 100644 index 00000000..6fd22ff4 --- /dev/null +++ b/packages/models/src/fyndr/FinderProfile/FinderProfile.ts @@ -0,0 +1,185 @@ +import type { AxiosRequestConfig } from "axios"; + +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; + +import type { + FinderProfileListModelQueryData, + FinderProfileListItemData, + FinderProfilePlanOptions, + FinderProfileData, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { Customer } from "../../customer/Customer/Customer.js"; +import { ContractDetailed } from "../../contract/index.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "FinderProfile", +}) +export class FinderProfile extends ReferenceModel { + public static aggregateMetaData = new AggregateMetaData( + "leadfinder", + "finderprofile", + ); + + public static async find(customerId: string, options?: AxiosRequestConfig) { + const data = await config.behaviors.finderProfile.find(customerId, options); + if (data) { + return new FinderProfileDetailed(data); + } + } + + public static async get(customerId: string, options?: AxiosRequestConfig) { + const data = await this.find(customerId, options); + assertObjectFound(data, FinderProfile, customerId); + return data; + } + + public static ofCustomer(customer: Customer | string): FinderProfile { + return this.ofCustomerId(extractId(customer)); + } + + public static ofCustomerId(customerId: string): FinderProfile { + return new FinderProfile(customerId); + } + + public static query(query: FinderProfileListModelQueryData = {}) { + return new FinderProfileListQuery(query); + } + + public async findCommon( + options?: AxiosRequestConfig, + ): Promise { + return this instanceof FinderProfileCommon + ? this + : this.findDetailed(options); + } + + public async findDetailed( + options?: AxiosRequestConfig, + ): Promise { + return FinderProfile.find(this.id, options); + } + + public async getCommon( + options?: AxiosRequestConfig, + ): Promise { + return this instanceof FinderProfileCommon + ? this + : this.getDetailed(options); + } + + public async getContract() { + const data = await config.behaviors.finderProfile.findContract(this.id); + if (data) { + return new ContractDetailed(data); + } + } + + public async getDetailed( + options?: AxiosRequestConfig, + ): Promise { + return FinderProfile.get(this.id, options); + } +} + +export class FinderProfileCommon extends WithData()( + FinderProfile, +) { + public readonly approvedAt: DateTime | undefined; + public readonly customer: Customer; + public override readonly data: FinderProfileData; + public readonly disabledAt: DateTime | undefined; + public readonly domain: string; + public readonly isDisabled: boolean; + public readonly plan: FinderProfilePlanOptions; + public readonly unlockContingentRenewalDate: DateTime | undefined; + public readonly url: string; + + public constructor(data: FinderProfileData) { + super(data.customerId); + this.data = data; + this.customer = Customer.ofId(data.customerId); + this.domain = data.domain; + this.url = data.domain.startsWith("https://") + ? data.domain + : `https://${data.domain}`; + this.disabledAt = data.disabledOn + ? DateTime.fromISO(data.disabledOn) + : undefined; + this.approvedAt = data.approvedOn + ? DateTime.fromISO(data.approvedOn) + : undefined; + this.isDisabled = !!data.disabledOn; + this.plan = data.tariff; + this.unlockContingentRenewalDate = data.tariff.nextUnlockRenewalDate + ? DateTime.fromISO(data.tariff.nextUnlockRenewalDate) + : undefined; + } + + public readonly hasAccess = () => { + return !this.isDisabled; + }; +} + +export class FinderProfileDetailed extends FinderProfileCommon { + public constructor(data: FinderProfileData) { + super(data); + } +} + +export class FinderProfileListItem extends FinderProfileCommon { + public constructor(data: FinderProfileListItemData) { + super(data); + } +} + +export class FinderProfileListQuery extends ListQueryModel { + public constructor(query: FinderProfileListModelQueryData) { + super(query); + } + + public async execute() { + const { totalCount, items } = await config.behaviors.finderProfile.list(); + + return new FinderProfileList( + this.query, + items.map((d) => new FinderProfileListItem(d)), + totalCount, + ); + } + + public refine(query: FinderProfileListModelQueryData) { + return new FinderProfileListQuery({ + ...this.query, + ...query, + }); + } +} + +export class FinderProfileList extends WithListData()( + FinderProfileListQuery, +) { + public override readonly items: readonly FinderProfileListItem[]; + public override readonly totalCount: number; + + public constructor( + query: FinderProfileListModelQueryData, + items: FinderProfileListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(items); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/fyndr/FinderProfile/behaviors/api.ts b/packages/models/src/fyndr/FinderProfile/behaviors/api.ts new file mode 100644 index 00000000..d94e4c04 --- /dev/null +++ b/packages/models/src/fyndr/FinderProfile/behaviors/api.ts @@ -0,0 +1,60 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { FinderProfileListItemData } from "../types.js"; +import type { FinderProfileBehaviors } from "./types.js"; + +import { withAxiosRequestConfig } from "../../../base/api/withModelRequestOptions.js"; +import { Customer } from "../../../customer/Customer/index.js"; + +export const apiFinderProfileBehaviors = ( + client: MittwaldAPIV2Client, +): FinderProfileBehaviors => ({ + list: async () => { + const customerList = await Customer.query().execute(); + + const customersAndFinderProfile = await Promise.all( + customerList.items.map(async (customer) => { + const finderProfileResult = + await client.leadFyndr.leadfyndrGetLeadFyndrProfile({ + customerId: customer.id, + }); + + return finderProfileResult.status === 200 + ? finderProfileResult.data + : undefined; + }), + ); + + const finderProfiles = customersAndFinderProfile.filter( + (e) => e !== undefined, + ) as FinderProfileListItemData[]; + + return { + totalCount: finderProfiles.length, + items: finderProfiles, + }; + }, + + find: async (customerId, options) => { + const response = await client.leadFyndr.leadfyndrGetLeadFyndrProfile( + { + customerId, + }, + withAxiosRequestConfig(options), + ); + + if (response.status === 200) { + return response.data; + } + }, + + findContract: async (customerId) => { + const response = await client.contract.getDetailOfContractByLeadFyndr({ + customerId, + }); + + if (response.status === 200) { + return response.data; + } + }, +}); diff --git a/packages/models/src/fyndr/FinderProfile/behaviors/index.ts b/packages/models/src/fyndr/FinderProfile/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/fyndr/FinderProfile/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/fyndr/FinderProfile/behaviors/types.ts b/packages/models/src/fyndr/FinderProfile/behaviors/types.ts new file mode 100644 index 00000000..01e9a604 --- /dev/null +++ b/packages/models/src/fyndr/FinderProfile/behaviors/types.ts @@ -0,0 +1,14 @@ +import type { AxiosRequestConfig } from "axios"; + +import type { FinderProfileListItemData, FinderProfileData } from "../types.js"; +import type { QueryResponseData } from "../../../base/index.js"; +import type { ContractData } from "../../../contract/index.js"; + +export interface FinderProfileBehaviors { + find: ( + finderProfileId: string, + options?: AxiosRequestConfig, + ) => Promise; + findContract: (finderProfileId: string) => Promise; + list: () => Promise>; +} diff --git a/packages/models/src/fyndr/FinderProfile/index.ts b/packages/models/src/fyndr/FinderProfile/index.ts new file mode 100644 index 00000000..24c0a795 --- /dev/null +++ b/packages/models/src/fyndr/FinderProfile/index.ts @@ -0,0 +1,2 @@ +export * from "./FinderProfile.js"; +export * from "./types.js"; diff --git a/packages/models/src/fyndr/FinderProfile/types.ts b/packages/models/src/fyndr/FinderProfile/types.ts new file mode 100644 index 00000000..2cee0092 --- /dev/null +++ b/packages/models/src/fyndr/FinderProfile/types.ts @@ -0,0 +1,11 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type FinderProfileData = + MittwaldAPIV2.Operations.LeadfyndrGetLeadFyndrProfile.ResponseData; + +export type FinderProfileListItemData = FinderProfileData; + +// eslint-disable-next-line @typescript-eslint/no-empty-object-type +export interface FinderProfileListModelQueryData {} + +export type FinderProfilePlanOptions = FinderProfileData["tariff"]; diff --git a/packages/models/src/fyndr/FinderProfileRequest/FinderProfileRequest.test.ts b/packages/models/src/fyndr/FinderProfileRequest/FinderProfileRequest.test.ts new file mode 100644 index 00000000..25db7855 --- /dev/null +++ b/packages/models/src/fyndr/FinderProfileRequest/FinderProfileRequest.test.ts @@ -0,0 +1,181 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { buildFinderProfileRequestCustomerData } from "../../testing/builders/buildFinderProfileRequestCustomerData.js"; +import { buildFinderProfileRequestData } from "../../testing/builders/buildFinderProfileRequestData.js"; +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { + FinderProfileRequestDetailed, + FinderProfileRequestCommon, + FinderProfileRequestList, + FinderProfileRequest, +} from "./FinderProfileRequest.js"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? type.name : undefined, +})); + +afterEach(resetBehaviors); + +describe("FinderProfileRequest", () => { + test("find and get delegate and handle missing data", async () => { + const options = { retryCache: false }; + const find = vi + .fn() + .mockResolvedValueOnce(buildFinderProfileRequestData()) + .mockResolvedValueOnce(buildFinderProfileRequestData()) + .mockResolvedValueOnce(undefined); + installBehaviors({ finderProfileRequest: { find } }); + + expect(await FinderProfileRequest.find("c-1", options)).toBeInstanceOf( + FinderProfileRequestDetailed, + ); + expect(find).toHaveBeenCalledWith("c-1", options); + expect(await FinderProfileRequest.get("c-1")).toBeInstanceOf( + FinderProfileRequestDetailed, + ); + await expect(FinderProfileRequest.get("missing")).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("exposes request data through getters", () => { + const request = new FinderProfileRequestDetailed( + buildFinderProfileRequestData({ resultOn: undefined }), + ); + const completed = new FinderProfileRequestDetailed( + buildFinderProfileRequestData({ + resultOn: "2024-02-01T00:00:00.000Z", + domain: "https://example.org", + }), + ); + + expect(request.profileId).toBe("p-1"); + expect(request.customer.id).toBe("c-1"); + expect(request.domain).toBe("example.com"); + expect(request.url).toBe("https://example.com"); + expect(request.createdAt.toUTC().toISO()).toBe("2024-01-01T00:00:00.000Z"); + expect(request.resultAt).toBeUndefined(); + expect(request.status).toBe("APPROVED"); + expect(completed.url).toBe("https://example.org"); + expect(completed.resultAt?.toUTC().toISO()).toBe( + "2024-02-01T00:00:00.000Z", + ); + }); + + test("create derives the domain from the customer owner email", async () => { + const customer = buildFinderProfileRequestCustomerData({ + owner: { + address: { + countryCode: "DE", + houseNumber: "1", + street: "Main", + city: "Kiel", + zip: "24103", + }, + emailAddress: "info@sub.example.com", + salutation: "mr", + }, + }); + const find = vi.fn().mockResolvedValue(customer); + const create = vi.fn().mockResolvedValue(undefined); + installBehaviors({ finderProfileRequest: { create }, customer: { find } }); + + await FinderProfileRequest.create("c-1"); + + expect(create).toHaveBeenCalledWith("c-1", { domain: "sub.example.com" }); + }); + + test("create rejects when the owner email is absent", async () => { + const customer = buildFinderProfileRequestCustomerData({ + owner: { + address: { + countryCode: "DE", + houseNumber: "1", + street: "Main", + city: "Kiel", + zip: "24103", + }, + salutation: "mr", + }, + }); + installBehaviors({ + customer: { find: vi.fn().mockResolvedValue(customer) }, + }); + + await expect(FinderProfileRequest.create("c-1")).rejects.toThrow( + "Contract partner email is not defined", + ); + }); + + test("preserves identity and queries the list behavior", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildFinderProfileRequestData()], + totalCount: 1, + }); + installBehaviors({ finderProfileRequest: { list } }); + + const result = await FinderProfileRequest.query().execute(); + + expect(result).toBeInstanceOf(FinderProfileRequestList); + expect(result.items[0]).toBeInstanceOf(FinderProfileRequest); + expect( + new FinderProfileRequestDetailed(buildFinderProfileRequestData()), + ).toBeInstanceOf(FinderProfileRequest); + expect(list).toHaveBeenCalledWith(); + }); + + test("findCommon and getCommon delegate to find", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildFinderProfileRequestData()) + .mockResolvedValueOnce(undefined) + .mockResolvedValueOnce(buildFinderProfileRequestData()) + .mockResolvedValueOnce(undefined); + installBehaviors({ finderProfileRequest: { find } }); + + expect( + await FinderProfileRequest.ofCustomer("c-1").findCommon(), + ).toBeInstanceOf(FinderProfileRequestCommon); + expect( + await FinderProfileRequest.ofCustomer("c-1").findCommon(), + ).toBeUndefined(); + expect( + await FinderProfileRequest.ofCustomer("c-1").getCommon(), + ).toBeInstanceOf(FinderProfileRequestCommon); + await expect( + FinderProfileRequest.ofCustomer("missing").getCommon(), + ).rejects.toBeInstanceOf(ObjectNotFoundError); + }); + + test("getCommon, findCommon and getDetailed are idempotent on a materialized request", async () => { + const find = vi.fn(); + installBehaviors({ finderProfileRequest: { find } }); + const detailed = new FinderProfileRequestDetailed( + buildFinderProfileRequestData(), + ); + + expect(await detailed.getCommon()).toBe(detailed); + expect(await detailed.findCommon()).toBe(detailed); + expect(await detailed.getDetailed()).toBe(detailed); + expect(find).not.toHaveBeenCalled(); + }); + + test("aggregateMetaData pins the cache identity", () => { + expect(FinderProfileRequest.aggregateMetaData).toBeInstanceOf( + AggregateMetaData, + ); + expect(FinderProfileRequest.aggregateMetaData.domain).toBe("leadfinder"); + expect(FinderProfileRequest.aggregateMetaData.aggregate).toBe( + "finderprofilerequest", + ); + }); +}); diff --git a/packages/models/src/fyndr/FinderProfileRequest/FinderProfileRequest.ts b/packages/models/src/fyndr/FinderProfileRequest/FinderProfileRequest.ts new file mode 100644 index 00000000..4a10d065 --- /dev/null +++ b/packages/models/src/fyndr/FinderProfileRequest/FinderProfileRequest.ts @@ -0,0 +1,188 @@ +import type { AxiosRequestConfig } from "axios"; + +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; + +import type { CustomerDetailed } from "../../customer/index.js"; +import type { + FinderProfileRequestListModelQueryData, + FinderProfileRequestListItemData, + FinderProfileRequestStatus, + FinderProfileRequestData, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { Customer } from "../../customer/Customer/Customer.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "FinderProfileRequest", +}) +export class FinderProfileRequest extends ReferenceModel { + public static aggregateMetaData = new AggregateMetaData( + "leadfinder", + "finderprofilerequest", + ); + + public static async create(customerId: string) { + const customer = await Customer.ofId(customerId).getDetailed(); + const contractPartnerDomain = + this.getDomainFromContractPartnerEmail(customer); + + await config.behaviors.finderProfileRequest.create(customerId, { + domain: contractPartnerDomain, + }); + } + + public static async find(customerId: string, options?: AxiosRequestConfig) { + const data = await config.behaviors.finderProfileRequest.find( + customerId, + options, + ); + if (data) { + return new FinderProfileRequestDetailed(data); + } + } + + public static async get(customerId: string) { + const profile = await this.find(customerId); + assertObjectFound(profile, FinderProfileRequest, customerId); + return profile; + } + + public static ofCustomer(customer: Customer | string): FinderProfileRequest { + return new FinderProfileRequest(extractId(customer)); + } + + public static query() { + return new FinderProfileRequestListQuery(); + } + + private static getDomainFromContractPartnerEmail(customer: CustomerDetailed) { + const contractPartnerEmail = customer.data.owner?.emailAddress; + + if (!contractPartnerEmail) { + throw new Error("Contract partner email is not defined"); + } + + return contractPartnerEmail.substring( + (contractPartnerEmail as string).lastIndexOf("@") + 1, + ); + } + + public async findCommon(): Promise { + return this instanceof FinderProfileRequestCommon + ? this + : this.findDetailed(); + } + + public async findDetailed( + options?: AxiosRequestConfig, + ): Promise { + return FinderProfileRequest.find(this.id, options); + } + + public async getCommon(): Promise { + return this instanceof FinderProfileRequestCommon + ? this + : this.getDetailed(); + } + + public async getDetailed(): Promise { + if (this instanceof FinderProfileRequestDetailed) { + return this; + } + return await FinderProfileRequest.get(this.id); + } +} + +export class FinderProfileRequestCommon extends WithData< + FinderProfileRequestListItemData | FinderProfileRequestData +>()(FinderProfileRequest) { + public readonly createdAt: DateTime; + public readonly customer: Customer; + public override readonly data: + FinderProfileRequestListItemData | FinderProfileRequestData; + public readonly domain: string; + public readonly profileId: string; + public readonly resultAt: DateTime | undefined; + public readonly status: FinderProfileRequestStatus; + public readonly url: string; + + public constructor( + data: FinderProfileRequestListItemData | FinderProfileRequestData, + ) { + super(data.customerId); + this.data = data; + this.profileId = data.profileId; + this.customer = Customer.ofId(data.customerId); + this.domain = data.domain; + this.createdAt = DateTime.fromISO(data.createdOn); + this.resultAt = data.resultOn ? DateTime.fromISO(data.resultOn) : undefined; + this.status = data.status; + this.url = data.domain.startsWith("https://") + ? data.domain + : `https://${data.domain}`; + } +} + +export class FinderProfileRequestDetailed extends FinderProfileRequestCommon { + public constructor(data: FinderProfileRequestData) { + super(data); + } +} + +export class FinderProfileRequestListItem extends FinderProfileRequestCommon { + public constructor(data: FinderProfileRequestListItemData) { + super(data); + } +} + +export class FinderProfileRequestListQuery extends ListQueryModel { + public constructor(query: FinderProfileRequestListModelQueryData = {}) { + super(query); + } + + public async execute() { + const { totalCount, items } = + await config.behaviors.finderProfileRequest.list(); + + return new FinderProfileRequestList( + this.query, + items.map((d) => new FinderProfileRequestListItem(d)), + totalCount, + ); + } + + public refine(query: FinderProfileRequestListModelQueryData) { + return new FinderProfileRequestListQuery({ + ...this.query, + ...query, + }); + } +} + +export class FinderProfileRequestList extends WithListData()( + FinderProfileRequestListQuery, +) { + public override readonly items: readonly FinderProfileRequestListItem[]; + public override readonly totalCount: number; + + public constructor( + query: FinderProfileRequestListModelQueryData, + items: FinderProfileRequestListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(items); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/fyndr/FinderProfileRequest/behaviors/api.ts b/packages/models/src/fyndr/FinderProfileRequest/behaviors/api.ts new file mode 100644 index 00000000..772db07f --- /dev/null +++ b/packages/models/src/fyndr/FinderProfileRequest/behaviors/api.ts @@ -0,0 +1,60 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; +import type { AxiosRequestConfig } from "axios"; + +import type { FinderProfileRequestListItemData } from "../types.js"; +import type { FinderProfileRequestBehaviors } from "./types.js"; + +import { withAxiosRequestConfig } from "../../../base/api/withModelRequestOptions.js"; +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { Customer } from "../../../customer/Customer/index.js"; + +export const apiFinderProfileRequestBehaviors = ( + client: MittwaldAPIV2Client, +): FinderProfileRequestBehaviors => ({ + list: async () => { + const customerList = await Customer.query().execute(); + + const customersAndFinderProfile = await Promise.all( + customerList.items.map(async (customer) => { + const finderProfileRequestResult = + await client.leadFyndr.leadfyndrGetLeadFyndrProfileRequest({ + customerId: customer.id, + }); + + return finderProfileRequestResult.status === 200 + ? finderProfileRequestResult.data + : undefined; + }), + ); + + const finderProfileRequests = customersAndFinderProfile.filter( + (e) => e !== undefined, + ) as FinderProfileRequestListItemData[]; + + return { + totalCount: finderProfileRequests.length, + items: finderProfileRequests, + }; + }, + find: async (customerId: string, options?: AxiosRequestConfig) => { + const response = await client.leadFyndr.leadfyndrGetLeadFyndrProfileRequest( + { + customerId, + }, + withAxiosRequestConfig(options), + ); + + if (response.status === 200) { + return response.data; + } + }, + create: async (customerId, data) => { + const response = + await client.leadFyndr.leadfyndrCreateLeadFyndrAccessRequest({ + customerId, + data, + }); + + validateResponse(response, 201); + }, +}); diff --git a/packages/models/src/fyndr/FinderProfileRequest/behaviors/index.ts b/packages/models/src/fyndr/FinderProfileRequest/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/fyndr/FinderProfileRequest/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/fyndr/FinderProfileRequest/behaviors/types.ts b/packages/models/src/fyndr/FinderProfileRequest/behaviors/types.ts new file mode 100644 index 00000000..0b54b127 --- /dev/null +++ b/packages/models/src/fyndr/FinderProfileRequest/behaviors/types.ts @@ -0,0 +1,20 @@ +import type { AxiosRequestConfig } from "axios"; + +import type { QueryResponseData } from "../../../base/index.js"; +import type { + FinderProfileRequestListItemData, + FinderProfileRequestRequestData, + FinderProfileRequestData, +} from "../types.js"; + +export interface FinderProfileRequestBehaviors { + find: ( + customerId: string, + options?: AxiosRequestConfig, + ) => Promise; + create: ( + customerId: string, + data: FinderProfileRequestRequestData, + ) => Promise; + list: () => Promise>; +} diff --git a/packages/models/src/fyndr/FinderProfileRequest/index.ts b/packages/models/src/fyndr/FinderProfileRequest/index.ts new file mode 100644 index 00000000..4c084ce4 --- /dev/null +++ b/packages/models/src/fyndr/FinderProfileRequest/index.ts @@ -0,0 +1,2 @@ +export * from "./FinderProfileRequest.js"; +export * from "./types.js"; diff --git a/packages/models/src/fyndr/FinderProfileRequest/types.ts b/packages/models/src/fyndr/FinderProfileRequest/types.ts new file mode 100644 index 00000000..1669499e --- /dev/null +++ b/packages/models/src/fyndr/FinderProfileRequest/types.ts @@ -0,0 +1,17 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type FinderProfileRequestData = + MittwaldAPIV2.Components.Schemas.LeadfyndrProfileRequest; + +export type FinderProfileRequestStatus = FinderProfileRequestData["status"]; + +export type FinderProfileRequestListItemData = FinderProfileRequestData; + +// eslint-disable-next-line @typescript-eslint/no-empty-object-type +export interface FinderProfileRequestListModelQueryData {} + +export type FinderProfileTariffOptionsData = + MittwaldAPIV2.Components.Schemas.LeadfyndrTariffOptions; + +export type FinderProfileRequestRequestData = + MittwaldAPIV2.Paths.V2CustomersCustomerIdLeadFyndrProfileRequest.Post.Parameters.RequestBody; diff --git a/packages/models/src/fyndr/Lead/Lead.test.ts b/packages/models/src/fyndr/Lead/Lead.test.ts new file mode 100644 index 00000000..ffa0eff4 --- /dev/null +++ b/packages/models/src/fyndr/Lead/Lead.test.ts @@ -0,0 +1,179 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { buildLeadData } from "../../testing/builders/buildLeadData.js"; +import { LeadDetailed, LeadListItem, LeadList, Lead } from "./Lead.js"; +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { getFormattedSalesVolume } from "../util/helper.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? type.name : undefined, +})); + +afterEach(resetBehaviors); + +describe("Lead", () => { + test("find and get delegate and handle missing data", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildLeadData()) + .mockResolvedValueOnce(buildLeadData()) + .mockResolvedValueOnce(undefined); + installBehaviors({ lead: { find } }); + + expect(await Lead.find("c-1", "l-1")).toBeInstanceOf(LeadDetailed); + expect(find).toHaveBeenCalledWith("c-1", "l-1"); + expect(await Lead.get("c-1", "l-1")).toBeInstanceOf(LeadDetailed); + await expect(Lead.get("c-1", "missing")).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("exposes derived lead data", () => { + const lead = new LeadDetailed( + "c-1", + buildLeadData({ businessFields: ["IT", "Retail"] }), + ); + const medium = new LeadDetailed("c-1", buildLeadData({ potential: 0.55 })); + const low = new LeadDetailed("c-1", buildLeadData({ potential: 0.5 })); + const unversioned = new LeadDetailed( + "c-1", + buildLeadData({ mainTechnology: { categoryPriority: 1, name: "React" } }), + ); + + expect(lead.businessFields).toBe("IT, Retail"); + expect(lead.potential).toBe(72); + expect(lead.potentialType).toBe("high"); + expect(medium.potentialType).toBe("medium"); + expect(low.potentialType).toBe("low"); + expect(lead.formattedSalesVolume).toBe(getFormattedSalesVolume(2_000_000)); + expect(lead.mainTechnologyWithVersionText).toBe("TYPO3 12"); + expect(unversioned.mainTechnologyWithVersionText).toBe("React"); + }); + + test("unlock delegates with the customer and lead ids", async () => { + const unlock = vi.fn().mockResolvedValue(undefined); + installBehaviors({ lead: { unlock } }); + + await Lead.ofId("c-1", "l-1").unlock(); + + expect(unlock).toHaveBeenCalledWith("c-1", "l-1"); + }); + + test("queries and maps lead lists", async () => { + const list = vi + .fn() + .mockResolvedValue({ items: [buildLeadData()], totalCount: 9 }); + installBehaviors({ lead: { list } }); + + const result = await Lead.query("c-1", { limit: 4 }).execute(); + + expect(list).toHaveBeenCalledWith("c-1", { limit: 4 }); + expect(result).toBeInstanceOf(LeadList); + expect(result.items[0]).toBeInstanceOf(LeadListItem); + expect(result.totalCount).toBe(9); + }); + + test("getTotalCount executes a zero-limit query", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 12, items: [] }); + installBehaviors({ lead: { list } }); + + expect(await Lead.query("c-1", { skip: 2 }).getTotalCount()).toBe(12); + expect(list).toHaveBeenCalledWith("c-1", { limit: 0, skip: 2 }); + }); + + test("maps store filters and omits the DACH placeholder location", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 0, items: [] }); + installBehaviors({ lead: { list } }); + + await Lead.queryFromStoreFilters("c-1", { + location: { zipCode: "24103", city: "Kiel", radius: "25" }, + employeeCount: { min: "10", max: "50" }, + technologies: ["TYPO3", "React"], + businessFields: ["IT"], + }).execute(); + expect(list).toHaveBeenLastCalledWith("c-1", { + technologies: ["TYPO3 CMS", "React"], + locationPostCode: "24103", + businessFields: ["IT"], + locationRadiusInKm: 25, + employeeCountMin: 10, + employeeCountMax: 50, + locationCity: "Kiel", + }); + + await Lead.queryFromStoreFilters("c-1", { + location: { zipCode: "DACH-RAUM", radius: "100", city: "" }, + employeeCount: null, + businessFields: [], + technologies: [], + }).execute(); + expect(list).toHaveBeenLastCalledWith("c-1", { + employeeCountMin: undefined, + employeeCountMax: undefined, + businessFields: [], + technologies: [], + }); + }); + + test("detailed leads retain Lead identity", () => { + expect(new LeadDetailed("c-1", buildLeadData())).toBeInstanceOf(Lead); + }); + + test("findCommon and getCommon delegate to find", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildLeadData()) + .mockResolvedValueOnce(undefined) + .mockResolvedValueOnce(buildLeadData()) + .mockResolvedValueOnce(undefined); + installBehaviors({ lead: { find } }); + + expect(await Lead.ofId("c-1", "l-1").findCommon()).toBeInstanceOf( + LeadDetailed, + ); + expect(find).toHaveBeenCalledWith("c-1", "l-1"); + expect(await Lead.ofId("c-1", "l-1").findCommon()).toBeUndefined(); + expect(await Lead.ofId("c-1", "l-1").getCommon()).toBeInstanceOf( + LeadDetailed, + ); + await expect( + Lead.ofId("c-1", "missing").getCommon(), + ).rejects.toBeInstanceOf(ObjectNotFoundError); + }); + + test("getCommon and findCommon are idempotent on a materialized lead", async () => { + const find = vi.fn(); + installBehaviors({ lead: { find } }); + const detailed = new LeadDetailed("c-1", buildLeadData()); + + expect(await detailed.getCommon()).toBe(detailed); + expect(await detailed.findCommon()).toBe(detailed); + expect(find).not.toHaveBeenCalled(); + }); + + test("aggregateMetaData pins the cache identity", () => { + expect(Lead.aggregateMetaData).toBeInstanceOf(AggregateMetaData); + expect(Lead.aggregateMetaData.domain).toBe("leadfinder"); + expect(Lead.aggregateMetaData.aggregate).toBe("lead"); + }); + + test("derived technology and scan fields fall back when data is absent", () => { + const lead = new LeadDetailed( + "c-1", + buildLeadData({ mainTechnology: undefined }), + ); + + expect(lead.mainTechnology).toBeUndefined(); + expect(lead.mainTechnologyWithVersionText).toBeUndefined(); + expect(lead.scannedAt).toBeUndefined(); + }); +}); diff --git a/packages/models/src/fyndr/Lead/Lead.ts b/packages/models/src/fyndr/Lead/Lead.ts new file mode 100644 index 00000000..06a7f3df --- /dev/null +++ b/packages/models/src/fyndr/Lead/Lead.ts @@ -0,0 +1,236 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; + +import type { + LeadHosterInformationData, + LeadTechnologyData, + LeadListQueryData, + LeadListItemData, + LeadCompanyData, + LeadMetricsData, + LeadFilterType, + LeadData, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { getFormattedSalesVolume } from "../util/helper.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { LOCATION_DACH_ZIP_CODE } from "../City/index.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "Lead", +}) +export class Lead extends ReferenceModel { + public static aggregateMetaData = new AggregateMetaData("leadfinder", "lead"); + + private readonly customerId: string; + + public constructor(customerId: string, id: string) { + super(id); + this.customerId = customerId; + } + + public static async find(customerId: string, id: string) { + const data = await config.behaviors.lead.find(customerId, id); + if (data) { + return new LeadDetailed(customerId, data); + } + } + + public static async get(customerId: string, id: string) { + const lead = await this.find(customerId, id); + assertObjectFound(lead, Lead, id); + return lead; + } + + public static ofId(customerId: string, leadId: string) { + return new Lead(customerId, leadId); + } + + public static query(customerId: string, query: LeadListQueryData = {}) { + return new LeadListQuery(customerId, query); + } + + public static queryFromStoreFilters( + customerId: string, + filterOptions: LeadFilterType, + ) { + const renamedTechnologies = filterOptions?.technologies.map((value) => { + switch (value) { + case "TYPO3": + return "TYPO3 CMS"; + default: + return value; + } + }); + + const builtLocationFilter = + filterOptions?.location && + filterOptions.location.zipCode !== LOCATION_DACH_ZIP_CODE + ? { + locationRadiusInKm: Number.parseInt(filterOptions.location.radius), + locationPostCode: filterOptions.location.zipCode, + locationCity: filterOptions.location.city, + } + : undefined; + + return new LeadListQuery(customerId, { + businessFields: filterOptions?.businessFields, + technologies: renamedTechnologies, + ...builtLocationFilter, + employeeCountMin: filterOptions?.employeeCount?.min + ? Number.parseInt(filterOptions.employeeCount.min) + : undefined, + employeeCountMax: filterOptions?.employeeCount?.max + ? Number.parseInt(filterOptions.employeeCount.max) + : undefined, + }); + } + + public async findCommon(): Promise { + return this instanceof LeadCommon ? this : this.findDetailed(); + } + + public findDetailed(): Promise { + return Lead.find(this.customerId, this.id); + } + + public async getCommon(): Promise { + return this instanceof LeadCommon ? this : this.getDetailed(); + } + + public getDetailed(): Promise { + return Lead.get(this.customerId, this.id); + } + + public async unlock() { + await config.behaviors.lead.unlock(this.customerId, this.id); + } +} + +export class LeadCommon extends WithData()(Lead) { + public readonly businessFields: string; + public readonly company: LeadCompanyData; + public override readonly data: LeadListItemData | LeadData; + public readonly description: string; + public readonly hosterInformation: LeadHosterInformationData; + public readonly mainTechnology: LeadTechnologyData | undefined; + public readonly mainTechnologyWithVersionText: string | undefined; + public readonly metrics: LeadMetricsData; + public readonly potential: number; + public readonly scannedAt: DateTime | undefined; + public readonly screenshotBase64: string; + public readonly technologies: LeadTechnologyData[]; + + public get formattedSalesVolume(): string { + return getFormattedSalesVolume(this.company.salesVolume); + } + + public get potentialType(): "medium" | "high" | "low" { + if (this.potential > 60) { + return "high"; + } else if (this.potential > 50) { + return "medium"; + } else { + return "low"; + } + } + + public constructor(customerId: string, data: LeadListItemData | LeadData) { + super(customerId, data.leadId); + this.data = data; + this.businessFields = data.businessFields.join(", "); + this.description = data.description; + this.screenshotBase64 = data.screenshot; + this.potential = Math.round(data.potential * 100); + this.metrics = data.metrics; + this.mainTechnology = data.mainTechnology; + this.mainTechnologyWithVersionText = data.mainTechnology + ? `${data.mainTechnology.name}${data.mainTechnology.version ? ` ${data.mainTechnology.version}` : ""}` + : undefined; + this.company = data.company; + this.technologies = data.technologies; + this.scannedAt = data.scannedAt + ? DateTime.fromISO(data.scannedAt) + : undefined; + this.hosterInformation = data.hoster; + } +} + +export class LeadDetailed extends LeadCommon { + public override readonly data: LeadData; + + public constructor(customerId: string, data: LeadData) { + super(customerId, data); + this.data = data; + } +} + +export class LeadListItem extends LeadCommon { + public override readonly data: LeadListItemData; + + public constructor(customerId: string, data: LeadListItemData) { + super(customerId, data); + this.data = data; + } +} + +export class LeadListQuery extends ListQueryModel { + private readonly customerId: string; + + public constructor(customerId: string, query: LeadListQueryData = {}) { + super(query); + this.customerId = customerId; + } + + public async execute() { + const { totalCount, items } = await config.behaviors.lead.list( + this.customerId, + this.query, + ); + + return new LeadList( + this.customerId, + this.query, + items.map((l) => new LeadListItem(this.customerId, l)), + totalCount, + ); + } + + public async getTotalCount() { + const { totalCount } = await this.refine(this.customerId, { + limit: 0, + }).execute(); + return totalCount; + } + + public refine(customerId: string, query: LeadListQueryData) { + return new LeadListQuery(customerId, { + ...this.query, + ...query, + }); + } +} + +export class LeadList extends WithListData()(LeadListQuery) { + public override readonly items: readonly LeadListItem[]; + public override readonly totalCount: number; + + public constructor( + customerId: string, + query: LeadListQueryData, + leads: LeadListItem[], + totalCount: number, + ) { + super(customerId, query); + this.items = Object.freeze(leads); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/fyndr/Lead/behavior/api.ts b/packages/models/src/fyndr/Lead/behavior/api.ts new file mode 100644 index 00000000..913c9b63 --- /dev/null +++ b/packages/models/src/fyndr/Lead/behavior/api.ts @@ -0,0 +1,40 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { LeadBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount } from "../../../base/index.js"; + +export const apiLeadBehaviors = ( + client: MittwaldAPIV2Client, +): LeadBehaviors => ({ + list: async (customerId, query) => { + const response = await client.leadFyndr.leadfyndrListLeads({ + queryParameters: query, + customerId, + }); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response, response.data.leads.length), + items: response.data.leads, + }; + }, + find: async (customerId, leadId) => { + const response = await client.leadFyndr.leadfyndrGetLead({ + customerId, + leadId, + }); + + if (response.status === 200) { + return response.data; + } + validateResponse(response, [403, 404, 429]); + }, + unlock: async (customerId, leadId) => { + const response = await client.leadFyndr.leadfyndrUnlockLead({ + customerId, + leadId, + }); + validateResponse(response, 200); + }, +}); diff --git a/packages/models/src/fyndr/Lead/behavior/index.ts b/packages/models/src/fyndr/Lead/behavior/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/fyndr/Lead/behavior/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/fyndr/Lead/behavior/types.ts b/packages/models/src/fyndr/Lead/behavior/types.ts new file mode 100644 index 00000000..b900131f --- /dev/null +++ b/packages/models/src/fyndr/Lead/behavior/types.ts @@ -0,0 +1,15 @@ +import type { + LeadListQueryData, + LeadListItemData, + LeadData, +} from "../types.js"; +import type { QueryResponseData } from "../../../base/index.js"; + +export interface LeadBehaviors { + list: ( + customerId: string, + query?: LeadListQueryData, + ) => Promise>; + find: (customerId: string, leadId: string) => Promise; + unlock: (customerId: string, leadId: string) => Promise; +} diff --git a/packages/models/src/fyndr/Lead/index.ts b/packages/models/src/fyndr/Lead/index.ts new file mode 100644 index 00000000..b1aa82b6 --- /dev/null +++ b/packages/models/src/fyndr/Lead/index.ts @@ -0,0 +1,2 @@ +export * from "./Lead.js"; +export * from "./types.js"; diff --git a/packages/models/src/fyndr/Lead/types.ts b/packages/models/src/fyndr/Lead/types.ts new file mode 100644 index 00000000..4f90bc5a --- /dev/null +++ b/packages/models/src/fyndr/Lead/types.ts @@ -0,0 +1,24 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type LeadData = MittwaldAPIV2.Operations.LeadfyndrGetLead.ResponseData; + +export type LeadListItemData = + MittwaldAPIV2.Operations.LeadfyndrListLeads.ResponseData["leads"][number]; + +export type LeadListQueryData = + MittwaldAPIV2.Paths.V2CustomersCustomerIdLeads.Get.Parameters.Query; + +export type LeadMetricsData = LeadData["metrics"]; + +export type LeadTechnologyData = LeadData["technologies"][number]; + +export type LeadCompanyData = LeadData["company"]; + +export type LeadHosterInformationData = LeadData["hoster"]; + +export type LeadFilterType = { + location: { zipCode: string; radius: string; city: string } | null; + employeeCount: { max: string | null; min: string } | null; + businessFields: string[]; + technologies: string[]; +} | null; diff --git a/packages/models/src/fyndr/LeadsExport/LeadsExport.test.ts b/packages/models/src/fyndr/LeadsExport/LeadsExport.test.ts new file mode 100644 index 00000000..5943b2ba --- /dev/null +++ b/packages/models/src/fyndr/LeadsExport/LeadsExport.test.ts @@ -0,0 +1,65 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; + +import type { LeadsExportRequestData } from "./types.js"; + +import { buildLeadsExportData } from "../../testing/builders/buildLeadsExportData.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { + LeadsExportListItem, + LeadsExportList, + LeadsExport, +} from "./LeadsExport.js"; + +afterEach(resetBehaviors); + +describe("LeadsExport", () => { + test("queries exports with request config and maps list items", async () => { + const list = vi + .fn() + .mockResolvedValue({ items: [buildLeadsExportData()], totalCount: 8 }); + const requestConfig = { retryCache: false }; + installBehaviors({ leadsExport: { list } }); + + const result = await LeadsExport.query("c-1", { limit: 3 }).execute( + requestConfig, + ); + + expect(list).toHaveBeenCalledWith("c-1", { limit: 3 }, requestConfig); + expect(result).toBeInstanceOf(LeadsExportList); + expect(result.items[0]).toBeInstanceOf(LeadsExportListItem); + expect(result.items[0]?.exportedAt.toUTC().toISO()).toBe( + "2024-01-01T00:00:00.000Z", + ); + expect(result.items[0]?.exportedBy).toEqual({ userId: "u-1" }); + expect(result.items[0]?.leadCount).toBe(5); + expect(result.totalCount).toBe(8); + }); + + test("getTotalCount executes a one-limit query", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 6, items: [] }); + installBehaviors({ leadsExport: { list } }); + + expect(await LeadsExport.query("c-1", { skip: 2 }).getTotalCount()).toBe(6); + expect(list).toHaveBeenCalledWith("c-1", { limit: 1, skip: 2 }, undefined); + }); + + test("create delegates and returns the behavior result", async () => { + const response = { base64FileContent: "csv", exportId: "e-1" }; + const create = vi.fn().mockResolvedValue(response); + const data: LeadsExportRequestData = { + fieldKeys: ["domain"], + exportAllLeads: true, + }; + installBehaviors({ leadsExport: { create } }); + + await expect(LeadsExport.create("c-1", data)).resolves.toBe(response); + expect(create).toHaveBeenCalledWith("c-1", data); + }); + + test("creates references by id", () => { + expect(LeadsExport.ofId("e-1").id).toBe("e-1"); + }); +}); diff --git a/packages/models/src/fyndr/LeadsExport/LeadsExport.ts b/packages/models/src/fyndr/LeadsExport/LeadsExport.ts new file mode 100644 index 00000000..5d3e50d9 --- /dev/null +++ b/packages/models/src/fyndr/LeadsExport/LeadsExport.ts @@ -0,0 +1,130 @@ +import type { AxiosRequestConfig } from "axios"; + +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; + +import type { + LeadsExportListQueryData, + LeadsExportListItemData, + LeadsExportRequestData, + LeadsExportExporter, + LeadsExportData, +} from "./types.js"; + +import { Customer } from "../../customer/Customer/Customer.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "LeadsExport", +}) +export class LeadsExport extends ReferenceModel { + public constructor(id: string) { + super(id); + } + + public static async create(customerId: string, data: LeadsExportRequestData) { + return await config.behaviors.leadsExport.create(customerId, data); + } + + public static ofId(id: string) { + return new LeadsExport(id); + } + + public static query( + customerId: string, + query: LeadsExportListQueryData = {}, + ) { + return new LeadsExportListQuery(customerId, query); + } +} + +export class LeadsExportCommon extends WithData< + LeadsExportListItemData | LeadsExportData +>()(LeadsExport) { + public override readonly data: LeadsExportListItemData | LeadsExportData; + public readonly exportedAt: DateTime; + public readonly exportedBy: LeadsExportExporter; + public readonly leadCount: number; + + public constructor(data: LeadsExportListItemData | LeadsExportData) { + super(data.exportId); + this.data = data; + this.exportedAt = DateTime.fromISO(data.exportedAt); + this.exportedBy = data.exportedBy; + this.leadCount = data.leadCount; + } +} + +export class LeadsExportDetailed extends LeadsExportCommon { + public constructor(data: LeadsExportData) { + super(data); + } +} + +export class LeadsExportListItem extends LeadsExportCommon { + public constructor(data: LeadsExportListItemData) { + super(data); + } +} + +export class LeadsExportListQuery extends ListQueryModel { + public readonly customer: Customer; + + public constructor(customerId: string, query: LeadsExportListQueryData = {}) { + super(query); + this.customer = Customer.ofId(customerId); + } + + public async execute(requestConfig?: AxiosRequestConfig) { + const { totalCount, items } = await config.behaviors.leadsExport.list( + this.customer.id, + this.query, + requestConfig, + ); + + return new LeadsExportList( + this.customer.id, + this.query, + items.map((le) => new LeadsExportListItem(le)), + totalCount, + ); + } + + public async getTotalCount() { + const { totalCount } = await this.refine({ + limit: 1, + }).execute(); + return totalCount; + } + + public refine(query: LeadsExportListQueryData) { + return new LeadsExportListQuery(this.customer.id, { + ...this.query, + ...query, + }); + } +} + +export class LeadsExportList extends WithListData()( + LeadsExportListQuery, +) { + public override readonly items: readonly LeadsExportListItem[]; + public override readonly totalCount: number; + + public constructor( + customerId: string, + query: LeadsExportListQueryData, + leadsExports: LeadsExportListItem[], + totalCount: number, + ) { + super(customerId, query); + this.items = Object.freeze(leadsExports); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/fyndr/LeadsExport/behavior/api.ts b/packages/models/src/fyndr/LeadsExport/behavior/api.ts new file mode 100644 index 00000000..e41d1ad6 --- /dev/null +++ b/packages/models/src/fyndr/LeadsExport/behavior/api.ts @@ -0,0 +1,59 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { LeadsExportBehavior } from "./types.js"; + +import { + withAxiosRequestConfig, + resolveTotalCount, +} from "../../../base/index.js"; +import { validateResponse } from "../../../base/api/validateResponse.js"; + +export const apiLeadsExportBehavior = ( + client: MittwaldAPIV2Client, +): LeadsExportBehavior => ({ + create: async (customerId, data) => { + const response = await client.leadFyndr.leadfyndrCreateLeadsExport({ + headers: { + accept: "application/json", + }, + customerId, + data, + }); + + validateResponse(response, [200, 404]); + + if (response.status === 200) { + if (typeof response.data === "string") { + throw new Error("LeadsExportBehavior dont expect a string value"); + } + + return { + base64FileContent: response.data.contentBase64, + exportId: response.data.exportId, + }; + } else if (response.status === 404) { + const errorMessage = response.data.message as string | undefined; + + return { + errorType: "NoLeadsToExport", + errorMessage, + }; + } + }, + list: async (customerId, query, requestConfig) => { + const response = await client.leadFyndr.leadfyndrGetLeadsExportHistory( + { + queryParameters: query, + customerId, + }, + withAxiosRequestConfig(requestConfig), + ); + + validateResponse(response, 200); + + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, +}); diff --git a/packages/models/src/fyndr/LeadsExport/behavior/index.ts b/packages/models/src/fyndr/LeadsExport/behavior/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/fyndr/LeadsExport/behavior/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/fyndr/LeadsExport/behavior/types.ts b/packages/models/src/fyndr/LeadsExport/behavior/types.ts new file mode 100644 index 00000000..21c8e238 --- /dev/null +++ b/packages/models/src/fyndr/LeadsExport/behavior/types.ts @@ -0,0 +1,30 @@ +import type { AxiosRequestConfig } from "axios"; + +import type { QueryResponseData } from "../../../base/index.js"; +import type { + LeadsExportListQueryData, + LeadsExportListItemData, + LeadsExportRequestData, +} from "../types.js"; + +export interface LeadsExportBehavior { + create: ( + customerId: string, + data: LeadsExportRequestData, + ) => Promise< + | { + errorType: "NoLeadsToExport" | string; + errorMessage: string | undefined; + } + | { + base64FileContent: string; + exportId: string; + } + | undefined + >; + list: ( + customerId: string, + query: LeadsExportListQueryData, + requestConfig?: AxiosRequestConfig, + ) => Promise>; +} diff --git a/packages/models/src/fyndr/LeadsExport/index.ts b/packages/models/src/fyndr/LeadsExport/index.ts new file mode 100644 index 00000000..13b9367b --- /dev/null +++ b/packages/models/src/fyndr/LeadsExport/index.ts @@ -0,0 +1,2 @@ +export * from "./LeadsExport.js"; +export * from "./types.js"; diff --git a/packages/models/src/fyndr/LeadsExport/types.ts b/packages/models/src/fyndr/LeadsExport/types.ts new file mode 100644 index 00000000..edbb7c84 --- /dev/null +++ b/packages/models/src/fyndr/LeadsExport/types.ts @@ -0,0 +1,18 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type LeadsExportData = + MittwaldAPIV2.Operations.LeadfyndrGetLeadsExportHistory.ResponseData[number]; + +export type LeadsExportListItemData = + MittwaldAPIV2.Operations.LeadfyndrGetLeadsExportHistory.ResponseData[number]; + +export type LeadsExportListQueryData = + MittwaldAPIV2.Paths.V2CustomersCustomerIdUnlockedLeadsExports.Get.Parameters.Query; + +export type LeadsExportRequestData = + MittwaldAPIV2.Paths.V2CustomersCustomerIdUnlockedLeadsExport.Post.Parameters.RequestBody; + +export type LeadsExportExporter = LeadsExportData["exportedBy"]; + +export type LeadsExportExportableField = + LeadsExportRequestData["fieldKeys"][number]; diff --git a/packages/models/src/fyndr/UnlockedLead/UnlockedLead.test.ts b/packages/models/src/fyndr/UnlockedLead/UnlockedLead.test.ts new file mode 100644 index 00000000..af9c1a4e --- /dev/null +++ b/packages/models/src/fyndr/UnlockedLead/UnlockedLead.test.ts @@ -0,0 +1,186 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { buildUnlockedLeadData } from "../../testing/builders/buildUnlockedLeadData.js"; +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { getFormattedSalesVolume } from "../util/helper.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { + UnlockedLeadListQuery, + UnlockedLeadDetailed, + UnlockedLeadListItem, + UnlockedLeadList, + UnlockedLead, +} from "./UnlockedLead.js"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? type.name : undefined, +})); + +afterEach(resetBehaviors); + +describe("UnlockedLead", () => { + test("find and get delegate and handle missing data", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildUnlockedLeadData()) + .mockResolvedValueOnce(buildUnlockedLeadData()) + .mockResolvedValueOnce(undefined); + installBehaviors({ unlockedLead: { find } }); + + expect(await UnlockedLead.find("c-1", "l-1")).toBeInstanceOf( + UnlockedLeadDetailed, + ); + expect(find).toHaveBeenCalledWith("c-1", "l-1"); + expect(await UnlockedLead.get("c-1", "l-1")).toBeInstanceOf( + UnlockedLeadDetailed, + ); + await expect(UnlockedLead.get("c-1", "missing")).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("exposes unlocked lead data through getters", () => { + const data = buildUnlockedLeadData({ + reservedAt: "2024-03-01T00:00:00.000Z", + businessFields: ["IT", "Retail"], + reservationAllowed: undefined, + }); + const lead = new UnlockedLeadDetailed("c-1", data); + const medium = new UnlockedLeadDetailed( + "c-1", + buildUnlockedLeadData({ potential: 0.55 }), + ); + const low = new UnlockedLeadDetailed( + "c-1", + buildUnlockedLeadData({ potential: 0.5 }), + ); + const unversioned = new UnlockedLeadDetailed( + "c-1", + buildUnlockedLeadData({ + mainTechnology: { categoryPriority: 1, name: "React" }, + }), + ); + + expect(lead.businessFields).toBe("IT, Retail"); + expect(lead.potential).toBe(72); + expect(lead.potentialType).toBe("high"); + expect(medium.potentialType).toBe("medium"); + expect(low.potentialType).toBe("low"); + expect(lead.formattedSalesVolume).toBe(getFormattedSalesVolume(2_000_000)); + expect(lead.mainTechnologyWithVersionText).toBe("TYPO3 12"); + expect(unversioned.mainTechnologyWithVersionText).toBe("React"); + expect(lead.reservedAt?.toUTC().toISO()).toBe("2024-03-01T00:00:00.000Z"); + expect(lead.isReserved).toBe(true); + expect(lead.unlockedAt.toUTC().toISO()).toBe("2024-02-01T00:00:00.000Z"); + expect(lead.socialMedia).toBe(data.socialMedia); + expect(lead.contact).toBe(data.contact); + expect(lead.languages).toBe(data.languages); + expect(lead.reservationAllowed).toBe(false); + expect(lead.actualUrl).toBe("https://example.com"); + expect(lead.domain).toBe("example.com"); + }); + + test("reservation mutations delegate with identifiers", async () => { + const reserve = vi.fn().mockResolvedValue(undefined); + const removeReservation = vi.fn().mockResolvedValue(undefined); + installBehaviors({ unlockedLead: { removeReservation, reserve } }); + const lead = UnlockedLead.ofId("c-1", "l-1"); + + await lead.reserve(); + await lead.removeReservation(); + + expect(reserve).toHaveBeenCalledWith("c-1", "l-1"); + expect(removeReservation).toHaveBeenCalledWith("c-1", "l-1"); + }); + + test("queries and maps unlocked lead lists", async () => { + const list = vi + .fn() + .mockResolvedValue({ items: [buildUnlockedLeadData()], totalCount: 9 }); + installBehaviors({ unlockedLead: { list } }); + + const result = await UnlockedLead.query("c-1", { limit: 4 }).execute(); + + expect(list).toHaveBeenCalledWith("c-1", { limit: 4 }); + expect(result).toBeInstanceOf(UnlockedLeadList); + expect(result.items[0]).toBeInstanceOf(UnlockedLeadListItem); + expect(result.totalCount).toBe(9); + }); + + test("count and reserved queries merge their special filters", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 12, items: [] }); + installBehaviors({ unlockedLead: { list } }); + + expect(await UnlockedLead.query("c-1", { skip: 2 }).getTotalCount()).toBe( + 12, + ); + expect(list).toHaveBeenLastCalledWith("c-1", { limit: 0, skip: 2 }); + await UnlockedLeadListQuery.reserved("c-1", { limit: 3 }).execute(); + expect(list).toHaveBeenLastCalledWith("c-1", { reserved: true, limit: 3 }); + }); + + test("detailed unlocked leads retain reference identity", () => { + expect( + new UnlockedLeadDetailed("c-1", buildUnlockedLeadData()), + ).toBeInstanceOf(UnlockedLead); + }); + + test("findCommon and getCommon delegate to find", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildUnlockedLeadData()) + .mockResolvedValueOnce(undefined) + .mockResolvedValueOnce(buildUnlockedLeadData()) + .mockResolvedValueOnce(undefined); + installBehaviors({ unlockedLead: { find } }); + + expect(await UnlockedLead.ofId("c-1", "l-1").findCommon()).toBeInstanceOf( + UnlockedLeadDetailed, + ); + expect(find).toHaveBeenCalledWith("c-1", "l-1"); + expect(await UnlockedLead.ofId("c-1", "l-1").findCommon()).toBeUndefined(); + expect(await UnlockedLead.ofId("c-1", "l-1").getCommon()).toBeInstanceOf( + UnlockedLeadDetailed, + ); + await expect( + UnlockedLead.ofId("c-1", "missing").getCommon(), + ).rejects.toBeInstanceOf(ObjectNotFoundError); + }); + + test("getCommon and findCommon are idempotent on a materialized unlocked lead", async () => { + const find = vi.fn(); + installBehaviors({ unlockedLead: { find } }); + const detailed = new UnlockedLeadDetailed("c-1", buildUnlockedLeadData()); + + expect(await detailed.getCommon()).toBe(detailed); + expect(await detailed.findCommon()).toBe(detailed); + expect(find).not.toHaveBeenCalled(); + }); + + test("aggregateMetaData pins the cache identity", () => { + expect(UnlockedLead.aggregateMetaData).toBeInstanceOf(AggregateMetaData); + expect(UnlockedLead.aggregateMetaData.domain).toBe("leadfinder"); + expect(UnlockedLead.aggregateMetaData.aggregate).toBe("unlockedlead"); + }); + + test("optional unlocked lead fields fall back when data is absent", () => { + const lead = new UnlockedLeadDetailed( + "c-1", + buildUnlockedLeadData({ mainTechnology: undefined }), + ); + + expect(lead.reservedAt).toBeUndefined(); + expect(lead.isReserved).toBe(false); + expect(lead.scannedAt).toBeUndefined(); + expect(lead.mainTechnology).toBeUndefined(); + expect(lead.mainTechnologyWithVersionText).toBeUndefined(); + }); +}); diff --git a/packages/models/src/fyndr/UnlockedLead/UnlockedLead.ts b/packages/models/src/fyndr/UnlockedLead/UnlockedLead.ts new file mode 100644 index 00000000..3596109f --- /dev/null +++ b/packages/models/src/fyndr/UnlockedLead/UnlockedLead.ts @@ -0,0 +1,253 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; + +import type { LeadTechnologyData } from "../Lead/index.js"; +import type { + UnlockedLeadHosterInformationData, + UnlockedLeadSocialMediaData, + UnlockedLeadListQueryData, + UnlockedLeadListItemData, + UnlockedLeadCompanyData, + UnlockedLeadContactData, + UnlockedLeadMetricsData, + UnlockedLeadData, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { getFormattedSalesVolume } from "../util/helper.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "UnlockedLead", +}) +export class UnlockedLead extends ReferenceModel { + public static aggregateMetaData = new AggregateMetaData( + "leadfinder", + "unlockedlead", + ); + + public readonly customerId: string; + + public constructor(customerId: string, id: string) { + super(id); + this.customerId = customerId; + } + + public static async find(customerId: string, id: string) { + const data = await config.behaviors.unlockedLead.find(customerId, id); + if (data) { + return new UnlockedLeadDetailed(customerId, data); + } + } + + public static async get(customerId: string, id: string) { + const unlockedLead = await this.find(customerId, id); + assertObjectFound(unlockedLead, UnlockedLead, id); + return unlockedLead; + } + + public static ofId(customerId: string, id: string) { + return new UnlockedLead(customerId, id); + } + + public static query( + customerId: string, + query: UnlockedLeadListQueryData = {}, + ) { + return new UnlockedLeadListQuery(customerId, query); + } + + public async findCommon(): Promise { + return this instanceof UnlockedLeadCommon ? this : this.findDetailed(); + } + + public async findDetailed(): Promise { + return UnlockedLead.find(this.customerId, this.id); + } + + public async getCommon(): Promise { + return this instanceof UnlockedLeadCommon ? this : this.getDetailed(); + } + + public async getDetailed(): Promise { + return UnlockedLead.get(this.customerId, this.id); + } + + public async removeReservation() { + await config.behaviors.unlockedLead.removeReservation( + this.customerId, + this.id, + ); + } + + public async reserve() { + await config.behaviors.unlockedLead.reserve(this.customerId, this.id); + } +} + +export class UnlockedLeadCommon extends WithData< + UnlockedLeadListItemData | UnlockedLeadData +>()(UnlockedLead) { + public readonly actualUrl: string; + public readonly businessFields: string; + public readonly company: UnlockedLeadCompanyData; + public readonly contact: UnlockedLeadContactData; + public override readonly data: UnlockedLeadListItemData | UnlockedLeadData; + public readonly description: string; + public readonly domain: string; + public readonly hosterInformation: UnlockedLeadHosterInformationData; + public readonly isReserved: boolean; + public readonly languages: string[]; + public readonly mainTechnology: LeadTechnologyData | undefined; + public readonly mainTechnologyWithVersionText: string | undefined; + public readonly metrics: UnlockedLeadMetricsData; + public readonly potential: number; + public readonly reservationAllowed: boolean; + public readonly reservedAt: DateTime | undefined; + public readonly scannedAt?: DateTime; + public readonly screenshotBase64: string; + public readonly socialMedia: UnlockedLeadSocialMediaData[]; + public readonly technologies: LeadTechnologyData[]; + public readonly unlockedAt: DateTime; + + public get formattedSalesVolume(): string { + return getFormattedSalesVolume(this.company.salesVolume); + } + + public get potentialType(): "medium" | "high" | "low" { + if (this.potential > 60) { + return "high"; + } else if (this.potential > 50) { + return "medium"; + } else { + return "low"; + } + } + + public constructor( + customerId: string, + data: UnlockedLeadListItemData | UnlockedLeadData, + ) { + super(customerId, data.leadId); + this.data = data; + this.domain = data.domain; + this.actualUrl = data.actualUrl; + this.businessFields = data.businessFields.join(", "); + this.description = data.description; + this.screenshotBase64 = data.screenshot; + this.potential = Math.round(data.potential * 100); + this.metrics = data.metrics; + this.mainTechnology = data.mainTechnology; + this.mainTechnologyWithVersionText = data.mainTechnology + ? `${data.mainTechnology.name}${data.mainTechnology.version ? ` ${data.mainTechnology.version}` : ""}` + : undefined; + this.company = data.company; + this.technologies = data.technologies; + this.reservedAt = data.reservedAt + ? DateTime.fromISO(data.reservedAt) + : undefined; + this.isReserved = !!data.reservedAt; + this.unlockedAt = DateTime.fromISO(data.unlockedAt); + this.scannedAt = data.scannedAt + ? DateTime.fromISO(data.scannedAt) + : undefined; + this.socialMedia = data.socialMedia; + this.hosterInformation = data.hoster; + this.contact = data.contact; + this.languages = data.languages; + this.reservationAllowed = data.reservationAllowed ?? false; + } +} + +export class UnlockedLeadDetailed extends UnlockedLeadCommon { + public override readonly data: UnlockedLeadData; + + public constructor(customerId: string, data: UnlockedLeadData) { + super(customerId, data); + this.data = data; + } +} + +export class UnlockedLeadListItem extends UnlockedLeadCommon { + public override readonly data: UnlockedLeadListItemData; + + public constructor(customerId: string, data: UnlockedLeadListItemData) { + super(customerId, data); + this.data = data; + } +} + +export class UnlockedLeadListQuery extends ListQueryModel { + private readonly customerId: string; + + public constructor( + customerId: string, + query: UnlockedLeadListQueryData = {}, + ) { + super(query); + this.customerId = customerId; + } + + public static reserved( + customerId: string, + query: UnlockedLeadListQueryData = {}, + ) { + return new UnlockedLeadListQuery(customerId, { + ...query, + reserved: true, + }); + } + + public async execute() { + const { totalCount, items } = await config.behaviors.unlockedLead.list( + this.customerId, + this.query, + ); + + return new UnlockedLeadList( + this.customerId, + this.query, + items.map((item) => new UnlockedLeadListItem(this.customerId, item)), + totalCount, + ); + } + + public async getTotalCount() { + const { totalCount } = await this.refine(this.customerId, { + limit: 0, + }).execute(); + return totalCount; + } + + public refine(customerId: string, query: UnlockedLeadListQueryData) { + return new UnlockedLeadListQuery(customerId, { + ...this.query, + ...query, + }); + } +} + +export class UnlockedLeadList extends WithListData()( + UnlockedLeadListQuery, +) { + public override readonly items: readonly UnlockedLeadListItem[]; + public override readonly totalCount: number; + + public constructor( + customerId: string, + query: UnlockedLeadListQueryData, + leads: UnlockedLeadListItem[], + totalCount: number, + ) { + super(customerId, query); + this.items = Object.freeze(leads); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/fyndr/UnlockedLead/behavior/api.ts b/packages/models/src/fyndr/UnlockedLead/behavior/api.ts new file mode 100644 index 00000000..0bb60f0c --- /dev/null +++ b/packages/models/src/fyndr/UnlockedLead/behavior/api.ts @@ -0,0 +1,48 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { UnlockedLeadBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount } from "../../../base/index.js"; + +export const apiUnlockedLeadBehaviors = ( + client: MittwaldAPIV2Client, +): UnlockedLeadBehaviors => ({ + list: async (customerId, query) => { + const response = await client.leadFyndr.leadfyndrListUnlockedLeads({ + queryParameters: query, + customerId, + }); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response, response.data.leads.length), + items: response.data.leads, + }; + }, + find: async (customerId, leadId) => { + const response = await client.leadFyndr.leadfyndrGetUnlockedLead({ + customerId, + leadId, + }); + + if (response.status === 200) { + return response.data; + } + validateResponse(response, [403, 404, 429]); + }, + removeReservation: async (customerId, leadId) => { + const response = + await client.leadFyndr.leadfyndrRemoveUnlockedLeadReservation({ + customerId, + leadId, + }); + validateResponse(response, 200); + }, + reserve: async (customerId, leadId) => { + const response = await client.leadFyndr.leadfyndrReserveUnlockedLead({ + customerId, + leadId, + }); + validateResponse(response, 200); + }, +}); diff --git a/packages/models/src/fyndr/UnlockedLead/behavior/index.ts b/packages/models/src/fyndr/UnlockedLead/behavior/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/fyndr/UnlockedLead/behavior/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/fyndr/UnlockedLead/behavior/types.ts b/packages/models/src/fyndr/UnlockedLead/behavior/types.ts new file mode 100644 index 00000000..15fd249d --- /dev/null +++ b/packages/models/src/fyndr/UnlockedLead/behavior/types.ts @@ -0,0 +1,19 @@ +import type { QueryResponseData } from "../../../base/index.js"; +import type { + UnlockedLeadListQueryData, + UnlockedLeadListItemData, + UnlockedLeadData, +} from "../types.js"; + +export interface UnlockedLeadBehaviors { + list: ( + customerId: string, + query?: UnlockedLeadListQueryData, + ) => Promise>; + find: ( + customerId: string, + leadId: string, + ) => Promise; + removeReservation: (customerId: string, leadId: string) => Promise; + reserve: (customerId: string, leadId: string) => Promise; +} diff --git a/packages/models/src/fyndr/UnlockedLead/index.ts b/packages/models/src/fyndr/UnlockedLead/index.ts new file mode 100644 index 00000000..123b4a19 --- /dev/null +++ b/packages/models/src/fyndr/UnlockedLead/index.ts @@ -0,0 +1,2 @@ +export * from "./types.js"; +export * from "./UnlockedLead.js"; diff --git a/packages/models/src/fyndr/UnlockedLead/types.ts b/packages/models/src/fyndr/UnlockedLead/types.ts new file mode 100644 index 00000000..946ad3b1 --- /dev/null +++ b/packages/models/src/fyndr/UnlockedLead/types.ts @@ -0,0 +1,21 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type UnlockedLeadData = + MittwaldAPIV2.Operations.LeadfyndrGetUnlockedLead.ResponseData; + +export type UnlockedLeadListItemData = + MittwaldAPIV2.Operations.LeadfyndrListUnlockedLeads.ResponseData["leads"][number]; + +export type UnlockedLeadListQueryData = + MittwaldAPIV2.Paths.V2CustomersCustomerIdUnlockedLeads.Get.Parameters.Query; + +export type UnlockedLeadMetricsData = UnlockedLeadData["metrics"]; + +export type UnlockedLeadCompanyData = UnlockedLeadData["company"]; + +export type UnlockedLeadSocialMediaData = + UnlockedLeadData["socialMedia"][number]; + +export type UnlockedLeadHosterInformationData = UnlockedLeadData["hoster"]; + +export type UnlockedLeadContactData = UnlockedLeadData["contact"]; diff --git a/packages/models/src/fyndr/index.ts b/packages/models/src/fyndr/index.ts new file mode 100644 index 00000000..a069f2e3 --- /dev/null +++ b/packages/models/src/fyndr/index.ts @@ -0,0 +1,8 @@ +export * from "./City/index.js"; +export * from "./FinderProfile/index.js"; +export * from "./FinderProfileRequest/index.js"; +export * from "./Lead/index.js"; +export * from "./LeadsExport/index.js"; +export type { AnyLeadCommon } from "./types.js"; +export * from "./UnlockedLead/index.js"; +export * from "./util/LeadFyndr.js"; diff --git a/packages/models/src/fyndr/types.ts b/packages/models/src/fyndr/types.ts new file mode 100644 index 00000000..8f9607d8 --- /dev/null +++ b/packages/models/src/fyndr/types.ts @@ -0,0 +1,4 @@ +import type { UnlockedLeadCommon } from "./UnlockedLead/index.js"; +import type { LeadCommon } from "./Lead/index.js"; + +export type AnyLeadCommon = UnlockedLeadCommon | LeadCommon; diff --git a/packages/models/src/fyndr/util/LeadFyndr.ts b/packages/models/src/fyndr/util/LeadFyndr.ts new file mode 100644 index 00000000..2954a46f --- /dev/null +++ b/packages/models/src/fyndr/util/LeadFyndr.ts @@ -0,0 +1,27 @@ +import { FinderProfileRequest } from "../FinderProfileRequest/index.js"; +import { FinderProfile } from "../FinderProfile/index.js"; + +export class LeadFyndr { + public static async customerIdHasAccess(customerId: string) { + const finderProfile = await FinderProfile.ofCustomer( + customerId, + ).findDetailed({ + retryCache: { + cache: false, + retry: false, + }, + }); + return finderProfile !== undefined && finderProfile.hasAccess(); + } + + public static async customerIdHasAccessRequest(customerId: string) { + return ( + (await FinderProfileRequest.ofCustomer(customerId).findDetailed({ + retryCache: { + cache: false, + retry: false, + }, + })) !== undefined + ); + } +} diff --git a/packages/models/src/fyndr/util/helper.ts b/packages/models/src/fyndr/util/helper.ts new file mode 100644 index 00000000..93c16efa --- /dev/null +++ b/packages/models/src/fyndr/util/helper.ts @@ -0,0 +1,27 @@ +const formatSalesVolume = ( + revenue: number, + currencySuffix: string | undefined = undefined, + digits = 1, +): string => { + const formatted = revenue.toLocaleString("de-DE", { + minimumFractionDigits: digits, + maximumFractionDigits: digits, + }); + + return [formatted, currencySuffix, "€"].filter(Boolean).join(" "); +}; + +export const getFormattedSalesVolume = ( + revenue: number | undefined = 0, +): string => { + switch (true) { + case revenue >= 1_000_000_000: + return formatSalesVolume(revenue / 1_000_000_000, "Mrd."); + case revenue >= 1_000_000: + return formatSalesVolume(revenue / 1_000_000, "Mio."); + case revenue >= 1_000: + return formatSalesVolume(revenue / 1_000, "Tsd."); + default: + return formatSalesVolume(revenue); + } +}; diff --git a/packages/models/src/index.ts b/packages/models/src/index.ts index 2bda4d61..47c75c7c 100644 --- a/packages/models/src/index.ts +++ b/packages/models/src/index.ts @@ -1,7 +1,43 @@ -export { MittwaldAPIV2Client } from "@mittwald/api-client"; -export * from "./config/index.js"; +export * from "./access/index.js"; +export * from "./activity/index.js"; +export * from "./ai/index.js"; +export * from "./app/index.js"; +export * from "./article/index.js"; +export * from "./auth/index.js"; +export * from "./backup/index.js"; +export { registerDefaultOnBeforeRequestHandler } from "./base/api/onBeforeRequest.js"; +export * from "./base/lib/extractId.js"; +export * from "./base/models/BaseModel.js"; +export * from "./base/models/DataModel.js"; +export * from "./base/models/ListDataModel.js"; +export * from "./base/models/ListQueryModel.js"; +export * from "./base/models/ReferenceModel.js"; +export * from "./certificate/index.js"; +export * from "./common/index.js"; +export type { InitApiModelsOptions } from "./config/initApiModels.js"; +export { initApiModels } from "./config/initApiModels.js"; +export * from "./container/index.js"; +export * from "./contract/index.js"; +export * from "./conversation/index.js"; +export * from "./cronjob/index.js"; +export * from "./customer/index.js"; +export * from "./database/index.js"; +export * from "./dns/index.js"; +export * from "./domain/index.js"; +export * from "./errors/index.js"; +export * from "./file/index.js"; +export * from "./fyndr/index.js"; +export * from "./ingress/index.js"; +export * from "./invoice/index.js"; +export type { ExplicitAny } from "./lib/types.js"; +export * from "./mail/index.js"; +export * from "./marketplace/index.js"; +export * from "./monitoring/index.js"; +export * from "./newsletter/index.js"; +export * from "./notifications/index.js"; +export * from "./order/index.js"; +export * from "./performance/index.js"; export * from "./project/index.js"; +export * from "./relocation/index.js"; export * from "./server/index.js"; -export * from "./domain/index.js"; -export * from "./customer/index.js"; -export * from "./base/index.js"; +export * from "./user/index.js"; diff --git a/packages/models/src/ingress/Ingress/Ingress.test.ts b/packages/models/src/ingress/Ingress/Ingress.test.ts new file mode 100644 index 00000000..896a9017 --- /dev/null +++ b/packages/models/src/ingress/Ingress/Ingress.test.ts @@ -0,0 +1,229 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { buildTlsCertificateData } from "../../testing/builders/buildTlsCertificateData.js"; +import { buildIngressData } from "../../testing/builders/buildIngressData.js"; +import { buildTlsAcmeData } from "../../testing/builders/buildTlsAcmeData.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { ReferenceModel } from "../../base/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { Project } from "../../project/index.js"; +import { + IngressDetailed, + IngressListItem, + IngressCommon, + IngressList, + Ingress, +} from "./Ingress.js"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (t: unknown) => + typeof t === "function" ? (t as { name?: string }).name : undefined, +})); + +afterEach(resetBehaviors); + +describe("Ingress", () => { + test("aggregateMetaData carries the ingress/ingress identity", () => { + expect(Ingress.aggregateMetaData).toBeInstanceOf(AggregateMetaData); + expect(Ingress.aggregateMetaData.domain).toBe("ingress"); + expect(Ingress.aggregateMetaData.aggregate).toBe("ingress"); + }); + + test("findCommon delegates to a detailed variant for a reference", async () => { + const find = vi.fn().mockResolvedValue(buildIngressData({ id: "i-1" })); + installBehaviors({ ingress: { find } }); + + const common = await Ingress.ofId("i-1").findCommon(); + + expect(common).toBeInstanceOf(IngressCommon); + expect(find).toHaveBeenCalledWith("i-1"); + }); + + test("getCommon throws for a missing reference", async () => { + installBehaviors({ + ingress: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(Ingress.ofId("i-1").getCommon()).rejects.toThrow(); + }); + + test("getCommon/findCommon are idempotent on materialized models", async () => { + const find = vi.fn(); + installBehaviors({ ingress: { find } }); + const detailed = new IngressDetailed(buildIngressData()); + const item = new IngressListItem(buildIngressData()); + + expect(await detailed.getCommon()).toBe(detailed); + expect(await detailed.findCommon()).toBe(detailed); + expect(await item.getCommon()).toBe(item); + expect(await item.findCommon()).toBe(item); + expect(find).not.toHaveBeenCalled(); + }); + + test("omits optional verification record for unverified ownership", () => { + const ingress = new IngressListItem( + buildIngressData({ ownership: { verified: false } }), + ); + + expect(ingress.verificationTxtRecord).toBeUndefined(); + expect(ingress.isVerified).toBe(false); + }); + + test("find delegates and materializes detailed data", async () => { + const find = vi.fn().mockResolvedValue(buildIngressData({ id: "i-1" })); + installBehaviors({ ingress: { find } }); + + const ingress = await Ingress.find("i-1"); + + expect(find).toHaveBeenCalledWith("i-1"); + expect(ingress).toBeInstanceOf(IngressDetailed); + expect(ingress?.id).toBe("i-1"); + }); + + test("find returns undefined when the behavior finds nothing", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ ingress: { find } }); + + expect(await Ingress.find("missing")).toBeUndefined(); + expect(find).toHaveBeenCalledWith("missing"); + }); + + test("get throws when the ingress is missing", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ ingress: { find } }); + + await expect(Ingress.get("missing")).rejects.toThrow(); + }); + + test("create delegates and returns an ingress reference", async () => { + const create = vi.fn().mockResolvedValue({ id: "new-ingress" }); + const paths = [{ target: { useDefaultPage: true }, path: "/" }]; + installBehaviors({ ingress: { create } }); + + const ingress = await Ingress.create("p-1", "example.com", paths); + + expect(create).toHaveBeenCalledWith("p-1", "example.com", paths); + expect(ingress).toBeInstanceOf(Ingress); + expect(ingress.id).toBe("new-ingress"); + }); + + test("instance mutations delegate with the ingress id", async () => { + const deleteIngress = vi.fn().mockResolvedValue(undefined); + const updatePaths = vi.fn().mockResolvedValue(undefined); + const verifyOwnership = vi.fn().mockResolvedValue(true); + const paths = [{ target: { useDefaultPage: true }, path: "/" }]; + installBehaviors({ + ingress: { delete: deleteIngress, verifyOwnership, updatePaths }, + }); + const ingress = Ingress.ofId("i-1"); + + await ingress.delete(); + await ingress.updatePaths(paths); + await expect(ingress.verifyOwnership()).resolves.toBe(true); + + expect(deleteIngress).toHaveBeenCalledWith("i-1"); + expect(updatePaths).toHaveBeenCalledWith("i-1", paths); + expect(verifyOwnership).toHaveBeenCalledWith("i-1"); + }); + + test("query materializes pagination data", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildIngressData({ id: "i-1" })], + totalCount: 3, + }); + installBehaviors({ ingress: { list } }); + + const result = await Ingress.query({ project: "p-1" }).execute(); + + expect(list).toHaveBeenCalledWith({ projectId: "p-1" }, undefined); + expect(result).toBeInstanceOf(IngressList); + expect(result.items).toHaveLength(1); + expect(result.items[0]).toBeInstanceOf(IngressListItem); + expect(result.totalCount).toBe(3); + }); + + test("execute strips the project key and resolves a project reference id", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 0, items: [] }); + installBehaviors({ ingress: { list } }); + + await Ingress.query({ project: Project.ofId("p-2"), limit: 5 }).execute(); + + expect(list).toHaveBeenCalledWith( + { projectId: "p-2", limit: 5 }, + undefined, + ); + }); + + test("exposes derived ingress properties", () => { + const ingress = new IngressListItem( + buildIngressData({ + ips: { v4: ["9.9.9.9"], v6: [] }, + hostname: "www.example.com", + isDefault: true, + }), + ); + + expect(ingress.baseUrl).toBe("https://www.example.com"); + expect(ingress.hostname).toBe("www.example.com"); + expect(ingress.hostnameWithProtocol).toBe("https://www.example.com"); + expect(ingress.isDefault).toBe(true); + expect(ingress.isSubdomain).toBe(true); + expect(ingress.isVerified).toBe(true); + expect(ingress.ips).toEqual(["9.9.9.9"]); + expect(ingress.defaultPath.path).toBe("/"); + expect( + new IngressListItem(buildIngressData({ hostname: "example.com" })) + .isSubdomain, + ).toBe(false); + }); + + test("preserves the ghostmaker identity chain", () => { + const ingress = new IngressListItem(buildIngressData()); + + expect(ingress).toBeInstanceOf(IngressListItem); + expect(ingress).toBeInstanceOf(IngressCommon); + expect(ingress).toBeInstanceOf(Ingress); + expect(ingress).toBeInstanceOf(ReferenceModel); + expect(ingress.data).toBeDefined(); + }); + describe("getTlsAcmeStatus", () => { + test("returns the ACME status for an enabled ingress", () => { + const ingress = new IngressListItem( + buildIngressData({ + tls: buildTlsAcmeData({ isCreated: false, acme: true }), + isEnabled: true, + }), + ); + + expect(ingress.getTlsAcmeStatus()).toBe("running"); + }); + + test("returns undefined for a disabled ingress", () => { + const ingress = new IngressListItem( + buildIngressData({ + tls: buildTlsAcmeData({ isCreated: false, acme: true }), + isEnabled: false, + }), + ); + + expect(ingress.getTlsAcmeStatus()).toBeUndefined(); + }); + + test("returns undefined for certificate TLS", () => { + const ingress = new IngressListItem( + buildIngressData({ + tls: buildTlsCertificateData(), + isEnabled: true, + }), + ); + + expect(ingress.getTlsAcmeStatus()).toBeUndefined(); + }); + }); +}); diff --git a/packages/models/src/ingress/Ingress/Ingress.ts b/packages/models/src/ingress/Ingress/Ingress.ts new file mode 100644 index 00000000..5d9c11dd --- /dev/null +++ b/packages/models/src/ingress/Ingress/Ingress.ts @@ -0,0 +1,300 @@ +import type { AxiosRequestConfig } from "axios"; + +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { getSubdomain } from "tldts"; +import { omit } from "remeda"; + +import type { CertificateListQuery } from "../../certificate/Certificate/index.js"; +import type { TlsStatus, Tls } from "../../certificate/Tls/index.js"; +import type { IngressTargetData } from "../IngressTarget/index.js"; +import type { + IngressListQueryModelData, + CertificateSettings, + IngressListItemData, + IngressPathSettings, + DnsValidationError, + IngressData, +} from "./types.js"; + +import { Certificate } from "../../certificate/Certificate/Certificate.js"; +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { tlsFactory } from "../../certificate/Tls/index.js"; +import { Project } from "../../project/internal.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { IngressPath } from "../IngressPath/index.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "Ingress", +}) +export class Ingress extends ReferenceModel { + public static aggregateMetaData = new AggregateMetaData("ingress", "ingress"); + + public static async create( + projectId: string, + hostname: string, + paths: IngressPathSettings[], + ) { + const { id } = await config.behaviors.ingress.create( + projectId, + hostname, + paths, + ); + return new Ingress(id); + } + + public static async find(id: string) { + const data = await config.behaviors.ingress.find(id); + if (data) { + return new IngressDetailed(data); + } + } + + public static async findDefaultIngress(project?: Project | string) { + const ingresses = await this.query({ project }).execute(); + + return ingresses.items.find((i) => i.data.isDefault); + } + + public static async get(id: string) { + const ingress = await this.find(id); + assertObjectFound(ingress, Ingress, id); + return ingress; + } + + /** + * Ingresses compatible with a certificate — either an existing one (pass the + * `Certificate` model or its id) or a not-yet-saved one (pass its project and + * raw PEM `certificateContent`). + */ + public static async listCompatibleWithCertificate( + certificate: + | { certificateContent: string; project: Project | string } + | Certificate + | string, + ) { + if ( + typeof certificate === "string" || + certificate instanceof ReferenceModel + ) { + return await config.behaviors.ingress.listCompatibleWithCertificate({ + certificateId: extractId(certificate), + }); + } + return await config.behaviors.ingress.listCompatibleWithCertificate({ + certificateContent: certificate.certificateContent, + projectId: extractId(certificate.project), + }); + } + + public static ofHostname(hostname: string) { + return Ingress.ofId(hostname); + } + + public static ofId(id: string) { + return new Ingress(id); + } + + public static query = (query: IngressListQueryModelData = {}) => + new IngressListQuery(query); + + public async delete() { + await config.behaviors.ingress.delete(this.id); + } + + public findCommon(): + Promise | IngressCommon | undefined { + return this instanceof IngressCommon ? this : this.findDetailed(); + } + + public async findDetailed(): Promise { + return Ingress.find(this.id); + } + + public getCommon(): Promise | IngressCommon { + return this instanceof IngressCommon ? this : this.getDetailed(); + } + + public async getDetailed(): Promise { + return Ingress.get(this.id); + } + public async requestAcmeCertificate() { + await config.behaviors.ingress.requestAcmeCertificate(this.id); + } + public async updatePaths(paths: IngressPathSettings[]) { + await config.behaviors.ingress.updatePaths(this.id, paths); + } + public async updateTls(certificate: CertificateSettings) { + await config.behaviors.ingress.updateTls(this.id, certificate); + if (certificate.type === "acme" && certificate.acme) { + await this.requestAcmeCertificate(); + } + } + + public async verifyOwnership() { + return await config.behaviors.ingress.verifyOwnership(this.id); + } +} + +export class IngressCommon extends WithData< + IngressListItemData | IngressData +>()(Ingress) { + public readonly baseUrl: string; + public readonly certificates: CertificateListQuery; + public override readonly data: IngressListItemData | IngressData; + public readonly defaultPath: IngressPath; + public readonly dnsValidationErrors: DnsValidationError[]; + public readonly hostname: string; + public readonly hostnameWithProtocol: string; + public readonly ips: string[]; + public readonly isDefault: boolean; + public readonly isEnabled: boolean; + public readonly isSubdomain: boolean; + public readonly isVerified: boolean; + public readonly paths: readonly IngressPath[]; + public readonly project: Project; + public readonly tls: Tls; + public readonly verificationTxtRecord?: string; + + public constructor(data: IngressListItemData | IngressData) { + super(data.id); + this.data = data; + this.baseUrl = `https://${data.hostname}`; + this.paths = Object.freeze(data.paths.map((p) => new IngressPath(this, p))); + this.isDefault = data.isDefault; + const subdomain = getSubdomain(data.hostname); + this.isSubdomain = subdomain !== null && subdomain !== ""; + this.isVerified = data.ownership.verified; + this.tls = tlsFactory(data.tls); + + const defaultPath = this.paths.find((p) => p.path === "/"); + if (defaultPath === undefined) { + throw new Error(`Ingress ${this.describe()} has no default path.`); + } + this.defaultPath = defaultPath; + this.hostname = data.hostname; + this.hostnameWithProtocol = `https://${data.hostname}`; + this.ips = data.ips.v4; + this.verificationTxtRecord = data.ownership.txtRecord; + this.project = Project.ofId(data.projectId); + this.dnsValidationErrors = data.dnsValidationErrors; + this.isEnabled = data.isEnabled; + this.certificates = Certificate.query({ ingress: this }); + } + + public async addPath(path: string, target: IngressTargetData) { + const paths: IngressPathSettings[] = this.paths.map((i) => i.data); + await this.updatePaths([...paths, { target, path }]); + } + + public getTlsAcmeStatus(): TlsStatus | undefined { + if (!this.isEnabled) { + return undefined; + } + return this.tls.type === "acme" ? this.tls.getStatus() : undefined; + } + public async removePath(path: string) { + const paths: IngressPathSettings[] = this.paths + .filter((i) => i.path !== path) + .map((i) => i.data); + await this.updatePaths(paths); + } + + public async setDefaultPath(target: IngressTargetData) { + await this.updatePath("/", { path: "/", target }); + } + + public async updatePath(path: string, newPath: IngressPathSettings) { + const paths: IngressPathSettings[] = this.paths.map((i) => { + if (i.path === path) { + return { + target: newPath.target, + path: newPath.path, + }; + } + return { + target: i.target!.data, + path: i.path, + }; + }); + + await this.updatePaths(paths); + } +} + +export class IngressDetailed extends IngressCommon { + public override readonly data: IngressData; + public constructor(data: IngressData) { + super(data); + this.data = data; + } +} + +export class IngressListItem extends IngressCommon { + public override readonly data: IngressListItemData; + public constructor(data: IngressListItemData) { + super(data); + this.data = data; + } +} + +export class IngressListQuery extends ListQueryModel { + public async execute(options?: AxiosRequestConfig) { + const { totalCount, items } = await config.behaviors.ingress.list( + { + ...omit(this.query, [ + "project", + "certificate", + "appInstallation", + "container", + ]), + appInstallationId: extractId(this.query.appInstallation), + certificateId: extractId(this.query.certificate), + containerId: extractId(this.query.container), + projectId: extractId(this.query.project), + }, + options, + ); + + return new IngressList( + this.query, + items.map((d) => new IngressListItem(d)), + totalCount, + ); + } + + public async getTotalCount() { + const { totalCount } = await this.refine({ limit: 1 }).execute(); + return totalCount; + } + + public refine(query: IngressListQueryModelData) { + return new IngressListQuery({ + ...this.query, + ...query, + }); + } +} + +export class IngressList extends WithListData()( + IngressListQuery, +) { + public override readonly items: readonly IngressListItem[]; + public override readonly totalCount: number; + public constructor( + query: IngressListQueryModelData, + ingresses: IngressListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(ingresses); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/ingress/Ingress/behaviors/api.ts b/packages/models/src/ingress/Ingress/behaviors/api.ts new file mode 100644 index 00000000..a54cd840 --- /dev/null +++ b/packages/models/src/ingress/Ingress/behaviors/api.ts @@ -0,0 +1,131 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { IngressBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { ValidationError } from "../../../errors/index.js"; +import { IngressListItem } from "../Ingress.js"; +import { + withAxiosRequestConfig, + resolveTotalCount, + anyStatus403, +} from "../../../base/index.js"; + +export const apiIngressBehaviors = ( + client: MittwaldAPIV2Client, +): IngressBehaviors => ({ + create: async (projectId, hostname, paths) => { + const response = await client.domain.ingressCreateIngress({ + data: { projectId, hostname, paths }, + }); + + if (response.status === 409) { + const message = + response.data.message && typeof response.data.message === "string" + ? response.data.message + : undefined; + if (message?.includes("another project")) { + throw new ValidationError({ + message: "alreadyRegisteredInAnotherProject", + type: "alreadyRegisteredInAnotherProject", + path: "hostname", + }); + } + throw new ValidationError({ + message: "alreadyRegistered", + type: "alreadyRegistered", + path: "hostname", + }); + } + validateResponse(response, 201); + return response.data; + }, + + listCompatibleWithCertificate: async (certificate) => { + const response = + "certificateId" in certificate + ? await client.domain.ingressListIngressesCompatibleWithCertificate({ + data: { certificateId: certificate.certificateId }, + }) + : await client.domain.ingressListIngressesCompatibleWithCertificate({ + data: { + certificate: certificate.certificateContent, + projectId: certificate.projectId, + }, + }); + validateResponse(response, 200); + return response.data.map((i) => new IngressListItem(i)); + }, + + updateTls: async (ingressId, certificate) => { + if (certificate.type == "acme") { + const response = await client.domain.ingressUpdateIngressTls({ + data: { + acme: certificate.acme, + }, + ingressId, + }); + validateResponse(response, 200); + return; + } + const response = await client.domain.ingressUpdateIngressTls({ + data: { + certificateId: certificate.certificateId, + }, + ingressId, + }); + validateResponse(response, 200); + }, + find: async (ingressId) => { + const response = await client.domain.ingressGetIngress({ ingressId }); + + if (response.status === 200) { + return response.data; + } + // API-DRIFT: ingressGetIngress omits 403 in its generated response type, so anyStatus403 (403 as any) is passed (resolve: use the literal 403 once the client type declares it) + validateResponse(response, [404, anyStatus403]); + }, + list: async (query = {}, options) => { + const response = await client.domain.ingressListIngresses( + { + queryParameters: query, + }, + withAxiosRequestConfig(options), + ); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + verifyOwnership: async (ingressId) => { + const response = await client.domain.ingressIngressVerifyOwnership({ + ingressId, + }); + if (response.status === 412) { + return false; + } + validateResponse(response, 200); + return true; + }, + requestAcmeCertificate: async (ingressId) => { + const response = + await client.domain.ingressRequestIngressAcmeCertificateIssuance({ + ingressId, + }); + validateResponse(response, 204); + }, + updatePaths: async (ingressId, paths) => { + const response = await client.domain.ingressUpdateIngressPaths({ + data: paths, + ingressId, + }); + validateResponse(response, 204); + }, + delete: async (ingressId) => { + const response = await client.domain.ingressDeleteIngress({ + ingressId, + }); + validateResponse(response, 204); + }, +}); diff --git a/packages/models/src/ingress/Ingress/behaviors/index.ts b/packages/models/src/ingress/Ingress/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/ingress/Ingress/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/ingress/Ingress/behaviors/types.ts b/packages/models/src/ingress/Ingress/behaviors/types.ts new file mode 100644 index 00000000..af17523f --- /dev/null +++ b/packages/models/src/ingress/Ingress/behaviors/types.ts @@ -0,0 +1,40 @@ +import type { AxiosRequestConfig } from "axios"; + +import type { QueryResponseData } from "../../../base/index.js"; +import type { IngressListItem } from "../Ingress.js"; +import type { + IngressListQueryData, + CertificateSettings, + IngressListItemData, + IngressPathSettings, + IngressData, +} from "../types.js"; + +export interface IngressBehaviors { + listCompatibleWithCertificate: ( + certificate: + | { certificateContent: string; projectId: string } + | { certificateId: string }, + ) => Promise; + list: ( + query?: IngressListQueryData, + options?: AxiosRequestConfig, + ) => Promise>; + create: ( + projectId: string, + hostname: string, + paths: IngressPathSettings[], + ) => Promise<{ id: string }>; + updateTls: ( + ingressId: string, + certificate: CertificateSettings, + ) => Promise; + updatePaths: ( + ingressId: string, + paths: IngressPathSettings[], + ) => Promise; + find: (ingressId: string) => Promise; + verifyOwnership: (ingressId: string) => Promise; + requestAcmeCertificate: (id: string) => Promise; + delete: (ingressId: string) => Promise; +} diff --git a/packages/models/src/domain/Ingress/index.ts b/packages/models/src/ingress/Ingress/index.ts similarity index 100% rename from packages/models/src/domain/Ingress/index.ts rename to packages/models/src/ingress/Ingress/index.ts diff --git a/packages/models/src/ingress/Ingress/types.ts b/packages/models/src/ingress/Ingress/types.ts new file mode 100644 index 00000000..03a2c093 --- /dev/null +++ b/packages/models/src/ingress/Ingress/types.ts @@ -0,0 +1,38 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import type { AppInstallation } from "../../app/AppInstallation/AppInstallation.js"; +import type { Certificate } from "../../certificate/Certificate/Certificate.js"; +import type { Container } from "../../container/Container/Container.js"; +import type { IngressTargetData } from "../IngressTarget/index.js"; +import type { Project } from "../../project/index.js"; + +export type IngressListQueryData = + MittwaldAPIV2.Paths.V2Ingresses.Get.Parameters.Query; + +export type IngressListQueryModelData = { + appInstallation?: AppInstallation | string; + certificate?: Certificate | string; + container?: Container | string; + project?: Project | string; +} & Omit< + IngressListQueryData, + "appInstallationId" | "certificateId" | "containerId" | "projectId" +>; + +export type IngressData = + MittwaldAPIV2.Operations.IngressGetIngress.ResponseData; + +export type IngressListItemData = + MittwaldAPIV2.Operations.IngressListIngresses.ResponseData[number]; + +export type CertificateSettings = + | { certificateId: string; type: "certificate" } + | { acme: boolean; type: "acme" }; + +export interface IngressPathSettings { + target: IngressTargetData; + path: string; +} + +export type DnsValidationError = + MittwaldAPIV2.Components.Schemas.IngressIngress["dnsValidationErrors"][number]; diff --git a/packages/models/src/ingress/IngressDomainList/IngressDomainList.test.ts b/packages/models/src/ingress/IngressDomainList/IngressDomainList.test.ts new file mode 100644 index 00000000..a6b3e2b6 --- /dev/null +++ b/packages/models/src/ingress/IngressDomainList/IngressDomainList.test.ts @@ -0,0 +1,73 @@ +import { afterEach, describe, expect, test } from "vitest"; + +import { buildDomainListItemData } from "../../testing/builders/buildDomainListItemData.js"; +import { + IngressDomainListQuery, + IngressDomainList, +} from "./IngressDomainList.js"; +import { buildIngressData } from "../../testing/builders/buildIngressData.js"; +import { resetBehaviors } from "../../testing/installBehaviors.js"; +import { DomainListItem } from "../../domain/Domain/index.js"; +import { IngressListItem } from "../Ingress/index.js"; +import { Project } from "../../project/index.js"; + +afterEach(resetBehaviors); + +describe("IngressDomainList", () => { + test("groups an ingress and finds it by id", () => { + const ingress = new IngressListItem( + buildIngressData({ hostname: "a.example.com", id: "ing-1" }), + ); + const list = new IngressDomainList(Project.ofId("p-1"), [ingress], [], []); + + expect(list.items).toHaveLength(1); + expect(list.items[0].hostname).toBe("a.example.com"); + expect(list.findById("ing-1")).toBe(list.items[0]); + expect(list.findById("ing-1")?.ingress?.id).toBe("ing-1"); + }); + + test("does not duplicate a domain matching an ingress hostname", () => { + const ingress = new IngressListItem( + buildIngressData({ hostname: "a.example.com" }), + ); + const domain = new DomainListItem( + buildDomainListItemData({ + domain: "a.example.com", + domainId: "dom-1", + }), + ); + + expect( + new IngressDomainList(Project.ofId("p-1"), [ingress], [domain], []).items, + ).toHaveLength(1); + }); + + test("adds and finds a domain with a different hostname", () => { + const ingress = new IngressListItem( + buildIngressData({ hostname: "a.example.com" }), + ); + const domain = new DomainListItem( + buildDomainListItemData({ + domain: "b.example.com", + domainId: "dom-1", + }), + ); + const list = new IngressDomainList( + Project.ofId("p-1"), + [ingress], + [domain], + [], + ); + + expect(list.items).toHaveLength(2); + expect(list.findById("dom-1")?.domain).toBe(domain); + }); + + test("creates a project-scoped query", () => { + const query = IngressDomainList.query({ project: "p-1" }); + + expect(query).toBeInstanceOf(IngressDomainListQuery); + expect(query.project).toBeInstanceOf(Project); + expect(query.project.id).toBe("p-1"); + }); +}); diff --git a/packages/models/src/ingress/IngressDomainList/IngressDomainList.ts b/packages/models/src/ingress/IngressDomainList/IngressDomainList.ts new file mode 100644 index 00000000..1de5936c --- /dev/null +++ b/packages/models/src/ingress/IngressDomainList/IngressDomainList.ts @@ -0,0 +1,116 @@ +import type { DomainListItem } from "../../domain/Domain/index.js"; +import type { IngressDomainListQueryData } from "./types.js"; +import type { IngressListItem } from "../Ingress/index.js"; +import type { OrderListItem } from "../../order/index.js"; + +import { IngressDomainListItem } from "../IngressDomainListItem/index.js"; +import { ListQueryModel, extractId } from "../../base/index.js"; +import { DomainArticleTemplate } from "../../article/index.js"; +import { Project } from "../../project/internal.js"; + +export class IngressDomainList { + public readonly items: IngressDomainListItem[]; + // Client-side merged list (no backend pagination), so the total is simply the + // number of materialized items. + public readonly totalCount: number; + public constructor( + project: Project, + ingresses: IngressListItem[], + domains: DomainListItem[], + orders: OrderListItem[], + ) { + const ingressesWithDomains: IngressDomainListItem[] = []; + + ingresses.forEach((ingress: IngressListItem) => { + const domain = domains.find( + (domain) => domain.domain === ingress.hostname, + ); + const { hostname } = ingress; + ingressesWithDomains.push( + new IngressDomainListItem({ hostname, ingress, project, domain }), + ); + }); + domains.forEach((domain: DomainListItem) => { + const existingDomain = ingressesWithDomains.find( + (d) => d.hostname === domain.domain, + ); + if (existingDomain) { + return; + } + ingressesWithDomains.push( + new IngressDomainListItem({ hostname: domain.domain, project, domain }), + ); + }); + + orders.forEach((order: OrderListItem) => { + const domainAttribute = order.getOrderItemAttribute("domain"); + + if (domainAttribute && domainAttribute.value) { + const hostname = domainAttribute.value; + const existingDomain = ingressesWithDomains.find( + (i) => i.hostname === hostname, + ); + // dont add order if a domain/ingress for this hostname is already in the list, to avoid duplicates if something goes wrong with the order but the domain/ingress are there + if (existingDomain) { + return; + } + ingressesWithDomains.push( + new IngressDomainListItem({ hostname, project, order }), + ); + } + }); + + this.items = ingressesWithDomains.map((i) => new IngressDomainListItem(i)); + this.totalCount = this.items.length; + } + + public static query(query: IngressDomainListQueryData) { + return new IngressDomainListQuery(query); + } + + public readonly findById = (id: string) => { + const ingress = this.items.find((item) => item.ingress?.id === id); + if (ingress) { + return ingress; + } + const domain = this.items.find((item) => item.domain?.id === id); + if (domain) { + return domain; + } + const order = this.items.find((item) => item.order?.id === id); + if (order) { + return order; + } + return undefined; + }; +} + +export class IngressDomainListQuery extends ListQueryModel { + public readonly project: Project; + + public constructor(query: IngressDomainListQueryData) { + super(query); + this.project = Project.ofId(extractId(query.project)); + } + + public static query(query: IngressDomainListQueryData) { + return new IngressDomainListQuery(query); + } + + public async execute() { + const [domainList, ingressList, orderList] = await Promise.all([ + this.project.domains.execute(), + this.project.ingresses.execute(), + this.project.orders + .refine({ + templateNames: [DomainArticleTemplate.templateName], + includesStatus: ["CONFIRMED"], + }) + .executeOptional(), + ]); + const ingresses = ingressList.items.map((i) => i); + const domains = domainList.items.map((i) => i); + const orders = orderList.items.filter((i) => i.type === "NEW_ORDER"); + return new IngressDomainList(this.project, ingresses, domains, orders); + } +} diff --git a/packages/models/src/ingress/IngressDomainList/index.ts b/packages/models/src/ingress/IngressDomainList/index.ts new file mode 100644 index 00000000..e790ea04 --- /dev/null +++ b/packages/models/src/ingress/IngressDomainList/index.ts @@ -0,0 +1,2 @@ +export * from "./IngressDomainList.js"; +export * from "./types.js"; diff --git a/packages/models/src/ingress/IngressDomainList/types.ts b/packages/models/src/ingress/IngressDomainList/types.ts new file mode 100644 index 00000000..0db3b3c6 --- /dev/null +++ b/packages/models/src/ingress/IngressDomainList/types.ts @@ -0,0 +1,9 @@ +import type { IOptions } from "tldts-core"; + +import type { Project } from "../../project/index.js"; + +export type ParseDomainOptions = Partial; + +export type IngressDomainListQueryData = { + project: Project | string; +}; diff --git a/packages/models/src/ingress/IngressDomainListItem/IngressDomainListItem.test.ts b/packages/models/src/ingress/IngressDomainListItem/IngressDomainListItem.test.ts new file mode 100644 index 00000000..ed877754 --- /dev/null +++ b/packages/models/src/ingress/IngressDomainListItem/IngressDomainListItem.test.ts @@ -0,0 +1,69 @@ +import { afterEach, describe, expect, test } from "vitest"; + +import { buildDomainListItemData } from "../../testing/builders/buildDomainListItemData.js"; +import { buildIngressData } from "../../testing/builders/buildIngressData.js"; +import { resetBehaviors } from "../../testing/installBehaviors.js"; +import { IngressDomainListItem } from "./IngressDomainListItem.js"; +import { DomainListItem } from "../../domain/Domain/index.js"; +import { IngressListItem } from "../Ingress/index.js"; +import { Project } from "../../project/index.js"; +import { DataModel } from "../../base/index.js"; + +afterEach(resetBehaviors); + +describe("IngressDomainListItem", () => { + test("represents a hostname-only virtual host", () => { + const item = new IngressDomainListItem({ + project: Project.ofId("p-1"), + hostname: "example.com", + }); + + expect(item.type).toBe("vhost"); + expect(item.hostname).toBe("example.com"); + expect(item.ingress).toBeUndefined(); + expect(item.domain).toBeUndefined(); + expect(item.order).toBeUndefined(); + expect(item.project.id).toBe("p-1"); + expect(item).toBeInstanceOf(DataModel); + }); + + test("represents a subdomain ingress", () => { + const ingress = new IngressListItem( + buildIngressData({ hostname: "sub.example.com" }), + ); + const item = new IngressDomainListItem({ + project: Project.ofId("p-1"), + hostname: ingress.hostname, + ingress, + }); + + expect(item.type).toBe("subdomain"); + expect(item.ingress).toBe(ingress); + expect(item.ingress?.project).toBeInstanceOf(Project); + }); + + test("represents a non-subdomain ingress as a virtual host", () => { + const ingress = new IngressListItem( + buildIngressData({ hostname: "example.com" }), + ); + const item = new IngressDomainListItem({ + project: Project.ofId("p-1"), + hostname: ingress.hostname, + ingress, + }); + + expect(item.type).toBe("vhost"); + }); + + test("represents a domain", () => { + const domain = new DomainListItem(buildDomainListItemData()); + const item = new IngressDomainListItem({ + project: Project.ofId("p-1"), + hostname: domain.domain, + domain, + }); + + expect(item.type).toBe("domain"); + expect(item.domain).toBe(domain); + }); +}); diff --git a/packages/models/src/ingress/IngressDomainListItem/IngressDomainListItem.ts b/packages/models/src/ingress/IngressDomainListItem/IngressDomainListItem.ts new file mode 100644 index 00000000..8a2205c2 --- /dev/null +++ b/packages/models/src/ingress/IngressDomainListItem/IngressDomainListItem.ts @@ -0,0 +1,44 @@ +import type { IngressDomainListItemData } from "./types.js"; +import type { Project } from "../../project/index.js"; + +import { + type DomainDetailed, + type DomainListItem, +} from "../../domain/Domain/index.js"; +import { + type IngressDetailed, + type IngressListItem, +} from "../Ingress/index.js"; +import { type OrderDetailed, type OrderListItem } from "../../order/index.js"; +import { DataModel } from "../../base/index.js"; + +export class IngressDomainListItem extends DataModel { + public readonly domain?: DomainListItem | DomainDetailed; + public readonly hostname: string; + public readonly ingress?: IngressListItem | IngressDetailed; + public readonly order?: OrderListItem | OrderDetailed; + public readonly project: Project; + public readonly type: "subdomain" | "domain" | "vhost"; + + public constructor(data: IngressDomainListItemData) { + super(data); + this.hostname = data.hostname; + this.project = data.project; + if (data.domain) { + this.domain = data.domain; + } + if (data.ingress) { + this.ingress = data.ingress; + } + if (data.order) { + this.order = data.order; + } + this.type = data.domain + ? "domain" + : data.ingress?.isSubdomain + ? "subdomain" + : data.order + ? "domain" + : "vhost"; + } +} diff --git a/packages/models/src/ingress/IngressDomainListItem/index.ts b/packages/models/src/ingress/IngressDomainListItem/index.ts new file mode 100644 index 00000000..231e1d4d --- /dev/null +++ b/packages/models/src/ingress/IngressDomainListItem/index.ts @@ -0,0 +1,2 @@ +export * from "./IngressDomainListItem.js"; +export * from "./types.js"; diff --git a/packages/models/src/ingress/IngressDomainListItem/types.ts b/packages/models/src/ingress/IngressDomainListItem/types.ts new file mode 100644 index 00000000..b9e443a1 --- /dev/null +++ b/packages/models/src/ingress/IngressDomainListItem/types.ts @@ -0,0 +1,12 @@ +import type { DomainListItem } from "../../domain/Domain/index.js"; +import type { IngressListItem } from "../Ingress/index.js"; +import type { OrderListItem } from "../../order/index.js"; +import type { Project } from "../../project/index.js"; + +export interface IngressDomainListItemData { + ingress?: IngressListItem; + domain?: DomainListItem; + order?: OrderListItem; + hostname: string; + project: Project; +} diff --git a/packages/models/src/ingress/IngressPath/IngressPath.test.ts b/packages/models/src/ingress/IngressPath/IngressPath.test.ts new file mode 100644 index 00000000..eea8357a --- /dev/null +++ b/packages/models/src/ingress/IngressPath/IngressPath.test.ts @@ -0,0 +1,57 @@ +import { afterEach, describe, expect, test } from "vitest"; + +import { buildIngressPathData } from "../../testing/builders/buildIngressPathData.js"; +import { buildIngressData } from "../../testing/builders/buildIngressData.js"; +import { resetBehaviors } from "../../testing/installBehaviors.js"; +import { IngressListItem } from "../Ingress/index.js"; +import { IngressPath } from "./IngressPath.js"; +import { Project } from "../../project/index.js"; +import { + IngressUndefinedTarget, + IngressRedirectTarget, +} from "../IngressTarget/index.js"; + +afterEach(resetBehaviors); + +describe("IngressPath", () => { + const ingress = new IngressListItem( + buildIngressData({ hostname: "example.com", projectId: "proj-9" }), + ); + + test("derives its URL and project from the ingress", () => { + const path = new IngressPath( + ingress, + buildIngressPathData({ path: "/foo" }), + ); + + expect(path.path).toBe("/foo"); + expect(path.url).toBeInstanceOf(URL); + expect(path.url.href).toBe("https://example.com/foo"); + expect(path.project).toBeInstanceOf(Project); + expect(path.project.id).toBe("proj-9"); + expect(path.ingress).toBe(ingress); + }); + + test("selects a redirect target", () => { + const path = new IngressPath( + ingress, + buildIngressPathData({ + target: { url: "https://target.example/" }, + path: "/r", + }), + ); + + expect(path.target).toBeInstanceOf(IngressRedirectTarget); + expect(path.target?.type).toBe("redirect"); + }); + + test("selects an undefined target for the default page", () => { + const path = new IngressPath( + ingress, + buildIngressPathData({ target: { useDefaultPage: true } }), + ); + + expect(path.target).toBeInstanceOf(IngressUndefinedTarget); + expect(path.target?.type).toBe("undefined"); + }); +}); diff --git a/packages/models/src/ingress/IngressPath/IngressPath.ts b/packages/models/src/ingress/IngressPath/IngressPath.ts new file mode 100644 index 00000000..6f3a0a14 --- /dev/null +++ b/packages/models/src/ingress/IngressPath/IngressPath.ts @@ -0,0 +1,24 @@ +import type { IngressCommon, Ingress } from "../Ingress/index.js"; +import type { IngressTarget } from "../IngressTarget/index.js"; +import type { IngressPathData } from "./types.js"; + +import { ingressTargetFactory } from "../IngressTarget/index.js"; +import { Project } from "../../project/internal.js"; +import { DataModel } from "../../base/index.js"; + +export class IngressPath extends DataModel { + public readonly ingress: Ingress; + public readonly path: string; + public readonly project: Project; + public readonly target?: IngressTarget; + public readonly url: URL; + + public constructor(ingress: IngressCommon, data: IngressPathData) { + super(data); + this.ingress = ingress; + this.project = Project.ofId(ingress.data.projectId); + this.path = data.path; + this.url = new URL(data.path, ingress.baseUrl); + this.target = ingressTargetFactory(this, data.target); + } +} diff --git a/packages/models/src/domain/IngressPath/index.ts b/packages/models/src/ingress/IngressPath/index.ts similarity index 100% rename from packages/models/src/domain/IngressPath/index.ts rename to packages/models/src/ingress/IngressPath/index.ts diff --git a/packages/models/src/domain/IngressPath/types.ts b/packages/models/src/ingress/IngressPath/types.ts similarity index 56% rename from packages/models/src/domain/IngressPath/types.ts rename to packages/models/src/ingress/IngressPath/types.ts index 3253a422..5a43ed74 100644 --- a/packages/models/src/domain/IngressPath/types.ts +++ b/packages/models/src/ingress/IngressPath/types.ts @@ -1,3 +1,3 @@ -import { MittwaldAPIV2 } from "@mittwald/api-client"; +import type { MittwaldAPIV2 } from "@mittwald/api-client"; export type IngressPathData = MittwaldAPIV2.Components.Schemas.IngressPath; diff --git a/packages/models/src/domain/IngressTarget/IngressTarget.test-types.ts b/packages/models/src/ingress/IngressTarget/IngressTarget.test-types.ts similarity index 80% rename from packages/models/src/domain/IngressTarget/IngressTarget.test-types.ts rename to packages/models/src/ingress/IngressTarget/IngressTarget.test-types.ts index c4ebde98..e450e27b 100644 --- a/packages/models/src/domain/IngressTarget/IngressTarget.test-types.ts +++ b/packages/models/src/ingress/IngressTarget/IngressTarget.test-types.ts @@ -1,4 +1,4 @@ -import { IngressTarget } from "./IngressTarget.js"; +import type { IngressTarget } from "./IngressTarget.js"; const target = {} as IngressTarget; diff --git a/packages/models/src/ingress/IngressTarget/IngressTarget.test.ts b/packages/models/src/ingress/IngressTarget/IngressTarget.test.ts new file mode 100644 index 00000000..e4f741b2 --- /dev/null +++ b/packages/models/src/ingress/IngressTarget/IngressTarget.test.ts @@ -0,0 +1,66 @@ +import { afterEach, describe, expect, test } from "vitest"; + +import { buildIngressPathData } from "../../testing/builders/buildIngressPathData.js"; +import { buildIngressData } from "../../testing/builders/buildIngressData.js"; +import { resetBehaviors } from "../../testing/installBehaviors.js"; +import { IngressListItem } from "../Ingress/index.js"; +import { IngressPath } from "../IngressPath/index.js"; +import { AppInstallation } from "../../app/index.js"; +import { Container } from "../../container/index.js"; +import { + IngressAppInstallationTarget, + IngressContainerTarget, + IngressUndefinedTarget, + IngressRedirectTarget, + ingressTargetFactory, +} from "./IngressTarget.js"; + +afterEach(resetBehaviors); + +describe("ingressTargetFactory", () => { + const ingress = new IngressListItem( + buildIngressData({ projectId: "proj-1" }), + ); + const path = new IngressPath(ingress, buildIngressPathData()); + + test("creates redirect targets", () => { + const target = ingressTargetFactory(path, { + url: "https://r.example/", + }); + + expect(target).toBeInstanceOf(IngressRedirectTarget); + expect(target?.type).toBe("redirect"); + expect(target).toHaveProperty("url.href", "https://r.example/"); + }); + + test("creates app installation targets", () => { + const target = ingressTargetFactory(path, { installationId: "inst-1" }); + + expect(target).toBeInstanceOf(IngressAppInstallationTarget); + expect(target?.type).toBe("appInstallation"); + expect(target).toHaveProperty( + "appInstallation", + expect.any(AppInstallation), + ); + expect(target).toHaveProperty("appInstallation.id", "inst-1"); + }); + + test("creates container targets", () => { + const target = ingressTargetFactory(path, { + container: { portProtocol: "8080/TCP", id: "cont-1" }, + }); + + expect(target).toBeInstanceOf(IngressContainerTarget); + expect(target?.type).toBe("container"); + expect(target).toHaveProperty("container", expect.any(Container)); + expect(target).toHaveProperty("container.id", "cont-1"); + expect(target).toHaveProperty("portProtocol", "8080/TCP"); + }); + + test("creates undefined targets for the default page", () => { + const target = ingressTargetFactory(path, { useDefaultPage: true }); + + expect(target).toBeInstanceOf(IngressUndefinedTarget); + expect(target?.type).toBe("undefined"); + }); +}); diff --git a/packages/models/src/domain/IngressTarget/IngressTarget.ts b/packages/models/src/ingress/IngressTarget/IngressTarget.ts similarity index 60% rename from packages/models/src/domain/IngressTarget/IngressTarget.ts rename to packages/models/src/ingress/IngressTarget/IngressTarget.ts index 366582ef..bc56ebc0 100644 --- a/packages/models/src/domain/IngressTarget/IngressTarget.ts +++ b/packages/models/src/ingress/IngressTarget/IngressTarget.ts @@ -1,14 +1,17 @@ -import { DataModel } from "../../base/DataModel.js"; -import { - IngressUndefinedTargetData, +import type { IngressPath } from "../IngressPath/index.js"; +import type { IngressAppInstallationTargetData, + IngressContainerTargetData, + IngressUndefinedTargetData, IngressRedirectTargetData, IngressTargetData, } from "./types.js"; -import { IngressPath } from "../IngressPath/IngressPath.js"; -import { AppInstallation } from "../../app/AppInstallation/index.js"; -abstract class IngressTargetBase< +import { AppInstallation } from "../../app/AppInstallation/AppInstallation.js"; +import { Container } from "../../container/Container/Container.js"; +import { DataModel } from "../../base/index.js"; + +export abstract class IngressTargetBase< T extends IngressTargetData, > extends DataModel { public readonly path: IngressPath; @@ -28,9 +31,10 @@ export class IngressRedirectTarget extends IngressTargetBase { - public readonly type = "appInstallation"; public readonly appInstallation: AppInstallation; + public readonly type = "appInstallation"; public constructor( path: IngressPath, @@ -41,17 +45,32 @@ export class IngressAppInstallationTarget extends IngressTargetBase { + public readonly container: Container; + public readonly portProtocol: string; + public readonly type = "container"; + + public constructor(path: IngressPath, data: IngressContainerTargetData) { + super(path, data); + this.container = Container.ofId(data.container.id, path.project.id); + this.portProtocol = data.container.portProtocol; + } +} + export class IngressUndefinedTarget extends IngressTargetBase { public readonly type = "undefined"; } export type IngressTarget = - IngressRedirectTarget | IngressAppInstallationTarget | IngressUndefinedTarget; + | IngressAppInstallationTarget + | IngressUndefinedTarget + | IngressContainerTarget + | IngressRedirectTarget; export const ingressTargetFactory = ( path: IngressPath, data: IngressTargetData, -): IngressTarget => { +): IngressTarget | undefined => { if ("url" in data) { return new IngressRedirectTarget(path, data); } @@ -60,9 +79,11 @@ export const ingressTargetFactory = ( return new IngressAppInstallationTarget(path, data); } + if ("container" in data) { + return new IngressContainerTarget(path, data); + } + if ("useDefaultPage" in data) { return new IngressUndefinedTarget(path, data); } - - throw new Error("Ingress target type is not supported."); }; diff --git a/packages/models/src/domain/IngressTarget/index.ts b/packages/models/src/ingress/IngressTarget/index.ts similarity index 100% rename from packages/models/src/domain/IngressTarget/index.ts rename to packages/models/src/ingress/IngressTarget/index.ts diff --git a/packages/models/src/domain/IngressTarget/types.ts b/packages/models/src/ingress/IngressTarget/types.ts similarity index 80% rename from packages/models/src/domain/IngressTarget/types.ts rename to packages/models/src/ingress/IngressTarget/types.ts index 30071daa..3213bdc1 100644 --- a/packages/models/src/domain/IngressTarget/types.ts +++ b/packages/models/src/ingress/IngressTarget/types.ts @@ -1,4 +1,4 @@ -import { MittwaldAPIV2 } from "@mittwald/api-client"; +import type { MittwaldAPIV2 } from "@mittwald/api-client"; export type IngressRedirectTargetData = MittwaldAPIV2.Components.Schemas.IngressTargetUrl; @@ -13,7 +13,7 @@ export type IngressUndefinedTargetData = MittwaldAPIV2.Components.Schemas.IngressTargetUseDefaultPage; export type IngressTargetData = - | IngressRedirectTargetData | IngressAppInstallationTargetData | IngressUndefinedTargetData - | IngressContainerTargetData; + | IngressContainerTargetData + | IngressRedirectTargetData; diff --git a/packages/models/src/ingress/index.ts b/packages/models/src/ingress/index.ts new file mode 100644 index 00000000..e77f9743 --- /dev/null +++ b/packages/models/src/ingress/index.ts @@ -0,0 +1,5 @@ +export * from "./Ingress/index.js"; +export * from "./IngressDomainList/index.js"; +export * from "./IngressDomainListItem/index.js"; +export * from "./IngressPath/index.js"; +export * from "./IngressTarget/index.js"; diff --git a/packages/models/src/invoice/Invoice/Invoice.test.ts b/packages/models/src/invoice/Invoice/Invoice.test.ts new file mode 100644 index 00000000..4d08e9b9 --- /dev/null +++ b/packages/models/src/invoice/Invoice/Invoice.test.ts @@ -0,0 +1,274 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { buildInvoiceItemData } from "../../testing/builders/buildInvoiceItemData.js"; +import { buildInvoiceData } from "../../testing/builders/buildInvoiceData.js"; +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { InvoiceCancellation } from "../InvoiceCancellation/index.js"; +import { InvoiceItemGroup } from "../InvoiceItemGroup/index.js"; +import { InvoiceRecipient } from "../InvoiceRecipient/index.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { Customer } from "../../customer/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { File } from "../../file/index.js"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { + InvoiceListQuery, + InvoiceDetailed, + InvoiceListItem, + InvoiceList, + Invoice, +} from "./Invoice.js"; + +afterEach(resetBehaviors); + +describe("Invoice references and delegation", () => { + test("ofId creates an invoice reference with the given id", () => { + const invoice = Invoice.ofId("i-1"); + + expect(invoice).toBeInstanceOf(Invoice); + expect(invoice.id).toBe("i-1"); + }); + + test("find delegates and materializes present data", async () => { + const find = vi.fn().mockResolvedValue(buildInvoiceData({ id: "i-1" })); + installBehaviors({ invoice: { find } }); + + const invoice = await Invoice.find("i-1"); + + expect(find).toHaveBeenCalledWith("i-1"); + expect(invoice).toBeInstanceOf(InvoiceDetailed); + expect(invoice?.id).toBe("i-1"); + }); + + test("find returns undefined for missing data", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ invoice: { find } }); + + await expect(Invoice.find("missing")).resolves.toBeUndefined(); + }); + + test("get returns detailed data and throws ObjectNotFoundError when missing", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildInvoiceData({ id: "i-1" })) + .mockResolvedValueOnce(undefined); + installBehaviors({ invoice: { find } }); + + await expect(Invoice.get("i-1")).resolves.toBeInstanceOf(InvoiceDetailed); + await expect(Invoice.get("missing")).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("findDetailed delegates with the reference id", async () => { + const find = vi.fn().mockResolvedValue(buildInvoiceData({ id: "i-1" })); + installBehaviors({ invoice: { find } }); + + const invoice = await Invoice.ofId("i-1").findDetailed(); + + expect(find).toHaveBeenCalledWith("i-1"); + expect(invoice).toBeInstanceOf(InvoiceDetailed); + }); + + test("common instances return themselves from findCommon and getCommon", async () => { + const find = vi.fn().mockResolvedValue(buildInvoiceData({ id: "i-1" })); + installBehaviors({ invoice: { find } }); + const invoice = await Invoice.find("i-1"); + + await expect(invoice?.findCommon()).resolves.toBe(invoice); + await expect(invoice?.getCommon()).resolves.toBe(invoice); + expect(find).toHaveBeenCalledTimes(1); + }); + + test("plain references delegate findCommon and getCommon", async () => { + const find = vi.fn().mockResolvedValue(buildInvoiceData({ id: "i-1" })); + installBehaviors({ invoice: { find } }); + const invoice = Invoice.ofId("i-1"); + + await expect(invoice.findCommon()).resolves.toBeInstanceOf(InvoiceDetailed); + await expect(invoice.getCommon()).resolves.toBeInstanceOf(InvoiceDetailed); + expect(find).toHaveBeenNthCalledWith(1, "i-1"); + expect(find).toHaveBeenNthCalledWith(2, "i-1"); + }); + + test("findCommon resolves undefined for a missing plain reference", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ invoice: { find } }); + + await expect(Invoice.ofId("missing").findCommon()).resolves.toBeUndefined(); + expect(find).toHaveBeenCalledWith("missing"); + }); + + test("getCommon throws ObjectNotFoundError for a missing plain reference", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ invoice: { find } }); + + await expect(Invoice.ofId("missing").getCommon()).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("getDetailed re-fetches even on an already materialized invoice", async () => { + const find = vi.fn().mockResolvedValue(buildInvoiceData({ id: "i-1" })); + installBehaviors({ invoice: { find } }); + const materialized = await Invoice.find("i-1"); + + const reFetched = await materialized?.getDetailed(); + + expect(reFetched).toBeInstanceOf(InvoiceDetailed); + expect(reFetched).not.toBe(materialized); + expect(find).toHaveBeenCalledTimes(2); + }); +}); + +describe("Invoice aggregate metadata", () => { + test("carries the invoice domain and aggregate identity", () => { + expect(Invoice.aggregateMetaData).toBeInstanceOf(AggregateMetaData); + expect(Invoice.aggregateMetaData.domain).toBe("invoice"); + expect(Invoice.aggregateMetaData.aggregate).toBe("invoice"); + }); +}); + +describe("Invoice detailed data", () => { + test("defaults missing monetary values to zero", () => { + const invoice = new InvoiceDetailed( + buildInvoiceData({ + totalGross: undefined, + amountPaid: undefined, + totalNet: undefined, + }), + ); + + expect(invoice.totalGross.getAmount()).toBe(0); + expect(invoice.totalNet.getAmount()).toBe(0); + expect(invoice.amountPaid.getAmount()).toBe(0); + expect(invoice.amountOutstanding.getAmount()).toBe(0); + }); + + test("maps invoice data to observable domain values", () => { + const invoice = new InvoiceDetailed( + buildInvoiceData({ + groups: [ + { + items: [ + buildInvoiceItemData({ itemId: "item-1" }), + buildInvoiceItemData({ itemId: "item-2" }), + ], + description: "Group", + }, + ], + }), + ); + + expect(invoice.invoiceNumber).toBe("INV-2024-001"); + expect(invoice.status).toBe("NEW"); + expect(invoice.invoiceType).toBe("REGULAR"); + expect(invoice.customer).toBeInstanceOf(Customer); + expect(invoice.customer.id).toBe("customer-id"); + expect(invoice.recipient).toBeInstanceOf(InvoiceRecipient); + expect(invoice.itemGroups).toHaveLength(1); + expect(invoice.itemGroups[0]).toBeInstanceOf(InvoiceItemGroup); + expect(invoice.itemsFlat.map((item) => item.id)).toEqual([ + "item-1", + "item-2", + ]); + expect(invoice.pdf).toBeInstanceOf(File); + expect(invoice.pdf.id).toBe("pdf-id"); + expect(invoice.pdf.isProtected).toBe(true); + }); + + test("maps money and derives the outstanding amount", () => { + const invoice = new InvoiceDetailed(buildInvoiceData()); + + expect(invoice.totalGross.getAmount()).toBe(11900); + expect(invoice.totalNet.getAmount()).toBe(10000); + expect(invoice.amountPaid.getAmount()).toBe(0); + expect(invoice.amountOutstanding.getAmount()).toBe(11900); + }); + + test("sets the outstanding amount to zero for a negative net total", () => { + const invoice = new InvoiceDetailed(buildInvoiceData({ totalNet: -100 })); + + expect(invoice.amountOutstanding.getAmount()).toBe(0); + }); + + test("is overdue only for an unpaid status after the payment term", () => { + const overdue = new InvoiceDetailed( + buildInvoiceData({ date: "2000-01-01T00:00:00.000Z", status: "NEW" }), + ); + const paid = new InvoiceDetailed( + buildInvoiceData({ date: "2000-01-01T00:00:00.000Z", status: "PAID" }), + ); + + expect(overdue.isOverdue).toBe(true); + expect(paid.isOverdue).toBe(false); + }); + + test("maps optional cancellation relationships", () => { + const cancellation = { + cancellationId: "cancellation-invoice-id", + cancelledAt: "2024-06-01T00:00:00.000Z", + correctionNumber: "COR-2024-001", + pdfId: "cancellation-pdf-id", + reason: "Correction", + }; + const present = new InvoiceDetailed( + buildInvoiceData({ cancellationOf: "original-invoice-id", cancellation }), + ); + const absent = new InvoiceDetailed( + buildInvoiceData({ cancellationOf: undefined, cancellation: undefined }), + ); + + expect(present.cancellation).toBeInstanceOf(InvoiceCancellation); + expect(present.cancellationOf).toBeInstanceOf(Invoice); + expect(present.cancellationOf?.id).toBe("original-invoice-id"); + expect(absent.cancellation).toBeUndefined(); + expect(absent.cancellationOf).toBeUndefined(); + }); +}); + +describe("Invoice list queries", () => { + test("delegates customer and query and materializes the result", async () => { + const customer = Customer.ofId("customer-id"); + const query = { limit: 2, page: 3 }; + const list = vi.fn().mockResolvedValue({ + items: [buildInvoiceData({ id: "i-1" })], + totalCount: 7, + }); + installBehaviors({ invoice: { list } }); + + const listQuery = Invoice.query({ customer: customer, ...query }); + const result = await listQuery.execute(); + + expect(listQuery).toBeInstanceOf(InvoiceListQuery); + expect(list).toHaveBeenCalledWith("customer-id", query); + expect(result).toBeInstanceOf(InvoiceList); + expect(result.items).toHaveLength(1); + expect(result.items[0]).toBeInstanceOf(InvoiceListItem); + expect(result.totalCount).toBe(7); + }); + + test("getTotalCount refines the query with limit one", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 23, items: [] }); + installBehaviors({ invoice: { list } }); + + const totalCount = await Invoice.query({ + customer: Customer.ofId("customer-id"), + page: 4, + }).getTotalCount(); + + expect(totalCount).toBe(23); + expect(list).toHaveBeenCalledWith("customer-id", { limit: 1, page: 4 }); + }); +}); diff --git a/packages/models/src/invoice/Invoice/Invoice.ts b/packages/models/src/invoice/Invoice/Invoice.ts new file mode 100644 index 00000000..e0289c9a --- /dev/null +++ b/packages/models/src/invoice/Invoice/Invoice.ts @@ -0,0 +1,194 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; +import { omit } from "remeda"; + +import type { InvoiceItem } from "../InvoiceItem/index.js"; +import type { + InvoiceListQueryModelData, + InvoiceListItemData, + InvoiceStatus, + InvoiceData, +} from "./types.js"; + +import { InvoicePdfAccessTokenProvider } from "./InvoicePdfAccessTokenProvider.js"; +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { InvoiceCancellation } from "../InvoiceCancellation/index.js"; +import { Customer } from "../../customer/Customer/Customer.js"; +import { AggregateMetaData, Money } from "../../common/index.js"; +import { InvoiceItemGroup } from "../InvoiceItemGroup/index.js"; +import { InvoiceRecipient } from "../InvoiceRecipient/index.js"; +import { File } from "../../file/File/internal.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "Invoice", +}) +export class Invoice extends ReferenceModel { + public static aggregateMetaData = new AggregateMetaData("invoice", "invoice"); + + public static async find(id: string) { + const data = await config.behaviors.invoice.find(id); + + if (data) { + return new InvoiceDetailed(data); + } + } + + public static async get(id: string) { + const invoice = await this.find(id); + assertObjectFound(invoice, Invoice, id); + return invoice; + } + + public static ofId(id: string) { + return new Invoice(id); + } + + public static query(query: InvoiceListQueryModelData) { + return new InvoiceListQuery(query); + } + + public async findCommon(): Promise { + return this instanceof InvoiceCommon ? this : this.findDetailed(); + } + + public async findDetailed(): Promise { + return Invoice.find(this.id); + } + + public async getCommon(): Promise { + return this instanceof InvoiceCommon ? this : this.getDetailed(); + } + + public async getDetailed(): Promise { + return Invoice.get(this.id); + } +} + +export class InvoiceCommon extends WithData< + InvoiceListItemData | InvoiceData +>()(Invoice) { + public readonly amountOutstanding: Money; + public readonly amountPaid: Money; + public readonly cancellation?: InvoiceCancellation; + public readonly cancellationOf?: Invoice; + public readonly customer: Customer; + public override readonly data: InvoiceListItemData | InvoiceData; + public readonly date: DateTime; + public readonly invoiceNumber: string; + public readonly invoiceType: string; + public readonly isOverdue: boolean; + public readonly itemGroups: InvoiceItemGroup[]; + public readonly itemsFlat: InvoiceItem[]; + public readonly paymentTerm: DateTime; + public readonly pdf: File; + public readonly recipient: InvoiceRecipient; + public readonly status: InvoiceStatus; + public readonly totalGross: Money; + public readonly totalNet: Money; + + public constructor(data: InvoiceListItemData | InvoiceData) { + super(data.id); + this.data = data; + this.invoiceNumber = data.invoiceNumber; + this.totalGross = Money({ amount: data.totalGross ?? 0, currency: "EUR" }); + this.totalNet = Money({ amount: data.totalNet ?? 0, currency: "EUR" }); + this.amountPaid = Money({ amount: data.amountPaid ?? 0, currency: "EUR" }); + this.amountOutstanding = this.totalNet.isNegative() + ? Money({ currency: "EUR" }) + : this.totalGross.subtract(this.amountPaid); + this.date = DateTime.fromISO(data.date); + this.paymentTerm = this.date.plus({ day: 14 }); + this.recipient = new InvoiceRecipient(data.recipient); + this.customer = Customer.ofId(data.customerId); + this.status = data.status; + this.invoiceType = data.invoiceType; + this.itemGroups = data.groups.map((g) => new InvoiceItemGroup(this, g)); + this.itemsFlat = this.itemGroups.flatMap((g) => g.items); + this.pdf = new File(data.pdfId, new InvoicePdfAccessTokenProvider(this)); + this.cancellation = data.cancellation + ? new InvoiceCancellation(this, data.cancellation) + : undefined; + this.cancellationOf = data.cancellationOf + ? Invoice.ofId(data.cancellationOf) + : undefined; + this.isOverdue = + (this.status === "PARTIALLY_PAID" || + this.status === "NEW" || + this.status === "CONFIRMED") && + this.paymentTerm.startOf("day") < DateTime.now().startOf("day"); + } +} + +export class InvoiceDetailed extends InvoiceCommon { + public override readonly data: InvoiceData; + + public constructor(data: InvoiceData) { + super(data); + this.data = data; + } +} + +export class InvoiceListItem extends InvoiceCommon { + public override readonly data: InvoiceListItemData; + + public constructor(data: InvoiceListItemData) { + super(data); + this.data = data; + } +} + +export class InvoiceListQuery extends ListQueryModel { + public constructor(query: InvoiceListQueryModelData) { + super(query, { dependencies: [extractId(query.customer)] }); + } + + public async execute() { + const { totalCount, items } = await config.behaviors.invoice.list( + extractId(this.query.customer), + omit(this.query, ["customer"]), + ); + + return new InvoiceList( + this.query, + items.map((d) => new InvoiceListItem(d)), + totalCount, + ); + } + + public async getTotalCount() { + const { totalCount } = await this.refine({ limit: 1 }).execute(); + return totalCount; + } + + public refine(query: Partial = {}) { + return new InvoiceListQuery({ + ...this.query, + ...query, + }); + } +} + +export class InvoiceList extends WithListData()( + InvoiceListQuery, +) { + public override readonly items: readonly InvoiceListItem[]; + public override readonly totalCount: number; + + public constructor( + query: InvoiceListQueryModelData, + invoices: InvoiceListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(invoices); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/invoice/Invoice/InvoicePdfAccessTokenProvider.ts b/packages/models/src/invoice/Invoice/InvoicePdfAccessTokenProvider.ts new file mode 100644 index 00000000..bd7429d7 --- /dev/null +++ b/packages/models/src/invoice/Invoice/InvoicePdfAccessTokenProvider.ts @@ -0,0 +1,22 @@ +import type { AxiosRequestConfig } from "axios"; + +import type { FileAccessTokenProvider } from "../../file/index.js"; +import type { InvoiceDetailed } from "./Invoice.js"; + +import { config } from "../../config/index.js"; + +export class InvoicePdfAccessTokenProvider implements FileAccessTokenProvider { + public readonly invoice: InvoiceDetailed; + + public constructor(invoice: InvoiceDetailed) { + this.invoice = invoice; + } + + public getDownloadToken(_: string, requestConfig?: AxiosRequestConfig) { + return config.behaviors.invoice.getFileAccessToken( + this.invoice.id, + this.invoice.customer.id, + requestConfig, + ); + } +} diff --git a/packages/models/src/invoice/Invoice/behaviors/api.ts b/packages/models/src/invoice/Invoice/behaviors/api.ts new file mode 100644 index 00000000..86ed21e5 --- /dev/null +++ b/packages/models/src/invoice/Invoice/behaviors/api.ts @@ -0,0 +1,47 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { InvoiceBehaviors } from "./types.js"; + +import { + withAxiosRequestConfig, + resolveTotalCount, +} from "../../../base/index.js"; +import { validateResponse } from "../../../base/api/validateResponse.js"; + +export const apiInvoiceBehaviors = ( + client: MittwaldAPIV2Client, +): InvoiceBehaviors => ({ + getFileAccessToken: async (invoiceId, customerId, requestConfig) => { + const response = await client.contract.invoiceGetFileAccessToken( + { + customerId, + invoiceId, + }, + withAxiosRequestConfig(requestConfig), + ); + validateResponse(response, 200); + return response.data; + }, + + list: async (customerId, query) => { + const response = await client.contract.invoiceListCustomerInvoices({ + queryParameters: query, + customerId, + }); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + find: async (invoiceId) => { + const response = await client.contract.invoiceDetail({ + invoiceId, + }); + if (response.status === 200) { + return response.data; + } + validateResponse(response, 404); + }, +}); diff --git a/packages/models/src/invoice/Invoice/behaviors/index.ts b/packages/models/src/invoice/Invoice/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/invoice/Invoice/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/invoice/Invoice/behaviors/types.ts b/packages/models/src/invoice/Invoice/behaviors/types.ts new file mode 100644 index 00000000..2d44473d --- /dev/null +++ b/packages/models/src/invoice/Invoice/behaviors/types.ts @@ -0,0 +1,24 @@ +import type { AxiosRequestConfig } from "axios"; + +import type { FileDownloadTokenData } from "../../../file/index.js"; +import type { QueryResponseData } from "../../../base/index.js"; +import type { + InvoiceListQueryData, + InvoiceListItemData, + InvoiceData, +} from "../types.js"; + +export interface InvoiceBehaviors { + getFileAccessToken: ( + invoiceId: string, + customerId: string, + requestConfig?: AxiosRequestConfig, + ) => Promise; + + list: ( + customerId: string, + query?: InvoiceListQueryData, + ) => Promise>; + + find: (invoiceId: string) => Promise; +} diff --git a/packages/models/src/invoice/Invoice/index.ts b/packages/models/src/invoice/Invoice/index.ts new file mode 100644 index 00000000..9b23d19b --- /dev/null +++ b/packages/models/src/invoice/Invoice/index.ts @@ -0,0 +1,2 @@ +export * from "./Invoice.js"; +export * from "./types.js"; diff --git a/packages/models/src/invoice/Invoice/types.ts b/packages/models/src/invoice/Invoice/types.ts new file mode 100644 index 00000000..af422d0c --- /dev/null +++ b/packages/models/src/invoice/Invoice/types.ts @@ -0,0 +1,27 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import type { Customer } from "../../customer/index.js"; + +export type InvoiceData = MittwaldAPIV2.Operations.InvoiceDetail.ResponseData; + +export type InvoiceListItemData = + MittwaldAPIV2.Operations.InvoiceListCustomerInvoices.ResponseData[number]; + +export const invoiceStatusList = [ + "PAID", + "PARTIALLY_PAID", + "OVERPAID", + "NEW", + "CONFIRMED", + "DENIED", +] as const; + +export type InvoiceStatus = NonNullable[number] & + (typeof invoiceStatusList)[number]; + +export type InvoiceListQueryData = + MittwaldAPIV2.Paths.V2CustomersCustomerIdInvoices.Get.Parameters.Query; + +export type InvoiceListQueryModelData = { + customer: Customer | string; +} & InvoiceListQueryData; diff --git a/packages/models/src/invoice/InvoiceCancellation/InvoiceCancellation.ts b/packages/models/src/invoice/InvoiceCancellation/InvoiceCancellation.ts new file mode 100644 index 00000000..b4ca5186 --- /dev/null +++ b/packages/models/src/invoice/InvoiceCancellation/InvoiceCancellation.ts @@ -0,0 +1,30 @@ +import { DateTime } from "luxon"; + +import type { InvoiceCancellationData } from "./types.js"; +import type { InvoiceDetailed } from "../Invoice/index.js"; +import type { Ctor } from "../../base/index.js"; + +import { ReferenceModel, WithData } from "../../base/index.js"; +import { Invoice } from "../Invoice/index.js"; + +export class InvoiceCancellation extends WithData()( + // `ReferenceModel` is abstract; the mixin's `Ctor` parameter is a concrete + // construct signature. The cast bridges that (ReferenceModel has no abstract + // members and is never instantiated directly — only via this subclass). + ReferenceModel as Ctor, +) { + public readonly cancelledAt: DateTime; + public readonly cancelledBy: Invoice; + public override readonly data: InvoiceCancellationData; + public readonly invoice: InvoiceDetailed; + public readonly reason?: string; + + public constructor(invoice: InvoiceDetailed, data: InvoiceCancellationData) { + super(data.cancellationId); + this.data = data; + this.invoice = invoice; + this.cancelledAt = DateTime.fromISO(data.cancelledAt); + this.cancelledBy = Invoice.ofId(data.cancellationId); + this.reason = data.reason; + } +} diff --git a/packages/models/src/invoice/InvoiceCancellation/index.ts b/packages/models/src/invoice/InvoiceCancellation/index.ts new file mode 100644 index 00000000..7c630222 --- /dev/null +++ b/packages/models/src/invoice/InvoiceCancellation/index.ts @@ -0,0 +1 @@ +export * from "./InvoiceCancellation.js"; diff --git a/packages/models/src/invoice/InvoiceCancellation/types.ts b/packages/models/src/invoice/InvoiceCancellation/types.ts new file mode 100644 index 00000000..1cdc5864 --- /dev/null +++ b/packages/models/src/invoice/InvoiceCancellation/types.ts @@ -0,0 +1,4 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type InvoiceCancellationData = + MittwaldAPIV2.Components.Schemas.InvoiceCancellation; diff --git a/packages/models/src/invoice/InvoiceItem/InvoiceItem.test.ts b/packages/models/src/invoice/InvoiceItem/InvoiceItem.test.ts new file mode 100644 index 00000000..4bdd89b2 --- /dev/null +++ b/packages/models/src/invoice/InvoiceItem/InvoiceItem.test.ts @@ -0,0 +1,61 @@ +import { afterEach, describe, expect, test } from "vitest"; + +import { buildInvoiceItemData } from "../../testing/builders/buildInvoiceItemData.js"; +import { resetBehaviors } from "../../testing/installBehaviors.js"; +import { ServicePeriod } from "./ServicePeriod.js"; +import { InvoiceItem } from "./InvoiceItem.js"; +import { Invoice } from "../Invoice/index.js"; + +afterEach(resetBehaviors); + +describe("InvoiceItem", () => { + test("maps its identity and invoice reference", () => { + const invoice = Invoice.ofId("i-1"); + const item = new InvoiceItem(invoice, buildInvoiceItemData()); + + expect(item.id).toBe("item-id"); + expect(item.invoice).toBe(invoice); + }); + + test("maps a service period", () => { + const item = new InvoiceItem( + Invoice.ofId("i-1"), + buildInvoiceItemData({ + servicePeriod: { + start: "2024-01-01T00:00:00.000Z", + end: "2024-03-01T00:00:00.000Z", + }, + }), + ); + + expect(item.servicePeriod).toBeInstanceOf(ServicePeriod); + expect(item.servicePeriod?.start.toMillis()).toBe( + Date.parse("2024-01-01T00:00:00.000Z"), + ); + expect(item.servicePeriod?.end.toMillis()).toBe( + Date.parse("2024-03-01T00:00:00.000Z"), + ); + expect(item.servicePeriod?.interval.isValid).toBe(true); + expect(item.servicePeriod?.possibleStartDates.length).toBeGreaterThan(0); + expect(item.servicePeriod?.possibleEndDates.length).toBeGreaterThan(0); + }); + + test("leaves an absent service period undefined", () => { + const item = new InvoiceItem(Invoice.ofId("i-1"), buildInvoiceItemData()); + + expect(item.servicePeriod).toBeUndefined(); + }); + + test("maps a service date and leaves an absent one undefined", () => { + const present = new InvoiceItem( + Invoice.ofId("i-1"), + buildInvoiceItemData({ serviceDate: "2024-02-03T00:00:00.000Z" }), + ); + const absent = new InvoiceItem(Invoice.ofId("i-1"), buildInvoiceItemData()); + + expect(present.serviceDate?.toMillis()).toBe( + Date.parse("2024-02-03T00:00:00.000Z"), + ); + expect(absent.serviceDate).toBeUndefined(); + }); +}); diff --git a/packages/models/src/invoice/InvoiceItem/InvoiceItem.ts b/packages/models/src/invoice/InvoiceItem/InvoiceItem.ts new file mode 100644 index 00000000..25b12e93 --- /dev/null +++ b/packages/models/src/invoice/InvoiceItem/InvoiceItem.ts @@ -0,0 +1,30 @@ +import { DateTime } from "luxon"; + +import type { InvoiceItemData } from "./types.js"; +import type { Invoice } from "../Invoice/index.js"; + +import { ServicePeriod } from "./ServicePeriod.js"; +import { DataModel } from "../../base/index.js"; + +export class InvoiceItem extends DataModel { + public readonly id: string; + public readonly invoice: Invoice; + public readonly serviceDate?: DateTime; + public readonly servicePeriod?: ServicePeriod; + + public constructor(invoice: Invoice, data: InvoiceItemData) { + super(data); + this.invoice = invoice; + this.id = data.itemId; + + if (data.servicePeriod) { + this.servicePeriod = new ServicePeriod( + DateTime.fromISO(data.servicePeriod.start), + DateTime.fromISO(data.servicePeriod.end), + ); + } + if (data.serviceDate) { + this.serviceDate = DateTime.fromISO(data.serviceDate); + } + } +} diff --git a/packages/models/src/invoice/InvoiceItem/ServicePeriod.ts b/packages/models/src/invoice/InvoiceItem/ServicePeriod.ts new file mode 100644 index 00000000..cb306683 --- /dev/null +++ b/packages/models/src/invoice/InvoiceItem/ServicePeriod.ts @@ -0,0 +1,25 @@ +import { type DateTime, Interval } from "luxon"; + +import { required } from "../../base/lib/required.js"; + +export class ServicePeriod { + public readonly end: DateTime; + public readonly interval: Interval; + public readonly possibleEndDates: DateTime[]; + public readonly possibleStartDates: DateTime[]; + public readonly start: DateTime; + + public constructor(start: DateTime, end: DateTime) { + this.start = start; + this.end = end; + this.interval = Interval.fromDateTimes(this.start, this.end); + + this.possibleStartDates = this.interval + .splitBy({ months: 1 }) + .map((i) => required(i.start)); + + this.possibleEndDates = this.interval + .splitBy({ months: 1 }) + .map((i) => required(i.end)); + } +} diff --git a/packages/models/src/invoice/InvoiceItem/index.ts b/packages/models/src/invoice/InvoiceItem/index.ts new file mode 100644 index 00000000..2820b198 --- /dev/null +++ b/packages/models/src/invoice/InvoiceItem/index.ts @@ -0,0 +1 @@ +export * from "./InvoiceItem.js"; diff --git a/packages/models/src/invoice/InvoiceItem/types.ts b/packages/models/src/invoice/InvoiceItem/types.ts new file mode 100644 index 00000000..4d7a197e --- /dev/null +++ b/packages/models/src/invoice/InvoiceItem/types.ts @@ -0,0 +1,4 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type InvoiceItemData = + MittwaldAPIV2.Components.Schemas.InvoiceInvoiceItem; diff --git a/packages/models/src/invoice/InvoiceItemGroup/InvoiceItemGroup.test.ts b/packages/models/src/invoice/InvoiceItemGroup/InvoiceItemGroup.test.ts new file mode 100644 index 00000000..dfd86a4c --- /dev/null +++ b/packages/models/src/invoice/InvoiceItemGroup/InvoiceItemGroup.test.ts @@ -0,0 +1,41 @@ +import { afterEach, describe, expect, test } from "vitest"; + +import { buildInvoiceItemGroupData } from "../../testing/builders/buildInvoiceItemGroupData.js"; +import { buildInvoiceItemData } from "../../testing/builders/buildInvoiceItemData.js"; +import { buildInvoiceData } from "../../testing/builders/buildInvoiceData.js"; +import { resetBehaviors } from "../../testing/installBehaviors.js"; +import { InvoiceItemGroup } from "./InvoiceItemGroup.js"; +import { InvoiceDetailed } from "../Invoice/index.js"; +import { InvoiceItem } from "../InvoiceItem/index.js"; + +afterEach(resetBehaviors); + +describe("InvoiceItemGroup", () => { + test("maps its description and items", () => { + const invoice = new InvoiceDetailed(buildInvoiceData()); + const group = new InvoiceItemGroup( + invoice, + buildInvoiceItemGroupData({ + items: [ + buildInvoiceItemData({ itemId: "item-1" }), + buildInvoiceItemData({ itemId: "item-2" }), + ], + }), + ); + + expect(group.description).toBe("Test group"); + expect(group.items).toHaveLength(2); + expect(group.items.every((item) => item instanceof InvoiceItem)).toBe(true); + expect(group.items.every((item) => item.invoice === invoice)).toBe(true); + }); + + test("leaves an omitted description undefined", () => { + const invoice = new InvoiceDetailed(buildInvoiceData()); + const group = new InvoiceItemGroup( + invoice, + buildInvoiceItemGroupData({ description: undefined }), + ); + + expect(group.description).toBeUndefined(); + }); +}); diff --git a/packages/models/src/invoice/InvoiceItemGroup/InvoiceItemGroup.ts b/packages/models/src/invoice/InvoiceItemGroup/InvoiceItemGroup.ts new file mode 100644 index 00000000..4dbc7916 --- /dev/null +++ b/packages/models/src/invoice/InvoiceItemGroup/InvoiceItemGroup.ts @@ -0,0 +1,18 @@ +import type { InvoiceItemGroupData } from "./types.js"; +import type { InvoiceDetailed } from "../Invoice/index.js"; + +import { InvoiceItem } from "../InvoiceItem/index.js"; +import { DataModel } from "../../base/index.js"; + +export class InvoiceItemGroup extends DataModel { + public readonly description?: string; + public readonly invoice: InvoiceDetailed; + public readonly items: InvoiceItem[]; + + public constructor(invoice: InvoiceDetailed, data: InvoiceItemGroupData) { + super(data); + this.invoice = invoice; + this.description = data.description; + this.items = data.items.map((i) => new InvoiceItem(invoice, i)); + } +} diff --git a/packages/models/src/invoice/InvoiceItemGroup/index.ts b/packages/models/src/invoice/InvoiceItemGroup/index.ts new file mode 100644 index 00000000..eea1f064 --- /dev/null +++ b/packages/models/src/invoice/InvoiceItemGroup/index.ts @@ -0,0 +1 @@ +export * from "./InvoiceItemGroup.js"; diff --git a/packages/models/src/invoice/InvoiceItemGroup/types.ts b/packages/models/src/invoice/InvoiceItemGroup/types.ts new file mode 100644 index 00000000..8cabbafb --- /dev/null +++ b/packages/models/src/invoice/InvoiceItemGroup/types.ts @@ -0,0 +1,3 @@ +import type { InvoiceData } from "../Invoice/index.js"; + +export type InvoiceItemGroupData = InvoiceData["groups"][number]; diff --git a/packages/models/src/invoice/InvoiceRecipient/InvoiceRecipient.test.ts b/packages/models/src/invoice/InvoiceRecipient/InvoiceRecipient.test.ts new file mode 100644 index 00000000..cf797dd0 --- /dev/null +++ b/packages/models/src/invoice/InvoiceRecipient/InvoiceRecipient.test.ts @@ -0,0 +1,72 @@ +import { afterEach, describe, expect, test } from "vitest"; + +import { buildInvoiceRecipientData } from "../../testing/builders/buildInvoiceRecipientData.js"; +import { resetBehaviors } from "../../testing/installBehaviors.js"; +import { InvoiceRecipient } from "./InvoiceRecipient.js"; + +afterEach(resetBehaviors); + +describe("InvoiceRecipient", () => { + test("maps recipient fields", () => { + const data = buildInvoiceRecipientData({ + phoneNumbers: ["+49 123", "+49 456"], + emailAddress: "test@example.com", + company: "Example GmbH", + useFormalTerm: true, + firstName: "First", + lastName: "Last", + title: "Dr.", + }); + + const recipient = new InvoiceRecipient(data); + + expect(recipient).toMatchObject({ + emailAddress: "test@example.com", + salutation: data.salutation, + company: "Example GmbH", + phoneNumber: "+49 123", + address: data.address, + useFormalTerm: true, + firstName: "First", + lastName: "Last", + title: "Dr.", + }); + }); + + test.each([undefined, []])( + "leaves phoneNumber undefined for %s phone numbers", + (phoneNumbers) => { + const recipient = new InvoiceRecipient( + buildInvoiceRecipientData({ phoneNumbers }), + ); + + expect(recipient.phoneNumber).toBeUndefined(); + }, + ); + + test("derives the full name and leaves it undefined without names", () => { + const named = new InvoiceRecipient( + buildInvoiceRecipientData({ firstName: "First", lastName: "Last" }), + ); + const unnamed = new InvoiceRecipient(buildInvoiceRecipientData()); + + expect(named.fullName).toBe("First Last"); + expect(unnamed.fullName).toBeUndefined(); + }); + + test("uses company as display name and falls back to full name", () => { + const company = new InvoiceRecipient( + buildInvoiceRecipientData({ + company: "Example GmbH", + firstName: "First", + lastName: "Last", + }), + ); + const person = new InvoiceRecipient( + buildInvoiceRecipientData({ firstName: "First", lastName: "Last" }), + ); + + expect(company.displayName).toBe("Example GmbH"); + expect(person.displayName).toBe("First Last"); + }); +}); diff --git a/packages/models/src/invoice/InvoiceRecipient/InvoiceRecipient.ts b/packages/models/src/invoice/InvoiceRecipient/InvoiceRecipient.ts new file mode 100644 index 00000000..132fc21b --- /dev/null +++ b/packages/models/src/invoice/InvoiceRecipient/InvoiceRecipient.ts @@ -0,0 +1,42 @@ +import type { Salutation, Address } from "../../customer/index.js"; +import type { InvoiceRecipientData } from "./types.js"; + +import { DataModel } from "../../base/index.js"; + +export class InvoiceRecipient extends DataModel { + public readonly address: Address; + public readonly company?: string; + public readonly displayName?: string; + public readonly emailAddress?: string; + public readonly firstName?: string; + public readonly fullName?: string; + public readonly lastName?: string; + public readonly leitwegId?: string; + public readonly phoneNumber?: string; + public readonly purchaseOrderReference?: string; + public readonly salutation: Salutation; + public readonly title?: string; + public readonly useFormalTerm?: boolean; + public constructor(data: InvoiceRecipientData) { + super(data); + this.company = data.company; + this.emailAddress = data.emailAddress; + this.firstName = data.firstName; + this.lastName = data.lastName; + this.leitwegId = data.leitwegId; + this.phoneNumber = + data.phoneNumbers && data.phoneNumbers.length > 0 + ? data.phoneNumbers[0] + : undefined; + this.purchaseOrderReference = data.purchaseOrderReference; + this.useFormalTerm = data.useFormalTerm; + this.title = data.title; + this.address = data.address; + this.salutation = data.salutation; + this.fullName = + this.firstName || this.lastName + ? `${this.data.firstName} ${this.data.lastName}`.trim() + : undefined; + this.displayName = this.data.company ?? this.fullName; + } +} diff --git a/packages/models/src/invoice/InvoiceRecipient/index.ts b/packages/models/src/invoice/InvoiceRecipient/index.ts new file mode 100644 index 00000000..7fc0fbdc --- /dev/null +++ b/packages/models/src/invoice/InvoiceRecipient/index.ts @@ -0,0 +1,2 @@ +export * from "./InvoiceRecipient.js"; +export * from "./types.js"; diff --git a/packages/models/src/invoice/InvoiceRecipient/types.ts b/packages/models/src/invoice/InvoiceRecipient/types.ts new file mode 100644 index 00000000..f23d3e9c --- /dev/null +++ b/packages/models/src/invoice/InvoiceRecipient/types.ts @@ -0,0 +1,3 @@ +import type { InvoiceData } from "../Invoice/index.js"; + +export type InvoiceRecipientData = InvoiceData["recipient"]; diff --git a/packages/models/src/invoice/index.ts b/packages/models/src/invoice/index.ts new file mode 100644 index 00000000..167209f5 --- /dev/null +++ b/packages/models/src/invoice/index.ts @@ -0,0 +1,5 @@ +export * from "./Invoice/index.js"; +export * from "./InvoiceCancellation/index.js"; +export * from "./InvoiceItem/index.js"; +export * from "./InvoiceItemGroup/index.js"; +export * from "./InvoiceRecipient/index.js"; diff --git a/packages/models/src/lib/arrayRemoveItem.ts b/packages/models/src/lib/arrayRemoveItem.ts new file mode 100644 index 00000000..1f5bec24 --- /dev/null +++ b/packages/models/src/lib/arrayRemoveItem.ts @@ -0,0 +1,6 @@ +export const arrayRemoveItem = ( + items: T[], + pred: (i: T) => boolean, +): void => { + items.splice(items.findIndex(pred), 1); +}; diff --git a/packages/models/src/lib/deepFreeze.ts b/packages/models/src/lib/deepFreeze.ts deleted file mode 100644 index 9bef3077..00000000 --- a/packages/models/src/lib/deepFreeze.ts +++ /dev/null @@ -1,10 +0,0 @@ -import deepFreezeLib from "another-deep-freeze"; -import type { ReadonlyDeep } from "type-fest"; -export type { ReadonlyDeep } from "type-fest"; - -type DeepFreeze = (subject: T) => ReadonlyDeep; - -// eslint-disable-next-line -const deepFreeze = (deepFreezeLib as any).default as DeepFreeze; - -export default deepFreeze; diff --git a/packages/models/src/lib/generateRandomAlphanumericString.ts b/packages/models/src/lib/generateRandomAlphanumericString.ts new file mode 100644 index 00000000..0f880193 --- /dev/null +++ b/packages/models/src/lib/generateRandomAlphanumericString.ts @@ -0,0 +1,13 @@ +const alphanumericCharacters = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + +export const generateRandomAlphanumericString = (length: number) => { + let result = ""; + const charactersLength = alphanumericCharacters.length; + for (let i = 0; i < length; i++) { + result += alphanumericCharacters.charAt( + Math.floor(Math.random() * charactersLength), + ); + } + return result; +}; diff --git a/packages/models/src/lib/index.ts b/packages/models/src/lib/index.ts new file mode 100644 index 00000000..a0c4ebf2 --- /dev/null +++ b/packages/models/src/lib/index.ts @@ -0,0 +1 @@ +export * from "./types.js"; diff --git a/packages/models/src/lib/joinedId.ts b/packages/models/src/lib/joinedId.ts index 5c164dd6..1cec1974 100644 --- a/packages/models/src/lib/joinedId.ts +++ b/packages/models/src/lib/joinedId.ts @@ -1 +1 @@ -export const joinedId = (...parts: Array) => parts.join(" | "); +export const joinedId = (...parts: unknown[]) => parts.join("."); diff --git a/packages/models/src/lib/replaceUrlTemplateValues.test.ts b/packages/models/src/lib/replaceUrlTemplateValues.test.ts new file mode 100644 index 00000000..6c9312e1 --- /dev/null +++ b/packages/models/src/lib/replaceUrlTemplateValues.test.ts @@ -0,0 +1,12 @@ +import { expect, test } from "vitest"; + +import { replaceUrlTemplateValues } from "./replaceUrlTemplateValues.js"; + +test("Does not replace values with keys with same starting substring", () => { + expect( + replaceUrlTemplateValues("http://test.de?id=:samePrefixAndMore", { + samePrefixAndMore: "bar", + samePrefix: "foo", + }), + ).toBe("http://test.de?id=bar"); +}); diff --git a/packages/models/src/lib/replaceUrlTemplateValues.ts b/packages/models/src/lib/replaceUrlTemplateValues.ts new file mode 100644 index 00000000..8b7a3c3c --- /dev/null +++ b/packages/models/src/lib/replaceUrlTemplateValues.ts @@ -0,0 +1,11 @@ +export const replaceUrlTemplateValues = ( + url: string, + values: Record = {}, +) => { + return Object.entries(values) + .sort((l, r) => r[0].length - l[0].length) + .reduce( + (replacedUrl, [key, value]) => replacedUrl.replace(`:${key}`, value), + url, + ); +}; diff --git a/packages/models/src/lib/types.ts b/packages/models/src/lib/types.ts index a443f1d6..32f304c9 100644 --- a/packages/models/src/lib/types.ts +++ b/packages/models/src/lib/types.ts @@ -1,9 +1 @@ -export type ParamsExceptFirst unknown> = - T extends (ignoredFirst: never, ...args: infer P) => unknown ? P : never; - -export type FirstParameter unknown> = T extends ( - first: infer P, - ...args: any[] -) => unknown - ? P - : never; +export type ExplicitAny = any; diff --git a/packages/models/src/mail/Autoresponder/Autoresponder.test.ts b/packages/models/src/mail/Autoresponder/Autoresponder.test.ts new file mode 100644 index 00000000..a0a53282 --- /dev/null +++ b/packages/models/src/mail/Autoresponder/Autoresponder.test.ts @@ -0,0 +1,48 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; +import { DateTime } from "luxon"; + +import { resetBehaviors } from "../../testing/installBehaviors.js"; +import { Autoresponder } from "./Autoresponder.js"; + +afterEach(resetBehaviors); + +describe("Autoresponder", () => { + test("is inactive when disabled", () => { + expect(new Autoresponder({ active: false }).isActive).toBe(false); + }); + + test("is active without an expiry date", () => { + const autoresponder = new Autoresponder({ message: "Away", active: true }); + + expect(autoresponder.isActive).toBe(true); + expect(autoresponder.message).toBe("Away"); + }); + + test("is planned when its start date is in the future", () => { + const autoresponder = new Autoresponder({ + startsAt: DateTime.now().plus({ days: 1 }).toISO(), + active: true, + }); + + expect(autoresponder.isPlanned).toBe(true); + expect(autoresponder.startsAt?.isValid).toBe(true); + }); + + test("is inactive after its expiry date", () => { + const autoresponder = new Autoresponder({ + expiresAt: DateTime.now().minus({ days: 1 }).toISO(), + active: true, + }); + + expect(autoresponder.isActive).toBe(false); + }); + + test("is not planned without a start date", () => { + const autoresponder = new Autoresponder({ active: true }); + + expect(autoresponder.isPlanned).toBe(false); + expect(autoresponder.startsAt).toBeUndefined(); + }); +}); + +void vi; diff --git a/packages/models/src/mail/Autoresponder/Autoresponder.ts b/packages/models/src/mail/Autoresponder/Autoresponder.ts new file mode 100644 index 00000000..87fad136 --- /dev/null +++ b/packages/models/src/mail/Autoresponder/Autoresponder.ts @@ -0,0 +1,27 @@ +import { DateTime } from "luxon"; + +import type { AutoresponderData } from "./types.js"; + +import { DataModel } from "../../base/index.js"; + +export class Autoresponder extends DataModel { + public readonly expiresAt?: DateTime; + public readonly isActive: boolean; + public readonly isPlanned: boolean; + public readonly message?: string; + public readonly startsAt?: DateTime; + + public constructor(data: AutoresponderData) { + super(data); + if (data.startsAt) { + this.startsAt = DateTime.fromISO(data.startsAt); + } + if (data.expiresAt) { + this.expiresAt = DateTime.fromISO(data.expiresAt); + } + this.message = data.message; + const now = DateTime.now(); + this.isPlanned = !!this.startsAt && this.startsAt > now; + this.isActive = data.active && (!this.expiresAt || this.expiresAt > now); + } +} diff --git a/packages/models/src/mail/Autoresponder/index.ts b/packages/models/src/mail/Autoresponder/index.ts new file mode 100644 index 00000000..3e160898 --- /dev/null +++ b/packages/models/src/mail/Autoresponder/index.ts @@ -0,0 +1,2 @@ +export * from "./Autoresponder.js"; +export * from "./types.js"; diff --git a/packages/models/src/mail/Autoresponder/types.ts b/packages/models/src/mail/Autoresponder/types.ts new file mode 100644 index 00000000..14c88f0e --- /dev/null +++ b/packages/models/src/mail/Autoresponder/types.ts @@ -0,0 +1,3 @@ +import type { MailAddressData } from "../MailAddress/index.js"; + +export type AutoresponderData = MailAddressData["autoResponder"]; diff --git a/packages/models/src/mail/DeliveryBox/DeliveryBox.test.ts b/packages/models/src/mail/DeliveryBox/DeliveryBox.test.ts new file mode 100644 index 00000000..dc25e5cf --- /dev/null +++ b/packages/models/src/mail/DeliveryBox/DeliveryBox.test.ts @@ -0,0 +1,196 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { buildDeliveryBoxData } from "../../testing/builders/buildDeliveryBoxData.js"; +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { config } from "../../config/config.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { Project } from "../../project/index.js"; +import { + DeliveryBoxListQuery, + DeliveryBoxDetailed, + DeliveryBoxListItem, + DeliveryBoxCommon, + DeliveryBoxList, + DeliveryBox, +} from "./DeliveryBox.js"; + +afterEach(resetBehaviors); + +describe("DeliveryBox", () => { + test("find delegates and returns detailed data", async () => { + const find = vi + .fn() + .mockResolvedValue(buildDeliveryBoxData({ id: "db-1" })); + installBehaviors({ deliveryBox: { find } }); + + const result = await DeliveryBox.find("db-1"); + + expect(find).toHaveBeenCalledWith("db-1"); + expect(result).toBeInstanceOf(DeliveryBoxDetailed); + expect(result?.id).toBe("db-1"); + }); + + test("find returns undefined when no delivery box exists", async () => { + installBehaviors({ + deliveryBox: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + expect(await DeliveryBox.find("missing")).toBeUndefined(); + }); + + test("references find their detailed data by id", async () => { + const find = vi + .fn() + .mockResolvedValue(buildDeliveryBoxData({ id: "db-1" })); + installBehaviors({ deliveryBox: { find } }); + const reference = DeliveryBox.ofId("db-1"); + + expect(reference).toBeInstanceOf(DeliveryBox); + await reference.findDetailed(); + expect(find).toHaveBeenCalledWith("db-1"); + }); + + test("create delegates and returns a reference", async () => { + const create = vi.fn().mockResolvedValue({ id: "db-new" }); + installBehaviors({ deliveryBox: { create } }); + const project = Project.ofId("p-1"); + + const result = await DeliveryBox.create(project, "Description", "secret"); + + expect(create).toHaveBeenCalledWith("p-1", "Description", "secret"); + expect(result).toBeInstanceOf(DeliveryBox); + expect(result.id).toBe("db-new"); + }); + + test("mutation methods delegate with the reference id", async () => { + const updateDescription = vi.fn(); + const updatePassword = vi.fn(); + const deleteBehavior = vi.fn(); + installBehaviors({ + deliveryBox: { + delete: deleteBehavior, + updateDescription, + updatePassword, + }, + }); + const deliveryBox = DeliveryBox.ofId("db-1"); + + await deliveryBox.updateDescription("New"); + await deliveryBox.updatePassword("password"); + await deliveryBox.delete(); + + expect(updateDescription).toHaveBeenCalledWith("db-1", "New"); + expect(updatePassword).toHaveBeenCalledWith("db-1", "password"); + expect(deleteBehavior).toHaveBeenCalledWith("db-1"); + }); + + test("query applies default pagination and maps list items", async () => { + const query = vi.fn().mockResolvedValue({ + items: [buildDeliveryBoxData()], + totalCount: 4, + }); + installBehaviors({ deliveryBox: { query } }); + const project = Project.ofId("p-1"); + + const listQuery = DeliveryBox.query({ project: project }); + expect(listQuery).toBeInstanceOf(DeliveryBoxListQuery); + const result = await listQuery.execute(); + + expect(query).toHaveBeenCalledWith( + "p-1", + expect.objectContaining({ limit: config.defaultPaginationLimit }), + ); + expect(result).toBeInstanceOf(DeliveryBoxList); + expect(result.items[0]).toBeInstanceOf(DeliveryBoxListItem); + expect(result.totalCount).toBe(4); + }); + + test("exposes common delivery box data", async () => { + installBehaviors({ + deliveryBox: { + find: vi.fn().mockResolvedValue( + buildDeliveryBoxData({ + sendingEnabled: false, + description: "Box", + projectId: "p-1", + name: "p-name", + }), + ), + }, + }); + + const result = await DeliveryBox.find("deliverybox-id"); + + expect(result?.sendingDisabled).toBe(true); + expect(result?.name).toBe("p-name"); + expect(result?.description).toBe("Box"); + expect(result?.project).toBeInstanceOf(Project); + expect(result?.project.id).toBe("p-1"); + }); + + test("list items retain ghostmaker class identity", () => { + const item = new DeliveryBoxListItem(buildDeliveryBoxData()); + + expect(item).toBeInstanceOf(DeliveryBoxListItem); + expect(item).toBeInstanceOf(DeliveryBoxCommon); + expect(item).toBeInstanceOf(DeliveryBox); + }); + + test("findCommon and getCommon delegate for a plain reference", async () => { + const find = vi + .fn() + .mockResolvedValue(buildDeliveryBoxData({ id: "db-1" })); + installBehaviors({ deliveryBox: { find } }); + const reference = DeliveryBox.ofId("db-1"); + + await expect(reference.findCommon()).resolves.toBeInstanceOf( + DeliveryBoxCommon, + ); + await expect(reference.getCommon()).resolves.toBeInstanceOf( + DeliveryBoxCommon, + ); + expect(find).toHaveBeenNthCalledWith(1, "db-1"); + expect(find).toHaveBeenNthCalledWith(2, "db-1"); + }); + + test("findCommon returns undefined and getCommon throws when the delivery box is missing", async () => { + installBehaviors({ + deliveryBox: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + DeliveryBox.ofId("missing").findCommon(), + ).resolves.toBeUndefined(); + await expect(DeliveryBox.ofId("missing").getCommon()).rejects.toThrow( + ObjectNotFoundError, + ); + }); + + test("findCommon and getCommon reuse an already materialized model without refetching", async () => { + const find = vi.fn().mockResolvedValue(buildDeliveryBoxData()); + installBehaviors({ deliveryBox: { find } }); + const detailed = await DeliveryBox.get("deliverybox-id"); + find.mockClear(); + + await expect(detailed.findCommon()).resolves.toBe(detailed); + await expect(detailed.getCommon()).resolves.toBe(detailed); + expect(find).not.toHaveBeenCalled(); + }); + + test("list items are already common and return themselves from findCommon and getCommon", async () => { + const item = new DeliveryBoxListItem(buildDeliveryBoxData()); + + await expect(item.findCommon()).resolves.toBe(item); + await expect(item.getCommon()).resolves.toBe(item); + }); +}); diff --git a/packages/models/src/mail/DeliveryBox/DeliveryBox.ts b/packages/models/src/mail/DeliveryBox/DeliveryBox.ts new file mode 100644 index 00000000..eba7bc15 --- /dev/null +++ b/packages/models/src/mail/DeliveryBox/DeliveryBox.ts @@ -0,0 +1,168 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { omit } from "remeda"; + +import type { + DeliveryBoxListQueryModelData, + DeliveryBoxListItemData, + DeliveryBoxData, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { Project } from "../../project/internal.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "DeliveryBox", +}) +export class DeliveryBox extends ReferenceModel { + public static readonly mailServer = "mail.agenturserver.de"; + public static readonly smtpSsl = "465"; + public static readonly smtpStartTls = "25"; + + public static async create( + project: Project, + description: string, + password: string, + ) { + const { id } = await config.behaviors.deliveryBox.create( + project.id, + description, + password, + ); + return new DeliveryBox(id); + } + + public static async find(id: string) { + const data = await config.behaviors.deliveryBox.find(id); + if (data !== undefined) { + return new DeliveryBoxDetailed(data); + } + } + + public static async get(id: string) { + const deliveryBox = await DeliveryBox.find(id); + assertObjectFound(deliveryBox, DeliveryBox, id); + return deliveryBox; + } + + public static ofId(id: string) { + return new DeliveryBox(id); + } + + public static query(query: DeliveryBoxListQueryModelData) { + return new DeliveryBoxListQuery(query); + } + + public async delete() { + await config.behaviors.deliveryBox.delete(this.id); + } + + public async findCommon(): Promise { + return this instanceof DeliveryBoxCommon ? this : this.findDetailed(); + } + + public findDetailed(): Promise { + return DeliveryBox.find(this.id); + } + + public async getCommon(): Promise { + return this instanceof DeliveryBoxCommon ? this : this.getDetailed(); + } + public getDetailed(): Promise { + return DeliveryBox.get(this.id); + } + public async updateDescription(description: string) { + await config.behaviors.deliveryBox.updateDescription(this.id, description); + } + + public async updatePassword(password: string) { + await config.behaviors.deliveryBox.updatePassword(this.id, password); + } +} + +export class DeliveryBoxCommon extends WithData()( + DeliveryBox, +) { + public override readonly data: DeliveryBoxData; + public readonly description: string; + public readonly id: string; + public readonly name: string; + public readonly project: Project; + public readonly sendingDisabled: boolean; + public constructor(data: DeliveryBoxData) { + super(data.id); + this.data = data; + this.id = data.id; + this.project = Project.ofId(this.data.projectId); + this.sendingDisabled = !data.sendingEnabled; + this.name = data.name; + this.description = data.description; + } +} + +export class DeliveryBoxDetailed extends DeliveryBoxCommon { + public constructor(data: DeliveryBoxData) { + super(data); + } +} + +export class DeliveryBoxListQuery extends ListQueryModel { + public constructor(query: DeliveryBoxListQueryModelData) { + super(query, { dependencies: [extractId(query.project)] }); + } + + public async execute() { + const { totalCount, items } = await config.behaviors.deliveryBox.query( + extractId(this.query.project), + { + limit: config.defaultPaginationLimit, + ...omit(this.query, ["project"]), + }, + ); + return new DeliveryBoxList( + this.query, + items.map((d) => new DeliveryBoxListItem(d)), + totalCount, + ); + } + + public async getTotalCount() { + const { items } = await this.refine({ limit: 1 }).execute(); + return items.length; + } + + public refine(query: Partial = {}) { + return new DeliveryBoxListQuery({ + ...this.query, + ...query, + }); + } +} +export class DeliveryBoxListItem extends DeliveryBoxCommon { + public constructor(data: DeliveryBoxListItemData) { + super(data); + } +} + +export class DeliveryBoxList extends WithListData()( + DeliveryBoxListQuery, +) { + public override readonly items: readonly DeliveryBoxListItem[]; + public override readonly totalCount: number; + public constructor( + query: DeliveryBoxListQueryModelData, + deliveryBoxes: DeliveryBoxListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(deliveryBoxes); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/mail/DeliveryBox/behaviors/api.ts b/packages/models/src/mail/DeliveryBox/behaviors/api.ts new file mode 100644 index 00000000..1ec32d2a --- /dev/null +++ b/packages/models/src/mail/DeliveryBox/behaviors/api.ts @@ -0,0 +1,62 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { DeliveryBoxBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount } from "../../../base/index.js"; + +export const apiDeliveryBoxBehaviors = ( + client: MittwaldAPIV2Client, +): DeliveryBoxBehaviors => ({ + query: async (projectId, query = {}) => { + const response = await client.mail.listDeliveryBoxes({ + queryParameters: query, + projectId, + }); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + create: async (projectId, description, password) => { + const response = await client.mail.createDeliverybox({ + data: { + description, + password, + }, + projectId, + }); + validateResponse(response, 201); + return response.data; + }, + updateDescription: async (deliveryBoxId, description) => { + const response = await client.mail.updateDeliveryBoxDescription({ + data: { + description, + }, + deliveryBoxId, + }); + validateResponse(response, 204); + }, + updatePassword: async (deliveryBoxId, password) => { + const response = await client.mail.updateDeliveryBoxPassword({ + data: { + password, + }, + deliveryBoxId, + }); + validateResponse(response, 204); + }, + find: async (deliveryBoxId) => { + const response = await client.mail.getDeliveryBox({ deliveryBoxId }); + if (response.status === 200) { + return response.data; + } + validateResponse(response, [403, 404]); + }, + delete: async (deliveryBoxId) => { + const response = await client.mail.deleteDeliveryBox({ deliveryBoxId }); + validateResponse(response, 204); + }, +}); diff --git a/packages/models/src/mail/DeliveryBox/behaviors/index.ts b/packages/models/src/mail/DeliveryBox/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/mail/DeliveryBox/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/mail/DeliveryBox/behaviors/types.ts b/packages/models/src/mail/DeliveryBox/behaviors/types.ts new file mode 100644 index 00000000..c6ea1a6a --- /dev/null +++ b/packages/models/src/mail/DeliveryBox/behaviors/types.ts @@ -0,0 +1,27 @@ +import type { QueryResponseData } from "../../../base/index.js"; +import type { + DeliveryBoxListQueryData, + DeliveryBoxListItemData, + DeliveryBoxData, +} from "../types.js"; + +export interface DeliveryBoxBehaviors { + query: ( + projectId: string, + query?: DeliveryBoxListQueryData, + ) => Promise>; + create: ( + projectId: string, + description: string, + password: string, + ) => Promise<{ id: string }>; + + updateDescription: ( + deliveryBoxId: string, + description: string, + ) => Promise; + + updatePassword: (deliveryBoxId: string, password: string) => Promise; + find: (deliveryBoxId: string) => Promise; + delete: (deliveryBoxId: string) => Promise; +} diff --git a/packages/models/src/mail/DeliveryBox/index.ts b/packages/models/src/mail/DeliveryBox/index.ts new file mode 100644 index 00000000..011568ae --- /dev/null +++ b/packages/models/src/mail/DeliveryBox/index.ts @@ -0,0 +1,2 @@ +export * from "./DeliveryBox.js"; +export * from "./types.js"; diff --git a/packages/models/src/mail/DeliveryBox/types.ts b/packages/models/src/mail/DeliveryBox/types.ts new file mode 100644 index 00000000..09c75a7d --- /dev/null +++ b/packages/models/src/mail/DeliveryBox/types.ts @@ -0,0 +1,16 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import type { Project } from "../../project/index.js"; + +export type DeliveryBoxData = + MittwaldAPIV2.Operations.MailGetDeliveryBox.ResponseData; + +export type DeliveryBoxListQueryData = + MittwaldAPIV2.Paths.V2ProjectsProjectIdDeliveryBoxes.Get.Parameters.Query; + +export type DeliveryBoxListQueryModelData = { + project: Project | string; +} & DeliveryBoxListQueryData; + +export type DeliveryBoxListItemData = + MittwaldAPIV2.Operations.MailListDeliveryBoxes.ResponseData[number]; diff --git a/packages/models/src/mail/MailAddress/MailAddress.test.ts b/packages/models/src/mail/MailAddress/MailAddress.test.ts new file mode 100644 index 00000000..11326f2f --- /dev/null +++ b/packages/models/src/mail/MailAddress/MailAddress.test.ts @@ -0,0 +1,326 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import type { MailAddressRequestData } from "./types.js"; + +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { + buildMailAddressData, + buildMailbox, +} from "../../testing/builders/buildMailAddressData.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { Autoresponder } from "../Autoresponder/index.js"; +import { MailRateLimit } from "../MailRateLimit/index.js"; +import { config } from "../../config/config.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { Project } from "../../project/index.js"; +import { + MailAddressListQuery, + MailAddressDetailed, + MailAddressListItem, + MailAddressCommon, + MailAddressList, + MailAddress, +} from "./MailAddress.js"; + +afterEach(resetBehaviors); + +describe("MailAddress", () => { + test("find delegates and returns detailed data", async () => { + const find = vi.fn().mockResolvedValue(buildMailAddressData({ id: "m-1" })); + installBehaviors({ mailAddress: { find } }); + + const result = await MailAddress.find("m-1"); + + expect(find).toHaveBeenCalledWith("m-1"); + expect(result).toBeInstanceOf(MailAddressDetailed); + expect(result?.id).toBe("m-1"); + }); + + test("find returns undefined when no mail address exists", async () => { + installBehaviors({ + mailAddress: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + expect(await MailAddress.find("missing")).toBeUndefined(); + }); + + test("references find their detailed data by id", async () => { + const find = vi.fn().mockResolvedValue(buildMailAddressData({ id: "m-1" })); + installBehaviors({ mailAddress: { find } }); + const reference = MailAddress.ofId("m-1"); + + expect(reference).toBeInstanceOf(MailAddress); + await reference.findDetailed(); + expect(find).toHaveBeenCalledWith("m-1"); + }); + + test("create delegates and returns a reference", async () => { + const createMailAddress = vi.fn().mockResolvedValue({ id: "m-new" }); + installBehaviors({ mailAddress: { createMailAddress } }); + const project = Project.ofId("p-1"); + const data: MailAddressRequestData = { + mailbox: { + enableSpamProtection: true, + quotaInBytes: 1073741824, + password: "secret", + }, + address: "info@example.com", + isCatchAll: false, + }; + + const result = await MailAddress.create(project, data); + + expect(createMailAddress).toHaveBeenCalledWith("p-1", data); + expect(result).toBeInstanceOf(MailAddress); + expect(result.id).toBe("m-new"); + }); + + test("mutation methods delegate with the reference id", async () => { + const updateAddress = vi.fn(); + const updatePassword = vi.fn(); + const deleteBehavior = vi.fn(); + const updateCatchAll = vi.fn(); + const updateForwardAddresses = vi.fn(); + const requestRateLimitChange = vi.fn(); + installBehaviors({ + mailAddress: { + delete: deleteBehavior, + requestRateLimitChange, + updateForwardAddresses, + updateCatchAll, + updatePassword, + updateAddress, + }, + }); + const mailAddress = MailAddress.ofId("m-1"); + + await mailAddress.updateAddress("a"); + await mailAddress.updatePassword("pw"); + await mailAddress.delete(); + await mailAddress.activateCatchAll(); + await mailAddress.deactivateCatchAll(); + await mailAddress.updateForwardAddresses(["x"]); + await mailAddress.requestRateLimitChange("rl-1"); + await mailAddress.requestRateLimitChange(MailRateLimit.ofId("rl-9")); + + expect(updateAddress).toHaveBeenCalledWith("m-1", "a"); + expect(updatePassword).toHaveBeenCalledWith("m-1", "pw"); + expect(deleteBehavior).toHaveBeenCalledWith("m-1"); + expect(updateCatchAll).toHaveBeenNthCalledWith(1, "m-1", true); + expect(updateCatchAll).toHaveBeenNthCalledWith(2, "m-1", false); + expect(updateForwardAddresses).toHaveBeenCalledWith("m-1", ["x"]); + expect(requestRateLimitChange).toHaveBeenNthCalledWith(1, "m-1", "rl-1"); + expect(requestRateLimitChange).toHaveBeenNthCalledWith(2, "m-1", "rl-9"); + }); + + test("converts quota from GiB to bytes", async () => { + const updateQuota = vi.fn(); + installBehaviors({ mailAddress: { updateQuota } }); + + await MailAddress.ofId("m-1").updateQuota(1); + + expect(updateQuota).toHaveBeenCalledWith("m-1", 1073741824); + }); + + test("derives forward address values without a mailbox", () => { + const address = new MailAddressDetailed(buildMailAddressData()); + + expect(address.isForward).toBe(true); + expect(address.storageUsagePercent).toBe(0); + expect(address.autoresponder).toBeInstanceOf(Autoresponder); + }); + + test("derives mailbox values and related references", () => { + const address = new MailAddressDetailed( + buildMailAddressData({ + mailbox: buildMailbox({ + spamProtection: { + relocationMinSpamScore: 1, + autoDeleteSpam: false, + folder: "spam", + active: true, + }, + storageInBytes: { + current: { updatedAt: "2024-01-01T00:00:00.000Z", value: 90 }, + limit: 100, + }, + sendingEnabled: false, + }), + rateLimitChangeRequest: { rateLimitId: "rl-requested" }, + address: "local@example.com", + }), + ); + + expect(address.isForward).toBe(false); + expect(address.sendingDisabled).toBe(true); + expect(address.storageUsagePercent).toBe(0.9); + expect(address.hasStorageUsageWarning).toBe(false); + expect(address.isStorageUsageCritical).toBe(true); + expect(address.storageLimit.in("bytes")).toBe(100); + expect(address.storageUsage.in("bytes")).toBe(90); + expect(address.domain).toBe("example.com"); + expect(address.localPart).toBe("local"); + expect(address.spamProtectionActive).toBe(true); + expect(address.rateLimit).toBeInstanceOf(MailRateLimit); + expect(address.rateLimit?.id).toBe("rl-1"); + expect(address.requestedRateLimit).toBeInstanceOf(MailRateLimit); + expect(address.requestedRateLimit?.id).toBe("rl-requested"); + }); + + test("distinguishes warning storage usage from critical usage", () => { + const address = new MailAddressDetailed( + buildMailAddressData({ + mailbox: buildMailbox({ + storageInBytes: { + current: { updatedAt: "2024-01-01T00:00:00.000Z", value: 80 }, + limit: 100, + }, + }), + }), + ); + + expect(address.hasStorageUsageWarning).toBe(true); + expect(address.isStorageUsageCritical).toBe(false); + }); + + test("splits email addresses into local and domain components", () => { + expect(MailAddress.getEmailAddressComponents("a@b.de")).toEqual({ + domain: "b.de", + local: "a", + }); + expect(MailAddress.getEmailAddressComponents("a")).toEqual({ + domain: "", + local: "a", + }); + }); + + test("queries project mail addresses with default pagination", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildMailAddressData()], + totalCount: 3, + }); + installBehaviors({ mailAddress: { list } }); + const project = Project.ofId("p-1"); + + const listQuery = MailAddress.query({ project }); + expect(listQuery).toBeInstanceOf(MailAddressListQuery); + const result = await listQuery.execute(); + + expect(list).toHaveBeenCalledWith( + "p-1", + expect.objectContaining({ limit: config.defaultPaginationLimit }), + ); + expect(result).toBeInstanceOf(MailAddressList); + expect(result.items[0]).toBeInstanceOf(MailAddressListItem); + expect(result.totalCount).toBe(3); + }); + + test("queries user mail addresses when no project is provided", async () => { + const listForUser = vi.fn().mockResolvedValue({ + items: [buildMailAddressData()], + totalCount: 2, + }); + installBehaviors({ mailAddress: { listForUser } }); + + const listQuery = MailAddress.query(); + expect(listQuery).toBeInstanceOf(MailAddressListQuery); + const result = await listQuery.execute(); + + expect(listForUser).toHaveBeenCalledWith( + expect.objectContaining({ limit: config.defaultPaginationLimit }), + ); + expect(result).toBeInstanceOf(MailAddressList); + expect(result.items[0]).toBeInstanceOf(MailAddressListItem); + expect(result.totalCount).toBe(2); + }); + + test("list items retain ghostmaker class identity", () => { + const item = new MailAddressListItem(buildMailAddressData()); + + expect(item).toBeInstanceOf(MailAddressListItem); + expect(item).toBeInstanceOf(MailAddressCommon); + expect(item).toBeInstanceOf(MailAddress); + }); + + test("findCommon and getCommon delegate for a plain reference", async () => { + const find = vi.fn().mockResolvedValue(buildMailAddressData({ id: "m-1" })); + installBehaviors({ mailAddress: { find } }); + const reference = MailAddress.ofId("m-1"); + + await expect(reference.findCommon()).resolves.toBeInstanceOf( + MailAddressCommon, + ); + await expect(reference.getCommon()).resolves.toBeInstanceOf( + MailAddressCommon, + ); + expect(find).toHaveBeenNthCalledWith(1, "m-1"); + expect(find).toHaveBeenNthCalledWith(2, "m-1"); + }); + + test("findCommon returns undefined when the reference cannot be resolved", async () => { + installBehaviors({ + mailAddress: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + MailAddress.ofId("missing").findCommon(), + ).resolves.toBeUndefined(); + }); + + test("getCommon throws when the reference cannot be resolved", async () => { + installBehaviors({ + mailAddress: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(MailAddress.ofId("missing").getCommon()).rejects.toThrow( + ObjectNotFoundError, + ); + }); + + test("findCommon and getCommon reuse an already materialized model without refetching", async () => { + const find = vi.fn().mockResolvedValue(buildMailAddressData()); + installBehaviors({ mailAddress: { find } }); + const detailed = await MailAddress.get("mailaddr-id"); + find.mockClear(); + + await expect(detailed.findCommon()).resolves.toBe(detailed); + await expect(detailed.getCommon()).resolves.toBe(detailed); + expect(find).not.toHaveBeenCalled(); + }); + + test("list items are already common and return themselves from findCommon and getCommon", async () => { + const item = new MailAddressListItem(buildMailAddressData()); + + await expect(item.findCommon()).resolves.toBe(item); + await expect(item.getCommon()).resolves.toBe(item); + }); + + test("aggregateMetaData pins the mail/mailaddress identity", () => { + expect(MailAddress.aggregateMetaData).toBeInstanceOf(AggregateMetaData); + expect(MailAddress.aggregateMetaData.domain).toBe("mail"); + expect(MailAddress.aggregateMetaData.aggregate).toBe("mailaddress"); + }); + + test("leaves rate limit and spam data unset for a forward without a mailbox", () => { + const address = new MailAddressDetailed( + buildMailAddressData({ address: "catchall" }), + ); + + expect(address.rateLimit).toBeUndefined(); + expect(address.requestedRateLimit).toBeUndefined(); + expect(address.sendingDisabled).toBe(false); + expect(address.spamProtectionActive).toBe(false); + expect(address.domain).toBeUndefined(); + expect(address.localPart).toBe("catchall"); + }); +}); diff --git a/packages/models/src/mail/MailAddress/MailAddress.ts b/packages/models/src/mail/MailAddress/MailAddress.ts new file mode 100644 index 00000000..ac6a20ae --- /dev/null +++ b/packages/models/src/mail/MailAddress/MailAddress.ts @@ -0,0 +1,385 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import invariant from "tiny-invariant"; +import { omit } from "remeda"; + +import type { MailAddressBackupListQuery } from "../MailAddressBackup/index.js"; +import type { + AutoresponderUpdateRequestData, + MailAddressListQueryModelData, + MailAddressListQueryData, + MailAddressListItemData, + MailAddressRequestData, + ForwardRequestData, + MailAddressData, +} from "./types.js"; + +import { MailArticleTemplate } from "../../article/Article/templates/MailArticleTemplate.js"; +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { MailAddressArchive } from "../MailAddressArchive/index.js"; +import { MailAddressBackup } from "../MailAddressBackup/index.js"; +import { AggregateMetaData, Bytes } from "../../common/index.js"; +import { MailArchiveOrderRequest } from "../../order/index.js"; +import { Project } from "../../project/internal.js"; +import { Autoresponder } from "../Autoresponder/index.js"; +import { MailRateLimit } from "../MailRateLimit/index.js"; +import { Article } from "../../article/index.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "MailAddress", +}) +export class MailAddress extends ReferenceModel { + public static aggregateMetaData = new AggregateMetaData( + "mail", + "mailaddress", + ); + + public static readonly imapSsl = "993"; + + public static readonly imapStartTls = "143"; + public static readonly mailboxMaxQuotaInGib = 150; + public static readonly mailboxMinQuotaInGib = 0.2; + public static readonly mailboxQuotaStepInGib = 0.1; + public static readonly mailServer = "mail.agenturserver.de"; + public static readonly pop3Ssl = "995"; + public static readonly pop3StartTls = "110"; + public static readonly quotaUsageError = 0.9; + public static readonly quotaUsageWarning = 0.75; + public static readonly smtpSsl = "465"; + public static readonly smtpStartTls = "25"; + public readonly backups: MailAddressBackupListQuery; + + public constructor(id: string) { + super(id); + this.backups = MailAddressBackup.query({ mailAddress: this }); + } + + public static async create(project: Project, data: MailAddressRequestData) { + const response = await config.behaviors.mailAddress.createMailAddress( + project.id, + data, + ); + + return new MailAddress(response.id); + } + + public static async createForward( + project: Project, + data: ForwardRequestData, + ) { + const response = await config.behaviors.mailAddress.createForward( + project.id, + data, + ); + + return new MailAddress(response.id); + } + + public static detectPhishingMail = async (file: File) => { + return await config.behaviors.mailAddress.detectPhishingMail(file); + }; + + public static async find(id: string) { + const data = await config.behaviors.mailAddress.find(id); + if (data !== undefined) { + return new MailAddressDetailed(data); + } + } + + public static async findMailArchiveArticle() { + const articles = await Article.query({ + templateNames: [MailArticleTemplate.templateName], + orderable: ["full"], + }).execute(); + return articles.items[0]; + } + + public static async get(id: string) { + const mailAddress = await MailAddress.find(id); + assertObjectFound(mailAddress, MailAddress, id); + return mailAddress; + } + + public static getEmailAddressComponents = ( + address = "", + ): { domain: string; local: string } => { + const parts = address.split("@"); + invariant(!!parts[0], "Invalid email address"); + return { domain: parts[1] ?? "", local: parts[0] }; + }; + + public static ofId(id: string) { + return new MailAddress(id); + } + + public static async previewMultipleMailArchiveOrders( + mailAddresses: + readonly MailAddressListItem[] | readonly MailAddressDetailed[], + syncExistingMails?: boolean, + ) { + return await Promise.all( + mailAddresses.map(async (mailAddress) => { + const preview = + await mailAddress.previewMailArchiveOrder(syncExistingMails); + return { mailAddress, preview }; + }), + ); + } + + public static query(query: MailAddressListQueryModelData = {}) { + return new MailAddressListQuery(query); + } + + public async activateCatchAll() { + await config.behaviors.mailAddress.updateCatchAll(this.id, true); + } + + public async deactivateCatchAll() { + await config.behaviors.mailAddress.updateCatchAll(this.id, false); + } + + public async delete() { + await config.behaviors.mailAddress.delete(this.id); + } + public async disableArchive() { + await config.behaviors.mailAddress.disableMailArchive(this.id); + } + + public async findCommon(): Promise { + return this instanceof MailAddressCommon ? this : this.findDetailed(); + } + + public findDetailed(): Promise { + return MailAddress.find(this.id); + } + + public async getCommon(): Promise { + return this instanceof MailAddressCommon ? this : this.getDetailed(); + } + + public getDetailed(): Promise { + return MailAddress.get(this.id); + } + + public async previewMailArchiveOrder(syncExistingMails = false) { + const request = new MailArchiveOrderRequest({ + mailAddress: this, + syncExistingMails, + }); + + return await request.getPreview(); + } + + public async requestRateLimitChange(rateLimit: MailRateLimit | string) { + const rateLimitId = + rateLimit instanceof MailRateLimit ? rateLimit.id : rateLimit; + await config.behaviors.mailAddress.requestRateLimitChange( + this.id, + rateLimitId, + ); + } + + public async updateAddress(address: string) { + return await config.behaviors.mailAddress.updateAddress(this.id, address); + } + + public async updateAutoResponder(data: AutoresponderUpdateRequestData) { + await config.behaviors.mailAddress.updateAutoResponder(this.id, data); + } + + public async updateForwardAddresses(addresses: string[]) { + const response = await config.behaviors.mailAddress.updateForwardAddresses( + this.id, + addresses, + ); + + return response; + } + + public async updatePassword(password: string) { + await config.behaviors.mailAddress.updatePassword(this.id, password); + } + + public async updateQuota(quotaInGib: number) { + await config.behaviors.mailAddress.updateQuota( + this.id, + Bytes.of(quotaInGib, "GiB").in("bytes"), + ); + } +} + +export class MailAddressCommon extends WithData()( + MailAddress, +) { + public readonly address: string; + public readonly archive: MailAddressArchive; + public readonly autoresponder: Autoresponder; + public override readonly data: MailAddressData; + public readonly domain?: string; + public readonly forwardAddresses: string[]; + public readonly hasStorageUsageWarning: boolean; + public readonly isArchived: boolean; + public readonly isBackupInProgress: boolean; + public readonly isCatchAll: boolean; + public readonly isForward: boolean; + public readonly isStorageUsageCritical: boolean; + public readonly localPart?: string; + public readonly originalAddress?: string; + public readonly project: Project; + public readonly rateLimit?: MailRateLimit; + public readonly receivingDisabled: boolean; + public readonly requestedRateLimit?: MailRateLimit; + public readonly sendingDisabled: boolean; + public readonly spamProtectionActive: boolean; + public readonly storageLimit: Bytes; + public readonly storageUsage: Bytes; + public readonly storageUsagePercent: number; + + public constructor(data: MailAddressData) { + super(data.id); + this.data = data; + this.project = Project.ofId(data.projectId); + this.isForward = !this.data.mailbox; + this.receivingDisabled = data.receivingDisabled; + this.sendingDisabled = data.mailbox?.sendingEnabled === false; + this.storageUsagePercent = this.data.mailbox + ? this.data.mailbox.storageInBytes.current.value / + this.data.mailbox.storageInBytes.limit + : 0; + this.isStorageUsageCritical = + this.storageUsagePercent >= MailAddress.quotaUsageError; + this.hasStorageUsageWarning = + !this.isStorageUsageCritical && + this.storageUsagePercent >= MailAddress.quotaUsageWarning; + this.storageLimit = Bytes.of( + data.mailbox?.storageInBytes.limit ?? 0, + "bytes", + ); + this.storageUsage = Bytes.of( + data.mailbox?.storageInBytes.current.value ?? 0, + "bytes", + ); + this.autoresponder = new Autoresponder(data.autoResponder); + this.address = data.address; + this.isArchived = data.isArchived; + this.isCatchAll = data.isCatchAll; + this.forwardAddresses = data.forwardAddresses; + this.domain = data.address.split("@").at(1); + this.localPart = data.address.split("@").at(0); + this.spamProtectionActive = data.mailbox?.spamProtection.active ?? false; + this.isBackupInProgress = data.isBackupInProgress; + this.archive = new MailAddressArchive(data.archive); + if (data?.mailbox?.mailsystemSettings.rateLimitId) { + this.rateLimit = MailRateLimit.ofId( + data.mailbox.mailsystemSettings.rateLimitId, + ); + } + if (data.rateLimitChangeRequest?.rateLimitId) { + this.requestedRateLimit = MailRateLimit.ofId( + data.rateLimitChangeRequest.rateLimitId, + ); + } + if (data.originalAddress) { + this.originalAddress = data.originalAddress; + } + } + + public async addForwardAddress(address: string) { + return await this.updateForwardAddresses([ + ...this.data.forwardAddresses, + address, + ]); + } + + public async deactivateAutoResponder() { + await this.updateAutoResponder({ + message: this.autoresponder.message ?? "", + active: false, + }); + } + + public async removeForwardAddress(address: string) { + await this.updateForwardAddresses( + this.data.forwardAddresses.filter((a) => a !== address), + ); + } + + public async updateSpamProtection(active: boolean) { + await config.behaviors.mailAddress.updateSpamProtection(this.id, { + relocationMinSpamScore: + this.data.mailbox?.spamProtection.relocationMinSpamScore ?? 1, + autoDeleteSpam: this.data.mailbox?.spamProtection.autoDeleteSpam ?? false, + folder: this.data.mailbox?.spamProtection.folder ?? "spam", + active, + }); + } +} + +export class MailAddressDetailed extends MailAddressCommon { + public constructor(data: MailAddressData) { + super(data); + } +} + +export class MailAddressListItem extends MailAddressCommon { + public constructor(data: MailAddressListItemData) { + super(data); + } +} + +export class MailAddressListQuery extends ListQueryModel { + public async execute() { + const projectId = extractId(this.query.project); + + const { totalCount, items } = projectId + ? await config.behaviors.mailAddress.list(projectId, { + limit: config.defaultPaginationLimit, + ...omit(this.query, ["project"]), + }) + : await config.behaviors.mailAddress.listForUser({ + limit: config.defaultPaginationLimit, + ...this.query, + }); + + return new MailAddressList( + this.query, + items.map((m) => new MailAddressListItem(m)), + totalCount, + ); + } + + public async getTotalCount() { + const { items } = await this.refine({ limit: 1 }).execute(); + return items.length; + } + + public refine(query: MailAddressListQueryData = {}) { + return new MailAddressListQuery({ + ...this.query, + ...query, + }); + } +} + +export class MailAddressList extends WithListData()( + MailAddressListQuery, +) { + public override readonly items: readonly MailAddressListItem[]; + public override readonly totalCount: number; + public constructor( + query: MailAddressListQueryData, + mailAddresses: MailAddressListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(mailAddresses); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/mail/MailAddress/behaviors/api.ts b/packages/models/src/mail/MailAddress/behaviors/api.ts new file mode 100644 index 00000000..1edeaf43 --- /dev/null +++ b/packages/models/src/mail/MailAddress/behaviors/api.ts @@ -0,0 +1,192 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { MailAddressBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount } from "../../../base/index.js"; + +export const apiMailAddressBehaviors = ( + client: MittwaldAPIV2Client, +): MailAddressBehaviors => ({ + updateForwardAddresses: async (mailAddressId, forwardAddresses) => { + const response = await client.mail.updateMailAddressForwardAddresses({ + data: { forwardAddresses }, + mailAddressId, + }); + + validateResponse(response, 204, { + validationError: { + typeMappings: { + "*": (e) => + e.message?.includes("must not forward to itself") + ? "forwardToItself" + : undefined, + }, + pathMappings: { + "*address*": "forwardAddress", + }, + }, + }); + }, + createForward: async (projectId, data) => { + const response = await client.mail.createMailAddress({ + projectId, + data, + }); + + validateResponse(response, 201, { + validationError: { + typeMappings: { + "*": (e) => + e.message?.includes("must not forward to itself") + ? "forwardToItself" + : undefined, + }, + pathMappings: { + "*forward_address*": "forwardAddress", + }, + }, + }); + return response.data; + }, + detectPhishingMail: async (file: File) => { + const formData = new FormData(); + formData.append("emailEml", file); + + const response = await client.misc.verificationDetectPhishingEmail({ + data: formData as unknown as Record, + }); + + validateResponse(response, 200, { + validationError: { + pathMappings: { + emailEml: "files", + }, + }, + }); + return response.data.result; + }, + list: async (projectId, query) => { + const response = await client.mail.listMailAddresses({ + queryParameters: query, + projectId, + }); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + listForUser: async (query) => { + const response = await client.mail.listMailAddressesForUser({ + queryParameters: query, + }); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + listBackups: async (mailAddressId) => { + const response = await client.mail.listBackupsForMailAddress({ + mailAddressId, + }); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + requestRateLimitChange: async ( + mailAddressId: string, + rateLimitId: string, + ) => { + const response = await client.mail.requestMailAddressRateLimitChange({ + data: { rateLimitId }, + mailAddressId, + }); + validateResponse(response, 204); + }, + updateSpamProtection: async (mailAddressId, data) => { + const response = await client.mail.updateMailAddressSpamProtection({ + data: { + spamProtection: data, + }, + mailAddressId, + }); + validateResponse(response, 204); + }, + updateCatchAll: async (mailAddressId, enabled) => { + const response = await client.mail.updateMailAddressCatchAll({ + data: { + active: enabled, + }, + mailAddressId, + }); + validateResponse(response, 204); + }, + updateAutoResponder: async (mailAddressId, data) => { + const response = await client.mail.updateMailAddressAutoresponder({ + data: { autoResponder: data }, + mailAddressId, + }); + validateResponse(response, 204); + }, + updatePassword: async (mailAddressId, password) => { + const response = await client.mail.updateMailAddressPassword({ + data: { + password, + }, + mailAddressId, + }); + validateResponse(response, 204); + }, + updateAddress: async (mailAddressId, address) => { + const response = await client.mail.updateMailAddressAddress({ + data: { + address, + }, + mailAddressId, + }); + + validateResponse(response, 204); + }, + find: async (mailAddressId) => { + const response = await client.mail.getMailAddress({ mailAddressId }); + if (response.status === 200) { + return response.data; + } + validateResponse(response, [403, 404]); + }, + updateQuota: async (mailAddressId, bytes) => { + const response = await client.mail.updateMailAddressQuota({ + data: { quotaInBytes: bytes }, + mailAddressId, + }); + validateResponse(response, 204); + }, + createMailAddress: async (projectId, data) => { + const response = await client.mail.createMailAddress({ + projectId, + data, + }); + + validateResponse(response, 201); + return response.data; + }, + restoreBackup: async (mailAddressId, backupId) => { + const response = await client.mail.recoverMailAddressEmails({ + mailAddressId, + backupId, + }); + validateResponse(response, 204); + }, + disableMailArchive: async (mailAddressId) => { + const response = await client.mail.disableMailArchive({ mailAddressId }); + validateResponse(response, 204); + }, + delete: async (mailAddressId) => { + const response = await client.mail.deleteMailAddress({ mailAddressId }); + validateResponse(response, 204); + }, +}); diff --git a/packages/models/src/mail/MailAddress/behaviors/index.ts b/packages/models/src/mail/MailAddress/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/mail/MailAddress/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/mail/MailAddress/behaviors/types.ts b/packages/models/src/mail/MailAddress/behaviors/types.ts new file mode 100644 index 00000000..10988608 --- /dev/null +++ b/packages/models/src/mail/MailAddress/behaviors/types.ts @@ -0,0 +1,62 @@ +import type { MailAddressBackupData } from "../../MailAddressBackup/index.js"; +import type { QueryResponseData } from "../../../base/index.js"; +import type { + AutoresponderUpdateRequestData, + SpamProtectionRequestData, + MailAddressListQueryData, + MailAddressListItemData, + MailAddressRequestData, + ForwardRequestData, + MailAddressData, + EmailOrigin, +} from "../types.js"; + +export interface MailAddressBehaviors { + list: ( + projectId: string, + query?: MailAddressListQueryData, + ) => Promise>; + updateAutoResponder: ( + mailAddressId: string, + data: AutoresponderUpdateRequestData, + ) => Promise; + + listForUser: ( + query?: MailAddressListQueryData, + ) => Promise>; + + createMailAddress: ( + projectId: string, + data: MailAddressRequestData, + ) => Promise<{ id: string }>; + + updateSpamProtection: ( + mailAddressId: string, + data: SpamProtectionRequestData, + ) => Promise; + updateForwardAddresses: ( + mailAddressId: string, + forwardAddresses: string[], + ) => Promise; + + createForward: ( + projectId: string, + data: ForwardRequestData, + ) => Promise<{ id: string }>; + listBackups: ( + mailAddressId: string, + ) => Promise>; + requestRateLimitChange: ( + mailAddressId: string, + rateLimitId: string, + ) => Promise; + updatePassword: (mailAddressId: string, password: string) => Promise; + updateCatchAll: (mailAddressId: string, active: boolean) => Promise; + restoreBackup: (mailAddressId: string, backupId: string) => Promise; + updateAddress: (mailAddressId: string, address: string) => Promise; + find: (mailAddressId: string) => Promise; + updateQuota: (mailAddressId: string, bytes: number) => Promise; + disableMailArchive: (mailArchiveId: string) => Promise; + detectPhishingMail: (input: File) => Promise; + delete: (mailAddressId: string) => Promise; +} diff --git a/packages/models/src/mail/MailAddress/index.ts b/packages/models/src/mail/MailAddress/index.ts new file mode 100644 index 00000000..1886a063 --- /dev/null +++ b/packages/models/src/mail/MailAddress/index.ts @@ -0,0 +1,2 @@ +export * from "./MailAddress.js"; +export * from "./types.js"; diff --git a/packages/models/src/mail/MailAddress/types.ts b/packages/models/src/mail/MailAddress/types.ts new file mode 100644 index 00000000..c9990798 --- /dev/null +++ b/packages/models/src/mail/MailAddress/types.ts @@ -0,0 +1,41 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import type { MailArchiveOrderPreview } from "../../order/Order/Preview/MailArchiveOrderPreview.js"; +import type { MailAddressListItem } from "./MailAddress.js"; +import type { Project } from "../../project/index.js"; + +export type MailAddressListQueryData = + MittwaldAPIV2.Paths.V2ProjectsProjectIdMailAddresses.Get.Parameters.Query; + +export type MailAddressListQueryModelData = Omit< + MailAddressListQueryData, + "projectId" +> & { + project?: Project | string; +}; + +export type MailAddressData = + MittwaldAPIV2.Operations.MailGetMailAddress.ResponseData; + +export type MailAddressListItemData = + MittwaldAPIV2.Operations.MailListMailAddresses.ResponseData[number]; + +export type MailAddressRequestData = + MittwaldAPIV2.Components.Schemas.MailCreateMailAddress; + +export type ForwardRequestData = + MittwaldAPIV2.Components.Schemas.MailCreateForwardAddress; + +export type AutoresponderUpdateRequestData = + MittwaldAPIV2.Paths.V2MailAddressesMailAddressIdAutoresponder.Patch.Parameters.RequestBody["autoResponder"]; + +export type SpamProtectionRequestData = + MittwaldAPIV2.Operations.MailUpdateMailAddressSpamProtection.RequestData["spamProtection"]; + +export type EmailOrigin = + MittwaldAPIV2.Components.Schemas.VerificationEmailOrigin; + +export interface MailAddressWithArchiveOrderPreview { + mailAddress: MailAddressListItem; + preview: MailArchiveOrderPreview; +} diff --git a/packages/models/src/mail/MailAddressArchive/MailAddressArchive.test.ts b/packages/models/src/mail/MailAddressArchive/MailAddressArchive.test.ts new file mode 100644 index 00000000..70a0afd9 --- /dev/null +++ b/packages/models/src/mail/MailAddressArchive/MailAddressArchive.test.ts @@ -0,0 +1,23 @@ +import { afterEach, expect, test } from "vitest"; + +import { + buildMailAddressArchiveData, + resetBehaviors, +} from "../../testing/index.js"; +import { MailAddressArchive } from "./MailAddressArchive.js"; + +afterEach(resetBehaviors); + +test("derives byte values and usage percentage", () => { + const data = buildMailAddressArchiveData({ + usedBytes: 268435456, + quota: 1073741824, + }); + const archive = new MailAddressArchive(data); + + expect(archive.quota.value).toBe(1073741824); + expect(archive.quota.gib).toBe(1); + expect(archive.usedBytes.value).toBe(268435456); + expect(archive.usedBytes.gib).toBe(0.25); + expect(archive.usagePercentage).toBe(0.25); +}); diff --git a/packages/models/src/mail/MailAddressArchive/MailAddressArchive.ts b/packages/models/src/mail/MailAddressArchive/MailAddressArchive.ts new file mode 100644 index 00000000..6311eac4 --- /dev/null +++ b/packages/models/src/mail/MailAddressArchive/MailAddressArchive.ts @@ -0,0 +1,19 @@ +import type { MailAddressArchiveData } from "./types.js"; + +import { DataModel } from "../../base/index.js"; +import { Bytes } from "../../common/index.js"; + +export class MailAddressArchive extends DataModel { + public readonly active: boolean; + public readonly quota: Bytes; + public readonly usagePercentage: number; + public readonly usedBytes: Bytes; + + public constructor(data: MailAddressArchiveData) { + super(data); + this.active = data.active; + this.quota = Bytes.of(data.quota, "bytes"); + this.usedBytes = Bytes.of(data.usedBytes, "bytes"); + this.usagePercentage = this.data.usedBytes / this.data.quota; + } +} diff --git a/packages/models/src/mail/MailAddressArchive/index.ts b/packages/models/src/mail/MailAddressArchive/index.ts new file mode 100644 index 00000000..4aa6c072 --- /dev/null +++ b/packages/models/src/mail/MailAddressArchive/index.ts @@ -0,0 +1,2 @@ +export * from "./MailAddressArchive.js"; +export * from "./types.js"; diff --git a/packages/models/src/mail/MailAddressArchive/types.ts b/packages/models/src/mail/MailAddressArchive/types.ts new file mode 100644 index 00000000..a8af6316 --- /dev/null +++ b/packages/models/src/mail/MailAddressArchive/types.ts @@ -0,0 +1,4 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type MailAddressArchiveData = + MittwaldAPIV2.Components.Schemas.MailMailAddress["archive"]; diff --git a/packages/models/src/mail/MailAddressBackup/MailAddressBackup.test.ts b/packages/models/src/mail/MailAddressBackup/MailAddressBackup.test.ts new file mode 100644 index 00000000..b574de19 --- /dev/null +++ b/packages/models/src/mail/MailAddressBackup/MailAddressBackup.test.ts @@ -0,0 +1,79 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { buildMailAddressBackupData } from "../../testing/builders/buildMailAddressBackupData.js"; +import { MailAddress } from "../MailAddress/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { + MailAddressBackupListQuery, + MailAddressBackupList, + MailAddressBackup, +} from "./MailAddressBackup.js"; + +afterEach(resetBehaviors); + +describe("MailAddressBackup", () => { + test("parses a valid backup date", () => { + const backup = new MailAddressBackup( + buildMailAddressBackupData({ name: "20240102" }), + MailAddress.ofId("m-1"), + ); + + expect(backup.name).toBe("20240102"); + expect(backup.date?.isValid).toBe(true); + expect(backup.date?.year).toBe(2024); + }); + + test("leaves date undefined for an invalid backup name", () => { + const backup = new MailAddressBackup( + buildMailAddressBackupData({ name: "not-a-date" }), + MailAddress.ofId("m-1"), + ); + + expect(backup.date).toBeUndefined(); + }); + + test("retains its mail address", () => { + const mailAddress = MailAddress.ofId("m-1"); + const backup = new MailAddressBackup( + buildMailAddressBackupData(), + mailAddress, + ); + + expect(backup.mailAddress).toBe(mailAddress); + }); + + test("restore delegates with the mail address id and backup name", async () => { + const restoreBackup = vi.fn(); + installBehaviors({ mailAddress: { restoreBackup } }); + const backup = new MailAddressBackup( + buildMailAddressBackupData({ name: "20240102" }), + MailAddress.ofId("m-1"), + ); + + await backup.restore(); + + expect(restoreBackup).toHaveBeenCalledWith("m-1", "20240102"); + }); + + test("query delegates and maps backup list data", async () => { + const listBackups = vi.fn().mockResolvedValue({ + items: [buildMailAddressBackupData({ name: "20240102" })], + totalCount: 2, + }); + installBehaviors({ mailAddress: { listBackups } }); + const mailAddress = MailAddress.ofId("m-1"); + + const listQuery = MailAddressBackup.query({ mailAddress: mailAddress }); + expect(listQuery).toBeInstanceOf(MailAddressBackupListQuery); + const result = await listQuery.execute(); + + expect(listBackups).toHaveBeenCalledWith("m-1"); + expect(result).toBeInstanceOf(MailAddressBackupList); + expect(result.items[0]).toBeInstanceOf(MailAddressBackup); + expect(result.items[0]?.name).toBe("20240102"); + expect(result.totalCount).toBe(2); + }); +}); diff --git a/packages/models/src/mail/MailAddressBackup/MailAddressBackup.ts b/packages/models/src/mail/MailAddressBackup/MailAddressBackup.ts new file mode 100644 index 00000000..d17f2a60 --- /dev/null +++ b/packages/models/src/mail/MailAddressBackup/MailAddressBackup.ts @@ -0,0 +1,78 @@ +import { DateTime } from "luxon"; + +import type { + MailAddressBackupListQueryModelData, + MailAddressBackupData, +} from "./types.js"; + +import { + ListQueryModel, + WithListData, + DataModel, + extractId, +} from "../../base/index.js"; +import { MailAddress } from "../MailAddress/index.js"; +import { config } from "../../config/index.js"; + +export class MailAddressBackup extends DataModel { + public readonly date?: DateTime; + public readonly mailAddress: MailAddress; + public readonly name: string; + + public constructor(data: MailAddressBackupData, mailAddress: MailAddress) { + super(data); + this.name = data.name; + this.mailAddress = mailAddress; + const parsedDate = DateTime.fromFormat(data.name, "yyyyMMdd"); + if (parsedDate.isValid) { + this.date = parsedDate; + } + } + + public static query(query: MailAddressBackupListQueryModelData) { + return new MailAddressBackupListQuery(query); + } + + public async restore(): Promise { + await config.behaviors.mailAddress.restoreBackup( + this.mailAddress.id, + this.name, + ); + } +} + +export class MailAddressBackupListQuery extends ListQueryModel { + public constructor(query: MailAddressBackupListQueryModelData) { + super(query, { dependencies: [extractId(query.mailAddress)] }); + } + + public async execute() { + const mailAddress = + typeof this.query.mailAddress === "string" + ? MailAddress.ofId(this.query.mailAddress) + : this.query.mailAddress; + const { totalCount, items } = + await config.behaviors.mailAddress.listBackups(mailAddress.id); + return new MailAddressBackupList( + this.query, + items.map((i) => new MailAddressBackup(i, mailAddress)), + totalCount, + ); + } +} + +export class MailAddressBackupList extends WithListData()( + MailAddressBackupListQuery, +) { + public override readonly items: readonly MailAddressBackup[]; + public override readonly totalCount: number; + public constructor( + query: MailAddressBackupListQueryModelData, + backups: MailAddressBackup[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(backups); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/mail/MailAddressBackup/index.ts b/packages/models/src/mail/MailAddressBackup/index.ts new file mode 100644 index 00000000..675dbeec --- /dev/null +++ b/packages/models/src/mail/MailAddressBackup/index.ts @@ -0,0 +1,2 @@ +export * from "./MailAddressBackup.js"; +export * from "./types.js"; diff --git a/packages/models/src/mail/MailAddressBackup/types.ts b/packages/models/src/mail/MailAddressBackup/types.ts new file mode 100644 index 00000000..03e4d9ea --- /dev/null +++ b/packages/models/src/mail/MailAddressBackup/types.ts @@ -0,0 +1,13 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import type { MailAddress } from "../MailAddress/index.js"; + +export type MailAddressBackupData = + MittwaldAPIV2.Operations.MailListBackupsForMailAddress.ResponseData[number]; + +export type MailAddressBackupListQueryModelData = { + mailAddress: MailAddress | string; +}; + +export type ListMailAddressBackupQueryData = + MittwaldAPIV2.Paths.V2MailAddressesMailAddressIdBackups.Get.Parameters.Query; diff --git a/packages/models/src/mail/MailRateLimit/MailRateLimit.test.ts b/packages/models/src/mail/MailRateLimit/MailRateLimit.test.ts new file mode 100644 index 00000000..ced1dac0 --- /dev/null +++ b/packages/models/src/mail/MailRateLimit/MailRateLimit.test.ts @@ -0,0 +1,141 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { buildMailRateLimitData } from "../../testing/builders/buildMailRateLimitData.js"; +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { + MailRateLimitListQuery, + MailRateLimitDetailed, + MailRateLimitListItem, + MailRateLimitCommon, + MailRateLimitList, + MailRateLimit, +} from "./MailRateLimit.js"; + +afterEach(resetBehaviors); + +describe("MailRateLimit", () => { + test("find delegates and returns detailed data", async () => { + const find = vi + .fn() + .mockResolvedValue( + buildMailRateLimitData({ rateLimit: 2000, id: "rl-1" }), + ); + installBehaviors({ mailRateLimit: { find } }); + + const result = await MailRateLimit.find("rl-1"); + + expect(find).toHaveBeenCalledWith("rl-1"); + expect(result).toBeInstanceOf(MailRateLimitDetailed); + expect(result?.id).toBe("rl-1"); + expect(result?.rateLimit).toBe(2000); + }); + + test("find returns undefined when no rate limit exists", async () => { + installBehaviors({ + mailRateLimit: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + expect(await MailRateLimit.find("missing")).toBeUndefined(); + }); + + test("references find their detailed data by id", async () => { + const find = vi + .fn() + .mockResolvedValue(buildMailRateLimitData({ id: "rl-1" })); + installBehaviors({ mailRateLimit: { find } }); + const reference = MailRateLimit.ofId("rl-1"); + + expect(reference).toBeInstanceOf(MailRateLimit); + await reference.findDetailed(); + expect(find).toHaveBeenCalledWith("rl-1"); + }); + + test("exposes the warning threshold", () => { + expect(MailRateLimit.warningThreshold).toBe(5000); + }); + + test("query delegates and maps list data", async () => { + const query = vi.fn().mockResolvedValue({ + items: [buildMailRateLimitData({ rateLimit: 3000 })], + totalCount: 5, + }); + installBehaviors({ mailRateLimit: { query } }); + + const listQuery = MailRateLimit.query(); + expect(listQuery).toBeInstanceOf(MailRateLimitListQuery); + const result = await listQuery.execute(); + + expect(query).toHaveBeenCalledWith(); + expect(result).toBeInstanceOf(MailRateLimitList); + expect(result.items[0]).toBeInstanceOf(MailRateLimitListItem); + expect(result.items[0]?.rateLimit).toBe(3000); + expect(result.totalCount).toBe(5); + }); + + test("list items retain ghostmaker class identity", () => { + const item = new MailRateLimitListItem(buildMailRateLimitData()); + + expect(item).toBeInstanceOf(MailRateLimitListItem); + expect(item).toBeInstanceOf(MailRateLimitCommon); + expect(item).toBeInstanceOf(MailRateLimit); + }); + + test("findCommon and getCommon delegate for a plain reference", async () => { + const find = vi + .fn() + .mockResolvedValue(buildMailRateLimitData({ id: "rl-1" })); + installBehaviors({ mailRateLimit: { find } }); + const reference = MailRateLimit.ofId("rl-1"); + + await expect(reference.findCommon()).resolves.toBeInstanceOf( + MailRateLimitCommon, + ); + await expect(reference.getCommon()).resolves.toBeInstanceOf( + MailRateLimitCommon, + ); + expect(find).toHaveBeenNthCalledWith(1, "rl-1"); + expect(find).toHaveBeenNthCalledWith(2, "rl-1"); + }); + + test("findCommon returns undefined and getCommon throws when the rate limit is missing", async () => { + installBehaviors({ + mailRateLimit: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + MailRateLimit.ofId("missing").findCommon(), + ).resolves.toBeUndefined(); + await expect(MailRateLimit.ofId("missing").getCommon()).rejects.toThrow( + ObjectNotFoundError, + ); + }); + + test("findCommon and getCommon reuse an already materialized model without refetching", async () => { + const find = vi.fn().mockResolvedValue(buildMailRateLimitData()); + installBehaviors({ mailRateLimit: { find } }); + const detailed = await MailRateLimit.get("ratelimit-id"); + find.mockClear(); + + await expect(detailed.findCommon()).resolves.toBe(detailed); + await expect(detailed.getCommon()).resolves.toBe(detailed); + expect(find).not.toHaveBeenCalled(); + }); + + test("list items are already common and return themselves from findCommon and getCommon", async () => { + const item = new MailRateLimitListItem(buildMailRateLimitData()); + + await expect(item.findCommon()).resolves.toBe(item); + await expect(item.getCommon()).resolves.toBe(item); + }); +}); diff --git a/packages/models/src/mail/MailRateLimit/MailRateLimit.ts b/packages/models/src/mail/MailRateLimit/MailRateLimit.ts new file mode 100644 index 00000000..1978327c --- /dev/null +++ b/packages/models/src/mail/MailRateLimit/MailRateLimit.ts @@ -0,0 +1,111 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; + +import type { MailRateLimitQueryData, MailRateLimitData } from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "MailRateLimit", +}) +export class MailRateLimit extends ReferenceModel { + public static warningThreshold = 5000; + + public constructor(id: string) { + super(id); + } + + public static async find(id: string) { + const data = await config.behaviors.mailRateLimit.find(id); + if (data !== undefined) { + return new MailRateLimitDetailed(data); + } + } + + public static async get(id: string) { + const rateLimit = await MailRateLimit.find(id); + assertObjectFound(rateLimit, MailRateLimit, id); + return rateLimit; + } + + public static ofId(id: string) { + return new MailRateLimit(id); + } + + public static query() { + return new MailRateLimitListQuery({}); + } + + public async findCommon(): Promise { + return this instanceof MailRateLimitCommon ? this : this.findDetailed(); + } + + public async findDetailed(): Promise { + return MailRateLimit.find(this.id); + } + + public async getCommon(): Promise { + return this instanceof MailRateLimitCommon ? this : this.getDetailed(); + } + + public async getDetailed(): Promise { + return MailRateLimit.get(this.id); + } +} + +export class MailRateLimitCommon extends WithData()( + MailRateLimit, +) { + public override readonly data: MailRateLimitData; + public readonly rateLimit: number; + public constructor(data: MailRateLimitData) { + super(data.id); + this.data = data; + this.rateLimit = data.rateLimit; + } +} + +export class MailRateLimitDetailed extends MailRateLimitCommon { + public constructor(data: MailRateLimitData) { + super(data); + } +} + +export class MailRateLimitListItem extends MailRateLimitCommon { + public constructor(data: MailRateLimitData) { + super(data); + } +} + +export class MailRateLimitListQuery extends ListQueryModel { + public async execute() { + const { totalCount, items } = await config.behaviors.mailRateLimit.query(); + return new MailRateLimitList( + this.query, + items.map((i) => new MailRateLimitListItem(i)), + totalCount, + ); + } +} + +export class MailRateLimitList extends WithListData()( + MailRateLimitListQuery, +) { + public override readonly items: readonly MailRateLimitListItem[]; + public override readonly totalCount: number; + public constructor( + query: MailRateLimitQueryData, + rateLimits: MailRateLimitListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(rateLimits); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/mail/MailRateLimit/behaviors/api.ts b/packages/models/src/mail/MailRateLimit/behaviors/api.ts new file mode 100644 index 00000000..63680ece --- /dev/null +++ b/packages/models/src/mail/MailRateLimit/behaviors/api.ts @@ -0,0 +1,27 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { MailRateLimitBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount } from "../../../base/index.js"; + +export const apiMailRateLimitBehaviors = ( + client: MittwaldAPIV2Client, +): MailRateLimitBehaviors => ({ + query: async () => { + const response = await client.mail.listMailRateLimits({}); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + find: async (rateLimitId) => { + const response = await client.mail.getMailRateLimit({ + mailRateLimitId: rateLimitId, + }); + if (response.status === 200) { + return response.data; + } + }, +}); diff --git a/packages/models/src/mail/MailRateLimit/behaviors/index.ts b/packages/models/src/mail/MailRateLimit/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/mail/MailRateLimit/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/mail/MailRateLimit/behaviors/types.ts b/packages/models/src/mail/MailRateLimit/behaviors/types.ts new file mode 100644 index 00000000..e9d56658 --- /dev/null +++ b/packages/models/src/mail/MailRateLimit/behaviors/types.ts @@ -0,0 +1,13 @@ +import type { QueryResponseData } from "../../../base/index.js"; +import type { + MailRateLimitListItemData, + MailRateLimitQueryData, + MailRateLimitData, +} from "../types.js"; + +export interface MailRateLimitBehaviors { + query: ( + query?: MailRateLimitQueryData, + ) => Promise>; + find: (rateLimitId: string) => Promise; +} diff --git a/packages/models/src/mail/MailRateLimit/index.ts b/packages/models/src/mail/MailRateLimit/index.ts new file mode 100644 index 00000000..3fa0a471 --- /dev/null +++ b/packages/models/src/mail/MailRateLimit/index.ts @@ -0,0 +1,2 @@ +export * from "./MailRateLimit.js"; +export * from "./types.js"; diff --git a/packages/models/src/mail/MailRateLimit/types.ts b/packages/models/src/mail/MailRateLimit/types.ts new file mode 100644 index 00000000..7e010344 --- /dev/null +++ b/packages/models/src/mail/MailRateLimit/types.ts @@ -0,0 +1,10 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type MailRateLimitData = + MittwaldAPIV2.Components.Schemas.MailsystemRateLimit; + +export type MailRateLimitQueryData = + MittwaldAPIV2.Paths.V2MailRateLimits.Get.Parameters.Query; + +export type MailRateLimitListItemData = + MittwaldAPIV2.Operations.MailListMailRateLimits.ResponseData[number]; diff --git a/packages/models/src/mail/MailSettings/MailSettings.test.ts b/packages/models/src/mail/MailSettings/MailSettings.test.ts new file mode 100644 index 00000000..fbce6415 --- /dev/null +++ b/packages/models/src/mail/MailSettings/MailSettings.test.ts @@ -0,0 +1,145 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { buildMailSettingsData } from "../../testing/builders/buildMailSettingsData.js"; +import { MailSettingsDetailed, MailSettings } from "./MailSettings.js"; +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; + +afterEach(resetBehaviors); + +describe("MailSettings", () => { + test("find delegates and returns detailed data", async () => { + const find = vi + .fn() + .mockResolvedValue(buildMailSettingsData({ projectId: "p-1" })); + installBehaviors({ mailSettings: { find } }); + + const result = await MailSettings.find("p-1"); + + expect(find).toHaveBeenCalledWith("p-1"); + expect(result).toBeInstanceOf(MailSettingsDetailed); + expect(result?.id).toBe("p-1"); + }); + + test("find returns undefined when no settings exist", async () => { + installBehaviors({ + mailSettings: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + expect(await MailSettings.find("missing")).toBeUndefined(); + }); + + test("maps blacklist and whitelist to public getters", () => { + const settings = new MailSettingsDetailed( + buildMailSettingsData({ blacklist: ["blocked"], whitelist: ["allowed"] }), + ); + + expect(settings.blocklist).toEqual(["blocked"]); + expect(settings.allowlist).toEqual(["allowed"]); + }); + + test("adds and removes blocklist entries", async () => { + const updateBlocklist = vi.fn(); + installBehaviors({ mailSettings: { updateBlocklist } }); + const settings = new MailSettingsDetailed( + buildMailSettingsData({ blacklist: ["existing"], projectId: "p-1" }), + ); + + await settings.addBlocklistEntry("new"); + await settings.removeBlocklistEntry("existing"); + + expect(updateBlocklist).toHaveBeenNthCalledWith(1, "p-1", [ + "existing", + "new", + ]); + expect(updateBlocklist).toHaveBeenNthCalledWith(2, "p-1", []); + }); + + test("adds and removes allowlist entries", async () => { + const updateAllowlist = vi.fn(); + installBehaviors({ mailSettings: { updateAllowlist } }); + const settings = new MailSettingsDetailed( + buildMailSettingsData({ whitelist: ["existing"], projectId: "p-1" }), + ); + + await settings.addAllowlistEntry("new"); + await settings.removeAllowlistEntry("existing"); + + expect(updateAllowlist).toHaveBeenNthCalledWith(1, "p-1", [ + "existing", + "new", + ]); + expect(updateAllowlist).toHaveBeenNthCalledWith(2, "p-1", []); + }); + + test("reference update methods delegate with project id", async () => { + const updateBlocklist = vi.fn(); + const updateAllowlist = vi.fn(); + installBehaviors({ mailSettings: { updateAllowlist, updateBlocklist } }); + const settings = MailSettings.ofId("p-1"); + + await settings.updateBlocklist(["blocked"]); + await settings.updateAllowlist(["allowed"]); + + expect(updateBlocklist).toHaveBeenCalledWith("p-1", ["blocked"]); + expect(updateAllowlist).toHaveBeenCalledWith("p-1", ["allowed"]); + }); + + test("detailed settings retain ghostmaker class identity", () => { + const settings = new MailSettingsDetailed(buildMailSettingsData()); + + expect(settings).toBeInstanceOf(MailSettingsDetailed); + expect(settings).toBeInstanceOf(MailSettings); + }); + + test("findCommon and getCommon delegate for a plain reference", async () => { + const find = vi + .fn() + .mockResolvedValue(buildMailSettingsData({ projectId: "p-1" })); + installBehaviors({ mailSettings: { find } }); + const reference = MailSettings.ofId("p-1"); + + await expect(reference.findCommon()).resolves.toBeInstanceOf( + MailSettingsDetailed, + ); + await expect(reference.getCommon()).resolves.toBeInstanceOf( + MailSettingsDetailed, + ); + expect(find).toHaveBeenNthCalledWith(1, "p-1"); + expect(find).toHaveBeenNthCalledWith(2, "p-1"); + }); + + test("findCommon returns undefined and getCommon throws when settings are missing", async () => { + installBehaviors({ + mailSettings: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + MailSettings.ofId("missing").findCommon(), + ).resolves.toBeUndefined(); + await expect(MailSettings.ofId("missing").getCommon()).rejects.toThrow( + ObjectNotFoundError, + ); + }); + + test("findCommon and getCommon reuse an already materialized model without refetching", async () => { + const find = vi.fn().mockResolvedValue(buildMailSettingsData()); + installBehaviors({ mailSettings: { find } }); + const detailed = await MailSettings.get("project-id"); + find.mockClear(); + + await expect(detailed.findCommon()).resolves.toBe(detailed); + await expect(detailed.getCommon()).resolves.toBe(detailed); + expect(find).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/models/src/mail/MailSettings/MailSettings.ts b/packages/models/src/mail/MailSettings/MailSettings.ts new file mode 100644 index 00000000..74f754ce --- /dev/null +++ b/packages/models/src/mail/MailSettings/MailSettings.ts @@ -0,0 +1,89 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; + +import type { MailSettingsData } from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { ReferenceModel, WithData } from "../../base/index.js"; +import { config } from "../../config/index.js"; + +@GhostMakerModel({ + name: "MailSettings", +}) +export class MailSettings extends ReferenceModel { + public static async find(projectId: string) { + const data = await config.behaviors.mailSettings.find(projectId); + if (data !== undefined) { + return new MailSettingsDetailed(data); + } + } + + public static async get(projectId: string) { + const settings = await MailSettings.find(projectId); + assertObjectFound(settings, MailSettings, projectId); + return settings; + } + + public static ofId(projectId: string) { + return new MailSettings(projectId); + } + + public async findCommon(): Promise { + return this instanceof MailSettingsDetailed ? this : this.findDetailed(); + } + + public async findDetailed(): Promise { + return MailSettings.find(this.id); + } + + public async getCommon(): Promise { + return this instanceof MailSettingsDetailed ? this : this.getDetailed(); + } + + public async getDetailed(): Promise { + return MailSettings.get(this.id); + } + + public async updateAllowlist(addresses: string[]) { + return await config.behaviors.mailSettings.updateAllowlist( + this.id, + addresses, + ); + } + + public async updateBlocklist(addresses: string[]) { + return await config.behaviors.mailSettings.updateBlocklist( + this.id, + addresses, + ); + } +} + +export class MailSettingsDetailed extends WithData()( + MailSettings, +) { + public readonly allowlist: string[]; + public readonly blocklist: string[]; + public override readonly data: MailSettingsData; + public constructor(data: MailSettingsData) { + super(data.projectId); + this.data = data; + this.blocklist = data.blacklist; + this.allowlist = data.whitelist; + } + + public async addAllowlistEntry(address: string) { + return await this.updateAllowlist([...this.allowlist, address]); + } + + public async addBlocklistEntry(address: string) { + return await this.updateBlocklist([...this.blocklist, address]); + } + + public async removeAllowlistEntry(address: string) { + await this.updateAllowlist(this.allowlist.filter((a) => a !== address)); + } + + public async removeBlocklistEntry(address: string) { + await this.updateBlocklist(this.blocklist.filter((a) => a !== address)); + } +} diff --git a/packages/models/src/mail/MailSettings/behaviors/api.ts b/packages/models/src/mail/MailSettings/behaviors/api.ts new file mode 100644 index 00000000..f2686250 --- /dev/null +++ b/packages/models/src/mail/MailSettings/behaviors/api.ts @@ -0,0 +1,47 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { MailSettingsBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; + +export const apiMailSettingsBehaviors = ( + client: MittwaldAPIV2Client, +): MailSettingsBehaviors => ({ + updateAllowlist: async (projectId, allowList) => { + const response = await client.mail.updateProjectMailSetting({ + data: { whitelist: allowList }, + mailSetting: "whitelist", + projectId, + }); + + validateResponse(response, 204, { + validationError: { + pathMappings: { + "*entry*": "address", + }, + }, + }); + }, + updateBlocklist: async (projectId, blocklist) => { + const response = await client.mail.updateProjectMailSetting({ + data: { blacklist: blocklist }, + mailSetting: "blacklist", + projectId, + }); + + validateResponse(response, 204, { + validationError: { + pathMappings: { + "*entry*": "address", + }, + }, + }); + }, + find: async (projectId) => { + const response = await client.mail.listProjectMailSettings({ projectId }); + if (response.status === 200) { + return response.data; + } + validateResponse(response, [404]); + }, +}); diff --git a/packages/models/src/mail/MailSettings/behaviors/index.ts b/packages/models/src/mail/MailSettings/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/mail/MailSettings/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/mail/MailSettings/behaviors/types.ts b/packages/models/src/mail/MailSettings/behaviors/types.ts new file mode 100644 index 00000000..e7b96f08 --- /dev/null +++ b/packages/models/src/mail/MailSettings/behaviors/types.ts @@ -0,0 +1,8 @@ +import type { MailSettingsData } from "../types.js"; + +export interface MailSettingsBehaviors { + updateAllowlist: (projectId: string, allowList: string[]) => Promise; + + updateBlocklist: (projectId: string, blockList: string[]) => Promise; + find: (projectId: string) => Promise; +} diff --git a/packages/models/src/mail/MailSettings/index.ts b/packages/models/src/mail/MailSettings/index.ts new file mode 100644 index 00000000..37159b32 --- /dev/null +++ b/packages/models/src/mail/MailSettings/index.ts @@ -0,0 +1,2 @@ +export * from "./MailSettings.js"; +export * from "./types.js"; diff --git a/packages/models/src/mail/MailSettings/types.ts b/packages/models/src/mail/MailSettings/types.ts new file mode 100644 index 00000000..d38d0969 --- /dev/null +++ b/packages/models/src/mail/MailSettings/types.ts @@ -0,0 +1,4 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type MailSettingsData = + MittwaldAPIV2.Operations.MailListProjectMailSettings.ResponseData; diff --git a/packages/models/src/mail/index.ts b/packages/models/src/mail/index.ts new file mode 100644 index 00000000..e7588f94 --- /dev/null +++ b/packages/models/src/mail/index.ts @@ -0,0 +1,6 @@ +export * from "./Autoresponder/index.js"; +export * from "./DeliveryBox/index.js"; +export * from "./MailAddress/index.js"; +export * from "./MailAddressBackup/index.js"; +export * from "./MailRateLimit/index.js"; +export * from "./MailSettings/index.js"; diff --git a/packages/models/src/marketplace/Contributor/Contributor.test.ts b/packages/models/src/marketplace/Contributor/Contributor.test.ts new file mode 100644 index 00000000..75f92119 --- /dev/null +++ b/packages/models/src/marketplace/Contributor/Contributor.test.ts @@ -0,0 +1,275 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +import type { OwnContributorData, ContributorData } from "./types.js"; + +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { LocalizedText } from "../../common/index.js"; +import { ReferenceModel } from "../../base/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { + OwnContributorDetailed, + ContributorListQuery, + ContributorDetailed, + ContributorListItem, + ContributorList, + Contributor, +} from "./Contributor.js"; + +afterEach(resetBehaviors); + +const mittwaldContributorId = "322ba411-aafc-493a-b8ad-a42a01939f42"; + +function buildContributorData( + overrides?: Partial, +): ContributorData { + return { + supportInformation: { + email: "support@example.com", + inherited: false, + phone: "12345", + }, + descriptions: { de: "Beschreibung" }, + homepage: "https://example.com", + customerId: "customer-id", + logoRefId: "logo-ref-id", + name: "Test Contributor", + email: "s@example.com", + id: "contributor-id", + state: "enabled", + ...overrides, + }; +} + +function buildOwnContributorData( + overrides?: Partial, +): OwnContributorData { + return { + contractOwner: { + contact: { + address: { + street: "Main Street", + city: "Space City", + countryCode: "DE", + houseNumber: "1", + zip: "12345", + }, + salutation: "mr", + }, + inherited: false, + }, + supportInformation: { email: "support@example.com", inherited: false }, + contactPersonUserId: "user-id", + contributorNumber: "C-4711", + verificationRequested: true, + customerId: "customer-id", + name: "Own Contributor", + email: "s@example.com", + id: "contributor-id", + nameInherited: false, + state: "enabled", + verified: false, + ...overrides, + }; +} + +describe("reference and delegation", () => { + test("ofId flags the mittwald contributor", () => { + expect(Contributor.ofId(mittwaldContributorId).isMittwald).toBe(true); + expect(Contributor.ofId("c-1").isMittwald).toBe(false); + }); + + test("find delegates and materializes a detailed contributor", async () => { + const find = vi.fn().mockResolvedValue(buildContributorData({ id: "c-1" })); + installBehaviors({ contributor: { find } }); + + const contributor = await Contributor.find("c-1"); + + expect(find).toHaveBeenCalledWith("c-1", undefined); + expect(contributor).toBeInstanceOf(ContributorDetailed); + expect(contributor?.id).toBe("c-1"); + }); + + test("find materializes an own contributor when verification data is present", async () => { + const find = vi + .fn() + .mockResolvedValue(buildOwnContributorData({ id: "c-2" })); + installBehaviors({ contributor: { find } }); + + const contributor = await Contributor.find("c-2"); + + expect(contributor).toBeInstanceOf(OwnContributorDetailed); + expect((contributor as OwnContributorDetailed).verificationRequested).toBe( + true, + ); + expect((contributor as OwnContributorDetailed).verified).toBe(false); + }); + + test("find returns undefined when the behavior does", async () => { + installBehaviors({ + contributor: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(Contributor.find("missing")).resolves.toBeUndefined(); + }); +}); + +describe("get on a missing contributor", () => { + test("throws ObjectNotFoundError", async () => { + installBehaviors({ + contributor: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(Contributor.get("missing")).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); +}); + +describe("common variant and idempotency", () => { + test("findCommon delegates to the detailed variant from a bare reference", async () => { + const find = vi.fn().mockResolvedValue(buildContributorData({ id: "c-1" })); + installBehaviors({ contributor: { find } }); + + const common = await Contributor.ofId("c-1").findCommon(); + + expect(find).toHaveBeenCalledWith("c-1", undefined); + expect(common).toBeInstanceOf(ContributorDetailed); + expect(common?.id).toBe("c-1"); + }); + + test("findCommon returns undefined when the behavior finds nothing", async () => { + installBehaviors({ + contributor: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + Contributor.ofId("missing").findCommon(), + ).resolves.toBeUndefined(); + }); + + test("getCommon delegates and throws when the contributor is missing", async () => { + installBehaviors({ + contributor: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + Contributor.ofId("missing").getCommon(), + ).rejects.toBeInstanceOf(ObjectNotFoundError); + }); + + test("getCommon on an already-common model returns itself without re-fetching", async () => { + const find = vi.fn(); + installBehaviors({ contributor: { find } }); + const detailed = new ContributorDetailed( + buildContributorData({ id: "c-3" }), + ); + + const common = await detailed.getCommon(); + + expect(common).toBe(detailed); + expect(find).not.toHaveBeenCalled(); + }); + + test("findCommon on an already-common model returns itself without re-fetching", async () => { + const find = vi.fn(); + installBehaviors({ contributor: { find } }); + const item = new ContributorListItem(buildContributorData({ id: "c-4" })); + + const common = await item.findCommon(); + + expect(common).toBe(item); + expect(find).not.toHaveBeenCalled(); + }); +}); + +test("exposes data and derived values", () => { + const contributor = new ContributorDetailed( + buildContributorData({ customerId: "cust-9", logoRefId: "logo-9" }), + ); + + expect(contributor.name).toBe("Test Contributor"); + expect(contributor.customer.id).toBe("cust-9"); + expect(contributor.state).toBe("enabled"); + expect(contributor.description).toBeInstanceOf(LocalizedText); + expect(contributor.description.getText()).toBe("Beschreibung"); + expect(contributor.email).toBe("support@example.com"); + expect(contributor.phone).toBe("12345"); + expect(contributor.homepage).toBe("https://example.com"); + expect(contributor.avatar?.id).toBe("logo-9"); +}); + +test("exposes the contributor number of an own contributor", () => { + const contributor = new OwnContributorDetailed(buildOwnContributorData()); + + expect(contributor.contributorNumber).toBe("C-4711"); + expect(contributor.verified).toBe(false); + expect(contributor.verificationRequested).toBe(true); +}); + +describe("absent optional source data", () => { + test("omits the avatar, homepage and contributor number when the source has none", () => { + const contributor = new ContributorDetailed( + buildContributorData({ + descriptions: undefined, + logoRefId: undefined, + homepage: undefined, + }), + ); + + expect(contributor.avatar).toBeUndefined(); + expect(contributor.homepage).toBeUndefined(); + expect(contributor.contributorNumber).toBeUndefined(); + expect(contributor.description).toBeInstanceOf(LocalizedText); + }); +}); + +describe("list query", () => { + test("delegates to the behavior and materializes list items", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildContributorData({ id: "c-list" })], + totalCount: 4, + }); + installBehaviors({ contributor: { list } }); + + const result = await Contributor.ofId("c-1").query().execute(); + + expect(list).toHaveBeenCalledWith({}); + expect(result).toBeInstanceOf(ContributorList); + expect(result).toBeInstanceOf(ContributorListQuery); + expect(result.items[0]).toBeInstanceOf(ContributorListItem); + expect(result.totalCount).toBe(4); + }); + + test("getTotalCount returns the behavior total", async () => { + installBehaviors({ + contributor: { + list: vi.fn().mockResolvedValue({ totalCount: 9, items: [] }), + }, + }); + + await expect(Contributor.ofId("c-1").query().getTotalCount()).resolves.toBe( + 9, + ); + }); +}); + +test("preserves ghostmaker identity chains", () => { + const item = new ContributorListItem(buildContributorData()); + + expect(item).toBeInstanceOf(ContributorListItem); + expect(item).toBeInstanceOf(Contributor); + expect(item).toBeInstanceOf(ReferenceModel); + expect(item.data).toBeDefined(); +}); diff --git a/packages/models/src/marketplace/Contributor/Contributor.ts b/packages/models/src/marketplace/Contributor/Contributor.ts index 07e507b8..57633cea 100644 --- a/packages/models/src/marketplace/Contributor/Contributor.ts +++ b/packages/models/src/marketplace/Contributor/Contributor.ts @@ -1,89 +1,229 @@ -import { config } from "../../config/config.js"; -import { classes } from "polytype"; -import { DataModel } from "../../base/DataModel.js"; -import assertObjectFound from "../../base/assertObjectFound.js"; -import { ReferenceModel } from "../../base/ReferenceModel.js"; -import { - AsyncResourceVariant, - provideReact, -} from "../../react/provideReact.js"; -import { ListQueryModel } from "../../base/ListQueryModel.js"; -import { ListDataModel } from "../../base/ListDataModel.js"; -import { ContributorIncomingInvoiceListQuery } from "./ContributorIncomingInvoice.js"; +import type { AxiosRequestConfig } from "axios"; + +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; + +import type { ContributorAvatarAccessTokenProvider as ContributorAvatarAccessTokenProviderType } from "./ContributorAvatarAccessTokenProvider.js"; +import type { ContributorIncomingInvoiceListQuery as ContributorIncomingInvoiceListQueryType } from "./ContributorIncomingInvoice.js"; +import type { ContributorExtensionListQuery } from "../ContributorExtension/index.js"; import type { - ContributorData, - ContributorListItemData, + ContributorUpdateRequestData, ContributorListQueryData, + ContributorListItemData, + ContributorImprint, + OwnContributorData, + ContributorState, + ContributorData, } from "./types.js"; +import { ContributorAvatarAccessTokenProvider } from "./ContributorAvatarAccessTokenProvider.js"; +import { ContributorIncomingInvoiceListQuery } from "./ContributorIncomingInvoice.js"; +import { ContributorOutgoingInvoice } from "./ContributorOutgoingInvoice.js"; +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { ContributorExtension } from "../ContributorExtension/index.js"; +import { Customer } from "../../customer/Customer/Customer.js"; +import { File } from "../../file/File/internal.js"; +import { LocalizedText } from "../../common/index.js"; +import { type DomFile } from "../../file/index.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + WithData, +} from "../../base/index.js"; + +const mittwaldContributorId = "322ba411-aafc-493a-b8ad-a42a01939f42"; + +@GhostMakerModel({ + name: "Contributor", +}) export class Contributor extends ReferenceModel { - public readonly incomingInvoices: ContributorIncomingInvoiceListQuery; + public readonly avatarAccessTokenProvider: ContributorAvatarAccessTokenProviderType; + + public readonly incomingInvoices: ContributorIncomingInvoiceListQueryType; + + public readonly isMittwald: boolean; + + public readonly ownExtensions: ContributorExtensionListQuery; public constructor(id: string) { super(id); + this.ownExtensions = ContributorExtension.query(this); + this.avatarAccessTokenProvider = new ContributorAvatarAccessTokenProvider( + this, + ); this.incomingInvoices = new ContributorIncomingInvoiceListQuery(this); + this.isMittwald = id === mittwaldContributorId; + } + public static async find(id: string, options?: AxiosRequestConfig) { + const data = await config.behaviors.contributor.find(id, options); + + if (data) { + if ("verificationRequested" in data) { + return new OwnContributorDetailed(data); + } + return new ContributorDetailed(data); + } } - public static ofId(id: string): Contributor { + public static async get(id: string, options?: AxiosRequestConfig) { + const contributor = await this.find(id, options); + assertObjectFound(contributor, Contributor, id); + return contributor; + } + + public static ofId(id: string) { return new Contributor(id); } - public static find = provideReact( - async (id: string): Promise => { - const data = await config.behaviors.contributor.find(id); - if (data !== undefined) { - return new ContributorDetailed(data); - } - }, - ); + public async contributorRequestVerification() { + return await config.behaviors.contributor.contributorRequestVerification( + this.id, + ); + } + + public async createStripeOnboardingLink() { + return await config.behaviors.contributor.getStripeOnboardingLink(this.id); + } + + public async findCommon( + options?: AxiosRequestConfig, + ): Promise { + return this instanceof ContributorCommon + ? this + : this.findDetailed(options); + } + + public async findDetailed( + options?: AxiosRequestConfig, + ): Promise { + return Contributor.find(this.id, options); + } + + public async getAvatarUploadRules() { + return File.getUploadRules("avatar"); + } + + public async getBillingInformation() { + return await config.behaviors.contributor.getBillingInformation(this.id); + } + + public async getCommon( + options?: AxiosRequestConfig, + ): Promise { + return this instanceof ContributorCommon ? this : this.getDetailed(options); + } + + public async getDetailed( + options?: AxiosRequestConfig, + ): Promise { + return Contributor.get(this.id, options); + } + + public async getStripeLoginLink() { + return await config.behaviors.contributor.getStripeLoginLink(this.id); + } - public static query(query: ContributorListQueryData = {}) { + public async listOutgoingInvoices() { + const response = await config.behaviors.contributor.listOnBehalfInvoices( + this.id, + ); + return response.map((i) => new ContributorOutgoingInvoice(i)); + } + + public query(query: ContributorListQueryData = {}) { return new ContributorListQuery(query); } - public static get = provideReact( - async (id: string): Promise => { - const contributor = await this.find(id); - assertObjectFound(contributor, this, id); - return contributor; - }, - ); + public async removeAvatar() { + await config.behaviors.contributor.removeAvatar(this.id); + } - public getDetailed = provideReact( - () => Contributor.get(this.id), - [this.id], - ) as AsyncResourceVariant<() => Promise>; + public async update(data: ContributorUpdateRequestData) { + if (data.deviatingSupportInformation?.phone == "") { + data.deviatingSupportInformation.phone = null as unknown as undefined; + } + return await config.behaviors.contributor.update(this.id, { + ...data, + descriptions: + data.descriptions?.de == "" + ? (null as unknown as undefined) + : data.descriptions, + homepage: + data.homepage == "" ? (null as unknown as undefined) : data.homepage, + }); + } - public findDetailed = provideReact( - () => Contributor.find(this.id), - [this.id], - ) as AsyncResourceVariant<() => Promise>; + public async uploadAvatar(file: DomFile) { + await File.upload(file, this.avatarAccessTokenProvider); + } } -class ContributorCommon extends classes( - DataModel, - Contributor, -) { +export class ContributorCommon extends WithData< + ContributorListItemData | ContributorData +>()(Contributor) { + public readonly avatar?: File; + public readonly contributorNumber?: string; + public readonly customer: Customer; + public override readonly data: ContributorListItemData | ContributorData; + public readonly description: LocalizedText; + public readonly email?: string; + public readonly homepage?: string; + public readonly imprint?: ContributorImprint; + public readonly name: string; + public readonly phone?: string; + public readonly state: ContributorState; + public constructor(data: ContributorListItemData | ContributorData) { - super([data], [data.id]); + super(data.id); + this.data = data; + this.customer = Customer.ofId(data.customerId); + this.name = data.name; + this.description = new LocalizedText(data.descriptions); + this.email = data.supportInformation.email; + this.phone = data.supportInformation.phone; + this.homepage = data.homepage; + this.state = data.state; + this.avatar = data.logoRefId ? File.ofId(data.logoRefId) : undefined; + this.imprint = data.imprint; + if ( + "contributorNumber" in data && + typeof data.contributorNumber === "string" + ) { + this.contributorNumber = data.contributorNumber; + } } } -export class ContributorDetailed extends classes( - ContributorCommon, - DataModel, -) { +export class ContributorDetailed extends ContributorCommon { + public override readonly data: ContributorData; public constructor(data: ContributorData) { - super([data], [data]); + super(data); + this.data = data; } } -export class ContributorListItem extends classes( - ContributorCommon, - DataModel, -) { +export class OwnContributorDetailed extends ContributorCommon { + public override readonly data: OwnContributorData; + public readonly logoInherited?: boolean; + public readonly verificationRequested: boolean; + public readonly verified: boolean; + + public constructor(data: OwnContributorData) { + super(data); + this.data = data; + + this.verificationRequested = data.verificationRequested; + this.verified = data.verified; + this.logoInherited = data.logoInherited; + } +} + +export class ContributorListItem extends ContributorCommon { + public override readonly data: ContributorListItemData; public constructor(data: ContributorListItemData) { - super([data], [data]); + super(data); + this.data = data; } } @@ -92,48 +232,43 @@ export class ContributorListQuery extends ListQueryModel { - const { items, totalCount } = await config.behaviors.contributor.list({ - limit: config.defaultPaginationLimit, - ...this.query, - }); + public async execute() { + const { totalCount, items } = await config.behaviors.contributor.list( + this.query, + ); return new ContributorList( this.query, items.map((d) => new ContributorListItem(d)), totalCount, ); - }, [this.queryId]); + } - public getTotalCount = provideReact(async () => { + public async getTotalCount() { const { totalCount } = await this.refine({ limit: 1 }).execute(); return totalCount; - }, [this.queryId]); + } - public findOneAndOnly = provideReact(async () => { - const { items, totalCount } = await this.refine({ limit: 2 }).execute(); - if (totalCount === 1) { - return items[0]; - } - }, [this.queryId]); + public refine(query: ContributorListQueryData) { + return new ContributorListQuery({ + ...this.query, + ...query, + }); + } } -export class ContributorList extends classes( +export class ContributorList extends WithListData()( ContributorListQuery, - ListDataModel, ) { + public override readonly items: readonly ContributorListItem[]; + public override readonly totalCount: number; public constructor( query: ContributorListQueryData, contributors: ContributorListItem[], totalCount: number, ) { - super([query], [contributors, totalCount]); + super(query); + this.items = Object.freeze(contributors); + this.totalCount = totalCount; } } diff --git a/packages/models/src/marketplace/Contributor/ContributorAvatarAccessTokenProvider.ts b/packages/models/src/marketplace/Contributor/ContributorAvatarAccessTokenProvider.ts new file mode 100644 index 00000000..f1b700ac --- /dev/null +++ b/packages/models/src/marketplace/Contributor/ContributorAvatarAccessTokenProvider.ts @@ -0,0 +1,18 @@ +import type { FileAccessTokenProvider } from "../../file/index.js"; +import type { Contributor } from "./Contributor.js"; + +import { config } from "../../config/index.js"; + +export class ContributorAvatarAccessTokenProvider implements FileAccessTokenProvider { + public readonly contributor: Contributor; + + public constructor(contributor: Contributor) { + this.contributor = contributor; + } + + public async createUploadToken() { + return await config.behaviors.contributor.createAvatarUploadToken( + this.contributor.id, + ); + } +} diff --git a/packages/models/src/marketplace/Contributor/ContributorIncomingInvoice.ts b/packages/models/src/marketplace/Contributor/ContributorIncomingInvoice.ts index f0aa5297..562b10c8 100644 --- a/packages/models/src/marketplace/Contributor/ContributorIncomingInvoice.ts +++ b/packages/models/src/marketplace/Contributor/ContributorIncomingInvoice.ts @@ -1,25 +1,25 @@ -import { classes } from "polytype"; -import { ListQueryModel } from "../../base/ListQueryModel.js"; -import { Money } from "../../base/Money.js"; -import { provideReact } from "../../react.js"; import { DateTime } from "luxon"; + import type { Contributor } from "./Contributor.js"; import type { - ContributorIncomingInvoiceData, ContributorListIncomingInvoiceQueryData, + ContributorIncomingInvoiceData, } from "./types.js"; -import { ListDataModel } from "../../base/ListDataModel.js"; -import { DataModel } from "../../base/DataModel.js"; -import { config } from "../../config/config.js"; + +import { ContributorIncomingInvoicePdfAccessTokenProvider } from "./ContributorIncomingInvoicePdfAccessTokenProvider.js"; +import { ListQueryModel, WithListData, DataModel } from "../../base/index.js"; +import { File } from "../../file/File/internal.js"; +import { config } from "../../config/index.js"; +import { Money } from "../../common/index.js"; export class ContributorIncomingInvoice extends DataModel { public readonly contributor: Contributor; + public readonly date: DateTime; public readonly id: string; - public readonly pdfId: string; public readonly invoiceNumber: string; - public readonly date: DateTime; - public readonly totalNet: Money; + public readonly pdf: File; public readonly totalGross: Money; + public readonly totalNet: Money; public constructor( contributor: Contributor, @@ -28,7 +28,10 @@ export class ContributorIncomingInvoice extends DataModel { - const { items, totalCount } = + public async execute() { + const { totalCount, items } = await config.behaviors.contributor.listIncomingInvoices( this.contributor.id, this.query, @@ -66,24 +62,34 @@ export class ContributorIncomingInvoiceListQuery extends ListQueryModel new ContributorIncomingInvoice(this.contributor, i)), totalCount, ); - }, [this.queryId]); + } - public getTotalCount = provideReact(async () => { + public async getTotalCount() { const result = await this.refine({ limit: 1, skip: 0 }).execute(); return result.totalCount; - }); + } + + public refine(query: ContributorListIncomingInvoiceQueryData) { + return new ContributorIncomingInvoiceListQuery(this.contributor, { + ...this.query, + ...query, + }); + } } -export class ContributorIncomingInvoicesList extends classes( +export class ContributorIncomingInvoicesList extends WithListData()( ContributorIncomingInvoiceListQuery, - ListDataModel, ) { + public override readonly items: readonly ContributorIncomingInvoice[]; + public override readonly totalCount: number; public constructor( contributor: Contributor, query: ContributorListIncomingInvoiceQueryData, invoices: ContributorIncomingInvoice[], totalCount: number, ) { - super([contributor, query], [invoices, totalCount]); + super(contributor, query); + this.items = Object.freeze(invoices); + this.totalCount = totalCount; } } diff --git a/packages/models/src/marketplace/Contributor/ContributorIncomingInvoicePdfAccessTokenProvider.ts b/packages/models/src/marketplace/Contributor/ContributorIncomingInvoicePdfAccessTokenProvider.ts new file mode 100644 index 00000000..b3703bec --- /dev/null +++ b/packages/models/src/marketplace/Contributor/ContributorIncomingInvoicePdfAccessTokenProvider.ts @@ -0,0 +1,22 @@ +import type { AxiosRequestConfig } from "axios"; + +import type { ContributorIncomingInvoice } from "./ContributorIncomingInvoice.js"; +import type { FileAccessTokenProvider } from "../../file/index.js"; + +import { config } from "../../config/index.js"; + +export class ContributorIncomingInvoicePdfAccessTokenProvider implements FileAccessTokenProvider { + public readonly invoice: ContributorIncomingInvoice; + + public constructor(invoice: ContributorIncomingInvoice) { + this.invoice = invoice; + } + + public getDownloadToken(_: string, requestConfig?: AxiosRequestConfig) { + return config.behaviors.contributor.getFileAccessToken( + this.invoice.contributor.id, + this.invoice.id, + requestConfig, + ); + } +} diff --git a/packages/models/src/marketplace/Contributor/ContributorOutgoingInvoice.test.ts b/packages/models/src/marketplace/Contributor/ContributorOutgoingInvoice.test.ts new file mode 100644 index 00000000..32aa6227 --- /dev/null +++ b/packages/models/src/marketplace/Contributor/ContributorOutgoingInvoice.test.ts @@ -0,0 +1,26 @@ +import { afterEach, expect, test } from "vitest"; + +import { ContributorOutgoingInvoice } from "./ContributorOutgoingInvoice.js"; +import { + buildContributorOnBehalfInvoiceData, + resetBehaviors, +} from "../../testing/index.js"; + +afterEach(resetBehaviors); + +test("derives monetary amounts and the invoice date", () => { + const data = buildContributorOnBehalfInvoiceData({ + invoiceDate: "2024-05-01", + totalGross: 11900, + totalNet: 10000, + }); + const invoice = new ContributorOutgoingInvoice(data); + + expect(invoice.totalNet.getAmount()).toBe(10000); + expect(invoice.totalNet.getCurrency()).toBe("EUR"); + expect(invoice.totalGross.getAmount()).toBe(11900); + expect(invoice.totalGross.getCurrency()).toBe("EUR"); + expect(invoice.date.year).toBe(2024); + expect(invoice.date.month).toBe(5); + expect(invoice.date.day).toBe(1); +}); diff --git a/packages/models/src/marketplace/Contributor/ContributorOutgoingInvoice.ts b/packages/models/src/marketplace/Contributor/ContributorOutgoingInvoice.ts new file mode 100644 index 00000000..b9e12b83 --- /dev/null +++ b/packages/models/src/marketplace/Contributor/ContributorOutgoingInvoice.ts @@ -0,0 +1,23 @@ +import { DateTime } from "luxon"; + +import type { ContributorOnBehalfInvoiceData } from "./types.js"; + +import { DataModel } from "../../base/index.js"; +import { Money } from "../../common/index.js"; + +export class ContributorOutgoingInvoice extends DataModel { + public readonly date: DateTime; + public readonly invoiceNumber: string; + public readonly pdfLink: string; + public readonly totalGross: Money; + public readonly totalNet: Money; + + public constructor(data: ContributorOnBehalfInvoiceData) { + super(data); + this.invoiceNumber = data.invoiceNumber; + this.totalNet = Money({ amount: data.totalNet, currency: "EUR" }); + this.totalGross = Money({ amount: data.totalGross, currency: "EUR" }); + this.pdfLink = data.pdfLink; + this.date = DateTime.fromISO(data.invoiceDate); + } +} diff --git a/packages/models/src/marketplace/Contributor/behaviors/api.ts b/packages/models/src/marketplace/Contributor/behaviors/api.ts index 28c6deb1..b83c9135 100644 --- a/packages/models/src/marketplace/Contributor/behaviors/api.ts +++ b/packages/models/src/marketplace/Contributor/behaviors/api.ts @@ -1,52 +1,174 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + import type { ContributorBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; import { - MittwaldAPIV2Client, - extractTotalCountHeader, - assertStatus, -} from "@mittwald/api-client"; + withAxiosRequestConfig, + resolveTotalCount, + anyStatus403, +} from "../../../base/index.js"; export const apiContributorBehaviors = ( client: MittwaldAPIV2Client, ): ContributorBehaviors => ({ - find: async (contributorId) => { - const response = await client.marketplace.extensionGetContributor({ + find: async (contributorId, options) => { + const response = await client.marketplace.extensionGetContributor( + { + contributorId, + }, + withAxiosRequestConfig(options), + ); + + if (response.status === 200) { + return response.data; + } + // API-DRIFT: extensionGetContributor omits 403 in its generated response type, so anyStatus403 (403 as any) is passed (resolve: use the literal 403 once the client type declares it) + validateResponse(response, [anyStatus403, 404]); + }, + + listIncomingInvoices: async (contributorId, queryParameters) => { + const response = await client.marketplace.contributorListIncomingInvoices({ + queryParameters, + contributorId, + }); + + if (response.status === 200) { + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + } + + validateResponse(response, 404); + return { + totalCount: resolveTotalCount({ ...response, data: [] }), + items: [], + }; + }, + + update: async (contributorId, data) => { + const response = await client.marketplace.contributorPatchContributor({ + contributorId, + data, + }); + + validateResponse(response, 200, { + validationError: { + pathMappings: { + "contributor.homepage": "homepage", + "*imprint*": "imprintUrl", + "*phone*": "phone", + "*mail*": "email", + }, + }, + }); + }, + + getFileAccessToken: async ( + contributorId, + contributorReceiptId, + requestConfig, + ) => { + const response = + await client.marketplace.contributorReceiptGetFileAccessToken( + { + contributorReceiptId, + contributorId, + }, + withAxiosRequestConfig(requestConfig), + ); + validateResponse(response, 200); + + return response.data; + }, + + createAvatarUploadToken: async (contributorId: string) => { + const response = + await client.marketplace.contributorRequestDeviatingContributorAvatarUpload( + { + contributorId, + }, + ); + validateResponse(response, 200); + + return { + token: response.data.avatarRefId, + rules: response.data.rules, + }; + }, + + getStripeOnboardingLink: async (contributorId) => { + const response = + await client.marketplace.extensionCreateContributorOnboardingProcess({ + data: { shippingCountryRestriction: "onlyDomestic" }, + contributorId, + }); + validateResponse(response, 201); + + return response.data.onboardingLink; + }, + + getStripeLoginLink: async (contributorId) => { + const response = await client.marketplace.contributorGetLoginLink({ + contributorId, + }); + + if (response.status === 200) { + return response.data.url; + } + + validateResponse(response, [403, 404]); + return undefined; + }, + + listOnBehalfInvoices: async (contributorId) => { + const response = await client.marketplace.contributorListOnbehalfInvoices({ contributorId, }); if (response.status === 200) { return response.data; } - assertStatus(response, 404); + + validateResponse(response, 404); + return []; }, list: async (query) => { const response = await client.marketplace.extensionListContributors({ queryParameters: query, }); - assertStatus(response, 200); + validateResponse(response, 200); return { + totalCount: resolveTotalCount(response), items: response.data, - totalCount: extractTotalCountHeader(response), }; }, - listIncomingInvoices: async (contributorId, queryParameters) => { - const response = await client.marketplace.contributorListIncomingInvoices({ + getBillingInformation: async (contributorId) => { + const response = await client.marketplace.contributorGetBillingInformation({ contributorId, - queryParameters, }); - if (response.status === 200) { - return { - items: response.data, - totalCount: extractTotalCountHeader(response), - }; - } + validateResponse(response, 200); - assertStatus(response, 404); - return { - items: [], - totalCount: 0, - }; + return response.data; + }, + + contributorRequestVerification: async (contributorId) => { + const response = await client.marketplace.contributorRequestVerification({ + contributorId, + }); + + validateResponse(response, 204, {}); + }, + + removeAvatar: async (contributorId: string) => { + const response = await client.marketplace.contributorResetContributorAvatar( + { contributorId }, + ); + + validateResponse(response, 204); }, }); diff --git a/packages/models/src/marketplace/Contributor/behaviors/types.ts b/packages/models/src/marketplace/Contributor/behaviors/types.ts index 66967bbc..2393c645 100644 --- a/packages/models/src/marketplace/Contributor/behaviors/types.ts +++ b/packages/models/src/marketplace/Contributor/behaviors/types.ts @@ -1,19 +1,23 @@ -import type { QueryResponseData } from "../../../base/types.js"; +import type { AxiosRequestConfig } from "axios"; + +import type { + FileDownloadTokenData, + FileUploadTokenData, +} from "../../../file/index.js"; +import type { QueryResponseData } from "../../../base/index.js"; import type { - ContributorData, - ContributorIncomingInvoiceData, ContributorListIncomingInvoiceQueryData, - ContributorListItemData, + ContributorBillingInformationData, + ContributorIncomingInvoiceData, + ContributorOnBehalfInvoiceData, + ContributorUpdateRequestData, ContributorListQueryData, + ContributorListItemData, + OwnContributorData, + ContributorData, } from "../types.js"; export interface ContributorBehaviors { - find: (contributorId: string) => Promise; - - list: ( - query?: ContributorListQueryData, - ) => Promise>; - listIncomingInvoices: ( contributorId: string, queryParameters?: ContributorListIncomingInvoiceQueryData, @@ -21,4 +25,46 @@ export interface ContributorBehaviors { items: ContributorIncomingInvoiceData[]; totalCount: number; }>; + + getFileAccessToken: ( + contributorId: string, + contributorReceiptId: string, + requestConfig?: AxiosRequestConfig, + ) => Promise; + + find: ( + contributorId: string, + options?: AxiosRequestConfig, + ) => Promise; + + list: ( + query?: ContributorListQueryData, + ) => Promise>; + + getBillingInformation: ( + contributorId: string, + ) => Promise; + + listOnBehalfInvoices: ( + contributorId: string, + ) => Promise; + + update: ( + contributorId: string, + data: ContributorUpdateRequestData, + ) => Promise; + + createAvatarUploadToken: ( + contributorId: string, + ) => Promise; + + getStripeOnboardingLink: ( + contributorId: string, + ) => Promise; + + getStripeLoginLink: (contributorId: string) => Promise; + + contributorRequestVerification: (contributorId: string) => Promise; + + removeAvatar: (contributorId: string) => Promise; } diff --git a/packages/models/src/marketplace/Contributor/index.ts b/packages/models/src/marketplace/Contributor/index.ts index 77a5d0d3..d1278628 100644 --- a/packages/models/src/marketplace/Contributor/index.ts +++ b/packages/models/src/marketplace/Contributor/index.ts @@ -1,3 +1,4 @@ export * from "./Contributor.js"; export * from "./ContributorIncomingInvoice.js"; +export * from "./ContributorOutgoingInvoice.js"; export * from "./types.js"; diff --git a/packages/models/src/marketplace/Contributor/types.ts b/packages/models/src/marketplace/Contributor/types.ts index 358c3290..9ce0c591 100644 --- a/packages/models/src/marketplace/Contributor/types.ts +++ b/packages/models/src/marketplace/Contributor/types.ts @@ -3,14 +3,32 @@ import type { MittwaldAPIV2 } from "@mittwald/api-client"; export type ContributorData = MittwaldAPIV2.Components.Schemas.MarketplaceContributor; +export type OwnContributorData = + MittwaldAPIV2.Components.Schemas.MarketplaceOwnContributor; + +export type ContributorState = + MittwaldAPIV2.Components.Schemas.MarketplaceContributorState; + export type ContributorListItemData = MittwaldAPIV2.Operations.ExtensionListContributors.ResponseData[number]; +export type ContributorUpdateRequestData = + MittwaldAPIV2.Operations.ContributorPatchContributor.RequestData; + export type ContributorListQueryData = MittwaldAPIV2.Paths.V2Contributors.Get.Parameters.Query; +export type ContributorImprint = + MittwaldAPIV2.Components.Schemas.MarketplaceContributorImprint; + +export type ContributorBillingInformationData = + MittwaldAPIV2.Operations.ContributorGetBillingInformation.ResponseData; + export type ContributorIncomingInvoiceData = MittwaldAPIV2.Operations.ContributorListIncomingInvoices.ResponseData[number]; export type ContributorListIncomingInvoiceQueryData = MittwaldAPIV2.Paths.V2ContributorsContributorIdInvoicesIncoming.Get.Parameters.Query; + +export type ContributorOnBehalfInvoiceData = + MittwaldAPIV2.Operations.ContributorListOnbehalfInvoices.ResponseData[number]; diff --git a/packages/models/src/marketplace/ContributorExtension/ContributorExtension.test.ts b/packages/models/src/marketplace/ContributorExtension/ContributorExtension.test.ts new file mode 100644 index 00000000..bc4d8efe --- /dev/null +++ b/packages/models/src/marketplace/ContributorExtension/ContributorExtension.test.ts @@ -0,0 +1,225 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { buildContributorExtensionListItemData } from "../../testing/builders/buildContributorExtensionListItemData.js"; +import { buildContributorExtensionData } from "../../testing/builders/buildContributorExtensionData.js"; +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { ReferenceModel } from "../../base/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { + ContributorExtensionListQuery, + ContributorExtensionDetailed, + ContributorExtensionListItem, + ContributorExtensionList, + ContributorExtension, +} from "./ContributorExtension.js"; + +afterEach(resetBehaviors); + +describe("reference and delegation", () => { + test("ofId preserves both identifiers", () => { + const extension = ContributorExtension.ofId("c-1", "e-1"); + expect(extension.contributorId).toBe("c-1"); + expect(extension.id).toBe("e-1"); + }); + + test("find delegates with both identifiers", async () => { + const find = vi + .fn() + .mockResolvedValue( + buildContributorExtensionData({ contributorId: "c-1", id: "e-1" }), + ); + installBehaviors({ contributorExtension: { find } }); + + const extension = await ContributorExtension.find("c-1", "e-1"); + + expect(find).toHaveBeenCalledWith("c-1", "e-1"); + expect(extension).toBeInstanceOf(ContributorExtensionDetailed); + expect(extension?.id).toBe("e-1"); + }); + + test("find returns undefined when the behavior does", async () => { + installBehaviors({ + contributorExtension: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + ContributorExtension.find("c-1", "missing"), + ).resolves.toBeUndefined(); + }); +}); + +test("create delegates and returns a reference", async () => { + const create = vi.fn().mockResolvedValue({ id: "new-id" }); + installBehaviors({ contributorExtension: { create } }); + + const extension = await ContributorExtension.create({ + contributorId: "c-1", + name: "X", + }); + + expect(create).toHaveBeenCalledWith("c-1", "X"); + expect(extension).toBeInstanceOf(ContributorExtension); + expect(extension.contributorId).toBe("c-1"); + expect(extension.id).toBe("new-id"); +}); + +test("exposes data and derived values", () => { + const extension = new ContributorExtensionDetailed( + buildContributorExtensionData({ + assets: [ + { assetType: "image", id: "asset-2", index: 2 }, + { assetType: "image", id: "asset-1", index: 1 }, + ], + deletionDeadline: "2025-02-03T00:00:00.000Z", + contributorId: "c-1", + verified: true, + }), + ); + + expect(extension.name).toBe("Own Extension"); + expect(extension.contributor.id).toBe("c-1"); + expect(extension.amountOfInstances).toBe(5); + expect(extension.assets.map(({ id }) => id)).toEqual(["asset-1", "asset-2"]); + expect(extension.verified).toBe(true); + expect(extension.deletionDeadline?.year).toBe(2025); +}); + +test("defaults the amount of instances to zero", () => { + const extension = new ContributorExtensionDetailed( + buildContributorExtensionData({ statistics: {} }), + ); + + expect(extension.amountOfInstances).toBe(0); +}); + +test("query delegates with the contributor and materializes items", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildContributorExtensionListItemData()], + totalCount: 1, + }); + installBehaviors({ contributorExtension: { list } }); + + const result = await ContributorExtension.query("c-1").execute(); + + expect(list).toHaveBeenCalledWith("c-1", expect.any(Object)); + expect(result).toBeInstanceOf(ContributorExtensionList); + expect(result).toBeInstanceOf(ContributorExtensionListQuery); + expect(result.items[0]).toBeInstanceOf(ContributorExtensionListItem); + expect(result.totalCount).toBe(1); +}); + +test("preserves ghostmaker identity chains", () => { + const item = new ContributorExtensionListItem( + buildContributorExtensionListItemData(), + ); + + expect(item).toBeInstanceOf(ContributorExtensionListItem); + expect(item).toBeInstanceOf(ContributorExtension); + expect(item).toBeInstanceOf(ReferenceModel); + expect(item.data).toBeDefined(); +}); + +describe("get on a missing contributor extension", () => { + test("throws ObjectNotFoundError", async () => { + installBehaviors({ + contributorExtension: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + ContributorExtension.get("c-1", "missing"), + ).rejects.toBeInstanceOf(ObjectNotFoundError); + }); +}); +describe("common variant and idempotency", () => { + test("findCommon delegates to the detailed variant from a bare reference", async () => { + const find = vi + .fn() + .mockResolvedValue( + buildContributorExtensionData({ contributorId: "c-1", id: "e-1" }), + ); + installBehaviors({ contributorExtension: { find } }); + + const common = await ContributorExtension.ofId("c-1", "e-1").findCommon(); + + expect(find).toHaveBeenCalledWith("c-1", "e-1"); + expect(common).toBeInstanceOf(ContributorExtensionDetailed); + expect(common?.id).toBe("e-1"); + }); + + test("findCommon returns undefined when the behavior finds nothing", async () => { + installBehaviors({ + contributorExtension: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + ContributorExtension.ofId("c-1", "missing").findCommon(), + ).resolves.toBeUndefined(); + }); + + test("getCommon delegates and throws when the extension is missing", async () => { + installBehaviors({ + contributorExtension: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + ContributorExtension.ofId("c-1", "missing").getCommon(), + ).rejects.toBeInstanceOf(ObjectNotFoundError); + }); + + test("getCommon on an already-common model returns itself without re-fetching", async () => { + const find = vi.fn(); + installBehaviors({ contributorExtension: { find } }); + const item = new ContributorExtensionListItem( + buildContributorExtensionListItemData({ id: "e-2" }), + ); + + const common = await item.getCommon(); + + expect(common).toBe(item); + expect(find).not.toHaveBeenCalled(); + }); + + test("findCommon on an already-common model returns itself without re-fetching", async () => { + const find = vi.fn(); + installBehaviors({ contributorExtension: { find } }); + const detailed = new ContributorExtensionDetailed( + buildContributorExtensionData({ id: "e-3" }), + ); + + const common = await detailed.findCommon(); + + expect(common).toBe(detailed); + expect(find).not.toHaveBeenCalled(); + }); +}); + +describe("absent optional source data", () => { + test("omits the logo, fragments and external frontends when the source has none", () => { + const extension = new ContributorExtensionDetailed( + buildContributorExtensionData({ logoRefId: undefined }), + ); + + expect(extension.logo).toBeUndefined(); + expect(extension.deprecation).toBeUndefined(); + expect(extension.deletionDeadline).toBeUndefined(); + expect(extension.frontendFragments).toEqual([]); + expect(extension.externalFrontends).toEqual([]); + expect( + extension.findFrontendFragment( + "/projects/project/menu/section/extensions/item", + ), + ).toBeUndefined(); + }); +}); diff --git a/packages/models/src/marketplace/ContributorExtension/ContributorExtension.ts b/packages/models/src/marketplace/ContributorExtension/ContributorExtension.ts new file mode 100644 index 00000000..621c8eac --- /dev/null +++ b/packages/models/src/marketplace/ContributorExtension/ContributorExtension.ts @@ -0,0 +1,654 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; + +import type { ContributorExtensionAssetAccessTokenProvider as ContributorExtensionAssetAccessTokenProviderType } from "./ContributorExtensionAssetAccessTokenProvider.js"; +import type { ContributorExtensionLogoAccessTokenProvider as ContributorExtensionLogoAccessTokenProviderType } from "./ContributorExtensionLogoAccessTokenProvider.js"; +import type { PricePlanEditingVariant } from "./PricePlanEditingVariant.js"; +import type { Money } from "../../common/index.js"; +import type { + MarketplaceDetailedDescriptionsFormat, + FrontendFragmentAnchor, + ExtensionPricePlan, + ExternalFrontend, +} from "../Extension/index.js"; +import type { + ContributorExtensionUpdatePricingRequestData, + ContributorExtensionUpdateRequestData, + ContributorExtensionListQueryData, + ContributorExtensionListItemData, + MarketplaceExtensionDeprecation, + MarketplaceExtendedSupportMeta, + ContributorExtensionData, + MarketplaceWebhookUrls, + ExtensionSecret, +} from "./types.js"; + +import { ContributorExtensionAssetAccessTokenProvider } from "./ContributorExtensionAssetAccessTokenProvider.js"; +import { ContributorExtensionLogoAccessTokenProvider } from "./ContributorExtensionLogoAccessTokenProvider.js"; +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { Customer } from "../../customer/Customer/Customer.js"; +import { File } from "../../file/File/internal.js"; +import { LocalizedText } from "../../common/index.js"; +import { Contributor } from "../Contributor/index.js"; +import { type DomFile } from "../../file/index.js"; +import { Project } from "../../project/index.js"; +import { config } from "../../config/index.js"; +import { + type MarketplaceContext, + ExtensionInstance, +} from "../ExtensionInstance/index.js"; +import { + extensionVariantsPricePlanFactory, + FrontendFragment, + ExtensionAsset, + Extension, +} from "../Extension/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + required, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "ContributorExtension", +}) +export class ContributorExtension extends ReferenceModel { + public readonly assetAccessTokenProvider: ContributorExtensionAssetAccessTokenProviderType; + public readonly contributorId: string; + + public readonly logoAccessTokenProvider: ContributorExtensionLogoAccessTokenProviderType; + + public constructor(contributorId: string, extensionId: string) { + super(extensionId); + this.logoAccessTokenProvider = + new ContributorExtensionLogoAccessTokenProvider(this); + this.assetAccessTokenProvider = + new ContributorExtensionAssetAccessTokenProvider(this); + this.contributorId = contributorId; + } + + public static async create(data: { contributorId: string; name: string }) { + const { contributorId, name } = data; + + const { id } = await config.behaviors.contributorExtension.create( + contributorId, + name, + ); + return new ContributorExtension(contributorId, id); + } + + public static async find(contributorId: string, extensionId: string) { + const data = await config.behaviors.contributorExtension.find( + contributorId, + extensionId, + ); + + if (data) { + return new ContributorExtensionDetailed(data); + } + } + + public static async get(contributorId: string, extensionId: string) { + const extension = await this.find(contributorId, extensionId); + assertObjectFound(extension, ContributorExtension, extensionId); + return extension; + } + + public static ofId(contributorId: string, extensionId: string) { + return new ContributorExtension(contributorId, extensionId); + } + + public static query( + contributor: Contributor | string, + query: ContributorExtensionListQueryData = {}, + ) { + return new ContributorExtensionListQuery(contributor, query); + } + + public async delete() { + return await config.behaviors.contributorExtension.delete( + this.contributorId, + this.id, + ); + } + + public async deleteExtensionAsset(assetRefId: string) { + return await config.behaviors.contributorExtension.deleteExtensionAsset( + this.contributorId, + this.id, + assetRefId, + ); + } + + public async findCommon(): Promise { + return this instanceof ContributorExtensionCommon + ? this + : this.findDetailed(); + } + + public async findDetailed(): Promise< + ContributorExtensionDetailed | undefined + > { + return ContributorExtension.find(this.contributorId, this.id); + } + + public async getCommon(): Promise { + return this instanceof ContributorExtensionCommon + ? this + : this.getDetailed(); + } + + public async getDetailed(): Promise { + return ContributorExtension.get(this.contributorId, this.id); + } + + public async getLogoUploadRules() { + return File.getUploadRules("avatar"); + } + + public async getMediaImageUploadRules() { + return File.getUploadRules("extensionAssetImage"); + } + + public async getMediaVideoUploadRules() { + return File.getUploadRules("extensionAssetVideo"); + } + + public async getPossibleScopes() { + return await config.behaviors.contributorExtension.getPossibleScopes(); + } + + public async publish() { + await config.behaviors.contributorExtension.publish( + this.contributorId, + this.id, + ); + } + + public async requestVerification( + contributor: Contributor | string, + extensionId: string, + ) { + const contributorId = extractId(contributor); + await config.behaviors.contributorExtension.requestVerification( + contributorId, + extensionId, + ); + } + + public async unpublish(reason: string) { + await config.behaviors.contributorExtension.unpublish( + this.contributorId, + this.id, + reason, + ); + } + + public async update(data: ContributorExtensionUpdateRequestData) { + return await config.behaviors.contributorExtension.update( + this.contributorId, + this.id, + data, + ); + } + + public async updateContext(context: MarketplaceContext) { + await config.behaviors.contributorExtension.updateContext( + context, + this.contributorId, + this.id, + ); + } + + public async uploadAsset(file: DomFile, assetType: "image" | "video") { + return await File.upload(file, this.assetAccessTokenProvider, assetType); + } + + public async uploadLogo(file: DomFile) { + await File.upload(file, this.logoAccessTokenProvider); + } +} + +export class ContributorExtensionCommon extends WithData< + ContributorExtensionListItemData | ContributorExtensionData +>()(ContributorExtension) { + public readonly amountOfInstances: number; + public readonly assets: ExtensionAsset[]; + public readonly blocked?: boolean; + public readonly context?: MarketplaceContext; + public readonly contributor: Contributor; + public readonly customer: Customer; + public override readonly data: + ContributorExtensionListItemData | ContributorExtensionData; + public readonly deletionDeadline?: DateTime; + public readonly deprecation?: MarketplaceExtensionDeprecation; + public readonly description?: string; + public readonly detailedDescription: LocalizedText; + public readonly disabled?: boolean; + public readonly externalFrontends: ExternalFrontend[]; + public readonly frontendFragments: FrontendFragment[]; + public readonly logo?: File; + public readonly name: string; + public readonly pricing?: ExtensionPricePlan; + public readonly published?: boolean; + public readonly requestedChanges?: { + webhookUrls?: MarketplaceWebhookUrls | Record; + context?: MarketplaceContext; + scopes?: string[]; + }; + public readonly scopes?: string[]; + public readonly secrets: ExtensionSecret[]; + public readonly state?: "disabled" | "enabled" | "blocked"; + public readonly subTitle: LocalizedText; + public readonly support?: MarketplaceExtendedSupportMeta; + public readonly tags?: string[]; + public readonly verificationRequested: boolean; + public readonly verified: boolean; + public readonly webhookUrls?: MarketplaceWebhookUrls; + + public constructor( + data: ContributorExtensionListItemData | ContributorExtensionData, + ) { + const { contributorId, id } = data; + super(contributorId, id); + this.data = data; + this.contributor = Contributor.ofId(contributorId); + this.name = data.name; + this.description = data.description; + this.detailedDescription = new LocalizedText(data.detailedDescriptions); + this.subTitle = new LocalizedText(data.subTitle); + this.context = data.context; + this.scopes = data.scopes; + this.logo = data.logoRefId ? File.ofId(data.logoRefId) : undefined; + this.assets = data.assets + .sort((a, b) => a.index - b.index) + .map((a) => new ExtensionAsset(a)); + this.amountOfInstances = this.data.statistics.amountOfInstances ?? 0; + this.pricing = extensionVariantsPricePlanFactory( + this, + data.pricing, + data.pricingDetails, + ); + + this.blocked = data.blocked; + this.deprecation = data.deprecation; + this.deletionDeadline = data.deletionDeadline + ? DateTime.fromISO(data.deletionDeadline) + : undefined; + this.externalFrontends = data.externalFrontends ?? []; + this.frontendFragments = data.frontendFragments + ? Object.entries(data.frontendFragments) + .filter(([key]) => Extension.isValidAnchor(key)) + .map( + ([key, value]) => + new FrontendFragment( + key as unknown as FrontendFragmentAnchor, + value, + this.name, + this, + ), + ) + : []; + this.requestedChanges = data.requestedChanges; + this.state = data.state; + this.secrets = data.secrets.map((s) => ({ + usableUntil: s.usableUntil ? DateTime.fromISO(s.usableUntil) : undefined, + secretId: s.secretId, + })); + this.tags = data.tags; + this.support = data.support; + this.verificationRequested = data.verificationRequested; + this.verified = data.verified; + this.webhookUrls = data.webhookUrls; + this.published = data.published; + this.disabled = data.disabled; + this.customer = Customer.ofId(contributorId); + } + + public async addFrontendFragment(name: string, url: string, anchor: string) { + const newFragment = { + additionalProperties: { + title: JSON.stringify({ de: name }), + anchor, + }, + url, + }; + + const updatedFragments = { + ...(this.data.frontendFragments ?? {}), + [anchor]: newFragment, + }; + + return await this.update({ + frontendFragments: updatedFragments, + }); + } + + public async deleteExtensionSecrets(secretId: string) { + return await config.behaviors.contributorExtension.deleteExtensionSecret( + this.contributorId, + this.id, + secretId, + ); + } + + public async deleteExternalFrontend() { + return await this.update({ + externalFrontends: null as unknown as undefined, + }); + } + + public async deleteSupport() { + return await this.update({ + support: null as unknown as undefined, + }); + } + public async deleteWebhooks() { + return await this.update({ + webhookUrls: null as unknown as MarketplaceWebhookUrls, + }); + } + + public findFrontendFragment(anchor: FrontendFragmentAnchor) { + return this.frontendFragments.find((f) => f.anchor === anchor); + } + + public async generateSecret() { + return await config.behaviors.contributorExtension.generateExtensionSecret( + this.contributorId, + this.id, + ); + } + + public async getNextPossiblePriceChangeDate() { + const response = await config.behaviors.contributorExtension.updatePricing( + this.id, + this.contributorId, + { + priceInCents: 0, + dryRun: true, + }, + ); + + if ("nextPossiblePriceChange" in response) { + const raw = response.nextPossiblePriceChange; + + if (typeof raw === "string") { + return DateTime.fromISO(raw); + } + } + } + + public async getTargetCustomer(contextId: string) { + if (this.context === "project") { + const project = await Project.ofId(contextId).getDetailed(); + return project.customer; + } else { + return Customer.ofId(contextId); + } + } + + public async install(contextId: string, variantKey?: string) { + const context = required(this.context, "context"); + + const { id } = await config.behaviors.extensionInstance.create({ + consentedScopes: this.scopes ?? [], + variantKey: variantKey, + context, + extensionId: this.id, + contextId: contextId, + }); + + return new ExtensionInstance(id); + } + + public async updateAssetOrder(assetIds: string[]) { + return this.update({ assets: assetIds }); + } + + public async updateContext(context: MarketplaceContext) { + return await config.behaviors.contributorExtension.updateContext( + context, + this.contributorId, + this.id, + ); + } + + public async updateDetails( + title: string, + subTitleDE: string, + description: string, + detailedDescriptionDE?: string, + ) { + if (detailedDescriptionDE) { + return await this.update({ + detailedDescriptions: { + de: { + markdown: detailedDescriptionDE, + }, + }, + subTitle: { + de: subTitleDE, + }, + description: description, + name: title, + }); + } + return await this.update({ + detailedDescriptions: null as unknown as undefined, + subTitle: { + de: subTitleDE, + }, + description: description, + name: title, + }); + } + + public async updateExternalFrontend(url: string) { + return await this.update({ + externalFrontends: [ + { + name: "external_frontend", + url: url, + }, + ], + }); + } + public async updatePrice(price: Money) { + return await config.behaviors.contributorExtension.updatePricing( + this.id, + this.contributorId, + { + priceInCents: price.getAmount(), + dryRun: false, + }, + ); + } + + public async updatePricePlan( + priceVariants: PricePlanEditingVariant[], + isUpgradeAllowed: boolean, + isDowngradeAllowed: boolean, + ) { + const variants = priceVariants.map((v) => ({ + descriptionChangeType: v.descriptionChangeType, + isDeletionScheduled: v.isDeletionScheduled, + isBookingStopped: v.isBookingStopped, + priceInCents: v.price.getAmount(), + description: v.description, + name: v.name, + key: v.key, + })); + const data: ContributorExtensionUpdatePricingRequestData = { + pricePlan: { + isDowngradeAllowed: isDowngradeAllowed, + isUpgradeAllowed: isUpgradeAllowed, + variants, + }, + dryRun: false, + }; + + return await config.behaviors.contributorExtension.updatePricing( + this.id, + this.contributorId, + data, + ); + } + + public async updatePricePlanDryRun(priceVariants: PricePlanEditingVariant[]) { + const variants = priceVariants.map((v) => ({ + descriptionChangeType: v.descriptionChangeType, + isDeletionScheduled: v.isDeletionScheduled, + isBookingStopped: v.isBookingStopped, + priceInCents: v.price.getAmount(), + description: v.description, + name: v.name, + key: v.key, + })); + + const data: ContributorExtensionUpdatePricingRequestData = { + pricePlan: { + variants, + }, + dryRun: true, + }; + + return await config.behaviors.contributorExtension.updatePricing( + this.id, + this.contributorId, + data, + ); + } + + public async updateScopes(scopes: string[]) { + return await this.update({ scopes: scopes }); + } + + public async updateSupport(email: string, phone?: string) { + return await this.update({ + support: { + phone: phone && phone != "" ? phone : (null as unknown as undefined), + email: email, + }, + }); + } + + public async updateWebhooksMultiple( + extensionAddedToContext: string, + extensionInstanceUpdated: string, + extensionInstanceSecretRotated: string, + extensionInstanceRemovedFromContext: string, + ) { + return await this.update({ + webhookUrls: { + extensionInstanceRemovedFromContext: { + url: extensionInstanceRemovedFromContext, + }, + extensionInstanceSecretRotated: { + url: extensionInstanceSecretRotated, + }, + extensionInstanceUpdated: { + url: extensionInstanceUpdated, + }, + extensionAddedToContext: { + url: extensionAddedToContext, + }, + }, + }); + } + + public async updateWebhooksSingle(webhookUrl: string) { + return await this.update({ + webhookUrls: { + extensionInstanceRemovedFromContext: { + url: webhookUrl, + }, + extensionInstanceSecretRotated: { + url: webhookUrl, + }, + extensionInstanceUpdated: { + url: webhookUrl, + }, + extensionAddedToContext: { + url: webhookUrl, + }, + }, + }); + } +} + +export class ContributorExtensionDetailed extends ContributorExtensionCommon { + public override readonly data: ContributorExtensionData; + public constructor(data: ContributorExtensionData) { + super(data); + this.data = data; + } +} + +export class ContributorExtensionListItem extends ContributorExtensionCommon { + public override readonly data: ContributorExtensionListItemData; + public constructor(data: ContributorExtensionListItemData) { + super(data); + this.data = data; + } +} + +export class ContributorExtensionListQuery extends ListQueryModel { + public readonly contributor: Contributor | string; + public constructor( + contributor: Contributor | string, + query: ContributorExtensionListQueryData = {}, + ) { + super(query, { + dependencies: [extractId(contributor)], + }); + this.contributor = contributor; + } + + public async execute() { + const { totalCount, items } = + await config.behaviors.contributorExtension.list( + extractId(this.contributor), + this.query, + ); + + return new ContributorExtensionList( + extractId(this.contributor), + this.query, + items.map((d) => new ContributorExtensionListItem(d)), + totalCount, + ); + } + + public async getTotalCount() { + const { totalCount } = await this.refine({ limit: 1 }).execute(); + return totalCount; + } + + public refine(query: ContributorExtensionListQueryData) { + return new ContributorExtensionListQuery(this.contributor, { + ...this.query, + ...query, + }); + } +} + +export class ContributorExtensionList extends WithListData()( + ContributorExtensionListQuery, +) { + public override readonly items: readonly ContributorExtensionListItem[]; + public override readonly totalCount: number; + public constructor( + contributor: Contributor | string, + query: ContributorExtensionListQueryData, + extensions: ContributorExtensionListItem[], + totalCount: number, + ) { + super(contributor, query); + this.items = Object.freeze(extensions); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/marketplace/ContributorExtension/ContributorExtensionAssetAccessTokenProvider.ts b/packages/models/src/marketplace/ContributorExtension/ContributorExtensionAssetAccessTokenProvider.ts new file mode 100644 index 00000000..76df185f --- /dev/null +++ b/packages/models/src/marketplace/ContributorExtension/ContributorExtensionAssetAccessTokenProvider.ts @@ -0,0 +1,27 @@ +import type { ContributorExtension } from "./ContributorExtension.js"; +import type { FileAccessTokenProvider } from "../../file/index.js"; + +import { config } from "../../config/index.js"; + +export class ContributorExtensionAssetAccessTokenProvider implements FileAccessTokenProvider { + public readonly contributorExtension: ContributorExtension; + + public constructor(contributorExtension: ContributorExtension) { + this.contributorExtension = contributorExtension; + } + + public async createAssetUploadToken(assetType: "image" | "video") { + return await config.behaviors.contributorExtension.createAssetUploadToken( + this.contributorExtension.contributorId, + this.contributorExtension.id, + assetType, + ); + } + + public async createLogoUploadToken() { + return await config.behaviors.contributorExtension.createLogoUploadToken( + this.contributorExtension.contributorId, + this.contributorExtension.id, + ); + } +} diff --git a/packages/models/src/marketplace/ContributorExtension/ContributorExtensionLogoAccessTokenProvider.ts b/packages/models/src/marketplace/ContributorExtension/ContributorExtensionLogoAccessTokenProvider.ts new file mode 100644 index 00000000..a9cfe0e3 --- /dev/null +++ b/packages/models/src/marketplace/ContributorExtension/ContributorExtensionLogoAccessTokenProvider.ts @@ -0,0 +1,19 @@ +import type { ContributorExtension } from "./ContributorExtension.js"; +import type { FileAccessTokenProvider } from "../../file/index.js"; + +import { config } from "../../config/index.js"; + +export class ContributorExtensionLogoAccessTokenProvider implements FileAccessTokenProvider { + public readonly contributorExtension: ContributorExtension; + + public constructor(contributorExtension: ContributorExtension) { + this.contributorExtension = contributorExtension; + } + + public async createUploadToken() { + return await config.behaviors.contributorExtension.createLogoUploadToken( + this.contributorExtension.contributorId, + this.contributorExtension.id, + ); + } +} diff --git a/packages/models/src/marketplace/ContributorExtension/PricePlanEditingVariant.ts b/packages/models/src/marketplace/ContributorExtension/PricePlanEditingVariant.ts new file mode 100644 index 00000000..58c4d463 --- /dev/null +++ b/packages/models/src/marketplace/ContributorExtension/PricePlanEditingVariant.ts @@ -0,0 +1,54 @@ +import { DateTime } from "luxon"; + +import type { ExtensionPricePlanVariantDetailed } from "../Extension/index.js"; +import type { PricePlanEditingVariantData } from "./types.js"; + +import { DataModel } from "../../base/index.js"; +import { Money } from "../../common/index.js"; + +export class PricePlanEditingVariant extends DataModel { + public readonly deletionDeadline?: DateTime; + public readonly description?: string; + public readonly descriptionChangeType: + "FEATURE_SET_UNCHANGED" | "FEATURE_SET_MODIFIED"; + public readonly isBookingStopped: boolean; + public readonly isDeletionScheduled: boolean; + public readonly isNew: boolean; + public readonly key: string; + public readonly name?: string; + public readonly price: Money; + + public constructor(data: PricePlanEditingVariantData, isNew: boolean) { + super(data); + this.description = data.description; + this.key = data.key; + this.name = data.name; + this.price = Money({ amount: data.priceInCents, currency: "EUR" }); + this.descriptionChangeType = + data.descriptionChangeType ?? "FEATURE_SET_UNCHANGED"; + this.isNew = isNew; + this.isBookingStopped = data.isBookingStopped ?? isNew; + this.isDeletionScheduled = data.isDeletionScheduled ?? isNew; + this.deletionDeadline = data.deletionDeadline + ? DateTime.fromISO(data.deletionDeadline) + : undefined; + } + + public static fromPricePlanVariant( + variant: ExtensionPricePlanVariantDetailed, + ) { + return new PricePlanEditingVariant( + { + deletionDeadline: variant.deletionDeadline?.toISO() ?? undefined, + isDeletionScheduled: variant.isDeletionScheduled, + descriptionChangeType: "FEATURE_SET_UNCHANGED", + isBookingStopped: variant.isBookingStopped, + priceInCents: variant.price.getAmount(), + description: variant.description, + name: variant.name, + key: variant.key, + }, + false, + ); + } +} diff --git a/packages/models/src/marketplace/ContributorExtension/behaviors/api.ts b/packages/models/src/marketplace/ContributorExtension/behaviors/api.ts new file mode 100644 index 00000000..1951d964 --- /dev/null +++ b/packages/models/src/marketplace/ContributorExtension/behaviors/api.ts @@ -0,0 +1,312 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { ContributorExtensionUpdatePricingRequestData } from "../types.js"; +import type { ContributorExtensionBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount } from "../../../base/index.js"; +import { ValidationError } from "../../../errors/index.js"; + +export const apiContributorExtensionBehaviors = ( + client: MittwaldAPIV2Client, +): ContributorExtensionBehaviors => ({ + update: async (contributorId, extensionId, data) => { + const response = await client.marketplace.extensionPatchExtension({ + contributorId, + extensionId, + data, + }); + + const validationErrors = ValidationError.fromResponse(response); + if (validationErrors) { + const mappedErrors = validationErrors.errors.map((e) => { + if (e.params?.["SecretRotated"]) { + return { + path: "extensionInstanceSecretRotated", + type: "invalid", + }; + } + if (e.params?.["InstanceRemovedFromContext"]) { + return { + path: "extensionInstanceRemovedFromContext", + type: "invalid", + }; + } + if (e.params?.["ExtensionAddedToContext"]) { + return { + path: "extensionAddedToContext", + type: "invalid", + }; + } + if (e.params?.["InstanceUpdated"]) { + return { + path: "extensionInstanceUpdated", + type: "invalid", + }; + } + + const pathStr = Array.isArray(e.path) ? e.path.join(".") : e.path; + + return { + ...e, + path: + e.path == "frontendFragments" + ? "url" + : e.path === "webhookUrls" + ? "oneHookUrl" + : pathStr.includes("phone") + ? "phone" + : pathStr.includes("mail") + ? "email" + : e.path, + }; + }); + throw new ValidationError(mappedErrors); + } + + validateResponse(response, 200); + }, + + updatePricing: async ( + extensionId: string, + contributorId: string, + data: ContributorExtensionUpdatePricingRequestData, + ) => { + let response; + + if ("pricePlan" in data) { + response = await client.marketplace.extensionUpdateExtensionPricing({ + data: { + pricePlan: data.pricePlan, + dryRun: data.dryRun, + }, + contributorId, + extensionId, + }); + } else if ("priceInCents" in data) { + response = await client.marketplace.extensionUpdateExtensionPricing({ + data: { + priceInCents: data.priceInCents, + dryRun: data.dryRun, + }, + contributorId, + extensionId, + }); + } else { + throw Error("Neither price with money value nor pricePlan were given."); + } + + if (response.status === 412) { + const rawMessage = + typeof response.data.message === "string" + ? response.data.message + : "Precondition Failed"; + + const match = /\b\d{2}\.\d{2}\.\d{4}\b/.exec(rawMessage); + const extractedDate = match?.[0]; + + throw new ValidationError({ + meta: { + date: extractedDate, + }, + message: "preconditionFailed", + type: "preconditionFailed", + path: "price", + }); + } + + validateResponse(response, 200, { + validationError: { + pathMappings: { + "*priceInCents": "priceInEuro", + "*name": "name", + "*key": "key", + }, + }, + }); + + return response.data; + }, + + requestVerification: async (contributorId, extensionId) => { + const response = + await client.marketplace.extensionRequestExtensionVerification({ + contributorId, + extensionId, + }); + + validateResponse(response, 204, { + validationError: { + typeMappings: { + "*": (e) => + e.message?.includes("verification failed for field 'name'") + ? "nameAlreadyTaken" + : undefined, + }, + pathMappings: { name: "root" }, + }, + }); + }, + + createAssetUploadToken: async ( + contributorId: string, + extensionId: string, + assetType: "image" | "video", + ) => { + const response = await client.marketplace.extensionRequestAssetUpload({ + data: { assetType }, + contributorId, + extensionId, + }); + validateResponse(response, 200); + + return { + token: response.data.assetRefId, + rules: response.data.rules, + }; + }, + + deleteExtensionSecret: async ( + contributorId: string, + extensionId: string, + secretId: string, + ) => { + const response = + await client.marketplace.extensionInvalidateExtensionSecret({ + contributorId: contributorId, + extensionSecretId: secretId, + extensionId: extensionId, + }); + + validateResponse(response, 204); + }, + + createLogoUploadToken: async (contributorId: string, extensionId: string) => { + const response = await client.marketplace.extensionRequestLogoUpload({ + contributorId, + extensionId, + }); + validateResponse(response, 200); + + return { + token: response.data.logoRefId, + rules: response.data.rules, + }; + }, + + unpublish: async (contributorId, extensionId, reason) => { + const response = + await client.marketplace.extensionSetExtensionPublishedState({ + data: { + published: false, + reason, + }, + contributorId, + extensionId, + }); + + validateResponse(response, 200); + }, + + list: async (contributorId, query) => { + const response = await client.marketplace.extensionListOwnExtensions({ + queryParameters: query, + contributorId, + }); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + find: async (contributorId: string, extensionId: string) => { + const response = await client.marketplace.extensionGetOwnExtension({ + contributorId, + extensionId, + }); + + if (response.status === 200) { + return response.data; + } + + validateResponse(response, 404); + }, + + deleteExtensionAsset: async ( + contributorId: string, + extensionId: string, + assetRefId: string, + ) => { + const response = await client.marketplace.extensionRemoveAsset({ + contributorId, + extensionId, + assetRefId, + }); + + validateResponse(response, 204); + }, + + generateExtensionSecret: async ( + contributorId: string, + extensionId: string, + ) => { + const response = await client.marketplace.extensionGenerateExtensionSecret({ + contributorId, + extensionId, + }); + validateResponse(response, 200); + + return response.data; + }, + + publish: async (contributorId, extensionId) => { + const response = + await client.marketplace.extensionSetExtensionPublishedState({ + data: { + published: true, + }, + contributorId, + extensionId, + }); + + validateResponse(response, 200); + }, + + updateContext: async (context, contributorId, extensionId) => { + const response = await client.marketplace.extensionChangeContext({ + data: { context }, + contributorId, + extensionId, + }); + + validateResponse(response, 200); + }, + + create: async (contributorId, name) => { + const response = await client.marketplace.extensionRegisterExtension({ + data: { + name, + }, + contributorId, + }); + validateResponse(response, 201); + return response.data; + }, + + delete: async (contributorId, extensionId) => { + const response = await client.marketplace.extensionDeleteExtension({ + contributorId, + extensionId, + }); + + validateResponse(response, 204); + }, + + getPossibleScopes: async () => { + const response = await client.marketplace.extensionListScopes(); + validateResponse(response, 200); + + return response.data; + }, +}); diff --git a/packages/models/src/marketplace/ContributorExtension/behaviors/index.ts b/packages/models/src/marketplace/ContributorExtension/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/marketplace/ContributorExtension/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/marketplace/ContributorExtension/behaviors/types.ts b/packages/models/src/marketplace/ContributorExtension/behaviors/types.ts new file mode 100644 index 00000000..4595271f --- /dev/null +++ b/packages/models/src/marketplace/ContributorExtension/behaviors/types.ts @@ -0,0 +1,89 @@ +import type { MarketplaceContext } from "../../ExtensionInstance/types.js"; +import type { FileUploadTokenData } from "../../../file/index.js"; +import type { QueryResponseData } from "../../../base/index.js"; +import type { + ContributorExtensionUpdatePricingRequestData, + ContributorExtensionUpdateRequestData, + ContributorExtensionListQueryData, + MarketplaceGenerateSecretResponse, + ContributorExtensionListItemData, + UpdatePricingResponseData, + ContributorExtensionData, +} from "../types.js"; + +export interface ContributorExtensionBehaviors { + updatePricing: ( + extensionId: string, + contributorId: string, + data: ContributorExtensionUpdatePricingRequestData, + ) => Promise; + + list: ( + contributorId: string, + query: ContributorExtensionListQueryData, + ) => Promise>; + + createAssetUploadToken: ( + contributorId: string, + extensionId: string, + assetType: "image" | "video", + ) => Promise; + + update: ( + contributorId: string, + extensionId: string, + data: ContributorExtensionUpdateRequestData, + ) => Promise; + + generateExtensionSecret: ( + contributorId: string, + extensionId: string, + ) => Promise; + + updateContext: ( + context: MarketplaceContext, + contributorId: string, + extensionId: string, + ) => Promise; + + deleteExtensionSecret: ( + contributorId: string, + extensionId: string, + secretId: string, + ) => Promise; + + deleteExtensionAsset: ( + contributorId: string, + extensionId: string, + assetId: string, + ) => Promise; + + find: ( + contributorId: string, + extensionId: string, + ) => Promise; + + createLogoUploadToken: ( + contributorId: string, + extensionId: string, + ) => Promise; + + unpublish: ( + contributorId: string, + extensionId: string, + reason: string, + ) => Promise; + + requestVerification: ( + contributorId: string, + extensionId: string, + ) => Promise; + + create: (contributorId: string, name: string) => Promise<{ id: string }>; + + publish: (contributorId: string, extensionId: string) => Promise; + + delete: (contributorId: string, extensionId: string) => Promise; + + getPossibleScopes: () => Promise<{ name: string }[]>; +} diff --git a/packages/models/src/marketplace/ContributorExtension/index.ts b/packages/models/src/marketplace/ContributorExtension/index.ts new file mode 100644 index 00000000..f54678c9 --- /dev/null +++ b/packages/models/src/marketplace/ContributorExtension/index.ts @@ -0,0 +1,3 @@ +export * from "./ContributorExtension.js"; +export * from "./PricePlanEditingVariant.js"; +export * from "./types.js"; diff --git a/packages/models/src/marketplace/ContributorExtension/types.ts b/packages/models/src/marketplace/ContributorExtension/types.ts new file mode 100644 index 00000000..034fa614 --- /dev/null +++ b/packages/models/src/marketplace/ContributorExtension/types.ts @@ -0,0 +1,46 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; +import type { DateTime } from "luxon"; +export type ContributorExtensionData = + MittwaldAPIV2.Operations.ExtensionGetOwnExtension.ResponseData; + +export type ContributorExtensionUpdateRequestData = + MittwaldAPIV2.Operations.ExtensionPatchExtension.RequestData; + +export type ContributorExtensionUpdatePricingRequestData = + MittwaldAPIV2.Operations.ExtensionUpdateExtensionPricing.RequestData; + +export type ContributorExtensionListItemData = + MittwaldAPIV2.Operations.ExtensionListOwnExtensions.ResponseData[number]; + +export type PricePlanEditingVariantData = + MittwaldAPIV2.Components.Schemas.ExtensionVariant; + +export type ContributorExtensionListQueryData = + MittwaldAPIV2.Paths.V2ContributorsContributorIdExtensions.Get.Parameters.Query; + +export type MarketplaceExtensionDeprecation = + MittwaldAPIV2.Components.Schemas.MarketplaceExtensionDeprecation; + +export type MarketplaceWebhookUrls = + MittwaldAPIV2.Components.Schemas.MarketplaceWebhookUrls; + +export type MarketplaceWebhookUrl = + MittwaldAPIV2.Components.Schemas.MarketplaceWebhookUrl; + +export type MarketplaceExtendedSupportMeta = + MittwaldAPIV2.Components.Schemas.MarketplaceSupportMeta & { + inherited: boolean; + }; + +export type MarketplaceWebhookType = keyof MarketplaceWebhookUrls; + +export type UpdatePricingResponseData = + MittwaldAPIV2.Operations.ExtensionUpdateExtensionPricing.ResponseData; + +export interface ExtensionSecret { + usableUntil?: DateTime; + secretId: string; +} + +export type MarketplaceGenerateSecretResponse = + MittwaldAPIV2.Operations.ExtensionGenerateExtensionSecret.ResponseData; diff --git a/packages/models/src/marketplace/Extension/Extension.test.ts b/packages/models/src/marketplace/Extension/Extension.test.ts new file mode 100644 index 00000000..56f21710 --- /dev/null +++ b/packages/models/src/marketplace/Extension/Extension.test.ts @@ -0,0 +1,235 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { buildExtensionListItemData } from "../../testing/builders/buildExtensionListItemData.js"; +import { buildExtensionData } from "../../testing/builders/buildExtensionData.js"; +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { AggregateMetaData, LocalizedText } from "../../common/index.js"; +import { ListQueryModel, ReferenceModel } from "../../base/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { + ExtensionListQuery, + ExtensionDetailed, + ExtensionListItem, + ExtensionCommon, + ExtensionList, + Extension, +} from "./Extension.js"; + +afterEach(resetBehaviors); + +describe("reference and delegation", () => { + test("find delegates and materializes a detailed extension", async () => { + const find = vi.fn().mockResolvedValue(buildExtensionData({ id: "e-1" })); + installBehaviors({ extension: { find } }); + + const extension = await Extension.find("e-1"); + + expect(find).toHaveBeenCalledWith("e-1"); + expect(extension).toBeInstanceOf(ExtensionDetailed); + expect(extension?.id).toBe("e-1"); + }); + + test("find returns undefined when the behavior does", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ extension: { find } }); + + await expect(Extension.find("missing")).resolves.toBeUndefined(); + }); + + test("get returns a found detailed extension", async () => { + installBehaviors({ + extension: { + find: vi.fn().mockResolvedValue(buildExtensionData({ id: "e-1" })), + }, + }); + + const extension = await Extension.get("e-1"); + + expect(extension).toBeInstanceOf(ExtensionDetailed); + expect(extension.id).toBe("e-1"); + }); +}); + +describe("get on a missing extension", () => { + test("throws ObjectNotFoundError", async () => { + installBehaviors({ + extension: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(Extension.get("missing")).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); +}); + +test("exposes data and derived values", () => { + const extension = new ExtensionDetailed( + buildExtensionData({ + assets: [ + { assetType: "image", id: "asset-2", index: 2 }, + { assetType: "image", id: "asset-1", index: 1 }, + ], + contributorId: "c-1", + logoRefId: "logo-1", + }), + ); + + expect(extension.name).toBe("Test Extension"); + expect(extension.context).toBe("project"); + expect(extension.contributor.id).toBe("c-1"); + expect(extension.logo?.id).toBe("logo-1"); + expect(extension.assets.map(({ id }) => id)).toEqual(["asset-1", "asset-2"]); + expect(extension.amountOfInstances).toBe(3); + expect(extension.subTitle).toBeInstanceOf(LocalizedText); + expect(extension.subTitle.getText()).toBe("Untertitel"); + expect(extension.createdAt?.year).toBe(2024); +}); + +describe("list query", () => { + test("passes the query through and materializes list items", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildExtensionListItemData()], + totalCount: 7, + }); + installBehaviors({ extension: { list } }); + + const result = await Extension.query().execute(); + + expect(list).toHaveBeenCalledWith({}); + expect(result).toBeInstanceOf(ExtensionList); + expect(result.items[0]).toBeInstanceOf(ExtensionListItem); + expect(result.totalCount).toBe(7); + }); + + test("preserves an explicit limit", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 0, items: [] }); + installBehaviors({ extension: { list } }); + + await Extension.query({ limit: 5 }).execute(); + + expect(list).toHaveBeenCalledWith(expect.objectContaining({ limit: 5 })); + }); + + test("getTotalCount returns the behavior total", async () => { + installBehaviors({ + extension: { + list: vi.fn().mockResolvedValue({ totalCount: 12, items: [] }), + }, + }); + + await expect(Extension.query().getTotalCount()).resolves.toBe(12); + }); +}); + +test("preserves ghostmaker identity chains", async () => { + const item = new ExtensionListItem(buildExtensionListItemData()); + expect(item).toBeInstanceOf(ExtensionListItem); + expect(item).toBeInstanceOf(ExtensionCommon); + expect(item).toBeInstanceOf(Extension); + expect(item).toBeInstanceOf(ReferenceModel); + expect(item.data).toBeDefined(); + + installBehaviors({ + extension: { + list: vi.fn().mockResolvedValue({ totalCount: 0, items: [] }), + }, + }); + const result = await Extension.query().execute(); + expect(result).toBeInstanceOf(ExtensionList); + expect(result).toBeInstanceOf(ExtensionListQuery); + expect(result).toBeInstanceOf(ListQueryModel); + expect(result.items).toBeDefined(); +}); +describe("common variant and idempotency", () => { + test("findCommon delegates to the detailed variant from a bare reference", async () => { + const find = vi.fn().mockResolvedValue(buildExtensionData({ id: "e-1" })); + installBehaviors({ extension: { find } }); + + const common = await Extension.ofId("e-1").findCommon(); + + expect(find).toHaveBeenCalledWith("e-1"); + expect(common).toBeInstanceOf(ExtensionCommon); + expect(common?.id).toBe("e-1"); + }); + + test("findCommon returns undefined when the behavior finds nothing", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ extension: { find } }); + + await expect( + Extension.ofId("missing").findCommon(), + ).resolves.toBeUndefined(); + }); + + test("getCommon delegates and throws when the extension is missing", async () => { + installBehaviors({ + extension: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(Extension.ofId("missing").getCommon()).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("getCommon on an already-common model returns itself without re-fetching", async () => { + const find = vi.fn(); + installBehaviors({ extension: { find } }); + const item = new ExtensionListItem( + buildExtensionListItemData({ id: "e-2" }), + ); + + const common = await item.getCommon(); + + expect(common).toBe(item); + expect(find).not.toHaveBeenCalled(); + }); + + test("findCommon on an already-common model returns itself without re-fetching", async () => { + const find = vi.fn(); + installBehaviors({ extension: { find } }); + const detailed = new ExtensionDetailed(buildExtensionData({ id: "e-3" })); + + const common = await detailed.findCommon(); + + expect(common).toBe(detailed); + expect(find).not.toHaveBeenCalled(); + }); +}); + +describe("aggregate metadata wiring", () => { + test("pins the extension aggregate identity", () => { + expect(Extension.aggregateMetaData).toBeInstanceOf(AggregateMetaData); + expect(Extension.aggregateMetaData.domain).toBe("extension"); + expect(Extension.aggregateMetaData.aggregate).toBe("extension"); + }); +}); + +describe("absent optional source data", () => { + test("omits the logo, description, fragments and external frontends when the source has none", () => { + const extension = new ExtensionDetailed( + buildExtensionData({ description: undefined, logoRefId: undefined }), + ); + + expect(extension.logo).toBeUndefined(); + expect(extension.description).toBeUndefined(); + expect(extension.frontendFragments).toEqual([]); + expect(extension.externalFrontends).toEqual([]); + expect( + extension.findFrontendFragment( + "/projects/project/menu/section/extensions/item", + ), + ).toBeUndefined(); + }); +}); diff --git a/packages/models/src/marketplace/Extension/Extension.ts b/packages/models/src/marketplace/Extension/Extension.ts new file mode 100644 index 00000000..895fb62f --- /dev/null +++ b/packages/models/src/marketplace/Extension/Extension.ts @@ -0,0 +1,257 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; + +import type { MarketplaceContext } from "../ExtensionInstance/index.js"; +import type { ExtensionPricePlan } from "./ExtensionPricePlan.js"; +import type { + MarketplaceDetailedDescriptionsFormat, + ExtensionListQueryData, + FrontendFragmentAnchor, + MarketplaceSupportMeta, + ExtensionListItemData, + ExternalFrontend, + ExtensionData, +} from "./types.js"; + +import { extensionVariantsPricePlanFactory } from "./ExtensionPricePlan.js"; +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { AggregateMetaData, LocalizedText } from "../../common/index.js"; +import { ContributorExtension } from "../ContributorExtension/index.js"; +import { ExtensionInstance } from "../ExtensionInstance/index.js"; +import { FrontendFragment } from "./FrontendFragment.js"; +import { ExtensionAsset } from "./ExtensionAsset.js"; +import { frontendFragmentAnchors } from "./types.js"; +import { File } from "../../file/File/internal.js"; +import { Contributor } from "../Contributor/index.js"; +import { Customer } from "../../customer/index.js"; +import { Project } from "../../project/index.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + required, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "Extension", +}) +export class Extension extends ReferenceModel { + public static aggregateMetaData = new AggregateMetaData( + "extension", + "extension", + ); + + public static async find(id: string) { + const data = await config.behaviors.extension.find(id); + + if (data) { + return new ExtensionDetailed(data); + } + } + + public static async get(id: string) { + const extension = await this.find(id); + assertObjectFound(extension, Extension, id); + return extension; + } + + public static isValidAnchor = ( + anchor: string, + ): anchor is FrontendFragmentAnchor => { + return frontendFragmentAnchors.includes(anchor as FrontendFragmentAnchor); + }; + + public static ofId(id: string) { + return new Extension(id); + } + + public static query(query: ExtensionListQueryData = {}) { + return new ExtensionListQuery(query); + } + + public async findCommon(): Promise { + return this instanceof ExtensionCommon ? this : this.findDetailed(); + } + + public async findDetailed(): Promise { + return Extension.find(this.id); + } + + public async getCommon(): Promise { + return this instanceof ExtensionCommon ? this : this.getDetailed(); + } + + public async getDetailed(): Promise { + return Extension.get(this.id); + } +} + +export class ExtensionCommon extends WithData< + ExtensionListItemData | ExtensionData +>()(Extension) { + public readonly amountOfInstances?: number; + public readonly assets: ExtensionAsset[]; + public readonly context?: MarketplaceContext; + public readonly contributor: Contributor; + public readonly createdAt?: DateTime; + public override readonly data: ExtensionListItemData | ExtensionData; + public readonly description?: string; + public readonly detailedDescription: LocalizedText; + public readonly externalFrontends: ExternalFrontend[]; + public readonly frontendFragments: FrontendFragment[]; + public readonly logo?: File; + public readonly name: string; + public readonly pricing: ExtensionPricePlan; + public readonly scopes: string[]; + public readonly subTitle: LocalizedText; + public readonly support?: MarketplaceSupportMeta; + + public get hasFrontends(): boolean { + return ( + this.frontendFragments.length > 0 || this.externalFrontends.length > 0 + ); + } + + public constructor(data: ExtensionListItemData | ExtensionData) { + super(data.id); + this.data = data; + this.contributor = Contributor.ofId(data.contributorId); + this.name = data.name; + this.description = data.description; + this.detailedDescription = new LocalizedText(data.detailedDescriptions); + this.subTitle = new LocalizedText(data.subTitle); + this.context = data.context; + this.scopes = data.scopes; + this.logo = data.logoRefId ? File.ofId(data.logoRefId) : undefined; + this.assets = data.assets + .sort((a, b) => a.index - b.index) + .map((a) => new ExtensionAsset(a)); + this.amountOfInstances = this.data.statistics.amountOfInstances; + this.pricing = extensionVariantsPricePlanFactory( + this, + data.pricing, + data.pricingDetails, + ); + this.frontendFragments = data.frontendFragments + ? Object.entries(data.frontendFragments) + .filter(([key]) => Extension.isValidAnchor(key)) + .map( + ([key, value]) => + new FrontendFragment( + key as FrontendFragmentAnchor, + value, + this.name, + ContributorExtension.ofId(this.contributor.id, this.id), + ), + ) + : []; + this.support = data.support; + this.createdAt = + "createdAt" in data ? DateTime.fromISO(data.createdAt) : undefined; + + this.externalFrontends = data.externalFrontends ?? []; + } + + public findFrontendFragment(anchor: FrontendFragmentAnchor) { + return this.frontendFragments.find((f) => f.anchor === anchor); + } + + public async getTargetCustomer(contextId: string) { + if (this.context === "project") { + const project = await Project.ofId(contextId).getDetailed(); + return project.customer; + } else { + return Customer.ofId(contextId); + } + } + + public async install(contextId: string, variantKey?: string) { + const context = required(this.context, "context"); + + const { id } = await config.behaviors.extensionInstance.create({ + consentedScopes: this.scopes, + variantKey: variantKey, + context, + extensionId: this.id, + contextId: contextId, + }); + + return new ExtensionInstance(id); + } + + public async order(contextId: string, variantKey?: string) { + const context = required(this.context, "context"); + + return await config.behaviors.extension.order(this.id, { + consentedScopes: this.scopes, + ...(context === "customer" + ? { customerId: contextId } + : { projectId: contextId }), + variantKey: variantKey, + }); + } +} + +export class ExtensionDetailed extends ExtensionCommon { + public override readonly data: ExtensionData; + public constructor(data: ExtensionData) { + super(data); + this.data = data; + } +} + +export class ExtensionListItem extends ExtensionCommon { + public override readonly data: ExtensionListItemData; + public constructor(data: ExtensionListItemData) { + super(data); + this.data = data; + } +} + +export class ExtensionListQuery extends ListQueryModel { + public constructor(query: ExtensionListQueryData = {}) { + super(query); + } + + public async execute() { + const { totalCount, items } = await config.behaviors.extension.list( + this.query, + ); + + return new ExtensionList( + this.query, + items.map((d) => new ExtensionListItem(d)), + totalCount, + ); + } + + public async getTotalCount() { + const { totalCount } = await this.refine({ limit: 1 }).execute(); + return totalCount; + } + + public refine(query: ExtensionListQueryData) { + return new ExtensionListQuery({ + ...this.query, + ...query, + }); + } +} + +export class ExtensionList extends WithListData()( + ExtensionListQuery, +) { + public override readonly items: readonly ExtensionListItem[]; + public override readonly totalCount: number; + public constructor( + query: ExtensionListQueryData, + extensions: ExtensionListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(extensions); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/marketplace/Extension/ExtensionAsset.ts b/packages/models/src/marketplace/Extension/ExtensionAsset.ts new file mode 100644 index 00000000..6fed9443 --- /dev/null +++ b/packages/models/src/marketplace/Extension/ExtensionAsset.ts @@ -0,0 +1,19 @@ +import type { ExtensionAssetData } from "./types.js"; + +import { File } from "../../file/File/internal.js"; +import { DataModel } from "../../base/index.js"; + +export class ExtensionAsset extends DataModel { + public readonly file: File; + public readonly id: string; + public readonly index: number; + public readonly type: string; + + public constructor(data: ExtensionAssetData) { + super(data); + this.file = File.ofId(data.id); + this.type = data.assetType; + this.id = data.id; + this.index = data.index; + } +} diff --git a/packages/models/src/marketplace/Extension/ExtensionPricePlan.ts b/packages/models/src/marketplace/Extension/ExtensionPricePlan.ts new file mode 100644 index 00000000..3b2d576a --- /dev/null +++ b/packages/models/src/marketplace/Extension/ExtensionPricePlan.ts @@ -0,0 +1,156 @@ +import type { ContributorExtensionDetailed } from "../ContributorExtension/index.js"; +import type { ExtensionDetailed } from "./Extension.js"; +import type { + ExtensionPricePlanVariantData, + MarketplacePricePlanDetails, + ExtensionPricePlanData, +} from "./types.js"; + +import { ExtensionPricePlanVariantDetailed } from "./ExtensionPricePlanVariant.js"; +import { Money } from "../../common/index.js"; + +type ExtensionPricePlanVariants = [ + ExtensionPricePlanVariantDetailed, + ExtensionPricePlanVariantDetailed, + ...ExtensionPricePlanVariantDetailed[], +]; + +export const extensionVariantsPricePlanFactory = ( + extension: ContributorExtensionDetailed | ExtensionDetailed, + data: ExtensionPricePlanData = [], + pricingDetails?: MarketplacePricePlanDetails, +) => { + if (data.length === 0) { + return new ExtensionFreePricePlan(extension, data); + } + + const bookableData = data.filter((d) => !d.isBookingStopped); + + if (bookableData.length === 0) { + return new ExtensionNotBookablePricePlan(extension, data, pricingDetails); + } + + if (bookableData.length === 1) { + if (bookableData[0]!.priceInCents === 0) { + return new ExtensionFreePricePlan( + extension, + data, + bookableData[0], + pricingDetails, + ); + } + return new ExtensionSinglePricePlan( + extension, + Money({ amount: bookableData[0]!.priceInCents, currency: "EUR" }), + data, + bookableData[0]!, + pricingDetails, + ); + } + + return new ExtensionVariantsPricePlan(extension, data, pricingDetails); +}; + +export abstract class ExtensionPricePlan { + public readonly allVariants: ExtensionPricePlanVariantDetailed[]; + public readonly extension: ContributorExtensionDetailed | ExtensionDetailed; + public readonly pricingDetails?: MarketplacePricePlanDetails; + + public constructor( + extension: ContributorExtensionDetailed | ExtensionDetailed, + data: ExtensionPricePlanVariantData[], + pricingDetails?: MarketplacePricePlanDetails, + ) { + this.extension = extension; + this.allVariants = data + .sort((a, b) => a.priceInCents - b.priceInCents) + .map((d) => new ExtensionPricePlanVariantDetailed(this, d)); + this.pricingDetails = pricingDetails; + } + + public getVariant( + key: string, + ): ExtensionPricePlanVariantDetailed | undefined { + return this.allVariants.find((variant) => variant.key === key); + } +} + +export class ExtensionFreePricePlan extends ExtensionPricePlan { + public readonly freeVariant?: ExtensionPricePlanVariantDetailed; + public constructor( + extension: ContributorExtensionDetailed | ExtensionDetailed, + data: ExtensionPricePlanVariantData[], + freeVariant?: ExtensionPricePlanVariantData, + pricingDetails?: MarketplacePricePlanDetails, + ) { + super(extension, data, pricingDetails); + if (freeVariant) { + this.freeVariant = new ExtensionPricePlanVariantDetailed( + this, + freeVariant, + ); + } + } +} + +export class ExtensionNotBookablePricePlan extends ExtensionPricePlan { + public constructor( + extension: ContributorExtensionDetailed | ExtensionDetailed, + data: ExtensionPricePlanVariantData[], + pricingDetails?: MarketplacePricePlanDetails, + ) { + super(extension, data, pricingDetails); + } +} + +export class ExtensionVariantsPricePlan extends ExtensionPricePlan { + public readonly bookableVariants: ExtensionPricePlanVariants; + + public constructor( + extension: ContributorExtensionDetailed | ExtensionDetailed, + data: ExtensionPricePlanVariantData[], + pricingDetails?: MarketplacePricePlanDetails, + ) { + super(extension, data, pricingDetails); + + this.bookableVariants = this.allVariants.filter( + (variant) => !variant.isBookingStopped, + ) as ExtensionPricePlanVariants; + } + + public getBookableVariant( + key: string, + ): ExtensionPricePlanVariantDetailed | undefined { + return this.bookableVariants.find((variant) => variant.key === key); + } + + public getCheapestBookableVariant(): ExtensionPricePlanVariantDetailed { + return this.bookableVariants.reduce((min, v) => + v.price.getAmount() < min.price.getAmount() ? v : min, + ); + } +} + +export class ExtensionSinglePricePlan extends ExtensionPricePlan { + public readonly bookableVariant: ExtensionPricePlanVariantDetailed; + public readonly price: Money; + + public constructor( + extension: ContributorExtensionDetailed | ExtensionDetailed, + price: Money, + data: ExtensionPricePlanVariantData[], + bookableVariant: ExtensionPricePlanVariantData, + pricingDetails?: MarketplacePricePlanDetails, + ) { + super(extension, data, pricingDetails); + this.price = price; + this.bookableVariant = new ExtensionPricePlanVariantDetailed( + this, + bookableVariant, + ); + } + + public getBookableVariant(): ExtensionPricePlanVariantDetailed | undefined { + return this.bookableVariant; + } +} diff --git a/packages/models/src/marketplace/Extension/ExtensionPricePlanVariant.ts b/packages/models/src/marketplace/Extension/ExtensionPricePlanVariant.ts new file mode 100644 index 00000000..1ae5fd73 --- /dev/null +++ b/packages/models/src/marketplace/Extension/ExtensionPricePlanVariant.ts @@ -0,0 +1,126 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; + +import type { ContributorExtension } from "../ContributorExtension/index.js"; +import type { ExtensionPricePlan } from "./ExtensionPricePlan.js"; +import type { + ExtensionPricePlanVariantBaseData, + ExtensionPricePlanVariantData, +} from "./types.js"; + +import { ReferenceModel, DataModel, WithData } from "../../base/index.js"; +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { Extension } from "./Extension.js"; +import { Money } from "../../common/index.js"; + +export class ExtensionPricePlanVariantBase extends DataModel { + public readonly deletionDeadline?: DateTime; + public readonly description?: string; + public readonly isBookingStopped?: boolean; + public readonly isDeletionScheduled?: boolean; + public readonly key: string; + public readonly name?: string; + public readonly price: Money; + + public constructor(data: ExtensionPricePlanVariantBaseData) { + super(data); + this.key = data.key; + this.description = data.description; + this.name = data.name; + this.price = Money({ amount: data.priceInCents, currency: "EUR" }); + this.isBookingStopped = data.isBookingStopped; + this.isDeletionScheduled = data.isDeletionScheduled; + this.deletionDeadline = data.deletionDeadline + ? DateTime.fromISO(data.deletionDeadline) + : undefined; + } +} + +@GhostMakerModel({ + name: "ExtensionPricePlanVariant", +}) +export class ExtensionPricePlanVariant extends ReferenceModel { + public readonly extension: ContributorExtension | Extension; + public readonly key: string; + + public constructor(extension: ContributorExtension | Extension, key: string) { + super(`${extension.id}::${key}`); + this.extension = extension; + this.key = key; + } + + public static async find(extensionId: string, key: string) { + const extension = await Extension.get(extensionId); + if (!extension.pricing) { + return undefined; + } + return extension.pricing.getVariant(key); + } + + public static async get(extensionId: string, key: string) { + const detailed = await ExtensionPricePlanVariant.find(extensionId, key); + assertObjectFound( + detailed, + ExtensionPricePlanVariant, + `${extensionId}::${key}`, + ); + return detailed; + } + + public static ofId(extension: Extension | string, key: string) { + return new ExtensionPricePlanVariant( + typeof extension === "string" ? Extension.ofId(extension) : extension, + key, + ); + } + + public async findCommon() { + return this instanceof ExtensionPricePlanVariantDetailed + ? this + : this.findDetailed(); + } + + public async findDetailed() { + return ExtensionPricePlanVariant.find(this.extension.id, this.key); + } + + public async getCommon() { + return this instanceof ExtensionPricePlanVariantDetailed + ? this + : this.getDetailed(); + } + + public async getDetailed() { + return ExtensionPricePlanVariant.get(this.extension.id, this.key); + } +} + +export class ExtensionPricePlanVariantDetailed extends WithData()( + ExtensionPricePlanVariant, +) { + public override readonly data: ExtensionPricePlanVariantData; + public readonly deletionDeadline?: DateTime; + public readonly description?: string; + public readonly isBookingStopped?: boolean; + public readonly isDeletionScheduled?: boolean; + public readonly name?: string; + public readonly plan: ExtensionPricePlan; + public readonly price: Money; + + public constructor( + plan: ExtensionPricePlan, + data: ExtensionPricePlanVariantData, + ) { + super(plan.extension, data.key); + this.data = data; + this.description = data.description; + this.name = data.name; + this.price = Money({ amount: data.priceInCents, currency: "EUR" }); + this.isBookingStopped = data.isBookingStopped; + this.isDeletionScheduled = data.isDeletionScheduled; + this.deletionDeadline = data.deletionDeadline + ? DateTime.fromISO(data.deletionDeadline) + : undefined; + this.plan = plan; + } +} diff --git a/packages/models/src/marketplace/Extension/FrontendFragment.ts b/packages/models/src/marketplace/Extension/FrontendFragment.ts new file mode 100644 index 00000000..3c83e416 --- /dev/null +++ b/packages/models/src/marketplace/Extension/FrontendFragment.ts @@ -0,0 +1,94 @@ +import type { FrontendFragmentAnchor, FrontendFragmentData } from "./types.js"; +import type { ContributorExtension } from "../ContributorExtension/index.js"; +import type { ExtensionInstanceCommon } from "../ExtensionInstance/index.js"; +import type { UserCommon } from "../../user/index.js"; + +import { replaceUrlTemplateValues } from "../../lib/replaceUrlTemplateValues.js"; +import { LocalizedText } from "../../common/index.js"; +import { DataModel } from "../../base/index.js"; + +export class FrontendFragment extends DataModel { + public readonly anchor: FrontendFragmentAnchor; + public readonly contributorExtension: ContributorExtension; + public readonly icon?: string; + public readonly title: LocalizedText; + public readonly url: string; + + public constructor( + anchor: FrontendFragmentAnchor, + data: FrontendFragmentData, + extensionName: string, + extension: ContributorExtension, + ) { + super(data); + + this.anchor = anchor; + this.title = LocalizedText.fromJsonString( + data.additionalProperties?.title ?? extensionName, + ); + this.icon = data.additionalProperties?.icon; + this.url = data.url; + this.contributorExtension = extension; + } + + public buildUrl(data: { + extensionInstance: ExtensionInstanceCommon; + pathParams?: Record; + fragmentDevUrl?: string; + user: UserCommon; + }) { + const { extensionInstance, fragmentDevUrl, pathParams, user } = data; + + const templatedFragmentUrl = replaceUrlTemplateValues( + fragmentDevUrl ?? this.url, + { + ...pathParams, + contextId: extensionInstance.context.value.id, + extensionInstanceId: extensionInstance.id, + context: extensionInstance.context.type, + userId: user.id, + }, + ); + + return new URL(templatedFragmentUrl); + } + + public async delete() { + const extension = await this.contributorExtension.getCommon(); + + const frontendFragments = { + ...extension.data.frontendFragments, + }; + delete frontendFragments[this.anchor]; + + return await extension.update({ + frontendFragments, + }); + } + + public async edit(name: string, url: string, newAnchor: string) { + const originalAnchor = this.anchor; + + const extension = await this.contributorExtension.getCommon(); + + const newFragment = { + additionalProperties: { + title: JSON.stringify({ de: name }), + anchor: newAnchor, + }, + url, + }; + + const fragments = { ...(extension.data.frontendFragments ?? {}) }; + + if (originalAnchor !== newAnchor) { + delete fragments[originalAnchor]; + } + + fragments[newAnchor] = newFragment; + + return await extension.update({ + frontendFragments: fragments, + }); + } +} diff --git a/packages/models/src/marketplace/Extension/behaviors/api.ts b/packages/models/src/marketplace/Extension/behaviors/api.ts new file mode 100644 index 00000000..ca4bdcbb --- /dev/null +++ b/packages/models/src/marketplace/Extension/behaviors/api.ts @@ -0,0 +1,69 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { ExtensionBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount } from "../../../base/index.js"; +import { ValidationError } from "../../../errors/index.js"; + +export const apiExtensionBehaviors = ( + client: MittwaldAPIV2Client, +): ExtensionBehaviors => ({ + order: async (extensionId, data) => { + const response = await client.marketplace.extensionOrderExtension( + "projectId" in data + ? { + data: { + consentedScopes: data.consentedScopes, + variantKey: data.variantKey, + projectId: data.projectId, + }, + extensionId, + } + : { + data: { + consentedScopes: data.consentedScopes, + customerId: data.customerId, + variantKey: data.variantKey, + }, + extensionId, + }, + ); + + if ( + response.status === 412 && + "type" in response.data && + typeof response.data.type === "string" + ) { + throw new ValidationError({ + type: response.data.type, + path: "root", + }); + } + + validateResponse(response, 201); + }, + + list: async (query) => { + const response = await client.marketplace.extensionListExtensions({ + queryParameters: query, + }); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + find: async (extensionId) => { + const response = await client.marketplace.extensionGetExtension({ + extensionId, + }); + + if (response.status === 200) { + return response.data; + } + + validateResponse(response, 404); + }, +}); diff --git a/packages/models/src/marketplace/Extension/behaviors/index.ts b/packages/models/src/marketplace/Extension/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/marketplace/Extension/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/marketplace/Extension/behaviors/types.ts b/packages/models/src/marketplace/Extension/behaviors/types.ts new file mode 100644 index 00000000..32642fb0 --- /dev/null +++ b/packages/models/src/marketplace/Extension/behaviors/types.ts @@ -0,0 +1,20 @@ +import type { QueryResponseData } from "../../../base/index.js"; +import type { + ExtensionOrderRequestData, + ExtensionListQueryData, + ExtensionListItemData, + ExtensionData, +} from "../types.js"; + +export interface ExtensionBehaviors { + list: ( + query: ExtensionListQueryData, + ) => Promise>; + + order: ( + extensionId: string, + data: ExtensionOrderRequestData, + ) => Promise; + + find: (extensionId: string) => Promise; +} diff --git a/packages/models/src/marketplace/Extension/index.ts b/packages/models/src/marketplace/Extension/index.ts new file mode 100644 index 00000000..63b3a7f0 --- /dev/null +++ b/packages/models/src/marketplace/Extension/index.ts @@ -0,0 +1,6 @@ +export * from "./Extension.js"; +export * from "./ExtensionAsset.js"; +export * from "./ExtensionPricePlan.js"; +export * from "./ExtensionPricePlanVariant.js"; +export * from "./FrontendFragment.js"; +export * from "./types.js"; diff --git a/packages/models/src/marketplace/Extension/types.ts b/packages/models/src/marketplace/Extension/types.ts new file mode 100644 index 00000000..969097a6 --- /dev/null +++ b/packages/models/src/marketplace/Extension/types.ts @@ -0,0 +1,53 @@ +import { type MittwaldAPIV2 } from "@mittwald/api-client"; + +export type ExtensionData = + MittwaldAPIV2.Operations.ExtensionGetExtension.ResponseData; + +export type ExtensionListItemData = + MittwaldAPIV2.Operations.ExtensionListExtensions.ResponseData[number]; + +export type ExtensionListQueryData = + MittwaldAPIV2.Paths.V2Extensions.Get.Parameters.Query; + +export type ExtensionAssetData = + MittwaldAPIV2.Components.Schemas.MarketplaceExtensionAsset; + +export type ExtensionPricePlanData = + MittwaldAPIV2.Components.Schemas.MarketplaceMonthlyPricePlanStrategy; + +export type MarketplacePricePlanDetails = + MittwaldAPIV2.Components.Schemas.MarketplacePricePlanDetails; + +export type ExtensionPricePlanVariantData = + MittwaldAPIV2.Components.Schemas.MarketplaceMonthlyPricePlanStrategy[0]; + +export type ExtensionPricePlanVariantBaseData = ExtensionPricePlanVariantData; + +export type MarketplaceSupportMeta = + MittwaldAPIV2.Components.Schemas.MarketplaceSupportMeta; + +export type ExtensionOrderRequestData = + MittwaldAPIV2.Paths.V2ExtensionsExtensionIdOrder.Post.Parameters.RequestBody; + +export type ExternalFrontend = + MittwaldAPIV2.Components.Schemas.MarketplaceExternalComponent; + +export type MarketplaceDetailedDescriptionsFormat = + MittwaldAPIV2.Components.Schemas.MarketplaceDescriptionFormats; + +export const frontendFragmentAnchors = [ + "/projects/project/apps/detail/menu-top/item", + "/projects/project/apps/detail/general/section", + "/projects/project/backups/detail/menu-top/item", + "/projects/project/container/containers/detail/general/section", + "/projects/project/container/containers/detail/menu-top/item", + "/projects/project/domain/domains/detail/menu-top/item", + "/projects/project/email/addresses/detail/menu-top/item", + "/projects/project/menu/section/extensions/item", + "/customers/customer/menu/section/extensions/item", +] as const; + +export type FrontendFragmentAnchor = (typeof frontendFragmentAnchors)[number]; + +export type FrontendFragmentData = + MittwaldAPIV2.Components.Schemas.MarketplaceFrontendFragment; diff --git a/packages/models/src/marketplace/ExtensionInstance/ExtensionInstance.test.ts b/packages/models/src/marketplace/ExtensionInstance/ExtensionInstance.test.ts new file mode 100644 index 00000000..8805591f --- /dev/null +++ b/packages/models/src/marketplace/ExtensionInstance/ExtensionInstance.test.ts @@ -0,0 +1,264 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +import type { ExtensionInstanceCreateRequestData } from "./types.js"; + +import { buildExtensionInstanceListItemData } from "../../testing/builders/buildExtensionInstanceListItemData.js"; +import { buildExtensionInstanceData } from "../../testing/builders/buildExtensionInstanceData.js"; +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { ReferenceModel } from "../../base/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { ExtensionInstanceContract } from "./ExtensionInstanceContract.js"; +import { ExtensionInstanceContext } from "./ExtensionInstanceContext.js"; +import { + ExtensionInstanceListQuery, + ExtensionInstanceDetailed, + ExtensionInstanceListItem, + ExtensionInstanceCommon, + ExtensionInstanceList, + ExtensionInstance, +} from "./ExtensionInstance.js"; + +afterEach(resetBehaviors); + +describe("reference and delegation", () => { + test("ofId creates its contract reference", () => { + const instance = ExtensionInstance.ofId("i-1"); + + expect(instance.id).toBe("i-1"); + expect(instance.contract).toBeInstanceOf(ExtensionInstanceContract); + expect(instance.contract.id).toBe("i-1"); + }); + + test("find delegates and materializes a detailed instance", async () => { + const find = vi + .fn() + .mockResolvedValue(buildExtensionInstanceData({ id: "i-1" })); + installBehaviors({ extensionInstance: { find } }); + + const instance = await ExtensionInstance.find("i-1"); + + expect(find).toHaveBeenCalledWith("i-1"); + expect(instance).toBeInstanceOf(ExtensionInstanceDetailed); + expect(instance?.id).toBe("i-1"); + }); + + test("find returns undefined when the behavior does", async () => { + installBehaviors({ + extensionInstance: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(ExtensionInstance.find("missing")).resolves.toBeUndefined(); + }); +}); + +test("create delegates and returns a reference", async () => { + const create = vi.fn().mockResolvedValue({ id: "i-9" }); + installBehaviors({ extensionInstance: { create } }); + const data = { + extensionId: "extension-id", + contextId: "project-id", + consentedScopes: [], + context: "project", + } satisfies ExtensionInstanceCreateRequestData; + + const instance = await ExtensionInstance.create(data); + + expect(create).toHaveBeenCalledWith(data); + expect(instance).toBeInstanceOf(ExtensionInstance); + expect(instance.id).toBe("i-9"); +}); + +test("findAggregate materializes metadata only for an id", () => { + expect(ExtensionInstance.findAggregate("i-1")).toEqual({ + id: "i-1", + ...ExtensionInstance.aggregateMetaData, + }); + expect(ExtensionInstance.findAggregate(undefined)).toBeUndefined(); +}); + +test("exposes data and derived values for a project context", () => { + const instance = new ExtensionInstanceDetailed( + buildExtensionInstanceData({ + createdAt: "2024-01-01T00:00:00.000Z", + consentedScopes: ["scope:read"], + variantKey: "variant-1", + }), + ); + + expect(instance.extension.id).toBe("extension-id"); + expect(instance.extensionName).toBe("Test Extension"); + expect(instance.consentedScopes).toEqual(["scope:read"]); + expect(instance.context).toBeInstanceOf(ExtensionInstanceContext); + expect(instance.context.type).toBe("project"); + expect(instance.context.project?.id).toBe("project-id"); + expect(instance.isOwnExtension).toBe(true); + expect(instance.pricePlanVariant?.key).toBe("variant-1"); + expect(instance.pricePlanVariant?.id).toBe("extension-id::variant-1"); + expect(instance.createdAtInSeconds).toBeTypeOf("number"); +}); + +test("supports customer context and an absent price plan variant", () => { + const instance = new ExtensionInstanceDetailed( + buildExtensionInstanceData({ + aggregateReference: { + aggregate: "customer", + domain: "customer", + id: "customer-id", + }, + variantKey: undefined, + }), + ); + + expect(instance.context.type).toBe("customer"); + expect(instance.context.customer?.id).toBe("customer-id"); + expect(instance.pricePlanVariant).toBeUndefined(); +}); + +test("base query materializes a paginated list", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildExtensionInstanceListItemData()], + totalCount: 1, + }); + installBehaviors({ extensionInstance: { list } }); + + const result = await ExtensionInstance.query().execute(); + + expect(list).toHaveBeenCalledWith(expect.any(Object)); + expect(result).toBeInstanceOf(ExtensionInstanceList); + expect(result).toBeInstanceOf(ExtensionInstanceListQuery); + expect(result.items).toHaveLength(1); + expect(result.items[0]).toBeInstanceOf(ExtensionInstanceListItem); + expect(result.totalCount).toBe(1); +}); + +test("preserves ghostmaker identity chains", () => { + const item = new ExtensionInstanceListItem( + buildExtensionInstanceListItemData(), + ); + + expect(item).toBeInstanceOf(ExtensionInstanceListItem); + expect(item).toBeInstanceOf(ExtensionInstance); + expect(item).toBeInstanceOf(ReferenceModel); + expect(item.data).toBeDefined(); +}); + +describe("get on a missing extension instance", () => { + test("throws ObjectNotFoundError", async () => { + installBehaviors({ + extensionInstance: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(ExtensionInstance.get("missing")).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); +}); +describe("common variant and idempotency", () => { + test("findCommon delegates to the detailed variant from a bare reference", async () => { + const find = vi + .fn() + .mockResolvedValue(buildExtensionInstanceData({ id: "i-1" })); + installBehaviors({ extensionInstance: { find } }); + + const common = await ExtensionInstance.ofId("i-1").findCommon(); + + expect(find).toHaveBeenCalledWith("i-1"); + expect(common).toBeInstanceOf(ExtensionInstanceCommon); + expect(common?.id).toBe("i-1"); + }); + + test("findCommon returns undefined when the behavior finds nothing", async () => { + installBehaviors({ + extensionInstance: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + ExtensionInstance.ofId("missing").findCommon(), + ).resolves.toBeUndefined(); + }); + + test("getCommon delegates and throws when the instance is missing", async () => { + installBehaviors({ + extensionInstance: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + ExtensionInstance.ofId("missing").getCommon(), + ).rejects.toBeInstanceOf(ObjectNotFoundError); + }); + + test("getCommon on an already-common model returns itself without re-fetching", async () => { + const find = vi.fn(); + installBehaviors({ extensionInstance: { find } }); + const item = new ExtensionInstanceListItem( + buildExtensionInstanceListItemData({ id: "i-2" }), + ); + + const common = await item.getCommon(); + + expect(common).toBe(item); + expect(find).not.toHaveBeenCalled(); + }); + + test("findCommon on an already-common model returns itself without re-fetching", async () => { + const find = vi.fn(); + installBehaviors({ extensionInstance: { find } }); + const detailed = new ExtensionInstanceDetailed( + buildExtensionInstanceData({ id: "i-3" }), + ); + + const common = await detailed.findCommon(); + + expect(common).toBe(detailed); + expect(find).not.toHaveBeenCalled(); + }); +}); + +describe("aggregate metadata wiring", () => { + test("pins the extension instance aggregate identity", () => { + expect(ExtensionInstance.aggregateMetaData).toBeInstanceOf( + AggregateMetaData, + ); + expect(ExtensionInstance.aggregateMetaData.domain).toBe("extension"); + expect(ExtensionInstance.aggregateMetaData.aggregate).toBe( + "extensionInstance", + ); + }); +}); + +describe("absent optional source data", () => { + test("omits the derived optionals when the source has none", () => { + const instance = new ExtensionInstanceDetailed( + buildExtensionInstanceData({ + extensionDeletionDeadline: undefined, + extensionSubTitle: undefined, + variantKey: undefined, + createdAt: undefined, + }), + ); + + expect(instance.extensionSubTitle).toBeUndefined(); + expect(instance.createdAtInSeconds).toBeUndefined(); + expect(instance.extensionDeletionDeadline).toBeUndefined(); + expect(instance.pricePlanVariant).toBeUndefined(); + expect(instance.frontendFragments).toEqual([]); + expect( + instance.findFrontendFragment( + "/projects/project/menu/section/extensions/item", + ), + ).toBeUndefined(); + }); +}); diff --git a/packages/models/src/marketplace/ExtensionInstance/ExtensionInstance.ts b/packages/models/src/marketplace/ExtensionInstance/ExtensionInstance.ts new file mode 100644 index 00000000..15add0aa --- /dev/null +++ b/packages/models/src/marketplace/ExtensionInstance/ExtensionInstance.ts @@ -0,0 +1,471 @@ +import type { AxiosRequestConfig } from "axios"; + +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; + +import type { FrontendFragmentAnchor } from "../Extension/index.js"; +import type { UserCommon } from "../../user/index.js"; +import type { + ExtensionInstanceListQueryModelData, + ExtensionInstanceCreateRequestData, + ExtensionInstanceChargeability, + ExtensionInstanceListItemData, + AccessTokenRetrievalKey, + ExtensionInstanceData, +} from "./types.js"; + +import { ExtensionInstanceContract } from "./ExtensionInstanceContract.js"; +import { ExtensionInstanceContext } from "./ExtensionInstanceContext.js"; +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { AggregateMetaData, LocalizedText } from "../../common/index.js"; +import { ContributorExtension } from "../ContributorExtension/index.js"; +import { Customer } from "../../customer/Customer/Customer.js"; +import { Project } from "../../project/internal.js"; +import { Contributor } from "../Contributor/index.js"; +import { config } from "../../config/index.js"; +import { + ExtensionPricePlanVariant, + FrontendFragment, + Extension, +} from "../Extension/index.js"; +import { + type QueryResponseData, + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "ExtensionInstance", +}) +export class ExtensionInstance extends ReferenceModel { + public static readonly aggregateMetaData = new AggregateMetaData( + "extension", + "extensionInstance", + ); + + public readonly contract: ExtensionInstanceContract; + + public constructor(id: string) { + super(id); + this.contract = ExtensionInstanceContract.ofId(id); + } + public static async create(data: ExtensionInstanceCreateRequestData) { + const { id } = await config.behaviors.extensionInstance.create(data); + + return new ExtensionInstance(id); + } + + public static async find(id: string) { + const data = await config.behaviors.extensionInstance.find(id); + + if (data) { + return new ExtensionInstanceDetailed(data); + } + } + + public static findAggregate(extensionInstanceId?: string) { + return extensionInstanceId + ? { id: extensionInstanceId, ...ExtensionInstance.aggregateMetaData } + : undefined; + } + + public static async get(id: string) { + const extensionInstance = await this.find(id); + assertObjectFound(extensionInstance, ExtensionInstance, id); + return extensionInstance; + } + + public static async listOpenOrders(context: Customer | Project) { + let data; + if (context instanceof Project) { + data = await config.behaviors.extensionInstance.findOpenProjectOrders( + context.id, + ); + } else { + data = await config.behaviors.extensionInstance.findOpenCustomerOrders( + context.id, + ); + } + + return ( + data + ?.filter((i) => !!i.extensionId && !!i.referencedId && !!i.context) + .map((i) => ({ + extension: Extension.ofId(i.extensionId!), + referencedId: i.referencedId!, + context: i.context!, + })) ?? [] + ); + } + + public static ofId(id: string) { + return new ExtensionInstance(id); + } + + public static query(query?: ExtensionInstanceListQueryModelData) { + return new ExtensionInstanceListQuery(query); + } + + public async cancelTermination() { + await config.behaviors.extensionInstance.cancelTermination(this.id); + } + + public async cancelVariantSwitch() { + return await config.behaviors.extensionInstance.cancelVariantSwitch( + this.id, + ); + } + + public async consentToScopes(consentedScopes: string[]) { + await config.behaviors.extensionInstance.consentToScopes(this.id, { + consentedScopes, + }); + } + + public async createRetrievalKey() { + return await config.behaviors.extensionInstance.createRetrievalKey(this.id); + } + + public async delete() { + await config.behaviors.extensionInstance.delete(this.id); + } + + public async disable() { + await config.behaviors.extensionInstance.disable(this.id); + } + + public async enable() { + await config.behaviors.extensionInstance.enable(this.id); + } + + public async findCommon(): Promise { + return this instanceof ExtensionInstanceCommon ? this : this.findDetailed(); + } + + public async findDetailed(): Promise { + return ExtensionInstance.find(this.id); + } + + public async getCommon(): Promise { + return this instanceof ExtensionInstanceCommon ? this : this.getDetailed(); + } + + public getDetailed(): Promise { + return ExtensionInstance.get(this.id); + } + + public async scheduleVariantSwitch(variantKey: string) { + return await config.behaviors.extensionInstance.scheduleVariantSwitch( + this.id, + variantKey, + ); + } + + public async terminate(instantTermination: boolean) { + await config.behaviors.extensionInstance.terminate( + this.id, + instantTermination, + ); + } + + public async updateContract(variantKey?: string) { + return await config.behaviors.extensionInstance.updateContract( + this.id, + variantKey, + ); + } +} + +export class ExtensionInstanceCommon extends WithData< + ExtensionInstanceListItemData | ExtensionInstanceData +>()(ExtensionInstance) { + public readonly chargeability?: ExtensionInstanceChargeability; + public readonly consentedScopes: string[]; + public readonly context: ExtensionInstanceContext; + public readonly contract: ExtensionInstanceContract; + public readonly contributor: Contributor; + public readonly contributorName: string; + public readonly createdAtInSeconds?: number; + public override readonly data: + ExtensionInstanceListItemData | ExtensionInstanceData; + public readonly extension: Extension; + public readonly extensionDeletionDeadline?: DateTime; + public readonly extensionName: string; + public readonly extensionSubTitle?: LocalizedText; + public readonly frontendFragments: FrontendFragment[]; + public readonly isOwnExtension: boolean; + public readonly pendingInstallation: boolean; + public readonly pendingRemoval: boolean; + public readonly pricePlanVariant?: ExtensionPricePlanVariant; + + public constructor( + data: ExtensionInstanceListItemData | ExtensionInstanceData, + ) { + super(data.id); + this.data = data; + this.extension = Extension.ofId(data.extensionId); + this.extensionName = data.extensionName; + this.extensionSubTitle = data.extensionSubTitle + ? new LocalizedText(data.extensionSubTitle) + : undefined; + this.pendingInstallation = data.pendingInstallation; + this.pendingRemoval = data.pendingRemoval; + this.consentedScopes = data.consentedScopes; + this.context = new ExtensionInstanceContext( + data.aggregateReference.aggregate === Project.aggregateMetaData.aggregate + ? Project.ofId(data.aggregateReference.id) + : Customer.ofId(data.aggregateReference.id), + ); + this.contributor = Contributor.ofId(data.contributorId); + this.contributorName = data.contributorName; + this.createdAtInSeconds = data.createdAt + ? DateTime.fromISO(data.createdAt).toSeconds() + : undefined; + this.isOwnExtension = + !data.chargeability?.isChargeable && + data.chargeability?.reasons.isOwnExtension; + this.chargeability = data.chargeability; + this.pricePlanVariant = data.variantKey + ? ExtensionPricePlanVariant.ofId(this.extension, data.variantKey) + : undefined; + this.contract = ExtensionInstanceContract.ofId(data.id); + this.extensionDeletionDeadline = data.extensionDeletionDeadline + ? DateTime.fromISO(data.extensionDeletionDeadline) + : undefined; + this.frontendFragments = data.frontendFragments + ? Object.entries(data.frontendFragments) + .filter(([key]) => Extension.isValidAnchor(key)) + .map( + ([key, value]) => + new FrontendFragment( + key as FrontendFragmentAnchor, + value, + this.extensionName, + ContributorExtension.ofId( + this.contributor.id, + this.extension.id, + ), + ), + ) + : []; + } + + public buildFragmentUrl(data: { + pathParams: Record; + anchor?: FrontendFragmentAnchor; + fragmentDevUrl?: string; + user: UserCommon; + }) { + const { fragmentDevUrl, pathParams, anchor, user } = data; + + if (!anchor) { + return undefined; + } + + const fragment = this.findFrontendFragment(anchor); + + if (!fragment) { + return; + } + + return fragment.buildUrl({ + extensionInstance: this, + fragmentDevUrl, + pathParams, + user, + }); + } + + public findFrontendFragment(anchor: FrontendFragmentAnchor) { + return this.frontendFragments.find((f) => f.anchor === anchor); + } + + public async getExtensionDetailsAction( + accessTokenRetrievalKey: AccessTokenRetrievalKey, + url: string | undefined, + ) { + const extension = await this.extension.getDetailed(); + + if (url === undefined) { + return undefined; + } + + return url + .replace(":userId", accessTokenRetrievalKey.userId) + .replace(":contextId", this.data.aggregateReference.id) + .replace(":context", this.context.type) + .replace(":contributorId", extension.data.contributorId) + .replace(":extensionId", this.data.extensionId) + .replace(":extensionInstanceId", this.id) + .replace( + ":accessTokenRetrievalKey", + accessTokenRetrievalKey.accessTokenRetrievalKey, + ) + .replace(":apiVersion", "v1"); + } + + public getFrontendFragment(anchor: FrontendFragmentAnchor) { + const fragement = this.findFrontendFragment(anchor); + assertObjectFound(fragement, FrontendFragment, anchor); + return fragement; + } + + public async getSessionToken(sessionId: string) { + const response = + await config.behaviors.extensionInstance.generateSessionToken( + this.id, + sessionId, + ); + + return response.sessionToken; + } + + public async getUnconsentedScopes() { + const extension = await this.extension.getDetailed(); + + return extension.scopes.filter( + (extScope) => !this.consentedScopes.includes(extScope), + ); + } + + public async getUrlWithParameters(url: string) { + const retrievalKeyData = await this.createRetrievalKey(); + + const extension = await this.extension.getDetailed(); + + return url + .replace(":userId", retrievalKeyData.userId) + .replace(":contextId", this.context.value.id) + .replace(":context", this.context.type) + .replace(":contributorId", extension.data.contributorId) + .replace(":extensionId", this.data.extensionId) + .replace(":extensionInstanceId", this.id) + .replace( + ":accessTokenRetrievalKey", + retrievalKeyData.accessTokenRetrievalKey, + ) + .replace(":apiVersion", "v1"); + } +} + +export class ExtensionInstanceDetailed extends ExtensionInstanceCommon { + public override readonly data: ExtensionInstanceData; + public constructor(data: ExtensionInstanceData) { + super(data); + this.data = data; + } +} + +export class ExtensionInstanceListItem extends ExtensionInstanceCommon { + public override readonly data: ExtensionInstanceListItemData; + public constructor(data: ExtensionInstanceListItemData) { + super(data); + this.data = data; + } +} + +export class ExtensionInstanceListQuery extends ListQueryModel { + public constructor(query: ExtensionInstanceListQueryModelData = {}) { + super(query); + } + + public async execute(options?: AxiosRequestConfig) { + const { extension, customer, project, ...rest } = this.query; + const restQuery = { ...rest, extensionId: extractId(extension) }; + + type Result = QueryResponseData; + + const emptyResult: Result = { + totalCount: 0, + items: [], + }; + + const projectResult = project + ? await config.behaviors.extensionInstance.list( + { + ...restQuery, + + contextId: extractId(project), + context: "project", + }, + options, + ) + : emptyResult; + + const projectMembership = project + ? await Project.ofReference(project)?.getOwnMembership() + : undefined; + + const hasAccessToCustomer = projectMembership?.inherited ?? true; + + const resolvedCustomer = customer; + + const customerResult = + hasAccessToCustomer && resolvedCustomer + ? await config.behaviors.extensionInstance.list( + { + ...restQuery, + contextId: extractId(resolvedCustomer), + context: "customer", + }, + options, + ) + : emptyResult; + + const baseResult = + !customer && !project + ? await config.behaviors.extensionInstance.list({ + ...restQuery, + }) + : emptyResult; + + const combinedResult: Result = { + totalCount: + projectResult.totalCount + + customerResult.totalCount + + baseResult.totalCount, + items: [ + ...projectResult.items, + ...customerResult.items, + ...baseResult.items, + ], + }; + + return new ExtensionInstanceList( + this.query, + combinedResult.items.map((d) => new ExtensionInstanceListItem(d)), + combinedResult.totalCount, + ); + } + + public async getTotalCount() { + const { totalCount } = await this.refine({ limit: 1 }).execute(); + return totalCount; + } + + public refine(query: ExtensionInstanceListQueryModelData) { + return new ExtensionInstanceListQuery({ + ...this.query, + ...query, + }); + } +} + +export class ExtensionInstanceList extends WithListData()( + ExtensionInstanceListQuery, +) { + public override readonly items: readonly ExtensionInstanceListItem[]; + public override readonly totalCount: number; + public constructor( + query: ExtensionInstanceListQueryModelData, + extensionInstances: ExtensionInstanceListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(extensionInstances); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/marketplace/ExtensionInstance/ExtensionInstanceContext.ts b/packages/models/src/marketplace/ExtensionInstance/ExtensionInstanceContext.ts new file mode 100644 index 00000000..017e1aa2 --- /dev/null +++ b/packages/models/src/marketplace/ExtensionInstance/ExtensionInstanceContext.ts @@ -0,0 +1,32 @@ +import type { MarketplaceContext } from "./types.js"; +import type { Customer } from "../../customer/index.js"; + +import { Project } from "../../project/index.js"; +import { required } from "../../base/index.js"; + +export class ExtensionInstanceContext { + public readonly customer?: Customer; + public readonly project?: Project; + public readonly type: MarketplaceContext; + public readonly value: Customer | Project; + + public constructor(value: Customer | Project) { + if (value instanceof Project) { + this.type = "project"; + this.project = value; + } else { + this.type = "customer"; + this.customer = value; + } + this.value = value; + } + + public async getCustomer() { + if (this.customer) { + return this.customer; + } + return Project.get(required(this.project, "Project").id).then( + (p) => p.customer, + ); + } +} diff --git a/packages/models/src/marketplace/ExtensionInstance/ExtensionInstanceContract.ts b/packages/models/src/marketplace/ExtensionInstance/ExtensionInstanceContract.ts new file mode 100644 index 00000000..6363d134 --- /dev/null +++ b/packages/models/src/marketplace/ExtensionInstance/ExtensionInstanceContract.ts @@ -0,0 +1,148 @@ +import type { AxiosRequestConfig } from "axios"; + +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; + +import type { + ExtensionInstanceContractStatus, + ExtensionInstanceContractData, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { ExtensionPricePlanVariantBase } from "../Extension/index.js"; +import { AggregateMetaData, Money } from "../../common/index.js"; +import { ReferenceModel, WithData } from "../../base/index.js"; +import { config } from "../../config/index.js"; + +@GhostMakerModel({ + name: "ExtensionInstanceContract", +}) +export class ExtensionInstanceContract extends ReferenceModel { + public static readonly aggregateMetaData = new AggregateMetaData( + "extension", + "extensionInstanceContract", + ); + + public static async find(id: string, requestConfig?: AxiosRequestConfig) { + const data = await config.behaviors.extensionInstance.findContract( + id, + requestConfig, + ); + + if (data) { + return new ExtensionInstanceContractDetailed(id, data); + } + } + + public static findAggregate(extensionInstanceContractId?: string) { + return extensionInstanceContractId + ? { + id: extensionInstanceContractId, + ...ExtensionInstanceContract.aggregateMetaData, + } + : undefined; + } + + public static async get(id: string, requestConfig?: AxiosRequestConfig) { + const extensionInstanceContract = await this.find(id, requestConfig); + assertObjectFound(extensionInstanceContract, ExtensionInstanceContract, id); + return extensionInstanceContract; + } + + public static ofId(id: string) { + return new ExtensionInstanceContract(id); + } + + public async findCommon( + requestConfig?: AxiosRequestConfig, + ): Promise { + return this instanceof ExtensionInstanceContractDetailed + ? this + : this.findDetailed(requestConfig); + } + + public async findDetailed(requestConfig?: AxiosRequestConfig) { + return ExtensionInstanceContract.find(this.id, requestConfig); + } + + public async getCommon( + requestConfig?: AxiosRequestConfig, + ): Promise { + return this instanceof ExtensionInstanceContractDetailed + ? this + : this.getDetailed(requestConfig); + } + + public async getDetailed(requestConfig?: AxiosRequestConfig) { + return ExtensionInstanceContract.get(this.id, requestConfig); + } + + public async update(variantKey?: string) { + return await config.behaviors.extensionInstance.updateContract( + this.id, + variantKey, + ); + } +} + +export class ExtensionInstanceContractDetailed extends WithData()( + ExtensionInstanceContract, +) { + public readonly contractPeriodEndDate?: DateTime; + public override readonly data: ExtensionInstanceContractData; + public readonly interactionDeadline?: DateTime; + public readonly interactionRequired: boolean; + public readonly pendingVariantChange?: { + targetVariantKey: string; + effectiveDate: DateTime; + }; + public readonly price: Money; + public readonly pricePlanVariant?: ExtensionPricePlanVariantBase; + public readonly status?: ExtensionInstanceContractStatus; + public readonly terminationTargetDate?: DateTime; + + public constructor(id: string, data: ExtensionInstanceContractData) { + super(id); + this.data = data; + + this.interactionDeadline = data.interactionDeadline + ? DateTime.fromISO(data.interactionDeadline) + : undefined; + + this.terminationTargetDate = data.terminationTargetDate + ? DateTime.fromISO(data.terminationTargetDate) + : undefined; + + this.contractPeriodEndDate = data.contractPeriodEndDate + ? DateTime.fromISO(data.contractPeriodEndDate) + : undefined; + + this.status = data.status; + this.interactionRequired = data.interactionRequired; + + this.price = Money({ + amount: data.currentPrice ?? 0, + currency: "EUR", + }); + + this.pendingVariantChange = data.pendingVariantChange + ? { + effectiveDate: DateTime.fromISO( + data.pendingVariantChange.effectiveDate, + ), + targetVariantKey: data.pendingVariantChange.targetVariantKey, + } + : undefined; + + if (data.variantKey) { + this.pricePlanVariant = new ExtensionPricePlanVariantBase({ + description: data.variantDescription, + priceInCents: data.currentPrice ?? 0, + isDeletionScheduled: false, + isBookingStopped: false, + name: data.variantName, + key: data.variantKey, + }); + } + } +} diff --git a/packages/models/src/marketplace/ExtensionInstance/behaviors/api.ts b/packages/models/src/marketplace/ExtensionInstance/behaviors/api.ts new file mode 100644 index 00000000..34231031 --- /dev/null +++ b/packages/models/src/marketplace/ExtensionInstance/behaviors/api.ts @@ -0,0 +1,182 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { ExtensionInstanceBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { + withAxiosRequestConfig, + resolveTotalCount, + anyStatus403, +} from "../../../base/index.js"; + +export const apiExtensionInstanceBehaviors = ( + client: MittwaldAPIV2Client, +): ExtensionInstanceBehaviors => ({ + findContract: async (extensionInstanceId, requestConfig) => { + const response = + await client.marketplace.extensionGetExtensionInstanceContract( + { + extensionInstanceId, + }, + withAxiosRequestConfig(requestConfig), + ); + + if (response.status === 200) { + return response.data; + } + + // API-DRIFT: extensionGetExtensionInstanceContract omits 403 in its generated response type, so anyStatus403 (403 as any) is passed (resolve: use the literal 403 once the client type declares it) + validateResponse(response, [anyStatus403, 404]); + }, + + findOpenCustomerOrders: async (customerId) => { + const response = + await client.marketplace.extensionGetCustomerExtensionInstanceOrders({ + customerId, + }); + + if (response.status === 200) { + return response.data; + } + // API-DRIFT: extensionGetCustomerExtensionInstanceOrders omits 403 in its generated response type, so anyStatus403 (403 as any) is passed (resolve: use the literal 403 once the client type declares it) + validateResponse(response, [404, anyStatus403]); + }, + + list: async (query, options) => { + const response = await client.marketplace.extensionListExtensionInstances( + { + queryParameters: query, + }, + withAxiosRequestConfig(options), + ); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + scheduleVariantSwitch: async (extensionInstanceId, variantKey) => { + const response = + await client.marketplace.extensionScheduleExtensionVariantChange({ + data: { targetVariantKey: variantKey }, + extensionInstanceId, + }); + validateResponse(response, 201); + }, + + findOpenProjectOrders: async (projectId) => { + const response = + await client.marketplace.extensionGetProjectExtensionInstanceOrders({ + projectId, + }); + + if (response.status === 200) { + return response.data; + } + + validateResponse(response, [404]); + }, + + terminate: async (extensionInstanceId, instantTermination) => { + const response = + await client.marketplace.extensionScheduleExtensionTermination({ + data: { instantTermination }, + extensionInstanceId, + }); + + validateResponse(response, 201); + }, + + find: async (extensionInstanceId) => { + const response = await client.marketplace.extensionGetExtensionInstance({ + extensionInstanceId, + }); + if (response.status === 200) { + return response.data; + } + validateResponse(response, [403, 404]); + }, + + updateContract: async (extensionInstanceId, variantKey) => { + const response = + await client.marketplace.extensionUpdateExtensionInstanceContract({ + data: { variantKey }, + extensionInstanceId, + }); + validateResponse(response, 200); + }, + + generateSessionToken: async (extensionInstanceId, sessionId) => { + const response = await client.marketplace.extensionGenerateSessionToken({ + extensionInstanceId, + sessionId, + }); + + validateResponse(response, 200); + + return response.data; + }, + + createRetrievalKey: async (extensionInstanceId) => { + const response = await client.marketplace.extensionCreateRetrievalKey({ + extensionInstanceId, + }); + validateResponse(response, 200); + + return response.data; + }, + + cancelVariantSwitch: async (extensionInstanceId) => { + const response = + await client.marketplace.extensionCancelExtensionVariantChange({ + extensionInstanceId, + }); + validateResponse(response, 200); + }, + + cancelTermination: async (extensionInstanceId) => { + const response = + await client.marketplace.extensionCancelExtensionTermination({ + extensionInstanceId, + }); + + validateResponse(response, 200); + }, + + consentToScopes: async (extensionInstanceId, data) => { + const response = await client.marketplace.extensionConsentToExtensionScopes( + { extensionInstanceId, data }, + ); + validateResponse(response, 204); + }, + + disable: async (extensionInstanceId) => { + const response = await client.marketplace.extensionDisableExtensionInstance( + { extensionInstanceId }, + ); + validateResponse(response, 204); + }, + + enable: async (extensionInstanceId) => { + const response = await client.marketplace.extensionEnableExtensionInstance({ + extensionInstanceId, + }); + validateResponse(response, 204); + }, + + delete: async (extensionInstanceId) => { + const response = await client.marketplace.extensionDeleteExtensionInstance({ + extensionInstanceId, + }); + validateResponse(response, 204); + }, + + create: async (data) => { + const response = await client.marketplace.extensionCreateExtensionInstance({ + data, + }); + validateResponse(response, 201); + return response.data; + }, +}); diff --git a/packages/models/src/marketplace/ExtensionInstance/behaviors/index.ts b/packages/models/src/marketplace/ExtensionInstance/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/marketplace/ExtensionInstance/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/marketplace/ExtensionInstance/behaviors/types.ts b/packages/models/src/marketplace/ExtensionInstance/behaviors/types.ts new file mode 100644 index 00000000..6ffb1d56 --- /dev/null +++ b/packages/models/src/marketplace/ExtensionInstance/behaviors/types.ts @@ -0,0 +1,78 @@ +import type { AxiosRequestConfig } from "axios"; + +import type { QueryResponseData } from "../../../base/index.js"; +import type { + ExtensionInstanceConsentToScopesRequestData, + ExtensionInstanceCreateRequestData, + ExtensionInstanceRetrievalKeyData, + ExtensionInstanceListQueryData, + OpenCustomerExtensionOrderData, + ExtensionInstanceContractData, + ExtensionInstanceListItemData, + OpenProjectExtensionOrderData, + ExtensionSessionTokenData, + ExtensionInstanceData, +} from "../types.js"; + +export interface ExtensionInstanceBehaviors { + list: ( + query: ExtensionInstanceListQueryData, + options?: AxiosRequestConfig, + ) => Promise>; + + findContract: ( + extensionInstanceId: string, + requestConfig?: AxiosRequestConfig, + ) => Promise; + + consentToScopes: ( + extensionInstanceId: string, + data: ExtensionInstanceConsentToScopesRequestData, + ) => Promise; + + generateSessionToken: ( + extensionInstanceId: string, + sessionId: string, + ) => Promise; + + findOpenCustomerOrders: ( + customerId: string, + ) => Promise; + findOpenProjectOrders: ( + projectId: string, + ) => Promise; + + createRetrievalKey: ( + extensionInstanceId: string, + ) => Promise; + + scheduleVariantSwitch: ( + extensionInstanceId: string, + variantKey?: string, + ) => Promise; + + terminate: ( + extensionInstanceId: string, + instantTermination: boolean, + ) => Promise; + + updateContract: ( + extensionInstanceId: string, + variantKey?: string, + ) => Promise; + + find: ( + extensionInstanceId: string, + ) => Promise; + + create: (data: ExtensionInstanceCreateRequestData) => Promise<{ id: string }>; + + cancelVariantSwitch: (extensionInstanceId: string) => Promise; + cancelTermination: (extensionInstanceId: string) => Promise; + + disable: (extensionInstanceId: string) => Promise; + + enable: (extensionInstanceId: string) => Promise; + + delete: (extensionInstanceId: string) => Promise; +} diff --git a/packages/models/src/marketplace/ExtensionInstance/index.ts b/packages/models/src/marketplace/ExtensionInstance/index.ts new file mode 100644 index 00000000..9990f8aa --- /dev/null +++ b/packages/models/src/marketplace/ExtensionInstance/index.ts @@ -0,0 +1,4 @@ +export * from "./ExtensionInstance.js"; +export * from "./ExtensionInstanceContext.js"; +export * from "./ExtensionInstanceContract.js"; +export * from "./types.js"; diff --git a/packages/models/src/marketplace/ExtensionInstance/types.ts b/packages/models/src/marketplace/ExtensionInstance/types.ts new file mode 100644 index 00000000..dc1f2e23 --- /dev/null +++ b/packages/models/src/marketplace/ExtensionInstance/types.ts @@ -0,0 +1,63 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import type { FrontendFragmentAnchor, Extension } from "../Extension/index.js"; +import type { Customer } from "../../customer/index.js"; +import type { Project } from "../../project/index.js"; + +export type ExtensionInstanceData = + MittwaldAPIV2.Operations.ExtensionGetExtensionInstance.ResponseData; + +export type ExtensionInstanceListItemData = + MittwaldAPIV2.Operations.ExtensionListExtensionInstances.ResponseData[number]; + +export type ExtensionInstanceListQueryData = + MittwaldAPIV2.Paths.V2ExtensionInstances.Get.Parameters.Query; + +export type ExtensionInstanceListQueryModelData = { + anchor?: FrontendFragmentAnchor; + extension?: Extension | string; + customer?: Customer | string; + project?: Project | string; +} & Omit< + ExtensionInstanceListQueryData, + "extensionId" | "contextId" | "context" +>; + +export type ExtensionInstanceCreateRequestData = + MittwaldAPIV2.Paths.V2ExtensionInstances.Post.Parameters.RequestBody; + +export type ExtensionInstanceConsentToScopesRequestData = + MittwaldAPIV2.Paths.V2ExtensionInstancesExtensionInstanceIdScopes.Patch.Parameters.RequestBody; + +export type MarketplaceContext = + MittwaldAPIV2.Components.Schemas.MarketplaceContext; + +export type ExtensionInstanceChargeability = + MittwaldAPIV2.Components.Schemas.MarketplaceExtensionInstanceChargeability; + +export type ExtensionInstanceRetrievalKeyData = + MittwaldAPIV2.Operations.ExtensionCreateRetrievalKey.ResponseData; + +export type ExtensionInstanceContractData = + MittwaldAPIV2.Operations.ExtensionGetExtensionInstanceContract.ResponseData; + +export type ExtensionInstanceContractStatus = + MittwaldAPIV2.Components.Schemas.ExtensionExtensionInstanceContract["status"]; + +export type OpenCustomerExtensionOrderData = + MittwaldAPIV2.Operations.ExtensionGetCustomerExtensionInstanceOrders.ResponseData[number]; + +export type OpenProjectExtensionOrderData = + MittwaldAPIV2.Operations.ExtensionGetCustomerExtensionInstanceOrders.ResponseData[number]; + +export interface OpenExtensionOrder { + context: MarketplaceContext; + referencedId: string; + extension: Extension; +} + +export type ExtensionSessionTokenData = + MittwaldAPIV2.Operations.ExtensionGenerateSessionToken.ResponseData; + +export type AccessTokenRetrievalKey = + MittwaldAPIV2.Operations.ExtensionCreateRetrievalKey.ResponseData; diff --git a/packages/models/src/marketplace/index.ts b/packages/models/src/marketplace/index.ts index acf7c8ee..e3b9b46b 100644 --- a/packages/models/src/marketplace/index.ts +++ b/packages/models/src/marketplace/index.ts @@ -1 +1,4 @@ export * from "./Contributor/index.js"; +export * from "./ContributorExtension/index.js"; +export * from "./Extension/index.js"; +export * from "./ExtensionInstance/index.js"; diff --git a/packages/models/src/monitoring/StorageMetrics/StorageMetrics.test.ts b/packages/models/src/monitoring/StorageMetrics/StorageMetrics.test.ts new file mode 100644 index 00000000..f02140ac --- /dev/null +++ b/packages/models/src/monitoring/StorageMetrics/StorageMetrics.test.ts @@ -0,0 +1,221 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; +import { DateTime } from "luxon"; + +import { StorageMetricsDetailed, StorageMetrics } from "./StorageMetrics.js"; +import { + buildStorageStatisticsCategoryData, + buildStorageMetricsData, +} from "../../testing/builders/buildStorageMetricsData.js"; +import { ReferenceModel } from "../../base/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { Project } from "../../project/index.js"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +afterEach(resetBehaviors); + +describe("StorageMetrics reference and delegation", () => { + test("ofId creates a storage metrics reference with its kind", () => { + const metrics = StorageMetrics.ofId("sm-1", "project"); + + expect(metrics).toBeInstanceOf(StorageMetrics); + expect(metrics).toBeInstanceOf(ReferenceModel); + expect(metrics.id).toBe("sm-1"); + expect(metrics.kind).toBe("project"); + }); + + test.each([ + ["project", "findByProject"], + ["server", "findByServer"], + ] as const)("find delegates %s metrics to %s", async (kind, behaviorName) => { + const findByProject = vi.fn().mockResolvedValue(buildStorageMetricsData()); + const findByServer = vi.fn().mockResolvedValue(buildStorageMetricsData()); + installBehaviors({ storageMetrics: { findByProject, findByServer } }); + + const result = await StorageMetrics.find("sm-1", kind); + + expect({ findByProject, findByServer }[behaviorName]).toHaveBeenCalledWith( + "sm-1", + ); + expect( + behaviorName === "findByProject" ? findByServer : findByProject, + ).not.toHaveBeenCalled(); + expect(result).toBeInstanceOf(StorageMetricsDetailed); + expect(result?.data).toBeDefined(); + }); + + test("find returns undefined when the behavior finds no metrics", async () => { + const findByServer = vi.fn().mockResolvedValue(undefined); + installBehaviors({ storageMetrics: { findByServer } }); + + await expect( + StorageMetrics.find("missing", "server"), + ).resolves.toBeUndefined(); + }); + + test("get returns detailed metrics when found", async () => { + const findByProject = vi + .fn() + .mockResolvedValue( + buildStorageMetricsData({ kind: "project", id: "sm-2" }), + ); + installBehaviors({ storageMetrics: { findByProject } }); + + const result = await StorageMetrics.get("sm-2", "project"); + + expect(findByProject).toHaveBeenCalledWith("sm-2"); + expect(result).toBeInstanceOf(StorageMetricsDetailed); + expect(result.id).toBe("sm-2"); + }); + + test("get rejects when no metrics are found", async () => { + installBehaviors({ + storageMetrics: { findByServer: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(StorageMetrics.get("missing", "server")).rejects.toBeDefined(); + }); +}); + +describe("StorageMetricsDetailed", () => { + test("derives notification state and total usage", () => { + const active = new StorageMetricsDetailed( + buildStorageMetricsData({ + notificationThresholdInBytes: 500, + meta: { totalUsageInBytes: 250 }, + }), + ); + const inactive = new StorageMetricsDetailed(buildStorageMetricsData()); + + expect(active.notificationActive).toBe(true); + expect(active.notificationThreshold?.value).toBe(500); + expect(active.totalStorageUsage.value).toBe(250); + expect(inactive.notificationActive).toBe(false); + expect(inactive.notificationThreshold).toBeUndefined(); + }); + + test.each([ + [100, true, false], + [95, false, true], + [50, false, false], + ])( + "derives exceeded states at %s percent", + (percentage, storageExceeded, storageAlmostExceeded) => { + const metrics = new StorageMetricsDetailed( + buildStorageMetricsData({ + meta: { totalUsageInPercentage: percentage, totalUsageInBytes: 100 }, + }), + ); + + expect(metrics.storageExceeded).toBe(storageExceeded); + expect(metrics.storageAlmostExceeded).toBe(storageAlmostExceeded); + }, + ); + + test("derives the storage limit and its constrained suggestion", () => { + const withoutLimit = new StorageMetricsDetailed(buildStorageMetricsData()); + const withLimit = new StorageMetricsDetailed( + buildStorageMetricsData({ + meta: { totalUsageInBytes: 100, limitInBytes: 1000 }, + }), + ); + + expect(withoutLimit.storageLimit).toBeUndefined(); + expect(withLimit.storageLimit?.value).toBe(1000); + expect(withLimit.notificationThresholdSuggestion.value).toBe(1000); + }); + + test("suggests one GiB when usage below one GiB has no limit", () => { + const metrics = new StorageMetricsDetailed( + buildStorageMetricsData({ meta: { totalUsageInBytes: 1 } }), + ); + + expect(metrics.notificationThresholdSuggestion.value).toBe(1073741824); + }); + + test("hides total available storage when the threshold is used as limit", () => { + const metrics = new StorageMetricsDetailed( + buildStorageMetricsData({ + meta: { + notificationThresholdUsedAsLimit: true, + totalUsageInBytes: 500, + totalFreeInBytes: 500, + }, + }), + ); + + expect(metrics.totalStorageAvailable).toBeUndefined(); + }); + + test("materializes statistic categories", () => { + const metrics = new StorageMetricsDetailed( + buildStorageMetricsData({ + statisticCategories: [ + buildStorageStatisticsCategoryData({ totalUsageInBytes: 1234 }), + ], + }), + ); + + expect(metrics.statisticCategories.webspace.totalUsage.value).toBe(1234); + }); + + test("sorts project statistics by descending usage", () => { + const metrics = new StorageMetricsDetailed( + buildStorageMetricsData({ + childStatistics: [ + buildStorageMetricsData({ + meta: { totalUsageInBytes: 100 }, + kind: "project", + id: "p-low", + }), + buildStorageMetricsData({ + meta: { totalUsageInBytes: 999 }, + id: "server-child", + kind: "server", + }), + buildStorageMetricsData({ + meta: { totalUsageInBytes: 500 }, + kind: "project", + id: "p-high", + }), + ], + }), + ); + + expect(metrics.projectStatistics).toHaveLength(2); + expect( + metrics.projectStatistics?.map((item) => item.totalStorageUsage.value), + ).toEqual([500, 100]); + expect(metrics.projectStatistics?.map((item) => item.project.id)).toEqual([ + "p-high", + "p-low", + ]); + expect( + metrics.projectStatistics?.every( + (item) => item.project instanceof Project, + ), + ).toBe(true); + }); + + test("parses the exceedance timestamp", () => { + const metrics = new StorageMetricsDetailed( + buildStorageMetricsData({ + meta: { + totalExceedanceInBytesSetAt: "2025-01-02T03:04:05.000Z", + totalUsageInBytes: 100, + }, + }), + ); + + expect(metrics.exceedanceSetAt).toBeInstanceOf(DateTime); + }); +}); diff --git a/packages/models/src/monitoring/StorageMetrics/StorageMetrics.ts b/packages/models/src/monitoring/StorageMetrics/StorageMetrics.ts new file mode 100644 index 00000000..6226986a --- /dev/null +++ b/packages/models/src/monitoring/StorageMetrics/StorageMetrics.ts @@ -0,0 +1,162 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; + +import type { + ServerProjectStatistics, + StorageMetricsData, + StorageMetricsKind, +} from "./types.js"; + +import { StorageStatisticsCategory } from "./StorageStatisticsCategory.js"; +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { ReferenceModel, WithData } from "../../base/index.js"; +import { Project } from "../../project/internal.js"; +import { config } from "../../config/index.js"; +import { Bytes } from "../../common/index.js"; + +@GhostMakerModel({ + name: "StorageMetrics", +}) +export class StorageMetrics extends ReferenceModel { + public static readonly storageUsageError = 100; + public static readonly storageUsageWarning = 90; + public readonly kind: StorageMetricsKind; + + public constructor(id: string, kind: StorageMetricsKind) { + super(id); + this.kind = kind; + } + + public static async find(id: string, type: StorageMetricsKind) { + const data = + type === "project" + ? await config.behaviors.storageMetrics.findByProject(id) + : await config.behaviors.storageMetrics.findByServer(id); + + if (data !== undefined) { + return new StorageMetricsDetailed(data); + } + } + + public static async get(id: string, type: StorageMetricsKind) { + const storageMetrics = await StorageMetrics.find(id, type); + assertObjectFound(storageMetrics, StorageMetrics, id); + return storageMetrics; + } + + public static ofId(id: string, kind: StorageMetricsKind) { + return new StorageMetrics(id, kind); + } +} + +export class StorageMetricsDetailed extends WithData()( + StorageMetrics, +) { + public readonly childStatistics?: StorageMetricsDetailed[]; + public override readonly data: StorageMetricsData; + public readonly exceedanceSetAt?: DateTime; + public readonly notificationActive: boolean; + public readonly notificationThreshold?: Bytes; + public readonly notificationThresholdSuggestion: Bytes; + public readonly notificationThresholdUsedAsLimit: boolean; + public readonly projectStatistics?: ServerProjectStatistics; + public readonly statisticCategories: { + container: StorageStatisticsCategory; + webspace: StorageStatisticsCategory; + backup: StorageStatisticsCategory; + mySql: StorageStatisticsCategory; + redis: StorageStatisticsCategory; + mail: StorageStatisticsCategory; + }; + public readonly storageAlmostExceeded: boolean; + public readonly storageExceeded: boolean; + public readonly storageLimit?: Bytes; + public readonly totalStorageAvailable?: Bytes; + public readonly totalStorageFree?: Bytes; + public readonly totalStorageUsage: Bytes; + + public constructor(data: StorageMetricsData) { + super(data.id, data.kind); + this.data = data; + this.childStatistics = data.childStatistics?.map( + (s) => new StorageMetricsDetailed(s), + ); + this.notificationActive = !!data.notificationThresholdInBytes; + this.notificationThreshold = data.notificationThresholdInBytes + ? Bytes.of(data.notificationThresholdInBytes, "bytes") + : undefined; + this.totalStorageUsage = Bytes.of(data.meta.totalUsageInBytes, "bytes"); + this.storageLimit = data.meta.limitInBytes + ? Bytes.of(data.meta.limitInBytes, "bytes") + : undefined; + + this.notificationThresholdSuggestion = this.storageLimit + ? this.storageLimit.multiply(0.8) + : this.totalStorageUsage.gib < 1 + ? Bytes.of(1, "GiB") + : this.totalStorageUsage.multiply(1.5); + if ( + this.storageLimit && + this.storageLimit.isGreaterThan(this.notificationThresholdSuggestion) + ) { + this.notificationThresholdSuggestion = this.storageLimit; + } + this.notificationThresholdUsedAsLimit = + !!data.meta.notificationThresholdUsedAsLimit; + this.storageExceeded = data.meta.totalUsageInPercentage + ? data.meta.totalUsageInPercentage >= StorageMetrics.storageUsageError + : false; + this.storageAlmostExceeded = data.meta.totalUsageInPercentage + ? !this.storageExceeded && + data.meta.totalUsageInPercentage >= StorageMetrics.storageUsageWarning + : false; + + this.statisticCategories = { + container: new StorageStatisticsCategory( + data.statisticCategories?.find((c) => c.kind === "containerVolume"), + ), + backup: new StorageStatisticsCategory( + data.statisticCategories?.find((c) => c.kind === "projectBackup"), + ), + mySql: new StorageStatisticsCategory( + data.statisticCategories?.find((c) => c.kind === "mysqlDatabase"), + ), + redis: new StorageStatisticsCategory( + data.statisticCategories?.find((c) => c.kind === "redisDatabase"), + ), + webspace: new StorageStatisticsCategory( + data.statisticCategories?.find((c) => c.kind === "webspace"), + ), + mail: new StorageStatisticsCategory( + data.statisticCategories?.find((c) => c.kind === "mailAddress"), + ), + }; + + this.totalStorageFree = data.meta.totalFreeInBytes + ? Bytes.of(data.meta.totalFreeInBytes, "bytes") + : undefined; + + const totalStorageAvailable = this.totalStorageFree + ? this.totalStorageUsage.add(this.totalStorageFree) + : this.storageLimit; + + this.totalStorageAvailable = this.notificationThresholdUsedAsLimit + ? undefined + : totalStorageAvailable; + + this.projectStatistics = data.childStatistics + ?.filter((s) => s.kind === "project") + .sort((a, b) => b.meta.totalUsageInBytes - a.meta.totalUsageInBytes) + .map((s) => ({ + notificationThreshold: s.notificationThresholdInBytes + ? Bytes.of(s.notificationThresholdInBytes, "bytes") + : undefined, + totalStorageUsage: Bytes.of(s.meta.totalUsageInBytes, "bytes"), + project: Project.ofId(s.id), + })); + + this.exceedanceSetAt = data.meta.totalExceedanceInBytesSetAt + ? DateTime.fromISO(data.meta.totalExceedanceInBytesSetAt) + : undefined; + } +} diff --git a/packages/models/src/monitoring/StorageMetrics/StorageStatisticsCategory.test.ts b/packages/models/src/monitoring/StorageMetrics/StorageStatisticsCategory.test.ts new file mode 100644 index 00000000..335cb604 --- /dev/null +++ b/packages/models/src/monitoring/StorageMetrics/StorageStatisticsCategory.test.ts @@ -0,0 +1,57 @@ +import { afterEach, describe, expect, test } from "vitest"; +import { DateTime } from "luxon"; + +import { buildStorageStatisticsCategoryData } from "../../testing/builders/buildStorageMetricsData.js"; +import { StorageStatisticsCategory } from "./StorageStatisticsCategory.js"; +import { resetBehaviors } from "../../testing/installBehaviors.js"; + +afterEach(resetBehaviors); + +describe("StorageStatisticsCategory", () => { + test("uses empty values when constructed without data", () => { + const category = new StorageStatisticsCategory(undefined); + + expect(category.kind).toBeUndefined(); + expect(category.totalUsage.value).toBe(0); + expect(category.updatedAt).toBeUndefined(); + expect(category.data).toBeUndefined(); + }); + + test("exposes frozen category data and its total usage", () => { + const category = new StorageStatisticsCategory( + buildStorageStatisticsCategoryData({ + totalUsageInBytes: 2048, + kind: "mysqlDatabase", + }), + ); + + expect(category.kind).toBe("mysqlDatabase"); + expect(category.totalUsage.value).toBe(2048); + expect(Object.isFrozen(category.data)).toBe(true); + }); + + test("uses the first resource timestamp as updatedAt", () => { + const category = new StorageStatisticsCategory( + buildStorageStatisticsCategoryData({ + resources: [ + { + usageInBytesSetAt: "2025-01-02T03:04:05.000Z", + usageInBytes: 100, + id: "resource-1", + name: "Resource", + }, + ], + }), + ); + + expect(category.updatedAt).toBeInstanceOf(DateTime); + }); + + test("has no updatedAt without resources", () => { + const category = new StorageStatisticsCategory( + buildStorageStatisticsCategoryData(), + ); + + expect(category.updatedAt).toBeUndefined(); + }); +}); diff --git a/packages/models/src/monitoring/StorageMetrics/StorageStatisticsCategory.ts b/packages/models/src/monitoring/StorageMetrics/StorageStatisticsCategory.ts new file mode 100644 index 00000000..ff3988ac --- /dev/null +++ b/packages/models/src/monitoring/StorageMetrics/StorageStatisticsCategory.ts @@ -0,0 +1,26 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import { DateTime } from "luxon"; + +import { Bytes } from "../../common/index.js"; + +export type StorageStatisticsCategoryApiData = + MittwaldAPIV2.Components.Schemas.StoragespaceStatisticsCategory; +export type StorageStatisticsCategoryKind = + MittwaldAPIV2.Components.Schemas.StoragespaceStatisticsCategoryKind; + +export class StorageStatisticsCategory { + public readonly data?: StorageStatisticsCategoryApiData; + public readonly kind?: StorageStatisticsCategoryKind; + public readonly totalUsage: Bytes; + public readonly updatedAt?: DateTime; + + public constructor(data?: StorageStatisticsCategoryApiData) { + this.data = Object.freeze(data); + this.kind = data?.kind; + this.totalUsage = new Bytes(data?.totalUsageInBytes ?? 0); + + const updatedAt = data?.resources?.[0]?.usageInBytesSetAt; + this.updatedAt = updatedAt ? DateTime.fromISO(updatedAt) : undefined; + } +} diff --git a/packages/models/src/monitoring/StorageMetrics/behaviors/api.ts b/packages/models/src/monitoring/StorageMetrics/behaviors/api.ts new file mode 100644 index 00000000..f2158969 --- /dev/null +++ b/packages/models/src/monitoring/StorageMetrics/behaviors/api.ts @@ -0,0 +1,31 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { StorageMetricsBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; + +export const apiStorageMetricsBehaviors = ( + client: MittwaldAPIV2Client, +): StorageMetricsBehaviors => ({ + findByProject: async (projectId) => { + const response = await client.project.storagespaceGetProjectStatistics({ + projectId, + }); + + if (response.status === 200) { + return response.data; + } + validateResponse(response, [403]); + }, + + findByServer: async (serverId) => { + const response = await client.project.storagespaceGetServerStatistics({ + serverId, + }); + + if (response.status === 200) { + return response.data; + } + validateResponse(response, [403]); + }, +}); diff --git a/packages/models/src/monitoring/StorageMetrics/behaviors/index.ts b/packages/models/src/monitoring/StorageMetrics/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/monitoring/StorageMetrics/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/monitoring/StorageMetrics/behaviors/types.ts b/packages/models/src/monitoring/StorageMetrics/behaviors/types.ts new file mode 100644 index 00000000..fe75578c --- /dev/null +++ b/packages/models/src/monitoring/StorageMetrics/behaviors/types.ts @@ -0,0 +1,6 @@ +import type { StorageMetricsData } from "../types.js"; + +export interface StorageMetricsBehaviors { + findByProject: (projectId: string) => Promise; + findByServer: (serverId: string) => Promise; +} diff --git a/packages/models/src/monitoring/StorageMetrics/index.ts b/packages/models/src/monitoring/StorageMetrics/index.ts new file mode 100644 index 00000000..e55b6137 --- /dev/null +++ b/packages/models/src/monitoring/StorageMetrics/index.ts @@ -0,0 +1,3 @@ +export * from "./StorageMetrics.js"; +export * from "./StorageStatisticsCategory.js"; +export * from "./types.js"; diff --git a/packages/models/src/monitoring/StorageMetrics/types.ts b/packages/models/src/monitoring/StorageMetrics/types.ts new file mode 100644 index 00000000..251894fd --- /dev/null +++ b/packages/models/src/monitoring/StorageMetrics/types.ts @@ -0,0 +1,16 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import type { Project } from "../../project/index.js"; +import type { Bytes } from "../../common/index.js"; + +export type StorageMetricsData = + MittwaldAPIV2.Components.Schemas.StoragespaceStatistics; + +export type StorageMetricsKind = + MittwaldAPIV2.Components.Schemas.StoragespaceStatisticsKind; + +export type ServerProjectStatistics = { + notificationThreshold?: Bytes; + totalStorageUsage: Bytes; + project: Project; +}[]; diff --git a/packages/models/src/monitoring/UsageMetrics/Metrics.ts b/packages/models/src/monitoring/UsageMetrics/Metrics.ts new file mode 100644 index 00000000..c31d47c3 --- /dev/null +++ b/packages/models/src/monitoring/UsageMetrics/Metrics.ts @@ -0,0 +1,31 @@ +import type { DateValue } from "@internationalized/date"; + +import { MetricsQueryRequest } from "../lib/metrics/index.js"; + +export interface MetricsRequestOptions { + from?: DateValue; + to?: DateValue; +} + +export class Metrics { + public static getRequest( + expression: string, + options?: MetricsRequestOptions, + ): MetricsQueryRequest { + const from = options?.from?.toDate("Europe/Berlin").toISOString(); + const to = options?.to?.toDate("Europe/Berlin").toISOString(); + + return new MetricsQueryRequest({ + queries: [ + { + datasource: { uid: "MetricsAuthPrometheus", type: "prometheus" }, + refId: MetricsQueryRequest.defaultRefId, + maxDataPoints: 1000, + expr: expression, + }, + ], + from, + to, + }); + } +} diff --git a/packages/models/src/monitoring/UsageMetrics/MetricsTimeRange.ts b/packages/models/src/monitoring/UsageMetrics/MetricsTimeRange.ts new file mode 100644 index 00000000..2749fe35 --- /dev/null +++ b/packages/models/src/monitoring/UsageMetrics/MetricsTimeRange.ts @@ -0,0 +1,67 @@ +import type { DurationLikeObject, DateTimeUnit } from "luxon"; +import type { DateValue } from "@internationalized/date"; + +import { DateTime } from "luxon"; + +import type { MonitoringInterval } from "./types.js"; + +export class MetricsTimeRange { + public readonly from?: DateValue; + public readonly interval: MonitoringInterval; + public readonly to?: DateValue; + + public constructor( + interval: MonitoringInterval, + from?: DateValue, + to?: DateValue, + ) { + this.interval = interval; + this.from = from; + this.to = to; + } + + public getRangeMillis(): [number, number] { + const from = this.from?.toDate("Europe/Berlin").toISOString(); + const fromDate = from ? DateTime.fromISO(from) : undefined; + + const to = this.to?.toDate("Europe/Berlin").toISOString(); + const toDate = to ? DateTime.fromISO(to) : undefined; + + return [fromDate ? fromDate.toMillis() : 0, toDate ? toDate.toMillis() : 0]; + } + + public getSlices(): DateTime[] { + const tickDuration: Record< + MonitoringInterval, + keyof DurationLikeObject & DateTimeUnit + > = { + multipleDays: "day", + oneHour: "minute", + oneDay: "hour", + }; + + const slices: DateTime[] = []; + + const from = this.from?.toDate("Europe/Berlin").toISOString(); + const fromDate = from ? DateTime.fromISO(from) : undefined; + + const to = this.to?.toDate("Europe/Berlin").toISOString(); + const toDate = to ? DateTime.fromISO(to) : undefined; + let currentDate = fromDate; + + if (!currentDate || !toDate) { + return slices; + } + + while (currentDate < toDate) { + slices.push(currentDate); + currentDate = currentDate.plus({ + [tickDuration[this.interval]]: this.interval === "oneHour" ? 5 : 1, + }); + } + + return slices; + } +} + +export default MetricsTimeRange; diff --git a/packages/models/src/monitoring/UsageMetrics/ProjectUsageMetrics.ts b/packages/models/src/monitoring/UsageMetrics/ProjectUsageMetrics.ts new file mode 100644 index 00000000..00e4b1c3 --- /dev/null +++ b/packages/models/src/monitoring/UsageMetrics/ProjectUsageMetrics.ts @@ -0,0 +1,87 @@ +import type { MetricsQueryRequest } from "../lib/metrics/index.js"; +import type { MetricsRequestOptions } from "./Metrics.js"; +import type { ProjectDetailed } from "../../project/index.js"; + +import { Metrics } from "./Metrics.js"; + +export class ProjectUsageMetrics { + public readonly project: ProjectDetailed; + + public constructor(project: ProjectDetailed) { + this.project = project; + } + + public static of(project: ProjectDetailed): ProjectUsageMetrics { + return new ProjectUsageMetrics(project); + } + + public getCpuUsage(options: MetricsRequestOptions): MetricsQueryRequest { + if (this.project.isProSpaceLite) { + return Metrics.getRequest( + ` + SUM (cloudhosting_project_usage_cpu_seconds_total_rate:5m{project="${this.project.shortId}"}) / + SUM (cloudhosting_project_limits_cpu_seconds:5m{project="${this.project.shortId}"}) + `, + options, + ); + } + + if (this.project.server) { + return Metrics.getRequest( + ` + SUM (cloudhosting_project_usage_cpu_seconds_total_rate:5m{project="${this.project.shortId}"}) / + SUM (cloudhosting_projectgroup_limits_cpu_seconds:5m{project_group="${this.project.serverGroupId}"}) + `, + options, + ); + } + + return Metrics.getRequest( + `clamp_max( + (SUM (cloudhosting_databasesetmember_usage_cpu_seconds_total_rate:5m{project_group="${this.project.serverGroupId}"} or vector (0)) + + SUM (cloudhosting_project_usage_cpu_seconds_total_rate:5m{project="${this.project.shortId}"})) / + SUM (cloudhosting_projectgroup_limits_cpu_seconds:5m{project_group="${this.project.serverGroupId}"}), + 1)`, + options, + ); + } + + public getMemoryUsage(options: MetricsRequestOptions): MetricsQueryRequest { + if (this.project.isProSpaceLite) { + return Metrics.getRequest( + `SUM (cloudhosting_project_usage_memory_bytes:5m:max{project="${this.project.shortId}"}) / + SUM (cloudhosting_project_limits_memory_bytes:5m{project="${this.project.shortId}"})`, + options, + ); + } + + if (this.project.server) { + return Metrics.getRequest( + ` + SUM (cloudhosting_project_usage_memory_bytes:5m:max{project="${this.project.shortId}"}) / + SUM (cloudhosting_projectgroup_limits_memory_bytes:5m{project_group="${this.project.serverGroupId}"}) + `, + options, + ); + } + + return Metrics.getRequest( + ` + (SUM (cloudhosting_databasesetmember_usage_memory_bytes:5m:max{project_group="${this.project.serverGroupId}"} or vector (0)) + + SUM (cloudhosting_project_usage_memory_bytes:5m:max{project="${this.project.shortId}"})) / + SUM (cloudhosting_projectgroup_limits_memory_bytes:5m{project_group="${this.project.serverGroupId}"})`, + options, + ); + } + + public getUsage( + type: "cpu" | "ram", + options: MetricsRequestOptions, + ): MetricsQueryRequest { + if (type === "cpu") { + return this.getCpuUsage(options); + } else { + return this.getMemoryUsage(options); + } + } +} diff --git a/packages/models/src/monitoring/UsageMetrics/ServerUsageMetrics.ts b/packages/models/src/monitoring/UsageMetrics/ServerUsageMetrics.ts new file mode 100644 index 00000000..608e0462 --- /dev/null +++ b/packages/models/src/monitoring/UsageMetrics/ServerUsageMetrics.ts @@ -0,0 +1,169 @@ +import type { MetricsRequestOptions } from "./Metrics.js"; +import type { ServerDetailed } from "../../server/index.js"; +import type { + ServerMetricsDataObject, + MetricsQueryRequest, +} from "../lib/metrics/index.js"; + +import { Metrics } from "./Metrics.js"; + +export class ServerUsageMetrics { + public readonly server: ServerDetailed; + + private constructor(server: ServerDetailed) { + this.server = server; + } + + public static of(server: ServerDetailed): ServerUsageMetrics { + return new ServerUsageMetrics(server); + } + + public getCpuLimit(): MetricsQueryRequest { + return Metrics.getRequest( + `SUM (cloudhosting_projectgroup_limits_cpu_seconds:5m{project_group="${this.server.groupId}"})`, + ); + } + + public getCpuUsage(options: MetricsRequestOptions): MetricsQueryRequest { + return Metrics.getRequest( + ` + (SUM (cloudhosting_databasesetmember_usage_cpu_seconds_total_rate:5m{project_group="${this.server.groupId}"} or vector (0)) + + SUM (cloudhosting_project_usage_cpu_seconds_total_rate:5m{project_group="${this.server.groupId}"})) / + SUM (cloudhosting_projectgroup_limits_cpu_seconds:5m{project_group="${this.server.groupId}"}) + `, + options, + ); + } + + public getDbCpuUsage(options: MetricsRequestOptions): MetricsQueryRequest { + return Metrics.getRequest( + `SUM(cloudhosting_databasesetmember_usage_cpu_seconds_total_rate:5m{project_group="${this.server.groupId}"} OR vector(0)) by (database_type, database_version)`, + options, + ); + } + + public getDbMemoryUsage(options: MetricsRequestOptions): MetricsQueryRequest { + return Metrics.getRequest( + `SUM(cloudhosting_databasesetmember_usage_memory_bytes:5m:max{project_group="${this.server.groupId}"} OR vector(0)) by (database_type, database_version)`, + options, + ); + } + + public getDetailedUsage( + type: "cpu" | "ram", + options: MetricsRequestOptions, + ): Promise { + if (type === "cpu") { + return this.getServerCpuMetrics(options); + } else { + return this.getServerMemoryMetrics(options); + } + } + + public getMemoryLimit(): MetricsQueryRequest { + return Metrics.getRequest( + `SUM (cloudhosting_projectgroup_limits_memory_bytes:5m{project_group="${this.server.groupId}"})`, + ); + } + + public getMemoryUsage(options: MetricsRequestOptions): MetricsQueryRequest { + return Metrics.getRequest( + ` + (SUM (cloudhosting_databasesetmember_usage_memory_bytes:5m:max{project_group="${this.server.groupId}"} or vector (0)) + + SUM (cloudhosting_project_usage_memory_bytes:5m:max{project_group="${this.server.groupId}"})) / + SUM (cloudhosting_projectgroup_limits_memory_bytes:5m{project_group="${this.server.groupId}"}) + `, + options, + ); + } + + public getProjectCpuUsage( + options: MetricsRequestOptions, + ): MetricsQueryRequest { + return Metrics.getRequest( + `SUM (cloudhosting_project_usage_cpu_seconds_total_rate:5m{project_group="${this.server.groupId}"} OR vector(0)) / + SUM (cloudhosting_projectgroup_limits_cpu_seconds:5m{project_group="${this.server.groupId}"})`, + options, + ); + } + + public getProjectMemoryUsage( + options: MetricsRequestOptions, + ): MetricsQueryRequest { + return Metrics.getRequest( + `SUM (cloudhosting_project_usage_memory_bytes:5m:max{project_group="${this.server.groupId}"} OR vector(0)) / + SUM (cloudhosting_projectgroup_limits_memory_bytes:5m{project_group="${this.server.groupId}"})`, + options, + ); + } + + public async getServerCpuMetrics( + options: MetricsRequestOptions, + ): Promise { + const projectUsage = await this.getProjectCpuUsage({ + from: options.from, + to: options.to, + }).getData(); + const dbUsage = await this.getDbCpuUsage({ + from: options.from, + to: options.to, + }).getData(); + const summaryUsage = await this.getCpuUsage({ + from: options.from, + to: options.to, + }).getData(); + const limitResponse = await this.getCpuLimit().getData(); + const limit = limitResponse.getFirstValue() ?? 0; + + return { + databases: dbUsage.getMultiFrameDataPoints([ + "database_type", + "database_version", + ]), + project: projectUsage.getDataPoints(), + summary: summaryUsage.getDataPoints(), + limit, + }; + } + + public async getServerMemoryMetrics( + options: MetricsRequestOptions, + ): Promise { + const projectUsage = await this.getProjectMemoryUsage({ + from: options.from, + to: options.to, + }).getData(); + const dbUsage = await this.getDbMemoryUsage({ + from: options.from, + to: options.to, + }).getData(); + const summaryUsage = await this.getMemoryUsage({ + from: options.from, + to: options.to, + }).getData(); + + const limitResponse = await this.getMemoryLimit().getData(); + const limit = limitResponse.getFirstValue() ?? 0; + + return { + databases: dbUsage.getMultiFrameDataPoints([ + "database_type", + "database_version", + ]), + project: projectUsage.getDataPoints(), + summary: summaryUsage.getDataPoints(), + limit, + }; + } + + public getUsage( + type: "cpu" | "ram", + options: MetricsRequestOptions, + ): MetricsQueryRequest { + if (type === "cpu") { + return this.getCpuUsage(options); + } else { + return this.getMemoryUsage(options); + } + } +} diff --git a/packages/models/src/monitoring/UsageMetrics/TimeSeriesBin.ts b/packages/models/src/monitoring/UsageMetrics/TimeSeriesBin.ts new file mode 100644 index 00000000..854cb206 --- /dev/null +++ b/packages/models/src/monitoring/UsageMetrics/TimeSeriesBin.ts @@ -0,0 +1,78 @@ +import type { DateTimeFormatOptions } from "luxon"; +import type { Bin } from "d3-array"; + +import invariant from "tiny-invariant"; +import { DateTime } from "luxon"; +import * as d3 from "d3-array"; + +import type { MetricsDataPoint } from "../lib/metrics/index.js"; +import type MetricsTimeRange from "./MetricsTimeRange.js"; +import type { MonitoringInterval } from "./types.js"; + +export class TimeSeriesBin { + public readonly data: Bin; + public readonly timeRange: MetricsTimeRange; + + public get max(): number | undefined { + const max = d3.max( + this.data.map((d) => TimeSeriesBin.getPercentage(d.value)), + ); + return max ? Math.round(max * 10) / 10 : 0; + } + + public get mean(): number { + const mean = d3.mean( + this.data.map((d) => TimeSeriesBin.getPercentage(d.value)), + ); + return mean ? Math.round(mean * 10) / 10 : 0; + } + + public get timeMillis() { + const timeMillis = this.data.x0 ?? this.data.x1; + invariant(timeMillis, "Invalid x0/x1"); + + return timeMillis; + } + + public constructor( + data: Bin, + timeRange: MetricsTimeRange, + ) { + this.data = data; + this.timeRange = timeRange; + } + + public static getTimeLabel( + millis: number, + interval: MonitoringInterval, + short?: boolean, + ): string { + const time = DateTime.fromMillis(millis); + + const rangeTypeFormat: Record = { + oneHour: { + month: short ? undefined : "numeric", + day: short ? undefined : "numeric", + minute: "numeric", + hour: "numeric", + }, + oneDay: { + month: short ? undefined : "numeric", + day: short ? undefined : "numeric", + minute: "numeric", + hour: "numeric", + }, + multipleDays: { + weekday: short ? "short" : "long", + month: "numeric", + day: "numeric", + }, + }; + + return time.toLocaleString(rangeTypeFormat[interval]); + } + + private static getPercentage(value: number): number { + return Number((value * 100).toFixed(1)); + } +} diff --git a/packages/models/src/monitoring/UsageMetrics/TimeSeriesBins.ts b/packages/models/src/monitoring/UsageMetrics/TimeSeriesBins.ts new file mode 100644 index 00000000..ae6f8816 --- /dev/null +++ b/packages/models/src/monitoring/UsageMetrics/TimeSeriesBins.ts @@ -0,0 +1,30 @@ +import * as d3 from "d3-array"; + +import type { MetricsDataPoint } from "../lib/metrics/index.js"; +import type MetricsTimeRange from "./MetricsTimeRange.js"; + +import { TimeSeriesBin } from "./TimeSeriesBin.js"; + +/** Groups time series values into "time bins" */ +export class TimeSeriesBins { + public readonly bins: TimeSeriesBin[]; + public readonly label?: string; + public readonly timeRange: MetricsTimeRange; + + public constructor( + dataPoints: MetricsDataPoint[], + range: MetricsTimeRange, + label?: string, + ) { + this.timeRange = range; + this.label = label; + this.bins = d3 + .bin() + .domain(range.getRangeMillis()) + .value((d) => d.date.toMillis()) + .thresholds(range.getSlices().map((s) => s.toMillis()))(dataPoints) + .map((b) => new TimeSeriesBin(b, range)); + } +} + +export default TimeSeriesBins; diff --git a/packages/models/src/monitoring/UsageMetrics/behaviors/api.ts b/packages/models/src/monitoring/UsageMetrics/behaviors/api.ts new file mode 100644 index 00000000..f2f5d0f9 --- /dev/null +++ b/packages/models/src/monitoring/UsageMetrics/behaviors/api.ts @@ -0,0 +1,25 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import invariant from "tiny-invariant"; +import { DateTime } from "luxon"; + +import type { UsageMetricsBehaviors } from "./types.js"; + +export const apiUsageMetricsBehaviors = ( + client: MittwaldAPIV2Client, + backendUri: string, +): UsageMetricsBehaviors => ({ + getData: async (request) => { + const { from, to, ...restApiData } = request; + + const response = await client.axios.post(backendUri, { + from: from ? from : DateTime.now().toISO(), + to: to ? to : DateTime.now().toISO(), + ...restApiData, + }); + + invariant(response.status === 200, "Failed to fetch metrics data"); + + return response.data; + }, +}); diff --git a/packages/models/src/monitoring/UsageMetrics/behaviors/types.ts b/packages/models/src/monitoring/UsageMetrics/behaviors/types.ts new file mode 100644 index 00000000..99b1ea4b --- /dev/null +++ b/packages/models/src/monitoring/UsageMetrics/behaviors/types.ts @@ -0,0 +1,10 @@ +import type { + MetricsQueryResponseApiData, + MetricsQueryRequestApiData, +} from "../../lib/metrics/index.js"; + +export interface UsageMetricsBehaviors { + getData: ( + request: MetricsQueryRequestApiData, + ) => Promise; +} diff --git a/packages/models/src/monitoring/UsageMetrics/index.ts b/packages/models/src/monitoring/UsageMetrics/index.ts new file mode 100644 index 00000000..4f31628b --- /dev/null +++ b/packages/models/src/monitoring/UsageMetrics/index.ts @@ -0,0 +1,6 @@ +export * from "./MetricsTimeRange.js"; +export * from "./ProjectUsageMetrics.js"; +export * from "./ServerUsageMetrics.js"; +export * from "./TimeSeriesBin.js"; +export * from "./TimeSeriesBins.js"; +export * from "./types.js"; diff --git a/packages/models/src/monitoring/UsageMetrics/types.ts b/packages/models/src/monitoring/UsageMetrics/types.ts new file mode 100644 index 00000000..5f2c60eb --- /dev/null +++ b/packages/models/src/monitoring/UsageMetrics/types.ts @@ -0,0 +1 @@ +export type MonitoringInterval = "multipleDays" | "oneHour" | "oneDay"; diff --git a/packages/models/src/monitoring/index.ts b/packages/models/src/monitoring/index.ts new file mode 100644 index 00000000..307e39cc --- /dev/null +++ b/packages/models/src/monitoring/index.ts @@ -0,0 +1,2 @@ +export * from "./StorageMetrics/index.js"; +export * from "./UsageMetrics/index.js"; diff --git a/packages/models/src/monitoring/lib/metrics/MetricsQueryRequest.ts b/packages/models/src/monitoring/lib/metrics/MetricsQueryRequest.ts new file mode 100644 index 00000000..cb9a52ce --- /dev/null +++ b/packages/models/src/monitoring/lib/metrics/MetricsQueryRequest.ts @@ -0,0 +1,21 @@ +import type { MetricsQueryRequestApiData } from "./types.js"; + +import { MetricsQueryResponse } from "./MetricsQueryResponse.js"; +import { config } from "../../../config/index.js"; + +export class MetricsQueryRequest { + public static defaultRefId = "Result"; + + private readonly requestData: MetricsQueryRequestApiData; + + public constructor(requestData: MetricsQueryRequestApiData) { + this.requestData = requestData; + } + + public async getData(): Promise { + const data = await config.behaviors.usageMetrics.getData(this.requestData); + return new MetricsQueryResponse(data); + } +} + +export default MetricsQueryRequest; diff --git a/packages/models/src/monitoring/lib/metrics/MetricsQueryResponse.ts b/packages/models/src/monitoring/lib/metrics/MetricsQueryResponse.ts new file mode 100644 index 00000000..03364610 --- /dev/null +++ b/packages/models/src/monitoring/lib/metrics/MetricsQueryResponse.ts @@ -0,0 +1,75 @@ +import { DateTime } from "luxon"; + +import type { + MetricsFrameDataPointObject, + MetricsQueryResponseApiData, + MetricsDataPoint, +} from "./types.js"; + +import MetricsQueryRequest from "./MetricsQueryRequest.js"; + +export class MetricsQueryResponse { + public readonly data: MetricsQueryResponseApiData; + + public constructor(data: MetricsQueryResponseApiData) { + this.data = data; + } + + public getDataPoints(): MetricsDataPoint[] { + const dataPoints = + this.data.results[MetricsQueryRequest.defaultRefId]?.frames[0]?.data + .values; + + const timeSeries = dataPoints?.[0] ?? []; + const valueSeries = dataPoints?.[1] ?? []; + + return timeSeries + .map((time, index) => ({ + date: DateTime.fromMillis(time), + value: valueSeries[index]!, + })) + .filter((value) => value.date.toMillis() <= DateTime.now().toMillis()); + } + + public getFirstValue(): number | undefined { + return this.getDataPoints()[0]?.value; + } + + public getMultiFrameDataPoints( + labelName: string[] | string = "database_type", + ): MetricsFrameDataPointObject { + const frames = this.data.results[MetricsQueryRequest.defaultRefId]?.frames; + + return frames?.reduce((prev, curr) => { + const labels = curr.schema.fields[1].labels; + const timeVal = curr.data.values[0].filter( + (t) => t <= DateTime.now().toMillis(), + ); + const val = curr.data.values[1]; + + let finalLabel; + + if (Array.isArray(labelName)) { + if (labels && Object.keys(labels).length > 0) { + for (const label of labelName) { + finalLabel = finalLabel + ? `${finalLabel}-${labels[label]}` + : `${labels[label]}`; + } + } + } else { + finalLabel = labels ? labels[labelName] : undefined; + } + + return { + ...prev, + [finalLabel ? finalLabel : "unlabeled"]: timeVal.map((t, i) => ({ + date: DateTime.fromMillis(t ? t : 0), + value: val[i] ? val[i] : 0, + })), + }; + }, {}) as MetricsFrameDataPointObject; + } +} + +export default MetricsQueryResponse; diff --git a/packages/models/src/monitoring/lib/metrics/index.ts b/packages/models/src/monitoring/lib/metrics/index.ts new file mode 100644 index 00000000..fa3689ba --- /dev/null +++ b/packages/models/src/monitoring/lib/metrics/index.ts @@ -0,0 +1,3 @@ +export * from "./MetricsQueryRequest.js"; +export * from "./MetricsQueryResponse.js"; +export * from "./types.js"; diff --git a/packages/models/src/monitoring/lib/metrics/types.ts b/packages/models/src/monitoring/lib/metrics/types.ts new file mode 100644 index 00000000..1a2c7466 --- /dev/null +++ b/packages/models/src/monitoring/lib/metrics/types.ts @@ -0,0 +1,67 @@ +import type { DateTime } from "luxon"; + +// Request +interface DataSource { + name?: string; + uid: string; + type: T; +} + +interface Query { + datasource: DataSource; + maxDataPoints?: number; + instant?: boolean; + hide?: boolean; + refId: string; +} + +interface PrometheusQuery extends Query<"prometheus"> { + expr: string; +} + +type AnyQuery = PrometheusQuery; + +type MetricsQueryTimeRangeValue = number | string; + +export interface MetricsQueryTimeRange { + from: MetricsQueryTimeRangeValue; + to: MetricsQueryTimeRangeValue; +} + +export interface MetricsQueryRequestApiData extends Partial { + queries: AnyQuery[]; +} + +// Response +type MetricsQueryResponseDataValues = [number[], number[]]; + +interface MetricsSchemaField { + labels?: Record; +} + +interface MetricsQueryResponseFrame { + schema: { fields: [MetricsSchemaField, MetricsSchemaField] }; + data: { values: MetricsQueryResponseDataValues }; +} + +interface MetricsQueryResponseResult { + frames: MetricsQueryResponseFrame[]; +} + +export interface MetricsQueryResponseApiData { + results: Record; +} + +export interface MetricsDataPoint { + date: DateTime; + value: number; +} + +export type MetricsFrameDataPointObject = Record; + +export interface ServerMetricsDataObject { + databases: MetricsFrameDataPointObject; + project: MetricsDataPoint[]; + summary: MetricsDataPoint[]; + limit: number; +} diff --git a/packages/models/src/newsletter/Newsletter/Newsletter.test.ts b/packages/models/src/newsletter/Newsletter/Newsletter.test.ts new file mode 100644 index 00000000..5f138214 --- /dev/null +++ b/packages/models/src/newsletter/Newsletter/Newsletter.test.ts @@ -0,0 +1,93 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { buildNewsletterSubscriberUserData } from "../../testing/builders/buildNewsletterSubscriberUserData.js"; +import { buildNewsletterInfoData } from "../../testing/builders/buildNewsletterInfoData.js"; +import { NewsletterInfo, Newsletter } from "./Newsletter.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; + +afterEach(resetBehaviors); + +describe("Newsletter.getInfo", () => { + test("returns newsletter info and forwards the request config", async () => { + const data = buildNewsletterInfoData(); + const getInfo = vi.fn().mockResolvedValue(data); + const requestConfig = { headers: { "x-test": "newsletter" } }; + installBehaviors({ newsletter: { getInfo } }); + + const result = await Newsletter.getInfo(requestConfig); + + expect(result).toBeInstanceOf(NewsletterInfo); + expect(getInfo).toHaveBeenCalledWith(requestConfig); + }); + + test.each([ + [{ registered: false, active: true }, "active"], + [{ registered: true, active: false }, "confirmationPending"], + [{ registered: false, active: false }, "inactive"], + ] as const)("derives status %s as %s", async (overrides, status) => { + const getInfo = vi + .fn() + .mockResolvedValue(buildNewsletterInfoData(overrides)); + installBehaviors({ newsletter: { getInfo } }); + + const result = await Newsletter.getInfo(); + + expect(result.status).toBe(status); + }); + + test("uses the email as the newsletter info id", async () => { + const data = buildNewsletterInfoData({ email: "newsletter@example.com" }); + const getInfo = vi.fn().mockResolvedValue(data); + installBehaviors({ newsletter: { getInfo } }); + + const result = await Newsletter.getInfo(); + + expect(result.id).toBe(data.email); + }); +}); + +describe("Newsletter.subscribe", () => { + test("subscribes with explicit subscriber data without loading the user", async () => { + const subscribe = vi.fn().mockResolvedValue(undefined); + const find = vi.fn(); + installBehaviors({ newsletter: { subscribe }, user: { find } }); + + await Newsletter.subscribe({ firstName: "Grace", lastName: "Hopper" }); + + expect(subscribe).toHaveBeenCalledOnce(); + expect(subscribe).toHaveBeenCalledWith({ + firstName: "Grace", + lastName: "Hopper", + }); + expect(find).not.toHaveBeenCalled(); + }); + + test("subscribes with subscriber data from the current user", async () => { + const userData = buildNewsletterSubscriberUserData(); + const subscribe = vi.fn().mockResolvedValue(undefined); + const find = vi.fn().mockResolvedValue(userData); + installBehaviors({ newsletter: { subscribe }, user: { find } }); + + await Newsletter.subscribe(); + + expect(find).toHaveBeenCalledWith("self", undefined); + expect(subscribe).toHaveBeenCalledWith({ + firstName: userData.person.firstName, + lastName: userData.person.lastName, + }); + }); +}); + +describe("Newsletter.unsubscribe", () => { + test("unsubscribes once", async () => { + const unsubscribe = vi.fn().mockResolvedValue(undefined); + installBehaviors({ newsletter: { unsubscribe } }); + + await Newsletter.unsubscribe(); + + expect(unsubscribe).toHaveBeenCalledOnce(); + }); +}); diff --git a/packages/models/src/newsletter/Newsletter/Newsletter.ts b/packages/models/src/newsletter/Newsletter/Newsletter.ts new file mode 100644 index 00000000..95aa0127 --- /dev/null +++ b/packages/models/src/newsletter/Newsletter/Newsletter.ts @@ -0,0 +1,50 @@ +import type { AxiosRequestConfig } from "axios"; + +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; + +import type { NewsletterInfoData } from "./types.js"; + +import { ReferenceModel, WithData } from "../../base/index.js"; +import { config } from "../../config/index.js"; +import { User } from "../../user/index.js"; + +@GhostMakerModel({ + name: "Newsletter", +}) +export class Newsletter extends ReferenceModel { + public static async getInfo(requestConfig?: AxiosRequestConfig) { + const data = await config.behaviors.newsletter.getInfo(requestConfig); + + return new NewsletterInfo(data); + } + + public static async subscribe(data?: { + firstName: string; + lastName: string; + }) { + const { firstName, lastName } = data ?? (await User.self.getDetailed()); + + await config.behaviors.newsletter.subscribe({ + firstName, + lastName, + }); + } + + public static async unsubscribe() { + await config.behaviors.newsletter.unsubscribe(); + } +} + +export class NewsletterInfo extends WithData()(Newsletter) { + public override readonly data: NewsletterInfoData; + public readonly status: "confirmationPending" | "inactive" | "active"; + public constructor(data: NewsletterInfoData) { + super(data.email); + this.data = data; + this.status = data.active + ? "active" + : data.registered + ? "confirmationPending" + : "inactive"; + } +} diff --git a/packages/models/src/newsletter/Newsletter/behaviors/api.ts b/packages/models/src/newsletter/Newsletter/behaviors/api.ts new file mode 100644 index 00000000..c3c010b0 --- /dev/null +++ b/packages/models/src/newsletter/Newsletter/behaviors/api.ts @@ -0,0 +1,36 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; +import type { AxiosRequestConfig } from "axios"; + +import type { NewsletterBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { withAxiosRequestConfig } from "../../../base/index.js"; + +export const apiNewsletterBehaviors = ( + client: MittwaldAPIV2Client, +): NewsletterBehaviors => ({ + getInfo: async (requestConfig?: AxiosRequestConfig) => { + const response = await client.notification.newsletterGetInfo( + {}, + withAxiosRequestConfig(requestConfig), + ); + + validateResponse(response, 200); + + return response.data; + }, + + subscribe: async (data) => { + const response = await client.notification.newsletterSubscribeUser({ + data, + }); + + validateResponse(response, 200); + }, + + unsubscribe: async () => { + const response = await client.notification.newsletterUnsubscribeUser(); + + validateResponse(response, 204); + }, +}); diff --git a/packages/models/src/newsletter/Newsletter/behaviors/index.ts b/packages/models/src/newsletter/Newsletter/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/newsletter/Newsletter/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/newsletter/Newsletter/behaviors/types.ts b/packages/models/src/newsletter/Newsletter/behaviors/types.ts new file mode 100644 index 00000000..61b503a4 --- /dev/null +++ b/packages/models/src/newsletter/Newsletter/behaviors/types.ts @@ -0,0 +1,11 @@ +import type { AxiosRequestConfig } from "axios"; + +import type { NewsletterSubscribeData, NewsletterInfoData } from "../types.js"; + +export interface NewsletterBehaviors { + getInfo: (requestConfig?: AxiosRequestConfig) => Promise; + + subscribe: (data: NewsletterSubscribeData) => Promise; + + unsubscribe: () => Promise; +} diff --git a/packages/models/src/newsletter/Newsletter/index.ts b/packages/models/src/newsletter/Newsletter/index.ts new file mode 100644 index 00000000..ebc40098 --- /dev/null +++ b/packages/models/src/newsletter/Newsletter/index.ts @@ -0,0 +1,2 @@ +export * from "./Newsletter.js"; +export * from "./types.js"; diff --git a/packages/models/src/newsletter/Newsletter/types.ts b/packages/models/src/newsletter/Newsletter/types.ts new file mode 100644 index 00000000..04724674 --- /dev/null +++ b/packages/models/src/newsletter/Newsletter/types.ts @@ -0,0 +1,7 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type NewsletterInfoData = + MittwaldAPIV2.Operations.NewsletterGetInfo.ResponseData; + +export type NewsletterSubscribeData = + MittwaldAPIV2.Paths.V2NewsletterSubscriptions.Post.Parameters.RequestBody; diff --git a/packages/models/src/newsletter/index.ts b/packages/models/src/newsletter/index.ts new file mode 100644 index 00000000..d00d260b --- /dev/null +++ b/packages/models/src/newsletter/index.ts @@ -0,0 +1 @@ +export * from "./Newsletter/index.js"; diff --git a/packages/models/src/notifications/Notifications/Notifications.test.ts b/packages/models/src/notifications/Notifications/Notifications.test.ts new file mode 100644 index 00000000..9a252145 --- /dev/null +++ b/packages/models/src/notifications/Notifications/Notifications.test.ts @@ -0,0 +1,210 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { buildNotificationListItemData } from "../../testing/builders/buildNotificationListItemData.js"; +import { installBehaviors, resetBehaviors } from "../../testing/index.js"; +import { ProjectInvite, Project } from "../../project/index.js"; +import { CustomerInvite } from "../../customer/index.js"; +import { config } from "../../config/config.js"; +import { + NotificationListItem, + NotificationList, + Notifications, +} from "./Notifications.js"; + +afterEach(resetBehaviors); + +describe("Notifications query (list + pagination)", () => { + test("applies the default pagination limit", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildNotificationListItemData({ id: "n-1" })], + totalCount: 1, + }); + installBehaviors({ notification: { list } }); + + const result = await Notifications.query().execute(); + + expect(result).toBeInstanceOf(NotificationList); + expect(result.items).toHaveLength(1); + expect(result.items[0]).toBeInstanceOf(NotificationListItem); + expect(result.totalCount).toBe(1); + expect(list).toHaveBeenCalledWith( + expect.objectContaining({ limit: config.defaultPaginationLimit }), + ); + }); + + test("uses an explicit pagination limit instead of the default", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 0, items: [] }); + installBehaviors({ notification: { list } }); + + await Notifications.query({ limit: 5 }).execute(); + + expect(5).not.toBe(config.defaultPaginationLimit); + expect(list).toHaveBeenCalledWith(expect.objectContaining({ limit: 5 })); + }); + + test("materializes behavior items and total count", async () => { + const items = [ + buildNotificationListItemData({ id: "n-1" }), + buildNotificationListItemData({ id: "n-2" }), + ]; + const list = vi.fn().mockResolvedValue({ totalCount: 7, items }); + installBehaviors({ notification: { list } }); + + const result = await Notifications.query({ limit: 2 }).execute(); + + expect(result.items).toHaveLength(2); + expect(result.items).toEqual([ + expect.objectContaining({ id: "n-1" }), + expect.objectContaining({ id: "n-2" }), + ]); + expect( + result.items.every((item) => item instanceof NotificationListItem), + ).toBe(true); + expect(result.totalCount).toBe(7); + }); + + test("refine merges query params", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 0, items: [] }); + installBehaviors({ notification: { list } }); + + await Notifications.query({ limit: 3 }).refine({ limit: 9 }).execute(); + + expect(list).toHaveBeenCalledWith(expect.objectContaining({ limit: 9 })); + }); + + test("getTotalCount requests a single item and returns the count", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 42, items: [] }); + installBehaviors({ notification: { list } }); + + const count = await Notifications.query().getTotalCount(); + + expect(count).toBe(42); + expect(list).toHaveBeenCalledWith(expect.objectContaining({ limit: 1 })); + }); +}); + +describe("Notifications mutations (delegation)", () => { + test("markAsRead delegates with the notification id", async () => { + const markAsRead = vi.fn().mockResolvedValue(undefined); + installBehaviors({ notification: { markAsRead } }); + + await Notifications.ofId("n-9").markAsRead(); + + expect(markAsRead).toHaveBeenCalledWith("n-9"); + }); + + test("markAllAsRead delegates to the behavior", async () => { + const markAllAsRead = vi.fn().mockResolvedValue(undefined); + installBehaviors({ notification: { markAllAsRead } }); + + await Notifications.markAllAsRead(); + + expect(markAllAsRead).toHaveBeenCalledTimes(1); + }); + + test("markAllAsRead delegates the query to the behavior", async () => { + const markAllAsRead = vi.fn().mockResolvedValue(undefined); + installBehaviors({ notification: { markAllAsRead } }); + + await Notifications.markAllAsRead({ + referenceAggregate: "appinstallation", + severities: ["info", "success"], + referenceDomain: "app", + referenceId: "a-1", + }); + + expect(markAllAsRead).toHaveBeenCalledWith({ + referenceAggregate: "appinstallation", + severities: ["info", "success"], + referenceDomain: "app", + referenceId: "a-1", + }); + }); +}); + +describe("NotificationListItem (data + derived getters)", () => { + test("derives observable fields from the notification data", () => { + const item = new NotificationListItem( + buildNotificationListItemData({ + createdAt: "2024-03-04T05:06:07.000Z", + type: "invoice.created", + severity: "warning", + read: false, + id: "n-1", + }), + ); + + expect(item.id).toBe("n-1"); + expect(item.type).toBe("invoice.created"); + expect(item.severity).toBe("warning"); + expect(item.unread).toBe(true); + expect(item.createdAt.year).toBe(2024); + expect(item.createdAt.month).toBe(3); + expect(item.createdAt.day).toBe(4); + }); + + test("marks a read notification as not unread", () => { + const item = new NotificationListItem( + buildNotificationListItemData({ read: true }), + ); + + expect(item.unread).toBe(false); + }); + + test("resolves the aggregate reference to a model", () => { + const item = new NotificationListItem( + buildNotificationListItemData({ + reference: { aggregate: "project", domain: "project", id: "p-1" }, + }), + ); + + expect(item.reference).toBeInstanceOf(Project); + expect(item.reference?.id).toBe("p-1"); + expect(item.isInvite).toBe(false); + }); + + test("keeps an unknown aggregate reference unresolved", () => { + const item = new NotificationListItem( + buildNotificationListItemData({ + reference: { + aggregate: "nope", + domain: "nope", + id: "x", + }, + }), + ); + + expect(item.reference).toBeUndefined(); + expect(item.isInvite).toBe(false); + }); + + test("flags project invite references as invites", () => { + const item = new NotificationListItem( + buildNotificationListItemData({ + reference: { + aggregate: "projectinvite", + domain: "membership", + id: "pi-1", + }, + }), + ); + + expect(item.reference).toBeInstanceOf(ProjectInvite); + expect(item.isInvite).toBe(true); + }); + + test("flags customer invite references as invites", () => { + const item = new NotificationListItem( + buildNotificationListItemData({ + reference: { + aggregate: "customerinvite", + domain: "membership", + id: "ci-1", + }, + }), + ); + + expect(item.reference).toBeInstanceOf(CustomerInvite); + expect(item.isInvite).toBe(true); + }); +}); diff --git a/packages/models/src/notifications/Notifications/Notifications.ts b/packages/models/src/notifications/Notifications/Notifications.ts new file mode 100644 index 00000000..6c5cb16f --- /dev/null +++ b/packages/models/src/notifications/Notifications/Notifications.ts @@ -0,0 +1,125 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; + +import type { + NotificationReadAllQueryData, + NotificationListQueryData, + NotificationListItemData, +} from "./types.js"; + +import { CustomerInvite } from "../../customer/index.js"; +import { ProjectInvite } from "../../project/index.js"; +import { config } from "../../config/index.js"; +import { + tryResolveAggregateReference, + type AggregateReference, +} from "../../common/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "Notifications", +}) +export class Notifications extends ReferenceModel { + public static async markAllAsRead(query?: NotificationReadAllQueryData) { + await config.behaviors.notification.markAllAsRead(query); + } + + public static ofId(id: string) { + return new Notifications(id); + } + + public static query(query: NotificationListQueryData = {}) { + return new NotificationListQuery(query); + } + + public async markAsRead() { + await config.behaviors.notification.markAsRead(this.id); + } +} + +export class NotificationCommon extends WithData()( + Notifications, +) { + public readonly createdAt: DateTime; + public override readonly data: NotificationListItemData; + public readonly isInvite: boolean; + public readonly reference: AggregateReference | undefined; + public readonly severity: "success" | "warning" | "error" | "info"; + public readonly type: string; + public readonly unread: boolean; + public constructor(data: NotificationListItemData) { + super(data.id); + this.data = data; + this.createdAt = DateTime.fromISO(data.createdAt); + this.type = data.type; + this.severity = data.severity; + this.reference = tryResolveAggregateReference({ + aggregate: data.reference.aggregate, + parent: data.reference.parents?.[0], + domain: data.reference.domain, + id: data.reference.id, + }); + this.unread = !data.read; + this.isInvite = + this.reference instanceof ProjectInvite || + this.reference instanceof CustomerInvite; + } +} + +export class NotificationListItem extends NotificationCommon { + public constructor(data: NotificationListItemData) { + super(data); + } +} + +export class NotificationListQuery extends ListQueryModel { + public constructor(query: NotificationListQueryData = {}) { + super(query); + } + + public async execute() { + const { totalCount, items } = await config.behaviors.notification.list({ + limit: config.defaultPaginationLimit, + ...this.query, + }); + + return new NotificationList( + this.query, + items.map((i) => new NotificationListItem(i)), + totalCount, + ); + } + + public async getTotalCount() { + const { totalCount } = await this.refine({ limit: 1 }).execute(); + return totalCount; + } + + public refine(query: NotificationListQueryData) { + return new NotificationListQuery({ + ...this.query, + ...query, + }); + } +} + +export class NotificationList extends WithListData()( + NotificationListQuery, +) { + public override readonly items: readonly NotificationListItem[]; + public override readonly totalCount: number; + public constructor( + query: NotificationListQueryData, + notifications: NotificationListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(notifications); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/notifications/Notifications/behaviors/api.ts b/packages/models/src/notifications/Notifications/behaviors/api.ts new file mode 100644 index 00000000..be4ad040 --- /dev/null +++ b/packages/models/src/notifications/Notifications/behaviors/api.ts @@ -0,0 +1,39 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { NotificationBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount } from "../../../base/index.js"; + +export const apiNotificationBehaviors = ( + client: MittwaldAPIV2Client, +): NotificationBehaviors => ({ + list: async (query) => { + const response = await client.notification.slistNotifications({ + queryParameters: query, + }); + + validateResponse(response, 200); + + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + markAsRead: async (notificationId) => { + const response = await client.notification.supdateNotificationStatus({ + data: { status: "read" }, + notificationId, + }); + + validateResponse(response, 200); + }, + + markAllAsRead: async (query) => { + const response = await client.notification.sreadAllNotifications({ + queryParameters: query, + }); + + validateResponse(response, 200); + }, +}); diff --git a/packages/models/src/notifications/Notifications/behaviors/index.ts b/packages/models/src/notifications/Notifications/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/notifications/Notifications/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/notifications/Notifications/behaviors/types.ts b/packages/models/src/notifications/Notifications/behaviors/types.ts new file mode 100644 index 00000000..f514c11f --- /dev/null +++ b/packages/models/src/notifications/Notifications/behaviors/types.ts @@ -0,0 +1,16 @@ +import type { QueryResponseData } from "../../../base/index.js"; +import type { + NotificationReadAllQueryData, + NotificationListQueryData, + NotificationListItemData, +} from "../types.js"; + +export interface NotificationBehaviors { + list: ( + query?: NotificationListQueryData, + ) => Promise>; + + markAllAsRead: (query?: NotificationReadAllQueryData) => Promise; + + markAsRead: (notificationId: string) => Promise; +} diff --git a/packages/models/src/notifications/Notifications/index.ts b/packages/models/src/notifications/Notifications/index.ts new file mode 100644 index 00000000..c2b4b9dc --- /dev/null +++ b/packages/models/src/notifications/Notifications/index.ts @@ -0,0 +1,2 @@ +export * from "./Notifications.js"; +export * from "./types.js"; diff --git a/packages/models/src/notifications/Notifications/types.ts b/packages/models/src/notifications/Notifications/types.ts new file mode 100644 index 00000000..85f4da8a --- /dev/null +++ b/packages/models/src/notifications/Notifications/types.ts @@ -0,0 +1,10 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type NotificationListItemData = + MittwaldAPIV2.Operations.NotificationsListNotifications.ResponseData[number]; + +export type NotificationListQueryData = + MittwaldAPIV2.Paths.V2Notifications.Get.Parameters.Query; + +export type NotificationReadAllQueryData = + MittwaldAPIV2.Paths.V2NotificationsActionsReadAll.Post.Parameters.Query; diff --git a/packages/models/src/notifications/index.ts b/packages/models/src/notifications/index.ts new file mode 100644 index 00000000..1caef73b --- /dev/null +++ b/packages/models/src/notifications/index.ts @@ -0,0 +1 @@ +export * from "./Notifications/index.js"; diff --git a/packages/models/src/order/Order/Order.test.ts b/packages/models/src/order/Order/Order.test.ts new file mode 100644 index 00000000..b7c9063a --- /dev/null +++ b/packages/models/src/order/Order/Order.test.ts @@ -0,0 +1,281 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { buildOrderItemData } from "../../testing/builders/buildOrderItemData.js"; +import { buildOrderData } from "../../testing/builders/buildOrderData.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { Customer } from "../../customer/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { + OrderListQuery, + OrderDetailed, + OrderListItem, + OrderList, + Order, +} from "./Order.js"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +afterEach(resetBehaviors); + +describe("Order reference", () => { + test("find delegates and materializes a detailed order", async () => { + const find = vi.fn().mockResolvedValue(buildOrderData({ orderId: "o-1" })); + installBehaviors({ order: { find } }); + + const result = await Order.find("o-1"); + + expect(find).toHaveBeenCalledWith("o-1"); + expect(result).toBeInstanceOf(OrderDetailed); + expect(result?.id).toBe("o-1"); + }); + + test("find returns undefined when the behavior finds nothing", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ order: { find } }); + + await expect(Order.find("missing")).resolves.toBeUndefined(); + }); + + test("get returns a detailed order when found", async () => { + const find = vi.fn().mockResolvedValue(buildOrderData({ orderId: "o-2" })); + installBehaviors({ order: { find } }); + + await expect(Order.get("o-2")).resolves.toBeInstanceOf(OrderDetailed); + }); + + test("get throws when the order is missing", async () => { + installBehaviors({ order: { find: vi.fn().mockResolvedValue(undefined) } }); + + await expect(Order.get("missing")).rejects.toThrow(); + }); + + test("reference detail methods delegate with their id", async () => { + const find = vi.fn().mockResolvedValue(buildOrderData({ orderId: "o-3" })); + installBehaviors({ order: { find } }); + const reference = Order.ofId("o-3"); + + await expect(reference.findDetailed()).resolves.toBeInstanceOf( + OrderDetailed, + ); + await expect(reference.getDetailed()).resolves.toBeInstanceOf( + OrderDetailed, + ); + expect(find).toHaveBeenNthCalledWith(1, "o-3"); + expect(find).toHaveBeenNthCalledWith(2, "o-3"); + }); + + test("changePlan delegates the unchanged request data", async () => { + const createTariffChange = vi.fn().mockResolvedValue(undefined); + installBehaviors({ order: { createTariffChange } }); + const data = { + tariffChangeData: { + contractId: "contract-id", + requestsPerMinute: 10, + monthlyTokens: 1000, + }, + tariffChangeType: "aiHosting" as const, + }; + + await Order.changePlan(data); + + expect(createTariffChange).toHaveBeenCalledWith(data); + }); + test("aggregate metadata pins the order domain and aggregate", () => { + expect(Order.aggregateMetaData).toBeInstanceOf(AggregateMetaData); + expect(Order.aggregateMetaData.domain).toBe("order"); + expect(Order.aggregateMetaData.aggregate).toBe("order"); + }); +}); + +describe("Order common variant", () => { + test("findCommon on a reference delegates and materializes the detailed order", async () => { + const find = vi.fn().mockResolvedValue(buildOrderData({ orderId: "o-c1" })); + installBehaviors({ order: { find } }); + + const result = await Order.ofId("o-c1").findCommon(); + + expect(find).toHaveBeenCalledWith("o-c1"); + expect(result).toBeInstanceOf(OrderDetailed); + expect(result?.id).toBe("o-c1"); + }); + + test("findCommon on a reference returns undefined when nothing is found", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ order: { find } }); + + await expect(Order.ofId("missing").findCommon()).resolves.toBeUndefined(); + }); + + test("getCommon on a reference delegates and materializes the detailed order", async () => { + const find = vi.fn().mockResolvedValue(buildOrderData({ orderId: "o-c2" })); + installBehaviors({ order: { find } }); + + await expect(Order.ofId("o-c2").getCommon()).resolves.toBeInstanceOf( + OrderDetailed, + ); + expect(find).toHaveBeenCalledWith("o-c2"); + }); + + test("getCommon on a reference throws when the order is missing", async () => { + installBehaviors({ order: { find: vi.fn().mockResolvedValue(undefined) } }); + + await expect(Order.ofId("missing").getCommon()).rejects.toThrow(); + }); + + test("findCommon on an already-materialized order is idempotent and skips the behavior", async () => { + const find = vi.fn(); + installBehaviors({ order: { find } }); + const order = new OrderDetailed(buildOrderData({ orderId: "o-c3" })); + + const result = await order.findCommon(); + + expect(result).toBe(order); + expect(find).not.toHaveBeenCalled(); + }); + + test("getCommon on an already-materialized order is idempotent and skips the behavior", async () => { + const find = vi.fn(); + installBehaviors({ order: { find } }); + const order = new OrderDetailed(buildOrderData({ orderId: "o-c4" })); + + const result = await order.getCommon(); + + expect(result).toBe(order); + expect(find).not.toHaveBeenCalled(); + }); +}); + +describe("Order data", () => { + test("exposes derived values", () => { + const order = new OrderDetailed( + buildOrderData({ + summary: { nonRecurring: 200, recurring: 800, summary: 1000 }, + items: [buildOrderItemData({ orderItemId: "i-1" })], + orderDate: "2026-01-02T00:00:00.000Z", + dueDate: "2026-01-10T00:00:00.000Z", + orderNumber: "ORD-2", + status: "CONFIRMED", + customerId: "c-1", + }), + ); + + expect(order.orderNumber).toBe("ORD-2"); + expect(order.status).toBe("CONFIRMED"); + expect(order.customer).toBeInstanceOf(Customer); + expect(order.customer.id).toBe("c-1"); + expect(order.summary?.getAmount()).toBe(1000); + expect(order.summaryRecurring?.getAmount()).toBe(800); + expect(order.summaryNonRecurring?.getAmount()).toBe(200); + expect(order.orderDate).toBeInstanceOf(Date); + expect(order.dueDate).toBeInstanceOf(Date); + expect(order.items?.[0]?.id).toBe("i-1"); + }); + + test("leaves absent dates undefined", () => { + const order = new OrderDetailed( + buildOrderData({ orderDate: undefined, dueDate: undefined }), + ); + + expect(order.orderDate).toBeUndefined(); + expect(order.dueDate).toBeUndefined(); + }); + + test("finds an order item attribute by key", () => { + const order = new OrderDetailed( + buildOrderData({ + items: [ + buildOrderItemData({ + attributeConfiguration: [{ value: "bar", key: "foo" }], + }), + ], + }), + ); + + expect(order.getOrderItemAttribute("foo")?.value).toBe("bar"); + expect(order.getOrderItemAttribute("missing")).toBeUndefined(); + }); + test("leaves summary values undefined when no summary is present", () => { + const order = new OrderDetailed(buildOrderData({ summary: undefined })); + + expect(order.summary).toBeUndefined(); + expect(order.summaryRecurring).toBeUndefined(); + expect(order.summaryNonRecurring).toBeUndefined(); + }); + + test("leaves items undefined and yields no attribute when items are absent", () => { + const order = new OrderDetailed(buildOrderData({ items: undefined })); + + expect(order.items).toBeUndefined(); + expect(order.getOrderItemAttribute("foo")).toBeUndefined(); + }); +}); + +describe("Order list query", () => { + test("delegates and materializes list items and count", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildOrderData({ orderId: "o-1" })], + totalCount: 1, + }); + installBehaviors({ order: { list } }); + + const result = await Order.query().execute(); + + expect(result).toBeInstanceOf(OrderList); + expect(result.items[0]).toBeInstanceOf(OrderListItem); + expect(result.totalCount).toBe(1); + }); + + test("maps model query references to behavior ids", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 0, items: [] }); + installBehaviors({ order: { list } }); + + await Order.query({ customer: "c-1", project: "p-1", limit: 5 }).execute(); + + expect(list).toHaveBeenCalledWith( + expect.objectContaining({ + customerId: "c-1", + projectId: "p-1", + limit: 5, + }), + ); + expect(list.mock.calls[0]?.[0]).not.toHaveProperty("customer"); + expect(list.mock.calls[0]?.[0]).not.toHaveProperty("project"); + }); + + test("refine merges query data into a new query", () => { + const original = Order.query({ customer: "c-1", limit: 10 }); + const refined = original.refine({ limit: 5 }); + + expect(refined).toBeInstanceOf(OrderListQuery); + expect(refined).not.toBe(original); + }); + + test("getTotalCount requests one item and returns the count", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 7, items: [] }); + installBehaviors({ order: { list } }); + + await expect(Order.query().getTotalCount()).resolves.toBe(7); + expect(list).toHaveBeenCalledWith(expect.objectContaining({ limit: 1 })); + }); + + test("executeOptional returns an empty list when listing rejects", async () => { + installBehaviors({ + order: { list: vi.fn().mockRejectedValue(new Error("failed")) }, + }); + + const result = await Order.query().executeOptional(); + + expect(result).toBeInstanceOf(OrderList); + expect(result.items).toHaveLength(0); + expect(result.totalCount).toBe(0); + }); +}); diff --git a/packages/models/src/order/Order/Order.ts b/packages/models/src/order/Order/Order.ts new file mode 100644 index 00000000..f9b68d32 --- /dev/null +++ b/packages/models/src/order/Order/Order.ts @@ -0,0 +1,191 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; + +import type { + OrderListQueryModelData, + PlanChangeRequestData, + OrderListItemData, + OrderTypeData, + OrderStatus, + OrderData, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { Customer } from "../../customer/Customer/Customer.js"; +import { AggregateMetaData, Money } from "../../common/index.js"; +import { OrderItem } from "../OrderItem/index.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "Order", +}) +export class Order extends ReferenceModel { + public static aggregateMetaData = new AggregateMetaData("order", "order"); + public static openStatuses: OrderStatus[] = ["CONFIRMED", "NEW"]; + + public static async changePlan(planChangeData: PlanChangeRequestData) { + await config.behaviors.order.createTariffChange(planChangeData); + } + + public static async find(id: string) { + const data = await config.behaviors.order.find(id); + + if (data) { + return new OrderDetailed(data); + } + } + + public static async get(id: string) { + const order = await Order.find(id); + assertObjectFound(order, Order, id); + return order; + } + + public static ofId(id: string) { + return new Order(id); + } + + public static query(query: OrderListQueryModelData = {}) { + return new OrderListQuery(query); + } + + public async findCommon(): Promise { + return this instanceof OrderCommon ? this : this.findDetailed(); + } + + public async findDetailed(): Promise { + return Order.find(this.id); + } + + public async getCommon(): Promise { + return this instanceof OrderCommon ? this : this.getDetailed(); + } + + public async getDetailed(): Promise { + return Order.get(this.id); + } +} + +export class OrderCommon extends WithData()( + Order, +) { + public readonly customer: Customer; + public override readonly data: OrderListItemData | OrderData; + public readonly dueDate?: Date; + public readonly items?: OrderItem[]; + public readonly orderDate?: Date; + public readonly orderNumber: string; + public readonly status: OrderStatus; + public readonly summary?: Money; + public readonly summaryNonRecurring?: Money; + public readonly summaryRecurring?: Money; + public readonly type: OrderTypeData; + + public constructor(data: OrderListItemData | OrderData) { + super(data.orderId); + this.data = data; + this.orderNumber = data.orderNumber; + this.status = data.status; + this.customer = Customer.ofId(data.customerId); + if (data.summary) { + this.summary = Money({ amount: data.summary.summary, currency: "EUR" }); + this.summaryRecurring = Money({ + amount: data.summary.recurring, + currency: "EUR", + }); + this.summaryNonRecurring = Money({ + amount: data.summary.nonRecurring, + currency: "EUR", + }); + } + this.orderDate = data.orderDate ? new Date(data.orderDate) : undefined; + this.dueDate = data.dueDate ? new Date(data.dueDate) : undefined; + if (data.items) { + this.items = data.items.map((i) => new OrderItem(i)); + } + this.type = data.type; + } + + public getOrderItemAttribute(key: string) { + return (this.items ?? []) + .flatMap((i) => i.attributeConfiguration) + .find((i) => i?.key === key); + } +} + +export class OrderDetailed extends OrderCommon { + public override readonly data: OrderData; + + public constructor(data: OrderData) { + super(data); + this.data = data; + } +} + +export class OrderListItem extends OrderCommon { + public override readonly data: OrderListItemData; + + public constructor(data: OrderListItemData) { + super(data); + this.data = data; + } +} + +export class OrderListQuery extends ListQueryModel { + public async execute() { + const { customer, project, ...restQuery } = this.query; + + const { totalCount, items } = await config.behaviors.order.list({ + ...restQuery, + customerId: extractId(customer), + projectId: extractId(project), + }); + + return new OrderList( + this.query, + items.map((d) => new OrderListItem(d)), + totalCount, + ); + } + + public async executeOptional() { + try { + return await this.execute(); + } catch { + return new OrderList(this.query, [], 0); + } + } + + public async getTotalCount() { + const { totalCount } = await this.refine({ limit: 1 }).execute(); + return totalCount; + } + + public refine(query: OrderListQueryModelData) { + return new OrderListQuery({ + ...this.query, + ...query, + }); + } +} + +export class OrderList extends WithListData()(OrderListQuery) { + public override readonly items: readonly OrderListItem[]; + public override readonly totalCount: number; + + public constructor( + query: OrderListQueryModelData, + orders: OrderListItem[], + totalCount: number, + ) { + super(query); + this.items = Object.freeze(orders); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/order/Order/Preview/AIHostingOrderPreview.ts b/packages/models/src/order/Order/Preview/AIHostingOrderPreview.ts new file mode 100644 index 00000000..9c99d55d --- /dev/null +++ b/packages/models/src/order/Order/Preview/AIHostingOrderPreview.ts @@ -0,0 +1,16 @@ +import { DataModel } from "../../../base/index.js"; +import { Money } from "../../../common/index.js"; + +export class AIHostingOrderPreview extends DataModel { + public readonly request: any; + public readonly totalPrice: Money; + + public constructor(request: any, data: any) { + super(data); + this.request = request; + this.totalPrice = Money({ + amount: data.totalPrice, + currency: "EUR", + }); + } +} diff --git a/packages/models/src/order/Order/Preview/DomainOrderPreview.ts b/packages/models/src/order/Order/Preview/DomainOrderPreview.ts new file mode 100644 index 00000000..d4f23fab --- /dev/null +++ b/packages/models/src/order/Order/Preview/DomainOrderPreview.ts @@ -0,0 +1,32 @@ +import type { DomainOrderRequest } from "../Request/DomainOrderRequest.js"; + +import { type DomainOrderPreviewData } from "../types.js"; +import { DataModel } from "../../../base/index.js"; +import { Money } from "../../../common/index.js"; + +export class DomainOrderPreview extends DataModel { + public readonly authCode?: string; + public readonly domain: string; + public readonly domainContractDuration: number; + public readonly domainPrice: Money; + public readonly feePrice: Money; + public readonly request: DomainOrderRequest; + public readonly totalPrice: Money; + + public constructor( + request: DomainOrderRequest, + data: DomainOrderPreviewData, + ) { + super(data); + this.request = request; + this.domainPrice = Money({ amount: data.domainPrice, currency: "EUR" }); + this.totalPrice = Money({ amount: data.totalPrice, currency: "EUR" }); + this.feePrice = Money({ + amount: data.feePrice, + currency: "EUR", + }); + this.domainContractDuration = data.domainContractDuration; + this.domain = request.domain; + this.authCode = request.authCode; + } +} diff --git a/packages/models/src/order/Order/Preview/ExternalCertificateOrderPreview.ts b/packages/models/src/order/Order/Preview/ExternalCertificateOrderPreview.ts new file mode 100644 index 00000000..88092b9b --- /dev/null +++ b/packages/models/src/order/Order/Preview/ExternalCertificateOrderPreview.ts @@ -0,0 +1,29 @@ +import type { ExternalCertificateOrderRequest } from "../Request/ExternalCertificateOrderRequest.js"; + +import { type ExternalCertificateOrderPreviewData } from "../types.js"; +import { DataModel } from "../../../base/index.js"; +import { Money } from "../../../common/index.js"; + +export class ExternalCertificateOrderPreview extends DataModel { + public readonly feePrice: Money; + public readonly recurringPrice: Money; + public readonly request: ExternalCertificateOrderRequest; + public readonly totalPrice: Money; + + public constructor( + request: ExternalCertificateOrderRequest, + data: ExternalCertificateOrderPreviewData, + ) { + super(data); + this.request = request; + this.recurringPrice = Money({ + amount: data.recurringPrice, + currency: "EUR", + }); + this.totalPrice = Money({ amount: data.totalPrice, currency: "EUR" }); + this.feePrice = Money({ + amount: data.feePrice, + currency: "EUR", + }); + } +} diff --git a/packages/models/src/order/Order/Preview/HostingOrderPreview.ts b/packages/models/src/order/Order/Preview/HostingOrderPreview.ts new file mode 100644 index 00000000..5e074c3a --- /dev/null +++ b/packages/models/src/order/Order/Preview/HostingOrderPreview.ts @@ -0,0 +1,49 @@ +import { DateTime } from "luxon"; + +import type { HostingOrderRequest } from "../Request/HostingOrderRequest.js"; +import type { HostingOrderPreviewData } from "../types.js"; + +import { DataModel } from "../../../base/index.js"; +import { Money } from "../../../common/index.js"; + +export class HostingOrderPreview extends DataModel { + public readonly freeTrialUntil?: DateTime; + public readonly machineTypePrice: Money; + public readonly request: HostingOrderRequest; + public readonly storagePrice: Money; + public readonly totalPrice: Money; + + public constructor( + request: HostingOrderRequest, + data: HostingOrderPreviewData, + ) { + super(data); + this.request = request; + this.totalPrice = Money({ amount: data.totalPrice, currency: "EUR" }); + this.storagePrice = Money({ amount: data.storagePrice, currency: "EUR" }); + this.machineTypePrice = Money({ + amount: data.machineTypePrice, + currency: "EUR", + }); + this.freeTrialUntil = data.freeTrialUntil + ? DateTime.fromISO(data.freeTrialUntil) + : undefined; + } + + public async getNextPossibleDowngradeDate() { + const contract = this.request.contract; + if (!contract) { + return; + } + + const detailedContract = await contract.getDetailed(); + + const isDowngrade = this.totalPrice.lessThan( + detailedContract.baseItem.totalPrice, + ); + + return isDowngrade + ? detailedContract.baseItem.nextPossibleDowngradeDate + : undefined; + } +} diff --git a/packages/models/src/order/Order/Preview/LeadFyndrOrderPreview.ts b/packages/models/src/order/Order/Preview/LeadFyndrOrderPreview.ts new file mode 100644 index 00000000..d625fa76 --- /dev/null +++ b/packages/models/src/order/Order/Preview/LeadFyndrOrderPreview.ts @@ -0,0 +1,19 @@ +import type { LeadFyndrOrderRequest } from "../Request/LeadFyndrOrderRequest.js"; +import type { LeadFyndrOrderPreviewData } from "../types.js"; + +import { DataModel } from "../../../base/index.js"; +import { Money } from "../../../common/index.js"; + +export class LeadFyndrOrderPreview extends DataModel { + public readonly request: LeadFyndrOrderRequest; + public readonly totalPrice: Money; + + public constructor( + request: LeadFyndrOrderRequest, + data: LeadFyndrOrderPreviewData, + ) { + super(data); + this.request = request; + this.totalPrice = Money({ amount: data.totalPrice, currency: "EUR" }); + } +} diff --git a/packages/models/src/order/Order/Preview/LicenseOrderPreview.ts b/packages/models/src/order/Order/Preview/LicenseOrderPreview.ts new file mode 100644 index 00000000..a8428568 --- /dev/null +++ b/packages/models/src/order/Order/Preview/LicenseOrderPreview.ts @@ -0,0 +1,19 @@ +import type { LicenseOrderRequest } from "../Request/LicenseOrderRequest.js"; +import type { LicenseOrderPreviewData } from "../types.js"; + +import { DataModel } from "../../../base/index.js"; +import { Money } from "../../../common/index.js"; + +export class LicenseOrderPreview extends DataModel { + public readonly request: LicenseOrderRequest; + public readonly totalPrice: Money; + + public constructor( + request: LicenseOrderRequest, + data: LicenseOrderPreviewData, + ) { + super(data); + this.request = request; + this.totalPrice = Money({ amount: data.totalPrice, currency: "EUR" }); + } +} diff --git a/packages/models/src/order/Order/Preview/MailArchiveOrderPreview.ts b/packages/models/src/order/Order/Preview/MailArchiveOrderPreview.ts new file mode 100644 index 00000000..a0290ab8 --- /dev/null +++ b/packages/models/src/order/Order/Preview/MailArchiveOrderPreview.ts @@ -0,0 +1,27 @@ +import type { MailArchiveOrderRequest } from "../Request/MailArchiveOrderRequest.js"; +import type { MailArchiveOrderPreviewData } from "../types.js"; + +import { DataModel } from "../../../base/index.js"; +import { Money } from "../../../common/index.js"; + +export class MailArchiveOrderPreview extends DataModel { + public readonly feePrice: Money; + public readonly recurringPrice: Money; + public readonly request: MailArchiveOrderRequest; + + public constructor( + request: MailArchiveOrderRequest, + data: MailArchiveOrderPreviewData, + ) { + super(data); + this.request = request; + this.recurringPrice = Money({ + amount: data.recurringPrice, + currency: "EUR", + }); + this.feePrice = Money({ + amount: data.feePrice, + currency: "EUR", + }); + } +} diff --git a/packages/models/src/order/Order/Preview/Preview.test.ts b/packages/models/src/order/Order/Preview/Preview.test.ts new file mode 100644 index 00000000..5f1b3cda --- /dev/null +++ b/packages/models/src/order/Order/Preview/Preview.test.ts @@ -0,0 +1,158 @@ +import { afterEach, describe, expect, test } from "vitest"; +import { DateTime } from "luxon"; + +import type { HostingOrderRequest } from "../Request/HostingOrderRequest.js"; + +import { buildExternalCertificateOrderPreviewData } from "../../../testing/builders/buildExternalCertificateOrderPreviewData.js"; +import { buildMailArchiveOrderPreviewData } from "../../../testing/builders/buildMailArchiveOrderPreviewData.js"; +import { buildLeadFyndrOrderPreviewData } from "../../../testing/builders/buildLeadFyndrOrderPreviewData.js"; +import { buildHostingOrderPreviewData } from "../../../testing/builders/buildHostingOrderPreviewData.js"; +import { buildLicenseOrderPreviewData } from "../../../testing/builders/buildLicenseOrderPreviewData.js"; +import { buildDomainOrderPreviewData } from "../../../testing/builders/buildDomainOrderPreviewData.js"; +import { ExternalCertificateOrderRequest } from "../Request/ExternalCertificateOrderRequest.js"; +import { ExternalCertificateOrderPreview } from "./ExternalCertificateOrderPreview.js"; +import { MailArchiveOrderRequest } from "../Request/MailArchiveOrderRequest.js"; +import { LeadFyndrOrderRequest } from "../Request/LeadFyndrOrderRequest.js"; +import { LicenseOrderRequest } from "../Request/LicenseOrderRequest.js"; +import { MailArchiveOrderPreview } from "./MailArchiveOrderPreview.js"; +import { resetBehaviors } from "../../../testing/installBehaviors.js"; +import { DomainOrderRequest } from "../Request/DomainOrderRequest.js"; +import { AIHostingOrderPreview } from "./AIHostingOrderPreview.js"; +import { LeadFyndrOrderPreview } from "./LeadFyndrOrderPreview.js"; +import { HostingOrderPreview } from "./HostingOrderPreview.js"; +import { LicenseOrderPreview } from "./LicenseOrderPreview.js"; +import { DomainOrderPreview } from "./DomainOrderPreview.js"; + +afterEach(resetBehaviors); + +describe("DomainOrderPreview", () => { + test("exposes prices, duration, and request data", () => { + const request = DomainOrderRequest.create({ + domain: "example.com", + authCode: "abc", + project: "p-1", + }); + const preview = new DomainOrderPreview( + request, + buildDomainOrderPreviewData({ + domainContractDuration: 12, + domainPrice: 500, + totalPrice: 700, + feePrice: 200, + }), + ); + + expect(preview.domainPrice.getAmount()).toBe(500); + expect(preview.totalPrice.getAmount()).toBe(700); + expect(preview.totalPrice.getCurrency()).toBe("EUR"); + expect(preview.feePrice.getAmount()).toBe(200); + expect(preview.domainContractDuration).toBe(12); + expect(preview.domain).toBe("example.com"); + expect(preview.authCode).toBe("abc"); + }); +}); + +describe("HostingOrderPreview", () => { + test("exposes prices and parses the free-trial date", () => { + const preview = new HostingOrderPreview( + {} as HostingOrderRequest, + buildHostingOrderPreviewData({ + freeTrialUntil: "2026-01-01T00:00:00.000Z", + machineTypePrice: 80, + storagePrice: 20, + totalPrice: 100, + }), + ); + + expect(preview.totalPrice.getAmount()).toBe(100); + expect(preview.totalPrice.getCurrency()).toBe("EUR"); + expect(preview.storagePrice.getAmount()).toBe(20); + expect(preview.machineTypePrice.getAmount()).toBe(80); + expect(DateTime.isDateTime(preview.freeTrialUntil)).toBe(true); + }); + + test("leaves an absent free-trial date undefined", () => { + const preview = new HostingOrderPreview( + {} as HostingOrderRequest, + buildHostingOrderPreviewData({ freeTrialUntil: undefined }), + ); + + expect(preview.freeTrialUntil).toBeUndefined(); + }); +}); + +describe("ExternalCertificateOrderPreview", () => { + test("exposes its prices", () => { + const request = ExternalCertificateOrderRequest.create({ + certificateRequestId: "cr-1", + project: "p-1", + }); + const preview = new ExternalCertificateOrderPreview( + request, + buildExternalCertificateOrderPreviewData({ + recurringPrice: 50, + totalPrice: 75, + feePrice: 25, + }), + ); + + expect(preview.recurringPrice.getAmount()).toBe(50); + expect(preview.totalPrice.getAmount()).toBe(75); + expect(preview.totalPrice.getCurrency()).toBe("EUR"); + expect(preview.feePrice.getAmount()).toBe(25); + }); +}); + +describe("LeadFyndrOrderPreview", () => { + test("exposes its total price", () => { + const request = new LeadFyndrOrderRequest({ + reservationLimit: 1, + unlockLimit: 1, + }); + const preview = new LeadFyndrOrderPreview( + request, + buildLeadFyndrOrderPreviewData({ totalPrice: 100 }), + ); + + expect(preview.totalPrice.getAmount()).toBe(100); + expect(preview.totalPrice.getCurrency()).toBe("EUR"); + }); +}); + +describe("LicenseOrderPreview", () => { + test("exposes its total price", () => { + const request = new LicenseOrderRequest({ + licenseType: "typo3", + majorVersion: 12, + }); + const preview = new LicenseOrderPreview( + request, + buildLicenseOrderPreviewData({ totalPrice: 120 }), + ); + + expect(preview.totalPrice.getAmount()).toBe(120); + expect(preview.totalPrice.getCurrency()).toBe("EUR"); + }); +}); + +describe("MailArchiveOrderPreview", () => { + test("exposes its recurring and fee prices", () => { + const request = new MailArchiveOrderRequest({ mailAddress: "m-1" }); + const preview = new MailArchiveOrderPreview( + request, + buildMailArchiveOrderPreviewData({ recurringPrice: 40, feePrice: 10 }), + ); + + expect(preview.recurringPrice.getAmount()).toBe(40); + expect(preview.recurringPrice.getCurrency()).toBe("EUR"); + expect(preview.feePrice.getAmount()).toBe(10); + }); +}); + +describe("AIHostingOrderPreview", () => { + test("exposes its total price", () => { + const preview = new AIHostingOrderPreview({} as any, { totalPrice: 250 }); + + expect(preview.totalPrice.getAmount()).toBe(250); + }); +}); diff --git a/packages/models/src/order/Order/Request/AIHostingOrderRequest.ts b/packages/models/src/order/Order/Request/AIHostingOrderRequest.ts new file mode 100644 index 00000000..35391187 --- /dev/null +++ b/packages/models/src/order/Order/Request/AIHostingOrderRequest.ts @@ -0,0 +1,52 @@ +import type { Contract } from "../../../contract/index.js"; +import type { + AiHostingOrderPreviewRequestData, + CompleteOrderRequestData, + AiHostingOrderData, +} from "../types.js"; + +import { AIHostingOrderPreview } from "../Preview/AIHostingOrderPreview.js"; +import { DataModel } from "../../../base/index.js"; +import { config } from "../../../config/index.js"; +import { Order } from "../Order.js"; + +export class AIHostingOrderRequest extends DataModel { + public readonly contract?: Contract; + + public constructor(data: AiHostingOrderPreviewRequestData) { + super(data); + } + + public async getPreview() { + if (this.contract) { + const response = await config.behaviors.order.previewTariffChange({ + tariffChangeData: { ...this.data, contractId: this.contract.id }, + tariffChangeType: "aiHosting", + }); + return new AIHostingOrderPreview(this, response); + } else { + const response = await config.behaviors.order.preview({ + orderType: "aiHosting", + orderData: this.data, + }); + return new AIHostingOrderPreview(this, response); + } + } + + public async order( + data: CompleteOrderRequestData< + AiHostingOrderPreviewRequestData, + AiHostingOrderData + >, + ): Promise { + const order = await config.behaviors.order.create({ + orderData: { + ...this.data, + ...data, + }, + orderType: "aiHosting", + }); + + return Order.ofId(order.id); + } +} diff --git a/packages/models/src/order/Order/Request/DomainOrderRequest.ts b/packages/models/src/order/Order/Request/DomainOrderRequest.ts new file mode 100644 index 00000000..840d86a5 --- /dev/null +++ b/packages/models/src/order/Order/Request/DomainOrderRequest.ts @@ -0,0 +1,64 @@ +import type { + DomainOrderPreviewRequestModelData, + DomainOrderRequestModelData, + CompleteOrderRequestData, + DomainOrderPreviewData, +} from "../types.js"; + +import { DomainOrderPreview } from "../Preview/DomainOrderPreview.js"; +import { DataModel, extractId } from "../../../base/index.js"; +import { config } from "../../../config/index.js"; +import { Order } from "../Order.js"; + +export class DomainOrderRequest extends DataModel { + public readonly authCode?: string; + public readonly domain: string; + + public constructor(data: DomainOrderPreviewRequestModelData) { + super(data); + this.domain = data.domain; + this.authCode = data.authCode; + } + + public static create(data: DomainOrderPreviewRequestModelData) { + return new DomainOrderRequest(data); + } + + public async getPreview() { + const { project, ...restData } = this.data; + + const response = await config.behaviors.order.preview({ + orderData: { + ...restData, + projectId: extractId(project), + }, + orderType: "domain", + }); + return new DomainOrderPreview(this, response as DomainOrderPreviewData); + } + + public async order( + data: CompleteOrderRequestData< + DomainOrderPreviewRequestModelData, + DomainOrderRequestModelData + >, + ): Promise { + const { ownerC, ...restData } = data; + const { project, ...restOrderData } = { + ...this.data, + ...restData, + handleData: { + ownerC, + }, + }; + + const order = await config.behaviors.order.create({ + orderData: { + ...restOrderData, + projectId: extractId(project), + }, + orderType: "domain", + }); + return Order.ofId(order.id); + } +} diff --git a/packages/models/src/order/Order/Request/ExternalCertificateOrderRequest.ts b/packages/models/src/order/Order/Request/ExternalCertificateOrderRequest.ts new file mode 100644 index 00000000..8a6b9ca1 --- /dev/null +++ b/packages/models/src/order/Order/Request/ExternalCertificateOrderRequest.ts @@ -0,0 +1,57 @@ +import type { + ExternalCertificateOrderPreviewRequestModelData, + ExternalCertificateOrderRequestModelData, + ExternalCertificateOrderPreviewData, + CompleteOrderRequestData, +} from "../types.js"; + +import { ExternalCertificateOrderPreview } from "../Preview/ExternalCertificateOrderPreview.js"; +import { DataModel, extractId } from "../../../base/index.js"; +import { config } from "../../../config/index.js"; +import { Order } from "../Order.js"; + +export class ExternalCertificateOrderRequest extends DataModel { + public constructor(data: ExternalCertificateOrderPreviewRequestModelData) { + super(data); + } + + public static create(data: ExternalCertificateOrderPreviewRequestModelData) { + return new ExternalCertificateOrderRequest(data); + } + + public async getPreview() { + const { project, ...restData } = this.data; + const response = await config.behaviors.order.preview({ + orderData: { + ...restData, + projectId: extractId(project), + }, + orderType: "externalCertificate", + }); + return new ExternalCertificateOrderPreview( + this, + response as ExternalCertificateOrderPreviewData, + ); + } + + public async order( + data: CompleteOrderRequestData< + ExternalCertificateOrderPreviewRequestModelData, + ExternalCertificateOrderRequestModelData + >, + ): Promise { + const { project, ...restOrderData } = { + ...this.data, + ...data, + }; + + const order = await config.behaviors.order.create({ + orderData: { + ...restOrderData, + projectId: extractId(project), + }, + orderType: "externalCertificate", + }); + return Order.ofId(order.id); + } +} diff --git a/packages/models/src/order/Order/Request/HostingOrderRequest.ts b/packages/models/src/order/Order/Request/HostingOrderRequest.ts new file mode 100644 index 00000000..3216e9cf --- /dev/null +++ b/packages/models/src/order/Order/Request/HostingOrderRequest.ts @@ -0,0 +1,209 @@ +import invariant from "tiny-invariant"; + +import type { HostingArticle } from "../../../article/Article/internal.js"; +import type { Contract } from "../../../contract/index.js"; +import type { Bytes } from "../../../common/index.js"; + +import { HostingOrderPreview } from "../Preview/HostingOrderPreview.js"; +import { ServerArticle } from "../../../article/Article/internal.js"; +import { HostingContractItem } from "../../../contract/index.js"; +import { config } from "../../../config/index.js"; +import { Order } from "../Order.js"; + +export class HostingOrderRequest { + public readonly contract?: Contract; + public readonly freeTrial?: boolean; + public readonly hostingArticle: HostingArticle; + public readonly storage: Bytes; + + public constructor( + hostingArticle: HostingArticle, + storage: Bytes, + contract?: Contract, + freeTrial?: boolean, + ) { + this.contract = contract; + this.hostingArticle = hostingArticle; + this.storage = + storage.gib < hostingArticle.baseStorageAttribute.bytes.gib + ? hostingArticle.baseStorageAttribute.bytes + : storage; + this.freeTrial = freeTrial; + } + + public static create( + hostingArticle: HostingArticle, + storage: Bytes, + contract?: Contract, + freeTrial?: boolean, + ) { + return new HostingOrderRequest( + hostingArticle, + storage, + contract, + freeTrial, + ); + } + + public readonly createPlanChange = async () => { + invariant(this.contract, "Contract is required"); + + const baseData = { + diskspaceInGiB: this.storage.gib, + contractId: this.contract.id, + }; + + const planChangeData = + this.hostingArticle instanceof ServerArticle + ? this.hostingArticle.isProSpace + ? { + ...baseData, + spec: { + machineType: this.hostingArticle.machineTypeSpecs.machineType, + }, + } + : { + ...baseData, + machineType: this.hostingArticle.machineTypeSpecs.machineType, + } + : { + ...baseData, + spec: { + ram: this.hostingArticle.hardwareSpecs.ram.gib, + vcpu: this.hostingArticle.hardwareSpecs.vcpu, + }, + }; + + const planChangeType = + this.hostingArticle instanceof ServerArticle && + !this.hostingArticle.isProSpace + ? "server" + : "projectHosting"; + + return await config.behaviors.order.createTariffChange({ + tariffChangeData: planChangeData, + tariffChangeType: planChangeType, + }); + }; + + public async getPreview() { + const baseData = { + diskspaceInGiB: this.storage.gib, + useFreeTrial: this.freeTrial, + }; + + const orderData = + this.hostingArticle instanceof ServerArticle + ? this.hostingArticle.isProSpace + ? { + ...baseData, + spec: { + machineType: this.hostingArticle.machineTypeSpecs.machineType, + }, + } + : { + ...baseData, + machineType: this.hostingArticle.machineTypeSpecs.machineType, + } + : { + ...baseData, + spec: { + ram: this.hostingArticle.hardwareSpecs.ram.gib, + vcpu: this.hostingArticle.hardwareSpecs.vcpu, + }, + }; + + const orderType = + this.hostingArticle instanceof ServerArticle && + !this.hostingArticle.isProSpace + ? "server" + : "projectHosting"; + + if (this.contract) { + const planChangeResponse = + await config.behaviors.order.previewTariffChange({ + tariffChangeData: { + ...orderData, + contractId: this.contract.id, + }, + tariffChangeType: orderType, + }); + + return new HostingOrderPreview(this, planChangeResponse); + } else { + const response = await config.behaviors.order.preview({ + orderData, + orderType, + }); + + invariant( + "machineTypePrice" in response, + "Expected machineTypePrice in response", + ); + + return new HostingOrderPreview(this, response); + } + } + + public readonly order = async (orderConfig: { + promotionCode?: string; + description: string; + customerId: string; + }) => { + const baseData = { + promotionCode: orderConfig.promotionCode, + description: orderConfig.description, + customerId: orderConfig.customerId, + diskspaceInGiB: this.storage.gib, + useFreeTrial: this.freeTrial, + }; + + const orderData = + this.hostingArticle instanceof ServerArticle + ? this.hostingArticle.isProSpace + ? { + ...baseData, + spec: { + machineType: this.hostingArticle.machineTypeSpecs.machineType, + }, + } + : { + ...baseData, + machineType: this.hostingArticle.machineTypeSpecs.machineType, + } + : { + ...baseData, + spec: { + ram: this.hostingArticle.hardwareSpecs.ram.gib, + vcpu: this.hostingArticle.hardwareSpecs.vcpu, + }, + }; + + const orderType = + this.hostingArticle instanceof ServerArticle && + !this.hostingArticle.isProSpace + ? "server" + : "projectHosting"; + + const order = await config.behaviors.order.create({ + orderData, + orderType, + }); + return Order.ofId(order.id); + }; + + protected async hasStorageConfigurationChanged() { + const contract = await this.contract?.getDetailed(); + if (!contract) { + return false; + } + + const hostingContractItem = HostingContractItem.fromContractItem( + contract.baseItem, + ); + + const contractStorage = await hostingContractItem.getStorage(); + invariant(!!contractStorage, "Contract storage should not be null"); + return !contractStorage.equals(this.storage); + } +} diff --git a/packages/models/src/order/Order/Request/LeadFyndrOrderRequest.ts b/packages/models/src/order/Order/Request/LeadFyndrOrderRequest.ts new file mode 100644 index 00000000..7817f54c --- /dev/null +++ b/packages/models/src/order/Order/Request/LeadFyndrOrderRequest.ts @@ -0,0 +1,58 @@ +import type { Contract } from "../../../contract/index.js"; +import type { + LeadFyndrOrderPreviewRequestData, + LeadFyndrOrderPreviewData, + LeadFyndrOrderRequestData, + CompleteOrderRequestData, +} from "../types.js"; + +import { LeadFyndrOrderPreview } from "../Preview/LeadFyndrOrderPreview.js"; +import { DataModel } from "../../../base/index.js"; +import { config } from "../../../config/index.js"; +import { Order } from "../Order.js"; + +export class LeadFyndrOrderRequest extends DataModel { + public readonly contract?: Contract; + + public constructor(data: LeadFyndrOrderPreviewRequestData) { + super(data); + } + + public async getPreview() { + if (this.contract) { + const response = await config.behaviors.order.previewTariffChange({ + tariffChangeData: { ...this.data, contractId: this.contract.id }, + tariffChangeType: "leadFyndr", + }); + return new LeadFyndrOrderPreview( + this, + response as LeadFyndrOrderPreviewData, + ); + } else { + const response = await config.behaviors.order.preview({ + orderType: "leadFyndr", + orderData: this.data, + }); + return new LeadFyndrOrderPreview( + this, + response as LeadFyndrOrderPreviewData, + ); + } + } + + public async order( + data: CompleteOrderRequestData< + LeadFyndrOrderPreviewRequestData, + LeadFyndrOrderRequestData + >, + ): Promise { + const order = await config.behaviors.order.create({ + orderData: { + ...this.data, + ...data, + }, + orderType: "leadFyndr", + }); + return Order.ofId(order.id); + } +} diff --git a/packages/models/src/order/Order/Request/LicenseOrderRequest.ts b/packages/models/src/order/Order/Request/LicenseOrderRequest.ts new file mode 100644 index 00000000..b7049b83 --- /dev/null +++ b/packages/models/src/order/Order/Request/LicenseOrderRequest.ts @@ -0,0 +1,44 @@ +import type { Contract } from "../../../contract/index.js"; +import type { + LicenseOrderPreviewRequestData, + CompleteOrderRequestData, + LicenseOrderPreviewData, + LicenseOrderRequestData, +} from "../types.js"; + +import { LicenseOrderPreview } from "../Preview/LicenseOrderPreview.js"; +import { DataModel } from "../../../base/index.js"; +import { config } from "../../../config/index.js"; +import { Order } from "../Order.js"; + +export class LicenseOrderRequest extends DataModel { + public readonly contract?: Contract; + + public constructor(data: LicenseOrderPreviewRequestData) { + super(data); + } + + public async getPreview() { + const response = await config.behaviors.order.preview({ + orderType: "license", + orderData: this.data, + }); + return new LicenseOrderPreview(this, response as LicenseOrderPreviewData); + } + + public async order( + data: CompleteOrderRequestData< + LicenseOrderPreviewRequestData, + LicenseOrderRequestData + >, + ): Promise { + const order = await config.behaviors.order.create({ + orderData: { + ...this.data, + ...data, + }, + orderType: "license", + }); + return Order.ofId(order.id); + } +} diff --git a/packages/models/src/order/Order/Request/MailArchiveOrderRequest.ts b/packages/models/src/order/Order/Request/MailArchiveOrderRequest.ts new file mode 100644 index 00000000..d06a45d5 --- /dev/null +++ b/packages/models/src/order/Order/Request/MailArchiveOrderRequest.ts @@ -0,0 +1,51 @@ +import type { + MailArchiveOrderPreviewRequestModelData, + MailArchiveOrderRequestModelData, + MailArchiveOrderPreviewData, + CompleteOrderRequestData, +} from "../types.js"; + +import { MailArchiveOrderPreview } from "../Preview/MailArchiveOrderPreview.js"; +import { DataModel, extractId } from "../../../base/index.js"; +import { config } from "../../../config/index.js"; +import { Order } from "../Order.js"; + +export class MailArchiveOrderRequest extends DataModel { + public constructor(data: MailArchiveOrderPreviewRequestModelData) { + super(data); + } + + public async getPreview() { + const { mailAddress, ...restData } = this.data; + + const response = await config.behaviors.order.preview({ + orderData: { mailAddressId: extractId(mailAddress), ...restData }, + orderType: "mailArchive", + }); + return new MailArchiveOrderPreview( + this, + response as MailArchiveOrderPreviewData, + ); + } + + public async order( + data: CompleteOrderRequestData< + MailArchiveOrderPreviewRequestModelData, + MailArchiveOrderRequestModelData + >, + ): Promise { + const { mailAddress, ...restData } = { + ...this.data, + ...data, + }; + + const order = await config.behaviors.order.create({ + orderData: { + ...restData, + mailAddressId: extractId(mailAddress), + }, + orderType: "mailArchive", + }); + return Order.ofId(order.id); + } +} diff --git a/packages/models/src/order/Order/Request/Request.test.ts b/packages/models/src/order/Order/Request/Request.test.ts new file mode 100644 index 00000000..afcad820 --- /dev/null +++ b/packages/models/src/order/Order/Request/Request.test.ts @@ -0,0 +1,305 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { buildExternalCertificateOrderPreviewData } from "../../../testing/builders/buildExternalCertificateOrderPreviewData.js"; +import { buildMailArchiveOrderPreviewData } from "../../../testing/builders/buildMailArchiveOrderPreviewData.js"; +import { buildLeadFyndrOrderPreviewData } from "../../../testing/builders/buildLeadFyndrOrderPreviewData.js"; +import { buildHostingOrderPreviewData } from "../../../testing/builders/buildHostingOrderPreviewData.js"; +import { buildLicenseOrderPreviewData } from "../../../testing/builders/buildLicenseOrderPreviewData.js"; +import { buildDomainOrderPreviewData } from "../../../testing/builders/buildDomainOrderPreviewData.js"; +import { ExternalCertificateOrderPreview } from "../Preview/ExternalCertificateOrderPreview.js"; +import { ExternalCertificateOrderRequest } from "./ExternalCertificateOrderRequest.js"; +import { MailArchiveOrderPreview } from "../Preview/MailArchiveOrderPreview.js"; +import { AIHostingOrderPreview } from "../Preview/AIHostingOrderPreview.js"; +import { LeadFyndrOrderPreview } from "../Preview/LeadFyndrOrderPreview.js"; +import { WebhostingArticle } from "../../../article/Article/internal.js"; +import { HostingOrderPreview } from "../Preview/HostingOrderPreview.js"; +import { LicenseOrderPreview } from "../Preview/LicenseOrderPreview.js"; +import { MailArchiveOrderRequest } from "./MailArchiveOrderRequest.js"; +import { DomainOrderPreview } from "../Preview/DomainOrderPreview.js"; +import { AIHostingOrderRequest } from "./AIHostingOrderRequest.js"; +import { LeadFyndrOrderRequest } from "./LeadFyndrOrderRequest.js"; +import { HostingOrderRequest } from "./HostingOrderRequest.js"; +import { LicenseOrderRequest } from "./LicenseOrderRequest.js"; +import { DomainOrderRequest } from "./DomainOrderRequest.js"; +import { + buildArticleAttributeData, + buildArticleTemplateData, + buildArticleData, +} from "../../../testing/builders/buildArticleData.js"; +import { Contract } from "../../../contract/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../../testing/installBehaviors.js"; +import { Bytes } from "../../../common/index.js"; +import { Order } from "../Order.js"; + +afterEach(resetBehaviors); + +describe("DomainOrderRequest", () => { + test("exposes construction data and delegates preview creation", async () => { + const preview = vi.fn().mockResolvedValue(buildDomainOrderPreviewData()); + installBehaviors({ order: { preview } }); + const request = DomainOrderRequest.create({ + domain: "example.com", + authCode: "abc", + project: "p-1", + }); + + const result = await request.getPreview(); + + expect(request.domain).toBe("example.com"); + expect(request.authCode).toBe("abc"); + expect(preview).toHaveBeenCalledWith( + expect.objectContaining({ + orderData: expect.objectContaining({ + domain: "example.com", + projectId: "p-1", + }), + orderType: "domain", + }), + ); + expect(result).toBeInstanceOf(DomainOrderPreview); + }); +}); + +describe("ExternalCertificateOrderRequest", () => { + test("delegates preview creation", async () => { + const preview = vi + .fn() + .mockResolvedValue(buildExternalCertificateOrderPreviewData()); + installBehaviors({ order: { preview } }); + const request = ExternalCertificateOrderRequest.create({ + certificateRequestId: "cr-1", + project: "p-1", + }); + + const result = await request.getPreview(); + + expect(preview).toHaveBeenCalledWith( + expect.objectContaining({ + orderData: expect.objectContaining({ projectId: "p-1" }), + orderType: "externalCertificate", + }), + ); + expect(result).toBeInstanceOf(ExternalCertificateOrderPreview); + }); +}); + +describe("LicenseOrderRequest", () => { + test("delegates preview creation", async () => { + const preview = vi.fn().mockResolvedValue(buildLicenseOrderPreviewData()); + installBehaviors({ order: { preview } }); + const request = new LicenseOrderRequest({ + licenseType: "typo3", + majorVersion: 12, + }); + + const result = await request.getPreview(); + + expect(preview).toHaveBeenCalledWith( + expect.objectContaining({ orderType: "license" }), + ); + expect(result).toBeInstanceOf(LicenseOrderPreview); + }); + + test("delegates ordering and returns an order reference", async () => { + const create = vi.fn().mockResolvedValue({ id: "new-order" }); + installBehaviors({ order: { create } }); + const request = new LicenseOrderRequest({ + licenseType: "typo3", + majorVersion: 12, + }); + + const result = await request.order({ description: "d", projectId: "p-1" }); + + expect(create).toHaveBeenCalledWith( + expect.objectContaining({ orderType: "license" }), + ); + expect(result).toBeInstanceOf(Order); + expect(result.id).toBe("new-order"); + }); +}); + +describe("LeadFyndrOrderRequest", () => { + test("delegates preview creation", async () => { + const preview = vi.fn().mockResolvedValue(buildLeadFyndrOrderPreviewData()); + installBehaviors({ order: { preview } }); + const request = new LeadFyndrOrderRequest({ + reservationLimit: 1, + unlockLimit: 1, + }); + + const result = await request.getPreview(); + + expect(preview).toHaveBeenCalledWith( + expect.objectContaining({ orderType: "leadFyndr" }), + ); + expect(result).toBeInstanceOf(LeadFyndrOrderPreview); + }); + + test("delegates ordering and returns an order reference", async () => { + const create = vi.fn().mockResolvedValue({ id: "new-order" }); + installBehaviors({ order: { create } }); + const request = new LeadFyndrOrderRequest({ + reservationLimit: 1, + unlockLimit: 1, + }); + + const result = await request.order({ customerId: "c-1" }); + + expect(create).toHaveBeenCalledWith( + expect.objectContaining({ orderType: "leadFyndr" }), + ); + expect(result).toBeInstanceOf(Order); + expect(result.id).toBe("new-order"); + }); +}); + +describe("MailArchiveOrderRequest", () => { + test("delegates preview creation with the mail address id", async () => { + const preview = vi + .fn() + .mockResolvedValue(buildMailArchiveOrderPreviewData()); + installBehaviors({ order: { preview } }); + const request = new MailArchiveOrderRequest({ mailAddress: "m-1" }); + + const result = await request.getPreview(); + + expect(preview).toHaveBeenCalledWith( + expect.objectContaining({ + orderData: expect.objectContaining({ mailAddressId: "m-1" }), + orderType: "mailArchive", + }), + ); + expect(result).toBeInstanceOf(MailArchiveOrderPreview); + }); +}); + +describe("AIHostingOrderRequest", () => { + test("delegates preview creation", async () => { + const preview = vi.fn().mockResolvedValue({ totalPrice: 100 }); + installBehaviors({ order: { preview } }); + const request = new AIHostingOrderRequest({ + requestsPerMinute: 10, + monthlyTokens: 1000, + }); + + const result = await request.getPreview(); + + expect(preview).toHaveBeenCalledWith( + expect.objectContaining({ orderType: "aiHosting" }), + ); + expect(result).toBeInstanceOf(AIHostingOrderPreview); + }); +}); + +const buildWebhostingArticle = () => + new WebhostingArticle( + buildArticleData({ + attributes: [ + buildArticleAttributeData({ key: "storage", value: "20", unit: "GiB" }), + buildArticleAttributeData({ unit: "GiB", key: "ram", value: "2" }), + buildArticleAttributeData({ key: "vcpu", value: "2" }), + ], + template: buildArticleTemplateData({ name: "Webhosting" }), + articleId: "webhosting-1", + }), + ); + +describe("HostingOrderRequest", () => { + test("clamps storage below the article base up to the base storage", () => { + const request = HostingOrderRequest.create( + buildWebhostingArticle(), + Bytes.of(5, "GiB"), + ); + + expect(request.storage.gib).toBe(20); + }); + + test("keeps storage at or above the article base", () => { + const request = HostingOrderRequest.create( + buildWebhostingArticle(), + Bytes.of(40, "GiB"), + ); + + expect(request.storage.gib).toBe(40); + }); + + test("delegates preview creation without a contract", async () => { + const preview = vi + .fn() + .mockResolvedValue(buildHostingOrderPreviewData({ totalPrice: 500 })); + installBehaviors({ order: { preview } }); + const request = HostingOrderRequest.create( + buildWebhostingArticle(), + Bytes.of(40, "GiB"), + ); + + const result = await request.getPreview(); + + expect(preview).toHaveBeenCalledWith({ + orderData: { + spec: { vcpu: 2, ram: 2 }, + useFreeTrial: undefined, + diskspaceInGiB: 40, + }, + orderType: "projectHosting", + }); + expect(result).toBeInstanceOf(HostingOrderPreview); + expect(result.totalPrice.getAmount()).toBe(500); + }); + + test("delegates a tariff-change preview when a contract is present", async () => { + const previewTariffChange = vi + .fn() + .mockResolvedValue(buildHostingOrderPreviewData()); + installBehaviors({ order: { previewTariffChange } }); + const request = HostingOrderRequest.create( + buildWebhostingArticle(), + Bytes.of(40, "GiB"), + Contract.ofId("contract-1"), + ); + + const result = await request.getPreview(); + + expect(previewTariffChange).toHaveBeenCalledWith({ + tariffChangeData: { + spec: { vcpu: 2, ram: 2 }, + contractId: "contract-1", + useFreeTrial: undefined, + diskspaceInGiB: 40, + }, + tariffChangeType: "projectHosting", + }); + expect(result).toBeInstanceOf(HostingOrderPreview); + }); + + test("delegates order creation with customer and description", async () => { + const create = vi.fn().mockResolvedValue({ id: "order-1" }); + installBehaviors({ order: { create } }); + const request = HostingOrderRequest.create( + buildWebhostingArticle(), + Bytes.of(40, "GiB"), + ); + + const result = await request.order({ + description: "My hosting", + customerId: "c-1", + }); + + expect(create).toHaveBeenCalledWith({ + orderData: { + description: "My hosting", + spec: { vcpu: 2, ram: 2 }, + promotionCode: undefined, + useFreeTrial: undefined, + diskspaceInGiB: 40, + customerId: "c-1", + }, + orderType: "projectHosting", + }); + expect(result).toBeInstanceOf(Order); + expect(result.id).toBe("order-1"); + }); +}); diff --git a/packages/models/src/order/Order/behaviors/api.ts b/packages/models/src/order/Order/behaviors/api.ts new file mode 100644 index 00000000..042c2823 --- /dev/null +++ b/packages/models/src/order/Order/behaviors/api.ts @@ -0,0 +1,84 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import { DateTime } from "luxon"; + +import type { OrderBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { anyStatus404 } from "../../../base/api/typeFixes.js"; +import { resolveTotalCount } from "../../../base/index.js"; + +export const apiOrderBehaviors = ( + client: MittwaldAPIV2Client, +): OrderBehaviors => ({ + list: async (query = {}) => { + const { customerId, projectId, ...restQuery } = query; + + const response = customerId + ? await client.contract.orderListCustomerOrders({ + queryParameters: restQuery, + customerId, + }) + : projectId + ? await client.contract.orderListProjectOrders({ + queryParameters: restQuery, + projectId, + }) + : await client.contract.orderListOrders({ + queryParameters: restQuery, + }); + + validateResponse(response, 200); + + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + find: async (orderId) => { + const response = await client.contract.orderGetOrder({ orderId }); + + if (response.status === 200) { + return response.data; + } + + // API-DRIFT: orderGetOrder omits 404 in its generated response type, so anyStatus404 (404 as any) is passed (resolve: use the literal 404 once the client type declares it) + validateResponse(response, anyStatus404); + }, + + preview: async (data) => { + const response = await client.contract.orderPreviewOrder({ + data, + }); + + validateResponse(response, 200); + return { + ...response.data, + freeTrialUntil: DateTime.now().plus({ days: 10 }).endOf("day").toISO(), + }; + }, + previewTariffChange: async (tariffChangePreviewData) => { + const response = await client.contract.orderPreviewTariffChange({ + data: tariffChangePreviewData, + }); + validateResponse(response, 200); + return response.data; + }, + + create: async (data) => { + const response = await client.contract.orderCreateOrder({ + data, + }); + validateResponse(response, 201); + + return { id: response.data.orderId }; + }, + + createTariffChange: async (data) => { + const response = await client.contract.orderCreateTariffChange({ + data, + }); + validateResponse(response, 201); + }, +}); diff --git a/packages/models/src/order/Order/behaviors/index.ts b/packages/models/src/order/Order/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/order/Order/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/order/Order/behaviors/types.ts b/packages/models/src/order/Order/behaviors/types.ts new file mode 100644 index 00000000..b1710595 --- /dev/null +++ b/packages/models/src/order/Order/behaviors/types.ts @@ -0,0 +1,28 @@ +import type { QueryResponseData } from "../../../base/index.js"; +import type { + CreateOrderPreviewRequestData, + PlanChangePreviewRequestData, + TariffChangePreviewData, + CreateOrderRequestData, + PlanChangeRequestData, + OrderListQueryData, + OrderListItemData, + OrderPreviewData, + OrderData, +} from "../types.js"; + +export interface OrderBehaviors { + previewTariffChange: ( + tariffChangePreviewData: PlanChangePreviewRequestData, + ) => Promise; + list: ( + query?: OrderListQueryData, + ) => Promise>; + + preview: (data: CreateOrderPreviewRequestData) => Promise; + createTariffChange: (data: PlanChangeRequestData) => Promise; + + create: (data: CreateOrderRequestData) => Promise<{ id: string }>; + + find: (orderId: string) => Promise; +} diff --git a/packages/models/src/order/Order/index.ts b/packages/models/src/order/Order/index.ts new file mode 100644 index 00000000..c02bfa70 --- /dev/null +++ b/packages/models/src/order/Order/index.ts @@ -0,0 +1,14 @@ +export * from "./Order.js"; +export * from "./Preview/DomainOrderPreview.js"; +export * from "./Preview/ExternalCertificateOrderPreview.js"; +export * from "./Preview/HostingOrderPreview.js"; +export * from "./Preview/LeadFyndrOrderPreview.js"; +export * from "./Preview/LicenseOrderPreview.js"; +export * from "./Request/AIHostingOrderRequest.js"; +export * from "./Request/DomainOrderRequest.js"; +export * from "./Request/ExternalCertificateOrderRequest.js"; +export * from "./Request/HostingOrderRequest.js"; +export * from "./Request/LeadFyndrOrderRequest.js"; +export * from "./Request/LicenseOrderRequest.js"; +export * from "./Request/MailArchiveOrderRequest.js"; +export * from "./types.js"; diff --git a/packages/models/src/order/Order/lib.ts b/packages/models/src/order/Order/lib.ts new file mode 100644 index 00000000..848786be --- /dev/null +++ b/packages/models/src/order/Order/lib.ts @@ -0,0 +1,112 @@ +export const getRecommendedStorage = (hardwareSpecs: string) => { + switch (hardwareSpecs) { + case "space-server.128cpu-dedicated.256gb-ram": + return "2000"; + case "space-server.128cpu-dedicated.128gb-ram": + return "1500"; + case "space-server.32cpu-dedicated.128gb-ram": + return "1500"; + case "space-server.64cpu-dedicated.128gb-ram": + return "1500"; + case "space-server.64cpu-dedicated.256gb-ram": + return "2000"; + case "space-server.64cpu-dedicated.512gb-ram": + return "2500"; + case "space-server.16cpu-dedicated.16gb-ram": + return "300"; + case "space-server.16cpu-dedicated.32gb-ram": + return "500"; + + case "space-server.16cpu-dedicated.64gb-ram": + return "850"; + case "space-server.32cpu-dedicated.32gb-ram": + return "500"; + case "space-server.32cpu-dedicated.64gb-ram": + return "850"; + case "space-server.64cpu-dedicated.64gb-ram": + return "850"; + case "space-server.8cpu-dedicated.16gb-ram": + return "300"; + case "space-server.8cpu-dedicated.32gb-ram": + return "500"; + case "space-server.8cpu-dedicated.8gb-ram": + return "200"; + case "space-server.32cpu-shared.128gb-ram": + return "1500"; + + case "space-server.16cpu-shared.64gb-ram": + return "850"; + case "space-server.4cpu-shared.16gb-ram": + return "300"; + case "space-server.8cpu-shared.32gb-ram": + return "500"; + case "space-server.2cpu-shared.8gb-ram": + return "100"; + case "prospace.shared.16cpu.128gb": + case "prospace.16cpu.128gb": + return "500"; + case "prospace.shared.16cpu.32gb": + case "prospace.16cpu.32gb": + return "300"; + + case "prospace.shared.16cpu.64gb": + case "prospace.16cpu.64gb": + return "400"; + case "prospace.shared.8cpu.16gb": + + // eslint-disable-next-line no-fallthrough -- adjacent cases intentionally share this return + case "prospace.8cpu.16gb": + return "200"; + case "prospace.shared.4cpu.16gb": + case "prospace.4cpu.16gb": + return "200"; + case "prospace.shared.8cpu.32gb": + case "prospace.8cpu.32gb": + return "300"; + case "prospace.shared.2cpu.16gb": + + // eslint-disable-next-line no-fallthrough -- adjacent cases intentionally share this return + case "prospace.2cpu.16gb": + return "100"; + case "prospace.shared.4cpu.32gb": + case "prospace.4cpu.32gb": + return "200"; + case "prospace.shared.8cpu.64gb": + case "prospace.8cpu.64gb": + return "400"; + case "prospace.shared.2cpu.4gb": + case "prospace.2cpu.4gb": + return "60"; + case "prospace.shared.4cpu.8gb": + case "prospace.4cpu.8gb": + return "100"; + case "prospace.shared.2cpu.8gb": + case "prospace.2cpu.8gb": + return "100"; + case '{"vcpu":1,"ram":1}': + return "20"; + case '{"vcpu":1,"ram":2}': + return "40"; + case '{"vcpu":2,"ram":4}': + return "60"; + case "PS23-BASIC-0001": + return "20"; + case "PS23-BASIC-0002": + return "40"; + case "PS23-BASIC-0003": + return "60"; + case "shared.2xlarge": + return "150"; + case "shared.3xlarge": + return "300"; + case "shared.4xlarge": + return "500"; + + case "shared.5xlarge": + return "850"; + case "shared.6xlarge": + return "1500"; + case "shared.xlarge": + return "100"; + } +}; diff --git a/packages/models/src/order/Order/types.ts b/packages/models/src/order/Order/types.ts new file mode 100644 index 00000000..46680eb1 --- /dev/null +++ b/packages/models/src/order/Order/types.ts @@ -0,0 +1,177 @@ +import type { RequiredKeysOf, SetOptional } from "type-fest"; +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import type { + MachineTypeSpecs, + HardwareSpecs, + Project, +} from "../../project/index.js"; +import type { Customer } from "../../customer/index.js"; +import type { MailAddress } from "../../mail/index.js"; + +export type OrderData = MittwaldAPIV2.Operations.OrderGetOrder.ResponseData; + +export type OrderListItemData = + MittwaldAPIV2.Operations.OrderListOrders.ResponseData[number]; + +export type OrderListQueryData = + MittwaldAPIV2.Paths.V2Orders.Get.Parameters.Query & { + customerId?: string; + projectId?: string; + }; + +export type OrderStatusApiData = + MittwaldAPIV2.Components.Schemas.OrderOrderStatus; + +export type OrderListQueryModelData = { + customer?: Customer | string; + project?: Project | string; +} & Omit; + +export type OrderTypeData = MittwaldAPIV2.Components.Schemas.OrderOrderType; + +export type ProjectOrderRequestData = + MittwaldAPIV2.Components.Schemas.OrderProjectHostingOrder; + +export type ProjectOrderRequestModelData = { + customer: Customer | string; + spec: HostingOrderSpecs; +} & Omit; + +export type DomainOrderRequestData = + MittwaldAPIV2.Components.Schemas.OrderDomainOrder; + +export type DomainOrderRequestModelData = { + ownerC: MittwaldAPIV2.Components.Schemas.OrderDomainOrder["handleData"]["ownerC"]; + project: Project | string; +} & Omit< + MittwaldAPIV2.Components.Schemas.OrderDomainOrder, + "handleData" | "projectId" +>; + +export type ExternalCertificateOrderRequestData = + MittwaldAPIV2.Components.Schemas.OrderExternalCertificateOrder; + +export type ExternalCertificateOrderRequestModelData = Omit< + ExternalCertificateOrderRequestData, + "projectId" +> & { + project: Project | string; +}; + +export type ExternalCertificateOrderData = + MittwaldAPIV2.Components.Schemas.OrderExternalCertificateOrder; + +export type LeadFyndrOrderRequestData = + MittwaldAPIV2.Components.Schemas.OrderLeadFyndrOrder; + +export type LicenseOrderRequestData = + MittwaldAPIV2.Components.Schemas.OrderLicenseOrder; + +export type HostingOrderSpecs = MachineTypeSpecs | HardwareSpecs; + +export type ExternalCertificateOrderPreviewRequestData = + MittwaldAPIV2.Components.Schemas.OrderExternalCertificateOrderPreview; + +export type ExternalCertificateOrderPreviewRequestModelData = Omit< + ExternalCertificateOrderPreviewRequestData, + "projectId" +> & { + project: Project | string; +}; + +export type DomainOrderPreviewRequestData = + MittwaldAPIV2.Components.Schemas.OrderDomainOrderPreview; + +export type DomainOrderPreviewRequestModelData = Omit< + MittwaldAPIV2.Components.Schemas.OrderDomainOrderPreview, + "projectId" +> & { + project: Project | string; +}; + +export type AiHostingOrderPreviewRequestData = + MittwaldAPIV2.Components.Schemas.OrderAIHostingOrderPreview; + +export type AiHostingOrderData = + MittwaldAPIV2.Components.Schemas.OrderAIHostingOrder; + +export type ServerOrderRequestData = + MittwaldAPIV2.Components.Schemas.OrderServerOrder; + +export type ServerOrderRequestModelData = { + machineType: MachineTypeSpecs; + customer: Customer | string; +} & Omit; + +export type MailArchiveOrderData = + MittwaldAPIV2.Components.Schemas.OrderMailArchiveOrder; + +export type MailArchiveOrderRequestModelData = Omit< + MittwaldAPIV2.Components.Schemas.OrderMailArchiveOrder, + "mailAddressId" +> & { + mailAddress: MailAddress | string; +}; + +export type MailArchiveOrderPreviewRequestModelData = Omit< + MittwaldAPIV2.Components.Schemas.OrderMailArchiveOrderPreview, + "mailAddressId" +> & { + mailAddress: MailAddress | string; +}; + +export type MailArchiveOrderPreviewData = + MittwaldAPIV2.Components.Schemas.OrderMailArchiveOrderPreviewResponse; + +export type CreateOrderRequestData = + MittwaldAPIV2.Paths.V2Orders.Post.Parameters.RequestBody; + +export type CreateOrderPreviewRequestData = + MittwaldAPIV2.Paths.V2OrderPreviews.Post.Parameters.RequestBody; + +export type OrderStatus = MittwaldAPIV2.Components.Schemas.OrderOrderStatus; + +export type PlanChangeRequestData = + MittwaldAPIV2.Operations.OrderCreateTariffChange.RequestData; + +export type PlanChangePreviewRequestData = + MittwaldAPIV2.Operations.OrderPreviewTariffChange.RequestData; + +export type DomainOrderPreviewData = + MittwaldAPIV2.Components.Schemas.OrderDomainOrderPreviewResponse; + +export type HostingOrderPreviewData = + MittwaldAPIV2.Components.Schemas.OrderHostingOrderPreviewResponse & { + freeTrialUntil?: string; + }; + +export type ExternalCertificateOrderPreviewData = + MittwaldAPIV2.Components.Schemas.OrderExternalCertificateOrderPreviewResponse; + +export type LeadFyndrOrderPreviewData = + MittwaldAPIV2.Components.Schemas.OrderLeadFyndrOrderPreviewResponse; + +export type LeadFyndrOrderPreviewRequestData = + MittwaldAPIV2.Components.Schemas.OrderLeadFyndrOrderPreview; + +export type LicenseOrderPreviewData = + MittwaldAPIV2.Components.Schemas.OrderLicenseOrderPreviewResponse; + +export type LicenseOrderPreviewRequestData = + MittwaldAPIV2.Components.Schemas.OrderLicenseOrderPreview; + +export type OrderPreviewData = + | ExternalCertificateOrderPreviewData + | LeadFyndrOrderPreviewData + | HostingOrderPreviewData + | LicenseOrderPreviewData + | DomainOrderPreviewData; + +export type CompleteOrderRequestData< + TRequest extends object, + TOrder extends object, +> = SetOptional, keyof TOrder>>; + +export type TariffChangePreviewData = + MittwaldAPIV2.Operations.OrderPreviewTariffChange.ResponseData; diff --git a/packages/models/src/order/OrderItem/OrderItem.test.ts b/packages/models/src/order/OrderItem/OrderItem.test.ts new file mode 100644 index 00000000..49600133 --- /dev/null +++ b/packages/models/src/order/OrderItem/OrderItem.test.ts @@ -0,0 +1,34 @@ +import { afterEach, expect, test } from "vitest"; + +import { buildOrderItemData } from "../../testing/builders/buildOrderItemData.js"; +import { resetBehaviors } from "../../testing/installBehaviors.js"; +import { OrderItem } from "./OrderItem.js"; +import { DataModel } from "../../base/index.js"; + +afterEach(resetBehaviors); + +test("constructs an order item from behavior data", () => { + const item = new OrderItem( + buildOrderItemData({ + attributeConfiguration: [{ value: "v", key: "k" }], + articleName: "My Article", + orderItemId: "i-1", + }), + ); + + expect(item.id).toBe("i-1"); + expect(item.name).toBe("My Article"); + expect(item.attributeConfiguration?.[0]?.value).toBe("v"); +}); + +test("uses the order item id as the name when the article name is absent", () => { + const item = new OrderItem( + buildOrderItemData({ articleName: undefined, orderItemId: "i-2" }), + ); + + expect(item.name).toBe("i-2"); +}); + +test("is a data model", () => { + expect(new OrderItem(buildOrderItemData())).toBeInstanceOf(DataModel); +}); diff --git a/packages/models/src/order/OrderItem/OrderItem.ts b/packages/models/src/order/OrderItem/OrderItem.ts new file mode 100644 index 00000000..a962bba3 --- /dev/null +++ b/packages/models/src/order/OrderItem/OrderItem.ts @@ -0,0 +1,19 @@ +import type { + OrderAttributeConfigurationData, + OrderItemData, +} from "./types.js"; + +import { DataModel } from "../../base/index.js"; + +export class OrderItem extends DataModel { + public readonly attributeConfiguration?: OrderAttributeConfigurationData[]; + public readonly id: string; + public readonly name: string; + + public constructor(data: OrderItemData) { + super(data); + this.id = data.orderItemId; + this.name = data.articleName ?? data.orderItemId; + this.attributeConfiguration = data.attributeConfiguration; + } +} diff --git a/packages/models/src/order/OrderItem/index.ts b/packages/models/src/order/OrderItem/index.ts new file mode 100644 index 00000000..97088abc --- /dev/null +++ b/packages/models/src/order/OrderItem/index.ts @@ -0,0 +1,2 @@ +export * from "./OrderItem.js"; +export * from "./types.js"; diff --git a/packages/models/src/order/OrderItem/types.ts b/packages/models/src/order/OrderItem/types.ts new file mode 100644 index 00000000..ef4c0129 --- /dev/null +++ b/packages/models/src/order/OrderItem/types.ts @@ -0,0 +1,6 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type OrderItemData = MittwaldAPIV2.Components.Schemas.OrderOrderItem; + +export type OrderAttributeConfigurationData = + MittwaldAPIV2.Components.Schemas.OrderAttributeConfiguration; diff --git a/packages/models/src/order/index.ts b/packages/models/src/order/index.ts new file mode 100644 index 00000000..061b5f31 --- /dev/null +++ b/packages/models/src/order/index.ts @@ -0,0 +1,2 @@ +export * from "./Order/index.js"; +export * from "./OrderItem/index.js"; diff --git a/packages/models/src/performance/Performance/Performance.test.ts b/packages/models/src/performance/Performance/Performance.test.ts new file mode 100644 index 00000000..5ea09f78 --- /dev/null +++ b/packages/models/src/performance/Performance/Performance.test.ts @@ -0,0 +1,423 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { buildPerformanceIngressListItemData } from "../../testing/builders/buildPerformanceIngressListItemData.js"; +import { buildPerformanceListItemData } from "../../testing/builders/buildPerformanceListItemData.js"; +import { buildPerformanceData } from "../../testing/builders/buildPerformanceData.js"; +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { ListQueryModel, ReferenceModel } from "../../base/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { Project } from "../../project/index.js"; +import { + PerformanceSubpageItem, + PerformanceListQuery, + PerformanceDetailed, + PerformanceListItem, + PerformanceMetric, + PerformanceList, + Performance, +} from "./Performance.js"; + +afterEach(resetBehaviors); + +describe("Performance", () => { + test("constructs a reference from its identifiers", () => { + const performance = Performance.ofIdentifier( + "p-1", + "i-1", + "example.com", + "/some", + "2024-06-01", + ); + + expect(performance.id).toBe("p-1/example.com/some"); + expect(performance.hostname).toBe("example.com"); + expect(performance.path).toBe("/some"); + expect(performance.project.id).toBe("p-1"); + expect(performance.ingress.id).toBe("i-1"); + expect(performance.date?.hour).toBe(12); + expect( + Performance.ofIdentifier("p-1", "i-1", "example.com").date, + ).toBeUndefined(); + }); + + test("find delegates and maps present data", async () => { + const data = buildPerformanceData(); + const find = vi.fn().mockResolvedValue(data); + installBehaviors({ performance: { find } }); + + const result = await Performance.find( + "p-1", + "i-1", + "example.com", + "/some", + "2024-06-01", + ); + + expect(find).toHaveBeenCalledWith("example.com", "/some", "2024-06-01"); + expect(result).toBeInstanceOf(PerformanceDetailed); + }); + + test("find returns undefined when no data exists", async () => { + installBehaviors({ + performance: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + Performance.find("p-1", "i-1", "example.com"), + ).resolves.toBeUndefined(); + }); + + test("get returns details or throws ObjectNotFoundError", async () => { + installBehaviors({ + performance: { find: vi.fn().mockResolvedValue(buildPerformanceData()) }, + }); + await expect( + Performance.get("p-1", "i-1", "example.com"), + ).resolves.toBeInstanceOf(PerformanceDetailed); + + installBehaviors({ + performance: { find: vi.fn().mockResolvedValue(undefined) }, + }); + const promise = Performance.get("p-1", "i-1", "example.com"); + await expect(promise).rejects.toThrow(); + await expect(promise).rejects.toBeInstanceOf(ObjectNotFoundError); + }); + + test("reference detail methods delegate with normalized identifiers", async () => { + const find = vi.fn().mockResolvedValue(buildPerformanceData()); + installBehaviors({ performance: { find } }); + const reference = Performance.ofIdentifier( + "p-1", + "i-1", + "example.com", + "/some", + "2024-06-01", + ); + + await expect(reference.findDetailed()).resolves.toBeInstanceOf( + PerformanceDetailed, + ); + await expect(reference.getDetailed()).resolves.toBeInstanceOf( + PerformanceDetailed, + ); + expect(find).toHaveBeenNthCalledWith( + 1, + "example.com", + "/some", + reference.date?.toISO(), + ); + expect(find).toHaveBeenNthCalledWith( + 2, + "example.com", + "/some", + reference.date?.toISO(), + ); + }); +}); + +describe("PerformanceDetailed", () => { + test("exposes metrics and derived values", () => { + const data = buildPerformanceData(); + const detailed = new PerformanceDetailed(data, "p-1", "i-1"); + + expect(detailed.metrics).toEqual(data.metrics); + expect(detailed.moreDataAvailable).toHaveLength(2); + expect(detailed.moreDataAvailable.every((date) => date.isValid)).toBe(true); + expect(detailed.performanceScoreMetric).toMatchObject({ + value: 87.5, + text: "87%", + }); + expect(detailed.ttfbSeconds).toMatchObject({ text: "0.50 s", value: 0.5 }); + expect(detailed.speedIndex).toMatchObject({ text: "1.00 s", value: 1 }); + expect(detailed.loadTimeSeconds).toMatchObject({ text: "–", value: 0 }); + }); + + test("preserves the ghostmaker identity chain", () => { + const detailed = new PerformanceDetailed( + buildPerformanceData(), + "p-1", + "i-1", + ); + const listItem = new PerformanceListItem( + buildPerformanceListItemData(), + "p-1", + "i-1", + ); + + expect(listItem).toBeInstanceOf(PerformanceListItem); + expect(listItem).toBeInstanceOf(Performance); + expect(listItem).toBeInstanceOf(ReferenceModel); + expect(listItem.data).toBeDefined(); + expect(detailed).toBeInstanceOf(PerformanceDetailed); + expect(detailed).toBeInstanceOf(Performance); + expect(detailed).toBeInstanceOf(ReferenceModel); + expect(detailed.data).toBeDefined(); + }); +}); + +describe("Performance common variant", () => { + test("findCommon delegates to the detailed lookup for a bare reference", async () => { + const find = vi.fn().mockResolvedValue(buildPerformanceData()); + installBehaviors({ performance: { find } }); + const reference = Performance.ofIdentifier( + "p-1", + "i-1", + "example.com", + "/some", + "2024-06-01", + ); + + const common = await reference.findCommon(); + + expect(find).toHaveBeenCalledWith( + "example.com", + "/some", + reference.date?.toISO(), + ); + expect(common).toBeInstanceOf(PerformanceDetailed); + }); + + test("findCommon resolves undefined when the reference cannot be found", async () => { + installBehaviors({ + performance: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + Performance.ofIdentifier("p-1", "i-1", "example.com").findCommon(), + ).resolves.toBeUndefined(); + }); + + test("getCommon delegates for a bare reference and throws when not found", async () => { + installBehaviors({ + performance: { find: vi.fn().mockResolvedValue(buildPerformanceData()) }, + }); + await expect( + Performance.ofIdentifier("p-1", "i-1", "example.com").getCommon(), + ).resolves.toBeInstanceOf(PerformanceDetailed); + + installBehaviors({ + performance: { find: vi.fn().mockResolvedValue(undefined) }, + }); + await expect( + Performance.ofIdentifier("p-1", "i-1", "example.com").getCommon(), + ).rejects.toBeInstanceOf(ObjectNotFoundError); + }); + + test("findCommon on an already-materialized model returns itself without re-fetching", async () => { + const find = vi.fn().mockResolvedValue(buildPerformanceData()); + installBehaviors({ performance: { find } }); + + const detailed = new PerformanceDetailed( + buildPerformanceData(), + "p-1", + "i-1", + ); + await expect(detailed.findCommon()).resolves.toBe(detailed); + + const listItem = new PerformanceListItem( + buildPerformanceListItemData(), + "p-1", + "i-1", + ); + await expect(listItem.findCommon()).resolves.toBe(listItem); + + expect(find).not.toHaveBeenCalled(); + }); + + test("getCommon on an already-materialized model returns itself without re-fetching", async () => { + const find = vi.fn().mockResolvedValue(buildPerformanceData()); + installBehaviors({ performance: { find } }); + + const detailed = new PerformanceDetailed( + buildPerformanceData(), + "p-1", + "i-1", + ); + await expect(detailed.getCommon()).resolves.toBe(detailed); + + const listItem = new PerformanceListItem( + buildPerformanceListItemData(), + "p-1", + "i-1", + ); + await expect(listItem.getCommon()).resolves.toBe(listItem); + + expect(find).not.toHaveBeenCalled(); + }); +}); + +describe("Performance absent-optional edge cases", () => { + test("PerformanceDetailed defaults metrics and moreDataAvailable to empty arrays when absent", () => { + const detailed = new PerformanceDetailed( + buildPerformanceData({ + moreDataAvailable: undefined, + metrics: undefined, + }), + "p-1", + "i-1", + ); + + expect(detailed.metrics).toEqual([]); + expect(detailed.moreDataAvailable).toEqual([]); + }); + + test("metric getters fall back to neutral display when the metric is missing", () => { + const detailed = new PerformanceDetailed( + buildPerformanceData({ metrics: [] }), + "p-1", + "i-1", + ); + + expect(detailed.ttfbSeconds).toMatchObject({ text: "–", value: 0 }); + expect(detailed.speedIndex).toMatchObject({ text: "–", value: 0 }); + expect(detailed.contentDownloadedBytes).toMatchObject({ + text: "–", + value: 0, + }); + }); + + test("PerformanceListItem yields no subpages when paths are absent", () => { + const item = new PerformanceListItem( + buildPerformanceListItemData({ paths: undefined }), + "p-1", + "i-1", + ); + + expect(item.subpages).toEqual([]); + }); + + test("common variant leaves screenshot/createdAt undefined and score at zero when source omits them", () => { + const item = new PerformanceListItem( + buildPerformanceListItemData({ paths: undefined }), + "p-1", + "i-1", + ); + + expect(item.screenshot).toBeUndefined(); + expect(item.createdAt).toBeUndefined(); + expect(item.performanceScore).toBe(0); + }); +}); + +describe("PerformanceMetric", () => { + test("classifies min-desired boundary values", () => { + const create = (value: number) => + new PerformanceMetric({ + mediumThreshold: 10, + lowThreshold: 20, + highest: 0, + lowest: 30, + value, + }); + + expect(create(9)).toMatchObject({ valueIsHigh: true, desired: "min" }); + expect(create(10)).toMatchObject({ valueIsMedium: true }); + expect(create(20)).toMatchObject({ valueIsLow: true }); + }); + + test("classifies max-desired boundary values and defaults missing display data", () => { + const create = (value?: number) => + new PerformanceMetric({ + mediumThreshold: 70, + lowThreshold: 40, + highest: 100, + lowest: 0, + value, + }); + + expect(create(71)).toMatchObject({ valueIsHigh: true, desired: "max" }); + expect(create(70)).toMatchObject({ valueIsMedium: true }); + expect(create(40)).toMatchObject({ valueIsLow: true }); + expect(create()).toMatchObject({ text: "–", value: 0 }); + }); +}); + +describe("Performance lists", () => { + test("query and refine preserve the project and merge query data", async () => { + const project = Project.ofId("project-1"); + const query = Performance.query(project, { domain: "x" }); + const refined = query.refine({ domain: "y" }); + + expect(query).toBeInstanceOf(PerformanceListQuery); + expect(query.project).toBe(project); + expect(refined).not.toBe(query); + expect(refined.project).toBe(project); + + // The merged query is observable through the list behavior on execute(). + const list = vi.fn().mockResolvedValue({ items: [] }); + installBehaviors({ + ingress: { + list: vi.fn().mockResolvedValue({ totalCount: 0, items: [] }), + }, + performance: { list }, + }); + + await refined.execute(); + + expect(list).toHaveBeenCalledWith("project-1", { domain: "y" }); + }); + + test("execute joins matching ingresses and creates list items", async () => { + installBehaviors({ + ingress: { + list: vi.fn().mockResolvedValue({ + items: [buildPerformanceIngressListItemData()], + totalCount: 1, + }), + }, + performance: { + list: vi.fn().mockResolvedValue({ + items: [buildPerformanceListItemData()], + }), + }, + }); + + const result = await Performance.query(Project.ofId("project-1")).execute(); + + expect(result).toBeInstanceOf(PerformanceList); + expect(result).toBeInstanceOf(PerformanceListQuery); + expect(result.items).toBeDefined(); + expect(result).toBeInstanceOf(ListQueryModel); + expect(result.items).toHaveLength(1); + expect(result.items[0]).toBeInstanceOf(PerformanceListItem); + }); + + test("execute filters performance data without a matching ingress", async () => { + installBehaviors({ + performance: { + list: vi.fn().mockResolvedValue({ + items: [buildPerformanceListItemData()], + }), + }, + ingress: { + list: vi.fn().mockResolvedValue({ totalCount: 0, items: [] }), + }, + }); + + const result = await Performance.query(Project.ofId("project-1")).execute(); + expect(result.items).toHaveLength(0); + }); + + test("list items expose subpages", () => { + const item = new PerformanceListItem( + buildPerformanceListItemData(), + "p-1", + "i-1", + ); + + expect(item.subpages).toHaveLength(1); + expect(item.subpages[0]).toBeInstanceOf(PerformanceSubpageItem); + expect(item.subpages[0]?.path).toBe("/"); + }); +}); diff --git a/packages/models/src/performance/Performance/Performance.ts b/packages/models/src/performance/Performance/Performance.ts new file mode 100644 index 00000000..ca3afaec --- /dev/null +++ b/packages/models/src/performance/Performance/Performance.ts @@ -0,0 +1,503 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; + +import type { + PerformanceSubpageItemData, + PerformanceListQueryData, + PerformanceListItemData, + PerformanceMetricData, + PerformanceData, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { Ingress } from "../../ingress/Ingress/Ingress.js"; +import { Project } from "../../project/internal.js"; +import { File } from "../../file/File/internal.js"; +import { config } from "../../config/index.js"; +import { Bytes } from "../../common/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + DataModel, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "Performance", +}) +export class Performance extends ReferenceModel { + public readonly date?: DateTime; + public readonly hostname: string; + public readonly ingress: Ingress; + public readonly path: string; + public readonly project: Project; + + public constructor( + projectId: string, + ingressId: string, + hostname: string, + path = "/", + date?: string, + ) { + super(`${projectId}/${hostname}${path}`); + this.ingress = Ingress.ofId(ingressId); + this.project = Project.ofId(projectId); + this.hostname = hostname; + this.path = path; + this.date = date ? DateTime.fromISO(date).plus({ hour: 12 }) : undefined; + } + + public static async find( + projectId: string, + ingressId: string, + hostname: string, + path = "/", + date?: string, + ) { + const data = await config.behaviors.performance.find(hostname, path, date); + if (data !== undefined) { + return new PerformanceDetailed(data, projectId, ingressId); + } + } + + public static async get( + projectId: string, + ingressId: string, + hostname: string, + path = "/", + date?: string, + ) { + const performance = await Performance.find( + projectId, + ingressId, + hostname, + path, + date, + ); + assertObjectFound( + performance, + Performance, + `${projectId}/${hostname}${path}`, + ); + return performance; + } + + public static ofIdentifier( + projectId: string, + ingressId: string, + hostname: string, + path = "/", + date?: string, + ): Performance { + return new Performance(projectId, ingressId, hostname, path, date); + } + + public static query( + project: Project, + query: PerformanceListQueryData = {}, + ): PerformanceListQuery { + return new PerformanceListQuery(project, query); + } + + public async findCommon(): Promise { + return this instanceof PerformanceCommon ? this : this.findDetailed(); + } + + public async findDetailed(): Promise { + return Performance.find( + this.project.id, + this.ingress.id, + this.hostname, + this.path, + this.date?.toISO() ?? undefined, + ); + } + + public async getCommon(): Promise { + return this instanceof PerformanceCommon ? this : this.getDetailed(); + } + + public async getDetailed(): Promise { + return Performance.get( + this.project.id, + this.ingress.id, + this.hostname, + this.path, + this.date?.toISO() ?? undefined, + ); + } +} + +export class PerformanceCommon extends WithData< + PerformanceListItemData | PerformanceData +>()(Performance) { + public readonly createdAt?: DateTime; + + public override readonly data: PerformanceListItemData | PerformanceData; + public readonly domain: string; + public readonly performanceScore: number; + public readonly screenshot?: File; + + public constructor( + data: PerformanceListItemData | PerformanceData, + projectId: string, + ingressId: string, + ) { + const path = "path" in data ? data.path : "/"; + super(projectId, ingressId, data.domain, path); + this.data = data; + this.domain = data.domain; + + if ("performanceScore" in data) { + this.performanceScore = data.performanceScore; + } else { + this.performanceScore = 0; + } + if ("screenshotFileRef" in data) { + this.screenshot = + typeof data.screenshotFileRef === "string" + ? File.ofId(data.screenshotFileRef) + : undefined; + } else if ("screenshot" in data && data.screenshot) { + this.screenshot = + typeof data.screenshot.fileRef === "string" + ? File.ofId(data.screenshot.fileRef) + : undefined; + } + + if ("createdAt" in data && data.createdAt) { + this.createdAt = DateTime.fromISO(data.createdAt); + } + } +} + +export class PerformanceDetailed extends PerformanceCommon { + public override readonly data: PerformanceData; + + public readonly metrics: NonNullable; + public readonly moreDataAvailable: DateTime[]; + + public get co2SustainableWebGrams(): PerformanceMetric { + const metric = this.findMetric( + "page_insights_browser_co2_sustainable_web_grams", + ); + return new PerformanceMetric({ + text: metric ? `${metric.value} g` : undefined, + mediumThreshold: 0.48, + value: metric?.value, + lowThreshold: 1.49, + highest: 0, + lowest: 3, + }); + } + + public get contentDownloadedBytes(): PerformanceMetric { + const metric = this.findMetric( + "page_insights_browser_content_downloaded_bytes", + ); + return new PerformanceMetric({ + text: metric ? Bytes.of(metric.value, "bytes").text() : undefined, + mediumThreshold: 2750000, + lowThreshold: 6000000, + value: metric?.value, + lowest: 8000000, + highest: 0, + }); + } + + public get cumulativeLayoutShift(): PerformanceMetric { + const metric = this.findMetric( + "page_insights_browser_cumulative_layout_shift", + ); + return new PerformanceMetric({ + text: metric ? `${metric.value.toFixed(2)}` : undefined, + value: metric?.value, + mediumThreshold: 0.1, + lowThreshold: 0.25, + lowest: 0.4, + highest: 0, + }); + } + + public get firstContentfulPaint(): PerformanceMetric { + const metric = this.findMetric( + "page_insights_browser_first_contentful_paint_seconds", + ); + return new PerformanceMetric({ + text: metric ? `${metric.value.toFixed(2)} s` : undefined, + mediumThreshold: 0.934, + value: metric?.value, + lowThreshold: 1.6, + lowest: 2.0, + highest: 0, + }); + } + + public get largestContentfulPaint(): PerformanceMetric { + const metric = this.findMetric( + "page_insights_browser_largest_contentful_paint_seconds", + ); + return new PerformanceMetric({ + text: metric ? `${metric.value.toFixed(2)} s` : undefined, + value: metric?.value, + mediumThreshold: 1.2, + lowThreshold: 2.4, + highest: 0, + lowest: 4, + }); + } + + public get loadTimeSeconds(): PerformanceMetric { + const metric = this.findMetric("page_insights_browser_load_time_seconds"); + return new PerformanceMetric({ + text: metric ? `${metric.value.toFixed(2)} s` : undefined, + value: metric?.value, + mediumThreshold: 4.0, + lowThreshold: 6.5, + highest: 0, + lowest: 9, + }); + } + + public get performanceScoreMetric(): PerformanceMetric { + return new PerformanceMetric({ + text: `${Math.trunc(this.performanceScore)}%`, + value: this.performanceScore, + mediumThreshold: 90, + lowThreshold: 50, + highest: 100, + lowest: 0, + }); + } + + public get serverProcessingSeconds(): PerformanceMetric { + const metric = this.findMetric( + "page_insights_httpstats_server_processing_seconds", + ); + return new PerformanceMetric({ + text: metric ? `${metric.value.toFixed(2)} s` : undefined, + value: metric?.value, + mediumThreshold: 0.6, + lowThreshold: 1.2, + highest: 0, + lowest: 2, + }); + } + + public get speedIndex(): PerformanceMetric { + const metric = this.findMetric("page_insights_browser_speed_index_seconds"); + return new PerformanceMetric({ + text: metric ? `${metric.value.toFixed(2)} s` : undefined, + mediumThreshold: 1.311, + value: metric?.value, + lowThreshold: 2.3, + lowest: 3.5, + highest: 0, + }); + } + + public get startRenderSeconds(): PerformanceMetric { + const metric = this.findMetric( + "page_insights_browser_start_render_seconds", + ); + return new PerformanceMetric({ + text: metric ? `${metric.value.toFixed(2)} s` : undefined, + value: metric?.value, + mediumThreshold: 4.0, + lowThreshold: 6.5, + highest: 0, + lowest: 9, + }); + } + + public get totalBlockingTimeSeconds(): PerformanceMetric { + const metric = this.findMetric( + "page_insights_browser_total_blocking_time_seconds", + ); + return new PerformanceMetric({ + text: metric ? `${metric.value.toFixed(2)} s` : undefined, + mediumThreshold: 0.15, + value: metric?.value, + lowThreshold: 0.35, + lowest: 0.6, + highest: 0, + }); + } + + public get ttfbSeconds(): PerformanceMetric { + const metric = this.findMetric("page_insights_browser_ttfb_seconds"); + return new PerformanceMetric({ + text: metric ? `${metric.value.toFixed(2)} s` : undefined, + value: metric?.value, + mediumThreshold: 0.8, + lowThreshold: 1.8, + highest: 0, + lowest: 3, + }); + } + + public constructor( + data: PerformanceData, + projectId: string, + ingressId: string, + ) { + super(data, projectId, ingressId); + this.data = data; + this.metrics = data.metrics ?? []; + this.moreDataAvailable = + data.moreDataAvailable?.map((d) => DateTime.fromISO(d)) ?? []; + } + + private findMetric( + name: string, + ): { value: number; name: string } | undefined { + return this.metrics?.find((m) => m.name === name); + } +} + +export class PerformanceSubpageItem extends DataModel { + public readonly createdAt?: DateTime; + public readonly path: string; + public readonly performanceScore: number; + public readonly screenshotFileRef?: string; + + public constructor(data: PerformanceSubpageItemData) { + super(data); + this.path = data.path; + this.performanceScore = data.performanceScore; + this.screenshotFileRef = data.screenshotFileRef; + if (data.createdAt) { + this.createdAt = DateTime.fromISO(data.createdAt); + } + } +} + +export class PerformanceListItem extends PerformanceCommon { + public override readonly data: PerformanceListItemData; + + public readonly subpages: PerformanceSubpageItem[]; + + public constructor( + data: PerformanceListItemData, + projectId: string, + ingressId: string, + ) { + super(data, projectId, ingressId); + this.data = data; + this.subpages = data.paths?.map((p) => new PerformanceSubpageItem(p)) ?? []; + } +} + +export class PerformanceListQuery extends ListQueryModel { + public readonly project: Project; + + public constructor(project: Project, query: PerformanceListQueryData = {}) { + super(query, { + dependencies: [project.id], + }); + this.project = project; + } + + public async execute() { + const [{ items: performanceItems, totalCount }, ingresses] = + await Promise.all([ + config.behaviors.performance.list(this.project.id, this.query), + Ingress.query({ project: this.project.id }).execute(), + ]); + + const items = performanceItems + .map((performanceItem) => { + const ingress = ingresses.items.find( + (i) => i.hostname === performanceItem.domain, + ); + + if (!ingress) { + return undefined; + } + + return new PerformanceListItem( + performanceItem, + this.project.id, + ingress.id, + ); + }) + .filter((item): item is PerformanceListItem => undefined !== item); + + return new PerformanceList(this.project, this.query, items, totalCount); + } + + public refine(query: PerformanceListQueryData) { + return new PerformanceListQuery(this.project, { + ...this.query, + ...query, + }); + } +} + +export class PerformanceList extends WithListData()( + PerformanceListQuery, +) { + public override readonly items: readonly PerformanceListItem[]; + public override readonly totalCount: number; + + public constructor( + project: Project, + query: PerformanceListQueryData, + performances: PerformanceListItem[], + totalCount: number, + ) { + super(project, query); + this.items = Object.freeze(performances); + this.totalCount = totalCount; + } +} + +export class PerformanceMetric { + public readonly desired: "max" | "min"; + public readonly highest: number; + public readonly lowest: number; + public readonly lowThreshold: number; + public readonly lowThresholdPercent: number; + public readonly mediumThreshold: number; + public readonly mediumThresholdPercent: number; + public readonly range: number; + public readonly text: string; + public readonly value: number; + public readonly valueIsHigh: boolean; + public readonly valueIsLow: boolean; + public readonly valueIsMedium: boolean; + public readonly valuePercent: number; + + public constructor(data: PerformanceMetricData) { + this.value = data.value ?? 0; + this.text = data.text ?? "–"; + this.highest = data.highest; + this.lowest = data.lowest; + this.desired = this.lowest < this.highest ? "max" : "min"; + this.range = + this.desired === "max" + ? this.highest - this.lowest + : this.lowest - this.highest; + this.mediumThreshold = data.mediumThreshold; + this.mediumThresholdPercent = (100 / this.range) * this.mediumThreshold; + this.lowThreshold = data.lowThreshold; + this.lowThresholdPercent = (100 / this.range) * this.lowThreshold; + this.valuePercent = + this.desired === "max" + ? 100 - (100 / this.range) * this.value + : (100 / this.range) * this.value; + this.valueIsHigh = + this.desired === "max" + ? this.value > this.mediumThreshold + : this.value < this.mediumThreshold; + this.valueIsMedium = + this.desired === "max" + ? this.value <= this.mediumThreshold && this.value > this.lowThreshold + : this.value >= this.mediumThreshold && this.value < this.lowThreshold; + this.valueIsLow = + this.desired === "max" + ? this.value <= this.lowThreshold + : this.value >= this.lowThreshold; + } +} diff --git a/packages/models/src/performance/Performance/behaviors/api.ts b/packages/models/src/performance/Performance/behaviors/api.ts new file mode 100644 index 00000000..7fccb66f --- /dev/null +++ b/packages/models/src/performance/Performance/behaviors/api.ts @@ -0,0 +1,39 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { PerformanceBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount } from "../../../base/index.js"; + +export const apiPerformanceBehaviors = ( + client: MittwaldAPIV2Client, +): PerformanceBehaviors => ({ + list: async (projectId, query) => { + const response = + await client.pageInsights.pageinsightsListPerformanceDataForProject({ + queryParameters: query, + projectId, + }); + + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + find: async (hostname, path, date) => { + const response = await client.pageInsights.pageinsightsGetPerformanceData({ + queryParameters: { + domain: hostname, + path, + date, + }, + }); + + if (response.status === 200) { + return response.data; + } + validateResponse(response, 403); + }, +}); diff --git a/packages/models/src/performance/Performance/behaviors/index.ts b/packages/models/src/performance/Performance/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/performance/Performance/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/performance/Performance/behaviors/types.ts b/packages/models/src/performance/Performance/behaviors/types.ts new file mode 100644 index 00000000..cc799e71 --- /dev/null +++ b/packages/models/src/performance/Performance/behaviors/types.ts @@ -0,0 +1,18 @@ +import type { + PerformanceListQueryData, + PerformanceListItemData, + PerformanceData, +} from "../types.js"; + +export interface PerformanceBehaviors { + list: ( + projectId: string, + query?: PerformanceListQueryData, + ) => Promise<{ items: PerformanceListItemData[]; totalCount: number }>; + + find: ( + hostname: string, + path: string, + date?: string, + ) => Promise; +} diff --git a/packages/models/src/performance/Performance/index.ts b/packages/models/src/performance/Performance/index.ts new file mode 100644 index 00000000..544780e7 --- /dev/null +++ b/packages/models/src/performance/Performance/index.ts @@ -0,0 +1,2 @@ +export * from "./Performance.js"; +export * from "./types.js"; diff --git a/packages/models/src/performance/Performance/types.ts b/packages/models/src/performance/Performance/types.ts new file mode 100644 index 00000000..79be1045 --- /dev/null +++ b/packages/models/src/performance/Performance/types.ts @@ -0,0 +1,30 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type PerformanceData = + MittwaldAPIV2.Operations.PageinsightsGetPerformanceData.ResponseData; + +export type PerformanceListItemData = + MittwaldAPIV2.Operations.PageinsightsListPerformanceDataForProject.ResponseData[number]; + +export type PerformanceSubpageItemData = NonNullable< + PerformanceListItemData["paths"] +>[number]; + +export type PerformanceListQueryData = + MittwaldAPIV2.Paths.V2ProjectsProjectIdPageInsights.Get.Parameters.Query; + +export interface PerformanceMetricData { + mediumThreshold: number; + lowThreshold: number; + highest: number; + value?: number; + lowest: number; + text?: string; +} + +export interface PerformanceIdentifier { + projectId: string; + hostname: string; + path?: string; + date?: string; +} diff --git a/packages/models/src/performance/PerformanceTtfbAnalysis/PerformanceTtfbAnalysis.test.ts b/packages/models/src/performance/PerformanceTtfbAnalysis/PerformanceTtfbAnalysis.test.ts new file mode 100644 index 00000000..aff047be --- /dev/null +++ b/packages/models/src/performance/PerformanceTtfbAnalysis/PerformanceTtfbAnalysis.test.ts @@ -0,0 +1,167 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; + +import type { PerformanceTtfbAnalysisStraceData } from "./types.js"; + +import { buildPerformanceTtfbAnalysisData } from "../../testing/builders/buildPerformanceTtfbAnalysisData.js"; +import { ReferenceModel, DataModel } from "../../base/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { + PerformanceTtfbAnalysisDetailed, + PerformanceTtfbSummaryMetric, + PerformanceTtfbAnalysis, +} from "./PerformanceTtfbAnalysis.js"; + +afterEach(resetBehaviors); + +describe("PerformanceTtfbAnalysis", () => { + test("constructs a reference", () => { + const analysis = PerformanceTtfbAnalysis.ofId("p-1", "t-1"); + + expect(analysis.id).toBe("p-1/t-1"); + expect(analysis.projectId).toBe("p-1"); + expect(analysis.ttfbAnalysisId).toBe("t-1"); + expect(analysis).toBeInstanceOf(ReferenceModel); + }); + + test("trigger delegates and returns the behavior result", async () => { + const scheduled = { id: "scheduled-1" }; + const trigger = vi.fn().mockResolvedValue(scheduled); + installBehaviors({ performanceTtfbAnalysis: { trigger } }); + + await expect( + PerformanceTtfbAnalysis.trigger("p-1", "https://example.com/"), + ).resolves.toBe(scheduled); + expect(trigger).toHaveBeenCalledWith("p-1", "https://example.com/"); + }); + + test("find delegates with request config and maps present data", async () => { + const data = buildPerformanceTtfbAnalysisData(); + const find = vi.fn().mockResolvedValue(data); + const requestConfig = { headers: { "x-test": "yes" } }; + installBehaviors({ performanceTtfbAnalysis: { find } }); + + const result = await PerformanceTtfbAnalysis.find( + "p-1", + "t-1", + requestConfig, + ); + + expect(find).toHaveBeenCalledWith("p-1", "t-1", requestConfig); + expect(result).toBeInstanceOf(PerformanceTtfbAnalysisDetailed); + expect(result).toBeInstanceOf(DataModel); + }); + + test("find returns undefined when no data exists", async () => { + installBehaviors({ + performanceTtfbAnalysis: { + find: vi.fn().mockResolvedValue(undefined), + }, + }); + + await expect( + PerformanceTtfbAnalysis.find("p-1", "t-1"), + ).resolves.toBeUndefined(); + }); + + test("findDetailed delegates reference identifiers and request config", async () => { + const find = vi.fn().mockResolvedValue(buildPerformanceTtfbAnalysisData()); + const requestConfig = { retryCache: false }; + installBehaviors({ performanceTtfbAnalysis: { find } }); + + await PerformanceTtfbAnalysis.ofId("p-1", "t-1").findDetailed( + requestConfig, + ); + expect(find).toHaveBeenCalledWith("p-1", "t-1", requestConfig); + }); +}); + +describe("PerformanceTtfbAnalysisDetailed", () => { + test("derives core values from successful strace data", () => { + const detailed = new PerformanceTtfbAnalysisDetailed( + buildPerformanceTtfbAnalysisData(), + ); + + expect(detailed.executedAt.isValid).toBe(true); + expect(detailed.totalDuration).toBe(200); + expect(detailed.actualUrl).toBe("https://example.com/"); + }); + + test("uses empty core values for an error result", () => { + const detailed = new PerformanceTtfbAnalysisDetailed( + buildPerformanceTtfbAnalysisData({ result: { errorMessage: "boom" } }), + ); + + expect(detailed.totalDuration).toBe(0); + expect(detailed.actualUrl).toBe(""); + }); + + test("builds stats summaries with values, ratings, and classifications", () => { + const detailed = new PerformanceTtfbAnalysisDetailed( + buildPerformanceTtfbAnalysisData(), + ); + + expect(detailed.fileStatsSummary).toMatchObject({ value: 600 }); + expect(detailed.networkStatsSummary).toMatchObject({ value: 20 }); + expect(detailed.dbStatsSummary).toMatchObject({ value: 300 }); + for (const summary of [ + detailed.fileStatsSummary, + detailed.networkStatsSummary, + detailed.dbStatsSummary, + ]) { + expect(summary).toBeInstanceOf(PerformanceTtfbSummaryMetric); + expect(summary.rating).toBeGreaterThanOrEqual(1); + expect(summary.rating).toBeLessThanOrEqual(5); + expect(summary.classification).toEqual(expect.any(String)); + } + expect(detailed.miscStatsSummary).toMatchObject({ + classification: "detail.ttfb.stats.classification.mid", + rating: 3, + }); + }); + + test("enriches operation timing", () => { + const detailed = new PerformanceTtfbAnalysisDetailed( + buildPerformanceTtfbAnalysisData(), + ); + + expect(detailed.fileOps[0]?.stats.totalTimeMs).toBe(75); + expect(detailed.dbQueries[0]?.stats.totalTimeMs).toBe(75); + expect(detailed.networkingOps[0]?.stats.totalTimeMs).toBe(75); + }); + + test("returns empty operations when an operation list is empty", () => { + const data = buildPerformanceTtfbAnalysisData(); + const result = data.result as PerformanceTtfbAnalysisStraceData; + const detailed = new PerformanceTtfbAnalysisDetailed( + buildPerformanceTtfbAnalysisData({ + result: { ...result, networkingOps: [], dbQueries: [], fileOps: [] }, + }), + ); + + expect(detailed.fileOps).toEqual([]); + expect(detailed.dbQueries).toEqual([]); + expect(detailed.networkingOps).toEqual([]); + }); +}); + +describe("PerformanceTtfbSummaryMetric", () => { + const create = (value: number) => + new PerformanceTtfbSummaryMetric( + { slowdownFactor: 1, kernelMs: value, userspaceMs: 0 }, + 100, + 50, + ); + + test("rates error and warning threshold values", () => { + expect(create(100).rating).toBe(1); + expect(create(75).rating).toBe(2); + }); + + test("rates low values in the low classifications", () => { + expect(create(20).rating).toBe(4); + expect(create(10).rating).toBe(5); + }); +}); diff --git a/packages/models/src/performance/PerformanceTtfbAnalysis/PerformanceTtfbAnalysis.ts b/packages/models/src/performance/PerformanceTtfbAnalysis/PerformanceTtfbAnalysis.ts new file mode 100644 index 00000000..cd73d7f5 --- /dev/null +++ b/packages/models/src/performance/PerformanceTtfbAnalysis/PerformanceTtfbAnalysis.ts @@ -0,0 +1,228 @@ +import type { AxiosRequestConfig } from "axios"; + +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; + +import type { + PerformanceTtfbAnalysisStraceData, + PerformanceTtfbSummaryMetricData, + PerformanceTtfbAnalysisData, + EnrichedNetworkingOps, + EnrichedDbQueries, + EnrichedFileOps, +} from "./types.js"; + +import { ReferenceModel, DataModel } from "../../base/index.js"; +import { config } from "../../config/index.js"; + +export class PerformanceTtfbAnalysisDetailed extends DataModel { + public readonly actualUrl: string; + public readonly executedAt: DateTime; + public readonly totalDuration: number; + + public get dbQueries(): EnrichedDbQueries { + const result = this.data.result as PerformanceTtfbAnalysisStraceData; + if (!result.dbQueries) { + return []; + } + return result.dbQueries.map((op) => { + return { + ...op, + stats: { + ...op.stats, + totalTimeMs: + (Number(op.stats.kernelMs) + Number(op.stats.userspaceMs)) / + result.slowdownFactor, + }, + }; + }); + } + + public get dbStatsSummary(): PerformanceTtfbSummaryMetric { + const result = this.data.result as PerformanceTtfbAnalysisStraceData; + return new PerformanceTtfbSummaryMetric( + { + userspaceMs: result.dbStats.userspaceMs, + slowdownFactor: result.slowdownFactor, + kernelMs: result.dbStats.kernelMs, + }, + 750, + 250, + ); + } + + public get fileOps(): EnrichedFileOps { + const result = this.data.result as PerformanceTtfbAnalysisStraceData; + if (!result.fileOps) { + return []; + } + return result.fileOps.map((op) => { + return { + ...op, + stats: { + ...op.stats, + totalTimeMs: + (Number(op.stats.kernelMs) + Number(op.stats.userspaceMs)) / + result.slowdownFactor, + }, + }; + }); + } + + public get fileStatsSummary(): PerformanceTtfbSummaryMetric { + const result = this.data.result as PerformanceTtfbAnalysisStraceData; + return new PerformanceTtfbSummaryMetric( + { + userspaceMs: result.fileOpsStats.userspaceMs, + kernelMs: result.fileOpsStats.kernelMs, + slowdownFactor: result.slowdownFactor, + }, + 2000, + 1200, + ); + } + + public get miscStatsSummary(): PerformanceTtfbSummaryMetric { + const result = this.data.result as PerformanceTtfbAnalysisStraceData; + return new PerformanceTtfbSummaryMetric({ + userspaceMs: result.miscStats.userspaceMs, + slowdownFactor: result.slowdownFactor, + kernelMs: result.miscStats.kernelMs, + }); + } + + public get networkingOps(): EnrichedNetworkingOps { + const result = this.data.result as PerformanceTtfbAnalysisStraceData; + if (!result.networkingOps) { + return []; + } + return result.networkingOps.map((op) => { + return { + ...op, + stats: { + ...op.stats, + totalTimeMs: + (Number(op.stats.kernelMs) + Number(op.stats.userspaceMs)) / + result.slowdownFactor, + }, + }; + }); + } + + public get networkStatsSummary(): PerformanceTtfbSummaryMetric { + const result = this.data.result as PerformanceTtfbAnalysisStraceData; + return new PerformanceTtfbSummaryMetric( + { + userspaceMs: result.networkingStats.userspaceMs, + kernelMs: result.networkingStats.kernelMs, + slowdownFactor: result.slowdownFactor, + }, + 100, + 25, + ); + } + + public constructor(data: PerformanceTtfbAnalysisData) { + super(data); + this.executedAt = DateTime.fromISO(data.executedAt); + if ("result" in data && data.result && "ttfbMs" in data.result) { + this.totalDuration = Math.round( + data.result.ttfbMs / data.result.slowdownFactor, + ); + this.actualUrl = data.result.actualUrl; + } else { + this.totalDuration = 0; + this.actualUrl = ""; + } + } +} + +export class PerformanceTtfbSummaryMetric { + public readonly classification: string; + public readonly rating: 0 | 1 | 2 | 3 | 4 | 5; + public readonly value: number; + + public constructor( + data: PerformanceTtfbSummaryMetricData, + errorThreshold?: number, + warningThreshold?: number, + ) { + this.value = Math.round( + (data.kernelMs + data.userspaceMs) / data.slowdownFactor, + ); + + if (!errorThreshold || !warningThreshold) { + this.rating = 3; + this.classification = "detail.ttfb.stats.classification.mid"; + return; + } + + if (this.value >= errorThreshold) { + this.rating = 1; + this.classification = "detail.ttfb.stats.classification.high"; + } else if (this.value >= warningThreshold) { + this.rating = 2; + this.classification = "detail.ttfb.stats.classification.high"; + } else if (this.value > warningThreshold * 0.5) { + this.rating = 3; + this.classification = "detail.ttfb.stats.classification.mid"; + } else if (this.value > warningThreshold * 0.25) { + this.rating = 4; + this.classification = "detail.ttfb.stats.classification.low"; + } else { + this.rating = 5; + this.classification = "detail.ttfb.stats.classification.low"; + } + } +} + +@GhostMakerModel({ + name: "PerformanceTtfbAnalysis", +}) +export class PerformanceTtfbAnalysis extends ReferenceModel { + public readonly projectId: string; + public readonly ttfbAnalysisId: string; + + public constructor(projectId: string, ttfbAnalysisId: string) { + super(`${projectId}/${ttfbAnalysisId}`); + this.projectId = projectId; + this.ttfbAnalysisId = ttfbAnalysisId; + } + + public static async find( + projectId: string, + ttfbAnalysisId: string, + requestConfig?: AxiosRequestConfig, + ): Promise { + const data = await config.behaviors.performanceTtfbAnalysis.find( + projectId, + ttfbAnalysisId, + requestConfig, + ); + + if (data) { + return new PerformanceTtfbAnalysisDetailed(data); + } + } + + public static ofId( + projectId: string, + ttfbAnalysisId: string, + ): PerformanceTtfbAnalysis { + return new PerformanceTtfbAnalysis(projectId, ttfbAnalysisId); + } + + public static async trigger(projectId: string, url: string) { + return config.behaviors.performanceTtfbAnalysis.trigger(projectId, url); + } + + public async findDetailed( + requestConfig?: AxiosRequestConfig, + ): Promise { + return PerformanceTtfbAnalysis.find( + this.projectId, + this.ttfbAnalysisId, + requestConfig, + ); + } +} diff --git a/packages/models/src/performance/PerformanceTtfbAnalysis/behaviors/api.ts b/packages/models/src/performance/PerformanceTtfbAnalysis/behaviors/api.ts new file mode 100644 index 00000000..4420f24b --- /dev/null +++ b/packages/models/src/performance/PerformanceTtfbAnalysis/behaviors/api.ts @@ -0,0 +1,43 @@ +import { type MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { PerformanceTtfbAnalysisBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { anyStatus404 } from "../../../base/api/typeFixes.js"; +import { withAxiosRequestConfig } from "../../../base/index.js"; + +export const apiPerformanceTtfbAnalysisBehaviors = ( + client: MittwaldAPIV2Client, +): PerformanceTtfbAnalysisBehaviors => ({ + find: async (projectId, ttfbAnalysisId, requestConfig) => { + const response = await client.pageInsights.pageinsightsGetStraceData( + { + straceId: ttfbAnalysisId, + projectId, + }, + withAxiosRequestConfig(requestConfig), + ); + + if (response.status === 200) { + if ("errorMessage" in response.data.result) { + throw new Error(response.data.result.errorMessage); + } + return response.data; + } + + // API-DRIFT: pageinsightsGetStraceData omits 404 in its generated response type, so anyStatus404 (404 as any) is passed (resolve: use the literal 404 once the client type declares it) + validateResponse(response, [403, anyStatus404]); + }, + + trigger: async (projectId, url) => { + const response = await client.pageInsights.pageinsightsScheduleStrace({ + data: { + url: url, + }, + projectId: projectId, + }); + + validateResponse(response, 202); + return response.data; + }, +}); diff --git a/packages/models/src/performance/PerformanceTtfbAnalysis/behaviors/index.ts b/packages/models/src/performance/PerformanceTtfbAnalysis/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/performance/PerformanceTtfbAnalysis/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/performance/PerformanceTtfbAnalysis/behaviors/types.ts b/packages/models/src/performance/PerformanceTtfbAnalysis/behaviors/types.ts new file mode 100644 index 00000000..379ae823 --- /dev/null +++ b/packages/models/src/performance/PerformanceTtfbAnalysis/behaviors/types.ts @@ -0,0 +1,18 @@ +import type { AxiosRequestConfig } from "axios"; + +import type { + SchedulePerformanceTtfbAnalysisData, + PerformanceTtfbAnalysisData, +} from "../types.js"; + +export interface PerformanceTtfbAnalysisBehaviors { + find: ( + projectId: string, + ttfbAnalysisId: string, + requestConfig?: AxiosRequestConfig, + ) => Promise; + trigger: ( + projectId: string, + url: string, + ) => Promise; +} diff --git a/packages/models/src/performance/PerformanceTtfbAnalysis/index.ts b/packages/models/src/performance/PerformanceTtfbAnalysis/index.ts new file mode 100644 index 00000000..4f1a5f36 --- /dev/null +++ b/packages/models/src/performance/PerformanceTtfbAnalysis/index.ts @@ -0,0 +1,2 @@ +export * from "./PerformanceTtfbAnalysis.js"; +export * from "./types.js"; diff --git a/packages/models/src/performance/PerformanceTtfbAnalysis/types.ts b/packages/models/src/performance/PerformanceTtfbAnalysis/types.ts new file mode 100644 index 00000000..82301cd6 --- /dev/null +++ b/packages/models/src/performance/PerformanceTtfbAnalysis/types.ts @@ -0,0 +1,58 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type PerformanceTtfbAnalysisScheduleData = + MittwaldAPIV2.Operations.PageinsightsScheduleStrace.ResponseData; + +export type PerformanceTtfbAnalysisData = + MittwaldAPIV2.Operations.PageinsightsGetStraceData.ResponseData; + +export type SchedulePerformanceTtfbAnalysisData = + MittwaldAPIV2.Operations.PageinsightsScheduleStrace.ResponseData<202>; + +export type PerformanceTtfbAnalysisStraceData = + MittwaldAPIV2.Components.Schemas.StraceData; + +export type PerformanceTtfbAnalysisStraceDataFileOps = + MittwaldAPIV2.Components.Schemas.StraceData["fileOps"]; + +export type PerformanceTtfbAnalysisStraceDataDatabaseQueries = + MittwaldAPIV2.Components.Schemas.StraceData["dbQueries"]; + +export type PerformanceTtfbAnalysisStraceDataNetworkOps = + MittwaldAPIV2.Components.Schemas.StraceData["networkingOps"]; + +export interface WithTtfb { + totalTimeMs: number; +} + +export interface PerformanceTtfbSummaryMetricData { + slowdownFactor: number; + userspaceMs: number; + kernelMs: number; +} + +export type PerformanceTtfbAnalysisStraceDataFileOpStats = + NonNullable[number]["stats"] & + WithTtfb; +export type PerformanceTtfbAnalysisStraceDataDbQueryStats = + NonNullable[number]["stats"] & + WithTtfb; +export type PerformanceTtfbAnalysisStraceDataNetworkingOpStats = + NonNullable[number]["stats"] & + WithTtfb; + +export type EnrichedFileOp = { + stats: PerformanceTtfbAnalysisStraceDataFileOpStats; +} & NonNullable[number]; +export type EnrichedFileOps = EnrichedFileOp[]; + +export type EnrichedDbQuery = + NonNullable[number] & { + stats: PerformanceTtfbAnalysisStraceDataDbQueryStats; + }; +export type EnrichedDbQueries = EnrichedDbQuery[]; + +export type EnrichedNetworkingOp = { + stats: PerformanceTtfbAnalysisStraceDataNetworkingOpStats; +} & NonNullable[number]; +export type EnrichedNetworkingOps = EnrichedNetworkingOp[]; diff --git a/packages/models/src/performance/index.ts b/packages/models/src/performance/index.ts new file mode 100644 index 00000000..81beb9cb --- /dev/null +++ b/packages/models/src/performance/index.ts @@ -0,0 +1,2 @@ +export * from "./Performance/index.js"; +export * from "./PerformanceTtfbAnalysis/index.js"; diff --git a/packages/models/src/project/Project/HardwareSpecs.ts b/packages/models/src/project/Project/HardwareSpecs.ts new file mode 100644 index 00000000..b6fdde5b --- /dev/null +++ b/packages/models/src/project/Project/HardwareSpecs.ts @@ -0,0 +1,97 @@ +import { z } from "zod"; + +import { getRecommendedStorage } from "../../order/Order/lib.js"; +import { + CpuArticleAttribute, + RamArticleAttribute, + type ArticleCommon, +} from "../../article/Article/internal.js"; +import { Bytes } from "../../common/index.js"; + +export const hardwareSpecsSchema = z.object({ + ramBytes: z.number().int(), + vcpu: z.number().int(), +}); + +export class HardwareSpecs { + public readonly ram: Bytes; + public readonly vcpu: number; + + public constructor(vcpu: number, ram: Bytes) { + this.vcpu = vcpu; + this.ram = ram; + } + + public static fromArticle(article: ArticleCommon) { + const ramAttribute = article.getRequiredAttribute(RamArticleAttribute); + const cpuAttribute = article.getRequiredAttribute(CpuArticleAttribute); + return new HardwareSpecs(cpuAttribute.cpuCount, ramAttribute.bytes); + } + + public static fromJson(json: string): HardwareSpecs { + const data = hardwareSpecsSchema.parse(JSON.parse(json)); + return new HardwareSpecs(data.vcpu, Bytes.of(data.ramBytes, "bytes")); + } + + public asJson(): z.infer { + return { + ramBytes: this.ram.in("bytes"), + vcpu: this.vcpu, + }; + } + + public asJsonString(): string { + return JSON.stringify(this.asJson()); + } + + public equals(specs: HardwareSpecs) { + return this.vcpu === specs.vcpu && this.ram.equals(specs.ram); + } + + public getRecommendedProjectCount() { + const recommendation = recommendations.find((r) => { + return r.cpu === this.vcpu && r.ram === this.ram.gib; + }); + return recommendation ? recommendation.projects : 0; + } + + public getRecommendedStorage(): string | undefined { + const hardwareSpecs = JSON.stringify({ + ram: this.ram.gib, + vcpu: this.vcpu, + }); + + return getRecommendedStorage(hardwareSpecs); + } + + public isDifferent(specs: HardwareSpecs) { + return !this.equals(specs); + } +} + +const recommendations: { + projects: number; + cpu: number; + ram: number; +}[] = [ + { + projects: 1, + cpu: 2, + ram: 2, + }, + { + projects: 2, + cpu: 4, + ram: 4, + }, + { + projects: 3, + cpu: 8, + ram: 8, + }, + { + projects: 5, + cpu: 16, + ram: 16, + }, +]; diff --git a/packages/models/src/project/Project/MachineTypeOptimization.ts b/packages/models/src/project/Project/MachineTypeOptimization.ts new file mode 100644 index 00000000..a5302b7d --- /dev/null +++ b/packages/models/src/project/Project/MachineTypeOptimization.ts @@ -0,0 +1,31 @@ +import type { ArticleDetailed } from "../../article/index.js"; + +import { ArticleTagName } from "../../article/Article/internal.js"; + +export const machineTypeOptimizationType = [ + ArticleTagName.ramOptimized, + ArticleTagName.cpuOptimized, + ArticleTagName.balancedOptimized, +] as const; + +export type MachineTypeOptimizationType = + (typeof machineTypeOptimizationType)[number]; + +export class MachineTypeOptimization { + public readonly type: MachineTypeOptimizationType; + + public constructor(type: MachineTypeOptimizationType) { + this.type = type; + } + + public static fromArticle(article: ArticleDetailed) { + if (article.hasTag(ArticleTagName.ramOptimized)) { + return new MachineTypeOptimization(ArticleTagName.ramOptimized); + } else if (article.hasTag(ArticleTagName.cpuOptimized)) { + return new MachineTypeOptimization(ArticleTagName.cpuOptimized); + } else if (article.hasTag(ArticleTagName.balancedOptimized)) { + return new MachineTypeOptimization(ArticleTagName.balancedOptimized); + } + throw new Error("Unknown machine type optimization for article"); + } +} diff --git a/packages/models/src/project/Project/MachineTypeSpecs.ts b/packages/models/src/project/Project/MachineTypeSpecs.ts new file mode 100644 index 00000000..00058785 --- /dev/null +++ b/packages/models/src/project/Project/MachineTypeSpecs.ts @@ -0,0 +1,83 @@ +import { z } from "zod"; + +import type { ArticleCommon } from "../../article/Article/internal.js"; + +import { hardwareSpecsSchema, HardwareSpecs } from "../internal.js"; +import { getRecommendedStorage } from "../../order/Order/lib.js"; +import { + MachineTypeArticleAttribute, + ArticleTagName, +} from "../../article/Article/internal.js"; +import { Bytes } from "../../common/index.js"; + +export const machineTypeSpecsSchema = z.object({ + hardwareSpecs: hardwareSpecsSchema, + isDedicated: z.boolean(), + machineType: z.string(), +}); + +export class MachineTypeSpecs { + public readonly hardwareSpecs: HardwareSpecs; + public readonly isDedicated: boolean; + public readonly machineType: string; + + public constructor( + machineType: string, + hardwareSpecs: HardwareSpecs, + isDedicated: boolean, + ) { + this.machineType = machineType; + this.hardwareSpecs = hardwareSpecs; + this.isDedicated = isDedicated; + } + + public static fromArticle(article: ArticleCommon) { + const machineTypeAttribute = article.getRequiredAttribute( + MachineTypeArticleAttribute, + ); + + const isDedicated = article.hasTag(ArticleTagName.dedicated); + + return new MachineTypeSpecs( + machineTypeAttribute.machineType, + HardwareSpecs.fromArticle(article), + isDedicated, + ); + } + + public static fromJson(json: string): MachineTypeSpecs { + const parsedJson = JSON.parse(json); + + const { hardwareSpecs, machineType, isDedicated } = + machineTypeSpecsSchema.parse(parsedJson); + + return new MachineTypeSpecs( + machineType, + new HardwareSpecs( + hardwareSpecs.vcpu, + Bytes.of(hardwareSpecs.ramBytes, "GiB"), + ), + isDedicated, + ); + } + + public asJson(): z.infer { + return { + hardwareSpecs: this.hardwareSpecs.asJson(), + machineType: this.machineType, + isDedicated: this.isDedicated, + }; + } + + public asJsonString() { + return JSON.stringify(this.asJson()); + } + + public equals(specs: MachineTypeSpecs) { + return this.machineType === specs.machineType; + } + + public getRecommendedStorage(): string | undefined { + return getRecommendedStorage(this.machineType); + } +} diff --git a/packages/models/src/project/Project/Project.test.ts b/packages/models/src/project/Project/Project.test.ts new file mode 100644 index 00000000..ad93a642 --- /dev/null +++ b/packages/models/src/project/Project/Project.test.ts @@ -0,0 +1,272 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; +import { DateTime } from "luxon"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { buildProjectListItemData } from "../../testing/builders/buildProjectListItemData.js"; +import { buildProjectData } from "../../testing/builders/buildProjectData.js"; +import { installBehaviors, resetBehaviors } from "../../testing/index.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { DnsZone } from "../../dns/index.js"; +import { + ProjectDetailed, + ProjectListItem, + ProjectList, + Project, +} from "../internal.js"; + +afterEach(resetBehaviors); + +describe("Project references and delegation", () => { + test("find delegates and materializes a detailed project", async () => { + const find = vi.fn().mockResolvedValue(buildProjectData({ id: "p-1" })); + installBehaviors({ project: { find } }); + + const result = await Project.find("p-1"); + + expect(find).toHaveBeenCalledWith("p-1", undefined); + expect(result).toBeInstanceOf(ProjectDetailed); + expect(result?.id).toBe("p-1"); + }); + + test("find maps a missing project to undefined", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ project: { find } }); + + await expect(Project.find("missing")).resolves.toBeUndefined(); + }); + + test("get returns a detailed project", async () => { + const find = vi.fn().mockResolvedValue(buildProjectData({ id: "p-2" })); + installBehaviors({ project: { find } }); + + const result = await Project.get("p-2"); + + expect(result).toBeInstanceOf(ProjectDetailed); + expect(result.id).toBe("p-2"); + }); + + test("get throws when the project is missing", async () => { + installBehaviors({ + project: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(Project.get("x")).rejects.toThrow(); + }); + + test("create delegates and returns a project reference", async () => { + const create = vi.fn().mockResolvedValue({ id: "p-created" }); + installBehaviors({ project: { create } }); + + const result = await Project.create({ + description: "created project", + serverId: "s-1", + }); + + expect(create).toHaveBeenCalledWith("s-1", "created project"); + expect(result).toBeInstanceOf(Project); + expect(result.id).toBe("p-created"); + }); + + test("createDnsZone delegates with the project id and returns a zone reference", async () => { + const create = vi.fn().mockResolvedValue({ id: "z-created" }); + installBehaviors({ dnsZone: { create } }); + + const result = await Project.ofId("p-1").createDnsZone("example.com"); + + expect(create).toHaveBeenCalledWith("p-1", "example.com"); + expect(result).toBeInstanceOf(DnsZone); + expect(result.id).toBe("z-created"); + }); + + test("updateDescription and delete delegate with the project id", async () => { + const updateDescription = vi.fn().mockResolvedValue(undefined); + const deleteProject = vi.fn().mockResolvedValue(undefined); + installBehaviors({ + project: { delete: deleteProject, updateDescription }, + }); + const project = Project.ofId("p-1"); + + await project.updateDescription("new description"); + await project.delete(); + + expect(updateDescription).toHaveBeenCalledWith("p-1", "new description"); + expect(deleteProject).toHaveBeenCalledWith("p-1"); + }); +}); + +describe("Project common resolution and idempotency", () => { + test("findCommon delegates from a reference and returns the common variant", async () => { + const find = vi.fn().mockResolvedValue(buildProjectData({ id: "p-1" })); + installBehaviors({ project: { find } }); + + const result = await Project.ofId("p-1").findCommon(); + + expect(find).toHaveBeenCalledWith("p-1", undefined); + expect(result).toBeInstanceOf(ProjectDetailed); + expect(result?.id).toBe("p-1"); + }); + + test("findCommon maps a missing reference to undefined", async () => { + installBehaviors({ + project: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(Project.ofId("missing").findCommon()).resolves.toBeUndefined(); + }); + + test("getCommon resolves the common variant and throws when missing", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildProjectData({ id: "p-2" })) + .mockResolvedValueOnce(undefined); + installBehaviors({ project: { find } }); + + await expect(Project.ofId("p-2").getCommon()).resolves.toBeInstanceOf( + ProjectDetailed, + ); + await expect(Project.ofId("missing").getCommon()).rejects.toThrow(); + }); + + test("findCommon and getCommon are idempotent on a materialized project", async () => { + const find = vi.fn(); + installBehaviors({ project: { find } }); + const item = new ProjectListItem(buildProjectListItemData({ id: "p-1" })); + + expect(await item.findCommon()).toBe(item); + expect(await item.getCommon()).toBe(item); + expect(find).not.toHaveBeenCalled(); + }); +}); + +describe("Project aggregate metadata", () => { + test("aggregateMetaData pins the cache identity", () => { + expect(Project.aggregateMetaData).toBeInstanceOf(AggregateMetaData); + expect(Project.aggregateMetaData.domain).toBe("project"); + expect(Project.aggregateMetaData.aggregate).toBe("project"); + }); + + test("findAggregate combines an id with the aggregate identity", () => { + expect(Project.findAggregate()).toBeUndefined(); + expect(Project.findAggregate("p-1")).toEqual({ + aggregate: "project", + domain: "project", + id: "p-1", + }); + }); +}); + +describe("Project data", () => { + test("derives ProSpace Lite state and omits a server reference", () => { + const project = new ProjectListItem( + buildProjectListItemData({ + projectHostingId: "hosting-id", + serverId: undefined, + }), + ); + + expect(project.isProSpaceLite).toBe(true); + expect(project.server).toBeUndefined(); + expect(new ProjectListItem(buildProjectListItemData()).isProSpaceLite).toBe( + false, + ); + }); + + test("derives disabled, suspended, and ordering state", () => { + const suspended = new ProjectListItem( + buildProjectListItemData({ disableReason: "suspended" }), + ); + const active = new ProjectListItem(buildProjectListItemData()); + + expect(suspended.isDisabled).toBe(true); + expect(suspended.isSuspended).toBe(true); + expect(suspended.isAllowedToPlaceOrders).toBe(false); + expect(active.isDisabled).toBe(false); + expect(active.isSuspended).toBe(false); + expect(active.isAllowedToPlaceOrders).toBe(true); + }); + + test("exposes container access and a parsed creation date", () => { + const project = new ProjectListItem( + buildProjectListItemData({ supportedFeatures: ["container"] }), + ); + + expect(project.hasContainerAccess).toBe(true); + expect(project.createdAt).toBeInstanceOf(DateTime); + expect(project.createdAt.isValid).toBe(true); + }); + + test("omits optional derived values when the source data is absent", () => { + const project = new ProjectListItem( + buildProjectListItemData({ supportedFeatures: undefined }), + ); + + expect(project.avatar).toBeUndefined(); + expect(project.disabledAt).toBeUndefined(); + expect(project.disabledReason).toBeUndefined(); + expect(project.features).toBeUndefined(); + expect(project.hasContainerAccess).toBeUndefined(); + }); + + test("derives the hostname and base directories for detailed projects", () => { + const project = new ProjectDetailed( + buildProjectData({ + directories: { + Logs: "/home/custom/logs", + Web: "/home/custom/html", + Home: "/home/custom", + }, + clusterDomain: "example.test", + clusterID: "cluster-2", + }), + ); + + expect(project.hostname).toBe("ssh.cluster-2.example.test"); + expect(project.getBaseDirectory("Home")).toBe("/home/custom"); + expect(project.getBaseDirectory()).toBe(""); + }); +}); + +describe("Project list query", () => { + test("materializes the behavior result", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildProjectListItemData({ id: "p-1" })], + totalCount: 1, + }); + installBehaviors({ project: { list } }); + + const result = await Project.query().execute(); + + expect(result).toBeInstanceOf(ProjectList); + expect(result.items[0]).toBeInstanceOf(ProjectListItem); + expect(result.items[0].id).toBe("p-1"); + expect(result.totalCount).toBe(1); + expect(list).toHaveBeenCalledTimes(1); + }); + + test("passes through an explicit limit", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 0, items: [] }); + installBehaviors({ project: { list } }); + + await Project.query({ limit: 5 }).execute(); + + expect(list).toHaveBeenCalledWith(expect.objectContaining({ limit: 5 })); + }); + + test("refine merges query values", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 0, items: [] }); + installBehaviors({ project: { list } }); + + await Project.query({ limit: 5, page: 2 }).refine({ limit: 10 }).execute(); + + expect(list).toHaveBeenCalledWith( + expect.objectContaining({ limit: 10, page: 2 }), + ); + }); +}); diff --git a/packages/models/src/project/Project/Project.ts b/packages/models/src/project/Project/Project.ts index ec78407c..e74eabe2 100644 --- a/packages/models/src/project/Project/Project.ts +++ b/packages/models/src/project/Project/Project.ts @@ -1,148 +1,552 @@ -import { - ProjectData, - ProjectListItemData, - ProjectListQueryData, +import type { AxiosRequestConfig } from "axios"; + +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; + +import type { + CronjobCreateRequestData, + CronjobListQuery, +} from "../../cronjob/index.js"; +import type { ProjectMembershipListQuery } from "../ProjectMembership/index.js"; +import type { ExtensionInstanceListQuery } from "../../marketplace/index.js"; +import type { ProjectPermission } from "../projectPermissions.js"; +import type { CertificateListQuery } from "../../certificate/index.js"; +import type { PerformanceListQuery } from "../../performance/index.js"; +import type { IngressListQuery } from "../../ingress/index.js"; +import type { DomainListQuery } from "../../domain/index.js"; +import type { DnsZoneListQuery } from "../../dns/index.js"; +import type { OrderListQuery } from "../../order/index.js"; +import type { + ProjectInviteCreateRequestData, + ProjectInviteListQuery, +} from "../ProjectInvite/index.js"; +import type { + ContainerStackPatchRequestData, + RegistryCreateRequestData, + ContainerStackListQuery, + ContainerListQuery, + RegistryListQuery, + RegistryLoginType, + VolumeListQuery, +} from "../../container/index.js"; +import type { + RedisCreateRequestData, + MySqlCreateRequest, + MySqlListQuery, + RedisListQuery, +} from "../../database/index.js"; +import type { + SftpUserCreateRequestData, + SshUserCreateRequestData, + SftpUserListQuery, + SshUserListQuery, +} from "../../access/index.js"; +import type { + BackupScheduleCreateRequestData, + BackupCreateRequestData, + BackupScheduleListQuery, + BackupListQuery, +} from "../../backup/index.js"; +import type { + MailAddressRequestData, + DeliveryBoxListQuery, + MailAddressListQuery, + ForwardRequestData, +} from "../../mail/index.js"; +import type { + AppInstallationCreateRequestData, + AppInstallationListQuery, + LicenseListQuery, +} from "../../app/index.js"; +import type { + ProjectAIModelListQuery, + ProjectAIPlanListQuery, +} from "../../ai/index.js"; +import type { ProjectListQueryModelData, + ProjectDisableReason, + ProjectListItemData, + ProjectFeature, + ProjectStatus, + ProjectData, } from "./types.js"; -import { config } from "../../config/config.js"; -import { classes } from "polytype"; -import { DataModel } from "../../base/DataModel.js"; -import assertObjectFound from "../../base/assertObjectFound.js"; -import { Server } from "../../server/index.js"; + +import { ExtensionInstance } from "../../marketplace/ExtensionInstance/ExtensionInstance.js"; +import { ProjectAvatarAccessTokenProvider } from "./ProjectAvatarAccessTokenProvider.js"; +import { AppInstallation } from "../../app/AppInstallation/AppInstallation.js"; +import { BackupSchedule } from "../../backup/BackupSchedule/BackupSchedule.js"; +import { ContainerStack } from "../../container/Container/ContainerStack.js"; +import { ProjectAIModel } from "../../ai/ProjectAIModel/ProjectAIModel.js"; +import { Certificate } from "../../certificate/Certificate/Certificate.js"; import { - AsyncResourceVariant, - provideReact, -} from "../../react/provideReact.js"; + type FileAccessTokenProvider, + type DomFile, +} from "../../file/index.js"; +import { Performance } from "../../performance/Performance/Performance.js"; +import { ProjectUsageMetrics, StorageMetrics } from "../../monitoring/index.js"; +import { ProjectAIPlan } from "../../ai/ProjectAIPlan/ProjectAIPlan.js"; +import { MailSettings } from "../../mail/MailSettings/MailSettings.js"; +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { DeliveryBox } from "../../mail/DeliveryBox/DeliveryBox.js"; +import { MailAddress } from "../../mail/MailAddress/MailAddress.js"; +import { Container } from "../../container/Container/Container.js"; +import { HostingContractItem, Contract } from "../../contract/index.js"; +import { Registry } from "../../container/Registry/Registry.js"; import { Customer } from "../../customer/Customer/Customer.js"; -import { ReferenceModel } from "../../base/ReferenceModel.js"; +import { projectPermissions } from "../projectPermissions.js"; +import { SftpUser } from "../../access/SftpUser/SftpUser.js"; +import { ProjectMembership } from "../ProjectMembership/index.js"; +import { Cronjob } from "../../cronjob/Cronjob/Cronjob.js"; +import { Ingress } from "../../ingress/Ingress/Ingress.js"; +import { SshUser } from "../../access/SshUser/SshUser.js"; +import { CertificateRequest } from "../../certificate/index.js"; +import { Volume } from "../../container/Volume/Volume.js"; +import { License } from "../../app/License/License.js"; +import { Backup } from "../../backup/Backup/Backup.js"; +import { DnsZone } from "../../dns/DnsZone/DnsZone.js"; +import { Domain } from "../../domain/Domain/Domain.js"; +import { Server } from "../../server/Server/Server.js"; +import { MySql } from "../../database/MySql/MySql.js"; +import { Redis } from "../../database/Redis/Redis.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { ProjectInvite } from "../ProjectInvite/index.js"; +import { Order } from "../../order/Order/Order.js"; +import { File } from "../../file/File/internal.js"; +import { HardwareSpecs } from "../internal.js"; import { - Ingress, - IngressListItem, - IngressListQuery, -} from "../../domain/index.js"; -import { ListQueryModel } from "../../base/ListQueryModel.js"; -import { ListDataModel } from "../../base/ListDataModel.js"; -import { AppInstallationListQuery } from "../../app/index.js"; + CpuArticleAttribute, + RamArticleAttribute, +} from "../../article/Article/internal.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; +@GhostMakerModel({ + name: "Project", +}) export class Project extends ReferenceModel { - public readonly ingresses: IngressListQuery; + public static aggregateMetaData = new AggregateMetaData("project", "project"); + public readonly aiModelsQuery: ProjectAIModelListQuery; + + public readonly aiPlans: ProjectAIPlanListQuery; + public readonly appInstallations: AppInstallationListQuery; + public readonly backups: BackupListQuery; + public readonly backupSchedules: BackupScheduleListQuery; + + public readonly certificates: CertificateListQuery; + + public readonly containers: ContainerListQuery; + public readonly cronjobs: CronjobListQuery; + + public readonly deliveryBoxes: DeliveryBoxListQuery; + public readonly dnsZones: DnsZoneListQuery; + public readonly domains: DomainListQuery; + public readonly extensionInstances: ExtensionInstanceListQuery; + + public readonly fileAccessTokenProvider: FileAccessTokenProvider; + + public readonly ingresses: IngressListQuery; + + public readonly invites: ProjectInviteListQuery; + + public readonly licenses: LicenseListQuery; + + public readonly mailAddresses: MailAddressListQuery; + + public readonly mailSettings: MailSettings; + + public readonly memberships: ProjectMembershipListQuery; + public readonly mySqlDatabases: MySqlListQuery; + + public readonly orders: OrderListQuery; + + public readonly performanceInsights: PerformanceListQuery; + + public readonly redisDatabases: RedisListQuery; + public readonly registries: RegistryListQuery; + public readonly sftpUsers: SftpUserListQuery; + public readonly sshUsers: SshUserListQuery; + + public readonly stacks: ContainerStackListQuery; + + public readonly volumes: VolumeListQuery; + public constructor(id: string) { super(id); - this.ingresses = new IngressListQuery({ - project: this, + this.fileAccessTokenProvider = new ProjectAvatarAccessTokenProvider(this); + this.dnsZones = DnsZone.query({ project: this }); + this.invites = ProjectInvite.query(this); + this.memberships = ProjectMembership.query(this); + this.deliveryBoxes = DeliveryBox.query({ project: this }); + this.sshUsers = SshUser.query({ project: this }); + this.sftpUsers = SftpUser.query({ project: this }); + this.mySqlDatabases = MySql.query({ project: this }); + this.redisDatabases = Redis.query({ project: this }); + this.backups = Backup.query({ project: this }); + this.backupSchedules = BackupSchedule.query(this); + this.cronjobs = Cronjob.query({ project: this }); + this.performanceInsights = Performance.query(this); + this.containers = Container.query({ project: this }); + this.volumes = Volume.query({ project: this }); + this.registries = Registry.query({ project: this }); + this.licenses = License.query(this); + this.stacks = ContainerStack.query({ project: this }); + this.ingresses = Ingress.query({ + project: id, + }); + this.domains = Domain.query({ + project: id, }); - this.appInstallations = new AppInstallationListQuery(this); + this.appInstallations = AppInstallation.query({ project: id }); + this.mailAddresses = MailAddress.query({ project: id }); + this.certificates = Certificate.query({ project: id }); + this.extensionInstances = ExtensionInstance.query({ project: id }); + this.mailSettings = MailSettings.ofId(this.id); + this.orders = Order.query({ project: id }); + this.aiPlans = ProjectAIPlan.query(this.id); + this.aiModelsQuery = ProjectAIModel.query(this.id); } - public static ofId(id: string): Project { + public static async create(data: { description: string; serverId: string }) { + const { description, serverId } = data; + + const { id } = await config.behaviors.project.create(serverId, description); return new Project(id); } - public static find = provideReact( - async (id: string): Promise => { - const data = await config.behaviors.project.find(id); + public static async find(id: string, options?: AxiosRequestConfig) { + const data = await config.behaviors.project.find(id, options); + if (data) { + return new ProjectDetailed(data); + } + } + public static findAggregate(projectId?: string) { + return projectId + ? { id: projectId, ...Project.aggregateMetaData } + : undefined; + } + + public static async get(id: Project | string, options?: AxiosRequestConfig) { + const project = await Project.find(extractId(id), options); + assertObjectFound(project, Project, id); + return project; + } - if (data !== undefined) { - return new ProjectDetailed(data); - } - }, - ); + public static ofId(id: string) { + return new Project(id); + } - public static get = provideReact( - async (id: string): Promise => { - const project = await this.find(id); - assertObjectFound(project, this, id); - return project; - }, - ); + public static ofReference(ref?: Project | string) { + const id = extractId(ref); + return id ? Project.ofId(id) : undefined; + } public static query(query: ProjectListQueryModelData = {}) { return new ProjectListQuery(query); } - /** @deprecated: use query(), Customer.projects or Server.projects */ - public static list = provideReact( - async ( - query: ProjectListQueryData = {}, - ): Promise>> => { - return new ProjectListQuery(query).execute().then((r) => r.items); - }, - ); + public async createBackup(data: BackupCreateRequestData) { + return Backup.create(this, data); + } - public static async create( - serverId: string, - description: string, - ): Promise { - const { id } = await config.behaviors.project.create(serverId, description); - return new Project(id); + public async createBackupSchedule(data: BackupScheduleCreateRequestData) { + return BackupSchedule.create(this, data); + } + + public async createContainer( + data: ContainerStackPatchRequestData, + stackId: string, + ) { + return Container.create(stackId, data); + } + + public async createCronjob(data: CronjobCreateRequestData) { + return Cronjob.create(this, data); + } + + public async createDeliveryBox(description: string, password: string) { + return DeliveryBox.create(this, description, password); + } + + public async createDnsCertificateRequest(commonName: string) { + return CertificateRequest.createDnsCertificate(this, commonName); + } + + public async createDnsZone(name: string) { + return DnsZone.create(this.id, name); + } + + public async createForward(data: ForwardRequestData) { + return MailAddress.createForward(this, data); + } + + public async createMailAddress(data: MailAddressRequestData) { + return MailAddress.create(this, data); + } + + public async createMySql(data: MySqlCreateRequest) { + return MySql.create(this, data); } - public getDetailed = provideReact( - () => Project.get(this.id), - [this.id], - ) as AsyncResourceVariant<() => Promise>; + public async createRedis(data: RedisCreateRequestData) { + return Redis.create(this, data); + } + + public async createRegistry( + data: RegistryCreateRequestData, + loginType: RegistryLoginType, + ) { + return Registry.create(this, data, loginType); + } + + public async createSftpUser(data: SftpUserCreateRequestData) { + return SftpUser.create(this, data); + } + + public async createSshUser(data: SshUserCreateRequestData) { + return SshUser.create(this, data); + } + + public async createVolume(name: string, stackId: string) { + return Volume.create(name, stackId); + } - public findDetailed = provideReact( - () => Project.find(this.id), - [this.id], - ) as AsyncResourceVariant<() => Promise>; + public async delete() { + await config.behaviors.project.delete(this.id); + } + + public findCommon(): Promise | ProjectCommon { + return this instanceof ProjectCommon ? this : this.findDetailed(); + } + + public async findContract(requestConfig?: AxiosRequestConfig) { + return await Contract.findByProject(this.id, requestConfig); + } - /** @deprecated: use ingresses property */ - public listIngresses = provideReact(() => - Ingress.list({ projectId: this.id }), - ); + public async findDefaultIngress() { + const ingresses = await this.ingresses.execute(); + return ingresses.items.find((i) => i.data.isDefault); + } - public getDefaultIngress = provideReact(async () => { - const ingresses = await Project.ofId(this.id).listIngresses(); - const defaultIngress = ingresses.find((i) => i.data.isDefault); - assertObjectFound(defaultIngress, IngressListItem, this); + public async findDetailed(): Promise { + return Project.find(this.id); + } + + public async findOpenExtensionOrders() { + return await ExtensionInstance.listOpenOrders(this); + } + + public async findStorageMetrics() { + return await StorageMetrics.find(this.id, "project"); + } + + public async getAvatarUploadRules() { + return File.getUploadRules("avatar"); + } + + public getCommon( + options?: AxiosRequestConfig, + ): Promise | ProjectCommon { + return this instanceof ProjectCommon ? this : this.getDetailed(options); + } + + public async getContract() { + return await Contract.getByProject(this.id); + } + + public async getContractArticle() { + const contract = await this.getContract(); + return contract.baseItem.baseArticle; + } + + public async getDefaultIngress() { + const defaultIngress = await this.findDefaultIngress(); + assertObjectFound(defaultIngress, Ingress, this); return defaultIngress; - }); + } + + public async getDetailed( + options?: AxiosRequestConfig, + ): Promise { + return Project.get(this.id, options); + } + + public async getHardwareSpecs() { + const article = await this.getContractArticle().then((a) => + a!.article.getDetailed(), + ); + + const vcpuAttribute = article.getAttribute(CpuArticleAttribute); + const ramAttribute = article.getAttribute(RamArticleAttribute); + + if (vcpuAttribute && ramAttribute) { + return new HardwareSpecs(vcpuAttribute.cpuCount, ramAttribute.bytes); + } + } - public async updateDescription(description: string): Promise { + public async getOwnMembership() { + return await ProjectMembership.getOwn(this); + } + + public async getStorage() { + const contract = await this.getContract(); + const hostingContractItem = HostingContractItem.fromContractItem( + contract.baseItem, + ); + return hostingContractItem.getStorage(); + } + + public async installApp(data: AppInstallationCreateRequestData) { + return AppInstallation.create(this, data); + } + + public async inviteMember(data: ProjectInviteCreateRequestData) { + return ProjectInvite.create(this, data); + } + + public async removeAvatar() { + await config.behaviors.project.removeAvatar(this.id); + } + + public async requestAvatarUpload(): Promise { + const response = await config.behaviors.project.createAvatarUploadToken( + this.id, + ); + + return response.token; + } + + public async updateDescription(description: string) { await config.behaviors.project.updateDescription(this.id, description); } - public async leave(): Promise { - await config.behaviors.project.leave(this.id); + public async updateStorageNotificationThreshold(threshold?: number) { + await config.behaviors.project.updateStorageNotificationThreshold( + this.id, + threshold, + ); } - public async delete(): Promise { - await config.behaviors.project.delete(this.id); + public async uploadAvatar(file: DomFile) { + await File.upload(file, this.fileAccessTokenProvider); } } -class ProjectCommon extends classes( - DataModel, - Project, -) { - public readonly server: Server | undefined; +export class ProjectCommon extends WithData< + ProjectListItemData | ProjectData +>()(Project) { + public readonly avatar?: File; + public readonly createdAt: DateTime; public readonly customer: Customer; + public override readonly data: ProjectListItemData | ProjectData; + public readonly description: string; + public readonly disabledAt?: DateTime; + public readonly disabledReason?: ProjectDisableReason; + public readonly enabled: boolean; + public readonly features?: ProjectFeature[]; + public readonly hasContainerAccess?: boolean; + public readonly isAllowedToPlaceOrders: boolean; + public readonly isDisabled: boolean; + public readonly isProSpaceLite: boolean; + public readonly isSuspended: boolean; + public readonly server?: Server; + public readonly shortId: string; + public readonly status: ProjectStatus; public constructor(data: ProjectListItemData | ProjectData) { - super([data], [data.id]); - this.server = data.serverId ? Server.ofId(data.serverId) : undefined; + super(data.id); + this.data = data; + this.server = + !data.projectHostingId && data.serverId + ? Server.ofId(data.serverId) + : undefined; this.customer = Customer.ofId(data.customerId); + this.shortId = data.shortId; + this.description = data.description; + if (data.disabledAt) { + this.disabledAt = DateTime.fromISO(data.disabledAt); + } + this.createdAt = DateTime.fromISO(data.createdAt); + this.avatar = data.imageRefId ? File.ofId(data.imageRefId) : undefined; + this.isProSpaceLite = !!data.projectHostingId && !data.serverId; + this.enabled = data.enabled; + this.features = data.supportedFeatures; + this.status = data.status; + this.isDisabled = !!data.disableReason; + this.isSuspended = data.disableReason === "suspended"; + this.disabledReason = data.disableReason; + this.isAllowedToPlaceOrders = !this.isSuspended; + if (this.features) { + this.hasContainerAccess = this.features.includes("container"); + } + } + + public async hasPermission(permission: ProjectPermission) { + const ownMembership = await this.getOwnMembership(); + + const inheritedRequired = + projectPermissions[permission].includes("inheritedOwner"); + + if (inheritedRequired) { + return ownMembership.inherited; + } + + return projectPermissions[permission].includes(ownMembership.role); } } -export class ProjectDetailed extends classes( - ProjectCommon, - DataModel, -) { +export class ProjectDetailed extends ProjectCommon { + public override readonly data: ProjectData; + public readonly hostname: string; + public readonly serverGroupId?: string; + public readonly serverShortId?: string; + public readonly usageMetrics: ProjectUsageMetrics; + public constructor(data: ProjectData) { - super([data], [data]); + super(data); + this.data = data; + this.hostname = `ssh.${data.clusterID}.${data.clusterDomain}`; + this.serverShortId = data.serverShortId; + this.serverGroupId = data.serverGroupId; + this.usageMetrics = ProjectUsageMetrics.of(this); + } + + public async findFileSystemDirectories( + directory: string, + requestConfig?: AxiosRequestConfig, + ) { + return await config.behaviors.project.findFileSystemDirectories( + this.id, + directory, + requestConfig, + ); + } + + public getBaseDirectory(base?: "Home" | "Logs" | "Web") { + if (!base) { + return ""; + } + + return this.data.directories[base]; + } + + public getMetrics() { + return new ProjectUsageMetrics(this); } } -export class ProjectListItem extends classes( - ProjectCommon, - DataModel, -) { +export class ProjectListItem extends ProjectCommon { + public override readonly data: ProjectListItemData; public constructor(data: ProjectListItemData) { - super([data], [data]); + super(data); + this.data = data; } } @@ -151,19 +555,12 @@ export class ProjectListQuery extends ListQueryModel super(query); } - public refine(query: ProjectListQueryModelData) { - return new ProjectListQuery({ - ...this.query, - ...query, - }); - } - - public execute = provideReact(async () => { - const { server, customer, ...query } = this.query; - const { items, totalCount } = await config.behaviors.project.list({ + public async execute() { + const { customer, server, ...query } = this.query; + const { totalCount, items } = await config.behaviors.project.list({ ...query, - serverId: server?.id, - customerId: customer?.id, + customerId: extractId(customer), + serverId: extractId(server), }); return new ProjectList( @@ -171,30 +568,43 @@ export class ProjectListQuery extends ListQueryModel items.map((d) => new ProjectListItem(d)), totalCount, ); - }, [this.queryId]); + } + + public async findLatest() { + const { items } = await this.refine({ + sort: "createdAt", + order: "desc", + limit: 1, + }).execute(); + + return items[0]; + } - public getTotalCount = provideReact(async () => { + public async getTotalCount() { const { totalCount } = await this.refine({ limit: 1 }).execute(); return totalCount; - }, [this.queryId]); + } - public findOneAndOnly = provideReact(async () => { - const { items, totalCount } = await this.refine({ limit: 2 }).execute(); - if (totalCount === 1) { - return items[0]; - } - }, [this.queryId]); + public refine(query: ProjectListQueryModelData) { + return new ProjectListQuery({ + ...this.query, + ...query, + }); + } } -export class ProjectList extends classes( +export class ProjectList extends WithListData()( ProjectListQuery, - ListDataModel, ) { + public override readonly items: readonly ProjectListItem[]; + public override readonly totalCount: number; public constructor( query: ProjectListQueryModelData, projects: ProjectListItem[], totalCount: number, ) { - super([query], [projects, totalCount]); + super(query); + this.items = Object.freeze(projects); + this.totalCount = totalCount; } } diff --git a/packages/models/src/project/Project/ProjectAvatarAccessTokenProvider.ts b/packages/models/src/project/Project/ProjectAvatarAccessTokenProvider.ts new file mode 100644 index 00000000..e0a39c62 --- /dev/null +++ b/packages/models/src/project/Project/ProjectAvatarAccessTokenProvider.ts @@ -0,0 +1,16 @@ +import type { FileAccessTokenProvider } from "../../file/index.js"; +import type { Project } from "../internal.js"; + +import { config } from "../../config/index.js"; + +export class ProjectAvatarAccessTokenProvider implements FileAccessTokenProvider { + public readonly project: Project; + + public constructor(project: Project) { + this.project = project; + } + + public createUploadToken() { + return config.behaviors.project.createAvatarUploadToken(this.project.id); + } +} diff --git a/packages/models/src/project/Project/behaviors/api.ts b/packages/models/src/project/Project/behaviors/api.ts index 3bddb753..ef2c2fe2 100644 --- a/packages/models/src/project/Project/behaviors/api.ts +++ b/packages/models/src/project/Project/behaviors/api.ts @@ -1,75 +1,109 @@ -import { ProjectBehaviors } from "./types.js"; +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { ProjectBehaviors } from "./types.js"; + import { - assertStatus, - extractTotalCountHeader, - MittwaldAPIV2Client, -} from "@mittwald/api-client"; -import { assertOneOfStatus } from "@mittwald/api-client"; + withAxiosRequestConfig, + resolveTotalCount, +} from "../../../base/index.js"; +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { anyStatus404 } from "../../../base/api/typeFixes.js"; export const apiProjectBehaviors = ( client: MittwaldAPIV2Client, ): ProjectBehaviors => ({ - find: async (id) => { - const response = await client.project.getProject({ - projectId: id, - }); + find: async (projectId, options) => { + const response = await client.project.getProject( + { + projectId, + }, + withAxiosRequestConfig(options), + ); + + if (response.status === 200) { + return response.data; + } + // API-DRIFT: getProject omits 404 in its generated response type, so anyStatus404 (404 as any) is passed (resolve: use the literal 404 once the client type declares it) + validateResponse(response, [403, anyStatus404]); + }, + + findFileSystemDirectories: async (projectId, directory, requestConfig) => { + const response = await client.projectFileSystem.getDirectories( + { + queryParameters: { directory }, + projectId, + }, + withAxiosRequestConfig(requestConfig), + ); if (response.status === 200) { return response.data; } - assertOneOfStatus(response, [403]); + }, + + updateStorageNotificationThreshold: async ( + projectId, + thresholdInBytes?: number, + ) => { + const response = await client.project.storagespaceUpdateProjectStatistics({ + data: { notificationThresholdInBytes: thresholdInBytes }, + projectId, + }); + + validateResponse(response, 204); + }, + + createAvatarUploadToken: async (projectId) => { + const response = await client.project.requestProjectAvatarUpload({ + projectId, + }); + validateResponse(response, 200); + return { + token: response.data.refId, + rules: response.data.rules, + }; }, list: async (query) => { const response = await client.project.listProjects({ queryParameters: query, }); - assertStatus(response, 200); + validateResponse(response, 200); return { + totalCount: resolveTotalCount(response), items: response.data, - totalCount: extractTotalCountHeader(response), }; }, - create: async (serverId: string, description: string) => { + create: async (serverId, description) => { const response = await client.project.createProject({ - serverId, data: { description, }, + serverId, }); - assertStatus(response, 201); + validateResponse(response, 201); return response.data; }, - leave: async (id: string) => { - const selfMembershipResponse = - await client.project.getSelfMembershipForProject({ - projectId: id, - }); - - assertStatus(selfMembershipResponse, 200); - - const response = await client.project.deleteProjectMembership({ - projectMembershipId: selfMembershipResponse.data.id, - }); - assertStatus(response, 204); - }, - - delete: async (id: string) => { - const response = await client.project.deleteProject({ - projectId: id, - }); - assertStatus(response, 204); - }, - - updateDescription: async (id: string, description: string) => { + updateDescription: async (projectId, description) => { const response = await client.project.updateProject({ - projectId: id, data: { description, }, + projectId, }); - assertStatus(response, 204); + validateResponse(response, 204); + }, + + removeAvatar: async (projectId) => { + const response = await client.project.deleteProjectAvatar({ projectId }); + + validateResponse(response, 204); + }, + + delete: async (projectId) => { + const response = await client.project.deleteProject({ projectId }); + validateResponse(response, 204); }, }); diff --git a/packages/models/src/project/Project/behaviors/inMem.ts b/packages/models/src/project/Project/behaviors/inMem.ts deleted file mode 100644 index 56742245..00000000 --- a/packages/models/src/project/Project/behaviors/inMem.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { ProjectBehaviors } from "./types.js"; -import { ProjectData } from "../types.js"; - -export const inMemProjectBehaviors = ( - store: Map, -): ProjectBehaviors => ({ - find: async (id) => store.get(id), - - list: async () => { - const items = Array.from(store.values()).map((detailedProject) => ({ - ...detailedProject, - deletionRequested: detailedProject.deletionRequested ?? false, - customerMeta: { - id: detailedProject.customerId, - }, - })); - - return { - items, - totalCount: items.length, - }; - }, - - create: async () => { - throw new Error("Not implemented"); - }, - - leave: async () => { - throw new Error("Not implemented"); - }, - - delete: async () => { - throw new Error("Not implemented"); - }, - - updateDescription: async () => { - throw new Error("Not implemented"); - }, -}); diff --git a/packages/models/src/project/Project/behaviors/index.ts b/packages/models/src/project/Project/behaviors/index.ts index 395a6730..a7b74f7c 100644 --- a/packages/models/src/project/Project/behaviors/index.ts +++ b/packages/models/src/project/Project/behaviors/index.ts @@ -1,3 +1,2 @@ export * from "./api.js"; -export * from "./inMem.js"; export * from "./types.js"; diff --git a/packages/models/src/project/Project/behaviors/types.ts b/packages/models/src/project/Project/behaviors/types.ts index cc948633..f6f361e8 100644 --- a/packages/models/src/project/Project/behaviors/types.ts +++ b/packages/models/src/project/Project/behaviors/types.ts @@ -1,19 +1,42 @@ -import { +import type { AxiosRequestConfig } from "axios"; + +import type { FileUploadTokenData } from "../../../file/index.js"; +import type { QueryResponseData } from "../../../base/index.js"; +import type { + FileSystemDirectoriesData, + ProjectListQueryData, ProjectListItemData, ProjectData, - ProjectListQueryData, } from "../types.js"; -import { QueryResponseData } from "../../../base/index.js"; export interface ProjectBehaviors { - find: (id: string) => Promise; + findFileSystemDirectories: ( + projectId: string, + directory?: string, + requestConfig?: AxiosRequestConfig, + ) => Promise; + + updateStorageNotificationThreshold: ( + projectId: string, + thresholdInBytes?: number, + ) => Promise; + + find: ( + projectId: string, + options?: AxiosRequestConfig, + ) => Promise; + list: ( query?: ProjectListQueryData, ) => Promise>; + updateDescription: (projectId: string, description: string) => Promise; + + createAvatarUploadToken: (projectId: string) => Promise; + create: (serverId: string, description: string) => Promise<{ id: string }>; - leave: (projectId: string) => Promise; + removeAvatar: (projectId: string) => Promise; + delete: (projectId: string) => Promise; - updateDescription: (projectId: string, description: string) => Promise; } diff --git a/packages/models/src/project/Project/index.ts b/packages/models/src/project/Project/index.ts index dc61385c..ae935f7b 100644 --- a/packages/models/src/project/Project/index.ts +++ b/packages/models/src/project/Project/index.ts @@ -1,2 +1,9 @@ -export * from "./Project.js"; +export { + Project, + ProjectCommon, + ProjectDetailed, + ProjectList, + ProjectListItem, + ProjectListQuery, +} from "../internal.js"; export * from "./types.js"; diff --git a/packages/models/src/project/Project/types.ts b/packages/models/src/project/Project/types.ts index 591d69c1..388e8453 100644 --- a/packages/models/src/project/Project/types.ts +++ b/packages/models/src/project/Project/types.ts @@ -1,20 +1,33 @@ -import { MittwaldAPIV2 } from "@mittwald/api-client"; -import { Server } from "../../server/index.js"; -import { Customer } from "../../customer/index.js"; +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import type { Customer } from "../../customer/index.js"; +import type { Server } from "../../server/index.js"; export type ProjectListQueryData = MittwaldAPIV2.Paths.V2Projects.Get.Parameters.Query; -export type ProjectListQueryModelData = Omit< - ProjectListQueryData, - "serverId" | "customerId" -> & { - server?: Server; - customer?: Customer; -}; +export type ProjectListQueryModelData = { + customer?: Customer | string; + server?: Server | string; +} & Omit; export type ProjectData = MittwaldAPIV2.Operations.ProjectGetProject.ResponseData; export type ProjectListItemData = MittwaldAPIV2.Operations.ProjectListProjects.ResponseData[number]; + +export type ProjectFeature = + MittwaldAPIV2.Components.Schemas.ProjectProjectFeature; + +export type ProjectDisableReason = + MittwaldAPIV2.Components.Schemas.ProjectDisableReason; + +export type ProjectStatus = + MittwaldAPIV2.Components.Schemas.ProjectProjectStatus; + +export type FileSystemDirectoriesData = + MittwaldAPIV2.Operations.ProjectFileSystemGetDirectories.ResponseData; + +export type FileSystemDirectory = + MittwaldAPIV2.Components.Schemas.ProjectFilesystemDirectoryListing; diff --git a/packages/models/src/project/ProjectInvite/ProjectInvite.test.ts b/packages/models/src/project/ProjectInvite/ProjectInvite.test.ts new file mode 100644 index 00000000..a0102aef --- /dev/null +++ b/packages/models/src/project/ProjectInvite/ProjectInvite.test.ts @@ -0,0 +1,218 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { buildProjectInviteData } from "../../testing/builders/buildProjectInviteData.js"; +import { installBehaviors, resetBehaviors } from "../../testing/index.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { Project } from "../Project/index.js"; +import { User } from "../../user/index.js"; +import { + ProjectInviteDetailed, + ProjectInviteListItem, + ProjectInviteList, + ProjectInvite, +} from "./ProjectInvite.js"; + +afterEach(resetBehaviors); + +describe("ProjectInvite references and delegation", () => { + test("find delegates and materializes a detailed invite", async () => { + const find = vi + .fn() + .mockResolvedValue(buildProjectInviteData({ id: "i-1" })); + installBehaviors({ projectInvite: { find } }); + + const result = await ProjectInvite.find("i-1"); + + expect(find).toHaveBeenCalledWith("i-1"); + expect(result).toBeInstanceOf(ProjectInviteDetailed); + expect(result?.id).toBe("i-1"); + }); + + test("find maps a missing invite to undefined", async () => { + installBehaviors({ + projectInvite: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(ProjectInvite.find("missing")).resolves.toBeUndefined(); + }); + + test("get returns a detailed invite and throws when missing", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildProjectInviteData()) + .mockResolvedValueOnce(undefined); + installBehaviors({ projectInvite: { find } }); + + await expect(ProjectInvite.get("invite-id")).resolves.toBeInstanceOf( + ProjectInviteDetailed, + ); + await expect(ProjectInvite.get("missing")).rejects.toThrow(); + }); + + test("create delegates and returns an invite reference", async () => { + const create = vi.fn().mockResolvedValue({ id: "i-created" }); + installBehaviors({ projectInvite: { create } }); + const project = Project.ofId("p-1"); + const data = { mailAddress: "new@example.com", role: "owner" as const }; + + const result = await ProjectInvite.create(project, data); + + expect(create).toHaveBeenCalledWith("p-1", data); + expect(result).toBeInstanceOf(ProjectInvite); + expect(result.id).toBe("i-created"); + }); + + test("delete and decline delegate with the invite id", async () => { + const deleteInvite = vi.fn().mockResolvedValue(undefined); + const decline = vi.fn().mockResolvedValue(undefined); + installBehaviors({ projectInvite: { delete: deleteInvite, decline } }); + const invite = ProjectInvite.ofId("i-1"); + + await invite.delete(); + await invite.decline(); + + expect(deleteInvite).toHaveBeenCalledWith("i-1"); + expect(decline).toHaveBeenCalledWith("i-1"); + }); + + test("acceptWithToken resolves the invite before accepting it", async () => { + const getByToken = vi.fn().mockResolvedValue({ id: "i-1" }); + const accept = vi.fn().mockResolvedValue(undefined); + installBehaviors({ projectInvite: { getByToken, accept } }); + + await ProjectInvite.acceptWithToken("secret-token"); + + expect(getByToken).toHaveBeenCalledWith("secret-token"); + expect(accept).toHaveBeenCalledWith("i-1", "secret-token"); + }); + + test("listIncoming materializes incoming invite items", async () => { + installBehaviors({ + projectInvite: { + listIncoming: vi.fn().mockResolvedValue({ + items: [buildProjectInviteData()], + }), + }, + }); + + const result = await ProjectInvite.listIncoming(); + + expect(result).toHaveLength(1); + expect(result[0]).toBeInstanceOf(ProjectInviteListItem); + }); +}); + +describe("ProjectInvite common resolution and idempotency", () => { + test("findCommon delegates from a reference and returns the common variant", async () => { + const find = vi + .fn() + .mockResolvedValue(buildProjectInviteData({ id: "i-1" })); + installBehaviors({ projectInvite: { find } }); + + const result = await ProjectInvite.ofId("i-1").findCommon(); + + expect(find).toHaveBeenCalledWith("i-1"); + expect(result).toBeInstanceOf(ProjectInviteDetailed); + expect(result?.id).toBe("i-1"); + }); + + test("findCommon maps a missing reference to undefined", async () => { + installBehaviors({ + projectInvite: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + ProjectInvite.ofId("missing").findCommon(), + ).resolves.toBeUndefined(); + }); + + test("getCommon resolves the common variant and throws when missing", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildProjectInviteData({ id: "i-2" })) + .mockResolvedValueOnce(undefined); + installBehaviors({ projectInvite: { find } }); + + await expect(ProjectInvite.ofId("i-2").getCommon()).resolves.toBeInstanceOf( + ProjectInviteDetailed, + ); + await expect(ProjectInvite.ofId("missing").getCommon()).rejects.toThrow(); + }); + + test("findCommon and getCommon are idempotent on a materialized invite", async () => { + const find = vi.fn(); + installBehaviors({ projectInvite: { find } }); + const item = new ProjectInviteListItem( + buildProjectInviteData({ id: "i-1" }), + ); + + expect(await item.findCommon()).toBe(item); + expect(await item.getCommon()).toBe(item); + expect(find).not.toHaveBeenCalled(); + }); +}); + +describe("ProjectInvite aggregate metadata", () => { + test("aggregateMetaData pins the cache identity", () => { + expect(ProjectInvite.aggregateMetaData).toBeInstanceOf(AggregateMetaData); + expect(ProjectInvite.aggregateMetaData.domain).toBe("membership"); + expect(ProjectInvite.aggregateMetaData.aggregate).toBe("projectinvite"); + }); +}); + +describe("ProjectInvite data", () => { + test("omits the message when the source data is absent", () => { + const invite = new ProjectInviteListItem(buildProjectInviteData()); + + expect(invite.message).toBeUndefined(); + }); + + test("exposes invite values and related references", () => { + const invite = new ProjectInviteListItem( + buildProjectInviteData({ + information: { invitedBy: "inviter-id" }, + projectDescription: "Example project", + mailAddress: "invitee@example.com", + message: "Welcome", + projectId: "p-1", + role: "external", + }), + ); + + expect(invite.role).toBe("external"); + expect(invite.mailAddress).toBe("invitee@example.com"); + expect(invite.projectDescription).toBe("Example project"); + expect(invite.message).toBe("Welcome"); + expect(invite.invitedBy).toBeInstanceOf(User); + expect(invite.invitedBy.id).toBe("inviter-id"); + expect(invite.project).toBeInstanceOf(Project); + expect(invite.project.id).toBe("p-1"); + }); +}); + +describe("ProjectInvite list query", () => { + test("delegates with project and query and materializes a list", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildProjectInviteData()], + totalCount: 1, + }); + installBehaviors({ projectInvite: { list } }); + const project = Project.ofId("p-1"); + const query = { limit: 5 }; + + const result = await ProjectInvite.query(project, query).execute(); + + expect(list).toHaveBeenCalledWith("p-1", expect.objectContaining(query)); + expect(result).toBeInstanceOf(ProjectInviteList); + expect(result.items[0]).toBeInstanceOf(ProjectInviteListItem); + expect(result.totalCount).toBe(result.items.length); + }); +}); diff --git a/packages/models/src/project/ProjectInvite/ProjectInvite.ts b/packages/models/src/project/ProjectInvite/ProjectInvite.ts new file mode 100644 index 00000000..2ce4c513 --- /dev/null +++ b/packages/models/src/project/ProjectInvite/ProjectInvite.ts @@ -0,0 +1,199 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; + +import type { ProjectRole } from "../ProjectMembership/index.js"; +import type { + ProjectInviteCreateRequestData, + ProjectInviteListQueryData, + ProjectInviteListItemData, + ProjectInviteData, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { User } from "../../user/User/User.js"; +import { config } from "../../config/index.js"; +import { Project } from "../Project/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "ProjectInvite", +}) +export class ProjectInvite extends ReferenceModel { + public static aggregateMetaData = new AggregateMetaData( + "membership", + "projectinvite", + ); + + public static async acceptWithToken(invitationToken: string) { + const invite = + await config.behaviors.projectInvite.getByToken(invitationToken); + + await config.behaviors.projectInvite.accept(invite.id, invitationToken); + } + + public static async create( + project: Project, + data: ProjectInviteCreateRequestData, + ) { + const response = await config.behaviors.projectInvite.create( + project.id, + data, + ); + + return new ProjectInvite(response.id); + } + + public static async find(id: string) { + const data = await config.behaviors.projectInvite.find(id); + if (data) { + return new ProjectInviteDetailed(data); + } + } + + public static async get(id: string) { + const projectInvite = await ProjectInvite.find(id); + assertObjectFound(projectInvite, ProjectInvite, id); + return projectInvite; + } + + public static async listIncoming() { + const data = await config.behaviors.projectInvite.listIncoming(); + + return data.items.map((i) => new ProjectInviteListItem(i)); + } + + public static ofId(id: string) { + return new ProjectInvite(id); + } + + public static query( + project: Project, + query: ProjectInviteListQueryData = {}, + ) { + return new ProjectInviteListQuery(project, query); + } + + public async decline() { + await config.behaviors.projectInvite.decline(this.id); + } + + public async delete() { + await config.behaviors.projectInvite.delete(this.id); + } + + public async findCommon(): Promise { + return this instanceof ProjectInviteCommon ? this : this.findDetailed(); + } + + public async findDetailed(): Promise { + return ProjectInvite.find(this.id); + } + + public async getCommon(): Promise { + return this instanceof ProjectInviteCommon ? this : this.getDetailed(); + } + + public async getDetailed(): Promise { + return ProjectInvite.get(this.id); + } +} + +export class ProjectInviteCommon extends WithData< + ProjectInviteListItemData | ProjectInviteData +>()(ProjectInvite) { + public override readonly data: ProjectInviteListItemData | ProjectInviteData; + public readonly invitedBy: User; + public readonly mailAddress: string; + public readonly message?: string; + public readonly project: Project; + public readonly projectDescription: string; + public readonly role: ProjectRole; + + public constructor(data: ProjectInviteListItemData | ProjectInviteData) { + super(data.id); + this.data = data; + this.role = data.role; + this.mailAddress = data.mailAddress; + this.projectDescription = data.projectDescription; + this.invitedBy = User.ofId(data.information.invitedBy); + this.message = data.message; + this.project = Project.ofId(data.projectId); + } + + public async accept() { + await config.behaviors.projectInvite.accept(this.id); + } +} + +export class ProjectInviteDetailed extends ProjectInviteCommon { + public override readonly data: ProjectInviteData; + public constructor(data: ProjectInviteData) { + super(data); + this.data = data; + } +} + +export class ProjectInviteListItem extends ProjectInviteCommon { + public override readonly data: ProjectInviteListItemData; + public constructor(data: ProjectInviteListItemData) { + super(data); + this.data = data; + } +} + +export class ProjectInviteListQuery extends ListQueryModel { + public readonly project: Project; + + public constructor(project: Project, query: ProjectInviteListQueryData = {}) { + super(query, { dependencies: [project.id] }); + this.project = project; + } + + public async execute() { + const { totalCount, items } = await config.behaviors.projectInvite.list( + this.project.id, + this.query, + ); + + return new ProjectInviteList( + this.project, + this.query, + items.map((d) => new ProjectInviteListItem(d)), + totalCount, + ); + } + + public async getTotalCount() { + const { totalCount } = await this.refine({ limit: 1 }).execute(); + return totalCount; + } + + public refine(query: ProjectInviteListQueryData) { + return new ProjectInviteListQuery(this.project, { + ...this.query, + ...query, + }); + } +} + +export class ProjectInviteList extends WithListData()( + ProjectInviteListQuery, +) { + public override readonly items: readonly ProjectInviteListItem[]; + public override readonly totalCount: number; + public constructor( + project: Project, + query: ProjectInviteListQueryData, + invites: ProjectInviteListItem[], + totalCount: number, + ) { + super(project, query); + this.items = Object.freeze(invites); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/project/ProjectInvite/behaviors/api.ts b/packages/models/src/project/ProjectInvite/behaviors/api.ts new file mode 100644 index 00000000..c88b34fd --- /dev/null +++ b/packages/models/src/project/ProjectInvite/behaviors/api.ts @@ -0,0 +1,117 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { ProjectInviteBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { anyStatus403 } from "../../../base/api/typeFixes.js"; +import { resolveTotalCount } from "../../../base/index.js"; +import { ValidationError } from "../../../errors/index.js"; + +export const apiProjectInviteBehaviors = ( + client: MittwaldAPIV2Client, +): ProjectInviteBehaviors => ({ + create: async (projectId, data) => { + const response = await client.project.createProjectInvite({ + projectId, + data, + }); + if (response.status === 409) { + const message = + response.data.message && typeof response.data.message === "string" + ? response.data.message + : undefined; + + if (message?.includes("already exists")) { + throw new ValidationError({ + message: "inviteAlreadyExists", + type: "inviteAlreadyExists", + path: "mailAddress", + }); + } + if (message?.includes("already member")) { + throw new ValidationError({ + message: "alreadyMember", + type: "alreadyMember", + path: "mailAddress", + }); + } + } + + validateResponse(response, 201, { + validationError: { + pathMappings: { + mail_address: "mailAddress", + }, + }, + }); + return response.data; + }, + + find: async (projectInviteId) => { + const response = await client.project.getProjectInvite({ + projectInviteId, + }); + if (response.status === 200) { + return response.data; + } + // API-DRIFT: getProjectInvite omits 403 in its generated response type, so anyStatus403 (403 as any) is passed (resolve: use the literal 403 once the client type declares it) + validateResponse(response, [404, anyStatus403]); + }, + + list: async (projectId, query) => { + const response = await client.project.listInvitesForProject({ + queryParameters: query, + projectId, + }); + + validateResponse(response, 200); + + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + getByToken: async (invitationToken) => { + const response = await client.project.getProjectTokenInvite({ + headers: { token: invitationToken }, + }); + validateResponse(response, 200); + + return response.data; + }, + + listIncoming: async (query) => { + const response = await client.project.listProjectInvites({ + queryParameters: query, + }); + + validateResponse(response, 200); + + return { + items: response.data, + }; + }, + + accept: async (projectInviteId, invitationToken) => { + const response = await client.project.acceptProjectInvite({ + data: { invitationToken }, + projectInviteId, + }); + validateResponse(response, 204); + }, + + decline: async (projectInviteId) => { + const response = await client.project.declineProjectInvite({ + projectInviteId, + }); + validateResponse(response, 204); + }, + + delete: async (projectInviteId) => { + const response = await client.project.deleteProjectInvite({ + projectInviteId, + }); + validateResponse(response, 204); + }, +}); diff --git a/packages/models/src/project/ProjectInvite/behaviors/index.ts b/packages/models/src/project/ProjectInvite/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/project/ProjectInvite/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/project/ProjectInvite/behaviors/types.ts b/packages/models/src/project/ProjectInvite/behaviors/types.ts new file mode 100644 index 00000000..4f43c062 --- /dev/null +++ b/packages/models/src/project/ProjectInvite/behaviors/types.ts @@ -0,0 +1,32 @@ +import type { + ProjectInviteCreateRequestData, + ProjectInviteListQueryData, + ProjectInviteListItemData, + ProjectInviteData, +} from "../types.js"; + +export interface ProjectInviteBehaviors { + list: ( + projectId: string, + query?: ProjectInviteListQueryData, + ) => Promise<{ items: ProjectInviteListItemData[]; totalCount: number }>; + + listIncoming: ( + query?: ProjectInviteListQueryData, + ) => Promise<{ items: ProjectInviteListItemData[] }>; + + create: ( + projectId: string, + data: ProjectInviteCreateRequestData, + ) => Promise<{ id: string }>; + + accept: (projectInviteId: string, invitationToken?: string) => Promise; + + find: (projectInviteId: string) => Promise; + + getByToken: (token: string) => Promise<{ id: string }>; + + decline: (projectInviteId: string) => Promise; + + delete: (projectInviteId: string) => Promise; +} diff --git a/packages/models/src/project/ProjectInvite/index.ts b/packages/models/src/project/ProjectInvite/index.ts new file mode 100644 index 00000000..eb2abb1e --- /dev/null +++ b/packages/models/src/project/ProjectInvite/index.ts @@ -0,0 +1,2 @@ +export * from "./ProjectInvite.js"; +export * from "./types.js"; diff --git a/packages/models/src/project/ProjectInvite/types.ts b/packages/models/src/project/ProjectInvite/types.ts new file mode 100644 index 00000000..cd9ee7ff --- /dev/null +++ b/packages/models/src/project/ProjectInvite/types.ts @@ -0,0 +1,13 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type ProjectInviteData = + MittwaldAPIV2.Operations.ProjectGetProjectInvite.ResponseData; + +export type ProjectInviteListItemData = + MittwaldAPIV2.Operations.ProjectListProjectInvites.ResponseData[number]; + +export type ProjectInviteListQueryData = + MittwaldAPIV2.Paths.V2ProjectsProjectIdInvites.Get.Parameters.Query; + +export type ProjectInviteCreateRequestData = + MittwaldAPIV2.Paths.V2ProjectsProjectIdInvites.Post.Parameters.RequestBody; diff --git a/packages/models/src/project/ProjectMembership/ProjectMembership.test.ts b/packages/models/src/project/ProjectMembership/ProjectMembership.test.ts new file mode 100644 index 00000000..8989b3b1 --- /dev/null +++ b/packages/models/src/project/ProjectMembership/ProjectMembership.test.ts @@ -0,0 +1,251 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; +import { DateTime } from "luxon"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { buildProjectMembershipData } from "../../testing/builders/buildProjectMembershipData.js"; +import { installBehaviors, resetBehaviors } from "../../testing/index.js"; +import { Project } from "../Project/index.js"; +import { File } from "../../file/index.js"; +import { User } from "../../user/index.js"; +import { + ProjectMembershipDetailed, + ProjectMembershipListItem, + ProjectMembershipList, + ProjectMembership, +} from "./ProjectMembership.js"; + +afterEach(resetBehaviors); + +describe("ProjectMembership references and delegation", () => { + test("find delegates and materializes a detailed membership", async () => { + const find = vi + .fn() + .mockResolvedValue(buildProjectMembershipData({ id: "m-1" })); + installBehaviors({ projectMembership: { find } }); + + const result = await ProjectMembership.find("m-1"); + + expect(find).toHaveBeenCalledWith("m-1", undefined); + expect(result).toBeInstanceOf(ProjectMembershipDetailed); + expect(result?.id).toBe("m-1"); + }); + + test("find maps a missing membership to undefined", async () => { + installBehaviors({ + projectMembership: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(ProjectMembership.find("missing")).resolves.toBeUndefined(); + }); + + test("get returns a detailed membership and throws when missing", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildProjectMembershipData()) + .mockResolvedValueOnce(undefined); + installBehaviors({ projectMembership: { find } }); + + await expect( + ProjectMembership.get("membership-id"), + ).resolves.toBeInstanceOf(ProjectMembershipDetailed); + await expect(ProjectMembership.get("missing")).rejects.toThrow(); + }); + + test("findOwn and getOwn delegate with the project id", async () => { + const findOwn = vi + .fn() + .mockResolvedValue(buildProjectMembershipData({ projectId: "p-1" })); + installBehaviors({ projectMembership: { findOwn } }); + const project = Project.ofId("p-1"); + + const found = await ProjectMembership.findOwn(project); + const gotten = await ProjectMembership.getOwn(project); + + expect(findOwn).toHaveBeenNthCalledWith(1, "p-1"); + expect(findOwn).toHaveBeenNthCalledWith(2, "p-1"); + expect(found).toBeInstanceOf(ProjectMembershipDetailed); + expect(gotten).toBeInstanceOf(ProjectMembershipDetailed); + }); + + test("getOwn throws when the membership is missing", async () => { + installBehaviors({ + projectMembership: { findOwn: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + ProjectMembership.getOwn(Project.ofId("p-1")), + ).rejects.toThrow(); + }); + + test("remove delegates with the membership id", async () => { + const remove = vi.fn().mockResolvedValue(undefined); + installBehaviors({ projectMembership: { remove } }); + + await ProjectMembership.ofId("m-1").remove(); + + expect(remove).toHaveBeenCalledWith("m-1"); + }); +}); + +describe("ProjectMembership common resolution and idempotency", () => { + test("findCommon delegates from a reference and returns the common variant", async () => { + const find = vi + .fn() + .mockResolvedValue(buildProjectMembershipData({ id: "m-1" })); + installBehaviors({ projectMembership: { find } }); + + const result = await ProjectMembership.ofId("m-1").findCommon(); + + expect(find).toHaveBeenCalledWith("m-1", undefined); + expect(result).toBeInstanceOf(ProjectMembershipDetailed); + expect(result?.id).toBe("m-1"); + }); + + test("findCommon maps a missing reference to undefined", async () => { + installBehaviors({ + projectMembership: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect( + ProjectMembership.ofId("missing").findCommon(), + ).resolves.toBeUndefined(); + }); + + test("getCommon resolves the common variant and throws when missing", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildProjectMembershipData({ id: "m-2" })) + .mockResolvedValueOnce(undefined); + installBehaviors({ projectMembership: { find } }); + + await expect( + ProjectMembership.ofId("m-2").getCommon(), + ).resolves.toBeInstanceOf(ProjectMembershipDetailed); + await expect( + ProjectMembership.ofId("missing").getCommon(), + ).rejects.toThrow(); + }); + + test("findCommon and getCommon are idempotent on a materialized membership", async () => { + const find = vi.fn(); + installBehaviors({ projectMembership: { find } }); + const item = new ProjectMembershipListItem( + buildProjectMembershipData({ id: "m-1" }), + ); + + expect(await item.findCommon()).toBe(item); + expect(await item.getCommon()).toBe(item); + expect(find).not.toHaveBeenCalled(); + }); +}); + +describe("ProjectMembership data and updates", () => { + test("omits the expiration date when the source data is absent", () => { + const membership = new ProjectMembershipListItem( + buildProjectMembershipData(), + ); + + expect(membership.expiresAt).toBeUndefined(); + }); + + test("exposes values, dates, and related references", () => { + const membership = new ProjectMembershipListItem( + buildProjectMembershipData({ + expiresAt: "2025-01-01T00:00:00.000Z", + avatarRef: "avatar-id", + firstName: "Grace", + lastName: "Hopper", + role: "emailadmin", + projectId: "p-1", + inherited: true, + userId: "u-1", + }), + ); + + expect(membership.user).toBeInstanceOf(User); + expect(membership.user.id).toBe("u-1"); + expect(membership.role).toBe("emailadmin"); + expect(membership.inherited).toBe(true); + expect(membership.fullName).toBe("Grace Hopper"); + expect(membership.expiresAt).toBeInstanceOf(DateTime); + expect(membership.expiresAt?.isValid).toBe(true); + expect(membership.avatar).toBeInstanceOf(File); + expect(membership.avatar?.id).toBe("avatar-id"); + expect(membership.project).toBeInstanceOf(Project); + expect(membership.project.id).toBe("p-1"); + expect( + new ProjectMembershipListItem(buildProjectMembershipData()).avatar, + ).toBeUndefined(); + }); + + test("updateRole delegates with the new role", async () => { + const update = vi.fn().mockResolvedValue(undefined); + installBehaviors({ projectMembership: { update } }); + const membership = new ProjectMembershipListItem( + buildProjectMembershipData({ role: "owner" }), + ); + + await membership.updateRole("external"); + + expect(update).toHaveBeenCalledWith( + "membership-id", + expect.objectContaining({ role: "external" }), + ); + }); + + test("updateExpirationDate delegates with the date and current role", async () => { + const update = vi.fn().mockResolvedValue(undefined); + installBehaviors({ projectMembership: { update } }); + const membership = new ProjectMembershipListItem( + buildProjectMembershipData({ role: "emailadmin" }), + ); + const expiresAt = "2025-06-01T00:00:00.000Z"; + + await membership.updateExpirationDate(expiresAt); + + expect(update).toHaveBeenCalledWith( + "membership-id", + expect.objectContaining({ role: "emailadmin", expiresAt }), + ); + }); +}); + +describe("ProjectMembership list query", () => { + test("delegates with the project id and materializes the result", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildProjectMembershipData()], + totalCount: 1, + }); + installBehaviors({ projectMembership: { list } }); + const project = Project.ofId("p-1"); + + const result = await ProjectMembership.query(project).execute(); + + expect(result).toBeInstanceOf(ProjectMembershipList); + expect(result.items[0]).toBeInstanceOf(ProjectMembershipListItem); + expect(result.totalCount).toBe(1); + expect(list).toHaveBeenCalledWith("p-1", expect.any(Object)); + }); + + test("getTotalCount requests one item and returns the total", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 17, items: [] }); + installBehaviors({ projectMembership: { list } }); + + const result = await ProjectMembership.query( + Project.ofId("p-1"), + ).getTotalCount(); + + expect(result).toBe(17); + expect(list).toHaveBeenCalledWith( + "p-1", + expect.objectContaining({ limit: 1 }), + ); + }); +}); diff --git a/packages/models/src/project/ProjectMembership/ProjectMembership.ts b/packages/models/src/project/ProjectMembership/ProjectMembership.ts new file mode 100644 index 00000000..7b5928cb --- /dev/null +++ b/packages/models/src/project/ProjectMembership/ProjectMembership.ts @@ -0,0 +1,212 @@ +import type { AxiosRequestConfig } from "axios"; + +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; + +import type { + ProjectMembershipListQueryData, + ProjectMembershipListItemData, + ProjectMembershipData, + ProjectRole, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { File } from "../../file/File/internal.js"; +import { User } from "../../user/User/User.js"; +import { config } from "../../config/index.js"; +import { Project } from "../Project/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "ProjectMembership", +}) +export class ProjectMembership extends ReferenceModel { + public static async find(id: string, options?: AxiosRequestConfig) { + const data = await config.behaviors.projectMembership.find(id, options); + if (data) { + return new ProjectMembershipDetailed(data); + } + } + + public static async findOwn(project: Project) { + const data = await config.behaviors.projectMembership.findOwn(project.id); + if (data) { + return new ProjectMembershipDetailed(data); + } + } + + public static async get(id: string, options?: AxiosRequestConfig) { + const projectMembership = await ProjectMembership.find(id, options); + assertObjectFound(projectMembership, ProjectMembership, id); + return projectMembership; + } + + public static async getOwn(project: Project) { + const membership = await ProjectMembership.findOwn(project); + assertObjectFound(membership, ProjectMembership, project.id); + return membership; + } + + public static ofId(id: string) { + return new ProjectMembership(id); + } + + public static query( + project: Project, + query: ProjectMembershipListQueryData = {}, + ) { + return new ProjectMembershipListQuery(project, query); + } + + public async findCommon( + options?: AxiosRequestConfig, + ): Promise { + return this instanceof ProjectMembershipCommon + ? this + : this.findDetailed(options); + } + + public async findDetailed( + options?: AxiosRequestConfig, + ): Promise { + return ProjectMembership.find(this.id, options); + } + + public async getCommon( + options?: AxiosRequestConfig, + ): Promise { + return this instanceof ProjectMembershipCommon + ? this + : this.getDetailed(options); + } + + public getDetailed( + options?: AxiosRequestConfig, + ): Promise { + return ProjectMembership.get(this.id, options); + } + + public async remove() { + await config.behaviors.projectMembership.remove(this.id); + } +} + +export class ProjectMembershipCommon extends WithData< + ProjectMembershipListItemData | ProjectMembershipData +>()(ProjectMembership) { + public readonly avatar?: File; + public override readonly data: + ProjectMembershipListItemData | ProjectMembershipData; + public readonly expiresAt?: DateTime; + public readonly fullName: string; + public readonly inherited: boolean; + public readonly project: Project; + public readonly role: ProjectRole; + public readonly user: User; + + public constructor( + data: ProjectMembershipListItemData | ProjectMembershipData, + ) { + super(data.id); + this.data = data; + this.user = User.ofId(data.userId); + this.role = data.role; + this.inherited = data.inherited; + if (data.expiresAt) { + this.expiresAt = DateTime.fromISO(data.expiresAt); + } + this.fullName = `${data.firstName} ${data.lastName}`; + this.avatar = data.avatarRef ? File.ofId(data.avatarRef) : undefined; + this.project = Project.ofId(data.projectId); + } + + public async updateExpirationDate(expiresAt: string | null) { + await config.behaviors.projectMembership.update(this.id, { + expiresAt: expiresAt as string | undefined, + role: this.role, + }); + } + + public async updateRole(role: ProjectRole) { + await config.behaviors.projectMembership.update(this.id, { + expiresAt: this.data.expiresAt, + role, + }); + } +} + +export class ProjectMembershipDetailed extends ProjectMembershipCommon { + public override readonly data: ProjectMembershipData; + public constructor(data: ProjectMembershipData) { + super(data); + this.data = data; + } +} + +export class ProjectMembershipListItem extends ProjectMembershipCommon { + public override readonly data: ProjectMembershipListItemData; + public constructor(data: ProjectMembershipListItemData) { + super(data); + this.data = data; + } +} + +export class ProjectMembershipListQuery extends ListQueryModel { + public readonly project: Project; + + public constructor( + project: Project, + query: ProjectMembershipListQueryData = {}, + ) { + super(query, { dependencies: [project.id] }); + this.project = project; + } + + public async execute() { + const { totalCount, items } = await config.behaviors.projectMembership.list( + this.project.id, + this.query, + ); + + return new ProjectMembershipList( + this.project, + this.query, + items.map((d) => new ProjectMembershipListItem(d)), + totalCount, + ); + } + + public async getTotalCount() { + const { totalCount } = await this.refine({ limit: 1 }).execute(); + return totalCount; + } + + public refine(query: ProjectMembershipListQueryData) { + return new ProjectMembershipListQuery(this.project, { + ...this.query, + ...query, + }); + } +} + +export class ProjectMembershipList extends WithListData()( + ProjectMembershipListQuery, +) { + public override readonly items: readonly ProjectMembershipListItem[]; + public override readonly totalCount: number; + public constructor( + project: Project, + query: ProjectMembershipListQueryData, + memberships: ProjectMembershipListItem[], + totalCount: number, + ) { + super(project, query); + this.items = Object.freeze(memberships); + this.totalCount = totalCount; + } +} diff --git a/packages/models/src/project/ProjectMembership/behaviors/api.ts b/packages/models/src/project/ProjectMembership/behaviors/api.ts new file mode 100644 index 00000000..1fa0ba42 --- /dev/null +++ b/packages/models/src/project/ProjectMembership/behaviors/api.ts @@ -0,0 +1,66 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { ProjectMembershipBehaviors } from "./types.js"; + +import { + withAxiosRequestConfig, + resolveTotalCount, +} from "../../../base/index.js"; +import { validateResponse } from "../../../base/api/validateResponse.js"; + +export const apiProjectMembershipBehaviors = ( + client: MittwaldAPIV2Client, +): ProjectMembershipBehaviors => ({ + find: async (projectMembershipId, options) => { + const response = await client.project.getProjectMembership( + { + projectMembershipId, + }, + withAxiosRequestConfig(options), + ); + if (response.status === 200) { + return response.data; + } + validateResponse(response, 404); + }, + + list: async (projectId, query) => { + const response = await client.project.listMembershipsForProject({ + queryParameters: query, + projectId, + }); + + validateResponse(response, 200); + + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + findOwn: async (projectId) => { + const response = await client.project.getSelfMembershipForProject({ + projectId, + }); + if (response.status === 200) { + return response.data; + } + + validateResponse(response, [404, 403]); + }, + + update: async (projectMembershipId, data) => { + const response = await client.project.updateProjectMembership({ + projectMembershipId, + data, + }); + validateResponse(response, 204); + }, + + remove: async (projectMembershipId) => { + const response = await client.project.deleteProjectMembership({ + projectMembershipId, + }); + validateResponse(response, 204); + }, +}); diff --git a/packages/models/src/project/ProjectMembership/behaviors/index.ts b/packages/models/src/project/ProjectMembership/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/project/ProjectMembership/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/project/ProjectMembership/behaviors/types.ts b/packages/models/src/project/ProjectMembership/behaviors/types.ts new file mode 100644 index 00000000..eb4b6625 --- /dev/null +++ b/packages/models/src/project/ProjectMembership/behaviors/types.ts @@ -0,0 +1,30 @@ +import type { AxiosRequestConfig } from "axios"; + +import type { QueryResponseData } from "../../../base/index.js"; +import type { + ProjectMembershipUpdateRequestData, + ProjectMembershipListQueryData, + ProjectMembershipListItemData, + ProjectMembershipData, +} from "../types.js"; + +export interface ProjectMembershipBehaviors { + list: ( + projectId: string, + query?: ProjectMembershipListQueryData, + ) => Promise>; + + find: ( + projectMembershipId: string, + options?: AxiosRequestConfig, + ) => Promise; + + update: ( + projectMembershipId: string, + data: ProjectMembershipUpdateRequestData, + ) => Promise; + + findOwn: (projectId: string) => Promise; + + remove: (projectMembershipId: string) => Promise; +} diff --git a/packages/models/src/project/ProjectMembership/index.ts b/packages/models/src/project/ProjectMembership/index.ts new file mode 100644 index 00000000..b328c339 --- /dev/null +++ b/packages/models/src/project/ProjectMembership/index.ts @@ -0,0 +1,2 @@ +export * from "./ProjectMembership.js"; +export * from "./types.js"; diff --git a/packages/models/src/project/ProjectMembership/types.ts b/packages/models/src/project/ProjectMembership/types.ts new file mode 100644 index 00000000..0f1f5600 --- /dev/null +++ b/packages/models/src/project/ProjectMembership/types.ts @@ -0,0 +1,16 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type ProjectMembershipData = + MittwaldAPIV2.Operations.ProjectGetProjectMembership.ResponseData; + +export type ProjectMembershipListItemData = + MittwaldAPIV2.Operations.ProjectListProjectMemberships.ResponseData[number]; + +export type ProjectMembershipListQueryData = + MittwaldAPIV2.Paths.V2ProjectsProjectIdMemberships.Get.Parameters.Query; + +export type ProjectRole = + MittwaldAPIV2.Components.Schemas.MembershipProjectRoles; + +export type ProjectMembershipUpdateRequestData = + MittwaldAPIV2.Paths.V2ProjectMembershipsProjectMembershipId.Patch.Parameters.RequestBody; diff --git a/packages/models/src/project/index.ts b/packages/models/src/project/index.ts index 12f077c8..a01043e9 100644 --- a/packages/models/src/project/index.ts +++ b/packages/models/src/project/index.ts @@ -1 +1,14 @@ -export * from "./Project/index.js"; +export { + HardwareSpecs, + hardwareSpecsSchema, + MachineTypeSpecs, + Project, + ProjectCommon, + ProjectDetailed, + ProjectListItem, + ProjectListQuery, +} from "./internal.js"; +export * from "./Project/types.js"; +export * from "./ProjectInvite/index.js"; +export * from "./ProjectMembership/index.js"; +export * from "./projectPermissions.js"; diff --git a/packages/models/src/project/internal.ts b/packages/models/src/project/internal.ts new file mode 100644 index 00000000..ec732ebf --- /dev/null +++ b/packages/models/src/project/internal.ts @@ -0,0 +1,3 @@ +export * from "./Project/HardwareSpecs.js"; +export * from "./Project/MachineTypeSpecs.js"; +export * from "./Project/Project.js"; diff --git a/packages/models/src/project/projectPermissions.ts b/packages/models/src/project/projectPermissions.ts new file mode 100644 index 00000000..eb9a3156 --- /dev/null +++ b/packages/models/src/project/projectPermissions.ts @@ -0,0 +1,61 @@ +import type { ProjectRole } from "./ProjectMembership/index.js"; + +export type ProjectPermission = + | "accessConversations" + | "accessPerformance" + | "accessFileSystem" + | "accessMonitoring" + | "accessActivities" + | "accessDashboard" + | "accessExtension" + | "accessContainer" + | "accessAiHosting" + | "accessDatabase" + | "accessCustomer" + | "accessCronjob" + | "accessSftpSsh" + | "deleteHosting" + | "accessInvites" + | "accessDomain" + | "accessMember" + | "accessBackup" + | "bookHosting" + | "editProject" + | "editDomain" + | "accessMail" + | "editMember" + | "accessPlan" + | "accessApp" + | "book"; + +export const projectPermissions: Record< + ProjectPermission, + ("inheritedOwner" | ProjectRole)[] +> = { + accessExtension: ["owner", "emailadmin", "external"], + accessDomain: ["owner", "emailadmin", "external"], + accessMail: ["owner", "emailadmin", "external"], + accessConversations: ["owner", "external"], + accessPerformance: ["owner", "external"], + accessFileSystem: ["owner", "external"], + accessMonitoring: ["owner", "external"], + accessActivities: ["owner", "external"], + accessDashboard: ["owner", "external"], + accessContainer: ["owner", "external"], + accessAiHosting: ["owner", "external"], + accessDatabase: ["owner", "external"], + accessCronjob: ["owner", "external"], + accessSftpSsh: ["owner", "external"], + accessMember: ["owner", "external"], + accessBackup: ["owner", "external"], + accessCustomer: ["inheritedOwner"], + editDomain: ["owner", "external"], + deleteHosting: ["inheritedOwner"], + accessApp: ["owner", "external"], + bookHosting: ["inheritedOwner"], + accessPlan: ["inheritedOwner"], + accessInvites: ["owner"], + editProject: ["owner"], + editMember: ["owner"], + book: ["owner"], +}; diff --git a/packages/models/src/publicApi.test.ts b/packages/models/src/publicApi.test.ts new file mode 100644 index 00000000..0e1fe9ae --- /dev/null +++ b/packages/models/src/publicApi.test.ts @@ -0,0 +1,86 @@ +import { readFileSync } from "node:fs"; +import { dirname } from "node:path"; +import { fileURLToPath } from "node:url"; +import ts from "typescript"; +import { expect, it } from "vitest"; +import * as api from "./index.js"; + +/** + * Pins the public surface of the package: every change to it shows up as a diff + * in `__snapshots__/publicApi.txt` and has to be waved through deliberately + * instead of slipping in as a side effect. + * + * `export *` makes the surface implicit — adding a file to a domain barrel + * silently publishes everything in it. Since `package.json#exports` only opens + * `"."`, that barrel _is_ the contract (see docs/adr/0003). + * + * The surface has two halves and only one of them exists at runtime: + * `Object.keys()` on the module sees values (classes, functions, consts) but + * not the type-only exports, which are roughly half of all exported names. The + * snapshot is therefore built from the TypeScript checker, which reports both, + * and marks type-only names with a `type ` prefix — so a name silently turning + * from a class into a type alias is a visible line change, not an invisible + * one. `Object.keys()` still runs, as a cross-check that the checker's view of + * the value half matches what the module actually exports. + * + * Not covered: the _shape_ behind each name. A changed method signature, a + * widened union or a dropped class member keeps the name and passes here — that + * is `test:compile`'s and the consumers' job, not this test's. + */ + +const entryPath = fileURLToPath(new URL("./index.ts", import.meta.url)); + +const readCompilerOptions = (): ts.CompilerOptions => { + const configPath = ts.findConfigFile(dirname(entryPath), ts.sys.fileExists); + if (!configPath) throw new Error("tsconfig.json not found"); + const { config } = ts.readConfigFile(configPath, (p) => + readFileSync(p, "utf8"), + ); + const parsed = ts.parseJsonConfigFileContent( + config, + ts.sys, + dirname(configPath), + ); + return { ...parsed.options, noEmit: true }; +}; + +const readDeclaredExports = (): { values: string[]; types: string[] } => { + const program = ts.createProgram([entryPath], readCompilerOptions()); + const checker = program.getTypeChecker(); + const entry = program.getSourceFile(entryPath); + if (!entry) throw new Error(`${entryPath} is not part of the program`); + const entrySymbol = checker.getSymbolAtLocation(entry); + if (!entrySymbol) throw new Error(`${entryPath} has no module symbol`); + + const values: string[] = []; + const types: string[] = []; + for (const exported of checker.getExportsOfModule(entrySymbol)) { + const target = + exported.flags & ts.SymbolFlags.Alias + ? checker.getAliasedSymbol(exported) + : exported; + const bucket = target.flags & ts.SymbolFlags.Value ? values : types; + bucket.push(exported.getName()); + } + return { values: values.sort(), types: types.sort() }; +}; + +const declaredExports = readDeclaredExports(); + +it("exports exactly the declared values at runtime", () => { + expect(Object.keys(api).sort()).toEqual(declaredExports.values); +}); + +it("exports exactly the documented surface", async () => { + const { values, types } = declaredExports; + const surface = [ + ...values.map((name) => ({ name, line: name })), + ...types.map((name) => ({ name, line: `type ${name}` })), + ] + .sort((a, b) => a.name.localeCompare(b.name, "en")) + .map((entry) => entry.line); + + await expect(surface.join("\n")).toMatchFileSnapshot( + "./__snapshots__/publicApi.txt", + ); +}); diff --git a/packages/models/src/react.ts b/packages/models/src/react.ts deleted file mode 100644 index 7177a171..00000000 --- a/packages/models/src/react.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./react/index.js"; diff --git a/packages/models/src/react/MittwaldApiModelProvider.tsx b/packages/models/src/react/MittwaldApiModelProvider.tsx deleted file mode 100644 index 42ee78b1..00000000 --- a/packages/models/src/react/MittwaldApiModelProvider.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { FC, PropsWithChildren, ReactNode } from "react"; -import { usePromise } from "@mittwald/react-use-promise"; -import { setModule } from "./reactUsePromise.js"; - -interface Props extends PropsWithChildren { - fallback?: ReactNode; -} - -export const MittwaldApiModelProvider: FC = (props) => { - const { fallback, children } = props; - - const module = usePromise( - () => import("@mittwald/react-use-promise").then(setModule), - [], - { - useSuspense: false, - }, - ); - - if (!module.hasValue) { - return fallback; - } - - return children; -}; diff --git a/packages/models/src/react/asyncResourceInvalidation.ts b/packages/models/src/react/asyncResourceInvalidation.ts deleted file mode 100644 index 6a7364cd..00000000 --- a/packages/models/src/react/asyncResourceInvalidation.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { Commons } from "@mittwald/api-client"; -import { reactProvisionContext } from "./reactProvisionContext.js"; -import { asyncResourceStore, refresh } from "@mittwald/react-use-promise"; -import { Store } from "@mittwald/react-use-promise/store"; - -const cacheTagStore = new Store>(); - -export const refreshProvideReactCache = (tag: string) => { - const idSets = cacheTagStore.getAll(tag); - const ids = new Set(idSets.flatMap((idSet) => [...idSet])); - - if (ids.size === 0) { - return; - } - - const resources = asyncResourceStore.getAll(); - const [firstResource] = resources; - - // AsyncResource.meta only exists since @mittwald/react-use-promise 4.1. All - // resources come from the same version, so checking one of them is enough. - if (firstResource && !firstResource.meta) { - ids.forEach((id) => refresh({ tag: id })); - return; - } - - const existingIds = new Set(); - - resources.forEach((resource) => { - const id = resource.meta.tags?.tags.find( - (resourceTag): resourceTag is string => - typeof resourceTag === "string" && ids.has(resourceTag), - ); - - if (id !== undefined) { - existingIds.add(id); - resource.refresh(); - } - }); - - idSets.forEach((idSet) => { - idSet.forEach((id) => { - if (!existingIds.has(id)) { - idSet.delete(id); - } - }); - }); - - // Store.releaseBy only exists since @mittwald/react-use-promise 4.3 - if (idSets.some((idSet) => idSet.size === 0)) { - cacheTagStore.releaseBy?.((idSet) => idSet.size === 0); - } -}; - -export const addTagToProvideReactCache = (tag: string) => { - const context = reactProvisionContext.use(); - - if (context) { - const ids = cacheTagStore.get(tag) ?? new Set(); - ids.add(context.id); - - cacheTagStore.set(tag, () => ids, { - tags: [tag], - }); - } -}; - -export const addUrlTagToProvideReactCache: Commons.RequestOptions["onBeforeRequest"] = - (request) => { - const url = request.requestConfig.url; - - if (request.requestConfig.method === "GET" && url) { - addTagToProvideReactCache(url); - } - }; diff --git a/packages/models/src/react/index.ts b/packages/models/src/react/index.ts deleted file mode 100644 index 21f88bee..00000000 --- a/packages/models/src/react/index.ts +++ /dev/null @@ -1,9 +0,0 @@ -export { - refreshProvideReactCache, - addTagToProvideReactCache, - addUrlTagToProvideReactCache, -} from "./asyncResourceInvalidation.js"; -export * from "./MittwaldApiModelProvider.js"; -export * from "./reactUsePromise.js"; -export { type AsyncResourceVariant } from "./provideReact.js"; -export { provideReact } from "./provideReact.js"; diff --git a/packages/models/src/react/provideReact.test-types.ts b/packages/models/src/react/provideReact.test-types.ts deleted file mode 100644 index 883ff6b2..00000000 --- a/packages/models/src/react/provideReact.test-types.ts +++ /dev/null @@ -1,34 +0,0 @@ -import type { IsEqual } from "type-fest"; -import { provideReact } from "./provideReact.js"; - -/* - * Type-level tests, checked by `tsc --noEmit` (the `test:compile` target). - * `true satisfies IsEqual<...>` asserts exact type identity; a plain - * assignability check would also accept a wider or narrower type. Expected - * rejections are marked with `@ts-expect-error`. - */ - -const reactProvided = provideReact( - async (ignoredP1: string, ignoredP2?: boolean) => Promise.resolve("foo"), -); - -function ignoredTestReturnTypesOfProvideReact() { - const ignoredUsedValue = reactProvided.use("foo"); - const ignoredResourceValue = reactProvided.asResource("foo").use(); - void (true satisfies IsEqual); - void (true satisfies IsEqual); -} - -function ignoredTestParameterTypesOfProvideReact() { - reactProvided.use("foo", true); - reactProvided.asResource("foo", true); - reactProvided.use("foo"); - reactProvided.asResource("foo"); - - // @ts-expect-error Not assignable - reactProvided.asResource(42); - // @ts-expect-error Not assignable - reactProvided.asResource("foo", 42); - // @ts-expect-error Not assignable - reactProvided.asResource("foo", true, 42); -} diff --git a/packages/models/src/react/provideReact.test.tsx b/packages/models/src/react/provideReact.test.tsx deleted file mode 100644 index 61a3f361..00000000 --- a/packages/models/src/react/provideReact.test.tsx +++ /dev/null @@ -1,167 +0,0 @@ -/** @jest-environment jsdom */ - -import "@testing-library/jest-dom"; -import { render, screen, waitFor } from "@testing-library/react"; -import { ReferenceModel } from "../base/index.js"; -import { provideReact } from "./provideReact.js"; -import React, { act, FC, PropsWithChildren, Suspense } from "react"; -import { beforeEach, jest } from "@jest/globals"; -import { MittwaldApiModelProvider } from "./MittwaldApiModelProvider.js"; -import { - addTagToProvideReactCache, - refreshProvideReactCache, -} from "./asyncResourceInvalidation.js"; -import { asyncResourceStore } from "@mittwald/react-use-promise"; -import { Store } from "@mittwald/react-use-promise/store"; - -const simulatedDataLoad = jest.fn(); -let rerender: ReturnType["rerender"] | undefined; - -beforeEach(() => { - jest.resetAllMocks(); - jest.useFakeTimers(); - asyncResourceStore.clear(); - rerender = undefined; - - simulatedDataLoad.mockImplementation(() => { - return new Promise((res) => setTimeout(res, 100)); - }); -}); - -class TestModel extends ReferenceModel { - public readonly lazyDependency: number; - - public static ofId(id: number, lazyDependency = 0) { - return new TestModel(String(id), lazyDependency); - } - - public constructor(id: string, lazyDependency: number) { - super(id); - this.lazyDependency = lazyDependency; - } - - public getDetailed = provideReact(async () => { - addTagToProvideReactCache(`test/get/${this.id}`); - await simulatedDataLoad(); - return { - id: this.id, - foo: true, - }; - }, [this.id, () => this.lazyDependency]); -} - -const TestComponent: FC<{ id: number; lazyDependency?: number }> = (props) => { - const model = TestModel.ofId( - props.id, - props.lazyDependency, - ).getDetailed.use(); - return {model.id}; -}; - -const TestWrapper: FC = (props) => ( - - {props.children} - -); - -const runTest = async ( - id: number, - expectedDataLoadingCount: number, - dynamicId = 0, -) => { - const ui = rerender - ? rerender() - : render(, { - wrapper: TestWrapper, - }); - - if (ui) { - rerender = ui.rerender; - } - expect(await screen.findByText(id)).toBeInTheDocument(); - expect(simulatedDataLoad).toHaveBeenCalledTimes(expectedDataLoadingCount); -}; - -test("Model data can be used", async () => { - await runTest(42, 1); - await runTest(43, 2); -}); - -test("Model caches data", async () => { - await runTest(42, 1); - await runTest(43, 2); - await runTest(42, 2); - await runTest(43, 2); -}); - -test("Model caches data with lazy dependency", async () => { - await runTest(43, 1); - await runTest(43, 2, 42); - await runTest(43, 2, 42); - await runTest(43, 3, 43); -}); - -test("Model cache can be refreshed", async () => { - await runTest(42, 1); - // Tag does not exist - act(() => refreshProvideReactCache("foo")); - await runTest(42, 1); - // Tag exist - act(() => refreshProvideReactCache("test/get/42")); - await runTest(42, 2); - // Tag exist - act(() => refreshProvideReactCache("test/**/*")); - await runTest(42, 3); -}); - -test("Model cache refreshes all resources matching the tag", async () => { - render( - <> - - - , - { wrapper: TestWrapper }, - ); - expect(await screen.findByText(42)).toBeInTheDocument(); - expect(await screen.findByText(43)).toBeInTheDocument(); - expect(simulatedDataLoad).toHaveBeenCalledTimes(2); - - act(() => refreshProvideReactCache("test/**/*")); - await waitFor(() => expect(simulatedDataLoad).toHaveBeenCalledTimes(4)); -}); - -test("Model cache can be refreshed after its resource was recreated", async () => { - await runTest(42, 1); - asyncResourceStore.clear(); - act(() => refreshProvideReactCache("test/get/42")); - await runTest(42, 2); - act(() => refreshProvideReactCache("test/get/42")); - await runTest(42, 3); -}); - -test("Model cache releases tags without any existing resource", async () => { - const releaseBy = jest.spyOn(Store.prototype, "releaseBy"); - - await runTest(42, 1); - act(() => refreshProvideReactCache("test/get/42")); - expect(releaseBy).not.toHaveBeenCalled(); - - asyncResourceStore.clear(); - act(() => refreshProvideReactCache("test/get/42")); - expect(releaseBy).toHaveBeenCalledTimes(1); - - const isReleased = releaseBy.mock.calls[0]![0]; - expect(isReleased(new Set())).toBe(true); - expect(isReleased(new Set(["id"]))).toBe(false); - - releaseBy.mockRestore(); -}); - -test("Model cache can be refreshed with react-use-promise before 4.1", async () => { - await runTest(42, 1); - asyncResourceStore.getAll().forEach((resource) => { - Object.assign(resource, { meta: undefined }); - }); - act(() => refreshProvideReactCache("test/get/42")); - await runTest(42, 2); -}); diff --git a/packages/models/src/react/provideReact.ts b/packages/models/src/react/provideReact.ts deleted file mode 100644 index 31f6be85..00000000 --- a/packages/models/src/react/provideReact.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { AsyncResource, reactUsePromise } from "./reactUsePromise.js"; -import { AsyncReturnType } from "type-fest"; -import { hash } from "object-code"; -import { reactProvisionContext } from "./reactProvisionContext.js"; -import { joinedId } from "../lib/joinedId.js"; - -type AsyncFn = (...args: any[]) => Promise; - -type ReactProvisionDep = string | number; -type LazyReactProvisionDep = () => ReactProvisionDep; -type ReactProvisionDeps = Array; - -export const provideReact = ( - loader: T, - dependencies: ReactProvisionDeps = [], -) => { - type P = Parameters; - const loaderHash = hash(loader); - let cachedProvisionId: string | undefined; - - const getAsyncResource = (params: P) => { - const provisionId = - cachedProvisionId ?? - joinedId( - loaderHash, - ...dependencies - .map((d) => (typeof d === "function" ? d() : d)) - .map((d) => hash(d)), - ); - - cachedProvisionId = provisionId; - - const contextId = joinedId(provisionId, hash(params)); - - const loaderWithContext = reactProvisionContext.bind( - { - id: contextId, - }, - loader, - ); - - return reactUsePromise.getAsyncResource(loaderWithContext, params, { - loaderId: provisionId, - tags: [contextId], - }); - }; - - return Object.assign(loader, { - asResource: (...params: P) => getAsyncResource(params), - use: (...params: P) => getAsyncResource(params).use(), - }) as AsyncResourceVariant; -}; - -export type AsyncResourceVariant = T & { - asResource: (...params: Parameters) => AsyncResource>; - use: (...params: Parameters) => AsyncReturnType; -}; diff --git a/packages/models/src/react/reactProvisionContext.ts b/packages/models/src/react/reactProvisionContext.ts deleted file mode 100644 index b9e65385..00000000 --- a/packages/models/src/react/reactProvisionContext.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { createCascade } from "context"; - -export const reactProvisionContext = createCascade<{ - id: string; -}>(); diff --git a/packages/models/src/react/reactUsePromise.ts b/packages/models/src/react/reactUsePromise.ts deleted file mode 100644 index 187b8df3..00000000 --- a/packages/models/src/react/reactUsePromise.ts +++ /dev/null @@ -1,31 +0,0 @@ -export type ReactUsePromiseModule = - typeof import("@mittwald/react-use-promise"); - -export type { - AsyncResource, - getAsyncResource, -} from "@mittwald/react-use-promise"; - -let module: ReactUsePromiseModule | undefined = undefined; - -/** @internal */ -export const reactUsePromise = new Proxy( - {} as ReactUsePromiseModule, - { - get: (_, prop) => { - if (module === undefined) { - // @todo Provide better error message - throw new Error("ModelProvider not found"); - } - - if (prop in module) { - return module[prop as keyof typeof module]; - } - }, - }, -); - -/** @internal */ -export const setModule = (theModule: ReactUsePromiseModule): void => { - module = theModule; -}; diff --git a/packages/models/src/relocation/RelocationRequest/RelocationRequest.test.ts b/packages/models/src/relocation/RelocationRequest/RelocationRequest.test.ts new file mode 100644 index 00000000..4e558136 --- /dev/null +++ b/packages/models/src/relocation/RelocationRequest/RelocationRequest.test.ts @@ -0,0 +1,274 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; + +import type { + RelocationRequestData, + RelocationMailInbox, + RelocationDomain, +} from "./types.js"; + +import { buildProjectData } from "../../testing/builders/buildProjectData.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { + calculateRelocationPrices, + RelocationRequest, +} from "./RelocationRequest.js"; + +afterEach(resetBehaviors); + +type RelocationRequestDataOverrides = { + loginData?: Partial; + contact?: Partial; + addOns?: Partial; + target?: Partial; +} & Partial< + Omit +>; + +const buildRelocationRequestData = ( + overrides: RelocationRequestDataOverrides = {}, +): RelocationRequestData => { + const { loginData, contact, addOns, target, ...rootOverrides } = overrides; + + return { + loginData: { + loginUrl: "https://login", + allowPasswordChange: true, + providerName: "Prov", + password: "pw", + userName: "u", + ...loginData, + }, + contact: { + email: "a@b.de", + firstName: "A", + lastName: "B", + ...contact, + }, + target: { + targetMode: "project", + id: "project-id", + ...target, + }, + addOns: { + dataComparison: "default", + ...addOns, + }, + websiteToRelocate: "https://old.example.com", + articleType: "cms-hosting", + userId: "user-1", + ...rootOverrides, + }; +}; + +const domains = [{}, {}] as RelocationDomain[]; +const emailInboxes = [{}, {}, {}] as RelocationMailInbox[]; + +describe("calculateRelocationPrices", () => { + test("calculates the base article price", () => { + const prices = calculateRelocationPrices(buildRelocationRequestData()); + + expect(prices.positions).toHaveLength(1); + expect(prices.positions[0]?.name).toBe("cms-hosting"); + expect(prices.positions[0]?.price).toBe(150); + expect(prices.total).toBe(150); + }); + + test("calculates the onlineshop express article price", () => { + const prices = calculateRelocationPrices( + buildRelocationRequestData({ articleType: "onlineshop-express" }), + ); + + expect(prices.positions[0]?.price).toBe(439); + expect(prices.total).toBe(439); + }); + + test("adds an additional data comparison", () => { + const prices = calculateRelocationPrices( + buildRelocationRequestData({ + addOns: { dataComparison: "additionalComparison" }, + }), + ); + + expect(prices.positions).toContainEqual({ + name: "additional-data-comparison", + price: 50, + }); + expect(prices.total).toBe(200); + }); + + test("omits the additional data comparison for the default option", () => { + const prices = calculateRelocationPrices(buildRelocationRequestData()); + + expect(prices.positions).not.toContainEqual( + expect.objectContaining({ name: "additional-data-comparison" }), + ); + }); + + test("adds domain transfers", () => { + const prices = calculateRelocationPrices( + buildRelocationRequestData({ addOns: { domains } }), + ); + + expect(prices.positions).toContainEqual({ + name: "domain-transfer", + unitPrice: 9, + quantity: 2, + price: 18, + }); + expect(prices.total).toBe(168); + }); + + test("omits domain transfers when domains are undefined", () => { + const prices = calculateRelocationPrices( + buildRelocationRequestData({ addOns: { domains: undefined } }), + ); + + expect(prices.positions).not.toContainEqual( + expect.objectContaining({ name: "domain-transfer" }), + ); + }); + + test("omits domain transfers when domains are empty", () => { + const prices = calculateRelocationPrices( + buildRelocationRequestData({ addOns: { domains: [] } }), + ); + + expect(prices.positions).not.toContainEqual( + expect.objectContaining({ name: "domain-transfer" }), + ); + }); + + test("adds email inbox transfers", () => { + const prices = calculateRelocationPrices( + buildRelocationRequestData({ addOns: { emailInboxes } }), + ); + + expect(prices.positions).toContainEqual({ + name: "email-inbox-transfer", + unitPrice: 9, + quantity: 3, + price: 27, + }); + }); + + test("omits email inbox transfers when inboxes are undefined", () => { + const prices = calculateRelocationPrices( + buildRelocationRequestData({ addOns: { emailInboxes: undefined } }), + ); + + expect(prices.positions).not.toContainEqual( + expect.objectContaining({ name: "email-inbox-transfer" }), + ); + }); + + test("omits email inbox transfers when inboxes are empty", () => { + const prices = calculateRelocationPrices( + buildRelocationRequestData({ addOns: { emailInboxes: [] } }), + ); + + expect(prices.positions).not.toContainEqual( + expect.objectContaining({ name: "email-inbox-transfer" }), + ); + }); + + test("calculates all relocation prices together", () => { + const prices = calculateRelocationPrices( + buildRelocationRequestData({ + addOns: { + dataComparison: "additionalComparison", + emailInboxes, + domains, + }, + }), + ); + + expect(prices.total).toBe(245); + expect(prices.positions).toHaveLength(4); + }); +}); + +describe("RelocationRequest.create", () => { + test("delegates mapped project data to the relocation behavior", async () => { + const create = vi.fn().mockResolvedValue(undefined); + installBehaviors({ + project: { + find: vi.fn().mockResolvedValue( + buildProjectData({ + customerId: "cust-9", + id: "project-id", + }), + ), + }, + relocation: { create }, + }); + + await RelocationRequest.create( + buildRelocationRequestData({ + target: { targetMode: "project", id: "project-id" }, + articleType: "cms-hosting", + }), + ); + + expect(create).toHaveBeenCalledOnce(); + expect(create).toHaveBeenCalledWith( + expect.objectContaining({ + target: { + projectName: "project-id", + organisation: "cust-9", + product: "Projekt", + system: "mstudio", + }, + prices: expect.objectContaining({ total: 150 }), + }), + ); + }); + + test("maps absent optional data to undefined", async () => { + const create = vi.fn().mockResolvedValue(undefined); + installBehaviors({ + project: { + find: vi.fn().mockResolvedValue(buildProjectData()), + }, + relocation: { create }, + }); + + await RelocationRequest.create(buildRelocationRequestData()); + + expect(create).toHaveBeenCalledWith( + expect.objectContaining({ + emailInboxes: undefined, + domains: undefined, + notes: undefined, + }), + ); + }); + + test.each([ + ["default", "default"], + ["additionalComparison", "additionalCompare"], + ] as const)( + "maps the %s data comparison option", + async (dataComparison, expectedDataCompare) => { + const create = vi.fn().mockResolvedValue(undefined); + installBehaviors({ + project: { + find: vi.fn().mockResolvedValue(buildProjectData()), + }, + relocation: { create }, + }); + + await RelocationRequest.create( + buildRelocationRequestData({ addOns: { dataComparison } }), + ); + + expect(create).toHaveBeenCalledWith( + expect.objectContaining({ + additionalServices: { dataCompare: expectedDataCompare }, + }), + ); + }, + ); +}); diff --git a/packages/models/src/relocation/RelocationRequest/RelocationRequest.ts b/packages/models/src/relocation/RelocationRequest/RelocationRequest.ts new file mode 100644 index 00000000..eb9737f8 --- /dev/null +++ b/packages/models/src/relocation/RelocationRequest/RelocationRequest.ts @@ -0,0 +1,124 @@ +import type { + RelocationRequestApiData, + RelocationRequestData, +} from "./types.js"; + +import { Project } from "../../project/index.js"; +import { config } from "../../config/index.js"; +import { Server } from "../../server/index.js"; +import { + emailInboxTransferPricePerInbox, + domainTransferPricePerDomain, + additionalDataComparePrice, + getArticleByName, +} from "./utils/articles.js"; + +export interface RelocationPricePosition { + unitPrice?: number; + quantity?: number; + price: number; + name: string; +} + +export interface RelocationPrices { + positions: RelocationPricePosition[]; + total: number; +} + +export const calculateRelocationPrices = ( + values: RelocationRequestData, +): RelocationPrices => { + const positions: RelocationPricePosition[] = []; + + const article = getArticleByName(values.articleType); + positions.push({ + price: article.price, + name: article.name, + }); + + if (values.addOns.dataComparison === "additionalComparison") { + positions.push({ + name: "additional-data-comparison", + price: additionalDataComparePrice, + }); + } + + const domainCount = values.addOns.domains?.length ?? 0; + if (domainCount > 0) { + positions.push({ + price: domainCount * domainTransferPricePerDomain, + unitPrice: domainTransferPricePerDomain, + name: "domain-transfer", + quantity: domainCount, + }); + } + + const inboxCount = values.addOns.emailInboxes?.length ?? 0; + if (inboxCount > 0) { + positions.push({ + price: inboxCount * emailInboxTransferPricePerInbox, + unitPrice: emailInboxTransferPricePerInbox, + name: "email-inbox-transfer", + quantity: inboxCount, + }); + } + + const total = positions.reduce((sum, p) => sum + p.price, 0); + + return { positions, total }; +}; + +export class RelocationRequest { + public static async create(values: RelocationRequestData): Promise { + const data = await RelocationRequest.mapFormToRequestData(values); + await config.behaviors.relocation.create(data); + } + + private static async mapFormToRequestData( + values: RelocationRequestData, + ): Promise { + const prices = calculateRelocationPrices(values); + const customerId = + values.target.targetMode === "server" + ? (await Server.ofId(values.target.id).getCommon()).customer.id + : (await Project.ofId(values.target.id).getCommon()).customer.id; + + return { + target: { + product: + values.target.targetMode === "server" + ? "vServer / Dedicated Server" + : "Projekt", + projectName: values.target.id, + organisation: customerId, + system: "mstudio", + }, + provider: { + sourceAccount: values.websiteToRelocate, + loginUrl: values.loginData.loginUrl, + name: values.loginData.providerName, + password: values.loginData.password, + userName: values.loginData.userName, + }, + contact: { + phoneNumber: values.contact.phoneNumber, + firstName: values.contact.firstName, + lastName: values.contact.lastName, + email: values.contact.email, + }, + additionalServices: { + dataCompare: + values.addOns.dataComparison === "additionalComparison" + ? "additionalCompare" + : "default", + }, + allowPasswordChange: values.loginData.allowPasswordChange, + emailInboxes: values.addOns.emailInboxes, + articleType: values.articleType, + domains: values.addOns.domains, + notes: values.contact.message, + userId: values.userId, + prices, + }; + } +} diff --git a/packages/models/src/relocation/RelocationRequest/behaviors/api.ts b/packages/models/src/relocation/RelocationRequest/behaviors/api.ts new file mode 100644 index 00000000..8aa8b3a5 --- /dev/null +++ b/packages/models/src/relocation/RelocationRequest/behaviors/api.ts @@ -0,0 +1,18 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { RelocationRequestApiData } from "../types.js"; +import type { RelocationBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; + +export const apiRelocationBehaviors = ( + client: MittwaldAPIV2Client, +): RelocationBehaviors => ({ + create: async (data: RelocationRequestApiData) => { + const response = await client.relocation.createRelocation({ + data: data, + }); + + validateResponse(response, 204); + }, +}); diff --git a/packages/models/src/relocation/RelocationRequest/behaviors/index.ts b/packages/models/src/relocation/RelocationRequest/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/relocation/RelocationRequest/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/relocation/RelocationRequest/behaviors/types.ts b/packages/models/src/relocation/RelocationRequest/behaviors/types.ts new file mode 100644 index 00000000..d99fe765 --- /dev/null +++ b/packages/models/src/relocation/RelocationRequest/behaviors/types.ts @@ -0,0 +1,5 @@ +import type { RelocationRequestApiData } from "../types.js"; + +export interface RelocationBehaviors { + create: (data: RelocationRequestApiData) => Promise; +} diff --git a/packages/models/src/relocation/RelocationRequest/index.ts b/packages/models/src/relocation/RelocationRequest/index.ts new file mode 100644 index 00000000..d1a260c4 --- /dev/null +++ b/packages/models/src/relocation/RelocationRequest/index.ts @@ -0,0 +1,3 @@ +export * from "./RelocationRequest.js"; +export * from "./types.js"; +export * from "./utils/articles.js"; diff --git a/packages/models/src/relocation/RelocationRequest/types.ts b/packages/models/src/relocation/RelocationRequest/types.ts new file mode 100644 index 00000000..23aa8c92 --- /dev/null +++ b/packages/models/src/relocation/RelocationRequest/types.ts @@ -0,0 +1,37 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type RelocationRequestApiData = + MittwaldAPIV2.Operations.RelocationCreateRelocation.RequestData; +export type RelocationDomain = MittwaldAPIV2.Components.Schemas.DirectusDomain; +export type RelocationMailInbox = + MittwaldAPIV2.Components.Schemas.DirectusEmailInbox; + +export interface RelocationRequestData { + addOns: { + dataComparison: "additionalComparison" | "default"; + emailInboxes?: RelocationMailInbox[]; + domains?: RelocationDomain[]; + }; + loginData: { + allowPasswordChange: boolean; + providerName: string; + loginUrl: string; + password: string; + userName: string; + }; + contact: { + phoneNumber?: string; + firstName: string; + lastName: string; + message?: string; + email: string; + }; + articleType: + "cms-hosting-express" | "onlineshop-express" | "cms-hosting" | "onlineshop"; + target: { + targetMode: "project" | "server"; + id: string; + }; + websiteToRelocate: string; + userId: string; +} diff --git a/packages/models/src/relocation/RelocationRequest/utils/articles.ts b/packages/models/src/relocation/RelocationRequest/utils/articles.ts new file mode 100644 index 00000000..31b81dbe --- /dev/null +++ b/packages/models/src/relocation/RelocationRequest/utils/articles.ts @@ -0,0 +1,62 @@ +export type ArticleNames = + "cms-hosting-express" | "onlineshop-express" | "cms-hosting" | "onlineshop"; + +interface RelocationArticle { + timeRange: { + min: number; + max: number; + }; + name: ArticleNames; + price: number; +} + +const cmsHosting: RelocationArticle = { + timeRange: { + max: 10, + min: 5, + }, + name: "cms-hosting", + price: 150, +}; + +const cmsHostingExpress: RelocationArticle = { + timeRange: { + min: 2, + max: 3, + }, + name: "cms-hosting-express", + price: 299, +}; + +const onlineshop: RelocationArticle = { + timeRange: { + min: 10, + max: 14, + }, + name: "onlineshop", + price: 250, +}; + +const onlineshopExpress: RelocationArticle = { + timeRange: { + min: 2, + max: 3, + }, + name: "onlineshop-express", + price: 439, +}; + +export const relocationArticles = [ + cmsHosting, + onlineshop, + cmsHostingExpress, + onlineshopExpress, +] as const; + +export const additionalDataComparePrice = 50; +export const domainTransferPricePerDomain = 9; +export const emailInboxTransferPricePerInbox = 9; + +export const getArticleByName = (name: ArticleNames): RelocationArticle => { + return relocationArticles.find((article) => article.name === name)!; +}; diff --git a/packages/models/src/relocation/index.ts b/packages/models/src/relocation/index.ts new file mode 100644 index 00000000..955d4394 --- /dev/null +++ b/packages/models/src/relocation/index.ts @@ -0,0 +1 @@ +export * from "./RelocationRequest/index.js"; diff --git a/packages/models/src/server/Server/Server.test.ts b/packages/models/src/server/Server/Server.test.ts new file mode 100644 index 00000000..cccf28c6 --- /dev/null +++ b/packages/models/src/server/Server/Server.test.ts @@ -0,0 +1,277 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { ListQueryModel, ReferenceModel } from "../../base/index.js"; +import { config } from "../../config/config.js"; +import { + buildServerListItemData, + installBehaviors, + resetBehaviors, +} from "../../testing/index.js"; +import { + ServerListQuery, + ServerDetailed, + ServerListItem, + ServerCommon, + ServerList, + Server, +} from "./Server.js"; + +afterEach(resetBehaviors); + +describe("Server list query", () => { + test("applies the default pagination limit", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildServerListItemData({ id: "s-1" })], + totalCount: 1, + }); + installBehaviors({ server: { list } }); + + const result = await Server.query().execute(); + + expect(result).toBeInstanceOf(ServerList); + expect(result.items).toHaveLength(1); + expect(result.items[0]).toBeInstanceOf(ServerListItem); + expect(result.totalCount).toBe(1); + expect(list).toHaveBeenCalledWith( + expect.objectContaining({ limit: config.defaultPaginationLimit }), + ); + }); + + test("uses an explicit pagination limit instead of the default", async () => { + const list = vi.fn().mockResolvedValue({ totalCount: 0, items: [] }); + installBehaviors({ server: { list } }); + + await Server.query({ limit: 5 }).execute(); + + expect(5).not.toBe(config.defaultPaginationLimit); + expect(list).toHaveBeenCalledWith(expect.objectContaining({ limit: 5 })); + }); + + test("materializes behavior items and total count", async () => { + const items = [ + buildServerListItemData({ id: "s-1" }), + buildServerListItemData({ id: "s-2" }), + ]; + const list = vi.fn().mockResolvedValue({ totalCount: 7, items }); + installBehaviors({ server: { list } }); + + const result = await Server.query({ limit: 2 }).execute(); + + expect(result.items).toHaveLength(2); + expect(result.items).toEqual([ + expect.objectContaining({ id: "s-1" }), + expect.objectContaining({ id: "s-2" }), + ]); + expect(result.items.every((item) => item instanceof ServerListItem)).toBe( + true, + ); + expect(result.totalCount).toBe(7); + }); +}); + +describe("Server ghostmaker identity", () => { + // Regression net for the planned polytype-to-mixin migration (ADR-0004). + test("preserves the item composition chain", () => { + const item = new ServerListItem(buildServerListItemData()); + + expect(item).toBeInstanceOf(ServerListItem); + expect(item).toBeInstanceOf(ServerCommon); + expect(item).toBeInstanceOf(Server); + expect(item).toBeInstanceOf(ReferenceModel); + expect(item.data).toBeDefined(); + }); + + test("preserves the list query composition chain", async () => { + const list = vi.fn().mockResolvedValue({ + items: [buildServerListItemData()], + totalCount: 1, + }); + installBehaviors({ server: { list } }); + + const result = await Server.query().execute(); + + expect(result).toBeInstanceOf(ServerList); + expect(result).toBeInstanceOf(ServerListQuery); + expect(result).toBeInstanceOf(ListQueryModel); + expect(result.items).toBeDefined(); + }); +}); + +describe("Server detail lookup", () => { + test("find delegates to the behavior and returns a detailed server", async () => { + const find = vi + .fn() + .mockResolvedValue(buildServerListItemData({ id: "s-1" })); + installBehaviors({ server: { find } }); + + const result = await Server.find("s-1"); + + expect(find).toHaveBeenCalledWith("s-1", undefined); + expect(result).toBeInstanceOf(ServerDetailed); + expect(result?.id).toBe("s-1"); + }); + + test("find returns undefined when the server is missing", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ server: { find } }); + + await expect(Server.find("missing")).resolves.toBeUndefined(); + expect(find).toHaveBeenCalledWith("missing", undefined); + }); + + test("get returns a detailed server", async () => { + const find = vi + .fn() + .mockResolvedValue(buildServerListItemData({ id: "s-2" })); + installBehaviors({ server: { find } }); + + const result = await Server.get("s-2"); + + expect(result).toBeInstanceOf(ServerDetailed); + expect(result.id).toBe("s-2"); + }); + + test("get rejects with ObjectNotFoundError when the server is missing", async () => { + installBehaviors({ + server: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(Server.get("missing")).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("findDetailed and getDetailed delegate with the reference id", async () => { + const find = vi + .fn() + .mockResolvedValue(buildServerListItemData({ id: "s-3" })); + installBehaviors({ server: { find } }); + const server = Server.ofId("s-3"); + + await expect(server.findDetailed()).resolves.toBeInstanceOf(ServerDetailed); + await expect(server.getDetailed()).resolves.toBeInstanceOf(ServerDetailed); + expect(find).toHaveBeenNthCalledWith(1, "s-3", undefined); + expect(find).toHaveBeenNthCalledWith(2, "s-3", undefined); + }); + + test("findCommon and getCommon reuse an already common instance without calling the behavior", async () => { + const find = vi.fn().mockResolvedValue(buildServerListItemData()); + installBehaviors({ server: { find } }); + const item = new ServerListItem(buildServerListItemData({ id: "s-4" })); + + await expect(item.findCommon()).resolves.toBe(item); + await expect(item.getCommon()).resolves.toBe(item); + expect(find).not.toHaveBeenCalled(); + }); + + test("findCommon delegates to the detailed lookup for a bare reference", async () => { + const find = vi + .fn() + .mockResolvedValue(buildServerListItemData({ id: "s-5" })); + installBehaviors({ server: { find } }); + + const result = await Server.ofId("s-5").findCommon(); + + expect(result).toBeInstanceOf(ServerDetailed); + expect(result).toBeInstanceOf(ServerCommon); + expect(find).toHaveBeenCalledWith("s-5", undefined); + }); + + test("getCommon delegates to the detailed lookup for a bare reference", async () => { + const find = vi + .fn() + .mockResolvedValue(buildServerListItemData({ id: "s-6" })); + installBehaviors({ server: { find } }); + + const result = await Server.ofId("s-6").getCommon(); + + expect(result).toBeInstanceOf(ServerDetailed); + expect(result.id).toBe("s-6"); + }); + + test("findCommon resolves undefined for a missing bare reference", async () => { + const find = vi.fn().mockResolvedValue(undefined); + installBehaviors({ server: { find } }); + + await expect(Server.ofId("missing").findCommon()).resolves.toBeUndefined(); + }); + + test("getCommon rejects with ObjectNotFoundError for a missing bare reference", async () => { + installBehaviors({ + server: { find: vi.fn().mockResolvedValue(undefined) }, + }); + + await expect(Server.ofId("missing").getCommon()).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); +}); + +describe("Server aggregate metadata", () => { + test("pins the domain and aggregate identity", () => { + expect(Server.aggregateMetaData).toMatchObject({ + aggregate: "placementgroup", + domain: "project", + }); + }); + + test("findAggregate materializes metadata only for an id", () => { + expect(Server.findAggregate("s-1")).toEqual({ + id: "s-1", + ...Server.aggregateMetaData, + }); + expect(Server.findAggregate(undefined)).toBeUndefined(); + }); +}); + +describe("Server optional and derived properties", () => { + test("omits the avatar when no image reference is present", () => { + const item = new ServerListItem( + buildServerListItemData({ imageRefId: undefined }), + ); + + expect(item.avatar).toBeUndefined(); + }); + + test("materializes the avatar file from the image reference", () => { + const item = new ServerListItem( + buildServerListItemData({ imageRefId: "file-1" }), + ); + + expect(item.avatar?.id).toBe("file-1"); + }); + + test("leaves cluster name and disabled reason undefined when absent", () => { + const item = new ServerListItem( + buildServerListItemData({ + disabledReason: undefined, + clusterName: undefined, + }), + ); + + expect(item.clusterName).toBeUndefined(); + expect(item.disabledReason).toBeUndefined(); + }); + + test("derives numeric capacity from machine type and storage strings", () => { + const item = new ServerListItem( + buildServerListItemData({ + machineType: { name: "big-machine", memory: "8Gi", cpu: "4" }, + storage: "50Gi", + }), + ); + + expect(item.vcpu).toBe(4); + expect(item.ram).toBe(8); + expect(item.storage).toBe(50); + }); +}); diff --git a/packages/models/src/server/Server/Server.ts b/packages/models/src/server/Server/Server.ts index a42bd9b2..c48a2b00 100644 --- a/packages/models/src/server/Server/Server.ts +++ b/packages/models/src/server/Server/Server.ts @@ -1,122 +1,217 @@ -import { ReferenceModel } from "../../base/ReferenceModel.js"; -import { - ServerData, - ServerListItemData, - ServerListQueryData, +import type { AxiosRequestConfig } from "axios"; + +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import invariant from "tiny-invariant"; +import { DateTime } from "luxon"; + +import type { ProjectListQuery as ProjectListQueryType } from "../../project/index.js"; +import type { ServerListQueryModelData, + ServerDisableReason, + ServerListItemData, + ServerStatus, + ServerData, } from "./types.js"; -import { config } from "../../config/config.js"; -import { classes } from "polytype"; -import { DataModel } from "../../base/DataModel.js"; -import assertObjectFound from "../../base/assertObjectFound.js"; -import { Project, ProjectListQuery } from "../../project/index.js"; -import { FirstParameter, ParamsExceptFirst } from "../../lib/types.js"; + +import { ServerAvatarAccessTokenProvider } from "./ServerAvatarAccessTokenProvider.js"; import { - AsyncResourceVariant, - provideReact, -} from "../../react/provideReact.js"; -import { ListQueryModel } from "../../base/ListQueryModel.js"; -import { ListDataModel } from "../../base/ListDataModel.js"; + type FileAccessTokenProvider, + type DomFile, +} from "../../file/index.js"; +import { ServerUsageMetrics, StorageMetrics } from "../../monitoring/index.js"; +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { Customer } from "../../customer/Customer/Customer.js"; +import { ProjectListQuery } from "../../project/internal.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { File } from "../../file/File/internal.js"; +import { Contract } from "../../contract/index.js"; +import { config } from "../../config/index.js"; +import { Order } from "../../order/index.js"; +import { + ListQueryModel, + ReferenceModel, + WithListData, + extractId, + WithData, +} from "../../base/index.js"; +@GhostMakerModel({ + name: "Server", +}) export class Server extends ReferenceModel { - public readonly projects: ProjectListQuery; + public static aggregateMetaData = new AggregateMetaData( + "project", + "placementgroup", + ); + public readonly fileAccessTokenProvider: FileAccessTokenProvider; + + public readonly projects: ProjectListQueryType; public constructor(id: string) { super(id); + this.fileAccessTokenProvider = new ServerAvatarAccessTokenProvider(this); this.projects = new ProjectListQuery({ server: this, }); } - public static ofId(id: string): Server { - return new Server(id); + public static async find(id: string, options?: AxiosRequestConfig) { + const data = await config.behaviors.server.find(id, options); + + if (data) { + return new ServerDetailed(data); + } } - public static find = provideReact( - async (id: string): Promise => { - const data = await config.behaviors.server.find(id); + public static findAggregate(serverId?: string) { + return serverId ? { id: serverId, ...Server.aggregateMetaData } : undefined; + } - if (data !== undefined) { - return new ServerDetailed(data); - } - }, - ); + public static async get(id: string, options?: AxiosRequestConfig) { + const server = await Server.find(id, options); + assertObjectFound(server, Server, id); + return server; + } - public static get = provideReact( - async (id: string): Promise => { - const server = await this.find(id); - assertObjectFound(server, this, id); - return server; - }, - ); + public static ofId(id: string) { + return new Server(id); + } public static query(query: ServerListQueryModelData = {}) { return new ServerListQuery(query); } - /** @deprecated: use query() or customer.servers */ - public static list = provideReact( - async ( - query: ServerListQueryData = {}, - ): Promise> => { - return new ServerListQuery(query).execute().then((r) => r.items); - }, - ); + public async findCommon( + options?: AxiosRequestConfig, + ): Promise { + return this instanceof ServerCommon ? this : this.findDetailed(options); + } - public async createProject( - ...parameters: ParamsExceptFirst - ): ReturnType { - return Project.create(this.id, ...parameters); - } - - /** @deprecated Use Server.projects property */ - public listProjects = provideReact( - async ( - query: Omit, "serverId"> = {}, - ): ReturnType => { - return Project.list({ - ...query, - serverId: this.id, - }); - }, - ); + public async findDetailed( + options?: AxiosRequestConfig, + ): Promise { + return Server.find(this.id, options); + } + + public async findStorageMetrics() { + return await StorageMetrics.find(this.id, "server"); + } + + public async getAvatarUploadRules() { + return File.getUploadRules("avatar"); + } + + public async getCommon(options?: AxiosRequestConfig): Promise { + return this instanceof ServerCommon ? this : this.getDetailed(options); + } + + public async getContract() { + return await Contract.getByServer(this.id); + } + + public async getDetailed( + options?: AxiosRequestConfig, + ): Promise { + return Server.get(this.id, options); + } + + public async removeAvatar() { + await config.behaviors.server.removeAvatar(this.id); + } + + public async requestAvatarUpload(): Promise { + const response = await config.behaviors.server.createAvatarUploadToken( + this.id, + ); + + return response.token; + } + + public async updateDescription(description: string) { + await config.behaviors.server.updateDescription(this.id, description); + } - public getDetailed = provideReact( - () => Server.get(this.id), - [this.id], - ) as AsyncResourceVariant<() => Promise>; + public async updatePlan(data: { machineType?: string; storage: number }) { + const { machineType, storage } = data; + + invariant(!!machineType, "Machine type is required for plan change"); + + const contract = await this.getContract(); + + await Order.changePlan({ + tariffChangeData: { + machineType: machineType, + diskspaceInGiB: storage, + contractId: contract.id, + }, + tariffChangeType: "server", + }); + } - public findDetailed = provideReact( - () => Server.find(this.id), - [this.id], - ) as AsyncResourceVariant<() => Promise>; + public async updateStorageNotificationThreshold(threshold?: number) { + await config.behaviors.server.updateStorageNotificationThreshold( + this.id, + threshold, + ); + } + + public async uploadAvatar(file: DomFile) { + await File.upload(file, this.fileAccessTokenProvider); + } } -// Common class for future extension -class ServerCommon extends classes( - DataModel, +export class ServerCommon extends WithData()( Server, ) { + public readonly avatar?: File; + public readonly clusterName: string; + public readonly createdAt: DateTime; + public readonly customer: Customer; + public override readonly data: ServerListItemData | ServerData; + public readonly description: string; + public readonly disabledReason?: ServerDisableReason; + public readonly groupId: string; + public readonly machineType: string; + public readonly ram: number; + public readonly shortId: string; + public readonly status: ServerStatus; + public readonly storage: number; + public readonly vcpu: number; + public constructor(data: ServerListItemData | ServerData) { - super([data], [data.id]); + super(data.id); + this.data = data; + this.customer = Customer.ofId(data.customerId); + this.shortId = data.shortId; + this.groupId = data.groupId; + this.vcpu = parseInt(data.machineType.cpu); + this.ram = parseInt(data.machineType.memory.replace("Gi", "")); + this.storage = parseInt(data.storage.replace("Gi", "")); + this.description = data.description; + this.clusterName = data.clusterName; + this.createdAt = DateTime.fromISO(data.createdAt); + this.avatar = data.imageRefId ? File.ofId(data.imageRefId) : undefined; + this.machineType = data.machineType.name; + this.status = data.status; + this.disabledReason = data.disabledReason; } } -export class ServerDetailed extends classes( - ServerCommon, - DataModel, -) { +export class ServerDetailed extends ServerCommon { + public override readonly data: ServerData; + public readonly usageMetrics: ServerUsageMetrics; public constructor(data: ServerData) { - super([data], [data]); + super(data); + this.data = data; + this.usageMetrics = ServerUsageMetrics.of(this); } } -export class ServerListItem extends classes( - ServerCommon, - DataModel, -) { +export class ServerListItem extends ServerCommon { + public override readonly data: ServerListItemData; public constructor(data: ServerListItemData) { - super([data], [data]); + super(data); + this.data = data; } } @@ -125,18 +220,11 @@ export class ServerListQuery extends ListQueryModel { super(query); } - public refine(query: ServerListQueryModelData) { - return new ServerListQuery({ - ...this.query, - ...query, - }); - } - - public execute = provideReact(async () => { + public async execute() { const { customer, ...query } = this.query; - const { items, totalCount } = await config.behaviors.server.list({ + const { totalCount, items } = await config.behaviors.server.list({ limit: config.defaultPaginationLimit, - customerId: customer?.id, + customerId: extractId(customer), ...query, }); @@ -145,30 +233,43 @@ export class ServerListQuery extends ListQueryModel { items.map((d) => new ServerListItem(d)), totalCount, ); - }, [this.queryId]); + } + + public async findLatest() { + const { items } = await this.refine({ + sort: "createdAt", + order: "desc", + limit: 1, + }).execute(); + + return items[0]; + } - public getTotalCount = provideReact(async () => { + public async getTotalCount() { const { totalCount } = await this.refine({ limit: 1 }).execute(); return totalCount; - }, [this.queryId]); + } - public findOneAndOnly = provideReact(async () => { - const { items, totalCount } = await this.refine({ limit: 2 }).execute(); - if (totalCount === 1) { - return items[0]; - } - }, [this.queryId]); + public refine(query: ServerListQueryModelData) { + return new ServerListQuery({ + ...this.query, + ...query, + }); + } } -export class ServerList extends classes( +export class ServerList extends WithListData()( ServerListQuery, - ListDataModel, ) { + public override readonly items: readonly ServerListItem[]; + public override readonly totalCount: number; public constructor( - query: ServerListQueryData, + query: ServerListQueryModelData, servers: ServerListItem[], totalCount: number, ) { - super([query], [servers, totalCount]); + super(query); + this.items = Object.freeze(servers); + this.totalCount = totalCount; } } diff --git a/packages/models/src/server/Server/ServerAvatarAccessTokenProvider.ts b/packages/models/src/server/Server/ServerAvatarAccessTokenProvider.ts new file mode 100644 index 00000000..66ec437a --- /dev/null +++ b/packages/models/src/server/Server/ServerAvatarAccessTokenProvider.ts @@ -0,0 +1,16 @@ +import type { FileAccessTokenProvider } from "../../file/index.js"; +import type { Server } from "./Server.js"; + +import { config } from "../../config/index.js"; + +export class ServerAvatarAccessTokenProvider implements FileAccessTokenProvider { + public readonly server: Server; + + public constructor(server: Server) { + this.server = server; + } + + public createUploadToken() { + return config.behaviors.server.createAvatarUploadToken(this.server.id); + } +} diff --git a/packages/models/src/server/Server/behaviors/api.ts b/packages/models/src/server/Server/behaviors/api.ts index 528723bc..7b954b32 100644 --- a/packages/models/src/server/Server/behaviors/api.ts +++ b/packages/models/src/server/Server/behaviors/api.ts @@ -1,33 +1,77 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { ServerBehaviors } from "./types.js"; + import { - assertStatus, - assertOneOfStatus, - MittwaldAPIV2Client, - extractTotalCountHeader, -} from "@mittwald/api-client"; -import { ServerBehaviors } from "./types.js"; + withAxiosRequestConfig, + resolveTotalCount, +} from "../../../base/index.js"; +import { validateResponse } from "../../../base/api/validateResponse.js"; export const apiServerBehaviors = ( client: MittwaldAPIV2Client, ): ServerBehaviors => ({ - find: async (id) => { - const response = await client.project.getServer({ - serverId: id, + updateStorageNotificationThreshold: async ( + serverId, + thresholdInBytes?: number, + ) => { + const response = await client.project.storagespaceUpdateServerStatistics({ + data: { notificationThresholdInBytes: thresholdInBytes }, + serverId, }); + validateResponse(response, 204); + }, + + find: async (serverId, options) => { + const response = await client.project.getServer( + { + serverId, + }, + withAxiosRequestConfig(options), + ); + if (response.status === 200) { return response.data; } - assertOneOfStatus(response, [403, 404]); + validateResponse(response, [403, 404]); + }, + + createAvatarUploadToken: async (serverId) => { + const response = await client.project.requestServerAvatarUpload({ + serverId, + }); + validateResponse(response, 200); + return { + token: response.data.refId, + rules: response.data.rules, + }; }, list: async (query) => { const response = await client.project.listServers({ queryParameters: query, }); - assertStatus(response, 200); + validateResponse(response, 200); return { + totalCount: resolveTotalCount(response), items: response.data, - totalCount: extractTotalCountHeader(response), }; }, + + updateDescription: async (serverId, description) => { + const response = await client.project.updateServer({ + data: { + description, + }, + serverId, + }); + validateResponse(response, 204); + }, + + removeAvatar: async (serverId) => { + const response = await client.project.deleteServerAvatar({ serverId }); + + validateResponse(response, 204); + }, }); diff --git a/packages/models/src/server/Server/behaviors/types.ts b/packages/models/src/server/Server/behaviors/types.ts index 11a7c7cd..eb126b86 100644 --- a/packages/models/src/server/Server/behaviors/types.ts +++ b/packages/models/src/server/Server/behaviors/types.ts @@ -1,13 +1,31 @@ -import { +import type { AxiosRequestConfig } from "axios"; + +import type { FileUploadTokenData } from "../../../file/index.js"; +import type { QueryResponseData } from "../../../base/index.js"; +import type { + ServerListQueryData, ServerListItemData, ServerData, - ServerListQueryData, } from "../types.js"; -import { QueryResponseData } from "../../../base/index.js"; export interface ServerBehaviors { - find: (id: string) => Promise; + updateStorageNotificationThreshold: ( + projectId: string, + thresholdInBytes?: number, + ) => Promise; + + find: ( + serverId: string, + options?: AxiosRequestConfig, + ) => Promise; + list: ( query?: ServerListQueryData, ) => Promise>; + + updateDescription: (serverId: string, description: string) => Promise; + + createAvatarUploadToken: (serverId: string) => Promise; + + removeAvatar: (serverId: string) => Promise; } diff --git a/packages/models/src/server/Server/types.ts b/packages/models/src/server/Server/types.ts index dd0a4418..c90cea9c 100644 --- a/packages/models/src/server/Server/types.ts +++ b/packages/models/src/server/Server/types.ts @@ -1,5 +1,6 @@ -import { MittwaldAPIV2 } from "@mittwald/api-client"; -import { Customer } from "../../customer/index.js"; +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +import type { Customer } from "../../customer/index.js"; export type ServerListQueryData = MittwaldAPIV2.Paths.V2Servers.Get.Parameters.Query; @@ -8,10 +9,15 @@ export type ServerListQueryModelData = Omit< ServerListQueryData, "customerId" > & { - customer?: Customer; + customer?: Customer | string; }; export type ServerData = MittwaldAPIV2.Operations.ProjectGetServer.ResponseData; export type ServerListItemData = MittwaldAPIV2.Operations.ProjectListServers.ResponseData[number]; + +export type ServerDisableReason = + MittwaldAPIV2.Components.Schemas.ProjectServerDisableReason; + +export type ServerStatus = MittwaldAPIV2.Components.Schemas.ProjectServerStatus; diff --git a/packages/models/src/testing/README.md b/packages/models/src/testing/README.md new file mode 100644 index 00000000..e306e74c --- /dev/null +++ b/packages/models/src/testing/README.md @@ -0,0 +1,71 @@ +# `@mittwald/api-models` test harness + +Utilities for unit-testing models by injecting fake **behaviors** into the +`config.behaviors` registry — the single seam through which every model reaches +the API. Tests exercise model logic (construction from data, derived getters, +guards, delegation) while treating the `api.ts` mapping layer as the boundary +rather than re-testing it. See ADR-0005 for the rationale. + +This code lives here publish-ready; the `@mittwald/api-models/testing` export is +decided later (P0-4). Until then it is imported only via relative paths from +tests. + +## What it gives you + +- `installBehaviors(partial)` — writes partial fake behaviors onto the + registry's Proxy target. Pass only the domains and methods a test touches. + Repeated calls merge onto the domain already installed. +- `resetBehaviors()` — removes every installed behavior, restoring the + registry's fail-fast state (accessing an uninstalled behavior throws the "is + not initialized" error again). +- `buildXData(overrides?)` — typed fixture builders per `*Data` type, with + sensible defaults and shallow overrides. `buildContainerData` is the first + one; add more lazily as tests need them. + +No `MittwaldAPIV2Client` fake, no `vi.mock` — behaviors are the boundary. Tests +run under vitest in the default `node` environment. + +## Per-file isolation + +The `config` object is a module singleton. Reset it after every test so state +cannot leak between tests and test order stays irrelevant. Put this at the top +of every test file that installs behaviors: + +```ts +import { afterEach } from "vitest"; +import { resetBehaviors } from "../testing/index.js"; + +afterEach(resetBehaviors); +``` + +Isolation is wired per file (not via a global setup file) until `models` becomes +its own package with its own vitest config (P0-4). + +## Example + +```ts +import { afterEach, expect, test, vi } from "vitest"; +import { config } from "../config/config.js"; +import { + buildContainerData, + installBehaviors, + resetBehaviors, +} from "../testing/index.js"; + +afterEach(resetBehaviors); + +test("Container.find delegates to the container behavior", async () => { + const find = vi.fn().mockResolvedValue(buildContainerData({ id: "c-1" })); + installBehaviors({ container: { find } }); + + const result = await config.behaviors.container.find("c-1", "s-1"); + + expect(find).toHaveBeenCalledWith("c-1", "s-1"); + expect(result?.id).toBe("c-1"); +}); +``` + +The registry/init contract itself (fail-fast before install → resolves after +`installBehaviors` → fail-fast again after `resetBehaviors`) is covered end to +end in `registryContract.test.ts`, which also serves as the reference for the +`afterEach(resetBehaviors)` pattern. diff --git a/packages/models/src/testing/builders/buildAIApiKeyData.ts b/packages/models/src/testing/builders/buildAIApiKeyData.ts new file mode 100644 index 00000000..c0b1c9be --- /dev/null +++ b/packages/models/src/testing/builders/buildAIApiKeyData.ts @@ -0,0 +1,19 @@ +import type { AIApiKeyData } from "../../ai/types.js"; + +export function buildAIApiKeyData( + overrides?: Partial, +): AIApiKeyData { + return { + rateLimit: { allowedRequestsPerUnit: 300, unit: "minute" }, + tokenUsage: { planLimit: 2_000_000, used: 500_000 }, + profileId: "customer-id", + projectId: "project-id", + key: "secret-key", + planId: "plan-id", + isBlocked: false, + keyId: "key-id", + name: "my key", + models: [], + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildAIModelData.ts b/packages/models/src/testing/builders/buildAIModelData.ts new file mode 100644 index 00000000..04d8e2bc --- /dev/null +++ b/packages/models/src/testing/builders/buildAIModelData.ts @@ -0,0 +1,15 @@ +import type { AIModelData } from "../../ai/AIModel/types.js"; + +export function buildAIModelData( + overrides?: Partial, +): AIModelData { + return { + termsOfServiceLink: "https://tos.example.com/model", + docLink: "https://docs.example.com/model", + displayName: "GPT Test", + name: "gpt-test", + label: "stable", + tokenFactor: 1, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildApiTokenData.ts b/packages/models/src/testing/builders/buildApiTokenData.ts new file mode 100644 index 00000000..df9ed059 --- /dev/null +++ b/packages/models/src/testing/builders/buildApiTokenData.ts @@ -0,0 +1,28 @@ +import type { + ApiTokenListItemData, + ApiTokenData, +} from "../../user/ApiToken/types.js"; + +export function buildApiTokenData( + overrides: Partial = {}, +): ApiTokenData { + return { + createdAt: "2024-01-01T00:00:00.000Z", + apiTokenId: "apitoken-id", + description: "test token", + roles: ["api_read"], + ...overrides, + }; +} + +export function buildApiTokenListItemData( + overrides: Partial = {}, +): ApiTokenListItemData { + return { + createdAt: "2024-01-01T00:00:00.000Z", + apiTokenId: "apitoken-id", + description: "test token", + roles: ["api_read"], + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildAppData.ts b/packages/models/src/testing/builders/buildAppData.ts new file mode 100644 index 00000000..910b2eef --- /dev/null +++ b/packages/models/src/testing/builders/buildAppData.ts @@ -0,0 +1,10 @@ +import type { AppData } from "../../app/App/types.js"; + +export function buildAppData(overrides?: Partial): AppData { + return { + name: "WordPress", + id: "app-id", + tags: [], + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildAppInstallationData.ts b/packages/models/src/testing/builders/buildAppInstallationData.ts new file mode 100644 index 00000000..0fabae67 --- /dev/null +++ b/packages/models/src/testing/builders/buildAppInstallationData.ts @@ -0,0 +1,27 @@ +import type { AppInstallationData } from "../../app/AppInstallation/types.js"; + +export function buildAppInstallationData( + overrides?: Partial, +): AppInstallationData { + return { + appVersion: { desired: "appversion-id" }, + createdAt: "2024-01-01T00:00:00.000Z", + projectDescription: "my project", + appExternalVersion: "6.4.0", + updatePolicy: "patchLevel", + id: "appinstallation-id", + projectId: "project-id", + description: "my site", + updateAvailable: false, + installationPath: "/", + appName: "WordPress", + linkedDatabases: [], + systemSoftware: [], + shortId: "abc123", + appId: "app-id", + disabled: false, + phase: "ready", + userInputs: [], + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildAppLinkedDatabaseData.ts b/packages/models/src/testing/builders/buildAppLinkedDatabaseData.ts new file mode 100644 index 00000000..fd99a6e2 --- /dev/null +++ b/packages/models/src/testing/builders/buildAppLinkedDatabaseData.ts @@ -0,0 +1,12 @@ +import type { AppLinkedDatabaseData } from "../../app/AppLinkedDatabase/types.js"; + +export function buildAppLinkedDatabaseData( + overrides?: Partial, +): AppLinkedDatabaseData { + return { + databaseId: "db-id", + purpose: "primary", + kind: "mysql", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildAppUserInputData.ts b/packages/models/src/testing/builders/buildAppUserInputData.ts new file mode 100644 index 00000000..a63c4dd7 --- /dev/null +++ b/packages/models/src/testing/builders/buildAppUserInputData.ts @@ -0,0 +1,13 @@ +import type { UserInputData } from "../../app/UserInput/types.js"; + +export function buildAppUserInputData( + overrides: Partial = {}, +): UserInputData { + return { + validationSchema: "{}", + dataType: "text", + required: true, + name: "input", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildAppVersionData.ts b/packages/models/src/testing/builders/buildAppVersionData.ts new file mode 100644 index 00000000..ad7e96fe --- /dev/null +++ b/packages/models/src/testing/builders/buildAppVersionData.ts @@ -0,0 +1,17 @@ +import type { AppVersionData } from "../../app/AppVersion/types.js"; + +export function buildAppVersionData( + overrides?: Partial, +): AppVersionData { + return { + systemSoftwareDependencies: [], + docRootUserEditable: false, + externalVersion: "6.4.0", + internalVersion: "6.4.0", + id: "appversion-id", + recommended: true, + appId: "app-id", + docRoot: "/", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildArticleData.ts b/packages/models/src/testing/builders/buildArticleData.ts new file mode 100644 index 00000000..683fa986 --- /dev/null +++ b/packages/models/src/testing/builders/buildArticleData.ts @@ -0,0 +1,83 @@ +import type { + ArticleAttributeData, + ArticleListItemData, + ArticleModifierData, + ArticleTemplateData, + ArticleTagData, + ArticleData, +} from "../../article/Article/types.js"; + +export function buildArticleTemplateData( + overrides: Partial = {}, +): ArticleTemplateData { + return { + isManagedByDomain: false, + type: "miscellaneous", + id: "template-id", + isRecurring: true, + name: "unknown", + ...overrides, + }; +} + +export function buildArticleAttributeData( + overrides: Partial = {}, +): ArticleAttributeData { + return { + key: "attribute-key", + ...overrides, + }; +} + +export function buildArticleTagData( + overrides: Partial = {}, +): ArticleTagData { + return { + id: "tag-id", + ...overrides, + }; +} + +export function buildArticleModifierData( + overrides: Partial = {}, +): ArticleModifierData { + return { + articleId: "modifier-article-id", + maxArticleCount: 1, + ...overrides, + }; +} + +export function buildArticleData( + overrides: Partial = {}, +): ArticleData { + return { + template: buildArticleTemplateData(), + contractDurationInMonth: 1, + articleId: "article-id", + modifierArticles: [], + name: "Test Article", + orderable: "full", + attributes: [], + price: 1000, + tags: [], + ...overrides, + }; +} + +export function buildArticleListItemData( + overrides: Partial = {}, +): ArticleListItemData { + return { + template: buildArticleTemplateData(), + contractDurationInMonth: 1, + articleId: "article-id", + modifierArticles: [], + name: "Test Article", + orderable: "full", + attributes: [], + price: 1000, + tags: [], + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildBackupData.ts b/packages/models/src/testing/builders/buildBackupData.ts new file mode 100644 index 00000000..857757c7 --- /dev/null +++ b/packages/models/src/testing/builders/buildBackupData.ts @@ -0,0 +1,14 @@ +import type { BackupData } from "../../backup/Backup/types.js"; + +export function buildBackupData( + overrides: Partial = {}, +): BackupData { + return { + requestedAt: "2024-01-01T00:00:00.000Z", + projectId: "project-id", + status: "Completed", + deletable: false, + id: "backup-id", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildBackupExportData.ts b/packages/models/src/testing/builders/buildBackupExportData.ts new file mode 100644 index 00000000..c887e54b --- /dev/null +++ b/packages/models/src/testing/builders/buildBackupExportData.ts @@ -0,0 +1,12 @@ +import type { BackupExportData } from "../../backup/Backup/types.js"; + +export function buildBackupExportData( + overrides: Partial = {}, +): BackupExportData { + return { + withPassword: false, + phase: "Completed", + format: "tar.gz", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildBackupScheduleData.ts b/packages/models/src/testing/builders/buildBackupScheduleData.ts new file mode 100644 index 00000000..6d4bb936 --- /dev/null +++ b/packages/models/src/testing/builders/buildBackupScheduleData.ts @@ -0,0 +1,13 @@ +import type { BackupScheduleData } from "../../backup/BackupSchedule/types.js"; + +export function buildBackupScheduleData( + overrides: Partial = {}, +): BackupScheduleData { + return { + id: "backup-schedule-id", + projectId: "project-id", + isSystemBackup: false, + schedule: "0 2 * * *", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildCertificateCheckReplaceResponseData.ts b/packages/models/src/testing/builders/buildCertificateCheckReplaceResponseData.ts new file mode 100644 index 00000000..924aeff7 --- /dev/null +++ b/packages/models/src/testing/builders/buildCertificateCheckReplaceResponseData.ts @@ -0,0 +1,10 @@ +import type { CertificateCheckReplaceResponseData } from "../../certificate/CertificateCheckReplaceResponse/types.js"; + +export function buildCertificateCheckReplaceResponseData( + overrides?: Partial, +): CertificateCheckReplaceResponseData { + return { + isReplaceable: true, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildCertificateContactData.ts b/packages/models/src/testing/builders/buildCertificateContactData.ts new file mode 100644 index 00000000..e2127bc4 --- /dev/null +++ b/packages/models/src/testing/builders/buildCertificateContactData.ts @@ -0,0 +1,14 @@ +import type { CertificateContactData } from "../../certificate/CertificateContact/types.js"; + +export function buildCertificateContactData( + overrides?: Partial, +): CertificateContactData { + return { + organizationalUnit: "Engineering", + state: "North Rhine-Westphalia", + company: "mittwald", + city: "Espelkamp", + country: "DE", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildCertificateData.ts b/packages/models/src/testing/builders/buildCertificateData.ts new file mode 100644 index 00000000..e7674a46 --- /dev/null +++ b/packages/models/src/testing/builders/buildCertificateData.ts @@ -0,0 +1,16 @@ +import type { CertificateData } from "../../certificate/Certificate/types.js"; + +export function buildCertificateData( + overrides?: Partial, +): CertificateData { + return { + dnsNames: ["example.com", "www.example.com"], + certificateRequestId: "certreq-id", + commonName: "example.com", + projectId: "project-id", + certificateType: 2, + isExpired: false, + id: "cert-id", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildCertificateRequestData.ts b/packages/models/src/testing/builders/buildCertificateRequestData.ts new file mode 100644 index 00000000..8c7e2f43 --- /dev/null +++ b/packages/models/src/testing/builders/buildCertificateRequestData.ts @@ -0,0 +1,17 @@ +import type { CertificateRequestData } from "../../certificate/CertificateRequest/types.js"; + +export function buildCertificateRequestData( + overrides?: Partial, +): CertificateRequestData { + return { + createdAt: "2024-01-01T00:00:00.000Z", + commonName: "example.com", + dnsNames: ["example.com"], + projectId: "project-id", + certificateData: {}, + certificateType: 2, + isCompleted: false, + id: "certreq-id", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildCityData.ts b/packages/models/src/testing/builders/buildCityData.ts new file mode 100644 index 00000000..fdce9616 --- /dev/null +++ b/packages/models/src/testing/builders/buildCityData.ts @@ -0,0 +1,12 @@ +import type { CitiesListItemData } from "../../fyndr/City/types.js"; + +export function buildCityData( + overrides?: Partial, +): CitiesListItemData { + return { + postCode: "24103", + country: "DE", + city: "Kiel", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildContactVerificationData.ts b/packages/models/src/testing/builders/buildContactVerificationData.ts new file mode 100644 index 00000000..9d952138 --- /dev/null +++ b/packages/models/src/testing/builders/buildContactVerificationData.ts @@ -0,0 +1,12 @@ +import type { ContactVerificationData } from "../../domain/ContactVerification/types.js"; + +export function buildContactVerificationData( + overrides?: Partial, +): ContactVerificationData { + return { + typeData: { value: "user@example.com", type: "email" }, + status: "pending", + id: "cv-id", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildContainerData.ts b/packages/models/src/testing/builders/buildContainerData.ts new file mode 100644 index 00000000..c251627a --- /dev/null +++ b/packages/models/src/testing/builders/buildContainerData.ts @@ -0,0 +1,20 @@ +import type { ContainerData } from "../../container/Container/types.js"; + +export function buildContainerData( + overrides?: Partial, +): ContainerData { + return { + deployedState: { image: "nginx:latest" }, + pendingState: { image: "nginx:latest" }, + statusSetAt: "2024-01-01T00:00:00.000Z", + description: "test container", + projectId: "project-id", + requiresRecreate: false, + stackId: "stack-id", + id: "container-id", + serviceName: "web", + shortId: "abc123", + status: "running", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildContractArticleData.ts b/packages/models/src/testing/builders/buildContractArticleData.ts new file mode 100644 index 00000000..c3f62547 --- /dev/null +++ b/packages/models/src/testing/builders/buildContractArticleData.ts @@ -0,0 +1,15 @@ +import type { ContractArticleData } from "../../contract/ContractArticle/types.js"; + +export function buildContractArticleData( + overrides?: Partial, +): ContractArticleData { + return { + unitPrice: { currency: "EUR", value: 1000 }, + articleTemplateId: "template-id", + name: "Test Article", + description: "desc", + id: "article-id", + amount: 1, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildContractData.ts b/packages/models/src/testing/builders/buildContractData.ts new file mode 100644 index 00000000..36e760dc --- /dev/null +++ b/packages/models/src/testing/builders/buildContractData.ts @@ -0,0 +1,15 @@ +import type { ContractData } from "../../contract/Contract/types.js"; + +import { buildContractItemData } from "./buildContractItemData.js"; + +export function buildContractData( + overrides?: Partial, +): ContractData { + return { + baseItem: buildContractItemData({ isBaseItem: true }), + contractId: "contract-id", + customerId: "customer-id", + contractNumber: "12345", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildContractItemData.ts b/packages/models/src/testing/builders/buildContractItemData.ts new file mode 100644 index 00000000..cca09cb4 --- /dev/null +++ b/packages/models/src/testing/builders/buildContractItemData.ts @@ -0,0 +1,18 @@ +import type { ContractItemData } from "../../contract/ContractItem/types.js"; + +import { buildContractArticleData } from "./buildContractArticleData.js"; + +export function buildContractItemData( + overrides?: Partial, +): ContractItemData { + return { + totalPrice: { currency: "EUR", value: 1000 }, + articles: [buildContractArticleData()], + description: "Test contract item", + contractPeriod: 12, + isActivated: true, + itemId: "item-id", + isBaseItem: true, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildContractPartnerData.ts b/packages/models/src/testing/builders/buildContractPartnerData.ts new file mode 100644 index 00000000..d63bd948 --- /dev/null +++ b/packages/models/src/testing/builders/buildContractPartnerData.ts @@ -0,0 +1,23 @@ +import type { ContractPartnerData } from "../../customer/ContractPartner/types.js"; + +export function buildContractPartnerData( + overrides?: Partial, +): ContractPartnerData { + return { + address: { + street: "Teststr.", + countryCode: "DE", + houseNumber: "1", + city: "Kiel", + zip: "24103", + }, + phoneNumbers: ["+49 431 123456"], + emailAddress: "ada@example.com", + leitwegId: "04011000-12345-67", + lastName: "Lovelace", + company: "Test GmbH", + salutation: "other", + firstName: "Ada", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildContributorExtensionData.ts b/packages/models/src/testing/builders/buildContributorExtensionData.ts new file mode 100644 index 00000000..051c75df --- /dev/null +++ b/packages/models/src/testing/builders/buildContributorExtensionData.ts @@ -0,0 +1,22 @@ +import type { ContributorExtensionData } from "../../marketplace/ContributorExtension/types.js"; + +export function buildContributorExtensionData( + overrides?: Partial, +): ContributorExtensionData { + return { + statistics: { amountOfInstances: 5 }, + contributorId: "contributor-id", + id: "contributor-extension-id", + subTitle: { de: "Untertitel" }, + verificationRequested: false, + name: "Own Extension", + context: "project", + functional: true, + published: false, + verified: false, + secrets: [], + assets: [], + scopes: [], + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildContributorExtensionListItemData.ts b/packages/models/src/testing/builders/buildContributorExtensionListItemData.ts new file mode 100644 index 00000000..c8196963 --- /dev/null +++ b/packages/models/src/testing/builders/buildContributorExtensionListItemData.ts @@ -0,0 +1,22 @@ +import type { ContributorExtensionListItemData } from "../../marketplace/ContributorExtension/types.js"; + +export function buildContributorExtensionListItemData( + overrides?: Partial, +): ContributorExtensionListItemData { + return { + id: "contributor-extension-list-item-id", + statistics: { amountOfInstances: 5 }, + contributorId: "contributor-id", + subTitle: { de: "Untertitel" }, + verificationRequested: false, + name: "Own Extension", + context: "project", + functional: true, + published: false, + verified: false, + secrets: [], + assets: [], + scopes: [], + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildContributorOnBehalfInvoiceData.ts b/packages/models/src/testing/builders/buildContributorOnBehalfInvoiceData.ts new file mode 100644 index 00000000..0d9e49ae --- /dev/null +++ b/packages/models/src/testing/builders/buildContributorOnBehalfInvoiceData.ts @@ -0,0 +1,16 @@ +import type { ContributorOnBehalfInvoiceData } from "../../marketplace/Contributor/types.js"; + +export function buildContributorOnBehalfInvoiceData( + overrides?: Partial, +): ContributorOnBehalfInvoiceData { + return { + pdfLink: "https://example.test/invoice.pdf", + invoiceNumber: "INV-2024-001", + invoiceDate: "2024-05-01", + invoiceId: "invoice-id", + invoiceType: "INVOICE", + totalGross: 11900, + totalNet: 10000, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildConversationCategoryData.ts b/packages/models/src/testing/builders/buildConversationCategoryData.ts new file mode 100644 index 00000000..b678975d --- /dev/null +++ b/packages/models/src/testing/builders/buildConversationCategoryData.ts @@ -0,0 +1,12 @@ +import type { ConversationCategoryData } from "../../conversation/ConversationCategory/types.js"; + +export function buildConversationCategoryData( + overrides: Partial = {}, +): ConversationCategoryData { + return { + referenceType: ["project"], + categoryId: "category-id", + name: "General", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildConversationData.ts b/packages/models/src/testing/builders/buildConversationData.ts new file mode 100644 index 00000000..48f062ff --- /dev/null +++ b/packages/models/src/testing/builders/buildConversationData.ts @@ -0,0 +1,16 @@ +import type { ConversationData } from "../../conversation/Conversation/types.js"; + +export function buildConversationData( + overrides: Partial = {}, +): ConversationData { + return { + createdAt: "2024-01-01T00:00:00.000Z", + conversationId: "conversation-id", + mainUser: { userId: "user-id" }, + title: "Test conversation", + visibility: "private", + shortId: "CONV-1", + status: "open", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildConversationListItemData.ts b/packages/models/src/testing/builders/buildConversationListItemData.ts new file mode 100644 index 00000000..fff17b5d --- /dev/null +++ b/packages/models/src/testing/builders/buildConversationListItemData.ts @@ -0,0 +1,16 @@ +import type { ConversationListItemData } from "../../conversation/Conversation/types.js"; + +export function buildConversationListItemData( + overrides: Partial = {}, +): ConversationListItemData { + return { + createdAt: "2024-01-01T00:00:00.000Z", + conversationId: "conversation-id", + mainUser: { userId: "user-id" }, + title: "Test conversation", + visibility: "private", + shortId: "CONV-1", + status: "open", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildConversationMessageData.ts b/packages/models/src/testing/builders/buildConversationMessageData.ts new file mode 100644 index 00000000..328f96ba --- /dev/null +++ b/packages/models/src/testing/builders/buildConversationMessageData.ts @@ -0,0 +1,14 @@ +import type { ConversationMessageData } from "../../conversation/ConversationMessage/types.js"; + +export function buildConversationMessageData( + overrides: Partial = {}, +): ConversationMessageData { + return { + createdAt: "2024-01-01T00:00:00.000Z", + conversationId: "conversation-id", + type: "MESSAGE" as const, + messageId: "message-id", + messageContent: "Hello", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildConversationUserData.ts b/packages/models/src/testing/builders/buildConversationUserData.ts new file mode 100644 index 00000000..38013eda --- /dev/null +++ b/packages/models/src/testing/builders/buildConversationUserData.ts @@ -0,0 +1,11 @@ +import type { ConversationUserData } from "../../conversation/ConversationUser/types.js"; + +export function buildConversationUserData( + overrides: Partial = {}, +): ConversationUserData { + return { + clearName: "Jane Doe", + userId: "user-id", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildCronjobData.ts b/packages/models/src/testing/builders/buildCronjobData.ts new file mode 100644 index 00000000..d74141af --- /dev/null +++ b/packages/models/src/testing/builders/buildCronjobData.ts @@ -0,0 +1,30 @@ +import type { + CronjobListItemData, + CronjobData, +} from "../../cronjob/Cronjob/types.js"; + +export function buildCronjobData( + overrides?: Partial, +): CronjobData { + return { + createdAt: "2024-01-01T00:00:00.000Z", + updatedAt: "2024-01-01T00:00:00.000Z", + failedExecutionAlertThreshold: 1, + description: "test cronjob", + interval: "*/5 * * * *", + projectId: "project-id", + shortId: "abc123", + id: "cronjob-id", + appId: "app-id", + timeout: 3600, + active: true, + ...overrides, + }; +} + +export function buildCronjobListItemData( + overrides?: Partial, +): CronjobListItemData { + // CronjobListItemData and CronjobData share the same CronjobCronjob schema. + return buildCronjobData(overrides as Partial); +} diff --git a/packages/models/src/testing/builders/buildCronjobExecutionData.ts b/packages/models/src/testing/builders/buildCronjobExecutionData.ts new file mode 100644 index 00000000..4f4e9136 --- /dev/null +++ b/packages/models/src/testing/builders/buildCronjobExecutionData.ts @@ -0,0 +1,28 @@ +import type { + CronjobExecutionListItemData, + CronjobExecutionData, +} from "../../cronjob/CronjobExecution/types.js"; + +export function buildCronjobExecutionData( + overrides?: Partial, +): CronjobExecutionData { + return { + start: "2024-01-01T00:00:00.000Z", + triggeredBy: { id: "user-id" }, + durationInMilliseconds: 5000, + logPath: "/logs/exec.log", + cronjobId: "cronjob-id", + id: "execution-id", + status: "Complete", + successful: true, + exitCode: 0, + ...overrides, + }; +} + +export function buildCronjobExecutionListItemData( + overrides?: Partial, +): CronjobExecutionListItemData { + // CronjobExecutionListItemData and CronjobExecutionData share the same schema. + return buildCronjobExecutionData(overrides as Partial); +} diff --git a/packages/models/src/testing/builders/buildCustomerAIDetailedModelData.ts b/packages/models/src/testing/builders/buildCustomerAIDetailedModelData.ts new file mode 100644 index 00000000..a9c6afee --- /dev/null +++ b/packages/models/src/testing/builders/buildCustomerAIDetailedModelData.ts @@ -0,0 +1,18 @@ +import type { CustomerAIModelData } from "../../ai/CustomerAIModel/types.js"; + +export function buildCustomerAIDetailedModelData( + overrides?: Partial, +): CustomerAIModelData { + return { + termsOfServiceLink: "https://tos.example.com/detailed", + docLink: "https://docs.example.com/detailed", + activeAt: "2024-01-01T00:00:00.000Z", + displayName: "GPT Detailed", + replacesModelNames: [], + name: "gpt-detailed", + status: "active", + label: "stable", + tokenFactor: 1, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildCustomerAIPlanData.ts b/packages/models/src/testing/builders/buildCustomerAIPlanData.ts new file mode 100644 index 00000000..16acc463 --- /dev/null +++ b/packages/models/src/testing/builders/buildCustomerAIPlanData.ts @@ -0,0 +1,25 @@ +import type { CustomerAIPlanData } from "../../ai/CustomerAIPlan/types.js"; + +export function buildCustomerAIPlanData( + overrides?: Partial, +): CustomerAIPlanData { + return { + topUsages: [ + { + projectId: "project-id", + tokenUsed: 300_000, + keyId: "key-a", + name: "key-a", + }, + ], + tokens: { available: 1_500_000, planLimit: 2_000_000, used: 500_000 }, + rateLimit: { allowedRequestsPerUnit: 300, unit: "minute" }, + keys: { planLimit: 10, available: 5, used: 5 }, + nextTokenReset: "2024-02-01T00:00:00.000Z", + modelTermsApprovalRequired: false, + customerId: "customer-id", + description: "plan-name", + planId: "plan-id", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildCustomerData.ts b/packages/models/src/testing/builders/buildCustomerData.ts new file mode 100644 index 00000000..4e639451 --- /dev/null +++ b/packages/models/src/testing/builders/buildCustomerData.ts @@ -0,0 +1,25 @@ +import type { + CustomerListItemData, + CustomerData, +} from "../../customer/Customer/types.js"; + +const defaults = { + creationDate: "2024-01-01T00:00:00.000Z", + customerId: "customer-id", + customerNumber: "12345", + name: "Test Customer", + projectCount: 0, + memberCount: 1, +}; + +export function buildCustomerData( + overrides?: Partial, +): CustomerData { + return { ...defaults, ...overrides }; +} + +export function buildCustomerListItemData( + overrides?: Partial, +): CustomerListItemData { + return { ...defaults, ...overrides }; +} diff --git a/packages/models/src/testing/builders/buildCustomerInviteData.ts b/packages/models/src/testing/builders/buildCustomerInviteData.ts new file mode 100644 index 00000000..569bc0c1 --- /dev/null +++ b/packages/models/src/testing/builders/buildCustomerInviteData.ts @@ -0,0 +1,26 @@ +import type { + CustomerInviteListItemData, + CustomerInviteData, +} from "../../customer/CustomerInvite/types.js"; + +const defaults = { + information: { invitedBy: "user-inviter" }, + mailAddress: "invitee@example.com", + customerName: "Test Customer", + customerId: "customer-id", + role: "member" as const, + message: "Join us", + id: "invite-id", +}; + +export function buildCustomerInviteData( + overrides?: Partial, +): CustomerInviteData { + return { ...defaults, ...overrides }; +} + +export function buildCustomerInviteListItemData( + overrides?: Partial, +): CustomerInviteListItemData { + return { ...defaults, ...overrides }; +} diff --git a/packages/models/src/testing/builders/buildCustomerMembershipData.ts b/packages/models/src/testing/builders/buildCustomerMembershipData.ts new file mode 100644 index 00000000..e2e72630 --- /dev/null +++ b/packages/models/src/testing/builders/buildCustomerMembershipData.ts @@ -0,0 +1,27 @@ +import type { + CustomerMembershipListItemData, + CustomerMembershipData, +} from "../../customer/CustomerMembership/types.js"; + +const defaults = { + email: "member@example.com", + customerId: "customer-id", + role: "member" as const, + id: "membership-id", + firstName: "Grace", + lastName: "Hopper", + userId: "user-id", + mfa: false, +}; + +export function buildCustomerMembershipData( + overrides?: Partial, +): CustomerMembershipData { + return { ...defaults, ...overrides }; +} + +export function buildCustomerMembershipListItemData( + overrides?: Partial, +): CustomerMembershipListItemData { + return { ...defaults, ...overrides }; +} diff --git a/packages/models/src/testing/builders/buildDeliveryBoxData.ts b/packages/models/src/testing/builders/buildDeliveryBoxData.ts new file mode 100644 index 00000000..d5601c4d --- /dev/null +++ b/packages/models/src/testing/builders/buildDeliveryBoxData.ts @@ -0,0 +1,17 @@ +import type { DeliveryBoxData } from "../../mail/DeliveryBox/types.js"; + +export function buildDeliveryBoxData( + overrides?: Partial, +): DeliveryBoxData { + return { + passwordUpdatedAt: "2024-01-01T00:00:00.000Z", + updatedAt: "2024-01-01T00:00:00.000Z", + authenticationEnabled: true, + description: "test box", + projectId: "project-id", + id: "deliverybox-id", + sendingEnabled: true, + name: "p-xxxx", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildDnsCertificateSpecData.ts b/packages/models/src/testing/builders/buildDnsCertificateSpecData.ts new file mode 100644 index 00000000..db7da880 --- /dev/null +++ b/packages/models/src/testing/builders/buildDnsCertificateSpecData.ts @@ -0,0 +1,10 @@ +import type { DnsCertificateSpecData } from "../../certificate/DnsCertificateSpec/types.js"; + +export function buildDnsCertificateSpecData( + overrides?: Partial, +): DnsCertificateSpecData { + return { + cnameTarget: "cname.example.com", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildDnsCertificateStatusData.ts b/packages/models/src/testing/builders/buildDnsCertificateStatusData.ts new file mode 100644 index 00000000..a1086cac --- /dev/null +++ b/packages/models/src/testing/builders/buildDnsCertificateStatusData.ts @@ -0,0 +1,12 @@ +import type { DnsCertificateStatusData } from "../../certificate/DnsCertificateStatus/types.js"; + +export function buildDnsCertificateStatusData( + overrides?: Partial, +): DnsCertificateStatusData { + return { + updatedAt: "2024-05-01T12:00:00.000Z", + message: "all good", + status: "ready", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildDnsRecordCaaData.ts b/packages/models/src/testing/builders/buildDnsRecordCaaData.ts new file mode 100644 index 00000000..5917a2f2 --- /dev/null +++ b/packages/models/src/testing/builders/buildDnsRecordCaaData.ts @@ -0,0 +1,36 @@ +import type { + DnsRecordCaaEntry, + DnsRecordCaaData, +} from "../../dns/DnsRecordCaa/types.js"; + +type DnsRecordCaaComponentData = Extract< + DnsRecordCaaData, + { records: unknown } +>; + +export function buildDnsRecordCaaComponentData( + overrides?: Partial, +): DnsRecordCaaComponentData { + return { + records: [ + { + value: "letsencrypt.org", + tag: "issue", + flags: 0, + }, + ], + settings: { ttl: { seconds: 3600 } }, + ...overrides, + }; +} + +export function buildDnsRecordCaaEntry( + overrides?: Partial, +): DnsRecordCaaEntry { + return { + value: "letsencrypt.org", + tag: "issue", + flags: 0, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildDnsRecordCnameData.ts b/packages/models/src/testing/builders/buildDnsRecordCnameData.ts new file mode 100644 index 00000000..c1c2041a --- /dev/null +++ b/packages/models/src/testing/builders/buildDnsRecordCnameData.ts @@ -0,0 +1,16 @@ +import type { DnsRecordCnameData } from "../../dns/DnsRecordCname/types.js"; + +type DnsRecordCnameComponentData = Extract< + DnsRecordCnameData, + { fqdn: unknown } +>; + +export function buildDnsRecordCnameComponentData( + overrides?: Partial, +): DnsRecordCnameComponentData { + return { + settings: { ttl: { seconds: 300 } }, + fqdn: "target.example.com", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildDnsRecordCombinedAData.ts b/packages/models/src/testing/builders/buildDnsRecordCombinedAData.ts new file mode 100644 index 00000000..25739c0b --- /dev/null +++ b/packages/models/src/testing/builders/buildDnsRecordCombinedAData.ts @@ -0,0 +1,29 @@ +import type { + DnsRecordCombinedAManagedData, + DnsRecordCombinedACustomData, + DnsRecordCombinedAUnsetData, +} from "../../dns/DnsRecordCombinedA/types.js"; + +export function buildDnsRecordCombinedACustomData( + overrides?: Partial, +): DnsRecordCombinedACustomData { + return { + settings: { ttl: { seconds: 600 } }, + aaaa: ["2001:db8::1"], + a: ["1.2.3.4"], + ...overrides, + }; +} + +export function buildDnsRecordCombinedAManagedData( + overrides?: Partial, +): DnsRecordCombinedAManagedData { + return { + managedBy: { ingressId: "ingress-1" }, + ...overrides, + }; +} + +export function buildDnsRecordCombinedAUnsetData(): DnsRecordCombinedAUnsetData { + return {}; +} diff --git a/packages/models/src/testing/builders/buildDnsRecordMxData.ts b/packages/models/src/testing/builders/buildDnsRecordMxData.ts new file mode 100644 index 00000000..04792cb1 --- /dev/null +++ b/packages/models/src/testing/builders/buildDnsRecordMxData.ts @@ -0,0 +1,39 @@ +import type { + DnsRecordMxManagedData, + DnsRecordMxCustomData, + DnsRecordMxUnsetData, + DnsRecordMxEntry, +} from "../../dns/DnsRecordMx/types.js"; + +export function buildDnsRecordMxCustomData( + overrides?: Partial, +): DnsRecordMxCustomData { + return { + records: [{ fqdn: "mx.example.com", priority: 10 }], + settings: { ttl: { seconds: 900 } }, + ...overrides, + }; +} + +export function buildDnsRecordMxManagedData( + overrides?: Partial, +): DnsRecordMxManagedData { + return { + managed: true, + ...overrides, + }; +} + +export function buildDnsRecordMxUnsetData(): DnsRecordMxUnsetData { + return {}; +} + +export function buildDnsRecordMxEntry( + overrides?: Partial, +): DnsRecordMxEntry { + return { + fqdn: "mx.example.com", + priority: 10, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildDnsRecordSettingsData.ts b/packages/models/src/testing/builders/buildDnsRecordSettingsData.ts new file mode 100644 index 00000000..90188318 --- /dev/null +++ b/packages/models/src/testing/builders/buildDnsRecordSettingsData.ts @@ -0,0 +1,7 @@ +import type { DnsRecordSettingsData } from "../../dns/DnsRecordSettings/types.js"; + +export function buildDnsRecordSettingsData( + overrides: Partial = {}, +): DnsRecordSettingsData { + return { ttl: { seconds: 3600 }, ...overrides }; +} diff --git a/packages/models/src/testing/builders/buildDnsRecordSrvComponentData.ts b/packages/models/src/testing/builders/buildDnsRecordSrvComponentData.ts new file mode 100644 index 00000000..9b3f5d16 --- /dev/null +++ b/packages/models/src/testing/builders/buildDnsRecordSrvComponentData.ts @@ -0,0 +1,11 @@ +import type { DnsRecordSrvData } from "../../dns/DnsRecordSrv/types.js"; + +export function buildDnsRecordSrvComponentData( + overrides: Partial = {}, +): Extract { + return { + records: [{ fqdn: "srv.example.com", priority: 10, port: 443, weight: 5 }], + settings: { ttl: { seconds: 3600 } }, + ...overrides, + } as Extract; +} diff --git a/packages/models/src/testing/builders/buildDnsRecordTxtComponentData.ts b/packages/models/src/testing/builders/buildDnsRecordTxtComponentData.ts new file mode 100644 index 00000000..ef98f11b --- /dev/null +++ b/packages/models/src/testing/builders/buildDnsRecordTxtComponentData.ts @@ -0,0 +1,11 @@ +import type { DnsRecordTxtData } from "../../dns/DnsRecordTxt/types.js"; + +export function buildDnsRecordTxtComponentData( + overrides: Partial = {}, +): Extract { + return { + settings: { ttl: { seconds: 3600 } }, + entries: ["v=spf1 ~all"], + ...overrides, + } as Extract; +} diff --git a/packages/models/src/testing/builders/buildDnsZoneData.ts b/packages/models/src/testing/builders/buildDnsZoneData.ts new file mode 100644 index 00000000..18618313 --- /dev/null +++ b/packages/models/src/testing/builders/buildDnsZoneData.ts @@ -0,0 +1,24 @@ +import type { DnsZoneData } from "../../dns/DnsZone/types.js"; + +export function buildDnsZoneData( + overrides: { + recordSet?: Partial; + } & Omit, "recordSet"> = {}, +): DnsZoneData { + const recordSet: DnsZoneData["recordSet"] = { + combinedARecords: {}, + cname: {}, + srv: {}, + txt: {}, + caa: {}, + mx: {}, + ...overrides.recordSet, + }; + + return { + domain: "example.com", + id: "zone-id", + ...overrides, + recordSet, + }; +} diff --git a/packages/models/src/testing/builders/buildDomainDomainData.ts b/packages/models/src/testing/builders/buildDomainDomainData.ts new file mode 100644 index 00000000..552c49a3 --- /dev/null +++ b/packages/models/src/testing/builders/buildDomainDomainData.ts @@ -0,0 +1,22 @@ +import type { DomainData } from "../../domain/Domain/types.js"; + +export function buildDomainDomainData( + overrides: Partial = {}, +): DomainData { + return { + nameservers: [ + "ns01.agenturserver.de", + "ns01.agenturserver.it", + "ns01.agenturserver.co", + ], + handles: { ownerC: { current: { handleFields: [] } } }, + usesDefaultNameserver: true, + projectId: "project-id", + domain: "example.com", + domainId: "domain-id", + connected: false, + deleted: false, + processes: [], + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildDomainHandleData.ts b/packages/models/src/testing/builders/buildDomainHandleData.ts new file mode 100644 index 00000000..477ee7c2 --- /dev/null +++ b/packages/models/src/testing/builders/buildDomainHandleData.ts @@ -0,0 +1,26 @@ +import type { HandleData } from "../../domain/DomainHandle/types.js"; + +import { buildDomainHandleFieldData } from "./buildDomainHandleFieldData.js"; + +export function buildDomainHandleData( + overrides?: Partial, +): HandleData { + return { + handleFields: [ + buildDomainHandleFieldData({ value: "Example Owner", name: "name" }), + buildDomainHandleFieldData({ + value: "Example GmbH", + name: "organization", + }), + buildDomainHandleFieldData({ value: "owner@example.com", name: "email" }), + buildDomainHandleFieldData({ value: "Example Street 1", name: "street" }), + buildDomainHandleFieldData({ value: "Example City", name: "city" }), + buildDomainHandleFieldData({ value: "12345", name: "zip" }), + buildDomainHandleFieldData({ name: "country", value: "DE" }), + buildDomainHandleFieldData({ value: "+49 123 456789", name: "phone" }), + buildDomainHandleFieldData({ value: "123", name: "fax" }), + ], + handleRef: "handle-1", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildDomainHandleFieldData.ts b/packages/models/src/testing/builders/buildDomainHandleFieldData.ts new file mode 100644 index 00000000..f81d6335 --- /dev/null +++ b/packages/models/src/testing/builders/buildDomainHandleFieldData.ts @@ -0,0 +1,11 @@ +import type { HandleField } from "../../domain/DomainHandle/types.js"; + +export function buildDomainHandleFieldData( + overrides?: Partial, +): HandleField { + return { + value: "Example Owner", + name: "name", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildDomainHandleReadableData.ts b/packages/models/src/testing/builders/buildDomainHandleReadableData.ts new file mode 100644 index 00000000..c9c622cb --- /dev/null +++ b/packages/models/src/testing/builders/buildDomainHandleReadableData.ts @@ -0,0 +1,12 @@ +import type { HandleReadableData } from "../../domain/DomainHandleReadable/types.js"; + +import { buildDomainHandleData } from "./buildDomainHandleData.js"; + +export function buildDomainHandleReadableData( + overrides?: Partial, +): HandleReadableData { + return { + current: buildDomainHandleData(), + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildDomainListItemData.ts b/packages/models/src/testing/builders/buildDomainListItemData.ts new file mode 100644 index 00000000..e775dc18 --- /dev/null +++ b/packages/models/src/testing/builders/buildDomainListItemData.ts @@ -0,0 +1,17 @@ +import type { DomainListItemData } from "../../domain/Domain/types.js"; + +export function buildDomainListItemData( + overrides?: Partial, +): DomainListItemData { + return { + handles: { ownerC: { current: {} } }, + usesDefaultNameserver: true, + projectId: "project-id", + domainId: "domain-id", + domain: "example.com", + connected: true, + nameservers: [], + deleted: false, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildDomainMigrationData.ts b/packages/models/src/testing/builders/buildDomainMigrationData.ts new file mode 100644 index 00000000..fe7612e8 --- /dev/null +++ b/packages/models/src/testing/builders/buildDomainMigrationData.ts @@ -0,0 +1,15 @@ +import type { DomainMigrationListItemData } from "../../domain/DomainMigration/types.js"; + +import { buildDomainMigrationDomainData } from "./buildDomainMigrationDomainData.js"; + +export function buildDomainMigrationData( + overrides?: Partial, +): DomainMigrationListItemData { + return { + domains: [buildDomainMigrationDomainData()], + pAccount: "p-account-1", + projectId: "project-1", + id: "migration-1", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildDomainMigrationDnsRecordData.ts b/packages/models/src/testing/builders/buildDomainMigrationDnsRecordData.ts new file mode 100644 index 00000000..95731f39 --- /dev/null +++ b/packages/models/src/testing/builders/buildDomainMigrationDnsRecordData.ts @@ -0,0 +1,12 @@ +import type { DomainMigrationDnsRecordData } from "../../domain/DomainMigrationDnsRecord/types.js"; + +export function buildDomainMigrationDnsRecordData( + overrides?: Partial, +): DomainMigrationDnsRecordData { + return { + value: "1.2.3.4", + type: "A", + ttl: 3600, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildDomainMigrationDomainData.ts b/packages/models/src/testing/builders/buildDomainMigrationDomainData.ts new file mode 100644 index 00000000..95e5ccc1 --- /dev/null +++ b/packages/models/src/testing/builders/buildDomainMigrationDomainData.ts @@ -0,0 +1,17 @@ +import type { DomainMigrationDomainData } from "../../domain/DomainMigrationDomain/types.js"; + +import { buildDomainMigrationDnsRecordData } from "./buildDomainMigrationDnsRecordData.js"; + +export function buildDomainMigrationDomainData( + overrides?: Partial, +): DomainMigrationDomainData { + return { + coabData: { + dnsRecords: [buildDomainMigrationDnsRecordData()], + }, + domain: "example.com", + domainId: "domain-1", + state: "pending", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildDomainOrderPreviewData.ts b/packages/models/src/testing/builders/buildDomainOrderPreviewData.ts new file mode 100644 index 00000000..7cf71a6e --- /dev/null +++ b/packages/models/src/testing/builders/buildDomainOrderPreviewData.ts @@ -0,0 +1,13 @@ +import type { DomainOrderPreviewData } from "../../order/Order/types.js"; + +export function buildDomainOrderPreviewData( + overrides: Partial = {}, +): DomainOrderPreviewData { + return { + domainContractDuration: 12, + domainPrice: 0, + totalPrice: 0, + feePrice: 0, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildDomainProcessData.ts b/packages/models/src/testing/builders/buildDomainProcessData.ts new file mode 100644 index 00000000..8b0e88a6 --- /dev/null +++ b/packages/models/src/testing/builders/buildDomainProcessData.ts @@ -0,0 +1,13 @@ +import type { DomainProcessData } from "../../domain/DomainProcess/types.js"; + +export function buildDomainProcessData( + overrides?: Partial, +): DomainProcessData { + return { + lastUpdate: "2024-01-01T00:00:00.000Z", + processType: "REGISTER", + transactionId: "tx-1", + state: "REQUESTED", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildExtensionData.ts b/packages/models/src/testing/builders/buildExtensionData.ts new file mode 100644 index 00000000..003656d8 --- /dev/null +++ b/packages/models/src/testing/builders/buildExtensionData.ts @@ -0,0 +1,27 @@ +import type { ExtensionData } from "../../marketplace/Extension/types.js"; + +export function buildExtensionData( + overrides?: Partial, +): ExtensionData { + return { + support: { email: "s@example.com", inherited: false }, + publishedAt: "2024-01-01T00:00:00.000Z", + createdAt: "2024-01-01T00:00:00.000Z", + statistics: { amountOfInstances: 3 }, + contributorId: "contributor-id", + subTitle: { de: "Untertitel" }, + logoRefId: "logo-ref-id", + name: "Test Extension", + description: "desc", + context: "project", + id: "extension-id", + state: "enabled", + disabled: false, + published: true, + blocked: false, + assets: [], + scopes: [], + tags: [], + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildExtensionInstanceContractData.ts b/packages/models/src/testing/builders/buildExtensionInstanceContractData.ts new file mode 100644 index 00000000..38e0668f --- /dev/null +++ b/packages/models/src/testing/builders/buildExtensionInstanceContractData.ts @@ -0,0 +1,14 @@ +import type { ExtensionInstanceContractData } from "../../marketplace/ExtensionInstance/types.js"; + +export function buildExtensionInstanceContractData( + overrides?: Partial, +): ExtensionInstanceContractData { + return { + interactionRequired: false, + variantName: "Variant 1", + variantKey: "variant-1", + currentPrice: 1000, + status: "active", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildExtensionInstanceData.ts b/packages/models/src/testing/builders/buildExtensionInstanceData.ts new file mode 100644 index 00000000..7a98d309 --- /dev/null +++ b/packages/models/src/testing/builders/buildExtensionInstanceData.ts @@ -0,0 +1,29 @@ +import type { ExtensionInstanceData } from "../../marketplace/ExtensionInstance/types.js"; + +export function buildExtensionInstanceData( + overrides?: Partial, +): ExtensionInstanceData { + return { + chargeability: { + reasons: { isNonChargeableCustomer: false, isOwnExtension: true }, + isChargeable: false, + }, + aggregateReference: { + aggregate: "project", + domain: "project", + id: "project-id", + }, + parentCustomerId: "customer-id", + contributorId: "contributor-id", + extensionName: "Test Extension", + contributorName: "Contributor", + webhookExecutionHalted: false, + extensionId: "extension-id", + id: "extension-instance-id", + pendingInstallation: false, + pendingRemoval: false, + consentedScopes: [], + disabled: false, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildExtensionInstanceListItemData.ts b/packages/models/src/testing/builders/buildExtensionInstanceListItemData.ts new file mode 100644 index 00000000..cf55bce3 --- /dev/null +++ b/packages/models/src/testing/builders/buildExtensionInstanceListItemData.ts @@ -0,0 +1,29 @@ +import type { ExtensionInstanceListItemData } from "../../marketplace/ExtensionInstance/types.js"; + +export function buildExtensionInstanceListItemData( + overrides?: Partial, +): ExtensionInstanceListItemData { + return { + chargeability: { + reasons: { isNonChargeableCustomer: false, isOwnExtension: true }, + isChargeable: false, + }, + aggregateReference: { + aggregate: "project", + domain: "project", + id: "project-id", + }, + id: "extension-instance-list-item-id", + contributorId: "contributor-id", + extensionName: "Test Extension", + parentCustomerId: "customer-id", + contributorName: "Contributor", + webhookExecutionHalted: false, + extensionId: "extension-id", + pendingInstallation: false, + pendingRemoval: false, + consentedScopes: [], + disabled: false, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildExtensionListItemData.ts b/packages/models/src/testing/builders/buildExtensionListItemData.ts new file mode 100644 index 00000000..b455dbe9 --- /dev/null +++ b/packages/models/src/testing/builders/buildExtensionListItemData.ts @@ -0,0 +1,27 @@ +import type { ExtensionListItemData } from "../../marketplace/Extension/types.js"; + +export function buildExtensionListItemData( + overrides?: Partial, +): ExtensionListItemData { + return { + support: { email: "s@example.com", inherited: false }, + publishedAt: "2024-01-01T00:00:00.000Z", + createdAt: "2024-01-01T00:00:00.000Z", + statistics: { amountOfInstances: 3 }, + contributorId: "contributor-id", + subTitle: { de: "Untertitel" }, + id: "extension-list-item-id", + logoRefId: "logo-ref-id", + name: "Test Extension", + description: "desc", + context: "project", + state: "enabled", + disabled: false, + published: true, + blocked: false, + assets: [], + scopes: [], + tags: [], + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildExternalCertificateOrderPreviewData.ts b/packages/models/src/testing/builders/buildExternalCertificateOrderPreviewData.ts new file mode 100644 index 00000000..3cf438fd --- /dev/null +++ b/packages/models/src/testing/builders/buildExternalCertificateOrderPreviewData.ts @@ -0,0 +1,12 @@ +import type { ExternalCertificateOrderPreviewData } from "../../order/Order/types.js"; + +export function buildExternalCertificateOrderPreviewData( + overrides: Partial = {}, +): ExternalCertificateOrderPreviewData { + return { + recurringPrice: 0, + totalPrice: 0, + feePrice: 0, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildFeedbackListItemData.ts b/packages/models/src/testing/builders/buildFeedbackListItemData.ts new file mode 100644 index 00000000..2e2330e8 --- /dev/null +++ b/packages/models/src/testing/builders/buildFeedbackListItemData.ts @@ -0,0 +1,14 @@ +import type { FeedbackListItemData } from "../../user/Feedback/types.js"; + +export function buildFeedbackListItemData( + overrides: Partial = {}, +): FeedbackListItemData { + return { + id: "feedback-id", + message: "great", + subject: "nps", + origin: "web", + vote: 10, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildFileDownloadTokenData.ts b/packages/models/src/testing/builders/buildFileDownloadTokenData.ts new file mode 100644 index 00000000..7bbedbbb --- /dev/null +++ b/packages/models/src/testing/builders/buildFileDownloadTokenData.ts @@ -0,0 +1,11 @@ +import type { FileDownloadTokenData } from "../../file/FileAccessToken/types.js"; + +export function buildFileDownloadTokenData( + overrides?: Partial, +): FileDownloadTokenData { + return { + expiresAt: "2099-01-01T00:00:00.000Z", + accessToken: "download-token", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildFileMetaData.ts b/packages/models/src/testing/builders/buildFileMetaData.ts new file mode 100644 index 00000000..44eb117c --- /dev/null +++ b/packages/models/src/testing/builders/buildFileMetaData.ts @@ -0,0 +1,17 @@ +import type { FileMetaData } from "../../file/File/types.js"; + +export function buildFileMetaData( + overrides?: Partial, +): FileMetaData { + return { + friendlyURL: "test-file", + friendlyUrl: "test-file", + shortId: "file-short-id", + mimeType: "text/plain", + type: "text/plain", + name: "test.txt", + sizeInBytes: 4, + id: "file-id", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildFileUploadRulesData.ts b/packages/models/src/testing/builders/buildFileUploadRulesData.ts new file mode 100644 index 00000000..ca6e4cb2 --- /dev/null +++ b/packages/models/src/testing/builders/buildFileUploadRulesData.ts @@ -0,0 +1,16 @@ +import type { FileUploadRules } from "../../file/File/types.js"; + +export function buildFileUploadRulesData( + overrides?: Partial, +): FileUploadRules { + return { + fileTypes: [{ mimeType: "text/plain", extensions: ["txt"] }], + mimeTypes: ["text/plain"], + maxSizeInBytes: 1_024, + extensions: ["txt"], + maxNameLength: 255, + maxSizeInKB: 1, + maxSizeInKb: 1, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildFileUploadTokenData.ts b/packages/models/src/testing/builders/buildFileUploadTokenData.ts new file mode 100644 index 00000000..4761113d --- /dev/null +++ b/packages/models/src/testing/builders/buildFileUploadTokenData.ts @@ -0,0 +1,13 @@ +import type { FileUploadTokenData } from "../../file/FileAccessToken/types.js"; + +export function buildFileUploadTokenData( + overrides?: Partial, +): FileUploadTokenData { + return { + rules: { + mimeTypes: ["text/plain"], + }, + token: "upload-token", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildFinderProfileData.ts b/packages/models/src/testing/builders/buildFinderProfileData.ts new file mode 100644 index 00000000..5409b942 --- /dev/null +++ b/packages/models/src/testing/builders/buildFinderProfileData.ts @@ -0,0 +1,17 @@ +import type { FinderProfileData } from "../../fyndr/FinderProfile/types.js"; + +export function buildFinderProfileData( + overrides?: Partial, +): FinderProfileData { + return { + tariff: { + reservation: { tariffLimit: 0, available: 0, used: 0 }, + unlocked: { tariffLimit: 0, available: 0, used: 0 }, + nextUnlockRenewalDate: "2024-06-01T00:00:00.000Z", + }, + approvedOn: "2024-01-01T00:00:00.000Z", + domain: "example.com", + customerId: "c-1", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildFinderProfileRequestCustomerData.ts b/packages/models/src/testing/builders/buildFinderProfileRequestCustomerData.ts new file mode 100644 index 00000000..11b8fb47 --- /dev/null +++ b/packages/models/src/testing/builders/buildFinderProfileRequestCustomerData.ts @@ -0,0 +1,26 @@ +import type { CustomerData } from "../../customer/Customer/types.js"; + +export function buildFinderProfileRequestCustomerData( + overrides?: Partial, +): CustomerData { + return { + owner: { + address: { + countryCode: "DE", + houseNumber: "1", + street: "Main", + city: "Kiel", + zip: "24103", + }, + emailAddress: "info@example.com", + salutation: "mr", + }, + creationDate: "2024-01-01T00:00:00.000Z", + customerNumber: "12345", + customerId: "c-1", + projectCount: 0, + memberCount: 1, + name: "Acme", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildFinderProfileRequestData.ts b/packages/models/src/testing/builders/buildFinderProfileRequestData.ts new file mode 100644 index 00000000..3ed4e0be --- /dev/null +++ b/packages/models/src/testing/builders/buildFinderProfileRequestData.ts @@ -0,0 +1,15 @@ +import type { FinderProfileRequestData } from "../../fyndr/FinderProfileRequest/types.js"; + +export function buildFinderProfileRequestData( + overrides?: Partial, +): FinderProfileRequestData { + return { + createdOn: "2024-01-01T00:00:00.000Z", + requestedBy: { userId: "u-1" }, + domain: "example.com", + status: "APPROVED", + customerId: "c-1", + profileId: "p-1", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildHostingOrderPreviewData.ts b/packages/models/src/testing/builders/buildHostingOrderPreviewData.ts new file mode 100644 index 00000000..0a202b58 --- /dev/null +++ b/packages/models/src/testing/builders/buildHostingOrderPreviewData.ts @@ -0,0 +1,12 @@ +import type { HostingOrderPreviewData } from "../../order/Order/types.js"; + +export function buildHostingOrderPreviewData( + overrides: Partial = {}, +): HostingOrderPreviewData { + return { + machineTypePrice: 0, + storagePrice: 0, + totalPrice: 0, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildIngressData.ts b/packages/models/src/testing/builders/buildIngressData.ts new file mode 100644 index 00000000..3e098050 --- /dev/null +++ b/packages/models/src/testing/builders/buildIngressData.ts @@ -0,0 +1,20 @@ +import type { IngressData } from "../../ingress/Ingress/types.js"; + +// IngressData === IngressListItemData (both resolve to IngressIngress). +export function buildIngressData( + overrides?: Partial, +): IngressData { + return { + paths: [{ target: { useDefaultPage: true }, path: "/" }], + ownership: { txtRecord: "txt-verify", verified: true }, + ips: { v4: ["1.2.3.4"], v6: ["::1"] }, + tls: { isCreated: true, acme: true }, + hostname: "example.com", + projectId: "project-id", + dnsValidationErrors: [], + id: "ingress-id", + isDefault: false, + isEnabled: true, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildIngressPathData.ts b/packages/models/src/testing/builders/buildIngressPathData.ts new file mode 100644 index 00000000..543155dd --- /dev/null +++ b/packages/models/src/testing/builders/buildIngressPathData.ts @@ -0,0 +1,11 @@ +import type { IngressPathData } from "../../ingress/IngressPath/types.js"; + +export function buildIngressPathData( + overrides?: Partial, +): IngressPathData { + return { + target: { useDefaultPage: true }, + path: "/", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildInstalledSystemSoftwareData.ts b/packages/models/src/testing/builders/buildInstalledSystemSoftwareData.ts new file mode 100644 index 00000000..9981d2ed --- /dev/null +++ b/packages/models/src/testing/builders/buildInstalledSystemSoftwareData.ts @@ -0,0 +1,15 @@ +import type { InstalledSystemSoftwareData } from "../../app/InstalledSystemSoftware/types.js"; + +export function buildInstalledSystemSoftwareData( + overrides?: Partial, +): InstalledSystemSoftwareData { + return { + systemSoftwareVersion: { current: "v1", desired: "v1" }, + systemSoftwareId: "sys-id", + updatePolicy: "patchLevel", + externalVersion: "8.2", + updateAvailable: false, + name: "php", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildInvoiceData.ts b/packages/models/src/testing/builders/buildInvoiceData.ts new file mode 100644 index 00000000..a444ccd2 --- /dev/null +++ b/packages/models/src/testing/builders/buildInvoiceData.ts @@ -0,0 +1,38 @@ +import type { InvoiceData } from "../../invoice/Invoice/types.js"; + +import { buildInvoiceItemData } from "./buildInvoiceItemData.js"; + +export function buildInvoiceData( + overrides?: Partial, +): InvoiceData { + return { + recipient: { + address: { + street: "Test Street", + city: "Test City", + countryCode: "DE", + houseNumber: "1", + zip: "12345", + }, + salutation: "mr", + }, + groups: [ + { + items: [buildInvoiceItemData()], + description: "Group 1", + }, + ], + date: "2024-05-01T00:00:00.000Z", + invoiceNumber: "INV-2024-001", + customerId: "customer-id", + invoiceType: "REGULAR", + totalGross: 11900, + id: "invoice-id", + currency: "EUR", + totalNet: 10000, + pdfId: "pdf-id", + status: "NEW", + amountPaid: 0, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildInvoiceItemData.ts b/packages/models/src/testing/builders/buildInvoiceItemData.ts new file mode 100644 index 00000000..76bd889f --- /dev/null +++ b/packages/models/src/testing/builders/buildInvoiceItemData.ts @@ -0,0 +1,14 @@ +import type { InvoiceItemData } from "../../invoice/InvoiceItem/types.js"; + +export function buildInvoiceItemData( + overrides?: Partial, +): InvoiceItemData { + return { + price: { currency: "EUR", value: 1000 }, + contractItemId: "contract-item-id", + description: "Test item", + itemId: "item-id", + vatRate: 19, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildInvoiceItemGroupData.ts b/packages/models/src/testing/builders/buildInvoiceItemGroupData.ts new file mode 100644 index 00000000..c6d6517e --- /dev/null +++ b/packages/models/src/testing/builders/buildInvoiceItemGroupData.ts @@ -0,0 +1,13 @@ +import type { InvoiceItemGroupData } from "../../invoice/InvoiceItemGroup/types.js"; + +import { buildInvoiceItemData } from "./buildInvoiceItemData.js"; + +export function buildInvoiceItemGroupData( + overrides?: Partial, +): InvoiceItemGroupData { + return { + items: [buildInvoiceItemData()], + description: "Test group", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildInvoiceRecipientData.ts b/packages/models/src/testing/builders/buildInvoiceRecipientData.ts new file mode 100644 index 00000000..10879e8a --- /dev/null +++ b/packages/models/src/testing/builders/buildInvoiceRecipientData.ts @@ -0,0 +1,17 @@ +import type { InvoiceRecipientData } from "../../invoice/InvoiceRecipient/types.js"; + +export function buildInvoiceRecipientData( + overrides?: Partial, +): InvoiceRecipientData { + return { + address: { + street: "Test Street", + city: "Test City", + countryCode: "DE", + houseNumber: "1", + zip: "12345", + }, + salutation: "mr", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildInvoiceSettingsData.ts b/packages/models/src/testing/builders/buildInvoiceSettingsData.ts new file mode 100644 index 00000000..4d111b2a --- /dev/null +++ b/packages/models/src/testing/builders/buildInvoiceSettingsData.ts @@ -0,0 +1,14 @@ +import type { InvoiceSettingsData } from "../../customer/InvoiceSettings/types.js"; + +export function buildInvoiceSettingsData( + overrides?: Partial, +): InvoiceSettingsData { + return { + paymentSettings: { method: "invoice" }, + additionalEmailRecipients: [], + id: "customer-id", + invoicePeriod: 1, + status: [], + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildLeadData.ts b/packages/models/src/testing/builders/buildLeadData.ts new file mode 100644 index 00000000..ad54c5fb --- /dev/null +++ b/packages/models/src/testing/builders/buildLeadData.ts @@ -0,0 +1,22 @@ +import type { LeadData } from "../../fyndr/Lead/types.js"; + +export function buildLeadData(overrides?: Partial): LeadData { + return { + mainTechnology: { + categoryPriority: 1, + name: "TYPO3", + version: "12", + }, + technologies: [{ categoryPriority: 1, name: "TYPO3", version: "12" }], + company: { salesVolume: 2_000_000, county: "SH" }, + metrics: { desktop: {}, mobile: {} }, + hoster: { server: ["srv"] }, + businessFields: ["IT"], + screenshot: "base64", + description: "desc", + languages: ["de"], + potential: 0.72, + leadId: "l-1", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildLeadFyndrOrderPreviewData.ts b/packages/models/src/testing/builders/buildLeadFyndrOrderPreviewData.ts new file mode 100644 index 00000000..defba2f9 --- /dev/null +++ b/packages/models/src/testing/builders/buildLeadFyndrOrderPreviewData.ts @@ -0,0 +1,7 @@ +import type { LeadFyndrOrderPreviewData } from "../../order/Order/types.js"; + +export function buildLeadFyndrOrderPreviewData( + overrides: Partial = {}, +): LeadFyndrOrderPreviewData { + return { totalPrice: 0, ...overrides }; +} diff --git a/packages/models/src/testing/builders/buildLeadsExportData.ts b/packages/models/src/testing/builders/buildLeadsExportData.ts new file mode 100644 index 00000000..7f6fe0ab --- /dev/null +++ b/packages/models/src/testing/builders/buildLeadsExportData.ts @@ -0,0 +1,14 @@ +import type { LeadsExportData } from "../../fyndr/LeadsExport/types.js"; + +export function buildLeadsExportData( + overrides?: Partial, +): LeadsExportData { + return { + exportedAt: "2024-01-01T00:00:00.000Z", + exportedBy: { userId: "u-1" }, + customerId: "c-1", + exportId: "e-1", + leadCount: 5, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildLicenseData.ts b/packages/models/src/testing/builders/buildLicenseData.ts new file mode 100644 index 00000000..6ce2392d --- /dev/null +++ b/packages/models/src/testing/builders/buildLicenseData.ts @@ -0,0 +1,19 @@ +import type { LicenseData } from "../../app/License/types.js"; + +export function buildLicenseData( + overrides?: Partial, +): LicenseData { + return { + reference: { + aggregate: "project", + domain: "project", + id: "project-id", + }, + keyReference: { key: "secret-key" }, + description: "my license", + kind: "typo3-elts", + id: "license-id", + meta: {}, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildLicenseOrderPreviewData.ts b/packages/models/src/testing/builders/buildLicenseOrderPreviewData.ts new file mode 100644 index 00000000..e4bb33cb --- /dev/null +++ b/packages/models/src/testing/builders/buildLicenseOrderPreviewData.ts @@ -0,0 +1,7 @@ +import type { LicenseOrderPreviewData } from "../../order/Order/types.js"; + +export function buildLicenseOrderPreviewData( + overrides: Partial = {}, +): LicenseOrderPreviewData { + return { totalPrice: 0, ...overrides }; +} diff --git a/packages/models/src/testing/builders/buildMailAddressArchiveData.ts b/packages/models/src/testing/builders/buildMailAddressArchiveData.ts new file mode 100644 index 00000000..4539f937 --- /dev/null +++ b/packages/models/src/testing/builders/buildMailAddressArchiveData.ts @@ -0,0 +1,12 @@ +import type { MailAddressArchiveData } from "../../mail/MailAddressArchive/types.js"; + +export function buildMailAddressArchiveData( + overrides?: Partial, +): MailAddressArchiveData { + return { + usedBytes: 536870912, + quota: 1073741824, + active: true, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildMailAddressBackupData.ts b/packages/models/src/testing/builders/buildMailAddressBackupData.ts new file mode 100644 index 00000000..629b4957 --- /dev/null +++ b/packages/models/src/testing/builders/buildMailAddressBackupData.ts @@ -0,0 +1,7 @@ +import type { MailAddressBackupData } from "../../mail/MailAddressBackup/types.js"; + +export function buildMailAddressBackupData( + overrides?: Partial, +): MailAddressBackupData { + return { name: "20240102", ...overrides }; +} diff --git a/packages/models/src/testing/builders/buildMailAddressData.ts b/packages/models/src/testing/builders/buildMailAddressData.ts new file mode 100644 index 00000000..beebb4c5 --- /dev/null +++ b/packages/models/src/testing/builders/buildMailAddressData.ts @@ -0,0 +1,42 @@ +import type { MailAddressData } from "../../mail/MailAddress/types.js"; + +type Mailbox = NonNullable; + +export function buildMailbox(overrides?: Partial): Mailbox { + return { + spamProtection: { + relocationMinSpamScore: 1, + autoDeleteSpam: false, + folder: "spam", + active: false, + }, + storageInBytes: { + current: { updatedAt: "2024-01-01T00:00:00.000Z", value: 0 }, + limit: 1073741824, + }, + passwordUpdatedAt: "2024-01-01T00:00:00.000Z", + mailsystemSettings: { rateLimitId: "rl-1" }, + sendingEnabled: true, + name: "info", + ...overrides, + }; +} + +export function buildMailAddressData( + overrides?: Partial, +): MailAddressData { + return { + archive: { quota: 1073741824, active: false, usedBytes: 0 }, + updatedAt: "2024-01-01T00:00:00.000Z", + autoResponder: { active: false }, + address: "info@example.com", + isBackupInProgress: false, + receivingDisabled: false, + projectId: "project-id", + forwardAddresses: [], + id: "mailaddr-id", + isArchived: false, + isCatchAll: false, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildMailArchiveOrderPreviewData.ts b/packages/models/src/testing/builders/buildMailArchiveOrderPreviewData.ts new file mode 100644 index 00000000..481f0edd --- /dev/null +++ b/packages/models/src/testing/builders/buildMailArchiveOrderPreviewData.ts @@ -0,0 +1,12 @@ +import type { MailArchiveOrderPreviewData } from "../../order/Order/types.js"; + +export function buildMailArchiveOrderPreviewData( + overrides: Partial = {}, +): MailArchiveOrderPreviewData { + return { + recurringPrice: 0, + totalPrice: 0, + feePrice: 0, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildMailRateLimitData.ts b/packages/models/src/testing/builders/buildMailRateLimitData.ts new file mode 100644 index 00000000..2d85917d --- /dev/null +++ b/packages/models/src/testing/builders/buildMailRateLimitData.ts @@ -0,0 +1,7 @@ +import type { MailRateLimitData } from "../../mail/MailRateLimit/types.js"; + +export function buildMailRateLimitData( + overrides?: Partial, +): MailRateLimitData { + return { id: "ratelimit-id", rateLimit: 1000, ...overrides }; +} diff --git a/packages/models/src/testing/builders/buildMailSettingsData.ts b/packages/models/src/testing/builders/buildMailSettingsData.ts new file mode 100644 index 00000000..502b2470 --- /dev/null +++ b/packages/models/src/testing/builders/buildMailSettingsData.ts @@ -0,0 +1,12 @@ +import type { MailSettingsData } from "../../mail/MailSettings/types.js"; + +export function buildMailSettingsData( + overrides?: Partial, +): MailSettingsData { + return { + projectId: "project-id", + blacklist: [], + whitelist: [], + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildMfaInitData.ts b/packages/models/src/testing/builders/buildMfaInitData.ts new file mode 100644 index 00000000..c34cf5c8 --- /dev/null +++ b/packages/models/src/testing/builders/buildMfaInitData.ts @@ -0,0 +1,11 @@ +import type { InitMfaResponseData } from "../../auth/Mfa/types.js"; + +export function buildMfaInitData( + overrides?: Partial, +): InitMfaResponseData { + return { + url: "otpauth://totp/mittwald?secret=THE-SECRET", + barcode: "base64-barcode-content", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildMfaStatusData.ts b/packages/models/src/testing/builders/buildMfaStatusData.ts new file mode 100644 index 00000000..64757b6a --- /dev/null +++ b/packages/models/src/testing/builders/buildMfaStatusData.ts @@ -0,0 +1,11 @@ +import type { MfaStatusData } from "../../auth/Mfa/types.js"; + +export function buildMfaStatusData( + overrides?: Partial, +): MfaStatusData { + return { + initialized: true, + confirmed: true, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildMySqlCharsetListItemData.ts b/packages/models/src/testing/builders/buildMySqlCharsetListItemData.ts new file mode 100644 index 00000000..1507e362 --- /dev/null +++ b/packages/models/src/testing/builders/buildMySqlCharsetListItemData.ts @@ -0,0 +1,12 @@ +import type { MySqlCharsetListItemData } from "../../database/MySql/types.js"; + +export function buildMySqlCharsetListItemData( + overrides?: Partial, +): MySqlCharsetListItemData { + return { + collations: ["utf8mb4_general_ci"], + versionId: "v-id", + name: "utf8mb4", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildMySqlDatabaseData.ts b/packages/models/src/testing/builders/buildMySqlDatabaseData.ts new file mode 100644 index 00000000..199e91cc --- /dev/null +++ b/packages/models/src/testing/builders/buildMySqlDatabaseData.ts @@ -0,0 +1,29 @@ +import type { MySqlData } from "../../database/MySql/types.js"; + +export function buildMySqlDatabaseData( + overrides?: Partial, +): MySqlData { + return { + characterSettings: { + collation: "utf8mb4_general_ci", + characterSet: "utf8mb4", + }, + storageUsageInBytesSetAt: "2024-01-01T00:00:00.000Z", + statusSetAt: "2024-01-01T00:00:00.000Z", + createdAt: "2024-01-01T00:00:00.000Z", + updatedAt: "2024-01-01T00:00:00.000Z", + externalHostname: "ext.example.com", + description: "test database", + hostname: "int.example.com", + storageUsageInBytes: 1024, + projectId: "project-id", + name: "db_user_abc123", + isShared: false, + status: "ready", + finalizers: [], + id: "mysql-id", + version: "8.0", + isReady: true, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildMySqlUserData.ts b/packages/models/src/testing/builders/buildMySqlUserData.ts new file mode 100644 index 00000000..cb4d8574 --- /dev/null +++ b/packages/models/src/testing/builders/buildMySqlUserData.ts @@ -0,0 +1,22 @@ +import type { MySqlUserData } from "../../database/MySqlUser/types.js"; + +export function buildMySqlUserData( + overrides?: Partial, +): MySqlUserData { + return { + passwordUpdatedAt: "2024-01-01T00:00:00.000Z", + statusSetAt: "2024-01-01T00:00:00.000Z", + createdAt: "2024-01-01T00:00:00.000Z", + updatedAt: "2024-01-01T00:00:00.000Z", + description: "test user", + databaseId: "mysql-id", + externalAccess: false, + accessLevel: "full", + id: "mysql-user-id", + disabled: false, + mainUser: false, + name: "db_user", + status: "ready", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildMySqlVersionData.ts b/packages/models/src/testing/builders/buildMySqlVersionData.ts new file mode 100644 index 00000000..2e72d70d --- /dev/null +++ b/packages/models/src/testing/builders/buildMySqlVersionData.ts @@ -0,0 +1,13 @@ +import type { MySqlVersionData } from "../../database/MySql/types.js"; + +export function buildMySqlVersionData( + overrides?: Partial, +): MySqlVersionData[number] { + return { + disabled: false, + number: "8.0", + name: "8.0", + id: "v-id", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildNewsletterInfoData.ts b/packages/models/src/testing/builders/buildNewsletterInfoData.ts new file mode 100644 index 00000000..a1899732 --- /dev/null +++ b/packages/models/src/testing/builders/buildNewsletterInfoData.ts @@ -0,0 +1,12 @@ +import type { NewsletterInfoData } from "../../newsletter/Newsletter/types.js"; + +export function buildNewsletterInfoData( + overrides?: Partial, +): NewsletterInfoData { + return { + email: "user@example.com", + registered: false, + active: false, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildNewsletterSubscriberUserData.ts b/packages/models/src/testing/builders/buildNewsletterSubscriberUserData.ts new file mode 100644 index 00000000..a3e68007 --- /dev/null +++ b/packages/models/src/testing/builders/buildNewsletterSubscriberUserData.ts @@ -0,0 +1,14 @@ +import type { UserData } from "../../user/User/types.js"; + +export function buildNewsletterSubscriberUserData( + overrides?: Partial, +): UserData { + return { + person: { + lastName: "Lovelace", + firstName: "Ada", + }, + userId: "self", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildNotificationListItemData.ts b/packages/models/src/testing/builders/buildNotificationListItemData.ts new file mode 100644 index 00000000..ca58d8d0 --- /dev/null +++ b/packages/models/src/testing/builders/buildNotificationListItemData.ts @@ -0,0 +1,15 @@ +import type { NotificationListItemData } from "../../notifications/Notifications/types.js"; + +export function buildNotificationListItemData( + overrides?: Partial, +): NotificationListItemData { + return { + reference: { aggregate: "project", domain: "project", id: "p-1" }, + createdAt: "2024-01-01T00:00:00.000Z", + type: "some-notification-type", + id: "notification-id", + severity: "info", + read: false, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildOrderData.ts b/packages/models/src/testing/builders/buildOrderData.ts new file mode 100644 index 00000000..4f802554 --- /dev/null +++ b/packages/models/src/testing/builders/buildOrderData.ts @@ -0,0 +1,15 @@ +import type { OrderData } from "../../order/Order/types.js"; + +export function buildOrderData(overrides: Partial = {}): OrderData { + return { + summary: { nonRecurring: 0, recurring: 0, summary: 0 }, + customerId: "customer-id", + orderNumber: "ORD-1", + invoicingPeriod: 12, + orderId: "order-id", + type: "NEW_ORDER", + status: "NEW", + items: [], + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildOrderItemData.ts b/packages/models/src/testing/builders/buildOrderItemData.ts new file mode 100644 index 00000000..8fb4f747 --- /dev/null +++ b/packages/models/src/testing/builders/buildOrderItemData.ts @@ -0,0 +1,14 @@ +import type { OrderItemData } from "../../order/OrderItem/types.js"; + +export function buildOrderItemData( + overrides: Partial = {}, +): OrderItemData { + return { + articleName: "Test Article", + articleId: "article-id", + orderItemId: "item-id", + isInclusive: false, + price: 0, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildPerformanceData.ts b/packages/models/src/testing/builders/buildPerformanceData.ts new file mode 100644 index 00000000..af77560d --- /dev/null +++ b/packages/models/src/testing/builders/buildPerformanceData.ts @@ -0,0 +1,35 @@ +import type { PerformanceData } from "../../performance/Performance/types.js"; + +export function buildPerformanceData( + overrides?: Partial, +): PerformanceData { + return { + metrics: [ + { + name: "page_insights_browser_ttfb_seconds", + createdAt: "2024-01-01T00:00:00.000Z", + value: 0.5, + }, + { + name: "page_insights_browser_speed_index_seconds", + createdAt: "2024-01-01T00:00:00.000Z", + value: 1, + }, + { + name: "page_insights_browser_content_downloaded_bytes", + createdAt: "2024-01-01T00:00:00.000Z", + value: 1_000_000, + }, + ], + screenshot: { + createdAt: "2024-01-01T00:00:00.000Z", + fileRef: "file-ref-1", + }, + moreDataAvailable: ["2024-06-01", "2024-06-02"], + createdAt: "2024-01-01T00:00:00.000Z", + performanceScore: 87.5, + domain: "example.com", + path: "/", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildPerformanceIngressListItemData.ts b/packages/models/src/testing/builders/buildPerformanceIngressListItemData.ts new file mode 100644 index 00000000..3e0d99bf --- /dev/null +++ b/packages/models/src/testing/builders/buildPerformanceIngressListItemData.ts @@ -0,0 +1,19 @@ +import type { IngressListItemData } from "../../ingress/Ingress/types.js"; + +export function buildPerformanceIngressListItemData( + overrides?: Partial, +): IngressListItemData { + return { + paths: [{ target: { useDefaultPage: true }, path: "/" }], + tls: { isCreated: true, acme: true }, + ips: { v4: ["1.2.3.4"], v6: [] }, + ownership: { verified: true }, + dnsValidationErrors: [], + hostname: "example.com", + projectId: "project-1", + id: "ingress-1", + isDefault: true, + isEnabled: true, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildPerformanceListItemData.ts b/packages/models/src/testing/builders/buildPerformanceListItemData.ts new file mode 100644 index 00000000..53326834 --- /dev/null +++ b/packages/models/src/testing/builders/buildPerformanceListItemData.ts @@ -0,0 +1,18 @@ +import type { PerformanceListItemData } from "../../performance/Performance/types.js"; + +export function buildPerformanceListItemData( + overrides?: Partial, +): PerformanceListItemData { + return { + paths: [ + { + createdAt: "2024-01-01T00:00:00.000Z", + screenshotFileRef: "file-1", + performanceScore: 90, + path: "/", + }, + ], + domain: "example.com", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildPerformanceTtfbAnalysisData.ts b/packages/models/src/testing/builders/buildPerformanceTtfbAnalysisData.ts new file mode 100644 index 00000000..16f5953e --- /dev/null +++ b/packages/models/src/testing/builders/buildPerformanceTtfbAnalysisData.ts @@ -0,0 +1,68 @@ +import type { + PerformanceTtfbAnalysisStraceData, + PerformanceTtfbAnalysisData, +} from "../../performance/PerformanceTtfbAnalysis/types.js"; + +type StraceStatistics = PerformanceTtfbAnalysisStraceData["dbStats"]; + +export function buildStraceStatistics( + overrides?: Partial, +): StraceStatistics { + return { + syscallCount: 10, + userspaceMs: 50, + occurrences: 1, + kernelMs: 100, + ...overrides, + }; +} + +export function buildPerformanceTtfbAnalysisData( + overrides?: Partial, +): PerformanceTtfbAnalysisData { + return { + result: { + networkingOps: [ + { + stats: buildStraceStatistics(), + description: "HTTPS request", + connectionType: "EXTERNAL", + warnLevel: "SEVERE", + ip: "203.0.113.1", + port: 443, + }, + ], + fileOps: [ + { + filepath: "/var/www/index.php", + stats: buildStraceStatistics(), + filename: "index.php", + warnLevel: "WARN", + }, + ], + dbQueries: [ + { + stats: buildStraceStatistics(), + query: "SELECT 1", + warnLevel: "NO", + }, + ], + networkingStats: buildStraceStatistics({ + userspaceMs: 10, + kernelMs: 30, + }), + fileOpsStats: buildStraceStatistics({ + userspaceMs: 400, + kernelMs: 800, + }), + dbStats: buildStraceStatistics({ userspaceMs: 200, kernelMs: 400 }), + miscStats: buildStraceStatistics({ userspaceMs: 20, kernelMs: 60 }), + actualUrl: "https://example.com/", + slowdownFactor: 2, + ttfbMs: 400, + }, + executedAt: "2024-01-01T00:00:00.000Z", + id: "strace-1", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildPlanChangeData.ts b/packages/models/src/testing/builders/buildPlanChangeData.ts new file mode 100644 index 00000000..8d517832 --- /dev/null +++ b/packages/models/src/testing/builders/buildPlanChangeData.ts @@ -0,0 +1,14 @@ +import type { PlanChangeData } from "../../contract/PlanChange/types.js"; + +import { buildContractArticleData } from "./buildContractArticleData.js"; + +export function buildPlanChangeData( + overrides?: Partial, +): PlanChangeData { + return { + scheduledAtDate: "2024-01-01T00:00:00.000Z", + newArticles: [buildContractArticleData()], + targetDate: "2024-06-01T00:00:00.000Z", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildProjectAIDetailedModelData.ts b/packages/models/src/testing/builders/buildProjectAIDetailedModelData.ts new file mode 100644 index 00000000..bdd993a0 --- /dev/null +++ b/packages/models/src/testing/builders/buildProjectAIDetailedModelData.ts @@ -0,0 +1,18 @@ +import type { ProjectAIModelData } from "../../ai/ProjectAIModel/types.js"; + +export function buildProjectAIDetailedModelData( + overrides?: Partial, +): ProjectAIModelData { + return { + termsOfServiceLink: "https://tos.example.com/detailed", + docLink: "https://docs.example.com/detailed", + activeAt: "2024-01-01T00:00:00.000Z", + displayName: "GPT Detailed", + replacesModelNames: [], + name: "gpt-detailed", + status: "active", + label: "stable", + tokenFactor: 1, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildProjectAIPlanData.ts b/packages/models/src/testing/builders/buildProjectAIPlanData.ts new file mode 100644 index 00000000..218601d1 --- /dev/null +++ b/packages/models/src/testing/builders/buildProjectAIPlanData.ts @@ -0,0 +1,18 @@ +import type { ProjectAIPlanData } from "../../ai/ProjectAIPlan/types.js"; + +export function buildProjectAIPlanData( + overrides?: Partial, +): ProjectAIPlanData { + return { + keys: { + planLimit: 1000, + available: 100, + used: 0, + }, + nextTokenReset: "2024-01-01T00:00:00.000Z", + modelTermsApprovalRequired: false, + projectId: "project-id", + planId: "plan-id", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildProjectData.ts b/packages/models/src/testing/builders/buildProjectData.ts new file mode 100644 index 00000000..15bd9cc6 --- /dev/null +++ b/packages/models/src/testing/builders/buildProjectData.ts @@ -0,0 +1,33 @@ +import type { ProjectData } from "../../project/Project/types.js"; + +export function buildProjectData( + overrides?: Partial, +): ProjectData { + return { + directories: { + Logs: "/home/p-1/logs", + Web: "/home/p-1/html", + Home: "/home/p-1", + }, + backupStorageUsageInBytesSetAt: "2024-01-01T00:00:00.000Z", + webStorageUsageInBytesSetAt: "2024-01-01T00:00:00.000Z", + statusSetAt: "2024-01-01T00:00:00.000Z", + createdAt: "2024-01-01T00:00:00.000Z", + backupStorageUsageInBytes: 0, + clusterDomain: "example.com", + description: "test project", + customerId: "customer-id", + serverGroupId: "group-id", + webStorageUsageInBytes: 0, + clusterID: "cluster-1", + serverId: "server-id", + supportedFeatures: [], + readiness: "ready", + shortId: "abc123", + id: "project-id", + status: "ready", + enabled: true, + isReady: true, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildProjectInviteData.ts b/packages/models/src/testing/builders/buildProjectInviteData.ts new file mode 100644 index 00000000..5c34515d --- /dev/null +++ b/packages/models/src/testing/builders/buildProjectInviteData.ts @@ -0,0 +1,15 @@ +import type { ProjectInviteData } from "../../project/ProjectInvite/types.js"; + +export function buildProjectInviteData( + overrides?: Partial, +): ProjectInviteData { + return { + information: { invitedBy: "user-id" }, + projectDescription: "test project", + mailAddress: "user@example.com", + projectId: "project-id", + id: "invite-id", + role: "owner", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildProjectListItemData.ts b/packages/models/src/testing/builders/buildProjectListItemData.ts new file mode 100644 index 00000000..a96560a6 --- /dev/null +++ b/packages/models/src/testing/builders/buildProjectListItemData.ts @@ -0,0 +1,28 @@ +import type { ProjectListItemData } from "../../project/Project/types.js"; + +export function buildProjectListItemData( + overrides?: Partial, +): ProjectListItemData { + return { + backupStorageUsageInBytesSetAt: "2024-01-01T00:00:00.000Z", + webStorageUsageInBytesSetAt: "2024-01-01T00:00:00.000Z", + statusSetAt: "2024-01-01T00:00:00.000Z", + createdAt: "2024-01-01T00:00:00.000Z", + customerMeta: { id: "customer-id" }, + backupStorageUsageInBytes: 0, + description: "test project", + customerId: "customer-id", + serverGroupId: "group-id", + webStorageUsageInBytes: 0, + deletionRequested: false, + serverId: "server-id", + supportedFeatures: [], + readiness: "ready", + shortId: "abc123", + id: "project-id", + status: "ready", + enabled: true, + isReady: true, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildProjectMembershipData.ts b/packages/models/src/testing/builders/buildProjectMembershipData.ts new file mode 100644 index 00000000..6d11a80e --- /dev/null +++ b/packages/models/src/testing/builders/buildProjectMembershipData.ts @@ -0,0 +1,18 @@ +import type { ProjectMembershipData } from "../../project/ProjectMembership/types.js"; + +export function buildProjectMembershipData( + overrides?: Partial, +): ProjectMembershipData { + return { + email: "user@example.com", + projectId: "project-id", + lastName: "Lovelace", + id: "membership-id", + userId: "user-id", + firstName: "Ada", + inherited: false, + role: "owner", + mfa: false, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildRecoveryCodesData.ts b/packages/models/src/testing/builders/buildRecoveryCodesData.ts new file mode 100644 index 00000000..4e053476 --- /dev/null +++ b/packages/models/src/testing/builders/buildRecoveryCodesData.ts @@ -0,0 +1,10 @@ +import type { RecoveryCodesData } from "../../auth/RecoveryCodes/types.js"; + +export function buildRecoveryCodesData( + overrides?: Partial, +): RecoveryCodesData { + return { + codes: ["code-1", "code-2", "code-3"], + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildRedisDatabaseData.ts b/packages/models/src/testing/builders/buildRedisDatabaseData.ts new file mode 100644 index 00000000..5e257eba --- /dev/null +++ b/packages/models/src/testing/builders/buildRedisDatabaseData.ts @@ -0,0 +1,29 @@ +import type { RedisData } from "../../database/Redis/types.js"; + +export function buildRedisDatabaseData( + overrides?: Partial, +): RedisData { + return { + configuration: { + maxMemoryPolicy: "noeviction", + additionalFlags: [], + maxMemory: "512Mi", + persistent: true, + }, + storageUsageInBytesSetAt: "2024-01-01T00:00:00.000Z", + statusSetAt: "2024-01-01T00:00:00.000Z", + createdAt: "2024-01-01T00:00:00.000Z", + updatedAt: "2024-01-01T00:00:00.000Z", + hostname: "redis.example.com", + description: "test redis", + storageUsageInBytes: 2048, + projectId: "project-id", + name: "redis_abc123", + status: "ready", + finalizers: [], + id: "redis-id", + version: "7.0", + port: 6379, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildRedisVersionData.ts b/packages/models/src/testing/builders/buildRedisVersionData.ts new file mode 100644 index 00000000..18620e78 --- /dev/null +++ b/packages/models/src/testing/builders/buildRedisVersionData.ts @@ -0,0 +1,13 @@ +import type { RedisVersionData } from "../../database/Redis/types.js"; + +export function buildRedisVersionData( + overrides?: Partial, +): RedisVersionData[number] { + return { + disabled: false, + number: "7.0", + name: "7.0", + id: "v-id", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildRegisterRequestData.ts b/packages/models/src/testing/builders/buildRegisterRequestData.ts new file mode 100644 index 00000000..082266fb --- /dev/null +++ b/packages/models/src/testing/builders/buildRegisterRequestData.ts @@ -0,0 +1,15 @@ +import type { RegisterRequestData } from "../../auth/Registration/types.js"; + +export function buildRegisterRequestData( + overrides?: Partial, +): RegisterRequestData { + return { + person: { + lastName: "Lovelace", + firstName: "Ada", + }, + password: "correct-horse-battery-staple", + email: "user@example.com", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildRegistryData.ts b/packages/models/src/testing/builders/buildRegistryData.ts new file mode 100644 index 00000000..49c7239f --- /dev/null +++ b/packages/models/src/testing/builders/buildRegistryData.ts @@ -0,0 +1,14 @@ +import type { RegistryData } from "../../container/Registry/types.js"; + +export function buildRegistryData( + overrides?: Partial, +): RegistryData { + return { + credentials: { username: "user", valid: true }, + description: "test registry", + uri: "registry.example.com", + projectId: "project-id", + id: "registry-id", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildServerData.ts b/packages/models/src/testing/builders/buildServerData.ts new file mode 100644 index 00000000..6b1b029b --- /dev/null +++ b/packages/models/src/testing/builders/buildServerData.ts @@ -0,0 +1,25 @@ +import type { ServerListItemData } from "../../server/Server/types.js"; + +export function buildServerListItemData( + overrides?: Partial, +): ServerListItemData { + return { + machineType: { + name: "test-machine", + memory: "4Gi", + cpu: "2", + }, + createdAt: "2024-01-01T00:00:00.000Z", + clusterName: "test-cluster", + description: "test server", + customerId: "customer-id", + groupId: "group-id", + readiness: "ready", + shortId: "abc123", + id: "server-id", + status: "ready", + storage: "20Gi", + isReady: true, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildSessionData.ts b/packages/models/src/testing/builders/buildSessionData.ts new file mode 100644 index 00000000..2d7f5b44 --- /dev/null +++ b/packages/models/src/testing/builders/buildSessionData.ts @@ -0,0 +1,26 @@ +import type { + SessionListItemData, + SessionData, +} from "../../user/Session/types.js"; + +export function buildSessionData( + overrides: Partial = {}, +): SessionData { + return { + device: { browser: "Firefox", type: "desktop", os: "Linux" }, + created: "2024-01-01T00:00:00.000Z", + tokenId: "token-id", + ...overrides, + }; +} + +export function buildSessionListItemData( + overrides: Partial = {}, +): SessionListItemData { + return { + device: { browser: "Firefox", type: "desktop", os: "Linux" }, + created: "2024-01-01T00:00:00.000Z", + tokenId: "token-id", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildSessionTokenData.ts b/packages/models/src/testing/builders/buildSessionTokenData.ts new file mode 100644 index 00000000..725290f0 --- /dev/null +++ b/packages/models/src/testing/builders/buildSessionTokenData.ts @@ -0,0 +1,12 @@ +import type { SessionTokenData } from "../../auth/SessionToken/types.js"; + +export function buildSessionTokenData( + overrides?: Partial, +): SessionTokenData { + return { + expires: "2099-01-01T00:00:00.000Z", + refreshToken: "refresh-token", + token: "session-token", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildSftpUserData.ts b/packages/models/src/testing/builders/buildSftpUserData.ts new file mode 100644 index 00000000..9a638680 --- /dev/null +++ b/packages/models/src/testing/builders/buildSftpUserData.ts @@ -0,0 +1,18 @@ +import type { SftpUserData } from "../../access/SftpUser/types.js"; + +export function buildSftpUserData( + overrides?: Partial, +): SftpUserData { + return { + authUpdatedAt: "2024-01-01T00:00:00.000Z", + createdAt: "2024-01-01T00:00:00.000Z", + description: "test sftp user", + projectId: "project-id", + accessLevel: "read", + id: "sftp-user-id", + userName: "p-sftp", + hasPassword: true, + active: true, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildSpotlightStateData.ts b/packages/models/src/testing/builders/buildSpotlightStateData.ts new file mode 100644 index 00000000..be08a32b --- /dev/null +++ b/packages/models/src/testing/builders/buildSpotlightStateData.ts @@ -0,0 +1,12 @@ +import type { SpotlightStateData } from "../../user/Spotlight/types.js"; + +export function buildSpotlightStateData( + overrides: Partial = {}, +): SpotlightStateData { + return { + spotlightId: "ai-agent-verknuepfen-btn", + acknowledged: false, + used: false, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildSshKeyData.ts b/packages/models/src/testing/builders/buildSshKeyData.ts new file mode 100644 index 00000000..57f62b56 --- /dev/null +++ b/packages/models/src/testing/builders/buildSshKeyData.ts @@ -0,0 +1,32 @@ +import type { + SshKeyListItemData, + SshKeyData, +} from "../../user/SshKey/types.js"; + +export function buildSshKeyData( + overrides: Partial = {}, +): SshKeyData { + return { + createdAt: "2024-01-01T00:00:00.000Z", + fingerprint: "SHA256:abc", + algorithm: "ssh-ed25519", + key: "ssh-ed25519 AAAA", + sshKeyId: "sshkey-id", + comment: "laptop", + ...overrides, + }; +} + +export function buildSshKeyListItemData( + overrides: Partial = {}, +): SshKeyListItemData { + return { + createdAt: "2024-01-01T00:00:00.000Z", + fingerprint: "SHA256:abc", + algorithm: "ssh-ed25519", + key: "ssh-ed25519 AAAA", + sshKeyId: "sshkey-id", + comment: "laptop", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildSshUserData.ts b/packages/models/src/testing/builders/buildSshUserData.ts new file mode 100644 index 00000000..e9d264fe --- /dev/null +++ b/packages/models/src/testing/builders/buildSshUserData.ts @@ -0,0 +1,17 @@ +import type { SshUserData } from "../../access/SshUser/types.js"; + +export function buildSshUserData( + overrides?: Partial, +): SshUserData { + return { + authUpdatedAt: "2024-01-01T00:00:00.000Z", + createdAt: "2024-01-01T00:00:00.000Z", + description: "test ssh user", + projectId: "project-id", + id: "ssh-user-id", + hasPassword: true, + userName: "p-ssh", + active: true, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildStorageMetricsData.ts b/packages/models/src/testing/builders/buildStorageMetricsData.ts new file mode 100644 index 00000000..e0ffac85 --- /dev/null +++ b/packages/models/src/testing/builders/buildStorageMetricsData.ts @@ -0,0 +1,24 @@ +import type { StorageStatisticsCategoryApiData } from "../../monitoring/StorageMetrics/StorageStatisticsCategory.js"; +import type { StorageMetricsData } from "../../monitoring/StorageMetrics/types.js"; + +export function buildStorageMetricsData( + overrides?: Partial, +): StorageMetricsData { + return { + meta: { totalUsageInBytes: 1073741824 }, + name: "test-metrics", + kind: "server", + id: "sm-1", + ...overrides, + }; +} + +export function buildStorageStatisticsCategoryData( + overrides?: Partial, +): StorageStatisticsCategoryApiData { + return { + totalUsageInBytes: 0, + kind: "webspace", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildSupportCodeData.ts b/packages/models/src/testing/builders/buildSupportCodeData.ts new file mode 100644 index 00000000..8a7007ef --- /dev/null +++ b/packages/models/src/testing/builders/buildSupportCodeData.ts @@ -0,0 +1,11 @@ +import type { SupportCodeData } from "../../user/SupportCode/types.js"; + +export function buildSupportCodeData( + overrides: Partial = {}, +): SupportCodeData { + return { + expiresAt: "2024-01-01T00:00:00.000Z", + supportCode: "SUP-123", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildSystemSoftwareData.ts b/packages/models/src/testing/builders/buildSystemSoftwareData.ts new file mode 100644 index 00000000..ddd69034 --- /dev/null +++ b/packages/models/src/testing/builders/buildSystemSoftwareData.ts @@ -0,0 +1,26 @@ +import type { + SystemSoftwareListItemData, + SystemSoftwareData, +} from "../../app/SystemSoftware/types.js"; + +export function buildSystemSoftwareData( + overrides: Partial = {}, +): SystemSoftwareData { + return { + id: "systemsoftware-id", + tags: ["php"], + name: "php", + ...overrides, + }; +} + +export function buildSystemSoftwareListItemData( + overrides: Partial = {}, +): SystemSoftwareListItemData { + return { + id: "systemsoftware-id", + tags: ["php"], + name: "php", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildSystemSoftwareVersionData.ts b/packages/models/src/testing/builders/buildSystemSoftwareVersionData.ts new file mode 100644 index 00000000..b8f33b37 --- /dev/null +++ b/packages/models/src/testing/builders/buildSystemSoftwareVersionData.ts @@ -0,0 +1,26 @@ +import type { + SystemSoftwareVersionListItemData, + SystemSoftwareVersionData, +} from "../../app/SystemSoftwareVersion/types.js"; + +export function buildSystemSoftwareVersionData( + overrides: Partial = {}, +): SystemSoftwareVersionData { + return { + id: "systemsoftwareversion-id", + internalVersion: "8.3.0", + externalVersion: "8.3", + ...overrides, + }; +} + +export function buildSystemSoftwareVersionListItemData( + overrides: Partial = {}, +): SystemSoftwareVersionListItemData { + return { + id: "systemsoftwareversion-id", + internalVersion: "8.3.0", + externalVersion: "8.3", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildTldData.ts b/packages/models/src/testing/builders/buildTldData.ts new file mode 100644 index 00000000..9936cc1f --- /dev/null +++ b/packages/models/src/testing/builders/buildTldData.ts @@ -0,0 +1,13 @@ +import type { TldData } from "../../domain/Tld/types.js"; + +// TldData === TldListItemData (both resolve to DomainTopLevel). +export function buildTldData(overrides?: Partial): TldData { + return { + transferAuthCodeRequired: false, + transferAuthentication: "code", + irtp: false, + rgpDays: 30, + tld: "de", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildTlsAcmeData.ts b/packages/models/src/testing/builders/buildTlsAcmeData.ts new file mode 100644 index 00000000..bbed70fb --- /dev/null +++ b/packages/models/src/testing/builders/buildTlsAcmeData.ts @@ -0,0 +1,12 @@ +import type { TlsAcmeData } from "../../certificate/Tls/types.js"; + +export function buildTlsAcmeData( + overrides?: Partial, +): TlsAcmeData { + return { + requestDeadline: "2999-01-01T00:00:00.000Z", + isCreated: false, + acme: true, + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildTlsCertificateData.ts b/packages/models/src/testing/builders/buildTlsCertificateData.ts new file mode 100644 index 00000000..dd81fa39 --- /dev/null +++ b/packages/models/src/testing/builders/buildTlsCertificateData.ts @@ -0,0 +1,10 @@ +import type { TlsCertificateData } from "../../certificate/Tls/types.js"; + +export function buildTlsCertificateData( + overrides?: Partial, +): TlsCertificateData { + return { + certificateId: "certificate-id", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildUnlockedLeadData.ts b/packages/models/src/testing/builders/buildUnlockedLeadData.ts new file mode 100644 index 00000000..38aab488 --- /dev/null +++ b/packages/models/src/testing/builders/buildUnlockedLeadData.ts @@ -0,0 +1,51 @@ +import type { UnlockedLeadData } from "../../fyndr/UnlockedLead/types.js"; + +export function buildUnlockedLeadData( + overrides?: Partial, +): UnlockedLeadData { + return { + company: { + phoneNumbers: ["+4943112345"], + websiteType: ["Corporate"], + coreProduct: ["Software"], + salesVolume: 2_000_000, + companyType: ["GmbH"], + targetGroup: ["B2B"], + city: "Kiel", + county: "SH", + name: "Acme", + }, + contact: { + address: { + countryCode: "DE", + houseNumber: "1", + street: "Main", + city: "Kiel", + zip: "24103", + }, + }, + hoster: { + mailServer: ["mail.example.com"], + nameServer: ["ns.example.com"], + server: ["srv"], + }, + mainTechnology: { + categoryPriority: 1, + name: "TYPO3", + version: "12", + }, + technologies: [{ categoryPriority: 1, name: "TYPO3", version: "12" }], + socialMedia: [{ url: "https://linkedin.com", network: "LinkedIn" }], + metrics: { basic: { desktop: {}, mobile: {} } }, + unlockedAt: "2024-02-01T00:00:00.000Z", + actualUrl: "https://example.com", + businessFields: ["IT"], + domain: "example.com", + screenshot: "base64", + description: "desc", + languages: ["de"], + potential: 0.72, + leadId: "l-1", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildUserData.ts b/packages/models/src/testing/builders/buildUserData.ts new file mode 100644 index 00000000..d59c1b6c --- /dev/null +++ b/packages/models/src/testing/builders/buildUserData.ts @@ -0,0 +1,9 @@ +import type { UserData } from "../../user/User/types.js"; + +export function buildUserData(overrides: Partial = {}): UserData { + return { + person: { lastName: "Lovelace", firstName: "Ada" }, + userId: "user-id", + ...overrides, + }; +} diff --git a/packages/models/src/testing/builders/buildVolumeData.ts b/packages/models/src/testing/builders/buildVolumeData.ts new file mode 100644 index 00000000..2413f219 --- /dev/null +++ b/packages/models/src/testing/builders/buildVolumeData.ts @@ -0,0 +1,14 @@ +import type { VolumeData } from "../../container/Volume/types.js"; + +export function buildVolumeData(overrides?: Partial): VolumeData { + return { + storageUsageInBytesSetAt: "2024-01-01T00:00:00.000Z", + linkedServices: ["container-a"], + storageUsageInBytes: 1024, + name: "test-volume", + stackId: "stack-id", + id: "volume-id", + orphaned: false, + ...overrides, + }; +} diff --git a/packages/models/src/testing/index.ts b/packages/models/src/testing/index.ts new file mode 100644 index 00000000..82739697 --- /dev/null +++ b/packages/models/src/testing/index.ts @@ -0,0 +1,138 @@ +export * from "./builders/buildAIApiKeyData.js"; +export * from "./builders/buildAIModelData.js"; +export * from "./builders/buildApiTokenData.js"; +export * from "./builders/buildAppData.js"; +export * from "./builders/buildAppInstallationData.js"; +export * from "./builders/buildAppLinkedDatabaseData.js"; +export * from "./builders/buildAppUserInputData.js"; +export * from "./builders/buildAppVersionData.js"; +export * from "./builders/buildArticleData.js"; +export * from "./builders/buildBackupData.js"; +export * from "./builders/buildBackupExportData.js"; +export * from "./builders/buildBackupScheduleData.js"; +export * from "./builders/buildCertificateCheckReplaceResponseData.js"; +export * from "./builders/buildCertificateContactData.js"; +export * from "./builders/buildCertificateData.js"; +export * from "./builders/buildCertificateRequestData.js"; +export * from "./builders/buildCityData.js"; +export * from "./builders/buildContactVerificationData.js"; +export * from "./builders/buildContainerData.js"; +export * from "./builders/buildContractArticleData.js"; +export * from "./builders/buildContractData.js"; +export * from "./builders/buildContractItemData.js"; +export * from "./builders/buildContractPartnerData.js"; +export * from "./builders/buildContributorExtensionData.js"; +export * from "./builders/buildContributorExtensionListItemData.js"; +export * from "./builders/buildContributorOnBehalfInvoiceData.js"; +export * from "./builders/buildConversationCategoryData.js"; +export * from "./builders/buildConversationData.js"; +export * from "./builders/buildConversationListItemData.js"; +export * from "./builders/buildConversationMessageData.js"; +export * from "./builders/buildConversationUserData.js"; +export * from "./builders/buildCronjobData.js"; +export * from "./builders/buildCronjobExecutionData.js"; +export * from "./builders/buildCustomerAIDetailedModelData.js"; +export * from "./builders/buildCustomerAIPlanData.js"; +export * from "./builders/buildCustomerData.js"; +export * from "./builders/buildCustomerInviteData.js"; +export * from "./builders/buildCustomerMembershipData.js"; +export * from "./builders/buildDeliveryBoxData.js"; +export * from "./builders/buildDnsCertificateSpecData.js"; +export * from "./builders/buildDnsCertificateStatusData.js"; +export * from "./builders/buildDnsRecordCaaData.js"; +export * from "./builders/buildDnsRecordCnameData.js"; +export * from "./builders/buildDnsRecordCombinedAData.js"; +export * from "./builders/buildDnsRecordMxData.js"; +export * from "./builders/buildDnsRecordSettingsData.js"; +export * from "./builders/buildDnsRecordSrvComponentData.js"; +export * from "./builders/buildDnsRecordTxtComponentData.js"; +export * from "./builders/buildDnsZoneData.js"; +export * from "./builders/buildDomainDomainData.js"; +export * from "./builders/buildDomainHandleData.js"; +export * from "./builders/buildDomainHandleFieldData.js"; +export * from "./builders/buildDomainHandleReadableData.js"; +export * from "./builders/buildDomainListItemData.js"; +export * from "./builders/buildDomainMigrationData.js"; +export * from "./builders/buildDomainMigrationDnsRecordData.js"; +export * from "./builders/buildDomainMigrationDomainData.js"; +export * from "./builders/buildDomainOrderPreviewData.js"; +export * from "./builders/buildDomainProcessData.js"; +export * from "./builders/buildExtensionData.js"; +export * from "./builders/buildExtensionInstanceContractData.js"; +export * from "./builders/buildExtensionInstanceData.js"; +export * from "./builders/buildExtensionInstanceListItemData.js"; +export * from "./builders/buildExtensionListItemData.js"; +export * from "./builders/buildExternalCertificateOrderPreviewData.js"; +export * from "./builders/buildFeedbackListItemData.js"; +export * from "./builders/buildFileDownloadTokenData.js"; +export * from "./builders/buildFileMetaData.js"; +export * from "./builders/buildFileUploadRulesData.js"; +export * from "./builders/buildFileUploadTokenData.js"; +export * from "./builders/buildFinderProfileData.js"; +export * from "./builders/buildFinderProfileRequestCustomerData.js"; +export * from "./builders/buildFinderProfileRequestData.js"; +export * from "./builders/buildHostingOrderPreviewData.js"; +export * from "./builders/buildIngressData.js"; +export * from "./builders/buildIngressPathData.js"; +export * from "./builders/buildInstalledSystemSoftwareData.js"; +export * from "./builders/buildInvoiceData.js"; +export * from "./builders/buildInvoiceItemData.js"; +export * from "./builders/buildInvoiceItemGroupData.js"; +export * from "./builders/buildInvoiceRecipientData.js"; +export * from "./builders/buildInvoiceSettingsData.js"; +export * from "./builders/buildLeadData.js"; +export * from "./builders/buildLeadFyndrOrderPreviewData.js"; +export * from "./builders/buildLeadsExportData.js"; +export * from "./builders/buildLicenseData.js"; +export * from "./builders/buildLicenseOrderPreviewData.js"; +export * from "./builders/buildMailAddressArchiveData.js"; +export * from "./builders/buildMailAddressBackupData.js"; +export * from "./builders/buildMailAddressData.js"; +export * from "./builders/buildMailArchiveOrderPreviewData.js"; +export * from "./builders/buildMailRateLimitData.js"; +export * from "./builders/buildMailSettingsData.js"; +export * from "./builders/buildMfaInitData.js"; +export * from "./builders/buildMfaStatusData.js"; +export * from "./builders/buildMySqlCharsetListItemData.js"; +export * from "./builders/buildMySqlDatabaseData.js"; +export * from "./builders/buildMySqlUserData.js"; +export * from "./builders/buildMySqlVersionData.js"; +export * from "./builders/buildNewsletterInfoData.js"; +export * from "./builders/buildNewsletterSubscriberUserData.js"; +export * from "./builders/buildNotificationListItemData.js"; +export * from "./builders/buildOrderData.js"; +export * from "./builders/buildOrderItemData.js"; +export * from "./builders/buildPerformanceData.js"; +export * from "./builders/buildPerformanceIngressListItemData.js"; +export * from "./builders/buildPerformanceListItemData.js"; +export * from "./builders/buildPerformanceTtfbAnalysisData.js"; +export * from "./builders/buildPlanChangeData.js"; +export * from "./builders/buildProjectAIDetailedModelData.js"; +export * from "./builders/buildProjectAIPlanData.js"; +export * from "./builders/buildProjectData.js"; +export * from "./builders/buildProjectInviteData.js"; +export * from "./builders/buildProjectListItemData.js"; +export * from "./builders/buildProjectMembershipData.js"; +export * from "./builders/buildRecoveryCodesData.js"; +export * from "./builders/buildRedisDatabaseData.js"; +export * from "./builders/buildRedisVersionData.js"; +export * from "./builders/buildRegisterRequestData.js"; +export * from "./builders/buildRegistryData.js"; +export * from "./builders/buildServerData.js"; +export * from "./builders/buildSessionData.js"; +export * from "./builders/buildSessionTokenData.js"; +export * from "./builders/buildSftpUserData.js"; +export * from "./builders/buildSpotlightStateData.js"; +export * from "./builders/buildSshKeyData.js"; +export * from "./builders/buildSshUserData.js"; +export * from "./builders/buildStorageMetricsData.js"; +export * from "./builders/buildSupportCodeData.js"; +export * from "./builders/buildSystemSoftwareData.js"; +export * from "./builders/buildSystemSoftwareVersionData.js"; +export * from "./builders/buildTldData.js"; +export * from "./builders/buildTlsAcmeData.js"; +export * from "./builders/buildTlsCertificateData.js"; +export * from "./builders/buildUnlockedLeadData.js"; +export * from "./builders/buildUserData.js"; +export * from "./builders/buildVolumeData.js"; +export * from "./installBehaviors.js"; diff --git a/packages/models/src/testing/installBehaviors.ts b/packages/models/src/testing/installBehaviors.ts new file mode 100644 index 00000000..ee4160eb --- /dev/null +++ b/packages/models/src/testing/installBehaviors.ts @@ -0,0 +1,34 @@ +import type { Behaviors } from "../config/config.js"; + +import { config } from "../config/config.js"; + +export type FakeBehaviors = { + [K in keyof Behaviors]?: Partial; +}; + +function installBehavior( + key: K, + partial: Partial, +): void { + // Object.keys avoids the Proxy's throwing get trap for missing behaviors. + const existing = Object.keys(config.behaviors).includes(key) + ? config.behaviors[key] + : {}; + + config.behaviors[key] = { + ...existing, + ...partial, + } as Behaviors[K]; +} + +export function installBehaviors(partial: FakeBehaviors): void { + for (const key of Object.keys(partial) as (keyof Behaviors)[]) { + installBehavior(key, partial[key] ?? {}); + } +} + +export function resetBehaviors(): void { + for (const key of Object.keys(config.behaviors)) { + delete config.behaviors[key as keyof Behaviors]; + } +} diff --git a/packages/models/src/testing/registryContract.test.ts b/packages/models/src/testing/registryContract.test.ts new file mode 100644 index 00000000..8e3c3e4e --- /dev/null +++ b/packages/models/src/testing/registryContract.test.ts @@ -0,0 +1,41 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { + buildContainerData, + installBehaviors, + resetBehaviors, +} from "./index.js"; +import { config } from "../config/config.js"; + +afterEach(resetBehaviors); + +describe("behavior registry contract", () => { + test("fails fast before behaviors are installed", () => { + expect(() => config.behaviors.container).toThrowError(/is not initialized/); + }); + + test("resolves behaviors after installBehaviors", async () => { + const find = vi.fn().mockResolvedValue(buildContainerData({ id: "c-1" })); + + installBehaviors({ container: { find } }); + + expect(config.behaviors.container.find).toBe(find); + + const container = await config.behaviors.container.find("c-1", "s-1"); + + expect(container?.id).toBe("c-1"); + expect(find).toHaveBeenCalledWith("c-1", "s-1"); + }); + + test("resetBehaviors restores fail-fast behavior", () => { + installBehaviors({ + container: { + find: vi.fn().mockResolvedValue(buildContainerData()), + }, + }); + + resetBehaviors(); + + expect(() => config.behaviors.container).toThrowError(/is not initialized/); + }); +}); diff --git a/packages/models/src/user/ApiToken/ApiToken.test.ts b/packages/models/src/user/ApiToken/ApiToken.test.ts new file mode 100644 index 00000000..ecc2f037 --- /dev/null +++ b/packages/models/src/user/ApiToken/ApiToken.test.ts @@ -0,0 +1,148 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { DateTime } from "luxon"; + +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { + buildApiTokenListItemData, + buildApiTokenData, +} from "../../testing/builders/buildApiTokenData.js"; +import { ReferenceModel } from "../../base/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { + ApiTokenDetailed, + ApiTokenListItem, + ApiTokenList, + ApiToken, +} from "./ApiToken.js"; + +afterEach(resetBehaviors); + +describe("ApiToken references", () => { + test("find delegates and returns detailed data", async () => { + const find = vi + .fn() + .mockResolvedValue(buildApiTokenData({ apiTokenId: "a-1" })); + installBehaviors({ apiToken: { find } }); + const result = await ApiToken.find("a-1"); + expect(find).toHaveBeenCalledWith("a-1"); + expect(result).toBeInstanceOf(ApiTokenDetailed); + expect(result?.id).toBe("a-1"); + }); + + test("find returns undefined when missing", async () => { + installBehaviors({ + apiToken: { find: vi.fn().mockResolvedValue(undefined) }, + }); + expect(await ApiToken.find("missing")).toBeUndefined(); + }); + + test("get returns a detailed token and throws when missing", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildApiTokenData()) + .mockResolvedValueOnce(undefined); + installBehaviors({ apiToken: { find } }); + expect(await ApiToken.get("apitoken-id")).toBeInstanceOf(ApiTokenDetailed); + await expect(ApiToken.get("missing")).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("findDetailed delegates with the reference id", async () => { + const find = vi + .fn() + .mockResolvedValue(buildApiTokenData({ apiTokenId: "a-2" })); + installBehaviors({ apiToken: { find } }); + await ApiToken.ofId("a-2").findDetailed(); + expect(find).toHaveBeenCalledWith("a-2"); + }); +}); + +test("maps data and expiration getters", async () => { + const find = vi + .fn() + .mockResolvedValueOnce( + buildApiTokenData({ + expiresAt: "2000-01-01T00:00:00.000Z", + description: "past", + }), + ) + .mockResolvedValueOnce( + buildApiTokenData({ expiresAt: "2999-01-01T00:00:00.000Z" }), + ); + installBehaviors({ apiToken: { find } }); + const past = await ApiToken.get("apitoken-id"); + const future = await ApiToken.get("apitoken-id"); + expect(past.description).toBe("past"); + expect(past.expiresAt).toBeInstanceOf(DateTime); + expect(past.expired).toBe(true); + expect(future.expired).toBe(false); +}); + +test("findCommon/getCommon resolve references and stay idempotent once materialized", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildApiTokenData({ apiTokenId: "a-c" })) + .mockResolvedValueOnce(buildApiTokenData({ apiTokenId: "a-g" })); + installBehaviors({ apiToken: { find } }); + const common = await ApiToken.ofId("a-c").findCommon(); + expect(common).toBeInstanceOf(ApiTokenDetailed); + expect(common?.id).toBe("a-c"); + expect(await ApiToken.ofId("a-g").getCommon()).toBeInstanceOf( + ApiTokenDetailed, + ); + + const materialized = new ApiTokenDetailed( + buildApiTokenData({ apiTokenId: "a-1" }), + ); + find.mockClear(); + expect(await materialized.findCommon()).toBe(materialized); + expect(await materialized.getCommon()).toBe(materialized); + expect(find).not.toHaveBeenCalled(); +}); + +test("findCommon yields undefined and getCommon throws for missing tokens", async () => { + installBehaviors({ + apiToken: { find: vi.fn().mockResolvedValue(undefined) }, + }); + expect(await ApiToken.ofId("missing").findCommon()).toBeUndefined(); + await expect(ApiToken.ofId("missing").getCommon()).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); +}); + +test("treats a token without expiration as non-expiring", () => { + const token = new ApiTokenDetailed(buildApiTokenData()); + expect(token.expiresAt).toBeUndefined(); + expect(token.expired).toBe(false); +}); + +test("materializes list items and total count", async () => { + const list = vi + .fn() + .mockResolvedValue({ items: [buildApiTokenListItemData()], totalCount: 7 }); + installBehaviors({ apiToken: { list } }); + const result = await ApiToken.query().execute(); + expect(result).toBeInstanceOf(ApiTokenList); + expect(result.items[0]).toBeInstanceOf(ApiTokenListItem); + expect(result.totalCount).toBe(7); + expect(await ApiToken.query().getTotalCount()).toBe(7); +}); + +test("preserves the list item composition chain", () => { + const item = new ApiTokenListItem(buildApiTokenListItemData()); + expect(item).toBeInstanceOf(ReferenceModel); + expect(item.data).toBeDefined(); +}); diff --git a/packages/models/src/user/ApiToken/ApiToken.ts b/packages/models/src/user/ApiToken/ApiToken.ts new file mode 100644 index 00000000..51cff87f --- /dev/null +++ b/packages/models/src/user/ApiToken/ApiToken.ts @@ -0,0 +1,124 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; + +import type { + ApiTokenCreateRequestData, + ApiTokenUpdateRequestData, + ApiTokenListItemData, + ApiTokenData, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + ListDataModel, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "ApiToken", +}) +export class ApiToken extends ReferenceModel { + public static async create(data: ApiTokenCreateRequestData) { + return await config.behaviors.apiToken.create(data); + } + + public static async find(id: string) { + const data = await config.behaviors.apiToken.find(id); + if (data) { + return new ApiTokenDetailed(data); + } + } + + public static async get(id: string) { + const apiToken = await this.find(id); + assertObjectFound(apiToken, ApiToken, id); + return apiToken; + } + + public static ofId(id: string) { + return new ApiToken(id); + } + + public static query() { + return new ApiTokenListQuery({}); + } + + public async delete() { + await config.behaviors.apiToken.delete(this.id); + } + + public async findCommon(): Promise { + return this instanceof ApiTokenCommon ? this : this.findDetailed(); + } + + public async findDetailed(): Promise { + return ApiToken.find(this.id); + } + + public async getCommon(): Promise { + return this instanceof ApiTokenCommon ? this : this.getDetailed(); + } + + public async getDetailed(): Promise { + return ApiToken.get(this.id); + } + + public async update(data: ApiTokenUpdateRequestData) { + await config.behaviors.apiToken.update(this.id, data); + } +} + +export class ApiTokenCommon extends WithData< + ApiTokenListItemData | ApiTokenData +>()(ApiToken) { + public override readonly data: ApiTokenListItemData | ApiTokenData; + public readonly description: string; + public readonly expired: boolean; + public readonly expiresAt?: DateTime; + + public constructor(data: ApiTokenListItemData | ApiTokenData) { + super(data.apiTokenId); + this.data = data; + this.description = data.description; + this.expiresAt = data.expiresAt + ? DateTime.fromISO(data.expiresAt) + : undefined; + this.expired = !!this.expiresAt && this.expiresAt < DateTime.now(); + } +} + +export class ApiTokenDetailed extends ApiTokenCommon { + public override readonly data: ApiTokenData; + public constructor(data: ApiTokenData) { + super(data); + this.data = data; + } +} + +export class ApiTokenListItem extends ApiTokenCommon { + public override readonly data: ApiTokenListItemData; + public constructor(data: ApiTokenListItemData) { + super(data); + this.data = data; + } +} + +export class ApiTokenListQuery extends ListQueryModel> { + public async execute() { + const { totalCount, items } = await config.behaviors.apiToken.list(); + + return new ApiTokenList( + items.map((d) => new ApiTokenListItem(d)), + totalCount, + ); + } +} + +export class ApiTokenList extends ListDataModel { + public constructor(apiTokens: ApiTokenListItem[], totalCount: number) { + super(apiTokens, totalCount); + } +} diff --git a/packages/models/src/user/ApiToken/behaviors/api.ts b/packages/models/src/user/ApiToken/behaviors/api.ts new file mode 100644 index 00000000..ed2cbfbf --- /dev/null +++ b/packages/models/src/user/ApiToken/behaviors/api.ts @@ -0,0 +1,43 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { ApiTokenBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount } from "../../../base/index.js"; + +export const apiApiTokenBehaviors = ( + client: MittwaldAPIV2Client, +): ApiTokenBehaviors => ({ + list: async () => { + const response = await client.user.listApiTokens(); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + find: async (apiTokenId) => { + const response = await client.user.getApiToken({ apiTokenId }); + if (response.status === 200) { + return response.data; + } + validateResponse(response, 404); + }, + + create: async (data) => { + const response = await client.user.createApiToken({ data }); + validateResponse(response, 201); + return response.data.token; + }, + + update: async (apiTokenId, data) => { + const response = await client.user.editApiToken({ apiTokenId, data }); + validateResponse(response, 204); + }, + + delete: async (apiTokenId) => { + const response = await client.user.deleteApiToken({ apiTokenId }); + validateResponse(response, 204); + }, +}); diff --git a/packages/models/src/user/ApiToken/behaviors/index.ts b/packages/models/src/user/ApiToken/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/user/ApiToken/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/user/ApiToken/behaviors/types.ts b/packages/models/src/user/ApiToken/behaviors/types.ts new file mode 100644 index 00000000..358eecd7 --- /dev/null +++ b/packages/models/src/user/ApiToken/behaviors/types.ts @@ -0,0 +1,22 @@ +import type { QueryResponseData } from "../../../base/index.js"; +import type { + ApiTokenCreateRequestData, + ApiTokenUpdateRequestData, + ApiTokenListItemData, + ApiTokenData, +} from "../types.js"; + +export interface ApiTokenBehaviors { + update: ( + apiTokenId: string, + data: ApiTokenUpdateRequestData, + ) => Promise; + + find: (apiTokenId: string) => Promise; + + list: () => Promise>; + + create: (data: ApiTokenCreateRequestData) => Promise; + + delete: (apiTokenId: string) => Promise; +} diff --git a/packages/models/src/user/ApiToken/index.ts b/packages/models/src/user/ApiToken/index.ts new file mode 100644 index 00000000..154ec582 --- /dev/null +++ b/packages/models/src/user/ApiToken/index.ts @@ -0,0 +1,2 @@ +export * from "./ApiToken.js"; +export * from "./types.js"; diff --git a/packages/models/src/user/ApiToken/types.ts b/packages/models/src/user/ApiToken/types.ts new file mode 100644 index 00000000..21796511 --- /dev/null +++ b/packages/models/src/user/ApiToken/types.ts @@ -0,0 +1,13 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type ApiTokenData = + MittwaldAPIV2.Operations.UserGetApiToken.ResponseData; + +export type ApiTokenListItemData = + MittwaldAPIV2.Operations.UserListApiTokens.ResponseData[number]; + +export type ApiTokenCreateRequestData = + MittwaldAPIV2.Paths.V2UsersSelfApiTokens.Post.Parameters.RequestBody; + +export type ApiTokenUpdateRequestData = + MittwaldAPIV2.Paths.V2UsersSelfApiTokensApiTokenId.Put.Parameters.RequestBody; diff --git a/packages/models/src/user/Feedback/Feedback.test.ts b/packages/models/src/user/Feedback/Feedback.test.ts new file mode 100644 index 00000000..b98d9eb7 --- /dev/null +++ b/packages/models/src/user/Feedback/Feedback.test.ts @@ -0,0 +1,53 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { buildFeedbackListItemData } from "../../testing/builders/buildFeedbackListItemData.js"; +import { FeedbackListItem, FeedbackCommon, Feedback } from "./Feedback.js"; +import { ReferenceModel } from "../../base/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; + +afterEach(resetBehaviors); + +describe("Feedback", () => { + test("list delegates and freezes materialized items", async () => { + const list = vi.fn().mockResolvedValue([buildFeedbackListItemData()]); + installBehaviors({ feedback: { list } }); + const result = await Feedback.list("u-1", { subject: "nps" }); + expect(list).toHaveBeenCalledWith("u-1", { subject: "nps" }); + expect(Object.isFrozen(result)).toBe(true); + expect(result[0]).toBeInstanceOf(FeedbackListItem); + }); + + test("isSubmitted reflects whether matching feedback exists", async () => { + const list = vi + .fn() + .mockResolvedValueOnce([buildFeedbackListItemData()]) + .mockResolvedValueOnce([]); + installBehaviors({ feedback: { list } }); + expect(await Feedback.isSubmitted("u-1", "nps")).toBe(true); + expect(await Feedback.isSubmitted("u-1", "other")).toBe(false); + expect(list).toHaveBeenNthCalledWith(1, "u-1", { subject: "nps" }); + expect(list).toHaveBeenNthCalledWith(2, "u-1", { subject: "other" }); + }); + + test("create delegates its data", async () => { + const create = vi.fn().mockResolvedValue(undefined); + installBehaviors({ feedback: { create } }); + const data = { message: "great", subject: "nps", origin: "web", vote: 10 }; + await Feedback.create(data); + expect(create).toHaveBeenCalledWith(data); + }); + + test("reference and data instances preserve composition", () => { + const ref = Feedback.ofId("f-1"); + const item = new FeedbackListItem(buildFeedbackListItemData()); + expect(ref.id).toBe("f-1"); + expect(ref).toBeInstanceOf(ReferenceModel); + expect(item).toBeInstanceOf(FeedbackCommon); + expect(item).toBeInstanceOf(Feedback); + expect(item).toBeInstanceOf(ReferenceModel); + expect(item.data).toBeDefined(); + }); +}); diff --git a/packages/models/src/user/Feedback/Feedback.ts b/packages/models/src/user/Feedback/Feedback.ts new file mode 100644 index 00000000..9bcd78ee --- /dev/null +++ b/packages/models/src/user/Feedback/Feedback.ts @@ -0,0 +1,49 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; + +import type { + FeedbackListItemData, + FeedbackCreateData, + FeedbackListQuery, +} from "./types.js"; + +import { ReferenceModel, WithData } from "../../base/index.js"; +import { config } from "../../config/index.js"; + +@GhostMakerModel({ + name: "Feedback", +}) +export class Feedback extends ReferenceModel { + public static async create(data: FeedbackCreateData) { + await config.behaviors.feedback.create(data); + } + + public static async isSubmitted(userId: string, subject: string) { + const feedbackList = await this.list(userId, { subject }); + + return feedbackList.length > 0; + } + + public static async list(userId: string, query: FeedbackListQuery) { + const data = await config.behaviors.feedback.list(userId, query); + + return Object.freeze(data.map((d) => new FeedbackListItem(d))); + } + + public static ofId(id: string) { + return new Feedback(id); + } +} + +export class FeedbackCommon extends WithData()(Feedback) { + public override readonly data: FeedbackListItemData; + public constructor(data: FeedbackListItemData) { + super(data.id); + this.data = data; + } +} + +export class FeedbackListItem extends FeedbackCommon { + public constructor(data: FeedbackListItemData) { + super(data); + } +} diff --git a/packages/models/src/user/Feedback/behaviors/api.ts b/packages/models/src/user/Feedback/behaviors/api.ts new file mode 100644 index 00000000..bf06e981 --- /dev/null +++ b/packages/models/src/user/Feedback/behaviors/api.ts @@ -0,0 +1,26 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { FeedbackBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; + +export const apiFeedbackBehaviors = ( + client: MittwaldAPIV2Client, +): FeedbackBehaviors => ({ + list: async (userId, query) => { + const response = await client.user.listFeedback({ + queryParameters: query, + userId, + }); + + validateResponse(response, 200); + + return response.data; + }, + + create: async (data) => { + const response = await client.user.createFeedback({ data }); + + validateResponse(response, 201); + }, +}); diff --git a/packages/models/src/user/Feedback/behaviors/index.ts b/packages/models/src/user/Feedback/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/user/Feedback/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/user/Feedback/behaviors/types.ts b/packages/models/src/user/Feedback/behaviors/types.ts new file mode 100644 index 00000000..e3b2a42b --- /dev/null +++ b/packages/models/src/user/Feedback/behaviors/types.ts @@ -0,0 +1,14 @@ +import type { + FeedbackListItemData, + FeedbackCreateData, + FeedbackListQuery, +} from "../types.js"; + +export interface FeedbackBehaviors { + list: ( + userId: string, + query?: FeedbackListQuery, + ) => Promise; + + create: (data: FeedbackCreateData) => Promise; +} diff --git a/packages/models/src/user/Feedback/index.ts b/packages/models/src/user/Feedback/index.ts new file mode 100644 index 00000000..e72d3fed --- /dev/null +++ b/packages/models/src/user/Feedback/index.ts @@ -0,0 +1,2 @@ +export * from "./Feedback.js"; +export * from "./types.js"; diff --git a/packages/models/src/user/Feedback/types.ts b/packages/models/src/user/Feedback/types.ts new file mode 100644 index 00000000..0672d7eb --- /dev/null +++ b/packages/models/src/user/Feedback/types.ts @@ -0,0 +1,10 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type FeedbackListItemData = + MittwaldAPIV2.Operations.UserListFeedback.ResponseData[number]; + +export type FeedbackListQuery = + MittwaldAPIV2.Paths.V2UsersUserIdFeedback.Get.Parameters.Query; + +export type FeedbackCreateData = + MittwaldAPIV2.Paths.V2UsersSelfFeedback.Post.Parameters.RequestBody; diff --git a/packages/models/src/user/Session/Session.test.ts b/packages/models/src/user/Session/Session.test.ts new file mode 100644 index 00000000..ea069e80 --- /dev/null +++ b/packages/models/src/user/Session/Session.test.ts @@ -0,0 +1,146 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { DateTime } from "luxon"; + +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { + buildSessionListItemData, + buildSessionData, +} from "../../testing/builders/buildSessionData.js"; +import { ReferenceModel } from "../../base/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { + SessionDetailed, + SessionListItem, + SessionList, + Session, +} from "./Session.js"; + +afterEach(resetBehaviors); + +test("find and get map found and missing sessions", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildSessionData({ tokenId: "t-1" })) + .mockResolvedValueOnce(buildSessionData({ tokenId: "t-2" })) + .mockResolvedValueOnce(undefined) + .mockResolvedValueOnce(undefined); + installBehaviors({ session: { find } }); + const found = await Session.find("t-1"); + expect(find).toHaveBeenCalledWith("t-1"); + expect(found).toBeInstanceOf(SessionDetailed); + expect(found?.id).toBe("t-1"); + expect(await Session.get("t-2")).toBeInstanceOf(SessionDetailed); + expect(await Session.find("missing")).toBeUndefined(); + await expect(Session.get("missing")).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); +}); + +test("findDetailed delegates with the reference id", async () => { + const find = vi.fn().mockResolvedValue(buildSessionData({ tokenId: "t-3" })); + installBehaviors({ session: { find } }); + await Session.ofId("t-3").findDetailed(); + expect(find).toHaveBeenCalledWith("t-3"); +}); + +describe("derived session data", () => { + test("maps device and date fields", () => { + const session = new SessionDetailed( + buildSessionData({ + device: { + browser: "Firefox", + model: "Phone", + type: "mobile", + os: "Linux", + }, + }), + ); + expect(session.isMobile).toBe(true); + expect(session.browser).toBe("Firefox"); + expect(session.os).toBe("Linux"); + expect(session.model).toBe("Phone"); + expect(session.createdAt).toBeInstanceOf(DateTime); + expect(session.lastAccess).toBe(session.createdAt); + expect(new SessionDetailed(buildSessionData()).isMobile).toBe(false); + }); + + test.each([ + [{ country: "Germany", city: "Espelkamp" }, "Germany, Espelkamp"], + [{ country: "Germany" }, "Germany"], + [{ city: "Espelkamp" }, "Espelkamp"], + [undefined, undefined], + ])("formats location", (location, expected) => { + expect(new SessionDetailed(buildSessionData({ location })).location).toBe( + expected, + ); + }); +}); + +test("findCommon/getCommon resolve references and stay idempotent once materialized", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildSessionData({ tokenId: "s-c" })) + .mockResolvedValueOnce(buildSessionData({ tokenId: "s-g" })); + installBehaviors({ session: { find } }); + const common = await Session.ofId("s-c").findCommon(); + expect(common).toBeInstanceOf(SessionDetailed); + expect(common?.id).toBe("s-c"); + expect(await Session.ofId("s-g").getCommon()).toBeInstanceOf(SessionDetailed); + + const materialized = new SessionDetailed( + buildSessionData({ tokenId: "s-1" }), + ); + find.mockClear(); + expect(await materialized.findCommon()).toBe(materialized); + expect(await materialized.getCommon()).toBe(materialized); + expect(find).not.toHaveBeenCalled(); +}); + +test("findCommon yields undefined and getCommon throws for missing sessions", async () => { + installBehaviors({ session: { find: vi.fn().mockResolvedValue(undefined) } }); + expect(await Session.ofId("missing").findCommon()).toBeUndefined(); + await expect(Session.ofId("missing").getCommon()).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); +}); + +test("leaves the optional device model undefined when absent", () => { + const session = new SessionDetailed(buildSessionData()); + expect(session.model).toBeUndefined(); +}); + +test("token helpers delegate and identify the current session", async () => { + const getToken = vi.fn().mockResolvedValue({ id: "current" }); + installBehaviors({ session: { getToken } }); + expect(await Session.getToken()).toEqual({ id: "current" }); + expect(await Session.ofId("current").isCurrentSession()).toBe(true); + expect(await Session.ofId("other").isCurrentSession()).toBe(false); + expect(getToken).toHaveBeenCalledTimes(3); +}); + +test("materializes a paginated list and preserves item composition", async () => { + const list = vi + .fn() + .mockResolvedValue({ items: [buildSessionListItemData()], totalCount: 4 }); + installBehaviors({ session: { list } }); + const result = await Session.query().execute(); + const item = result.items[0]; + expect(result).toBeInstanceOf(SessionList); + expect(item).toBeInstanceOf(SessionListItem); + expect(item).toBeInstanceOf(Session); + expect(item).toBeInstanceOf(ReferenceModel); + expect(item.data).toBeDefined(); + expect(result.totalCount).toBe(4); +}); diff --git a/packages/models/src/user/Session/Session.ts b/packages/models/src/user/Session/Session.ts new file mode 100644 index 00000000..497e21b4 --- /dev/null +++ b/packages/models/src/user/Session/Session.ts @@ -0,0 +1,144 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; + +import type { SessionListItemData, SessionData } from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + ListDataModel, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "Session", +}) +export class Session extends ReferenceModel { + public static async closeAll() { + await config.behaviors.session.closeAll(); + } + + public static async find(id: string) { + const data = await config.behaviors.session.find(id); + if (data) { + return new SessionDetailed(data); + } + } + + public static async get(id: string) { + const session = await this.find(id); + assertObjectFound(session, Session, id); + return session; + } + + public static async getToken() { + return await config.behaviors.session.getToken(); + } + + public static ofId(id: string) { + return new Session(id); + } + + public static query() { + return new SessionListQuery({}); + } + + public async close() { + await config.behaviors.session.close(this.id); + } + + public async findCommon(): Promise { + return this instanceof SessionCommon ? this : this.findDetailed(); + } + + public findDetailed(): Promise { + return Session.find(this.id); + } + + public async getCommon(): Promise { + return this instanceof SessionCommon ? this : this.getDetailed(); + } + + public getDetailed(): Promise { + return Session.get(this.id); + } + + public async isCurrentSession() { + const currentToken = await config.behaviors.session.getToken(); + return currentToken.id === this.id; + } +} + +export class SessionCommon extends WithData< + SessionListItemData | SessionData +>()(Session) { + public readonly browser?: string; + public readonly createdAt: DateTime; + public override readonly data: SessionListItemData | SessionData; + public readonly isMobile: boolean; + public readonly lastAccess: DateTime; + public readonly lastAccessSeconds: number; + public readonly location?: string; + public readonly model?: string; + public readonly os?: string; + + public constructor(data: SessionListItemData | SessionData) { + super(data.tokenId); + this.data = data; + this.isMobile = data.device.type === "mobile"; + this.browser = data.device.browser; + this.os = data.device.os; + this.model = data.device.model; + if (data.location) { + this.location = + data.location.country && data.location.city + ? `${data.location.country}, ${data.location.city}` + : (data.location.country ?? data.location.city); + } + this.createdAt = DateTime.fromISO(data.created); + this.lastAccess = data.lastAccess + ? DateTime.fromISO(data.lastAccess) + : this.createdAt; + this.lastAccessSeconds = this.lastAccess.toMillis(); + } + + public async isActive() { + const currentToken = await Session.getToken(); + return this.data.tokenId === currentToken.id; + } +} + +export class SessionDetailed extends SessionCommon { + public override readonly data: SessionData; + public constructor(data: SessionData) { + super(data); + this.data = data; + } +} + +export class SessionListItem extends SessionCommon { + public override readonly data: SessionListItemData; + public constructor(data: SessionListItemData) { + super(data); + this.data = data; + } +} + +export class SessionListQuery extends ListQueryModel> { + public async execute() { + const { totalCount, items } = await config.behaviors.session.list(); + + return new SessionList( + items.map((d) => new SessionListItem(d)), + totalCount, + ); + } +} + +export class SessionList extends ListDataModel { + public constructor(sessions: SessionListItem[], totalCount: number) { + super(sessions, totalCount); + } +} diff --git a/packages/models/src/user/Session/behaviors/api.ts b/packages/models/src/user/Session/behaviors/api.ts new file mode 100644 index 00000000..1e1ddd93 --- /dev/null +++ b/packages/models/src/user/Session/behaviors/api.ts @@ -0,0 +1,54 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import { ApiClientError } from "@mittwald/api-client-commons"; + +import type { SessionBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount } from "../../../base/index.js"; + +export const apiSessionBehaviors = ( + client: MittwaldAPIV2Client, +): SessionBehaviors => ({ + getToken: async () => { + const response = await client.axios.post( + "/v2/users/self/credentials/token", + { + validateResponse: () => true, + }, + ); + if (response.status !== 200) { + throw new ApiClientError( + `Unexpected response status (expected 200, got: ${response.status})`, + ); + } + return response.data; + }, + + list: async () => { + const response = await client.user.listSessions(); + validateResponse(response, 200); + return { + totalCount: resolveTotalCount(response), + items: response.data, + }; + }, + + find: async (tokenId) => { + const response = await client.user.getSession({ tokenId }); + if (response.status === 200) { + return response.data; + } + validateResponse(response, 404); + }, + + close: async (tokenId) => { + const response = await client.user.terminateSession({ tokenId }); + validateResponse(response, 204); + }, + + closeAll: async () => { + const response = await client.user.terminateAllSessions(); + validateResponse(response, 204); + }, +}); diff --git a/packages/models/src/user/Session/behaviors/index.ts b/packages/models/src/user/Session/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/user/Session/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/user/Session/behaviors/types.ts b/packages/models/src/user/Session/behaviors/types.ts new file mode 100644 index 00000000..2ee432b0 --- /dev/null +++ b/packages/models/src/user/Session/behaviors/types.ts @@ -0,0 +1,18 @@ +import type { QueryResponseData } from "../../../base/index.js"; +import type { + SessionListItemData, + SessionTokenData, + SessionData, +} from "../types.js"; + +export interface SessionBehaviors { + find: (tokenId: string) => Promise; + + list: () => Promise>; + + getToken: () => Promise; + + close: (tokenId: string) => Promise; + + closeAll: () => Promise; +} diff --git a/packages/models/src/user/Session/index.ts b/packages/models/src/user/Session/index.ts new file mode 100644 index 00000000..62add299 --- /dev/null +++ b/packages/models/src/user/Session/index.ts @@ -0,0 +1,2 @@ +export * from "./Session.js"; +export * from "./types.js"; diff --git a/packages/models/src/user/Session/types.ts b/packages/models/src/user/Session/types.ts new file mode 100644 index 00000000..4a70777a --- /dev/null +++ b/packages/models/src/user/Session/types.ts @@ -0,0 +1,10 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type SessionData = MittwaldAPIV2.Operations.UserGetSession.ResponseData; + +export type SessionListItemData = + MittwaldAPIV2.Operations.UserListSessions.ResponseData[number]; + +export interface SessionTokenData { + id: string; +} diff --git a/packages/models/src/user/Spotlight/Spotlight.test.ts b/packages/models/src/user/Spotlight/Spotlight.test.ts new file mode 100644 index 00000000..eb3760dc --- /dev/null +++ b/packages/models/src/user/Spotlight/Spotlight.test.ts @@ -0,0 +1,79 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; + +import { buildSpotlightStateData } from "../../testing/builders/buildSpotlightStateData.js"; +import { SpotlightState, Spotlight } from "./Spotlight.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; + +afterEach(resetBehaviors); + +const state = (overrides: Parameters[0] = {}) => + new SpotlightState(buildSpotlightStateData(overrides)); + +describe("Spotlight", () => { + test("getSelfState delegates and materializes the state", async () => { + const getSelfState = vi.fn().mockResolvedValue(buildSpotlightStateData()); + installBehaviors({ spotlight: { getSelfState } }); + + const result = await Spotlight.ofId( + "ai-agent-verknuepfen-btn", + ).getSelfState(); + + expect(getSelfState).toHaveBeenCalledWith( + "ai-agent-verknuepfen-btn", + undefined, + ); + expect(result).toBeInstanceOf(SpotlightState); + expect(result.id).toBe("ai-agent-verknuepfen-btn"); + }); + + test("reportInteraction and submitFeedback delegate their data", async () => { + const reportInteraction = vi.fn().mockResolvedValue(undefined); + const submitFeedback = vi.fn().mockResolvedValue(undefined); + installBehaviors({ spotlight: { reportInteraction, submitFeedback } }); + + await Spotlight.ofId("s-1").reportInteraction({ + acknowledged: true, + }); + await Spotlight.ofId("s-1").submitFeedback({ + decision: "keep", + }); + + expect(reportInteraction).toHaveBeenCalledWith("s-1", { + acknowledged: true, + }); + expect(submitFeedback).toHaveBeenCalledWith("s-1", { + decision: "keep", + }); + }); +}); + +describe("SpotlightState", () => { + test("the promo stays due until it is acknowledged", () => { + expect(state().isPromoDue()).toBe(true); + expect(state({ acknowledged: true }).isPromoDue()).toBe(false); + }); + + test("without use tracking, acknowledging makes feedback due", () => { + expect(state().isFeedbackDue(false)).toBe(false); + expect(state({ acknowledged: true }).isFeedbackDue(false)).toBe(true); + }); + + test("with use tracking, acknowledging alone does not make feedback due", () => { + expect(state({ acknowledged: true }).isFeedbackDue(true)).toBe(false); + expect(state({ acknowledged: true, used: true }).isFeedbackDue(true)).toBe( + true, + ); + }); + + test("a recorded decision closes feedback for good in both modes", () => { + for (const decision of ["keep", "kill", "ignore"] as const) { + const decided = state({ acknowledged: true, used: true, decision }); + + expect(decided.isFeedbackDue(false)).toBe(false); + expect(decided.isFeedbackDue(true)).toBe(false); + } + }); +}); diff --git a/packages/models/src/user/Spotlight/Spotlight.ts b/packages/models/src/user/Spotlight/Spotlight.ts new file mode 100644 index 00000000..12df5747 --- /dev/null +++ b/packages/models/src/user/Spotlight/Spotlight.ts @@ -0,0 +1,59 @@ +import type { AxiosRequestConfig } from "axios"; + +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; + +import type { + SpotlightInteractionData, + SpotlightFeedbackData, + SpotlightStateData, +} from "./types.js"; + +import { ReferenceModel, WithData } from "../../base/index.js"; +import { config } from "../../config/index.js"; + +@GhostMakerModel({ + name: "Spotlight", +}) +export class Spotlight extends ReferenceModel { + public static ofId(id: string) { + return new Spotlight(id); + } + + public async getSelfState(requestConfig?: AxiosRequestConfig) { + const data = await config.behaviors.spotlight.getSelfState( + this.id, + requestConfig, + ); + + return new SpotlightState(data); + } + + public async reportInteraction(data: SpotlightInteractionData) { + await config.behaviors.spotlight.reportInteraction(this.id, data); + } + + public async submitFeedback(data: SpotlightFeedbackData) { + await config.behaviors.spotlight.submitFeedback(this.id, data); + } +} + +export class SpotlightState extends WithData()(Spotlight) { + public override readonly data: SpotlightStateData; + + public constructor(data: SpotlightStateData) { + super(data.spotlightId); + this.data = data; + } + + public isFeedbackDue(tracksUse: boolean) { + if (this.data.decision !== undefined) { + return false; + } + + return tracksUse ? this.data.used : this.data.acknowledged; + } + + public isPromoDue() { + return !this.data.acknowledged; + } +} diff --git a/packages/models/src/user/Spotlight/behaviors/api.ts b/packages/models/src/user/Spotlight/behaviors/api.ts new file mode 100644 index 00000000..d31c6a24 --- /dev/null +++ b/packages/models/src/user/Spotlight/behaviors/api.ts @@ -0,0 +1,40 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { SpotlightFeedbackData } from "../types.js"; +import type { SpotlightBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { withAxiosRequestConfig } from "../../../base/index.js"; + +export const apiSpotlightBehaviors = ( + client: MittwaldAPIV2Client, +): SpotlightBehaviors => ({ + submitFeedback: async (spotlightId, data) => { + // API-DRIFT: the feedback body declares `owner` as required and the client + // does not send it, so the omission has to be cast away here (resolve: drop + // `owner` from the request schema) + const response = await client.user.spotlightFeedback({ + data: data as SpotlightFeedbackData & { owner: string }, + spotlightId, + }); + + validateResponse(response, 204); + }, + + getSelfState: async (spotlightId, requestConfig) => { + const response = await client.user.getSpotlightInfo( + { spotlightId }, + withAxiosRequestConfig(requestConfig), + ); + + validateResponse(response, 200); + + return response.data; + }, + + reportInteraction: async (spotlightId, data) => { + const response = await client.user.spotlightUsage({ spotlightId, data }); + + validateResponse(response, 204); + }, +}); diff --git a/packages/models/src/user/Spotlight/behaviors/index.ts b/packages/models/src/user/Spotlight/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/user/Spotlight/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/user/Spotlight/behaviors/types.ts b/packages/models/src/user/Spotlight/behaviors/types.ts new file mode 100644 index 00000000..a0212841 --- /dev/null +++ b/packages/models/src/user/Spotlight/behaviors/types.ts @@ -0,0 +1,24 @@ +import type { AxiosRequestConfig } from "axios"; + +import type { + SpotlightInteractionData, + SpotlightFeedbackData, + SpotlightStateData, +} from "../types.js"; + +export interface SpotlightBehaviors { + getSelfState: ( + spotlightId: string, + requestConfig?: AxiosRequestConfig, + ) => Promise; + + reportInteraction: ( + spotlightId: string, + data: SpotlightInteractionData, + ) => Promise; + + submitFeedback: ( + spotlightId: string, + data: SpotlightFeedbackData, + ) => Promise; +} diff --git a/packages/models/src/user/Spotlight/index.ts b/packages/models/src/user/Spotlight/index.ts new file mode 100644 index 00000000..9e664554 --- /dev/null +++ b/packages/models/src/user/Spotlight/index.ts @@ -0,0 +1,2 @@ +export * from "./Spotlight.js"; +export * from "./types.js"; diff --git a/packages/models/src/user/Spotlight/types.ts b/packages/models/src/user/Spotlight/types.ts new file mode 100644 index 00000000..ddf28dce --- /dev/null +++ b/packages/models/src/user/Spotlight/types.ts @@ -0,0 +1,21 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type SpotlightDecision = + MittwaldAPIV2.Components.Schemas.UserUserFeedbackSpotlightDecision; + +export type SpotlightStateData = + MittwaldAPIV2.Operations.UserGetSpotlightInfo.ResponseData; + +// API-DRIFT: both request bodies declare an `owner` and the feedback body marks +// it required; the client sends neither, so it is omitted here and cast away +// where the feedback is submitted (resolve: drop `owner` from the request +// schemas) +export type SpotlightInteractionData = Omit< + MittwaldAPIV2.Paths.V2UsersSelfSpotlightsSpotlightId.Post.Parameters.RequestBody, + "owner" +>; + +export type SpotlightFeedbackData = Omit< + MittwaldAPIV2.Paths.V2UsersSelfSpotlightsSpotlightIdFeedback.Post.Parameters.RequestBody, + "owner" +>; diff --git a/packages/models/src/user/SshKey/SshKey.test.ts b/packages/models/src/user/SshKey/SshKey.test.ts new file mode 100644 index 00000000..9289783e --- /dev/null +++ b/packages/models/src/user/SshKey/SshKey.test.ts @@ -0,0 +1,105 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, expect, test, vi } from "vitest"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { DateTime } from "luxon"; + +import { + SshKeyDetailed, + SshKeyListItem, + SshKeyList, + SshKey, +} from "./SshKey.js"; +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { + buildSshKeyListItemData, + buildSshKeyData, +} from "../../testing/builders/buildSshKeyData.js"; +import { ReferenceModel } from "../../base/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; + +afterEach(resetBehaviors); + +test("find/get map found and missing keys", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildSshKeyData({ sshKeyId: "k-1" })) + .mockResolvedValueOnce(buildSshKeyData({ sshKeyId: "k-2" })) + .mockResolvedValueOnce(undefined) + .mockResolvedValueOnce(undefined); + installBehaviors({ sshKey: { find } }); + const found = await SshKey.find("k-1"); + expect(find).toHaveBeenCalledWith("k-1"); + expect(found).toBeInstanceOf(SshKeyDetailed); + expect(found?.id).toBe("k-1"); + expect(await SshKey.get("k-2")).toBeInstanceOf(SshKeyDetailed); + expect(await SshKey.find("missing")).toBeUndefined(); + await expect(SshKey.get("missing")).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); +}); + +test("findDetailed delegates with the reference id", async () => { + const find = vi.fn().mockResolvedValue(buildSshKeyData({ sshKeyId: "k-3" })); + installBehaviors({ sshKey: { find } }); + await SshKey.ofId("k-3").findDetailed(); + expect(find).toHaveBeenCalledWith("k-3"); +}); + +test("maps comment and optional expiration", () => { + const expiring = new SshKeyDetailed( + buildSshKeyData({ expiresAt: "2025-01-01T00:00:00.000Z" }), + ); + expect(expiring.comment).toBe("laptop"); + expect(expiring.expiresAt).toBeInstanceOf(DateTime); + expect(new SshKeyDetailed(buildSshKeyData()).expiresAt).toBeUndefined(); +}); + +test("findCommon/getCommon resolve a reference and stay idempotent once materialized", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildSshKeyData({ sshKeyId: "k-c" })) + .mockResolvedValueOnce(buildSshKeyData({ sshKeyId: "k-g" })); + installBehaviors({ sshKey: { find } }); + const common = await SshKey.ofId("k-c").findCommon(); + expect(common).toBeInstanceOf(SshKeyDetailed); + expect(common?.id).toBe("k-c"); + expect(await SshKey.ofId("k-g").getCommon()).toBeInstanceOf(SshKeyDetailed); + + const materialized = new SshKeyDetailed(buildSshKeyData({ sshKeyId: "k-1" })); + find.mockClear(); + expect(await materialized.findCommon()).toBe(materialized); + expect(await materialized.getCommon()).toBe(materialized); + expect(find).not.toHaveBeenCalled(); +}); + +test("findCommon yields undefined and getCommon throws for missing keys", async () => { + installBehaviors({ sshKey: { find: vi.fn().mockResolvedValue(undefined) } }); + expect(await SshKey.ofId("missing").findCommon()).toBeUndefined(); + await expect(SshKey.ofId("missing").getCommon()).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); +}); + +test("materializes list data and item composition", async () => { + const list = vi + .fn() + .mockResolvedValue({ items: [buildSshKeyListItemData()], totalCount: 2 }); + installBehaviors({ sshKey: { list } }); + const result = await SshKey.query().execute(); + const item = result.items[0]; + expect(result).toBeInstanceOf(SshKeyList); + expect(item).toBeInstanceOf(SshKeyListItem); + expect(item).toBeInstanceOf(ReferenceModel); + expect(item.data).toBeDefined(); + expect(result.totalCount).toBe(2); +}); diff --git a/packages/models/src/user/SshKey/SshKey.ts b/packages/models/src/user/SshKey/SshKey.ts new file mode 100644 index 00000000..0328cf20 --- /dev/null +++ b/packages/models/src/user/SshKey/SshKey.ts @@ -0,0 +1,118 @@ +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; + +import type { + SshKeyListItemData, + SshKeyCreateData, + SshKeyUpdateData, + SshKeyData, +} from "./types.js"; + +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { config } from "../../config/index.js"; +import { + ListQueryModel, + ReferenceModel, + ListDataModel, + WithData, +} from "../../base/index.js"; + +@GhostMakerModel({ + name: "SshKey", +}) +export class SshKey extends ReferenceModel { + public static async create(data: SshKeyCreateData) { + await config.behaviors.sshKey.create(data); + } + + public static async find(id: string) { + const data = await config.behaviors.sshKey.find(id); + if (data) { + return new SshKeyDetailed(data); + } + } + + public static async get(id: string) { + const sshKey = await this.find(id); + assertObjectFound(sshKey, SshKey, id); + return sshKey; + } + + public static ofId(id: string) { + return new SshKey(id); + } + + public static query() { + return new SshKeyListQuery({}); + } + + public async delete() { + await config.behaviors.sshKey.delete(this.id); + } + + public async findCommon(): Promise { + return this instanceof SshKeyCommon ? this : this.findDetailed(); + } + + public async findDetailed(): Promise { + return SshKey.find(this.id); + } + + public async getCommon(): Promise { + return this instanceof SshKeyCommon ? this : this.getDetailed(); + } + + public async getDetailed(): Promise { + return SshKey.get(this.id); + } + + public async update(data: SshKeyUpdateData) { + await config.behaviors.sshKey.update(this.id, data); + } +} + +export class SshKeyCommon extends WithData()(SshKey) { + public readonly comment: string; + public override readonly data: SshKeyData; + public readonly expiresAt?: DateTime; + + public constructor(data: SshKeyData) { + super(data.sshKeyId); + this.data = data; + this.comment = data.comment; + this.expiresAt = data.expiresAt + ? DateTime.fromISO(data.expiresAt) + : undefined; + } +} + +export class SshKeyDetailed extends SshKeyCommon { + public constructor(data: SshKeyData) { + super(data); + } +} + +export class SshKeyListItem extends SshKeyCommon { + public override readonly data: SshKeyListItemData; + public constructor(data: SshKeyListItemData) { + super(data); + this.data = data; + } +} + +export class SshKeyListQuery extends ListQueryModel> { + public async execute() { + const { totalCount, items } = await config.behaviors.sshKey.list(); + + return new SshKeyList( + items.map((d) => new SshKeyListItem(d)), + totalCount, + ); + } +} + +export class SshKeyList extends ListDataModel { + public constructor(sshKeys: SshKeyListItem[], totalCount: number) { + super(sshKeys, totalCount); + } +} diff --git a/packages/models/src/user/SshKey/behaviors/api.ts b/packages/models/src/user/SshKey/behaviors/api.ts new file mode 100644 index 00000000..502b43b0 --- /dev/null +++ b/packages/models/src/user/SshKey/behaviors/api.ts @@ -0,0 +1,45 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { SshKeyBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { resolveTotalCount } from "../../../base/index.js"; + +export const apiSshKeyBehaviors = ( + client: MittwaldAPIV2Client, +): SshKeyBehaviors => ({ + list: async () => { + const response = await client.user.listSshKeys(); + validateResponse(response, 200); + const items = response.data.sshKeys ?? []; + return { + totalCount: resolveTotalCount({ ...response, data: items }), + items, + }; + }, + + find: async (sshKeyId) => { + const response = await client.user.getSshKey({ sshKeyId }); + + if (response.status === 200) { + return response.data.sshKey; + } + validateResponse(response, 404); + }, + + update: async (sshKeyId, data) => { + const response = await client.user.editSshKey({ sshKeyId, data }); + validateResponse(response, 204); + }, + + delete: async (sshKeyId) => { + const response = await client.user.deleteSshKey({ sshKeyId }); + validateResponse(response, 204); + }, + + create: async (data) => { + const response = await client.user.createSshKey({ data }); + + validateResponse(response, 201); + }, +}); diff --git a/packages/models/src/user/SshKey/behaviors/index.ts b/packages/models/src/user/SshKey/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/user/SshKey/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/user/SshKey/behaviors/types.ts b/packages/models/src/user/SshKey/behaviors/types.ts new file mode 100644 index 00000000..db0e5a70 --- /dev/null +++ b/packages/models/src/user/SshKey/behaviors/types.ts @@ -0,0 +1,19 @@ +import type { QueryResponseData } from "../../../base/index.js"; +import type { + SshKeyListItemData, + SshKeyCreateData, + SshKeyUpdateData, + SshKeyData, +} from "../types.js"; + +export interface SshKeyBehaviors { + update: (sshKeyId: string, data: SshKeyUpdateData) => Promise; + + find: (sshKeyId: string) => Promise; + + list: () => Promise>; + + create: (data: SshKeyCreateData) => Promise; + + delete: (sshKeyId: string) => Promise; +} diff --git a/packages/models/src/user/SshKey/index.ts b/packages/models/src/user/SshKey/index.ts new file mode 100644 index 00000000..17fb1e7f --- /dev/null +++ b/packages/models/src/user/SshKey/index.ts @@ -0,0 +1,2 @@ +export * from "./SshKey.js"; +export * from "./types.js"; diff --git a/packages/models/src/user/SshKey/types.ts b/packages/models/src/user/SshKey/types.ts new file mode 100644 index 00000000..50c7bf6c --- /dev/null +++ b/packages/models/src/user/SshKey/types.ts @@ -0,0 +1,14 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type SshKeyData = + MittwaldAPIV2.Operations.UserGetSshKey.ResponseData["sshKey"]; + +export type SshKeyListItemData = NonNullable< + MittwaldAPIV2.Operations.UserListSshKeys.ResponseData["sshKeys"] +>[number]; + +export type SshKeyCreateData = + MittwaldAPIV2.Paths.V2UsersSelfSshKeys.Post.Parameters.RequestBody; + +export type SshKeyUpdateData = + MittwaldAPIV2.Paths.V2UsersSelfSshKeysSshKeyId.Put.Parameters.RequestBody; diff --git a/packages/models/src/user/SupportCode/SupportCode.test.ts b/packages/models/src/user/SupportCode/SupportCode.test.ts new file mode 100644 index 00000000..b27ad8de --- /dev/null +++ b/packages/models/src/user/SupportCode/SupportCode.test.ts @@ -0,0 +1,26 @@ +import { afterEach, expect, test, vi } from "vitest"; +import { DateTime } from "luxon"; + +import { buildSupportCodeData } from "../../testing/builders/buildSupportCodeData.js"; +import { SupportCodeDetailed, SupportCode } from "./SupportCode.js"; +import { ReferenceModel } from "../../base/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; + +afterEach(resetBehaviors); + +test("get forwards request config and maps support code data", async () => { + const get = vi.fn().mockResolvedValue(buildSupportCodeData()); + installBehaviors({ supportCode: { get } }); + const requestConfig = { headers: { "x-test": "yes" } }; + const result = await SupportCode.get(requestConfig); + expect(get).toHaveBeenCalledWith(requestConfig); + expect(result).toBeInstanceOf(SupportCodeDetailed); + expect(result.supportCode).toBe("SUP-123"); + expect(result.expiresAt).toBeInstanceOf(DateTime); + expect(result).toBeInstanceOf(SupportCode); + expect(result).toBeInstanceOf(ReferenceModel); + expect(result.data).toBeDefined(); +}); diff --git a/packages/models/src/user/SupportCode/SupportCode.ts b/packages/models/src/user/SupportCode/SupportCode.ts new file mode 100644 index 00000000..de381e8f --- /dev/null +++ b/packages/models/src/user/SupportCode/SupportCode.ts @@ -0,0 +1,40 @@ +import type { AxiosRequestConfig } from "axios"; + +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; + +import type { SupportCodeData } from "./types.js"; + +import { ReferenceModel, WithData } from "../../base/index.js"; +import { config } from "../../config/index.js"; + +@GhostMakerModel({ + name: "SupportCode", +}) +export class SupportCode extends ReferenceModel { + public static async get(requestConfig?: AxiosRequestConfig) { + const data = await config.behaviors.supportCode.get(requestConfig); + return new SupportCodeDetailed(data); + } +} + +export class SupportCodeCommon extends WithData()( + SupportCode, +) { + public override readonly data: SupportCodeData; + public readonly expiresAt: DateTime; + public readonly supportCode: string; + + public constructor(data: SupportCodeData) { + super("static"); + this.data = data; + this.supportCode = data.supportCode; + this.expiresAt = DateTime.fromISO(data.expiresAt); + } +} + +export class SupportCodeDetailed extends SupportCodeCommon { + public constructor(data: SupportCodeData) { + super(data); + } +} diff --git a/packages/models/src/user/SupportCode/behaviors/api.ts b/packages/models/src/user/SupportCode/behaviors/api.ts new file mode 100644 index 00000000..6c144e65 --- /dev/null +++ b/packages/models/src/user/SupportCode/behaviors/api.ts @@ -0,0 +1,21 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { SupportCodeBehaviors } from "./types.js"; + +import { validateResponse } from "../../../base/api/validateResponse.js"; +import { withAxiosRequestConfig } from "../../../base/index.js"; + +export const apiSupportCodeBehaviors = ( + client: MittwaldAPIV2Client, +): SupportCodeBehaviors => ({ + get: async (requestConfig) => { + const response = await client.user.supportCodeRequest( + {}, + withAxiosRequestConfig(requestConfig), + ); + + validateResponse(response, 200); + + return response.data; + }, +}); diff --git a/packages/models/src/user/SupportCode/behaviors/index.ts b/packages/models/src/user/SupportCode/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/user/SupportCode/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/user/SupportCode/behaviors/types.ts b/packages/models/src/user/SupportCode/behaviors/types.ts new file mode 100644 index 00000000..50077a76 --- /dev/null +++ b/packages/models/src/user/SupportCode/behaviors/types.ts @@ -0,0 +1,7 @@ +import type { AxiosRequestConfig } from "axios"; + +import type { SupportCodeData } from "../types.js"; + +export interface SupportCodeBehaviors { + get: (requestConfig?: AxiosRequestConfig) => Promise; +} diff --git a/packages/models/src/user/SupportCode/index.ts b/packages/models/src/user/SupportCode/index.ts new file mode 100644 index 00000000..60227de9 --- /dev/null +++ b/packages/models/src/user/SupportCode/index.ts @@ -0,0 +1,2 @@ +export * from "./SupportCode.js"; +export * from "./types.js"; diff --git a/packages/models/src/user/SupportCode/types.ts b/packages/models/src/user/SupportCode/types.ts new file mode 100644 index 00000000..8ad74cf5 --- /dev/null +++ b/packages/models/src/user/SupportCode/types.ts @@ -0,0 +1,4 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type SupportCodeData = + MittwaldAPIV2.Operations.UserSupportCodeRequest.ResponseData; diff --git a/packages/models/src/user/User/User.test.ts b/packages/models/src/user/User/User.test.ts new file mode 100644 index 00000000..0055c5ad --- /dev/null +++ b/packages/models/src/user/User/User.test.ts @@ -0,0 +1,170 @@ +import type * as ReactGhostmaker from "@mittwald/react-ghostmaker/model"; + +import { afterEach, describe, expect, test, vi } from "vitest"; + +vi.mock("@mittwald/react-ghostmaker/model", async (importOriginal) => ({ + ...(await importOriginal()), + getModelName: (type: unknown) => + typeof type === "function" ? (type as { name?: string }).name : undefined, +})); + +import { DateTime } from "luxon"; + +import { buildUserData } from "../../testing/builders/buildUserData.js"; +import ObjectNotFoundError from "../../errors/ObjectNotFoundError.js"; +import { UserDetailed, UserCommon, User } from "./User.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { ReferenceModel } from "../../base/index.js"; +import { + installBehaviors, + resetBehaviors, +} from "../../testing/installBehaviors.js"; +import { Project } from "../../project/index.js"; +import { File } from "../../file/index.js"; + +afterEach(resetBehaviors); + +test("find/get map found and missing users", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(buildUserData({ userId: "u-1" })) + .mockResolvedValueOnce(buildUserData({ userId: "u-2" })) + .mockResolvedValueOnce(undefined) + .mockResolvedValueOnce(undefined); + installBehaviors({ user: { find } }); + const found = await User.find("u-1"); + expect(find).toHaveBeenCalledWith("u-1", undefined); + expect(found).toBeInstanceOf(UserDetailed); + expect(found?.id).toBe("u-1"); + expect(await User.get("u-2")).toBeInstanceOf(UserDetailed); + expect(await User.find("missing")).toBeUndefined(); + await expect(User.get("missing")).rejects.toBeInstanceOf(ObjectNotFoundError); +}); + +test("self and aggregate references expose their ids", () => { + expect(User.self).toBeInstanceOf(User); + expect(User.self.id).toBe("self"); + expect(User.findAggregate("u-1")).toEqual( + expect.objectContaining({ id: "u-1" }), + ); + expect(User.findAggregate()).toBeUndefined(); +}); + +describe("derived user data", () => { + test("maps personal information, avatar, and registration date", () => { + const recent = DateTime.now().minus({ days: 1 }).toISO(); + const user = new UserDetailed( + buildUserData({ + person: { firstName: "First", lastName: "Last", title: "ms" }, + email: "ada@example.test", + phoneNumber: "+49123", + registeredAt: recent, + avatarRef: "file-1", + }), + ); + expect(user.fullName).toBe("First Last"); + expect(user.firstName).toBe("First"); + expect(user.lastName).toBe("Last"); + expect(user.email).toBe("ada@example.test"); + expect(user.phoneNumber).toBe("+49123"); + expect(user.title).toBe("ms"); + expect(user.avatar).toBeInstanceOf(File); + expect(user.isNew).toBe(true); + expect(user.registeredAt).toBeInstanceOf(DateTime); + }); + + test("handles absent avatars and old registrations", () => { + const user = new UserDetailed( + buildUserData({ registeredAt: "2000-01-01T00:00:00.000Z" }), + ); + expect(user.avatar).toBeUndefined(); + expect(user.isNew).toBe(false); + }); + + test("findRole reads the matching project membership", async () => { + const user = new UserDetailed( + buildUserData({ + projectMemberships: { + "p-1": { + memberSince: "2024-01-01T00:00:00.000Z", + inherited: false, + role: "owner", + }, + }, + }), + ); + expect(await user.findRole(Project.ofId("p-1"))).toBe("owner"); + }); + + test("leaves optional contact fields undefined when absent", () => { + const user = new UserDetailed(buildUserData()); + expect(user.email).toBeUndefined(); + expect(user.phoneNumber).toBeUndefined(); + expect(user.title).toBeUndefined(); + }); + + test("findRole yields undefined when the project membership is absent", async () => { + const user = new UserDetailed(buildUserData()); + expect(await user.findRole(Project.ofId("p-1"))).toBeUndefined(); + }); +}); + +describe("common variant and idempotency", () => { + test("findCommon resolves a reference into the common variant", async () => { + const find = vi.fn().mockResolvedValue(buildUserData({ userId: "u-c" })); + installBehaviors({ user: { find } }); + const common = await User.ofId("u-c").findCommon(); + expect(find).toHaveBeenCalledWith("u-c", undefined); + expect(common).toBeInstanceOf(UserCommon); + expect(common?.id).toBe("u-c"); + }); + + test("findCommon yields undefined and getCommon throws for missing users", async () => { + const find = vi + .fn() + .mockResolvedValueOnce(undefined) + .mockResolvedValueOnce(undefined); + installBehaviors({ user: { find } }); + expect(await User.ofId("missing").findCommon()).toBeUndefined(); + await expect(User.ofId("missing").getCommon()).rejects.toBeInstanceOf( + ObjectNotFoundError, + ); + }); + + test("getCommon resolves a reference into the common variant", async () => { + const find = vi.fn().mockResolvedValue(buildUserData({ userId: "u-g" })); + installBehaviors({ user: { find } }); + const common = await User.ofId("u-g").getCommon(); + expect(common).toBeInstanceOf(UserCommon); + expect(common.id).toBe("u-g"); + }); + + test("findCommon/getCommon return a materialized model without another behavior call", async () => { + const find = vi.fn(); + installBehaviors({ user: { find } }); + const user = new UserDetailed(buildUserData({ userId: "u-1" })); + expect(await user.findCommon()).toBe(user); + expect(await user.getCommon()).toBe(user); + expect(find).not.toHaveBeenCalled(); + }); +}); + +test("aggregateMetaData nails the cache identity", () => { + expect(User.aggregateMetaData).toBeInstanceOf(AggregateMetaData); + expect(User.aggregateMetaData).toEqual( + expect.objectContaining({ aggregate: "user", domain: "user" }), + ); + expect(User.findAggregate("u-1")).toEqual({ + aggregate: "user", + domain: "user", + id: "u-1", + }); +}); + +test("preserves the detailed user composition chain", () => { + const user = new UserDetailed(buildUserData()); + expect(user).toBeInstanceOf(UserCommon); + expect(user).toBeInstanceOf(User); + expect(user).toBeInstanceOf(ReferenceModel); + expect(user.data).toBeDefined(); +}); diff --git a/packages/models/src/user/User/User.ts b/packages/models/src/user/User/User.ts new file mode 100644 index 00000000..452ca1e9 --- /dev/null +++ b/packages/models/src/user/User/User.ts @@ -0,0 +1,215 @@ +import type { AxiosRequestConfig } from "axios"; + +import { GhostMakerModel } from "@mittwald/react-ghostmaker/model"; +import { DateTime } from "luxon"; + +import type { FileAccessTokenProvider, DomFile } from "../../file/index.js"; +import type { Salutation } from "../../customer/index.js"; +import type { Project } from "../../project/index.js"; +import type { + UserUpdatePersonalInformationRequestData, + UserConfirmPasswordResetRequestData, + UserVerifyPhoneNumberRequestData, + UserUpdatePasswordRequestData, + UserVerifyEmailRequestData, + UserDeleteRequestData, + FeedbackPollStatus, + UserData, +} from "./types.js"; + +import { UserAvatarAccessTokenProvider } from "./UserAvatarAccessTokenProvider.js"; +import assertObjectFound from "../../base/lib/assertObjectFound.js"; +import { ReferenceModel, WithData } from "../../base/index.js"; +import { AggregateMetaData } from "../../common/index.js"; +import { File } from "../../file/File/internal.js"; +import { config } from "../../config/index.js"; + +@GhostMakerModel({ + name: "User", +}) +export class User extends ReferenceModel { + public static aggregateMetaData = new AggregateMetaData("user", "user"); + public static self = User.ofId("self"); + public readonly fileAccessTokenProvider: FileAccessTokenProvider; + + public constructor(id: string) { + super(id); + this.fileAccessTokenProvider = new UserAvatarAccessTokenProvider(this); + } + + public static async confirmPasswordReset( + data: UserConfirmPasswordResetRequestData, + ) { + await config.behaviors.user.confirmPasswordReset(data); + } + + public static async find(id: string, options?: AxiosRequestConfig) { + const data = await config.behaviors.user.find(id, options); + + if (data) { + return new UserDetailed(data); + } + } + + public static findAggregate(userId?: string) { + return userId ? { id: userId, ...User.aggregateMetaData } : undefined; + } + + public static async get(id: string, options?: AxiosRequestConfig) { + const user = await this.find(id, options); + assertObjectFound(user, User, id); + return user; + } + + public static ofId(id: string) { + return new User(id); + } + + public static async resetPassword(email: string) { + await config.behaviors.user.resetPassword(email); + } + + public async addPhoneNumber(phoneNumber: string) { + await config.behaviors.user.addPhoneNumber(this.id, phoneNumber); + } + + public async delete(data: UserDeleteRequestData) { + await config.behaviors.user.delete(data); + } + + public async findCommon( + options?: AxiosRequestConfig, + ): Promise { + return this instanceof UserCommon ? this : this.findDetailed(options); + } + + public async findDetailed( + options?: AxiosRequestConfig, + ): Promise { + return User.find(this.id, options); + } + + public async getAvatarUploadRules() { + return File.getUploadRules("avatar"); + } + + public getCommon( + options?: AxiosRequestConfig, + ): Promise | UserCommon { + return this instanceof UserCommon ? this : this.getDetailed(options); + } + + public async getDetailed( + options?: AxiosRequestConfig, + ): Promise { + return User.get(this.id, options); + } + + public async getPasswordUpdatedAt() { + return await config.behaviors.user.getPasswordUpdatedAt(); + } + + public async removeAvatar() { + await config.behaviors.user.removeAvatar(this.id); + } + + public async removePhoneNumber() { + await config.behaviors.user.removePhoneNumber(this.id); + } + + public async requestAvatarUpload(): Promise { + const response = await config.behaviors.user.createAvatarUploadToken( + this.id, + ); + + return response.token; + } + + public async updateEmail(email: string) { + return await config.behaviors.user.updateEmail(email); + } + + public async updatePassword(data: UserUpdatePasswordRequestData) { + return await config.behaviors.user.updatePassword(data); + } + + public async updatePersonalInformation( + data: UserUpdatePersonalInformationRequestData, + ) { + await config.behaviors.user.updatePersonalInformation(this.id, data); + } + + public async uploadAvatar(file: DomFile) { + await File.upload(file, this.fileAccessTokenProvider); + } + + public async verifyEmail(data: UserVerifyEmailRequestData) { + await config.behaviors.user.verifyEmail(data); + } + + public async verifyPhoneNumber(data: UserVerifyPhoneNumberRequestData) { + return await config.behaviors.user.verifyPhoneNumber(this.id, data); + } +} + +export class UserCommon extends WithData()(User) { + public readonly avatar?: File; + public override readonly data: UserData; + public readonly email?: string; + public readonly firstName: string; + public readonly fullName: string; + public readonly isEmployee: boolean; + public readonly isNew: boolean; + public readonly lastName: string; + public readonly phoneNumber?: string; + public readonly registeredAt: DateTime; + public readonly title?: Salutation; + + public constructor(data: UserData) { + super(data.userId); + this.data = data; + this.firstName = data.person.firstName; + this.lastName = data.person.lastName; + this.fullName = `${data.person.firstName} ${data.person.lastName}`; + this.avatar = data.avatarRef ? File.ofId(data.avatarRef) : undefined; + this.email = data.email; + this.title = data.person.title; + this.phoneNumber = data.phoneNumber; + this.isEmployee = data.isEmployee ?? config.isEmployee?.(this) ?? false; + + const threeMonthsAgo = DateTime.now().minus({ months: 3 }); + // API-DRIFT: registeredAt falls back to DateTime.now() because /user/self omits the field, which wrongly makes accounts look isNew (resolve: drop the fallback once the API returns registeredAt) + this.registeredAt = data.registeredAt + ? DateTime.fromISO(data.registeredAt) + : DateTime.now(); + this.isNew = this.registeredAt > threeMonthsAgo; + } + + public async checkShowFeedbackPoll(requestConfig?: AxiosRequestConfig) { + return await config.behaviors.user.checkShowFeedbackPoll( + this.id, + requestConfig, + ); + } + + public async findRole(project: Project) { + return this.data.projectMemberships?.[project.id]?.role; + } + + public async resendEmailVerification(email: string) { + await config.behaviors.registration.resendVerificationEmail({ + userId: this.id, + email, + }); + } + + public async updateFeedbackPollStatus(status: FeedbackPollStatus) { + await config.behaviors.user.updateFeedbackPollStatus(this.id, status); + } +} + +export class UserDetailed extends UserCommon { + public constructor(data: UserData) { + super(data); + } +} diff --git a/packages/models/src/user/User/UserAvatarAccessTokenProvider.ts b/packages/models/src/user/User/UserAvatarAccessTokenProvider.ts new file mode 100644 index 00000000..2555749f --- /dev/null +++ b/packages/models/src/user/User/UserAvatarAccessTokenProvider.ts @@ -0,0 +1,16 @@ +import type { FileAccessTokenProvider } from "../../file/index.js"; +import type { User } from "./User.js"; + +import { config } from "../../config/index.js"; + +export class UserAvatarAccessTokenProvider implements FileAccessTokenProvider { + public readonly user: User; + + public constructor(user: User) { + this.user = user; + } + + public createUploadToken() { + return config.behaviors.user.createAvatarUploadToken(this.user.id); + } +} diff --git a/packages/models/src/user/User/behaviors/api.ts b/packages/models/src/user/User/behaviors/api.ts new file mode 100644 index 00000000..2bd338f8 --- /dev/null +++ b/packages/models/src/user/User/behaviors/api.ts @@ -0,0 +1,184 @@ +import type { MittwaldAPIV2Client } from "@mittwald/api-client"; + +import type { UserBehaviors } from "./types.js"; + +import { ValidationError } from "../../../errors/index.js"; +import { + withAxiosRequestConfig, + validateResponse, + anyStatus400, + anyStatus404, + anyStatus409, +} from "../../../base/index.js"; + +export const apiUserBehaviors = ( + client: MittwaldAPIV2Client, +): UserBehaviors => ({ + delete: async (data) => { + const response = await client.user.deleteUser({ data }); + + if ( + // API-DRIFT: deleteUser omits 409 in its generated response type, so anyStatus409 (409 as any) is compared (resolve: use the literal 409 once the client type declares it) + response.status === anyStatus409 || + (typeof response.data === "object" && + "originalStatus" in response.data && + response.data.originalStatus === 409) + ) { + throw new ValidationError({ type: "isLastOwner", path: "root" }); + } + + // API-DRIFT: deleteUser omits 404 in its generated response type, so anyStatus404 (404 as any) is passed (resolve: use the literal 404 once the client type declares it) + validateResponse(response, [200, 202, anyStatus404]); + }, + + find: async (userId, options) => { + const response = await client.user.getUser( + { + userId, + }, + withAxiosRequestConfig(options), + ); + if (response.status === 200) { + return response.data; + } + // API-DRIFT: getUser omits 400 in its generated response type, so anyStatus400 (400 as any) is passed (resolve: use the literal 400 once the client type declares it) + validateResponse(response, [anyStatus400, 403, 404]); + }, + + updatePersonalInformation: async (userId, data) => { + const response = await client.user.updatePersonalInformation({ + data: { person: data }, + userId, + }); + + validateResponse(response, 204, { + validationError: { + pathMappings: { + "person.first_name": "firstName", + "person.last_name": "lastName", + }, + }, + }); + }, + + updateEmail: async (email) => { + const response = await client.user.changeEmail({ data: { email } }); + + validateResponse(response, 204, { + validationError: { + typeMappings: { + "*": (e) => + e.message?.includes("already in use") ? "alreadyInUse" : "custom", + }, + }, + }); + }, + + verifyPhoneNumber: async (userId, data) => { + const response = await client.user.verifyPhoneNumber({ userId, data }); + + validateResponse(response, 204, { + validationError: { + pathMappings: { + verification_token: "code", + }, + }, + }); + }, + + checkShowFeedbackPoll: async (userId, requestConfig) => { + const response = await client.user.getPollStatus( + { userId }, + withAxiosRequestConfig(requestConfig), + ); + + validateResponse(response, 200); + + return response.data.shouldShow; + }, + + createAvatarUploadToken: async (userId) => { + const response = await client.user.requestAvatarUpload({ userId }); + validateResponse(response, 200); + return { + token: response.data.refId, + rules: response.data.rules, + }; + }, + + updatePassword: async (data) => { + const response = await client.user.changePassword({ data }); + + validateResponse(response, [200, 202]); + + if (response.status === 202) { + return "mfaRequired"; + } + + return response.data; + }, + + updateFeedbackPollStatus: async (userId, status) => { + const response = await client.user.postPollStatus({ + data: { status, userId }, + userId, + }); + + validateResponse(response, 200); + }, + + refreshSession: async (refreshToken) => { + const response = await client.user.refreshSession({ + data: { refreshToken }, + }); + validateResponse(response, 200); + + return response.data; + }, + + addPhoneNumber: async (userId, phoneNumber) => { + const response = await client.user.addPhoneNumber({ + data: { phoneNumber }, + userId, + }); + + validateResponse(response, 204); + }, + + getPasswordUpdatedAt: async () => { + const response = await client.user.getPasswordUpdatedAt({}); + + validateResponse(response, 200); + + return response.data; + }, + + resetPassword: async (email) => { + const response = await client.user.initPasswordReset({ data: { email } }); + + validateResponse(response, 201); + }, + + confirmPasswordReset: async (data) => { + const response = await client.user.confirmPasswordReset({ data }); + + validateResponse(response, 204); + }, + + removePhoneNumber: async (userId) => { + const response = await client.user.removePhoneNumber({ userId }); + + validateResponse(response, 204); + }, + + removeAvatar: async (userId) => { + const response = await client.user.removeAvatar({ userId }); + + validateResponse(response, 204); + }, + + verifyEmail: async (data) => { + const response = await client.user.verifyEmail({ data }); + validateResponse(response, 204); + }, +}); diff --git a/packages/models/src/user/User/behaviors/index.ts b/packages/models/src/user/User/behaviors/index.ts new file mode 100644 index 00000000..a7b74f7c --- /dev/null +++ b/packages/models/src/user/User/behaviors/index.ts @@ -0,0 +1,2 @@ +export * from "./api.js"; +export * from "./types.js"; diff --git a/packages/models/src/user/User/behaviors/types.ts b/packages/models/src/user/User/behaviors/types.ts new file mode 100644 index 00000000..9e9de543 --- /dev/null +++ b/packages/models/src/user/User/behaviors/types.ts @@ -0,0 +1,62 @@ +import type { AxiosRequestConfig } from "axios"; + +import type { FileUploadTokenData } from "../../../file/index.js"; +import type { + UserUpdatePersonalInformationRequestData, + UserConfirmPasswordResetRequestData, + UserVerifyPhoneNumberRequestData, + UserUpdatePasswordRequestData, + UserVerifyEmailRequestData, + UserUpdatePasswordResult, + UserDeleteRequestData, + FeedbackPollStatus, + RefreshSessionData, + UserData, +} from "../types.js"; + +export interface UserBehaviors { + updatePersonalInformation: ( + userId: string, + data: UserUpdatePersonalInformationRequestData, + ) => Promise; + + checkShowFeedbackPoll: ( + userId: string, + requestConfig?: AxiosRequestConfig, + ) => Promise; + verifyPhoneNumber: ( + userId: string, + data: UserVerifyPhoneNumberRequestData, + ) => Promise; + + updateFeedbackPollStatus: ( + userId: string, + status: FeedbackPollStatus, + ) => Promise; + + updatePassword: ( + data: UserUpdatePasswordRequestData, + ) => Promise; + find: ( + userId: string, + options?: AxiosRequestConfig, + ) => Promise; + confirmPasswordReset: ( + data: UserConfirmPasswordResetRequestData, + ) => Promise; + + createAvatarUploadToken: (userId: string) => Promise; + addPhoneNumber: (userId: string, phoneNumber: string) => Promise; + + refreshSession: (refreshToken: string) => Promise; + getPasswordUpdatedAt: () => Promise<{ passwordUpdatedAt: string }>; + verifyEmail: (data: UserVerifyEmailRequestData) => Promise; + delete: (data: UserDeleteRequestData) => Promise; + + removePhoneNumber: (userId: string) => Promise; + + removeAvatar: (userId: string) => Promise; + + resetPassword: (email: string) => Promise; + updateEmail: (email: string) => Promise; +} diff --git a/packages/models/src/user/User/index.ts b/packages/models/src/user/User/index.ts new file mode 100644 index 00000000..1d871016 --- /dev/null +++ b/packages/models/src/user/User/index.ts @@ -0,0 +1,2 @@ +export * from "./types.js"; +export * from "./User.js"; diff --git a/packages/models/src/user/User/types.ts b/packages/models/src/user/User/types.ts new file mode 100644 index 00000000..89b2de87 --- /dev/null +++ b/packages/models/src/user/User/types.ts @@ -0,0 +1,30 @@ +import type { MittwaldAPIV2 } from "@mittwald/api-client"; + +export type UserData = MittwaldAPIV2.Operations.UserGetUser.ResponseData; + +export type UserUpdatePersonalInformationRequestData = + MittwaldAPIV2.Paths.V2UsersSelfPersonalInformation.Put.Parameters.RequestBody["person"]; + +export type UserVerifyPhoneNumberRequestData = + MittwaldAPIV2.Paths.V2UsersUserIdActionsVerifyPhone.Post.Parameters.RequestBody; + +export type UserVerifyEmailRequestData = + MittwaldAPIV2.Paths.V2UsersSelfCredentialsEmailActionsVerifyEmail.Post.Parameters.RequestBody; + +export type UserUpdatePasswordRequestData = + MittwaldAPIV2.Paths.V2UsersSelfCredentialsPassword.Put.Parameters.RequestBody; + +export type UserUpdatePasswordResult = + MittwaldAPIV2.Operations.UserChangePassword.ResponseData | "mfaRequired"; + +export type UserConfirmPasswordResetRequestData = + MittwaldAPIV2.Paths.V2UsersSelfCredentialsPasswordConfirmReset.Post.Parameters.RequestBody; + +export type UserDeleteRequestData = + MittwaldAPIV2.Paths.V2UsersSelf.Delete.Parameters.RequestBody; + +export type RefreshSessionData = + MittwaldAPIV2.Operations.UserRefreshSession.ResponseData; + +export type FeedbackPollStatus = + MittwaldAPIV2.Paths.V2PollSettingsUserId.Post.Parameters.RequestBody["status"]; diff --git a/packages/models/src/user/index.ts b/packages/models/src/user/index.ts new file mode 100644 index 00000000..5b056109 --- /dev/null +++ b/packages/models/src/user/index.ts @@ -0,0 +1,7 @@ +export * from "./ApiToken/index.js"; +export * from "./Feedback/index.js"; +export * from "./Session/index.js"; +export * from "./Spotlight/index.js"; +export * from "./SshKey/index.js"; +export * from "./SupportCode/index.js"; +export * from "./User/index.js"; diff --git a/packages/models/tsconfig.json b/packages/models/tsconfig.json index d9d3d2a8..f0f937c3 100644 --- a/packages/models/tsconfig.json +++ b/packages/models/tsconfig.json @@ -2,7 +2,10 @@ "compilerOptions": { "declarationDir": "./dist/types", "outDir": "./dist/esm", - "rootDir": "./src" + "rootDir": "./src", + "lib": ["ES2022", "DOM"], + "experimentalDecorators": true, + "emitDecoratorMetadata": true }, "extends": "../../tsconfig.json", "include": ["src/**/*.ts"] diff --git a/packages/models/vitest.config.ts b/packages/models/vitest.config.ts new file mode 100644 index 00000000..53487dbf --- /dev/null +++ b/packages/models/vitest.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + globals: true, + include: ["src/**/*.test.ts"], + }, +}); diff --git a/yarn.lock b/yarn.lock index 42d783f7..9e4e1cc7 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5,13 +5,6 @@ __metadata: version: 8 cacheKey: 10 -"@adobe/css-tools@npm:^4.4.0": - version: 4.4.0 - resolution: "@adobe/css-tools@npm:4.4.0" - checksum: 10/9c6315fe9efa5075d6ddb6ded7a1424bc9c41a01f2314b6bdcc368723985fe161008d03ddcc2b27b2da50cb9c14190fbce965d15cefe5f9a31bdd43f35b52115 - languageName: node - linkType: hard - "@ampproject/remapping@npm:^2.2.0": version: 2.2.1 resolution: "@ampproject/remapping@npm:2.2.1" @@ -42,19 +35,6 @@ __metadata: languageName: node linkType: hard -"@asamuzakjp/css-color@npm:^3.2.0": - version: 3.2.0 - resolution: "@asamuzakjp/css-color@npm:3.2.0" - dependencies: - "@csstools/css-calc": "npm:^2.1.3" - "@csstools/css-color-parser": "npm:^3.0.9" - "@csstools/css-parser-algorithms": "npm:^3.0.4" - "@csstools/css-tokenizer": "npm:^3.0.3" - lru-cache: "npm:^10.4.3" - checksum: 10/870f661460173174fef8bfebea0799ba26566f3aa7b307e5adabb7aae84fed2da68e40080104ed0c83b43c5be632ee409e65396af13bfe948a3ef4c2c729ecd9 - languageName: node - linkType: hard - "@babel/code-frame@npm:^7.0.0": version: 7.21.4 resolution: "@babel/code-frame@npm:7.21.4" @@ -64,16 +44,6 @@ __metadata: languageName: node linkType: hard -"@babel/code-frame@npm:^7.10.4": - version: 7.24.7 - resolution: "@babel/code-frame@npm:7.24.7" - dependencies: - "@babel/highlight": "npm:^7.24.7" - picocolors: "npm:^1.0.0" - checksum: 10/4812e94885ba7e3213d49583a155fdffb05292330f0a9b2c41b49288da70cf3c746a3fda0bf1074041a6d741c33f8d7be24be5e96f41ef77395eeddc5c9ff624 - languageName: node - linkType: hard - "@babel/code-frame@npm:^7.23.5": version: 7.23.5 resolution: "@babel/code-frame@npm:7.23.5" @@ -353,13 +323,6 @@ __metadata: languageName: node linkType: hard -"@babel/helper-validator-identifier@npm:^7.24.7": - version: 7.24.7 - resolution: "@babel/helper-validator-identifier@npm:7.24.7" - checksum: 10/86875063f57361471b531dbc2ea10bbf5406e12b06d249b03827d361db4cad2388c6f00936bcd9dc86479f7e2c69ea21412c2228d4b3672588b754b70a449d4b - languageName: node - linkType: hard - "@babel/helper-validator-identifier@npm:^7.29.7": version: 7.29.7 resolution: "@babel/helper-validator-identifier@npm:7.29.7" @@ -424,18 +387,6 @@ __metadata: languageName: node linkType: hard -"@babel/highlight@npm:^7.24.7": - version: 7.24.7 - resolution: "@babel/highlight@npm:7.24.7" - dependencies: - "@babel/helper-validator-identifier": "npm:^7.24.7" - chalk: "npm:^2.4.2" - js-tokens: "npm:^4.0.0" - picocolors: "npm:^1.0.0" - checksum: 10/69b73f38cdd4f881b09b939a711e76646da34f4834f4ce141d7a49a6bb1926eab1c594148970a8aa9360398dff800f63aade4e81fafdd7c8d8a8489ea93bfec1 - languageName: node - linkType: hard - "@babel/parser@npm:^7.1.0, @babel/parser@npm:^7.20.7": version: 7.21.4 resolution: "@babel/parser@npm:7.21.4" @@ -652,15 +603,6 @@ __metadata: languageName: node linkType: hard -"@babel/runtime@npm:^7.12.5": - version: 7.25.6 - resolution: "@babel/runtime@npm:7.25.6" - dependencies: - regenerator-runtime: "npm:^0.14.0" - checksum: 10/0c4134734deb20e1005ffb9165bf342e1074576621b246d8e5e41cc7cb315a885b7d98950fbf5c63619a2990a56ae82f444d35fe8c4691a0b70c2fe5673667dc - languageName: node - linkType: hard - "@babel/template@npm:^7.22.15, @babel/template@npm:^7.24.0": version: 7.24.0 resolution: "@babel/template@npm:7.24.0" @@ -825,52 +767,6 @@ __metadata: languageName: node linkType: hard -"@csstools/color-helpers@npm:^5.1.0": - version: 5.1.0 - resolution: "@csstools/color-helpers@npm:5.1.0" - checksum: 10/0138b3d5ccbe77aeccf6721fd008a53523c70e932f0c82dca24a1277ca780447e1d8357da47512ebf96358476f8764de57002f3e491920d67e69202f5a74c383 - languageName: node - linkType: hard - -"@csstools/css-calc@npm:^2.1.3, @csstools/css-calc@npm:^2.1.4": - version: 2.1.4 - resolution: "@csstools/css-calc@npm:2.1.4" - peerDependencies: - "@csstools/css-parser-algorithms": ^3.0.5 - "@csstools/css-tokenizer": ^3.0.4 - checksum: 10/06975b650c0f44c60eeb7afdb3fd236f2dd607b2c622e0bc908d3f54de39eb84e0692833320d03dac04bd6c1ab0154aa3fa0dd442bd9e5f917cf14d8e2ba8d74 - languageName: node - linkType: hard - -"@csstools/css-color-parser@npm:^3.0.9": - version: 3.1.0 - resolution: "@csstools/css-color-parser@npm:3.1.0" - dependencies: - "@csstools/color-helpers": "npm:^5.1.0" - "@csstools/css-calc": "npm:^2.1.4" - peerDependencies: - "@csstools/css-parser-algorithms": ^3.0.5 - "@csstools/css-tokenizer": ^3.0.4 - checksum: 10/4741095fdc4501e8e7ada4ed14fbf9dbbe6fea9b989818790ebca15657c29c62defbebacf18592cde2aa638a1d098bbe86d742d2c84ba932fbc00fac51cb8805 - languageName: node - linkType: hard - -"@csstools/css-parser-algorithms@npm:^3.0.4": - version: 3.0.5 - resolution: "@csstools/css-parser-algorithms@npm:3.0.5" - peerDependencies: - "@csstools/css-tokenizer": ^3.0.4 - checksum: 10/e93083b5cb36a3c1e7a47ce10cf62961d05bd1e4c608bb3ee50186ff740157ab0ec16a3956f7b86251efd10703034d849693201eea858ae904848c68d2d46ada - languageName: node - linkType: hard - -"@csstools/css-tokenizer@npm:^3.0.3": - version: 3.0.4 - resolution: "@csstools/css-tokenizer@npm:3.0.4" - checksum: 10/eb6c84c086312f6bb8758dfe2c85addd7475b0927333c5e39a4d59fb210b9810f8c346972046f95e60a721329cffe98895abe451e51de753ad1ca7a8c24ec65f - languageName: node - linkType: hard - "@emnapi/core@npm:1.10.0": version: 1.10.0 resolution: "@emnapi/core@npm:1.10.0" @@ -1361,6 +1257,15 @@ __metadata: languageName: node linkType: hard +"@internationalized/date@npm:^3.12.2": + version: 3.12.4 + resolution: "@internationalized/date@npm:3.12.4" + dependencies: + "@swc/helpers": "npm:^0.5.0" + checksum: 10/002c10b4cf93d87fbeef83faa232a957f5e04d7e5a1c967db40abbf78a02ac6b61328ce447ada3d6dfb875fbf31acf146625e90d7586d04a43d88759ebfbcca1 + languageName: node + linkType: hard + "@isaacs/balanced-match@npm:^4.0.1": version: 4.0.1 resolution: "@isaacs/balanced-match@npm:4.0.1" @@ -1496,27 +1401,6 @@ __metadata: languageName: node linkType: hard -"@jest/environment-jsdom-abstract@npm:30.5.2": - version: 30.5.2 - resolution: "@jest/environment-jsdom-abstract@npm:30.5.2" - dependencies: - "@jest/environment": "npm:30.5.2" - "@jest/fake-timers": "npm:30.5.2" - "@jest/types": "npm:30.5.1" - "@types/node": "npm:*" - jest-mock: "npm:30.5.2" - jest-util: "npm:30.5.1" - peerDependencies: - "@types/jsdom": "*" - canvas: ^3.0.0 - jsdom: "*" - peerDependenciesMeta: - canvas: - optional: true - checksum: 10/fafe9b4ea6131fc1ce4abd3caeec84f91671a48bfa015820c6b4fe3814912274d64b7282ac7a8859755a261c88006d324fd54aab3731caad28edb8da5ebdaa64 - languageName: node - linkType: hard - "@jest/environment@npm:30.5.2": version: 30.5.2 resolution: "@jest/environment@npm:30.5.2" @@ -1801,7 +1685,7 @@ __metadata: languageName: node linkType: hard -"@jridgewell/sourcemap-codec@npm:^1.4.14, @jridgewell/sourcemap-codec@npm:^1.5.0": +"@jridgewell/sourcemap-codec@npm:^1.4.14, @jridgewell/sourcemap-codec@npm:^1.5.0, @jridgewell/sourcemap-codec@npm:^1.5.5": version: 1.6.0 resolution: "@jridgewell/sourcemap-codec@npm:1.6.0" checksum: 10/eb53fbf7eb4051302a599d6b91425f381168b2856f321336fb00852cea1e0c1904af2610c157b1535e94a61caa98f0bd068d1d0394dd46adf9e9c45c4e11af91 @@ -2100,52 +1984,136 @@ __metadata: languageName: unknown linkType: soft -"@mittwald/api-models@workspace:packages/models": +"@mittwald/api-models-react@workspace:packages/models-react": version: 0.0.0-use.local - resolution: "@mittwald/api-models@workspace:packages/models" + resolution: "@mittwald/api-models-react@workspace:packages/models-react" dependencies: "@eslint/js": "npm:^10.0.1" - "@jest/globals": "npm:^30.5.0" "@mittwald/api-client": "workspace:^" - "@mittwald/react-use-promise": "npm:^4.3.0" - "@testing-library/dom": "npm:^10.4.1" - "@testing-library/jest-dom": "npm:^7.0.1" - "@testing-library/react": "npm:^16.3.3" + "@mittwald/api-client-commons": "workspace:^" + "@mittwald/api-models": "workspace:^" + "@mittwald/react-async-proxy": "npm:^0.0.12" + "@mittwald/react-ghostmaker": "npm:^1.6.0" + "@sindresorhus/is": "npm:^8.1.0" + "@tanstack/react-query": "npm:^5.102.8" + "@types/react": "npm:^19.2.17" + eslint: "npm:^10.9.1" + eslint-config-prettier: "npm:^10.1.8" + eslint-plugin-json: "npm:^5.0.0" + eslint-plugin-prettier: "npm:^5.5.6" + globals: "npm:^17.11.0" + minimatch: "npm:^10.2.5" + prettier: "npm:^3.9.6" + react: "npm:^19.2.7" + rimraf: "npm:^6.1.3" + typescript: "npm:^5.9.3" + typescript-eslint: "npm:^8.68.0" + vitest: "npm:^4.1.8" + peerDependencies: + "@mittwald/api-client": "workspace:^" + "@mittwald/api-client-commons": "workspace:^" + "@tanstack/react-query": ^5 + react: ">=19.2" + languageName: unknown + linkType: soft + +"@mittwald/api-models@workspace:^, @mittwald/api-models@workspace:packages/models": + version: 0.0.0-use.local + resolution: "@mittwald/api-models@workspace:packages/models" + dependencies: + "@eslint/js": "npm:^10.0.1" + "@internationalized/date": "npm:^3.12.2" + "@mittwald/axios-cache-with-retry": "npm:^1.0.0" + "@mittwald/react-ghostmaker": "npm:^1.6.0" + "@sindresorhus/is": "npm:^8.1.0" + "@types/d3-array": "npm:^3.2.2" "@types/dinero.js": "npm:^1.9.4" - "@types/jest": "npm:^30.0.0" + "@types/filesize-parser": "npm:^1.5.3" "@types/luxon": "npm:^3.7.5" - "@types/react": "npm:^18.3.31" - "@types/react-dom": "npm:^18.3.7" - another-deep-freeze: "npm:1.0.0" - context: "npm:^4.0.18" + "@types/semver-compare": "npm:^1.0.3" + axios: "npm:^1.15.2" + convert: "npm:^7.0.0" + d3-array: "npm:^3.2.4" dinero.js: "npm:^1.9.1" eslint: "npm:^10.9.1" eslint-config-prettier: "npm:^10.1.8" + eslint-plugin-api-models: "portal:./eslint-rules" eslint-plugin-json: "npm:^5.0.0" eslint-plugin-prettier: "npm:^5.5.6" + filesize-parser: "npm:^1.5.1" globals: "npm:^17.11.0" - jest: "npm:^30.5.0" - jest-environment-jsdom: "npm:^30.5.0" + jsonschema: "npm:^1.5.0" luxon: "npm:^3.7.2" + minimatch: "npm:^10.2.5" object-code: "npm:^2.0.0" - polytype: "npm:^0.17.0" prettier: "npm:^3.9.6" - react: "npm:^18.3.1" - react-dom: "npm:^18.3.1" + pretty-bytes: "npm:^7.1.0" + remeda: "npm:^2.37.0" rimraf: "npm:^6.1.3" - ts-jest: "npm:^29.4.12" - type-fest: "npm:^4.30.0" + semver-compare: "npm:^1.0.0" + shellwords: "npm:^1.1.1" + slugify: "npm:^1.6.9" + tiny-invariant: "npm:^1.3.3" + tldts: "npm:^7.4.2" + tldts-core: "npm:^7.4.2" + type-fest: "npm:^5.7.0" typescript: "npm:^5.9.3" typescript-eslint: "npm:^8.68.0" + vitest: "npm:^4.1.8" + yaml: "npm:^2.9.1" + zod: "npm:^4.4.3" peerDependencies: - "@mittwald/react-use-promise": ^2.6.0 || ^3.0.0 || ^4.0.0 + "@mittwald/api-client": "workspace:^" + "@mittwald/api-client-commons": "workspace:^" + languageName: unknown + linkType: soft + +"@mittwald/axios-cache-with-retry@npm:^1.0.0": + version: 1.1.0 + resolution: "@mittwald/axios-cache-with-retry@npm:1.1.0" + peerDependencies: + axios: ^1 + checksum: 10/98c6606e9f68c47b95b83440fbee2324e2b22b967b33022dff2cc0644abc1dd99b4e37fb24f985ded0b976d0049a3be2d2cd3a4f44f247f66a333fe6c5c42312 + languageName: node + linkType: hard + +"@mittwald/react-async-proxy@npm:^0.0.12": + version: 0.0.12 + resolution: "@mittwald/react-async-proxy@npm:0.0.12" + dependencies: + "@sindresorhus/is": "npm:^7.1.0" + context: "npm:^3.0.33" + object-code: "npm:^1.3.4" + type-fest: "npm:^5.1.0" + peerDependencies: + "@tanstack/react-query": ^5 + react: ">=18.3" + checksum: 10/1d4d88633453c445bb92c77cba1df1daf4d46c04c4265a49813f8cf7ae41ba2c584b765b368dfd048844150137453cf06541caa81cf8479ec0fc16344d2b31cd + languageName: node + linkType: hard + +"@mittwald/react-ghostmaker@npm:^1.6.0": + version: 1.6.0 + resolution: "@mittwald/react-ghostmaker@npm:1.6.0" + dependencies: + "@sindresorhus/is": "npm:^7.2.0" + context: "npm:^3.0.33" + object-code: "npm:^2.0.0" + type-fest: "npm:^5.4.4" + peerDependencies: + "@tanstack/react-query": ^5 + polytype: ^0.17.0 + react: ">=19.2" peerDependenciesMeta: - "@mittwald/react-use-promise": + "@tanstack/react-query": + optional: true + polytype: optional: true react: optional: true - languageName: unknown - linkType: soft + checksum: 10/b0da2dcd4427768883670634944aa44e5b31ae374261c1e203975fc280eb72a3a6300fefd0862b3b67d0617e1169adf72b6a30877e98a6e4407200bb7c7b6a4f + languageName: node + linkType: hard "@mittwald/react-use-promise@npm:^4.3.0": version: 4.3.0 @@ -2938,6 +2906,13 @@ __metadata: languageName: node linkType: hard +"@oxc-project/types@npm:=0.153.0": + version: 0.153.0 + resolution: "@oxc-project/types@npm:0.153.0" + checksum: 10/b123d6c8ed40b683be9af3a976148d522c621421bbae2d5716d210cda7a858108daa4bad77450b780f63529f2c43bd00e4c179f5952ffb6abbaacebdc71e282f + languageName: node + linkType: hard + "@parcel/watcher-android-arm64@npm:2.6.0": version: 2.6.0 resolution: "@parcel/watcher-android-arm64@npm:2.6.0" @@ -3086,6 +3061,118 @@ __metadata: languageName: node linkType: hard +"@rolldown/binding-android-arm-eabi@npm:1.2.13": + version: 1.2.13 + resolution: "@rolldown/binding-android-arm-eabi@npm:1.2.13" + conditions: os=android & cpu=arm + languageName: node + linkType: hard + +"@rolldown/binding-android-arm64@npm:1.2.13": + version: 1.2.13 + resolution: "@rolldown/binding-android-arm64@npm:1.2.13" + conditions: os=android & cpu=arm64 + languageName: node + linkType: hard + +"@rolldown/binding-darwin-arm64@npm:1.2.13": + version: 1.2.13 + resolution: "@rolldown/binding-darwin-arm64@npm:1.2.13" + conditions: os=darwin & cpu=arm64 + languageName: node + linkType: hard + +"@rolldown/binding-darwin-x64@npm:1.2.13": + version: 1.2.13 + resolution: "@rolldown/binding-darwin-x64@npm:1.2.13" + conditions: os=darwin & cpu=x64 + languageName: node + linkType: hard + +"@rolldown/binding-freebsd-x64@npm:1.2.13": + version: 1.2.13 + resolution: "@rolldown/binding-freebsd-x64@npm:1.2.13" + conditions: os=freebsd & cpu=x64 + languageName: node + linkType: hard + +"@rolldown/binding-linux-arm-gnueabihf@npm:1.2.13": + version: 1.2.13 + resolution: "@rolldown/binding-linux-arm-gnueabihf@npm:1.2.13" + conditions: os=linux & cpu=arm + languageName: node + linkType: hard + +"@rolldown/binding-linux-arm64-gnu@npm:1.2.13": + version: 1.2.13 + resolution: "@rolldown/binding-linux-arm64-gnu@npm:1.2.13" + conditions: os=linux & cpu=arm64 & libc=glibc + languageName: node + linkType: hard + +"@rolldown/binding-linux-arm64-musl@npm:1.2.13": + version: 1.2.13 + resolution: "@rolldown/binding-linux-arm64-musl@npm:1.2.13" + conditions: os=linux & cpu=arm64 & libc=musl + languageName: node + linkType: hard + +"@rolldown/binding-linux-ppc64-gnu@npm:1.2.13": + version: 1.2.13 + resolution: "@rolldown/binding-linux-ppc64-gnu@npm:1.2.13" + conditions: os=linux & cpu=ppc64 & libc=glibc + languageName: node + linkType: hard + +"@rolldown/binding-linux-s390x-gnu@npm:1.2.13": + version: 1.2.13 + resolution: "@rolldown/binding-linux-s390x-gnu@npm:1.2.13" + conditions: os=linux & cpu=s390x & libc=glibc + languageName: node + linkType: hard + +"@rolldown/binding-linux-x64-gnu@npm:1.2.13": + version: 1.2.13 + resolution: "@rolldown/binding-linux-x64-gnu@npm:1.2.13" + conditions: os=linux & cpu=x64 & libc=glibc + languageName: node + linkType: hard + +"@rolldown/binding-linux-x64-musl@npm:1.2.13": + version: 1.2.13 + resolution: "@rolldown/binding-linux-x64-musl@npm:1.2.13" + conditions: os=linux & cpu=x64 & libc=musl + languageName: node + linkType: hard + +"@rolldown/binding-openharmony-arm64@npm:1.2.13": + version: 1.2.13 + resolution: "@rolldown/binding-openharmony-arm64@npm:1.2.13" + conditions: os=openharmony & cpu=arm64 + languageName: node + linkType: hard + +"@rolldown/binding-win32-arm64-msvc@npm:1.2.13": + version: 1.2.13 + resolution: "@rolldown/binding-win32-arm64-msvc@npm:1.2.13" + conditions: os=win32 & cpu=arm64 + languageName: node + linkType: hard + +"@rolldown/binding-win32-x64-msvc@npm:1.2.13": + version: 1.2.13 + resolution: "@rolldown/binding-win32-x64-msvc@npm:1.2.13" + conditions: os=win32 & cpu=x64 + languageName: node + linkType: hard + +"@rolldown/pluginutils@npm:^1.0.0": + version: 1.0.1 + resolution: "@rolldown/pluginutils@npm:1.0.1" + checksum: 10/4e95cf9ce23d75e5aa03ea0249cd86f7d1e21f83fbf6f8520e4edd8a251ba1b82c4ba9bc13cd24b6c4661daec6225b06e6d35c64c604e731b230b2a49af47d05 + languageName: node + linkType: hard + "@sigstore/bundle@npm:^4.0.0": version: 4.0.0 resolution: "@sigstore/bundle@npm:4.0.0" @@ -3201,6 +3288,13 @@ __metadata: languageName: node linkType: hard +"@sindresorhus/is@npm:^7.1.0, @sindresorhus/is@npm:^7.2.0": + version: 7.2.0 + resolution: "@sindresorhus/is@npm:7.2.0" + checksum: 10/d4f93d0fae3a799e1cb1cf31cdcc77f087f4203e2659e25afd7296493d9b4d430f37c4193404f56658d220a7467928fd2b29946dc141218bf42a2d2ebf8597fb + languageName: node + linkType: hard + "@sindresorhus/is@npm:^8.1.0": version: 8.1.0 resolution: "@sindresorhus/is@npm:8.1.0" @@ -3226,6 +3320,22 @@ __metadata: languageName: node linkType: hard +"@standard-schema/spec@npm:^1.1.0": + version: 1.1.0 + resolution: "@standard-schema/spec@npm:1.1.0" + checksum: 10/a209615c9e8b2ea535d7db0a5f6aa0f962fd4ab73ee86a46c100fb78116964af1f55a27c1794d4801e534a196794223daa25ff5135021e03c7828aa3d95e1763 + languageName: node + linkType: hard + +"@swc/helpers@npm:^0.5.0": + version: 0.5.23 + resolution: "@swc/helpers@npm:0.5.23" + dependencies: + tslib: "npm:^2.8.0" + checksum: 10/899c9761e827d5bf504bd02067596cfe59ad6c7d6b6f0691a2fb05acf3e6c2954ddece7e15d4a6a81e8d95c81500652e6abec326c6c9bbb50bc3e2141696de43 + languageName: node + linkType: hard + "@szmarczak/http-timer@npm:^4.0.5": version: 4.0.6 resolution: "@szmarczak/http-timer@npm:4.0.6" @@ -3235,59 +3345,21 @@ __metadata: languageName: node linkType: hard -"@testing-library/dom@npm:^10.4.1": - version: 10.4.1 - resolution: "@testing-library/dom@npm:10.4.1" - dependencies: - "@babel/code-frame": "npm:^7.10.4" - "@babel/runtime": "npm:^7.12.5" - "@types/aria-query": "npm:^5.0.1" - aria-query: "npm:5.3.0" - dom-accessibility-api: "npm:^0.5.9" - lz-string: "npm:^1.5.0" - picocolors: "npm:1.1.1" - pretty-format: "npm:^27.0.2" - checksum: 10/7f93e09ea015f151f8b8f42cbab0b2b858999b5445f15239a72a612ef7716e672b14c40c421218194cf191cbecbde0afa6f3dc2cc83dda93ff6a4fb0237df6e6 - languageName: node - linkType: hard - -"@testing-library/jest-dom@npm:^7.0.1": - version: 7.0.1 - resolution: "@testing-library/jest-dom@npm:7.0.1" - dependencies: - "@adobe/css-tools": "npm:^4.4.0" - aria-query: "npm:^5.0.0" - css.escape: "npm:^1.5.1" - dom-accessibility-api: "npm:^0.6.3" - picocolors: "npm:^1.1.1" - redent: "npm:^3.0.0" - peerDependencies: - "@testing-library/dom": ">=10 <11" - vitest: ">= 0.32" - peerDependenciesMeta: - vitest: - optional: true - checksum: 10/0770454b47da9370e59cda691f797c0442e53caefcd412c504b33c7a9bee099c8a9e7d1f07f7eae8d380ea52c34a5d70139e875480a57f729588068edc78f57b +"@tanstack/query-core@npm:5.104.1": + version: 5.104.1 + resolution: "@tanstack/query-core@npm:5.104.1" + checksum: 10/05a4410e32e91eb471a7ca1f420c839b49a11367e15a3cebe8ca94e6bfdfbd3bf75a8c22da664746032113419da95d4a37a3be18471fab009d94601d9295d890 languageName: node linkType: hard -"@testing-library/react@npm:^16.3.3": - version: 16.3.3 - resolution: "@testing-library/react@npm:16.3.3" +"@tanstack/react-query@npm:^5.102.8": + version: 5.104.1 + resolution: "@tanstack/react-query@npm:5.104.1" dependencies: - "@babel/runtime": "npm:^7.12.5" + "@tanstack/query-core": "npm:5.104.1" peerDependencies: - "@testing-library/dom": ^10.0.0 - "@types/react": ^18.0.0 || ^19.0.0 - "@types/react-dom": ^18.0.0 || ^19.0.0 - react: ^18.0.0 || ^19.0.0 - react-dom: ^18.0.0 || ^19.0.0 - peerDependenciesMeta: - "@types/react": - optional: true - "@types/react-dom": - optional: true - checksum: 10/c330e2d8158fd0f4b059cb1cd30f74265c6e80b204cf7245c9b2c4117582d6deb985d51edb62bd1b94e79ef48a2eaba4d002278d06caf725830a8b0f475e0118 + react: ^18 || ^19 + checksum: 10/845b0e7549bce8b85adeb8d092bbdf749b8215296420a02023f2abcee3b350e5d54fcc5aaf396eff617a86581da8313652c3e4de2f6d30848424c1f201409c86 languageName: node linkType: hard @@ -3336,13 +3408,6 @@ __metadata: languageName: node linkType: hard -"@types/aria-query@npm:^5.0.1": - version: 5.0.4 - resolution: "@types/aria-query@npm:5.0.4" - checksum: 10/c0084c389dc030daeaf0115a92ce43a3f4d42fc8fef2d0e22112d87a42798d4a15aac413019d4a63f868327d52ad6740ab99609462b442fe6b9286b172d2e82e - languageName: node - linkType: hard - "@types/babel__core@npm:^7.20.5": version: 7.20.5 resolution: "@types/babel__core@npm:7.20.5" @@ -3396,6 +3461,16 @@ __metadata: languageName: node linkType: hard +"@types/chai@npm:^5.2.2": + version: 5.2.3 + resolution: "@types/chai@npm:5.2.3" + dependencies: + "@types/deep-eql": "npm:*" + assertion-error: "npm:^2.0.1" + checksum: 10/e79947307dc235953622e65f83d2683835212357ca261389116ab90bed369ac862ba28b146b4fed08b503ae1e1a12cb93ce783f24bb8d562950469f4320e1c7c + languageName: node + linkType: hard + "@types/clone-deep@npm:^4.0.4": version: 4.0.4 resolution: "@types/clone-deep@npm:4.0.4" @@ -3403,6 +3478,13 @@ __metadata: languageName: node linkType: hard +"@types/d3-array@npm:^3.2.2": + version: 3.2.2 + resolution: "@types/d3-array@npm:3.2.2" + checksum: 10/1afebd05b688cafaaea295f765b409789f088b274b8a7ca40a4bc2b79760044a898e06a915f40bbc59cf39eabdd2b5d32e960b136fc025fd05c9a9d4435614c6 + languageName: node + linkType: hard + "@types/debug@npm:^4.0.0": version: 4.1.12 resolution: "@types/debug@npm:4.1.12" @@ -3412,6 +3494,13 @@ __metadata: languageName: node linkType: hard +"@types/deep-eql@npm:*": + version: 4.0.2 + resolution: "@types/deep-eql@npm:4.0.2" + checksum: 10/249a27b0bb22f6aa28461db56afa21ec044fa0e303221a62dff81831b20c8530502175f1a49060f7099e7be06181078548ac47c668de79ff9880241968d43d0c + languageName: node + linkType: hard + "@types/dinero.js@npm:^1.9.4": version: 1.9.4 resolution: "@types/dinero.js@npm:1.9.4" @@ -3433,13 +3522,20 @@ __metadata: languageName: node linkType: hard -"@types/estree@npm:^1.0.6, @types/estree@npm:^1.0.8": +"@types/estree@npm:^1.0.0, @types/estree@npm:^1.0.6, @types/estree@npm:^1.0.8": version: 1.0.9 resolution: "@types/estree@npm:1.0.9" checksum: 10/16aabfa703b5bdac83f719b07ce92a11b2d3c9b8628eacc92889d8af46cab2d78fc45c7b5378de383d0500585cea5c2f79125eeddfe5fbc6bd6a27eb0c8ccee5 languageName: node linkType: hard +"@types/filesize-parser@npm:^1.5.3": + version: 1.5.3 + resolution: "@types/filesize-parser@npm:1.5.3" + checksum: 10/f6637c474ea6142c6100dd537959efd8e73ffaad995c8af3e265bdf9c440aa8ee2dd08aab7d69d15792f4bb5cd97d57628124c0218b4d8247284f98f6086990d + languageName: node + linkType: hard + "@types/http-cache-semantics@npm:*": version: 4.0.1 resolution: "@types/http-cache-semantics@npm:4.0.1" @@ -3496,17 +3592,6 @@ __metadata: languageName: node linkType: hard -"@types/jsdom@npm:^21.1.7": - version: 21.1.7 - resolution: "@types/jsdom@npm:21.1.7" - dependencies: - "@types/node": "npm:*" - "@types/tough-cookie": "npm:*" - parse5: "npm:^7.0.0" - checksum: 10/a5ee54aec813ac928ef783f69828213af4d81325f584e1fe7573a9ae139924c40768d1d5249237e62d51b9a34ed06bde059c86c6b0248d627457ec5e5d532dfa - languageName: node - linkType: hard - "@types/json-schema@npm:^7.0.15": version: 7.0.15 resolution: "@types/json-schema@npm:7.0.15" @@ -3620,15 +3705,6 @@ __metadata: languageName: node linkType: hard -"@types/react-dom@npm:^18.3.7": - version: 18.3.7 - resolution: "@types/react-dom@npm:18.3.7" - peerDependencies: - "@types/react": ^18.0.0 - checksum: 10/317569219366d487a3103ba1e5e47154e95a002915fdcf73a44162c48fe49c3a57fcf7f57fc6979e70d447112681e6b13c6c3c1df289db8b544df4aab2d318f3 - languageName: node - linkType: hard - "@types/react@npm:^18.3.31": version: 18.3.31 resolution: "@types/react@npm:18.3.31" @@ -3639,6 +3715,15 @@ __metadata: languageName: node linkType: hard +"@types/react@npm:^19.2.17": + version: 19.3.0 + resolution: "@types/react@npm:19.3.0" + dependencies: + csstype: "npm:^3.2.2" + checksum: 10/2f4589222fd9c512e1ef78e65f334ade8777400add8ec0803fcc3a044761679b7984ba8410a890af24255383c3251a568bb692b60acfa22397ba0a64b2e032bf + languageName: node + linkType: hard + "@types/responselike@npm:^1.0.0": version: 1.0.0 resolution: "@types/responselike@npm:1.0.0" @@ -3648,6 +3733,13 @@ __metadata: languageName: node linkType: hard +"@types/semver-compare@npm:^1.0.3": + version: 1.0.3 + resolution: "@types/semver-compare@npm:1.0.3" + checksum: 10/be6d31ee0de2132ae53d9c675c9774e11037240656e227f6551e7e404293c157a6cd6181c42cec7e85a8a00b3512f0c43e13dac7aaee4a94cbebf73e11e2b68c + languageName: node + linkType: hard + "@types/semver@npm:^7.1.0": version: 7.3.13 resolution: "@types/semver@npm:7.3.13" @@ -3672,13 +3764,6 @@ __metadata: languageName: node linkType: hard -"@types/tough-cookie@npm:*": - version: 4.0.5 - resolution: "@types/tough-cookie@npm:4.0.5" - checksum: 10/01fd82efc8202670865928629697b62fe9bf0c0dcbc5b1c115831caeb073a2c0abb871ff393d7df1ae94ea41e256cb87d2a5a91fd03cdb1b0b4384e08d4ee482 - languageName: node - linkType: hard - "@types/treeify@npm:^1.0.0": version: 1.0.0 resolution: "@types/treeify@npm:1.0.0" @@ -4023,6 +4108,88 @@ __metadata: languageName: node linkType: hard +"@vitest/expect@npm:4.1.11": + version: 4.1.11 + resolution: "@vitest/expect@npm:4.1.11" + dependencies: + "@standard-schema/spec": "npm:^1.1.0" + "@types/chai": "npm:^5.2.2" + "@vitest/spy": "npm:4.1.11" + "@vitest/utils": "npm:4.1.11" + chai: "npm:^6.2.2" + tinyrainbow: "npm:^3.1.0" + checksum: 10/9bfcfe5ad926ab58beea1c700dc057f17422f14516506f8fc12c9881ed3e81d4c2faadb768042c8497fdee7007e201c1bd3e7d2e91157dbb47fb5c07c4c02aaa + languageName: node + linkType: hard + +"@vitest/mocker@npm:4.1.11": + version: 4.1.11 + resolution: "@vitest/mocker@npm:4.1.11" + dependencies: + "@vitest/spy": "npm:4.1.11" + estree-walker: "npm:^3.0.3" + magic-string: "npm:^0.30.21" + peerDependencies: + msw: ^2.4.9 + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + checksum: 10/00b6e1266d8403194b49313e3a9a1af0dff2c773f4b2df11f4955fa0f244fd4b59484cd23381dfef8af30298e2651c1aaa42b439fdbc871bb4bb911de38a9509 + languageName: node + linkType: hard + +"@vitest/pretty-format@npm:4.1.11": + version: 4.1.11 + resolution: "@vitest/pretty-format@npm:4.1.11" + dependencies: + tinyrainbow: "npm:^3.1.0" + checksum: 10/2dfc2f20dbe1c4dbea33ec42e85a8b5648aa6585521bea47573406f5cefb81cd3b86b71f981c4e3d69946e77252cb42a700416c1dc656bb0478cb2932c953cdc + languageName: node + linkType: hard + +"@vitest/runner@npm:4.1.11": + version: 4.1.11 + resolution: "@vitest/runner@npm:4.1.11" + dependencies: + "@vitest/utils": "npm:4.1.11" + pathe: "npm:^2.0.3" + checksum: 10/5247df824fa28b458ba0102592dfec50707982193b62076db941fbe5d7c88fb7067e68a33c194db0092bbe35459cfbeaed33b3c667e5f02192c18baeb4f56239 + languageName: node + linkType: hard + +"@vitest/snapshot@npm:4.1.11": + version: 4.1.11 + resolution: "@vitest/snapshot@npm:4.1.11" + dependencies: + "@vitest/pretty-format": "npm:4.1.11" + "@vitest/utils": "npm:4.1.11" + magic-string: "npm:^0.30.21" + pathe: "npm:^2.0.3" + checksum: 10/5d096373fb4b102f65ff884844a18c2d2e7d88caf68a64a842a245573311b2d531ca5a94ebf7e4fe39324e71a78670f74c949d4ec2cad3764c3f4c272b84d982 + languageName: node + linkType: hard + +"@vitest/spy@npm:4.1.11": + version: 4.1.11 + resolution: "@vitest/spy@npm:4.1.11" + checksum: 10/d49a7ed7501080e5f817d61250a169a46fcc7901887e4985a1e08705ce79aea8d1edcffd74f4dc6669ea1bc3d717a39354ce89c67188d81a63dc439d42f195f6 + languageName: node + linkType: hard + +"@vitest/utils@npm:4.1.11": + version: 4.1.11 + resolution: "@vitest/utils@npm:4.1.11" + dependencies: + "@vitest/pretty-format": "npm:4.1.11" + convert-source-map: "npm:^2.0.0" + tinyrainbow: "npm:^3.1.0" + checksum: 10/f05381e12d0926db7b01bfaae9a577fa664d36b96c23df185e4b0f6dad3a9fb59ac00931613da53b4511ee6ab473a14ac500c72c5ec5e9b3c3042875051f20c4 + languageName: node + linkType: hard + "@yarnpkg/core@npm:^4.9.1": version: 4.9.1 resolution: "@yarnpkg/core@npm:4.9.1" @@ -4292,13 +4459,6 @@ __metadata: languageName: node linkType: hard -"another-deep-freeze@npm:1.0.0": - version: 1.0.0 - resolution: "another-deep-freeze@npm:1.0.0" - checksum: 10/73dd20db6176a84ea347089e53a0cd36847a3f3f0a39c32ae21b114ae8bfeb2d6b5bb0d60bc0612540af7cd8bfed3a3470583e32540418045211525cc5a9e411 - languageName: node - linkType: hard - "ansi-escapes@npm:^4.3.2": version: 4.3.2 resolution: "ansi-escapes@npm:4.3.2" @@ -4347,7 +4507,7 @@ __metadata: languageName: node linkType: hard -"ansi-styles@npm:^5.0.0, ansi-styles@npm:^5.2.0": +"ansi-styles@npm:^5.2.0": version: 5.2.0 resolution: "ansi-styles@npm:5.2.0" checksum: 10/d7f4e97ce0623aea6bc0d90dcd28881ee04cba06c570b97fd3391bd7a268eedfd9d5e2dd4fdcbdd82b8105df5faf6f24aaedc08eaf3da898e702db5948f63469 @@ -4429,22 +4589,6 @@ __metadata: languageName: node linkType: hard -"aria-query@npm:5.3.0": - version: 5.3.0 - resolution: "aria-query@npm:5.3.0" - dependencies: - dequal: "npm:^2.0.3" - checksum: 10/c3e1ed127cc6886fea4732e97dd6d3c3938e64180803acfb9df8955517c4943760746ffaf4020ce8f7ffaa7556a3b5f85c3769a1f5ca74a1288e02d042f9ae4e - languageName: node - linkType: hard - -"aria-query@npm:^5.0.0": - version: 5.3.1 - resolution: "aria-query@npm:5.3.1" - checksum: 10/4b39d2e466992121886ae436d67085537af895b7e545e6092b89950a1f2c372e4a91b0b1daa16a5164564fdefbc6415a1d04d0fe2db8b1326f9ca6728f8384d0 - languageName: node - linkType: hard - "array-find-index@npm:^1.0.2": version: 1.0.2 resolution: "array-find-index@npm:1.0.2" @@ -4466,6 +4610,13 @@ __metadata: languageName: node linkType: hard +"assertion-error@npm:^2.0.1": + version: 2.0.1 + resolution: "assertion-error@npm:2.0.1" + checksum: 10/a0789dd882211b87116e81e2648ccb7f60340b34f19877dd020b39ebb4714e475eb943e14ba3e22201c221ef6645b7bfe10297e76b6ac95b48a9898c1211ce66 + languageName: node + linkType: hard + "async@npm:^3.2.3": version: 3.2.5 resolution: "async@npm:3.2.5" @@ -4956,6 +5107,13 @@ __metadata: languageName: node linkType: hard +"chai@npm:^6.2.2": + version: 6.3.0 + resolution: "chai@npm:6.3.0" + checksum: 10/8798b98c6df6ad8d880239e8d6a2de8a1472c4dd19430e712bd1d846433679be8217427a2ceb9344af2db108a99030a6eaee689aa19baed7f917fa90354a50fa + languageName: node + linkType: hard + "chalk@npm:4.1.2, chalk@npm:^4.0.2, chalk@npm:^4.1.0, chalk@npm:^4.1.2": version: 4.1.2 resolution: "chalk@npm:4.1.2" @@ -5260,7 +5418,7 @@ __metadata: languageName: node linkType: hard -"context@npm:^3.1.0": +"context@npm:^3.0.33, context@npm:^3.1.0": version: 3.1.0 resolution: "context@npm:3.1.0" dependencies: @@ -5269,15 +5427,6 @@ __metadata: languageName: node linkType: hard -"context@npm:^4.0.18": - version: 4.0.18 - resolution: "context@npm:4.0.18" - dependencies: - vest-utils: "npm:^2.0.18" - checksum: 10/ef59931ef811ecb1e239f83ccd67bd4c501b260016ce61afc5705a2a7c9b9317be22184f767a65efa51543cc3643fd58cd918398cac78c6e51f5b24837a2623b - languageName: node - linkType: hard - "conventional-changelog-angular@npm:^9.4.0": version: 9.4.0 resolution: "conventional-changelog-angular@npm:9.4.0" @@ -5369,6 +5518,13 @@ __metadata: languageName: node linkType: hard +"convert@npm:^7.0.0": + version: 7.0.2 + resolution: "convert@npm:7.0.2" + checksum: 10/60322ddb56f092e09f99be876aae4c5c217a91061496cf6cb8487f2fb47904f89acc31d62bfe2dc883cbfd8466152be73fe52c18c5a4b115e891e82a8663fe67 + languageName: node + linkType: hard + "core-util-is@npm:1.0.2": version: 1.0.2 resolution: "core-util-is@npm:1.0.2" @@ -5411,13 +5567,6 @@ __metadata: languageName: node linkType: hard -"css.escape@npm:^1.5.1": - version: 1.5.1 - resolution: "css.escape@npm:1.5.1" - checksum: 10/f6d38088d870a961794a2580b2b2af1027731bb43261cfdce14f19238a88664b351cc8978abc20f06cc6bbde725699dec8deb6fe9816b139fc3f2af28719e774 - languageName: node - linkType: hard - "cssesc@npm:^3.0.0": version: 3.0.0 resolution: "cssesc@npm:3.0.0" @@ -5427,16 +5576,6 @@ __metadata: languageName: node linkType: hard -"cssstyle@npm:^4.2.1": - version: 4.6.0 - resolution: "cssstyle@npm:4.6.0" - dependencies: - "@asamuzakjp/css-color": "npm:^3.2.0" - rrweb-cssom: "npm:^0.8.0" - checksum: 10/1cb25c9d66b87adb165f978b75cdeb6f225d7e31ba30a8934666046a0be037e4e7200d359bfa79d4f1a4aef1083ea09633b81bcdb36a2f2ac888e8c73ea3a289 - languageName: node - linkType: hard - "csstype@npm:^3.2.2": version: 3.2.3 resolution: "csstype@npm:3.2.3" @@ -5444,13 +5583,12 @@ __metadata: languageName: node linkType: hard -"data-urls@npm:^5.0.0": - version: 5.0.0 - resolution: "data-urls@npm:5.0.0" +"d3-array@npm:^3.2.4": + version: 3.2.4 + resolution: "d3-array@npm:3.2.4" dependencies: - whatwg-mimetype: "npm:^4.0.0" - whatwg-url: "npm:^14.0.0" - checksum: 10/5c40568c31b02641a70204ff233bc4e42d33717485d074244a98661e5f2a1e80e38fe05a5755dfaf2ee549f2ab509d6a3af2a85f4b2ad2c984e5d176695eaf46 + internmap: "npm:1 - 2" + checksum: 10/5800c467f89634776a5977f6dae3f4e127d91be80f1d07e3e6e35303f9de93e6636d014b234838eea620f7469688d191b3f41207a30040aab750a63c97ec1d7c languageName: node linkType: hard @@ -5478,13 +5616,6 @@ __metadata: languageName: node linkType: hard -"decimal.js@npm:^10.5.0": - version: 10.6.0 - resolution: "decimal.js@npm:10.6.0" - checksum: 10/c0d45842d47c311d11b38ce7ccc911121953d4df3ebb1465d92b31970eb4f6738a065426a06094af59bee4b0d64e42e7c8984abd57b6767c64ea90cf90bb4a69 - languageName: node - linkType: hard - "decode-named-character-reference@npm:^1.0.0": version: 1.0.2 resolution: "decode-named-character-reference@npm:1.0.2" @@ -5593,7 +5724,7 @@ __metadata: languageName: node linkType: hard -"dequal@npm:^2.0.0, dequal@npm:^2.0.3": +"dequal@npm:^2.0.0": version: 2.0.3 resolution: "dequal@npm:2.0.3" checksum: 10/6ff05a7561f33603df87c45e389c9ac0a95e3c056be3da1a0c4702149e3a7f6fe5ffbb294478687ba51a9e95f3a60e8b6b9005993acd79c292c7d15f71964b6b @@ -5660,20 +5791,6 @@ __metadata: languageName: node linkType: hard -"dom-accessibility-api@npm:^0.5.9": - version: 0.5.16 - resolution: "dom-accessibility-api@npm:0.5.16" - checksum: 10/377b4a7f9eae0a5d72e1068c369c99e0e4ca17fdfd5219f3abd32a73a590749a267475a59d7b03a891f9b673c27429133a818c44b2e47e32fec024b34274e2ca - languageName: node - linkType: hard - -"dom-accessibility-api@npm:^0.6.3": - version: 0.6.3 - resolution: "dom-accessibility-api@npm:0.6.3" - checksum: 10/83d3371f8226487fbad36e160d44f1d9017fb26d46faba6a06fcad15f34633fc827b8c3e99d49f71d5f3253d866e2131826866fd0a3c86626f8eccfc361881ff - languageName: node - linkType: hard - "dot-prop@npm:^10.2.0": version: 10.2.0 resolution: "dot-prop@npm:10.2.0" @@ -5836,20 +5953,6 @@ __metadata: languageName: node linkType: hard -"entities@npm:^4.4.0": - version: 4.5.0 - resolution: "entities@npm:4.5.0" - checksum: 10/ede2a35c9bce1aeccd055a1b445d41c75a14a2bb1cd22e242f20cf04d236cdcd7f9c859eb83f76885327bfae0c25bf03303665ee1ce3d47c5927b98b0e3e3d48 - languageName: node - linkType: hard - -"entities@npm:^6.0.0": - version: 6.0.1 - resolution: "entities@npm:6.0.1" - checksum: 10/62af1307202884349d2867f0aac5c60d8b57102ea0b0e768b16246099512c28e239254ad772d6834e7e14cb1b6f153fc3d0c031934e3183b086c86d3838d874a - languageName: node - linkType: hard - "env-paths@npm:^2.2.0": version: 2.2.1 resolution: "env-paths@npm:2.2.1" @@ -5887,7 +5990,7 @@ __metadata: languageName: node linkType: hard -"es-module-lexer@npm:^2.1.0": +"es-module-lexer@npm:^2.0.0, es-module-lexer@npm:^2.1.0": version: 2.3.2 resolution: "es-module-lexer@npm:2.3.2" checksum: 10/065246d6e2b2dfea3287650b5800a30326771e0d9d238570e81371d7ae8d53db239bccb2166e272926bba44917da7c66dd7407a5214d17b0af5269005b1fec52 @@ -6069,6 +6172,12 @@ __metadata: languageName: node linkType: hard +"eslint-plugin-api-models@portal:./eslint-rules::locator=%40mittwald%2Fapi-models%40workspace%3Apackages%2Fmodels": + version: 0.0.0-use.local + resolution: "eslint-plugin-api-models@portal:./eslint-rules::locator=%40mittwald%2Fapi-models%40workspace%3Apackages%2Fmodels" + languageName: node + linkType: soft + "eslint-plugin-json@npm:^5.0.0": version: 5.0.0 resolution: "eslint-plugin-json@npm:5.0.0" @@ -6216,6 +6325,15 @@ __metadata: languageName: node linkType: hard +"estree-walker@npm:^3.0.3": + version: 3.0.3 + resolution: "estree-walker@npm:3.0.3" + dependencies: + "@types/estree": "npm:^1.0.0" + checksum: 10/a65728d5727b71de172c5df323385755a16c0fdab8234dc756c3854cfee343261ddfbb72a809a5660fac8c75d960bb3e21aa898c2d7e9b19bb298482ca58a3af + languageName: node + linkType: hard + "esutils@npm:^2.0.2": version: 2.0.3 resolution: "esutils@npm:2.0.3" @@ -6247,6 +6365,13 @@ __metadata: languageName: node linkType: hard +"expect-type@npm:^1.3.0": + version: 1.4.0 + resolution: "expect-type@npm:1.4.0" + checksum: 10/bad91f4b7eb807248695ee840a935d12818fe531ad523bc7ac7dcc540a4d86dc566a3ef829f4da6e8b5a458ac84092771739865114c91e7e8a9317302f401f09 + languageName: node + linkType: hard + "expect@npm:30.5.2, expect@npm:^30.0.0": version: 30.5.2 resolution: "expect@npm:30.5.2" @@ -6449,6 +6574,13 @@ __metadata: languageName: node linkType: hard +"filesize-parser@npm:^1.5.1": + version: 1.5.2 + resolution: "filesize-parser@npm:1.5.2" + checksum: 10/c3742a0ac36c9ba8599b4eb1415b3ccec9035823a71455388c915138479ba63b94d114335b5d158f765811b33b20ab1d952ff32c7ff159beca77ec97b453ff61 + languageName: node + linkType: hard + "fill-range@npm:^7.1.1": version: 7.1.1 resolution: "fill-range@npm:7.1.1" @@ -7034,15 +7166,6 @@ __metadata: languageName: node linkType: hard -"html-encoding-sniffer@npm:^4.0.0": - version: 4.0.0 - resolution: "html-encoding-sniffer@npm:4.0.0" - dependencies: - whatwg-encoding: "npm:^3.1.1" - checksum: 10/e86efd493293a5671b8239bd099d42128433bb3c7b0fdc7819282ef8e118a21f5dead0ad6f358e024a4e5c84f17ebb7a9b36075220fac0a6222b207248bede6f - languageName: node - linkType: hard - "html-escaper@npm:^2.0.0": version: 2.0.2 resolution: "html-escaper@npm:2.0.2" @@ -7057,7 +7180,7 @@ __metadata: languageName: node linkType: hard -"http-proxy-agent@npm:^7.0.0, http-proxy-agent@npm:^7.0.2": +"http-proxy-agent@npm:^7.0.0": version: 7.0.2 resolution: "http-proxy-agent@npm:7.0.2" dependencies: @@ -7104,16 +7227,6 @@ __metadata: languageName: node linkType: hard -"https-proxy-agent@npm:^7.0.6": - version: 7.0.6 - resolution: "https-proxy-agent@npm:7.0.6" - dependencies: - agent-base: "npm:^7.1.2" - debug: "npm:4" - checksum: 10/784b628cbd55b25542a9d85033bdfd03d4eda630fb8b3c9477959367f3be95dc476ed2ecbb9836c359c7c698027fc7b45723a302324433590f45d6c1706e8c13 - languageName: node - linkType: hard - "human-signals@npm:^2.1.0": version: 2.1.0 resolution: "human-signals@npm:2.1.0" @@ -7121,7 +7234,7 @@ __metadata: languageName: node linkType: hard -"iconv-lite@npm:0.6.3, iconv-lite@npm:^0.6.2": +"iconv-lite@npm:^0.6.2": version: 0.6.3 resolution: "iconv-lite@npm:0.6.3" dependencies: @@ -7264,6 +7377,13 @@ __metadata: languageName: node linkType: hard +"internmap@npm:1 - 2": + version: 2.0.3 + resolution: "internmap@npm:2.0.3" + checksum: 10/873e0e7fcfe32f999aa0997a0b648b1244508e56e3ea6b8259b5245b50b5eeb3853fba221f96692bd6d1def501da76c32d64a5cb22a0b26cdd9b445664f805e0 + languageName: node + linkType: hard + "invariant@npm:^2.2.4": version: 2.2.4 resolution: "invariant@npm:2.2.4" @@ -7402,13 +7522,6 @@ __metadata: languageName: node linkType: hard -"is-potential-custom-element-name@npm:^1.0.1": - version: 1.0.1 - resolution: "is-potential-custom-element-name@npm:1.0.1" - checksum: 10/ced7bbbb6433a5b684af581872afe0e1767e2d1146b2207ca0068a648fb5cab9d898495d1ac0583524faaf24ca98176a7d9876363097c2d14fee6dd324f3a1ab - languageName: node - linkType: hard - "is-ssh@npm:^1.4.0": version: 1.4.0 resolution: "is-ssh@npm:1.4.0" @@ -7716,23 +7829,6 @@ __metadata: languageName: node linkType: hard -"jest-environment-jsdom@npm:^30.5.0": - version: 30.5.2 - resolution: "jest-environment-jsdom@npm:30.5.2" - dependencies: - "@jest/environment": "npm:30.5.2" - "@jest/environment-jsdom-abstract": "npm:30.5.2" - "@types/jsdom": "npm:^21.1.7" - jsdom: "npm:^26.1.0" - peerDependencies: - canvas: ^3.0.0 - peerDependenciesMeta: - canvas: - optional: true - checksum: 10/8f316ec57f973de7f7ec7151d33c0038a4c6ed3d02e0cac910d69dacb805cd0f21133fea4b1f575c8d5c8a33d71a2c1a320e2d710df16dd0901284ecff9fecd6 - languageName: node - linkType: hard - "jest-environment-node@npm:30.5.2": version: 30.5.2 resolution: "jest-environment-node@npm:30.5.2" @@ -8076,39 +8172,6 @@ __metadata: languageName: node linkType: hard -"jsdom@npm:^26.1.0": - version: 26.1.0 - resolution: "jsdom@npm:26.1.0" - dependencies: - cssstyle: "npm:^4.2.1" - data-urls: "npm:^5.0.0" - decimal.js: "npm:^10.5.0" - html-encoding-sniffer: "npm:^4.0.0" - http-proxy-agent: "npm:^7.0.2" - https-proxy-agent: "npm:^7.0.6" - is-potential-custom-element-name: "npm:^1.0.1" - nwsapi: "npm:^2.2.16" - parse5: "npm:^7.2.1" - rrweb-cssom: "npm:^0.8.0" - saxes: "npm:^6.0.0" - symbol-tree: "npm:^3.2.4" - tough-cookie: "npm:^5.1.1" - w3c-xmlserializer: "npm:^5.0.0" - webidl-conversions: "npm:^7.0.0" - whatwg-encoding: "npm:^3.1.1" - whatwg-mimetype: "npm:^4.0.0" - whatwg-url: "npm:^14.1.1" - ws: "npm:^8.18.0" - xml-name-validator: "npm:^5.0.0" - peerDependencies: - canvas: ^3.0.0 - peerDependenciesMeta: - canvas: - optional: true - checksum: 10/39d78c4889cac20826393400dce1faed1666e9244fe0c8342a8f08c315375878e6be7fcfe339a33d6ff1a083bfe9e71b16d56ecf4d9a87db2da8c795925ea8c1 - languageName: node - linkType: hard - "jsesc@npm:^2.5.1": version: 2.5.2 resolution: "jsesc@npm:2.5.2" @@ -8252,6 +8315,13 @@ __metadata: languageName: node linkType: hard +"jsonschema@npm:^1.5.0": + version: 1.5.0 + resolution: "jsonschema@npm:1.5.0" + checksum: 10/46bf49b388ba922073bcb3c8d5e90af9d29fc8303dc866fd440182c88d6b4fd2807679fd39cdefb4113156d104ea47da9c0ff4bbcb0032c9fa29461cb1a92182 + languageName: node + linkType: hard + "just-diff-apply@npm:^5.2.0": version: 5.5.0 resolution: "just-diff-apply@npm:5.5.0" @@ -8455,6 +8525,126 @@ __metadata: languageName: node linkType: hard +"lightningcss-android-arm64@npm:1.33.0": + version: 1.33.0 + resolution: "lightningcss-android-arm64@npm:1.33.0" + conditions: os=android & cpu=arm64 + languageName: node + linkType: hard + +"lightningcss-darwin-arm64@npm:1.33.0": + version: 1.33.0 + resolution: "lightningcss-darwin-arm64@npm:1.33.0" + conditions: os=darwin & cpu=arm64 + languageName: node + linkType: hard + +"lightningcss-darwin-x64@npm:1.33.0": + version: 1.33.0 + resolution: "lightningcss-darwin-x64@npm:1.33.0" + conditions: os=darwin & cpu=x64 + languageName: node + linkType: hard + +"lightningcss-freebsd-x64@npm:1.33.0": + version: 1.33.0 + resolution: "lightningcss-freebsd-x64@npm:1.33.0" + conditions: os=freebsd & cpu=x64 + languageName: node + linkType: hard + +"lightningcss-linux-arm-gnueabihf@npm:1.33.0": + version: 1.33.0 + resolution: "lightningcss-linux-arm-gnueabihf@npm:1.33.0" + conditions: os=linux & cpu=arm + languageName: node + linkType: hard + +"lightningcss-linux-arm64-gnu@npm:1.33.0": + version: 1.33.0 + resolution: "lightningcss-linux-arm64-gnu@npm:1.33.0" + conditions: os=linux & cpu=arm64 & libc=glibc + languageName: node + linkType: hard + +"lightningcss-linux-arm64-musl@npm:1.33.0": + version: 1.33.0 + resolution: "lightningcss-linux-arm64-musl@npm:1.33.0" + conditions: os=linux & cpu=arm64 & libc=musl + languageName: node + linkType: hard + +"lightningcss-linux-x64-gnu@npm:1.33.0": + version: 1.33.0 + resolution: "lightningcss-linux-x64-gnu@npm:1.33.0" + conditions: os=linux & cpu=x64 & libc=glibc + languageName: node + linkType: hard + +"lightningcss-linux-x64-musl@npm:1.33.0": + version: 1.33.0 + resolution: "lightningcss-linux-x64-musl@npm:1.33.0" + conditions: os=linux & cpu=x64 & libc=musl + languageName: node + linkType: hard + +"lightningcss-win32-arm64-msvc@npm:1.33.0": + version: 1.33.0 + resolution: "lightningcss-win32-arm64-msvc@npm:1.33.0" + conditions: os=win32 & cpu=arm64 + languageName: node + linkType: hard + +"lightningcss-win32-x64-msvc@npm:1.33.0": + version: 1.33.0 + resolution: "lightningcss-win32-x64-msvc@npm:1.33.0" + conditions: os=win32 & cpu=x64 + languageName: node + linkType: hard + +"lightningcss@npm:^1.33.0": + version: 1.33.0 + resolution: "lightningcss@npm:1.33.0" + dependencies: + detect-libc: "npm:^2.0.3" + lightningcss-android-arm64: "npm:1.33.0" + lightningcss-darwin-arm64: "npm:1.33.0" + lightningcss-darwin-x64: "npm:1.33.0" + lightningcss-freebsd-x64: "npm:1.33.0" + lightningcss-linux-arm-gnueabihf: "npm:1.33.0" + lightningcss-linux-arm64-gnu: "npm:1.33.0" + lightningcss-linux-arm64-musl: "npm:1.33.0" + lightningcss-linux-x64-gnu: "npm:1.33.0" + lightningcss-linux-x64-musl: "npm:1.33.0" + lightningcss-win32-arm64-msvc: "npm:1.33.0" + lightningcss-win32-x64-msvc: "npm:1.33.0" + dependenciesMeta: + lightningcss-android-arm64: + optional: true + lightningcss-darwin-arm64: + optional: true + lightningcss-darwin-x64: + optional: true + lightningcss-freebsd-x64: + optional: true + lightningcss-linux-arm-gnueabihf: + optional: true + lightningcss-linux-arm64-gnu: + optional: true + lightningcss-linux-arm64-musl: + optional: true + lightningcss-linux-x64-gnu: + optional: true + lightningcss-linux-x64-musl: + optional: true + lightningcss-win32-arm64-msvc: + optional: true + lightningcss-win32-x64-msvc: + optional: true + checksum: 10/9b3b5db404af352fe5861926b9909281d29bede175539035c1a01e1ad4dcee8bb6f871e8e3d01a67a85e9e1cd18a63e52871a48cf62feab4d1aa868d4f2c3c2e + languageName: node + linkType: hard + "lilconfig@npm:^3.1.2": version: 3.1.2 resolution: "lilconfig@npm:3.1.2" @@ -8557,7 +8747,7 @@ __metadata: languageName: node linkType: hard -"lru-cache@npm:^10.0.1, lru-cache@npm:^10.2.0, lru-cache@npm:^10.4.3": +"lru-cache@npm:^10.0.1, lru-cache@npm:^10.2.0": version: 10.4.3 resolution: "lru-cache@npm:10.4.3" checksum: 10/e6e90267360476720fa8e83cc168aa2bf0311f3f2eea20a6ba78b90a885ae72071d9db132f40fda4129c803e7dcec3a6b6a6fbb44ca90b081630b810b5d6a41a @@ -8587,12 +8777,12 @@ __metadata: languageName: node linkType: hard -"lz-string@npm:^1.5.0": - version: 1.5.0 - resolution: "lz-string@npm:1.5.0" - bin: - lz-string: bin/bin.js - checksum: 10/e86f0280e99a8d8cd4eef24d8601ddae15ce54e43ac9990dfcb79e1e081c255ad24424a30d78d2ad8e51a8ce82a66a930047fed4b4aa38c6f0b392ff9300edfc +"magic-string@npm:^0.30.21": + version: 0.30.21 + resolution: "magic-string@npm:0.30.21" + dependencies: + "@jridgewell/sourcemap-codec": "npm:^1.5.5" + checksum: 10/57d5691f41ed40d962d8bd300148114f53db67fadbff336207db10a99f2bdf4a1be9cac3a68ee85dba575912ee1d4402e4396408196ec2d3afd043b076156221 languageName: node linkType: hard @@ -9023,13 +9213,6 @@ __metadata: languageName: node linkType: hard -"min-indent@npm:^1.0.0": - version: 1.0.1 - resolution: "min-indent@npm:1.0.1" - checksum: 10/bfc6dd03c5eaf623a4963ebd94d087f6f4bbbfd8c41329a7f09706b0cb66969c4ddd336abeb587bc44bc6f08e13bf90f0b374f9d71f9f01e04adc2cd6f083ef1 - languageName: node - linkType: hard - "minimatch@npm:10.2.5": version: 10.2.5 resolution: "minimatch@npm:10.2.5" @@ -9260,6 +9443,15 @@ __metadata: languageName: node linkType: hard +"nanoid@npm:^3.3.19": + version: 3.3.20 + resolution: "nanoid@npm:3.3.20" + bin: + nanoid: bin/nanoid.cjs + checksum: 10/b19641487fc25325189175226a4b9fcc8da39989c6a39fd35921802158d6b1725d59d8454a4e30643d2bb4837382cac11ee129417282678a67f8394b31c228d9 + languageName: node + linkType: hard + "napi-postinstall@npm:^0.3.4": version: 0.3.4 resolution: "napi-postinstall@npm:0.3.4" @@ -9768,13 +9960,6 @@ __metadata: languageName: node linkType: hard -"nwsapi@npm:^2.2.16": - version: 2.2.28 - resolution: "nwsapi@npm:2.2.28" - checksum: 10/2395c1d894d2a11c7299c92f62e51849b6a02256d48a9a40c64a40e32ca06b188145cd984256a3134a6930794623abf9d7df9ab9f31dd63f471d1f999efb4830 - languageName: node - linkType: hard - "nx@npm:^23.1.2": version: 23.2.1 resolution: "nx@npm:23.2.1" @@ -10028,6 +10213,13 @@ __metadata: languageName: node linkType: hard +"obug@npm:^2.1.1": + version: 2.2.1 + resolution: "obug@npm:2.2.1" + checksum: 10/306f1bf423aafdd46bc4a99108ffa2a1f6f82b87b10f535ad9853b580d565612f7913a0e71542914fb88d8920b97d6313c36fc1eec858d08071fe2eea0a8aa12 + languageName: node + linkType: hard + "once@npm:1.4.0, once@npm:^1.3.0, once@npm:^1.3.1, once@npm:^1.4.0": version: 1.4.0 resolution: "once@npm:1.4.0" @@ -10327,24 +10519,6 @@ __metadata: languageName: node linkType: hard -"parse5@npm:^7.0.0": - version: 7.1.2 - resolution: "parse5@npm:7.1.2" - dependencies: - entities: "npm:^4.4.0" - checksum: 10/3c86806bb0fb1e9a999ff3a4c883b1ca243d99f45a619a0898dbf021a95a0189ed955c31b07fe49d342b54e814f33f2c9d7489198e8630dacd5477d413ec5782 - languageName: node - linkType: hard - -"parse5@npm:^7.2.1": - version: 7.3.0 - resolution: "parse5@npm:7.3.0" - dependencies: - entities: "npm:^6.0.0" - checksum: 10/b0e48be20b820c655b138b86fa6fb3a790de6c891aa2aba536524f8027b4dca4fe538f11a0e5cf2f6f847d120dbb9e4822dcaeb933ff1e10850a2ef0154d1d88 - languageName: node - linkType: hard - "path-exists@npm:^4.0.0": version: 4.0.0 resolution: "path-exists@npm:4.0.0" @@ -10410,6 +10584,13 @@ __metadata: languageName: node linkType: hard +"pathe@npm:^2.0.3": + version: 2.0.3 + resolution: "pathe@npm:2.0.3" + checksum: 10/01e9a69928f39087d96e1751ce7d6d50da8c39abf9a12e0ac2389c42c83bc76f78c45a475bd9026a02e6a6f79be63acc75667df855862fe567d99a00a540d23d + languageName: node + linkType: hard + "picocolors@npm:1.1.1, picocolors@npm:^1.1.1": version: 1.1.1 resolution: "picocolors@npm:1.1.1" @@ -10417,13 +10598,6 @@ __metadata: languageName: node linkType: hard -"picocolors@npm:^1.0.0": - version: 1.1.0 - resolution: "picocolors@npm:1.1.0" - checksum: 10/a2ad60d94d185c30f2a140b19c512547713fb89b920d32cc6cf658fa786d63a37ba7b8451872c3d9fc34883971fb6e5878e07a20b60506e0bb2554dce9169ccb - languageName: node - linkType: hard - "picocolors@npm:^1.0.1": version: 1.0.1 resolution: "picocolors@npm:1.0.1" @@ -10452,7 +10626,7 @@ __metadata: languageName: node linkType: hard -"picomatch@npm:^4.0.4": +"picomatch@npm:^4.0.4, picomatch@npm:^4.0.7": version: 4.0.7 resolution: "picomatch@npm:4.0.7" checksum: 10/66e1df34bc39c72fa3756be4069f7887ea3e35e94bba1c3f6167763007698cb04b8a0a365161d186fda6e9571a2d3efb606b2966eb6a7dea6252911224dc2f48 @@ -10475,13 +10649,6 @@ __metadata: languageName: node linkType: hard -"polytype@npm:^0.17.0": - version: 0.17.0 - resolution: "polytype@npm:0.17.0" - checksum: 10/f6ebd1752a98f4b27689604fd3b36e60ae1296d84030421bbc7ecb785fd9f3b85e95b2f8aacaf2802ab30c79cb0b47bbf36493a46e8f6b5759ba14fd53ae301a - languageName: node - linkType: hard - "postcss-selector-parser@npm:^7.0.0": version: 7.1.0 resolution: "postcss-selector-parser@npm:7.1.0" @@ -10492,6 +10659,17 @@ __metadata: languageName: node linkType: hard +"postcss@npm:^8.5.29": + version: 8.5.29 + resolution: "postcss@npm:8.5.29" + dependencies: + nanoid: "npm:^3.3.19" + picocolors: "npm:^1.1.1" + source-map-js: "npm:^1.2.2" + checksum: 10/801c352ab8aa59aaea145c11e59f1f134db834be0398e15e16969a1ca19dabbd2aa709cdca285d796a8462cee1a1a2626d435b4b63d1a1010100934e9fac3a1b + languageName: node + linkType: hard + "powershell-utils@npm:^0.1.0": version: 0.1.0 resolution: "powershell-utils@npm:0.1.0" @@ -10576,6 +10754,13 @@ __metadata: languageName: node linkType: hard +"pretty-bytes@npm:^7.1.0": + version: 7.2.0 + resolution: "pretty-bytes@npm:7.2.0" + checksum: 10/8129d82cc618a25985b3269036f84b9ded26d5902d8a680d9fbda9c149d3cbe7bbba64ba38b34fb700a3791d9827a4f628d8ab32530d2e729fceec13caa0f6eb + languageName: node + linkType: hard + "pretty-format@npm:30.5.1, pretty-format@npm:^30.0.0": version: 30.5.1 resolution: "pretty-format@npm:30.5.1" @@ -10588,17 +10773,6 @@ __metadata: languageName: node linkType: hard -"pretty-format@npm:^27.0.2": - version: 27.5.1 - resolution: "pretty-format@npm:27.5.1" - dependencies: - ansi-regex: "npm:^5.0.1" - ansi-styles: "npm:^5.0.0" - react-is: "npm:^17.0.1" - checksum: 10/248990cbef9e96fb36a3e1ae6b903c551ca4ddd733f8d0912b9cc5141d3d0b3f9f8dfb4d799fb1c6723382c9c2083ffbfa4ad43ff9a0e7535d32d41fd5f01da6 - languageName: node - linkType: hard - "proc-log@npm:^4.0.0, proc-log@npm:^4.1.0, proc-log@npm:^4.2.0": version: 4.2.0 resolution: "proc-log@npm:4.2.0" @@ -10691,7 +10865,7 @@ __metadata: languageName: node linkType: hard -"punycode@npm:^2.1.0, punycode@npm:^2.3.1": +"punycode@npm:^2.1.0": version: 2.3.1 resolution: "punycode@npm:2.3.1" checksum: 10/febdc4362bead22f9e2608ff0171713230b57aff9dddc1c273aa2a651fbd366f94b7d6a71d78342a7c0819906750351ca7f2edd26ea41b626d87d6a13d1bd059 @@ -10737,25 +10911,6 @@ __metadata: languageName: node linkType: hard -"react-dom@npm:^18.3.1": - version: 18.3.1 - resolution: "react-dom@npm:18.3.1" - dependencies: - loose-envify: "npm:^1.1.0" - scheduler: "npm:^0.23.2" - peerDependencies: - react: ^18.3.1 - checksum: 10/3f4b73a3aa083091173b29812b10394dd06f4ac06aff410b74702cfb3aa29d7b0ced208aab92d5272919b612e5cda21aeb1d54191848cf6e46e9e354f3541f81 - languageName: node - linkType: hard - -"react-is@npm:^17.0.1": - version: 17.0.2 - resolution: "react-is@npm:17.0.2" - checksum: 10/73b36281e58eeb27c9cc6031301b6ae19ecdc9f18ae2d518bdb39b0ac564e65c5779405d623f1df9abf378a13858b79442480244bd579968afc1faf9a2ce5e05 - languageName: node - linkType: hard - "react@npm:^18.3.1": version: 18.3.1 resolution: "react@npm:18.3.1" @@ -10765,6 +10920,13 @@ __metadata: languageName: node linkType: hard +"react@npm:^19.2.7": + version: 19.3.0 + resolution: "react@npm:19.3.0" + checksum: 10/e98669f09750c41abb1bf020af67cc847e018c91a8c5413d3f40ddd737e3daef6e419bcd1521b113fda73fd667ae82d5f0e9d9e3ff462faeb82059c09e7f04b1 + languageName: node + linkType: hard + "read-cmd-shim@npm:^6.0.0": version: 6.0.0 resolution: "read-cmd-shim@npm:6.0.0" @@ -10805,16 +10967,6 @@ __metadata: languageName: node linkType: hard -"redent@npm:^3.0.0": - version: 3.0.0 - resolution: "redent@npm:3.0.0" - dependencies: - indent-string: "npm:^4.0.0" - strip-indent: "npm:^3.0.0" - checksum: 10/fa1ef20404a2d399235e83cc80bd55a956642e37dd197b4b612ba7327bf87fa32745aeb4a1634b2bab25467164ab4ed9c15be2c307923dd08b0fe7c52431ae6b - languageName: node - linkType: hard - "reftools@npm:^1.1.9": version: 1.1.9 resolution: "reftools@npm:1.1.9" @@ -10822,10 +10974,10 @@ __metadata: languageName: node linkType: hard -"regenerator-runtime@npm:^0.14.0": - version: 0.14.1 - resolution: "regenerator-runtime@npm:0.14.1" - checksum: 10/5db3161abb311eef8c45bcf6565f4f378f785900ed3945acf740a9888c792f75b98ecb77f0775f3bf95502ff423529d23e94f41d80c8256e8fa05ed4b07cf471 +"remeda@npm:^2.37.0": + version: 2.51.0 + resolution: "remeda@npm:2.51.0" + checksum: 10/1f3c94189d21f446eabd98c34beb4f5b199f15be8c84888bc49fb79636eb511d575f856d4b62cc1f9f542a355bf9819f6767e13d5575e31ac8c5241b5c7dbd80 languageName: node linkType: hard @@ -10925,6 +11077,64 @@ __metadata: languageName: node linkType: hard +"rolldown@npm:~1.2.12": + version: 1.2.13 + resolution: "rolldown@npm:1.2.13" + dependencies: + "@oxc-project/types": "npm:=0.153.0" + "@rolldown/binding-android-arm-eabi": "npm:1.2.13" + "@rolldown/binding-android-arm64": "npm:1.2.13" + "@rolldown/binding-darwin-arm64": "npm:1.2.13" + "@rolldown/binding-darwin-x64": "npm:1.2.13" + "@rolldown/binding-freebsd-x64": "npm:1.2.13" + "@rolldown/binding-linux-arm-gnueabihf": "npm:1.2.13" + "@rolldown/binding-linux-arm64-gnu": "npm:1.2.13" + "@rolldown/binding-linux-arm64-musl": "npm:1.2.13" + "@rolldown/binding-linux-ppc64-gnu": "npm:1.2.13" + "@rolldown/binding-linux-s390x-gnu": "npm:1.2.13" + "@rolldown/binding-linux-x64-gnu": "npm:1.2.13" + "@rolldown/binding-linux-x64-musl": "npm:1.2.13" + "@rolldown/binding-openharmony-arm64": "npm:1.2.13" + "@rolldown/binding-win32-arm64-msvc": "npm:1.2.13" + "@rolldown/binding-win32-x64-msvc": "npm:1.2.13" + "@rolldown/pluginutils": "npm:^1.0.0" + dependenciesMeta: + "@rolldown/binding-android-arm-eabi": + optional: true + "@rolldown/binding-android-arm64": + optional: true + "@rolldown/binding-darwin-arm64": + optional: true + "@rolldown/binding-darwin-x64": + optional: true + "@rolldown/binding-freebsd-x64": + optional: true + "@rolldown/binding-linux-arm-gnueabihf": + optional: true + "@rolldown/binding-linux-arm64-gnu": + optional: true + "@rolldown/binding-linux-arm64-musl": + optional: true + "@rolldown/binding-linux-ppc64-gnu": + optional: true + "@rolldown/binding-linux-s390x-gnu": + optional: true + "@rolldown/binding-linux-x64-gnu": + optional: true + "@rolldown/binding-linux-x64-musl": + optional: true + "@rolldown/binding-openharmony-arm64": + optional: true + "@rolldown/binding-win32-arm64-msvc": + optional: true + "@rolldown/binding-win32-x64-msvc": + optional: true + bin: + rolldown: ./bin/cli.mjs + checksum: 10/7e602afd9c851e1e4c26711030211ec36c538f57a59e5c84ea74167a98db14eeecc8741a8c3564bcce8b9377ec0c5502973acc823bca4788da25ad6f70283416 + languageName: node + linkType: hard + "root@workspace:.": version: 0.0.0-use.local resolution: "root@workspace:." @@ -10951,13 +11161,6 @@ __metadata: languageName: unknown linkType: soft -"rrweb-cssom@npm:^0.8.0": - version: 0.8.0 - resolution: "rrweb-cssom@npm:0.8.0" - checksum: 10/07521ee36fb6569c17906afad1ac7ff8f099d49ade9249e190693ac36cdf27f88d9acf0cc66978935d5d0a23fca105643d7e9125b9a9d91ed9db9e02d31d7d80 - languageName: node - linkType: hard - "run-applescript@npm:7.0.0": version: 7.0.0 resolution: "run-applescript@npm:7.0.0" @@ -11004,21 +11207,10 @@ __metadata: languageName: node linkType: hard -"saxes@npm:^6.0.0": - version: 6.0.0 - resolution: "saxes@npm:6.0.0" - dependencies: - xmlchars: "npm:^2.2.0" - checksum: 10/97b50daf6ca3a153e89842efa18a862e446248296622b7473c169c84c823ee8a16e4a43bac2f73f11fc8cb9168c73fbb0d73340f26552bac17970e9052367aa9 - languageName: node - linkType: hard - -"scheduler@npm:^0.23.2": - version: 0.23.2 - resolution: "scheduler@npm:0.23.2" - dependencies: - loose-envify: "npm:^1.1.0" - checksum: 10/e8d68b89d18d5b028223edf090092846868a765a591944760942b77ea1f69b17235f7e956696efbb62c8130ab90af7e0949bfb8eba7896335507317236966bc9 +"semver-compare@npm:^1.0.0": + version: 1.0.0 + resolution: "semver-compare@npm:1.0.0" + checksum: 10/75f9c7a7786d1756f64b1429017746721e07bd7691bdad6368f7643885d3a98a27586777e9699456564f4844b407e9f186cc1d588a3f9c0be71310e517e942c3 languageName: node linkType: hard @@ -11099,6 +11291,13 @@ __metadata: languageName: node linkType: hard +"shellwords@npm:^1.1.1": + version: 1.1.1 + resolution: "shellwords@npm:1.1.1" + checksum: 10/ab90aefb4fd4e1ecd9d2f41bd8c1490700bb4280ec177eee2d6f05a18d39a9da88d21af3efe869d8e669f6a42e99e8a8490c1b71b94a650f14fa2dc3bba59c5f + languageName: node + linkType: hard + "should-equal@npm:^2.0.0": version: 2.0.0 resolution: "should-equal@npm:2.0.0" @@ -11155,6 +11354,13 @@ __metadata: languageName: node linkType: hard +"siginfo@npm:^2.0.0": + version: 2.0.0 + resolution: "siginfo@npm:2.0.0" + checksum: 10/e93ff66c6531a079af8fb217240df01f980155b5dc408d2d7bebc398dd284e383eb318153bf8acd4db3c4fe799aa5b9a641e38b0ba3b1975700b1c89547ea4e7 + languageName: node + linkType: hard + "signal-exit@npm:3.0.7, signal-exit@npm:^3.0.2, signal-exit@npm:^3.0.3": version: 3.0.7 resolution: "signal-exit@npm:3.0.7" @@ -11197,6 +11403,13 @@ __metadata: languageName: node linkType: hard +"slugify@npm:^1.6.9": + version: 1.6.9 + resolution: "slugify@npm:1.6.9" + checksum: 10/101599a77585ac3b3fe49662db8666260c8ee1c5090d28a13c6ecabf16b42057e69ea209654797f46b13faee4c53224f48784044bd734a9443b7b88e0357110e + languageName: node + linkType: hard + "smart-buffer@npm:^4.2.0": version: 4.2.0 resolution: "smart-buffer@npm:4.2.0" @@ -11266,6 +11479,13 @@ __metadata: languageName: node linkType: hard +"source-map-js@npm:^1.2.2": + version: 1.2.2 + resolution: "source-map-js@npm:1.2.2" + checksum: 10/4807c894bb6280c8b84886159b96080e3996f42c6e8015e647881edfd4f955f6024ceebb8bb40d33ce8b106e24b2e29c133575e1c60c01c8aae57a05fdf17761 + languageName: node + linkType: hard + "source-map@npm:^0.6.1": version: 0.6.1 resolution: "source-map@npm:0.6.1" @@ -11396,6 +11616,20 @@ __metadata: languageName: node linkType: hard +"stackback@npm:0.0.2": + version: 0.0.2 + resolution: "stackback@npm:0.0.2" + checksum: 10/2d4dc4e64e2db796de4a3c856d5943daccdfa3dd092e452a1ce059c81e9a9c29e0b9badba91b43ef0d5ff5c04ee62feb3bcc559a804e16faf447bac2d883aa99 + languageName: node + linkType: hard + +"std-env@npm:^4.0.0-rc.1": + version: 4.3.0 + resolution: "std-env@npm:4.3.0" + checksum: 10/1a44e665e05aafab70880b253d7c3ee96611e375dec317e8af2392305e68809decd399a78fd2480c687705e29836137dac49f4df19ce0470d50dd48aabd54d26 + languageName: node + linkType: hard + "strict-event-emitter@npm:^0.5.1": version: 0.5.1 resolution: "strict-event-emitter@npm:0.5.1" @@ -11522,15 +11756,6 @@ __metadata: languageName: node linkType: hard -"strip-indent@npm:^3.0.0": - version: 3.0.0 - resolution: "strip-indent@npm:3.0.0" - dependencies: - min-indent: "npm:^1.0.0" - checksum: 10/18f045d57d9d0d90cd16f72b2313d6364fd2cb4bf85b9f593523ad431c8720011a4d5f08b6591c9d580f446e78855c5334a30fb91aa1560f5d9f95ed1b4a0530 - languageName: node - linkType: hard - "strip-json-comments@npm:^3.1.1": version: 3.1.1 resolution: "strip-json-comments@npm:3.1.1" @@ -11595,13 +11820,6 @@ __metadata: languageName: node linkType: hard -"symbol-tree@npm:^3.2.4": - version: 3.2.4 - resolution: "symbol-tree@npm:3.2.4" - checksum: 10/c09a00aadf279d47d0c5c46ca3b6b2fbaeb45f0a184976d599637d412d3a70bbdc043ff33effe1206dea0e36e0ad226cb957112e7ce9a4bf2daedf7fa4f85c53 - languageName: node - linkType: hard - "synckit@npm:^0.11.13, synckit@npm:^0.11.8": version: 0.11.13 resolution: "synckit@npm:0.11.13" @@ -11689,6 +11907,13 @@ __metadata: languageName: node linkType: hard +"tiny-invariant@npm:^1.3.3": + version: 1.3.3 + resolution: "tiny-invariant@npm:1.3.3" + checksum: 10/5e185c8cc2266967984ce3b352a4e57cb89dad5a8abb0dea21468a6ecaa67cd5bb47a3b7a85d08041008644af4f667fb8b6575ba38ba5fb00b3b5068306e59fe + languageName: node + linkType: hard + "tiny-relative-date@npm:^2.0.2": version: 2.0.2 resolution: "tiny-relative-date@npm:2.0.2" @@ -11696,7 +11921,14 @@ __metadata: languageName: node linkType: hard -"tinyexec@npm:^1.3.1": +"tinybench@npm:^2.9.0": + version: 2.9.0 + resolution: "tinybench@npm:2.9.0" + checksum: 10/cfa1e1418e91289219501703c4693c70708c91ffb7f040fd318d24aef419fb5a43e0c0160df9471499191968b2451d8da7f8087b08c3133c251c40d24aced06c + languageName: node + linkType: hard + +"tinyexec@npm:^1.0.2, tinyexec@npm:^1.3.1": version: 1.3.1 resolution: "tinyexec@npm:1.3.1" checksum: 10/9c7a8ce2633f76c776d9ff663531c7b34d605f41909c2f97a27397e8c12bcaf721dae7680b6683232ffe7a6d465090be9926d5ffd00b5d7be9336a43b45289b1 @@ -11740,21 +11972,28 @@ __metadata: languageName: node linkType: hard -"tldts-core@npm:^6.1.86": - version: 6.1.86 - resolution: "tldts-core@npm:6.1.86" - checksum: 10/cb5dff9cc15661ac773a2099e98c99a5cb3cebc35909c23cc4261ff7992032c7501995ae995de3574dbbf3431e59c47496534d52f5e96abcb231f0e72144c020 +"tinyrainbow@npm:^3.1.0": + version: 3.2.0 + resolution: "tinyrainbow@npm:3.2.0" + checksum: 10/27089c12ad4b18439fbdd651bf9d076584aad9b2a36da36ba841d6bd31156f5489e15497b2377162478277cb89cf6ea6a323be401fd9d55794a6963b65fe55d4 + languageName: node + linkType: hard + +"tldts-core@npm:^7.4.18, tldts-core@npm:^7.4.2": + version: 7.4.18 + resolution: "tldts-core@npm:7.4.18" + checksum: 10/6b5713a7098f442e510eb2d1e0fd0c27fa1ef43ac5ed49fd1132b7b1ef86e7049456b3ea28d38e850e1f5a20dfdef7e759de1400349bb659db5cf1958180cd48 languageName: node linkType: hard -"tldts@npm:^6.1.32": - version: 6.1.86 - resolution: "tldts@npm:6.1.86" +"tldts@npm:^7.4.2": + version: 7.4.18 + resolution: "tldts@npm:7.4.18" dependencies: - tldts-core: "npm:^6.1.86" + tldts-core: "npm:^7.4.18" bin: tldts: bin/cli.js - checksum: 10/f7e66824e44479ccdda55ea556af14ce61c4d27708be403e3f90631defde49f82a580e1ca07187cc7e3b349e257a30c2808a22903f3a0548e136ebb609ccc109 + checksum: 10/8b29032c713d6fbdd806cc4f81ee2e860e3997ef2a96f1325b02c953af2cf3cd6ccf9cd1e54857388e748da088a4ccd03bfc3bed056040d887efbbd56ad288aa languageName: node linkType: hard @@ -11781,24 +12020,6 @@ __metadata: languageName: node linkType: hard -"tough-cookie@npm:^5.1.1": - version: 5.1.2 - resolution: "tough-cookie@npm:5.1.2" - dependencies: - tldts: "npm:^6.1.32" - checksum: 10/de430e6e6d34b794137e05b8ac2aa6b74ebbe6cdceb4126f168cf1e76101162a4b2e0e7587c3b70e728bd8654fc39958b2035be7619ee6f08e7257610ba4cd04 - languageName: node - linkType: hard - -"tr46@npm:^5.1.0": - version: 5.1.1 - resolution: "tr46@npm:5.1.1" - dependencies: - punycode: "npm:^2.3.1" - checksum: 10/833a0e1044574da5790148fd17866d4ddaea89e022de50279967bcd6b28b4ce0d30d59eb3acf9702b60918975b3bad481400337e3a2e6326cffa5c77b874753d - languageName: node - linkType: hard - "tr46@npm:~0.0.3": version: 0.0.3 resolution: "tr46@npm:0.0.3" @@ -11889,7 +12110,7 @@ __metadata: languageName: node linkType: hard -"tslib@npm:2.8.1": +"tslib@npm:2.8.1, tslib@npm:^2.8.0": version: 2.8.1 resolution: "tslib@npm:2.8.1" checksum: 10/3e2e043d5c2316461cb54e5c7fe02c30ef6dccb3384717ca22ae5c6b5bc95232a6241df19c622d9c73b809bea33b187f6dbc73030963e29950c2141bc32a79f7 @@ -11984,7 +12205,7 @@ __metadata: languageName: node linkType: hard -"type-fest@npm:^5.0.0, type-fest@npm:^5.4.4": +"type-fest@npm:^5.0.0, type-fest@npm:^5.1.0, type-fest@npm:^5.4.4, type-fest@npm:^5.7.0": version: 5.10.0 resolution: "type-fest@npm:5.10.0" dependencies: @@ -12311,10 +12532,128 @@ __metadata: languageName: node linkType: hard -"vest-utils@npm:^2.0.18": - version: 2.0.18 - resolution: "vest-utils@npm:2.0.18" - checksum: 10/57c32faf43d8d6a4369a639da89541ae639654355c2baf0f60eded17240deda237661472de7b29fe57aca42bcab2979554196d9dc10ba693619c9a9930716565 +"vite@npm:^6.0.0 || ^7.0.0 || ^8.0.0": + version: 8.3.4 + resolution: "vite@npm:8.3.4" + dependencies: + fsevents: "npm:~2.3.3" + lightningcss: "npm:^1.33.0" + picomatch: "npm:^4.0.7" + postcss: "npm:^8.5.29" + rolldown: "npm:~1.2.12" + tinyglobby: "npm:^0.2.17" + peerDependencies: + "@types/node": ^20.19.0 || >=22.12.0 + "@vitejs/devtools": ^0.7.1 + esbuild: ^0.27.0 || ^0.28.0 + jiti: ">=1.21.0" + less: ^4.0.0 + sass: ^1.70.0 + sass-embedded: ^1.70.0 + stylus: ">=0.54.8" + sugarss: ^5.0.0 + terser: ^5.16.0 + tsx: ^4.8.1 + yaml: ^2.4.2 + dependenciesMeta: + fsevents: + optional: true + peerDependenciesMeta: + "@types/node": + optional: true + "@vitejs/devtools": + optional: true + esbuild: + optional: true + jiti: + optional: true + less: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + tsx: + optional: true + yaml: + optional: true + bin: + vite: bin/vite.js + checksum: 10/b1f7cbae6aae9ce8851c5ac86fde04b2193379d33eca99da653d4a4cff61705381a954bacc5a985aacad65ee72e783b19c12a2eca95ef3c97aeb91f147f371de + languageName: node + linkType: hard + +"vitest@npm:^4.1.8": + version: 4.1.11 + resolution: "vitest@npm:4.1.11" + dependencies: + "@vitest/expect": "npm:4.1.11" + "@vitest/mocker": "npm:4.1.11" + "@vitest/pretty-format": "npm:4.1.11" + "@vitest/runner": "npm:4.1.11" + "@vitest/snapshot": "npm:4.1.11" + "@vitest/spy": "npm:4.1.11" + "@vitest/utils": "npm:4.1.11" + es-module-lexer: "npm:^2.0.0" + expect-type: "npm:^1.3.0" + magic-string: "npm:^0.30.21" + obug: "npm:^2.1.1" + pathe: "npm:^2.0.3" + picomatch: "npm:^4.0.3" + std-env: "npm:^4.0.0-rc.1" + tinybench: "npm:^2.9.0" + tinyexec: "npm:^1.0.2" + tinyglobby: "npm:^0.2.15" + tinyrainbow: "npm:^3.1.0" + vite: "npm:^6.0.0 || ^7.0.0 || ^8.0.0" + why-is-node-running: "npm:^2.3.0" + peerDependencies: + "@edge-runtime/vm": "*" + "@opentelemetry/api": ^1.9.0 + "@types/node": ^20.0.0 || ^22.0.0 || >=24.0.0 + "@vitest/browser-playwright": 4.1.11 + "@vitest/browser-preview": 4.1.11 + "@vitest/browser-webdriverio": 4.1.11 + "@vitest/coverage-istanbul": 4.1.11 + "@vitest/coverage-v8": 4.1.11 + "@vitest/ui": 4.1.11 + happy-dom: "*" + jsdom: "*" + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + "@edge-runtime/vm": + optional: true + "@opentelemetry/api": + optional: true + "@types/node": + optional: true + "@vitest/browser-playwright": + optional: true + "@vitest/browser-preview": + optional: true + "@vitest/browser-webdriverio": + optional: true + "@vitest/coverage-istanbul": + optional: true + "@vitest/coverage-v8": + optional: true + "@vitest/ui": + optional: true + happy-dom: + optional: true + jsdom: + optional: true + vite: + optional: false + bin: + vitest: ./vitest.mjs + checksum: 10/054f1e25d90d911693b0b93c5b85a7c3105775aa3e39c3279c7d3e7af719e2d94070a898d6d74292445366c1215bb91d07063989ac0965973f0c5ae22ad3b06b languageName: node linkType: hard @@ -12359,15 +12698,6 @@ __metadata: languageName: node linkType: hard -"w3c-xmlserializer@npm:^5.0.0": - version: 5.0.0 - resolution: "w3c-xmlserializer@npm:5.0.0" - dependencies: - xml-name-validator: "npm:^5.0.0" - checksum: 10/d78f59e6b4f924aa53b6dfc56949959229cae7fe05ea9374eb38d11edcec01398b7f5d7a12576bd5acc57ff446abb5c9115cd83b9d882555015437cf858d42f0 - languageName: node - linkType: hard - "walk-up-path@npm:^4.0.0": version: 4.0.0 resolution: "walk-up-path@npm:4.0.0" @@ -12391,39 +12721,6 @@ __metadata: languageName: node linkType: hard -"webidl-conversions@npm:^7.0.0": - version: 7.0.0 - resolution: "webidl-conversions@npm:7.0.0" - checksum: 10/4c4f65472c010eddbe648c11b977d048dd96956a625f7f8b9d64e1b30c3c1f23ea1acfd654648426ce5c743c2108a5a757c0592f02902cf7367adb7d14e67721 - languageName: node - linkType: hard - -"whatwg-encoding@npm:^3.1.1": - version: 3.1.1 - resolution: "whatwg-encoding@npm:3.1.1" - dependencies: - iconv-lite: "npm:0.6.3" - checksum: 10/bbef815eb67f91487c7f2ef96329743f5fd8357d7d62b1119237d25d41c7e452dff8197235b2d3c031365a17f61d3bb73ca49d0ed1582475aa4a670815e79534 - languageName: node - linkType: hard - -"whatwg-mimetype@npm:^4.0.0": - version: 4.0.0 - resolution: "whatwg-mimetype@npm:4.0.0" - checksum: 10/894a618e2d90bf444b6f309f3ceb6e58cf21b2beaa00c8b333696958c4076f0c7b30b9d33413c9ffff7c5832a0a0c8569e5bb347ef44beded72aeefd0acd62e8 - languageName: node - linkType: hard - -"whatwg-url@npm:^14.0.0, whatwg-url@npm:^14.1.1": - version: 14.2.0 - resolution: "whatwg-url@npm:14.2.0" - dependencies: - tr46: "npm:^5.1.0" - webidl-conversions: "npm:^7.0.0" - checksum: 10/f0a95b0601c64f417c471536a2d828b4c16fe37c13662483a32f02f183ed0f441616609b0663fb791e524e8cd56d9a86dd7366b1fc5356048ccb09b576495e7c - languageName: node - linkType: hard - "whatwg-url@npm:^5.0.0": version: 5.0.0 resolution: "whatwg-url@npm:5.0.0" @@ -12489,6 +12786,18 @@ __metadata: languageName: node linkType: hard +"why-is-node-running@npm:^2.3.0": + version: 2.3.0 + resolution: "why-is-node-running@npm:2.3.0" + dependencies: + siginfo: "npm:^2.0.0" + stackback: "npm:0.0.2" + bin: + why-is-node-running: cli.js + checksum: 10/0de6e6cd8f2f94a8b5ca44e84cf1751eadcac3ebedcdc6e5fbbe6c8011904afcbc1a2777c53496ec02ced7b81f2e7eda61e76bf8262a8bc3ceaa1f6040508051 + languageName: node + linkType: hard + "widest-line@npm:^3.1.0": version: 3.1.0 resolution: "widest-line@npm:3.1.0" @@ -12593,21 +12902,6 @@ __metadata: languageName: node linkType: hard -"ws@npm:^8.18.0": - version: 8.22.0 - resolution: "ws@npm:8.22.0" - peerDependencies: - bufferutil: ^4.0.1 - utf-8-validate: ">=5.0.2" - peerDependenciesMeta: - bufferutil: - optional: true - utf-8-validate: - optional: true - checksum: 10/ed771c2766bdb5724a66872f60ffc1a39f06e1a5bc8849f453c273e97c91a40ed5a224f06dc0e22f44b4a9e03938bf746fc5938d6887433cc0f4c416237d3b10 - languageName: node - linkType: hard - "wsl-utils@npm:^0.4.0": version: 0.4.0 resolution: "wsl-utils@npm:0.4.0" @@ -12618,20 +12912,6 @@ __metadata: languageName: node linkType: hard -"xml-name-validator@npm:^5.0.0": - version: 5.0.0 - resolution: "xml-name-validator@npm:5.0.0" - checksum: 10/43f30f3f6786e406dd665acf08cd742d5f8a46486bd72517edb04b27d1bcd1599664c2a4a99fc3f1e56a3194bff588b12f178b7972bc45c8047bdc4c3ac8d4a1 - languageName: node - linkType: hard - -"xmlchars@npm:^2.2.0": - version: 2.2.0 - resolution: "xmlchars@npm:2.2.0" - checksum: 10/4ad5924974efd004a47cce6acf5c0269aee0e62f9a805a426db3337af7bcbd331099df174b024ace4fb18971b8a56de386d2e73a1c4b020e3abd63a4a9b917f1 - languageName: node - linkType: hard - "y18n@npm:5.0.8, y18n@npm:^5.0.5": version: 5.0.8 resolution: "y18n@npm:5.0.8" @@ -12785,7 +13065,7 @@ __metadata: languageName: node linkType: hard -"zod@npm:^4.6.5": +"zod@npm:^4.4.3, zod@npm:^4.6.5": version: 4.6.5 resolution: "zod@npm:4.6.5" checksum: 10/db004952e4dc6eab38b70f0cdef9251a65da84f5d08c5a0ef85e2590cfa9c477544ce734161ff5c05f89a15f0967137607a7feb16716195e04965f030db47213