mirror of https://github.com/ghostfolio/ghostfolio
Browse Source
- Login page (login.html) with email/password auth, error states, demo hint - /auth/login FastAPI endpoint with credential validation - /chat/steps SSE endpoint streaming real-time LangGraph node events - /me endpoint for user profile lookup - chat_ui.html: auth guard, sign-out, localStorage persistence, category quick prompts, live thinking panel, tool badges, confidence bar, verification badge, copy button, retry button, latency tracker, session summary toast, /tools command, message timestamps Co-authored-by: Cursor <cursoragent@cursor.com>pull/6453/head
1385 changed files with 6596 additions and 284820 deletions
@ -1,14 +0,0 @@ |
|||||
import { defineConfig } from '@prisma/config'; |
|
||||
import { config } from 'dotenv'; |
|
||||
import { expand } from 'dotenv-expand'; |
|
||||
import { join } from 'node:path'; |
|
||||
|
|
||||
expand(config({ quiet: true })); |
|
||||
|
|
||||
export default defineConfig({ |
|
||||
migrations: { |
|
||||
path: join(__dirname, '..', 'prisma', 'migrations'), |
|
||||
seed: `node ${join(__dirname, '..', 'prisma', 'seed.mts')}` |
|
||||
}, |
|
||||
schema: join(__dirname, '..', 'prisma', 'schema.prisma') |
|
||||
}); |
|
||||
@ -1,13 +0,0 @@ |
|||||
# Editor configuration, see http://editorconfig.org |
|
||||
root = true |
|
||||
|
|
||||
[*] |
|
||||
charset = utf-8 |
|
||||
indent_style = space |
|
||||
indent_size = 2 |
|
||||
insert_final_newline = true |
|
||||
trim_trailing_whitespace = true |
|
||||
|
|
||||
[*.md] |
|
||||
max_line_length = off |
|
||||
trim_trailing_whitespace = false |
|
||||
@ -1,24 +0,0 @@ |
|||||
COMPOSE_PROJECT_NAME=ghostfolio-development |
|
||||
|
|
||||
# CACHE |
|
||||
REDIS_HOST=localhost |
|
||||
REDIS_PORT=6379 |
|
||||
REDIS_PASSWORD=<INSERT_REDIS_PASSWORD> |
|
||||
|
|
||||
# POSTGRES |
|
||||
POSTGRES_DB=ghostfolio-db |
|
||||
POSTGRES_USER=user |
|
||||
POSTGRES_PASSWORD=<INSERT_POSTGRES_PASSWORD> |
|
||||
|
|
||||
# VARIOUS |
|
||||
ACCESS_TOKEN_SALT=<INSERT_RANDOM_STRING> |
|
||||
DATABASE_URL=postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:5432/${POSTGRES_DB}?connect_timeout=300&sslmode=prefer |
|
||||
JWT_SECRET_KEY=<INSERT_RANDOM_STRING> |
|
||||
|
|
||||
# DEVELOPMENT |
|
||||
|
|
||||
# Nx 18 enables using plugins to infer targets by default |
|
||||
# This is disabled for existing workspaces to maintain compatibility |
|
||||
# For more info, see: https://nx.dev/concepts/inferred-tasks |
|
||||
NX_ADD_PLUGINS=false |
|
||||
|
|
||||
@ -1,16 +1,13 @@ |
|||||
COMPOSE_PROJECT_NAME=ghostfolio |
# ── Anthropic (Required) ────────────────────────────────────────────────────── |
||||
|
# Get from: https://console.anthropic.com/settings/keys |
||||
|
ANTHROPIC_API_KEY= |
||||
|
|
||||
# CACHE |
# ── Ghostfolio (Required) ───────────────────────────────────────────────────── |
||||
REDIS_HOST=redis |
GHOSTFOLIO_BASE_URL=http://localhost:3333 |
||||
REDIS_PORT=6379 |
GHOSTFOLIO_BEARER_TOKEN= |
||||
REDIS_PASSWORD=<INSERT_REDIS_PASSWORD> |
|
||||
|
|
||||
# POSTGRES |
# ── LangSmith Observability (Required for tracing) ─────────────────────────── |
||||
POSTGRES_DB=ghostfolio-db |
# Get from: https://smith.langchain.com → Settings → API Keys |
||||
POSTGRES_USER=user |
LANGCHAIN_TRACING_V2=true |
||||
POSTGRES_PASSWORD=<INSERT_POSTGRES_PASSWORD> |
LANGCHAIN_API_KEY= |
||||
|
LANGCHAIN_PROJECT=ghostfolio-agent |
||||
# VARIOUS |
|
||||
ACCESS_TOKEN_SALT=<INSERT_RANDOM_STRING> |
|
||||
DATABASE_URL=postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB}?connect_timeout=300&sslmode=prefer |
|
||||
JWT_SECRET_KEY=<INSERT_RANDOM_STRING> |
|
||||
|
|||||
@ -1,2 +0,0 @@ |
|||||
buy_me_a_coffee: ghostfolio |
|
||||
github: ghostfolio |
|
||||
@ -1,53 +0,0 @@ |
|||||
--- |
|
||||
name: Bug report |
|
||||
about: Create a report to help us improve |
|
||||
title: '[BUG]' |
|
||||
labels: '' |
|
||||
assignees: '' |
|
||||
--- |
|
||||
|
|
||||
**Important Notice** |
|
||||
|
|
||||
The issue tracker is **ONLY** used for reporting bugs. New features should be discussed in our [Slack](https://join.slack.com/t/ghostfolio/shared_invite/zt-vsaan64h-F_I0fEo5M0P88lP9ibCxFg) community or in [Discussions](https://github.com/ghostfolio/ghostfolio/discussions). |
|
||||
|
|
||||
Incomplete or non-reproducible issues may be closed, but we are here to help! If you encounter difficulties reproducing the bug or need assistance, please reach out to our community channels mentioned above. |
|
||||
|
|
||||
Thank you for your understanding and cooperation! |
|
||||
|
|
||||
**Bug Description** |
|
||||
|
|
||||
<!-- A clear and concise description of what the bug is. --> |
|
||||
|
|
||||
**To Reproduce** |
|
||||
|
|
||||
<!-- Steps to reproduce the behavior --> |
|
||||
|
|
||||
1. |
|
||||
2. |
|
||||
3. |
|
||||
|
|
||||
**Expected Behavior** |
|
||||
|
|
||||
<!-- A clear and concise description of what you expected to happen. --> |
|
||||
|
|
||||
**Screenshots** |
|
||||
|
|
||||
<!-- If applicable, add screenshots to help explain your problem. --> |
|
||||
|
|
||||
**Logs** |
|
||||
|
|
||||
<!-- If applicable, add logs to help explain your problem. --> |
|
||||
|
|
||||
**Environment** |
|
||||
|
|
||||
<!-- Please complete the following information --> |
|
||||
|
|
||||
- Ghostfolio Version X.Y.Z |
|
||||
- Cloud or Self-hosted |
|
||||
- Experimental Features enabled or disabled |
|
||||
- Browser |
|
||||
- OS |
|
||||
|
|
||||
**Additional Context** |
|
||||
|
|
||||
<!-- Add any other context about the problem here. --> |
|
||||
@ -1,42 +0,0 @@ |
|||||
name: Build code |
|
||||
|
|
||||
on: |
|
||||
pull_request: |
|
||||
workflow_dispatch: |
|
||||
|
|
||||
permissions: |
|
||||
contents: read |
|
||||
|
|
||||
jobs: |
|
||||
build: |
|
||||
runs-on: ubuntu-latest |
|
||||
strategy: |
|
||||
matrix: |
|
||||
node_version: |
|
||||
- 22 |
|
||||
steps: |
|
||||
- name: Checkout code |
|
||||
uses: actions/checkout@v4 |
|
||||
with: |
|
||||
fetch-depth: 0 |
|
||||
|
|
||||
- name: Use Node.js ${{ matrix.node_version }} |
|
||||
uses: actions/setup-node@v4 |
|
||||
with: |
|
||||
node-version: ${{ matrix.node_version }} |
|
||||
cache: 'npm' |
|
||||
|
|
||||
- name: Install dependencies |
|
||||
run: npm ci |
|
||||
|
|
||||
- name: Check code style |
|
||||
run: npm run lint |
|
||||
|
|
||||
- name: Check formatting |
|
||||
run: npm run format:check |
|
||||
|
|
||||
- name: Execute tests |
|
||||
run: npm test |
|
||||
|
|
||||
- name: Build application |
|
||||
run: npm run build:production |
|
||||
@ -1,50 +0,0 @@ |
|||||
name: Docker image CD |
|
||||
|
|
||||
on: |
|
||||
push: |
|
||||
tags: |
|
||||
- '*.*.*' |
|
||||
pull_request: |
|
||||
branches: |
|
||||
- 'main' |
|
||||
|
|
||||
jobs: |
|
||||
build_and_push: |
|
||||
runs-on: ubuntu-latest |
|
||||
steps: |
|
||||
- name: Checkout code |
|
||||
uses: actions/checkout@v4 |
|
||||
|
|
||||
- name: Docker metadata |
|
||||
id: meta |
|
||||
uses: docker/metadata-action@v4 |
|
||||
with: |
|
||||
images: ${{ vars.DOCKER_REPOSITORY || 'ghostfolio/ghostfolio' }} |
|
||||
tags: | |
|
||||
type=semver,pattern={{major}} |
|
||||
type=semver,pattern={{version}} |
|
||||
|
|
||||
- name: Set up QEMU |
|
||||
uses: docker/setup-qemu-action@v2 |
|
||||
|
|
||||
- name: Set up Docker Buildx |
|
||||
id: buildx |
|
||||
uses: docker/setup-buildx-action@v2 |
|
||||
|
|
||||
- name: Login to DockerHub |
|
||||
if: github.event_name != 'pull_request' |
|
||||
uses: docker/login-action@v2 |
|
||||
with: |
|
||||
username: ${{ secrets.DOCKER_HUB_USERNAME }} |
|
||||
password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }} |
|
||||
|
|
||||
- name: Build and push |
|
||||
uses: docker/build-push-action@v3 |
|
||||
with: |
|
||||
context: . |
|
||||
platforms: linux/amd64,linux/arm/v7,linux/arm64 |
|
||||
push: ${{ github.event_name != 'pull_request' }} |
|
||||
tags: ${{ steps.meta.outputs.tags }} |
|
||||
labels: ${{ steps.meta.output.labels }} |
|
||||
cache-from: type=gha |
|
||||
cache-to: type=gha,mode=max |
|
||||
@ -1,40 +0,0 @@ |
|||||
name: Extract locales |
|
||||
|
|
||||
on: |
|
||||
push: |
|
||||
branches: |
|
||||
- main |
|
||||
|
|
||||
permissions: |
|
||||
contents: write |
|
||||
pull-requests: write |
|
||||
|
|
||||
jobs: |
|
||||
extract_locales: |
|
||||
runs-on: ubuntu-latest |
|
||||
steps: |
|
||||
- name: Checkout code |
|
||||
uses: actions/checkout@v4 |
|
||||
with: |
|
||||
fetch-depth: 0 |
|
||||
|
|
||||
- name: Install dependencies |
|
||||
run: npm ci |
|
||||
|
|
||||
- name: Extract locales |
|
||||
run: npm run extract-locales |
|
||||
|
|
||||
- name: Check changes |
|
||||
id: verify-changed-files |
|
||||
uses: tj-actions/verify-changed-files@v20 |
|
||||
|
|
||||
- name: Create pull request |
|
||||
if: steps.verify-changed-files.outputs.files_changed == 'true' |
|
||||
uses: peter-evans/create-pull-request@v7 |
|
||||
with: |
|
||||
author: 'github-actions[bot] <github-actions[bot]@users.noreply.github.com>' |
|
||||
branch: 'task/update-locales' |
|
||||
commit-message: 'Update locales' |
|
||||
delete-branch: true |
|
||||
title: 'Task/update locales' |
|
||||
token: ${{ secrets.GITHUB_TOKEN }} |
|
||||
@ -1,44 +1,31 @@ |
|||||
# See http://help.github.com/ignore-files/ for more about ignoring files. |
# Secrets — never commit |
||||
|
|
||||
# compiled output |
|
||||
/out-tsc |
|
||||
/tmp |
|
||||
|
|
||||
# dependencies |
|
||||
/node_modules |
|
||||
npm-debug.log |
|
||||
|
|
||||
# IDEs and editors |
|
||||
/.idea |
|
||||
.project |
|
||||
.classpath |
|
||||
.c9/ |
|
||||
*.launch |
|
||||
.settings/ |
|
||||
*.sublime-workspace |
|
||||
|
|
||||
# IDE - VSCode |
|
||||
.vscode/* |
|
||||
!.vscode/extensions.json |
|
||||
!.vscode/launch.json |
|
||||
!.vscode/settings.json |
|
||||
|
|
||||
# misc |
|
||||
/.angular/cache |
|
||||
.cursor/rules/nx-rules.mdc |
|
||||
.env |
.env |
||||
|
.env.local |
||||
.env.prod |
.env.prod |
||||
.github/instructions/nx.instructions.md |
|
||||
.nx/cache |
|
||||
.nx/workspace-data |
|
||||
/.sass-cache |
|
||||
/connect.lock |
|
||||
/coverage |
|
||||
/dist |
|
||||
/libpeerconnection.log |
|
||||
testem.log |
|
||||
/typings |
|
||||
|
|
||||
# System Files |
# Python |
||||
|
venv/ |
||||
|
__pycache__/ |
||||
|
*.py[cod] |
||||
|
*.pyo |
||||
|
*.pyd |
||||
|
.Python |
||||
|
*.egg-info/ |
||||
|
dist/ |
||||
|
build/ |
||||
|
.eggs/ |
||||
|
.pytest_cache/ |
||||
|
.mypy_cache/ |
||||
|
.ruff_cache/ |
||||
|
|
||||
|
# Eval artifacts (raw results — commit only if you want) |
||||
|
evals/results.json |
||||
|
|
||||
|
# OS |
||||
.DS_Store |
.DS_Store |
||||
Thumbs.db |
Thumbs.db |
||||
|
|
||||
|
# IDE |
||||
|
.idea/ |
||||
|
.vscode/ |
||||
|
*.swp |
||||
|
|||||
@ -1,6 +0,0 @@ |
|||||
# 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 |
|
||||
|
|
||||
# Check formatting on modified and uncommitted files, stop the commit if issues are found |
|
||||
npm run format:check --uncommitted || exit 1 |
|
||||
@ -1 +0,0 @@ |
|||||
v22 |
|
||||
@ -1,5 +0,0 @@ |
|||||
/.nx/cache |
|
||||
/.nx/workspace-data |
|
||||
/apps/client/src/polyfills.ts |
|
||||
/dist |
|
||||
/test/import |
|
||||
@ -1,37 +0,0 @@ |
|||||
{ |
|
||||
"attributeGroups": [ |
|
||||
"$ANGULAR_ELEMENT_REF", |
|
||||
"$ANGULAR_STRUCTURAL_DIRECTIVE", |
|
||||
"$DEFAULT", |
|
||||
"$ANGULAR_INPUT", |
|
||||
"$ANGULAR_TWO_WAY_BINDING", |
|
||||
"$ANGULAR_OUTPUT" |
|
||||
], |
|
||||
"attributeSort": "ASC", |
|
||||
"endOfLine": "auto", |
|
||||
"importOrder": ["^@ghostfolio/(.*)$", "<THIRD_PARTY_MODULES>", "^[./]"], |
|
||||
"importOrderSeparation": true, |
|
||||
"overrides": [ |
|
||||
{ |
|
||||
"files": "*.html", |
|
||||
"options": { |
|
||||
"parser": "angular" |
|
||||
} |
|
||||
}, |
|
||||
{ |
|
||||
"files": "*.ts", |
|
||||
"options": { |
|
||||
"importOrderParserPlugins": ["decorators-legacy", "typescript"] |
|
||||
} |
|
||||
} |
|
||||
], |
|
||||
"plugins": [ |
|
||||
"prettier-plugin-organize-attributes", |
|
||||
"@trivago/prettier-plugin-sort-imports" |
|
||||
], |
|
||||
"printWidth": 80, |
|
||||
"singleQuote": true, |
|
||||
"tabWidth": 2, |
|
||||
"trailingComma": "none", |
|
||||
"useTabs": false |
|
||||
} |
|
||||
@ -1,8 +0,0 @@ |
|||||
{ |
|
||||
"recommendations": [ |
|
||||
"angular.ng-template", |
|
||||
"esbenp.prettier-vscode", |
|
||||
"firsttris.vscode-jest-runner", |
|
||||
"nrwl.angular-console" |
|
||||
] |
|
||||
} |
|
||||
@ -1,34 +0,0 @@ |
|||||
{ |
|
||||
"version": "0.2.0", |
|
||||
"configurations": [ |
|
||||
{ |
|
||||
"args": [ |
|
||||
"test", |
|
||||
"--codeCoverage=false", |
|
||||
"--testFile=${workspaceFolder}/apps/api/src/app/portfolio/portfolio-calculator-novn-buy-and-sell.spec.ts" |
|
||||
], |
|
||||
"console": "internalConsole", |
|
||||
"cwd": "${workspaceFolder}", |
|
||||
"name": "Debug Jest", |
|
||||
"program": "${workspaceFolder}/node_modules/@nrwl/cli/bin/nx", |
|
||||
"request": "launch", |
|
||||
"type": "node" |
|
||||
}, |
|
||||
{ |
|
||||
"autoAttachChildProcesses": true, |
|
||||
"console": "integratedTerminal", |
|
||||
"cwd": "${workspaceFolder}/apps/api", |
|
||||
"envFile": "${workspaceFolder}/.env", |
|
||||
"name": "Debug API", |
|
||||
"outFiles": ["${workspaceFolder}/dist/apps/api/**/*.js"], |
|
||||
"program": "${workspaceFolder}/apps/api/src/main.ts", |
|
||||
"request": "launch", |
|
||||
"runtimeArgs": ["--nolazy", "-r", "ts-node/register"], |
|
||||
"skipFiles": [ |
|
||||
"${workspaceFolder}/node_modules/**/*.js", |
|
||||
"<node_internals>/**/*.js" |
|
||||
], |
|
||||
"type": "node" |
|
||||
} |
|
||||
] |
|
||||
} |
|
||||
@ -1,4 +0,0 @@ |
|||||
{ |
|
||||
"editor.defaultFormatter": "esbenp.prettier-vscode", |
|
||||
"editor.formatOnSave": true |
|
||||
} |
|
||||
File diff suppressed because it is too large
@ -1,122 +0,0 @@ |
|||||
# Ghostfolio Development Guide |
|
||||
|
|
||||
## Development Environment |
|
||||
|
|
||||
### Prerequisites |
|
||||
|
|
||||
- [Docker](https://www.docker.com/products/docker-desktop) |
|
||||
- [Node.js](https://nodejs.org/en/download) (version `>=22.18.0`) |
|
||||
- Create a local copy of this Git repository (clone) |
|
||||
- Copy the file `.env.dev` to `.env` and populate it with your data (`cp .env.dev .env`) |
|
||||
|
|
||||
### Setup |
|
||||
|
|
||||
1. Run `npm install` |
|
||||
1. Run `docker compose -f docker/docker-compose.dev.yml up -d` to start [PostgreSQL](https://www.postgresql.org) and [Redis](https://redis.io) |
|
||||
1. Run `npm run database:setup` to initialize the database schema |
|
||||
1. Start the [server](#start-server) and the [client](#start-client) |
|
||||
1. Open https://localhost:4200/en in your browser |
|
||||
1. Create a new user via _Get Started_ (this first user will get the role `ADMIN`) |
|
||||
|
|
||||
### Start Server |
|
||||
|
|
||||
#### Debug |
|
||||
|
|
||||
Run `npm run watch:server` and click _Debug API_ in [Visual Studio Code](https://code.visualstudio.com) |
|
||||
|
|
||||
#### Serve |
|
||||
|
|
||||
Run `npm run start:server` |
|
||||
|
|
||||
### Start Client |
|
||||
|
|
||||
#### English (Default) |
|
||||
|
|
||||
Run `npm run start:client` and open https://localhost:4200/en in your browser. |
|
||||
|
|
||||
#### Other Languages |
|
||||
|
|
||||
To start the client in a different language, such as German (`de`), adapt the `start:client` script in the `package.json` file by changing `--configuration=development-en` to `--configuration=development-de`. Then, run `npm run start:client` and open https://localhost:4200/de in your browser. |
|
||||
|
|
||||
### Start _Storybook_ |
|
||||
|
|
||||
Run `npm run start:storybook` |
|
||||
|
|
||||
### Migrate Database |
|
||||
|
|
||||
With the following command you can keep your database schema in sync: |
|
||||
|
|
||||
```bash |
|
||||
npm run database:push |
|
||||
``` |
|
||||
|
|
||||
## Testing |
|
||||
|
|
||||
Run `npm test` |
|
||||
|
|
||||
## Experimental Features |
|
||||
|
|
||||
New functionality can be enabled using a feature flag switch from the user settings. |
|
||||
|
|
||||
### Backend |
|
||||
|
|
||||
Remove permission in `UserService` using `without()` |
|
||||
|
|
||||
### Frontend |
|
||||
|
|
||||
Use `@if (user?.settings?.isExperimentalFeatures) {}` in HTML template |
|
||||
|
|
||||
## Component Library (_Storybook_) |
|
||||
|
|
||||
https://ghostfol.io/development/storybook |
|
||||
|
|
||||
## Git |
|
||||
|
|
||||
### Rebase |
|
||||
|
|
||||
`git rebase -i --autosquash main` |
|
||||
|
|
||||
## Dependencies |
|
||||
|
|
||||
### Angular |
|
||||
|
|
||||
#### Upgrade (minor versions) |
|
||||
|
|
||||
1. Run `npx npm-check-updates --upgrade --target "minor" --filter "/@angular.*/"` |
|
||||
|
|
||||
### Nx |
|
||||
|
|
||||
#### Upgrade |
|
||||
|
|
||||
1. Run `npx nx migrate latest` |
|
||||
1. Make sure `package.json` changes make sense and then run `npm install` |
|
||||
1. Run `npx nx migrate --run-migrations` |
|
||||
|
|
||||
### Prisma |
|
||||
|
|
||||
#### Access database via GUI |
|
||||
|
|
||||
Run `npm run database:gui` |
|
||||
|
|
||||
https://www.prisma.io/studio |
|
||||
|
|
||||
#### Synchronize schema with database for prototyping |
|
||||
|
|
||||
Run `npm run database:push` |
|
||||
|
|
||||
https://www.prisma.io/docs/concepts/components/prisma-migrate/db-push |
|
||||
|
|
||||
#### Create schema migration |
|
||||
|
|
||||
Run `npm run prisma migrate dev --name added_job_title` |
|
||||
|
|
||||
https://www.prisma.io/docs/concepts/components/prisma-migrate#getting-started-with-prisma-migrate |
|
||||
|
|
||||
## SSL |
|
||||
|
|
||||
Generate `localhost.cert` and `localhost.pem` files. |
|
||||
|
|
||||
``` |
|
||||
openssl req -x509 -newkey rsa:2048 -nodes -keyout apps/client/localhost.pem -out apps/client/localhost.cert -days 365 \ |
|
||||
-subj "/C=CH/ST=State/L=City/O=Organization/OU=Unit/CN=localhost" |
|
||||
``` |
|
||||
@ -1,66 +0,0 @@ |
|||||
FROM --platform=$BUILDPLATFORM node:22-slim AS builder |
|
||||
|
|
||||
# Build application and add additional files |
|
||||
WORKDIR /ghostfolio |
|
||||
|
|
||||
RUN apt-get update && apt-get install -y --no-install-suggests \ |
|
||||
g++ \ |
|
||||
git \ |
|
||||
make \ |
|
||||
openssl \ |
|
||||
python3 \ |
|
||||
&& rm -rf /var/lib/apt/lists/* |
|
||||
|
|
||||
# Only add basic files without the application itself to avoid rebuilding |
|
||||
# layers when files (package.json etc.) have not changed |
|
||||
COPY ./.config .config/ |
|
||||
COPY ./CHANGELOG.md CHANGELOG.md |
|
||||
COPY ./LICENSE LICENSE |
|
||||
COPY ./package.json package.json |
|
||||
COPY ./package-lock.json package-lock.json |
|
||||
COPY ./prisma/schema.prisma prisma/ |
|
||||
|
|
||||
RUN npm install |
|
||||
|
|
||||
COPY ./apps apps/ |
|
||||
COPY ./libs libs/ |
|
||||
COPY ./jest.config.ts jest.config.ts |
|
||||
COPY ./jest.preset.js jest.preset.js |
|
||||
COPY ./nx.json nx.json |
|
||||
COPY ./replace.build.mjs replace.build.mjs |
|
||||
COPY ./tsconfig.base.json tsconfig.base.json |
|
||||
|
|
||||
ENV NX_DAEMON=false |
|
||||
RUN npm run build:production |
|
||||
|
|
||||
# Prepare the dist image with additional node_modules |
|
||||
WORKDIR /ghostfolio/dist/apps/api |
|
||||
# package.json was generated by the build process, however the original |
|
||||
# package-lock.json needs to be used to ensure the same versions |
|
||||
COPY ./package-lock.json /ghostfolio/dist/apps/api/ |
|
||||
|
|
||||
RUN npm install |
|
||||
COPY .config /ghostfolio/dist/apps/api/.config/ |
|
||||
COPY prisma /ghostfolio/dist/apps/api/prisma/ |
|
||||
|
|
||||
# Overwrite the generated package.json with the original one to ensure having |
|
||||
# all the scripts |
|
||||
COPY package.json /ghostfolio/dist/apps/api/ |
|
||||
RUN npm run database:generate-typings |
|
||||
|
|
||||
# Image to run, copy everything needed from builder |
|
||||
FROM node:22-slim |
|
||||
LABEL org.opencontainers.image.source="https://github.com/ghostfolio/ghostfolio" |
|
||||
ENV NODE_ENV=production |
|
||||
|
|
||||
RUN apt-get update && apt-get install -y --no-install-suggests \ |
|
||||
curl \ |
|
||||
openssl \ |
|
||||
&& rm -rf /var/lib/apt/lists/* |
|
||||
|
|
||||
COPY --chown=node:node --from=builder /ghostfolio/dist/apps /ghostfolio/apps/ |
|
||||
COPY --chown=node:node ./docker/entrypoint.sh /ghostfolio/ |
|
||||
WORKDIR /ghostfolio/apps/api |
|
||||
EXPOSE ${PORT:-3333} |
|
||||
USER node |
|
||||
CMD [ "/ghostfolio/entrypoint.sh" ] |
|
||||
@ -1,617 +0,0 @@ |
|||||
GNU AFFERO GENERAL PUBLIC LICENSE |
|
||||
Version 3, 19 November 2007 |
|
||||
|
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> |
|
||||
Everyone is permitted to copy and distribute verbatim copies |
|
||||
of this license document, but changing it is not allowed. |
|
||||
|
|
||||
Preamble |
|
||||
|
|
||||
The GNU Affero General Public License is a free, copyleft license for |
|
||||
software and other kinds of works, specifically designed to ensure |
|
||||
cooperation with the community in the case of network server software. |
|
||||
|
|
||||
The licenses for most software and other practical works are designed |
|
||||
to take away your freedom to share and change the works. By contrast, |
|
||||
our General Public Licenses are intended to guarantee your freedom to |
|
||||
share and change all versions of a program--to make sure it remains free |
|
||||
software for all its users. |
|
||||
|
|
||||
When we speak of free software, we are referring to freedom, not |
|
||||
price. Our General Public Licenses are designed to make sure that you |
|
||||
have the freedom to distribute copies of free software (and charge for |
|
||||
them if you wish), that you receive source code or can get it if you |
|
||||
want it, that you can change the software or use pieces of it in new |
|
||||
free programs, and that you know you can do these things. |
|
||||
|
|
||||
Developers that use our General Public Licenses protect your rights |
|
||||
with two steps: (1) assert copyright on the software, and (2) offer |
|
||||
you this License which gives you legal permission to copy, distribute |
|
||||
and/or modify the software. |
|
||||
|
|
||||
A secondary benefit of defending all users' freedom is that |
|
||||
improvements made in alternate versions of the program, if they |
|
||||
receive widespread use, become available for other developers to |
|
||||
incorporate. Many developers of free software are heartened and |
|
||||
encouraged by the resulting cooperation. However, in the case of |
|
||||
software used on network servers, this result may fail to come about. |
|
||||
The GNU General Public License permits making a modified version and |
|
||||
letting the public access it on a server without ever releasing its |
|
||||
source code to the public. |
|
||||
|
|
||||
The GNU Affero General Public License is designed specifically to |
|
||||
ensure that, in such cases, the modified source code becomes available |
|
||||
to the community. It requires the operator of a network server to |
|
||||
provide the source code of the modified version running there to the |
|
||||
users of that server. Therefore, public use of a modified version, on |
|
||||
a publicly accessible server, gives the public access to the source |
|
||||
code of the modified version. |
|
||||
|
|
||||
An older license, called the Affero General Public License and |
|
||||
published by Affero, was designed to accomplish similar goals. This is |
|
||||
a different license, not a version of the Affero GPL, but Affero has |
|
||||
released a new version of the Affero GPL which permits relicensing under |
|
||||
this license. |
|
||||
|
|
||||
The precise terms and conditions for copying, distribution and |
|
||||
modification follow. |
|
||||
|
|
||||
TERMS AND CONDITIONS |
|
||||
|
|
||||
0. Definitions. |
|
||||
|
|
||||
"This License" refers to version 3 of the GNU Affero General Public License. |
|
||||
|
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of |
|
||||
works, such as semiconductor masks. |
|
||||
|
|
||||
"The Program" refers to any copyrightable work licensed under this |
|
||||
License. Each licensee is addressed as "you". "Licensees" and |
|
||||
"recipients" may be individuals or organizations. |
|
||||
|
|
||||
To "modify" a work means to copy from or adapt all or part of the work |
|
||||
in a fashion requiring copyright permission, other than the making of an |
|
||||
exact copy. The resulting work is called a "modified version" of the |
|
||||
earlier work or a work "based on" the earlier work. |
|
||||
|
|
||||
A "covered work" means either the unmodified Program or a work based |
|
||||
on the Program. |
|
||||
|
|
||||
To "propagate" a work means to do anything with it that, without |
|
||||
permission, would make you directly or secondarily liable for |
|
||||
infringement under applicable copyright law, except executing it on a |
|
||||
computer or modifying a private copy. Propagation includes copying, |
|
||||
distribution (with or without modification), making available to the |
|
||||
public, and in some countries other activities as well. |
|
||||
|
|
||||
To "convey" a work means any kind of propagation that enables other |
|
||||
parties to make or receive copies. Mere interaction with a user through |
|
||||
a computer network, with no transfer of a copy, is not conveying. |
|
||||
|
|
||||
An interactive user interface displays "Appropriate Legal Notices" |
|
||||
to the extent that it includes a convenient and prominently visible |
|
||||
feature that (1) displays an appropriate copyright notice, and (2) |
|
||||
tells the user that there is no warranty for the work (except to the |
|
||||
extent that warranties are provided), that licensees may convey the |
|
||||
work under this License, and how to view a copy of this License. If |
|
||||
the interface presents a list of user commands or options, such as a |
|
||||
menu, a prominent item in the list meets this criterion. |
|
||||
|
|
||||
1. Source Code. |
|
||||
|
|
||||
The "source code" for a work means the preferred form of the work |
|
||||
for making modifications to it. "Object code" means any non-source |
|
||||
form of a work. |
|
||||
|
|
||||
A "Standard Interface" means an interface that either is an official |
|
||||
standard defined by a recognized standards body, or, in the case of |
|
||||
interfaces specified for a particular programming language, one that |
|
||||
is widely used among developers working in that language. |
|
||||
|
|
||||
The "System Libraries" of an executable work include anything, other |
|
||||
than the work as a whole, that (a) is included in the normal form of |
|
||||
packaging a Major Component, but which is not part of that Major |
|
||||
Component, and (b) serves only to enable use of the work with that |
|
||||
Major Component, or to implement a Standard Interface for which an |
|
||||
implementation is available to the public in source code form. A |
|
||||
"Major Component", in this context, means a major essential component |
|
||||
(kernel, window system, and so on) of the specific operating system |
|
||||
(if any) on which the executable work runs, or a compiler used to |
|
||||
produce the work, or an object code interpreter used to run it. |
|
||||
|
|
||||
The "Corresponding Source" for a work in object code form means all |
|
||||
the source code needed to generate, install, and (for an executable |
|
||||
work) run the object code and to modify the work, including scripts to |
|
||||
control those activities. However, it does not include the work's |
|
||||
System Libraries, or general-purpose tools or generally available free |
|
||||
programs which are used unmodified in performing those activities but |
|
||||
which are not part of the work. For example, Corresponding Source |
|
||||
includes interface definition files associated with source files for |
|
||||
the work, and the source code for shared libraries and dynamically |
|
||||
linked subprograms that the work is specifically designed to require, |
|
||||
such as by intimate data communication or control flow between those |
|
||||
subprograms and other parts of the work. |
|
||||
|
|
||||
The Corresponding Source need not include anything that users |
|
||||
can regenerate automatically from other parts of the Corresponding |
|
||||
Source. |
|
||||
|
|
||||
The Corresponding Source for a work in source code form is that |
|
||||
same work. |
|
||||
|
|
||||
2. Basic Permissions. |
|
||||
|
|
||||
All rights granted under this License are granted for the term of |
|
||||
copyright on the Program, and are irrevocable provided the stated |
|
||||
conditions are met. This License explicitly affirms your unlimited |
|
||||
permission to run the unmodified Program. The output from running a |
|
||||
covered work is covered by this License only if the output, given its |
|
||||
content, constitutes a covered work. This License acknowledges your |
|
||||
rights of fair use or other equivalent, as provided by copyright law. |
|
||||
|
|
||||
You may make, run and propagate covered works that you do not |
|
||||
convey, without conditions so long as your license otherwise remains |
|
||||
in force. You may convey covered works to others for the sole purpose |
|
||||
of having them make modifications exclusively for you, or provide you |
|
||||
with facilities for running those works, provided that you comply with |
|
||||
the terms of this License in conveying all material for which you do |
|
||||
not control copyright. Those thus making or running the covered works |
|
||||
for you must do so exclusively on your behalf, under your direction |
|
||||
and control, on terms that prohibit them from making any copies of |
|
||||
your copyrighted material outside their relationship with you. |
|
||||
|
|
||||
Conveying under any other circumstances is permitted solely under |
|
||||
the conditions stated below. Sublicensing is not allowed; section 10 |
|
||||
makes it unnecessary. |
|
||||
|
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law. |
|
||||
|
|
||||
No covered work shall be deemed part of an effective technological |
|
||||
measure under any applicable law fulfilling obligations under article |
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or |
|
||||
similar laws prohibiting or restricting circumvention of such |
|
||||
measures. |
|
||||
|
|
||||
When you convey a covered work, you waive any legal power to forbid |
|
||||
circumvention of technological measures to the extent such circumvention |
|
||||
is effected by exercising rights under this License with respect to |
|
||||
the covered work, and you disclaim any intention to limit operation or |
|
||||
modification of the work as a means of enforcing, against the work's |
|
||||
users, your or third parties' legal rights to forbid circumvention of |
|
||||
technological measures. |
|
||||
|
|
||||
4. Conveying Verbatim Copies. |
|
||||
|
|
||||
You may convey verbatim copies of the Program's source code as you |
|
||||
receive it, in any medium, provided that you conspicuously and |
|
||||
appropriately publish on each copy an appropriate copyright notice; |
|
||||
keep intact all notices stating that this License and any |
|
||||
non-permissive terms added in accord with section 7 apply to the code; |
|
||||
keep intact all notices of the absence of any warranty; and give all |
|
||||
recipients a copy of this License along with the Program. |
|
||||
|
|
||||
You may charge any price or no price for each copy that you convey, |
|
||||
and you may offer support or warranty protection for a fee. |
|
||||
|
|
||||
5. Conveying Modified Source Versions. |
|
||||
|
|
||||
You may convey a work based on the Program, or the modifications to |
|
||||
produce it from the Program, in the form of source code under the |
|
||||
terms of section 4, provided that you also meet all of these conditions: |
|
||||
|
|
||||
a) The work must carry prominent notices stating that you modified |
|
||||
it, and giving a relevant date. |
|
||||
|
|
||||
b) The work must carry prominent notices stating that it is |
|
||||
released under this License and any conditions added under section |
|
||||
7. This requirement modifies the requirement in section 4 to |
|
||||
"keep intact all notices". |
|
||||
|
|
||||
c) You must license the entire work, as a whole, under this |
|
||||
License to anyone who comes into possession of a copy. This |
|
||||
License will therefore apply, along with any applicable section 7 |
|
||||
additional terms, to the whole of the work, and all its parts, |
|
||||
regardless of how they are packaged. This License gives no |
|
||||
permission to license the work in any other way, but it does not |
|
||||
invalidate such permission if you have separately received it. |
|
||||
|
|
||||
d) If the work has interactive user interfaces, each must display |
|
||||
Appropriate Legal Notices; however, if the Program has interactive |
|
||||
interfaces that do not display Appropriate Legal Notices, your |
|
||||
work need not make them do so. |
|
||||
|
|
||||
A compilation of a covered work with other separate and independent |
|
||||
works, which are not by their nature extensions of the covered work, |
|
||||
and which are not combined with it such as to form a larger program, |
|
||||
in or on a volume of a storage or distribution medium, is called an |
|
||||
"aggregate" if the compilation and its resulting copyright are not |
|
||||
used to limit the access or legal rights of the compilation's users |
|
||||
beyond what the individual works permit. Inclusion of a covered work |
|
||||
in an aggregate does not cause this License to apply to the other |
|
||||
parts of the aggregate. |
|
||||
|
|
||||
6. Conveying Non-Source Forms. |
|
||||
|
|
||||
You may convey a covered work in object code form under the terms |
|
||||
of sections 4 and 5, provided that you also convey the |
|
||||
machine-readable Corresponding Source under the terms of this License, |
|
||||
in one of these ways: |
|
||||
|
|
||||
a) Convey the object code in, or embodied in, a physical product |
|
||||
(including a physical distribution medium), accompanied by the |
|
||||
Corresponding Source fixed on a durable physical medium |
|
||||
customarily used for software interchange. |
|
||||
|
|
||||
b) Convey the object code in, or embodied in, a physical product |
|
||||
(including a physical distribution medium), accompanied by a |
|
||||
written offer, valid for at least three years and valid for as |
|
||||
long as you offer spare parts or customer support for that product |
|
||||
model, to give anyone who possesses the object code either (1) a |
|
||||
copy of the Corresponding Source for all the software in the |
|
||||
product that is covered by this License, on a durable physical |
|
||||
medium customarily used for software interchange, for a price no |
|
||||
more than your reasonable cost of physically performing this |
|
||||
conveying of source, or (2) access to copy the |
|
||||
Corresponding Source from a network server at no charge. |
|
||||
|
|
||||
c) Convey individual copies of the object code with a copy of the |
|
||||
written offer to provide the Corresponding Source. This |
|
||||
alternative is allowed only occasionally and noncommercially, and |
|
||||
only if you received the object code with such an offer, in accord |
|
||||
with subsection 6b. |
|
||||
|
|
||||
d) Convey the object code by offering access from a designated |
|
||||
place (gratis or for a charge), and offer equivalent access to the |
|
||||
Corresponding Source in the same way through the same place at no |
|
||||
further charge. You need not require recipients to copy the |
|
||||
Corresponding Source along with the object code. If the place to |
|
||||
copy the object code is a network server, the Corresponding Source |
|
||||
may be on a different server (operated by you or a third party) |
|
||||
that supports equivalent copying facilities, provided you maintain |
|
||||
clear directions next to the object code saying where to find the |
|
||||
Corresponding Source. Regardless of what server hosts the |
|
||||
Corresponding Source, you remain obligated to ensure that it is |
|
||||
available for as long as needed to satisfy these requirements. |
|
||||
|
|
||||
e) Convey the object code using peer-to-peer transmission, provided |
|
||||
you inform other peers where the object code and Corresponding |
|
||||
Source of the work are being offered to the general public at no |
|
||||
charge under subsection 6d. |
|
||||
|
|
||||
A separable portion of the object code, whose source code is excluded |
|
||||
from the Corresponding Source as a System Library, need not be |
|
||||
included in conveying the object code work. |
|
||||
|
|
||||
A "User Product" is either (1) a "consumer product", which means any |
|
||||
tangible personal property which is normally used for personal, family, |
|
||||
or household purposes, or (2) anything designed or sold for incorporation |
|
||||
into a dwelling. In determining whether a product is a consumer product, |
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular |
|
||||
product received by a particular user, "normally used" refers to a |
|
||||
typical or common use of that class of product, regardless of the status |
|
||||
of the particular user or of the way in which the particular user |
|
||||
actually uses, or expects or is expected to use, the product. A product |
|
||||
is a consumer product regardless of whether the product has substantial |
|
||||
commercial, industrial or non-consumer uses, unless such uses represent |
|
||||
the only significant mode of use of the product. |
|
||||
|
|
||||
"Installation Information" for a User Product means any methods, |
|
||||
procedures, authorization keys, or other information required to install |
|
||||
and execute modified versions of a covered work in that User Product from |
|
||||
a modified version of its Corresponding Source. The information must |
|
||||
suffice to ensure that the continued functioning of the modified object |
|
||||
code is in no case prevented or interfered with solely because |
|
||||
modification has been made. |
|
||||
|
|
||||
If you convey an object code work under this section in, or with, or |
|
||||
specifically for use in, a User Product, and the conveying occurs as |
|
||||
part of a transaction in which the right of possession and use of the |
|
||||
User Product is transferred to the recipient in perpetuity or for a |
|
||||
fixed term (regardless of how the transaction is characterized), the |
|
||||
Corresponding Source conveyed under this section must be accompanied |
|
||||
by the Installation Information. But this requirement does not apply |
|
||||
if neither you nor any third party retains the ability to install |
|
||||
modified object code on the User Product (for example, the work has |
|
||||
been installed in ROM). |
|
||||
|
|
||||
The requirement to provide Installation Information does not include a |
|
||||
requirement to continue to provide support service, warranty, or updates |
|
||||
for a work that has been modified or installed by the recipient, or for |
|
||||
the User Product in which it has been modified or installed. Access to a |
|
||||
network may be denied when the modification itself materially and |
|
||||
adversely affects the operation of the network or violates the rules and |
|
||||
protocols for communication across the network. |
|
||||
|
|
||||
Corresponding Source conveyed, and Installation Information provided, |
|
||||
in accord with this section must be in a format that is publicly |
|
||||
documented (and with an implementation available to the public in |
|
||||
source code form), and must require no special password or key for |
|
||||
unpacking, reading or copying. |
|
||||
|
|
||||
7. Additional Terms. |
|
||||
|
|
||||
"Additional permissions" are terms that supplement the terms of this |
|
||||
License by making exceptions from one or more of its conditions. |
|
||||
Additional permissions that are applicable to the entire Program shall |
|
||||
be treated as though they were included in this License, to the extent |
|
||||
that they are valid under applicable law. If additional permissions |
|
||||
apply only to part of the Program, that part may be used separately |
|
||||
under those permissions, but the entire Program remains governed by |
|
||||
this License without regard to the additional permissions. |
|
||||
|
|
||||
When you convey a copy of a covered work, you may at your option |
|
||||
remove any additional permissions from that copy, or from any part of |
|
||||
it. (Additional permissions may be written to require their own |
|
||||
removal in certain cases when you modify the work.) You may place |
|
||||
additional permissions on material, added by you to a covered work, |
|
||||
for which you have or can give appropriate copyright permission. |
|
||||
|
|
||||
Notwithstanding any other provision of this License, for material you |
|
||||
add to a covered work, you may (if authorized by the copyright holders of |
|
||||
that material) supplement the terms of this License with terms: |
|
||||
|
|
||||
a) Disclaiming warranty or limiting liability differently from the |
|
||||
terms of sections 15 and 16 of this License; or |
|
||||
|
|
||||
b) Requiring preservation of specified reasonable legal notices or |
|
||||
author attributions in that material or in the Appropriate Legal |
|
||||
Notices displayed by works containing it; or |
|
||||
|
|
||||
c) Prohibiting misrepresentation of the origin of that material, or |
|
||||
requiring that modified versions of such material be marked in |
|
||||
reasonable ways as different from the original version; or |
|
||||
|
|
||||
d) Limiting the use for publicity purposes of names of licensors or |
|
||||
authors of the material; or |
|
||||
|
|
||||
e) Declining to grant rights under trademark law for use of some |
|
||||
trade names, trademarks, or service marks; or |
|
||||
|
|
||||
f) Requiring indemnification of licensors and authors of that |
|
||||
material by anyone who conveys the material (or modified versions of |
|
||||
it) with contractual assumptions of liability to the recipient, for |
|
||||
any liability that these contractual assumptions directly impose on |
|
||||
those licensors and authors. |
|
||||
|
|
||||
All other non-permissive additional terms are considered "further |
|
||||
restrictions" within the meaning of section 10. If the Program as you |
|
||||
received it, or any part of it, contains a notice stating that it is |
|
||||
governed by this License along with a term that is a further |
|
||||
restriction, you may remove that term. If a license document contains |
|
||||
a further restriction but permits relicensing or conveying under this |
|
||||
License, you may add to a covered work material governed by the terms |
|
||||
of that license document, provided that the further restriction does |
|
||||
not survive such relicensing or conveying. |
|
||||
|
|
||||
If you add terms to a covered work in accord with this section, you |
|
||||
must place, in the relevant source files, a statement of the |
|
||||
additional terms that apply to those files, or a notice indicating |
|
||||
where to find the applicable terms. |
|
||||
|
|
||||
Additional terms, permissive or non-permissive, may be stated in the |
|
||||
form of a separately written license, or stated as exceptions; |
|
||||
the above requirements apply either way. |
|
||||
|
|
||||
8. Termination. |
|
||||
|
|
||||
You may not propagate or modify a covered work except as expressly |
|
||||
provided under this License. Any attempt otherwise to propagate or |
|
||||
modify it is void, and will automatically terminate your rights under |
|
||||
this License (including any patent licenses granted under the third |
|
||||
paragraph of section 11). |
|
||||
|
|
||||
However, if you cease all violation of this License, then your |
|
||||
license from a particular copyright holder is reinstated (a) |
|
||||
provisionally, unless and until the copyright holder explicitly and |
|
||||
finally terminates your license, and (b) permanently, if the copyright |
|
||||
holder fails to notify you of the violation by some reasonable means |
|
||||
prior to 60 days after the cessation. |
|
||||
|
|
||||
Moreover, your license from a particular copyright holder is |
|
||||
reinstated permanently if the copyright holder notifies you of the |
|
||||
violation by some reasonable means, this is the first time you have |
|
||||
received notice of violation of this License (for any work) from that |
|
||||
copyright holder, and you cure the violation prior to 30 days after |
|
||||
your receipt of the notice. |
|
||||
|
|
||||
Termination of your rights under this section does not terminate the |
|
||||
licenses of parties who have received copies or rights from you under |
|
||||
this License. If your rights have been terminated and not permanently |
|
||||
reinstated, you do not qualify to receive new licenses for the same |
|
||||
material under section 10. |
|
||||
|
|
||||
9. Acceptance Not Required for Having Copies. |
|
||||
|
|
||||
You are not required to accept this License in order to receive or |
|
||||
run a copy of the Program. Ancillary propagation of a covered work |
|
||||
occurring solely as a consequence of using peer-to-peer transmission |
|
||||
to receive a copy likewise does not require acceptance. However, |
|
||||
nothing other than this License grants you permission to propagate or |
|
||||
modify any covered work. These actions infringe copyright if you do |
|
||||
not accept this License. Therefore, by modifying or propagating a |
|
||||
covered work, you indicate your acceptance of this License to do so. |
|
||||
|
|
||||
10. Automatic Licensing of Downstream Recipients. |
|
||||
|
|
||||
Each time you convey a covered work, the recipient automatically |
|
||||
receives a license from the original licensors, to run, modify and |
|
||||
propagate that work, subject to this License. You are not responsible |
|
||||
for enforcing compliance by third parties with this License. |
|
||||
|
|
||||
An "entity transaction" is a transaction transferring control of an |
|
||||
organization, or substantially all assets of one, or subdividing an |
|
||||
organization, or merging organizations. If propagation of a covered |
|
||||
work results from an entity transaction, each party to that |
|
||||
transaction who receives a copy of the work also receives whatever |
|
||||
licenses to the work the party's predecessor in interest had or could |
|
||||
give under the previous paragraph, plus a right to possession of the |
|
||||
Corresponding Source of the work from the predecessor in interest, if |
|
||||
the predecessor has it or can get it with reasonable efforts. |
|
||||
|
|
||||
You may not impose any further restrictions on the exercise of the |
|
||||
rights granted or affirmed under this License. For example, you may |
|
||||
not impose a license fee, royalty, or other charge for exercise of |
|
||||
rights granted under this License, and you may not initiate litigation |
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that |
|
||||
any patent claim is infringed by making, using, selling, offering for |
|
||||
sale, or importing the Program or any portion of it. |
|
||||
|
|
||||
11. Patents. |
|
||||
|
|
||||
A "contributor" is a copyright holder who authorizes use under this |
|
||||
License of the Program or a work on which the Program is based. The |
|
||||
work thus licensed is called the contributor's "contributor version". |
|
||||
|
|
||||
A contributor's "essential patent claims" are all patent claims |
|
||||
owned or controlled by the contributor, whether already acquired or |
|
||||
hereafter acquired, that would be infringed by some manner, permitted |
|
||||
by this License, of making, using, or selling its contributor version, |
|
||||
but do not include claims that would be infringed only as a |
|
||||
consequence of further modification of the contributor version. For |
|
||||
purposes of this definition, "control" includes the right to grant |
|
||||
patent sublicenses in a manner consistent with the requirements of |
|
||||
this License. |
|
||||
|
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free |
|
||||
patent license under the contributor's essential patent claims, to |
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and |
|
||||
propagate the contents of its contributor version. |
|
||||
|
|
||||
In the following three paragraphs, a "patent license" is any express |
|
||||
agreement or commitment, however denominated, not to enforce a patent |
|
||||
(such as an express permission to practice a patent or covenant not to |
|
||||
sue for patent infringement). To "grant" such a patent license to a |
|
||||
party means to make such an agreement or commitment not to enforce a |
|
||||
patent against the party. |
|
||||
|
|
||||
If you convey a covered work, knowingly relying on a patent license, |
|
||||
and the Corresponding Source of the work is not available for anyone |
|
||||
to copy, free of charge and under the terms of this License, through a |
|
||||
publicly available network server or other readily accessible means, |
|
||||
then you must either (1) cause the Corresponding Source to be so |
|
||||
available, or (2) arrange to deprive yourself of the benefit of the |
|
||||
patent license for this particular work, or (3) arrange, in a manner |
|
||||
consistent with the requirements of this License, to extend the patent |
|
||||
license to downstream recipients. "Knowingly relying" means you have |
|
||||
actual knowledge that, but for the patent license, your conveying the |
|
||||
covered work in a country, or your recipient's use of the covered work |
|
||||
in a country, would infringe one or more identifiable patents in that |
|
||||
country that you have reason to believe are valid. |
|
||||
|
|
||||
If, pursuant to or in connection with a single transaction or |
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a |
|
||||
covered work, and grant a patent license to some of the parties |
|
||||
receiving the covered work authorizing them to use, propagate, modify |
|
||||
or convey a specific copy of the covered work, then the patent license |
|
||||
you grant is automatically extended to all recipients of the covered |
|
||||
work and works based on it. |
|
||||
|
|
||||
A patent license is "discriminatory" if it does not include within |
|
||||
the scope of its coverage, prohibits the exercise of, or is |
|
||||
conditioned on the non-exercise of one or more of the rights that are |
|
||||
specifically granted under this License. You may not convey a covered |
|
||||
work if you are a party to an arrangement with a third party that is |
|
||||
in the business of distributing software, under which you make payment |
|
||||
to the third party based on the extent of your activity of conveying |
|
||||
the work, and under which the third party grants, to any of the |
|
||||
parties who would receive the covered work from you, a discriminatory |
|
||||
patent license (a) in connection with copies of the covered work |
|
||||
conveyed by you (or copies made from those copies), or (b) primarily |
|
||||
for and in connection with specific products or compilations that |
|
||||
contain the covered work, unless you entered into that arrangement, |
|
||||
or that patent license was granted, prior to 28 March 2007. |
|
||||
|
|
||||
Nothing in this License shall be construed as excluding or limiting |
|
||||
any implied license or other defenses to infringement that may |
|
||||
otherwise be available to you under applicable patent law. |
|
||||
|
|
||||
12. No Surrender of Others' Freedom. |
|
||||
|
|
||||
If conditions are imposed on you (whether by court order, agreement or |
|
||||
otherwise) that contradict the conditions of this License, they do not |
|
||||
excuse you from the conditions of this License. If you cannot convey a |
|
||||
covered work so as to satisfy simultaneously your obligations under this |
|
||||
License and any other pertinent obligations, then as a consequence you may |
|
||||
not convey it at all. For example, if you agree to terms that obligate you |
|
||||
to collect a royalty for further conveying from those to whom you convey |
|
||||
the Program, the only way you could satisfy both those terms and this |
|
||||
License would be to refrain entirely from conveying the Program. |
|
||||
|
|
||||
13. Remote Network Interaction; Use with the GNU General Public License. |
|
||||
|
|
||||
Notwithstanding any other provision of this License, if you modify the |
|
||||
Program, your modified version must prominently offer all users |
|
||||
interacting with it remotely through a computer network (if your version |
|
||||
supports such interaction) an opportunity to receive the Corresponding |
|
||||
Source of your version by providing access to the Corresponding Source |
|
||||
from a network server at no charge, through some standard or customary |
|
||||
means of facilitating copying of software. This Corresponding Source |
|
||||
shall include the Corresponding Source for any work covered by version 3 |
|
||||
of the GNU General Public License that is incorporated pursuant to the |
|
||||
following paragraph. |
|
||||
|
|
||||
Notwithstanding any other provision of this License, you have |
|
||||
permission to link or combine any covered work with a work licensed |
|
||||
under version 3 of the GNU General Public License into a single |
|
||||
combined work, and to convey the resulting work. The terms of this |
|
||||
License will continue to apply to the part which is the covered work, |
|
||||
but the work with which it is combined will remain governed by version |
|
||||
3 of the GNU General Public License. |
|
||||
|
|
||||
14. Revised Versions of this License. |
|
||||
|
|
||||
The Free Software Foundation may publish revised and/or new versions of |
|
||||
the GNU Affero General Public License from time to time. Such new versions |
|
||||
will be similar in spirit to the present version, but may differ in detail to |
|
||||
address new problems or concerns. |
|
||||
|
|
||||
Each version is given a distinguishing version number. If the |
|
||||
Program specifies that a certain numbered version of the GNU Affero General |
|
||||
Public License "or any later version" applies to it, you have the |
|
||||
option of following the terms and conditions either of that numbered |
|
||||
version or of any later version published by the Free Software |
|
||||
Foundation. If the Program does not specify a version number of the |
|
||||
GNU Affero General Public License, you may choose any version ever published |
|
||||
by the Free Software Foundation. |
|
||||
|
|
||||
If the Program specifies that a proxy can decide which future |
|
||||
versions of the GNU Affero General Public License can be used, that proxy's |
|
||||
public statement of acceptance of a version permanently authorizes you |
|
||||
to choose that version for the Program. |
|
||||
|
|
||||
Later license versions may give you additional or different |
|
||||
permissions. However, no additional obligations are imposed on any |
|
||||
author or copyright holder as a result of your choosing to follow a |
|
||||
later version. |
|
||||
|
|
||||
15. Disclaimer of Warranty. |
|
||||
|
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY |
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT |
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY |
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, |
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR |
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM |
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF |
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION. |
|
||||
|
|
||||
16. Limitation of Liability. |
|
||||
|
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING |
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS |
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY |
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE |
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF |
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD |
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), |
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF |
|
||||
SUCH DAMAGES. |
|
||||
|
|
||||
17. Interpretation of Sections 15 and 16. |
|
||||
|
|
||||
If the disclaimer of warranty and limitation of liability provided |
|
||||
above cannot be given local legal effect according to their terms, |
|
||||
reviewing courts shall apply local law that most closely approximates |
|
||||
an absolute waiver of all civil liability in connection with the |
|
||||
Program, unless a warranty or assumption of liability accompanies a |
|
||||
copy of the Program in return for a fee. |
|
||||
@ -0,0 +1 @@ |
|||||
|
web: uvicorn main:app --host 0.0.0.0 --port $PORT |
||||
@ -1,336 +0,0 @@ |
|||||
<div align="center"> |
|
||||
|
|
||||
[<img src="https://avatars.githubusercontent.com/u/82473144?s=200" width="100" alt="Ghostfolio logo">](https://ghostfol.io) |
|
||||
|
|
||||
# Ghostfolio |
|
||||
|
|
||||
**Open Source Wealth Management Software** |
|
||||
|
|
||||
[**Ghostfol.io**](https://ghostfol.io) | [**Live Demo**](https://ghostfol.io/en/demo) | [**Ghostfolio Premium**](https://ghostfol.io/en/pricing) | [**FAQ**](https://ghostfol.io/en/faq) | |
|
||||
[**Blog**](https://ghostfol.io/en/blog) | [**LinkedIn**](https://www.linkedin.com/company/ghostfolio) | [**Slack**](https://join.slack.com/t/ghostfolio/shared_invite/zt-vsaan64h-F_I0fEo5M0P88lP9ibCxFg) | [**X**](https://x.com/ghostfolio_) |
|
||||
|
|
||||
[](https://www.buymeacoffee.com/ghostfolio) |
|
||||
[](#contributing) [](https://hub.docker.com/r/ghostfolio/ghostfolio) |
|
||||
[](https://www.gnu.org/licenses/agpl-3.0) |
|
||||
|
|
||||
</div> |
|
||||
|
|
||||
**Ghostfolio** is an open source wealth management software built with web technology. The application empowers busy people to keep track of stocks, ETFs or cryptocurrencies and make solid, data-driven investment decisions. The software is designed for personal use in continuous operation. |
|
||||
|
|
||||
<div align="center"> |
|
||||
|
|
||||
[<img src="./apps/client/src/assets/images/video-preview.jpg" width="600" alt="Preview image of the Ghostfolio video trailer">](https://www.youtube.com/watch?v=yY6ObSQVJZk) |
|
||||
|
|
||||
</div> |
|
||||
|
|
||||
## Ghostfolio Premium |
|
||||
|
|
||||
Our official **[Ghostfolio Premium](https://ghostfol.io/en/pricing)** cloud offering is the easiest way to get started. Due to the time it saves, this will be the best option for most people. Revenue is used to cover operational costs for the hosting infrastructure and professional data providers, and to fund ongoing development. |
|
||||
|
|
||||
If you prefer to run Ghostfolio on your own infrastructure, please find further instructions in the [Self-hosting](#self-hosting) section. |
|
||||
|
|
||||
## Why Ghostfolio? |
|
||||
|
|
||||
Ghostfolio is for you if you are... |
|
||||
|
|
||||
- 💼 trading stocks, ETFs or cryptocurrencies on multiple platforms |
|
||||
- 🏦 pursuing a buy & hold strategy |
|
||||
- 🎯 interested in getting insights of your portfolio composition |
|
||||
- 👻 valuing privacy and data ownership |
|
||||
- 🧘 into minimalism |
|
||||
- 🧺 caring about diversifying your financial resources |
|
||||
- 🆓 interested in financial independence |
|
||||
- 🙅 saying no to spreadsheets |
|
||||
- 😎 still reading this list |
|
||||
|
|
||||
## Features |
|
||||
|
|
||||
- ✅ Create, update and delete transactions |
|
||||
- ✅ Multi account management |
|
||||
- ✅ Portfolio performance: Return on Average Investment (ROAI) for `Today`, `WTD`, `MTD`, `YTD`, `1Y`, `5Y`, `Max` |
|
||||
- ✅ Various charts |
|
||||
- ✅ Static analysis to identify potential risks in your portfolio |
|
||||
- ✅ Import and export transactions |
|
||||
- ✅ Dark Mode |
|
||||
- ✅ Zen Mode |
|
||||
- ✅ Progressive Web App (PWA) with a mobile-first design |
|
||||
|
|
||||
<div align="center"> |
|
||||
|
|
||||
<img src="./apps/client/src/assets/images/screenshot.png" width="300" alt="Image of a phone showing the Ghostfolio app open"> |
|
||||
|
|
||||
</div> |
|
||||
|
|
||||
## Technology Stack |
|
||||
|
|
||||
Ghostfolio is a modern web application written in [TypeScript](https://www.typescriptlang.org) and organized as an [Nx](https://nx.dev) workspace. |
|
||||
|
|
||||
### Backend |
|
||||
|
|
||||
The backend is based on [NestJS](https://nestjs.com) using [PostgreSQL](https://www.postgresql.org) as a database together with [Prisma](https://www.prisma.io) and [Redis](https://redis.io) for caching. |
|
||||
|
|
||||
### Frontend |
|
||||
|
|
||||
The frontend is built with [Angular](https://angular.dev) and uses [Angular Material](https://material.angular.io) with utility classes from [Bootstrap](https://getbootstrap.com). |
|
||||
|
|
||||
## Self-hosting |
|
||||
|
|
||||
We provide official container images hosted on [Docker Hub](https://hub.docker.com/r/ghostfolio/ghostfolio) for `linux/amd64`, `linux/arm/v7` and `linux/arm64`. |
|
||||
|
|
||||
<div align="center"> |
|
||||
|
|
||||
[<img src="./apps/client/src/assets/images/button-buy-me-a-coffee.png" width="150" alt="Buy me a coffee button"/>](https://www.buymeacoffee.com/ghostfolio) |
|
||||
|
|
||||
</div> |
|
||||
|
|
||||
### Supported Environment Variables |
|
||||
|
|
||||
| Name | Type | Default Value | Description | |
|
||||
| --------------------------- | --------------------- | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | |
|
||||
| `ACCESS_TOKEN_SALT` | `string` | | A random string used as salt for access tokens | |
|
||||
| `API_KEY_COINGECKO_DEMO` | `string` (optional) | | The _CoinGecko_ Demo API key | |
|
||||
| `API_KEY_COINGECKO_PRO` | `string` (optional) | | The _CoinGecko_ Pro API key | |
|
||||
| `DATABASE_URL` | `string` | | The database connection URL, e.g. `postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:5432/${POSTGRES_DB}?sslmode=prefer` | |
|
||||
| `ENABLE_FEATURE_AUTH_TOKEN` | `boolean` (optional) | `true` | Enables authentication via security token | |
|
||||
| `HOST` | `string` (optional) | `0.0.0.0` | The host where the Ghostfolio application will run on | |
|
||||
| `JWT_SECRET_KEY` | `string` | | A random string used for _JSON Web Tokens_ (JWT) | |
|
||||
| `LOG_LEVELS` | `string[]` (optional) | | The logging levels for the Ghostfolio application, e.g. `["debug","error","log","warn"]` | |
|
||||
| `PORT` | `number` (optional) | `3333` | The port where the Ghostfolio application will run on | |
|
||||
| `POSTGRES_DB` | `string` | | The name of the _PostgreSQL_ database | |
|
||||
| `POSTGRES_PASSWORD` | `string` | | The password of the _PostgreSQL_ database | |
|
||||
| `POSTGRES_USER` | `string` | | The user of the _PostgreSQL_ database | |
|
||||
| `REDIS_DB` | `number` (optional) | `0` | The database index of _Redis_ | |
|
||||
| `REDIS_HOST` | `string` | | The host where _Redis_ is running | |
|
||||
| `REDIS_PASSWORD` | `string` | | The password of _Redis_ | |
|
||||
| `REDIS_PORT` | `number` | | The port where _Redis_ is running | |
|
||||
| `REQUEST_TIMEOUT` | `number` (optional) | `2000` | The timeout of network requests to data providers in milliseconds | |
|
||||
| `ROOT_URL` | `string` (optional) | `http://0.0.0.0:3333` | The root URL of the Ghostfolio application, used for generating callback URLs and external links. | |
|
||||
|
|
||||
#### OpenID Connect OIDC (Experimental) |
|
||||
|
|
||||
| Name | Type | Default Value | Description | |
|
||||
| -------------------------- | --------------------- | ------------------------------------ | ---------------------------------------------------------------------------------------------------- | |
|
||||
| `ENABLE_FEATURE_AUTH_OIDC` | `boolean` (optional) | `false` | Enables authentication via _OpenID Connect_ | |
|
||||
| `OIDC_AUTHORIZATION_URL` | `string` (optional) | | Manual override for the OIDC authorization endpoint (falls back to the discovery from the issuer) | |
|
||||
| `OIDC_CALLBACK_URL` | `string` (optional) | `${ROOT_URL}/api/auth/oidc/callback` | The OIDC callback URL | |
|
||||
| `OIDC_CLIENT_ID` | `string` | | The OIDC client ID | |
|
||||
| `OIDC_CLIENT_SECRET` | `string` | | The OIDC client secret | |
|
||||
| `OIDC_ISSUER` | `string` | | The OIDC issuer URL, used to discover the OIDC configuration via `/.well-known/openid-configuration` | |
|
||||
| `OIDC_SCOPE` | `string[]` (optional) | `["openid"]` | The OIDC scope to request, e.g. `["email","openid","profile"]` | |
|
||||
| `OIDC_TOKEN_URL` | `string` (optional) | | Manual override for the OIDC token endpoint (falls back to the discovery from the issuer) | |
|
||||
| `OIDC_USER_INFO_URL` | `string` (optional) | | Manual override for the OIDC user info endpoint (falls back to the discovery from the issuer) | |
|
||||
|
|
||||
### Run with Docker Compose |
|
||||
|
|
||||
#### Prerequisites |
|
||||
|
|
||||
- Basic knowledge of Docker |
|
||||
- Installation of [Docker](https://www.docker.com/products/docker-desktop) |
|
||||
- Create a local copy of this Git repository (clone) |
|
||||
- Copy the file `.env.example` to `.env` and populate it with your data (`cp .env.example .env`) |
|
||||
|
|
||||
#### a. Run environment |
|
||||
|
|
||||
Run the following command to start the Docker images from [Docker Hub](https://hub.docker.com/r/ghostfolio/ghostfolio): |
|
||||
|
|
||||
```bash |
|
||||
docker compose -f docker/docker-compose.yml up -d |
|
||||
``` |
|
||||
|
|
||||
#### b. Build and run environment |
|
||||
|
|
||||
Run the following commands to build and start the Docker images: |
|
||||
|
|
||||
```bash |
|
||||
docker compose -f docker/docker-compose.build.yml build |
|
||||
docker compose -f docker/docker-compose.build.yml up -d |
|
||||
``` |
|
||||
|
|
||||
#### Setup |
|
||||
|
|
||||
1. Open http://localhost:3333 in your browser |
|
||||
1. Create a new user via _Get Started_ (this first user will get the role `ADMIN`) |
|
||||
|
|
||||
#### Upgrade Version |
|
||||
|
|
||||
1. Update the _Ghostfolio_ Docker image |
|
||||
- Increase the version of the `ghostfolio/ghostfolio` Docker image in `docker/docker-compose.yml` |
|
||||
- Run the following command if `ghostfolio:latest` is set: |
|
||||
```bash |
|
||||
docker compose -f docker/docker-compose.yml pull |
|
||||
``` |
|
||||
|
|
||||
1. Run the following command to start the new Docker image: |
|
||||
```bash |
|
||||
docker compose -f docker/docker-compose.yml up -d |
|
||||
``` |
|
||||
The container will automatically apply any required database schema migrations during startup. |
|
||||
|
|
||||
### Home Server Systems (Community) |
|
||||
|
|
||||
Ghostfolio is available for various home server systems, including [CasaOS](https://github.com/bigbeartechworld/big-bear-casaos), [Home Assistant](https://github.com/lildude/ha-addon-ghostfolio), [Runtipi](https://www.runtipi.io/docs/apps-available), [TrueCharts](https://truecharts.org/charts/stable/ghostfolio), [Umbrel](https://apps.umbrel.com/app/ghostfolio), and [Unraid](https://unraid.net/community/apps?q=ghostfolio). |
|
||||
|
|
||||
## Development |
|
||||
|
|
||||
For detailed information on the environment setup and development process, please refer to [DEVELOPMENT.md](./DEVELOPMENT.md). |
|
||||
|
|
||||
## Public API |
|
||||
|
|
||||
### Authorization: Bearer Token |
|
||||
|
|
||||
Set the header for each request as follows: |
|
||||
|
|
||||
``` |
|
||||
"Authorization": "Bearer eyJh..." |
|
||||
``` |
|
||||
|
|
||||
You can get the _Bearer Token_ via `POST http://localhost:3333/api/v1/auth/anonymous` (Body: `{ "accessToken": "<INSERT_SECURITY_TOKEN_OF_ACCOUNT>" }`) |
|
||||
|
|
||||
Deprecated: `GET http://localhost:3333/api/v1/auth/anonymous/<INSERT_SECURITY_TOKEN_OF_ACCOUNT>` or `curl -s http://localhost:3333/api/v1/auth/anonymous/<INSERT_SECURITY_TOKEN_OF_ACCOUNT>`. |
|
||||
|
|
||||
### Health Check (experimental) |
|
||||
|
|
||||
#### Request |
|
||||
|
|
||||
`GET http://localhost:3333/api/v1/health` |
|
||||
|
|
||||
**Info:** No Bearer Token is required for health check |
|
||||
|
|
||||
#### Response |
|
||||
|
|
||||
##### Success |
|
||||
|
|
||||
`200 OK` |
|
||||
|
|
||||
``` |
|
||||
{ |
|
||||
"status": "OK" |
|
||||
} |
|
||||
``` |
|
||||
|
|
||||
### Import Activities |
|
||||
|
|
||||
#### Prerequisites |
|
||||
|
|
||||
[Bearer Token](#authorization-bearer-token) for authorization |
|
||||
|
|
||||
#### Request |
|
||||
|
|
||||
`POST http://localhost:3333/api/v1/import` |
|
||||
|
|
||||
#### Body |
|
||||
|
|
||||
``` |
|
||||
{ |
|
||||
"activities": [ |
|
||||
{ |
|
||||
"currency": "USD", |
|
||||
"dataSource": "YAHOO", |
|
||||
"date": "2021-09-15T00:00:00.000Z", |
|
||||
"fee": 19, |
|
||||
"quantity": 5, |
|
||||
"symbol": "MSFT", |
|
||||
"type": "BUY", |
|
||||
"unitPrice": 298.58 |
|
||||
} |
|
||||
] |
|
||||
} |
|
||||
``` |
|
||||
|
|
||||
| Field | Type | Description | |
|
||||
| ------------ | ------------------- | ------------------------------------------------------------------- | |
|
||||
| `accountId` | `string` (optional) | Id of the account | |
|
||||
| `comment` | `string` (optional) | Comment of the activity | |
|
||||
| `currency` | `string` | `CHF` \| `EUR` \| `USD` etc. | |
|
||||
| `dataSource` | `string` | `COINGECKO` \| `GHOSTFOLIO` [^1] \| `MANUAL` \| `YAHOO` | |
|
||||
| `date` | `string` | Date in the format `ISO-8601` | |
|
||||
| `fee` | `number` | Fee of the activity | |
|
||||
| `quantity` | `number` | Quantity of the activity | |
|
||||
| `symbol` | `string` | Symbol of the activity (suitable for `dataSource`) | |
|
||||
| `type` | `string` | `BUY` \| `DIVIDEND` \| `FEE` \| `INTEREST` \| `LIABILITY` \| `SELL` | |
|
||||
| `unitPrice` | `number` | Price per unit of the activity | |
|
||||
|
|
||||
#### Response |
|
||||
|
|
||||
##### Success |
|
||||
|
|
||||
`201 Created` |
|
||||
|
|
||||
##### Error |
|
||||
|
|
||||
`400 Bad Request` |
|
||||
|
|
||||
``` |
|
||||
{ |
|
||||
"error": "Bad Request", |
|
||||
"message": [ |
|
||||
"activities.1 is a duplicate activity" |
|
||||
] |
|
||||
} |
|
||||
``` |
|
||||
|
|
||||
### Portfolio (experimental) |
|
||||
|
|
||||
#### Prerequisites |
|
||||
|
|
||||
Grant access of type _Public_ in the _Access_ tab of _My Ghostfolio_. |
|
||||
|
|
||||
#### Request |
|
||||
|
|
||||
`GET http://localhost:3333/api/v1/public/<INSERT_ACCESS_ID>/portfolio` |
|
||||
|
|
||||
**Info:** No Bearer Token is required for authorization |
|
||||
|
|
||||
#### Response |
|
||||
|
|
||||
##### Success |
|
||||
|
|
||||
``` |
|
||||
{ |
|
||||
"performance": { |
|
||||
"1d": { |
|
||||
"relativeChange": 0 // normalized from -1 to 1 |
|
||||
}; |
|
||||
"ytd": { |
|
||||
"relativeChange": 0 // normalized from -1 to 1 |
|
||||
}, |
|
||||
"max": { |
|
||||
"relativeChange": 0 // normalized from -1 to 1 |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
``` |
|
||||
|
|
||||
## Community Projects |
|
||||
|
|
||||
Discover a variety of community projects for Ghostfolio: https://github.com/topics/ghostfolio |
|
||||
|
|
||||
Are you building your own project? Add the `ghostfolio` topic to your _GitHub_ repository to get listed as well. [Learn more →](https://docs.github.com/en/articles/classifying-your-repository-with-topics) |
|
||||
|
|
||||
## Contributing |
|
||||
|
|
||||
Ghostfolio is **100% free** and **open source**. We encourage and support an active and healthy community that accepts contributions from the public - including you. |
|
||||
|
|
||||
Not sure what to work on? We have [some ideas](https://github.com/ghostfolio/ghostfolio/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22%20no%3Aassignee), even for [newcomers](https://github.com/ghostfolio/ghostfolio/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22%20no%3Aassignee). Please join the Ghostfolio [Slack](https://join.slack.com/t/ghostfolio/shared_invite/zt-vsaan64h-F_I0fEo5M0P88lP9ibCxFg) channel or post to [@ghostfolio\_](https://x.com/ghostfolio_) on _X_. We would love to hear from you. |
|
||||
|
|
||||
If you like to support this project, become a [**Sponsor**](https://github.com/sponsors/ghostfolio), get [**Ghostfolio Premium**](https://ghostfol.io/en/pricing) or [**Buy me a coffee**](https://www.buymeacoffee.com/ghostfolio). |
|
||||
|
|
||||
## Sponsors |
|
||||
|
|
||||
<div align="center"> |
|
||||
<a href="https://www.testmuai.com?utm_medium=sponsor&utm_source=ghostfolio" target="_blank" title="TestMu AI - AI Powered Testing Tool"> |
|
||||
<img alt="TestMu AI Logo" height="45" src="https://assets.testmuai.com/resources/images/logos/logo.svg" /> |
|
||||
</a> |
|
||||
</div> |
|
||||
|
|
||||
## Analytics |
|
||||
|
|
||||
 |
|
||||
|
|
||||
## License |
|
||||
|
|
||||
© 2021 - 2026 [Ghostfolio](https://ghostfol.io) |
|
||||
|
|
||||
Licensed under the [AGPLv3 License](https://www.gnu.org/licenses/agpl-3.0.html). |
|
||||
|
|
||||
[^1]: Available with [**Ghostfolio Premium**](https://ghostfol.io/en/pricing). |
|
||||
@ -1,13 +0,0 @@ |
|||||
# Security Policy |
|
||||
|
|
||||
## Reporting Security Issues |
|
||||
|
|
||||
If you discover a security vulnerability in this repository, please report it to security[at]ghostfol.io. We will acknowledge your report and provide guidance on the next steps. |
|
||||
|
|
||||
To help us resolve the issue, please include the following details: |
|
||||
|
|
||||
- A description of the vulnerability |
|
||||
- Steps to reproduce the vulnerability |
|
||||
- Affected versions of the software |
|
||||
|
|
||||
We appreciate your responsible disclosure and will work to address the issue promptly. |
|
||||
@ -1,31 +0,0 @@ |
|||||
const baseConfig = require('../../eslint.config.cjs'); |
|
||||
|
|
||||
module.exports = [ |
|
||||
{ |
|
||||
ignores: ['**/dist'] |
|
||||
}, |
|
||||
...baseConfig, |
|
||||
{ |
|
||||
rules: {} |
|
||||
}, |
|
||||
{ |
|
||||
files: ['**/*.ts', '**/*.tsx', '**/*.js', '**/*.jsx'], |
|
||||
// Override or add rules here |
|
||||
rules: {}, |
|
||||
languageOptions: { |
|
||||
parserOptions: { |
|
||||
project: ['apps/api/tsconfig.*?.json'] |
|
||||
} |
|
||||
} |
|
||||
}, |
|
||||
{ |
|
||||
files: ['**/*.ts', '**/*.tsx'], |
|
||||
// Override or add rules here |
|
||||
rules: {} |
|
||||
}, |
|
||||
{ |
|
||||
files: ['**/*.js', '**/*.jsx'], |
|
||||
// Override or add rules here |
|
||||
rules: {} |
|
||||
} |
|
||||
]; |
|
||||
@ -1,18 +0,0 @@ |
|||||
/* eslint-disable */ |
|
||||
export default { |
|
||||
displayName: 'api', |
|
||||
|
|
||||
globals: {}, |
|
||||
transform: { |
|
||||
'^.+\\.[tj]s$': [ |
|
||||
'ts-jest', |
|
||||
{ |
|
||||
tsconfig: '<rootDir>/tsconfig.spec.json' |
|
||||
} |
|
||||
] |
|
||||
}, |
|
||||
moduleFileExtensions: ['ts', 'js', 'html'], |
|
||||
coverageDirectory: '../../coverage/apps/api', |
|
||||
testEnvironment: 'node', |
|
||||
preset: '../../jest.preset.js' |
|
||||
}; |
|
||||
@ -1,78 +0,0 @@ |
|||||
{ |
|
||||
"name": "api", |
|
||||
"$schema": "../../node_modules/nx/schemas/project-schema.json", |
|
||||
"sourceRoot": "apps/api/src", |
|
||||
"projectType": "application", |
|
||||
"prefix": "api", |
|
||||
"generators": {}, |
|
||||
"targets": { |
|
||||
"build": { |
|
||||
"executor": "@nx/webpack:webpack", |
|
||||
"options": { |
|
||||
"compiler": "tsc", |
|
||||
"deleteOutputPath": false, |
|
||||
"main": "apps/api/src/main.ts", |
|
||||
"outputPath": "dist/apps/api", |
|
||||
"sourceMap": true, |
|
||||
"target": "node", |
|
||||
"tsConfig": "apps/api/tsconfig.app.json", |
|
||||
"webpackConfig": "apps/api/webpack.config.js" |
|
||||
}, |
|
||||
"configurations": { |
|
||||
"production": { |
|
||||
"generatePackageJson": true, |
|
||||
"optimization": true, |
|
||||
"extractLicenses": true, |
|
||||
"inspect": false, |
|
||||
"fileReplacements": [ |
|
||||
{ |
|
||||
"replace": "apps/api/src/environments/environment.ts", |
|
||||
"with": "apps/api/src/environments/environment.prod.ts" |
|
||||
} |
|
||||
] |
|
||||
} |
|
||||
}, |
|
||||
"outputs": ["{options.outputPath}"] |
|
||||
}, |
|
||||
"copy-assets": { |
|
||||
"executor": "nx:run-commands", |
|
||||
"options": { |
|
||||
"commands": [ |
|
||||
{ |
|
||||
"command": "shx rm -rf dist/apps/api" |
|
||||
}, |
|
||||
{ |
|
||||
"command": "shx mkdir -p dist/apps/api/assets/locales" |
|
||||
}, |
|
||||
{ |
|
||||
"command": "shx cp -r apps/api/src/assets/* dist/apps/api/assets" |
|
||||
}, |
|
||||
{ |
|
||||
"command": "shx cp -r apps/client/src/locales/* dist/apps/api/assets/locales" |
|
||||
} |
|
||||
], |
|
||||
"parallel": false |
|
||||
} |
|
||||
}, |
|
||||
"serve": { |
|
||||
"executor": "@nx/js:node", |
|
||||
"options": { |
|
||||
"buildTarget": "api:build" |
|
||||
} |
|
||||
}, |
|
||||
"lint": { |
|
||||
"executor": "@nx/eslint:lint", |
|
||||
"options": { |
|
||||
"lintFilePatterns": ["apps/api/**/*.ts"] |
|
||||
} |
|
||||
}, |
|
||||
"test": { |
|
||||
"executor": "@nx/jest:jest", |
|
||||
"options": { |
|
||||
"jestConfig": "apps/api/jest.config.ts" |
|
||||
}, |
|
||||
"outputs": ["{workspaceRoot}/coverage/apps/api"] |
|
||||
} |
|
||||
}, |
|
||||
"tags": [] |
|
||||
} |
|
||||
@ -1,171 +0,0 @@ |
|||||
import { HasPermission } from '@ghostfolio/api/decorators/has-permission.decorator'; |
|
||||
import { HasPermissionGuard } from '@ghostfolio/api/guards/has-permission.guard'; |
|
||||
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; |
|
||||
import { CreateAccessDto, UpdateAccessDto } from '@ghostfolio/common/dtos'; |
|
||||
import { Access } from '@ghostfolio/common/interfaces'; |
|
||||
import { permissions } from '@ghostfolio/common/permissions'; |
|
||||
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'; |
|
||||
|
|
||||
import { AccessService } from './access.service'; |
|
||||
|
|
||||
@Controller('access') |
|
||||
export class AccessController { |
|
||||
public constructor( |
|
||||
private readonly accessService: AccessService, |
|
||||
private readonly configurationService: ConfigurationService, |
|
||||
@Inject(REQUEST) private readonly request: RequestWithUser |
|
||||
) {} |
|
||||
|
|
||||
@Get() |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async getAllAccesses(): Promise<Access[]> { |
|
||||
const accessesWithGranteeUser = await this.accessService.accesses({ |
|
||||
include: { |
|
||||
granteeUser: true |
|
||||
}, |
|
||||
orderBy: [{ granteeUserId: 'desc' }, { createdAt: 'asc' }], |
|
||||
where: { userId: this.request.user.id } |
|
||||
}); |
|
||||
|
|
||||
return accessesWithGranteeUser.map( |
|
||||
({ alias, granteeUser, id, permissions }) => { |
|
||||
if (granteeUser) { |
|
||||
return { |
|
||||
alias, |
|
||||
id, |
|
||||
permissions, |
|
||||
grantee: granteeUser?.id, |
|
||||
type: 'PRIVATE' |
|
||||
}; |
|
||||
} |
|
||||
|
|
||||
return { |
|
||||
alias, |
|
||||
id, |
|
||||
permissions, |
|
||||
grantee: 'Public', |
|
||||
type: 'PUBLIC' |
|
||||
}; |
|
||||
} |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
@HasPermission(permissions.createAccess) |
|
||||
@Post() |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async createAccess( |
|
||||
@Body() data: CreateAccessDto |
|
||||
): Promise<AccessModel> { |
|
||||
if ( |
|
||||
this.configurationService.get('ENABLE_FEATURE_SUBSCRIPTION') && |
|
||||
this.request.user.subscription.type === 'Basic' |
|
||||
) { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.FORBIDDEN), |
|
||||
StatusCodes.FORBIDDEN |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
try { |
|
||||
return this.accessService.createAccess({ |
|
||||
alias: data.alias || undefined, |
|
||||
granteeUser: data.granteeUserId |
|
||||
? { connect: { id: data.granteeUserId } } |
|
||||
: undefined, |
|
||||
permissions: data.permissions, |
|
||||
user: { connect: { id: this.request.user.id } } |
|
||||
}); |
|
||||
} 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<AccessModel> { |
|
||||
const originalAccess = await this.accessService.access({ |
|
||||
id, |
|
||||
userId: this.request.user.id |
|
||||
}); |
|
||||
|
|
||||
if (!originalAccess) { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.FORBIDDEN), |
|
||||
StatusCodes.FORBIDDEN |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
return this.accessService.deleteAccess({ |
|
||||
id |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
@HasPermission(permissions.updateAccess) |
|
||||
@Put(':id') |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async updateAccess( |
|
||||
@Body() data: UpdateAccessDto, |
|
||||
@Param('id') id: string |
|
||||
): Promise<AccessModel> { |
|
||||
if ( |
|
||||
this.configurationService.get('ENABLE_FEATURE_SUBSCRIPTION') && |
|
||||
this.request.user.subscription.type === '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 |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
try { |
|
||||
return this.accessService.updateAccess({ |
|
||||
data: { |
|
||||
alias: data.alias, |
|
||||
granteeUser: data.granteeUserId |
|
||||
? { connect: { id: data.granteeUserId } } |
|
||||
: { disconnect: true }, |
|
||||
permissions: data.permissions |
|
||||
}, |
|
||||
where: { id } |
|
||||
}); |
|
||||
} catch { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.BAD_REQUEST), |
|
||||
StatusCodes.BAD_REQUEST |
|
||||
); |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
@ -1,15 +0,0 @@ |
|||||
import { ConfigurationModule } from '@ghostfolio/api/services/configuration/configuration.module'; |
|
||||
import { PrismaModule } from '@ghostfolio/api/services/prisma/prisma.module'; |
|
||||
|
|
||||
import { Module } from '@nestjs/common'; |
|
||||
|
|
||||
import { AccessController } from './access.controller'; |
|
||||
import { AccessService } from './access.service'; |
|
||||
|
|
||||
@Module({ |
|
||||
controllers: [AccessController], |
|
||||
exports: [AccessService], |
|
||||
imports: [ConfigurationModule, PrismaModule], |
|
||||
providers: [AccessService] |
|
||||
}) |
|
||||
export class AccessModule {} |
|
||||
@ -1,68 +0,0 @@ |
|||||
import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service'; |
|
||||
import { AccessWithGranteeUser } from '@ghostfolio/common/types'; |
|
||||
|
|
||||
import { Injectable } from '@nestjs/common'; |
|
||||
import { Access, Prisma } from '@prisma/client'; |
|
||||
|
|
||||
@Injectable() |
|
||||
export class AccessService { |
|
||||
public constructor(private readonly prismaService: PrismaService) {} |
|
||||
|
|
||||
public async access( |
|
||||
accessWhereInput: Prisma.AccessWhereInput |
|
||||
): Promise<AccessWithGranteeUser | null> { |
|
||||
return this.prismaService.access.findFirst({ |
|
||||
include: { |
|
||||
granteeUser: true |
|
||||
}, |
|
||||
where: accessWhereInput |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
public async accesses(params: { |
|
||||
cursor?: Prisma.AccessWhereUniqueInput; |
|
||||
include?: Prisma.AccessInclude; |
|
||||
orderBy?: Prisma.Enumerable<Prisma.AccessOrderByWithRelationInput>; |
|
||||
skip?: number; |
|
||||
take?: number; |
|
||||
where?: Prisma.AccessWhereInput; |
|
||||
}): Promise<AccessWithGranteeUser[]> { |
|
||||
const { cursor, include, orderBy, skip, take, where } = params; |
|
||||
|
|
||||
return this.prismaService.access.findMany({ |
|
||||
cursor, |
|
||||
include, |
|
||||
orderBy, |
|
||||
skip, |
|
||||
take, |
|
||||
where |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
public async createAccess(data: Prisma.AccessCreateInput): Promise<Access> { |
|
||||
return this.prismaService.access.create({ |
|
||||
data |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
public async deleteAccess( |
|
||||
where: Prisma.AccessWhereUniqueInput |
|
||||
): Promise<Access> { |
|
||||
return this.prismaService.access.delete({ |
|
||||
where |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
public async updateAccess({ |
|
||||
data, |
|
||||
where |
|
||||
}: { |
|
||||
data: Prisma.AccessUpdateInput; |
|
||||
where: Prisma.AccessWhereUniqueInput; |
|
||||
}): Promise<Access> { |
|
||||
return this.prismaService.access.update({ |
|
||||
data, |
|
||||
where |
|
||||
}); |
|
||||
} |
|
||||
} |
|
||||
@ -1,84 +0,0 @@ |
|||||
import { AccountService } from '@ghostfolio/api/app/account/account.service'; |
|
||||
import { HasPermission } from '@ghostfolio/api/decorators/has-permission.decorator'; |
|
||||
import { HasPermissionGuard } from '@ghostfolio/api/guards/has-permission.guard'; |
|
||||
import { CreateAccountBalanceDto } from '@ghostfolio/common/dtos'; |
|
||||
import { permissions } from '@ghostfolio/common/permissions'; |
|
||||
import type { RequestWithUser } from '@ghostfolio/common/types'; |
|
||||
|
|
||||
import { |
|
||||
Controller, |
|
||||
Body, |
|
||||
Post, |
|
||||
Delete, |
|
||||
HttpException, |
|
||||
Inject, |
|
||||
Param, |
|
||||
UseGuards |
|
||||
} from '@nestjs/common'; |
|
||||
import { REQUEST } from '@nestjs/core'; |
|
||||
import { AuthGuard } from '@nestjs/passport'; |
|
||||
import { AccountBalance } from '@prisma/client'; |
|
||||
import { StatusCodes, getReasonPhrase } from 'http-status-codes'; |
|
||||
|
|
||||
import { AccountBalanceService } from './account-balance.service'; |
|
||||
|
|
||||
@Controller('account-balance') |
|
||||
export class AccountBalanceController { |
|
||||
public constructor( |
|
||||
private readonly accountBalanceService: AccountBalanceService, |
|
||||
private readonly accountService: AccountService, |
|
||||
@Inject(REQUEST) private readonly request: RequestWithUser |
|
||||
) {} |
|
||||
|
|
||||
@HasPermission(permissions.createAccountBalance) |
|
||||
@Post() |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async createAccountBalance( |
|
||||
@Body() data: CreateAccountBalanceDto |
|
||||
): Promise<AccountBalance> { |
|
||||
const account = await this.accountService.account({ |
|
||||
id_userId: { |
|
||||
id: data.accountId, |
|
||||
userId: this.request.user.id |
|
||||
} |
|
||||
}); |
|
||||
|
|
||||
if (!account) { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.FORBIDDEN), |
|
||||
StatusCodes.FORBIDDEN |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
return this.accountBalanceService.createOrUpdateAccountBalance({ |
|
||||
accountId: account.id, |
|
||||
balance: data.balance, |
|
||||
date: data.date, |
|
||||
userId: account.userId |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
@HasPermission(permissions.deleteAccountBalance) |
|
||||
@Delete(':id') |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async deleteAccountBalance( |
|
||||
@Param('id') id: string |
|
||||
): Promise<AccountBalance> { |
|
||||
const accountBalance = await this.accountBalanceService.accountBalance({ |
|
||||
id, |
|
||||
userId: this.request.user.id |
|
||||
}); |
|
||||
|
|
||||
if (!accountBalance) { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.FORBIDDEN), |
|
||||
StatusCodes.FORBIDDEN |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
return this.accountBalanceService.deleteAccountBalance({ |
|
||||
id: accountBalance.id, |
|
||||
userId: accountBalance.userId |
|
||||
}); |
|
||||
} |
|
||||
} |
|
||||
@ -1,16 +0,0 @@ |
|||||
import { AccountService } from '@ghostfolio/api/app/account/account.service'; |
|
||||
import { ExchangeRateDataModule } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.module'; |
|
||||
import { PrismaModule } from '@ghostfolio/api/services/prisma/prisma.module'; |
|
||||
|
|
||||
import { Module } from '@nestjs/common'; |
|
||||
|
|
||||
import { AccountBalanceController } from './account-balance.controller'; |
|
||||
import { AccountBalanceService } from './account-balance.service'; |
|
||||
|
|
||||
@Module({ |
|
||||
controllers: [AccountBalanceController], |
|
||||
exports: [AccountBalanceService], |
|
||||
imports: [ExchangeRateDataModule, PrismaModule], |
|
||||
providers: [AccountBalanceService, AccountService] |
|
||||
}) |
|
||||
export class AccountBalanceModule {} |
|
||||
@ -1,186 +0,0 @@ |
|||||
import { PortfolioChangedEvent } from '@ghostfolio/api/events/portfolio-changed.event'; |
|
||||
import { LogPerformance } from '@ghostfolio/api/interceptors/performance-logging/performance-logging.interceptor'; |
|
||||
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.service'; |
|
||||
import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service'; |
|
||||
import { CreateAccountBalanceDto } from '@ghostfolio/common/dtos'; |
|
||||
import { DATE_FORMAT, getSum, resetHours } from '@ghostfolio/common/helper'; |
|
||||
import { |
|
||||
AccountBalancesResponse, |
|
||||
Filter, |
|
||||
HistoricalDataItem |
|
||||
} from '@ghostfolio/common/interfaces'; |
|
||||
|
|
||||
import { Injectable } from '@nestjs/common'; |
|
||||
import { EventEmitter2 } from '@nestjs/event-emitter'; |
|
||||
import { AccountBalance, Prisma } from '@prisma/client'; |
|
||||
import { Big } from 'big.js'; |
|
||||
import { format, parseISO } from 'date-fns'; |
|
||||
|
|
||||
@Injectable() |
|
||||
export class AccountBalanceService { |
|
||||
public constructor( |
|
||||
private readonly eventEmitter: EventEmitter2, |
|
||||
private readonly exchangeRateDataService: ExchangeRateDataService, |
|
||||
private readonly prismaService: PrismaService |
|
||||
) {} |
|
||||
|
|
||||
public async accountBalance( |
|
||||
accountBalanceWhereInput: Prisma.AccountBalanceWhereInput |
|
||||
): Promise<AccountBalance | null> { |
|
||||
return this.prismaService.accountBalance.findFirst({ |
|
||||
include: { |
|
||||
account: true |
|
||||
}, |
|
||||
where: accountBalanceWhereInput |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
public async createOrUpdateAccountBalance({ |
|
||||
accountId, |
|
||||
balance, |
|
||||
date, |
|
||||
userId |
|
||||
}: CreateAccountBalanceDto & { |
|
||||
userId: string; |
|
||||
}): Promise<AccountBalance> { |
|
||||
const accountBalance = await this.prismaService.accountBalance.upsert({ |
|
||||
create: { |
|
||||
account: { |
|
||||
connect: { |
|
||||
id_userId: { |
|
||||
userId, |
|
||||
id: accountId |
|
||||
} |
|
||||
} |
|
||||
}, |
|
||||
date: resetHours(parseISO(date)), |
|
||||
value: balance |
|
||||
}, |
|
||||
update: { |
|
||||
value: balance |
|
||||
}, |
|
||||
where: { |
|
||||
accountId_date: { |
|
||||
accountId, |
|
||||
date: resetHours(parseISO(date)) |
|
||||
} |
|
||||
} |
|
||||
}); |
|
||||
|
|
||||
this.eventEmitter.emit( |
|
||||
PortfolioChangedEvent.getName(), |
|
||||
new PortfolioChangedEvent({ |
|
||||
userId |
|
||||
}) |
|
||||
); |
|
||||
|
|
||||
return accountBalance; |
|
||||
} |
|
||||
|
|
||||
public async deleteAccountBalance( |
|
||||
where: Prisma.AccountBalanceWhereUniqueInput |
|
||||
): Promise<AccountBalance> { |
|
||||
const accountBalance = await this.prismaService.accountBalance.delete({ |
|
||||
where |
|
||||
}); |
|
||||
|
|
||||
this.eventEmitter.emit( |
|
||||
PortfolioChangedEvent.getName(), |
|
||||
new PortfolioChangedEvent({ |
|
||||
userId: where.userId as string |
|
||||
}) |
|
||||
); |
|
||||
|
|
||||
return accountBalance; |
|
||||
} |
|
||||
|
|
||||
public async getAccountBalanceItems({ |
|
||||
filters, |
|
||||
userCurrency, |
|
||||
userId |
|
||||
}: { |
|
||||
filters?: Filter[]; |
|
||||
userCurrency: string; |
|
||||
userId: string; |
|
||||
}): Promise<HistoricalDataItem[]> { |
|
||||
const { balances } = await this.getAccountBalances({ |
|
||||
filters, |
|
||||
userCurrency, |
|
||||
userId, |
|
||||
withExcludedAccounts: false // TODO
|
|
||||
}); |
|
||||
const accumulatedBalancesByDate: { [date: string]: HistoricalDataItem } = |
|
||||
{}; |
|
||||
const lastBalancesByAccount: { [accountId: string]: Big } = {}; |
|
||||
|
|
||||
for (const { accountId, date, valueInBaseCurrency } of balances) { |
|
||||
const formattedDate = format(date, DATE_FORMAT); |
|
||||
|
|
||||
lastBalancesByAccount[accountId] = new Big(valueInBaseCurrency); |
|
||||
|
|
||||
const totalBalance = getSum(Object.values(lastBalancesByAccount)); |
|
||||
|
|
||||
// Add or update the accumulated balance for this date
|
|
||||
accumulatedBalancesByDate[formattedDate] = { |
|
||||
date: formattedDate, |
|
||||
value: totalBalance.toNumber() |
|
||||
}; |
|
||||
} |
|
||||
|
|
||||
return Object.values(accumulatedBalancesByDate); |
|
||||
} |
|
||||
|
|
||||
@LogPerformance |
|
||||
public async getAccountBalances({ |
|
||||
filters, |
|
||||
userCurrency, |
|
||||
userId, |
|
||||
withExcludedAccounts |
|
||||
}: { |
|
||||
filters?: Filter[]; |
|
||||
userCurrency: string; |
|
||||
userId: string; |
|
||||
withExcludedAccounts?: boolean; |
|
||||
}): Promise<AccountBalancesResponse> { |
|
||||
const where: Prisma.AccountBalanceWhereInput = { userId }; |
|
||||
|
|
||||
const accountFilter = filters?.find(({ type }) => { |
|
||||
return type === 'ACCOUNT'; |
|
||||
}); |
|
||||
|
|
||||
if (accountFilter) { |
|
||||
where.accountId = accountFilter.id; |
|
||||
} |
|
||||
|
|
||||
if (withExcludedAccounts === false) { |
|
||||
where.account = { isExcluded: false }; |
|
||||
} |
|
||||
|
|
||||
const balances = await this.prismaService.accountBalance.findMany({ |
|
||||
where, |
|
||||
orderBy: { |
|
||||
date: 'asc' |
|
||||
}, |
|
||||
select: { |
|
||||
account: true, |
|
||||
date: true, |
|
||||
id: true, |
|
||||
value: true |
|
||||
} |
|
||||
}); |
|
||||
|
|
||||
return { |
|
||||
balances: balances.map((balance) => { |
|
||||
return { |
|
||||
...balance, |
|
||||
accountId: balance.account.id, |
|
||||
valueInBaseCurrency: this.exchangeRateDataService.toCurrency( |
|
||||
balance.value, |
|
||||
balance.account.currency, |
|
||||
userCurrency |
|
||||
) |
|
||||
}; |
|
||||
}) |
|
||||
}; |
|
||||
} |
|
||||
} |
|
||||
@ -1,295 +0,0 @@ |
|||||
import { AccountBalanceService } from '@ghostfolio/api/app/account-balance/account-balance.service'; |
|
||||
import { PortfolioService } from '@ghostfolio/api/app/portfolio/portfolio.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 |
|
||||
) {} |
|
||||
|
|
||||
@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); |
|
||||
|
|
||||
return this.accountBalanceService.getAccountBalances({ |
|
||||
filters: [{ id, type: 'ACCOUNT' }], |
|
||||
userCurrency: this.request.user.settings.settings.baseCurrency, |
|
||||
userId: impersonationUserId || this.request.user.id |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
@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,30 +0,0 @@ |
|||||
import { AccountBalanceModule } from '@ghostfolio/api/app/account-balance/account-balance.module'; |
|
||||
import { PortfolioModule } from '@ghostfolio/api/app/portfolio/portfolio.module'; |
|
||||
import { RedactValuesInResponseModule } from '@ghostfolio/api/interceptors/redact-values-in-response/redact-values-in-response.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'; |
|
||||
|
|
||||
@Module({ |
|
||||
controllers: [AccountController], |
|
||||
exports: [AccountService], |
|
||||
imports: [ |
|
||||
AccountBalanceModule, |
|
||||
ApiModule, |
|
||||
ConfigurationModule, |
|
||||
ExchangeRateDataModule, |
|
||||
ImpersonationModule, |
|
||||
PortfolioModule, |
|
||||
PrismaModule, |
|
||||
RedactValuesInResponseModule |
|
||||
], |
|
||||
providers: [AccountService] |
|
||||
}) |
|
||||
export class AccountModule {} |
|
||||
@ -1,288 +0,0 @@ |
|||||
import { AccountBalanceService } from '@ghostfolio/api/app/account-balance/account-balance.service'; |
|
||||
import { PortfolioChangedEvent } from '@ghostfolio/api/events/portfolio-changed.event'; |
|
||||
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.service'; |
|
||||
import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service'; |
|
||||
import { DATE_FORMAT } from '@ghostfolio/common/helper'; |
|
||||
import { Filter } from '@ghostfolio/common/interfaces'; |
|
||||
|
|
||||
import { Injectable } from '@nestjs/common'; |
|
||||
import { EventEmitter2 } from '@nestjs/event-emitter'; |
|
||||
import { |
|
||||
Account, |
|
||||
AccountBalance, |
|
||||
Order, |
|
||||
Platform, |
|
||||
Prisma, |
|
||||
SymbolProfile |
|
||||
} from '@prisma/client'; |
|
||||
import { Big } from 'big.js'; |
|
||||
import { format } from 'date-fns'; |
|
||||
import { groupBy } from 'lodash'; |
|
||||
|
|
||||
import { CashDetails } from './interfaces/cash-details.interface'; |
|
||||
|
|
||||
@Injectable() |
|
||||
export class AccountService { |
|
||||
public constructor( |
|
||||
private readonly accountBalanceService: AccountBalanceService, |
|
||||
private readonly eventEmitter: EventEmitter2, |
|
||||
private readonly exchangeRateDataService: ExchangeRateDataService, |
|
||||
private readonly prismaService: PrismaService |
|
||||
) {} |
|
||||
|
|
||||
public async account({ |
|
||||
id_userId |
|
||||
}: Prisma.AccountWhereUniqueInput): Promise<Account | null> { |
|
||||
const [account] = await this.accounts({ |
|
||||
where: id_userId |
|
||||
}); |
|
||||
|
|
||||
return account; |
|
||||
} |
|
||||
|
|
||||
public async accountWithActivities( |
|
||||
accountWhereUniqueInput: Prisma.AccountWhereUniqueInput, |
|
||||
accountInclude: Prisma.AccountInclude |
|
||||
): Promise< |
|
||||
Account & { |
|
||||
activities?: Order[]; |
|
||||
} |
|
||||
> { |
|
||||
return this.prismaService.account.findUnique({ |
|
||||
include: accountInclude, |
|
||||
where: accountWhereUniqueInput |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
public async accounts(params: { |
|
||||
include?: Prisma.AccountInclude; |
|
||||
skip?: number; |
|
||||
take?: number; |
|
||||
cursor?: Prisma.AccountWhereUniqueInput; |
|
||||
where?: Prisma.AccountWhereInput; |
|
||||
orderBy?: Prisma.AccountOrderByWithRelationInput; |
|
||||
}): Promise< |
|
||||
(Account & { |
|
||||
activities?: (Order & { SymbolProfile?: SymbolProfile })[]; |
|
||||
balances?: AccountBalance[]; |
|
||||
platform?: Platform; |
|
||||
})[] |
|
||||
> { |
|
||||
const { include = {}, skip, take, cursor, where, orderBy } = params; |
|
||||
|
|
||||
const isBalancesIncluded = !!include.balances; |
|
||||
|
|
||||
include.balances = { |
|
||||
orderBy: { date: 'desc' }, |
|
||||
...(isBalancesIncluded ? {} : { take: 1 }) |
|
||||
}; |
|
||||
|
|
||||
const accounts = await this.prismaService.account.findMany({ |
|
||||
cursor, |
|
||||
include, |
|
||||
orderBy, |
|
||||
skip, |
|
||||
take, |
|
||||
where |
|
||||
}); |
|
||||
|
|
||||
return accounts.map((account) => { |
|
||||
account = { ...account, balance: account.balances[0]?.value ?? 0 }; |
|
||||
|
|
||||
if (!isBalancesIncluded) { |
|
||||
delete account.balances; |
|
||||
} |
|
||||
|
|
||||
return account; |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
public async createAccount( |
|
||||
data: Prisma.AccountCreateInput, |
|
||||
aUserId: string |
|
||||
): Promise<Account> { |
|
||||
const account = await this.prismaService.account.create({ |
|
||||
data |
|
||||
}); |
|
||||
|
|
||||
await this.accountBalanceService.createOrUpdateAccountBalance({ |
|
||||
accountId: account.id, |
|
||||
balance: data.balance, |
|
||||
date: format(new Date(), DATE_FORMAT), |
|
||||
userId: aUserId |
|
||||
}); |
|
||||
|
|
||||
this.eventEmitter.emit( |
|
||||
PortfolioChangedEvent.getName(), |
|
||||
new PortfolioChangedEvent({ |
|
||||
userId: account.userId |
|
||||
}) |
|
||||
); |
|
||||
|
|
||||
return account; |
|
||||
} |
|
||||
|
|
||||
public async deleteAccount( |
|
||||
where: Prisma.AccountWhereUniqueInput |
|
||||
): Promise<Account> { |
|
||||
const account = await this.prismaService.account.delete({ |
|
||||
where |
|
||||
}); |
|
||||
|
|
||||
this.eventEmitter.emit( |
|
||||
PortfolioChangedEvent.getName(), |
|
||||
new PortfolioChangedEvent({ |
|
||||
userId: account.userId |
|
||||
}) |
|
||||
); |
|
||||
|
|
||||
return account; |
|
||||
} |
|
||||
|
|
||||
public async getAccounts(aUserId: string): Promise<Account[]> { |
|
||||
const accounts = await this.accounts({ |
|
||||
include: { |
|
||||
activities: true, |
|
||||
platform: true |
|
||||
}, |
|
||||
orderBy: { name: 'asc' }, |
|
||||
where: { userId: aUserId } |
|
||||
}); |
|
||||
|
|
||||
return accounts.map((account) => { |
|
||||
let activitiesCount = 0; |
|
||||
|
|
||||
for (const { isDraft } of account.activities) { |
|
||||
if (!isDraft) { |
|
||||
activitiesCount += 1; |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
const result = { ...account, activitiesCount }; |
|
||||
|
|
||||
delete result.activities; |
|
||||
|
|
||||
return result; |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
public async getCashDetails({ |
|
||||
currency, |
|
||||
filters = [], |
|
||||
userId, |
|
||||
withExcludedAccounts = false |
|
||||
}: { |
|
||||
currency: string; |
|
||||
filters?: Filter[]; |
|
||||
userId: string; |
|
||||
withExcludedAccounts?: boolean; |
|
||||
}): Promise<CashDetails> { |
|
||||
let totalCashBalanceInBaseCurrency = new Big(0); |
|
||||
|
|
||||
const where: Prisma.AccountWhereInput = { |
|
||||
userId |
|
||||
}; |
|
||||
|
|
||||
if (withExcludedAccounts === false) { |
|
||||
where.isExcluded = false; |
|
||||
} |
|
||||
|
|
||||
const { ACCOUNT: filtersByAccount } = groupBy(filters, ({ type }) => { |
|
||||
return type; |
|
||||
}); |
|
||||
|
|
||||
if (filtersByAccount?.length > 0) { |
|
||||
where.id = { |
|
||||
in: filtersByAccount.map(({ id }) => { |
|
||||
return id; |
|
||||
}) |
|
||||
}; |
|
||||
} |
|
||||
|
|
||||
const accounts = await this.accounts({ where }); |
|
||||
|
|
||||
for (const account of accounts) { |
|
||||
totalCashBalanceInBaseCurrency = totalCashBalanceInBaseCurrency.plus( |
|
||||
this.exchangeRateDataService.toCurrency( |
|
||||
account.balance, |
|
||||
account.currency, |
|
||||
currency |
|
||||
) |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
return { |
|
||||
accounts, |
|
||||
balanceInBaseCurrency: totalCashBalanceInBaseCurrency.toNumber() |
|
||||
}; |
|
||||
} |
|
||||
|
|
||||
public async updateAccount( |
|
||||
params: { |
|
||||
where: Prisma.AccountWhereUniqueInput; |
|
||||
data: Prisma.AccountUpdateInput; |
|
||||
}, |
|
||||
aUserId: string |
|
||||
): Promise<Account> { |
|
||||
const { data, where } = params; |
|
||||
|
|
||||
await this.accountBalanceService.createOrUpdateAccountBalance({ |
|
||||
accountId: data.id as string, |
|
||||
balance: data.balance as number, |
|
||||
date: format(new Date(), DATE_FORMAT), |
|
||||
userId: aUserId |
|
||||
}); |
|
||||
|
|
||||
const account = await this.prismaService.account.update({ |
|
||||
data, |
|
||||
where |
|
||||
}); |
|
||||
|
|
||||
this.eventEmitter.emit( |
|
||||
PortfolioChangedEvent.getName(), |
|
||||
new PortfolioChangedEvent({ |
|
||||
userId: account.userId |
|
||||
}) |
|
||||
); |
|
||||
|
|
||||
return account; |
|
||||
} |
|
||||
|
|
||||
public async updateAccountBalance({ |
|
||||
accountId, |
|
||||
amount, |
|
||||
currency, |
|
||||
date = new Date(), |
|
||||
userId |
|
||||
}: { |
|
||||
accountId: string; |
|
||||
amount: number; |
|
||||
currency: string; |
|
||||
date?: Date; |
|
||||
userId: string; |
|
||||
}) { |
|
||||
const { balance, currency: currencyOfAccount } = await this.account({ |
|
||||
id_userId: { |
|
||||
userId, |
|
||||
id: accountId |
|
||||
} |
|
||||
}); |
|
||||
|
|
||||
const amountInCurrencyOfAccount = |
|
||||
await this.exchangeRateDataService.toCurrencyAtDate( |
|
||||
amount, |
|
||||
currency, |
|
||||
currencyOfAccount, |
|
||||
date |
|
||||
); |
|
||||
|
|
||||
if (amountInCurrencyOfAccount) { |
|
||||
await this.accountBalanceService.createOrUpdateAccountBalance({ |
|
||||
accountId, |
|
||||
userId, |
|
||||
balance: new Big(balance).plus(amountInCurrencyOfAccount).toNumber(), |
|
||||
date: date.toISOString() |
|
||||
}); |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
@ -1,6 +0,0 @@ |
|||||
import { Account } from '@prisma/client'; |
|
||||
|
|
||||
export interface CashDetails { |
|
||||
accounts: Account[]; |
|
||||
balanceInBaseCurrency: number; |
|
||||
} |
|
||||
@ -1,337 +0,0 @@ |
|||||
import { HasPermission } from '@ghostfolio/api/decorators/has-permission.decorator'; |
|
||||
import { HasPermissionGuard } from '@ghostfolio/api/guards/has-permission.guard'; |
|
||||
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 { ManualService } from '@ghostfolio/api/services/data-provider/manual/manual.service'; |
|
||||
import { DemoService } from '@ghostfolio/api/services/demo/demo.service'; |
|
||||
import { DataGatheringService } from '@ghostfolio/api/services/queues/data-gathering/data-gathering.service'; |
|
||||
import { getIntervalFromDateRange } from '@ghostfolio/common/calculation-helper'; |
|
||||
import { |
|
||||
DATA_GATHERING_QUEUE_PRIORITY_HIGH, |
|
||||
DATA_GATHERING_QUEUE_PRIORITY_MEDIUM, |
|
||||
GATHER_ASSET_PROFILE_PROCESS_JOB_NAME, |
|
||||
GATHER_ASSET_PROFILE_PROCESS_JOB_OPTIONS |
|
||||
} from '@ghostfolio/common/config'; |
|
||||
import { |
|
||||
UpdateAssetProfileDto, |
|
||||
UpdatePropertyDto |
|
||||
} from '@ghostfolio/common/dtos'; |
|
||||
import { getAssetProfileIdentifier } from '@ghostfolio/common/helper'; |
|
||||
import { |
|
||||
AdminData, |
|
||||
AdminMarketData, |
|
||||
AdminUserResponse, |
|
||||
AdminUsersResponse, |
|
||||
EnhancedSymbolProfile, |
|
||||
ScraperConfiguration |
|
||||
} from '@ghostfolio/common/interfaces'; |
|
||||
import { permissions } from '@ghostfolio/common/permissions'; |
|
||||
import type { |
|
||||
DateRange, |
|
||||
MarketDataPreset, |
|
||||
RequestWithUser |
|
||||
} from '@ghostfolio/common/types'; |
|
||||
|
|
||||
import { |
|
||||
Body, |
|
||||
Controller, |
|
||||
Delete, |
|
||||
Get, |
|
||||
HttpException, |
|
||||
Inject, |
|
||||
Logger, |
|
||||
Param, |
|
||||
Patch, |
|
||||
Post, |
|
||||
Put, |
|
||||
Query, |
|
||||
UseGuards, |
|
||||
UseInterceptors |
|
||||
} from '@nestjs/common'; |
|
||||
import { REQUEST } from '@nestjs/core'; |
|
||||
import { AuthGuard } from '@nestjs/passport'; |
|
||||
import { DataSource, MarketData, Prisma, SymbolProfile } from '@prisma/client'; |
|
||||
import { isDate, parseISO } from 'date-fns'; |
|
||||
import { StatusCodes, getReasonPhrase } from 'http-status-codes'; |
|
||||
|
|
||||
import { AdminService } from './admin.service'; |
|
||||
|
|
||||
@Controller('admin') |
|
||||
export class AdminController { |
|
||||
public constructor( |
|
||||
private readonly adminService: AdminService, |
|
||||
private readonly apiService: ApiService, |
|
||||
private readonly dataGatheringService: DataGatheringService, |
|
||||
private readonly demoService: DemoService, |
|
||||
private readonly manualService: ManualService, |
|
||||
@Inject(REQUEST) private readonly request: RequestWithUser |
|
||||
) {} |
|
||||
|
|
||||
@Get() |
|
||||
@HasPermission(permissions.accessAdminControl) |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async getAdminData(): Promise<AdminData> { |
|
||||
return this.adminService.get(); |
|
||||
} |
|
||||
|
|
||||
@Get('demo-user/sync') |
|
||||
@HasPermission(permissions.syncDemoUserAccount) |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async syncDemoUserAccount(): Promise<Prisma.BatchPayload> { |
|
||||
return this.demoService.syncDemoUserAccount(); |
|
||||
} |
|
||||
|
|
||||
@HasPermission(permissions.accessAdminControl) |
|
||||
@Post('gather') |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async gather7Days(): Promise<void> { |
|
||||
this.dataGatheringService.gather7Days(); |
|
||||
} |
|
||||
|
|
||||
@HasPermission(permissions.accessAdminControl) |
|
||||
@Post('gather/max') |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async gatherMax(): Promise<void> { |
|
||||
const assetProfileIdentifiers = |
|
||||
await this.dataGatheringService.getActiveAssetProfileIdentifiers(); |
|
||||
|
|
||||
await this.dataGatheringService.addJobsToQueue( |
|
||||
assetProfileIdentifiers.map(({ dataSource, symbol }) => { |
|
||||
return { |
|
||||
data: { |
|
||||
dataSource, |
|
||||
symbol |
|
||||
}, |
|
||||
name: GATHER_ASSET_PROFILE_PROCESS_JOB_NAME, |
|
||||
opts: { |
|
||||
...GATHER_ASSET_PROFILE_PROCESS_JOB_OPTIONS, |
|
||||
jobId: getAssetProfileIdentifier({ dataSource, symbol }), |
|
||||
priority: DATA_GATHERING_QUEUE_PRIORITY_MEDIUM |
|
||||
} |
|
||||
}; |
|
||||
}) |
|
||||
); |
|
||||
|
|
||||
this.dataGatheringService.gatherMax(); |
|
||||
} |
|
||||
|
|
||||
@HasPermission(permissions.accessAdminControl) |
|
||||
@Post('gather/profile-data') |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async gatherProfileData(): Promise<void> { |
|
||||
const assetProfileIdentifiers = |
|
||||
await this.dataGatheringService.getActiveAssetProfileIdentifiers(); |
|
||||
|
|
||||
await this.dataGatheringService.addJobsToQueue( |
|
||||
assetProfileIdentifiers.map(({ dataSource, symbol }) => { |
|
||||
return { |
|
||||
data: { |
|
||||
dataSource, |
|
||||
symbol |
|
||||
}, |
|
||||
name: GATHER_ASSET_PROFILE_PROCESS_JOB_NAME, |
|
||||
opts: { |
|
||||
...GATHER_ASSET_PROFILE_PROCESS_JOB_OPTIONS, |
|
||||
jobId: getAssetProfileIdentifier({ dataSource, symbol }), |
|
||||
priority: DATA_GATHERING_QUEUE_PRIORITY_MEDIUM |
|
||||
} |
|
||||
}; |
|
||||
}) |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
@HasPermission(permissions.accessAdminControl) |
|
||||
@Post('gather/profile-data/:dataSource/:symbol') |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async gatherProfileDataForSymbol( |
|
||||
@Param('dataSource') dataSource: DataSource, |
|
||||
@Param('symbol') symbol: string |
|
||||
): Promise<void> { |
|
||||
await this.dataGatheringService.addJobToQueue({ |
|
||||
data: { |
|
||||
dataSource, |
|
||||
symbol |
|
||||
}, |
|
||||
name: GATHER_ASSET_PROFILE_PROCESS_JOB_NAME, |
|
||||
opts: { |
|
||||
...GATHER_ASSET_PROFILE_PROCESS_JOB_OPTIONS, |
|
||||
jobId: getAssetProfileIdentifier({ dataSource, symbol }), |
|
||||
priority: DATA_GATHERING_QUEUE_PRIORITY_HIGH |
|
||||
} |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
@Post('gather/:dataSource/:symbol') |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
@HasPermission(permissions.accessAdminControl) |
|
||||
public async gatherSymbol( |
|
||||
@Param('dataSource') dataSource: DataSource, |
|
||||
@Param('symbol') symbol: string, |
|
||||
@Query('range') dateRange: DateRange |
|
||||
): Promise<void> { |
|
||||
let date: Date; |
|
||||
|
|
||||
if (dateRange) { |
|
||||
const { startDate } = getIntervalFromDateRange(dateRange); |
|
||||
date = startDate; |
|
||||
} |
|
||||
|
|
||||
this.dataGatheringService.gatherSymbol({ |
|
||||
dataSource, |
|
||||
date, |
|
||||
symbol |
|
||||
}); |
|
||||
|
|
||||
return; |
|
||||
} |
|
||||
|
|
||||
@HasPermission(permissions.accessAdminControl) |
|
||||
@Post('gather/:dataSource/:symbol/:dateString') |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async gatherSymbolForDate( |
|
||||
@Param('dataSource') dataSource: DataSource, |
|
||||
@Param('dateString') dateString: string, |
|
||||
@Param('symbol') symbol: string |
|
||||
): Promise<MarketData> { |
|
||||
const date = parseISO(dateString); |
|
||||
|
|
||||
if (!isDate(date)) { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.BAD_REQUEST), |
|
||||
StatusCodes.BAD_REQUEST |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
return this.dataGatheringService.gatherSymbolForDate({ |
|
||||
dataSource, |
|
||||
date, |
|
||||
symbol |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
@Get('market-data') |
|
||||
@HasPermission(permissions.accessAdminControl) |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async getMarketData( |
|
||||
@Query('assetSubClasses') filterByAssetSubClasses?: string, |
|
||||
@Query('dataSource') filterByDataSource?: string, |
|
||||
@Query('presetId') presetId?: MarketDataPreset, |
|
||||
@Query('query') filterBySearchQuery?: string, |
|
||||
@Query('skip') skip?: number, |
|
||||
@Query('sortColumn') sortColumn?: string, |
|
||||
@Query('sortDirection') sortDirection?: Prisma.SortOrder, |
|
||||
@Query('take') take?: number |
|
||||
): Promise<AdminMarketData> { |
|
||||
const filters = this.apiService.buildFiltersFromQueryParams({ |
|
||||
filterByAssetSubClasses, |
|
||||
filterByDataSource, |
|
||||
filterBySearchQuery |
|
||||
}); |
|
||||
|
|
||||
return this.adminService.getMarketData({ |
|
||||
filters, |
|
||||
presetId, |
|
||||
sortColumn, |
|
||||
sortDirection, |
|
||||
skip: isNaN(skip) ? undefined : skip, |
|
||||
take: isNaN(take) ? undefined : take |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
@HasPermission(permissions.accessAdminControl) |
|
||||
@Post('market-data/:dataSource/:symbol/test') |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async testMarketData( |
|
||||
@Body() data: { scraperConfiguration: ScraperConfiguration }, |
|
||||
@Param('dataSource') dataSource: DataSource, |
|
||||
@Param('symbol') symbol: string |
|
||||
): Promise<{ price: number }> { |
|
||||
try { |
|
||||
const price = await this.manualService.test({ |
|
||||
symbol, |
|
||||
scraperConfiguration: data.scraperConfiguration |
|
||||
}); |
|
||||
|
|
||||
if (price) { |
|
||||
return { price }; |
|
||||
} |
|
||||
|
|
||||
throw new Error( |
|
||||
`Could not parse the market price for ${symbol} (${dataSource})` |
|
||||
); |
|
||||
} catch (error) { |
|
||||
Logger.error(error, 'AdminController'); |
|
||||
|
|
||||
throw new HttpException(error.message, StatusCodes.BAD_REQUEST); |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
@HasPermission(permissions.accessAdminControl) |
|
||||
@Post('profile-data/:dataSource/:symbol') |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
@UseInterceptors(TransformDataSourceInRequestInterceptor) |
|
||||
public async addProfileData( |
|
||||
@Param('dataSource') dataSource: DataSource, |
|
||||
@Param('symbol') symbol: string |
|
||||
): Promise<SymbolProfile | never> { |
|
||||
return this.adminService.addAssetProfile({ |
|
||||
dataSource, |
|
||||
symbol, |
|
||||
currency: this.request.user.settings.settings.baseCurrency |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
@Delete('profile-data/:dataSource/:symbol') |
|
||||
@HasPermission(permissions.accessAdminControl) |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async deleteProfileData( |
|
||||
@Param('dataSource') dataSource: DataSource, |
|
||||
@Param('symbol') symbol: string |
|
||||
): Promise<void> { |
|
||||
return this.adminService.deleteProfileData({ dataSource, symbol }); |
|
||||
} |
|
||||
|
|
||||
@HasPermission(permissions.accessAdminControl) |
|
||||
@Patch('profile-data/:dataSource/:symbol') |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async patchAssetProfileData( |
|
||||
@Body() assetProfile: UpdateAssetProfileDto, |
|
||||
@Param('dataSource') dataSource: DataSource, |
|
||||
@Param('symbol') symbol: string |
|
||||
): Promise<EnhancedSymbolProfile> { |
|
||||
return this.adminService.patchAssetProfileData( |
|
||||
{ dataSource, symbol }, |
|
||||
assetProfile |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
@HasPermission(permissions.accessAdminControl) |
|
||||
@Put('settings/:key') |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async updateProperty( |
|
||||
@Param('key') key: string, |
|
||||
@Body() data: UpdatePropertyDto |
|
||||
) { |
|
||||
return this.adminService.putSetting(key, data.value); |
|
||||
} |
|
||||
|
|
||||
@Get('user') |
|
||||
@HasPermission(permissions.accessAdminControl) |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async getUsers( |
|
||||
@Query('skip') skip?: number, |
|
||||
@Query('take') take?: number |
|
||||
): Promise<AdminUsersResponse> { |
|
||||
return this.adminService.getUsers({ |
|
||||
skip: isNaN(skip) ? undefined : skip, |
|
||||
take: isNaN(take) ? undefined : take |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
@Get('user/:id') |
|
||||
@HasPermission(permissions.accessAdminControl) |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async getUser(@Param('id') id: string): Promise<AdminUserResponse> { |
|
||||
return this.adminService.getUser(id); |
|
||||
} |
|
||||
} |
|
||||
@ -1,42 +0,0 @@ |
|||||
import { OrderModule } from '@ghostfolio/api/app/order/order.module'; |
|
||||
import { TransformDataSourceInRequestModule } from '@ghostfolio/api/interceptors/transform-data-source-in-request/transform-data-source-in-request.module'; |
|
||||
import { ApiModule } from '@ghostfolio/api/services/api/api.module'; |
|
||||
import { BenchmarkModule } from '@ghostfolio/api/services/benchmark/benchmark.module'; |
|
||||
import { ConfigurationModule } from '@ghostfolio/api/services/configuration/configuration.module'; |
|
||||
import { DataProviderModule } from '@ghostfolio/api/services/data-provider/data-provider.module'; |
|
||||
import { DemoModule } from '@ghostfolio/api/services/demo/demo.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 { PropertyModule } from '@ghostfolio/api/services/property/property.module'; |
|
||||
import { DataGatheringModule } 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 { AdminController } from './admin.controller'; |
|
||||
import { AdminService } from './admin.service'; |
|
||||
import { QueueModule } from './queue/queue.module'; |
|
||||
|
|
||||
@Module({ |
|
||||
imports: [ |
|
||||
ApiModule, |
|
||||
BenchmarkModule, |
|
||||
ConfigurationModule, |
|
||||
DataGatheringModule, |
|
||||
DataProviderModule, |
|
||||
DemoModule, |
|
||||
ExchangeRateDataModule, |
|
||||
MarketDataModule, |
|
||||
OrderModule, |
|
||||
PrismaModule, |
|
||||
PropertyModule, |
|
||||
QueueModule, |
|
||||
SymbolProfileModule, |
|
||||
TransformDataSourceInRequestModule |
|
||||
], |
|
||||
controllers: [AdminController], |
|
||||
providers: [AdminService], |
|
||||
exports: [AdminService] |
|
||||
}) |
|
||||
export class AdminModule {} |
|
||||
@ -1,938 +0,0 @@ |
|||||
import { OrderService } from '@ghostfolio/api/app/order/order.service'; |
|
||||
import { environment } from '@ghostfolio/api/environments/environment'; |
|
||||
import { BenchmarkService } from '@ghostfolio/api/services/benchmark/benchmark.service'; |
|
||||
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; |
|
||||
import { DataProviderService } from '@ghostfolio/api/services/data-provider/data-provider.service'; |
|
||||
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.service'; |
|
||||
import { MarketDataService } from '@ghostfolio/api/services/market-data/market-data.service'; |
|
||||
import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service'; |
|
||||
import { PropertyService } from '@ghostfolio/api/services/property/property.service'; |
|
||||
import { SymbolProfileService } from '@ghostfolio/api/services/symbol-profile/symbol-profile.service'; |
|
||||
import { |
|
||||
PROPERTY_CURRENCIES, |
|
||||
PROPERTY_IS_READ_ONLY_MODE, |
|
||||
PROPERTY_IS_USER_SIGNUP_ENABLED |
|
||||
} from '@ghostfolio/common/config'; |
|
||||
import { |
|
||||
getAssetProfileIdentifier, |
|
||||
getCurrencyFromSymbol, |
|
||||
isCurrency |
|
||||
} from '@ghostfolio/common/helper'; |
|
||||
import { |
|
||||
AdminData, |
|
||||
AdminMarketData, |
|
||||
AdminMarketDataDetails, |
|
||||
AdminMarketDataItem, |
|
||||
AdminUserResponse, |
|
||||
AdminUsersResponse, |
|
||||
AssetProfileIdentifier, |
|
||||
EnhancedSymbolProfile, |
|
||||
Filter |
|
||||
} from '@ghostfolio/common/interfaces'; |
|
||||
import { Sector } from '@ghostfolio/common/interfaces/sector.interface'; |
|
||||
import { MarketDataPreset } from '@ghostfolio/common/types'; |
|
||||
|
|
||||
import { |
|
||||
BadRequestException, |
|
||||
HttpException, |
|
||||
Injectable, |
|
||||
Logger, |
|
||||
NotFoundException |
|
||||
} from '@nestjs/common'; |
|
||||
import { |
|
||||
AssetClass, |
|
||||
AssetSubClass, |
|
||||
DataSource, |
|
||||
Prisma, |
|
||||
PrismaClient, |
|
||||
Property, |
|
||||
SymbolProfile |
|
||||
} from '@prisma/client'; |
|
||||
import { differenceInDays } from 'date-fns'; |
|
||||
import { StatusCodes, getReasonPhrase } from 'http-status-codes'; |
|
||||
import { groupBy } from 'lodash'; |
|
||||
|
|
||||
@Injectable() |
|
||||
export class AdminService { |
|
||||
public constructor( |
|
||||
private readonly benchmarkService: BenchmarkService, |
|
||||
private readonly configurationService: ConfigurationService, |
|
||||
private readonly dataProviderService: DataProviderService, |
|
||||
private readonly exchangeRateDataService: ExchangeRateDataService, |
|
||||
private readonly marketDataService: MarketDataService, |
|
||||
private readonly orderService: OrderService, |
|
||||
private readonly prismaService: PrismaService, |
|
||||
private readonly propertyService: PropertyService, |
|
||||
private readonly symbolProfileService: SymbolProfileService |
|
||||
) {} |
|
||||
|
|
||||
public async addAssetProfile({ |
|
||||
currency, |
|
||||
dataSource, |
|
||||
symbol |
|
||||
}: AssetProfileIdentifier & { currency?: string }): Promise< |
|
||||
SymbolProfile | never |
|
||||
> { |
|
||||
try { |
|
||||
if (dataSource === 'MANUAL') { |
|
||||
return this.symbolProfileService.add({ |
|
||||
currency, |
|
||||
dataSource, |
|
||||
symbol |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
const assetProfiles = await this.dataProviderService.getAssetProfiles([ |
|
||||
{ dataSource, symbol } |
|
||||
]); |
|
||||
|
|
||||
if (!assetProfiles[symbol]?.currency) { |
|
||||
throw new BadRequestException( |
|
||||
`Asset profile not found for ${symbol} (${dataSource})` |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
return this.symbolProfileService.add( |
|
||||
assetProfiles[symbol] as Prisma.SymbolProfileCreateInput |
|
||||
); |
|
||||
} catch (error) { |
|
||||
if ( |
|
||||
error instanceof Prisma.PrismaClientKnownRequestError && |
|
||||
error.code === 'P2002' |
|
||||
) { |
|
||||
throw new BadRequestException( |
|
||||
`Asset profile of ${symbol} (${dataSource}) already exists` |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
throw error; |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
public async deleteProfileData({ |
|
||||
dataSource, |
|
||||
symbol |
|
||||
}: AssetProfileIdentifier) { |
|
||||
await this.marketDataService.deleteMany({ dataSource, symbol }); |
|
||||
|
|
||||
const currency = getCurrencyFromSymbol(symbol); |
|
||||
const customCurrencies = |
|
||||
await this.propertyService.getByKey<string[]>(PROPERTY_CURRENCIES); |
|
||||
|
|
||||
if (customCurrencies.includes(currency)) { |
|
||||
const updatedCustomCurrencies = customCurrencies.filter( |
|
||||
(customCurrency) => { |
|
||||
return customCurrency !== currency; |
|
||||
} |
|
||||
); |
|
||||
|
|
||||
await this.putSetting( |
|
||||
PROPERTY_CURRENCIES, |
|
||||
JSON.stringify(updatedCustomCurrencies) |
|
||||
); |
|
||||
} else { |
|
||||
await this.symbolProfileService.delete({ dataSource, symbol }); |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
public async get(): Promise<AdminData> { |
|
||||
const dataSources = Object.values(DataSource); |
|
||||
|
|
||||
const [activitiesCount, enabledDataSources, settings, userCount] = |
|
||||
await Promise.all([ |
|
||||
this.prismaService.order.count(), |
|
||||
this.dataProviderService.getDataSources(), |
|
||||
this.propertyService.get(), |
|
||||
this.countUsersWithAnalytics() |
|
||||
]); |
|
||||
|
|
||||
const dataProviders = ( |
|
||||
await Promise.all( |
|
||||
dataSources.map(async (dataSource) => { |
|
||||
const assetProfileCount = |
|
||||
await this.prismaService.symbolProfile.count({ |
|
||||
where: { |
|
||||
dataSource |
|
||||
} |
|
||||
}); |
|
||||
|
|
||||
const isEnabled = enabledDataSources.includes(dataSource); |
|
||||
|
|
||||
if ( |
|
||||
assetProfileCount > 0 || |
|
||||
dataSource === 'GHOSTFOLIO' || |
|
||||
isEnabled |
|
||||
) { |
|
||||
const dataProviderInfo = this.dataProviderService |
|
||||
.getDataProvider(dataSource) |
|
||||
.getDataProviderInfo(); |
|
||||
|
|
||||
return { |
|
||||
...dataProviderInfo, |
|
||||
assetProfileCount, |
|
||||
useForExchangeRates: |
|
||||
dataSource === |
|
||||
this.dataProviderService.getDataSourceForExchangeRates() |
|
||||
}; |
|
||||
} |
|
||||
|
|
||||
return null; |
|
||||
}) |
|
||||
) |
|
||||
).filter(Boolean); |
|
||||
|
|
||||
return { |
|
||||
activitiesCount, |
|
||||
dataProviders, |
|
||||
settings, |
|
||||
userCount, |
|
||||
version: environment.version |
|
||||
}; |
|
||||
} |
|
||||
|
|
||||
public async getMarketData({ |
|
||||
filters, |
|
||||
presetId, |
|
||||
sortColumn, |
|
||||
sortDirection = 'asc', |
|
||||
skip, |
|
||||
take = Number.MAX_SAFE_INTEGER |
|
||||
}: { |
|
||||
filters?: Filter[]; |
|
||||
presetId?: MarketDataPreset; |
|
||||
skip?: number; |
|
||||
sortColumn?: string; |
|
||||
sortDirection?: Prisma.SortOrder; |
|
||||
take?: number; |
|
||||
}): Promise<AdminMarketData> { |
|
||||
let orderBy: Prisma.Enumerable<Prisma.SymbolProfileOrderByWithRelationInput> = |
|
||||
[{ symbol: 'asc' }]; |
|
||||
const where: Prisma.SymbolProfileWhereInput = {}; |
|
||||
|
|
||||
if (presetId === 'BENCHMARKS') { |
|
||||
const benchmarkAssetProfiles = |
|
||||
await this.benchmarkService.getBenchmarkAssetProfiles(); |
|
||||
|
|
||||
where.id = { |
|
||||
in: benchmarkAssetProfiles.map(({ id }) => { |
|
||||
return id; |
|
||||
}) |
|
||||
}; |
|
||||
} else if (presetId === 'CURRENCIES') { |
|
||||
return this.getMarketDataForCurrencies(); |
|
||||
} else if ( |
|
||||
presetId === 'ETF_WITHOUT_COUNTRIES' || |
|
||||
presetId === 'ETF_WITHOUT_SECTORS' |
|
||||
) { |
|
||||
filters = [{ id: 'ETF', type: 'ASSET_SUB_CLASS' }]; |
|
||||
} else if (presetId === 'NO_ACTIVITIES') { |
|
||||
where.activities = { |
|
||||
none: {} |
|
||||
}; |
|
||||
} |
|
||||
|
|
||||
const searchQuery = filters.find(({ type }) => { |
|
||||
return type === 'SEARCH_QUERY'; |
|
||||
})?.id; |
|
||||
|
|
||||
const { |
|
||||
ASSET_SUB_CLASS: filtersByAssetSubClass, |
|
||||
DATA_SOURCE: filtersByDataSource |
|
||||
} = groupBy(filters, ({ type }) => { |
|
||||
return type; |
|
||||
}); |
|
||||
|
|
||||
const marketDataItems = await this.prismaService.marketData.groupBy({ |
|
||||
_count: true, |
|
||||
by: ['dataSource', 'symbol'] |
|
||||
}); |
|
||||
|
|
||||
if (filtersByAssetSubClass) { |
|
||||
where.assetSubClass = AssetSubClass[filtersByAssetSubClass[0].id]; |
|
||||
} |
|
||||
|
|
||||
if (filtersByDataSource) { |
|
||||
where.dataSource = DataSource[filtersByDataSource[0].id]; |
|
||||
} |
|
||||
|
|
||||
if (searchQuery) { |
|
||||
where.OR = [ |
|
||||
{ id: { mode: 'insensitive', startsWith: searchQuery } }, |
|
||||
{ isin: { mode: 'insensitive', startsWith: searchQuery } }, |
|
||||
{ name: { mode: 'insensitive', startsWith: searchQuery } }, |
|
||||
{ symbol: { mode: 'insensitive', startsWith: searchQuery } } |
|
||||
]; |
|
||||
} |
|
||||
|
|
||||
if (sortColumn) { |
|
||||
orderBy = [{ [sortColumn]: sortDirection }]; |
|
||||
|
|
||||
if (sortColumn === 'activitiesCount') { |
|
||||
orderBy = [ |
|
||||
{ |
|
||||
activities: { |
|
||||
_count: sortDirection |
|
||||
} |
|
||||
} |
|
||||
]; |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
const extendedPrismaClient = this.getExtendedPrismaClient(); |
|
||||
|
|
||||
try { |
|
||||
const symbolProfileResult = await Promise.all([ |
|
||||
extendedPrismaClient.symbolProfile.findMany({ |
|
||||
skip, |
|
||||
take, |
|
||||
where, |
|
||||
orderBy: [...orderBy, { id: sortDirection }], |
|
||||
select: { |
|
||||
_count: { |
|
||||
select: { |
|
||||
activities: true, |
|
||||
watchedBy: true |
|
||||
} |
|
||||
}, |
|
||||
activities: { |
|
||||
orderBy: [{ date: 'asc' }], |
|
||||
select: { date: true }, |
|
||||
take: 1 |
|
||||
}, |
|
||||
assetClass: true, |
|
||||
assetSubClass: true, |
|
||||
comment: true, |
|
||||
countries: true, |
|
||||
currency: true, |
|
||||
dataSource: true, |
|
||||
id: true, |
|
||||
isActive: true, |
|
||||
isUsedByUsersWithSubscription: true, |
|
||||
name: true, |
|
||||
scraperConfiguration: true, |
|
||||
sectors: true, |
|
||||
symbol: true, |
|
||||
SymbolProfileOverrides: true |
|
||||
} |
|
||||
}), |
|
||||
this.prismaService.symbolProfile.count({ where }) |
|
||||
]); |
|
||||
const assetProfiles = symbolProfileResult[0]; |
|
||||
let count = symbolProfileResult[1]; |
|
||||
|
|
||||
const lastMarketPrices = await this.prismaService.marketData.findMany({ |
|
||||
distinct: ['dataSource', 'symbol'], |
|
||||
orderBy: { date: 'desc' }, |
|
||||
select: { |
|
||||
dataSource: true, |
|
||||
marketPrice: true, |
|
||||
symbol: true |
|
||||
}, |
|
||||
where: { |
|
||||
dataSource: { |
|
||||
in: assetProfiles.map(({ dataSource }) => { |
|
||||
return dataSource; |
|
||||
}) |
|
||||
}, |
|
||||
symbol: { |
|
||||
in: assetProfiles.map(({ symbol }) => { |
|
||||
return symbol; |
|
||||
}) |
|
||||
} |
|
||||
} |
|
||||
}); |
|
||||
|
|
||||
const lastMarketPriceMap = new Map<string, number>(); |
|
||||
|
|
||||
for (const { dataSource, marketPrice, symbol } of lastMarketPrices) { |
|
||||
lastMarketPriceMap.set( |
|
||||
getAssetProfileIdentifier({ dataSource, symbol }), |
|
||||
marketPrice |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
let marketData: AdminMarketDataItem[] = await Promise.all( |
|
||||
assetProfiles.map( |
|
||||
async ({ |
|
||||
_count, |
|
||||
activities, |
|
||||
assetClass, |
|
||||
assetSubClass, |
|
||||
comment, |
|
||||
countries, |
|
||||
currency, |
|
||||
dataSource, |
|
||||
id, |
|
||||
isActive, |
|
||||
isUsedByUsersWithSubscription, |
|
||||
name, |
|
||||
sectors, |
|
||||
symbol, |
|
||||
SymbolProfileOverrides |
|
||||
}) => { |
|
||||
let countriesCount = countries ? Object.keys(countries).length : 0; |
|
||||
|
|
||||
const lastMarketPrice = lastMarketPriceMap.get( |
|
||||
getAssetProfileIdentifier({ dataSource, symbol }) |
|
||||
); |
|
||||
|
|
||||
const marketDataItemCount = |
|
||||
marketDataItems.find((marketDataItem) => { |
|
||||
return ( |
|
||||
marketDataItem.dataSource === dataSource && |
|
||||
marketDataItem.symbol === symbol |
|
||||
); |
|
||||
})?._count ?? 0; |
|
||||
|
|
||||
let sectorsCount = sectors ? Object.keys(sectors).length : 0; |
|
||||
|
|
||||
if (SymbolProfileOverrides) { |
|
||||
assetClass = SymbolProfileOverrides.assetClass ?? assetClass; |
|
||||
assetSubClass = |
|
||||
SymbolProfileOverrides.assetSubClass ?? assetSubClass; |
|
||||
|
|
||||
if ( |
|
||||
( |
|
||||
SymbolProfileOverrides.countries as unknown as Prisma.JsonArray |
|
||||
)?.length > 0 |
|
||||
) { |
|
||||
countriesCount = ( |
|
||||
SymbolProfileOverrides.countries as unknown as Prisma.JsonArray |
|
||||
).length; |
|
||||
} |
|
||||
|
|
||||
name = SymbolProfileOverrides.name ?? name; |
|
||||
|
|
||||
if ( |
|
||||
(SymbolProfileOverrides.sectors as unknown as Sector[]) |
|
||||
?.length > 0 |
|
||||
) { |
|
||||
sectorsCount = ( |
|
||||
SymbolProfileOverrides.sectors as unknown as Prisma.JsonArray |
|
||||
).length; |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
return { |
|
||||
assetClass, |
|
||||
assetSubClass, |
|
||||
comment, |
|
||||
currency, |
|
||||
countriesCount, |
|
||||
dataSource, |
|
||||
id, |
|
||||
isActive, |
|
||||
lastMarketPrice, |
|
||||
name, |
|
||||
symbol, |
|
||||
marketDataItemCount, |
|
||||
sectorsCount, |
|
||||
activitiesCount: _count.activities, |
|
||||
date: activities?.[0]?.date, |
|
||||
isUsedByUsersWithSubscription: |
|
||||
await isUsedByUsersWithSubscription, |
|
||||
watchedByCount: _count.watchedBy |
|
||||
}; |
|
||||
} |
|
||||
) |
|
||||
); |
|
||||
|
|
||||
if (presetId) { |
|
||||
if (presetId === 'ETF_WITHOUT_COUNTRIES') { |
|
||||
marketData = marketData.filter(({ countriesCount }) => { |
|
||||
return countriesCount === 0; |
|
||||
}); |
|
||||
} else if (presetId === 'ETF_WITHOUT_SECTORS') { |
|
||||
marketData = marketData.filter(({ sectorsCount }) => { |
|
||||
return sectorsCount === 0; |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
count = marketData.length; |
|
||||
} |
|
||||
|
|
||||
return { |
|
||||
count, |
|
||||
marketData |
|
||||
}; |
|
||||
} finally { |
|
||||
await extendedPrismaClient.$disconnect(); |
|
||||
|
|
||||
Logger.debug('Disconnect extended prisma client', 'AdminService'); |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
public async getMarketDataBySymbol({ |
|
||||
dataSource, |
|
||||
symbol |
|
||||
}: AssetProfileIdentifier): Promise<AdminMarketDataDetails> { |
|
||||
let activitiesCount: EnhancedSymbolProfile['activitiesCount'] = 0; |
|
||||
let currency: EnhancedSymbolProfile['currency'] = '-'; |
|
||||
let dateOfFirstActivity: EnhancedSymbolProfile['dateOfFirstActivity']; |
|
||||
|
|
||||
if (isCurrency(getCurrencyFromSymbol(symbol))) { |
|
||||
currency = getCurrencyFromSymbol(symbol); |
|
||||
({ activitiesCount, dateOfFirstActivity } = |
|
||||
await this.orderService.getStatisticsByCurrency(currency)); |
|
||||
} |
|
||||
|
|
||||
const [[assetProfile], marketData] = await Promise.all([ |
|
||||
this.symbolProfileService.getSymbolProfiles([ |
|
||||
{ |
|
||||
dataSource, |
|
||||
symbol |
|
||||
} |
|
||||
]), |
|
||||
this.marketDataService.marketDataItems({ |
|
||||
orderBy: { |
|
||||
date: 'asc' |
|
||||
}, |
|
||||
where: { |
|
||||
dataSource, |
|
||||
symbol |
|
||||
} |
|
||||
}) |
|
||||
]); |
|
||||
|
|
||||
if (assetProfile) { |
|
||||
assetProfile.dataProviderInfo = this.dataProviderService |
|
||||
.getDataProvider(assetProfile.dataSource) |
|
||||
.getDataProviderInfo(); |
|
||||
} |
|
||||
|
|
||||
return { |
|
||||
marketData, |
|
||||
assetProfile: assetProfile ?? { |
|
||||
activitiesCount, |
|
||||
currency, |
|
||||
dataSource, |
|
||||
dateOfFirstActivity, |
|
||||
symbol, |
|
||||
isActive: true |
|
||||
} |
|
||||
}; |
|
||||
} |
|
||||
|
|
||||
public async getUser(id: string): Promise<AdminUserResponse> { |
|
||||
const [user] = await this.getUsersWithAnalytics({ |
|
||||
where: { id } |
|
||||
}); |
|
||||
|
|
||||
if (!user) { |
|
||||
throw new NotFoundException(`User with ID ${id} not found`); |
|
||||
} |
|
||||
|
|
||||
return user; |
|
||||
} |
|
||||
|
|
||||
public async getUsers({ |
|
||||
skip, |
|
||||
take = Number.MAX_SAFE_INTEGER |
|
||||
}: { |
|
||||
skip?: number; |
|
||||
take?: number; |
|
||||
}): Promise<AdminUsersResponse> { |
|
||||
const [count, users] = await Promise.all([ |
|
||||
this.countUsersWithAnalytics(), |
|
||||
this.getUsersWithAnalytics({ |
|
||||
skip, |
|
||||
take |
|
||||
}) |
|
||||
]); |
|
||||
|
|
||||
return { count, users }; |
|
||||
} |
|
||||
|
|
||||
public async patchAssetProfileData( |
|
||||
{ dataSource, symbol }: AssetProfileIdentifier, |
|
||||
{ |
|
||||
assetClass, |
|
||||
assetSubClass, |
|
||||
comment, |
|
||||
countries, |
|
||||
currency, |
|
||||
dataSource: newDataSource, |
|
||||
holdings, |
|
||||
isActive, |
|
||||
name, |
|
||||
scraperConfiguration, |
|
||||
sectors, |
|
||||
symbol: newSymbol, |
|
||||
symbolMapping, |
|
||||
url |
|
||||
}: Prisma.SymbolProfileUpdateInput |
|
||||
) { |
|
||||
if ( |
|
||||
newSymbol && |
|
||||
newDataSource && |
|
||||
(newSymbol !== symbol || newDataSource !== dataSource) |
|
||||
) { |
|
||||
const [assetProfile] = await this.symbolProfileService.getSymbolProfiles([ |
|
||||
{ |
|
||||
dataSource: DataSource[newDataSource.toString()], |
|
||||
symbol: newSymbol as string |
|
||||
} |
|
||||
]); |
|
||||
|
|
||||
if (assetProfile) { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.CONFLICT), |
|
||||
StatusCodes.CONFLICT |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
try { |
|
||||
Promise.all([ |
|
||||
await this.symbolProfileService.updateAssetProfileIdentifier( |
|
||||
{ |
|
||||
dataSource, |
|
||||
symbol |
|
||||
}, |
|
||||
{ |
|
||||
dataSource: DataSource[newDataSource.toString()], |
|
||||
symbol: newSymbol as string |
|
||||
} |
|
||||
), |
|
||||
await this.marketDataService.updateAssetProfileIdentifier( |
|
||||
{ |
|
||||
dataSource, |
|
||||
symbol |
|
||||
}, |
|
||||
{ |
|
||||
dataSource: DataSource[newDataSource.toString()], |
|
||||
symbol: newSymbol as string |
|
||||
} |
|
||||
) |
|
||||
]); |
|
||||
|
|
||||
return this.symbolProfileService.getSymbolProfiles([ |
|
||||
{ |
|
||||
dataSource: DataSource[newDataSource.toString()], |
|
||||
symbol: newSymbol as string |
|
||||
} |
|
||||
])?.[0]; |
|
||||
} catch { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.BAD_REQUEST), |
|
||||
StatusCodes.BAD_REQUEST |
|
||||
); |
|
||||
} |
|
||||
} else { |
|
||||
const symbolProfileOverrides = { |
|
||||
assetClass: assetClass as AssetClass, |
|
||||
assetSubClass: assetSubClass as AssetSubClass, |
|
||||
name: name as string, |
|
||||
url: url as string |
|
||||
}; |
|
||||
|
|
||||
const updatedSymbolProfile: Prisma.SymbolProfileUpdateInput = { |
|
||||
comment, |
|
||||
countries, |
|
||||
currency, |
|
||||
dataSource, |
|
||||
holdings, |
|
||||
isActive, |
|
||||
scraperConfiguration, |
|
||||
sectors, |
|
||||
symbol, |
|
||||
symbolMapping, |
|
||||
...(dataSource === 'MANUAL' |
|
||||
? { assetClass, assetSubClass, name, url } |
|
||||
: { |
|
||||
SymbolProfileOverrides: { |
|
||||
upsert: { |
|
||||
create: symbolProfileOverrides, |
|
||||
update: symbolProfileOverrides |
|
||||
} |
|
||||
} |
|
||||
}) |
|
||||
}; |
|
||||
|
|
||||
await this.symbolProfileService.updateSymbolProfile( |
|
||||
{ |
|
||||
dataSource, |
|
||||
symbol |
|
||||
}, |
|
||||
updatedSymbolProfile |
|
||||
); |
|
||||
|
|
||||
return this.symbolProfileService.getSymbolProfiles([ |
|
||||
{ |
|
||||
dataSource: dataSource as DataSource, |
|
||||
symbol: symbol as string |
|
||||
} |
|
||||
])?.[0]; |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
public async putSetting(key: string, value: string) { |
|
||||
let response: Property; |
|
||||
|
|
||||
if (value) { |
|
||||
response = await this.propertyService.put({ key, value }); |
|
||||
} else { |
|
||||
response = await this.propertyService.delete({ key }); |
|
||||
} |
|
||||
|
|
||||
if (key === PROPERTY_IS_READ_ONLY_MODE && value === 'true') { |
|
||||
await this.putSetting(PROPERTY_IS_USER_SIGNUP_ENABLED, 'false'); |
|
||||
} else if (key === PROPERTY_CURRENCIES) { |
|
||||
await this.exchangeRateDataService.initialize(); |
|
||||
} |
|
||||
|
|
||||
return response; |
|
||||
} |
|
||||
|
|
||||
private async countUsersWithAnalytics() { |
|
||||
let where: Prisma.UserWhereInput; |
|
||||
|
|
||||
if (this.configurationService.get('ENABLE_FEATURE_SUBSCRIPTION')) { |
|
||||
where = { |
|
||||
NOT: { |
|
||||
analytics: null |
|
||||
} |
|
||||
}; |
|
||||
} |
|
||||
|
|
||||
return this.prismaService.user.count({ |
|
||||
where |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
private getExtendedPrismaClient() { |
|
||||
Logger.debug('Connect extended prisma client', 'AdminService'); |
|
||||
|
|
||||
const symbolProfileExtension = Prisma.defineExtension((client) => { |
|
||||
return client.$extends({ |
|
||||
result: { |
|
||||
symbolProfile: { |
|
||||
isUsedByUsersWithSubscription: { |
|
||||
compute: async ({ id }) => { |
|
||||
const { _count } = |
|
||||
await this.prismaService.symbolProfile.findUnique({ |
|
||||
select: { |
|
||||
_count: { |
|
||||
select: { |
|
||||
activities: { |
|
||||
where: { |
|
||||
user: { |
|
||||
subscriptions: { |
|
||||
some: { |
|
||||
expiresAt: { |
|
||||
gt: new Date() |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
}, |
|
||||
where: { |
|
||||
id |
|
||||
} |
|
||||
}); |
|
||||
|
|
||||
return _count.activities > 0; |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
}); |
|
||||
}); |
|
||||
|
|
||||
return new PrismaClient().$extends(symbolProfileExtension); |
|
||||
} |
|
||||
|
|
||||
private async getMarketDataForCurrencies(): Promise<AdminMarketData> { |
|
||||
const currencyPairs = this.exchangeRateDataService.getCurrencyPairs(); |
|
||||
|
|
||||
const [lastMarketPrices, marketDataItems] = await Promise.all([ |
|
||||
this.prismaService.marketData.findMany({ |
|
||||
distinct: ['dataSource', 'symbol'], |
|
||||
orderBy: { date: 'desc' }, |
|
||||
select: { |
|
||||
dataSource: true, |
|
||||
marketPrice: true, |
|
||||
symbol: true |
|
||||
}, |
|
||||
where: { |
|
||||
dataSource: { |
|
||||
in: currencyPairs.map(({ dataSource }) => { |
|
||||
return dataSource; |
|
||||
}) |
|
||||
}, |
|
||||
symbol: { |
|
||||
in: currencyPairs.map(({ symbol }) => { |
|
||||
return symbol; |
|
||||
}) |
|
||||
} |
|
||||
} |
|
||||
}), |
|
||||
this.prismaService.marketData.groupBy({ |
|
||||
_count: true, |
|
||||
by: ['dataSource', 'symbol'] |
|
||||
}) |
|
||||
]); |
|
||||
|
|
||||
const lastMarketPriceMap = new Map<string, number>(); |
|
||||
|
|
||||
for (const { dataSource, marketPrice, symbol } of lastMarketPrices) { |
|
||||
lastMarketPriceMap.set( |
|
||||
getAssetProfileIdentifier({ dataSource, symbol }), |
|
||||
marketPrice |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
const marketDataPromise: Promise<AdminMarketDataItem>[] = currencyPairs.map( |
|
||||
async ({ dataSource, symbol }) => { |
|
||||
let activitiesCount: EnhancedSymbolProfile['activitiesCount'] = 0; |
|
||||
let currency: EnhancedSymbolProfile['currency'] = '-'; |
|
||||
let dateOfFirstActivity: EnhancedSymbolProfile['dateOfFirstActivity']; |
|
||||
|
|
||||
if (isCurrency(getCurrencyFromSymbol(symbol))) { |
|
||||
currency = getCurrencyFromSymbol(symbol); |
|
||||
({ activitiesCount, dateOfFirstActivity } = |
|
||||
await this.orderService.getStatisticsByCurrency(currency)); |
|
||||
} |
|
||||
|
|
||||
const lastMarketPrice = lastMarketPriceMap.get( |
|
||||
getAssetProfileIdentifier({ dataSource, symbol }) |
|
||||
); |
|
||||
|
|
||||
const marketDataItemCount = |
|
||||
marketDataItems.find((marketDataItem) => { |
|
||||
return ( |
|
||||
marketDataItem.dataSource === dataSource && |
|
||||
marketDataItem.symbol === symbol |
|
||||
); |
|
||||
})?._count ?? 0; |
|
||||
|
|
||||
return { |
|
||||
activitiesCount, |
|
||||
currency, |
|
||||
dataSource, |
|
||||
lastMarketPrice, |
|
||||
marketDataItemCount, |
|
||||
symbol, |
|
||||
assetClass: AssetClass.LIQUIDITY, |
|
||||
assetSubClass: AssetSubClass.CASH, |
|
||||
countriesCount: 0, |
|
||||
date: dateOfFirstActivity, |
|
||||
id: undefined, |
|
||||
isActive: true, |
|
||||
name: symbol, |
|
||||
sectorsCount: 0, |
|
||||
watchedByCount: 0 |
|
||||
}; |
|
||||
} |
|
||||
); |
|
||||
|
|
||||
const marketData = await Promise.all(marketDataPromise); |
|
||||
return { marketData, count: marketData.length }; |
|
||||
} |
|
||||
|
|
||||
private async getUsersWithAnalytics({ |
|
||||
skip, |
|
||||
take, |
|
||||
where |
|
||||
}: { |
|
||||
skip?: number; |
|
||||
take?: number; |
|
||||
where?: Prisma.UserWhereInput; |
|
||||
}): Promise<AdminUsersResponse['users']> { |
|
||||
let orderBy: Prisma.Enumerable<Prisma.UserOrderByWithRelationInput> = [ |
|
||||
{ createdAt: 'desc' } |
|
||||
]; |
|
||||
|
|
||||
if (this.configurationService.get('ENABLE_FEATURE_SUBSCRIPTION')) { |
|
||||
orderBy = [ |
|
||||
{ |
|
||||
analytics: { |
|
||||
lastRequestAt: 'desc' |
|
||||
} |
|
||||
} |
|
||||
]; |
|
||||
|
|
||||
const noAnalyticsCondition: Prisma.UserWhereInput['NOT'] = { |
|
||||
analytics: null |
|
||||
}; |
|
||||
|
|
||||
if (where) { |
|
||||
if (where.NOT) { |
|
||||
where.NOT = { ...where.NOT, ...noAnalyticsCondition }; |
|
||||
} else { |
|
||||
where.NOT = noAnalyticsCondition; |
|
||||
} |
|
||||
} else { |
|
||||
where = { NOT: noAnalyticsCondition }; |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
const usersWithAnalytics = await this.prismaService.user.findMany({ |
|
||||
skip, |
|
||||
take, |
|
||||
where, |
|
||||
orderBy: [...orderBy, { id: 'desc' }], |
|
||||
select: { |
|
||||
_count: { |
|
||||
select: { accounts: true, activities: true } |
|
||||
}, |
|
||||
analytics: { |
|
||||
select: { |
|
||||
activityCount: true, |
|
||||
country: true, |
|
||||
dataProviderGhostfolioDailyRequests: true, |
|
||||
updatedAt: true |
|
||||
} |
|
||||
}, |
|
||||
createdAt: true, |
|
||||
id: true, |
|
||||
provider: true, |
|
||||
role: true, |
|
||||
subscriptions: { |
|
||||
orderBy: { |
|
||||
expiresAt: 'desc' |
|
||||
}, |
|
||||
take: 1, |
|
||||
where: { |
|
||||
expiresAt: { |
|
||||
gt: new Date() |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
}); |
|
||||
|
|
||||
return usersWithAnalytics.map( |
|
||||
({ _count, analytics, createdAt, id, provider, role, subscriptions }) => { |
|
||||
const daysSinceRegistration = |
|
||||
differenceInDays(new Date(), createdAt) + 1; |
|
||||
const engagement = analytics |
|
||||
? analytics.activityCount / daysSinceRegistration |
|
||||
: undefined; |
|
||||
|
|
||||
const subscription = |
|
||||
this.configurationService.get('ENABLE_FEATURE_SUBSCRIPTION') && |
|
||||
subscriptions?.length > 0 |
|
||||
? subscriptions[0] |
|
||||
: undefined; |
|
||||
|
|
||||
return { |
|
||||
createdAt, |
|
||||
engagement, |
|
||||
id, |
|
||||
provider, |
|
||||
role, |
|
||||
subscription, |
|
||||
accountCount: _count.accounts || 0, |
|
||||
activityCount: _count.activities || 0, |
|
||||
country: analytics?.country, |
|
||||
dailyApiRequests: analytics?.dataProviderGhostfolioDailyRequests || 0, |
|
||||
lastActivity: analytics?.updatedAt |
|
||||
}; |
|
||||
} |
|
||||
); |
|
||||
} |
|
||||
} |
|
||||
@ -1,56 +0,0 @@ |
|||||
import { HasPermission } from '@ghostfolio/api/decorators/has-permission.decorator'; |
|
||||
import { HasPermissionGuard } from '@ghostfolio/api/guards/has-permission.guard'; |
|
||||
import { AdminJobs } from '@ghostfolio/common/interfaces'; |
|
||||
import { permissions } from '@ghostfolio/common/permissions'; |
|
||||
|
|
||||
import { |
|
||||
Controller, |
|
||||
Delete, |
|
||||
Get, |
|
||||
Param, |
|
||||
Query, |
|
||||
UseGuards |
|
||||
} from '@nestjs/common'; |
|
||||
import { AuthGuard } from '@nestjs/passport'; |
|
||||
import { JobStatus } from 'bull'; |
|
||||
|
|
||||
import { QueueService } from './queue.service'; |
|
||||
|
|
||||
@Controller('admin/queue') |
|
||||
export class QueueController { |
|
||||
public constructor(private readonly queueService: QueueService) {} |
|
||||
|
|
||||
@Delete('job') |
|
||||
@HasPermission(permissions.accessAdminControl) |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async deleteJobs( |
|
||||
@Query('status') filterByStatus?: string |
|
||||
): Promise<void> { |
|
||||
const status = (filterByStatus?.split(',') as JobStatus[]) ?? undefined; |
|
||||
return this.queueService.deleteJobs({ status }); |
|
||||
} |
|
||||
|
|
||||
@Get('job') |
|
||||
@HasPermission(permissions.accessAdminControl) |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async getJobs( |
|
||||
@Query('status') filterByStatus?: string |
|
||||
): Promise<AdminJobs> { |
|
||||
const status = (filterByStatus?.split(',') as JobStatus[]) ?? undefined; |
|
||||
return this.queueService.getJobs({ status }); |
|
||||
} |
|
||||
|
|
||||
@Delete('job/:id') |
|
||||
@HasPermission(permissions.accessAdminControl) |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async deleteJob(@Param('id') id: string): Promise<void> { |
|
||||
return this.queueService.deleteJob(id); |
|
||||
} |
|
||||
|
|
||||
@Get('job/:id/execute') |
|
||||
@HasPermission(permissions.accessAdminControl) |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async executeJob(@Param('id') id: string): Promise<void> { |
|
||||
return this.queueService.executeJob(id); |
|
||||
} |
|
||||
} |
|
||||
@ -1,14 +0,0 @@ |
|||||
import { DataGatheringModule } from '@ghostfolio/api/services/queues/data-gathering/data-gathering.module'; |
|
||||
import { PortfolioSnapshotQueueModule } from '@ghostfolio/api/services/queues/portfolio-snapshot/portfolio-snapshot.module'; |
|
||||
|
|
||||
import { Module } from '@nestjs/common'; |
|
||||
|
|
||||
import { QueueController } from './queue.controller'; |
|
||||
import { QueueService } from './queue.service'; |
|
||||
|
|
||||
@Module({ |
|
||||
controllers: [QueueController], |
|
||||
imports: [DataGatheringModule, PortfolioSnapshotQueueModule], |
|
||||
providers: [QueueService] |
|
||||
}) |
|
||||
export class QueueModule {} |
|
||||
@ -1,91 +0,0 @@ |
|||||
import { |
|
||||
DATA_GATHERING_QUEUE, |
|
||||
PORTFOLIO_SNAPSHOT_COMPUTATION_QUEUE, |
|
||||
QUEUE_JOB_STATUS_LIST |
|
||||
} from '@ghostfolio/common/config'; |
|
||||
import { AdminJobs } from '@ghostfolio/common/interfaces'; |
|
||||
|
|
||||
import { InjectQueue } from '@nestjs/bull'; |
|
||||
import { Injectable } from '@nestjs/common'; |
|
||||
import { JobStatus, Queue } from 'bull'; |
|
||||
|
|
||||
@Injectable() |
|
||||
export class QueueService { |
|
||||
public constructor( |
|
||||
@InjectQueue(DATA_GATHERING_QUEUE) |
|
||||
private readonly dataGatheringQueue: Queue, |
|
||||
@InjectQueue(PORTFOLIO_SNAPSHOT_COMPUTATION_QUEUE) |
|
||||
private readonly portfolioSnapshotQueue: Queue |
|
||||
) {} |
|
||||
|
|
||||
public async deleteJob(aId: string) { |
|
||||
let job = await this.dataGatheringQueue.getJob(aId); |
|
||||
|
|
||||
if (!job) { |
|
||||
job = await this.portfolioSnapshotQueue.getJob(aId); |
|
||||
} |
|
||||
|
|
||||
return job?.remove(); |
|
||||
} |
|
||||
|
|
||||
public async deleteJobs({ |
|
||||
status = QUEUE_JOB_STATUS_LIST |
|
||||
}: { |
|
||||
status?: JobStatus[]; |
|
||||
}) { |
|
||||
for (const statusItem of status) { |
|
||||
const queueStatus = statusItem === 'waiting' ? 'wait' : statusItem; |
|
||||
|
|
||||
await this.dataGatheringQueue.clean(300, queueStatus); |
|
||||
await this.portfolioSnapshotQueue.clean(300, queueStatus); |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
public async executeJob(aId: string) { |
|
||||
let job = await this.dataGatheringQueue.getJob(aId); |
|
||||
|
|
||||
if (!job) { |
|
||||
job = await this.portfolioSnapshotQueue.getJob(aId); |
|
||||
} |
|
||||
|
|
||||
return job?.promote(); |
|
||||
} |
|
||||
|
|
||||
public async getJobs({ |
|
||||
limit = 1000, |
|
||||
status = QUEUE_JOB_STATUS_LIST |
|
||||
}: { |
|
||||
limit?: number; |
|
||||
status?: JobStatus[]; |
|
||||
}): Promise<AdminJobs> { |
|
||||
const [dataGatheringJobs, portfolioSnapshotJobs] = await Promise.all([ |
|
||||
this.dataGatheringQueue.getJobs(status), |
|
||||
this.portfolioSnapshotQueue.getJobs(status) |
|
||||
]); |
|
||||
|
|
||||
const jobsWithState = await Promise.all( |
|
||||
[...dataGatheringJobs, ...portfolioSnapshotJobs] |
|
||||
.filter((job) => { |
|
||||
return job; |
|
||||
}) |
|
||||
.slice(0, limit) |
|
||||
.map(async (job) => { |
|
||||
return { |
|
||||
attemptsMade: job.attemptsMade, |
|
||||
data: job.data, |
|
||||
finishedOn: job.finishedOn, |
|
||||
id: job.id, |
|
||||
name: job.name, |
|
||||
opts: job.opts, |
|
||||
stacktrace: job.stacktrace, |
|
||||
state: await job.getState(), |
|
||||
timestamp: job.timestamp |
|
||||
}; |
|
||||
}) |
|
||||
); |
|
||||
|
|
||||
return { |
|
||||
jobs: jobsWithState |
|
||||
}; |
|
||||
} |
|
||||
} |
|
||||
@ -1,18 +0,0 @@ |
|||||
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.service'; |
|
||||
|
|
||||
import { Controller } from '@nestjs/common'; |
|
||||
|
|
||||
@Controller() |
|
||||
export class AppController { |
|
||||
public constructor( |
|
||||
private readonly exchangeRateDataService: ExchangeRateDataService |
|
||||
) { |
|
||||
this.initialize(); |
|
||||
} |
|
||||
|
|
||||
private async initialize() { |
|
||||
try { |
|
||||
await this.exchangeRateDataService.initialize(); |
|
||||
} catch {} |
|
||||
} |
|
||||
} |
|
||||
@ -1,148 +0,0 @@ |
|||||
import { EventsModule } from '@ghostfolio/api/events/events.module'; |
|
||||
import { HtmlTemplateMiddleware } from '@ghostfolio/api/middlewares/html-template.middleware'; |
|
||||
import { ConfigurationModule } from '@ghostfolio/api/services/configuration/configuration.module'; |
|
||||
import { CronModule } from '@ghostfolio/api/services/cron/cron.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 { I18nService } from '@ghostfolio/api/services/i18n/i18n.service'; |
|
||||
import { PrismaModule } from '@ghostfolio/api/services/prisma/prisma.module'; |
|
||||
import { PropertyModule } from '@ghostfolio/api/services/property/property.module'; |
|
||||
import { DataGatheringModule } from '@ghostfolio/api/services/queues/data-gathering/data-gathering.module'; |
|
||||
import { PortfolioSnapshotQueueModule } from '@ghostfolio/api/services/queues/portfolio-snapshot/portfolio-snapshot.module'; |
|
||||
import { |
|
||||
DEFAULT_LANGUAGE_CODE, |
|
||||
SUPPORTED_LANGUAGE_CODES |
|
||||
} from '@ghostfolio/common/config'; |
|
||||
|
|
||||
import { BullModule } from '@nestjs/bull'; |
|
||||
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common'; |
|
||||
import { ConfigModule } from '@nestjs/config'; |
|
||||
import { EventEmitterModule } from '@nestjs/event-emitter'; |
|
||||
import { ScheduleModule } from '@nestjs/schedule'; |
|
||||
import { ServeStaticModule } from '@nestjs/serve-static'; |
|
||||
import { StatusCodes } from 'http-status-codes'; |
|
||||
import { join } from 'node:path'; |
|
||||
|
|
||||
import { AccessModule } from './access/access.module'; |
|
||||
import { AccountModule } from './account/account.module'; |
|
||||
import { AdminModule } from './admin/admin.module'; |
|
||||
import { AppController } from './app.controller'; |
|
||||
import { AssetModule } from './asset/asset.module'; |
|
||||
import { AuthDeviceModule } from './auth-device/auth-device.module'; |
|
||||
import { AuthModule } from './auth/auth.module'; |
|
||||
import { CacheModule } from './cache/cache.module'; |
|
||||
import { AiModule } from './endpoints/ai/ai.module'; |
|
||||
import { ApiKeysModule } from './endpoints/api-keys/api-keys.module'; |
|
||||
import { AssetsModule } from './endpoints/assets/assets.module'; |
|
||||
import { BenchmarksModule } from './endpoints/benchmarks/benchmarks.module'; |
|
||||
import { GhostfolioModule } from './endpoints/data-providers/ghostfolio/ghostfolio.module'; |
|
||||
import { MarketDataModule } from './endpoints/market-data/market-data.module'; |
|
||||
import { PlatformsModule } from './endpoints/platforms/platforms.module'; |
|
||||
import { PublicModule } from './endpoints/public/public.module'; |
|
||||
import { SitemapModule } from './endpoints/sitemap/sitemap.module'; |
|
||||
import { TagsModule } from './endpoints/tags/tags.module'; |
|
||||
import { WatchlistModule } from './endpoints/watchlist/watchlist.module'; |
|
||||
import { ExchangeRateModule } from './exchange-rate/exchange-rate.module'; |
|
||||
import { ExportModule } from './export/export.module'; |
|
||||
import { HealthModule } from './health/health.module'; |
|
||||
import { ImportModule } from './import/import.module'; |
|
||||
import { InfoModule } from './info/info.module'; |
|
||||
import { LogoModule } from './logo/logo.module'; |
|
||||
import { OrderModule } from './order/order.module'; |
|
||||
import { PlatformModule } from './platform/platform.module'; |
|
||||
import { PortfolioModule } from './portfolio/portfolio.module'; |
|
||||
import { RedisCacheModule } from './redis-cache/redis-cache.module'; |
|
||||
import { SubscriptionModule } from './subscription/subscription.module'; |
|
||||
import { SymbolModule } from './symbol/symbol.module'; |
|
||||
import { UserModule } from './user/user.module'; |
|
||||
|
|
||||
@Module({ |
|
||||
controllers: [AppController], |
|
||||
imports: [ |
|
||||
AdminModule, |
|
||||
AccessModule, |
|
||||
AccountModule, |
|
||||
AiModule, |
|
||||
ApiKeysModule, |
|
||||
AssetModule, |
|
||||
AssetsModule, |
|
||||
AuthDeviceModule, |
|
||||
AuthModule, |
|
||||
BenchmarksModule, |
|
||||
BullModule.forRoot({ |
|
||||
redis: { |
|
||||
db: parseInt(process.env.REDIS_DB ?? '0', 10), |
|
||||
host: process.env.REDIS_HOST, |
|
||||
password: process.env.REDIS_PASSWORD, |
|
||||
port: parseInt(process.env.REDIS_PORT ?? '6379', 10) |
|
||||
} |
|
||||
}), |
|
||||
CacheModule, |
|
||||
ConfigModule.forRoot(), |
|
||||
ConfigurationModule, |
|
||||
CronModule, |
|
||||
DataGatheringModule, |
|
||||
DataProviderModule, |
|
||||
EventEmitterModule.forRoot(), |
|
||||
EventsModule, |
|
||||
ExchangeRateModule, |
|
||||
ExchangeRateDataModule, |
|
||||
ExportModule, |
|
||||
GhostfolioModule, |
|
||||
HealthModule, |
|
||||
ImportModule, |
|
||||
InfoModule, |
|
||||
LogoModule, |
|
||||
MarketDataModule, |
|
||||
OrderModule, |
|
||||
PlatformModule, |
|
||||
PlatformsModule, |
|
||||
PortfolioModule, |
|
||||
PortfolioSnapshotQueueModule, |
|
||||
PrismaModule, |
|
||||
PropertyModule, |
|
||||
PublicModule, |
|
||||
RedisCacheModule, |
|
||||
ScheduleModule.forRoot(), |
|
||||
ServeStaticModule.forRoot({ |
|
||||
exclude: ['/.well-known/*wildcard', '/api/*wildcard', '/sitemap.xml'], |
|
||||
rootPath: join(__dirname, '..', 'client'), |
|
||||
serveStaticOptions: { |
|
||||
setHeaders: (res) => { |
|
||||
if (res.req?.path === '/') { |
|
||||
let languageCode = DEFAULT_LANGUAGE_CODE; |
|
||||
|
|
||||
try { |
|
||||
const code = res.req.headers['accept-language'] |
|
||||
.split(',')[0] |
|
||||
.split('-')[0]; |
|
||||
|
|
||||
if (SUPPORTED_LANGUAGE_CODES.includes(code)) { |
|
||||
languageCode = code; |
|
||||
} |
|
||||
} catch {} |
|
||||
|
|
||||
res.set('Location', `/${languageCode}`); |
|
||||
res.statusCode = StatusCodes.MOVED_PERMANENTLY; |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
}), |
|
||||
ServeStaticModule.forRoot({ |
|
||||
rootPath: join(__dirname, '..', 'client', '.well-known'), |
|
||||
serveRoot: '/.well-known' |
|
||||
}), |
|
||||
SitemapModule, |
|
||||
SubscriptionModule, |
|
||||
SymbolModule, |
|
||||
TagsModule, |
|
||||
UserModule, |
|
||||
WatchlistModule |
|
||||
], |
|
||||
providers: [I18nService] |
|
||||
}) |
|
||||
export class AppModule implements NestModule { |
|
||||
public configure(consumer: MiddlewareConsumer) { |
|
||||
consumer.apply(HtmlTemplateMiddleware).forRoutes('*wildcard'); |
|
||||
} |
|
||||
} |
|
||||
@ -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,17 +0,0 @@ |
|||||
import { AdminModule } from '@ghostfolio/api/app/admin/admin.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 { Module } from '@nestjs/common'; |
|
||||
|
|
||||
import { AssetController } from './asset.controller'; |
|
||||
|
|
||||
@Module({ |
|
||||
controllers: [AssetController], |
|
||||
imports: [ |
|
||||
AdminModule, |
|
||||
TransformDataSourceInRequestModule, |
|
||||
TransformDataSourceInResponseModule |
|
||||
] |
|
||||
}) |
|
||||
export class AssetModule {} |
|
||||
@ -1,19 +0,0 @@ |
|||||
import { AuthDeviceService } from '@ghostfolio/api/app/auth-device/auth-device.service'; |
|
||||
import { HasPermission } from '@ghostfolio/api/decorators/has-permission.decorator'; |
|
||||
import { HasPermissionGuard } from '@ghostfolio/api/guards/has-permission.guard'; |
|
||||
import { permissions } from '@ghostfolio/common/permissions'; |
|
||||
|
|
||||
import { Controller, Delete, Param, UseGuards } from '@nestjs/common'; |
|
||||
import { AuthGuard } from '@nestjs/passport'; |
|
||||
|
|
||||
@Controller('auth-device') |
|
||||
export class AuthDeviceController { |
|
||||
public constructor(private readonly authDeviceService: AuthDeviceService) {} |
|
||||
|
|
||||
@Delete(':id') |
|
||||
@HasPermission(permissions.deleteAuthDevice) |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async deleteAuthDevice(@Param('id') id: string): Promise<void> { |
|
||||
await this.authDeviceService.deleteAuthDevice({ id }); |
|
||||
} |
|
||||
} |
|
||||
@ -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 {} |
|
||||
@ -1,62 +0,0 @@ |
|||||
import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service'; |
|
||||
|
|
||||
import { Injectable } from '@nestjs/common'; |
|
||||
import { AuthDevice, Prisma } from '@prisma/client'; |
|
||||
|
|
||||
@Injectable() |
|
||||
export class AuthDeviceService { |
|
||||
public constructor(private readonly prismaService: PrismaService) {} |
|
||||
|
|
||||
public async authDevice( |
|
||||
where: Prisma.AuthDeviceWhereUniqueInput |
|
||||
): Promise<AuthDevice | null> { |
|
||||
return this.prismaService.authDevice.findUnique({ |
|
||||
where |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
public async authDevices(params: { |
|
||||
skip?: number; |
|
||||
take?: number; |
|
||||
cursor?: Prisma.AuthDeviceWhereUniqueInput; |
|
||||
where?: Prisma.AuthDeviceWhereInput; |
|
||||
orderBy?: Prisma.AuthDeviceOrderByWithRelationInput; |
|
||||
}): Promise<AuthDevice[]> { |
|
||||
const { skip, take, cursor, where, orderBy } = params; |
|
||||
return this.prismaService.authDevice.findMany({ |
|
||||
skip, |
|
||||
take, |
|
||||
cursor, |
|
||||
where, |
|
||||
orderBy |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
public async createAuthDevice( |
|
||||
data: Prisma.AuthDeviceCreateInput |
|
||||
): Promise<AuthDevice> { |
|
||||
return this.prismaService.authDevice.create({ |
|
||||
data |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
public async updateAuthDevice(params: { |
|
||||
data: Prisma.AuthDeviceUpdateInput; |
|
||||
where: Prisma.AuthDeviceWhereUniqueInput; |
|
||||
}): Promise<AuthDevice> { |
|
||||
const { data, where } = params; |
|
||||
|
|
||||
return this.prismaService.authDevice.update({ |
|
||||
data, |
|
||||
where |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
public async deleteAuthDevice( |
|
||||
where: Prisma.AuthDeviceWhereUniqueInput |
|
||||
): Promise<AuthDevice> { |
|
||||
return this.prismaService.authDevice.delete({ |
|
||||
where |
|
||||
}); |
|
||||
} |
|
||||
} |
|
||||
@ -1,70 +0,0 @@ |
|||||
import { UserService } from '@ghostfolio/api/app/user/user.service'; |
|
||||
import { ApiKeyService } from '@ghostfolio/api/services/api-key/api-key.service'; |
|
||||
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; |
|
||||
import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service'; |
|
||||
import { HEADER_KEY_TOKEN } from '@ghostfolio/common/config'; |
|
||||
import { hasRole } from '@ghostfolio/common/permissions'; |
|
||||
|
|
||||
import { HttpException, Injectable } from '@nestjs/common'; |
|
||||
import { PassportStrategy } from '@nestjs/passport'; |
|
||||
import { StatusCodes, getReasonPhrase } from 'http-status-codes'; |
|
||||
import { HeaderAPIKeyStrategy } from 'passport-headerapikey'; |
|
||||
|
|
||||
@Injectable() |
|
||||
export class ApiKeyStrategy extends PassportStrategy( |
|
||||
HeaderAPIKeyStrategy, |
|
||||
'api-key' |
|
||||
) { |
|
||||
public constructor( |
|
||||
private readonly apiKeyService: ApiKeyService, |
|
||||
private readonly configurationService: ConfigurationService, |
|
||||
private readonly prismaService: PrismaService, |
|
||||
private readonly userService: UserService |
|
||||
) { |
|
||||
super({ header: HEADER_KEY_TOKEN, prefix: 'Api-Key ' }, false); |
|
||||
} |
|
||||
|
|
||||
public async validate(apiKey: string) { |
|
||||
const user = await this.validateApiKey(apiKey); |
|
||||
|
|
||||
if (this.configurationService.get('ENABLE_FEATURE_SUBSCRIPTION')) { |
|
||||
if (hasRole(user, 'INACTIVE')) { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.TOO_MANY_REQUESTS), |
|
||||
StatusCodes.TOO_MANY_REQUESTS |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
await this.prismaService.analytics.upsert({ |
|
||||
create: { user: { connect: { id: user.id } } }, |
|
||||
update: { |
|
||||
activityCount: { increment: 1 }, |
|
||||
lastRequestAt: new Date() |
|
||||
}, |
|
||||
where: { userId: user.id } |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
return user; |
|
||||
} |
|
||||
|
|
||||
private async validateApiKey(apiKey: string) { |
|
||||
if (!apiKey) { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.UNAUTHORIZED), |
|
||||
StatusCodes.UNAUTHORIZED |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
try { |
|
||||
const { id } = await this.apiKeyService.getUserByApiKey(apiKey); |
|
||||
|
|
||||
return this.userService.user({ id }); |
|
||||
} catch { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.UNAUTHORIZED), |
|
||||
StatusCodes.UNAUTHORIZED |
|
||||
); |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
@ -1,175 +0,0 @@ |
|||||
import { WebAuthService } from '@ghostfolio/api/app/auth/web-auth.service'; |
|
||||
import { HasPermissionGuard } from '@ghostfolio/api/guards/has-permission.guard'; |
|
||||
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; |
|
||||
import { DEFAULT_LANGUAGE_CODE } from '@ghostfolio/common/config'; |
|
||||
import { |
|
||||
AssertionCredentialJSON, |
|
||||
AttestationCredentialJSON, |
|
||||
OAuthResponse |
|
||||
} from '@ghostfolio/common/interfaces'; |
|
||||
|
|
||||
import { |
|
||||
Body, |
|
||||
Controller, |
|
||||
Get, |
|
||||
HttpException, |
|
||||
Param, |
|
||||
Post, |
|
||||
Req, |
|
||||
Res, |
|
||||
UseGuards, |
|
||||
Version, |
|
||||
VERSION_NEUTRAL |
|
||||
} from '@nestjs/common'; |
|
||||
import { AuthGuard } from '@nestjs/passport'; |
|
||||
import { Request, Response } from 'express'; |
|
||||
import { getReasonPhrase, StatusCodes } from 'http-status-codes'; |
|
||||
|
|
||||
import { AuthService } from './auth.service'; |
|
||||
|
|
||||
@Controller('auth') |
|
||||
export class AuthController { |
|
||||
public constructor( |
|
||||
private readonly authService: AuthService, |
|
||||
private readonly configurationService: ConfigurationService, |
|
||||
private readonly webAuthService: WebAuthService |
|
||||
) {} |
|
||||
|
|
||||
/** |
|
||||
* @deprecated |
|
||||
*/ |
|
||||
@Get('anonymous/:accessToken') |
|
||||
public async accessTokenLoginGet( |
|
||||
@Param('accessToken') accessToken: string |
|
||||
): Promise<OAuthResponse> { |
|
||||
try { |
|
||||
const authToken = |
|
||||
await this.authService.validateAnonymousLogin(accessToken); |
|
||||
return { authToken }; |
|
||||
} catch { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.FORBIDDEN), |
|
||||
StatusCodes.FORBIDDEN |
|
||||
); |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
@Post('anonymous') |
|
||||
public async accessTokenLogin( |
|
||||
@Body() body: { accessToken: string } |
|
||||
): Promise<OAuthResponse> { |
|
||||
try { |
|
||||
const authToken = await this.authService.validateAnonymousLogin( |
|
||||
body.accessToken |
|
||||
); |
|
||||
return { authToken }; |
|
||||
} catch { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.FORBIDDEN), |
|
||||
StatusCodes.FORBIDDEN |
|
||||
); |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
@Get('google') |
|
||||
@UseGuards(AuthGuard('google')) |
|
||||
public googleLogin() { |
|
||||
// Initiates the Google OAuth2 login flow
|
|
||||
} |
|
||||
|
|
||||
@Get('google/callback') |
|
||||
@UseGuards(AuthGuard('google')) |
|
||||
@Version(VERSION_NEUTRAL) |
|
||||
public googleLoginCallback( |
|
||||
@Req() request: Request, |
|
||||
@Res() response: Response |
|
||||
) { |
|
||||
const jwt: string = (request.user as any).jwt; |
|
||||
|
|
||||
if (jwt) { |
|
||||
response.redirect( |
|
||||
`${this.configurationService.get( |
|
||||
'ROOT_URL' |
|
||||
)}/${DEFAULT_LANGUAGE_CODE}/auth/${jwt}` |
|
||||
); |
|
||||
} else { |
|
||||
response.redirect( |
|
||||
`${this.configurationService.get( |
|
||||
'ROOT_URL' |
|
||||
)}/${DEFAULT_LANGUAGE_CODE}/auth` |
|
||||
); |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
@Get('oidc') |
|
||||
@UseGuards(AuthGuard('oidc')) |
|
||||
@Version(VERSION_NEUTRAL) |
|
||||
public oidcLogin() { |
|
||||
if (!this.configurationService.get('ENABLE_FEATURE_AUTH_OIDC')) { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.FORBIDDEN), |
|
||||
StatusCodes.FORBIDDEN |
|
||||
); |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
@Get('oidc/callback') |
|
||||
@UseGuards(AuthGuard('oidc')) |
|
||||
@Version(VERSION_NEUTRAL) |
|
||||
public oidcLoginCallback(@Req() request: Request, @Res() response: Response) { |
|
||||
const jwt: string = (request.user as any).jwt; |
|
||||
|
|
||||
if (jwt) { |
|
||||
response.redirect( |
|
||||
`${this.configurationService.get( |
|
||||
'ROOT_URL' |
|
||||
)}/${DEFAULT_LANGUAGE_CODE}/auth/${jwt}` |
|
||||
); |
|
||||
} else { |
|
||||
response.redirect( |
|
||||
`${this.configurationService.get( |
|
||||
'ROOT_URL' |
|
||||
)}/${DEFAULT_LANGUAGE_CODE}/auth` |
|
||||
); |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
@Post('webauthn/generate-authentication-options') |
|
||||
public async generateAuthenticationOptions( |
|
||||
@Body() body: { deviceId: string } |
|
||||
) { |
|
||||
return this.webAuthService.generateAuthenticationOptions(body.deviceId); |
|
||||
} |
|
||||
|
|
||||
@Get('webauthn/generate-registration-options') |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async generateRegistrationOptions() { |
|
||||
return this.webAuthService.generateRegistrationOptions(); |
|
||||
} |
|
||||
|
|
||||
@Post('webauthn/verify-attestation') |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async verifyAttestation( |
|
||||
@Body() body: { deviceName: string; credential: AttestationCredentialJSON } |
|
||||
) { |
|
||||
return this.webAuthService.verifyAttestation(body.credential); |
|
||||
} |
|
||||
|
|
||||
@Post('webauthn/verify-authentication') |
|
||||
public async verifyAuthentication( |
|
||||
@Body() body: { deviceId: string; credential: AssertionCredentialJSON } |
|
||||
) { |
|
||||
try { |
|
||||
const authToken = await this.webAuthService.verifyAuthentication( |
|
||||
body.deviceId, |
|
||||
body.credential |
|
||||
); |
|
||||
return { authToken }; |
|
||||
} catch { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.FORBIDDEN), |
|
||||
StatusCodes.FORBIDDEN |
|
||||
); |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
@ -1,122 +0,0 @@ |
|||||
import { AuthDeviceService } from '@ghostfolio/api/app/auth-device/auth-device.service'; |
|
||||
import { WebAuthService } from '@ghostfolio/api/app/auth/web-auth.service'; |
|
||||
import { SubscriptionModule } from '@ghostfolio/api/app/subscription/subscription.module'; |
|
||||
import { UserModule } from '@ghostfolio/api/app/user/user.module'; |
|
||||
import { ApiKeyService } from '@ghostfolio/api/services/api-key/api-key.service'; |
|
||||
import { ConfigurationModule } from '@ghostfolio/api/services/configuration/configuration.module'; |
|
||||
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; |
|
||||
import { PrismaModule } from '@ghostfolio/api/services/prisma/prisma.module'; |
|
||||
import { PropertyModule } from '@ghostfolio/api/services/property/property.module'; |
|
||||
|
|
||||
import { Logger, Module } from '@nestjs/common'; |
|
||||
import { JwtModule } from '@nestjs/jwt'; |
|
||||
import type { StrategyOptions } from 'passport-openidconnect'; |
|
||||
|
|
||||
import { ApiKeyStrategy } from './api-key.strategy'; |
|
||||
import { AuthController } from './auth.controller'; |
|
||||
import { AuthService } from './auth.service'; |
|
||||
import { GoogleStrategy } from './google.strategy'; |
|
||||
import { JwtStrategy } from './jwt.strategy'; |
|
||||
import { OidcStrategy } from './oidc.strategy'; |
|
||||
|
|
||||
@Module({ |
|
||||
controllers: [AuthController], |
|
||||
imports: [ |
|
||||
ConfigurationModule, |
|
||||
JwtModule.register({ |
|
||||
secret: process.env.JWT_SECRET_KEY, |
|
||||
signOptions: { expiresIn: '180 days' } |
|
||||
}), |
|
||||
PrismaModule, |
|
||||
PropertyModule, |
|
||||
SubscriptionModule, |
|
||||
UserModule |
|
||||
], |
|
||||
providers: [ |
|
||||
ApiKeyService, |
|
||||
ApiKeyStrategy, |
|
||||
AuthDeviceService, |
|
||||
AuthService, |
|
||||
GoogleStrategy, |
|
||||
JwtStrategy, |
|
||||
{ |
|
||||
inject: [AuthService, ConfigurationService], |
|
||||
provide: OidcStrategy, |
|
||||
useFactory: async ( |
|
||||
authService: AuthService, |
|
||||
configurationService: ConfigurationService |
|
||||
) => { |
|
||||
const isOidcEnabled = configurationService.get( |
|
||||
'ENABLE_FEATURE_AUTH_OIDC' |
|
||||
); |
|
||||
|
|
||||
if (!isOidcEnabled) { |
|
||||
return null; |
|
||||
} |
|
||||
|
|
||||
const issuer = configurationService.get('OIDC_ISSUER'); |
|
||||
const scope = configurationService.get('OIDC_SCOPE'); |
|
||||
|
|
||||
const callbackUrl = |
|
||||
configurationService.get('OIDC_CALLBACK_URL') || |
|
||||
`${configurationService.get('ROOT_URL')}/api/auth/oidc/callback`; |
|
||||
|
|
||||
// Check for manual URL overrides
|
|
||||
const manualAuthorizationUrl = configurationService.get( |
|
||||
'OIDC_AUTHORIZATION_URL' |
|
||||
); |
|
||||
const manualTokenUrl = configurationService.get('OIDC_TOKEN_URL'); |
|
||||
const manualUserInfoUrl = |
|
||||
configurationService.get('OIDC_USER_INFO_URL'); |
|
||||
|
|
||||
let authorizationURL: string; |
|
||||
let tokenURL: string; |
|
||||
let userInfoURL: string; |
|
||||
|
|
||||
if (manualAuthorizationUrl && manualTokenUrl && manualUserInfoUrl) { |
|
||||
// Use manual URLs
|
|
||||
authorizationURL = manualAuthorizationUrl; |
|
||||
tokenURL = manualTokenUrl; |
|
||||
userInfoURL = manualUserInfoUrl; |
|
||||
} else { |
|
||||
// Fetch OIDC configuration from discovery endpoint
|
|
||||
try { |
|
||||
const response = await fetch( |
|
||||
`${issuer}/.well-known/openid-configuration` |
|
||||
); |
|
||||
|
|
||||
const config = (await response.json()) as { |
|
||||
authorization_endpoint: string; |
|
||||
token_endpoint: string; |
|
||||
userinfo_endpoint: string; |
|
||||
}; |
|
||||
|
|
||||
// Manual URLs take priority over discovered ones
|
|
||||
authorizationURL = |
|
||||
manualAuthorizationUrl || config.authorization_endpoint; |
|
||||
tokenURL = manualTokenUrl || config.token_endpoint; |
|
||||
userInfoURL = manualUserInfoUrl || config.userinfo_endpoint; |
|
||||
} catch (error) { |
|
||||
Logger.error(error, 'OidcStrategy'); |
|
||||
throw new Error('Failed to fetch OIDC configuration from issuer'); |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
const options: StrategyOptions = { |
|
||||
authorizationURL, |
|
||||
issuer, |
|
||||
scope, |
|
||||
tokenURL, |
|
||||
userInfoURL, |
|
||||
callbackURL: callbackUrl, |
|
||||
clientID: configurationService.get('OIDC_CLIENT_ID'), |
|
||||
clientSecret: configurationService.get('OIDC_CLIENT_SECRET') |
|
||||
}; |
|
||||
|
|
||||
return new OidcStrategy(authService, options); |
|
||||
} |
|
||||
}, |
|
||||
WebAuthService |
|
||||
] |
|
||||
}) |
|
||||
export class AuthModule {} |
|
||||
@ -1,74 +0,0 @@ |
|||||
import { UserService } from '@ghostfolio/api/app/user/user.service'; |
|
||||
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; |
|
||||
import { PropertyService } from '@ghostfolio/api/services/property/property.service'; |
|
||||
|
|
||||
import { Injectable, InternalServerErrorException } from '@nestjs/common'; |
|
||||
import { JwtService } from '@nestjs/jwt'; |
|
||||
|
|
||||
import { ValidateOAuthLoginParams } from './interfaces/interfaces'; |
|
||||
|
|
||||
@Injectable() |
|
||||
export class AuthService { |
|
||||
public constructor( |
|
||||
private readonly configurationService: ConfigurationService, |
|
||||
private readonly jwtService: JwtService, |
|
||||
private readonly propertyService: PropertyService, |
|
||||
private readonly userService: UserService |
|
||||
) {} |
|
||||
|
|
||||
public async validateAnonymousLogin(accessToken: string): Promise<string> { |
|
||||
const hashedAccessToken = this.userService.createAccessToken({ |
|
||||
password: accessToken, |
|
||||
salt: this.configurationService.get('ACCESS_TOKEN_SALT') |
|
||||
}); |
|
||||
|
|
||||
const [user] = await this.userService.users({ |
|
||||
where: { accessToken: hashedAccessToken } |
|
||||
}); |
|
||||
|
|
||||
if (user) { |
|
||||
return this.jwtService.sign({ |
|
||||
id: user.id |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
throw new Error(); |
|
||||
} |
|
||||
|
|
||||
public async validateOAuthLogin({ |
|
||||
provider, |
|
||||
thirdPartyId |
|
||||
}: ValidateOAuthLoginParams): Promise<string> { |
|
||||
try { |
|
||||
let [user] = await this.userService.users({ |
|
||||
where: { provider, thirdPartyId } |
|
||||
}); |
|
||||
|
|
||||
if (!user) { |
|
||||
const isUserSignupEnabled = |
|
||||
await this.propertyService.isUserSignupEnabled(); |
|
||||
|
|
||||
if (!isUserSignupEnabled) { |
|
||||
throw new Error('Sign up forbidden'); |
|
||||
} |
|
||||
|
|
||||
// Create new user if not found
|
|
||||
user = await this.userService.createUser({ |
|
||||
data: { |
|
||||
provider, |
|
||||
thirdPartyId |
|
||||
} |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
return this.jwtService.sign({ |
|
||||
id: user.id |
|
||||
}); |
|
||||
} catch (error) { |
|
||||
throw new InternalServerErrorException( |
|
||||
'validateOAuthLogin', |
|
||||
error instanceof Error ? error.message : 'Unknown error' |
|
||||
); |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
@ -1,47 +0,0 @@ |
|||||
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; |
|
||||
|
|
||||
import { Injectable, Logger } from '@nestjs/common'; |
|
||||
import { PassportStrategy } from '@nestjs/passport'; |
|
||||
import { Provider } from '@prisma/client'; |
|
||||
import { DoneCallback } from 'passport'; |
|
||||
import { Profile, Strategy } from 'passport-google-oauth20'; |
|
||||
|
|
||||
import { AuthService } from './auth.service'; |
|
||||
|
|
||||
@Injectable() |
|
||||
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') { |
|
||||
public constructor( |
|
||||
private readonly authService: AuthService, |
|
||||
configurationService: ConfigurationService |
|
||||
) { |
|
||||
super({ |
|
||||
callbackURL: `${configurationService.get( |
|
||||
'ROOT_URL' |
|
||||
)}/api/auth/google/callback`,
|
|
||||
clientID: configurationService.get('GOOGLE_CLIENT_ID'), |
|
||||
clientSecret: configurationService.get('GOOGLE_SECRET'), |
|
||||
passReqToCallback: true, |
|
||||
scope: ['profile'] |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
public async validate( |
|
||||
_request: any, |
|
||||
_token: string, |
|
||||
_refreshToken: string, |
|
||||
profile: Profile, |
|
||||
done: DoneCallback |
|
||||
) { |
|
||||
try { |
|
||||
const jwt = await this.authService.validateOAuthLogin({ |
|
||||
provider: Provider.GOOGLE, |
|
||||
thirdPartyId: profile.id |
|
||||
}); |
|
||||
|
|
||||
done(null, { jwt }); |
|
||||
} catch (error) { |
|
||||
Logger.error(error, 'GoogleStrategy'); |
|
||||
done(error, false); |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
@ -1,31 +0,0 @@ |
|||||
import { AuthDeviceDto } from '@ghostfolio/common/dtos'; |
|
||||
|
|
||||
import { Provider } from '@prisma/client'; |
|
||||
|
|
||||
export interface AuthDeviceDialogParams { |
|
||||
authDevice: AuthDeviceDto; |
|
||||
} |
|
||||
|
|
||||
export interface OidcContext { |
|
||||
claims?: { |
|
||||
sub?: string; |
|
||||
}; |
|
||||
} |
|
||||
|
|
||||
export interface OidcIdToken { |
|
||||
sub?: string; |
|
||||
} |
|
||||
|
|
||||
export interface OidcParams { |
|
||||
sub?: string; |
|
||||
} |
|
||||
|
|
||||
export interface OidcProfile { |
|
||||
id?: string; |
|
||||
sub?: string; |
|
||||
} |
|
||||
|
|
||||
export interface ValidateOAuthLoginParams { |
|
||||
provider: Provider; |
|
||||
thirdPartyId: string; |
|
||||
} |
|
||||
@ -1,85 +0,0 @@ |
|||||
import { UserService } from '@ghostfolio/api/app/user/user.service'; |
|
||||
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; |
|
||||
import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service'; |
|
||||
import { |
|
||||
DEFAULT_CURRENCY, |
|
||||
DEFAULT_LANGUAGE_CODE, |
|
||||
HEADER_KEY_TIMEZONE |
|
||||
} from '@ghostfolio/common/config'; |
|
||||
import { hasRole } from '@ghostfolio/common/permissions'; |
|
||||
|
|
||||
import { HttpException, Injectable } from '@nestjs/common'; |
|
||||
import { PassportStrategy } from '@nestjs/passport'; |
|
||||
import * as countriesAndTimezones from 'countries-and-timezones'; |
|
||||
import { StatusCodes, getReasonPhrase } from 'http-status-codes'; |
|
||||
import { ExtractJwt, Strategy } from 'passport-jwt'; |
|
||||
|
|
||||
@Injectable() |
|
||||
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') { |
|
||||
public constructor( |
|
||||
private readonly configurationService: ConfigurationService, |
|
||||
private readonly prismaService: PrismaService, |
|
||||
private readonly userService: UserService |
|
||||
) { |
|
||||
super({ |
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), |
|
||||
passReqToCallback: true, |
|
||||
secretOrKey: configurationService.get('JWT_SECRET_KEY') |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
public async validate(request: Request, { id }: { id: string }) { |
|
||||
try { |
|
||||
const timezone = request.headers[HEADER_KEY_TIMEZONE.toLowerCase()]; |
|
||||
const user = await this.userService.user({ id }); |
|
||||
|
|
||||
if (user) { |
|
||||
if (this.configurationService.get('ENABLE_FEATURE_SUBSCRIPTION')) { |
|
||||
if (hasRole(user, 'INACTIVE')) { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.TOO_MANY_REQUESTS), |
|
||||
StatusCodes.TOO_MANY_REQUESTS |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
const country = |
|
||||
countriesAndTimezones.getCountryForTimezone(timezone)?.id; |
|
||||
|
|
||||
await this.prismaService.analytics.upsert({ |
|
||||
create: { country, user: { connect: { id: user.id } } }, |
|
||||
update: { |
|
||||
country, |
|
||||
activityCount: { increment: 1 }, |
|
||||
lastRequestAt: new Date() |
|
||||
}, |
|
||||
where: { userId: user.id } |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
if (!user.settings.settings.baseCurrency) { |
|
||||
user.settings.settings.baseCurrency = DEFAULT_CURRENCY; |
|
||||
} |
|
||||
|
|
||||
if (!user.settings.settings.language) { |
|
||||
user.settings.settings.language = DEFAULT_LANGUAGE_CODE; |
|
||||
} |
|
||||
|
|
||||
return user; |
|
||||
} else { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.NOT_FOUND), |
|
||||
StatusCodes.NOT_FOUND |
|
||||
); |
|
||||
} |
|
||||
} catch (error) { |
|
||||
if (error?.getStatus?.() === StatusCodes.TOO_MANY_REQUESTS) { |
|
||||
throw error; |
|
||||
} else { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.UNAUTHORIZED), |
|
||||
StatusCodes.UNAUTHORIZED |
|
||||
); |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
@ -1,114 +0,0 @@ |
|||||
import ms from 'ms'; |
|
||||
|
|
||||
/** |
|
||||
* Custom state store for OIDC authentication that doesn't rely on express-session. |
|
||||
* This store manages OAuth2 state parameters in memory with automatic cleanup. |
|
||||
*/ |
|
||||
export class OidcStateStore { |
|
||||
private readonly STATE_EXPIRY_MS = ms('10 minutes'); |
|
||||
|
|
||||
private stateMap = new Map< |
|
||||
string, |
|
||||
{ |
|
||||
appState?: unknown; |
|
||||
ctx: { issued?: Date; maxAge?: number; nonce?: string }; |
|
||||
meta?: unknown; |
|
||||
timestamp: number; |
|
||||
} |
|
||||
>(); |
|
||||
|
|
||||
/** |
|
||||
* Store request state. |
|
||||
* Signature matches passport-openidconnect SessionStore |
|
||||
*/ |
|
||||
public store( |
|
||||
_req: unknown, |
|
||||
_meta: unknown, |
|
||||
appState: unknown, |
|
||||
ctx: { maxAge?: number; nonce?: string; issued?: Date }, |
|
||||
callback: (err: Error | null, handle?: string) => void |
|
||||
) { |
|
||||
try { |
|
||||
// Generate a unique handle for this state
|
|
||||
const handle = this.generateHandle(); |
|
||||
|
|
||||
this.stateMap.set(handle, { |
|
||||
appState, |
|
||||
ctx, |
|
||||
meta: _meta, |
|
||||
timestamp: Date.now() |
|
||||
}); |
|
||||
|
|
||||
// Clean up expired states
|
|
||||
this.cleanup(); |
|
||||
|
|
||||
callback(null, handle); |
|
||||
} catch (error) { |
|
||||
callback(error as Error); |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
/** |
|
||||
* Verify request state. |
|
||||
* Signature matches passport-openidconnect SessionStore |
|
||||
*/ |
|
||||
public verify( |
|
||||
_req: unknown, |
|
||||
handle: string, |
|
||||
callback: ( |
|
||||
err: Error | null, |
|
||||
appState?: unknown, |
|
||||
ctx?: { maxAge?: number; nonce?: string; issued?: Date } |
|
||||
) => void |
|
||||
) { |
|
||||
try { |
|
||||
const data = this.stateMap.get(handle); |
|
||||
|
|
||||
if (!data) { |
|
||||
return callback(null, undefined, undefined); |
|
||||
} |
|
||||
|
|
||||
if (Date.now() - data.timestamp > this.STATE_EXPIRY_MS) { |
|
||||
// State has expired
|
|
||||
this.stateMap.delete(handle); |
|
||||
return callback(null, undefined, undefined); |
|
||||
} |
|
||||
|
|
||||
// Remove state after verification (one-time use)
|
|
||||
this.stateMap.delete(handle); |
|
||||
|
|
||||
callback(null, data.ctx, data.appState); |
|
||||
} catch (error) { |
|
||||
callback(error as Error); |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
/** |
|
||||
* Clean up expired states |
|
||||
*/ |
|
||||
private cleanup() { |
|
||||
const now = Date.now(); |
|
||||
const expiredKeys: string[] = []; |
|
||||
|
|
||||
for (const [key, value] of this.stateMap.entries()) { |
|
||||
if (now - value.timestamp > this.STATE_EXPIRY_MS) { |
|
||||
expiredKeys.push(key); |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
for (const key of expiredKeys) { |
|
||||
this.stateMap.delete(key); |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
/** |
|
||||
* Generate a cryptographically secure random handle |
|
||||
*/ |
|
||||
private generateHandle() { |
|
||||
return ( |
|
||||
Math.random().toString(36).substring(2, 15) + |
|
||||
Math.random().toString(36).substring(2, 15) + |
|
||||
Date.now().toString(36) |
|
||||
); |
|
||||
} |
|
||||
} |
|
||||
@ -1,69 +0,0 @@ |
|||||
import { Injectable, Logger } from '@nestjs/common'; |
|
||||
import { PassportStrategy } from '@nestjs/passport'; |
|
||||
import { Provider } from '@prisma/client'; |
|
||||
import { Request } from 'express'; |
|
||||
import { Strategy, type StrategyOptions } from 'passport-openidconnect'; |
|
||||
|
|
||||
import { AuthService } from './auth.service'; |
|
||||
import { |
|
||||
OidcContext, |
|
||||
OidcIdToken, |
|
||||
OidcParams, |
|
||||
OidcProfile |
|
||||
} from './interfaces/interfaces'; |
|
||||
import { OidcStateStore } from './oidc-state.store'; |
|
||||
|
|
||||
@Injectable() |
|
||||
export class OidcStrategy extends PassportStrategy(Strategy, 'oidc') { |
|
||||
private static readonly stateStore = new OidcStateStore(); |
|
||||
|
|
||||
public constructor( |
|
||||
private readonly authService: AuthService, |
|
||||
options: StrategyOptions |
|
||||
) { |
|
||||
super({ |
|
||||
...options, |
|
||||
passReqToCallback: true, |
|
||||
store: OidcStrategy.stateStore |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
public async validate( |
|
||||
_request: Request, |
|
||||
issuer: string, |
|
||||
profile: OidcProfile, |
|
||||
context: OidcContext, |
|
||||
idToken: OidcIdToken, |
|
||||
_accessToken: string, |
|
||||
_refreshToken: string, |
|
||||
params: OidcParams |
|
||||
) { |
|
||||
try { |
|
||||
const thirdPartyId = |
|
||||
profile?.id ?? |
|
||||
profile?.sub ?? |
|
||||
idToken?.sub ?? |
|
||||
params?.sub ?? |
|
||||
context?.claims?.sub; |
|
||||
|
|
||||
const jwt = await this.authService.validateOAuthLogin({ |
|
||||
thirdPartyId, |
|
||||
provider: Provider.OIDC |
|
||||
}); |
|
||||
|
|
||||
if (!thirdPartyId) { |
|
||||
Logger.error( |
|
||||
`Missing subject identifier in OIDC response from ${issuer}`, |
|
||||
'OidcStrategy' |
|
||||
); |
|
||||
|
|
||||
throw new Error('Missing subject identifier in OIDC response'); |
|
||||
} |
|
||||
|
|
||||
return { jwt }; |
|
||||
} catch (error) { |
|
||||
Logger.error(error, 'OidcStrategy'); |
|
||||
throw error; |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
@ -1,234 +0,0 @@ |
|||||
import { AuthDeviceService } from '@ghostfolio/api/app/auth-device/auth-device.service'; |
|
||||
import { UserService } from '@ghostfolio/api/app/user/user.service'; |
|
||||
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; |
|
||||
import { AuthDeviceDto } from '@ghostfolio/common/dtos'; |
|
||||
import { |
|
||||
AssertionCredentialJSON, |
|
||||
AttestationCredentialJSON |
|
||||
} from '@ghostfolio/common/interfaces'; |
|
||||
import type { RequestWithUser } from '@ghostfolio/common/types'; |
|
||||
|
|
||||
import { |
|
||||
Inject, |
|
||||
Injectable, |
|
||||
InternalServerErrorException, |
|
||||
Logger |
|
||||
} from '@nestjs/common'; |
|
||||
import { REQUEST } from '@nestjs/core'; |
|
||||
import { JwtService } from '@nestjs/jwt'; |
|
||||
import { |
|
||||
generateAuthenticationOptions, |
|
||||
GenerateAuthenticationOptionsOpts, |
|
||||
generateRegistrationOptions, |
|
||||
GenerateRegistrationOptionsOpts, |
|
||||
VerifiedAuthenticationResponse, |
|
||||
VerifiedRegistrationResponse, |
|
||||
verifyAuthenticationResponse, |
|
||||
VerifyAuthenticationResponseOpts, |
|
||||
verifyRegistrationResponse, |
|
||||
VerifyRegistrationResponseOpts |
|
||||
} from '@simplewebauthn/server'; |
|
||||
import { isoBase64URL, isoUint8Array } from '@simplewebauthn/server/helpers'; |
|
||||
import ms from 'ms'; |
|
||||
|
|
||||
@Injectable() |
|
||||
export class WebAuthService { |
|
||||
public constructor( |
|
||||
private readonly configurationService: ConfigurationService, |
|
||||
private readonly deviceService: AuthDeviceService, |
|
||||
private readonly jwtService: JwtService, |
|
||||
private readonly userService: UserService, |
|
||||
@Inject(REQUEST) private readonly request: RequestWithUser |
|
||||
) {} |
|
||||
|
|
||||
private get expectedOrigin() { |
|
||||
return this.configurationService.get('ROOT_URL'); |
|
||||
} |
|
||||
|
|
||||
private get rpID() { |
|
||||
return new URL(this.configurationService.get('ROOT_URL')).hostname; |
|
||||
} |
|
||||
|
|
||||
public async generateRegistrationOptions() { |
|
||||
const user = this.request.user; |
|
||||
|
|
||||
const opts: GenerateRegistrationOptionsOpts = { |
|
||||
authenticatorSelection: { |
|
||||
authenticatorAttachment: 'platform', |
|
||||
residentKey: 'required', |
|
||||
userVerification: 'preferred' |
|
||||
}, |
|
||||
rpID: this.rpID, |
|
||||
rpName: 'Ghostfolio', |
|
||||
timeout: ms('60 seconds'), |
|
||||
userID: isoUint8Array.fromUTF8String(user.id), |
|
||||
userName: '' |
|
||||
}; |
|
||||
|
|
||||
const registrationOptions = await generateRegistrationOptions(opts); |
|
||||
|
|
||||
await this.userService.updateUser({ |
|
||||
data: { |
|
||||
authChallenge: registrationOptions.challenge |
|
||||
}, |
|
||||
where: { |
|
||||
id: user.id |
|
||||
} |
|
||||
}); |
|
||||
|
|
||||
return registrationOptions; |
|
||||
} |
|
||||
|
|
||||
public async verifyAttestation( |
|
||||
credential: AttestationCredentialJSON |
|
||||
): Promise<AuthDeviceDto> { |
|
||||
const user = this.request.user; |
|
||||
const expectedChallenge = user.authChallenge; |
|
||||
let verification: VerifiedRegistrationResponse; |
|
||||
|
|
||||
try { |
|
||||
const opts: VerifyRegistrationResponseOpts = { |
|
||||
expectedChallenge, |
|
||||
expectedOrigin: this.expectedOrigin, |
|
||||
expectedRPID: this.rpID, |
|
||||
requireUserVerification: false, |
|
||||
response: { |
|
||||
clientExtensionResults: credential.clientExtensionResults, |
|
||||
id: credential.id, |
|
||||
rawId: credential.rawId, |
|
||||
response: credential.response, |
|
||||
type: 'public-key' |
|
||||
} |
|
||||
}; |
|
||||
|
|
||||
verification = await verifyRegistrationResponse(opts); |
|
||||
} catch (error) { |
|
||||
Logger.error(error, 'WebAuthService'); |
|
||||
throw new InternalServerErrorException(error.message); |
|
||||
} |
|
||||
|
|
||||
const { registrationInfo, verified } = verification; |
|
||||
|
|
||||
const devices = await this.deviceService.authDevices({ |
|
||||
where: { userId: user.id } |
|
||||
}); |
|
||||
if (registrationInfo && verified) { |
|
||||
const { |
|
||||
credential: { |
|
||||
counter, |
|
||||
id: credentialId, |
|
||||
publicKey: credentialPublicKey |
|
||||
} |
|
||||
} = registrationInfo; |
|
||||
|
|
||||
let existingDevice = devices.find((device) => { |
|
||||
return isoBase64URL.fromBuffer(device.credentialId) === credentialId; |
|
||||
}); |
|
||||
|
|
||||
if (!existingDevice) { |
|
||||
/** |
|
||||
* Add the returned device to the user's list of devices |
|
||||
*/ |
|
||||
existingDevice = await this.deviceService.createAuthDevice({ |
|
||||
counter, |
|
||||
credentialId: Buffer.from(credentialId), |
|
||||
credentialPublicKey: Buffer.from(credentialPublicKey), |
|
||||
user: { connect: { id: user.id } } |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
return { |
|
||||
createdAt: existingDevice.createdAt.toISOString(), |
|
||||
id: existingDevice.id |
|
||||
}; |
|
||||
} |
|
||||
|
|
||||
throw new InternalServerErrorException('An unknown error occurred'); |
|
||||
} |
|
||||
|
|
||||
public async generateAuthenticationOptions(deviceId: string) { |
|
||||
const device = await this.deviceService.authDevice({ id: deviceId }); |
|
||||
|
|
||||
if (!device) { |
|
||||
throw new Error('Device not found'); |
|
||||
} |
|
||||
|
|
||||
const opts: GenerateAuthenticationOptionsOpts = { |
|
||||
allowCredentials: [], |
|
||||
rpID: this.rpID, |
|
||||
timeout: ms('60 seconds'), |
|
||||
userVerification: 'preferred' |
|
||||
}; |
|
||||
|
|
||||
const authenticationOptions = await generateAuthenticationOptions(opts); |
|
||||
|
|
||||
await this.userService.updateUser({ |
|
||||
data: { |
|
||||
authChallenge: authenticationOptions.challenge |
|
||||
}, |
|
||||
where: { |
|
||||
id: device.userId |
|
||||
} |
|
||||
}); |
|
||||
|
|
||||
return authenticationOptions; |
|
||||
} |
|
||||
|
|
||||
public async verifyAuthentication( |
|
||||
deviceId: string, |
|
||||
credential: AssertionCredentialJSON |
|
||||
) { |
|
||||
const device = await this.deviceService.authDevice({ id: deviceId }); |
|
||||
|
|
||||
if (!device) { |
|
||||
throw new Error('Device not found'); |
|
||||
} |
|
||||
|
|
||||
const user = await this.userService.user({ id: device.userId }); |
|
||||
|
|
||||
let verification: VerifiedAuthenticationResponse; |
|
||||
|
|
||||
try { |
|
||||
const opts: VerifyAuthenticationResponseOpts = { |
|
||||
credential: { |
|
||||
counter: device.counter, |
|
||||
id: isoBase64URL.fromBuffer(device.credentialId), |
|
||||
publicKey: device.credentialPublicKey |
|
||||
}, |
|
||||
expectedChallenge: `${user.authChallenge}`, |
|
||||
expectedOrigin: this.expectedOrigin, |
|
||||
expectedRPID: this.rpID, |
|
||||
requireUserVerification: false, |
|
||||
response: { |
|
||||
clientExtensionResults: credential.clientExtensionResults, |
|
||||
id: credential.id, |
|
||||
rawId: credential.rawId, |
|
||||
response: credential.response, |
|
||||
type: 'public-key' |
|
||||
} |
|
||||
}; |
|
||||
|
|
||||
verification = await verifyAuthenticationResponse(opts); |
|
||||
} catch (error) { |
|
||||
Logger.error(error, 'WebAuthService'); |
|
||||
throw new InternalServerErrorException({ error: error.message }); |
|
||||
} |
|
||||
|
|
||||
const { authenticationInfo, verified } = verification; |
|
||||
|
|
||||
if (verified) { |
|
||||
device.counter = authenticationInfo.newCounter; |
|
||||
|
|
||||
await this.deviceService.updateAuthDevice({ |
|
||||
data: device, |
|
||||
where: { id: device.id } |
|
||||
}); |
|
||||
|
|
||||
return this.jwtService.sign({ |
|
||||
id: user.id |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
throw new Error(); |
|
||||
} |
|
||||
} |
|
||||
@ -1,19 +0,0 @@ |
|||||
import { RedisCacheService } from '@ghostfolio/api/app/redis-cache/redis-cache.service'; |
|
||||
import { HasPermission } from '@ghostfolio/api/decorators/has-permission.decorator'; |
|
||||
import { HasPermissionGuard } from '@ghostfolio/api/guards/has-permission.guard'; |
|
||||
import { permissions } from '@ghostfolio/common/permissions'; |
|
||||
|
|
||||
import { Controller, Post, UseGuards } from '@nestjs/common'; |
|
||||
import { AuthGuard } from '@nestjs/passport'; |
|
||||
|
|
||||
@Controller('cache') |
|
||||
export class CacheController { |
|
||||
public constructor(private readonly redisCacheService: RedisCacheService) {} |
|
||||
|
|
||||
@HasPermission(permissions.accessAdminControl) |
|
||||
@Post('flush') |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async flushCache(): Promise<void> { |
|
||||
await this.redisCacheService.reset(); |
|
||||
} |
|
||||
} |
|
||||
@ -1,11 +0,0 @@ |
|||||
import { RedisCacheModule } from '@ghostfolio/api/app/redis-cache/redis-cache.module'; |
|
||||
|
|
||||
import { Module } from '@nestjs/common'; |
|
||||
|
|
||||
import { CacheController } from './cache.controller'; |
|
||||
|
|
||||
@Module({ |
|
||||
controllers: [CacheController], |
|
||||
imports: [RedisCacheModule] |
|
||||
}) |
|
||||
export class CacheModule {} |
|
||||
@ -1,59 +0,0 @@ |
|||||
import { HasPermission } from '@ghostfolio/api/decorators/has-permission.decorator'; |
|
||||
import { HasPermissionGuard } from '@ghostfolio/api/guards/has-permission.guard'; |
|
||||
import { ApiService } from '@ghostfolio/api/services/api/api.service'; |
|
||||
import { AiPromptResponse } from '@ghostfolio/common/interfaces'; |
|
||||
import { permissions } from '@ghostfolio/common/permissions'; |
|
||||
import type { AiPromptMode, RequestWithUser } from '@ghostfolio/common/types'; |
|
||||
|
|
||||
import { |
|
||||
Controller, |
|
||||
Get, |
|
||||
Inject, |
|
||||
Param, |
|
||||
Query, |
|
||||
UseGuards |
|
||||
} from '@nestjs/common'; |
|
||||
import { REQUEST } from '@nestjs/core'; |
|
||||
import { AuthGuard } from '@nestjs/passport'; |
|
||||
|
|
||||
import { AiService } from './ai.service'; |
|
||||
|
|
||||
@Controller('ai') |
|
||||
export class AiController { |
|
||||
public constructor( |
|
||||
private readonly aiService: AiService, |
|
||||
private readonly apiService: ApiService, |
|
||||
@Inject(REQUEST) private readonly request: RequestWithUser |
|
||||
) {} |
|
||||
|
|
||||
@Get('prompt/:mode') |
|
||||
@HasPermission(permissions.readAiPrompt) |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async getPrompt( |
|
||||
@Param('mode') mode: AiPromptMode, |
|
||||
@Query('accounts') filterByAccounts?: string, |
|
||||
@Query('assetClasses') filterByAssetClasses?: string, |
|
||||
@Query('dataSource') filterByDataSource?: string, |
|
||||
@Query('symbol') filterBySymbol?: string, |
|
||||
@Query('tags') filterByTags?: string |
|
||||
): Promise<AiPromptResponse> { |
|
||||
const filters = this.apiService.buildFiltersFromQueryParams({ |
|
||||
filterByAccounts, |
|
||||
filterByAssetClasses, |
|
||||
filterByDataSource, |
|
||||
filterBySymbol, |
|
||||
filterByTags |
|
||||
}); |
|
||||
|
|
||||
const prompt = await this.aiService.getPrompt({ |
|
||||
filters, |
|
||||
mode, |
|
||||
impersonationId: undefined, |
|
||||
languageCode: this.request.user.settings.settings.language, |
|
||||
userCurrency: this.request.user.settings.settings.baseCurrency, |
|
||||
userId: this.request.user.id |
|
||||
}); |
|
||||
|
|
||||
return { prompt }; |
|
||||
} |
|
||||
} |
|
||||
@ -1,59 +0,0 @@ |
|||||
import { AccountBalanceService } from '@ghostfolio/api/app/account-balance/account-balance.service'; |
|
||||
import { AccountService } from '@ghostfolio/api/app/account/account.service'; |
|
||||
import { OrderModule } from '@ghostfolio/api/app/order/order.module'; |
|
||||
import { PortfolioCalculatorFactory } from '@ghostfolio/api/app/portfolio/calculator/portfolio-calculator.factory'; |
|
||||
import { CurrentRateService } from '@ghostfolio/api/app/portfolio/current-rate.service'; |
|
||||
import { PortfolioService } from '@ghostfolio/api/app/portfolio/portfolio.service'; |
|
||||
import { RulesService } from '@ghostfolio/api/app/portfolio/rules.service'; |
|
||||
import { RedisCacheModule } from '@ghostfolio/api/app/redis-cache/redis-cache.module'; |
|
||||
import { UserModule } from '@ghostfolio/api/app/user/user.module'; |
|
||||
import { ApiModule } from '@ghostfolio/api/services/api/api.module'; |
|
||||
import { BenchmarkModule } from '@ghostfolio/api/services/benchmark/benchmark.module'; |
|
||||
import { ConfigurationModule } from '@ghostfolio/api/services/configuration/configuration.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 { I18nModule } from '@ghostfolio/api/services/i18n/i18n.module'; |
|
||||
import { ImpersonationModule } from '@ghostfolio/api/services/impersonation/impersonation.module'; |
|
||||
import { MarketDataModule } from '@ghostfolio/api/services/market-data/market-data.module'; |
|
||||
import { MarketDataService } from '@ghostfolio/api/services/market-data/market-data.service'; |
|
||||
import { PrismaModule } from '@ghostfolio/api/services/prisma/prisma.module'; |
|
||||
import { PropertyModule } from '@ghostfolio/api/services/property/property.module'; |
|
||||
import { PortfolioSnapshotQueueModule } from '@ghostfolio/api/services/queues/portfolio-snapshot/portfolio-snapshot.module'; |
|
||||
import { SymbolProfileModule } from '@ghostfolio/api/services/symbol-profile/symbol-profile.module'; |
|
||||
|
|
||||
import { Module } from '@nestjs/common'; |
|
||||
|
|
||||
import { AiController } from './ai.controller'; |
|
||||
import { AiService } from './ai.service'; |
|
||||
|
|
||||
@Module({ |
|
||||
controllers: [AiController], |
|
||||
imports: [ |
|
||||
ApiModule, |
|
||||
BenchmarkModule, |
|
||||
ConfigurationModule, |
|
||||
DataProviderModule, |
|
||||
ExchangeRateDataModule, |
|
||||
I18nModule, |
|
||||
ImpersonationModule, |
|
||||
MarketDataModule, |
|
||||
OrderModule, |
|
||||
PortfolioSnapshotQueueModule, |
|
||||
PrismaModule, |
|
||||
PropertyModule, |
|
||||
RedisCacheModule, |
|
||||
SymbolProfileModule, |
|
||||
UserModule |
|
||||
], |
|
||||
providers: [ |
|
||||
AccountBalanceService, |
|
||||
AccountService, |
|
||||
AiService, |
|
||||
CurrentRateService, |
|
||||
MarketDataService, |
|
||||
PortfolioCalculatorFactory, |
|
||||
PortfolioService, |
|
||||
RulesService |
|
||||
] |
|
||||
}) |
|
||||
export class AiModule {} |
|
||||
@ -1,169 +0,0 @@ |
|||||
import { PortfolioService } from '@ghostfolio/api/app/portfolio/portfolio.service'; |
|
||||
import { PropertyService } from '@ghostfolio/api/services/property/property.service'; |
|
||||
import { |
|
||||
PROPERTY_API_KEY_OPENROUTER, |
|
||||
PROPERTY_OPENROUTER_MODEL |
|
||||
} from '@ghostfolio/common/config'; |
|
||||
import { Filter } from '@ghostfolio/common/interfaces'; |
|
||||
import type { AiPromptMode } from '@ghostfolio/common/types'; |
|
||||
|
|
||||
import { Injectable } from '@nestjs/common'; |
|
||||
import { createOpenRouter } from '@openrouter/ai-sdk-provider'; |
|
||||
import { generateText } from 'ai'; |
|
||||
import type { ColumnDescriptor } from 'tablemark'; |
|
||||
|
|
||||
@Injectable() |
|
||||
export class AiService { |
|
||||
private static readonly HOLDINGS_TABLE_COLUMN_DEFINITIONS: ({ |
|
||||
key: |
|
||||
| 'ALLOCATION_PERCENTAGE' |
|
||||
| 'ASSET_CLASS' |
|
||||
| 'ASSET_SUB_CLASS' |
|
||||
| 'CURRENCY' |
|
||||
| 'NAME' |
|
||||
| 'SYMBOL'; |
|
||||
} & ColumnDescriptor)[] = [ |
|
||||
{ key: 'NAME', name: 'Name' }, |
|
||||
{ key: 'SYMBOL', name: 'Symbol' }, |
|
||||
{ key: 'CURRENCY', name: 'Currency' }, |
|
||||
{ key: 'ASSET_CLASS', name: 'Asset Class' }, |
|
||||
{ key: 'ASSET_SUB_CLASS', name: 'Asset Sub Class' }, |
|
||||
{ |
|
||||
align: 'right', |
|
||||
key: 'ALLOCATION_PERCENTAGE', |
|
||||
name: 'Allocation in Percentage' |
|
||||
} |
|
||||
]; |
|
||||
|
|
||||
public constructor( |
|
||||
private readonly portfolioService: PortfolioService, |
|
||||
private readonly propertyService: PropertyService |
|
||||
) {} |
|
||||
|
|
||||
public async generateText({ prompt }: { prompt: string }) { |
|
||||
const openRouterApiKey = await this.propertyService.getByKey<string>( |
|
||||
PROPERTY_API_KEY_OPENROUTER |
|
||||
); |
|
||||
|
|
||||
const openRouterModel = await this.propertyService.getByKey<string>( |
|
||||
PROPERTY_OPENROUTER_MODEL |
|
||||
); |
|
||||
|
|
||||
const openRouterService = createOpenRouter({ |
|
||||
apiKey: openRouterApiKey |
|
||||
}); |
|
||||
|
|
||||
return generateText({ |
|
||||
prompt, |
|
||||
model: openRouterService.chat(openRouterModel) |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
public async getPrompt({ |
|
||||
filters, |
|
||||
impersonationId, |
|
||||
languageCode, |
|
||||
mode, |
|
||||
userCurrency, |
|
||||
userId |
|
||||
}: { |
|
||||
filters?: Filter[]; |
|
||||
impersonationId: string; |
|
||||
languageCode: string; |
|
||||
mode: AiPromptMode; |
|
||||
userCurrency: string; |
|
||||
userId: string; |
|
||||
}) { |
|
||||
const { holdings } = await this.portfolioService.getDetails({ |
|
||||
filters, |
|
||||
impersonationId, |
|
||||
userId |
|
||||
}); |
|
||||
|
|
||||
const holdingsTableColumns: ColumnDescriptor[] = |
|
||||
AiService.HOLDINGS_TABLE_COLUMN_DEFINITIONS.map(({ align, name }) => { |
|
||||
return { name, align: align ?? 'left' }; |
|
||||
}); |
|
||||
|
|
||||
const holdingsTableRows = Object.values(holdings) |
|
||||
.sort((a, b) => { |
|
||||
return b.allocationInPercentage - a.allocationInPercentage; |
|
||||
}) |
|
||||
.map( |
|
||||
({ |
|
||||
allocationInPercentage, |
|
||||
assetClass, |
|
||||
assetSubClass, |
|
||||
currency, |
|
||||
name: label, |
|
||||
symbol |
|
||||
}) => { |
|
||||
return AiService.HOLDINGS_TABLE_COLUMN_DEFINITIONS.reduce( |
|
||||
(row, { key, name }) => { |
|
||||
switch (key) { |
|
||||
case 'ALLOCATION_PERCENTAGE': |
|
||||
row[name] = `${(allocationInPercentage * 100).toFixed(3)}%`; |
|
||||
break; |
|
||||
|
|
||||
case 'ASSET_CLASS': |
|
||||
row[name] = assetClass ?? ''; |
|
||||
break; |
|
||||
|
|
||||
case 'ASSET_SUB_CLASS': |
|
||||
row[name] = assetSubClass ?? ''; |
|
||||
break; |
|
||||
|
|
||||
case 'CURRENCY': |
|
||||
row[name] = currency; |
|
||||
break; |
|
||||
|
|
||||
case 'NAME': |
|
||||
row[name] = label; |
|
||||
break; |
|
||||
|
|
||||
case 'SYMBOL': |
|
||||
row[name] = symbol; |
|
||||
break; |
|
||||
|
|
||||
default: |
|
||||
row[name] = ''; |
|
||||
break; |
|
||||
} |
|
||||
|
|
||||
return row; |
|
||||
}, |
|
||||
{} as Record<string, string> |
|
||||
); |
|
||||
} |
|
||||
); |
|
||||
|
|
||||
// Dynamic import to load ESM module from CommonJS context
|
|
||||
// eslint-disable-next-line @typescript-eslint/no-implied-eval
|
|
||||
const dynamicImport = new Function('s', 'return import(s)') as ( |
|
||||
s: string |
|
||||
) => Promise<typeof import('tablemark')>; |
|
||||
const { tablemark } = await dynamicImport('tablemark'); |
|
||||
|
|
||||
const holdingsTableString = tablemark(holdingsTableRows, { |
|
||||
columns: holdingsTableColumns |
|
||||
}); |
|
||||
|
|
||||
if (mode === 'portfolio') { |
|
||||
return holdingsTableString; |
|
||||
} |
|
||||
|
|
||||
return [ |
|
||||
`You are a neutral financial assistant. Please analyze the following investment portfolio (base currency being ${userCurrency}) in simple words.`, |
|
||||
holdingsTableString, |
|
||||
'Structure your answer with these sections:', |
|
||||
'Overview: Briefly summarize the portfolio’s composition and allocation rationale.', |
|
||||
'Risk Assessment: Identify potential risks, including market volatility, concentration, and sectoral imbalances.', |
|
||||
'Advantages: Highlight strengths, focusing on growth potential, diversification, or other benefits.', |
|
||||
'Disadvantages: Point out weaknesses, such as overexposure or lack of defensive assets.', |
|
||||
'Target Group: Discuss who this portfolio might suit (e.g., risk tolerance, investment goals, life stages, and experience levels).', |
|
||||
'Optimization Ideas: Offer ideas to complement the portfolio, ensuring they are constructive and neutral in tone.', |
|
||||
'Conclusion: Provide a concise summary highlighting key insights.', |
|
||||
`Provide your answer in the following language: ${languageCode}.` |
|
||||
].join('\n'); |
|
||||
} |
|
||||
} |
|
||||
@ -1,25 +0,0 @@ |
|||||
import { HasPermission } from '@ghostfolio/api/decorators/has-permission.decorator'; |
|
||||
import { HasPermissionGuard } from '@ghostfolio/api/guards/has-permission.guard'; |
|
||||
import { ApiKeyService } from '@ghostfolio/api/services/api-key/api-key.service'; |
|
||||
import { ApiKeyResponse } from '@ghostfolio/common/interfaces'; |
|
||||
import { permissions } from '@ghostfolio/common/permissions'; |
|
||||
import type { RequestWithUser } from '@ghostfolio/common/types'; |
|
||||
|
|
||||
import { Controller, Inject, Post, UseGuards } from '@nestjs/common'; |
|
||||
import { REQUEST } from '@nestjs/core'; |
|
||||
import { AuthGuard } from '@nestjs/passport'; |
|
||||
|
|
||||
@Controller('api-keys') |
|
||||
export class ApiKeysController { |
|
||||
public constructor( |
|
||||
private readonly apiKeyService: ApiKeyService, |
|
||||
@Inject(REQUEST) private readonly request: RequestWithUser |
|
||||
) {} |
|
||||
|
|
||||
@HasPermission(permissions.createApiKey) |
|
||||
@Post() |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async createApiKey(): Promise<ApiKeyResponse> { |
|
||||
return this.apiKeyService.create({ userId: this.request.user.id }); |
|
||||
} |
|
||||
} |
|
||||
@ -1,11 +0,0 @@ |
|||||
import { ApiKeyModule } from '@ghostfolio/api/services/api-key/api-key.module'; |
|
||||
|
|
||||
import { Module } from '@nestjs/common'; |
|
||||
|
|
||||
import { ApiKeysController } from './api-keys.controller'; |
|
||||
|
|
||||
@Module({ |
|
||||
controllers: [ApiKeysController], |
|
||||
imports: [ApiKeyModule] |
|
||||
}) |
|
||||
export class ApiKeysModule {} |
|
||||
@ -1,46 +0,0 @@ |
|||||
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; |
|
||||
import { interpolate } from '@ghostfolio/common/helper'; |
|
||||
|
|
||||
import { |
|
||||
Controller, |
|
||||
Get, |
|
||||
Param, |
|
||||
Res, |
|
||||
Version, |
|
||||
VERSION_NEUTRAL |
|
||||
} from '@nestjs/common'; |
|
||||
import { Response } from 'express'; |
|
||||
import { readFileSync } from 'node:fs'; |
|
||||
import { join } from 'node:path'; |
|
||||
|
|
||||
@Controller('assets') |
|
||||
export class AssetsController { |
|
||||
private webManifest = ''; |
|
||||
|
|
||||
public constructor( |
|
||||
public readonly configurationService: ConfigurationService |
|
||||
) { |
|
||||
try { |
|
||||
this.webManifest = readFileSync( |
|
||||
join(__dirname, 'assets', 'site.webmanifest'), |
|
||||
'utf8' |
|
||||
); |
|
||||
} catch {} |
|
||||
} |
|
||||
|
|
||||
@Get('/:languageCode/site.webmanifest') |
|
||||
@Version(VERSION_NEUTRAL) |
|
||||
public getWebManifest( |
|
||||
@Param('languageCode') languageCode: string, |
|
||||
@Res() response: Response |
|
||||
): void { |
|
||||
const rootUrl = this.configurationService.get('ROOT_URL'); |
|
||||
const webManifest = interpolate(this.webManifest, { |
|
||||
languageCode, |
|
||||
rootUrl |
|
||||
}); |
|
||||
|
|
||||
response.setHeader('Content-Type', 'application/json'); |
|
||||
response.send(webManifest); |
|
||||
} |
|
||||
} |
|
||||
@ -1,11 +0,0 @@ |
|||||
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; |
|
||||
|
|
||||
import { Module } from '@nestjs/common'; |
|
||||
|
|
||||
import { AssetsController } from './assets.controller'; |
|
||||
|
|
||||
@Module({ |
|
||||
controllers: [AssetsController], |
|
||||
providers: [ConfigurationService] |
|
||||
}) |
|
||||
export class AssetsModule {} |
|
||||
@ -1,156 +0,0 @@ |
|||||
import { HasPermission } from '@ghostfolio/api/decorators/has-permission.decorator'; |
|
||||
import { HasPermissionGuard } from '@ghostfolio/api/guards/has-permission.guard'; |
|
||||
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 { ApiService } from '@ghostfolio/api/services/api/api.service'; |
|
||||
import { BenchmarkService } from '@ghostfolio/api/services/benchmark/benchmark.service'; |
|
||||
import { getIntervalFromDateRange } from '@ghostfolio/common/calculation-helper'; |
|
||||
import { HEADER_KEY_IMPERSONATION } from '@ghostfolio/common/config'; |
|
||||
import type { |
|
||||
AssetProfileIdentifier, |
|
||||
BenchmarkMarketDataDetailsResponse, |
|
||||
BenchmarkResponse |
|
||||
} from '@ghostfolio/common/interfaces'; |
|
||||
import { permissions } from '@ghostfolio/common/permissions'; |
|
||||
import type { DateRange, RequestWithUser } from '@ghostfolio/common/types'; |
|
||||
|
|
||||
import { |
|
||||
Body, |
|
||||
Controller, |
|
||||
Delete, |
|
||||
Get, |
|
||||
Headers, |
|
||||
HttpException, |
|
||||
Inject, |
|
||||
Param, |
|
||||
Post, |
|
||||
Query, |
|
||||
UseGuards, |
|
||||
UseInterceptors |
|
||||
} from '@nestjs/common'; |
|
||||
import { REQUEST } from '@nestjs/core'; |
|
||||
import { AuthGuard } from '@nestjs/passport'; |
|
||||
import { DataSource } from '@prisma/client'; |
|
||||
import { StatusCodes, getReasonPhrase } from 'http-status-codes'; |
|
||||
|
|
||||
import { BenchmarksService } from './benchmarks.service'; |
|
||||
|
|
||||
@Controller('benchmarks') |
|
||||
export class BenchmarksController { |
|
||||
public constructor( |
|
||||
private readonly apiService: ApiService, |
|
||||
private readonly benchmarkService: BenchmarkService, |
|
||||
private readonly benchmarksService: BenchmarksService, |
|
||||
@Inject(REQUEST) private readonly request: RequestWithUser |
|
||||
) {} |
|
||||
|
|
||||
@HasPermission(permissions.accessAdminControl) |
|
||||
@Post() |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async addBenchmark( |
|
||||
@Body() { dataSource, symbol }: AssetProfileIdentifier |
|
||||
) { |
|
||||
try { |
|
||||
const benchmark = await this.benchmarkService.addBenchmark({ |
|
||||
dataSource, |
|
||||
symbol |
|
||||
}); |
|
||||
|
|
||||
if (!benchmark) { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.NOT_FOUND), |
|
||||
StatusCodes.NOT_FOUND |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
return benchmark; |
|
||||
} catch { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.INTERNAL_SERVER_ERROR), |
|
||||
StatusCodes.INTERNAL_SERVER_ERROR |
|
||||
); |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
@Delete(':dataSource/:symbol') |
|
||||
@HasPermission(permissions.accessAdminControl) |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async deleteBenchmark( |
|
||||
@Param('dataSource') dataSource: DataSource, |
|
||||
@Param('symbol') symbol: string |
|
||||
) { |
|
||||
try { |
|
||||
const benchmark = await this.benchmarkService.deleteBenchmark({ |
|
||||
dataSource, |
|
||||
symbol |
|
||||
}); |
|
||||
|
|
||||
if (!benchmark) { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.NOT_FOUND), |
|
||||
StatusCodes.NOT_FOUND |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
return benchmark; |
|
||||
} catch { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.INTERNAL_SERVER_ERROR), |
|
||||
StatusCodes.INTERNAL_SERVER_ERROR |
|
||||
); |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
@Get() |
|
||||
@UseInterceptors(TransformDataSourceInRequestInterceptor) |
|
||||
@UseInterceptors(TransformDataSourceInResponseInterceptor) |
|
||||
public async getBenchmark(): Promise<BenchmarkResponse> { |
|
||||
return { |
|
||||
benchmarks: await this.benchmarkService.getBenchmarks() |
|
||||
}; |
|
||||
} |
|
||||
|
|
||||
@Get(':dataSource/:symbol/:startDateString') |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
@UseInterceptors(TransformDataSourceInRequestInterceptor) |
|
||||
public async getBenchmarkMarketDataForUser( |
|
||||
@Headers(HEADER_KEY_IMPERSONATION.toLowerCase()) impersonationId: string, |
|
||||
@Param('dataSource') dataSource: DataSource, |
|
||||
@Param('startDateString') startDateString: string, |
|
||||
@Param('symbol') symbol: string, |
|
||||
@Query('range') dateRange: DateRange = 'max', |
|
||||
@Query('accounts') filterByAccounts?: string, |
|
||||
@Query('assetClasses') filterByAssetClasses?: string, |
|
||||
@Query('dataSource') filterByDataSource?: string, |
|
||||
@Query('symbol') filterBySymbol?: string, |
|
||||
@Query('tags') filterByTags?: string, |
|
||||
@Query('withExcludedAccounts') withExcludedAccountsParam = 'false' |
|
||||
): Promise<BenchmarkMarketDataDetailsResponse> { |
|
||||
const { endDate, startDate } = getIntervalFromDateRange( |
|
||||
dateRange, |
|
||||
new Date(startDateString) |
|
||||
); |
|
||||
|
|
||||
const filters = this.apiService.buildFiltersFromQueryParams({ |
|
||||
filterByAccounts, |
|
||||
filterByAssetClasses, |
|
||||
filterByDataSource, |
|
||||
filterBySymbol, |
|
||||
filterByTags |
|
||||
}); |
|
||||
|
|
||||
const withExcludedAccounts = withExcludedAccountsParam === 'true'; |
|
||||
|
|
||||
return this.benchmarksService.getMarketDataForUser({ |
|
||||
dataSource, |
|
||||
dateRange, |
|
||||
endDate, |
|
||||
filters, |
|
||||
impersonationId, |
|
||||
startDate, |
|
||||
symbol, |
|
||||
withExcludedAccounts, |
|
||||
user: this.request.user |
|
||||
}); |
|
||||
} |
|
||||
} |
|
||||
@ -1,65 +0,0 @@ |
|||||
import { AccountBalanceService } from '@ghostfolio/api/app/account-balance/account-balance.service'; |
|
||||
import { AccountService } from '@ghostfolio/api/app/account/account.service'; |
|
||||
import { OrderModule } from '@ghostfolio/api/app/order/order.module'; |
|
||||
import { PortfolioCalculatorFactory } from '@ghostfolio/api/app/portfolio/calculator/portfolio-calculator.factory'; |
|
||||
import { CurrentRateService } from '@ghostfolio/api/app/portfolio/current-rate.service'; |
|
||||
import { PortfolioService } from '@ghostfolio/api/app/portfolio/portfolio.service'; |
|
||||
import { RulesService } from '@ghostfolio/api/app/portfolio/rules.service'; |
|
||||
import { RedisCacheModule } from '@ghostfolio/api/app/redis-cache/redis-cache.module'; |
|
||||
import { SymbolModule } from '@ghostfolio/api/app/symbol/symbol.module'; |
|
||||
import { UserModule } from '@ghostfolio/api/app/user/user.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 { ApiModule } from '@ghostfolio/api/services/api/api.module'; |
|
||||
import { BenchmarkService } from '@ghostfolio/api/services/benchmark/benchmark.service'; |
|
||||
import { ConfigurationModule } from '@ghostfolio/api/services/configuration/configuration.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 { I18nModule } from '@ghostfolio/api/services/i18n/i18n.module'; |
|
||||
import { ImpersonationModule } from '@ghostfolio/api/services/impersonation/impersonation.module'; |
|
||||
import { MarketDataModule } from '@ghostfolio/api/services/market-data/market-data.module'; |
|
||||
import { MarketDataService } from '@ghostfolio/api/services/market-data/market-data.service'; |
|
||||
import { PrismaModule } from '@ghostfolio/api/services/prisma/prisma.module'; |
|
||||
import { PropertyModule } from '@ghostfolio/api/services/property/property.module'; |
|
||||
import { PortfolioSnapshotQueueModule } from '@ghostfolio/api/services/queues/portfolio-snapshot/portfolio-snapshot.module'; |
|
||||
import { SymbolProfileModule } from '@ghostfolio/api/services/symbol-profile/symbol-profile.module'; |
|
||||
|
|
||||
import { Module } from '@nestjs/common'; |
|
||||
|
|
||||
import { BenchmarksController } from './benchmarks.controller'; |
|
||||
import { BenchmarksService } from './benchmarks.service'; |
|
||||
|
|
||||
@Module({ |
|
||||
controllers: [BenchmarksController], |
|
||||
imports: [ |
|
||||
ApiModule, |
|
||||
ConfigurationModule, |
|
||||
DataProviderModule, |
|
||||
ExchangeRateDataModule, |
|
||||
I18nModule, |
|
||||
ImpersonationModule, |
|
||||
MarketDataModule, |
|
||||
OrderModule, |
|
||||
PortfolioSnapshotQueueModule, |
|
||||
PrismaModule, |
|
||||
PropertyModule, |
|
||||
RedisCacheModule, |
|
||||
SymbolModule, |
|
||||
SymbolProfileModule, |
|
||||
TransformDataSourceInRequestModule, |
|
||||
TransformDataSourceInResponseModule, |
|
||||
UserModule |
|
||||
], |
|
||||
providers: [ |
|
||||
AccountBalanceService, |
|
||||
AccountService, |
|
||||
BenchmarkService, |
|
||||
BenchmarksService, |
|
||||
CurrentRateService, |
|
||||
MarketDataService, |
|
||||
PortfolioCalculatorFactory, |
|
||||
PortfolioService, |
|
||||
RulesService |
|
||||
] |
|
||||
}) |
|
||||
export class BenchmarksModule {} |
|
||||
@ -1,163 +0,0 @@ |
|||||
import { PortfolioService } from '@ghostfolio/api/app/portfolio/portfolio.service'; |
|
||||
import { SymbolService } from '@ghostfolio/api/app/symbol/symbol.service'; |
|
||||
import { BenchmarkService } from '@ghostfolio/api/services/benchmark/benchmark.service'; |
|
||||
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.service'; |
|
||||
import { MarketDataService } from '@ghostfolio/api/services/market-data/market-data.service'; |
|
||||
import { DATE_FORMAT, parseDate, resetHours } from '@ghostfolio/common/helper'; |
|
||||
import { |
|
||||
AssetProfileIdentifier, |
|
||||
BenchmarkMarketDataDetailsResponse, |
|
||||
Filter |
|
||||
} from '@ghostfolio/common/interfaces'; |
|
||||
import { DateRange, UserWithSettings } from '@ghostfolio/common/types'; |
|
||||
|
|
||||
import { Injectable, Logger } from '@nestjs/common'; |
|
||||
import { format, isSameDay } from 'date-fns'; |
|
||||
import { isNumber } from 'lodash'; |
|
||||
|
|
||||
@Injectable() |
|
||||
export class BenchmarksService { |
|
||||
public constructor( |
|
||||
private readonly benchmarkService: BenchmarkService, |
|
||||
private readonly exchangeRateDataService: ExchangeRateDataService, |
|
||||
private readonly marketDataService: MarketDataService, |
|
||||
private readonly portfolioService: PortfolioService, |
|
||||
private readonly symbolService: SymbolService |
|
||||
) {} |
|
||||
|
|
||||
public async getMarketDataForUser({ |
|
||||
dataSource, |
|
||||
dateRange, |
|
||||
endDate = new Date(), |
|
||||
filters, |
|
||||
impersonationId, |
|
||||
startDate, |
|
||||
symbol, |
|
||||
user, |
|
||||
withExcludedAccounts |
|
||||
}: { |
|
||||
dateRange: DateRange; |
|
||||
endDate?: Date; |
|
||||
filters?: Filter[]; |
|
||||
impersonationId: string; |
|
||||
startDate: Date; |
|
||||
user: UserWithSettings; |
|
||||
withExcludedAccounts?: boolean; |
|
||||
} & AssetProfileIdentifier): Promise<BenchmarkMarketDataDetailsResponse> { |
|
||||
const marketData: { date: string; value: number }[] = []; |
|
||||
const userCurrency = user.settings.settings.baseCurrency; |
|
||||
const userId = user.id; |
|
||||
|
|
||||
const { chart } = await this.portfolioService.getPerformance({ |
|
||||
dateRange, |
|
||||
filters, |
|
||||
impersonationId, |
|
||||
userId, |
|
||||
withExcludedAccounts |
|
||||
}); |
|
||||
|
|
||||
const [currentSymbolItem, marketDataItems] = await Promise.all([ |
|
||||
this.symbolService.get({ |
|
||||
dataGatheringItem: { |
|
||||
dataSource, |
|
||||
symbol |
|
||||
} |
|
||||
}), |
|
||||
this.marketDataService.marketDataItems({ |
|
||||
orderBy: { |
|
||||
date: 'asc' |
|
||||
}, |
|
||||
where: { |
|
||||
dataSource, |
|
||||
symbol, |
|
||||
date: { |
|
||||
in: chart.map(({ date }) => { |
|
||||
return resetHours(parseDate(date)); |
|
||||
}) |
|
||||
} |
|
||||
} |
|
||||
}) |
|
||||
]); |
|
||||
|
|
||||
const exchangeRates = |
|
||||
await this.exchangeRateDataService.getExchangeRatesByCurrency({ |
|
||||
startDate, |
|
||||
currencies: [currentSymbolItem.currency], |
|
||||
targetCurrency: userCurrency |
|
||||
}); |
|
||||
|
|
||||
const exchangeRateAtStartDate = |
|
||||
exchangeRates[`${currentSymbolItem.currency}${userCurrency}`]?.[ |
|
||||
format(startDate, DATE_FORMAT) |
|
||||
]; |
|
||||
|
|
||||
const marketPriceAtStartDate = marketDataItems?.find(({ date }) => { |
|
||||
return isSameDay(date, startDate); |
|
||||
})?.marketPrice; |
|
||||
|
|
||||
if (!marketPriceAtStartDate) { |
|
||||
Logger.error( |
|
||||
`No historical market data has been found for ${symbol} (${dataSource}) at ${format( |
|
||||
startDate, |
|
||||
DATE_FORMAT |
|
||||
)}`,
|
|
||||
'BenchmarkService' |
|
||||
); |
|
||||
|
|
||||
return { marketData }; |
|
||||
} |
|
||||
|
|
||||
for (const marketDataItem of marketDataItems) { |
|
||||
const exchangeRate = |
|
||||
exchangeRates[`${currentSymbolItem.currency}${userCurrency}`]?.[ |
|
||||
format(marketDataItem.date, DATE_FORMAT) |
|
||||
]; |
|
||||
|
|
||||
const exchangeRateFactor = |
|
||||
isNumber(exchangeRateAtStartDate) && isNumber(exchangeRate) |
|
||||
? exchangeRate / exchangeRateAtStartDate |
|
||||
: 1; |
|
||||
|
|
||||
marketData.push({ |
|
||||
date: format(marketDataItem.date, DATE_FORMAT), |
|
||||
value: |
|
||||
marketPriceAtStartDate === 0 |
|
||||
? 0 |
|
||||
: this.benchmarkService.calculateChangeInPercentage( |
|
||||
marketPriceAtStartDate, |
|
||||
marketDataItem.marketPrice * exchangeRateFactor |
|
||||
) * 100 |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
const includesEndDate = isSameDay( |
|
||||
parseDate(marketData.at(-1).date), |
|
||||
endDate |
|
||||
); |
|
||||
|
|
||||
if (currentSymbolItem?.marketPrice && !includesEndDate) { |
|
||||
const exchangeRate = |
|
||||
exchangeRates[`${currentSymbolItem.currency}${userCurrency}`]?.[ |
|
||||
format(endDate, DATE_FORMAT) |
|
||||
]; |
|
||||
|
|
||||
const exchangeRateFactor = |
|
||||
isNumber(exchangeRateAtStartDate) && isNumber(exchangeRate) |
|
||||
? exchangeRate / exchangeRateAtStartDate |
|
||||
: 1; |
|
||||
|
|
||||
marketData.push({ |
|
||||
date: format(endDate, DATE_FORMAT), |
|
||||
value: |
|
||||
this.benchmarkService.calculateChangeInPercentage( |
|
||||
marketPriceAtStartDate, |
|
||||
currentSymbolItem.marketPrice * exchangeRateFactor |
|
||||
) * 100 |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
return { |
|
||||
marketData |
|
||||
}; |
|
||||
} |
|
||||
} |
|
||||
@ -1,15 +0,0 @@ |
|||||
import { Granularity } from '@ghostfolio/common/types'; |
|
||||
|
|
||||
import { IsIn, IsISO8601, IsOptional } from 'class-validator'; |
|
||||
|
|
||||
export class GetDividendsDto { |
|
||||
@IsISO8601() |
|
||||
from: string; |
|
||||
|
|
||||
@IsIn(['day', 'month'] as Granularity[]) |
|
||||
@IsOptional() |
|
||||
granularity: Granularity; |
|
||||
|
|
||||
@IsISO8601() |
|
||||
to: string; |
|
||||
} |
|
||||
@ -1,15 +0,0 @@ |
|||||
import { Granularity } from '@ghostfolio/common/types'; |
|
||||
|
|
||||
import { IsIn, IsISO8601, IsOptional } from 'class-validator'; |
|
||||
|
|
||||
export class GetHistoricalDto { |
|
||||
@IsISO8601() |
|
||||
from: string; |
|
||||
|
|
||||
@IsIn(['day', 'month'] as Granularity[]) |
|
||||
@IsOptional() |
|
||||
granularity: Granularity; |
|
||||
|
|
||||
@IsISO8601() |
|
||||
to: string; |
|
||||
} |
|
||||
@ -1,10 +0,0 @@ |
|||||
import { Transform } from 'class-transformer'; |
|
||||
import { IsString } from 'class-validator'; |
|
||||
|
|
||||
export class GetQuotesDto { |
|
||||
@IsString({ each: true }) |
|
||||
@Transform(({ value }) => |
|
||||
typeof value === 'string' ? value.split(',') : value |
|
||||
) |
|
||||
symbols: string[]; |
|
||||
} |
|
||||
@ -1,249 +0,0 @@ |
|||||
import { HasPermission } from '@ghostfolio/api/decorators/has-permission.decorator'; |
|
||||
import { HasPermissionGuard } from '@ghostfolio/api/guards/has-permission.guard'; |
|
||||
import { AssetProfileInvalidError } from '@ghostfolio/api/services/data-provider/errors/asset-profile-invalid.error'; |
|
||||
import { parseDate } from '@ghostfolio/common/helper'; |
|
||||
import { |
|
||||
DataProviderGhostfolioAssetProfileResponse, |
|
||||
DataProviderGhostfolioStatusResponse, |
|
||||
DividendsResponse, |
|
||||
HistoricalResponse, |
|
||||
LookupResponse, |
|
||||
QuotesResponse |
|
||||
} from '@ghostfolio/common/interfaces'; |
|
||||
import { permissions } from '@ghostfolio/common/permissions'; |
|
||||
import { RequestWithUser } from '@ghostfolio/common/types'; |
|
||||
|
|
||||
import { |
|
||||
Controller, |
|
||||
Get, |
|
||||
HttpException, |
|
||||
Inject, |
|
||||
Param, |
|
||||
Query, |
|
||||
UseGuards, |
|
||||
Version |
|
||||
} from '@nestjs/common'; |
|
||||
import { REQUEST } from '@nestjs/core'; |
|
||||
import { AuthGuard } from '@nestjs/passport'; |
|
||||
import { isISIN } from 'class-validator'; |
|
||||
import { getReasonPhrase, StatusCodes } from 'http-status-codes'; |
|
||||
|
|
||||
import { GetDividendsDto } from './get-dividends.dto'; |
|
||||
import { GetHistoricalDto } from './get-historical.dto'; |
|
||||
import { GetQuotesDto } from './get-quotes.dto'; |
|
||||
import { GhostfolioService } from './ghostfolio.service'; |
|
||||
|
|
||||
@Controller('data-providers/ghostfolio') |
|
||||
export class GhostfolioController { |
|
||||
public constructor( |
|
||||
private readonly ghostfolioService: GhostfolioService, |
|
||||
@Inject(REQUEST) private readonly request: RequestWithUser |
|
||||
) {} |
|
||||
|
|
||||
@Get('asset-profile/:symbol') |
|
||||
@HasPermission(permissions.enableDataProviderGhostfolio) |
|
||||
@UseGuards(AuthGuard('api-key'), HasPermissionGuard) |
|
||||
public async getAssetProfile( |
|
||||
@Param('symbol') symbol: string |
|
||||
): Promise<DataProviderGhostfolioAssetProfileResponse> { |
|
||||
const maxDailyRequests = await this.ghostfolioService.getMaxDailyRequests(); |
|
||||
|
|
||||
if ( |
|
||||
this.request.user.dataProviderGhostfolioDailyRequests > maxDailyRequests |
|
||||
) { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.TOO_MANY_REQUESTS), |
|
||||
StatusCodes.TOO_MANY_REQUESTS |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
try { |
|
||||
const assetProfile = await this.ghostfolioService.getAssetProfile({ |
|
||||
symbol |
|
||||
}); |
|
||||
|
|
||||
await this.ghostfolioService.incrementDailyRequests({ |
|
||||
userId: this.request.user.id |
|
||||
}); |
|
||||
|
|
||||
return assetProfile; |
|
||||
} catch (error) { |
|
||||
if (error instanceof AssetProfileInvalidError) { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.NOT_FOUND), |
|
||||
StatusCodes.NOT_FOUND |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.INTERNAL_SERVER_ERROR), |
|
||||
StatusCodes.INTERNAL_SERVER_ERROR |
|
||||
); |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
@Get('dividends/:symbol') |
|
||||
@HasPermission(permissions.enableDataProviderGhostfolio) |
|
||||
@UseGuards(AuthGuard('api-key'), HasPermissionGuard) |
|
||||
@Version('2') |
|
||||
public async getDividends( |
|
||||
@Param('symbol') symbol: string, |
|
||||
@Query() query: GetDividendsDto |
|
||||
): Promise<DividendsResponse> { |
|
||||
const maxDailyRequests = await this.ghostfolioService.getMaxDailyRequests(); |
|
||||
|
|
||||
if ( |
|
||||
this.request.user.dataProviderGhostfolioDailyRequests > maxDailyRequests |
|
||||
) { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.TOO_MANY_REQUESTS), |
|
||||
StatusCodes.TOO_MANY_REQUESTS |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
try { |
|
||||
const dividends = await this.ghostfolioService.getDividends({ |
|
||||
symbol, |
|
||||
from: parseDate(query.from), |
|
||||
granularity: query.granularity, |
|
||||
to: parseDate(query.to) |
|
||||
}); |
|
||||
|
|
||||
await this.ghostfolioService.incrementDailyRequests({ |
|
||||
userId: this.request.user.id |
|
||||
}); |
|
||||
|
|
||||
return dividends; |
|
||||
} catch { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.INTERNAL_SERVER_ERROR), |
|
||||
StatusCodes.INTERNAL_SERVER_ERROR |
|
||||
); |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
@Get('historical/:symbol') |
|
||||
@HasPermission(permissions.enableDataProviderGhostfolio) |
|
||||
@UseGuards(AuthGuard('api-key'), HasPermissionGuard) |
|
||||
@Version('2') |
|
||||
public async getHistorical( |
|
||||
@Param('symbol') symbol: string, |
|
||||
@Query() query: GetHistoricalDto |
|
||||
): Promise<HistoricalResponse> { |
|
||||
const maxDailyRequests = await this.ghostfolioService.getMaxDailyRequests(); |
|
||||
|
|
||||
if ( |
|
||||
this.request.user.dataProviderGhostfolioDailyRequests > maxDailyRequests |
|
||||
) { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.TOO_MANY_REQUESTS), |
|
||||
StatusCodes.TOO_MANY_REQUESTS |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
try { |
|
||||
const historicalData = await this.ghostfolioService.getHistorical({ |
|
||||
symbol, |
|
||||
from: parseDate(query.from), |
|
||||
granularity: query.granularity, |
|
||||
to: parseDate(query.to) |
|
||||
}); |
|
||||
|
|
||||
await this.ghostfolioService.incrementDailyRequests({ |
|
||||
userId: this.request.user.id |
|
||||
}); |
|
||||
|
|
||||
return historicalData; |
|
||||
} catch { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.INTERNAL_SERVER_ERROR), |
|
||||
StatusCodes.INTERNAL_SERVER_ERROR |
|
||||
); |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
@Get('lookup') |
|
||||
@HasPermission(permissions.enableDataProviderGhostfolio) |
|
||||
@UseGuards(AuthGuard('api-key'), HasPermissionGuard) |
|
||||
@Version('2') |
|
||||
public async lookupSymbol( |
|
||||
@Query('includeIndices') includeIndicesParam = 'false', |
|
||||
@Query('query') query = '' |
|
||||
): Promise<LookupResponse> { |
|
||||
const includeIndices = includeIndicesParam === 'true'; |
|
||||
const maxDailyRequests = await this.ghostfolioService.getMaxDailyRequests(); |
|
||||
|
|
||||
if ( |
|
||||
this.request.user.dataProviderGhostfolioDailyRequests > maxDailyRequests |
|
||||
) { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.TOO_MANY_REQUESTS), |
|
||||
StatusCodes.TOO_MANY_REQUESTS |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
try { |
|
||||
const result = await this.ghostfolioService.lookup({ |
|
||||
includeIndices, |
|
||||
query: isISIN(query.toUpperCase()) |
|
||||
? query.toUpperCase() |
|
||||
: query.toLowerCase() |
|
||||
}); |
|
||||
|
|
||||
await this.ghostfolioService.incrementDailyRequests({ |
|
||||
userId: this.request.user.id |
|
||||
}); |
|
||||
|
|
||||
return result; |
|
||||
} catch { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.INTERNAL_SERVER_ERROR), |
|
||||
StatusCodes.INTERNAL_SERVER_ERROR |
|
||||
); |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
@Get('quotes') |
|
||||
@HasPermission(permissions.enableDataProviderGhostfolio) |
|
||||
@UseGuards(AuthGuard('api-key'), HasPermissionGuard) |
|
||||
@Version('2') |
|
||||
public async getQuotes( |
|
||||
@Query() query: GetQuotesDto |
|
||||
): Promise<QuotesResponse> { |
|
||||
const maxDailyRequests = await this.ghostfolioService.getMaxDailyRequests(); |
|
||||
|
|
||||
if ( |
|
||||
this.request.user.dataProviderGhostfolioDailyRequests > maxDailyRequests |
|
||||
) { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.TOO_MANY_REQUESTS), |
|
||||
StatusCodes.TOO_MANY_REQUESTS |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
try { |
|
||||
const quotes = await this.ghostfolioService.getQuotes({ |
|
||||
symbols: query.symbols |
|
||||
}); |
|
||||
|
|
||||
await this.ghostfolioService.incrementDailyRequests({ |
|
||||
userId: this.request.user.id |
|
||||
}); |
|
||||
|
|
||||
return quotes; |
|
||||
} catch { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.INTERNAL_SERVER_ERROR), |
|
||||
StatusCodes.INTERNAL_SERVER_ERROR |
|
||||
); |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
@Get('status') |
|
||||
@HasPermission(permissions.enableDataProviderGhostfolio) |
|
||||
@UseGuards(AuthGuard('api-key'), HasPermissionGuard) |
|
||||
@Version('2') |
|
||||
public async getStatus(): Promise<DataProviderGhostfolioStatusResponse> { |
|
||||
return this.ghostfolioService.getStatus({ user: this.request.user }); |
|
||||
} |
|
||||
} |
|
||||
@ -1,83 +0,0 @@ |
|||||
import { RedisCacheModule } from '@ghostfolio/api/app/redis-cache/redis-cache.module'; |
|
||||
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; |
|
||||
import { CryptocurrencyModule } from '@ghostfolio/api/services/cryptocurrency/cryptocurrency.module'; |
|
||||
import { AlphaVantageService } from '@ghostfolio/api/services/data-provider/alpha-vantage/alpha-vantage.service'; |
|
||||
import { CoinGeckoService } from '@ghostfolio/api/services/data-provider/coingecko/coingecko.service'; |
|
||||
import { YahooFinanceDataEnhancerService } from '@ghostfolio/api/services/data-provider/data-enhancer/yahoo-finance/yahoo-finance.service'; |
|
||||
import { DataProviderModule } from '@ghostfolio/api/services/data-provider/data-provider.module'; |
|
||||
import { DataProviderService } from '@ghostfolio/api/services/data-provider/data-provider.service'; |
|
||||
import { EodHistoricalDataService } from '@ghostfolio/api/services/data-provider/eod-historical-data/eod-historical-data.service'; |
|
||||
import { FinancialModelingPrepService } from '@ghostfolio/api/services/data-provider/financial-modeling-prep/financial-modeling-prep.service'; |
|
||||
import { GoogleSheetsService } from '@ghostfolio/api/services/data-provider/google-sheets/google-sheets.service'; |
|
||||
import { ManualService } from '@ghostfolio/api/services/data-provider/manual/manual.service'; |
|
||||
import { RapidApiService } from '@ghostfolio/api/services/data-provider/rapid-api/rapid-api.service'; |
|
||||
import { YahooFinanceService } from '@ghostfolio/api/services/data-provider/yahoo-finance/yahoo-finance.service'; |
|
||||
import { MarketDataModule } from '@ghostfolio/api/services/market-data/market-data.module'; |
|
||||
import { PrismaModule } from '@ghostfolio/api/services/prisma/prisma.module'; |
|
||||
import { PropertyModule } from '@ghostfolio/api/services/property/property.module'; |
|
||||
import { SymbolProfileModule } from '@ghostfolio/api/services/symbol-profile/symbol-profile.module'; |
|
||||
|
|
||||
import { Module } from '@nestjs/common'; |
|
||||
|
|
||||
import { GhostfolioController } from './ghostfolio.controller'; |
|
||||
import { GhostfolioService } from './ghostfolio.service'; |
|
||||
|
|
||||
@Module({ |
|
||||
controllers: [GhostfolioController], |
|
||||
imports: [ |
|
||||
CryptocurrencyModule, |
|
||||
DataProviderModule, |
|
||||
MarketDataModule, |
|
||||
PrismaModule, |
|
||||
PropertyModule, |
|
||||
RedisCacheModule, |
|
||||
SymbolProfileModule |
|
||||
], |
|
||||
providers: [ |
|
||||
AlphaVantageService, |
|
||||
CoinGeckoService, |
|
||||
ConfigurationService, |
|
||||
DataProviderService, |
|
||||
EodHistoricalDataService, |
|
||||
FinancialModelingPrepService, |
|
||||
GhostfolioService, |
|
||||
GoogleSheetsService, |
|
||||
ManualService, |
|
||||
RapidApiService, |
|
||||
YahooFinanceService, |
|
||||
YahooFinanceDataEnhancerService, |
|
||||
{ |
|
||||
inject: [ |
|
||||
AlphaVantageService, |
|
||||
CoinGeckoService, |
|
||||
EodHistoricalDataService, |
|
||||
FinancialModelingPrepService, |
|
||||
GoogleSheetsService, |
|
||||
ManualService, |
|
||||
RapidApiService, |
|
||||
YahooFinanceService |
|
||||
], |
|
||||
provide: 'DataProviderInterfaces', |
|
||||
useFactory: ( |
|
||||
alphaVantageService, |
|
||||
coinGeckoService, |
|
||||
eodHistoricalDataService, |
|
||||
financialModelingPrepService, |
|
||||
googleSheetsService, |
|
||||
manualService, |
|
||||
rapidApiService, |
|
||||
yahooFinanceService |
|
||||
) => [ |
|
||||
alphaVantageService, |
|
||||
coinGeckoService, |
|
||||
eodHistoricalDataService, |
|
||||
financialModelingPrepService, |
|
||||
googleSheetsService, |
|
||||
manualService, |
|
||||
rapidApiService, |
|
||||
yahooFinanceService |
|
||||
] |
|
||||
} |
|
||||
] |
|
||||
}) |
|
||||
export class GhostfolioModule {} |
|
||||
@ -1,375 +0,0 @@ |
|||||
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; |
|
||||
import { DataProviderService } from '@ghostfolio/api/services/data-provider/data-provider.service'; |
|
||||
import { GhostfolioService as GhostfolioDataProviderService } from '@ghostfolio/api/services/data-provider/ghostfolio/ghostfolio.service'; |
|
||||
import { |
|
||||
GetAssetProfileParams, |
|
||||
GetDividendsParams, |
|
||||
GetHistoricalParams, |
|
||||
GetQuotesParams, |
|
||||
GetSearchParams |
|
||||
} from '@ghostfolio/api/services/data-provider/interfaces/data-provider.interface'; |
|
||||
import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service'; |
|
||||
import { PropertyService } from '@ghostfolio/api/services/property/property.service'; |
|
||||
import { |
|
||||
DEFAULT_CURRENCY, |
|
||||
DERIVED_CURRENCIES |
|
||||
} from '@ghostfolio/common/config'; |
|
||||
import { PROPERTY_DATA_SOURCES_GHOSTFOLIO_DATA_PROVIDER_MAX_REQUESTS } from '@ghostfolio/common/config'; |
|
||||
import { |
|
||||
DataProviderGhostfolioAssetProfileResponse, |
|
||||
DataProviderHistoricalResponse, |
|
||||
DataProviderInfo, |
|
||||
DividendsResponse, |
|
||||
HistoricalResponse, |
|
||||
LookupItem, |
|
||||
LookupResponse, |
|
||||
QuotesResponse |
|
||||
} from '@ghostfolio/common/interfaces'; |
|
||||
import { UserWithSettings } from '@ghostfolio/common/types'; |
|
||||
|
|
||||
import { Injectable, Logger } from '@nestjs/common'; |
|
||||
import { DataSource, SymbolProfile } from '@prisma/client'; |
|
||||
import { Big } from 'big.js'; |
|
||||
|
|
||||
@Injectable() |
|
||||
export class GhostfolioService { |
|
||||
public constructor( |
|
||||
private readonly configurationService: ConfigurationService, |
|
||||
private readonly dataProviderService: DataProviderService, |
|
||||
private readonly prismaService: PrismaService, |
|
||||
private readonly propertyService: PropertyService |
|
||||
) {} |
|
||||
|
|
||||
public async getAssetProfile({ symbol }: GetAssetProfileParams) { |
|
||||
let result: DataProviderGhostfolioAssetProfileResponse = {}; |
|
||||
|
|
||||
try { |
|
||||
const promises: Promise<Partial<SymbolProfile>>[] = []; |
|
||||
|
|
||||
for (const dataProviderService of this.getDataProviderServices()) { |
|
||||
promises.push( |
|
||||
this.dataProviderService |
|
||||
.getAssetProfiles([ |
|
||||
{ |
|
||||
symbol, |
|
||||
dataSource: dataProviderService.getName() |
|
||||
} |
|
||||
]) |
|
||||
.then(async (assetProfiles) => { |
|
||||
const assetProfile = assetProfiles[symbol]; |
|
||||
const dataSourceOrigin = DataSource.GHOSTFOLIO; |
|
||||
|
|
||||
if (assetProfile) { |
|
||||
await this.prismaService.assetProfileResolution.upsert({ |
|
||||
create: { |
|
||||
dataSourceOrigin, |
|
||||
currency: assetProfile.currency, |
|
||||
dataSourceTarget: assetProfile.dataSource, |
|
||||
symbolOrigin: symbol, |
|
||||
symbolTarget: assetProfile.symbol |
|
||||
}, |
|
||||
update: { |
|
||||
requestCount: { |
|
||||
increment: 1 |
|
||||
} |
|
||||
}, |
|
||||
where: { |
|
||||
dataSourceOrigin_symbolOrigin: { |
|
||||
dataSourceOrigin, |
|
||||
symbolOrigin: symbol |
|
||||
} |
|
||||
} |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
result = { |
|
||||
...result, |
|
||||
...assetProfile, |
|
||||
dataSource: dataSourceOrigin |
|
||||
}; |
|
||||
|
|
||||
return assetProfile; |
|
||||
}) |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
await Promise.all(promises); |
|
||||
|
|
||||
return result; |
|
||||
} catch (error) { |
|
||||
Logger.error(error, 'GhostfolioService'); |
|
||||
|
|
||||
throw error; |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
public async getDividends({ |
|
||||
from, |
|
||||
granularity, |
|
||||
requestTimeout = this.configurationService.get('REQUEST_TIMEOUT'), |
|
||||
symbol, |
|
||||
to |
|
||||
}: GetDividendsParams) { |
|
||||
const result: DividendsResponse = { dividends: {} }; |
|
||||
|
|
||||
try { |
|
||||
const promises: Promise<{ |
|
||||
[date: string]: DataProviderHistoricalResponse; |
|
||||
}>[] = []; |
|
||||
|
|
||||
for (const dataProviderService of this.getDataProviderServices()) { |
|
||||
promises.push( |
|
||||
dataProviderService |
|
||||
.getDividends({ |
|
||||
from, |
|
||||
granularity, |
|
||||
requestTimeout, |
|
||||
symbol, |
|
||||
to |
|
||||
}) |
|
||||
.then((dividends) => { |
|
||||
result.dividends = dividends; |
|
||||
|
|
||||
return dividends; |
|
||||
}) |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
await Promise.all(promises); |
|
||||
|
|
||||
return result; |
|
||||
} catch (error) { |
|
||||
Logger.error(error, 'GhostfolioService'); |
|
||||
|
|
||||
throw error; |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
public async getHistorical({ |
|
||||
from, |
|
||||
granularity, |
|
||||
requestTimeout, |
|
||||
to, |
|
||||
symbol |
|
||||
}: GetHistoricalParams) { |
|
||||
const result: HistoricalResponse = { historicalData: {} }; |
|
||||
|
|
||||
try { |
|
||||
const promises: Promise<{ |
|
||||
[symbol: string]: { [date: string]: DataProviderHistoricalResponse }; |
|
||||
}>[] = []; |
|
||||
|
|
||||
for (const dataProviderService of this.getDataProviderServices()) { |
|
||||
promises.push( |
|
||||
dataProviderService |
|
||||
.getHistorical({ |
|
||||
from, |
|
||||
granularity, |
|
||||
requestTimeout, |
|
||||
symbol, |
|
||||
to |
|
||||
}) |
|
||||
.then((historicalData) => { |
|
||||
result.historicalData = historicalData[symbol]; |
|
||||
|
|
||||
return historicalData; |
|
||||
}) |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
await Promise.all(promises); |
|
||||
|
|
||||
return result; |
|
||||
} catch (error) { |
|
||||
Logger.error(error, 'GhostfolioService'); |
|
||||
|
|
||||
throw error; |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
public async getMaxDailyRequests() { |
|
||||
return parseInt( |
|
||||
(await this.propertyService.getByKey<string>( |
|
||||
PROPERTY_DATA_SOURCES_GHOSTFOLIO_DATA_PROVIDER_MAX_REQUESTS |
|
||||
)) || '0', |
|
||||
10 |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
public async getQuotes({ requestTimeout, symbols }: GetQuotesParams) { |
|
||||
const results: QuotesResponse = { quotes: {} }; |
|
||||
|
|
||||
try { |
|
||||
const promises: Promise<any>[] = []; |
|
||||
|
|
||||
for (const dataProvider of this.getDataProviderServices()) { |
|
||||
const maximumNumberOfSymbolsPerRequest = |
|
||||
dataProvider.getMaxNumberOfSymbolsPerRequest?.() ?? |
|
||||
Number.MAX_SAFE_INTEGER; |
|
||||
|
|
||||
for ( |
|
||||
let i = 0; |
|
||||
i < symbols.length; |
|
||||
i += maximumNumberOfSymbolsPerRequest |
|
||||
) { |
|
||||
const symbolsChunk = symbols.slice( |
|
||||
i, |
|
||||
i + maximumNumberOfSymbolsPerRequest |
|
||||
); |
|
||||
|
|
||||
const promise = Promise.resolve( |
|
||||
dataProvider.getQuotes({ requestTimeout, symbols: symbolsChunk }) |
|
||||
); |
|
||||
|
|
||||
promises.push( |
|
||||
promise.then(async (result) => { |
|
||||
for (const [symbol, dataProviderResponse] of Object.entries( |
|
||||
result |
|
||||
)) { |
|
||||
dataProviderResponse.dataSource = 'GHOSTFOLIO'; |
|
||||
|
|
||||
if ( |
|
||||
[ |
|
||||
...DERIVED_CURRENCIES.map(({ currency }) => { |
|
||||
return `${DEFAULT_CURRENCY}${currency}`; |
|
||||
}), |
|
||||
`${DEFAULT_CURRENCY}USX` |
|
||||
].includes(symbol) |
|
||||
) { |
|
||||
continue; |
|
||||
} |
|
||||
|
|
||||
results.quotes[symbol] = dataProviderResponse; |
|
||||
|
|
||||
for (const { |
|
||||
currency, |
|
||||
factor, |
|
||||
rootCurrency |
|
||||
} of DERIVED_CURRENCIES) { |
|
||||
if (symbol === `${DEFAULT_CURRENCY}${rootCurrency}`) { |
|
||||
results.quotes[`${DEFAULT_CURRENCY}${currency}`] = { |
|
||||
...dataProviderResponse, |
|
||||
currency, |
|
||||
marketPrice: new Big( |
|
||||
result[`${DEFAULT_CURRENCY}${rootCurrency}`].marketPrice |
|
||||
) |
|
||||
.mul(factor) |
|
||||
.toNumber(), |
|
||||
marketState: 'open' |
|
||||
}; |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
}) |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
await Promise.all(promises); |
|
||||
} |
|
||||
|
|
||||
return results; |
|
||||
} catch (error) { |
|
||||
Logger.error(error, 'GhostfolioService'); |
|
||||
|
|
||||
throw error; |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
public async getStatus({ user }: { user: UserWithSettings }) { |
|
||||
return { |
|
||||
dailyRequests: user.dataProviderGhostfolioDailyRequests, |
|
||||
dailyRequestsMax: await this.getMaxDailyRequests(), |
|
||||
subscription: user.subscription |
|
||||
}; |
|
||||
} |
|
||||
|
|
||||
public async incrementDailyRequests({ userId }: { userId: string }) { |
|
||||
await this.prismaService.analytics.update({ |
|
||||
data: { |
|
||||
dataProviderGhostfolioDailyRequests: { increment: 1 } |
|
||||
}, |
|
||||
where: { userId } |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
public async lookup({ |
|
||||
includeIndices = false, |
|
||||
query |
|
||||
}: GetSearchParams): Promise<LookupResponse> { |
|
||||
const results: LookupResponse = { items: [] }; |
|
||||
|
|
||||
if (!query) { |
|
||||
return results; |
|
||||
} |
|
||||
|
|
||||
try { |
|
||||
let lookupItems: LookupItem[] = []; |
|
||||
const promises: Promise<{ items: LookupItem[] }>[] = []; |
|
||||
|
|
||||
if (query?.length < 2) { |
|
||||
return { items: lookupItems }; |
|
||||
} |
|
||||
|
|
||||
for (const dataProviderService of this.getDataProviderServices()) { |
|
||||
promises.push( |
|
||||
dataProviderService.search({ |
|
||||
includeIndices, |
|
||||
query |
|
||||
}) |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
const searchResults = await Promise.all(promises); |
|
||||
|
|
||||
for (const { items } of searchResults) { |
|
||||
if (items?.length > 0) { |
|
||||
lookupItems = lookupItems.concat(items); |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
const filteredItems = lookupItems |
|
||||
.filter(({ currency }) => { |
|
||||
// Only allow symbols with supported currency
|
|
||||
return currency ? true : false; |
|
||||
}) |
|
||||
.sort(({ name: name1 }, { name: name2 }) => { |
|
||||
return name1?.toLowerCase().localeCompare(name2?.toLowerCase()); |
|
||||
}) |
|
||||
.map((lookupItem) => { |
|
||||
lookupItem.dataProviderInfo = this.getDataProviderInfo(); |
|
||||
lookupItem.dataSource = 'GHOSTFOLIO'; |
|
||||
|
|
||||
return lookupItem; |
|
||||
}); |
|
||||
|
|
||||
results.items = filteredItems; |
|
||||
|
|
||||
return results; |
|
||||
} catch (error) { |
|
||||
Logger.error(error, 'GhostfolioService'); |
|
||||
|
|
||||
throw error; |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
private getDataProviderInfo(): DataProviderInfo { |
|
||||
const ghostfolioDataProviderService = new GhostfolioDataProviderService( |
|
||||
this.configurationService, |
|
||||
this.propertyService |
|
||||
); |
|
||||
|
|
||||
return { |
|
||||
...ghostfolioDataProviderService.getDataProviderInfo(), |
|
||||
isPremium: false, |
|
||||
name: 'Ghostfolio Premium' |
|
||||
}; |
|
||||
} |
|
||||
|
|
||||
private getDataProviderServices() { |
|
||||
return this.configurationService |
|
||||
.get('DATA_SOURCES_GHOSTFOLIO_DATA_PROVIDER') |
|
||||
.map((dataSource) => { |
|
||||
return this.dataProviderService.getDataProvider(DataSource[dataSource]); |
|
||||
}); |
|
||||
} |
|
||||
} |
|
||||
@ -1,193 +0,0 @@ |
|||||
import { AdminService } from '@ghostfolio/api/app/admin/admin.service'; |
|
||||
import { SymbolService } from '@ghostfolio/api/app/symbol/symbol.service'; |
|
||||
import { HasPermission } from '@ghostfolio/api/decorators/has-permission.decorator'; |
|
||||
import { HasPermissionGuard } from '@ghostfolio/api/guards/has-permission.guard'; |
|
||||
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 { MarketDataService } from '@ghostfolio/api/services/market-data/market-data.service'; |
|
||||
import { SymbolProfileService } from '@ghostfolio/api/services/symbol-profile/symbol-profile.service'; |
|
||||
import { |
|
||||
ghostfolioFearAndGreedIndexDataSourceCryptocurrencies, |
|
||||
ghostfolioFearAndGreedIndexDataSourceStocks, |
|
||||
ghostfolioFearAndGreedIndexSymbolCryptocurrencies, |
|
||||
ghostfolioFearAndGreedIndexSymbolStocks |
|
||||
} from '@ghostfolio/common/config'; |
|
||||
import { UpdateBulkMarketDataDto } from '@ghostfolio/common/dtos'; |
|
||||
import { getCurrencyFromSymbol, isCurrency } from '@ghostfolio/common/helper'; |
|
||||
import { |
|
||||
MarketDataDetailsResponse, |
|
||||
MarketDataOfMarketsResponse |
|
||||
} from '@ghostfolio/common/interfaces'; |
|
||||
import { hasPermission, permissions } from '@ghostfolio/common/permissions'; |
|
||||
import { RequestWithUser } from '@ghostfolio/common/types'; |
|
||||
|
|
||||
import { |
|
||||
Body, |
|
||||
Controller, |
|
||||
Get, |
|
||||
HttpException, |
|
||||
Inject, |
|
||||
Param, |
|
||||
Post, |
|
||||
Query, |
|
||||
UseGuards, |
|
||||
UseInterceptors |
|
||||
} from '@nestjs/common'; |
|
||||
import { REQUEST } from '@nestjs/core'; |
|
||||
import { AuthGuard } from '@nestjs/passport'; |
|
||||
import { DataSource, Prisma } from '@prisma/client'; |
|
||||
import { parseISO } from 'date-fns'; |
|
||||
import { getReasonPhrase, StatusCodes } from 'http-status-codes'; |
|
||||
|
|
||||
@Controller('market-data') |
|
||||
export class MarketDataController { |
|
||||
public constructor( |
|
||||
private readonly adminService: AdminService, |
|
||||
private readonly marketDataService: MarketDataService, |
|
||||
@Inject(REQUEST) private readonly request: RequestWithUser, |
|
||||
private readonly symbolProfileService: SymbolProfileService, |
|
||||
private readonly symbolService: SymbolService |
|
||||
) {} |
|
||||
|
|
||||
@Get('markets') |
|
||||
@HasPermission(permissions.readMarketDataOfMarkets) |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async getMarketDataOfMarkets( |
|
||||
@Query('includeHistoricalData') includeHistoricalData = 0 |
|
||||
): Promise<MarketDataOfMarketsResponse> { |
|
||||
const [ |
|
||||
marketDataFearAndGreedIndexCryptocurrencies, |
|
||||
marketDataFearAndGreedIndexStocks |
|
||||
] = await Promise.all([ |
|
||||
this.symbolService.get({ |
|
||||
includeHistoricalData, |
|
||||
dataGatheringItem: { |
|
||||
dataSource: ghostfolioFearAndGreedIndexDataSourceCryptocurrencies, |
|
||||
symbol: ghostfolioFearAndGreedIndexSymbolCryptocurrencies |
|
||||
} |
|
||||
}), |
|
||||
this.symbolService.get({ |
|
||||
includeHistoricalData, |
|
||||
dataGatheringItem: { |
|
||||
dataSource: ghostfolioFearAndGreedIndexDataSourceStocks, |
|
||||
symbol: ghostfolioFearAndGreedIndexSymbolStocks |
|
||||
} |
|
||||
}) |
|
||||
]); |
|
||||
|
|
||||
return { |
|
||||
fearAndGreedIndex: { |
|
||||
CRYPTOCURRENCIES: { |
|
||||
...marketDataFearAndGreedIndexCryptocurrencies |
|
||||
}, |
|
||||
STOCKS: { |
|
||||
...marketDataFearAndGreedIndexStocks |
|
||||
} |
|
||||
} |
|
||||
}; |
|
||||
} |
|
||||
|
|
||||
@Get(':dataSource/:symbol') |
|
||||
@UseGuards(AuthGuard('jwt')) |
|
||||
@UseInterceptors(TransformDataSourceInRequestInterceptor) |
|
||||
@UseInterceptors(TransformDataSourceInResponseInterceptor) |
|
||||
public async getMarketDataBySymbol( |
|
||||
@Param('dataSource') dataSource: DataSource, |
|
||||
@Param('symbol') symbol: string |
|
||||
): Promise<MarketDataDetailsResponse> { |
|
||||
const [assetProfile] = await this.symbolProfileService.getSymbolProfiles([ |
|
||||
{ dataSource, symbol } |
|
||||
]); |
|
||||
|
|
||||
if (!assetProfile && !isCurrency(getCurrencyFromSymbol(symbol))) { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.NOT_FOUND), |
|
||||
StatusCodes.NOT_FOUND |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
const canReadAllAssetProfiles = hasPermission( |
|
||||
this.request.user.permissions, |
|
||||
permissions.readMarketData |
|
||||
); |
|
||||
|
|
||||
const canReadOwnAssetProfile = |
|
||||
assetProfile?.userId === this.request.user.id && |
|
||||
hasPermission( |
|
||||
this.request.user.permissions, |
|
||||
permissions.readMarketDataOfOwnAssetProfile |
|
||||
); |
|
||||
|
|
||||
if (!canReadAllAssetProfiles && !canReadOwnAssetProfile) { |
|
||||
throw new HttpException( |
|
||||
assetProfile.userId |
|
||||
? getReasonPhrase(StatusCodes.NOT_FOUND) |
|
||||
: getReasonPhrase(StatusCodes.FORBIDDEN), |
|
||||
assetProfile.userId ? StatusCodes.NOT_FOUND : StatusCodes.FORBIDDEN |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
return this.adminService.getMarketDataBySymbol({ dataSource, symbol }); |
|
||||
} |
|
||||
|
|
||||
@Post(':dataSource/:symbol') |
|
||||
@UseGuards(AuthGuard('jwt')) |
|
||||
public async updateMarketData( |
|
||||
@Body() data: UpdateBulkMarketDataDto, |
|
||||
@Param('dataSource') dataSource: DataSource, |
|
||||
@Param('symbol') symbol: string |
|
||||
) { |
|
||||
const [assetProfile] = await this.symbolProfileService.getSymbolProfiles([ |
|
||||
{ dataSource, symbol } |
|
||||
]); |
|
||||
|
|
||||
if (!assetProfile && !isCurrency(getCurrencyFromSymbol(symbol))) { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.NOT_FOUND), |
|
||||
StatusCodes.NOT_FOUND |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
const canUpsertAllAssetProfiles = |
|
||||
hasPermission( |
|
||||
this.request.user.permissions, |
|
||||
permissions.createMarketData |
|
||||
) && |
|
||||
hasPermission( |
|
||||
this.request.user.permissions, |
|
||||
permissions.updateMarketData |
|
||||
); |
|
||||
|
|
||||
const canUpsertOwnAssetProfile = |
|
||||
assetProfile?.userId === this.request.user.id && |
|
||||
hasPermission( |
|
||||
this.request.user.permissions, |
|
||||
permissions.createMarketDataOfOwnAssetProfile |
|
||||
) && |
|
||||
hasPermission( |
|
||||
this.request.user.permissions, |
|
||||
permissions.updateMarketDataOfOwnAssetProfile |
|
||||
); |
|
||||
|
|
||||
if (!canUpsertAllAssetProfiles && !canUpsertOwnAssetProfile) { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.FORBIDDEN), |
|
||||
StatusCodes.FORBIDDEN |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
const dataBulkUpdate: Prisma.MarketDataUpdateInput[] = data.marketData.map( |
|
||||
({ date, marketPrice }) => ({ |
|
||||
dataSource, |
|
||||
marketPrice, |
|
||||
symbol, |
|
||||
date: parseISO(date), |
|
||||
state: 'CLOSE' |
|
||||
}) |
|
||||
); |
|
||||
|
|
||||
return this.marketDataService.updateMany({ |
|
||||
data: dataBulkUpdate |
|
||||
}); |
|
||||
} |
|
||||
} |
|
||||
@ -1,23 +0,0 @@ |
|||||
import { AdminModule } from '@ghostfolio/api/app/admin/admin.module'; |
|
||||
import { SymbolModule } from '@ghostfolio/api/app/symbol/symbol.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 { MarketDataModule as MarketDataServiceModule } from '@ghostfolio/api/services/market-data/market-data.module'; |
|
||||
import { SymbolProfileModule } from '@ghostfolio/api/services/symbol-profile/symbol-profile.module'; |
|
||||
|
|
||||
import { Module } from '@nestjs/common'; |
|
||||
|
|
||||
import { MarketDataController } from './market-data.controller'; |
|
||||
|
|
||||
@Module({ |
|
||||
controllers: [MarketDataController], |
|
||||
imports: [ |
|
||||
AdminModule, |
|
||||
MarketDataServiceModule, |
|
||||
SymbolModule, |
|
||||
SymbolProfileModule, |
|
||||
TransformDataSourceInRequestModule, |
|
||||
TransformDataSourceInResponseModule |
|
||||
] |
|
||||
}) |
|
||||
export class MarketDataModule {} |
|
||||
@ -1,24 +0,0 @@ |
|||||
import { PlatformService } from '@ghostfolio/api/app/platform/platform.service'; |
|
||||
import { HasPermission } from '@ghostfolio/api/decorators/has-permission.decorator'; |
|
||||
import { HasPermissionGuard } from '@ghostfolio/api/guards/has-permission.guard'; |
|
||||
import { PlatformsResponse } from '@ghostfolio/common/interfaces'; |
|
||||
import { permissions } from '@ghostfolio/common/permissions'; |
|
||||
|
|
||||
import { Controller, Get, UseGuards } from '@nestjs/common'; |
|
||||
import { AuthGuard } from '@nestjs/passport'; |
|
||||
|
|
||||
@Controller('platforms') |
|
||||
export class PlatformsController { |
|
||||
public constructor(private readonly platformService: PlatformService) {} |
|
||||
|
|
||||
@Get() |
|
||||
@HasPermission(permissions.readPlatforms) |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async getPlatforms(): Promise<PlatformsResponse> { |
|
||||
const platforms = await this.platformService.getPlatforms({ |
|
||||
orderBy: { name: 'asc' } |
|
||||
}); |
|
||||
|
|
||||
return { platforms }; |
|
||||
} |
|
||||
} |
|
||||
@ -1,11 +0,0 @@ |
|||||
import { PlatformModule } from '@ghostfolio/api/app/platform/platform.module'; |
|
||||
|
|
||||
import { Module } from '@nestjs/common'; |
|
||||
|
|
||||
import { PlatformsController } from './platforms.controller'; |
|
||||
|
|
||||
@Module({ |
|
||||
controllers: [PlatformsController], |
|
||||
imports: [PlatformModule] |
|
||||
}) |
|
||||
export class PlatformsModule {} |
|
||||
@ -1,187 +0,0 @@ |
|||||
import { AccessService } from '@ghostfolio/api/app/access/access.service'; |
|
||||
import { OrderService } from '@ghostfolio/api/app/order/order.service'; |
|
||||
import { PortfolioService } from '@ghostfolio/api/app/portfolio/portfolio.service'; |
|
||||
import { UserService } from '@ghostfolio/api/app/user/user.service'; |
|
||||
import { RedactValuesInResponseInterceptor } from '@ghostfolio/api/interceptors/redact-values-in-response/redact-values-in-response.interceptor'; |
|
||||
import { TransformDataSourceInResponseInterceptor } from '@ghostfolio/api/interceptors/transform-data-source-in-response/transform-data-source-in-response.interceptor'; |
|
||||
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; |
|
||||
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.service'; |
|
||||
import { DEFAULT_CURRENCY } from '@ghostfolio/common/config'; |
|
||||
import { getSum } from '@ghostfolio/common/helper'; |
|
||||
import { PublicPortfolioResponse } from '@ghostfolio/common/interfaces'; |
|
||||
import type { RequestWithUser } from '@ghostfolio/common/types'; |
|
||||
|
|
||||
import { |
|
||||
Controller, |
|
||||
Get, |
|
||||
HttpException, |
|
||||
Inject, |
|
||||
Param, |
|
||||
UseInterceptors |
|
||||
} from '@nestjs/common'; |
|
||||
import { REQUEST } from '@nestjs/core'; |
|
||||
import { Type as ActivityType } from '@prisma/client'; |
|
||||
import { Big } from 'big.js'; |
|
||||
import { StatusCodes, getReasonPhrase } from 'http-status-codes'; |
|
||||
|
|
||||
@Controller('public') |
|
||||
export class PublicController { |
|
||||
public constructor( |
|
||||
private readonly accessService: AccessService, |
|
||||
private readonly configurationService: ConfigurationService, |
|
||||
private readonly exchangeRateDataService: ExchangeRateDataService, |
|
||||
private readonly orderService: OrderService, |
|
||||
private readonly portfolioService: PortfolioService, |
|
||||
@Inject(REQUEST) private readonly request: RequestWithUser, |
|
||||
private readonly userService: UserService |
|
||||
) {} |
|
||||
|
|
||||
@Get(':accessId/portfolio') |
|
||||
@UseInterceptors(RedactValuesInResponseInterceptor) |
|
||||
@UseInterceptors(TransformDataSourceInResponseInterceptor) |
|
||||
public async getPublicPortfolio( |
|
||||
@Param('accessId') accessId: string |
|
||||
): Promise<PublicPortfolioResponse> { |
|
||||
const access = await this.accessService.access({ id: accessId }); |
|
||||
|
|
||||
if (!access) { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.NOT_FOUND), |
|
||||
StatusCodes.NOT_FOUND |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
let hasDetails = true; |
|
||||
|
|
||||
const user = await this.userService.user({ |
|
||||
id: access.userId |
|
||||
}); |
|
||||
|
|
||||
if (this.configurationService.get('ENABLE_FEATURE_SUBSCRIPTION')) { |
|
||||
hasDetails = user.subscription.type === 'Premium'; |
|
||||
} |
|
||||
|
|
||||
const [ |
|
||||
{ createdAt, holdings, markets }, |
|
||||
{ performance: performance1d }, |
|
||||
{ performance: performanceMax }, |
|
||||
{ performance: performanceYtd } |
|
||||
] = await Promise.all([ |
|
||||
this.portfolioService.getDetails({ |
|
||||
impersonationId: access.userId, |
|
||||
userId: user.id, |
|
||||
withMarkets: true |
|
||||
}), |
|
||||
...['1d', 'max', 'ytd'].map((dateRange) => { |
|
||||
return this.portfolioService.getPerformance({ |
|
||||
dateRange, |
|
||||
impersonationId: undefined, |
|
||||
userId: user.id |
|
||||
}); |
|
||||
}) |
|
||||
]); |
|
||||
|
|
||||
const { activities } = await this.orderService.getOrders({ |
|
||||
sortColumn: 'date', |
|
||||
sortDirection: 'desc', |
|
||||
take: 10, |
|
||||
types: [ActivityType.BUY, ActivityType.SELL], |
|
||||
userCurrency: user.settings?.settings.baseCurrency ?? DEFAULT_CURRENCY, |
|
||||
userId: user.id, |
|
||||
withExcludedAccountsAndActivities: false |
|
||||
}); |
|
||||
|
|
||||
// Experimental
|
|
||||
const latestActivities = this.configurationService.get( |
|
||||
'ENABLE_FEATURE_SUBSCRIPTION' |
|
||||
) |
|
||||
? [] |
|
||||
: activities.map( |
|
||||
({ |
|
||||
currency, |
|
||||
date, |
|
||||
fee, |
|
||||
quantity, |
|
||||
SymbolProfile, |
|
||||
type, |
|
||||
unitPrice, |
|
||||
value, |
|
||||
valueInBaseCurrency |
|
||||
}) => { |
|
||||
return { |
|
||||
currency, |
|
||||
date, |
|
||||
fee, |
|
||||
quantity, |
|
||||
SymbolProfile, |
|
||||
type, |
|
||||
unitPrice, |
|
||||
value, |
|
||||
valueInBaseCurrency |
|
||||
}; |
|
||||
} |
|
||||
); |
|
||||
|
|
||||
Object.values(markets ?? {}).forEach((market) => { |
|
||||
delete market.valueInBaseCurrency; |
|
||||
}); |
|
||||
|
|
||||
const publicPortfolioResponse: PublicPortfolioResponse = { |
|
||||
createdAt, |
|
||||
hasDetails, |
|
||||
latestActivities, |
|
||||
markets, |
|
||||
alias: access.alias, |
|
||||
holdings: {}, |
|
||||
performance: { |
|
||||
'1d': { |
|
||||
relativeChange: |
|
||||
performance1d.netPerformancePercentageWithCurrencyEffect |
|
||||
}, |
|
||||
max: { |
|
||||
relativeChange: |
|
||||
performanceMax.netPerformancePercentageWithCurrencyEffect |
|
||||
}, |
|
||||
ytd: { |
|
||||
relativeChange: |
|
||||
performanceYtd.netPerformancePercentageWithCurrencyEffect |
|
||||
} |
|
||||
} |
|
||||
}; |
|
||||
|
|
||||
const totalValue = getSum( |
|
||||
Object.values(holdings).map(({ currency, marketPrice, quantity }) => { |
|
||||
return new Big( |
|
||||
this.exchangeRateDataService.toCurrency( |
|
||||
quantity * marketPrice, |
|
||||
currency, |
|
||||
this.request.user?.settings?.settings.baseCurrency ?? |
|
||||
DEFAULT_CURRENCY |
|
||||
) |
|
||||
); |
|
||||
}) |
|
||||
).toNumber(); |
|
||||
|
|
||||
for (const [symbol, portfolioPosition] of Object.entries(holdings)) { |
|
||||
publicPortfolioResponse.holdings[symbol] = { |
|
||||
allocationInPercentage: |
|
||||
portfolioPosition.valueInBaseCurrency / totalValue, |
|
||||
assetClass: hasDetails ? portfolioPosition.assetClass : undefined, |
|
||||
countries: hasDetails ? portfolioPosition.countries : [], |
|
||||
currency: hasDetails ? portfolioPosition.currency : undefined, |
|
||||
dataSource: portfolioPosition.dataSource, |
|
||||
dateOfFirstActivity: portfolioPosition.dateOfFirstActivity, |
|
||||
markets: hasDetails ? portfolioPosition.markets : undefined, |
|
||||
name: portfolioPosition.name, |
|
||||
netPerformancePercentWithCurrencyEffect: |
|
||||
portfolioPosition.netPerformancePercentWithCurrencyEffect, |
|
||||
sectors: hasDetails ? portfolioPosition.sectors : [], |
|
||||
symbol: portfolioPosition.symbol, |
|
||||
url: portfolioPosition.url, |
|
||||
valueInPercentage: portfolioPosition.valueInBaseCurrency / totalValue |
|
||||
}; |
|
||||
} |
|
||||
|
|
||||
return publicPortfolioResponse; |
|
||||
} |
|
||||
} |
|
||||
@ -1,53 +0,0 @@ |
|||||
import { AccessModule } from '@ghostfolio/api/app/access/access.module'; |
|
||||
import { AccountBalanceService } from '@ghostfolio/api/app/account-balance/account-balance.service'; |
|
||||
import { AccountService } from '@ghostfolio/api/app/account/account.service'; |
|
||||
import { OrderModule } from '@ghostfolio/api/app/order/order.module'; |
|
||||
import { PortfolioCalculatorFactory } from '@ghostfolio/api/app/portfolio/calculator/portfolio-calculator.factory'; |
|
||||
import { CurrentRateService } from '@ghostfolio/api/app/portfolio/current-rate.service'; |
|
||||
import { PortfolioService } from '@ghostfolio/api/app/portfolio/portfolio.service'; |
|
||||
import { RulesService } from '@ghostfolio/api/app/portfolio/rules.service'; |
|
||||
import { RedisCacheModule } from '@ghostfolio/api/app/redis-cache/redis-cache.module'; |
|
||||
import { UserModule } from '@ghostfolio/api/app/user/user.module'; |
|
||||
import { TransformDataSourceInRequestModule } from '@ghostfolio/api/interceptors/transform-data-source-in-request/transform-data-source-in-request.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 { I18nModule } from '@ghostfolio/api/services/i18n/i18n.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 { PortfolioSnapshotQueueModule } from '@ghostfolio/api/services/queues/portfolio-snapshot/portfolio-snapshot.module'; |
|
||||
import { SymbolProfileModule } from '@ghostfolio/api/services/symbol-profile/symbol-profile.module'; |
|
||||
|
|
||||
import { Module } from '@nestjs/common'; |
|
||||
|
|
||||
import { PublicController } from './public.controller'; |
|
||||
|
|
||||
@Module({ |
|
||||
controllers: [PublicController], |
|
||||
imports: [ |
|
||||
AccessModule, |
|
||||
BenchmarkModule, |
|
||||
DataProviderModule, |
|
||||
ExchangeRateDataModule, |
|
||||
I18nModule, |
|
||||
ImpersonationModule, |
|
||||
MarketDataModule, |
|
||||
OrderModule, |
|
||||
PortfolioSnapshotQueueModule, |
|
||||
PrismaModule, |
|
||||
RedisCacheModule, |
|
||||
SymbolProfileModule, |
|
||||
TransformDataSourceInRequestModule, |
|
||||
UserModule |
|
||||
], |
|
||||
providers: [ |
|
||||
AccountBalanceService, |
|
||||
AccountService, |
|
||||
CurrentRateService, |
|
||||
PortfolioCalculatorFactory, |
|
||||
PortfolioService, |
|
||||
RulesService |
|
||||
] |
|
||||
}) |
|
||||
export class PublicModule {} |
|
||||
@ -1,52 +0,0 @@ |
|||||
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; |
|
||||
import { |
|
||||
DATE_FORMAT, |
|
||||
getYesterday, |
|
||||
interpolate |
|
||||
} from '@ghostfolio/common/helper'; |
|
||||
|
|
||||
import { Controller, Get, Res, VERSION_NEUTRAL, Version } from '@nestjs/common'; |
|
||||
import { format } from 'date-fns'; |
|
||||
import { Response } from 'express'; |
|
||||
import { readFileSync } from 'node:fs'; |
|
||||
import { join } from 'node:path'; |
|
||||
|
|
||||
import { SitemapService } from './sitemap.service'; |
|
||||
|
|
||||
@Controller('sitemap.xml') |
|
||||
export class SitemapController { |
|
||||
public sitemapXml = ''; |
|
||||
|
|
||||
public constructor( |
|
||||
private readonly configurationService: ConfigurationService, |
|
||||
private readonly sitemapService: SitemapService |
|
||||
) { |
|
||||
try { |
|
||||
this.sitemapXml = readFileSync( |
|
||||
join(__dirname, 'assets', 'sitemap.xml'), |
|
||||
'utf8' |
|
||||
); |
|
||||
} catch {} |
|
||||
} |
|
||||
|
|
||||
@Get() |
|
||||
@Version(VERSION_NEUTRAL) |
|
||||
public getSitemapXml(@Res() response: Response) { |
|
||||
const currentDate = format(getYesterday(), DATE_FORMAT); |
|
||||
|
|
||||
response.setHeader('content-type', 'application/xml'); |
|
||||
response.send( |
|
||||
interpolate(this.sitemapXml, { |
|
||||
blogPosts: this.sitemapService.getBlogPosts({ currentDate }), |
|
||||
personalFinanceTools: this.configurationService.get( |
|
||||
'ENABLE_FEATURE_SUBSCRIPTION' |
|
||||
) |
|
||||
? this.sitemapService.getPersonalFinanceTools({ currentDate }) |
|
||||
: '', |
|
||||
publicRoutes: this.sitemapService.getPublicRoutes({ |
|
||||
currentDate |
|
||||
}) |
|
||||
}) |
|
||||
); |
|
||||
} |
|
||||
} |
|
||||
@ -1,14 +0,0 @@ |
|||||
import { ConfigurationModule } from '@ghostfolio/api/services/configuration/configuration.module'; |
|
||||
import { I18nModule } from '@ghostfolio/api/services/i18n/i18n.module'; |
|
||||
|
|
||||
import { Module } from '@nestjs/common'; |
|
||||
|
|
||||
import { SitemapController } from './sitemap.controller'; |
|
||||
import { SitemapService } from './sitemap.service'; |
|
||||
|
|
||||
@Module({ |
|
||||
controllers: [SitemapController], |
|
||||
imports: [ConfigurationModule, I18nModule], |
|
||||
providers: [SitemapService] |
|
||||
}) |
|
||||
export class SitemapModule {} |
|
||||
@ -1,256 +0,0 @@ |
|||||
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; |
|
||||
import { I18nService } from '@ghostfolio/api/services/i18n/i18n.service'; |
|
||||
import { SUPPORTED_LANGUAGE_CODES } from '@ghostfolio/common/config'; |
|
||||
import { personalFinanceTools } from '@ghostfolio/common/personal-finance-tools'; |
|
||||
import { PublicRoute } from '@ghostfolio/common/routes/interfaces/public-route.interface'; |
|
||||
import { publicRoutes } from '@ghostfolio/common/routes/routes'; |
|
||||
|
|
||||
import { Injectable } from '@nestjs/common'; |
|
||||
|
|
||||
@Injectable() |
|
||||
export class SitemapService { |
|
||||
private static readonly TRANSLATION_TAGGED_MESSAGE_REGEX = |
|
||||
/:.*@@(?<id>[a-zA-Z0-9.]+):(?<message>.+)/; |
|
||||
|
|
||||
public constructor( |
|
||||
private readonly configurationService: ConfigurationService, |
|
||||
private readonly i18nService: I18nService |
|
||||
) {} |
|
||||
|
|
||||
public getBlogPosts({ currentDate }: { currentDate: string }) { |
|
||||
const rootUrl = this.configurationService.get('ROOT_URL'); |
|
||||
|
|
||||
return [ |
|
||||
{ |
|
||||
languageCode: 'de', |
|
||||
routerLink: ['2021', '07', 'hallo-ghostfolio'] |
|
||||
}, |
|
||||
{ |
|
||||
languageCode: 'en', |
|
||||
routerLink: ['2021', '07', 'hello-ghostfolio'] |
|
||||
}, |
|
||||
{ |
|
||||
languageCode: 'en', |
|
||||
routerLink: ['2022', '01', 'ghostfolio-first-months-in-open-source'] |
|
||||
}, |
|
||||
{ |
|
||||
languageCode: 'en', |
|
||||
routerLink: ['2022', '07', 'ghostfolio-meets-internet-identity'] |
|
||||
}, |
|
||||
{ |
|
||||
languageCode: 'en', |
|
||||
routerLink: ['2022', '07', 'how-do-i-get-my-finances-in-order'] |
|
||||
}, |
|
||||
{ |
|
||||
languageCode: 'en', |
|
||||
routerLink: ['2022', '08', '500-stars-on-github'] |
|
||||
}, |
|
||||
{ |
|
||||
languageCode: 'en', |
|
||||
routerLink: ['2022', '10', 'hacktoberfest-2022'] |
|
||||
}, |
|
||||
{ |
|
||||
languageCode: 'en', |
|
||||
routerLink: ['2022', '11', 'black-friday-2022'] |
|
||||
}, |
|
||||
{ |
|
||||
languageCode: 'en', |
|
||||
routerLink: [ |
|
||||
'2022', |
|
||||
'12', |
|
||||
'the-importance-of-tracking-your-personal-finances' |
|
||||
] |
|
||||
}, |
|
||||
{ |
|
||||
languageCode: 'de', |
|
||||
routerLink: ['2023', '01', 'ghostfolio-auf-sackgeld-vorgestellt'] |
|
||||
}, |
|
||||
{ |
|
||||
languageCode: 'en', |
|
||||
routerLink: ['2023', '02', 'ghostfolio-meets-umbrel'] |
|
||||
}, |
|
||||
{ |
|
||||
languageCode: 'en', |
|
||||
routerLink: ['2023', '03', 'ghostfolio-reaches-1000-stars-on-github'] |
|
||||
}, |
|
||||
{ |
|
||||
languageCode: 'en', |
|
||||
routerLink: [ |
|
||||
'2023', |
|
||||
'05', |
|
||||
'unlock-your-financial-potential-with-ghostfolio' |
|
||||
] |
|
||||
}, |
|
||||
{ |
|
||||
languageCode: 'en', |
|
||||
routerLink: ['2023', '07', 'exploring-the-path-to-fire'] |
|
||||
}, |
|
||||
{ |
|
||||
languageCode: 'en', |
|
||||
routerLink: ['2023', '08', 'ghostfolio-joins-oss-friends'] |
|
||||
}, |
|
||||
{ |
|
||||
languageCode: 'en', |
|
||||
routerLink: ['2023', '09', 'ghostfolio-2'] |
|
||||
}, |
|
||||
{ |
|
||||
languageCode: 'en', |
|
||||
routerLink: ['2023', '09', 'hacktoberfest-2023'] |
|
||||
}, |
|
||||
{ |
|
||||
languageCode: 'en', |
|
||||
routerLink: ['2023', '11', 'black-week-2023'] |
|
||||
}, |
|
||||
{ |
|
||||
languageCode: 'en', |
|
||||
routerLink: ['2023', '11', 'hacktoberfest-2023-debriefing'] |
|
||||
}, |
|
||||
{ |
|
||||
languageCode: 'en', |
|
||||
routerLink: ['2024', '09', 'hacktoberfest-2024'] |
|
||||
}, |
|
||||
{ |
|
||||
languageCode: 'en', |
|
||||
routerLink: ['2024', '11', 'black-weeks-2024'] |
|
||||
}, |
|
||||
{ |
|
||||
languageCode: 'en', |
|
||||
routerLink: ['2025', '09', 'hacktoberfest-2025'] |
|
||||
}, |
|
||||
{ |
|
||||
languageCode: 'en', |
|
||||
routerLink: ['2025', '11', 'black-weeks-2025'] |
|
||||
} |
|
||||
] |
|
||||
.map(({ languageCode, routerLink }) => { |
|
||||
return this.createRouteSitemapUrl({ |
|
||||
currentDate, |
|
||||
languageCode, |
|
||||
rootUrl, |
|
||||
route: { |
|
||||
routerLink: [publicRoutes.blog.path, ...routerLink], |
|
||||
path: undefined |
|
||||
} |
|
||||
}); |
|
||||
}) |
|
||||
.join('\n'); |
|
||||
} |
|
||||
|
|
||||
public getPersonalFinanceTools({ currentDate }: { currentDate: string }) { |
|
||||
const rootUrl = this.configurationService.get('ROOT_URL'); |
|
||||
|
|
||||
return SUPPORTED_LANGUAGE_CODES.flatMap((languageCode) => { |
|
||||
const resourcesPath = this.i18nService.getTranslation({ |
|
||||
languageCode, |
|
||||
id: publicRoutes.resources.path.match( |
|
||||
SitemapService.TRANSLATION_TAGGED_MESSAGE_REGEX |
|
||||
).groups.id |
|
||||
}); |
|
||||
|
|
||||
const personalFinanceToolsPath = this.i18nService.getTranslation({ |
|
||||
languageCode, |
|
||||
id: publicRoutes.resources.subRoutes.personalFinanceTools.path.match( |
|
||||
SitemapService.TRANSLATION_TAGGED_MESSAGE_REGEX |
|
||||
).groups.id |
|
||||
}); |
|
||||
|
|
||||
const productPath = this.i18nService.getTranslation({ |
|
||||
languageCode, |
|
||||
id: publicRoutes.resources.subRoutes.personalFinanceTools.subRoutes.product.path.match( |
|
||||
SitemapService.TRANSLATION_TAGGED_MESSAGE_REGEX |
|
||||
).groups.id |
|
||||
}); |
|
||||
|
|
||||
return personalFinanceTools.map(({ alias, key }) => { |
|
||||
const routerLink = [ |
|
||||
resourcesPath, |
|
||||
personalFinanceToolsPath, |
|
||||
`${productPath}-${alias ?? key}` |
|
||||
]; |
|
||||
|
|
||||
return this.createRouteSitemapUrl({ |
|
||||
currentDate, |
|
||||
languageCode, |
|
||||
rootUrl, |
|
||||
route: { |
|
||||
routerLink, |
|
||||
path: undefined |
|
||||
} |
|
||||
}); |
|
||||
}); |
|
||||
}).join('\n'); |
|
||||
} |
|
||||
|
|
||||
public getPublicRoutes({ currentDate }: { currentDate: string }) { |
|
||||
const rootUrl = this.configurationService.get('ROOT_URL'); |
|
||||
|
|
||||
return SUPPORTED_LANGUAGE_CODES.flatMap((languageCode) => { |
|
||||
const params = { |
|
||||
currentDate, |
|
||||
languageCode, |
|
||||
rootUrl |
|
||||
}; |
|
||||
|
|
||||
return [ |
|
||||
this.createRouteSitemapUrl(params), |
|
||||
...this.createSitemapUrls(params, publicRoutes) |
|
||||
]; |
|
||||
}).join('\n'); |
|
||||
} |
|
||||
|
|
||||
private createRouteSitemapUrl({ |
|
||||
currentDate, |
|
||||
languageCode, |
|
||||
rootUrl, |
|
||||
route |
|
||||
}: { |
|
||||
currentDate: string; |
|
||||
languageCode: string; |
|
||||
rootUrl: string; |
|
||||
route?: PublicRoute; |
|
||||
}): string { |
|
||||
const segments = |
|
||||
route?.routerLink.map((link) => { |
|
||||
const match = link.match( |
|
||||
SitemapService.TRANSLATION_TAGGED_MESSAGE_REGEX |
|
||||
); |
|
||||
|
|
||||
const segment = match |
|
||||
? (this.i18nService.getTranslation({ |
|
||||
languageCode, |
|
||||
id: match.groups.id |
|
||||
}) ?? match.groups.message) |
|
||||
: link; |
|
||||
|
|
||||
return segment.replace(/^\/+|\/+$/, ''); |
|
||||
}) ?? []; |
|
||||
|
|
||||
const location = [rootUrl, languageCode, ...segments].join('/'); |
|
||||
|
|
||||
return [ |
|
||||
' <url>', |
|
||||
` <loc>${location}</loc>`, |
|
||||
` <lastmod>${currentDate}T00:00:00+00:00</lastmod>`, |
|
||||
' </url>' |
|
||||
].join('\n'); |
|
||||
} |
|
||||
|
|
||||
private createSitemapUrls( |
|
||||
params: { currentDate: string; languageCode: string; rootUrl: string }, |
|
||||
routes: Record<string, PublicRoute> |
|
||||
): string[] { |
|
||||
return Object.values(routes).flatMap((route) => { |
|
||||
if (route.excludeFromSitemap) { |
|
||||
return []; |
|
||||
} |
|
||||
|
|
||||
const urls = [this.createRouteSitemapUrl({ ...params, route })]; |
|
||||
|
|
||||
if (route.subRoutes) { |
|
||||
urls.push(...this.createSitemapUrls(params, route.subRoutes)); |
|
||||
} |
|
||||
|
|
||||
return urls; |
|
||||
}); |
|
||||
} |
|
||||
} |
|
||||
@ -1,113 +0,0 @@ |
|||||
import { HasPermission } from '@ghostfolio/api/decorators/has-permission.decorator'; |
|
||||
import { HasPermissionGuard } from '@ghostfolio/api/guards/has-permission.guard'; |
|
||||
import { TagService } from '@ghostfolio/api/services/tag/tag.service'; |
|
||||
import { CreateTagDto, UpdateTagDto } from '@ghostfolio/common/dtos'; |
|
||||
import { hasPermission, permissions } from '@ghostfolio/common/permissions'; |
|
||||
import { 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 { Tag } from '@prisma/client'; |
|
||||
import { StatusCodes, getReasonPhrase } from 'http-status-codes'; |
|
||||
|
|
||||
@Controller('tags') |
|
||||
export class TagsController { |
|
||||
public constructor( |
|
||||
@Inject(REQUEST) private readonly request: RequestWithUser, |
|
||||
private readonly tagService: TagService |
|
||||
) {} |
|
||||
|
|
||||
@Post() |
|
||||
@UseGuards(AuthGuard('jwt')) |
|
||||
public async createTag(@Body() data: CreateTagDto): Promise<Tag> { |
|
||||
const canCreateOwnTag = hasPermission( |
|
||||
this.request.user.permissions, |
|
||||
permissions.createOwnTag |
|
||||
); |
|
||||
|
|
||||
const canCreateTag = hasPermission( |
|
||||
this.request.user.permissions, |
|
||||
permissions.createTag |
|
||||
); |
|
||||
|
|
||||
if (!canCreateOwnTag && !canCreateTag) { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.FORBIDDEN), |
|
||||
StatusCodes.FORBIDDEN |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
if (canCreateOwnTag && !canCreateTag) { |
|
||||
if (data.userId !== this.request.user.id) { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.BAD_REQUEST), |
|
||||
StatusCodes.BAD_REQUEST |
|
||||
); |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
return this.tagService.createTag(data); |
|
||||
} |
|
||||
|
|
||||
@Delete(':id') |
|
||||
@HasPermission(permissions.deleteTag) |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async deleteTag(@Param('id') id: string) { |
|
||||
const originalTag = await this.tagService.getTag({ |
|
||||
id |
|
||||
}); |
|
||||
|
|
||||
if (!originalTag) { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.FORBIDDEN), |
|
||||
StatusCodes.FORBIDDEN |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
return this.tagService.deleteTag({ id }); |
|
||||
} |
|
||||
|
|
||||
@Get() |
|
||||
@HasPermission(permissions.readTags) |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async getTags() { |
|
||||
return this.tagService.getTagsWithActivityCount(); |
|
||||
} |
|
||||
|
|
||||
@HasPermission(permissions.updateTag) |
|
||||
@Put(':id') |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async updateTag(@Param('id') id: string, @Body() data: UpdateTagDto) { |
|
||||
const originalTag = await this.tagService.getTag({ |
|
||||
id |
|
||||
}); |
|
||||
|
|
||||
if (!originalTag) { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.FORBIDDEN), |
|
||||
StatusCodes.FORBIDDEN |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
return this.tagService.updateTag({ |
|
||||
data: { |
|
||||
...data |
|
||||
}, |
|
||||
where: { |
|
||||
id |
|
||||
} |
|
||||
}); |
|
||||
} |
|
||||
} |
|
||||
@ -1,12 +0,0 @@ |
|||||
import { PrismaModule } from '@ghostfolio/api/services/prisma/prisma.module'; |
|
||||
import { TagModule } from '@ghostfolio/api/services/tag/tag.module'; |
|
||||
|
|
||||
import { Module } from '@nestjs/common'; |
|
||||
|
|
||||
import { TagsController } from './tags.controller'; |
|
||||
|
|
||||
@Module({ |
|
||||
controllers: [TagsController], |
|
||||
imports: [PrismaModule, TagModule] |
|
||||
}) |
|
||||
export class TagsModule {} |
|
||||
@ -1,100 +0,0 @@ |
|||||
import { HasPermission } from '@ghostfolio/api/decorators/has-permission.decorator'; |
|
||||
import { HasPermissionGuard } from '@ghostfolio/api/guards/has-permission.guard'; |
|
||||
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 { ImpersonationService } from '@ghostfolio/api/services/impersonation/impersonation.service'; |
|
||||
import { HEADER_KEY_IMPERSONATION } from '@ghostfolio/common/config'; |
|
||||
import { CreateWatchlistItemDto } from '@ghostfolio/common/dtos'; |
|
||||
import { WatchlistResponse } from '@ghostfolio/common/interfaces'; |
|
||||
import { permissions } from '@ghostfolio/common/permissions'; |
|
||||
import { RequestWithUser } from '@ghostfolio/common/types'; |
|
||||
|
|
||||
import { |
|
||||
Body, |
|
||||
Controller, |
|
||||
Delete, |
|
||||
Get, |
|
||||
Headers, |
|
||||
HttpException, |
|
||||
Inject, |
|
||||
Param, |
|
||||
Post, |
|
||||
UseGuards, |
|
||||
UseInterceptors |
|
||||
} from '@nestjs/common'; |
|
||||
import { REQUEST } from '@nestjs/core'; |
|
||||
import { AuthGuard } from '@nestjs/passport'; |
|
||||
import { DataSource } from '@prisma/client'; |
|
||||
import { StatusCodes, getReasonPhrase } from 'http-status-codes'; |
|
||||
|
|
||||
import { WatchlistService } from './watchlist.service'; |
|
||||
|
|
||||
@Controller('watchlist') |
|
||||
export class WatchlistController { |
|
||||
public constructor( |
|
||||
private readonly impersonationService: ImpersonationService, |
|
||||
@Inject(REQUEST) private readonly request: RequestWithUser, |
|
||||
private readonly watchlistService: WatchlistService |
|
||||
) {} |
|
||||
|
|
||||
@Post() |
|
||||
@HasPermission(permissions.createWatchlistItem) |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
@UseInterceptors(TransformDataSourceInRequestInterceptor) |
|
||||
public async createWatchlistItem(@Body() data: CreateWatchlistItemDto) { |
|
||||
return this.watchlistService.createWatchlistItem({ |
|
||||
dataSource: data.dataSource, |
|
||||
symbol: data.symbol, |
|
||||
userId: this.request.user.id |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
@Delete(':dataSource/:symbol') |
|
||||
@HasPermission(permissions.deleteWatchlistItem) |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
@UseInterceptors(TransformDataSourceInRequestInterceptor) |
|
||||
public async deleteWatchlistItem( |
|
||||
@Param('dataSource') dataSource: DataSource, |
|
||||
@Param('symbol') symbol: string |
|
||||
) { |
|
||||
const watchlistItems = await this.watchlistService.getWatchlistItems( |
|
||||
this.request.user.id |
|
||||
); |
|
||||
|
|
||||
const watchlistItem = watchlistItems.find((item) => { |
|
||||
return item.dataSource === dataSource && item.symbol === symbol; |
|
||||
}); |
|
||||
|
|
||||
if (!watchlistItem) { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.NOT_FOUND), |
|
||||
StatusCodes.NOT_FOUND |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
return this.watchlistService.deleteWatchlistItem({ |
|
||||
dataSource, |
|
||||
symbol, |
|
||||
userId: this.request.user.id |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
@Get() |
|
||||
@HasPermission(permissions.readWatchlist) |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
@UseInterceptors(TransformDataSourceInResponseInterceptor) |
|
||||
public async getWatchlistItems( |
|
||||
@Headers(HEADER_KEY_IMPERSONATION.toLowerCase()) impersonationId: string |
|
||||
): Promise<WatchlistResponse> { |
|
||||
const impersonationUserId = |
|
||||
await this.impersonationService.validateImpersonationId(impersonationId); |
|
||||
|
|
||||
const watchlist = await this.watchlistService.getWatchlistItems( |
|
||||
impersonationUserId || this.request.user.id |
|
||||
); |
|
||||
|
|
||||
return { |
|
||||
watchlist |
|
||||
}; |
|
||||
} |
|
||||
} |
|
||||
@ -1,31 +0,0 @@ |
|||||
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 { BenchmarkModule } from '@ghostfolio/api/services/benchmark/benchmark.module'; |
|
||||
import { DataProviderModule } from '@ghostfolio/api/services/data-provider/data-provider.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 { DataGatheringModule } 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 { WatchlistController } from './watchlist.controller'; |
|
||||
import { WatchlistService } from './watchlist.service'; |
|
||||
|
|
||||
@Module({ |
|
||||
controllers: [WatchlistController], |
|
||||
imports: [ |
|
||||
BenchmarkModule, |
|
||||
DataGatheringModule, |
|
||||
DataProviderModule, |
|
||||
ImpersonationModule, |
|
||||
MarketDataModule, |
|
||||
PrismaModule, |
|
||||
SymbolProfileModule, |
|
||||
TransformDataSourceInRequestModule, |
|
||||
TransformDataSourceInResponseModule |
|
||||
], |
|
||||
providers: [WatchlistService] |
|
||||
}) |
|
||||
export class WatchlistModule {} |
|
||||
@ -1,155 +0,0 @@ |
|||||
import { BenchmarkService } from '@ghostfolio/api/services/benchmark/benchmark.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 { SymbolProfileService } from '@ghostfolio/api/services/symbol-profile/symbol-profile.service'; |
|
||||
import { WatchlistResponse } from '@ghostfolio/common/interfaces'; |
|
||||
|
|
||||
import { BadRequestException, Injectable } from '@nestjs/common'; |
|
||||
import { DataSource, Prisma } from '@prisma/client'; |
|
||||
|
|
||||
@Injectable() |
|
||||
export class WatchlistService { |
|
||||
public constructor( |
|
||||
private readonly benchmarkService: BenchmarkService, |
|
||||
private readonly dataGatheringService: DataGatheringService, |
|
||||
private readonly dataProviderService: DataProviderService, |
|
||||
private readonly marketDataService: MarketDataService, |
|
||||
private readonly prismaService: PrismaService, |
|
||||
private readonly symbolProfileService: SymbolProfileService |
|
||||
) {} |
|
||||
|
|
||||
public async createWatchlistItem({ |
|
||||
dataSource, |
|
||||
symbol, |
|
||||
userId |
|
||||
}: { |
|
||||
dataSource: DataSource; |
|
||||
symbol: string; |
|
||||
userId: string; |
|
||||
}): Promise<void> { |
|
||||
const symbolProfile = await this.prismaService.symbolProfile.findUnique({ |
|
||||
where: { |
|
||||
dataSource_symbol: { dataSource, symbol } |
|
||||
} |
|
||||
}); |
|
||||
|
|
||||
if (!symbolProfile) { |
|
||||
const assetProfiles = await this.dataProviderService.getAssetProfiles([ |
|
||||
{ dataSource, symbol } |
|
||||
]); |
|
||||
|
|
||||
if (!assetProfiles[symbol]?.currency) { |
|
||||
throw new BadRequestException( |
|
||||
`Asset profile not found for ${symbol} (${dataSource})` |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
await this.symbolProfileService.add( |
|
||||
assetProfiles[symbol] as Prisma.SymbolProfileCreateInput |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
await this.dataGatheringService.gatherSymbol({ |
|
||||
dataSource, |
|
||||
symbol |
|
||||
}); |
|
||||
|
|
||||
await this.prismaService.user.update({ |
|
||||
data: { |
|
||||
watchlist: { |
|
||||
connect: { |
|
||||
dataSource_symbol: { dataSource, symbol } |
|
||||
} |
|
||||
} |
|
||||
}, |
|
||||
where: { id: userId } |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
public async deleteWatchlistItem({ |
|
||||
dataSource, |
|
||||
symbol, |
|
||||
userId |
|
||||
}: { |
|
||||
dataSource: DataSource; |
|
||||
symbol: string; |
|
||||
userId: string; |
|
||||
}) { |
|
||||
await this.prismaService.user.update({ |
|
||||
data: { |
|
||||
watchlist: { |
|
||||
disconnect: { |
|
||||
dataSource_symbol: { dataSource, symbol } |
|
||||
} |
|
||||
} |
|
||||
}, |
|
||||
where: { id: userId } |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
public async getWatchlistItems( |
|
||||
userId: string |
|
||||
): Promise<WatchlistResponse['watchlist']> { |
|
||||
const user = await this.prismaService.user.findUnique({ |
|
||||
select: { |
|
||||
watchlist: { |
|
||||
select: { dataSource: true, symbol: true } |
|
||||
} |
|
||||
}, |
|
||||
where: { id: userId } |
|
||||
}); |
|
||||
|
|
||||
const [assetProfiles, quotes] = await Promise.all([ |
|
||||
this.symbolProfileService.getSymbolProfiles(user.watchlist), |
|
||||
this.dataProviderService.getQuotes({ |
|
||||
items: user.watchlist.map(({ dataSource, symbol }) => { |
|
||||
return { dataSource, symbol }; |
|
||||
}) |
|
||||
}) |
|
||||
]); |
|
||||
|
|
||||
const watchlist = await Promise.all( |
|
||||
user.watchlist.map(async ({ dataSource, symbol }) => { |
|
||||
const assetProfile = assetProfiles.find((profile) => { |
|
||||
return profile.dataSource === dataSource && profile.symbol === symbol; |
|
||||
}); |
|
||||
|
|
||||
const [allTimeHigh, trends] = await Promise.all([ |
|
||||
this.marketDataService.getMax({ |
|
||||
dataSource, |
|
||||
symbol |
|
||||
}), |
|
||||
this.benchmarkService.getBenchmarkTrends({ dataSource, symbol }) |
|
||||
]); |
|
||||
|
|
||||
const performancePercent = |
|
||||
this.benchmarkService.calculateChangeInPercentage( |
|
||||
allTimeHigh?.marketPrice, |
|
||||
quotes[symbol]?.marketPrice |
|
||||
); |
|
||||
|
|
||||
return { |
|
||||
dataSource, |
|
||||
symbol, |
|
||||
marketCondition: |
|
||||
this.benchmarkService.getMarketCondition(performancePercent), |
|
||||
name: assetProfile?.name, |
|
||||
performances: { |
|
||||
allTimeHigh: { |
|
||||
performancePercent, |
|
||||
date: allTimeHigh?.date |
|
||||
} |
|
||||
}, |
|
||||
trend50d: trends.trend50d, |
|
||||
trend200d: trends.trend200d |
|
||||
}; |
|
||||
}) |
|
||||
); |
|
||||
|
|
||||
return watchlist.sort((a, b) => { |
|
||||
return a.name.localeCompare(b.name); |
|
||||
}); |
|
||||
} |
|
||||
} |
|
||||
@ -1,45 +0,0 @@ |
|||||
import { HasPermissionGuard } from '@ghostfolio/api/guards/has-permission.guard'; |
|
||||
import { DataProviderHistoricalResponse } from '@ghostfolio/common/interfaces'; |
|
||||
|
|
||||
import { |
|
||||
Controller, |
|
||||
Get, |
|
||||
HttpException, |
|
||||
Param, |
|
||||
UseGuards |
|
||||
} from '@nestjs/common'; |
|
||||
import { AuthGuard } from '@nestjs/passport'; |
|
||||
import { parseISO } from 'date-fns'; |
|
||||
import { StatusCodes, getReasonPhrase } from 'http-status-codes'; |
|
||||
|
|
||||
import { ExchangeRateService } from './exchange-rate.service'; |
|
||||
|
|
||||
@Controller('exchange-rate') |
|
||||
export class ExchangeRateController { |
|
||||
public constructor( |
|
||||
private readonly exchangeRateService: ExchangeRateService |
|
||||
) {} |
|
||||
|
|
||||
@Get(':symbol/:dateString') |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
public async getExchangeRate( |
|
||||
@Param('dateString') dateString: string, |
|
||||
@Param('symbol') symbol: string |
|
||||
): Promise<DataProviderHistoricalResponse> { |
|
||||
const date = parseISO(dateString); |
|
||||
|
|
||||
const exchangeRate = await this.exchangeRateService.getExchangeRate({ |
|
||||
date, |
|
||||
symbol |
|
||||
}); |
|
||||
|
|
||||
if (exchangeRate) { |
|
||||
return { marketPrice: exchangeRate }; |
|
||||
} |
|
||||
|
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.NOT_FOUND), |
|
||||
StatusCodes.NOT_FOUND |
|
||||
); |
|
||||
} |
|
||||
} |
|
||||
@ -1,14 +0,0 @@ |
|||||
import { ExchangeRateDataModule } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.module'; |
|
||||
|
|
||||
import { Module } from '@nestjs/common'; |
|
||||
|
|
||||
import { ExchangeRateController } from './exchange-rate.controller'; |
|
||||
import { ExchangeRateService } from './exchange-rate.service'; |
|
||||
|
|
||||
@Module({ |
|
||||
controllers: [ExchangeRateController], |
|
||||
exports: [ExchangeRateService], |
|
||||
imports: [ExchangeRateDataModule], |
|
||||
providers: [ExchangeRateService] |
|
||||
}) |
|
||||
export class ExchangeRateModule {} |
|
||||
@ -1,27 +0,0 @@ |
|||||
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.service'; |
|
||||
|
|
||||
import { Injectable } from '@nestjs/common'; |
|
||||
|
|
||||
@Injectable() |
|
||||
export class ExchangeRateService { |
|
||||
public constructor( |
|
||||
private readonly exchangeRateDataService: ExchangeRateDataService |
|
||||
) {} |
|
||||
|
|
||||
public async getExchangeRate({ |
|
||||
date, |
|
||||
symbol |
|
||||
}: { |
|
||||
date: Date; |
|
||||
symbol: string; |
|
||||
}): Promise<number> { |
|
||||
const [currency1, currency2] = symbol.split('-'); |
|
||||
|
|
||||
return this.exchangeRateDataService.toCurrencyAtDate( |
|
||||
1, |
|
||||
currency1, |
|
||||
currency2, |
|
||||
date |
|
||||
); |
|
||||
} |
|
||||
} |
|
||||
@ -1,57 +0,0 @@ |
|||||
import { HasPermissionGuard } from '@ghostfolio/api/guards/has-permission.guard'; |
|
||||
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 { ApiService } from '@ghostfolio/api/services/api/api.service'; |
|
||||
import { ExportResponse } from '@ghostfolio/common/interfaces'; |
|
||||
import type { RequestWithUser } from '@ghostfolio/common/types'; |
|
||||
|
|
||||
import { |
|
||||
Controller, |
|
||||
Get, |
|
||||
Inject, |
|
||||
Query, |
|
||||
UseGuards, |
|
||||
UseInterceptors |
|
||||
} from '@nestjs/common'; |
|
||||
import { REQUEST } from '@nestjs/core'; |
|
||||
import { AuthGuard } from '@nestjs/passport'; |
|
||||
|
|
||||
import { ExportService } from './export.service'; |
|
||||
|
|
||||
@Controller('export') |
|
||||
export class ExportController { |
|
||||
public constructor( |
|
||||
private readonly apiService: ApiService, |
|
||||
private readonly exportService: ExportService, |
|
||||
@Inject(REQUEST) private readonly request: RequestWithUser |
|
||||
) {} |
|
||||
|
|
||||
@Get() |
|
||||
@UseGuards(AuthGuard('jwt'), HasPermissionGuard) |
|
||||
@UseInterceptors(TransformDataSourceInRequestInterceptor) |
|
||||
@UseInterceptors(TransformDataSourceInResponseInterceptor) |
|
||||
public async export( |
|
||||
@Query('accounts') filterByAccounts?: string, |
|
||||
@Query('activityIds') filterByActivityIds?: string, |
|
||||
@Query('assetClasses') filterByAssetClasses?: string, |
|
||||
@Query('dataSource') filterByDataSource?: string, |
|
||||
@Query('symbol') filterBySymbol?: string, |
|
||||
@Query('tags') filterByTags?: string |
|
||||
): Promise<ExportResponse> { |
|
||||
const activityIds = filterByActivityIds?.split(',') ?? []; |
|
||||
const filters = this.apiService.buildFiltersFromQueryParams({ |
|
||||
filterByAccounts, |
|
||||
filterByAssetClasses, |
|
||||
filterByDataSource, |
|
||||
filterBySymbol, |
|
||||
filterByTags |
|
||||
}); |
|
||||
|
|
||||
return this.exportService.export({ |
|
||||
activityIds, |
|
||||
filters, |
|
||||
userId: this.request.user.id, |
|
||||
userSettings: this.request.user.settings.settings |
|
||||
}); |
|
||||
} |
|
||||
} |
|
||||
@ -1,25 +0,0 @@ |
|||||
import { AccountModule } from '@ghostfolio/api/app/account/account.module'; |
|
||||
import { OrderModule } from '@ghostfolio/api/app/order/order.module'; |
|
||||
import { TransformDataSourceInRequestModule } from '@ghostfolio/api/interceptors/transform-data-source-in-request/transform-data-source-in-request.module'; |
|
||||
import { ApiModule } from '@ghostfolio/api/services/api/api.module'; |
|
||||
import { MarketDataModule } from '@ghostfolio/api/services/market-data/market-data.module'; |
|
||||
import { TagModule } from '@ghostfolio/api/services/tag/tag.module'; |
|
||||
|
|
||||
import { Module } from '@nestjs/common'; |
|
||||
|
|
||||
import { ExportController } from './export.controller'; |
|
||||
import { ExportService } from './export.service'; |
|
||||
|
|
||||
@Module({ |
|
||||
controllers: [ExportController], |
|
||||
imports: [ |
|
||||
AccountModule, |
|
||||
ApiModule, |
|
||||
MarketDataModule, |
|
||||
OrderModule, |
|
||||
TagModule, |
|
||||
TransformDataSourceInRequestModule |
|
||||
], |
|
||||
providers: [ExportService] |
|
||||
}) |
|
||||
export class ExportModule {} |
|
||||
@ -1,258 +0,0 @@ |
|||||
import { AccountService } from '@ghostfolio/api/app/account/account.service'; |
|
||||
import { OrderService } from '@ghostfolio/api/app/order/order.service'; |
|
||||
import { environment } from '@ghostfolio/api/environments/environment'; |
|
||||
import { MarketDataService } from '@ghostfolio/api/services/market-data/market-data.service'; |
|
||||
import { TagService } from '@ghostfolio/api/services/tag/tag.service'; |
|
||||
import { |
|
||||
ExportResponse, |
|
||||
Filter, |
|
||||
UserSettings |
|
||||
} from '@ghostfolio/common/interfaces'; |
|
||||
|
|
||||
import { Injectable } from '@nestjs/common'; |
|
||||
import { Platform, Prisma } from '@prisma/client'; |
|
||||
import { groupBy, uniqBy } from 'lodash'; |
|
||||
|
|
||||
@Injectable() |
|
||||
export class ExportService { |
|
||||
public constructor( |
|
||||
private readonly accountService: AccountService, |
|
||||
private readonly marketDataService: MarketDataService, |
|
||||
private readonly orderService: OrderService, |
|
||||
private readonly tagService: TagService |
|
||||
) {} |
|
||||
|
|
||||
public async export({ |
|
||||
activityIds, |
|
||||
filters, |
|
||||
userId, |
|
||||
userSettings |
|
||||
}: { |
|
||||
activityIds?: string[]; |
|
||||
filters?: Filter[]; |
|
||||
userId: string; |
|
||||
userSettings: UserSettings; |
|
||||
}): Promise<ExportResponse> { |
|
||||
const { ACCOUNT: filtersByAccount } = groupBy(filters, ({ type }) => { |
|
||||
return type; |
|
||||
}); |
|
||||
const platformsMap: { [platformId: string]: Platform } = {}; |
|
||||
|
|
||||
let { activities } = await this.orderService.getOrders({ |
|
||||
filters, |
|
||||
userId, |
|
||||
includeDrafts: true, |
|
||||
sortColumn: 'date', |
|
||||
sortDirection: 'asc', |
|
||||
userCurrency: userSettings?.baseCurrency, |
|
||||
withExcludedAccountsAndActivities: true |
|
||||
}); |
|
||||
|
|
||||
if (activityIds?.length > 0) { |
|
||||
activities = activities.filter(({ id }) => { |
|
||||
return activityIds.includes(id); |
|
||||
}); |
|
||||
} |
|
||||
|
|
||||
const where: Prisma.AccountWhereInput = { userId }; |
|
||||
|
|
||||
if (filtersByAccount?.length > 0) { |
|
||||
where.id = { |
|
||||
in: filtersByAccount.map(({ id }) => { |
|
||||
return id; |
|
||||
}) |
|
||||
}; |
|
||||
} |
|
||||
|
|
||||
const accounts = ( |
|
||||
await this.accountService.accounts({ |
|
||||
where, |
|
||||
include: { |
|
||||
balances: true, |
|
||||
platform: true |
|
||||
}, |
|
||||
orderBy: { |
|
||||
name: 'asc' |
|
||||
} |
|
||||
}) |
|
||||
) |
|
||||
.filter(({ id }) => { |
|
||||
return activityIds?.length > 0 |
|
||||
? activities.some(({ accountId }) => { |
|
||||
return accountId === id; |
|
||||
}) |
|
||||
: true; |
|
||||
}) |
|
||||
.map( |
|
||||
({ |
|
||||
balance, |
|
||||
balances, |
|
||||
comment, |
|
||||
currency, |
|
||||
id, |
|
||||
isExcluded, |
|
||||
name, |
|
||||
platform, |
|
||||
platformId |
|
||||
}) => { |
|
||||
if (platformId) { |
|
||||
platformsMap[platformId] = platform; |
|
||||
} |
|
||||
|
|
||||
return { |
|
||||
balance, |
|
||||
balances: balances.map(({ date, value }) => { |
|
||||
return { date: date.toISOString(), value }; |
|
||||
}), |
|
||||
comment, |
|
||||
currency, |
|
||||
id, |
|
||||
isExcluded, |
|
||||
name, |
|
||||
platformId |
|
||||
}; |
|
||||
} |
|
||||
); |
|
||||
|
|
||||
const customAssetProfiles = uniqBy( |
|
||||
activities |
|
||||
.map(({ SymbolProfile }) => { |
|
||||
return SymbolProfile; |
|
||||
}) |
|
||||
.filter(({ userId: assetProfileUserId }) => { |
|
||||
return assetProfileUserId === userId; |
|
||||
}), |
|
||||
({ id }) => { |
|
||||
return id; |
|
||||
} |
|
||||
); |
|
||||
|
|
||||
const marketDataByAssetProfile = Object.fromEntries( |
|
||||
await Promise.all( |
|
||||
customAssetProfiles.map(async ({ dataSource, id, symbol }) => { |
|
||||
const marketData = ( |
|
||||
await this.marketDataService.marketDataItems({ |
|
||||
where: { dataSource, symbol } |
|
||||
}) |
|
||||
).map(({ date, marketPrice }) => ({ |
|
||||
date: date.toISOString(), |
|
||||
marketPrice |
|
||||
})); |
|
||||
|
|
||||
return [id, marketData] as const; |
|
||||
}) |
|
||||
) |
|
||||
); |
|
||||
|
|
||||
const tags = (await this.tagService.getTagsForUser(userId)) |
|
||||
.filter(({ id, isUsed }) => { |
|
||||
return ( |
|
||||
isUsed && |
|
||||
activities.some((activity) => { |
|
||||
return activity.tags.some(({ id: tagId }) => { |
|
||||
return tagId === id; |
|
||||
}); |
|
||||
}) |
|
||||
); |
|
||||
}) |
|
||||
.map(({ id, name }) => { |
|
||||
return { |
|
||||
id, |
|
||||
name |
|
||||
}; |
|
||||
}); |
|
||||
|
|
||||
return { |
|
||||
meta: { date: new Date().toISOString(), version: environment.version }, |
|
||||
accounts, |
|
||||
assetProfiles: customAssetProfiles.map( |
|
||||
({ |
|
||||
assetClass, |
|
||||
assetSubClass, |
|
||||
comment, |
|
||||
countries, |
|
||||
currency, |
|
||||
cusip, |
|
||||
dataSource, |
|
||||
figi, |
|
||||
figiComposite, |
|
||||
figiShareClass, |
|
||||
holdings, |
|
||||
id, |
|
||||
isActive, |
|
||||
isin, |
|
||||
name, |
|
||||
scraperConfiguration, |
|
||||
sectors, |
|
||||
symbol, |
|
||||
symbolMapping, |
|
||||
url |
|
||||
}) => { |
|
||||
return { |
|
||||
assetClass, |
|
||||
assetSubClass, |
|
||||
comment, |
|
||||
countries: countries as unknown as Prisma.JsonArray, |
|
||||
currency, |
|
||||
cusip, |
|
||||
dataSource, |
|
||||
figi, |
|
||||
figiComposite, |
|
||||
figiShareClass, |
|
||||
holdings: holdings as unknown as Prisma.JsonArray, |
|
||||
isActive, |
|
||||
isin, |
|
||||
marketData: marketDataByAssetProfile[id], |
|
||||
name, |
|
||||
scraperConfiguration: |
|
||||
scraperConfiguration as unknown as Prisma.JsonArray, |
|
||||
sectors: sectors as unknown as Prisma.JsonArray, |
|
||||
symbol, |
|
||||
symbolMapping, |
|
||||
url |
|
||||
}; |
|
||||
} |
|
||||
), |
|
||||
platforms: Object.values(platformsMap), |
|
||||
tags, |
|
||||
activities: activities.map( |
|
||||
({ |
|
||||
accountId, |
|
||||
comment, |
|
||||
currency, |
|
||||
date, |
|
||||
fee, |
|
||||
id, |
|
||||
quantity, |
|
||||
SymbolProfile, |
|
||||
tags: currentTags, |
|
||||
type, |
|
||||
unitPrice |
|
||||
}) => { |
|
||||
return { |
|
||||
accountId, |
|
||||
comment, |
|
||||
fee, |
|
||||
id, |
|
||||
quantity, |
|
||||
type, |
|
||||
unitPrice, |
|
||||
currency: currency ?? SymbolProfile.currency, |
|
||||
dataSource: SymbolProfile.dataSource, |
|
||||
date: date.toISOString(), |
|
||||
symbol: SymbolProfile.symbol, |
|
||||
tags: currentTags.map(({ id: tagId }) => { |
|
||||
return tagId; |
|
||||
}) |
|
||||
}; |
|
||||
} |
|
||||
), |
|
||||
user: { |
|
||||
settings: { |
|
||||
currency: userSettings?.baseCurrency, |
|
||||
performanceCalculationType: userSettings?.performanceCalculationType |
|
||||
} |
|
||||
} |
|
||||
}; |
|
||||
} |
|
||||
} |
|
||||
@ -1,88 +0,0 @@ |
|||||
import { TransformDataSourceInRequestInterceptor } from '@ghostfolio/api/interceptors/transform-data-source-in-request/transform-data-source-in-request.interceptor'; |
|
||||
import { |
|
||||
DataEnhancerHealthResponse, |
|
||||
DataProviderHealthResponse |
|
||||
} from '@ghostfolio/common/interfaces'; |
|
||||
|
|
||||
import { |
|
||||
Controller, |
|
||||
Get, |
|
||||
HttpException, |
|
||||
HttpStatus, |
|
||||
Param, |
|
||||
Res, |
|
||||
UseInterceptors |
|
||||
} from '@nestjs/common'; |
|
||||
import { DataSource } from '@prisma/client'; |
|
||||
import { Response } from 'express'; |
|
||||
import { StatusCodes, getReasonPhrase } from 'http-status-codes'; |
|
||||
|
|
||||
import { HealthService } from './health.service'; |
|
||||
|
|
||||
@Controller('health') |
|
||||
export class HealthController { |
|
||||
public constructor(private readonly healthService: HealthService) {} |
|
||||
|
|
||||
@Get() |
|
||||
public async getHealth(@Res() response: Response) { |
|
||||
const databaseServiceHealthy = await this.healthService.isDatabaseHealthy(); |
|
||||
const redisCacheServiceHealthy = |
|
||||
await this.healthService.isRedisCacheHealthy(); |
|
||||
|
|
||||
if (databaseServiceHealthy && redisCacheServiceHealthy) { |
|
||||
return response |
|
||||
.status(HttpStatus.OK) |
|
||||
.json({ status: getReasonPhrase(StatusCodes.OK) }); |
|
||||
} else { |
|
||||
return response |
|
||||
.status(HttpStatus.SERVICE_UNAVAILABLE) |
|
||||
.json({ status: getReasonPhrase(StatusCodes.SERVICE_UNAVAILABLE) }); |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
@Get('data-enhancer/:name') |
|
||||
public async getHealthOfDataEnhancer( |
|
||||
@Param('name') name: string, |
|
||||
@Res() response: Response |
|
||||
): Promise<Response<DataEnhancerHealthResponse>> { |
|
||||
const hasResponse = |
|
||||
await this.healthService.hasResponseFromDataEnhancer(name); |
|
||||
|
|
||||
if (hasResponse) { |
|
||||
return response.status(HttpStatus.OK).json({ |
|
||||
status: getReasonPhrase(StatusCodes.OK) |
|
||||
}); |
|
||||
} else { |
|
||||
return response |
|
||||
.status(HttpStatus.SERVICE_UNAVAILABLE) |
|
||||
.json({ status: getReasonPhrase(StatusCodes.SERVICE_UNAVAILABLE) }); |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
@Get('data-provider/:dataSource') |
|
||||
@UseInterceptors(TransformDataSourceInRequestInterceptor) |
|
||||
public async getHealthOfDataProvider( |
|
||||
@Param('dataSource') dataSource: DataSource, |
|
||||
@Res() response: Response |
|
||||
): Promise<Response<DataProviderHealthResponse>> { |
|
||||
if (!DataSource[dataSource]) { |
|
||||
throw new HttpException( |
|
||||
getReasonPhrase(StatusCodes.NOT_FOUND), |
|
||||
StatusCodes.NOT_FOUND |
|
||||
); |
|
||||
} |
|
||||
|
|
||||
const hasResponse = |
|
||||
await this.healthService.hasResponseFromDataProvider(dataSource); |
|
||||
|
|
||||
if (hasResponse) { |
|
||||
return response |
|
||||
.status(HttpStatus.OK) |
|
||||
.json({ status: getReasonPhrase(StatusCodes.OK) }); |
|
||||
} else { |
|
||||
return response |
|
||||
.status(HttpStatus.SERVICE_UNAVAILABLE) |
|
||||
.json({ status: getReasonPhrase(StatusCodes.SERVICE_UNAVAILABLE) }); |
|
||||
} |
|
||||
} |
|
||||
} |
|
||||
@ -1,23 +0,0 @@ |
|||||
import { RedisCacheModule } from '@ghostfolio/api/app/redis-cache/redis-cache.module'; |
|
||||
import { TransformDataSourceInRequestModule } from '@ghostfolio/api/interceptors/transform-data-source-in-request/transform-data-source-in-request.module'; |
|
||||
import { DataEnhancerModule } from '@ghostfolio/api/services/data-provider/data-enhancer/data-enhancer.module'; |
|
||||
import { DataProviderModule } from '@ghostfolio/api/services/data-provider/data-provider.module'; |
|
||||
import { PropertyModule } from '@ghostfolio/api/services/property/property.module'; |
|
||||
|
|
||||
import { Module } from '@nestjs/common'; |
|
||||
|
|
||||
import { HealthController } from './health.controller'; |
|
||||
import { HealthService } from './health.service'; |
|
||||
|
|
||||
@Module({ |
|
||||
controllers: [HealthController], |
|
||||
imports: [ |
|
||||
DataEnhancerModule, |
|
||||
DataProviderModule, |
|
||||
PropertyModule, |
|
||||
RedisCacheModule, |
|
||||
TransformDataSourceInRequestModule |
|
||||
], |
|
||||
providers: [HealthService] |
|
||||
}) |
|
||||
export class HealthModule {} |
|
||||
Some files were not shown because too many files changed in this diff
Loading…
Reference in new issue