Compare commits
44 Commits
a5e5824a44
...
1.2.0
| Author | SHA1 | Date | |
|---|---|---|---|
| 9a109b4709 | |||
| 7fd7882188 | |||
| af648bca70 | |||
| b7e0fa1c8b | |||
| b58008c8bc | |||
| ac0118d435 | |||
| 765c5d5b32 | |||
| b8ca1b94ec | |||
| b19cdd0264 | |||
| 27f747b44d | |||
| 8f42add0c2 | |||
| 9d1cf862c7 | |||
| 003cf7e2da | |||
| 6203a83af3 | |||
| c1c530c46b | |||
| 41e32efd7e | |||
| d73d349a58 | |||
| f958fb7853 | |||
| 7ad72119a8 | |||
| f7f2bf5768 | |||
| 28df2a66ca | |||
| 29f26a8a18 | |||
| a3fa59f347 | |||
| 2880934644 | |||
| b42980200d | |||
| 8381cdbffa | |||
| 5cab2fed3b | |||
| 417eef7042 | |||
| ed5543ce61 | |||
| 40b8f45de8 | |||
| b221d07b48 | |||
| 0e63b6e4e6 | |||
| 4a04c85fe8 | |||
| b8e2c9114d | |||
| 0876eecf50 | |||
| 5549691d50 | |||
| 46c8df45d6 | |||
| 50d274f36a | |||
| ba4f365f06 | |||
| 19c7e1915f | |||
| 229a6a8a43 | |||
| 76e878ff5c | |||
| 726be3f613 | |||
| 936140e76f |
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(git add *)",
|
||||
"Bash(git commit *)"
|
||||
]
|
||||
}
|
||||
}
|
||||
+37
-34
@@ -7,48 +7,51 @@ on:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-java17
|
||||
|
||||
steps:
|
||||
# 1. Checkout the code
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v2
|
||||
uses: actions/checkout@v4
|
||||
|
||||
# 2. Set up Java and Maven
|
||||
- name: Set up JDK (Eclipse Temurin)
|
||||
uses: actions/setup-java@v3
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: "17"
|
||||
cache: maven
|
||||
|
||||
# 3. Verify Maven installation
|
||||
- name: Install Maven
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y maven
|
||||
mvn -version
|
||||
|
||||
# 4. Build the Spring Boot application
|
||||
# 2. Build the Spring Boot application using the Maven wrapper (Java 17 pre-installed in runner image)
|
||||
- name: Build Spring Boot Application
|
||||
run: |
|
||||
mvn clean package -DskipTests
|
||||
run: ./mvnw clean package -DskipTests
|
||||
|
||||
# 5. Set up Docker
|
||||
- name: Set up Docker
|
||||
run: |
|
||||
docker --version
|
||||
# 4. Set up Docker Buildx (enables layer caching)
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
# 6. Build the Docker image
|
||||
- name: Build and Package Docker Image
|
||||
run: |
|
||||
docker build -t tea.zendric.de/cedric/xpensely-server:latest .
|
||||
# 5. Login to Docker Hub to avoid pull rate limits
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USER }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
# 7. Docker login
|
||||
# 6. Docker login to Gitea registry
|
||||
- name: Login to Docker Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: tea.zendric.de
|
||||
username: ${{ secrets.TEAUSER }}
|
||||
password: ${{ secrets.TEAPASSWORD }}
|
||||
|
||||
# 7. Build and push Docker image with layer caching
|
||||
- name: Build and Push Docker Image
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
tags: tea.zendric.de/cedric/xpensely-server:latest
|
||||
cache-from: type=registry,ref=tea.zendric.de/cedric/xpensely-server:buildcache
|
||||
cache-to: type=registry,ref=tea.zendric.de/cedric/xpensely-server:buildcache,mode=max
|
||||
|
||||
# 8. Trigger Dokploy to redeploy the dev server automatically via API
|
||||
- name: Trigger Dokploy Redeploy
|
||||
run: |
|
||||
echo "${{ secrets.TEAPASSWORD }}" | docker login tea.zendric.de -u ${{ secrets.TEAUSER }} --password-stdin
|
||||
# 8. Push Docker image
|
||||
- name: Push the Docker Image to registry
|
||||
run: |
|
||||
docker push tea.zendric.de/cedric/xpensely-server:latest
|
||||
curl -X POST "https://dokploy.zendric.de/api/compose.deploy" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "x-api-key: ${{ secrets.DOKPLOY_API_TOKEN }}" \
|
||||
-d "{\"composeId\": \"${{ secrets.DOKPLOY_COMPOSE_ID }}\"}" \
|
||||
--fail
|
||||
|
||||
@@ -7,78 +7,65 @@ on:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-java17
|
||||
|
||||
steps:
|
||||
# 1. Checkout the code
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v2
|
||||
uses: actions/checkout@v4
|
||||
|
||||
# 2. Set up Java and Maven
|
||||
- name: Set up JDK (Eclipse Temurin)
|
||||
uses: actions/setup-java@v3
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: "17"
|
||||
cache: maven
|
||||
|
||||
# 3. Verify Maven installation
|
||||
- name: Install Maven
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y maven
|
||||
mvn -version
|
||||
|
||||
# 4. Build the Spring Boot application
|
||||
# 2. Build the Spring Boot application using the Maven wrapper
|
||||
# (Java 17 is pre-installed in the runner image)
|
||||
- name: Build Spring Boot Application
|
||||
run: |
|
||||
mvn clean package -DskipTests
|
||||
run: ./mvnw clean package -DskipTests
|
||||
|
||||
# 5. Set up Docker
|
||||
- name: Set up Docker
|
||||
# 3. Derive version tags from the pushed git tag
|
||||
# e.g. 1.1.0 -> tag_version=1.1.0, minor=1.1, major=1
|
||||
- name: Extract version tags
|
||||
id: ver
|
||||
run: |
|
||||
docker --version
|
||||
|
||||
# 6. Extract the tag name
|
||||
- name: Extract Tag Version
|
||||
id: extract_version
|
||||
run: |
|
||||
TAG_VERSION=$(echo "${GITHUB_REF}" | sed 's#refs/tags/##')
|
||||
TAG_VERSION="${{ github.ref_name }}"
|
||||
if [ -z "$TAG_VERSION" ]; then
|
||||
echo "Error: TAG_VERSION is empty."
|
||||
exit 1
|
||||
fi
|
||||
echo "TAG_VERSION=$TAG_VERSION" >> $GITHUB_ENV
|
||||
MINOR_VERSION=$(echo "$TAG_VERSION" | cut -d. -f1,2)
|
||||
MAJOR_VERSION=$(echo "$TAG_VERSION" | cut -d. -f1)
|
||||
echo "tag_version=$TAG_VERSION" >> "$GITHUB_OUTPUT"
|
||||
echo "minor=$MINOR_VERSION" >> "$GITHUB_OUTPUT"
|
||||
echo "major=$MAJOR_VERSION" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# Extract major and minor versions
|
||||
MAJOR_VERSION=$(echo "${TAG_VERSION}" | cut -d. -f1)
|
||||
MINOR_VERSION=$(echo "${TAG_VERSION}" | cut -d. -f1,2)
|
||||
echo "MAJOR_VERSION=$MAJOR_VERSION" >> $GITHUB_ENV
|
||||
echo "MINOR_VERSION=$MINOR_VERSION" >> $GITHUB_ENV
|
||||
# 4. Set up Docker Buildx (enables layer caching)
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
# 7. Build the Docker image with the tag
|
||||
- name: Build and Package Docker Image
|
||||
run: |
|
||||
docker build -t tea.zendric.de/cedric/xpensely-server:${{ env.TAG_VERSION }} .
|
||||
# 5. Login to Docker Hub to avoid base-image pull rate limits
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USER }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
# 8. Tag the image with Major Version (e.g., 0)
|
||||
- name: Tag with Major Version
|
||||
run: |
|
||||
docker tag tea.zendric.de/cedric/xpensely-server:${{ env.TAG_VERSION }} tea.zendric.de/cedric/xpensely-server:${{ env.MAJOR_VERSION }}
|
||||
|
||||
# 9. Tag the image with Minor Version (e.g., 0.1)
|
||||
- name: Tag with Minor Version
|
||||
run: |
|
||||
docker tag tea.zendric.de/cedric/xpensely-server:${{ env.TAG_VERSION }} tea.zendric.de/cedric/xpensely-server:${{ env.MINOR_VERSION }}
|
||||
|
||||
# 10. Docker login
|
||||
# 6. Login to the Gitea registry
|
||||
- name: Login to Docker Registry
|
||||
run: |
|
||||
echo "${{ secrets.TEAPASSWORD }}" | docker login tea.zendric.de -u ${{ secrets.TEAUSER }} --password-stdin
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: tea.zendric.de
|
||||
username: ${{ secrets.TEAUSER }}
|
||||
password: ${{ secrets.TEAPASSWORD }}
|
||||
|
||||
# 11. Push the Docker images with the tags
|
||||
- name: Push the Docker Image to registry
|
||||
run: |
|
||||
docker push tea.zendric.de/cedric/xpensely-server:${{ env.TAG_VERSION }}
|
||||
docker push tea.zendric.de/cedric/xpensely-server:${{ env.MAJOR_VERSION }}
|
||||
docker push tea.zendric.de/cedric/xpensely-server:${{ env.MINOR_VERSION }}
|
||||
# 7. Build and push the versioned Docker images with layer caching.
|
||||
# Pushes exact, minor, and major tags. The prod compose references
|
||||
# the major tag (":1"), so pushing here makes the new build available
|
||||
# to pull in Dockge — deploy is triggered MANUALLY after the DB migration.
|
||||
- name: Build and Push Docker Image
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
tags: |
|
||||
tea.zendric.de/cedric/xpensely-server:${{ steps.ver.outputs.tag_version }}
|
||||
tea.zendric.de/cedric/xpensely-server:${{ steps.ver.outputs.minor }}
|
||||
tea.zendric.de/cedric/xpensely-server:${{ steps.ver.outputs.major }}
|
||||
cache-from: type=registry,ref=tea.zendric.de/cedric/xpensely-server:buildcache
|
||||
cache-to: type=registry,ref=tea.zendric.de/cedric/xpensely-server:buildcache,mode=max
|
||||
|
||||
@@ -6,6 +6,11 @@ target/
|
||||
!**/src/test/**/target/
|
||||
.env
|
||||
|
||||
# Local debugging (not for CI/prod)
|
||||
.env.local
|
||||
Dockerfile.local
|
||||
compose.local.yml
|
||||
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
Run it locally:
|
||||
|
||||
1. build the current state:
|
||||
mvn clean install or mvn clean install -DskipTests
|
||||
|
||||
2. docker it up and run it
|
||||
docker-compose -f dev-docker-compose.yml up --build
|
||||
+85
-1
@@ -1,6 +1,6 @@
|
||||
<mxfile host="65bd71144e">
|
||||
<diagram id="TZX9Tq6sZIlTxQ58HocZ" name="Page-1">
|
||||
<mxGraphModel dx="826" dy="472" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="850" pageHeight="1100" math="0" shadow="0">
|
||||
<mxGraphModel dx="989" dy="570" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="850" pageHeight="1100" math="0" shadow="0">
|
||||
<root>
|
||||
<mxCell id="0"/>
|
||||
<mxCell id="1" parent="0"/>
|
||||
@@ -193,6 +193,90 @@
|
||||
<mxCell id="73" value="<span style="font-size: 8px;">24.12.24 ; Expense ; 24,12 €</span>" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#76608a;fontColor=#ffffff;strokeColor=#432D57;" parent="1" vertex="1">
|
||||
<mxGeometry x="1399" y="226" width="120" height="20" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="86" style="edgeStyle=none;html=1;entryX=0;entryY=0.5;entryDx=0;entryDy=0;" edge="1" parent="1" source="74" target="79">
|
||||
<mxGeometry relative="1" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="74" value="List" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#60a917;fontColor=#ffffff;strokeColor=#2D7600;" vertex="1" parent="1">
|
||||
<mxGeometry x="1880" y="160" width="120" height="60" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="75" value="DB-Structure for Categories" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">
|
||||
<mxGeometry x="1930" y="35" width="100" height="30" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="78" style="edgeStyle=none;html=1;entryX=0;entryY=0.5;entryDx=0;entryDy=0;" edge="1" parent="1" source="76" target="77">
|
||||
<mxGeometry relative="1" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="76" value="List Entry" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="1">
|
||||
<mxGeometry x="1920" y="220" width="120" height="60" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="79" value="Available Categories" style="ellipse;whiteSpace=wrap;html=1;" vertex="1" parent="1">
|
||||
<mxGeometry x="2160" y="150" width="120" height="80" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="83" style="edgeStyle=none;html=1;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" edge="1" parent="1" source="81" target="79">
|
||||
<mxGeometry relative="1" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="81" value="Standard Categories" style="ellipse;whiteSpace=wrap;html=1;" vertex="1" parent="1">
|
||||
<mxGeometry x="2060" y="35" width="120" height="80" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="84" style="edgeStyle=none;html=1;entryX=0.5;entryY=0;entryDx=0;entryDy=0;" edge="1" parent="1" source="82" target="79">
|
||||
<mxGeometry relative="1" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="82" value="Custom Categories" style="ellipse;whiteSpace=wrap;html=1;" vertex="1" parent="1">
|
||||
<mxGeometry x="2270" y="35" width="120" height="80" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="91" style="edgeStyle=none;html=1;entryX=0;entryY=0.5;entryDx=0;entryDy=0;" edge="1" parent="1" source="87" target="90">
|
||||
<mxGeometry relative="1" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="87" value="List Entry" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="1">
|
||||
<mxGeometry x="1920" y="280" width="120" height="60" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="92" style="edgeStyle=none;html=1;entryX=0;entryY=0.5;entryDx=0;entryDy=0;" edge="1" parent="1" source="88" target="89">
|
||||
<mxGeometry relative="1" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="88" value="List Entry" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="1">
|
||||
<mxGeometry x="1920" y="340" width="120" height="60" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="89" value="Category" style="ellipse;whiteSpace=wrap;html=1;" vertex="1" parent="1">
|
||||
<mxGeometry x="2150" y="370" width="120" height="80" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="90" value="Category" style="ellipse;whiteSpace=wrap;html=1;" vertex="1" parent="1">
|
||||
<mxGeometry x="2150" y="315" width="120" height="80" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="94" value="<h1 style="font-size: 18px;">- list id</h1><div>- List &lt;String&gt;</div>" style="text;html=1;strokeColor=none;fillColor=none;spacing=5;spacingTop=-20;whiteSpace=wrap;overflow=hidden;rounded=0;fontSize=18;" vertex="1" parent="1">
|
||||
<mxGeometry x="2410" y="50" width="130" height="70" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="77" value="Category" style="ellipse;whiteSpace=wrap;html=1;" vertex="1" parent="1">
|
||||
<mxGeometry x="2150" y="260" width="120" height="80" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="97" value="" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="1">
|
||||
<mxGeometry x="1730" y="510" width="200" height="320" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="98" value="ExpenseList" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="1">
|
||||
<mxGeometry x="1770" y="520" width="120" height="20" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="100" value="+" style="rounded=1;whiteSpace=wrap;html=1;" vertex="1" parent="1">
|
||||
<mxGeometry x="1880" y="790" width="30" height="30" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="101" value="Categorie" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">
|
||||
<mxGeometry x="1770" y="480" width="120" height="30" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="102" value="<span style="font-size: 8px;">Amount : 24,12 €<br>Title: Expense<br>Date: 24.12.24<br>From: Jessi<br>Deviation: 0 €</span>" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#76608a;fontColor=#ffffff;strokeColor=#432D57;align=left;spacingLeft=12;" vertex="1" parent="1">
|
||||
<mxGeometry x="1745" y="550" width="170" height="170" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="105" value="<span style="font-size: 8px;">Essen</span>" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#1ba1e2;fontColor=#ffffff;strokeColor=#006EAF;align=left;spacingLeft=12;" vertex="1" parent="1">
|
||||
<mxGeometry x="1760" y="680" width="40" height="10" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="106" value="<span style="font-size: 8px;">Trinken</span>" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#a20025;fontColor=#ffffff;strokeColor=#6F0000;align=left;spacingLeft=12;" vertex="1" parent="1">
|
||||
<mxGeometry x="1800" y="680" width="40" height="10" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="107" value="<span style="font-size: 8px;">Auto</span>" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#d80073;fontColor=#ffffff;strokeColor=#A50040;align=left;spacingLeft=12;" vertex="1" parent="1">
|
||||
<mxGeometry x="1840" y="680" width="40" height="10" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="111" style="edgeStyle=none;html=1;entryX=0;entryY=0.5;entryDx=0;entryDy=0;fontSize=18;" edge="1" parent="1" source="108" target="74">
|
||||
<mxGeometry relative="1" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="108" value="Actor" style="shape=umlActor;verticalLabelPosition=bottom;verticalAlign=top;html=1;outlineConnect=0;fontSize=18;" vertex="1" parent="1">
|
||||
<mxGeometry x="1715" y="150" width="30" height="60" as="geometry"/>
|
||||
</mxCell>
|
||||
</root>
|
||||
</mxGraphModel>
|
||||
</diagram>
|
||||
|
||||
+1
-3
@@ -1,11 +1,9 @@
|
||||
services:
|
||||
xpensely-server:
|
||||
image: tea.zendric.de/cedric/xpensely-server:latest
|
||||
pull_policy: always
|
||||
restart: always
|
||||
environment:
|
||||
GOOGLE_CLIENT_ID: ${GOOGLE_CLIENT_ID}
|
||||
GOOGLE_CLIENT_SECRET: ${GOOGLE_CLIENT_SECRET}
|
||||
|
||||
DB_PORT: 5432
|
||||
DB_P_NAME: ${POSTGRES_DB}
|
||||
DB_USERNAME: ${POSTGRES_USER}
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
FROM eclipse-temurin:17-jdk
|
||||
FROM eclipse-temurin:21-jdk
|
||||
|
||||
COPY ./target/*.jar app.jar
|
||||
|
||||
|
||||
+37
-9
@@ -1,6 +1,6 @@
|
||||
# Xpensely Server — API Reference
|
||||
|
||||
> Last updated: 2026-05-09 · Branch: `feature/security-hardening`
|
||||
> Last updated: 2026-05-14 · Branch: `dev`
|
||||
|
||||
## Table of Contents
|
||||
1. [Overview](#1-overview)
|
||||
@@ -28,6 +28,7 @@ Xpensely Server is a Spring Boot REST API that manages shared expense lists for
|
||||
| Method | Path | Description |
|
||||
|--------|------|-------------|
|
||||
| GET | `/` | Health check — returns `"Welcome"` |
|
||||
| GET | `/api/version` | Returns build version and timestamp |
|
||||
| POST | `/api/users/createUser` | Register a new user |
|
||||
| GET | `/api/users/byName` | Look up a user by username |
|
||||
|
||||
@@ -98,6 +99,25 @@ Welcome
|
||||
|
||||
---
|
||||
|
||||
#### `GET /api/version`
|
||||
|
||||
Returns the application version and build timestamp. No authentication required.
|
||||
|
||||
**Response:** `200 OK`
|
||||
```json
|
||||
{
|
||||
"version": "0.0.1-SNAPSHOT",
|
||||
"builtAt": "2026-05-09T10:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Notes |
|
||||
|-------|------|-------|
|
||||
| `version` | String | Maven project version |
|
||||
| `builtAt` | String (ISO-8601) | UTC timestamp of the build |
|
||||
|
||||
---
|
||||
|
||||
### 4.2 Users
|
||||
|
||||
Base path: `/api/users`
|
||||
@@ -121,7 +141,7 @@ Base path: `/api/users`
|
||||
| `username` | String | Required. 3–30 chars. Pattern: `^[a-zA-Z0-9_.\-]+$` |
|
||||
| `googleId` | String | Required. Non-blank. Must match the JWT `sub` from Google. |
|
||||
|
||||
**Success response:** `200 OK` — returns the created [AppUser](#appuser) object.
|
||||
**Success response:** `201 Created` — returns the created [AppUser](#appuser) object.
|
||||
|
||||
**Error responses:**
|
||||
| Status | Condition |
|
||||
@@ -145,6 +165,7 @@ Base path: `/api/users`
|
||||
**Error responses:**
|
||||
| Status | Condition |
|
||||
|--------|-----------|
|
||||
| 403 | Authenticated user's ID does not match the requested `id` |
|
||||
| 404 | No user found for `id` |
|
||||
|
||||
---
|
||||
@@ -181,6 +202,7 @@ Base path: `/api/users`
|
||||
**Error responses:**
|
||||
| Status | Condition |
|
||||
|--------|-----------|
|
||||
| 403 | Requested Google ID does not match the authenticated user's Google ID |
|
||||
| 404 | No user found for that Google ID |
|
||||
|
||||
---
|
||||
@@ -194,11 +216,12 @@ Base path: `/api/users`
|
||||
|-------|------|----------|-------------|
|
||||
| `id` | Long | Yes | Database ID of the user to delete |
|
||||
|
||||
**Success response:** `200 OK` — returns the deleted [AppUser](#appuser).
|
||||
**Success response:** `200 OK` — returns a plain string: `"User deleted: <username>"`.
|
||||
|
||||
**Error responses:**
|
||||
| Status | Condition |
|
||||
|--------|-----------|
|
||||
| 403 | Authenticated user's ID does not match the requested `id` |
|
||||
| 404 | No user found for `id` |
|
||||
|
||||
---
|
||||
@@ -219,7 +242,11 @@ Returns all expense lists where the caller is the owner **or** has been shared t
|
||||
|
||||
**Request body:** None
|
||||
|
||||
**Success response:** `200 OK` — array of [ExpenseList](#expenselist).
|
||||
**Success responses:**
|
||||
| Status | Condition |
|
||||
|--------|-----------|
|
||||
| 200 OK | Returns array of [ExpenseList](#expenselist) |
|
||||
| 204 No Content | Caller has no expense lists |
|
||||
|
||||
```json
|
||||
[
|
||||
@@ -337,7 +364,7 @@ Only the **owner** may delete a list. Deleting a list cascades to all its expens
|
||||
| `date` | String (ISO-8601) | Required. Format: `YYYY-MM-DD`. |
|
||||
| `category` | String | Required. Non-blank category name. |
|
||||
|
||||
**Success response:** `200 OK` — returns the created [Expense](#expense).
|
||||
**Success response:** `201 Created` — returns the created [Expense](#expense).
|
||||
|
||||
**Error responses:**
|
||||
| Status | Condition |
|
||||
@@ -411,7 +438,7 @@ Caller must be a member of the list. Expense must belong to the specified list.
|
||||
|
||||
Caller must be a member of the list.
|
||||
|
||||
**Success response:** `200 OK` — returns the deleted [Expense](#expense).
|
||||
**Success response:** `204 No Content`
|
||||
|
||||
**Error responses:**
|
||||
| Status | Condition |
|
||||
@@ -465,13 +492,14 @@ Joins the caller to a shared expense list using an invite code.
|
||||
|-------|------|-------------|
|
||||
| `inviteCode` | String | Required. Exactly 6 characters. |
|
||||
|
||||
**Success response:** `200 OK` — returns the [ExpenseList](#expenselist) the caller joined.
|
||||
**Success response:** `200 OK` — returns a plain string: `"User added to the list"`.
|
||||
|
||||
**Error responses:**
|
||||
| Status | Condition |
|
||||
|--------|-----------|
|
||||
| 400 | Validation failure or invite code not found / expired |
|
||||
| 403 | Caller is already the owner of this list |
|
||||
| 400 | Validation failure or caller is already the owner of the list |
|
||||
| 404 | Invite code not found or expired |
|
||||
| 226 IM Used | List already has a second member (`sharedWith` is not null) |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
# Xpensely API — Manual test file (IntelliJ HTTP Client / VS Code REST Client)
|
||||
#
|
||||
# HOW TO GET A TOKEN:
|
||||
# 1. Run the Flutter dev app and sign in with Google
|
||||
# 2. Add a breakpoint or log in auth_interceptor.dart after _storage.read(key: 'id_token')
|
||||
# 3. Paste the token value below (valid for ~1 hour)
|
||||
#
|
||||
# Switch between dev and prod by changing @baseUrl.
|
||||
|
||||
@devBaseUrl = https://dev-xpensely.zendric.de/api
|
||||
@prodBaseUrl = https://xpensely.zendric.de/api
|
||||
@baseUrl = {{devBaseUrl}}
|
||||
|
||||
# Paste your Google ID token here:
|
||||
@token = PASTE_ID_TOKEN_HERE
|
||||
|
||||
# Your Google sub (from the JWT payload — decode at jwt.io):
|
||||
@googleId = PASTE_GOOGLE_SUB_HERE
|
||||
|
||||
|
||||
### ─── Health ────────────────────────────────────────────────────────────────
|
||||
|
||||
### Version (no auth required — should always return 200)
|
||||
GET {{baseUrl}}/version
|
||||
|
||||
### ─── Auth probe ─────────────────────────────────────────────────────────────
|
||||
|
||||
### Any protected endpoint without a token — expect 401
|
||||
GET {{baseUrl}}/users/byGoogleId?id={{googleId}}
|
||||
|
||||
### ─── Users ──────────────────────────────────────────────────────────────────
|
||||
|
||||
### Look up your account by Google ID — expect 200 if account exists, 403 if not
|
||||
GET {{baseUrl}}/users/byGoogleId?id={{googleId}}
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
###
|
||||
|
||||
### Get your account by DB id — replace {id} with your numeric user id
|
||||
GET {{baseUrl}}/users?id=1
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
###
|
||||
|
||||
### Get any user by username (no auth required)
|
||||
GET {{baseUrl}}/users/byName?username=testuser
|
||||
|
||||
###
|
||||
|
||||
### Create a new account (requires valid JWT — account must not exist yet)
|
||||
POST {{baseUrl}}/users/createUser
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
{
|
||||
"username": "myusername",
|
||||
"googleId": "{{googleId}}"
|
||||
}
|
||||
|
||||
###
|
||||
|
||||
### Delete your account — replace {id} with your numeric user id
|
||||
DELETE {{baseUrl}}/users?id=1
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### ─── Expense Lists ───────────────────────────────────────────────────────────
|
||||
|
||||
### Get all your expense lists — expect 200 (with data) or 204 (empty)
|
||||
GET {{baseUrl}}/expenselist/mine
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
###
|
||||
|
||||
### Get a specific expense list by id
|
||||
GET {{baseUrl}}/expenselist/byId?id=1
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
###
|
||||
|
||||
### Create a new expense list
|
||||
POST {{baseUrl}}/expenselist/create
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
{
|
||||
"name": "Groceries"
|
||||
}
|
||||
|
||||
###
|
||||
|
||||
### Add an expense to a list — replace {listId} in the URL
|
||||
POST {{baseUrl}}/expenselist/1/add
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
{
|
||||
"title": "Coffee",
|
||||
"owner": "myusername",
|
||||
"amount": 4.50,
|
||||
"date": "2026-05-15",
|
||||
"category": "Food"
|
||||
}
|
||||
|
||||
###
|
||||
|
||||
### Update an expense in a list
|
||||
PUT {{baseUrl}}/expenselist/1/update
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
{
|
||||
"id": 1,
|
||||
"title": "Coffee (updated)",
|
||||
"ownerName": "myusername",
|
||||
"amount": 5.00,
|
||||
"date": "2026-05-15",
|
||||
"category": "Food",
|
||||
"expenseListId": 1
|
||||
}
|
||||
|
||||
###
|
||||
|
||||
### Delete an expense from a list
|
||||
DELETE {{baseUrl}}/expenselist/1/delete?expenseId=1
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
###
|
||||
|
||||
### Generate an invite code for a list (you must be the owner)
|
||||
POST {{baseUrl}}/expenselist/1/invite
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
###
|
||||
|
||||
### Accept an invite
|
||||
POST {{baseUrl}}/expenselist/accept-invite
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
{
|
||||
"inviteCode": "PASTE_6_CHAR_CODE_HERE"
|
||||
}
|
||||
|
||||
###
|
||||
|
||||
### Delete an expense list (you must be the owner)
|
||||
DELETE {{baseUrl}}/expenselist/1
|
||||
Authorization: Bearer {{token}}
|
||||
@@ -6,11 +6,11 @@
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>4.0.6</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
<relativePath/>
|
||||
</parent>
|
||||
<groupId>de.zendric.app</groupId>
|
||||
<artifactId>XpenselyServer</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<version>1.2.0</version>
|
||||
<name>XpenselyServer</name>
|
||||
<description>XpenselyServer used to handle the Xpensely App</description>
|
||||
<url/>
|
||||
@@ -52,10 +52,6 @@
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-oauth2-client</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
@@ -128,6 +124,13 @@
|
||||
</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>build-info</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
@@ -9,6 +9,7 @@ import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import de.zendric.app.xpensely_server.model.AppUser;
|
||||
import de.zendric.app.xpensely_server.model.AppUserCreateRequest;
|
||||
import de.zendric.app.xpensely_server.model.UsernameUpdateRequest;
|
||||
import de.zendric.app.xpensely_server.security.AuthenticatedUserResolver;
|
||||
import de.zendric.app.xpensely_server.services.UserService;
|
||||
|
||||
@@ -31,11 +32,6 @@ public class AppUserController {
|
||||
return ResponseEntity.ok(userService.getUser(id));
|
||||
}
|
||||
|
||||
@GetMapping("/byName")
|
||||
public AppUser getUserByName(@RequestParam String username) {
|
||||
return userService.getUserByName(username);
|
||||
}
|
||||
|
||||
@GetMapping("/byGoogleId")
|
||||
public ResponseEntity<AppUser> getUserByGoogleId(@RequestParam String id, Authentication authentication) {
|
||||
AppUser self = authenticatedUserResolver.resolveCurrentUser(authentication);
|
||||
@@ -51,6 +47,14 @@ public class AppUserController {
|
||||
return new ResponseEntity<>(nUser, HttpStatus.CREATED);
|
||||
}
|
||||
|
||||
@PutMapping("/username")
|
||||
public ResponseEntity<AppUser> updateUsername(@RequestBody @Valid UsernameUpdateRequest request,
|
||||
Authentication authentication) {
|
||||
AppUser self = authenticatedUserResolver.resolveCurrentUser(authentication);
|
||||
AppUser updated = userService.updateUsername(self.getId(), request.getUsername());
|
||||
return ResponseEntity.ok(updated);
|
||||
}
|
||||
|
||||
@DeleteMapping
|
||||
public ResponseEntity<String> deleteUser(@RequestParam Long id, Authentication authentication) {
|
||||
AppUser self = authenticatedUserResolver.resolveCurrentUser(authentication);
|
||||
|
||||
+68
-10
@@ -14,10 +14,12 @@ import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import de.zendric.app.xpensely_server.model.*;
|
||||
import de.zendric.app.xpensely_server.model.DTO.HistoryPageDto;
|
||||
import de.zendric.app.xpensely_server.model.DTO.RecentHistoryEntryDto;
|
||||
import de.zendric.app.xpensely_server.security.AuthenticatedUserResolver;
|
||||
import de.zendric.app.xpensely_server.services.CategoryService;
|
||||
import de.zendric.app.xpensely_server.services.ExpenseListService;
|
||||
import de.zendric.app.xpensely_server.services.UserService;
|
||||
import de.zendric.app.xpensely_server.services.HistoryService;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/expenselist")
|
||||
@@ -26,16 +28,17 @@ public class ExpenseListController {
|
||||
private static final Logger log = LoggerFactory.getLogger(ExpenseListController.class);
|
||||
|
||||
private final ExpenseListService expenseListService;
|
||||
private final UserService userService;
|
||||
private final CategoryService categoryService;
|
||||
private final AuthenticatedUserResolver authenticatedUserResolver;
|
||||
private final HistoryService historyService;
|
||||
|
||||
public ExpenseListController(ExpenseListService expenseListService, UserService userService,
|
||||
CategoryService categoryService, AuthenticatedUserResolver authenticatedUserResolver) {
|
||||
public ExpenseListController(ExpenseListService expenseListService,
|
||||
CategoryService categoryService, AuthenticatedUserResolver authenticatedUserResolver,
|
||||
HistoryService historyService) {
|
||||
this.expenseListService = expenseListService;
|
||||
this.userService = userService;
|
||||
this.categoryService = categoryService;
|
||||
this.authenticatedUserResolver = authenticatedUserResolver;
|
||||
this.historyService = historyService;
|
||||
}
|
||||
|
||||
@GetMapping("/mine")
|
||||
@@ -83,6 +86,18 @@ public class ExpenseListController {
|
||||
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
|
||||
}
|
||||
|
||||
@PutMapping("/{id}/rename")
|
||||
public ResponseEntity<ExpenseList> rename(@PathVariable("id") Long id,
|
||||
@RequestBody @Valid CreateExpenseListRequest request, Authentication authentication) {
|
||||
AppUser user = authenticatedUserResolver.resolveCurrentUser(authentication);
|
||||
Optional<ExpenseList> listOpt = expenseListService.findById(id);
|
||||
if (listOpt.isEmpty())
|
||||
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
||||
assertOwner(user, listOpt.get());
|
||||
ExpenseList renamed = expenseListService.renameList(id, request.getName());
|
||||
return new ResponseEntity<>(renamed, HttpStatus.OK);
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/add")
|
||||
public ResponseEntity<Expense> addExpenseToList(
|
||||
@PathVariable("id") Long expenseListId,
|
||||
@@ -93,9 +108,9 @@ public class ExpenseListController {
|
||||
if (listOpt.isEmpty())
|
||||
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
||||
assertMember(user, listOpt.get());
|
||||
AppUser expenseOwner = userService.getUserByName(expenseInput.getOwner());
|
||||
AppUser expenseOwner = resolveListMember(listOpt.get(), expenseInput.getOwner());
|
||||
Expense expense = expenseInput.convertToExpense(expenseOwner.getId());
|
||||
Expense addedExpense = expenseListService.addExpenseToList(expenseListId, expense);
|
||||
Expense addedExpense = expenseListService.addExpenseToList(expenseListId, expense, user);
|
||||
return new ResponseEntity<>(addedExpense, HttpStatus.CREATED);
|
||||
}
|
||||
|
||||
@@ -109,9 +124,9 @@ public class ExpenseListController {
|
||||
if (expenseListOpt.isEmpty())
|
||||
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
||||
assertMember(user, expenseListOpt.get());
|
||||
AppUser expenseOwner = userService.getUserByName(expenseChangeRequest.getOwnerName());
|
||||
AppUser expenseOwner = resolveListMember(expenseListOpt.get(), expenseChangeRequest.getOwnerName());
|
||||
Expense expense = expenseChangeRequest.convertToExpense(expenseOwner.getId(), expenseListOpt.get());
|
||||
Expense updatedExpense = expenseListService.updateExpense(expenseListId, expense);
|
||||
Expense updatedExpense = expenseListService.updateExpense(expenseListId, expense, user);
|
||||
return new ResponseEntity<>(updatedExpense, HttpStatus.OK);
|
||||
}
|
||||
|
||||
@@ -125,7 +140,7 @@ public class ExpenseListController {
|
||||
if (listOpt.isEmpty())
|
||||
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
||||
assertMember(user, listOpt.get());
|
||||
expenseListService.deleteExpenseFromList(expenseListId, expenseId);
|
||||
expenseListService.deleteExpenseFromList(expenseListId, expenseId, user);
|
||||
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
|
||||
}
|
||||
|
||||
@@ -156,11 +171,38 @@ public class ExpenseListController {
|
||||
if (list.getOwner().getId().equals(authenticatedUser.getId())) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("You cannot join your own list");
|
||||
}
|
||||
if (list.getOwner().getUsername().equals(authenticatedUser.getUsername())) {
|
||||
return ResponseEntity.status(HttpStatus.CONFLICT).body(
|
||||
"You and the list owner both use the username \"" + authenticatedUser.getUsername()
|
||||
+ "\". Please change your username before joining this list.");
|
||||
}
|
||||
list.setSharedWith(authenticatedUser);
|
||||
expenseListService.save(list);
|
||||
return ResponseEntity.ok("User added to the list");
|
||||
}
|
||||
|
||||
@GetMapping("/{id}/history")
|
||||
public ResponseEntity<HistoryPageDto> getHistory(
|
||||
@PathVariable("id") Long id,
|
||||
@RequestParam(defaultValue = "0") int page,
|
||||
@RequestParam(defaultValue = "30") int size,
|
||||
Authentication authentication) {
|
||||
AppUser user = authenticatedUserResolver.resolveCurrentUser(authentication);
|
||||
Optional<ExpenseList> listOpt = expenseListService.findById(id);
|
||||
if (listOpt.isEmpty())
|
||||
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
||||
assertMember(user, listOpt.get());
|
||||
return ResponseEntity.ok(historyService.getHistory(id, page, size));
|
||||
}
|
||||
|
||||
@GetMapping("/history/recent")
|
||||
public ResponseEntity<List<RecentHistoryEntryDto>> getRecentHistory(
|
||||
@RequestParam(defaultValue = "4") int limit,
|
||||
Authentication authentication) {
|
||||
AppUser user = authenticatedUserResolver.resolveCurrentUser(authentication);
|
||||
return ResponseEntity.ok(historyService.getRecentForUser(user, limit));
|
||||
}
|
||||
|
||||
private void assertOwner(AppUser authenticated, ExpenseList list) {
|
||||
if (!list.getOwner().getId().equals(authenticated.getId()))
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN);
|
||||
@@ -173,4 +215,20 @@ public class ExpenseListController {
|
||||
if (!isOwner && !isShared)
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves an expense owner by username among the list's members. Usernames are
|
||||
* not globally unique, so the owner must be one of this list's (at most two)
|
||||
* members — never a global lookup.
|
||||
*/
|
||||
private AppUser resolveListMember(ExpenseList list, String username) {
|
||||
if (list.getOwner() != null && list.getOwner().getUsername().equals(username)) {
|
||||
return list.getOwner();
|
||||
}
|
||||
if (list.getSharedWith() != null && list.getSharedWith().getUsername().equals(username)) {
|
||||
return list.getSharedWith();
|
||||
}
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST,
|
||||
"Expense owner must be a member of this list");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package de.zendric.app.xpensely_server.controller;
|
||||
|
||||
import de.zendric.app.xpensely_server.model.Exception.GoogleAccountAlreadyRegisteredException;
|
||||
import de.zendric.app.xpensely_server.model.Exception.ResourceNotFoundException;
|
||||
import de.zendric.app.xpensely_server.model.Exception.UsernameAlreadyExistsException;
|
||||
import org.slf4j.Logger;
|
||||
@@ -47,6 +48,13 @@ public class GlobalExceptionHandler {
|
||||
.body(Map.of("error", ex.getMessage()));
|
||||
}
|
||||
|
||||
@ExceptionHandler(GoogleAccountAlreadyRegisteredException.class)
|
||||
public ResponseEntity<Map<String, String>> handleGoogleAccountConflict(
|
||||
GoogleAccountAlreadyRegisteredException ex) {
|
||||
return ResponseEntity.status(HttpStatus.CONFLICT)
|
||||
.body(Map.of("error", ex.getMessage()));
|
||||
}
|
||||
|
||||
@ExceptionHandler(ResponseStatusException.class)
|
||||
public ResponseEntity<Map<String, String>> handleResponseStatus(ResponseStatusException ex) {
|
||||
return ResponseEntity.status(ex.getStatusCode())
|
||||
|
||||
@@ -1,13 +1,30 @@
|
||||
package de.zendric.app.xpensely_server.controller;
|
||||
|
||||
import org.springframework.boot.info.BuildProperties;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
class HomeController {
|
||||
|
||||
private final BuildProperties buildProperties;
|
||||
|
||||
HomeController(BuildProperties buildProperties) {
|
||||
this.buildProperties = buildProperties;
|
||||
}
|
||||
|
||||
@GetMapping("/")
|
||||
public String getAll() {
|
||||
return "Welcome";
|
||||
}
|
||||
|
||||
@GetMapping("/api/version")
|
||||
public Map<String, String> version() {
|
||||
return Map.of(
|
||||
"version", buildProperties.getVersion(),
|
||||
"builtAt", buildProperties.getTime().toString()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -26,9 +26,10 @@ public class AppUser {
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "username", nullable = false, unique = true)
|
||||
@Column(name = "username", nullable = false)
|
||||
private String username;
|
||||
|
||||
@Column(name = "google_id", unique = true)
|
||||
@JsonIgnore
|
||||
private String googleId;
|
||||
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package de.zendric.app.xpensely_server.model.DTO;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
import de.zendric.app.xpensely_server.model.FieldChange;
|
||||
|
||||
public record HistoryEntryDto(
|
||||
String type,
|
||||
String actorUsername,
|
||||
String expenseTitle,
|
||||
LocalDateTime timestamp,
|
||||
List<FieldChange> changes) {
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package de.zendric.app.xpensely_server.model.DTO;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record HistoryPageDto(List<HistoryEntryDto> entries, boolean hasMore) {
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package de.zendric.app.xpensely_server.model.DTO;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public record RecentHistoryEntryDto(
|
||||
String type,
|
||||
String actorUsername,
|
||||
String expenseTitle,
|
||||
LocalDateTime timestamp,
|
||||
Long listId,
|
||||
String listName) {
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package de.zendric.app.xpensely_server.model.Exception;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
@ResponseStatus(HttpStatus.CONFLICT)
|
||||
public class GoogleAccountAlreadyRegisteredException extends RuntimeException {
|
||||
public GoogleAccountAlreadyRegisteredException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package de.zendric.app.xpensely_server.model;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonBackReference;
|
||||
|
||||
@@ -36,6 +37,7 @@ public class Expense {
|
||||
private Double otherPersonAmount;
|
||||
private String category;
|
||||
private LocalDate date;
|
||||
private LocalDateTime lastModified;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "expense_list_id", nullable = false)
|
||||
|
||||
@@ -24,8 +24,10 @@ public class ExpenseChangeRequest {
|
||||
@NotBlank(message = "Owner name is required")
|
||||
private String ownerName;
|
||||
|
||||
// Same bounds as ExpenseInput: Quick Add creates stub expenses with amount 0
|
||||
// and no category, and those stubs must remain editable.
|
||||
@NotNull(message = "Amount is required")
|
||||
@DecimalMin(value = "0.01", message = "Amount must be greater than zero")
|
||||
@DecimalMin(value = "0.00", message = "Amount must not be negative")
|
||||
private Double amount;
|
||||
|
||||
private Double personalUseAmount;
|
||||
@@ -34,7 +36,6 @@ public class ExpenseChangeRequest {
|
||||
@NotNull(message = "Date is required")
|
||||
private LocalDate date;
|
||||
|
||||
@NotBlank(message = "Category is required")
|
||||
private String category;
|
||||
|
||||
public Expense convertToExpense(Long userId, ExpenseList expenseList) {
|
||||
@@ -51,7 +52,9 @@ public class ExpenseChangeRequest {
|
||||
expense.setId(id);
|
||||
expense.setOwner(appUser);
|
||||
expense.setTitle(title);
|
||||
expense.setCategory(category);
|
||||
// The edit dialog sends "" for a missing category; store null so the
|
||||
// stub state stays uniform and history diffs don't report null -> "".
|
||||
expense.setCategory(category == null || category.isBlank() ? null : category);
|
||||
|
||||
return expense;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package de.zendric.app.xpensely_server.model;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.EnumType;
|
||||
import jakarta.persistence.Enumerated;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Index;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@Entity
|
||||
@Table(name = "expense_history_entry", indexes = @Index(name = "idx_history_list_timestamp", columnList = "expense_list_id, timestamp DESC"))
|
||||
public class ExpenseHistoryEntry {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "expense_list_id", nullable = false)
|
||||
private ExpenseList expenseList;
|
||||
|
||||
/** Plain column on purpose — no FK, so history survives expense deletion. */
|
||||
private Long expenseId;
|
||||
|
||||
/** Denormalized so entries for deleted expenses still render. */
|
||||
private String expenseTitle;
|
||||
|
||||
@ManyToOne
|
||||
private AppUser actor;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
private HistoryEntryType type;
|
||||
|
||||
private LocalDateTime timestamp;
|
||||
|
||||
/** JSON array of FieldChange; null for CREATED/DELETED. */
|
||||
@Column(columnDefinition = "TEXT")
|
||||
private String changes;
|
||||
}
|
||||
@@ -27,7 +27,7 @@ public class ExpenseInput {
|
||||
private String owner;
|
||||
|
||||
@NotNull(message = "Amount is required")
|
||||
@DecimalMin(value = "0.01", message = "Amount must be greater than zero")
|
||||
@DecimalMin(value = "0.00", message = "Amount must not be negative")
|
||||
private Double amount;
|
||||
|
||||
private Double personalUseAmount;
|
||||
@@ -36,7 +36,7 @@ public class ExpenseInput {
|
||||
@NotNull(message = "Date is required")
|
||||
private LocalDate date;
|
||||
|
||||
@NotBlank(message = "Category is required")
|
||||
// Optional: Quick Add creates stub expenses without a category, to be filled in later.
|
||||
private String category;
|
||||
|
||||
private ExpenseList expenseList;
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
package de.zendric.app.xpensely_server.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
public record FieldChange(
|
||||
String field,
|
||||
@JsonProperty("old") String oldValue,
|
||||
@JsonProperty("new") String newValue) {
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package de.zendric.app.xpensely_server.model;
|
||||
|
||||
public enum HistoryEntryType {
|
||||
CREATED, UPDATED, DELETED
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package de.zendric.app.xpensely_server.model;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class UsernameUpdateRequest {
|
||||
|
||||
@NotBlank(message = "Username is required")
|
||||
@Size(min = 3, max = 30, message = "Username must be between 3 and 30 characters")
|
||||
@Pattern(regexp = "^[a-zA-Z0-9_.\\-]+$", message = "Username may only contain letters, digits, underscores, dots, and hyphens")
|
||||
private String username;
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package de.zendric.app.xpensely_server.preparation;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import de.zendric.app.xpensely_server.model.Expense;
|
||||
import de.zendric.app.xpensely_server.model.ExpenseHistoryEntry;
|
||||
import de.zendric.app.xpensely_server.model.HistoryEntryType;
|
||||
import de.zendric.app.xpensely_server.repo.ExpenseHistoryRepository;
|
||||
import de.zendric.app.xpensely_server.repo.ExpenseRepository;
|
||||
|
||||
/**
|
||||
* One-time (idempotent) backfill for the history feature: fills
|
||||
* Expense.lastModified from the expense date and creates a synthetic CREATED
|
||||
* history entry for every expense that predates change logging. Both steps
|
||||
* are no-ops on every startup after the first.
|
||||
*/
|
||||
@Component
|
||||
public class HistoryBackfillRunner implements CommandLineRunner {
|
||||
|
||||
private final ExpenseRepository expenseRepository;
|
||||
private final ExpenseHistoryRepository historyRepository;
|
||||
|
||||
public HistoryBackfillRunner(ExpenseRepository expenseRepository,
|
||||
ExpenseHistoryRepository historyRepository) {
|
||||
this.expenseRepository = expenseRepository;
|
||||
this.historyRepository = historyRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void run(String... args) {
|
||||
for (Expense expense : expenseRepository.findByLastModifiedIsNull()) {
|
||||
expense.setLastModified(startOfDayOrNow(expense));
|
||||
expenseRepository.save(expense);
|
||||
}
|
||||
|
||||
Set<Long> loggedExpenseIds = new HashSet<>(historyRepository.findAllExpenseIds());
|
||||
for (Expense expense : expenseRepository.findAll()) {
|
||||
if (loggedExpenseIds.contains(expense.getId()))
|
||||
continue;
|
||||
ExpenseHistoryEntry entry = new ExpenseHistoryEntry();
|
||||
entry.setExpenseList(expense.getExpenseList());
|
||||
entry.setExpenseId(expense.getId());
|
||||
entry.setExpenseTitle(expense.getTitle());
|
||||
entry.setActor(expense.getOwner());
|
||||
entry.setType(HistoryEntryType.CREATED);
|
||||
entry.setTimestamp(startOfDayOrNow(expense));
|
||||
historyRepository.save(entry);
|
||||
}
|
||||
}
|
||||
|
||||
private LocalDateTime startOfDayOrNow(Expense expense) {
|
||||
return expense.getDate() == null ? LocalDateTime.now() : expense.getDate().atStartOfDay();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package de.zendric.app.xpensely_server.repo;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
|
||||
import de.zendric.app.xpensely_server.model.ExpenseHistoryEntry;
|
||||
|
||||
public interface ExpenseHistoryRepository extends JpaRepository<ExpenseHistoryEntry, Long> {
|
||||
|
||||
Page<ExpenseHistoryEntry> findByExpenseListIdOrderByTimestampDescIdDesc(Long expenseListId, Pageable pageable);
|
||||
|
||||
Page<ExpenseHistoryEntry> findByExpenseListOwnerIdOrExpenseListSharedWithIdOrderByTimestampDescIdDesc(
|
||||
Long ownerId, Long sharedWithId, Pageable pageable);
|
||||
|
||||
@Query("select h.expenseId from ExpenseHistoryEntry h")
|
||||
List<Long> findAllExpenseIds();
|
||||
|
||||
void deleteByExpenseListId(Long expenseListId);
|
||||
}
|
||||
@@ -10,4 +10,6 @@ import de.zendric.app.xpensely_server.model.Expense;
|
||||
@Repository
|
||||
public interface ExpenseRepository extends JpaRepository<Expense, Long> {
|
||||
List<Expense> findAllByOrderByDateAsc();
|
||||
|
||||
List<Expense> findByLastModifiedIsNull();
|
||||
}
|
||||
|
||||
@@ -14,4 +14,6 @@ public interface UserRepository extends JpaRepository<AppUser, Long> {
|
||||
Optional<AppUser> findByGoogleId(String id);
|
||||
|
||||
Boolean existsByUsername(String username);
|
||||
|
||||
Boolean existsByGoogleId(String googleId);
|
||||
}
|
||||
|
||||
+3
-6
@@ -1,6 +1,7 @@
|
||||
package de.zendric.app.xpensely_server.security;
|
||||
|
||||
import de.zendric.app.xpensely_server.model.AppUser;
|
||||
import de.zendric.app.xpensely_server.model.Exception.ResourceNotFoundException;
|
||||
import de.zendric.app.xpensely_server.services.UserService;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.Authentication;
|
||||
@@ -24,12 +25,8 @@ public class AuthenticatedUserResolver {
|
||||
Jwt jwt = (Jwt) authentication.getPrincipal();
|
||||
String googleId = jwt.getSubject();
|
||||
try {
|
||||
AppUser user = userService.getUserByGoogleId(googleId);
|
||||
if (user == null) {
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "User not registered");
|
||||
}
|
||||
return user;
|
||||
} catch (IllegalArgumentException e) {
|
||||
return userService.getUserByGoogleId(googleId);
|
||||
} catch (IllegalArgumentException | ResourceNotFoundException e) {
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "User not registered");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,10 +28,10 @@ public class SecurityConfig {
|
||||
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers("/api/version").permitAll()
|
||||
.anyRequest().authenticated())
|
||||
.oauth2ResourceServer(oauth2 -> oauth2
|
||||
.jwt(Customizer.withDefaults()))
|
||||
.oauth2Login(Customizer.withDefaults())
|
||||
.addFilterAfter(new RateLimitFilter(), BearerTokenAuthenticationFilter.class)
|
||||
.csrf(csrf -> csrf.disable());
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import java.util.UUID;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import de.zendric.app.xpensely_server.model.AppUser;
|
||||
import de.zendric.app.xpensely_server.model.Expense;
|
||||
import de.zendric.app.xpensely_server.model.ExpenseList;
|
||||
import de.zendric.app.xpensely_server.model.Exception.ResourceNotFoundException;
|
||||
@@ -23,12 +24,14 @@ public class ExpenseListService {
|
||||
private final ExpenseListRepository repository;
|
||||
private final ExpenseRepository expenseRepository;
|
||||
private final XpenselyCustomCategoryRepository customCategoryRepository;
|
||||
private final HistoryService historyService;
|
||||
|
||||
public ExpenseListService(ExpenseListRepository repository, ExpenseRepository expenseRepository,
|
||||
XpenselyCustomCategoryRepository customCategoryRepository) {
|
||||
XpenselyCustomCategoryRepository customCategoryRepository, HistoryService historyService) {
|
||||
this.repository = repository;
|
||||
this.expenseRepository = expenseRepository;
|
||||
this.customCategoryRepository = customCategoryRepository;
|
||||
this.historyService = historyService;
|
||||
}
|
||||
|
||||
public ExpenseList createList(ExpenseList list) {
|
||||
@@ -36,9 +39,17 @@ public class ExpenseListService {
|
||||
}
|
||||
|
||||
public void deleteById(Long id) {
|
||||
historyService.deleteForList(id);
|
||||
repository.deleteById(id);
|
||||
}
|
||||
|
||||
public ExpenseList renameList(Long id, String newName) {
|
||||
ExpenseList list = repository.findById(id)
|
||||
.orElseThrow(() -> new ResourceNotFoundException("ExpenseList not found with id: " + id));
|
||||
list.setName(newName);
|
||||
return repository.save(list);
|
||||
}
|
||||
|
||||
public Optional<ExpenseList> findById(Long id) {
|
||||
return repository.findById(id);
|
||||
}
|
||||
@@ -55,15 +66,17 @@ public class ExpenseListService {
|
||||
return repository.findByOwnerUsernameOrSharedWithUsername(username);
|
||||
}
|
||||
|
||||
public Expense addExpenseToList(Long expenseListId, Expense expense) {
|
||||
public Expense addExpenseToList(Long expenseListId, Expense expense, AppUser actor) {
|
||||
ExpenseList expenseList = repository.findById(expenseListId)
|
||||
.orElseThrow(() -> new ResourceNotFoundException("ExpenseList not found with id: " + expenseListId));
|
||||
expense.setLastModified(LocalDateTime.now());
|
||||
expenseList.addExpense(expense);
|
||||
repository.save(expenseList);
|
||||
historyService.recordCreated(expenseList, expense, actor);
|
||||
return expense;
|
||||
}
|
||||
|
||||
public void deleteExpenseFromList(Long expenseListId, Long expenseId) {
|
||||
public void deleteExpenseFromList(Long expenseListId, Long expenseId, AppUser actor) {
|
||||
ExpenseList expenseList = repository.findById(expenseListId)
|
||||
.orElseThrow(() -> new ResourceNotFoundException("ExpenseList not found with id: " + expenseListId));
|
||||
Expense expenseToRemove = null;
|
||||
@@ -73,11 +86,11 @@ public class ExpenseListService {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (expenseToRemove != null) {
|
||||
expenseList.removeExpense(expenseToRemove);
|
||||
} else {
|
||||
if (expenseToRemove == null) {
|
||||
throw new ResourceNotFoundException("Expense not found with id: " + expenseId);
|
||||
}
|
||||
historyService.recordDeleted(expenseList, expenseToRemove, actor);
|
||||
expenseList.removeExpense(expenseToRemove);
|
||||
repository.save(expenseList);
|
||||
}
|
||||
|
||||
@@ -103,7 +116,7 @@ public class ExpenseListService {
|
||||
return repository.findByInviteCode(inviteCode);
|
||||
}
|
||||
|
||||
public Expense updateExpense(Long expenseListId, Expense updatedExpense) {
|
||||
public Expense updateExpense(Long expenseListId, Expense updatedExpense, AppUser actor) {
|
||||
ExpenseList expenseList = repository.findById(expenseListId)
|
||||
.orElseThrow(() -> new ResourceNotFoundException("ExpenseList not found with id: " + expenseListId));
|
||||
|
||||
@@ -114,6 +127,9 @@ public class ExpenseListService {
|
||||
|
||||
Expense existingExpense = expenseRepository.findById(updatedExpense.getId())
|
||||
.orElseThrow(() -> new ResourceNotFoundException("Expense not found with id: " + updatedExpense.getId()));
|
||||
|
||||
Expense before = snapshot(existingExpense);
|
||||
|
||||
existingExpense.setTitle(updatedExpense.getTitle());
|
||||
existingExpense.setAmount(updatedExpense.getAmount());
|
||||
existingExpense.setPersonalUseAmount(updatedExpense.getPersonalUseAmount());
|
||||
@@ -121,8 +137,25 @@ public class ExpenseListService {
|
||||
existingExpense.setDate(updatedExpense.getDate());
|
||||
existingExpense.setOwner(updatedExpense.getOwner());
|
||||
existingExpense.setCategory(updatedExpense.getCategory());
|
||||
existingExpense.setLastModified(LocalDateTime.now());
|
||||
|
||||
return expenseRepository.save(existingExpense);
|
||||
Expense saved = expenseRepository.save(existingExpense);
|
||||
historyService.recordUpdated(expenseList, before, saved, actor);
|
||||
return saved;
|
||||
}
|
||||
|
||||
/** Detached copy of the mutable fields, taken before applying an update. */
|
||||
private Expense snapshot(Expense e) {
|
||||
Expense copy = new Expense();
|
||||
copy.setId(e.getId());
|
||||
copy.setTitle(e.getTitle());
|
||||
copy.setAmount(e.getAmount());
|
||||
copy.setPersonalUseAmount(e.getPersonalUseAmount());
|
||||
copy.setOtherPersonAmount(e.getOtherPersonAmount());
|
||||
copy.setCategory(e.getCategory());
|
||||
copy.setDate(e.getDate());
|
||||
copy.setOwner(e.getOwner());
|
||||
return copy;
|
||||
}
|
||||
|
||||
// TODO implement API for this
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
package de.zendric.app.xpensely_server.services;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import tools.jackson.core.JacksonException;
|
||||
import tools.jackson.core.type.TypeReference;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
|
||||
import de.zendric.app.xpensely_server.model.AppUser;
|
||||
import de.zendric.app.xpensely_server.model.DTO.HistoryEntryDto;
|
||||
import de.zendric.app.xpensely_server.model.DTO.HistoryPageDto;
|
||||
import de.zendric.app.xpensely_server.model.DTO.RecentHistoryEntryDto;
|
||||
import de.zendric.app.xpensely_server.model.Expense;
|
||||
import de.zendric.app.xpensely_server.model.ExpenseHistoryEntry;
|
||||
import de.zendric.app.xpensely_server.model.ExpenseList;
|
||||
import de.zendric.app.xpensely_server.model.FieldChange;
|
||||
import de.zendric.app.xpensely_server.model.HistoryEntryType;
|
||||
import de.zendric.app.xpensely_server.repo.ExpenseHistoryRepository;
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
public class HistoryService {
|
||||
|
||||
private final ExpenseHistoryRepository historyRepository;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public HistoryService(ExpenseHistoryRepository historyRepository, ObjectMapper objectMapper) {
|
||||
this.historyRepository = historyRepository;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
public void recordCreated(ExpenseList list, Expense expense, AppUser actor) {
|
||||
historyRepository.save(baseEntry(list, expense, actor, HistoryEntryType.CREATED));
|
||||
}
|
||||
|
||||
public void recordUpdated(ExpenseList list, Expense before, Expense after, AppUser actor) {
|
||||
List<FieldChange> changes = diff(before, after);
|
||||
if (changes.isEmpty())
|
||||
return;
|
||||
ExpenseHistoryEntry entry = baseEntry(list, after, actor, HistoryEntryType.UPDATED);
|
||||
try {
|
||||
entry.setChanges(objectMapper.writeValueAsString(changes));
|
||||
} catch (JacksonException e) {
|
||||
throw new IllegalStateException("Failed to serialize history changes", e);
|
||||
}
|
||||
historyRepository.save(entry);
|
||||
}
|
||||
|
||||
public void recordDeleted(ExpenseList list, Expense expense, AppUser actor) {
|
||||
historyRepository.save(baseEntry(list, expense, actor, HistoryEntryType.DELETED));
|
||||
}
|
||||
|
||||
public void deleteForList(Long listId) {
|
||||
historyRepository.deleteByExpenseListId(listId);
|
||||
}
|
||||
|
||||
public List<FieldChange> diff(Expense before, Expense after) {
|
||||
List<FieldChange> changes = new ArrayList<>();
|
||||
addIfChanged(changes, "title", before.getTitle(), after.getTitle());
|
||||
addIfChanged(changes, "amount", before.getAmount(), after.getAmount());
|
||||
addIfChanged(changes, "personalUseAmount", before.getPersonalUseAmount(), after.getPersonalUseAmount());
|
||||
addIfChanged(changes, "otherPersonAmount", before.getOtherPersonAmount(), after.getOtherPersonAmount());
|
||||
addIfChanged(changes, "category", before.getCategory(), after.getCategory());
|
||||
addIfChanged(changes, "date", before.getDate(), after.getDate());
|
||||
addIfChanged(changes, "owner",
|
||||
before.getOwner() == null ? null : before.getOwner().getUsername(),
|
||||
after.getOwner() == null ? null : after.getOwner().getUsername());
|
||||
return changes;
|
||||
}
|
||||
|
||||
private ExpenseHistoryEntry baseEntry(ExpenseList list, Expense expense, AppUser actor, HistoryEntryType type) {
|
||||
ExpenseHistoryEntry entry = new ExpenseHistoryEntry();
|
||||
entry.setExpenseList(list);
|
||||
entry.setExpenseId(expense.getId());
|
||||
entry.setExpenseTitle(expense.getTitle());
|
||||
entry.setActor(actor);
|
||||
entry.setType(type);
|
||||
entry.setTimestamp(LocalDateTime.now());
|
||||
return entry;
|
||||
}
|
||||
|
||||
private void addIfChanged(List<FieldChange> changes, String field, Object oldVal, Object newVal) {
|
||||
if (!Objects.equals(oldVal, newVal)) {
|
||||
changes.add(new FieldChange(field,
|
||||
oldVal == null ? null : String.valueOf(oldVal),
|
||||
newVal == null ? null : String.valueOf(newVal)));
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public HistoryPageDto getHistory(Long listId, int page, int size) {
|
||||
int cappedSize = Math.min(Math.max(size, 1), 100);
|
||||
Page<ExpenseHistoryEntry> result = historyRepository
|
||||
.findByExpenseListIdOrderByTimestampDescIdDesc(listId,
|
||||
PageRequest.of(Math.max(page, 0), cappedSize));
|
||||
List<HistoryEntryDto> entries = result.getContent().stream().map(this::toDto).toList();
|
||||
return new HistoryPageDto(entries, result.hasNext());
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<RecentHistoryEntryDto> getRecentForUser(AppUser user, int limit) {
|
||||
int cappedLimit = Math.min(Math.max(limit, 1), 20);
|
||||
Page<ExpenseHistoryEntry> result = historyRepository
|
||||
.findByExpenseListOwnerIdOrExpenseListSharedWithIdOrderByTimestampDescIdDesc(
|
||||
user.getId(), user.getId(), PageRequest.of(0, cappedLimit));
|
||||
return result.getContent().stream()
|
||||
.map(e -> new RecentHistoryEntryDto(
|
||||
e.getType().name(),
|
||||
e.getActor() == null ? null : e.getActor().getUsername(),
|
||||
e.getExpenseTitle(),
|
||||
e.getTimestamp(),
|
||||
e.getExpenseList().getId(),
|
||||
e.getExpenseList().getName()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private HistoryEntryDto toDto(ExpenseHistoryEntry entry) {
|
||||
List<FieldChange> changes = List.of();
|
||||
if (entry.getChanges() != null) {
|
||||
try {
|
||||
changes = objectMapper.readValue(entry.getChanges(),
|
||||
new TypeReference<List<FieldChange>>() {
|
||||
});
|
||||
} catch (JacksonException e) {
|
||||
throw new IllegalStateException("Corrupt history changes for entry " + entry.getId(), e);
|
||||
}
|
||||
}
|
||||
return new HistoryEntryDto(
|
||||
entry.getType().name(),
|
||||
entry.getActor() == null ? null : entry.getActor().getUsername(),
|
||||
entry.getExpenseTitle(),
|
||||
entry.getTimestamp(),
|
||||
changes);
|
||||
}
|
||||
}
|
||||
@@ -5,8 +5,8 @@ import java.util.List;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import de.zendric.app.xpensely_server.model.AppUser;
|
||||
import de.zendric.app.xpensely_server.model.Exception.GoogleAccountAlreadyRegisteredException;
|
||||
import de.zendric.app.xpensely_server.model.Exception.ResourceNotFoundException;
|
||||
import de.zendric.app.xpensely_server.model.Exception.UsernameAlreadyExistsException;
|
||||
import de.zendric.app.xpensely_server.repo.UserRepository;
|
||||
|
||||
@Service
|
||||
@@ -22,9 +22,18 @@ public class UserService {
|
||||
}
|
||||
|
||||
public AppUser createUser(AppUser user) {
|
||||
if (Boolean.TRUE.equals(userRepository.existsByUsername(user.getUsername()))) {
|
||||
throw new UsernameAlreadyExistsException("Username already exists");
|
||||
if (Boolean.TRUE.equals(userRepository.existsByGoogleId(user.getGoogleId()))) {
|
||||
throw new GoogleAccountAlreadyRegisteredException(
|
||||
"An account already exists for this Google account");
|
||||
}
|
||||
// Usernames are not unique — identity is the Google account (googleId).
|
||||
return userRepository.save(user);
|
||||
}
|
||||
|
||||
public AppUser updateUsername(Long userId, String newUsername) {
|
||||
AppUser user = userRepository.findById(userId)
|
||||
.orElseThrow(() -> new ResourceNotFoundException("User not found with id: " + userId));
|
||||
user.setUsername(newUsername);
|
||||
return userRepository.save(user);
|
||||
}
|
||||
|
||||
|
||||
@@ -3,8 +3,6 @@ spring.application.name=XpenselyServer
|
||||
|
||||
#Security
|
||||
spring.security.enabled=false
|
||||
spring.security.oauth2.client.registration.google.client-id=${GOOGLE_CLIENT_ID}
|
||||
spring.security.oauth2.client.registration.google.client-secret=${GOOGLE_CLIENT_SECRET}
|
||||
spring.security.oauth2.resourceserver.jwt.issuer-uri=https://accounts.google.com
|
||||
|
||||
# PostgreSQL Configuration
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package de.zendric.app.xpensely_Server.config;
|
||||
|
||||
import org.springframework.boot.test.context.TestConfiguration;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.security.oauth2.jwt.JwtDecoder;
|
||||
import org.springframework.security.oauth2.jwt.JwtException;
|
||||
|
||||
/**
|
||||
* Provides a no-op JwtDecoder so the application context starts without
|
||||
* fetching Google's JWKS endpoint. Tests use SecurityMockMvcRequestPostProcessors.jwt()
|
||||
* which populates the SecurityContext directly and never calls this decoder.
|
||||
*/
|
||||
@TestConfiguration
|
||||
public class TestJwtDecoderConfig {
|
||||
|
||||
@Bean
|
||||
@Primary
|
||||
public JwtDecoder jwtDecoder() {
|
||||
return token -> {
|
||||
throw new JwtException("Real JWT validation is disabled in integration tests — use jwt() post-processor");
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -6,8 +6,6 @@ import de.zendric.app.xpensely_server.security.AuthenticatedUserResolver;
|
||||
import de.zendric.app.xpensely_server.services.UserService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.security.oauth2.client.autoconfigure.OAuth2ClientAutoConfiguration;
|
||||
import org.springframework.boot.security.oauth2.client.autoconfigure.servlet.OAuth2ClientWebSecurityAutoConfiguration;
|
||||
import org.springframework.boot.security.oauth2.server.resource.autoconfigure.servlet.OAuth2ResourceServerAutoConfiguration;
|
||||
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
|
||||
@@ -22,8 +20,6 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
@WebMvcTest(value = AppUserController.class, excludeAutoConfiguration = {
|
||||
OAuth2ClientAutoConfiguration.class,
|
||||
OAuth2ClientWebSecurityAutoConfiguration.class,
|
||||
OAuth2ResourceServerAutoConfiguration.class
|
||||
})
|
||||
@AutoConfigureMockMvc(addFilters = false)
|
||||
@@ -99,4 +95,38 @@ class AppUserControllerTest {
|
||||
mockMvc.perform(delete("/api/users").param("id", "99"))
|
||||
.andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
// --- Rename username ---
|
||||
|
||||
@Test
|
||||
void updateUsername_valid_returns200WithUpdatedUser() throws Exception {
|
||||
AppUser self = new AppUser(); self.setId(1L); self.setUsername("old");
|
||||
AppUser updated = new AppUser(); updated.setId(1L); updated.setUsername("newname");
|
||||
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(self);
|
||||
when(userService.updateUsername(1L, "newname")).thenReturn(updated);
|
||||
|
||||
mockMvc.perform(put("/api/users/username")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"username\":\"newname\"}"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.username").value("newname"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateUsername_invalidPattern_returns400() throws Exception {
|
||||
mockMvc.perform(put("/api/users/username")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"username\":\"bad name!\"}"))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("$.username").exists());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateUsername_tooShort_returns400() throws Exception {
|
||||
mockMvc.perform(put("/api/users/username")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"username\":\"ab\"}"))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("$.username").exists());
|
||||
}
|
||||
}
|
||||
|
||||
+244
-6
@@ -2,15 +2,16 @@ package de.zendric.app.xpensely_Server.controller;
|
||||
|
||||
import de.zendric.app.xpensely_server.controller.ExpenseListController;
|
||||
import de.zendric.app.xpensely_server.model.AppUser;
|
||||
import de.zendric.app.xpensely_server.model.DTO.HistoryPageDto;
|
||||
import de.zendric.app.xpensely_server.model.DTO.RecentHistoryEntryDto;
|
||||
import de.zendric.app.xpensely_server.model.Expense;
|
||||
import de.zendric.app.xpensely_server.model.ExpenseList;
|
||||
import de.zendric.app.xpensely_server.security.AuthenticatedUserResolver;
|
||||
import de.zendric.app.xpensely_server.services.CategoryService;
|
||||
import de.zendric.app.xpensely_server.services.ExpenseListService;
|
||||
import de.zendric.app.xpensely_server.services.UserService;
|
||||
import de.zendric.app.xpensely_server.services.HistoryService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.security.oauth2.client.autoconfigure.OAuth2ClientAutoConfiguration;
|
||||
import org.springframework.boot.security.oauth2.client.autoconfigure.servlet.OAuth2ClientWebSecurityAutoConfiguration;
|
||||
import org.springframework.boot.security.oauth2.server.resource.autoconfigure.servlet.OAuth2ResourceServerAutoConfiguration;
|
||||
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
|
||||
@@ -19,17 +20,17 @@ import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.context.bean.override.mockito.MockitoBean;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
@WebMvcTest(value = ExpenseListController.class, excludeAutoConfiguration = {
|
||||
OAuth2ClientAutoConfiguration.class,
|
||||
OAuth2ClientWebSecurityAutoConfiguration.class,
|
||||
OAuth2ResourceServerAutoConfiguration.class
|
||||
})
|
||||
@AutoConfigureMockMvc(addFilters = false)
|
||||
@@ -38,9 +39,9 @@ class ExpenseListControllerTest {
|
||||
|
||||
@Autowired MockMvc mockMvc;
|
||||
@MockitoBean ExpenseListService expenseListService;
|
||||
@MockitoBean UserService userService;
|
||||
@MockitoBean CategoryService categoryService;
|
||||
@MockitoBean AuthenticatedUserResolver authenticatedUserResolver;
|
||||
@MockitoBean HistoryService historyService;
|
||||
|
||||
// --- Validation tests ---
|
||||
|
||||
@@ -53,6 +54,54 @@ class ExpenseListControllerTest {
|
||||
.andExpect(jsonPath("$.title").exists());
|
||||
}
|
||||
|
||||
// Quick Add creates stub expenses (amount 0, no category); updating such a
|
||||
// stub must be allowed so the user can fill in the details afterwards.
|
||||
@Test
|
||||
void updateExpense_quickAddStub_zeroAmountAndNoCategory_returns200() throws Exception {
|
||||
AppUser owner = new AppUser(); owner.setId(1L); owner.setUsername("alice");
|
||||
ExpenseList list = new ExpenseList(); list.setId(1L); list.setOwner(owner);
|
||||
when(expenseListService.findById(1L)).thenReturn(Optional.of(list));
|
||||
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(owner);
|
||||
when(expenseListService.updateExpense(eq(1L), any(Expense.class), eq(owner)))
|
||||
.thenAnswer(inv -> inv.getArgument(1));
|
||||
|
||||
mockMvc.perform(put("/api/expenselist/1/update")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"id\":42,\"title\":\"Groceries\",\"ownerName\":\"alice\",\"amount\":0.0,"
|
||||
+ "\"personalUseAmount\":0.0,\"otherPersonAmount\":0.0,\"date\":\"2026-07-06\"}"))
|
||||
.andExpect(status().isOk());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateExpense_blankCategory_isStoredAsNull() throws Exception {
|
||||
AppUser owner = new AppUser(); owner.setId(1L); owner.setUsername("alice");
|
||||
ExpenseList list = new ExpenseList(); list.setId(1L); list.setOwner(owner);
|
||||
when(expenseListService.findById(1L)).thenReturn(Optional.of(list));
|
||||
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(owner);
|
||||
when(expenseListService.updateExpense(eq(1L), any(Expense.class), eq(owner)))
|
||||
.thenAnswer(inv -> inv.getArgument(1));
|
||||
|
||||
mockMvc.perform(put("/api/expenselist/1/update")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"id\":42,\"title\":\"Groceries\",\"ownerName\":\"alice\",\"amount\":0.0,"
|
||||
+ "\"personalUseAmount\":0.0,\"otherPersonAmount\":0.0,\"date\":\"2026-07-06\",\"category\":\"\"}"))
|
||||
.andExpect(status().isOk());
|
||||
|
||||
org.mockito.ArgumentCaptor<Expense> captor = org.mockito.ArgumentCaptor.forClass(Expense.class);
|
||||
org.mockito.Mockito.verify(expenseListService).updateExpense(eq(1L), captor.capture(), eq(owner));
|
||||
org.assertj.core.api.Assertions.assertThat(captor.getValue().getCategory()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateExpense_negativeAmount_returns400() throws Exception {
|
||||
mockMvc.perform(put("/api/expenselist/1/update")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"id\":42,\"title\":\"Groceries\",\"ownerName\":\"alice\",\"amount\":-5.0,"
|
||||
+ "\"personalUseAmount\":0.0,\"otherPersonAmount\":0.0,\"date\":\"2026-07-06\",\"category\":\"Food\"}"))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("$.amount").exists());
|
||||
}
|
||||
|
||||
@Test
|
||||
void addExpense_negativeAmount_returns400() throws Exception {
|
||||
mockMvc.perform(post("/api/expenselist/1/add")
|
||||
@@ -178,4 +227,193 @@ class ExpenseListControllerTest {
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("$.name").exists());
|
||||
}
|
||||
|
||||
// --- Owner resolution within list members ---
|
||||
|
||||
@Test
|
||||
void addExpense_ownerNotAListMember_returns400() throws Exception {
|
||||
AppUser member = new AppUser(); member.setId(1L); member.setUsername("alice");
|
||||
ExpenseList list = new ExpenseList(); list.setId(1L); list.setOwner(member);
|
||||
|
||||
when(expenseListService.findById(1L)).thenReturn(Optional.of(list));
|
||||
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(member);
|
||||
|
||||
mockMvc.perform(post("/api/expenselist/1/add")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"title\":\"Lunch\",\"owner\":\"ghost\",\"amount\":10.0,\"date\":\"2026-05-04\",\"category\":\"Food\"}"))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
void addExpense_ownerIsAListMember_returns201() throws Exception {
|
||||
AppUser member = new AppUser(); member.setId(1L); member.setUsername("alice");
|
||||
ExpenseList list = new ExpenseList(); list.setId(1L); list.setOwner(member);
|
||||
|
||||
when(expenseListService.findById(1L)).thenReturn(Optional.of(list));
|
||||
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(member);
|
||||
when(expenseListService.addExpenseToList(eq(1L), any(), any())).thenReturn(new Expense());
|
||||
|
||||
mockMvc.perform(post("/api/expenselist/1/add")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"title\":\"Lunch\",\"owner\":\"alice\",\"amount\":10.0,\"date\":\"2026-05-04\",\"category\":\"Food\"}"))
|
||||
.andExpect(status().isCreated());
|
||||
}
|
||||
|
||||
// --- Rename list ---
|
||||
|
||||
@Test
|
||||
void renameList_owner_returns200WithRenamedList() throws Exception {
|
||||
AppUser owner = new AppUser(); owner.setId(1L);
|
||||
ExpenseList list = new ExpenseList(); list.setId(5L); list.setOwner(owner);
|
||||
ExpenseList renamed = new ExpenseList(); renamed.setId(5L); renamed.setName("Groceries");
|
||||
|
||||
when(expenseListService.findById(5L)).thenReturn(Optional.of(list));
|
||||
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(owner);
|
||||
when(expenseListService.renameList(5L, "Groceries")).thenReturn(renamed);
|
||||
|
||||
mockMvc.perform(put("/api/expenselist/5/rename")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"name\":\"Groceries\"}"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.name").value("Groceries"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void renameList_nonOwner_returns403() throws Exception {
|
||||
AppUser owner = new AppUser(); owner.setId(1L);
|
||||
AppUser nonOwner = new AppUser(); nonOwner.setId(2L);
|
||||
ExpenseList list = new ExpenseList(); list.setId(5L); list.setOwner(owner);
|
||||
|
||||
when(expenseListService.findById(5L)).thenReturn(Optional.of(list));
|
||||
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(nonOwner);
|
||||
|
||||
mockMvc.perform(put("/api/expenselist/5/rename")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"name\":\"Groceries\"}"))
|
||||
.andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
@Test
|
||||
void renameList_blankName_returns400() throws Exception {
|
||||
mockMvc.perform(put("/api/expenselist/5/rename")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"name\":\"\"}"))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("$.name").exists());
|
||||
}
|
||||
|
||||
@Test
|
||||
void renameList_notFound_returns404() throws Exception {
|
||||
AppUser owner = new AppUser(); owner.setId(1L);
|
||||
when(expenseListService.findById(9L)).thenReturn(Optional.empty());
|
||||
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(owner);
|
||||
|
||||
mockMvc.perform(put("/api/expenselist/9/rename")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"name\":\"Groceries\"}"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
// --- Duplicate-username invite guard ---
|
||||
|
||||
@Test
|
||||
void acceptInvite_sameUsernameAsOwner_returns409() throws Exception {
|
||||
AppUser owner = new AppUser(); owner.setId(1L); owner.setUsername("cedric");
|
||||
AppUser joiner = new AppUser(); joiner.setId(2L); joiner.setUsername("cedric");
|
||||
ExpenseList list = new ExpenseList();
|
||||
list.setId(1L);
|
||||
list.setOwner(owner);
|
||||
list.setInviteCodeExpiration(LocalDateTime.now().plusHours(1));
|
||||
|
||||
when(expenseListService.findByInviteCode("ABC123")).thenReturn(list);
|
||||
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(joiner);
|
||||
|
||||
mockMvc.perform(post("/api/expenselist/accept-invite")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"inviteCode\":\"ABC123\"}"))
|
||||
.andExpect(status().isConflict());
|
||||
}
|
||||
|
||||
// --- History endpoint ---
|
||||
|
||||
@Test
|
||||
void getHistory_member_returns200WithPage() throws Exception {
|
||||
AppUser owner = new AppUser(); owner.setId(1L); owner.setUsername("alice");
|
||||
ExpenseList list = new ExpenseList(); list.setId(1L); list.setOwner(owner);
|
||||
when(expenseListService.findById(1L)).thenReturn(Optional.of(list));
|
||||
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(owner);
|
||||
when(historyService.getHistory(1L, 0, 30))
|
||||
.thenReturn(new HistoryPageDto(List.of(), false));
|
||||
|
||||
mockMvc.perform(get("/api/expenselist/1/history"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.entries").isArray())
|
||||
.andExpect(jsonPath("$.hasMore").value(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getHistory_nonMember_returns403() throws Exception {
|
||||
AppUser owner = new AppUser(); owner.setId(1L);
|
||||
AppUser stranger = new AppUser(); stranger.setId(2L);
|
||||
ExpenseList list = new ExpenseList(); list.setId(1L); list.setOwner(owner);
|
||||
when(expenseListService.findById(1L)).thenReturn(Optional.of(list));
|
||||
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(stranger);
|
||||
|
||||
mockMvc.perform(get("/api/expenselist/1/history"))
|
||||
.andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getHistory_unknownList_returns404() throws Exception {
|
||||
when(expenseListService.findById(99L)).thenReturn(Optional.empty());
|
||||
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(new AppUser());
|
||||
|
||||
mockMvc.perform(get("/api/expenselist/99/history"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
// --- Recent history endpoint ---
|
||||
|
||||
@Test
|
||||
void getRecentHistory_returnsArrayWithListInfo() throws Exception {
|
||||
AppUser user = new AppUser(); user.setId(1L); user.setUsername("alice");
|
||||
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(user);
|
||||
when(historyService.getRecentForUser(user, 4)).thenReturn(List.of(
|
||||
new RecentHistoryEntryDto("UPDATED", "alice", "Groceries",
|
||||
LocalDateTime.of(2026, 7, 6, 12, 0), 10L, "Trip to Rome")));
|
||||
|
||||
mockMvc.perform(get("/api/expenselist/history/recent"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$[0].type").value("UPDATED"))
|
||||
.andExpect(jsonPath("$[0].actorUsername").value("alice"))
|
||||
.andExpect(jsonPath("$[0].expenseTitle").value("Groceries"))
|
||||
.andExpect(jsonPath("$[0].listId").value(10))
|
||||
.andExpect(jsonPath("$[0].listName").value("Trip to Rome"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getRecentHistory_passesLimitParam() throws Exception {
|
||||
AppUser user = new AppUser(); user.setId(1L);
|
||||
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(user);
|
||||
when(historyService.getRecentForUser(user, 10)).thenReturn(List.of());
|
||||
|
||||
mockMvc.perform(get("/api/expenselist/history/recent").param("limit", "10"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getRecentHistory_doesNotClashWithPerListHistoryRoute() throws Exception {
|
||||
// /api/expenselist/1/history must still hit the per-list handler.
|
||||
AppUser owner = new AppUser(); owner.setId(1L); owner.setUsername("alice");
|
||||
ExpenseList list = new ExpenseList(); list.setId(1L); list.setOwner(owner);
|
||||
when(expenseListService.findById(1L)).thenReturn(Optional.of(list));
|
||||
when(authenticatedUserResolver.resolveCurrentUser(any())).thenReturn(owner);
|
||||
when(historyService.getHistory(1L, 0, 30))
|
||||
.thenReturn(new HistoryPageDto(List.of(), false));
|
||||
|
||||
mockMvc.perform(get("/api/expenselist/1/history"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.entries").isArray());
|
||||
}
|
||||
}
|
||||
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
package de.zendric.app.xpensely_Server.preparation;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import de.zendric.app.xpensely_server.model.AppUser;
|
||||
import de.zendric.app.xpensely_server.model.Expense;
|
||||
import de.zendric.app.xpensely_server.model.ExpenseHistoryEntry;
|
||||
import de.zendric.app.xpensely_server.model.ExpenseList;
|
||||
import de.zendric.app.xpensely_server.model.HistoryEntryType;
|
||||
import de.zendric.app.xpensely_server.preparation.HistoryBackfillRunner;
|
||||
import de.zendric.app.xpensely_server.repo.ExpenseHistoryRepository;
|
||||
import de.zendric.app.xpensely_server.repo.ExpenseRepository;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class HistoryBackfillRunnerTest {
|
||||
|
||||
@Mock ExpenseRepository expenseRepository;
|
||||
@Mock ExpenseHistoryRepository historyRepository;
|
||||
|
||||
@InjectMocks
|
||||
HistoryBackfillRunner runner;
|
||||
|
||||
private Expense expense(long id, LocalDate date) {
|
||||
AppUser owner = new AppUser(); owner.setId(1L); owner.setUsername("alice");
|
||||
ExpenseList list = new ExpenseList(); list.setId(10L);
|
||||
Expense e = new Expense();
|
||||
e.setId(id);
|
||||
e.setTitle("Groceries");
|
||||
e.setDate(date);
|
||||
e.setOwner(owner);
|
||||
e.setExpenseList(list);
|
||||
return e;
|
||||
}
|
||||
|
||||
@Test
|
||||
void fillsLastModifiedFromDate_forExpensesMissingIt() throws Exception {
|
||||
Expense e = expense(42L, LocalDate.of(2026, 6, 1));
|
||||
when(expenseRepository.findByLastModifiedIsNull()).thenReturn(List.of(e));
|
||||
when(expenseRepository.findAll()).thenReturn(List.of(e));
|
||||
when(historyRepository.findAllExpenseIds()).thenReturn(List.of(42L));
|
||||
|
||||
runner.run();
|
||||
|
||||
assertThat(e.getLastModified()).isEqualTo(LocalDate.of(2026, 6, 1).atStartOfDay());
|
||||
verify(expenseRepository).save(e);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createsSyntheticCreatedEntry_forExpensesWithoutHistory() throws Exception {
|
||||
Expense e = expense(42L, LocalDate.of(2026, 6, 1));
|
||||
when(expenseRepository.findByLastModifiedIsNull()).thenReturn(List.of());
|
||||
when(expenseRepository.findAll()).thenReturn(List.of(e));
|
||||
when(historyRepository.findAllExpenseIds()).thenReturn(List.of());
|
||||
|
||||
runner.run();
|
||||
|
||||
ArgumentCaptor<ExpenseHistoryEntry> captor = ArgumentCaptor.forClass(ExpenseHistoryEntry.class);
|
||||
verify(historyRepository).save(captor.capture());
|
||||
ExpenseHistoryEntry entry = captor.getValue();
|
||||
assertThat(entry.getType()).isEqualTo(HistoryEntryType.CREATED);
|
||||
assertThat(entry.getExpenseId()).isEqualTo(42L);
|
||||
assertThat(entry.getExpenseTitle()).isEqualTo("Groceries");
|
||||
assertThat(entry.getActor().getUsername()).isEqualTo("alice");
|
||||
assertThat(entry.getTimestamp()).isEqualTo(LocalDate.of(2026, 6, 1).atStartOfDay());
|
||||
}
|
||||
|
||||
@Test
|
||||
void isIdempotent_skipsExpensesThatAlreadyHaveHistory() throws Exception {
|
||||
Expense e = expense(42L, LocalDate.of(2026, 6, 1));
|
||||
when(expenseRepository.findByLastModifiedIsNull()).thenReturn(List.of());
|
||||
when(expenseRepository.findAll()).thenReturn(List.of(e));
|
||||
when(historyRepository.findAllExpenseIds()).thenReturn(List.of(42L));
|
||||
|
||||
runner.run();
|
||||
|
||||
verify(historyRepository, never()).save(any());
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -1,6 +1,7 @@
|
||||
package de.zendric.app.xpensely_Server.security;
|
||||
|
||||
import de.zendric.app.xpensely_server.model.AppUser;
|
||||
import de.zendric.app.xpensely_server.model.Exception.ResourceNotFoundException;
|
||||
import de.zendric.app.xpensely_server.security.AuthenticatedUserResolver;
|
||||
import de.zendric.app.xpensely_server.services.UserService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -48,7 +49,8 @@ class AuthenticatedUserResolverTest {
|
||||
.subject("unknown-id")
|
||||
.build();
|
||||
JwtAuthenticationToken auth = new JwtAuthenticationToken(jwt);
|
||||
when(userService.getUserByGoogleId("unknown-id")).thenReturn(null);
|
||||
when(userService.getUserByGoogleId("unknown-id"))
|
||||
.thenThrow(new ResourceNotFoundException("User not found with Google ID: unknown-id"));
|
||||
|
||||
ResponseStatusException ex = assertThrows(ResponseStatusException.class,
|
||||
() -> resolver.resolveCurrentUser(auth));
|
||||
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
package de.zendric.app.xpensely_Server.security;
|
||||
|
||||
import de.zendric.app.xpensely_Server.config.TestJwtDecoderConfig;
|
||||
import de.zendric.app.xpensely_server.model.AppUser;
|
||||
import de.zendric.app.xpensely_server.repo.ExpenseListRepository;
|
||||
import de.zendric.app.xpensely_server.repo.UserRepository;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
/**
|
||||
* Full-stack integration tests for the security filter chain.
|
||||
* Runs with the real securityFilterChain (not the test permit-all chain).
|
||||
* Uses an H2 in-memory database (see application-integration.properties).
|
||||
* JWT validation is bypassed via jwt() post-processor — no real Google token needed.
|
||||
*/
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
|
||||
@AutoConfigureMockMvc
|
||||
@ActiveProfiles("integration")
|
||||
@Import(TestJwtDecoderConfig.class)
|
||||
class SecurityFilterChainIntegrationTest {
|
||||
|
||||
@Autowired MockMvc mockMvc;
|
||||
@Autowired UserRepository userRepository;
|
||||
@Autowired ExpenseListRepository expenseListRepository;
|
||||
|
||||
private static final String KNOWN_GOOGLE_ID = "google-integration-test-123";
|
||||
private static final String UNKNOWN_GOOGLE_ID = "google-unknown-999";
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
expenseListRepository.deleteAll();
|
||||
userRepository.deleteAll();
|
||||
|
||||
AppUser user = new AppUser();
|
||||
user.setGoogleId(KNOWN_GOOGLE_ID);
|
||||
user.setUsername("integrationtestuser");
|
||||
userRepository.save(user);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
expenseListRepository.deleteAll();
|
||||
userRepository.deleteAll();
|
||||
}
|
||||
|
||||
// --- Public endpoints ---
|
||||
|
||||
@Test
|
||||
void versionEndpoint_noAuth_returns200() throws Exception {
|
||||
mockMvc.perform(get("/api/version"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.version").exists());
|
||||
}
|
||||
|
||||
// --- Unauthenticated access (no JWT) → 401 ---
|
||||
|
||||
@Test
|
||||
void byGoogleId_noJwt_returns401() throws Exception {
|
||||
mockMvc.perform(get("/api/users/byGoogleId").param("id", KNOWN_GOOGLE_ID))
|
||||
.andExpect(status().isUnauthorized());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createUser_noJwt_returns401() throws Exception {
|
||||
mockMvc.perform(post("/api/users/createUser")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"username\":\"newuser\",\"googleId\":\"new-google-id\"}"))
|
||||
.andExpect(status().isUnauthorized());
|
||||
}
|
||||
|
||||
@Test
|
||||
void expenseListMine_noJwt_returns401() throws Exception {
|
||||
mockMvc.perform(get("/api/expenselist/mine"))
|
||||
.andExpect(status().isUnauthorized());
|
||||
}
|
||||
|
||||
// --- Authenticated, user exists in DB → success ---
|
||||
|
||||
@Test
|
||||
void byGoogleId_withJwt_userInDb_returns200() throws Exception {
|
||||
mockMvc.perform(get("/api/users/byGoogleId")
|
||||
.param("id", KNOWN_GOOGLE_ID)
|
||||
.with(jwt().jwt(j -> j.subject(KNOWN_GOOGLE_ID))))
|
||||
.andExpect(status().isOk());
|
||||
}
|
||||
|
||||
@Test
|
||||
void expenseListMine_withJwt_userInDb_emptyList_returns204() throws Exception {
|
||||
mockMvc.perform(get("/api/expenselist/mine")
|
||||
.with(jwt().jwt(j -> j.subject(KNOWN_GOOGLE_ID))))
|
||||
.andExpect(status().isNoContent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createUser_withJwt_validBody_returns201() throws Exception {
|
||||
mockMvc.perform(post("/api/users/createUser")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"username\":\"newuser123\",\"googleId\":\"brand-new-google-id\"}")
|
||||
.with(jwt().jwt(j -> j.subject("brand-new-google-id"))))
|
||||
.andExpect(status().isCreated());
|
||||
}
|
||||
|
||||
// --- Authenticated, user NOT in DB → 403 ---
|
||||
|
||||
@Test
|
||||
void byGoogleId_withJwt_userNotInDb_returns403() throws Exception {
|
||||
mockMvc.perform(get("/api/users/byGoogleId")
|
||||
.param("id", UNKNOWN_GOOGLE_ID)
|
||||
.with(jwt().jwt(j -> j.subject(UNKNOWN_GOOGLE_ID))))
|
||||
.andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
@Test
|
||||
void expenseListMine_withJwt_userNotInDb_returns403() throws Exception {
|
||||
mockMvc.perform(get("/api/expenselist/mine")
|
||||
.with(jwt().jwt(j -> j.subject(UNKNOWN_GOOGLE_ID))))
|
||||
.andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
// --- Authenticated, accessing another user's resource → 403 ---
|
||||
|
||||
@Test
|
||||
void byGoogleId_withJwt_differentId_returns403() throws Exception {
|
||||
mockMvc.perform(get("/api/users/byGoogleId")
|
||||
.param("id", UNKNOWN_GOOGLE_ID)
|
||||
.with(jwt().jwt(j -> j.subject(KNOWN_GOOGLE_ID))))
|
||||
.andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
// --- Validation errors still return 400 with JWT ---
|
||||
|
||||
@Test
|
||||
void createUser_withJwt_blankUsername_returns400() throws Exception {
|
||||
mockMvc.perform(post("/api/users/createUser")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"username\":\"\",\"googleId\":\"some-id\"}")
|
||||
.with(jwt().jwt(j -> j.subject("some-id"))))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("$.username").exists());
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,27 @@
|
||||
package de.zendric.app.xpensely_Server.services;
|
||||
|
||||
import de.zendric.app.xpensely_server.model.AppUser;
|
||||
import de.zendric.app.xpensely_server.model.Expense;
|
||||
import de.zendric.app.xpensely_server.model.ExpenseList;
|
||||
import de.zendric.app.xpensely_server.repo.ExpenseListRepository;
|
||||
import de.zendric.app.xpensely_server.repo.ExpenseRepository;
|
||||
import de.zendric.app.xpensely_server.repo.XpenselyCustomCategoryRepository;
|
||||
import de.zendric.app.xpensely_server.services.ExpenseListService;
|
||||
import de.zendric.app.xpensely_server.services.HistoryService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.any;
|
||||
import static org.mockito.Mockito.eq;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.mockito.Mockito.never;
|
||||
@@ -25,6 +32,7 @@ class ExpenseListServiceTest {
|
||||
@Mock ExpenseListRepository repository;
|
||||
@Mock ExpenseRepository expenseRepository;
|
||||
@Mock XpenselyCustomCategoryRepository customCategoryRepository;
|
||||
@Mock HistoryService historyService;
|
||||
|
||||
@InjectMocks
|
||||
ExpenseListService service;
|
||||
@@ -54,4 +62,72 @@ class ExpenseListServiceTest {
|
||||
verify(repository).findByOwnerUsernameOrSharedWithUsername("alice");
|
||||
verify(repository, never()).findAll();
|
||||
}
|
||||
|
||||
private Expense makeExpense(Long id, String title, double amount) {
|
||||
Expense e = new Expense();
|
||||
e.setId(id);
|
||||
e.setTitle(title);
|
||||
e.setAmount(amount);
|
||||
e.setPersonalUseAmount(0.0);
|
||||
e.setOtherPersonAmount(0.0);
|
||||
e.setDate(LocalDate.of(2026, 7, 1));
|
||||
return e;
|
||||
}
|
||||
|
||||
@Test
|
||||
void addExpenseToList_setsLastModified_andRecordsCreated() {
|
||||
AppUser actor = new AppUser(); actor.setId(1L);
|
||||
ExpenseList list = new ExpenseList(); list.setId(10L);
|
||||
list.setExpenses(new ArrayList<>());
|
||||
when(repository.findById(10L)).thenReturn(Optional.of(list));
|
||||
|
||||
Expense expense = makeExpense(null, "Lunch", 10.0);
|
||||
service.addExpenseToList(10L, expense, actor);
|
||||
|
||||
assertThat(expense.getLastModified()).isNotNull();
|
||||
verify(historyService).recordCreated(list, expense, actor);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateExpense_setsLastModified_andRecordsUpdatedWithBeforeSnapshot() {
|
||||
AppUser actor = new AppUser(); actor.setId(1L);
|
||||
ExpenseList list = new ExpenseList(); list.setId(10L);
|
||||
Expense existing = makeExpense(42L, "Old title", 12.0);
|
||||
list.setExpenses(new ArrayList<>(List.of(existing)));
|
||||
when(repository.findById(10L)).thenReturn(Optional.of(list));
|
||||
when(expenseRepository.findById(42L)).thenReturn(Optional.of(existing));
|
||||
when(expenseRepository.save(any(Expense.class))).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
Expense updated = makeExpense(42L, "New title", 15.0);
|
||||
service.updateExpense(10L, updated, actor);
|
||||
|
||||
assertThat(existing.getLastModified()).isNotNull();
|
||||
org.mockito.ArgumentCaptor<Expense> beforeCaptor =
|
||||
org.mockito.ArgumentCaptor.forClass(Expense.class);
|
||||
verify(historyService).recordUpdated(eq(list), beforeCaptor.capture(), eq(existing), eq(actor));
|
||||
assertThat(beforeCaptor.getValue().getTitle()).isEqualTo("Old title");
|
||||
assertThat(beforeCaptor.getValue().getAmount()).isEqualTo(12.0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteById_deletesHistoryEntriesBeforeDeletingList() {
|
||||
service.deleteById(10L);
|
||||
|
||||
org.mockito.InOrder inOrder = org.mockito.Mockito.inOrder(historyService, repository);
|
||||
inOrder.verify(historyService).deleteForList(10L);
|
||||
inOrder.verify(repository).deleteById(10L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteExpenseFromList_recordsDeleted() {
|
||||
AppUser actor = new AppUser(); actor.setId(1L);
|
||||
ExpenseList list = new ExpenseList(); list.setId(10L);
|
||||
Expense existing = makeExpense(42L, "Taxi", 9.0);
|
||||
list.setExpenses(new ArrayList<>(List.of(existing)));
|
||||
when(repository.findById(10L)).thenReturn(Optional.of(list));
|
||||
|
||||
service.deleteExpenseFromList(10L, 42L, actor);
|
||||
|
||||
verify(historyService).recordDeleted(eq(list), any(Expense.class), eq(actor));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
package de.zendric.app.xpensely_Server.services;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Spy;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.data.domain.PageImpl;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
|
||||
import de.zendric.app.xpensely_server.model.AppUser;
|
||||
import de.zendric.app.xpensely_server.model.DTO.HistoryPageDto;
|
||||
import de.zendric.app.xpensely_server.model.DTO.RecentHistoryEntryDto;
|
||||
import de.zendric.app.xpensely_server.model.Expense;
|
||||
import de.zendric.app.xpensely_server.model.ExpenseHistoryEntry;
|
||||
import de.zendric.app.xpensely_server.model.ExpenseList;
|
||||
import de.zendric.app.xpensely_server.model.FieldChange;
|
||||
import de.zendric.app.xpensely_server.model.HistoryEntryType;
|
||||
import de.zendric.app.xpensely_server.repo.ExpenseHistoryRepository;
|
||||
import de.zendric.app.xpensely_server.services.HistoryService;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class HistoryServiceTest {
|
||||
|
||||
@Mock ExpenseHistoryRepository historyRepository;
|
||||
@Spy ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
@InjectMocks
|
||||
HistoryService service;
|
||||
|
||||
private AppUser user(long id, String name) {
|
||||
AppUser u = new AppUser();
|
||||
u.setId(id);
|
||||
u.setUsername(name);
|
||||
return u;
|
||||
}
|
||||
|
||||
private Expense expense(String title, double amount, String category, LocalDate date, AppUser owner) {
|
||||
Expense e = new Expense();
|
||||
e.setId(42L);
|
||||
e.setTitle(title);
|
||||
e.setAmount(amount);
|
||||
e.setPersonalUseAmount(0.0);
|
||||
e.setOtherPersonAmount(0.0);
|
||||
e.setCategory(category);
|
||||
e.setDate(date);
|
||||
e.setOwner(owner);
|
||||
return e;
|
||||
}
|
||||
|
||||
@Test
|
||||
void diff_detectsChangedFields_withOldAndNewValues() {
|
||||
AppUser alice = user(1L, "alice");
|
||||
Expense before = expense("Groceries", 12.0, "Food", LocalDate.of(2026, 7, 1), alice);
|
||||
Expense after = expense("Groceries", 15.5, "Household", LocalDate.of(2026, 7, 1), alice);
|
||||
|
||||
List<FieldChange> changes = service.diff(before, after);
|
||||
|
||||
assertThat(changes).containsExactlyInAnyOrder(
|
||||
new FieldChange("amount", "12.0", "15.5"),
|
||||
new FieldChange("category", "Food", "Household"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void diff_ownerChange_isReportedByUsername() {
|
||||
Expense before = expense("Taxi", 9.0, null, LocalDate.of(2026, 7, 1), user(1L, "alice"));
|
||||
Expense after = expense("Taxi", 9.0, null, LocalDate.of(2026, 7, 1), user(2L, "ben"));
|
||||
|
||||
List<FieldChange> changes = service.diff(before, after);
|
||||
|
||||
assertThat(changes).containsExactly(new FieldChange("owner", "alice", "ben"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void diff_nullToValue_isReported() {
|
||||
Expense before = expense("Taxi", 9.0, null, LocalDate.of(2026, 7, 1), user(1L, "alice"));
|
||||
Expense after = expense("Taxi", 9.0, "Transportation", LocalDate.of(2026, 7, 1), user(1L, "alice"));
|
||||
|
||||
assertThat(service.diff(before, after))
|
||||
.containsExactly(new FieldChange("category", null, "Transportation"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordUpdated_noChanges_writesNothing() {
|
||||
AppUser alice = user(1L, "alice");
|
||||
Expense same = expense("Groceries", 12.0, "Food", LocalDate.of(2026, 7, 1), alice);
|
||||
ExpenseList list = new ExpenseList();
|
||||
list.setId(5L);
|
||||
|
||||
service.recordUpdated(list, same, same, alice);
|
||||
|
||||
verify(historyRepository, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordUpdated_savesEntryWithJsonChanges() {
|
||||
AppUser alice = user(1L, "alice");
|
||||
ExpenseList list = new ExpenseList();
|
||||
list.setId(5L);
|
||||
Expense before = expense("Groceries", 12.0, "Food", LocalDate.of(2026, 7, 1), alice);
|
||||
Expense after = expense("Groceries", 15.5, "Food", LocalDate.of(2026, 7, 1), alice);
|
||||
|
||||
service.recordUpdated(list, before, after, alice);
|
||||
|
||||
ArgumentCaptor<ExpenseHistoryEntry> captor = ArgumentCaptor.forClass(ExpenseHistoryEntry.class);
|
||||
verify(historyRepository).save(captor.capture());
|
||||
ExpenseHistoryEntry entry = captor.getValue();
|
||||
assertThat(entry.getType()).isEqualTo(HistoryEntryType.UPDATED);
|
||||
assertThat(entry.getExpenseId()).isEqualTo(42L);
|
||||
assertThat(entry.getExpenseTitle()).isEqualTo("Groceries");
|
||||
assertThat(entry.getActor()).isEqualTo(alice);
|
||||
assertThat(entry.getExpenseList()).isEqualTo(list);
|
||||
assertThat(entry.getTimestamp()).isNotNull();
|
||||
assertThat(entry.getChanges())
|
||||
.isEqualTo("[{\"field\":\"amount\",\"old\":\"12.0\",\"new\":\"15.5\"}]");
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordCreated_savesEntryWithoutChanges() {
|
||||
AppUser alice = user(1L, "alice");
|
||||
ExpenseList list = new ExpenseList();
|
||||
list.setId(5L);
|
||||
Expense e = expense("Groceries", 12.0, "Food", LocalDate.of(2026, 7, 1), alice);
|
||||
|
||||
service.recordCreated(list, e, alice);
|
||||
|
||||
ArgumentCaptor<ExpenseHistoryEntry> captor = ArgumentCaptor.forClass(ExpenseHistoryEntry.class);
|
||||
verify(historyRepository).save(captor.capture());
|
||||
assertThat(captor.getValue().getType()).isEqualTo(HistoryEntryType.CREATED);
|
||||
assertThat(captor.getValue().getChanges()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordDeleted_savesEntry() {
|
||||
AppUser alice = user(1L, "alice");
|
||||
ExpenseList list = new ExpenseList();
|
||||
list.setId(5L);
|
||||
Expense e = expense("Taxi", 9.0, null, LocalDate.of(2026, 7, 1), alice);
|
||||
|
||||
service.recordDeleted(list, e, alice);
|
||||
|
||||
ArgumentCaptor<ExpenseHistoryEntry> captor = ArgumentCaptor.forClass(ExpenseHistoryEntry.class);
|
||||
verify(historyRepository).save(captor.capture());
|
||||
assertThat(captor.getValue().getType()).isEqualTo(HistoryEntryType.DELETED);
|
||||
assertThat(captor.getValue().getExpenseTitle()).isEqualTo("Taxi");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getHistory_mapsEntriesToDto_andParsesChangesJson() {
|
||||
ExpenseHistoryEntry entry = new ExpenseHistoryEntry();
|
||||
entry.setType(HistoryEntryType.UPDATED);
|
||||
entry.setActor(user(1L, "alice"));
|
||||
entry.setExpenseTitle("Groceries");
|
||||
entry.setTimestamp(java.time.LocalDateTime.of(2026, 7, 6, 14, 31));
|
||||
entry.setChanges("[{\"field\":\"amount\",\"old\":\"12.0\",\"new\":\"15.5\"}]");
|
||||
when(historyRepository.findByExpenseListIdOrderByTimestampDescIdDesc(eq(5L), any(Pageable.class)))
|
||||
.thenReturn(new PageImpl<>(List.of(entry), PageRequest.of(0, 30), 31));
|
||||
|
||||
HistoryPageDto page = service.getHistory(5L, 0, 30);
|
||||
|
||||
assertThat(page.hasMore()).isTrue();
|
||||
assertThat(page.entries()).hasSize(1);
|
||||
assertThat(page.entries().get(0).type()).isEqualTo("UPDATED");
|
||||
assertThat(page.entries().get(0).actorUsername()).isEqualTo("alice");
|
||||
assertThat(page.entries().get(0).changes())
|
||||
.containsExactly(new FieldChange("amount", "12.0", "15.5"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getHistory_capsPageSizeAt100() {
|
||||
when(historyRepository.findByExpenseListIdOrderByTimestampDescIdDesc(eq(5L), any(Pageable.class)))
|
||||
.thenReturn(new PageImpl<>(List.of()));
|
||||
|
||||
service.getHistory(5L, 0, 5000);
|
||||
|
||||
ArgumentCaptor<Pageable> captor = ArgumentCaptor.forClass(Pageable.class);
|
||||
verify(historyRepository).findByExpenseListIdOrderByTimestampDescIdDesc(eq(5L), captor.capture());
|
||||
assertThat(captor.getValue().getPageSize()).isEqualTo(100);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getHistory_nullChanges_yieldsEmptyList() {
|
||||
ExpenseHistoryEntry entry = new ExpenseHistoryEntry();
|
||||
entry.setType(HistoryEntryType.CREATED);
|
||||
entry.setActor(user(1L, "alice"));
|
||||
entry.setExpenseTitle("Groceries");
|
||||
entry.setTimestamp(java.time.LocalDateTime.of(2026, 7, 6, 14, 31));
|
||||
when(historyRepository.findByExpenseListIdOrderByTimestampDescIdDesc(eq(5L), any(Pageable.class)))
|
||||
.thenReturn(new PageImpl<>(List.of(entry)));
|
||||
|
||||
HistoryPageDto page = service.getHistory(5L, 0, 30);
|
||||
|
||||
assertThat(page.entries().get(0).changes()).isEmpty();
|
||||
}
|
||||
|
||||
private ExpenseHistoryEntry historyEntry(Long id, ExpenseList list, AppUser actor,
|
||||
HistoryEntryType type, String title, java.time.LocalDateTime timestamp) {
|
||||
ExpenseHistoryEntry e = new ExpenseHistoryEntry();
|
||||
e.setId(id);
|
||||
e.setExpenseList(list);
|
||||
e.setActor(actor);
|
||||
e.setType(type);
|
||||
e.setExpenseTitle(title);
|
||||
e.setTimestamp(timestamp);
|
||||
return e;
|
||||
}
|
||||
|
||||
@Test
|
||||
void getRecentForUser_mapsEntriesWithListIdAndName() {
|
||||
AppUser alice = user(1L, "alice");
|
||||
ExpenseList list = new ExpenseList();
|
||||
list.setId(10L);
|
||||
list.setName("Trip to Rome");
|
||||
ExpenseHistoryEntry entry = historyEntry(100L, list, alice,
|
||||
HistoryEntryType.UPDATED, "Groceries", java.time.LocalDateTime.of(2026, 7, 6, 12, 0));
|
||||
|
||||
when(historyRepository
|
||||
.findByExpenseListOwnerIdOrExpenseListSharedWithIdOrderByTimestampDescIdDesc(
|
||||
eq(1L), eq(1L), any(Pageable.class)))
|
||||
.thenReturn(new PageImpl<>(List.of(entry)));
|
||||
|
||||
List<RecentHistoryEntryDto> result = service.getRecentForUser(alice, 4);
|
||||
|
||||
assertThat(result).containsExactly(new RecentHistoryEntryDto(
|
||||
"UPDATED", "alice", "Groceries",
|
||||
java.time.LocalDateTime.of(2026, 7, 6, 12, 0), 10L, "Trip to Rome"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getRecentForUser_nullActor_mapsToNullUsername() {
|
||||
AppUser alice = user(1L, "alice");
|
||||
ExpenseList list = new ExpenseList();
|
||||
list.setId(10L);
|
||||
list.setName("Trip to Rome");
|
||||
ExpenseHistoryEntry entry = historyEntry(100L, list, null,
|
||||
HistoryEntryType.CREATED, "Taxi", java.time.LocalDateTime.of(2026, 7, 6, 12, 0));
|
||||
|
||||
when(historyRepository
|
||||
.findByExpenseListOwnerIdOrExpenseListSharedWithIdOrderByTimestampDescIdDesc(
|
||||
eq(1L), eq(1L), any(Pageable.class)))
|
||||
.thenReturn(new PageImpl<>(List.of(entry)));
|
||||
|
||||
List<RecentHistoryEntryDto> result = service.getRecentForUser(alice, 4);
|
||||
|
||||
assertThat(result.get(0).actorUsername()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void getRecentForUser_clampsLimitBetween1And20() {
|
||||
AppUser alice = user(1L, "alice");
|
||||
when(historyRepository
|
||||
.findByExpenseListOwnerIdOrExpenseListSharedWithIdOrderByTimestampDescIdDesc(
|
||||
eq(1L), eq(1L), any(Pageable.class)))
|
||||
.thenReturn(new PageImpl<>(List.of()));
|
||||
|
||||
service.getRecentForUser(alice, 500);
|
||||
verify(historyRepository)
|
||||
.findByExpenseListOwnerIdOrExpenseListSharedWithIdOrderByTimestampDescIdDesc(
|
||||
1L, 1L, PageRequest.of(0, 20));
|
||||
|
||||
service.getRecentForUser(alice, 0);
|
||||
verify(historyRepository)
|
||||
.findByExpenseListOwnerIdOrExpenseListSharedWithIdOrderByTimestampDescIdDesc(
|
||||
1L, 1L, PageRequest.of(0, 1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
build.artifact=xpensely-server
|
||||
build.group=de.zendric.app
|
||||
build.name=XpenselyServer
|
||||
build.time=2026-01-01T00\:00\:00.000Z
|
||||
build.version=test
|
||||
@@ -0,0 +1,10 @@
|
||||
# H2 in-memory database replaces PostgreSQL for integration tests
|
||||
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;MODE=PostgreSQL
|
||||
spring.datasource.driver-class-name=org.h2.Driver
|
||||
spring.datasource.username=sa
|
||||
spring.datasource.password=
|
||||
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
|
||||
spring.jpa.hibernate.ddl-auto=create-drop
|
||||
|
||||
# Placeholder URI — TestJwtDecoderConfig overrides the decoder bean so this URI is never fetched
|
||||
spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://placeholder.invalid/jwks
|
||||
Reference in New Issue
Block a user