initial commit

This commit is contained in:
Urban Modig
2026-03-22 16:36:05 +01:00
parent 67a2cd4290
commit 2c93f6777b
54 changed files with 9822 additions and 0 deletions

BIN
.DS_Store vendored Normal file

Binary file not shown.

8
.idea/.gitignore generated vendored Normal file
View File

@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

9
.idea/householdmanager.iml generated Normal file
View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

5
.idea/misc.xml generated Normal file
View File

@ -0,0 +1,5 @@
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="temurin-21" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

8
.idea/modules.xml generated Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/householdmanager.iml" filepath="$PROJECT_DIR$/.idea/householdmanager.iml" />
</modules>
</component>
</project>

9
backend/.dockerignore Normal file
View File

@ -0,0 +1,9 @@
target/
.mvn/
mvnw
mvnw.cmd
.git/
.gitignore
.idea/
.vscode/
*.log

2
backend/.gitattributes vendored Normal file
View File

@ -0,0 +1,2 @@
/mvnw text eol=lf
*.cmd text eol=crlf

33
backend/.gitignore vendored Normal file
View File

@ -0,0 +1,33 @@
HELP.md
target/
.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/

View File

@ -0,0 +1,3 @@
wrapperVersion=3.3.4
distributionType=only-script
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.12/apache-maven-3.9.12-bin.zip

16
backend/Dockerfile Normal file
View File

@ -0,0 +1,16 @@
# Build stage
FROM maven:3.9.9-eclipse-temurin-21-alpine AS build
WORKDIR /app
COPY pom.xml .
# Download dependencies first for caching
RUN mvn dependency:go-offline
COPY src ./src
# Build the application - this includes code generation from OpenAPI spec
RUN mvn clean package -DskipTests
# Run stage
FROM eclipse-temurin:21-jre-alpine
WORKDIR /app
COPY --from=build /app/target/*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]

295
backend/mvnw vendored Executable file
View File

@ -0,0 +1,295 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version 3.3.4
#
# Optional ENV vars
# -----------------
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
# MVNW_REPOURL - repo url base for downloading maven distribution
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
# ----------------------------------------------------------------------------
set -euf
[ "${MVNW_VERBOSE-}" != debug ] || set -x
# OS specific support.
native_path() { printf %s\\n "$1"; }
case "$(uname)" in
CYGWIN* | MINGW*)
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
native_path() { cygpath --path --windows "$1"; }
;;
esac
# set JAVACMD and JAVACCMD
set_java_home() {
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
if [ -n "${JAVA_HOME-}" ]; then
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
JAVACCMD="$JAVA_HOME/jre/sh/javac"
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACCMD="$JAVA_HOME/bin/javac"
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
return 1
fi
fi
else
JAVACMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v java
)" || :
JAVACCMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v javac
)" || :
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
return 1
fi
fi
}
# hash string like Java String::hashCode
hash_string() {
str="${1:-}" h=0
while [ -n "$str" ]; do
char="${str%"${str#?}"}"
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
str="${str#?}"
done
printf %x\\n $h
}
verbose() { :; }
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
die() {
printf %s\\n "$1" >&2
exit 1
}
trim() {
# MWRAPPER-139:
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
# Needed for removing poorly interpreted newline sequences when running in more
# exotic environments such as mingw bash on Windows.
printf "%s" "${1}" | tr -d '[:space:]'
}
scriptDir="$(dirname "$0")"
scriptName="$(basename "$0")"
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
while IFS="=" read -r key value; do
case "${key-}" in
distributionUrl) distributionUrl=$(trim "${value-}") ;;
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
esac
done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties"
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
case "${distributionUrl##*/}" in
maven-mvnd-*bin.*)
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
*)
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
distributionPlatform=linux-amd64
;;
esac
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
;;
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
esac
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
distributionUrlName="${distributionUrl##*/}"
distributionUrlNameMain="${distributionUrlName%.*}"
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
exec_maven() {
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
}
if [ -d "$MAVEN_HOME" ]; then
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
exec_maven "$@"
fi
case "${distributionUrl-}" in
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
esac
# prepare tmp dir
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
trap clean HUP INT TERM EXIT
else
die "cannot create temp dir"
fi
mkdir -p -- "${MAVEN_HOME%/*}"
# Download and Install Apache Maven
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
verbose "Downloading from: $distributionUrl"
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
# select .zip or .tar.gz
if ! command -v unzip >/dev/null; then
distributionUrl="${distributionUrl%.zip}.tar.gz"
distributionUrlName="${distributionUrl##*/}"
fi
# verbose opt
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
# normalize http auth
case "${MVNW_PASSWORD:+has-password}" in
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
esac
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
verbose "Found wget ... using wget"
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
verbose "Found curl ... using curl"
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
elif set_java_home; then
verbose "Falling back to use Java to download"
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
cat >"$javaSource" <<-END
public class Downloader extends java.net.Authenticator
{
protected java.net.PasswordAuthentication getPasswordAuthentication()
{
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
}
public static void main( String[] args ) throws Exception
{
setDefault( new Downloader() );
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
}
}
END
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
verbose " - Compiling Downloader.java ..."
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
verbose " - Running Downloader.java ..."
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
fi
# If specified, validate the SHA-256 sum of the Maven distribution zip file
if [ -n "${distributionSha256Sum-}" ]; then
distributionSha256Result=false
if [ "$MVN_CMD" = mvnd.sh ]; then
echo "Checksum validation is not supported for maven-mvnd." >&2
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
elif command -v sha256sum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then
distributionSha256Result=true
fi
elif command -v shasum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
distributionSha256Result=true
fi
else
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
fi
if [ $distributionSha256Result = false ]; then
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
exit 1
fi
fi
# unzip and move
if command -v unzip >/dev/null; then
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
else
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
fi
# Find the actual extracted directory name (handles snapshots where filename != directory name)
actualDistributionDir=""
# First try the expected directory name (for regular distributions)
if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then
if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then
actualDistributionDir="$distributionUrlNameMain"
fi
fi
# If not found, search for any directory with the Maven executable (for snapshots)
if [ -z "$actualDistributionDir" ]; then
# enable globbing to iterate over items
set +f
for dir in "$TMP_DOWNLOAD_DIR"/*; do
if [ -d "$dir" ]; then
if [ -f "$dir/bin/$MVN_CMD" ]; then
actualDistributionDir="$(basename "$dir")"
break
fi
fi
done
set -f
fi
if [ -z "$actualDistributionDir" ]; then
verbose "Contents of $TMP_DOWNLOAD_DIR:"
verbose "$(ls -la "$TMP_DOWNLOAD_DIR")"
die "Could not find Maven distribution directory in extracted archive"
fi
verbose "Found extracted Maven distribution directory: $actualDistributionDir"
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url"
mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
clean || :
exec_maven "$@"

189
backend/mvnw.cmd vendored Normal file
View File

@ -0,0 +1,189 @@
<# : batch portion
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.3.4
@REM
@REM Optional ENV vars
@REM MVNW_REPOURL - repo url base for downloading maven distribution
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
@REM ----------------------------------------------------------------------------
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
@SET __MVNW_CMD__=
@SET __MVNW_ERROR__=
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
@SET PSModulePath=
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
)
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
@SET __MVNW_PSMODULEP_SAVE=
@SET __MVNW_ARG0_NAME__=
@SET MVNW_USERNAME=
@SET MVNW_PASSWORD=
@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*)
@echo Cannot start maven from wrapper >&2 && exit /b 1
@GOTO :EOF
: end batch / begin powershell #>
$ErrorActionPreference = "Stop"
if ($env:MVNW_VERBOSE -eq "true") {
$VerbosePreference = "Continue"
}
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
if (!$distributionUrl) {
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
}
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
"maven-mvnd-*" {
$USE_MVND = $true
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
$MVN_CMD = "mvnd.cmd"
break
}
default {
$USE_MVND = $false
$MVN_CMD = $script -replace '^mvnw','mvn'
break
}
}
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
if ($env:MVNW_REPOURL) {
$MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" }
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')"
}
$distributionUrlName = $distributionUrl -replace '^.*/',''
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
$MAVEN_M2_PATH = "$HOME/.m2"
if ($env:MAVEN_USER_HOME) {
$MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
}
if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
}
$MAVEN_WRAPPER_DISTS = $null
if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) {
$MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists"
} else {
$MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists"
}
$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain"
$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
exit $?
}
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
}
# prepare tmp dir
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
trap {
if ($TMP_DOWNLOAD_DIR.Exists) {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
}
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
# Download and Install Apache Maven
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
Write-Verbose "Downloading from: $distributionUrl"
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
$webclient = New-Object System.Net.WebClient
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
# If specified, validate the SHA-256 sum of the Maven distribution zip file
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
if ($distributionSha256Sum) {
if ($USE_MVND) {
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
}
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
}
}
# unzip and move
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
# Find the actual extracted directory name (handles snapshots where filename != directory name)
$actualDistributionDir = ""
# First try the expected directory name (for regular distributions)
$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain"
$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD"
if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) {
$actualDistributionDir = $distributionUrlNameMain
}
# If not found, search for any directory with the Maven executable (for snapshots)
if (!$actualDistributionDir) {
Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object {
$testPath = Join-Path $_.FullName "bin/$MVN_CMD"
if (Test-Path -Path $testPath -PathType Leaf) {
$actualDistributionDir = $_.Name
}
}
}
if (!$actualDistributionDir) {
Write-Error "Could not find Maven distribution directory in extracted archive"
}
Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir"
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null
try {
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
} catch {
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
Write-Error "fail to move MAVEN_HOME"
}
} finally {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"

151
backend/pom.xml Normal file
View File

@ -0,0 +1,151 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.0.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.21.1</version>
</dependency>
<dependency>
<groupId>tools.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>3.1.0</version>
</dependency>
</dependencies>
</dependencyManagement>
<groupId>se.urmo</groupId>
<artifactId>householdmanager</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>backend</name>
<description>backend</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>21</java.version>
<jackson-databind-nullable.version>0.2.6</jackson-databind-nullable.version>
<swagger-annotations.version>2.2.22</swagger-annotations.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>io.swagger.core.v3</groupId>
<artifactId>swagger-annotations</artifactId>
<version>${swagger-annotations.version}</version>
</dependency>
<dependency>
<groupId>org.openapitools</groupId>
<artifactId>jackson-databind-nullable</artifactId>
<version>${jackson-databind-nullable.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
<plugin>
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<version>7.10.0</version>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<inputSpec>
${project.basedir}/src/main/resources/openapi/hemkoll-api.yml
</inputSpec>
<generatorName>spring</generatorName>
<library>spring-boot</library>
<apiPackage>se.urmo.householdmanager.api</apiPackage>
<modelPackage>se.urmo.householdmanager.model</modelPackage>
<invokerPackage>se.urmo.householdmanager.invoker</invokerPackage>
<configOptions>
<interfaceOnly>true</interfaceOnly>
<useSpringBoot3>true</useSpringBoot3>
<dateLibrary>java8</dateLibrary>
<useTags>false</useTags>
<openApiNullable>false</openApiNullable>
</configOptions>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,13 @@
package se.urmo.householdmanager;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BackendApplication {
public static void main(String[] args) {
SpringApplication.run(BackendApplication.class, args);
}
}

View File

@ -0,0 +1,15 @@
package se.urmo.householdmanager.health;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
public class HealthController {
@GetMapping("/health")
public Map<String, String> health() {
return Map.of("status", "ok");
}
}

View File

@ -0,0 +1,53 @@
package se.urmo.householdmanager.impl;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;
import se.urmo.householdmanager.api.TasksApi;
import se.urmo.householdmanager.model.*;
import se.urmo.householdmanager.service.TaskService;
import java.util.List;
import java.util.NoSuchElementException;
@RestController
public class TasksApiImpl implements TasksApi {
private final TaskService taskService;
public TasksApiImpl(TaskService taskService) {
this.taskService = taskService;
}
@Override
public ResponseEntity<List<Task>> tasksGet() {
return ResponseEntity.ok(taskService.getAll());
}
@Override
public ResponseEntity<Task> tasksPost(TaskCreate taskCreate) {
return ResponseEntity.ok(taskService.create(taskCreate));
}
@Override
public ResponseEntity<Void> tasksIdPatch(Integer id, TaskUpdate taskUpdate) {
try {
taskService.update(id, taskUpdate);
return ResponseEntity.ok().build();
} catch (NoSuchElementException e) {
return ResponseEntity.notFound().build();
} catch (IllegalArgumentException e) {
return ResponseEntity.badRequest().build();
}
}
@Override
public ResponseEntity<Void> tasksIdDelete(Integer id) {
try {
taskService.delete(id);
return ResponseEntity.ok().build();
} catch (NoSuchElementException e) {
return ResponseEntity.notFound().build();
}
}
}

View File

@ -0,0 +1,44 @@
package se.urmo.householdmanager.impl;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;
import se.urmo.householdmanager.api.UsersApi;
import se.urmo.householdmanager.model.LeaderboardEntry;
import se.urmo.householdmanager.model.User;
import se.urmo.householdmanager.model.UserCreate;
import se.urmo.householdmanager.service.TaskService;
import se.urmo.householdmanager.service.UserService;
import java.util.List;
@RestController
public class UsersApiImpl implements UsersApi {
private final UserService userService;
private final TaskService taskService;
public UsersApiImpl(UserService userService, TaskService taskService) {
this.userService = userService;
this.taskService = taskService;
}
@Override
public ResponseEntity<List<User>> usersGet() {
return ResponseEntity.ok(userService.getAll());
}
@Override
public ResponseEntity<User> usersPost(UserCreate userCreate) {
try {
return ResponseEntity.ok(userService.create(userCreate));
} catch (IllegalArgumentException e) {
return ResponseEntity.badRequest().build();
}
}
@Override
public ResponseEntity<List<LeaderboardEntry>> usersLeaderboardGet() {
return ResponseEntity.ok(userService.getLeaderboard(taskService.getAll()));
}
}

View File

@ -0,0 +1,16 @@
package se.urmo.householdmanager.service;
import se.urmo.householdmanager.model.*;
import java.util.List;
public interface TaskService {
List<Task> getAll();
Task create(TaskCreate request);
void update(Integer id, TaskUpdate update);
void delete(Integer id);
}

View File

@ -0,0 +1,17 @@
package se.urmo.householdmanager.service;
import se.urmo.householdmanager.model.LeaderboardEntry;
import se.urmo.householdmanager.model.Task;
import se.urmo.householdmanager.model.User;
import se.urmo.householdmanager.model.UserCreate;
import java.util.List;
public interface UserService {
List<User> getAll();
User create(UserCreate request);
List<LeaderboardEntry> getLeaderboard(List<Task> tasks);
}

View File

@ -0,0 +1,192 @@
package se.urmo.householdmanager.service.impl;
import org.springframework.stereotype.Service;
import se.urmo.householdmanager.model.Task;
import se.urmo.householdmanager.model.TaskCreate;
import se.urmo.householdmanager.model.TaskStatus;
import se.urmo.householdmanager.model.TaskUpdate;
import se.urmo.householdmanager.service.TaskService;
import se.urmo.householdmanager.service.UserService;
import se.urmo.householdmanager.model.User;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
@Service
public class InMemoryTaskService implements TaskService {
private final List<Task> tasks = new ArrayList<>();
private final AtomicInteger idCounter = new AtomicInteger();
private final UserService userService;
public InMemoryTaskService(UserService userService) {
this.userService = userService;
}
@Override
public List<Task> getAll() {
tasks.forEach(this::populateUserFields);
return tasks;
}
private void populateUserFields(Task task) {
if (task.getUserId() != null) {
Optional<User> userOpt = userService.getAll().stream()
.filter(u -> u.getId().equals(task.getUserId()))
.findFirst();
userOpt.ifPresent(user -> {
task.setUserName(user.getName());
task.setUserColor(user.getColor());
task.setUserAvatar(user.getAvatar());
});
} else {
task.setUserName(null);
task.setUserColor(null);
task.setUserAvatar(null);
}
}
@Override
public Task create(TaskCreate request) {
Task task = new Task();
task.setId(idCounter.incrementAndGet());
task.setTitle(request.getTitle());
task.setDescription(request.getDescription());
task.setStatus(
request.getStatus() != null
? request.getStatus()
: TaskStatus.PENDING
);
task.setPoints(request.getPoints() != null ? request.getPoints() : 0);
task.setUserId(request.getUserId());
task.setIsRecurring(request.getIsRecurring() != null && request.getIsRecurring());
task.setRecurrencePeriod(
request.getRecurrencePeriod()
);
task.setDueDate(
request.getDueDate()
);
task.setCreatedAt(OffsetDateTime.now());
populateUserFields(task);
tasks.add(task);
return task;
}
@Override
public void update(Integer id, TaskUpdate update) {
Task task = tasks.stream()
.filter(t -> t.getId().equals(id))
.findFirst()
.orElseThrow(() -> new NoSuchElementException("Task not found"));
// Update simple fields
if (update.getTitle() != null) {
task.setTitle(update.getTitle());
}
if (update.getDescription() != null) {
task.setDescription(update.getDescription());
}
if (update.getPoints() != null) {
task.setPoints(update.getPoints());
}
if (update.getIsRecurring() != null) {
task.setIsRecurring(update.getIsRecurring());
}
if (update.getRecurrencePeriod() != null) {
task.setRecurrencePeriod(update.getRecurrencePeriod());
}
if (update.getDueDate() != null) {
task.setDueDate(update.getDueDate());
}
// Handle assignment/unassignment
if (Boolean.TRUE.equals(update.getUnassignUser())) {
task.setUserId(null);
populateUserFields(task);
} else if (update.getUserId() != null) {
task.setUserId(update.getUserId());
populateUserFields(task);
}
// Update status and handle recurrence logic
if (update.getStatus() != null) {
TaskStatus newStatus = update.getStatus();
if (newStatus == TaskStatus.IN_PROGRESS && task.getUserId() == null) {
throw new IllegalArgumentException("Task must have user to be in_progress");
}
// Check if completing a recurring task
if (newStatus == TaskStatus.COMPLETED &&
task.getStatus() != TaskStatus.COMPLETED &&
Boolean.TRUE.equals(task.getIsRecurring())) {
createNextRecurringTask(task);
}
task.setStatus(newStatus);
}
}
private void createNextRecurringTask(Task completedTask) {
TaskCreate newTask = new TaskCreate();
newTask.setTitle(completedTask.getTitle());
newTask.setDescription(completedTask.getDescription());
newTask.setPoints(completedTask.getPoints());
// Unassign user for the new task
newTask.setUserId(null);
newTask.setIsRecurring(true);
newTask.setRecurrencePeriod(completedTask.getRecurrencePeriod());
newTask.setStatus(TaskStatus.PENDING);
if (completedTask.getDueDate() != null && completedTask.getRecurrencePeriod() != null) {
LocalDate oldDate = completedTask.getDueDate();
LocalDate newDate = oldDate;
switch (completedTask.getRecurrencePeriod()) {
case DAILY:
newDate = oldDate.plusDays(1);
break;
case WEEKLY:
newDate = oldDate.plusWeeks(1);
break;
case BIWEEKLY:
newDate = oldDate.plusWeeks(2);
break;
case MONTHLY:
newDate = oldDate.plusMonths(1);
break;
}
newTask.setDueDate(newDate);
}
create(newTask);
}
@Override
public void delete(Integer id) {
boolean removed = tasks.removeIf(t -> t.getId().equals(id));
if (!removed) {
throw new NoSuchElementException("Task not found");
}
}
}

View File

@ -0,0 +1,76 @@
package se.urmo.householdmanager.service.impl;
import org.springframework.stereotype.Service;
import se.urmo.householdmanager.model.LeaderboardEntry;
import se.urmo.householdmanager.model.Task;
import se.urmo.householdmanager.model.TaskStatus;
import se.urmo.householdmanager.model.User;
import se.urmo.householdmanager.model.UserCreate;
import se.urmo.householdmanager.service.UserService;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
@Service
public class InMemoryUserService implements UserService {
private final List<User> users = new ArrayList<>();
private final AtomicInteger idCounter = new AtomicInteger();
public InMemoryUserService() {
// No-arg constructor
}
@Override
public List<User> getAll() {
return users;
}
@Override
public User create(UserCreate request) {
boolean exists = users.stream()
.anyMatch(u -> u.getName().equalsIgnoreCase(request.getName()));
if (exists) {
throw new IllegalArgumentException("User already exists");
}
User user = new User();
user.setId(idCounter.incrementAndGet());
user.setName(request.getName());
user.setColor(request.getColor());
user.setAvatar(
request.getAvatar() != null
? request.getAvatar()
: "UserIcon"
);
users.add(user);
return user;
}
@Override
public List<LeaderboardEntry> getLeaderboard(List<Task> tasks) {
Map<Integer, Integer> userScores = tasks.stream()
.filter(task -> task.getStatus() == TaskStatus.COMPLETED && task.getUserId() != null)
.collect(Collectors.groupingBy(
task -> task.getUserId(),
Collectors.summingInt(task -> task.getPoints())
));
return getAll().stream()
.map(user -> {
LeaderboardEntry entry = new LeaderboardEntry();
entry.setUsername(user.getName());
entry.setTotalPoints(userScores.getOrDefault(user.getId(), 0));
return entry;
})
.sorted(Comparator.comparingInt(LeaderboardEntry::getTotalPoints).reversed())
.collect(Collectors.toList());
}
}

View File

@ -0,0 +1,8 @@
spring.application.name=backend
server.port=8080
# Use context-path to prefix all generated API endpoints with /api as defined in the OpenAPI spec
server.servlet.context-path=/api
logging.level.root=DEBUG
management.endpoints.web.exposure.include=health,info

View File

@ -0,0 +1,273 @@
openapi: 3.0.0
info:
title: HemKoll API
description: Backend API for the HemKoll household task management application.
version: 1.0.0
servers:
- url: /api
description: Local development server
paths:
/users:
get:
summary: List all users
description: Returns a list of all registered household members.
responses:
'200':
description: A list of users
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
post:
summary: Create a new user
description: Registers a new household member with a name, color, and avatar.
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/UserCreate'
responses:
'200':
description: User created successfully
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'400':
description: User already exists or validation failed
/users/leaderboard:
get:
summary: Get the leaderboard
description: Returns a list of users sorted by their total points.
responses:
'200':
description: A list of leaderboard entries
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/LeaderboardEntry'
/tasks:
get:
summary: List all tasks
description: Returns all tasks, including details about assigned users.
responses:
'200':
description: A list of tasks
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Task'
post:
summary: Create a new task
description: Adds a new task to the list.
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/TaskCreate'
responses:
'200':
description: Task created successfully
content:
application/json:
schema:
$ref: '#/components/schemas/Task'
/tasks/{id}:
patch:
summary: Update a task
description: Updates specific fields of a task, such as status or assigned user.
parameters:
- name: id
in: path
required: true
description: The ID of the task to update
schema:
type: integer
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/TaskUpdate'
responses:
'200':
description: Task updated successfully
'400':
description: Validation error (e.g., moving a task to 'in_progress' without a user)
'404':
description: Task not found
delete:
summary: Delete a task
description: Permanently removes a task from the system.
parameters:
- name: id
in: path
required: true
description: The ID of the task to delete
schema:
type: integer
responses:
'200':
description: Task deleted successfully
'404':
description: Task not found
components:
schemas:
User:
type: object
description: A household member.
properties:
id:
type: integer
description: Unique identifier for the user.
name:
type: string
description: The user's display name.
color:
type: string
description: Tailwind CSS background color class (e.g., 'bg-blue-500').
avatar:
type: string
description: The name of the avatar icon (e.g., 'Cat', 'Pizza').
default: UserIcon
UserCreate:
type: object
required:
- name
- color
properties:
name:
type: string
description: The user's display name.
color:
type: string
description: Tailwind CSS background color class.
avatar:
type: string
description: The name of the avatar icon.
default: UserIcon
Task:
type: object
description: A household chore or task.
properties:
id:
type: integer
description: Unique identifier for the task.
title:
type: string
description: Short title of the task.
description:
type: string
description: Detailed description of the task.
status:
$ref: '#/components/schemas/TaskStatus'
points:
type: integer
description: Reward points for completing the task.
user_id:
type: integer
description: ID of the assigned user.
user_name:
type: string
description: Name of the assigned user (joined from users table).
user_color:
type: string
description: Color of the assigned user.
user_avatar:
type: string
description: Avatar of the assigned user.
is_recurring:
type: boolean
description: Whether the task should repeat automatically.
recurrence_period:
$ref: '#/components/schemas/RecurrencePeriod'
due_date:
type: string
format: date
description: Deadline for the task.
created_at:
type: string
format: date-time
description: When the task was first created.
TaskCreate:
type: object
required:
- title
properties:
title:
type: string
description: Title of the task.
description:
type: string
description: Detailed description.
status:
$ref: '#/components/schemas/TaskStatus'
points:
type: integer
default: 0
user_id:
type: integer
is_recurring:
type: boolean
default: false
recurrence_period:
$ref: '#/components/schemas/RecurrencePeriod'
due_date:
type: string
format: date
TaskUpdate:
type: object
description: Fields that can be updated on a task.
properties:
title:
type: string
description:
type: string
status:
$ref: '#/components/schemas/TaskStatus'
points:
type: integer
user_id:
type: integer
unassign_user:
type: boolean
default: false
is_recurring:
type: boolean
recurrence_period:
$ref: '#/components/schemas/RecurrencePeriod'
due_date:
type: string
format: date
LeaderboardEntry:
type: object
properties:
username:
type: string
totalPoints:
type: integer
RecurrencePeriod:
type: string
enum: [ daily, weekly, biweekly, monthly ]
TaskStatus:
type: string
enum: [ pending, in_progress, completed ]

View File

@ -0,0 +1,13 @@
package se.urmo.householdmanager;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class BackendApplicationTests {
@Test
void contextLoads() {
}
}

17
backend/task.http Normal file
View File

@ -0,0 +1,17 @@
### Create a task
POST http://localhost:8080/api/tasks
Content-Type: application/json
{
"title": "Clean the kitchen",
"points": 10,
"status": "väntande",
"recurrence": "weekly",
"dueDate": "2026-03-01"
}
### Retrieve all tasks
GET http://localhost:8080/api/tasks
### Retrieve all tasks
GET http://localhost:8080/api/health

12
backend/user.http Normal file
View File

@ -0,0 +1,12 @@
### Create a user
POST http://localhost:8080/api/users
Content-Type: application/json
{
"name": "John Doe",
"avatar": "https://api.dicebear.com/7.x/avataaars/svg?seed=John"
}
### Fetch users
GET http://localhost:8080/api/users

16
docker-compose.yml Normal file
View File

@ -0,0 +1,16 @@
services:
backend:
build:
context: ./backend
ports:
- "8080:8080"
container_name: householdmanager-backend
frontend:
build:
context: ./frontend
ports:
- "3000:3000"
container_name: householdmanager-frontend
environment:
- VITE_API_BASE_URL=http://backend:8080

5
frontend/.dockerignore Normal file
View File

@ -0,0 +1,5 @@
node_modules
dist
tasks.db
.git
.DS_Store

10
frontend/.env Normal file
View File

@ -0,0 +1,10 @@
# Uncomment the line corresponding to the backend you want to use
# 1. Fake backend (server.ts) - Default
# VITE_API_BASE_URL=
# 2. Local backend
VITE_API_BASE_URL=http://localhost:3000
# 3. Production backend
# VITE_API_BASE_URL=https://rubble.se/householdmanager

24
frontend/.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

48
frontend/Dockerfile Normal file
View File

@ -0,0 +1,48 @@
# Build stage
FROM node:22-slim AS builder
WORKDIR /app
# Copy package files
COPY package.json package-lock.json ./
# Install all dependencies
RUN npm ci
# Copy the rest of the source
COPY . .
# Build the frontend (creates the 'dist' folder)
RUN npm run build
# Runtime stage
FROM node:22-slim
# Install sqlite3 runtime dependencies
RUN apt-get update && apt-get install -y python3 make g++ && rm -rf /var/lib/apt/lists/*
WORKDIR /app
# Copy package files
COPY package.json package-lock.json ./
# Install only production dependencies (better-sqlite3 needs compilation)
RUN npm ci --only=production && npm install -g tsx
# Copy built frontend from builder stage
COPY --from=builder /app/dist ./dist
# Copy the server file and other necessary source
COPY server.ts ./
# (If there are other source files needed by server.ts, they should be copied too)
# Looking at server.ts, it doesn't seem to import other local files besides 'vite'
# but wait, it uses 'path' and 'url' (built-in).
# Expose the port the app runs on
EXPOSE 3000
# Set environment to production
ENV NODE_ENV=production
# Command to run the server
CMD ["tsx", "server.ts"]

73
frontend/README.md Normal file
View File

@ -0,0 +1,73 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```

23
frontend/eslint.config.js Normal file
View File

@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])

9
frontend/frontend.iml Normal file
View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

13
frontend/index.html Normal file
View File

@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>my-app</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

6675
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

43
frontend/package.json Normal file
View File

@ -0,0 +1,43 @@
{
"name": "my-app",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "tsx server.ts",
"build": "tsc && vite build",
"lint": "eslint .",
"preview": "vite preview",
"start": "node server.ts"
},
"dependencies": {
"@tailwindcss/vite": "^4.2.1",
"axios": "^1.7.2",
"better-sqlite3": "^12.6.2",
"express": "^5.2.1",
"http-proxy-middleware": "^3.0.5",
"lucide-react": "^0.575.0",
"motion": "^12.34.3",
"react": "^19.2.0",
"react-dom": "^19.2.0",
"react-markdown": "^10.1.0"
},
"devDependencies": {
"@eslint/js": "^9.39.1",
"@types/better-sqlite3": "^7.6.13",
"@types/express": "^5.0.6",
"@types/http-proxy-middleware": "^0.19.3",
"@types/node": "^24.10.1",
"@types/react": "^19.2.7",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^5.1.4",
"eslint": "^9.39.1",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.4.24",
"globals": "^16.5.0",
"tsx": "^4.21.0",
"typescript": "~5.9.3",
"typescript-eslint": "^8.48.0",
"vite": "^7.3.1"
}
}

1
frontend/public/vite.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

139
frontend/server.ts Normal file
View File

@ -0,0 +1,139 @@
import express from "express";
import { createServer as createViteServer } from "vite";
import { createProxyMiddleware } from "http-proxy-middleware";
import Database from "better-sqlite3";
import path from "path";
import { fileURLToPath } from "url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const db = new Database("tasks.db");
// Initiera databasen
db.exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
color TEXT NOT NULL,
avatar TEXT DEFAULT 'UserIcon'
);
CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
description TEXT,
status TEXT NOT NULL CHECK (status IN ('pending', 'in_progress', 'completed')),
points INTEGER DEFAULT 0,
user_id INTEGER,
is_recurring BOOLEAN DEFAULT 0,
recurrence_period TEXT,
due_date DATETIME,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id)
);
`);
// Migreringar (för säkerhets skull)
try { db.prepare("ALTER TABLE tasks ADD COLUMN recurrence_period TEXT").run(); } catch (e) {}
try { db.prepare("ALTER TABLE users ADD COLUMN avatar TEXT DEFAULT 'UserIcon'").run(); } catch (e) {}
async function startServer() {
const app = express();
const BACKEND_URL = process.env.VITE_API_BASE_URL;
if (BACKEND_URL) {
console.log(`Proxying /api requests to ${BACKEND_URL}`);
app.use(createProxyMiddleware({
target: BACKEND_URL,
changeOrigin: true,
pathFilter: "/api",
}));
}
app.use(express.json());
// API-rutter
app.get("/api/users", (req, res) => {
const users = db.prepare("SELECT * FROM users").all();
res.json(users);
});
app.post("/api/users", (req, res) => {
const { name, color, avatar } = req.body;
try {
const info = db.prepare("INSERT INTO users (name, color, avatar) VALUES (?, ?, ?)").run(name, color, avatar || 'UserIcon');
res.json({ id: info.lastInsertRowid, name, color, avatar: avatar || 'UserIcon' });
} catch (e) {
res.status(400).json({ error: "Användaren finns redan" });
}
});
app.get("/api/tasks", (req, res) => {
const tasks = db.prepare(`
SELECT tasks.*, users.name as user_name, users.color as user_color, users.avatar as user_avatar
FROM tasks
LEFT JOIN users ON tasks.user_id = users.id
`).all();
res.json(tasks);
});
app.post("/api/tasks", (req, res) => {
const { title, description, status, points, user_id, is_recurring, recurrence_period, due_date } = req.body;
const info = db.prepare(`
INSERT INTO tasks (title, description, status, points, user_id, is_recurring, recurrence_period, due_date)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
`).run(title, description, status || 'pending', points || 0, user_id || null, is_recurring ? 1 : 0, recurrence_period || null, due_date || null);
res.json({ id: info.lastInsertRowid, ...req.body });
});
app.patch("/api/tasks/:id", (req, res) => {
const { id } = req.params;
const { status, user_id } = req.body;
const existingTask = db.prepare("SELECT * FROM tasks WHERE id = ?").get(id) as any;
if (!existingTask) return res.status(404).json({ error: "Hittade inte uppgiften" });
const updates = Object.keys(req.body).map(key => `${key} = ?`).join(", ");
const values = Object.values(req.body);
db.prepare(`UPDATE tasks SET ${updates} WHERE id = ?`).run(...values, id);
if (status === 'completed' && existingTask.is_recurring && existingTask.recurrence_period && existingTask.due_date) {
const nextDueDate = new Date(existingTask.due_date);
if (existingTask.recurrence_period === 'daily') nextDueDate.setDate(nextDueDate.getDate() + 1);
else if (existingTask.recurrence_period === 'weekly') nextDueDate.setDate(nextDueDate.getDate() + 7);
else if (existingTask.recurrence_period === 'biweekly') nextDueDate.setDate(nextDueDate.getDate() + 14);
else if (existingTask.recurrence_period === 'monthly') nextDueDate.setMonth(nextDueDate.getMonth() + 1);
db.prepare(`
INSERT INTO tasks (title, description, status, points, user_id, is_recurring, recurrence_period, due_date)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
`).run(existingTask.title, existingTask.description, 'pending', existingTask.points, null, 1, existingTask.recurrence_period, nextDueDate.toISOString());
}
res.json({ success: true });
});
app.delete("/api/tasks/:id", (req, res) => {
db.prepare("DELETE FROM tasks WHERE id = ?").run(req.params.id);
res.json({ success: true });
});
// Vite integration
if (process.env.NODE_ENV !== "production") {
const vite = await createViteServer({
server: { middlewareMode: true },
appType: "spa",
});
app.use(vite.middlewares);
} else {
app.use(express.static(path.join(__dirname, "dist")));
app.get("/{*path}", (req: any, res: any) => res.sendFile(path.join(__dirname, "dist", "index.html")));
}
const PORT = 3000;
app.listen(PORT, "0.0.0.0", () => {
console.log(`Server körs på http://localhost:${PORT}`);
});
}
startServer();

42
frontend/src/App.css Normal file
View File

@ -0,0 +1,42 @@
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}

29
frontend/src/App.jsx Normal file
View File

@ -0,0 +1,29 @@
import { useEffect, useState } from 'react';
import apiClient from './api/client';
function App() {
const [currentUser, setCurrentUser] = useState(null);
useEffect(() => {
const verifySession = async () => {
try {
// Anrop till ett endpoint som returnerar nuvarande användare (t.ex. /users/me)
const response = await apiClient.get('/users/me');
setCurrentUser(response.data);
} catch (err) {
// Om detta misslyckas (t.ex. 401), kommer vår interceptor
// att hantera utloggningen automatiskt.
setCurrentUser(null);
}
};
if (localStorage.getItem('user')) {
verifySession();
}
}, []);
return (
/* Din övriga app-kod */
<div>{currentUser ? `Inloggad som: ${currentUser.username}` : 'Ej inloggad'}</div>
);
}

885
frontend/src/App.tsx Normal file
View File

@ -0,0 +1,885 @@
/**
* @license
* SPDX-License-Identifier: Apache-2.0
*/
import React, { useState, useEffect, useCallback } from 'react';
import {
Plus,
Trash2,
User as UserIcon,
CheckCircle2,
Clock,
PlayCircle,
X,
UserPlus,
RefreshCw,
Trophy,
LogOut,
Calendar,
Search,
Smile,
Heart,
Star,
Zap,
Coffee,
Ghost,
Cat,
Dog,
Gamepad2,
Music,
Camera,
Pizza,
ChevronDown,
ChevronUp
} from 'lucide-react';
import { motion, AnimatePresence } from 'motion/react';
import { API_BASE_URL } from './config';
import Leaderboard from './components/Leaderboard';
type Status = 'pending' | 'in_progress' | 'completed';
interface User {
id: number;
name: string;
color: string;
avatar: string;
}
const AVATARS = [
{ name: 'UserIcon', icon: UserIcon },
{ name: 'Smile', icon: Smile },
{ name: 'Heart', icon: Heart },
{ name: 'Star', icon: Star },
{ name: 'Zap', icon: Zap },
{ name: 'Coffee', icon: Coffee },
{ name: 'Ghost', icon: Ghost },
{ name: 'Cat', icon: Cat },
{ name: 'Dog', icon: Dog },
{ name: 'Gamepad2', icon: Gamepad2 },
{ name: 'Music', icon: Music },
{ name: 'Camera', icon: Camera },
{ name: 'Pizza', icon: Pizza },
];
const AvatarRenderer = ({ name, size = 24, className = "" }: { name: string, size?: number, className?: string }) => {
const avatar = AVATARS.find(a => a.name === name) || AVATARS[0];
const Icon = avatar.icon;
return <Icon size={size} className={className} />;
};
interface Task {
id: number;
title: string;
description: string;
status: Status;
points: number;
user_id: number | null;
user_name: string | null;
user_color: string | null;
user_avatar: string | null;
is_recurring: boolean;
recurrence_period: string | null;
due_date: string | null;
}
const COLORS = [
'bg-blue-500', 'bg-emerald-500', 'bg-violet-500',
'bg-amber-500', 'bg-rose-500', 'bg-indigo-500',
'bg-cyan-500', 'bg-orange-500'
];
export default function App() {
const [tasks, setTasks] = useState<Task[]>([]);
const [users, setUsers] = useState<User[]>([]);
const [currentUser, setCurrentUser] = useState<User | null>(() => {
const saved = localStorage.getItem('hemkoll_user');
return saved ? JSON.parse(saved) : null;
});
const [isTaskModalOpen, setIsTaskModalOpen] = useState(false);
const [isUserModalOpen, setIsUserModalOpen] = useState(false);
const [isLeaderboardOpen, setIsLeaderboardOpen] = useState(false);
const [loading, setLoading] = useState(true);
const [searchQuery, setSearchQuery] = useState('');
const [expandedTasks, setExpandedTasks] = useState<Set<number>>(new Set());
const toggleTaskExpansion = (taskId: number) => {
setExpandedTasks(prev => {
const next = new Set(prev);
if (next.has(taskId)) {
next.delete(taskId);
} else {
next.add(taskId);
}
return next;
});
};
// Custom modal states
const [confirmModal, setConfirmModal] = useState<{
isOpen: boolean;
title: string;
message: string;
onConfirm: () => void;
}>({ isOpen: false, title: '', message: '', onConfirm: () => {} });
const [alertModal, setAlertModal] = useState<{
isOpen: boolean;
title: string;
message: string;
}>({ isOpen: false, title: '', message: '' });
const showAlert = (title: string, message: string) => {
setAlertModal({ isOpen: true, title, message });
};
const showConfirm = (title: string, message: string, onConfirm: () => void) => {
setConfirmModal({ isOpen: true, title, message, onConfirm });
};
const getTaskCardColor = (task: Task) => {
if (task.status === 'completed' || !task.due_date) return 'bg-white border-black/5';
const dueDate = new Date(task.due_date);
const now = new Date();
const diffTime = dueDate.getTime() - now.getTime();
const diffDays = diffTime / (1000 * 60 * 60 * 24);
if (diffTime < 0) return 'bg-red-50 border-red-200';
if (diffDays <= 2) return 'bg-orange-50 border-orange-200';
return 'bg-white border-black/5';
};
useEffect(() => {
if (currentUser) {
localStorage.setItem('hemkoll_user', JSON.stringify(currentUser));
} else {
localStorage.removeItem('hemkoll_user');
}
}, [currentUser]);
// New task form state
const [newTask, setNewTask] = useState({
title: '',
description: '',
points: 5,
user_id: null as number | null,
is_recurring: false,
recurrence_period: 'weekly',
due_date: ''
});
// New user form state
const [newUserName, setNewUserName] = useState('');
const [newUserAvatar, setNewUserAvatar] = useState('UserIcon');
const fetchData = useCallback(async () => {
try {
const [tasksRes, usersRes] = await Promise.all([
fetch(`${API_BASE_URL}/api/tasks`),
fetch(`${API_BASE_URL}/api/users`)
]);
const tasksData = await tasksRes.json();
const usersData = await usersRes.json();
setTasks(tasksData);
setUsers(usersData);
} catch (error) {
console.error("Failed to fetch data", error);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchData();
}, [fetchData]);
const handleCreateTask = async (e: React.FormEvent) => {
e.preventDefault();
if (!newTask.title) return;
if (newTask.is_recurring && !newTask.due_date) {
showAlert("Obs!", "En återkommande uppgift måste ha ett förfallodatum.");
return;
}
try {
const res = await fetch(`${API_BASE_URL}/api/tasks`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
...newTask,
status: 'pending',
due_date: newTask.due_date || null,
recurrence_period: newTask.is_recurring ? newTask.recurrence_period : null
})
});
if (res.ok) {
setIsTaskModalOpen(false);
setNewTask({ title: '', description: '', points: 5, user_id: null, is_recurring: false, recurrence_period: 'weekly', due_date: '' });
fetchData();
}
} catch (error) {
console.error("Failed to create task", error);
}
};
const handleCreateUser = async (e: React.FormEvent) => {
e.preventDefault();
if (!newUserName) return;
const color = COLORS[Math.floor(Math.random() * COLORS.length)];
try {
const res = await fetch(`${API_BASE_URL}/api/users`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: newUserName, color, avatar: newUserAvatar })
});
if (res.ok) {
setIsUserModalOpen(false);
setNewUserName('');
setNewUserAvatar('UserIcon');
fetchData();
}
} catch (error) {
console.error("Failed to create user", error);
}
};
const updateTaskStatus = async (taskId: number, newStatus: Status, userId?: number | null) => {
const task = tasks.find(t => t.id === taskId);
if (!task) return;
const effectiveUserId = userId !== undefined ? userId : task.user_id;
if (newStatus === 'in_progress' && !effectiveUserId) {
showAlert("Obs!", "En pågående uppgift måste ha en ansvarig användare!");
return;
}
try {
const res = await fetch(`${API_BASE_URL}/api/tasks/${taskId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ status: newStatus, user_id: effectiveUserId })
});
if (res.ok) {
fetchData();
} else {
const err = await res.json();
showAlert("Ett fel uppstod", err.error || "Kunde inte uppdatera uppgift");
}
} catch (error) {
console.error("Failed to update task", error);
}
};
const deleteTask = async (e: React.MouseEvent, id: number) => {
e.preventDefault();
e.stopPropagation();
showConfirm(
"Radera uppgift",
"Är du säker på att du vill radera denna uppgift? Detta går inte att ångra.",
async () => {
try {
const res = await fetch(`${API_BASE_URL}/api/tasks/${id}`, { method: 'DELETE' });
if (res.ok) {
fetchData();
}
} catch (error) {
console.error("Failed to delete task", error);
}
}
);
};
const onDragStart = (e: React.DragEvent, taskId: number) => {
e.dataTransfer.setData('taskId', taskId.toString());
e.dataTransfer.effectAllowed = 'move';
// Add a ghost image or styling if needed, but standard is fine
// We can also add a class to the body to help with styling during drag
document.body.classList.add('is-dragging');
};
const onDragEnd = () => {
document.body.classList.remove('is-dragging');
};
const onDrop = (e: React.DragEvent, newStatus: Status) => {
e.preventDefault();
const taskIdStr = e.dataTransfer.getData('taskId');
if (!taskIdStr) return;
const taskId = parseInt(taskIdStr);
if (isNaN(taskId)) return;
updateTaskStatus(taskId, newStatus);
};
const onDragOver = (e: React.DragEvent) => {
e.preventDefault();
};
if (!currentUser && !loading) {
if (users.length > 0) {
return (
<div className="min-h-screen bg-[#F5F5F4] flex items-center justify-center p-4 font-sans">
<div className="bg-white p-8 rounded-3xl shadow-sm border border-black/5 w-full max-w-md">
<h1 className="text-3xl font-semibold tracking-tight mb-6 text-center">Vem är du?</h1>
<div className="grid grid-cols-2 gap-4 mb-6">
{users.map(user => (
<button
key={user.id}
onClick={() => setCurrentUser(user)}
className="flex flex-col items-center p-4 rounded-2xl hover:bg-black/5 transition-colors border border-transparent hover:border-black/10"
>
<div className={`w-12 h-12 ${user.color} rounded-full flex items-center justify-center text-white mb-2 shadow-sm`}>
<AvatarRenderer name={user.avatar} size={24} />
</div>
<span className="font-medium text-sm">{user.name}</span>
</button>
))}
</div>
<button
onClick={() => setIsUserModalOpen(true)}
className="w-full py-3 rounded-xl border-2 border-dashed border-black/10 text-black/40 hover:text-black/60 hover:border-black/20 transition-all flex items-center justify-center gap-2"
>
<UserPlus size={20} />
<span>Lägg till användare</span>
</button>
</div>
<AnimatePresence>
{isUserModalOpen && (
<div className="fixed inset-0 bg-black/40 backdrop-blur-sm flex items-center justify-center p-4 z-50">
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.95 }}
className="bg-white p-6 rounded-3xl shadow-xl w-full max-w-sm"
>
<div className="flex justify-between items-center mb-4">
<h2 className="text-xl font-bold">Ny Användare</h2>
<button onClick={() => setIsUserModalOpen(false)} className="p-2 hover:bg-black/5 rounded-full"><X size={20} /></button>
</div>
<form onSubmit={handleCreateUser}>
<div className="mb-4">
<label className="block text-[10px] font-bold uppercase tracking-widest text-black/40 mb-2">Namn</label>
<input
autoFocus
type="text"
placeholder="Namn"
className="w-full p-3 rounded-xl bg-black/5 border-none focus:ring-2 focus:ring-black/10"
value={newUserName}
onChange={e => setNewUserName(e.target.value)}
/>
</div>
<div className="mb-6">
<label className="block text-[10px] font-bold uppercase tracking-widest text-black/40 mb-2">Välj Ikon</label>
<div className="grid grid-cols-5 gap-2 max-h-40 overflow-y-auto p-1">
{AVATARS.map(avatar => (
<button
key={avatar.name}
type="button"
onClick={() => setNewUserAvatar(avatar.name)}
className={`p-2 rounded-xl flex items-center justify-center transition-all ${newUserAvatar === avatar.name ? 'bg-black text-white scale-110 shadow-md' : 'bg-black/5 text-black/40 hover:bg-black/10'}`}
>
<avatar.icon size={20} />
</button>
))}
</div>
</div>
<button type="submit" className="w-full py-3 bg-black text-white rounded-xl font-medium hover:bg-black/80 transition-colors">
Skapa
</button>
</form>
</motion.div>
</div>
)}
</AnimatePresence>
</div>
);
} else {
return (
<div className="min-h-screen bg-[#F5F5F4] flex items-center justify-center p-4">
<div className="bg-white p-8 rounded-3xl shadow-sm border border-black/5 w-full max-w-md text-center">
<div className="w-16 h-16 bg-black/5 rounded-full flex items-center justify-center mx-auto mb-4">
<UserPlus size={32} className="text-black/40" />
</div>
<h1 className="text-2xl font-bold mb-2">Välkommen till HemKoll</h1>
<p className="text-black/60 mb-6">Börja med att skapa den första användaren för att komma igång.</p>
<form onSubmit={handleCreateUser}>
<div className="mb-4 text-left">
<label className="block text-[10px] font-bold uppercase tracking-widest text-black/40 mb-2">Ditt namn</label>
<input
autoFocus
type="text"
placeholder="Ditt namn"
className="w-full p-3 rounded-xl bg-black/5 border-none focus:ring-2 focus:ring-black/10"
value={newUserName}
onChange={e => setNewUserName(e.target.value)}
/>
</div>
<div className="mb-6 text-left">
<label className="block text-[10px] font-bold uppercase tracking-widest text-black/40 mb-2">Välj din ikon</label>
<div className="grid grid-cols-5 gap-2 p-1">
{AVATARS.map(avatar => (
<button
key={avatar.name}
type="button"
onClick={() => setNewUserAvatar(avatar.name)}
className={`p-2 rounded-xl flex items-center justify-center transition-all ${newUserAvatar === avatar.name ? 'bg-black text-white scale-110 shadow-md' : 'bg-black/5 text-black/40 hover:bg-black/10'}`}
>
<avatar.icon size={20} />
</button>
))}
</div>
</div>
<button type="submit" className="w-full py-3 bg-black text-white rounded-xl font-medium hover:bg-black/80 transition-colors">
Skapa Användare
</button>
</form>
</div>
</div>
);
}
}
const columns: { id: Status; title: string; icon: any; color: string }[] = [
{ id: 'pending', title: 'Väntande', icon: Clock, color: 'text-amber-500' },
{ id: 'in_progress', title: 'Pågående', icon: PlayCircle, color: 'text-blue-500' },
{ id: 'completed', title: 'Klart', icon: CheckCircle2, color: 'text-emerald-500' },
];
return (
<div className="min-h-screen bg-[#F5F5F4] text-[#1A1A1A] font-sans">
<header className="bg-white border-b border-black/5 px-6 py-4 flex items-center justify-between sticky top-0 z-30">
<div className="flex items-center gap-3">
<div className="w-10 h-10 bg-black rounded-xl flex items-center justify-center text-white">
<Trophy size={20} />
</div>
<div>
<h1 className="font-bold text-lg leading-tight">HemKoll</h1>
<p className="text-xs text-black/40 uppercase tracking-wider font-semibold">Dashboard</p>
</div>
</div>
<div className="flex items-center gap-4 flex-1 max-w-md mx-8">
<div className="relative w-full">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 text-black/20" size={16} />
<input
type="text"
placeholder="Sök uppgifter..."
className="w-full pl-10 pr-4 py-2 bg-black/5 border-none rounded-xl text-sm focus:ring-2 focus:ring-black/10 transition-all"
value={searchQuery}
onChange={e => setSearchQuery(e.target.value)}
/>
</div>
</div>
<div className="flex items-center gap-4">
<button
onClick={() => setIsTaskModalOpen(true)}
className="bg-black text-white px-4 py-2 rounded-xl flex items-center gap-2 text-sm font-medium hover:bg-black/80 transition-all active:scale-95"
>
<Plus size={18} />
<span className="hidden sm:inline">Ny Uppgift</span>
</button>
<div className="h-8 w-px bg-black/10 mx-2" />
<button
onClick={() => setIsLeaderboardOpen(true)}
className="flex items-center gap-2 p-1.5 pr-4 rounded-full hover:bg-yellow-50 text-black/60 hover:text-yellow-600 transition-all group border border-transparent hover:border-yellow-100"
title="Leaderboard"
>
<Trophy size={20} />
</button>
<button
onClick={() => setCurrentUser(null)}
className="flex items-center gap-2 p-1.5 pr-4 rounded-full hover:bg-red-50 text-black/60 hover:text-red-600 transition-all group border border-transparent hover:border-red-100"
title="Logga ut"
>
<div className={`w-8 h-8 ${currentUser?.color} rounded-full flex items-center justify-center text-white shadow-sm`}>
<AvatarRenderer name={currentUser?.avatar || 'UserIcon'} size={16} />
</div>
<div className="flex flex-col items-start">
<span className="text-xs font-bold leading-none">{currentUser?.name}</span>
<span className="text-[10px] font-medium opacity-50 group-hover:opacity-100 flex items-center gap-0.5">
<LogOut size={10} />
Logga ut
</span>
</div>
</button>
</div>
</header>
<main className="p-6">
<div className="grid grid-cols-1 md:grid-cols-3 gap-6 h-[calc(100vh-140px)]">
{columns.map(col => (
<div
key={col.id}
className="flex flex-col h-full"
onDragOver={onDragOver}
onDrop={(e) => onDrop(e, col.id)}
>
<div className="flex items-center justify-between mb-4 px-2">
<div className="flex items-center gap-2">
<col.icon size={18} className={col.color} />
<h2 className="font-bold text-sm uppercase tracking-widest text-black/60">{col.title}</h2>
<span className="bg-black/5 text-black/40 text-[10px] font-bold px-2 py-0.5 rounded-full">
{tasks.filter(t => t.status === col.id).length}
</span>
</div>
</div>
<div className="flex-1 bg-black/[0.02] rounded-3xl p-3 overflow-y-auto border border-black/5">
<div className="space-y-3">
{tasks
.filter(t => t.status === col.id)
.filter(t => t.title.toLowerCase().includes(searchQuery.toLowerCase()) || t.description.toLowerCase().includes(searchQuery.toLowerCase()))
.sort((a, b) => {
if (!a.due_date) return 1;
if (!b.due_date) return -1;
return new Date(a.due_date).getTime() - new Date(b.due_date).getTime();
})
.map(task => (
<motion.div
layoutId={`task-${task.id}`}
key={task.id}
draggable
onDragStart={(e) => onDragStart(e as any, task.id)}
onDragEnd={onDragEnd}
className={`${getTaskCardColor(task)} p-4 rounded-2xl shadow-sm border cursor-grab active:cursor-grabbing hover:shadow-md transition-all group relative overflow-hidden`}
>
<div className="flex justify-between items-center gap-2">
<div className="flex items-center gap-2 flex-1 min-w-0">
<h3 className="font-semibold text-sm leading-snug truncate">{task.title}</h3>
{!expandedTasks.has(task.id) && task.user_id && (
<div className={`w-5 h-5 ${task.user_color} rounded-full flex items-center justify-center text-white shadow-sm flex-shrink-0`}>
<AvatarRenderer name={task.user_avatar || 'UserIcon'} size={10} />
</div>
)}
</div>
<div className="flex items-center gap-1">
{expandedTasks.has(task.id) && (
<button
onClick={(e) => deleteTask(e, task.id)}
className="text-black/20 hover:text-red-500 transition-colors p-1 rounded-lg hover:bg-red-50"
>
<Trash2 size={14} />
</button>
)}
<button
onClick={(e) => { e.stopPropagation(); toggleTaskExpansion(task.id); }}
className="text-black/20 hover:text-black/60 p-1 rounded-lg hover:bg-black/5 transition-all"
>
{expandedTasks.has(task.id) ? <ChevronUp size={16} /> : <ChevronDown size={16} />}
</button>
</div>
</div>
<AnimatePresence>
{expandedTasks.has(task.id) && (
<motion.div
initial={{ height: 0, opacity: 0 }}
animate={{ height: 'auto', opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
className="overflow-hidden"
>
<div className="pt-3 border-t border-black/5 mt-3">
{task.description && (
<p className="text-xs text-black/50 mb-3">
{task.description}
</p>
)}
{task.due_date && (
<div className="flex items-center gap-1 text-[10px] text-black/40 mb-3">
{(() => {
const dateStr = task.due_date;
if (!dateStr) return null;
const date = new Date(dateStr);
return (
<>
<Calendar size={12} className={date < new Date() && task.status !== 'completed' ? 'text-red-500' : ''} />
<span className={date < new Date() && task.status !== 'completed' ? 'text-red-500 font-bold' : ''}>
{date.toLocaleString('sv-SE', {
month: 'short',
day: 'numeric'
})}
</span>
</>
);
})()}
</div>
)}
<div className="flex items-center justify-between mt-auto">
<div className="flex items-center gap-1.5">
<div className="bg-black/5 px-2 py-1 rounded-lg flex items-center gap-1">
<Trophy size={10} className="text-amber-500" />
<span className="text-[10px] font-bold">{task.points}</span>
</div>
{task.is_recurring && (
<div className="bg-blue-50 text-blue-500 px-2 py-1 rounded-lg flex items-center gap-1">
<RefreshCw size={10} />
<span className="text-[10px] font-bold">
{task.recurrence_period === 'daily' && 'Dagligen'}
{task.recurrence_period === 'weekly' && 'Veckovis'}
{task.recurrence_period === 'biweekly' && 'Varannan vecka'}
{task.recurrence_period === 'monthly' && 'Månadsvis'}
</span>
</div>
)}
</div>
{task.user_id ? (
<div className="flex items-center gap-1.5">
<span className="text-[10px] font-medium text-black/40">
{task.user_name}
</span>
<div className={`w-6 h-6 ${task.user_color} rounded-full flex items-center justify-center text-white shadow-sm`}>
<AvatarRenderer name={task.user_avatar || 'UserIcon'} size={12} />
</div>
</div>
) : (
<button
onClick={(e) => { e.stopPropagation(); updateTaskStatus(task.id, task.status, currentUser?.id); }}
className="text-[10px] font-bold text-black/30 hover:text-black/60 flex items-center gap-1"
>
<UserPlus size={12} />
<span>Ta uppgift</span>
</button>
)}
</div>
</div>
</motion.div>
)}
</AnimatePresence>
</motion.div>
))}
</div>
</div>
</div>
))}
</div>
</main>
<AnimatePresence>
{isTaskModalOpen && (
<div className="fixed inset-0 bg-black/40 backdrop-blur-sm flex items-center justify-center p-4 z-50">
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: 20 }}
className="bg-white p-8 rounded-[32px] shadow-2xl w-full max-w-lg border border-black/5"
>
<div className="flex justify-between items-center mb-6">
<h2 className="text-2xl font-bold tracking-tight">Skapa ny uppgift</h2>
<button onClick={() => setIsTaskModalOpen(false)} className="p-2 hover:bg-black/5 rounded-full transition-colors">
<X size={24} />
</button>
</div>
<form onSubmit={handleCreateTask} className="space-y-6">
<div>
<label className="block text-[10px] font-bold uppercase tracking-widest text-black/40 mb-2">Titel</label>
<input
autoFocus
required
type="text"
placeholder="Vad behöver göras?"
className="w-full p-4 rounded-2xl bg-black/5 border-none focus:ring-2 focus:ring-black/10 text-lg"
value={newTask.title}
onChange={e => setNewTask({...newTask, title: e.target.value})}
/>
</div>
<div>
<label className="block text-[10px] font-bold uppercase tracking-widest text-black/40 mb-2">Beskrivning (valfritt)</label>
<textarea
placeholder="Mer detaljer..."
className="w-full p-4 rounded-2xl bg-black/5 border-none focus:ring-2 focus:ring-black/10 min-h-[100px] resize-none"
value={newTask.description}
onChange={e => setNewTask({...newTask, description: e.target.value})}
/>
</div>
<div className="grid grid-cols-2 gap-6">
<div>
<label className="block text-[10px] font-bold uppercase tracking-widest text-black/40 mb-2">Poäng (1-100)</label>
<div className="flex items-center gap-3">
<input
type="range"
min="1"
max="100"
className="flex-1 accent-black"
value={newTask.points}
onChange={e => setNewTask({...newTask, points: parseInt(e.target.value)})}
/>
<span className="font-mono font-bold text-lg w-10">{newTask.points}</span>
</div>
</div>
<div>
<label className="block text-[10px] font-bold uppercase tracking-widest text-black/40 mb-2">Tilldela</label>
<select
className="w-full p-3 rounded-xl bg-black/5 border-none focus:ring-2 focus:ring-black/10 text-sm"
value={newTask.user_id || ''}
onChange={e => setNewTask({...newTask, user_id: e.target.value ? parseInt(e.target.value) : null})}
>
<option value="">Ingen</option>
{users.map(u => <option key={u.id} value={u.id}>{u.name}</option>)}
</select>
</div>
</div>
<div>
<label className="block text-[10px] font-bold uppercase tracking-widest text-black/40 mb-2">Deadline (valfritt)</label>
<input
type="date"
className="w-full p-4 rounded-2xl bg-black/5 border-none focus:ring-2 focus:ring-black/10 text-sm"
value={newTask.due_date}
onChange={e => setNewTask({...newTask, due_date: e.target.value})}
/>
</div>
<div className="space-y-4">
<div className="flex items-center gap-3 p-4 rounded-2xl bg-black/5">
<input
type="checkbox"
id="recurring"
className="w-5 h-5 accent-black rounded-lg"
checked={newTask.is_recurring}
onChange={e => setNewTask({...newTask, is_recurring: e.target.checked})}
/>
<label htmlFor="recurring" className="text-sm font-medium cursor-pointer">Återkommande uppgift</label>
</div>
<AnimatePresence>
{newTask.is_recurring && (
<motion.div
initial={{ height: 0, opacity: 0 }}
animate={{ height: 'auto', opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
className="overflow-hidden"
>
<div className="p-4 rounded-2xl bg-black/5 space-y-3">
<label className="block text-[10px] font-bold uppercase tracking-widest text-black/40">Periodicitet</label>
<select
className="w-full p-3 rounded-xl bg-white border-none focus:ring-2 focus:ring-black/10 text-sm"
value={newTask.recurrence_period}
onChange={e => setNewTask({...newTask, recurrence_period: e.target.value})}
>
<option value="daily">Dagligen</option>
<option value="weekly">Veckovis</option>
<option value="biweekly">Varannan vecka</option>
<option value="monthly">Månadsvis</option>
</select>
<p className="text-[10px] text-black/40 italic">En ny uppgift skapas automatiskt när denna markeras som klar.</p>
</div>
</motion.div>
)}
</AnimatePresence>
</div>
<button type="submit" className="w-full py-4 bg-black text-white rounded-2xl font-bold text-lg hover:bg-black/80 transition-all active:scale-[0.98] shadow-lg shadow-black/10">
Skapa Uppgift
</button>
</form>
</motion.div>
</div>
)}
</AnimatePresence>
{/* Leaderboard Modal */}
<AnimatePresence>
{isLeaderboardOpen && (
<div className="fixed inset-0 bg-black/40 backdrop-blur-sm flex items-center justify-center p-4 z-[100]">
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.95 }}
className="bg-white p-6 rounded-3xl shadow-2xl w-full max-w-sm border border-black/5 max-h-[80vh] overflow-y-auto"
>
<div className="flex justify-between items-center mb-4">
<button onClick={() => setIsLeaderboardOpen(false)} className="p-2 hover:bg-black/5 rounded-full ml-auto">
<X size={20} />
</button>
</div>
<Leaderboard />
</motion.div>
</div>
)}
</AnimatePresence>
{/* Custom Alert Modal */}
<AnimatePresence>
{alertModal.isOpen && (
<div className="fixed inset-0 bg-black/40 backdrop-blur-sm flex items-center justify-center p-4 z-[100]">
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.95 }}
className="bg-white p-6 rounded-3xl shadow-2xl w-full max-w-sm border border-black/5"
>
<h3 className="text-xl font-bold mb-2">{alertModal.title}</h3>
<p className="text-black/60 mb-6">{alertModal.message}</p>
<button
onClick={() => setAlertModal({ ...alertModal, isOpen: false })}
className="w-full py-3 bg-black text-white rounded-xl font-bold hover:bg-black/80 transition-all"
>
Okej
</button>
</motion.div>
</div>
)}
</AnimatePresence>
{/* Custom Confirm Modal */}
<AnimatePresence>
{confirmModal.isOpen && (
<div className="fixed inset-0 bg-black/40 backdrop-blur-sm flex items-center justify-center p-4 z-[100]">
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.95 }}
className="bg-white p-6 rounded-3xl shadow-2xl w-full max-w-sm border border-black/5"
>
<h3 className="text-xl font-bold mb-2">{confirmModal.title}</h3>
<p className="text-black/60 mb-6">{confirmModal.message}</p>
<div className="flex gap-3">
<button
onClick={() => setConfirmModal({ ...confirmModal, isOpen: false })}
className="flex-1 py-3 bg-black/5 text-black rounded-xl font-bold hover:bg-black/10 transition-all"
>
Avbryt
</button>
<button
onClick={() => {
confirmModal.onConfirm();
setConfirmModal({ ...confirmModal, isOpen: false });
}}
className="flex-1 py-3 bg-red-500 text-white rounded-xl font-bold hover:bg-red-600 transition-all shadow-lg shadow-red-500/20"
>
Radera
</button>
</div>
</motion.div>
</div>
)}
</AnimatePresence>
</div>
);
}

View File

@ -0,0 +1,27 @@
import axios from 'axios';
const apiClient = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL + '/api',
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Pragma': 'no-cache',
'Expires': '0',
},
});
// Interceptor för att fånga upp om sessionen är ogiltig (t.ex. efter backend-omstart)
apiClient.interceptors.response.use(
(response) => response,
(error) => {
if (error.response && error.response.status === 401) {
// Om backenden säger att vi inte är inloggade, rensa lokal state
localStorage.removeItem('user');
localStorage.removeItem('token');
window.location.href = '/login';
}
return Promise.reject(error);
}
);
export default apiClient;

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

View File

@ -0,0 +1,24 @@
import React from 'react';
import LeaderboardOverlay from './LeaderboardOverlay';
const Dashboard = () => {
return (
<div style={{ padding: '2rem', maxWidth: '800px', margin: '0 auto' }}>
<header style={{ marginBottom: '2rem' }}>
<h1>Hushålls-Dashboard</h1>
<p>Välkommen till din översikt av sysslor.</p>
</header>
<main>
{/* Här skulle din lista med Tasks ligga */}
<div style={{ padding: '2rem', background: '#f9f9f9', borderRadius: '8px' }}>
<p>Här visas dina aktiva uppgifter...</p>
</div>
</main>
<LeaderboardOverlay />
</div>
);
};
export default Dashboard;

View File

@ -0,0 +1,64 @@
import React, { useEffect, useState } from 'react';
import { getLeaderboard } from '../services/userService';
const Leaderboard = () => {
const [scores, setScores] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchLeaderboard = async () => {
try {
const data = await getLeaderboard();
// Sortera fallande baserat på poäng (om backenden inte redan gjort det)
const sortedData = data.sort((a, b) => b.totalPoints - a.totalPoints);
setScores(sortedData);
} catch (err) {
setError('Kunde inte hämta topplistan.');
console.error(err);
} finally {
setLoading(false);
}
};
fetchLeaderboard();
}, []);
if (loading) return <p>Laddar topplistan...</p>;
if (error) return <p style={{ color: 'red' }}>{error}</p>;
return (
<div className="leaderboard-container" style={{ padding: '0' }}>
<h2>Topplista - Flest poäng</h2>
<table style={{ width: '100%', borderCollapse: 'collapse', marginTop: '1rem' }}>
<thead>
<tr style={{ borderBottom: '2px solid #ccc', textAlign: 'left' }}>
<th style={{ padding: '8px' }}>Rank</th>
<th style={{ padding: '8px' }}>Användare</th>
<th style={{ padding: '8px' }}>Totala Poäng</th>
</tr>
</thead>
<tbody>
{scores.map((entry, index) => (
<tr
key={entry.username}
style={{
borderBottom: '1px solid #eee',
backgroundColor: index === 0 ? '#fffef0' : 'transparent' // Guld-aktig för vinnaren
}}
>
<td style={{ padding: '8px', fontWeight: index < 3 ? 'bold' : 'normal' }}>
{index === 0 ? '🥇' : index === 1 ? '🥈' : index === 2 ? '🥉' : index + 1}
</td>
<td style={{ padding: '8px' }}>{entry.username}</td>
<td style={{ padding: '8px', fontWeight: 'bold' }}>{entry.totalPoints} p</td>
</tr>
))}
</tbody>
</table>
{scores.length === 0 && <p>Inga poäng registrerade ännu!</p>}
</div>
);
};
export default Leaderboard;

View File

@ -0,0 +1,96 @@
import React, { useState } from 'react';
import Leaderboard from './Leaderboard';
const LeaderboardOverlay = () => {
const [isOpen, setIsOpen] = useState(false);
const toggleModal = () => setIsOpen(!isOpen);
// Stil för modal-overlay (bakgrunden)
const overlayStyle = {
position: 'fixed',
top: 0,
left: 0,
width: '100vw',
height: '100vh',
backgroundColor: 'rgba(0, 0, 0, 0.7)',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
zIndex: 1000,
};
// Stil för själva modal-fönstret
const modalStyle = {
backgroundColor: 'white',
padding: '2rem',
borderRadius: '12px',
position: 'relative',
width: '90%',
maxWidth: '500px',
boxShadow: '0 4px 20px rgba(0,0,0,0.3)',
maxHeight: '80vh',
overflowY: 'auto'
};
// Stil för stäng-knappen
const closeButtonStyle = {
position: 'absolute',
top: '10px',
right: '10px',
border: 'none',
background: 'none',
fontSize: '1.5rem',
cursor: 'pointer',
color: '#666'
};
// Stil för pokal-ikonen
const iconButtonStyle = {
background: '#f0f0f0',
border: 'none',
borderRadius: '50%',
width: '50px',
height: '50px',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
cursor: 'pointer',
fontSize: '1.5rem',
boxShadow: '0 2px 5px rgba(0,0,0,0.1)',
transition: 'transform 0.2s',
position: 'fixed',
bottom: '30px',
right: '30px',
zIndex: 900,
};
return (
<>
{/* Pokal-ikon som fungerar som knapp */}
<button
onClick={toggleModal}
style={iconButtonStyle}
onMouseOver={(e) => e.currentTarget.style.transform = 'scale(1.1)'}
onMouseOut={(e) => e.currentTarget.style.transform = 'scale(1)'}
title="Visa Topplista"
>
🏆
</button>
{/* Själva modalen */}
{isOpen && (
<div style={overlayStyle} onClick={toggleModal}>
<div style={modalStyle} onClick={(e) => e.stopPropagation()}>
<button style={closeButtonStyle} onClick={toggleModal}>
&times;
</button>
<Leaderboard />
</div>
</div>
)}
</>
);
};
export default LeaderboardOverlay;

9
frontend/src/config.ts Normal file
View File

@ -0,0 +1,9 @@
/**
* Configuration for the application.
*
* VITE_API_BASE_URL can be set in .env files to point to different backends.
* - If empty (default), it uses relative paths (works with server.ts fake backend).
* - Set to 'http://localhost:3000' for a local backend running separately.
* - Set to 'https://rubble.se/householdmanager' for production.
*/
export const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || '';

10
frontend/src/index.css Normal file
View File

@ -0,0 +1,10 @@
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
@import "tailwindcss";
@theme {
--font-sans: "Inter", ui-sans-serif, system-ui, sans-serif;
}
body {
@apply antialiased text-slate-900;
}

10
frontend/src/main.tsx Normal file
View File

@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)

View File

@ -0,0 +1,30 @@
import apiClient from '../api/client';
export const registerUser = async (userData) => {
localStorage.clear();
sessionStorage.clear();
const response = await apiClient.post('/users/register', userData);
return response.data;
};
export const loginUser = async (credentials) => {
// Rensa allt innan login för att tvinga bort "spökanvändare"
localStorage.clear();
sessionStorage.clear();
const response = await apiClient.post('/auth/login', credentials);
// Spara den NYA användaren direkt i localStorage så att den finns vid omladdning
localStorage.setItem('user', JSON.stringify(response.data));
// Tips: Om du märker att UI:t inte uppdateras, kan du avkommentera raden nedan
// window.location.href = '/'; // Tvingar en total rensning av JS-minnet
return response.data;
};
export const getLeaderboard = async () => {
const response = await apiClient.get('/users/leaderboard');
return response.data;
};

BIN
frontend/tasks.db Normal file

Binary file not shown.

28
frontend/tsconfig.json Normal file
View File

@ -0,0 +1,28 @@
{
"compilerOptions": {
"target": "ES2022",
"experimentalDecorators": true,
"useDefineForClassFields": false,
"module": "ESNext",
"lib": [
"ES2022",
"DOM",
"DOM.Iterable"
],
"skipLibCheck": true,
"moduleResolution": "bundler",
"isolatedModules": true,
"moduleDetection": "force",
"allowJs": true,
"jsx": "react-jsx",
"paths": {
"@/*": [
"./*"
]
},
"allowImportingTsExtensions": true,
"types": ["vite/client"],
"noEmit": true
}
}

11
frontend/vite.config.ts Normal file
View File

@ -0,0 +1,11 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
export default defineConfig({
plugins: [react(), tailwindcss()],
server: {
port: 3000,
host: '0.0.0.0'
}
})