mirror of https://github.com/ghostfolio/ghostfolio
Browse Source
# Conflicts: # apps/client/src/app/pages/portfolio/analysis/analysis-page.component.ts # apps/client/src/app/pages/portfolio/analysis/analysis-page.htmlpull/7034/head
1031 changed files with 127539 additions and 64705 deletions
@ -1,66 +1,39 @@ |
|||
# End-to-End (E2E) Testing |
|||
|
|||
This project uses [Cypress](https://www.cypress.io/) for end-to-end (E2E) testing, which simulates real user interactions in a browser. The E2E tests are located primarily within the `devtools/` package. |
|||
|
|||
## Running E2E Tests |
|||
|
|||
The primary way to run E2E tests is through the `pnpm` script defined in the root `package.json`. |
|||
|
|||
1. **Build DevTools:** The E2E tests run against a built version of the devtools extension. You must build it first: |
|||
|
|||
```shell |
|||
pnpm -F ng-devtools-mcp build:dev |
|||
``` |
|||
|
|||
2. **Run Cypress:** Use the `cy:open` or `cy:run` script: |
|||
- To open the interactive Cypress Test Runner: |
|||
```shell |
|||
pnpm -F ng-devtools-mcp cy:open |
|||
``` |
|||
- To run the tests headlessly in the terminal (ideal for CI): |
|||
```shell |
|||
pnpm -F ng-devtools-mcp cy:run |
|||
``` |
|||
|
|||
## Test Structure |
|||
|
|||
- **Configuration:** The main Cypress configuration is located at `devtools/cypress.json`. |
|||
- **Specs:** Test files (specs) are located in `devtools/cypress/integration/`. |
|||
- **Custom Commands:** Reusable custom commands and actions are defined in `devtools/cypress/support/`. |
|||
|
|||
### Example E2E Test Snippet |
|||
|
|||
A typical test might look like this: |
|||
|
|||
```typescript |
|||
// in devtools/cypress/integration/profiler.spec.ts |
|||
|
|||
describe('Profiler', () => { |
|||
beforeEach(() => { |
|||
cy.visit('/?e2e-app'); |
|||
cy.wait(1000); |
|||
cy.get('ng-devtools-tabs').find('a').contains('Profiler').click(); |
|||
}); |
|||
|
|||
it('should record and display profiling data', () => { |
|||
// Find the record button and click it |
|||
cy.get('button[aria-label="start-recording-button"]').click(); |
|||
|
|||
// Interact with the test application to generate profiling data |
|||
cy.get('body').find('#cards button').first().click(); |
|||
cy.wait(500); |
|||
|
|||
// Stop recording |
|||
cy.get('button[aria-label="stop-recording-button"]').click(); |
|||
|
|||
// Assert that the flame graph is now visible |
|||
cy.get('ng-devtools-recording-timeline').find('canvas').should('be.visible'); |
|||
}); |
|||
}); |
|||
> [!IMPORTANT] |
|||
> Only use the setup guidelines in this file if there is no existing E2E testing framework configured in the workspace, or if the user has explicitly requested to change or set up E2E testing. |
|||
|
|||
## Setting Up and Running E2E Tests |
|||
|
|||
Add supported E2E frameworks to the project using `ng add`: |
|||
|
|||
- **Playwright:** |
|||
```shell |
|||
ng add playwright-ng-schematics |
|||
``` |
|||
- **Cypress:** |
|||
```shell |
|||
ng add @cypress/schematic |
|||
``` |
|||
- **Nightwatch:** |
|||
```shell |
|||
ng add @nightwatch/schematics |
|||
``` |
|||
- **WebdriverIO:** |
|||
```shell |
|||
ng add @wdio/schematics |
|||
``` |
|||
- **Puppeteer:** |
|||
```shell |
|||
ng add @puppeteer/ng-schematics |
|||
``` |
|||
|
|||
Run E2E tests: |
|||
|
|||
```shell |
|||
ng e2e [project] [options] |
|||
``` |
|||
|
|||
### Best Practices |
|||
## Custom & Enterprise Testing Tools |
|||
|
|||
- **Use `data-` attributes:** Whenever possible, use `data-cy` or similar attributes for selecting elements to make tests more resilient to CSS or structural changes. |
|||
- **Custom Commands:** Encapsulate common sequences of actions into custom commands in the `support` directory to keep tests clean and readable. |
|||
- **Wait for Application State:** Use `cy.wait()` for arbitrary waits sparingly. Prefer to wait for specific UI elements to appear or for network requests to complete to avoid flaky tests. |
|||
For custom enterprise runners (e.g., Katalon Studio, TestCafe, Selenium), define execution commands in `package.json` scripts. |
|||
|
|||
@ -0,0 +1,137 @@ |
|||
# Environment configuration |
|||
|
|||
## Configuration strategies |
|||
|
|||
Angular supports two main configuration strategies: |
|||
|
|||
- **Build-time configuration** using environment files |
|||
- **Runtime configuration** by loading values at application startup |
|||
|
|||
Choose the approach based on your deployment requirements. |
|||
|
|||
--- |
|||
|
|||
## Build-time configuration |
|||
|
|||
Environment files define configuration values that are replaced at build time. |
|||
|
|||
> **Security note:** Environment files are bundled into the client-side application. |
|||
> They are visible to anyone who can load the page. |
|||
> Never store sensitive information like API keys, secrets, or credentials in environment files. |
|||
> These values can be easily accessed by users. |
|||
|
|||
Generate environment files using the CLI: |
|||
|
|||
```bash |
|||
ng generate environments |
|||
``` |
|||
|
|||
This creates environment-specific files such as: |
|||
|
|||
```ts |
|||
// environment.ts |
|||
export const environment = { |
|||
apiUrl: 'https://api.example.com', |
|||
}; |
|||
``` |
|||
|
|||
```ts |
|||
// environment.development.ts |
|||
export const environment = { |
|||
apiUrl: 'http://localhost:3000', |
|||
}; |
|||
``` |
|||
|
|||
Import the environment where needed: |
|||
|
|||
```ts |
|||
import {environment} from '../environments/environment'; |
|||
|
|||
const apiUrl = environment.apiUrl; |
|||
``` |
|||
|
|||
The Angular CLI replaces the appropriate file based on the build configuration. |
|||
|
|||
If you need a development-mode check, use `isDevMode()` from `@angular/core` instead of relying on a manually maintained `production` flag. |
|||
|
|||
> Changes to environment files require rebuilding the application. |
|||
|
|||
--- |
|||
|
|||
## Runtime configuration (advanced) |
|||
|
|||
In some scenarios, applications need to load configuration at runtime instead of build time. |
|||
|
|||
This allows the same build artifact to be deployed across multiple environments without rebuilding. |
|||
|
|||
A common approach is to load a JSON configuration file from the `assets` folder during application |
|||
initialization. |
|||
|
|||
### Example |
|||
|
|||
```json |
|||
// src/assets/config.json |
|||
{ |
|||
"apiUrl": "https://api.example.com" |
|||
} |
|||
``` |
|||
|
|||
Load the configuration before the application starts: |
|||
|
|||
```ts |
|||
import {Service, inject} from '@angular/core'; |
|||
import {HttpClient} from '@angular/common/http'; |
|||
import {tap} from 'rxjs'; |
|||
|
|||
interface AppConfig { |
|||
apiUrl: string; |
|||
} |
|||
|
|||
@Service() |
|||
export class AppConfigService { |
|||
private config!: AppConfig; |
|||
|
|||
private readonly http = inject(HttpClient); |
|||
|
|||
loadConfig() { |
|||
return this.http.get<AppConfig>('/assets/config.json').pipe( |
|||
tap((data) => { |
|||
this.config = data; |
|||
}), |
|||
); |
|||
} |
|||
|
|||
get apiUrl(): string { |
|||
return this.config.apiUrl; |
|||
} |
|||
} |
|||
``` |
|||
|
|||
Register the loader during application bootstrap: |
|||
|
|||
```ts |
|||
import {provideAppInitializer, inject} from '@angular/core'; |
|||
|
|||
provideAppInitializer(() => { |
|||
const config = inject(AppConfigService); |
|||
return config.loadConfig(); |
|||
}); |
|||
``` |
|||
|
|||
This ensures configuration is available before the application renders. |
|||
|
|||
> Runtime configuration is an advanced pattern and is not required for most applications. |
|||
|
|||
--- |
|||
|
|||
## Choosing a strategy |
|||
|
|||
| Criteria | Build-time | Runtime | |
|||
| ---------------------- | ---------- | ------------ | |
|||
| Change without rebuild | No | Yes | |
|||
| Startup performance | Faster | Slight delay | |
|||
| Complexity | Low | Moderate | |
|||
| Deployment flexibility | Limited | High | |
|||
|
|||
Use build-time configuration for most applications, and runtime configuration when you need to |
|||
deploy the same build across multiple environments. |
|||
@ -0,0 +1,108 @@ |
|||
# HTTP communication with `HttpClient` and `httpResource` |
|||
|
|||
Use Angular's HTTP APIs for backend communication so requests participate in dependency injection, interceptors, transfer cache, and security features. |
|||
|
|||
## Setup |
|||
|
|||
In Angular v21 and later, `HttpClient` is available for injection by default. Add `provideHttpClient(...)` only when an app needs to configure HTTP features for a specific injector: |
|||
|
|||
```ts |
|||
import {provideHttpClient, withInterceptors} from '@angular/common/http'; |
|||
|
|||
export const appConfig = { |
|||
providers: [provideHttpClient(withInterceptors([authInterceptor]))], |
|||
}; |
|||
``` |
|||
|
|||
- `HttpClient` uses the fetch backend by default. |
|||
- Use `withXhr()` only when upload progress events are required. Do not use `withXhr()` for server-side rendering. |
|||
- Use `provideHttpClient(...)` for feature configuration such as interceptors, XSRF options, XHR, or parent-request delegation. |
|||
- Calling `provideHttpClient()` with no features is not required for basic HTTP requests, but it configures the default HTTP feature set for that injector, including Angular's XSRF interceptor. |
|||
- Prefer `provideHttpClient(...)` over `HttpClientModule` for feature configuration, especially with multiple injectors. |
|||
- Use `withRequestsMadeViaParent()` when a child injector should add interceptors while still delegating to the parent HTTP chain. |
|||
|
|||
## `HttpClient` |
|||
|
|||
Encapsulate backend calls in injectable services, not components: |
|||
|
|||
```ts |
|||
import {HttpClient} from '@angular/common/http'; |
|||
import {Service, inject} from '@angular/core'; |
|||
|
|||
@Service() |
|||
export class UserService { |
|||
private readonly http = inject(HttpClient); |
|||
|
|||
getUser(id: string) { |
|||
return this.http.get<User>(`/api/users/${id}`); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
Important rules: |
|||
|
|||
- `HttpClient` requests are cold `Observable`s. No request is sent until the `Observable` is subscribed to. Multiple subscriptions send multiple backend requests. |
|||
- Subscribe to mutation requests (`post`, `put`, `patch`, `delete`) so they execute. |
|||
- The generic type parameter is a type assertion only. Validate unknown backend data at runtime when the shape is not trusted. |
|||
- Use literal values for `responseType` and `observe`; if options are extracted, write values like `responseType: 'text' as const`. |
|||
- `HttpHeaders` and `HttpParams` are immutable; use the returned instance from `.set()` or `.append()`. |
|||
- Fetch options such as `timeout`, `cache`, `priority`, `mode`, `redirect`, `credentials`, `keepalive`, `referrer`, `referrerPolicy`, and `integrity` are supported where the backend supports them. `withCredentials: true` overrides `credentials`. |
|||
- Handle failures through `HttpErrorResponse`. Network and timeout failures use status `0`; backend failures use the server status code. |
|||
- Prefer the `async` pipe or `toSignal` for component reads so subscriptions are cleaned up. |
|||
|
|||
## Interceptors |
|||
|
|||
Prefer functional interceptors configured with `withInterceptors`. |
|||
|
|||
```ts |
|||
import { |
|||
HttpHandlerFn, |
|||
HttpRequest, |
|||
provideHttpClient, |
|||
withInterceptors, |
|||
} from '@angular/common/http'; |
|||
|
|||
export function authInterceptor(req: HttpRequest<unknown>, next: HttpHandlerFn) { |
|||
return next(req.clone({setHeaders: {Authorization: 'Bearer token'}})); |
|||
} |
|||
|
|||
export const appConfig = { |
|||
providers: [provideHttpClient(withInterceptors([authInterceptor]))], |
|||
}; |
|||
``` |
|||
|
|||
- Interceptors run in the order listed. |
|||
- Request and response objects are mostly immutable; clone before changing them. |
|||
- Request and response bodies are not deeply immutable. Avoid in-place body mutation because retries can run the same interceptor again. |
|||
- Use `inject()` inside functional interceptors for services. |
|||
- Use `HttpContextToken` for per-request metadata that interceptors need but the backend should not receive. |
|||
- Use DI-based interceptors only for existing code, and enable them with `withInterceptorsFromDi()`. |
|||
|
|||
## Security |
|||
|
|||
- `HttpClient` strips the XSSI prefix from JSON responses when present. |
|||
- `provideHttpClient()` configures XSRF protection by default for mutating relative and same-origin requests. It reads the `XSRF-TOKEN` cookie and sends the `X-XSRF-TOKEN` header. |
|||
- The backend must set the XSRF cookie and verify the header. Customize names with `withXsrfConfiguration(...)`; disable only deliberately with `withNoXsrfProtection()`. |
|||
|
|||
## `httpResource` |
|||
|
|||
Use `httpResource` to create an asynchronous derivation that fetches data over HTTP and exposes the result as reactive signals. |
|||
|
|||
```ts |
|||
import {httpResource} from '@angular/common/http'; |
|||
import {input} from '@angular/core'; |
|||
|
|||
export class UserProfile { |
|||
readonly userId = input.required<string>(); |
|||
readonly user = httpResource(() => `/api/users/${this.userId()}`); |
|||
} |
|||
``` |
|||
|
|||
- `httpResource` is eager. It sends a request when its reactive request computation runs, not when an `Observable` is subscribed. |
|||
- When a dependency changes, it cancels the pending request and sends the next one. |
|||
- Return `undefined` from the request function to skip a backend request. |
|||
- Prefer `httpResource` for reads. Use `HttpClient` directly for mutations such as `POST`, `PUT`, `PATCH`, and `DELETE`. |
|||
- Guard `value()` reads with `hasValue()`; reading `value()` while the resource is in an error state throws. |
|||
- Use `httpResource.text`, `httpResource.blob`, or `httpResource.arrayBuffer` for non-JSON responses. |
|||
- Use the `parse` option to validate or transform responses with a runtime schema. |
|||
- Read `headers()`, `statusCode()`, and `progress()` when response metadata or download progress is needed. Set `reportProgress: true` for progress events. |
|||
@ -0,0 +1,76 @@ |
|||
# Angular Naming Conventions (Angular v20+ Style Guide) |
|||
|
|||
This skill enforces Angular naming conventions for components, services, directives, pipes, and models. While it promotes the modern **"Intent over Role"** philosophy introduced in Angular v20, **it must respect existing project configurations first**. |
|||
|
|||
--- |
|||
|
|||
## Core Principles |
|||
|
|||
1. **Prioritize Existing Conventions**: Before generating or refactoring files, check the existing project files, `angular.json` configuration, and ESLint rules. **Do not force suffixless naming on projects that rely on standard suffixes.** |
|||
2. **Remove Role Suffixes (Modern Projects Only)**: In projects configured for "Intent over Role" or newly bootstrapped v20+ projects, filenames no longer include functional extensions like `.component.ts`, `.service.ts`, or `.directive.ts`. Corresponding TypeScript classes drop suffixes like `Component`, `Service`, or `Directive`. |
|||
3. **Intent/Purpose-Based Naming**: When suffixless naming is active, name files and classes based on their specific domain, responsibility, or business purpose (e.g., `-data`, `-store`, `-api`, or `-formatter`). |
|||
4. **Folder Location as Context**: Lean on folder hierarchy (`core/`, `features/`, `shared/`) and IDE capabilities to identify the technical role of files, rather than encoding that context within the file name. |
|||
5. **Interface/Model Exception**: Interfaces and data models still retain the `.model.ts` suffix to clearly declare type contracts. |
|||
|
|||
--- |
|||
|
|||
## Recommended Project Structure & Naming Rules |
|||
|
|||
### 1. File/Identifier Matching & Consistency |
|||
|
|||
- **Hyphens in Filenames**: Continue using kebab-case (hyphens) to separate words in filenames (e.g., `product-list.ts`). |
|||
- **Identifier Matching**: Filenames must align directly with the primary TypeScript class/identifier (e.g., `product-list.ts` contains `class ProductList`). |
|||
- **Unified Filenames**: If using split template or style files, keep names identical to the main TypeScript file: |
|||
- `product-list.ts` |
|||
- `product-list.html` |
|||
- `product-list.css` |
|||
- **Test Files**: Continue to use the same base name with the `.spec.ts` suffix (e.g., `product-list.spec.ts` for `product-list.ts`). |
|||
|
|||
### 2. Core Directory (Application Foundation) |
|||
|
|||
Houses singleton services, global state, and system-wide models. |
|||
|
|||
- **Services (Logic/State)**: |
|||
- _Old_: `auth.service.ts` (Class: `AuthService`) |
|||
- _New_: `auth.ts` (Class: `AuthService`) |
|||
- _Alternative (Intent-specific)_: Use descriptive domain-purpose suffixes like `[domain]-data.ts`, `[domain]-store.ts`, or `[domain]-data-client.ts` (e.g., `auth-data.ts` / `AuthData`, `user-data-client.ts` / `UserDataClient`). |
|||
- **Models**: Retain the `.model.ts` suffix for data shapes. |
|||
- _Example_: `user.model.ts` (Interface: `User`) |
|||
|
|||
### 3. Features Directory (Domain Business Logic) |
|||
|
|||
Organize files into feature-specific folders containing components, local services, and routes related to that domain. |
|||
|
|||
- **Main Feature Component**: Name the main feature component after the route or feature itself. |
|||
- _Example_: `features/profile/profile.ts` (Class: `Profile`) |
|||
- **Feature Sub-Components**: Name sub-components based on their display or functional role. |
|||
- _Example_: `features/profile/components/profile-header.ts` (Class: `ProfileHeader`) |
|||
- _Example_: `features/projects/components/project-card.ts` (Class: `ProjectCard`) |
|||
- **Feature Services**: Name feature services based on feature-specific data or state needs. |
|||
- _Example_: `features/projects/projects-data.ts` (Class: `ProjectsData`) |
|||
|
|||
### 4. Shared Directory (Reusable UI Toolkit) |
|||
|
|||
Store pure, presentational elements and helpers with zero business logic in a shared folder. |
|||
|
|||
- **Shared Components**: Name shared components based on their reusable UI role. |
|||
- _Example_: `shared/components/button/button.ts` (Class: `Button`) |
|||
- _Example_: `shared/components/spinner/spinner.ts` (Class: `Spinner`) |
|||
- **Shared Pipes**: Name shared pipes according to their formatting purpose. |
|||
- _Example_: `shared/pipes/format-date.ts` (Class: `FormatDate`) |
|||
- **Shared Directives**: Name directives according to the behavior they attach to elements. |
|||
- _Old_: `highlight.directive.ts` (Class: `HighlightDirective`) |
|||
- _New_: `highlight.ts` (Class: `Highlight`) |
|||
|
|||
--- |
|||
|
|||
## Best Practices & Coexistence Rules |
|||
|
|||
- **How to Determine the Style in Use**: |
|||
1. Inspect adjacent files in the target directory (do they end in `.component.ts` or `.ts`?). |
|||
2. Check `angular.json` for custom schematics options that might configure suffix behaviors. |
|||
3. If unsure, use the traditional role suffix style (`.component.ts`, `.service.ts`) as it is the safest default in the Angular ecosystem. |
|||
- **Avoid Namespace Collisions**: Without role suffixes, files like `user.ts` (component) and `user.model.ts` (model) can collide if they both declare a class/interface named `User`. |
|||
- To prevent this use more specific, intent-based names for components (e.g. `class UserProfile` in `user-profile.ts` or `class UserDetail` in `user-detail.ts`) while keeping the simple domain name for the interface (`interface User` in `user.model.ts`). |
|||
- **Consistency Check**: Do not mix old suffix styles and new suffixless styles in the same feature folder or module. Keep existing legacy code as-is unless migrating the entire module to the modern structure. |
|||
- **Lean on the IDE**: Rely on modern IDE code navigation (e.g., "Go to Definition" or fuzzy searches for class names like `AuthData` or `ProfileHeader`) and file type icons rather than visual scan of suffix strings. |
|||
@ -0,0 +1,145 @@ |
|||
# Pipes |
|||
|
|||
Pipes transform data declaratively inside Angular templates using the `|` operator. |
|||
|
|||
## Using pipes in templates |
|||
|
|||
Import the pipe class and add it to the component's `imports` array. |
|||
|
|||
```ts |
|||
import {Component} from '@angular/core'; |
|||
import {DatePipe, CurrencyPipe} from '@angular/common'; |
|||
|
|||
@Component({ |
|||
selector: 'app-invoice', |
|||
imports: [DatePipe, CurrencyPipe], |
|||
template: ` |
|||
<p>Date: {{ issuedOn | date: 'mediumDate' }}</p> |
|||
<p>Total: {{ amount | currency }}</p> |
|||
`, |
|||
}) |
|||
export class Invoice { |
|||
issuedOn = new Date(); |
|||
amount = 49.99; |
|||
} |
|||
``` |
|||
|
|||
## Using pipe logic outside templates |
|||
|
|||
**Do NOT inject pipe classes into services or other classes.** Pipes are template operators, not injectable services. Injecting them causes DI errors in standalone contexts and creates unnecessary coupling. |
|||
|
|||
### Custom pipes — extract the transformation function |
|||
|
|||
Extract the logic into a plain function. The pipe delegates to it; services import the function directly. |
|||
|
|||
```ts |
|||
// kebab-case.ts |
|||
export function toKebabCase(value: string): string { |
|||
return value.toLowerCase().replace(/ /g, '-'); |
|||
} |
|||
``` |
|||
|
|||
```ts |
|||
// kebab-case.pipe.ts |
|||
import {Pipe, PipeTransform} from '@angular/core'; |
|||
import {toKebabCase} from './kebab-case'; |
|||
|
|||
@Pipe({name: 'kebabCase'}) |
|||
export class KebabCasePipe implements PipeTransform { |
|||
transform(value: string): string { |
|||
return toKebabCase(value); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
```ts |
|||
// formatter.service.ts — import the function, NOT the pipe |
|||
import {Service} from '@angular/core'; |
|||
import {toKebabCase} from './kebab-case'; |
|||
|
|||
@Service() |
|||
export class FormatterService { |
|||
toSlug(title: string): string { |
|||
return toKebabCase(title); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
### Built-in locale-aware pipes — use standalone formatting functions |
|||
|
|||
`@angular/common` exports a standalone function for each locale-aware built-in pipe: |
|||
|
|||
| Pipe | Standalone function | |
|||
| -------------- | ------------------- | |
|||
| `DatePipe` | `formatDate` | |
|||
| `CurrencyPipe` | `formatCurrency` | |
|||
| `DecimalPipe` | `formatNumber` | |
|||
| `PercentPipe` | `formatPercent` | |
|||
|
|||
Inject `LOCALE_ID` to get the current locale and pass it to the function. |
|||
|
|||
```ts |
|||
// CORRECT — use formatNumber instead of injecting DecimalPipe |
|||
import {Service, LOCALE_ID, inject} from '@angular/core'; |
|||
import {formatNumber} from '@angular/common'; |
|||
|
|||
@Service() |
|||
export class PriceService { |
|||
private locale = inject(LOCALE_ID); |
|||
|
|||
formatQuantity(value: number): string { |
|||
return formatNumber(value, this.locale, '1.0-0'); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
```ts |
|||
// WRONG — do not inject pipe classes |
|||
import {Service, inject} from '@angular/core'; |
|||
import {DecimalPipe} from '@angular/common'; |
|||
|
|||
@Service() |
|||
export class PriceService { |
|||
// ❌ DecimalPipe is not designed to be injected |
|||
private pipe = inject(DecimalPipe); |
|||
} |
|||
``` |
|||
|
|||
## Creating custom pipes |
|||
|
|||
Use the Angular CLI to generate a pipe: |
|||
|
|||
```bash |
|||
ng generate pipe path/to/my-pipe |
|||
``` |
|||
|
|||
A pipe needs a `@Pipe` decorator with a `name` and a `transform` method implementing `PipeTransform`. |
|||
|
|||
```ts |
|||
import {Pipe, PipeTransform} from '@angular/core'; |
|||
|
|||
@Pipe({name: 'truncate'}) |
|||
export class TruncatePipe implements PipeTransform { |
|||
transform(value: string, limit = 50): string { |
|||
return value.length > limit ? value.slice(0, limit) + '…' : value; |
|||
} |
|||
} |
|||
``` |
|||
|
|||
- **`name`**: camelCase. Do not use hyphens. |
|||
- **Class name**: PascalCase version of `name` with `Pipe` appended (e.g., `TruncatePipe`). |
|||
|
|||
## Impure pipes |
|||
|
|||
Mark a pipe `pure: false` only when you need to detect mutations inside arrays or objects. Impure pipes run on every change-detection cycle and can hurt performance. |
|||
|
|||
```ts |
|||
@Pipe({name: 'filterItems', pure: false}) |
|||
export class FilterItemsPipe implements PipeTransform { |
|||
transform(items: string[], query: string): string[] { |
|||
return items.filter((i) => i.includes(query)); |
|||
} |
|||
} |
|||
``` |
|||
|
|||
IMPORTANT: Avoid impure pipes unless absolutely necessary. |
|||
@ -0,0 +1,72 @@ |
|||
--- |
|||
name: karpathy-guidelines |
|||
description: Behavioral guidelines to reduce common LLM coding mistakes. Use when writing, reviewing, or refactoring code to avoid overcomplication, make surgical changes, surface assumptions, and define verifiable success criteria. |
|||
license: MIT |
|||
--- |
|||
|
|||
# Karpathy Guidelines |
|||
|
|||
Behavioral guidelines to reduce common LLM coding mistakes, derived from [Andrej Karpathy's observations](https://x.com/karpathy/status/2015883857489522876) on LLM coding pitfalls. |
|||
|
|||
**Tradeoff:** These guidelines bias toward caution over speed. For trivial tasks, use judgment. |
|||
|
|||
## 1. Think Before Coding |
|||
|
|||
**Don't assume. Don't hide confusion. Surface tradeoffs.** |
|||
|
|||
Before implementing: |
|||
|
|||
- State your assumptions explicitly. If uncertain, ask. |
|||
- If multiple interpretations exist, present them - don't pick silently. |
|||
- If a simpler approach exists, say so. Push back when warranted. |
|||
- If something is unclear, stop. Name what's confusing. Ask. |
|||
|
|||
## 2. Simplicity First |
|||
|
|||
**Minimum code that solves the problem. Nothing speculative.** |
|||
|
|||
- No features beyond what was asked. |
|||
- No abstractions for single-use code. |
|||
- No "flexibility" or "configurability" that wasn't requested. |
|||
- No error handling for impossible scenarios. |
|||
- If you write 200 lines and it could be 50, rewrite it. |
|||
|
|||
Ask yourself: "Would a senior engineer say this is overcomplicated?" If yes, simplify. |
|||
|
|||
## 3. Surgical Changes |
|||
|
|||
**Touch only what you must. Clean up only your own mess.** |
|||
|
|||
When editing existing code: |
|||
|
|||
- Don't "improve" adjacent code, comments, or formatting. |
|||
- Don't refactor things that aren't broken. |
|||
- Match existing style, even if you'd do it differently. |
|||
- If you notice unrelated dead code, mention it - don't delete it. |
|||
|
|||
When your changes create orphans: |
|||
|
|||
- Remove imports/variables/functions that YOUR changes made unused. |
|||
- Don't remove pre-existing dead code unless asked. |
|||
|
|||
The test: Every changed line should trace directly to the user's request. |
|||
|
|||
## 4. Goal-Driven Execution |
|||
|
|||
**Define success criteria. Loop until verified.** |
|||
|
|||
Transform tasks into verifiable goals: |
|||
|
|||
- "Add validation" → "Write tests for invalid inputs, then make them pass" |
|||
- "Fix the bug" → "Write a test that reproduces it, then make it pass" |
|||
- "Refactor X" → "Ensure tests pass before and after" |
|||
|
|||
For multi-step tasks, state a brief plan: |
|||
|
|||
``` |
|||
1. [Step] → verify: [check] |
|||
2. [Step] → verify: [check] |
|||
3. [Step] → verify: [check] |
|||
``` |
|||
|
|||
Strong success criteria let you loop independently. Weak criteria ("make it work") require constant clarification. |
|||
@ -0,0 +1 @@ |
|||
../../.agents/skills/karpathy-guidelines |
|||
@ -1,6 +1,6 @@ |
|||
# Run linting and stop the commit process if any errors are found |
|||
# --quiet suppresses warnings (temporary until all warnings are fixed) |
|||
npm run affected:lint --base=main --head=HEAD --parallel=2 --quiet || exit 1 |
|||
# Run linting on staged and unstaged changes and stop if any errors are found |
|||
# --quiet skips warning-level rules (temporary until all warnings are fixed) |
|||
npm run affected:lint -- --uncommitted --parallel=2 --quiet || exit 1 |
|||
|
|||
# Check formatting on modified and uncommitted files, stop the commit if issues are found |
|||
npm run format:check --uncommitted || exit 1 |
|||
# Check formatting on staged and unstaged changes and stop if any issues are found |
|||
npm run format:check -- --uncommitted || exit 1 |
|||
|
|||
File diff suppressed because it is too large
@ -0,0 +1,35 @@ |
|||
const NodeEnvironment = require('jest-environment-node').TestEnvironment; |
|||
|
|||
// Jest gives each test file a copy of `process`, so a test cannot change the
|
|||
// time zone at run time. This environment sets `TZ` on the real process of the
|
|||
// worker, which resets the internal date cache of Node.
|
|||
class TimeZoneEnvironment extends NodeEnvironment { |
|||
constructor(config, context) { |
|||
super(config, context); |
|||
|
|||
this.previousTimeZone = process.env.TZ; |
|||
this.timeZone = config.projectConfig.testEnvironmentOptions?.timeZone; |
|||
} |
|||
|
|||
async setup() { |
|||
if (this.timeZone) { |
|||
process.env.TZ = this.timeZone; |
|||
} |
|||
|
|||
await super.setup(); |
|||
} |
|||
|
|||
async teardown() { |
|||
try { |
|||
await super.teardown(); |
|||
} finally { |
|||
if (this.previousTimeZone === undefined) { |
|||
delete process.env.TZ; |
|||
} else { |
|||
process.env.TZ = this.previousTimeZone; |
|||
} |
|||
} |
|||
} |
|||
} |
|||
|
|||
module.exports = TimeZoneEnvironment; |
|||
File diff suppressed because it is too large
@ -1,300 +0,0 @@ |
|||
import { AccountBalanceService } from '@ghostfolio/api/app/account-balance/account-balance.service'; |
|||
import { PortfolioService } from '@ghostfolio/api/app/portfolio/portfolio.service'; |
|||
import { UserService } from '@ghostfolio/api/app/user/user.service'; |
|||
import { HasPermission } from '@ghostfolio/api/decorators/has-permission.decorator'; |
|||
import { HasPermissionGuard } from '@ghostfolio/api/guards/has-permission.guard'; |
|||
import { RedactValuesInResponseInterceptor } from '@ghostfolio/api/interceptors/redact-values-in-response/redact-values-in-response.interceptor'; |
|||
import { TransformDataSourceInRequestInterceptor } from '@ghostfolio/api/interceptors/transform-data-source-in-request/transform-data-source-in-request.interceptor'; |
|||
import { ApiService } from '@ghostfolio/api/services/api/api.service'; |
|||
import { ImpersonationService } from '@ghostfolio/api/services/impersonation/impersonation.service'; |
|||
import { HEADER_KEY_IMPERSONATION } from '@ghostfolio/common/config'; |
|||
import { |
|||
CreateAccountDto, |
|||
TransferBalanceDto, |
|||
UpdateAccountDto |
|||
} from '@ghostfolio/common/dtos'; |
|||
import { |
|||
AccountBalancesResponse, |
|||
AccountResponse, |
|||
AccountsResponse |
|||
} from '@ghostfolio/common/interfaces'; |
|||
import { permissions } from '@ghostfolio/common/permissions'; |
|||
import type { RequestWithUser } from '@ghostfolio/common/types'; |
|||
|
|||
import { |
|||
Body, |
|||
Controller, |
|||
Delete, |
|||
Get, |
|||
Headers, |
|||
HttpException, |
|||
Inject, |
|||
Param, |
|||
Post, |
|||
Put, |
|||
Query, |
|||
UseGuards, |
|||
UseInterceptors |
|||
} from '@nestjs/common'; |
|||
import { REQUEST } from '@nestjs/core'; |
|||
import { AuthGuard } from '@nestjs/passport'; |
|||
import { Account as AccountModel } from '@prisma/client'; |
|||
import { StatusCodes, getReasonPhrase } from 'http-status-codes'; |
|||
|
|||
import { AccountService } from './account.service'; |
|||
|
|||
@Controller('account') |
|||
export class AccountController { |
|||
public constructor( |
|||
private readonly accountBalanceService: AccountBalanceService, |
|||
private readonly accountService: AccountService, |
|||
private readonly apiService: ApiService, |
|||
private readonly impersonationService: ImpersonationService, |
|||
private readonly portfolioService: PortfolioService, |
|||
@Inject(REQUEST) private readonly request: RequestWithUser, |
|||
private readonly userService: UserService |
|||
) {} |
|||
|
|||
@Delete(':id') |
|||
@HasPermission(permissions.deleteAccount) |
|||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|||
public async deleteAccount(@Param('id') id: string): Promise<AccountModel> { |
|||
const account = await this.accountService.accountWithActivities( |
|||
{ |
|||
id_userId: { |
|||
id, |
|||
userId: this.request.user.id |
|||
} |
|||
}, |
|||
{ activities: true } |
|||
); |
|||
|
|||
if (!account || account?.activities.length > 0) { |
|||
throw new HttpException( |
|||
getReasonPhrase(StatusCodes.FORBIDDEN), |
|||
StatusCodes.FORBIDDEN |
|||
); |
|||
} |
|||
|
|||
return this.accountService.deleteAccount({ |
|||
id_userId: { |
|||
id, |
|||
userId: this.request.user.id |
|||
} |
|||
}); |
|||
} |
|||
|
|||
@Get() |
|||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|||
@UseInterceptors(RedactValuesInResponseInterceptor) |
|||
@UseInterceptors(TransformDataSourceInRequestInterceptor) |
|||
public async getAllAccounts( |
|||
@Headers(HEADER_KEY_IMPERSONATION.toLowerCase()) impersonationId: string, |
|||
@Query('dataSource') filterByDataSource?: string, |
|||
@Query('query') filterBySearchQuery?: string, |
|||
@Query('symbol') filterBySymbol?: string |
|||
): Promise<AccountsResponse> { |
|||
const impersonationUserId = |
|||
await this.impersonationService.validateImpersonationId(impersonationId); |
|||
|
|||
const filters = this.apiService.buildFiltersFromQueryParams({ |
|||
filterByDataSource, |
|||
filterBySearchQuery, |
|||
filterBySymbol |
|||
}); |
|||
|
|||
return this.portfolioService.getAccountsWithAggregations({ |
|||
filters, |
|||
userId: impersonationUserId || this.request.user.id, |
|||
withExcludedAccounts: true |
|||
}); |
|||
} |
|||
|
|||
@Get(':id') |
|||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|||
@UseInterceptors(RedactValuesInResponseInterceptor) |
|||
public async getAccountById( |
|||
@Headers(HEADER_KEY_IMPERSONATION.toLowerCase()) impersonationId: string, |
|||
@Param('id') id: string |
|||
): Promise<AccountResponse> { |
|||
const impersonationUserId = |
|||
await this.impersonationService.validateImpersonationId(impersonationId); |
|||
|
|||
const accountsWithAggregations = |
|||
await this.portfolioService.getAccountsWithAggregations({ |
|||
filters: [{ id, type: 'ACCOUNT' }], |
|||
userId: impersonationUserId || this.request.user.id, |
|||
withExcludedAccounts: true |
|||
}); |
|||
|
|||
return accountsWithAggregations.accounts[0]; |
|||
} |
|||
|
|||
@Get(':id/balances') |
|||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|||
@UseInterceptors(RedactValuesInResponseInterceptor) |
|||
public async getAccountBalancesById( |
|||
@Headers(HEADER_KEY_IMPERSONATION.toLowerCase()) impersonationId: string, |
|||
@Param('id') id: string |
|||
): Promise<AccountBalancesResponse> { |
|||
const impersonationUserId = |
|||
await this.impersonationService.validateImpersonationId(impersonationId); |
|||
const userId = impersonationUserId || this.request.user.id; |
|||
|
|||
const { settings } = await this.userService.user({ id: userId }); |
|||
|
|||
return this.accountBalanceService.getAccountBalances({ |
|||
userId, |
|||
filters: [{ id, type: 'ACCOUNT' }], |
|||
userCurrency: settings.settings.baseCurrency |
|||
}); |
|||
} |
|||
|
|||
@HasPermission(permissions.createAccount) |
|||
@Post() |
|||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|||
public async createAccount( |
|||
@Body() data: CreateAccountDto |
|||
): Promise<AccountModel> { |
|||
if (data.platformId) { |
|||
const platformId = data.platformId; |
|||
delete data.platformId; |
|||
|
|||
return this.accountService.createAccount( |
|||
{ |
|||
...data, |
|||
platform: { connect: { id: platformId } }, |
|||
user: { connect: { id: this.request.user.id } } |
|||
}, |
|||
this.request.user.id |
|||
); |
|||
} else { |
|||
delete data.platformId; |
|||
|
|||
return this.accountService.createAccount( |
|||
{ |
|||
...data, |
|||
user: { connect: { id: this.request.user.id } } |
|||
}, |
|||
this.request.user.id |
|||
); |
|||
} |
|||
} |
|||
|
|||
@HasPermission(permissions.updateAccount) |
|||
@Post('transfer-balance') |
|||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|||
public async transferAccountBalance( |
|||
@Body() { accountIdFrom, accountIdTo, balance }: TransferBalanceDto |
|||
) { |
|||
const accountsOfUser = await this.accountService.getAccounts( |
|||
this.request.user.id |
|||
); |
|||
|
|||
const accountFrom = accountsOfUser.find(({ id }) => { |
|||
return id === accountIdFrom; |
|||
}); |
|||
|
|||
const accountTo = accountsOfUser.find(({ id }) => { |
|||
return id === accountIdTo; |
|||
}); |
|||
|
|||
if (!accountFrom || !accountTo) { |
|||
throw new HttpException( |
|||
getReasonPhrase(StatusCodes.NOT_FOUND), |
|||
StatusCodes.NOT_FOUND |
|||
); |
|||
} |
|||
|
|||
if (accountFrom.id === accountTo.id) { |
|||
throw new HttpException( |
|||
getReasonPhrase(StatusCodes.BAD_REQUEST), |
|||
StatusCodes.BAD_REQUEST |
|||
); |
|||
} |
|||
|
|||
if (accountFrom.balance < balance) { |
|||
throw new HttpException( |
|||
getReasonPhrase(StatusCodes.BAD_REQUEST), |
|||
StatusCodes.BAD_REQUEST |
|||
); |
|||
} |
|||
|
|||
await this.accountService.updateAccountBalance({ |
|||
accountId: accountFrom.id, |
|||
amount: -balance, |
|||
currency: accountFrom.currency, |
|||
userId: this.request.user.id |
|||
}); |
|||
|
|||
await this.accountService.updateAccountBalance({ |
|||
accountId: accountTo.id, |
|||
amount: balance, |
|||
currency: accountFrom.currency, |
|||
userId: this.request.user.id |
|||
}); |
|||
} |
|||
|
|||
@HasPermission(permissions.updateAccount) |
|||
@Put(':id') |
|||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|||
public async update(@Param('id') id: string, @Body() data: UpdateAccountDto) { |
|||
const originalAccount = await this.accountService.account({ |
|||
id_userId: { |
|||
id, |
|||
userId: this.request.user.id |
|||
} |
|||
}); |
|||
|
|||
if (!originalAccount) { |
|||
throw new HttpException( |
|||
getReasonPhrase(StatusCodes.FORBIDDEN), |
|||
StatusCodes.FORBIDDEN |
|||
); |
|||
} |
|||
|
|||
if (data.platformId) { |
|||
const platformId = data.platformId; |
|||
delete data.platformId; |
|||
|
|||
return this.accountService.updateAccount( |
|||
{ |
|||
data: { |
|||
...data, |
|||
platform: { connect: { id: platformId } }, |
|||
user: { connect: { id: this.request.user.id } } |
|||
}, |
|||
where: { |
|||
id_userId: { |
|||
id, |
|||
userId: this.request.user.id |
|||
} |
|||
} |
|||
}, |
|||
this.request.user.id |
|||
); |
|||
} else { |
|||
// platformId is null, remove it
|
|||
delete data.platformId; |
|||
|
|||
return this.accountService.updateAccount( |
|||
{ |
|||
data: { |
|||
...data, |
|||
platform: originalAccount.platformId |
|||
? { disconnect: true } |
|||
: undefined, |
|||
user: { connect: { id: this.request.user.id } } |
|||
}, |
|||
where: { |
|||
id_userId: { |
|||
id, |
|||
userId: this.request.user.id |
|||
} |
|||
} |
|||
}, |
|||
this.request.user.id |
|||
); |
|||
} |
|||
} |
|||
} |
|||
@ -1,6 +0,0 @@ |
|||
import { Account } from '@prisma/client'; |
|||
|
|||
export interface CashDetails { |
|||
accounts: Account[]; |
|||
balanceInBaseCurrency: number; |
|||
} |
|||
@ -0,0 +1,21 @@ |
|||
import { DATE_RANGE_PATTERN } from '@ghostfolio/api/dtos/date-range-filter.dto'; |
|||
import { FilterDto } from '@ghostfolio/api/dtos/filter.dto'; |
|||
import { DateRange } from '@ghostfolio/common/types'; |
|||
|
|||
import { Type as ActivityType } from '@prisma/client'; |
|||
import { Transform, TransformFnParams } from 'class-transformer'; |
|||
import { IsEnum, IsOptional, Matches } from 'class-validator'; |
|||
import { isString } from 'lodash-es'; |
|||
|
|||
export class ActivitiesFilterDto extends FilterDto { |
|||
@IsEnum(ActivityType, { each: true }) |
|||
@IsOptional() |
|||
@Transform(({ value }: TransformFnParams) => { |
|||
return isString(value) ? value.split(',') : value; |
|||
}) |
|||
activityTypes?: ActivityType[]; |
|||
|
|||
@IsOptional() |
|||
@Matches(DATE_RANGE_PATTERN) |
|||
range?: DateRange; |
|||
} |
|||
@ -1,44 +1,29 @@ |
|||
import { AccountBalanceService } from '@ghostfolio/api/app/account-balance/account-balance.service'; |
|||
import { AccountService } from '@ghostfolio/api/app/account/account.service'; |
|||
import { CacheModule } from '@ghostfolio/api/app/cache/cache.module'; |
|||
import { RedisCacheModule } from '@ghostfolio/api/app/redis-cache/redis-cache.module'; |
|||
import { RedactValuesInResponseModule } from '@ghostfolio/api/interceptors/redact-values-in-response/redact-values-in-response.module'; |
|||
import { TransformDataSourceInRequestModule } from '@ghostfolio/api/interceptors/transform-data-source-in-request/transform-data-source-in-request.module'; |
|||
import { TransformDataSourceInResponseModule } from '@ghostfolio/api/interceptors/transform-data-source-in-response/transform-data-source-in-response.module'; |
|||
import { ActivitiesModule as ActivitiesServiceModule } from '@ghostfolio/api/services/activities/activities.module'; |
|||
import { ApiModule } from '@ghostfolio/api/services/api/api.module'; |
|||
import { BenchmarkModule } from '@ghostfolio/api/services/benchmark/benchmark.module'; |
|||
import { DataProviderModule } from '@ghostfolio/api/services/data-provider/data-provider.module'; |
|||
import { ExchangeRateDataModule } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.module'; |
|||
import { ImpersonationModule } from '@ghostfolio/api/services/impersonation/impersonation.module'; |
|||
import { MarketDataModule } from '@ghostfolio/api/services/market-data/market-data.module'; |
|||
import { PrismaModule } from '@ghostfolio/api/services/prisma/prisma.module'; |
|||
import { DataGatheringQueueModule } from '@ghostfolio/api/services/queues/data-gathering/data-gathering.module'; |
|||
import { SymbolProfileModule } from '@ghostfolio/api/services/symbol-profile/symbol-profile.module'; |
|||
|
|||
import { Module } from '@nestjs/common'; |
|||
|
|||
import { ActivitiesController } from './activities.controller'; |
|||
import { ActivitiesService } from './activities.service'; |
|||
|
|||
@Module({ |
|||
controllers: [ActivitiesController], |
|||
exports: [ActivitiesService], |
|||
imports: [ |
|||
ActivitiesServiceModule, |
|||
ApiModule, |
|||
BenchmarkModule, |
|||
CacheModule, |
|||
DataGatheringQueueModule, |
|||
DataProviderModule, |
|||
ExchangeRateDataModule, |
|||
ImpersonationModule, |
|||
MarketDataModule, |
|||
PrismaModule, |
|||
RedactValuesInResponseModule, |
|||
RedisCacheModule, |
|||
SymbolProfileModule, |
|||
TransformDataSourceInRequestModule, |
|||
TransformDataSourceInResponseModule |
|||
], |
|||
providers: [AccountBalanceService, AccountService, ActivitiesService] |
|||
] |
|||
}) |
|||
export class ActivitiesModule {} |
|||
|
|||
@ -0,0 +1,27 @@ |
|||
import { Prisma } from '@prisma/client'; |
|||
import { Type } from 'class-transformer'; |
|||
import { IsIn, IsInt, IsOptional, Min } from 'class-validator'; |
|||
|
|||
import { ActivitiesFilterDto } from './activities-filter.dto'; |
|||
|
|||
export class GetActivitiesDto extends ActivitiesFilterDto { |
|||
@IsInt() |
|||
@IsOptional() |
|||
@Min(0) |
|||
@Type(() => Number) |
|||
skip?: number; |
|||
|
|||
@IsIn(Object.values(Prisma.OrderScalarFieldEnum)) |
|||
@IsOptional() |
|||
sortColumn?: keyof typeof Prisma.OrderScalarFieldEnum; |
|||
|
|||
@IsIn(['asc', 'desc'] as Prisma.SortOrder[]) |
|||
@IsOptional() |
|||
sortDirection?: Prisma.SortOrder; |
|||
|
|||
@IsInt() |
|||
@IsOptional() |
|||
@Min(0) |
|||
@Type(() => Number) |
|||
take?: number; |
|||
} |
|||
File diff suppressed because it is too large
@ -0,0 +1,29 @@ |
|||
import * as config from '@ghostfolio/common/config'; |
|||
import type { PropertyKey } from '@ghostfolio/common/types'; |
|||
|
|||
import { BadRequestException, Injectable, PipeTransform } from '@nestjs/common'; |
|||
|
|||
@Injectable() |
|||
export class PropertyKeyPipe implements PipeTransform<string, PropertyKey> { |
|||
private readonly allowedKeys: Set<string>; |
|||
|
|||
public constructor() { |
|||
this.allowedKeys = new Set<string>( |
|||
Object.entries(config) |
|||
.filter(([key]) => { |
|||
return key.startsWith('PROPERTY_'); |
|||
}) |
|||
.map(([, value]) => { |
|||
return value as string; |
|||
}) |
|||
); |
|||
} |
|||
|
|||
public transform(value: string): PropertyKey { |
|||
if (!this.allowedKeys.has(value)) { |
|||
throw new BadRequestException(`Invalid property key: ${value}`); |
|||
} |
|||
|
|||
return value as PropertyKey; |
|||
} |
|||
} |
|||
@ -0,0 +1,356 @@ |
|||
import { ALLOW_DURING_IMPERSONATION_KEY } from '@ghostfolio/api/decorators/allow-during-impersonation.decorator'; |
|||
import { HAS_PERMISSION_KEY } from '@ghostfolio/api/decorators/has-permission.decorator'; |
|||
import { REQUIRES_SCOPE_KEY } from '@ghostfolio/api/decorators/requires-scope.decorator'; |
|||
|
|||
import { |
|||
DynamicModule, |
|||
ForwardReference, |
|||
RequestMethod, |
|||
Type, |
|||
VERSION_NEUTRAL |
|||
} from '@nestjs/common'; |
|||
import { |
|||
GUARDS_METADATA, |
|||
INTERCEPTORS_METADATA, |
|||
METHOD_METADATA, |
|||
MODULE_METADATA, |
|||
PATH_METADATA, |
|||
VERSION_METADATA |
|||
} from '@nestjs/common/constants'; |
|||
import { VersionValue } from '@nestjs/common/interfaces'; |
|||
import { MetadataScanner } from '@nestjs/core'; |
|||
import { AuthGuard } from '@nestjs/passport'; |
|||
import { Test } from '@nestjs/testing'; |
|||
import { isUndefined, omitBy } from 'lodash-es'; |
|||
|
|||
import { AppModule } from './app.module'; |
|||
|
|||
// The packages are ECMAScript modules, which Jest cannot load
|
|||
jest.mock('@openrouter/ai-sdk-provider', () => { |
|||
return {}; |
|||
}); |
|||
jest.mock('ai', () => { |
|||
return {}; |
|||
}); |
|||
|
|||
// A queue of Bull connects to Redis on its creation
|
|||
jest.mock('bull', () => { |
|||
return jest.fn().mockImplementation(() => { |
|||
return { close: jest.fn() }; |
|||
}); |
|||
}); |
|||
|
|||
type ModuleDefinition = |
|||
DynamicModule | ForwardReference<() => Type> | Promise<DynamicModule> | Type; |
|||
|
|||
/** |
|||
* The strategies of the authentication which the routes apply via |
|||
* AuthGuard(). The class of such a guard has a random name, hence the |
|||
* snapshot of the routes names it by its strategy |
|||
*/ |
|||
const AUTHENTICATION_STRATEGIES = ['api-key', 'google', 'jwt', 'oidc']; |
|||
|
|||
/** |
|||
* The routes of the controllers which answer a request without the |
|||
* authentication of a user or of an API key, sorted by the request method and |
|||
* the path. A new route has to apply AuthGuard('api-key') or AuthGuard('jwt') |
|||
* (e.g. via the decorator RequiresScope) or has to be added here. |
|||
* |
|||
* The MCP transport, Bull Board and the static files are not covered, as they |
|||
* are not served by a controller |
|||
*/ |
|||
const PUBLIC_ROUTES = [ |
|||
'GET /assets/:languageCode/site.webmanifest', |
|||
'GET /auth/google', |
|||
'GET /auth/google/callback', |
|||
'GET /auth/oidc', |
|||
'GET /auth/oidc/callback', |
|||
'GET /benchmarks', |
|||
'GET /health', |
|||
'GET /health/data-enhancer/:name', |
|||
'GET /health/data-provider/:dataSource', |
|||
'GET /health/liveness', |
|||
'GET /info', |
|||
'GET /logo', |
|||
'GET /logo/:dataSource/:symbol', |
|||
'GET /public/:accessId/portfolio', |
|||
'GET /sitemap.xml', |
|||
'GET /subscription/stripe/callback', |
|||
'POST /auth/anonymous', |
|||
'POST /auth/webauthn/generate-authentication-options', |
|||
'POST /auth/webauthn/verify-authentication', |
|||
'POST /user' |
|||
]; |
|||
|
|||
/** |
|||
* Gives the controllers of the module and of each module which it imports |
|||
*/ |
|||
async function getControllers( |
|||
moduleDefinition: ModuleDefinition, |
|||
visitedModules = new Set<DynamicModule | Type>() |
|||
): Promise<Type[]> { |
|||
const resolvedModule = await ('forwardRef' in moduleDefinition |
|||
? moduleDefinition.forwardRef() |
|||
: moduleDefinition); |
|||
|
|||
if (visitedModules.has(resolvedModule)) { |
|||
return []; |
|||
} |
|||
|
|||
visitedModules.add(resolvedModule); |
|||
|
|||
const isDynamicModule = 'module' in resolvedModule; |
|||
|
|||
const controllers = [ |
|||
...(isDynamicModule |
|||
? (resolvedModule.controllers ?? []) |
|||
: ((Reflect.getMetadata(MODULE_METADATA.CONTROLLERS, resolvedModule) ?? |
|||
[]) as Type[])) |
|||
]; |
|||
|
|||
const importedModules = isDynamicModule |
|||
? [resolvedModule.module, ...(resolvedModule.imports ?? [])] |
|||
: ((Reflect.getMetadata(MODULE_METADATA.IMPORTS, resolvedModule) ?? |
|||
[]) as ModuleDefinition[]); |
|||
|
|||
for (const importedModule of importedModules) { |
|||
controllers.push(...(await getControllers(importedModule, visitedModules))); |
|||
} |
|||
|
|||
return [...new Set(controllers)]; |
|||
} |
|||
|
|||
/** |
|||
* Gives the guards or the interceptors which the decorators of the controller |
|||
* and of the route handler set, in the order in which they run |
|||
*/ |
|||
function getEnhancers(key: string, controller: Type, routeHandler: object) { |
|||
return [controller, routeHandler].flatMap((target) => { |
|||
return (Reflect.getMetadata(key, target) ?? []) as Type[]; |
|||
}); |
|||
} |
|||
|
|||
/** |
|||
* Gives the metadata of the route handler or, if it has none, of the |
|||
* controller, as Reflector.getAllAndOverride() does |
|||
*/ |
|||
function getMetadataOfRoute<T>( |
|||
key: string, |
|||
controller: Type, |
|||
routeHandler: object |
|||
) { |
|||
return (Reflect.getMetadata(key, routeHandler) ?? |
|||
Reflect.getMetadata(key, controller)) as T | undefined; |
|||
} |
|||
|
|||
/** |
|||
* Gives the name of a guard or of an interceptor. The function mixin() |
|||
* replaces the name of a class by a random one, hence the name is read from |
|||
* the declaration of the class. A guard which extends AuthGuard() is named |
|||
* with its strategy |
|||
*/ |
|||
function getName(enhancer: Type) { |
|||
const authenticationStrategy = AUTHENTICATION_STRATEGIES.find((strategy) => { |
|||
return AuthGuard(strategy) === enhancer; |
|||
}); |
|||
|
|||
if (authenticationStrategy) { |
|||
return `AuthGuard('${authenticationStrategy}')`; |
|||
} |
|||
|
|||
const name = /^class\s+([\w$]+)/.exec(enhancer.toString())?.[1]; |
|||
|
|||
if (!name || name === 'MixinAuthGuard') { |
|||
throw new Error('The name of a guard or of an interceptor is unknown'); |
|||
} |
|||
|
|||
const parentStrategy = AUTHENTICATION_STRATEGIES.find((strategy) => { |
|||
return Object.getPrototypeOf(enhancer) === AuthGuard(strategy); |
|||
}); |
|||
|
|||
return parentStrategy ? `${name}('${parentStrategy}')` : name; |
|||
} |
|||
|
|||
/** |
|||
* Gives the paths which the decorator of a controller or of a route sets |
|||
*/ |
|||
function getPaths(target: object) { |
|||
return [ |
|||
(Reflect.getMetadata(PATH_METADATA, target) ?? '') as string | string[] |
|||
].flat(); |
|||
} |
|||
|
|||
/** |
|||
* Gives the routes of the controller, each as the request method and the path |
|||
* with its route handler |
|||
*/ |
|||
function getRoutes(controller: Type) { |
|||
const routeHandlersByName = controller.prototype as Record<string, object>; |
|||
|
|||
return new MetadataScanner() |
|||
.getAllMethodNames(routeHandlersByName) |
|||
.flatMap((methodName) => { |
|||
const routeHandler = routeHandlersByName[methodName]; |
|||
const requestMethod = Reflect.getMetadata( |
|||
METHOD_METADATA, |
|||
routeHandler |
|||
) as RequestMethod | undefined; |
|||
|
|||
if (requestMethod === undefined) { |
|||
return []; |
|||
} |
|||
|
|||
return getPaths(controller).flatMap((controllerPath) => { |
|||
return getPaths(routeHandler).map((routePath) => { |
|||
const path = `${controllerPath}/${routePath}` |
|||
.split('/') |
|||
.filter(Boolean) |
|||
.join('/'); |
|||
|
|||
return { |
|||
routeHandler, |
|||
route: `${RequestMethod[requestMethod]} /${path}` |
|||
}; |
|||
}); |
|||
}); |
|||
}); |
|||
} |
|||
|
|||
/** |
|||
* Gives the routes of the controller which apply neither AuthGuard('api-key') |
|||
* nor AuthGuard('jwt'), each as the request method and the path |
|||
*/ |
|||
function getRoutesWithoutAuthentication(controller: Type) { |
|||
const authenticationGuards: unknown[] = [ |
|||
AuthGuard('api-key'), |
|||
AuthGuard('jwt') |
|||
]; |
|||
|
|||
return getRoutes(controller) |
|||
.filter(({ routeHandler }) => { |
|||
const hasAuthentication = getEnhancers( |
|||
GUARDS_METADATA, |
|||
controller, |
|||
routeHandler |
|||
).some((guard) => { |
|||
return authenticationGuards.includes(guard); |
|||
}); |
|||
|
|||
return !hasAuthentication; |
|||
}) |
|||
.map(({ route }) => { |
|||
return route; |
|||
}); |
|||
} |
|||
|
|||
/** |
|||
* Gives the routes of the controller, each as the request method, the path |
|||
* and the version with the guards and the interceptors in the order in which |
|||
* they run, the permission, the scopes and whether the route stays available |
|||
* while an impersonation is active |
|||
*/ |
|||
function getRoutesWithSecurity(controller: Type) { |
|||
return getRoutes(controller).map(({ route, routeHandler }) => { |
|||
const security = omitBy( |
|||
{ |
|||
allowDuringImpersonation: getMetadataOfRoute<boolean>( |
|||
ALLOW_DURING_IMPERSONATION_KEY, |
|||
controller, |
|||
routeHandler |
|||
), |
|||
guards: getEnhancers(GUARDS_METADATA, controller, routeHandler).map( |
|||
(guard) => { |
|||
return getName(guard); |
|||
} |
|||
), |
|||
interceptors: getEnhancers( |
|||
INTERCEPTORS_METADATA, |
|||
controller, |
|||
routeHandler |
|||
).map((interceptor) => { |
|||
return getName(interceptor); |
|||
}), |
|||
// HasPermissionGuard reads the permission of the route handler only
|
|||
permission: Reflect.getMetadata(HAS_PERMISSION_KEY, routeHandler) as |
|||
string | undefined, |
|||
scopes: getMetadataOfRoute<string[]>( |
|||
REQUIRES_SCOPE_KEY, |
|||
controller, |
|||
routeHandler |
|||
) |
|||
}, |
|||
isUndefined |
|||
); |
|||
|
|||
return [ |
|||
`${route}${getVersionSuffix(controller, routeHandler)}`, |
|||
security |
|||
] as const; |
|||
}); |
|||
} |
|||
|
|||
/** |
|||
* Gives the version of the route as a suffix of its key, which is empty for |
|||
* the default version |
|||
*/ |
|||
function getVersionSuffix(controller: Type, routeHandler: object) { |
|||
const version = getMetadataOfRoute<VersionValue>( |
|||
VERSION_METADATA, |
|||
controller, |
|||
routeHandler |
|||
); |
|||
|
|||
if (version === undefined) { |
|||
return ''; |
|||
} |
|||
|
|||
const versions = [version].flat().map((value) => { |
|||
return value === VERSION_NEUTRAL ? 'neutral' : value; |
|||
}); |
|||
|
|||
return ` (version ${versions.join(', ')})`; |
|||
} |
|||
|
|||
describe('AppModule', () => { |
|||
it('should require the authentication for each route which is not public', async () => { |
|||
const controllers = await getControllers(AppModule); |
|||
|
|||
const routesWithoutAuthentication = controllers |
|||
.flatMap((controller) => { |
|||
return getRoutesWithoutAuthentication(controller); |
|||
}) |
|||
.sort(); |
|||
|
|||
expect(routesWithoutAuthentication).toEqual(PUBLIC_ROUTES); |
|||
}); |
|||
|
|||
// An intended change of a route is confirmed by an update of the snapshot
|
|||
// (--updateSnapshot), hence each change shows in the review
|
|||
it('should keep the security of each route', async () => { |
|||
const controllers = await getControllers(AppModule); |
|||
|
|||
const routesWithSecurity = controllers.flatMap((controller) => { |
|||
return getRoutesWithSecurity(controller); |
|||
}); |
|||
|
|||
const routes = routesWithSecurity.map(([route]) => { |
|||
return route; |
|||
}); |
|||
|
|||
// The snapshot is an object, which would hide a route declared twice
|
|||
expect(new Set(routes).size).toBe(routes.length); |
|||
expect(Object.fromEntries(routesWithSecurity)).toMatchSnapshot(); |
|||
}); |
|||
|
|||
it('should resolve the dependencies of each provider', async () => { |
|||
const testingModule = await Test.createTestingModule({ |
|||
imports: [AppModule] |
|||
}).compile(); |
|||
|
|||
try { |
|||
expect(testingModule.get(AppModule)).toBeInstanceOf(AppModule); |
|||
} finally { |
|||
await testingModule.close(); |
|||
} |
|||
}); |
|||
}); |
|||
@ -1,29 +0,0 @@ |
|||
import { AdminService } from '@ghostfolio/api/app/admin/admin.service'; |
|||
import { TransformDataSourceInRequestInterceptor } from '@ghostfolio/api/interceptors/transform-data-source-in-request/transform-data-source-in-request.interceptor'; |
|||
import { TransformDataSourceInResponseInterceptor } from '@ghostfolio/api/interceptors/transform-data-source-in-response/transform-data-source-in-response.interceptor'; |
|||
import type { AssetResponse } from '@ghostfolio/common/interfaces'; |
|||
|
|||
import { Controller, Get, Param, UseInterceptors } from '@nestjs/common'; |
|||
import { DataSource } from '@prisma/client'; |
|||
import { pick } from 'lodash'; |
|||
|
|||
@Controller('asset') |
|||
export class AssetController { |
|||
public constructor(private readonly adminService: AdminService) {} |
|||
|
|||
@Get(':dataSource/:symbol') |
|||
@UseInterceptors(TransformDataSourceInRequestInterceptor) |
|||
@UseInterceptors(TransformDataSourceInResponseInterceptor) |
|||
public async getAsset( |
|||
@Param('dataSource') dataSource: DataSource, |
|||
@Param('symbol') symbol: string |
|||
): Promise<AssetResponse> { |
|||
const { assetProfile, marketData } = |
|||
await this.adminService.getMarketDataBySymbol({ dataSource, symbol }); |
|||
|
|||
return { |
|||
marketData, |
|||
assetProfile: pick(assetProfile, ['dataSource', 'name', 'symbol']) |
|||
}; |
|||
} |
|||
} |
|||
@ -1,19 +0,0 @@ |
|||
import { AuthDeviceController } from '@ghostfolio/api/app/auth-device/auth-device.controller'; |
|||
import { AuthDeviceService } from '@ghostfolio/api/app/auth-device/auth-device.service'; |
|||
import { PrismaModule } from '@ghostfolio/api/services/prisma/prisma.module'; |
|||
|
|||
import { Module } from '@nestjs/common'; |
|||
import { JwtModule } from '@nestjs/jwt'; |
|||
|
|||
@Module({ |
|||
controllers: [AuthDeviceController], |
|||
imports: [ |
|||
JwtModule.register({ |
|||
secret: process.env.JWT_SECRET_KEY, |
|||
signOptions: { expiresIn: '180 days' } |
|||
}), |
|||
PrismaModule |
|||
], |
|||
providers: [AuthDeviceService] |
|||
}) |
|||
export class AuthDeviceModule {} |
|||
@ -0,0 +1,267 @@ |
|||
import { AllowDuringImpersonation } from '@ghostfolio/api/decorators/allow-during-impersonation.decorator'; |
|||
import { HasPermission } from '@ghostfolio/api/decorators/has-permission.decorator'; |
|||
import { HasPermissionGuard } from '@ghostfolio/api/guards/has-permission.guard'; |
|||
import { AccessService } from '@ghostfolio/api/services/access/access.service'; |
|||
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; |
|||
import { CreateAccessDto, UpdateAccessDto } from '@ghostfolio/common/dtos'; |
|||
import { SubscriptionType } from '@ghostfolio/common/enums'; |
|||
import { |
|||
canApplyFiltersToAccess, |
|||
isValidGranteeOfAccess |
|||
} from '@ghostfolio/common/helper'; |
|||
import { |
|||
AccessResponse, |
|||
AccessSettings, |
|||
AccessesResponse |
|||
} from '@ghostfolio/common/interfaces'; |
|||
import { permissions } from '@ghostfolio/common/permissions'; |
|||
import { getScopesOfAccess } from '@ghostfolio/common/scopes'; |
|||
import type { RequestWithUser } from '@ghostfolio/common/types'; |
|||
|
|||
import { |
|||
Body, |
|||
Controller, |
|||
Delete, |
|||
Get, |
|||
HttpException, |
|||
Inject, |
|||
Param, |
|||
Post, |
|||
Put, |
|||
UseGuards |
|||
} from '@nestjs/common'; |
|||
import { REQUEST } from '@nestjs/core'; |
|||
import { AuthGuard } from '@nestjs/passport'; |
|||
import { Access as AccessModel } from '@prisma/client'; |
|||
import { StatusCodes, getReasonPhrase } from 'http-status-codes'; |
|||
|
|||
@AllowDuringImpersonation() |
|||
@Controller('accesses') |
|||
export class AccessesController { |
|||
public constructor( |
|||
private readonly accessService: AccessService, |
|||
private readonly configurationService: ConfigurationService, |
|||
@Inject(REQUEST) private readonly request: RequestWithUser |
|||
) {} |
|||
|
|||
@HasPermission(permissions.createAccess) |
|||
@Post() |
|||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|||
public async createAccess( |
|||
@Body() data: CreateAccessDto |
|||
): Promise<AccessResponse> { |
|||
if ( |
|||
this.configurationService.get('ENABLE_FEATURE_SUBSCRIPTION') && |
|||
this.request.user.subscription?.type === SubscriptionType.Basic |
|||
) { |
|||
throw new HttpException( |
|||
getReasonPhrase(StatusCodes.FORBIDDEN), |
|||
StatusCodes.FORBIDDEN |
|||
); |
|||
} |
|||
|
|||
const type = data.type ?? (data.granteeUserId ? 'PRIVATE' : 'PUBLIC'); |
|||
|
|||
if ( |
|||
type === 'MCP' && |
|||
!this.configurationService.get('ENABLE_FEATURE_MCP') |
|||
) { |
|||
// The client hides the type while the feature is disabled, hence an
|
|||
// access of this type must not become a credential which is dormant
|
|||
// until the feature is enabled
|
|||
throw new HttpException( |
|||
getReasonPhrase(StatusCodes.BAD_REQUEST), |
|||
StatusCodes.BAD_REQUEST |
|||
); |
|||
} |
|||
|
|||
if ( |
|||
!isValidGranteeOfAccess({ |
|||
type, |
|||
granteeUserId: data.granteeUserId, |
|||
userId: this.request.user.id |
|||
}) |
|||
) { |
|||
throw new HttpException( |
|||
getReasonPhrase(StatusCodes.BAD_REQUEST), |
|||
StatusCodes.BAD_REQUEST |
|||
); |
|||
} |
|||
|
|||
if (data.filters?.length && !canApplyFiltersToAccess({ type })) { |
|||
throw new HttpException( |
|||
getReasonPhrase(StatusCodes.BAD_REQUEST), |
|||
StatusCodes.BAD_REQUEST |
|||
); |
|||
} |
|||
|
|||
try { |
|||
const access = await this.accessService.createAccess({ |
|||
type, |
|||
alias: data.alias || undefined, |
|||
expiresAt: new Date(data.expiresAt), |
|||
granteeUser: data.granteeUserId |
|||
? { connect: { id: data.granteeUserId } } |
|||
: undefined, |
|||
scopes: getScopesOfAccess({ |
|||
type, |
|||
scopes: data.scopes |
|||
}), |
|||
settings: this.accessService.buildSettings(data.filters), |
|||
user: { connect: { id: this.request.user.id } } |
|||
}); |
|||
|
|||
return this.getAccessResponse(access); |
|||
} catch { |
|||
throw new HttpException( |
|||
getReasonPhrase(StatusCodes.BAD_REQUEST), |
|||
StatusCodes.BAD_REQUEST |
|||
); |
|||
} |
|||
} |
|||
|
|||
@Delete(':id') |
|||
@HasPermission(permissions.deleteAccess) |
|||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|||
public async deleteAccess(@Param('id') id: string): Promise<void> { |
|||
const originalAccess = await this.accessService.access({ |
|||
id, |
|||
OR: [ |
|||
{ granteeUserId: this.request.user.id }, |
|||
{ userId: this.request.user.id } |
|||
] |
|||
}); |
|||
|
|||
if (!originalAccess) { |
|||
throw new HttpException( |
|||
getReasonPhrase(StatusCodes.FORBIDDEN), |
|||
StatusCodes.FORBIDDEN |
|||
); |
|||
} |
|||
|
|||
await this.accessService.deleteAccess({ |
|||
id |
|||
}); |
|||
} |
|||
|
|||
@Get() |
|||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|||
public async getAllAccesses(): Promise<AccessesResponse> { |
|||
const accesses = await this.accessService.accesses({ |
|||
orderBy: [{ granteeUserId: 'desc' }, { createdAt: 'asc' }], |
|||
where: { userId: this.request.user.id } |
|||
}); |
|||
|
|||
return { |
|||
accesses: accesses.map((access) => { |
|||
return this.getAccessResponse(access); |
|||
}) |
|||
}; |
|||
} |
|||
|
|||
@HasPermission(permissions.updateAccess) |
|||
@Put(':id') |
|||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|||
public async updateAccess( |
|||
@Body() data: UpdateAccessDto, |
|||
@Param('id') id: string |
|||
): Promise<AccessResponse> { |
|||
if ( |
|||
this.configurationService.get('ENABLE_FEATURE_SUBSCRIPTION') && |
|||
this.request.user.subscription?.type === SubscriptionType.Basic |
|||
) { |
|||
throw new HttpException( |
|||
getReasonPhrase(StatusCodes.FORBIDDEN), |
|||
StatusCodes.FORBIDDEN |
|||
); |
|||
} |
|||
|
|||
const originalAccess = await this.accessService.access({ |
|||
id, |
|||
userId: this.request.user.id |
|||
}); |
|||
|
|||
if (!originalAccess) { |
|||
throw new HttpException( |
|||
getReasonPhrase(StatusCodes.FORBIDDEN), |
|||
StatusCodes.FORBIDDEN |
|||
); |
|||
} |
|||
|
|||
if ( |
|||
originalAccess.type === 'MCP' && |
|||
!this.configurationService.get('ENABLE_FEATURE_MCP') |
|||
) { |
|||
throw new HttpException( |
|||
getReasonPhrase(StatusCodes.BAD_REQUEST), |
|||
StatusCodes.BAD_REQUEST |
|||
); |
|||
} |
|||
|
|||
if ( |
|||
!isValidGranteeOfAccess({ |
|||
granteeUserId: data.granteeUserId, |
|||
type: originalAccess.type, |
|||
userId: this.request.user.id |
|||
}) |
|||
) { |
|||
throw new HttpException( |
|||
getReasonPhrase(StatusCodes.BAD_REQUEST), |
|||
StatusCodes.BAD_REQUEST |
|||
); |
|||
} |
|||
|
|||
if ( |
|||
data.filters?.length && |
|||
!canApplyFiltersToAccess({ type: originalAccess.type }) |
|||
) { |
|||
throw new HttpException( |
|||
getReasonPhrase(StatusCodes.BAD_REQUEST), |
|||
StatusCodes.BAD_REQUEST |
|||
); |
|||
} |
|||
|
|||
try { |
|||
const access = await this.accessService.updateAccess({ |
|||
data: { |
|||
alias: data.alias || null, |
|||
expiresAt: new Date(data.expiresAt), |
|||
granteeUser: data.granteeUserId |
|||
? { connect: { id: data.granteeUserId } } |
|||
: { disconnect: true }, |
|||
scopes: getScopesOfAccess({ |
|||
scopes: data.scopes ?? originalAccess.scopes, |
|||
type: originalAccess.type |
|||
}), |
|||
settings: this.accessService.buildSettings(data.filters) |
|||
}, |
|||
where: { id } |
|||
}); |
|||
|
|||
return this.getAccessResponse(access); |
|||
} catch { |
|||
throw new HttpException( |
|||
getReasonPhrase(StatusCodes.BAD_REQUEST), |
|||
StatusCodes.BAD_REQUEST |
|||
); |
|||
} |
|||
} |
|||
|
|||
private getAccessResponse(access: AccessModel): AccessResponse { |
|||
const { alias, expiresAt, granteeUserId, id, lastUsedAt, settings, type } = |
|||
access; |
|||
|
|||
const { filters } = (settings ?? {}) as AccessSettings; |
|||
|
|||
return { |
|||
alias, |
|||
expiresAt, |
|||
id, |
|||
lastUsedAt, |
|||
type, |
|||
grantee: granteeUserId ?? undefined, |
|||
scopes: getScopesOfAccess(access), |
|||
settings: canApplyFiltersToAccess({ type }) ? { filters } : {} |
|||
}; |
|||
} |
|||
} |
|||
@ -0,0 +1,13 @@ |
|||
import { AccessModule } from '@ghostfolio/api/services/access/access.module'; |
|||
import { ConfigurationModule } from '@ghostfolio/api/services/configuration/configuration.module'; |
|||
|
|||
import { Module } from '@nestjs/common'; |
|||
|
|||
import { AccessController } from './access.controller'; |
|||
import { AccessesController } from './accesses.controller'; |
|||
|
|||
@Module({ |
|||
controllers: [AccessController, AccessesController], |
|||
imports: [AccessModule, ConfigurationModule] |
|||
}) |
|||
export class AccessesModule {} |
|||
@ -0,0 +1,375 @@ |
|||
import { PortfolioService } from '@ghostfolio/api/app/portfolio/portfolio.service'; |
|||
import { HasPermission } from '@ghostfolio/api/decorators/has-permission.decorator'; |
|||
import { Impersonation } from '@ghostfolio/api/decorators/impersonation.decorator'; |
|||
import { RequiresScope } from '@ghostfolio/api/decorators/requires-scope.decorator'; |
|||
import { RedactValuesInResponseInterceptor } from '@ghostfolio/api/interceptors/redact-values-in-response/redact-values-in-response.interceptor'; |
|||
import { TransformDataSourceInRequestInterceptor } from '@ghostfolio/api/interceptors/transform-data-source-in-request/transform-data-source-in-request.interceptor'; |
|||
import { AccountBalanceService } from '@ghostfolio/api/services/account-balance/account-balance.service'; |
|||
import { AccountService } from '@ghostfolio/api/services/account/account.service'; |
|||
import { ApiService } from '@ghostfolio/api/services/api/api.service'; |
|||
import { |
|||
CreateAccountBalanceDto, |
|||
CreateAccountDto, |
|||
TransferBalanceDto, |
|||
UpdateAccountDto |
|||
} from '@ghostfolio/common/dtos'; |
|||
import { |
|||
AccountBalanceResponse, |
|||
AccountBalancesResponse, |
|||
AccountResponse, |
|||
AccountsResponse |
|||
} from '@ghostfolio/common/interfaces'; |
|||
import { permissions } from '@ghostfolio/common/permissions'; |
|||
import { scopes } from '@ghostfolio/common/scopes'; |
|||
import type { ImpersonationContext } from '@ghostfolio/common/types'; |
|||
|
|||
import { |
|||
Body, |
|||
Controller, |
|||
Delete, |
|||
Get, |
|||
HttpException, |
|||
Param, |
|||
Post, |
|||
Put, |
|||
Query, |
|||
UseInterceptors |
|||
} from '@nestjs/common'; |
|||
import { Account as AccountModel } from '@prisma/client'; |
|||
import { StatusCodes, getReasonPhrase } from 'http-status-codes'; |
|||
import { pick } from 'lodash-es'; |
|||
|
|||
import { GetAllAccountsDto } from './get-all-accounts.dto'; |
|||
|
|||
@Controller([ |
|||
'accounts', |
|||
/** @deprecated */ |
|||
'account' |
|||
]) |
|||
export class AccountsController { |
|||
public constructor( |
|||
private readonly accountBalanceService: AccountBalanceService, |
|||
private readonly accountService: AccountService, |
|||
private readonly apiService: ApiService, |
|||
private readonly portfolioService: PortfolioService |
|||
) {} |
|||
|
|||
@Delete(':id') |
|||
@HasPermission(permissions.deleteAccount) |
|||
@RequiresScope(scopes.accountDelete) |
|||
@UseInterceptors(RedactValuesInResponseInterceptor) |
|||
public async deleteAccount( |
|||
@Impersonation() { userId }: ImpersonationContext, |
|||
@Param('id') id: string |
|||
): Promise<AccountModel> { |
|||
const account = await this.accountService.accountWithActivities( |
|||
{ |
|||
id_userId: { |
|||
id, |
|||
userId |
|||
} |
|||
}, |
|||
{ activities: true } |
|||
); |
|||
|
|||
if (!account || account?.activities.length > 0) { |
|||
throw new HttpException( |
|||
getReasonPhrase(StatusCodes.FORBIDDEN), |
|||
StatusCodes.FORBIDDEN |
|||
); |
|||
} |
|||
|
|||
return this.accountService.deleteAccount({ |
|||
id_userId: { |
|||
id, |
|||
userId |
|||
} |
|||
}); |
|||
} |
|||
|
|||
@Delete(':id/balances/:balanceId') |
|||
@HasPermission(permissions.deleteAccountBalance) |
|||
@RequiresScope(scopes.accountUpdate) |
|||
public async deleteAccountBalance( |
|||
@Impersonation() { userId }: ImpersonationContext, |
|||
@Param('balanceId') balanceId: string, |
|||
@Param('id') id: string |
|||
): Promise<void> { |
|||
const accountBalance = await this.accountBalanceService.accountBalance({ |
|||
userId, |
|||
accountId: id, |
|||
id: balanceId |
|||
}); |
|||
|
|||
if (!accountBalance) { |
|||
throw new HttpException( |
|||
getReasonPhrase(StatusCodes.FORBIDDEN), |
|||
StatusCodes.FORBIDDEN |
|||
); |
|||
} |
|||
|
|||
await this.accountBalanceService.deleteAccountBalance({ |
|||
id: accountBalance.id, |
|||
userId: accountBalance.userId |
|||
}); |
|||
} |
|||
|
|||
@Get() |
|||
@RequiresScope(scopes.accountRead) |
|||
@UseInterceptors(RedactValuesInResponseInterceptor) |
|||
@UseInterceptors(TransformDataSourceInRequestInterceptor) |
|||
public async getAllAccounts( |
|||
@Impersonation() { userId }: ImpersonationContext, |
|||
@Query() |
|||
{ |
|||
accounts, |
|||
assetClasses, |
|||
dataSource, |
|||
query, |
|||
symbol, |
|||
tags |
|||
}: GetAllAccountsDto |
|||
): Promise<AccountsResponse> { |
|||
const filters = this.apiService.buildFiltersFromQueryParams({ |
|||
filterByAccounts: accounts, |
|||
filterByAssetClasses: assetClasses, |
|||
filterByDataSource: dataSource, |
|||
filterBySearchQuery: query, |
|||
filterBySymbol: symbol, |
|||
filterByTags: tags |
|||
}); |
|||
|
|||
return this.portfolioService.getAccountsWithAggregations({ |
|||
filters, |
|||
userId, |
|||
withExcludedAccounts: true |
|||
}); |
|||
} |
|||
|
|||
@Get(':id') |
|||
@RequiresScope(scopes.accountRead) |
|||
@UseInterceptors(RedactValuesInResponseInterceptor) |
|||
public async getAccountById( |
|||
@Impersonation() { userId }: ImpersonationContext, |
|||
@Param('id') id: string |
|||
): Promise<AccountResponse> { |
|||
const accountsWithAggregations = |
|||
await this.portfolioService.getAccountsWithAggregations({ |
|||
userId, |
|||
filters: [{ id, type: 'ACCOUNT' }], |
|||
withExcludedAccounts: true |
|||
}); |
|||
|
|||
return accountsWithAggregations.accounts[0]; |
|||
} |
|||
|
|||
@Get(':id/balances') |
|||
@RequiresScope(scopes.accountRead) |
|||
@UseInterceptors(RedactValuesInResponseInterceptor) |
|||
public async getAccountBalancesById( |
|||
@Impersonation() { userId, userSettings }: ImpersonationContext, |
|||
@Param('id') id: string |
|||
): Promise<AccountBalancesResponse> { |
|||
return this.accountBalanceService.getAccountBalances({ |
|||
userId, |
|||
filters: [{ id, type: 'ACCOUNT' }], |
|||
userCurrency: userSettings.baseCurrency |
|||
}); |
|||
} |
|||
|
|||
@HasPermission(permissions.createAccount) |
|||
@Post() |
|||
@RequiresScope(scopes.accountCreate) |
|||
@UseInterceptors(RedactValuesInResponseInterceptor) |
|||
public async createAccount( |
|||
@Body() data: CreateAccountDto, |
|||
@Impersonation() { userId }: ImpersonationContext |
|||
): Promise<AccountModel> { |
|||
const { balance, tags: tagIds, ...accountData } = data; |
|||
|
|||
if (accountData.platformId) { |
|||
const platformId = accountData.platformId; |
|||
delete accountData.platformId; |
|||
|
|||
return this.accountService.createAccount({ |
|||
balance, |
|||
tagIds, |
|||
userId, |
|||
data: { |
|||
...accountData, |
|||
platform: { connect: { id: platformId } }, |
|||
user: { connect: { id: userId } } |
|||
} |
|||
}); |
|||
} else { |
|||
delete accountData.platformId; |
|||
|
|||
return this.accountService.createAccount({ |
|||
balance, |
|||
tagIds, |
|||
userId, |
|||
data: { |
|||
...accountData, |
|||
user: { connect: { id: userId } } |
|||
} |
|||
}); |
|||
} |
|||
} |
|||
|
|||
@HasPermission(permissions.createAccountBalance) |
|||
@Post(':id/balances') |
|||
@RequiresScope(scopes.accountUpdate) |
|||
@UseInterceptors(RedactValuesInResponseInterceptor) |
|||
public async createAccountBalance( |
|||
@Body() { balance, date }: CreateAccountBalanceDto, |
|||
@Impersonation() { userId }: ImpersonationContext, |
|||
@Param('id') id: string |
|||
): Promise<AccountBalanceResponse> { |
|||
const account = await this.accountService.account({ |
|||
id_userId: { |
|||
id, |
|||
userId |
|||
} |
|||
}); |
|||
|
|||
if (!account) { |
|||
throw new HttpException( |
|||
getReasonPhrase(StatusCodes.FORBIDDEN), |
|||
StatusCodes.FORBIDDEN |
|||
); |
|||
} |
|||
|
|||
const accountBalance = |
|||
await this.accountBalanceService.createOrUpdateAccountBalance({ |
|||
balance, |
|||
date, |
|||
accountId: account.id, |
|||
userId: account.userId |
|||
}); |
|||
|
|||
return pick(accountBalance, ['accountId', 'date', 'id', 'value']); |
|||
} |
|||
|
|||
@HasPermission(permissions.updateAccount) |
|||
@Post('transfer-balance') |
|||
@RequiresScope(scopes.accountUpdate) |
|||
public async transferAccountBalance( |
|||
@Body() { accountIdFrom, accountIdTo, balance }: TransferBalanceDto, |
|||
@Impersonation() { userId }: ImpersonationContext |
|||
) { |
|||
const accountsOfUser = await this.accountService.getAccounts(userId); |
|||
|
|||
const accountFrom = accountsOfUser.find(({ id }) => { |
|||
return id === accountIdFrom; |
|||
}); |
|||
|
|||
const accountTo = accountsOfUser.find(({ id }) => { |
|||
return id === accountIdTo; |
|||
}); |
|||
|
|||
if (!accountFrom || !accountTo) { |
|||
throw new HttpException( |
|||
getReasonPhrase(StatusCodes.NOT_FOUND), |
|||
StatusCodes.NOT_FOUND |
|||
); |
|||
} |
|||
|
|||
if (accountFrom.id === accountTo.id) { |
|||
throw new HttpException( |
|||
getReasonPhrase(StatusCodes.BAD_REQUEST), |
|||
StatusCodes.BAD_REQUEST |
|||
); |
|||
} |
|||
|
|||
if (accountFrom.balance < balance) { |
|||
throw new HttpException( |
|||
getReasonPhrase(StatusCodes.BAD_REQUEST), |
|||
StatusCodes.BAD_REQUEST |
|||
); |
|||
} |
|||
|
|||
await this.accountService.updateAccountBalance({ |
|||
userId, |
|||
accountId: accountFrom.id, |
|||
amount: -balance, |
|||
currency: accountFrom.currency |
|||
}); |
|||
|
|||
await this.accountService.updateAccountBalance({ |
|||
userId, |
|||
accountId: accountTo.id, |
|||
amount: balance, |
|||
currency: accountFrom.currency |
|||
}); |
|||
} |
|||
|
|||
@HasPermission(permissions.updateAccount) |
|||
@Put(':id') |
|||
@RequiresScope(scopes.accountUpdate) |
|||
@UseInterceptors(RedactValuesInResponseInterceptor) |
|||
public async update( |
|||
@Body() data: UpdateAccountDto, |
|||
@Impersonation() { userId }: ImpersonationContext, |
|||
@Param('id') id: string |
|||
) { |
|||
const originalAccount = await this.accountService.account({ |
|||
id_userId: { |
|||
id, |
|||
userId |
|||
} |
|||
}); |
|||
|
|||
if (!originalAccount) { |
|||
throw new HttpException( |
|||
getReasonPhrase(StatusCodes.FORBIDDEN), |
|||
StatusCodes.FORBIDDEN |
|||
); |
|||
} |
|||
|
|||
const { balance, tags: tagIds, ...accountData } = data; |
|||
|
|||
if (accountData.platformId) { |
|||
const platformId = accountData.platformId; |
|||
delete accountData.platformId; |
|||
|
|||
return this.accountService.updateAccount({ |
|||
balance, |
|||
tagIds, |
|||
userId, |
|||
data: { |
|||
...accountData, |
|||
platform: { connect: { id: platformId } }, |
|||
user: { connect: { id: userId } } |
|||
}, |
|||
where: { |
|||
id_userId: { |
|||
id, |
|||
userId |
|||
} |
|||
} |
|||
}); |
|||
} else { |
|||
// platformId is null, remove it
|
|||
delete accountData.platformId; |
|||
|
|||
return this.accountService.updateAccount({ |
|||
balance, |
|||
tagIds, |
|||
userId, |
|||
data: { |
|||
...accountData, |
|||
platform: originalAccount.platformId |
|||
? { disconnect: true } |
|||
: undefined, |
|||
user: { connect: { id: userId } } |
|||
}, |
|||
where: { |
|||
id_userId: { |
|||
id, |
|||
userId |
|||
} |
|||
} |
|||
}); |
|||
} |
|||
} |
|||
} |
|||
@ -1,32 +1,28 @@ |
|||
import { AccountBalanceModule } from '@ghostfolio/api/app/account-balance/account-balance.module'; |
|||
import { PortfolioModule } from '@ghostfolio/api/app/portfolio/portfolio.module'; |
|||
import { UserModule } from '@ghostfolio/api/app/user/user.module'; |
|||
import { RedactValuesInResponseModule } from '@ghostfolio/api/interceptors/redact-values-in-response/redact-values-in-response.module'; |
|||
import { AccountBalanceModule } from '@ghostfolio/api/services/account-balance/account-balance.module'; |
|||
import { AccountModule } from '@ghostfolio/api/services/account/account.module'; |
|||
import { ApiModule } from '@ghostfolio/api/services/api/api.module'; |
|||
import { ConfigurationModule } from '@ghostfolio/api/services/configuration/configuration.module'; |
|||
import { ExchangeRateDataModule } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.module'; |
|||
import { ImpersonationModule } from '@ghostfolio/api/services/impersonation/impersonation.module'; |
|||
import { PrismaModule } from '@ghostfolio/api/services/prisma/prisma.module'; |
|||
|
|||
import { Module } from '@nestjs/common'; |
|||
|
|||
import { AccountController } from './account.controller'; |
|||
import { AccountService } from './account.service'; |
|||
import { AccountBalanceController } from './account-balance.controller'; |
|||
import { AccountsController } from './accounts.controller'; |
|||
|
|||
@Module({ |
|||
controllers: [AccountController], |
|||
exports: [AccountService], |
|||
controllers: [AccountBalanceController, AccountsController], |
|||
imports: [ |
|||
AccountBalanceModule, |
|||
AccountModule, |
|||
ApiModule, |
|||
ConfigurationModule, |
|||
ExchangeRateDataModule, |
|||
ImpersonationModule, |
|||
PortfolioModule, |
|||
PrismaModule, |
|||
RedactValuesInResponseModule, |
|||
UserModule |
|||
], |
|||
providers: [AccountService] |
|||
] |
|||
}) |
|||
export class AccountModule {} |
|||
export class AccountsModule {} |
|||
@ -0,0 +1,11 @@ |
|||
import { FilterDto } from '@ghostfolio/api/dtos/filter.dto'; |
|||
import { SEARCH_QUERY_MAXIMUM_LENGTH } from '@ghostfolio/common/config'; |
|||
|
|||
import { IsOptional, IsString, MaxLength } from 'class-validator'; |
|||
|
|||
export class GetAllAccountsDto extends FilterDto { |
|||
@IsOptional() |
|||
@IsString() |
|||
@MaxLength(SEARCH_QUERY_MAXIMUM_LENGTH) |
|||
query?: string; |
|||
} |
|||
@ -0,0 +1,279 @@ |
|||
import { HAS_PERMISSION_KEY } from '@ghostfolio/api/decorators/has-permission.decorator'; |
|||
import { CallerFacingError } from '@ghostfolio/api/errors/caller-facing.error'; |
|||
import { CustomThrottlerGuard } from '@ghostfolio/api/guards/custom-throttler.guard'; |
|||
import { HasPermissionGuard } from '@ghostfolio/api/guards/has-permission.guard'; |
|||
import { ApiService } from '@ghostfolio/api/services/api/api.service'; |
|||
import { |
|||
AI_ACTIVITIES_TIMEOUT, |
|||
AI_MAX_ACTIVITIES, |
|||
THROTTLE_AI_ACTIVITIES_LIMIT, |
|||
THROTTLE_AI_ACTIVITIES_TTL |
|||
} from '@ghostfolio/common/config'; |
|||
import { permissions } from '@ghostfolio/common/permissions'; |
|||
import type { RequestWithUser } from '@ghostfolio/common/types'; |
|||
|
|||
import { HttpException, Logger } from '@nestjs/common'; |
|||
import { GUARDS_METADATA } from '@nestjs/common/constants'; |
|||
import { |
|||
THROTTLER_LIMIT, |
|||
THROTTLER_TRACKER, |
|||
THROTTLER_TTL |
|||
} from '@nestjs/throttler/dist/throttler.constants'; |
|||
import type { Response } from 'express'; |
|||
import { StatusCodes } from 'http-status-codes'; |
|||
import { EventEmitter } from 'node:events'; |
|||
|
|||
import { AiController } from './ai.controller'; |
|||
import { AiService } from './ai.service'; |
|||
|
|||
// The packages are ECMAScript modules, which Jest cannot load
|
|||
jest.mock('@openrouter/ai-sdk-provider', () => { |
|||
return {}; |
|||
}); |
|||
jest.mock('ai', () => { |
|||
return {}; |
|||
}); |
|||
|
|||
describe('AiController', () => { |
|||
const pdfFile = { |
|||
buffer: Buffer.from('%PDF-1.7'), |
|||
originalname: 'statement.pdf' |
|||
}; |
|||
|
|||
const user = { id: 'user-id' }; |
|||
|
|||
let aiController: AiController; |
|||
let aiService: AiService; |
|||
|
|||
function createCsvFile(dataRowCount: number) { |
|||
return { |
|||
buffer: Buffer.from( |
|||
[ |
|||
'Date,Symbol', |
|||
...Array.from({ length: dataRowCount }, () => { |
|||
return '2026-01-15,AAPL'; |
|||
}) |
|||
].join('\n') |
|||
), |
|||
originalname: 'statement.csv' |
|||
}; |
|||
} |
|||
|
|||
function createResponse() { |
|||
return Object.assign(new EventEmitter(), { |
|||
writableFinished: false |
|||
}) as unknown as Response; |
|||
} |
|||
|
|||
function getMetadataOfMethod<T>(metadataKey: string) { |
|||
return Reflect.getMetadata( |
|||
metadataKey, |
|||
AiController.prototype.getActivitiesFromFile |
|||
) as T; |
|||
} |
|||
|
|||
beforeEach(() => { |
|||
jest.spyOn(Logger.prototype, 'warn').mockImplementation(); |
|||
|
|||
aiService = { |
|||
getActivitiesFromFile: jest.fn().mockResolvedValue({ |
|||
activities: [], |
|||
assetProfiles: [], |
|||
rowsWithoutMatch: [] |
|||
}) |
|||
} as unknown as AiService; |
|||
|
|||
aiController = new AiController( |
|||
aiService, |
|||
{} as ApiService, |
|||
{ |
|||
user |
|||
} as unknown as RequestWithUser |
|||
); |
|||
}); |
|||
|
|||
describe('getActivitiesFromFile', () => { |
|||
it('Requires the permission and limits the requests of each user per week', () => { |
|||
expect(getMetadataOfMethod<string>(HAS_PERMISSION_KEY)).toBe( |
|||
permissions.enableGhostfolioAi |
|||
); |
|||
|
|||
const guards = getMetadataOfMethod<unknown[]>(GUARDS_METADATA); |
|||
|
|||
expect(guards.slice(1)).toEqual([ |
|||
HasPermissionGuard, |
|||
CustomThrottlerGuard |
|||
]); |
|||
|
|||
expect(getMetadataOfMethod<number>(`${THROTTLER_LIMIT}default`)).toBe( |
|||
THROTTLE_AI_ACTIVITIES_LIMIT |
|||
); |
|||
|
|||
expect(getMetadataOfMethod<number>(`${THROTTLER_TTL}default`)).toBe( |
|||
THROTTLE_AI_ACTIVITIES_TTL |
|||
); |
|||
|
|||
expect( |
|||
getMetadataOfMethod<(request: unknown) => string>( |
|||
`${THROTTLER_TRACKER}default` |
|||
)({ ip: '127.0.0.1', user }) |
|||
).toBe(user.id); |
|||
}); |
|||
|
|||
it('Refuses a request without a file or with a file of another type', async () => { |
|||
for (const file of [ |
|||
undefined, |
|||
{ buffer: Buffer.from('Date,Symbol'), originalname: 'statement.txt' } |
|||
]) { |
|||
await expect( |
|||
aiController.getActivitiesFromFile(createResponse(), file) |
|||
).rejects.toThrow(HttpException); |
|||
} |
|||
|
|||
expect(aiService.getActivitiesFromFile).not.toHaveBeenCalled(); |
|||
}); |
|||
|
|||
it(`Refuses a CSV file with more than ${AI_MAX_ACTIVITIES} rows before a model call`, async () => { |
|||
await expect( |
|||
aiController.getActivitiesFromFile( |
|||
createResponse(), |
|||
createCsvFile(AI_MAX_ACTIVITIES + 1) |
|||
) |
|||
).rejects.toThrow(HttpException); |
|||
|
|||
expect(aiService.getActivitiesFromFile).not.toHaveBeenCalled(); |
|||
|
|||
expect(Logger.prototype.warn).toHaveBeenCalledWith( |
|||
`Rejected a CSV file with ${AI_MAX_ACTIVITIES + 1} rows` |
|||
); |
|||
}); |
|||
|
|||
it(`Accepts a CSV file with ${AI_MAX_ACTIVITIES} rows`, async () => { |
|||
const file = createCsvFile(AI_MAX_ACTIVITIES); |
|||
|
|||
await aiController.getActivitiesFromFile(createResponse(), file); |
|||
|
|||
expect(aiService.getActivitiesFromFile).toHaveBeenCalledWith( |
|||
expect.objectContaining({ |
|||
file: { |
|||
buffer: file.buffer, |
|||
mediaType: 'text/csv', |
|||
name: 'statement.csv' |
|||
} |
|||
}) |
|||
); |
|||
}); |
|||
|
|||
it('Passes the file with its media type and its name and the user of the request', async () => { |
|||
await expect( |
|||
aiController.getActivitiesFromFile(createResponse(), pdfFile) |
|||
).resolves.toEqual({ |
|||
activities: [], |
|||
assetProfiles: [], |
|||
rowsWithoutMatch: [] |
|||
}); |
|||
|
|||
expect(aiService.getActivitiesFromFile).toHaveBeenCalledWith( |
|||
expect.objectContaining({ |
|||
user, |
|||
file: { |
|||
buffer: pdfFile.buffer, |
|||
mediaType: 'application/pdf', |
|||
name: 'statement.pdf' |
|||
} |
|||
}) |
|||
); |
|||
|
|||
const [[{ abortSignal }]] = jest.mocked(aiService.getActivitiesFromFile) |
|||
.mock.calls; |
|||
|
|||
expect(abortSignal).toBeInstanceOf(AbortSignal); |
|||
}); |
|||
|
|||
it('Stops the models if the client closes the request before the response', async () => { |
|||
const response = createResponse(); |
|||
|
|||
await aiController.getActivitiesFromFile(response, pdfFile); |
|||
|
|||
const [[{ abortSignal }]] = jest.mocked(aiService.getActivitiesFromFile) |
|||
.mock.calls; |
|||
|
|||
expect(abortSignal.aborted).toBe(false); |
|||
|
|||
response.emit('close'); |
|||
|
|||
expect(abortSignal.aborted).toBe(true); |
|||
}); |
|||
|
|||
it('Does not stop the models when the response is finished', async () => { |
|||
const response = createResponse(); |
|||
|
|||
await aiController.getActivitiesFromFile(response, pdfFile); |
|||
|
|||
const [[{ abortSignal }]] = jest.mocked(aiService.getActivitiesFromFile) |
|||
.mock.calls; |
|||
|
|||
Object.assign(response, { writableFinished: true }); |
|||
response.emit('close'); |
|||
|
|||
expect(abortSignal.aborted).toBe(false); |
|||
}); |
|||
|
|||
it('Gives the status 400 with the message of an error for the caller', async () => { |
|||
jest |
|||
.mocked(aiService.getActivitiesFromFile) |
|||
.mockRejectedValueOnce( |
|||
new CallerFacingError('The file has too many activities') |
|||
); |
|||
|
|||
await expect( |
|||
aiController.getActivitiesFromFile(createResponse(), pdfFile) |
|||
).rejects.toMatchObject({ |
|||
response: { message: ['The file has too many activities'] }, |
|||
status: StatusCodes.BAD_REQUEST |
|||
}); |
|||
}); |
|||
|
|||
it('Gives the status 400 with a message for the caller at the timeout', async () => { |
|||
const timeoutSignal = AbortSignal.abort( |
|||
new DOMException( |
|||
'The operation was aborted due to timeout', |
|||
'TimeoutError' |
|||
) |
|||
); |
|||
|
|||
jest.spyOn(AbortSignal, 'timeout').mockReturnValueOnce(timeoutSignal); |
|||
|
|||
jest |
|||
.mocked(aiService.getActivitiesFromFile) |
|||
.mockRejectedValueOnce(timeoutSignal.reason); |
|||
|
|||
await expect( |
|||
aiController.getActivitiesFromFile(createResponse(), pdfFile) |
|||
).rejects.toMatchObject({ |
|||
response: { |
|||
message: [ |
|||
'Ghostfolio AI needs too much time for the file. Split it into smaller files.' |
|||
] |
|||
}, |
|||
status: StatusCodes.BAD_REQUEST |
|||
}); |
|||
|
|||
expect(AbortSignal.timeout).toHaveBeenCalledWith(AI_ACTIVITIES_TIMEOUT); |
|||
|
|||
expect(Logger.prototype.warn).toHaveBeenCalledWith( |
|||
`Stopped reading a file of the type application/pdf at the timeout of ${AI_ACTIVITIES_TIMEOUT} ms` |
|||
); |
|||
}); |
|||
|
|||
it('Passes on every other error', async () => { |
|||
const error = new Error('Model error'); |
|||
|
|||
jest.mocked(aiService.getActivitiesFromFile).mockRejectedValueOnce(error); |
|||
|
|||
await expect( |
|||
aiController.getActivitiesFromFile(createResponse(), pdfFile) |
|||
).rejects.toBe(error); |
|||
}); |
|||
}); |
|||
}); |
|||
@ -0,0 +1,99 @@ |
|||
import { |
|||
getDataRowCountOfCsvFile, |
|||
getMediaTypeOfActivityFile |
|||
} from './ai.helper'; |
|||
|
|||
describe('getDataRowCountOfCsvFile', () => { |
|||
it('Gives the number of the lines which are not empty, without the header', () => { |
|||
expect( |
|||
getDataRowCountOfCsvFile( |
|||
Buffer.from('Date,Symbol\n2026-01-15,AAPL\n\n2026-01-16,MSFT\n') |
|||
) |
|||
).toBe(2); |
|||
}); |
|||
|
|||
it('Counts each line of a value with a line break in quotes', () => { |
|||
expect( |
|||
getDataRowCountOfCsvFile( |
|||
Buffer.from('Date,Comment\r\n2026-01-15,"First\r\nsecond"\r\n') |
|||
) |
|||
).toBe(2); |
|||
}); |
|||
|
|||
it('Counts each line after a quote which is not closed', () => { |
|||
expect( |
|||
getDataRowCountOfCsvFile( |
|||
Buffer.from( |
|||
[ |
|||
'Date,Symbol,Quantity', |
|||
'2026-01-15,"AAPL,1', |
|||
...Array.from({ length: 200 }, () => { |
|||
return '2026-01-16,MSFT,1'; |
|||
}) |
|||
].join('\n') |
|||
) |
|||
) |
|||
).toBe(201); |
|||
}); |
|||
|
|||
it('Gives 0 for a file with a header only or without content', () => { |
|||
expect(getDataRowCountOfCsvFile(Buffer.from('Date,Symbol\n'))).toBe(0); |
|||
expect(getDataRowCountOfCsvFile(Buffer.from(''))).toBe(0); |
|||
}); |
|||
}); |
|||
|
|||
describe('getMediaTypeOfActivityFile', () => { |
|||
it('Identifies a JPEG, a PDF and a PNG file by the first bytes', () => { |
|||
expect( |
|||
getMediaTypeOfActivityFile({ |
|||
buffer: Buffer.from([0xff, 0xd8, 0xff, 0xe0]), |
|||
fileName: 'statement' |
|||
}) |
|||
).toBe('image/jpeg'); |
|||
|
|||
expect( |
|||
getMediaTypeOfActivityFile({ |
|||
buffer: Buffer.from('%PDF-1.7'), |
|||
fileName: 'statement.csv' |
|||
}) |
|||
).toBe('application/pdf'); |
|||
|
|||
expect( |
|||
getMediaTypeOfActivityFile({ |
|||
buffer: Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), |
|||
fileName: 'statement.jpg' |
|||
}) |
|||
).toBe('image/png'); |
|||
}); |
|||
|
|||
it('Identifies a CSV file by the extension and the content in UTF-8', () => { |
|||
for (const fileName of ['statement.csv', 'STATEMENT.CSV']) { |
|||
expect( |
|||
getMediaTypeOfActivityFile({ |
|||
fileName, |
|||
buffer: Buffer.from('Datum;Stück\n15.01.2026;10\n') |
|||
}) |
|||
).toBe('text/csv'); |
|||
} |
|||
}); |
|||
|
|||
it('Refuses a CSV file which is not in UTF-8', () => { |
|||
expect( |
|||
getMediaTypeOfActivityFile({ |
|||
buffer: Buffer.from([0x53, 0x74, 0xfc, 0x63, 0x6b]), |
|||
fileName: 'statement.csv' |
|||
}) |
|||
).toBeUndefined(); |
|||
}); |
|||
|
|||
it('Refuses any other file', () => { |
|||
for (const { buffer, fileName } of [ |
|||
{ buffer: Buffer.from('Date,Symbol'), fileName: 'statement.txt' }, |
|||
{ buffer: Buffer.from('<html></html>'), fileName: 'statement.pdf' }, |
|||
{ buffer: Buffer.from([0xff, 0xd8]), fileName: 'statement.jpg' }, |
|||
{ buffer: Buffer.from(''), fileName: 'statement.png' } |
|||
]) { |
|||
expect(getMediaTypeOfActivityFile({ buffer, fileName })).toBeUndefined(); |
|||
} |
|||
}); |
|||
}); |
|||
@ -0,0 +1,57 @@ |
|||
import { isUtf8 } from 'node:buffer'; |
|||
|
|||
const JPEG_SIGNATURE = [0xff, 0xd8, 0xff]; |
|||
const PDF_SIGNATURE = [0x25, 0x50, 0x44, 0x46, 0x2d]; |
|||
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]; |
|||
|
|||
/** |
|||
* Gives the number of the lines of a CSV file which are not empty, without |
|||
* the first line. A line before the header and each line of a value with a |
|||
* line break are counted as data rows, hence the number is never too low, |
|||
* also for a file with a quote which is not closed. |
|||
*/ |
|||
export function getDataRowCountOfCsvFile(buffer: Buffer) { |
|||
const lineCount = buffer |
|||
.toString('utf8') |
|||
.split(/\r\n|\r|\n/) |
|||
.filter((line) => { |
|||
return line.trim().length > 0; |
|||
}).length; |
|||
|
|||
return Math.max(lineCount - 1, 0); |
|||
} |
|||
|
|||
/** |
|||
* Gives the media type of a file which Ghostfolio AI reads. A JPEG, a PDF or |
|||
* a PNG file is identified by its first bytes, a CSV file by its extension |
|||
* and by its content in UTF-8, as the media type which a client sends for a |
|||
* CSV file varies. |
|||
*/ |
|||
export function getMediaTypeOfActivityFile({ |
|||
buffer, |
|||
fileName |
|||
}: { |
|||
buffer: Buffer; |
|||
fileName: string; |
|||
}) { |
|||
if (startsWith(buffer, JPEG_SIGNATURE)) { |
|||
return 'image/jpeg'; |
|||
} else if (startsWith(buffer, PDF_SIGNATURE)) { |
|||
return 'application/pdf'; |
|||
} else if (startsWith(buffer, PNG_SIGNATURE)) { |
|||
return 'image/png'; |
|||
} else if (fileName.toLowerCase().endsWith('.csv') && isUtf8(buffer)) { |
|||
return 'text/csv'; |
|||
} |
|||
|
|||
return undefined; |
|||
} |
|||
|
|||
function startsWith(buffer: Buffer, signature: number[]) { |
|||
return ( |
|||
buffer.length >= signature.length && |
|||
signature.every((byte, index) => { |
|||
return buffer[index] === byte; |
|||
}) |
|||
); |
|||
} |
|||
@ -0,0 +1,101 @@ |
|||
import { |
|||
AI_MAX_ACTIVITIES, |
|||
SEARCH_QUERY_MAXIMUM_LENGTH |
|||
} from '@ghostfolio/common/config'; |
|||
|
|||
import { isObject } from 'lodash-es'; |
|||
import { z } from 'zod'; |
|||
|
|||
import { ACTIVITY_ROWS_OUTPUT, ROW_MATCHES_OUTPUT } from './ai.schemas'; |
|||
import { createActivityRow } from './ai.test-utils'; |
|||
import { ActivityRow } from './types/activity-row.type'; |
|||
|
|||
describe('ACTIVITY_ROWS_OUTPUT', () => { |
|||
it('Accepts a row with null for the values which the file does not show', () => { |
|||
expect( |
|||
ACTIVITY_ROWS_OUTPUT.safeParse({ |
|||
broker: null, |
|||
rows: [ |
|||
createActivityRow({ |
|||
accountName: null, |
|||
currency: null, |
|||
isin: null, |
|||
symbol: null |
|||
}) |
|||
] |
|||
}).success |
|||
).toBe(true); |
|||
}); |
|||
|
|||
it('Refuses a row with a value which is left out instead of null', () => { |
|||
const row: Partial<ActivityRow> = createActivityRow(); |
|||
|
|||
delete row.isin; |
|||
|
|||
expect( |
|||
ACTIVITY_ROWS_OUTPUT.safeParse({ broker: null, rows: [row] }).success |
|||
).toBe(false); |
|||
}); |
|||
|
|||
it('Accepts a currency, a date, a number, a printed text and a number of rows which the join checks, so that one value does not refuse all rows', () => { |
|||
expect( |
|||
ACTIVITY_ROWS_OUTPUT.safeParse({ |
|||
broker: null, |
|||
rows: [ |
|||
createActivityRow({ |
|||
currency: 'GBX', |
|||
date: '15.01.2026', |
|||
name: 'A'.repeat(SEARCH_QUERY_MAXIMUM_LENGTH + 1) |
|||
}), |
|||
createActivityRow({ fee: -1, quantity: -1, unitPrice: -1 }), |
|||
...Array.from({ length: AI_MAX_ACTIVITIES }, () => { |
|||
return createActivityRow(); |
|||
}) |
|||
] |
|||
}).success |
|||
).toBe(true); |
|||
}); |
|||
|
|||
it('Trims a printed text', () => { |
|||
const { data } = ACTIVITY_ROWS_OUTPUT.safeParse({ |
|||
broker: ' Swissquote ', |
|||
rows: [createActivityRow({ name: ' Apple Inc. ' })] |
|||
}); |
|||
|
|||
expect(data.broker).toBe('Swissquote'); |
|||
expect(data.rows[0].name).toBe('Apple Inc.'); |
|||
}); |
|||
}); |
|||
|
|||
describe.each([ |
|||
['ACTIVITY_ROWS_OUTPUT', ACTIVITY_ROWS_OUTPUT], |
|||
['ROW_MATCHES_OUTPUT', ROW_MATCHES_OUTPUT] |
|||
])('%s', (_name, schema) => { |
|||
it('Gives a JSON schema which the strict mode of the structured outputs supports', () => { |
|||
// The options of the conversion in the AI SDK
|
|||
const jsonSchema = z.toJSONSchema(schema, { |
|||
io: 'input', |
|||
target: 'draft-7' |
|||
}); |
|||
|
|||
const objectJsonSchemas: { properties: object; required: string[] }[] = []; |
|||
|
|||
JSON.stringify(jsonSchema, (_key, value: unknown) => { |
|||
if (isObject(value) && 'properties' in value) { |
|||
objectJsonSchemas.push( |
|||
value as { properties: object; required: string[] } |
|||
); |
|||
} |
|||
|
|||
return value; |
|||
}); |
|||
|
|||
expect(objectJsonSchemas.length).toBeGreaterThan(1); |
|||
|
|||
for (const { properties, required } of objectJsonSchemas) { |
|||
expect([...required].sort()).toEqual(Object.keys(properties).sort()); |
|||
} |
|||
|
|||
expect(JSON.stringify(jsonSchema)).not.toMatch(/"(max|min)(imum|Length)"/); |
|||
}); |
|||
}); |
|||
@ -0,0 +1,87 @@ |
|||
import { AI_MAX_ACTIVITIES } from '@ghostfolio/common/config'; |
|||
|
|||
import { Type as ActivityType } from '@prisma/client'; |
|||
import { z } from 'zod'; |
|||
|
|||
// The strict mode of the structured outputs requires every property, hence a
|
|||
// value which the file does not show is null instead of being left out. The
|
|||
// values are checked when the rows and the matches are joined to the
|
|||
// activities to import, so that a wrong value or a wrong match skips its rows
|
|||
// only
|
|||
const PRINTED_TEXT = z.string().trim().nullable(); |
|||
|
|||
export const ACTIVITY_ROWS_OUTPUT = z.object({ |
|||
broker: PRINTED_TEXT.describe( |
|||
'The name of the broker or of the bank which issued the file' |
|||
), |
|||
rows: z |
|||
.array( |
|||
z.object({ |
|||
accountName: PRINTED_TEXT.describe( |
|||
'The name or the number of the account, as printed' |
|||
), |
|||
currency: z |
|||
.string() |
|||
.nullable() |
|||
.describe( |
|||
'The currency of the fee and of the unit price, as an ISO 4217 code in upper case' |
|||
), |
|||
date: z |
|||
.string() |
|||
.describe('The date of the activity, as an ISO 8601 date'), |
|||
fee: z.number().describe('The fee of the activity'), |
|||
isin: PRINTED_TEXT.describe('The ISIN of the asset, as printed'), |
|||
name: PRINTED_TEXT.describe( |
|||
'The name of the asset, or the description of a fee, an interest or a liability, as printed' |
|||
), |
|||
quantity: z.number().describe('The quantity of the activity'), |
|||
symbol: PRINTED_TEXT.describe( |
|||
'The ticker symbol of the asset, as printed, not a national number such as a valor, a WKN or a CUSIP' |
|||
), |
|||
type: z.enum(ActivityType).describe('The type of the activity'), |
|||
unitPrice: z.number().describe('The unit price of the activity') |
|||
}) |
|||
) |
|||
.describe(`The activities of the file, at most ${AI_MAX_ACTIVITIES}`) |
|||
}); |
|||
|
|||
export const ROW_MATCHES_OUTPUT = z.object({ |
|||
accounts: z |
|||
.array( |
|||
z.object({ |
|||
accountId: z |
|||
.string() |
|||
.nullable() |
|||
.describe( |
|||
'The id of the account of the user which matches, as given in the accounts, or null if no account matches' |
|||
), |
|||
id: z.number().describe('The id of the account hint, as given') |
|||
}) |
|||
) |
|||
.describe('One entry for each account hint of the file'), |
|||
assets: z |
|||
.array( |
|||
z.object({ |
|||
currency: z |
|||
.string() |
|||
.nullable() |
|||
.describe( |
|||
'The currency of the selected holding or asset profile, as given' |
|||
), |
|||
dataSource: z |
|||
.string() |
|||
.nullable() |
|||
.describe( |
|||
'The data source of the selected holding or asset profile, as given' |
|||
), |
|||
id: z.number().describe('The id of the asset, as given'), |
|||
symbol: z |
|||
.string() |
|||
.nullable() |
|||
.describe( |
|||
'The symbol of the selected holding or asset profile, as given, or null if no holding and no asset profile matches' |
|||
) |
|||
}) |
|||
) |
|||
.describe('One entry for each asset of the file') |
|||
}); |
|||
File diff suppressed because it is too large
@ -0,0 +1,21 @@ |
|||
import { Type as ActivityType } from '@prisma/client'; |
|||
|
|||
import { ActivityRow } from './types/activity-row.type'; |
|||
|
|||
export function createActivityRow( |
|||
overrides: Partial<ActivityRow> = {} |
|||
): ActivityRow { |
|||
return { |
|||
accountName: 'Brokerage', |
|||
currency: 'USD', |
|||
date: '2026-01-15', |
|||
fee: 1, |
|||
isin: 'US0378331005', |
|||
name: 'Apple Inc.', |
|||
quantity: 10, |
|||
symbol: 'AAPL', |
|||
type: ActivityType.BUY, |
|||
unitPrice: 230, |
|||
...overrides |
|||
}; |
|||
} |
|||
@ -0,0 +1,6 @@ |
|||
import { ActivityRow } from './activity-row.type'; |
|||
|
|||
export type AccountHint = Pick<ActivityRow, 'accountName'> & { |
|||
broker: string | null; |
|||
id: number; |
|||
}; |
|||
@ -0,0 +1,3 @@ |
|||
import { Account } from '@prisma/client'; |
|||
|
|||
export type AccountToMatch = Pick<Account, 'currency' | 'id' | 'name'>; |
|||
@ -0,0 +1,5 @@ |
|||
import { z } from 'zod'; |
|||
|
|||
import { ACTIVITY_ROWS_OUTPUT } from '../ai.schemas'; |
|||
|
|||
export type ActivityRow = z.infer<typeof ACTIVITY_ROWS_OUTPUT>['rows'][number]; |
|||
@ -0,0 +1,6 @@ |
|||
import { ActivityRow } from './activity-row.type'; |
|||
|
|||
export type AssetToMatch = Pick< |
|||
ActivityRow, |
|||
'currency' | 'isin' | 'name' | 'symbol' |
|||
> & { id: number }; |
|||
@ -1,13 +1,39 @@ |
|||
import { TransformDataSourceInRequestModule } from '@ghostfolio/api/interceptors/transform-data-source-in-request/transform-data-source-in-request.module'; |
|||
import { TransformDataSourceInResponseModule } from '@ghostfolio/api/interceptors/transform-data-source-in-response/transform-data-source-in-response.module'; |
|||
import { ActivitiesModule } from '@ghostfolio/api/services/activities/activities.module'; |
|||
import { ApiModule } from '@ghostfolio/api/services/api/api.module'; |
|||
import { AssetProfileSplitModule } from '@ghostfolio/api/services/asset-profile-split/asset-profile-split.module'; |
|||
import { BenchmarkModule } from '@ghostfolio/api/services/benchmark/benchmark.module'; |
|||
import { DataProviderModule } from '@ghostfolio/api/services/data-provider/data-provider.module'; |
|||
import { ExchangeRateDataModule } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.module'; |
|||
import { MarketDataModule } from '@ghostfolio/api/services/market-data/market-data.module'; |
|||
import { PrismaModule } from '@ghostfolio/api/services/prisma/prisma.module'; |
|||
import { DataGatheringQueueModule } from '@ghostfolio/api/services/queues/data-gathering/data-gathering.module'; |
|||
import { SymbolProfileModule } from '@ghostfolio/api/services/symbol-profile/symbol-profile.module'; |
|||
|
|||
import { Module } from '@nestjs/common'; |
|||
|
|||
import { AssetProfilesController } from './asset-profiles.controller'; |
|||
import { AssetProfilesService } from './asset-profiles.service'; |
|||
import { AssetController } from './asset.controller'; |
|||
|
|||
@Module({ |
|||
controllers: [AssetProfilesController], |
|||
imports: [SymbolProfileModule], |
|||
controllers: [AssetController, AssetProfilesController], |
|||
exports: [AssetProfilesService], |
|||
imports: [ |
|||
ActivitiesModule, |
|||
ApiModule, |
|||
AssetProfileSplitModule, |
|||
BenchmarkModule, |
|||
DataGatheringQueueModule, |
|||
DataProviderModule, |
|||
ExchangeRateDataModule, |
|||
MarketDataModule, |
|||
PrismaModule, |
|||
SymbolProfileModule, |
|||
TransformDataSourceInRequestModule, |
|||
TransformDataSourceInResponseModule |
|||
], |
|||
providers: [AssetProfilesService] |
|||
}) |
|||
export class AssetProfilesModule {} |
|||
|
|||
@ -0,0 +1,259 @@ |
|||
import { PortfolioChangedEvent } from '@ghostfolio/api/events/portfolio-changed.event'; |
|||
import { ActivitiesService } from '@ghostfolio/api/services/activities/activities.service'; |
|||
import { AssetProfileSplitService } from '@ghostfolio/api/services/asset-profile-split/asset-profile-split.service'; |
|||
import { DataProviderService } from '@ghostfolio/api/services/data-provider/data-provider.service'; |
|||
import { MarketDataService } from '@ghostfolio/api/services/market-data/market-data.service'; |
|||
import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service'; |
|||
import { DataGatheringService } from '@ghostfolio/api/services/queues/data-gathering/data-gathering.service'; |
|||
|
|||
import { NotFoundException } from '@nestjs/common'; |
|||
import { EventEmitter2 } from '@nestjs/event-emitter'; |
|||
import { AssetProfileSplit, DataSource } from '@prisma/client'; |
|||
|
|||
import { AssetProfilesService } from './asset-profiles.service'; |
|||
|
|||
describe('AssetProfilesService', () => { |
|||
let assetProfilesService: AssetProfilesService; |
|||
let deleteById: jest.Mock; |
|||
let emit: jest.Mock; |
|||
let findMany: jest.Mock; |
|||
let finished: jest.Mock; |
|||
let gatherSymbol: jest.Mock; |
|||
let getUserIdsBySymbolProfileId: jest.Mock; |
|||
let upsert: jest.Mock; |
|||
|
|||
beforeEach(() => { |
|||
deleteById = jest.fn(); |
|||
emit = jest.fn(); |
|||
findMany = jest.fn(); |
|||
finished = jest.fn().mockResolvedValue(undefined); |
|||
gatherSymbol = jest.fn().mockResolvedValue([{ finished }]); |
|||
getUserIdsBySymbolProfileId = jest.fn().mockResolvedValue([]); |
|||
upsert = jest.fn(); |
|||
|
|||
assetProfilesService = new AssetProfilesService( |
|||
{ getUserIdsBySymbolProfileId } as unknown as ActivitiesService, |
|||
{ |
|||
deleteById, |
|||
upsert |
|||
} as unknown as AssetProfileSplitService, |
|||
null, |
|||
{ gatherSymbol } as unknown as DataGatheringService, |
|||
{ |
|||
getDataProvider: jest.fn().mockReturnValue({ |
|||
getDataProviderInfo: jest.fn() |
|||
}) |
|||
} as unknown as DataProviderService, |
|||
{ emit } as unknown as EventEmitter2, |
|||
null, |
|||
{ |
|||
getLatest: jest.fn().mockResolvedValue(undefined) |
|||
} as unknown as MarketDataService, |
|||
{ |
|||
marketData: { |
|||
count: jest.fn().mockResolvedValue(0) |
|||
}, |
|||
symbolProfile: { |
|||
findMany, |
|||
count: jest.fn().mockResolvedValue(0) |
|||
} |
|||
} as unknown as PrismaService, |
|||
null |
|||
); |
|||
}); |
|||
|
|||
describe('createSplit', () => { |
|||
it('upserts the split and refreshes the asset profile data', async () => { |
|||
const split = {} as AssetProfileSplit; |
|||
const data = { |
|||
dataSource: DataSource.YAHOO, |
|||
date: new Date('2024-06-15T18:30:00.000Z'), |
|||
denominator: 1, |
|||
numerator: 2, |
|||
symbol: 'AAPL', |
|||
symbolProfileId: 'profile-id' |
|||
}; |
|||
upsert.mockResolvedValue(split); |
|||
|
|||
const result = await assetProfilesService.createSplit(data); |
|||
|
|||
expect(upsert).toHaveBeenCalledWith({ |
|||
date: data.date, |
|||
denominator: data.denominator, |
|||
numerator: data.numerator, |
|||
symbolProfileId: data.symbolProfileId |
|||
}); |
|||
expect(gatherSymbol).toHaveBeenCalledWith({ |
|||
dataSource: data.dataSource, |
|||
force: true, |
|||
symbol: data.symbol |
|||
}); |
|||
expect(result).toBe(split); |
|||
}); |
|||
|
|||
it('invalidates portfolio snapshots for users holding the asset', async () => { |
|||
upsert.mockResolvedValue({} as AssetProfileSplit); |
|||
getUserIdsBySymbolProfileId.mockResolvedValue(['user-1', 'user-2']); |
|||
|
|||
await assetProfilesService.createSplit({ |
|||
dataSource: DataSource.YAHOO, |
|||
date: new Date('2024-06-15T18:30:00.000Z'), |
|||
denominator: 1, |
|||
numerator: 2, |
|||
symbol: 'AAPL', |
|||
symbolProfileId: 'profile-id' |
|||
}); |
|||
await flushPendingPromises(); |
|||
|
|||
expect(getUserIdsBySymbolProfileId).toHaveBeenCalledWith('profile-id'); |
|||
expect(emit.mock.calls.map(([, event]) => event.getUserId())).toEqual([ |
|||
'user-1', |
|||
'user-2' |
|||
]); |
|||
expect(emit.mock.calls[0][0]).toBe(PortfolioChangedEvent.getName()); |
|||
}); |
|||
|
|||
it('emits the events only once the market data has been gathered', async () => { |
|||
let completeJob: () => void; |
|||
|
|||
finished.mockReturnValue( |
|||
new Promise<void>((resolve) => { |
|||
completeJob = resolve; |
|||
}) |
|||
); |
|||
upsert.mockResolvedValue({} as AssetProfileSplit); |
|||
getUserIdsBySymbolProfileId.mockResolvedValue(['user-1']); |
|||
|
|||
await assetProfilesService.createSplit({ |
|||
dataSource: DataSource.YAHOO, |
|||
date: new Date('2024-06-15T18:30:00.000Z'), |
|||
denominator: 1, |
|||
numerator: 2, |
|||
symbol: 'AAPL', |
|||
symbolProfileId: 'profile-id' |
|||
}); |
|||
await flushPendingPromises(); |
|||
|
|||
expect(emit).not.toHaveBeenCalled(); |
|||
|
|||
completeJob(); |
|||
await flushPendingPromises(); |
|||
|
|||
expect(emit.mock.calls.map(([, event]) => event.getUserId())).toEqual([ |
|||
'user-1' |
|||
]); |
|||
}); |
|||
}); |
|||
|
|||
describe('getAssetProfiles', () => { |
|||
it('flags the asset profiles used by users with a subscription', async () => { |
|||
findMany |
|||
.mockResolvedValueOnce([ |
|||
createSymbolProfile({ activitiesCount: 2, id: 'profile-id-1' }), |
|||
createSymbolProfile({ activitiesCount: 1, id: 'profile-id-2' }), |
|||
createSymbolProfile({ activitiesCount: 0, id: 'profile-id-3' }) |
|||
]) |
|||
.mockResolvedValueOnce([{ id: 'profile-id-1' }]); |
|||
|
|||
const { assetProfiles } = await assetProfilesService.getAssetProfiles({}); |
|||
|
|||
expect(findMany).toHaveBeenLastCalledWith( |
|||
expect.objectContaining({ |
|||
where: expect.objectContaining({ |
|||
id: { in: ['profile-id-1', 'profile-id-2'] } |
|||
}) |
|||
}) |
|||
); |
|||
expect( |
|||
assetProfiles.map(({ id, isUsedByUsersWithSubscription }) => { |
|||
return { id, isUsedByUsersWithSubscription }; |
|||
}) |
|||
).toEqual([ |
|||
{ id: 'profile-id-1', isUsedByUsersWithSubscription: true }, |
|||
{ id: 'profile-id-2', isUsedByUsersWithSubscription: false }, |
|||
{ id: 'profile-id-3', isUsedByUsersWithSubscription: false } |
|||
]); |
|||
}); |
|||
|
|||
it('skips the subscription query when no asset profile has activities', async () => { |
|||
findMany.mockResolvedValueOnce([ |
|||
createSymbolProfile({ activitiesCount: 0, id: 'profile-id-1' }) |
|||
]); |
|||
|
|||
const { assetProfiles } = await assetProfilesService.getAssetProfiles({}); |
|||
|
|||
expect(findMany).toHaveBeenCalledTimes(1); |
|||
expect(assetProfiles[0].isUsedByUsersWithSubscription).toBe(false); |
|||
}); |
|||
}); |
|||
|
|||
describe('deleteSplit', () => { |
|||
it('throws NotFoundException when the scoped split does not exist', async () => { |
|||
deleteById.mockResolvedValue(false); |
|||
|
|||
await expect( |
|||
assetProfilesService.deleteSplit({ |
|||
dataSource: DataSource.YAHOO, |
|||
id: 'split-id', |
|||
symbol: 'AAPL', |
|||
symbolProfileId: 'profile-id' |
|||
}) |
|||
).rejects.toBeInstanceOf(NotFoundException); |
|||
await flushPendingPromises(); |
|||
|
|||
expect(gatherSymbol).not.toHaveBeenCalled(); |
|||
expect(emit).not.toHaveBeenCalled(); |
|||
}); |
|||
|
|||
it('deletes an existing split using its profile scope', async () => { |
|||
deleteById.mockResolvedValue(true); |
|||
getUserIdsBySymbolProfileId.mockResolvedValue(['user-1']); |
|||
|
|||
await expect( |
|||
assetProfilesService.deleteSplit({ |
|||
dataSource: DataSource.YAHOO, |
|||
id: 'split-id', |
|||
symbol: 'AAPL', |
|||
symbolProfileId: 'profile-id' |
|||
}) |
|||
).resolves.toBeUndefined(); |
|||
await flushPendingPromises(); |
|||
|
|||
expect(deleteById).toHaveBeenCalledWith({ |
|||
id: 'split-id', |
|||
symbolProfileId: 'profile-id' |
|||
}); |
|||
expect(emit.mock.calls.map(([, event]) => event.getUserId())).toEqual([ |
|||
'user-1' |
|||
]); |
|||
expect(gatherSymbol).toHaveBeenCalledWith({ |
|||
dataSource: DataSource.YAHOO, |
|||
force: true, |
|||
symbol: 'AAPL' |
|||
}); |
|||
}); |
|||
}); |
|||
}); |
|||
|
|||
function createSymbolProfile({ |
|||
activitiesCount, |
|||
id |
|||
}: { |
|||
activitiesCount: number; |
|||
id: string; |
|||
}) { |
|||
return { |
|||
id, |
|||
_count: { activities: activitiesCount, watchedBy: 0 }, |
|||
activities: [], |
|||
assetProfileOverrides: null, |
|||
dataSource: DataSource.YAHOO, |
|||
symbol: 'AAPL' |
|||
}; |
|||
} |
|||
|
|||
function flushPendingPromises() { |
|||
return new Promise((resolve) => { |
|||
setImmediate(resolve); |
|||
}); |
|||
} |
|||
@ -0,0 +1,49 @@ |
|||
import { TransformDataSourceInRequestInterceptor } from '@ghostfolio/api/interceptors/transform-data-source-in-request/transform-data-source-in-request.interceptor'; |
|||
import { TransformDataSourceInResponseInterceptor } from '@ghostfolio/api/interceptors/transform-data-source-in-response/transform-data-source-in-response.interceptor'; |
|||
import type { AssetResponse } from '@ghostfolio/common/interfaces'; |
|||
|
|||
import { |
|||
Controller, |
|||
Get, |
|||
Param, |
|||
UseGuards, |
|||
UseInterceptors |
|||
} from '@nestjs/common'; |
|||
import { AuthGuard } from '@nestjs/passport'; |
|||
import { DataSource } from '@prisma/client'; |
|||
import { pick } from 'lodash-es'; |
|||
|
|||
import { AssetProfilesService } from './asset-profiles.service'; |
|||
|
|||
@Controller('asset') |
|||
export class AssetController { |
|||
public constructor( |
|||
private readonly assetProfilesService: AssetProfilesService |
|||
) {} |
|||
|
|||
@Get(':dataSource/:symbol') |
|||
@UseGuards(AuthGuard('jwt')) |
|||
@UseInterceptors(TransformDataSourceInRequestInterceptor) |
|||
@UseInterceptors(TransformDataSourceInResponseInterceptor) |
|||
public async getAsset( |
|||
@Param('dataSource') dataSource: DataSource, |
|||
@Param('symbol') symbol: string |
|||
): Promise<AssetResponse> { |
|||
const { assetProfile, marketData, splits } = |
|||
await this.assetProfilesService.getAssetProfile({ |
|||
dataSource, |
|||
symbol |
|||
}); |
|||
|
|||
return { |
|||
marketData, |
|||
splits, |
|||
assetProfile: { |
|||
...pick(assetProfile, ['dataSource', 'name', 'symbol']), |
|||
// An index has no asset class and its value has no currency,
|
|||
// thus show no currency for any asset profile without asset class
|
|||
currency: assetProfile.assetClass ? assetProfile.currency : undefined |
|||
} |
|||
}; |
|||
} |
|||
} |
|||
@ -0,0 +1,64 @@ |
|||
import { SEARCH_QUERY_MAXIMUM_LENGTH } from '@ghostfolio/common/config'; |
|||
import { MarketDataPreset } from '@ghostfolio/common/types'; |
|||
|
|||
import { Prisma } from '@prisma/client'; |
|||
import { Type } from 'class-transformer'; |
|||
import { |
|||
IsIn, |
|||
IsInt, |
|||
IsOptional, |
|||
IsString, |
|||
MaxLength, |
|||
Min |
|||
} from 'class-validator'; |
|||
|
|||
export class GetAssetProfilesDto { |
|||
@IsOptional() |
|||
@IsString() |
|||
assetSubClasses?: string; |
|||
|
|||
@IsOptional() |
|||
@IsString() |
|||
dataSource?: string; |
|||
|
|||
@IsIn([ |
|||
'BENCHMARKS', |
|||
'CURRENCIES', |
|||
'ETF_WITHOUT_COUNTRIES', |
|||
'ETF_WITHOUT_SECTORS', |
|||
'NO_ACTIVITIES' |
|||
] as MarketDataPreset[]) |
|||
@IsOptional() |
|||
presetId?: MarketDataPreset; |
|||
|
|||
@IsOptional() |
|||
@IsString() |
|||
@MaxLength(SEARCH_QUERY_MAXIMUM_LENGTH) |
|||
query?: string; |
|||
|
|||
@IsInt() |
|||
@IsOptional() |
|||
@Min(0) |
|||
@Type(() => Number) |
|||
skip?: number; |
|||
|
|||
@IsIn([ |
|||
'activitiesCount', |
|||
'assetClass', |
|||
'assetSubClass', |
|||
'dataSource', |
|||
'symbol' |
|||
]) |
|||
@IsOptional() |
|||
sortColumn?: string; |
|||
|
|||
@IsIn(['asc', 'desc'] as Prisma.SortOrder[]) |
|||
@IsOptional() |
|||
sortDirection?: Prisma.SortOrder; |
|||
|
|||
@IsInt() |
|||
@IsOptional() |
|||
@Min(0) |
|||
@Type(() => Number) |
|||
take?: number; |
|||
} |
|||
@ -0,0 +1,11 @@ |
|||
import { AuthDeviceModule } from '@ghostfolio/api/services/auth-device/auth-device.module'; |
|||
|
|||
import { Module } from '@nestjs/common'; |
|||
|
|||
import { AuthDevicesController } from './auth-devices.controller'; |
|||
|
|||
@Module({ |
|||
controllers: [AuthDevicesController], |
|||
imports: [AuthDeviceModule] |
|||
}) |
|||
export class AuthDevicesModule {} |
|||
@ -0,0 +1,6 @@ |
|||
import { IsUUID } from 'class-validator'; |
|||
|
|||
export class GenerateAuthenticationOptionsDto { |
|||
@IsUUID() |
|||
deviceId: string; |
|||
} |
|||
@ -0,0 +1,20 @@ |
|||
import { getOidcDiscoveryUrl } from './oidc.helper'; |
|||
|
|||
describe('getOidcDiscoveryUrl', () => { |
|||
it.each([ |
|||
[ |
|||
'https://auth.example.com', |
|||
'https://auth.example.com/.well-known/openid-configuration' |
|||
], |
|||
[ |
|||
'https://auth.example.com/', |
|||
'https://auth.example.com/.well-known/openid-configuration' |
|||
], |
|||
[ |
|||
'https://auth.example.com/application/o/ghostfolio/', |
|||
'https://auth.example.com/application/o/ghostfolio/.well-known/openid-configuration' |
|||
] |
|||
])('creates the discovery URL for %s', (issuer, expected) => { |
|||
expect(getOidcDiscoveryUrl(issuer)).toBe(expected); |
|||
}); |
|||
}); |
|||
@ -0,0 +1,4 @@ |
|||
export function getOidcDiscoveryUrl(issuer: string) { |
|||
// Remove trailing slashes
|
|||
return `${issuer.replace(/\/+$/, '')}/.well-known/openid-configuration`; |
|||
} |
|||
Some files were not shown because too many files changed in this diff
Loading…
Reference in new issue