mirror of
https://github.com/spliit-app/spliit.git
synced 2026-02-15 20:16:12 +01:00
Compare commits
26 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e990e00a75 | ||
|
|
0c05499107 | ||
|
|
3887efd9ee | ||
|
|
e619c1a5b4 | ||
|
|
10e13d1f6b | ||
|
|
f9d915378b | ||
|
|
74465c0565 | ||
|
|
d3fd8027a5 | ||
|
|
833237b613 | ||
|
|
1cd2b273f9 | ||
|
|
1ad470309b | ||
|
|
2fd38aadd9 | ||
|
|
b61d1836ea | ||
|
|
c3903849ec | ||
|
|
b67a0be0dd | ||
|
|
e07d237218 | ||
|
|
cc37083389 | ||
|
|
552953151a | ||
|
|
b227401dd6 | ||
|
|
6a5efc5f3f | ||
|
|
4c5f8a6aa5 | ||
|
|
c2b591349b | ||
|
|
56c1865264 | ||
|
|
2f991e680b | ||
|
|
2af0660383 | ||
|
|
50525ad881 |
42
.devcontainer/devcontainer.json
Normal file
42
.devcontainer/devcontainer.json
Normal file
@@ -0,0 +1,42 @@
|
||||
// For format details, see https://aka.ms/devcontainer.json. For config options, see the
|
||||
// README at: https://github.com/devcontainers/templates/tree/main/src/javascript-node-postgres
|
||||
{
|
||||
"name": "spliit",
|
||||
"dockerComposeFile": "docker-compose.yml",
|
||||
"service": "app",
|
||||
|
||||
// Features to add to the dev container. More info: https://containers.dev/features.
|
||||
// "features": {
|
||||
// "ghcr.io/frntn/devcontainers-features/prism:1": {}
|
||||
// },
|
||||
|
||||
// Use 'postCreateCommand' to run commands after the container is created.
|
||||
"postCreateCommand": "cp container.env.example .env && npm install",
|
||||
"postAttachCommand": {
|
||||
"npm": "npm run dev"
|
||||
},
|
||||
|
||||
// Use 'forwardPorts' to make a list of ports inside the container available locally.
|
||||
// This can be used to network with other containers or with the host.
|
||||
"forwardPorts": [3000, 5432],
|
||||
"portsAttributes": {
|
||||
"3000": {
|
||||
"label": "App"
|
||||
},
|
||||
"5432": {
|
||||
"label": "PostgreSQL"
|
||||
}
|
||||
},
|
||||
|
||||
// Configure tool-specific properties.
|
||||
"customizations": {
|
||||
"codespaces": {
|
||||
"openFiles": [
|
||||
"README.md"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
// Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root.
|
||||
// "remoteUser": "root"
|
||||
}
|
||||
33
.devcontainer/docker-compose.yml
Normal file
33
.devcontainer/docker-compose.yml
Normal file
@@ -0,0 +1,33 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
app:
|
||||
image: mcr.microsoft.com/devcontainers/typescript-node:latest
|
||||
|
||||
volumes:
|
||||
- ../..:/workspaces:cached
|
||||
|
||||
# Overrides default command so things don't shut down after the process ends.
|
||||
command: sleep infinity
|
||||
|
||||
# Runs app on the same network as the database container, allows "forwardPorts" in devcontainer.json function.
|
||||
network_mode: service:db
|
||||
|
||||
# Use "forwardPorts" in **devcontainer.json** to forward an app port locally.
|
||||
# (Adding the "ports" property to this file will not forward from a Codespace.)
|
||||
|
||||
db:
|
||||
image: postgres:latest
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
- postgres-data:/var/lib/postgresql/data
|
||||
environment:
|
||||
POSTGRES_PASSWORD: 1234
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_DB: postgres
|
||||
|
||||
# Add "forwardPorts": ["5432"] to **devcontainer.json** to forward PostgreSQL locally.
|
||||
# (Adding the "ports" property to this file will not forward from a Codespace.)
|
||||
|
||||
volumes:
|
||||
postgres-data:
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -28,6 +28,7 @@ yarn-error.log*
|
||||
# local env files
|
||||
.env*.local
|
||||
*.env
|
||||
!scripts/build.env
|
||||
|
||||
# vercel
|
||||
.vercel
|
||||
|
||||
60
Dockerfile
60
Dockerfile
@@ -1,22 +1,48 @@
|
||||
FROM node:21-slim as base
|
||||
FROM node:21-alpine as base
|
||||
|
||||
WORKDIR /usr/app
|
||||
COPY ./package.json \
|
||||
./package-lock.json \
|
||||
./next.config.js \
|
||||
./tsconfig.json \
|
||||
./reset.d.ts \
|
||||
./tailwind.config.js \
|
||||
./postcss.config.js ./
|
||||
COPY ./scripts ./scripts
|
||||
COPY ./prisma ./prisma
|
||||
|
||||
RUN apk add --no-cache openssl && \
|
||||
npm ci --ignore-scripts && \
|
||||
npx prisma generate
|
||||
|
||||
COPY ./src ./src
|
||||
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
|
||||
COPY scripts/build.env .env
|
||||
RUN npm run build
|
||||
|
||||
RUN rm -r .next/cache
|
||||
|
||||
FROM node:21-alpine as runtime-deps
|
||||
|
||||
WORKDIR /usr/app
|
||||
COPY --from=base /usr/app/package.json /usr/app/package-lock.json /usr/app/next.config.js ./
|
||||
COPY --from=base /usr/app/prisma ./prisma
|
||||
|
||||
RUN npm ci --omit=dev --omit=optional --ignore-scripts && \
|
||||
npx prisma generate
|
||||
|
||||
FROM node:21-alpine as runner
|
||||
|
||||
EXPOSE 3000/tcp
|
||||
WORKDIR /usr/app
|
||||
COPY ./ ./
|
||||
|
||||
RUN apt update && \
|
||||
apt install openssl -y && \
|
||||
apt clean && \
|
||||
apt autoclean && \
|
||||
apt autoremove && \
|
||||
npm ci --ignore-scripts && \
|
||||
npm install -g prisma && \
|
||||
prisma generate
|
||||
COPY --from=base /usr/app/package.json /usr/app/package-lock.json /usr/app/next.config.js ./
|
||||
COPY --from=runtime-deps /usr/app/node_modules ./node_modules
|
||||
COPY ./public ./public
|
||||
COPY ./scripts ./scripts
|
||||
COPY --from=base /usr/app/prisma ./prisma
|
||||
COPY --from=base /usr/app/.next ./.next
|
||||
|
||||
# env vars needed for build not to fail
|
||||
ARG POSTGRES_PRISMA_URL
|
||||
ARG POSTGRES_URL_NON_POOLING
|
||||
|
||||
RUN npm run build
|
||||
|
||||
ENTRYPOINT ["/usr/app/scripts/container-entrypoint.sh"]
|
||||
ENTRYPOINT ["/bin/sh", "/usr/app/scripts/container-entrypoint.sh"]
|
||||
|
||||
@@ -23,6 +23,12 @@ const nextConfig = {
|
||||
images: {
|
||||
remotePatterns
|
||||
},
|
||||
// Required to run in a codespace (see https://github.com/vercel/next.js/issues/58019)
|
||||
experimental: {
|
||||
serverActions: {
|
||||
allowedOrigins: ['localhost:3000'],
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
module.exports = nextConfig
|
||||
|
||||
232
package-lock.json
generated
232
package-lock.json
generated
@@ -33,15 +33,17 @@
|
||||
"embla-carousel-react": "^8.0.0-rc21",
|
||||
"lucide-react": "^0.290.0",
|
||||
"nanoid": "^5.0.4",
|
||||
"next": "^14.1.0",
|
||||
"next": "^14.2.3",
|
||||
"next-s3-upload": "^0.3.4",
|
||||
"next-themes": "^0.2.1",
|
||||
"next13-progressbar": "^1.1.1",
|
||||
"openai": "^4.25.0",
|
||||
"pg": "^8.11.3",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"prisma": "^5.7.0",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-hook-form": "^7.47.0",
|
||||
"react-intersection-observer": "^9.8.0",
|
||||
"sharp": "^0.33.2",
|
||||
"tailwind-merge": "^1.14.0",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
@@ -65,7 +67,6 @@
|
||||
"postcss": "^8",
|
||||
"prettier": "^3.0.3",
|
||||
"prettier-plugin-organize-imports": "^3.2.3",
|
||||
"prisma": "^5.7.0",
|
||||
"tailwindcss": "^3",
|
||||
"tsconfig-paths": "^4.2.0",
|
||||
"typescript": "^5.3.3"
|
||||
@@ -1189,9 +1190,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/env": {
|
||||
"version": "14.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@next/env/-/env-14.1.0.tgz",
|
||||
"integrity": "sha512-Py8zIo+02ht82brwwhTg36iogzFqGLPXlRGKQw5s+qP/kMNc4MAyDeEwBKDijk6zTIbegEgu8Qy7C1LboslQAw=="
|
||||
"version": "14.2.3",
|
||||
"resolved": "https://registry.npmjs.org/@next/env/-/env-14.2.3.tgz",
|
||||
"integrity": "sha512-W7fd7IbkfmeeY2gXrzJYDx8D2lWKbVoTIj1o1ScPHNzvp30s1AuoEFSdr39bC5sjxJaxTtq3OTCZboNp0lNWHA=="
|
||||
},
|
||||
"node_modules/@next/eslint-plugin-next": {
|
||||
"version": "14.1.0",
|
||||
@@ -1249,9 +1250,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-darwin-arm64": {
|
||||
"version": "14.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-14.1.0.tgz",
|
||||
"integrity": "sha512-nUDn7TOGcIeyQni6lZHfzNoo9S0euXnu0jhsbMOmMJUBfgsnESdjN97kM7cBqQxZa8L/bM9om/S5/1dzCrW6wQ==",
|
||||
"version": "14.2.3",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-14.2.3.tgz",
|
||||
"integrity": "sha512-3pEYo/RaGqPP0YzwnlmPN2puaF2WMLM3apt5jLW2fFdXD9+pqcoTzRk+iZsf8ta7+quAe4Q6Ms0nR0SFGFdS1A==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -1264,9 +1265,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-darwin-x64": {
|
||||
"version": "14.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-14.1.0.tgz",
|
||||
"integrity": "sha512-1jgudN5haWxiAl3O1ljUS2GfupPmcftu2RYJqZiMJmmbBT5M1XDffjUtRUzP4W3cBHsrvkfOFdQ71hAreNQP6g==",
|
||||
"version": "14.2.3",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-14.2.3.tgz",
|
||||
"integrity": "sha512-6adp7waE6P1TYFSXpY366xwsOnEXM+y1kgRpjSRVI2CBDOcbRjsJ67Z6EgKIqWIue52d2q/Mx8g9MszARj8IEA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -1279,9 +1280,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-linux-arm64-gnu": {
|
||||
"version": "14.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-14.1.0.tgz",
|
||||
"integrity": "sha512-RHo7Tcj+jllXUbK7xk2NyIDod3YcCPDZxj1WLIYxd709BQ7WuRYl3OWUNG+WUfqeQBds6kvZYlc42NJJTNi4tQ==",
|
||||
"version": "14.2.3",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-14.2.3.tgz",
|
||||
"integrity": "sha512-cuzCE/1G0ZSnTAHJPUT1rPgQx1w5tzSX7POXSLaS7w2nIUJUD+e25QoXD/hMfxbsT9rslEXugWypJMILBj/QsA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -1294,9 +1295,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-linux-arm64-musl": {
|
||||
"version": "14.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-14.1.0.tgz",
|
||||
"integrity": "sha512-v6kP8sHYxjO8RwHmWMJSq7VZP2nYCkRVQ0qolh2l6xroe9QjbgV8siTbduED4u0hlk0+tjS6/Tuy4n5XCp+l6g==",
|
||||
"version": "14.2.3",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-14.2.3.tgz",
|
||||
"integrity": "sha512-0D4/oMM2Y9Ta3nGuCcQN8jjJjmDPYpHX9OJzqk42NZGJocU2MqhBq5tWkJrUQOQY9N+In9xOdymzapM09GeiZw==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -1309,9 +1310,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-linux-x64-gnu": {
|
||||
"version": "14.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-14.1.0.tgz",
|
||||
"integrity": "sha512-zJ2pnoFYB1F4vmEVlb/eSe+VH679zT1VdXlZKX+pE66grOgjmKJHKacf82g/sWE4MQ4Rk2FMBCRnX+l6/TVYzQ==",
|
||||
"version": "14.2.3",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-14.2.3.tgz",
|
||||
"integrity": "sha512-ENPiNnBNDInBLyUU5ii8PMQh+4XLr4pG51tOp6aJ9xqFQ2iRI6IH0Ds2yJkAzNV1CfyagcyzPfROMViS2wOZ9w==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -1324,9 +1325,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-linux-x64-musl": {
|
||||
"version": "14.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-14.1.0.tgz",
|
||||
"integrity": "sha512-rbaIYFt2X9YZBSbH/CwGAjbBG2/MrACCVu2X0+kSykHzHnYH5FjHxwXLkcoJ10cX0aWCEynpu+rP76x0914atg==",
|
||||
"version": "14.2.3",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-14.2.3.tgz",
|
||||
"integrity": "sha512-BTAbq0LnCbF5MtoM7I/9UeUu/8ZBY0i8SFjUMCbPDOLv+un67e2JgyN4pmgfXBwy/I+RHu8q+k+MCkDN6P9ViQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -1339,9 +1340,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-win32-arm64-msvc": {
|
||||
"version": "14.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-14.1.0.tgz",
|
||||
"integrity": "sha512-o1N5TsYc8f/HpGt39OUQpQ9AKIGApd3QLueu7hXk//2xq5Z9OxmV6sQfNp8C7qYmiOlHYODOGqNNa0e9jvchGQ==",
|
||||
"version": "14.2.3",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-14.2.3.tgz",
|
||||
"integrity": "sha512-AEHIw/dhAMLNFJFJIJIyOFDzrzI5bAjI9J26gbO5xhAKHYTZ9Or04BesFPXiAYXDNdrwTP2dQceYA4dL1geu8A==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -1354,9 +1355,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-win32-ia32-msvc": {
|
||||
"version": "14.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-win32-ia32-msvc/-/swc-win32-ia32-msvc-14.1.0.tgz",
|
||||
"integrity": "sha512-XXIuB1DBRCFwNO6EEzCTMHT5pauwaSj4SWs7CYnME57eaReAKBXCnkUE80p/pAZcewm7hs+vGvNqDPacEXHVkw==",
|
||||
"version": "14.2.3",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-win32-ia32-msvc/-/swc-win32-ia32-msvc-14.2.3.tgz",
|
||||
"integrity": "sha512-vga40n1q6aYb0CLrM+eEmisfKCR45ixQYXuBXxOOmmoV8sYST9k7E3US32FsY+CkkF7NtzdcebiFT4CHuMSyZw==",
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
@@ -1369,9 +1370,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-win32-x64-msvc": {
|
||||
"version": "14.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-14.1.0.tgz",
|
||||
"integrity": "sha512-9WEbVRRAqJ3YFVqEZIxUqkiO8l1nool1LmNxygr5HWF8AcSYsEpneUDhmjUVJEzO2A04+oPtZdombzzPPkTtgg==",
|
||||
"version": "14.2.3",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-14.2.3.tgz",
|
||||
"integrity": "sha512-Q1/zm43RWynxrO7lW4ehciQVj+5ePBhOK+/K2P7pLFX3JaJ/IZVC69SHidrmZSOkqz7ECIOhhy7XhAFG4JYyHA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -1429,13 +1430,10 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@prisma/client": {
|
||||
"version": "5.6.0",
|
||||
"resolved": "https://registry.npmjs.org/@prisma/client/-/client-5.6.0.tgz",
|
||||
"integrity": "sha512-mUDefQFa1wWqk4+JhKPYq8BdVoFk9NFMBXUI8jAkBfQTtgx8WPx02U2HB/XbAz3GSUJpeJOKJQtNvaAIDs6sug==",
|
||||
"version": "5.9.1",
|
||||
"resolved": "https://registry.npmjs.org/@prisma/client/-/client-5.9.1.tgz",
|
||||
"integrity": "sha512-caSOnG4kxcSkhqC/2ShV7rEoWwd3XrftokxJqOCMVvia4NYV/TPtJlS9C2os3Igxw/Qyxumj9GBQzcStzECvtQ==",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@prisma/engines-version": "5.6.0-32.e95e739751f42d8ca026f6b910f5a2dc5adeaeee"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16.13"
|
||||
},
|
||||
@@ -1449,59 +1447,48 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@prisma/debug": {
|
||||
"version": "5.7.0",
|
||||
"resolved": "https://registry.npmjs.org/@prisma/debug/-/debug-5.7.0.tgz",
|
||||
"integrity": "sha512-tZ+MOjWlVvz1kOEhNYMa4QUGURY+kgOUBqLHYIV8jmCsMuvA1tWcn7qtIMLzYWCbDcQT4ZS8xDgK0R2gl6/0wA==",
|
||||
"devOptional": true
|
||||
"version": "5.9.1",
|
||||
"resolved": "https://registry.npmjs.org/@prisma/debug/-/debug-5.9.1.tgz",
|
||||
"integrity": "sha512-yAHFSFCg8KVoL0oRUno3m60GAjsUKYUDkQ+9BA2X2JfVR3kRVSJFc/GpQ2fSORi4pSHZR9orfM4UC9OVXIFFTA=="
|
||||
},
|
||||
"node_modules/@prisma/engines": {
|
||||
"version": "5.7.0",
|
||||
"resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-5.7.0.tgz",
|
||||
"integrity": "sha512-TkOMgMm60n5YgEKPn9erIvFX2/QuWnl3GBo6yTRyZKk5O5KQertXiNnrYgSLy0SpsKmhovEPQb+D4l0SzyE7XA==",
|
||||
"devOptional": true,
|
||||
"version": "5.9.1",
|
||||
"resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-5.9.1.tgz",
|
||||
"integrity": "sha512-gkdXmjxQ5jktxWNdDA5aZZ6R8rH74JkoKq6LD5mACSvxd2vbqWeWIOV0Py5wFC8vofOYShbt6XUeCIUmrOzOnQ==",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@prisma/debug": "5.7.0",
|
||||
"@prisma/engines-version": "5.7.0-41.79fb5193cf0a8fdbef536e4b4a159cad677ab1b9",
|
||||
"@prisma/fetch-engine": "5.7.0",
|
||||
"@prisma/get-platform": "5.7.0"
|
||||
"@prisma/debug": "5.9.1",
|
||||
"@prisma/engines-version": "5.9.0-32.23fdc5965b1e05fc54e5f26ed3de66776b93de64",
|
||||
"@prisma/fetch-engine": "5.9.1",
|
||||
"@prisma/get-platform": "5.9.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@prisma/engines-version": {
|
||||
"version": "5.6.0-32.e95e739751f42d8ca026f6b910f5a2dc5adeaeee",
|
||||
"resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-5.6.0-32.e95e739751f42d8ca026f6b910f5a2dc5adeaeee.tgz",
|
||||
"integrity": "sha512-UoFgbV1awGL/3wXuUK3GDaX2SolqczeeJ5b4FVec9tzeGbSWJboPSbT0psSrmgYAKiKnkOPFSLlH6+b+IyOwAw=="
|
||||
},
|
||||
"node_modules/@prisma/engines/node_modules/@prisma/engines-version": {
|
||||
"version": "5.7.0-41.79fb5193cf0a8fdbef536e4b4a159cad677ab1b9",
|
||||
"resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-5.7.0-41.79fb5193cf0a8fdbef536e4b4a159cad677ab1b9.tgz",
|
||||
"integrity": "sha512-V6tgRVi62jRwTm0Hglky3Scwjr/AKFBFtS+MdbsBr7UOuiu1TKLPc6xfPiyEN1+bYqjEtjxwGsHgahcJsd1rNg==",
|
||||
"devOptional": true
|
||||
"version": "5.9.0-32.23fdc5965b1e05fc54e5f26ed3de66776b93de64",
|
||||
"resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-5.9.0-32.23fdc5965b1e05fc54e5f26ed3de66776b93de64.tgz",
|
||||
"integrity": "sha512-HFl7275yF0FWbdcNvcSRbbu9JCBSLMcurYwvWc8WGDnpu7APxQo2ONtZrUggU3WxLxUJ2uBX+0GOFIcJeVeOOQ=="
|
||||
},
|
||||
"node_modules/@prisma/fetch-engine": {
|
||||
"version": "5.7.0",
|
||||
"resolved": "https://registry.npmjs.org/@prisma/fetch-engine/-/fetch-engine-5.7.0.tgz",
|
||||
"integrity": "sha512-zIn/qmO+N/3FYe7/L9o+yZseIU8ivh4NdPKSkQRIHfg2QVTVMnbhGoTcecbxfVubeTp+DjcbjS0H9fCuM4W04w==",
|
||||
"devOptional": true,
|
||||
"version": "5.9.1",
|
||||
"resolved": "https://registry.npmjs.org/@prisma/fetch-engine/-/fetch-engine-5.9.1.tgz",
|
||||
"integrity": "sha512-l0goQOMcNVOJs1kAcwqpKq3ylvkD9F04Ioe1oJoCqmz05mw22bNAKKGWuDd3zTUoUZr97va0c/UfLNru+PDmNA==",
|
||||
"dependencies": {
|
||||
"@prisma/debug": "5.7.0",
|
||||
"@prisma/engines-version": "5.7.0-41.79fb5193cf0a8fdbef536e4b4a159cad677ab1b9",
|
||||
"@prisma/get-platform": "5.7.0"
|
||||
"@prisma/debug": "5.9.1",
|
||||
"@prisma/engines-version": "5.9.0-32.23fdc5965b1e05fc54e5f26ed3de66776b93de64",
|
||||
"@prisma/get-platform": "5.9.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@prisma/fetch-engine/node_modules/@prisma/engines-version": {
|
||||
"version": "5.7.0-41.79fb5193cf0a8fdbef536e4b4a159cad677ab1b9",
|
||||
"resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-5.7.0-41.79fb5193cf0a8fdbef536e4b4a159cad677ab1b9.tgz",
|
||||
"integrity": "sha512-V6tgRVi62jRwTm0Hglky3Scwjr/AKFBFtS+MdbsBr7UOuiu1TKLPc6xfPiyEN1+bYqjEtjxwGsHgahcJsd1rNg==",
|
||||
"devOptional": true
|
||||
"version": "5.9.0-32.23fdc5965b1e05fc54e5f26ed3de66776b93de64",
|
||||
"resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-5.9.0-32.23fdc5965b1e05fc54e5f26ed3de66776b93de64.tgz",
|
||||
"integrity": "sha512-HFl7275yF0FWbdcNvcSRbbu9JCBSLMcurYwvWc8WGDnpu7APxQo2ONtZrUggU3WxLxUJ2uBX+0GOFIcJeVeOOQ=="
|
||||
},
|
||||
"node_modules/@prisma/get-platform": {
|
||||
"version": "5.7.0",
|
||||
"resolved": "https://registry.npmjs.org/@prisma/get-platform/-/get-platform-5.7.0.tgz",
|
||||
"integrity": "sha512-ZeV/Op4bZsWXuw5Tg05WwRI8BlKiRFhsixPcAM+5BKYSiUZiMKIi713tfT3drBq8+T0E1arNZgYSA9QYcglWNA==",
|
||||
"devOptional": true,
|
||||
"version": "5.9.1",
|
||||
"resolved": "https://registry.npmjs.org/@prisma/get-platform/-/get-platform-5.9.1.tgz",
|
||||
"integrity": "sha512-6OQsNxTyhvG+T2Ksr8FPFpuPeL4r9u0JF0OZHUBI/Uy9SS43sPyAIutt4ZEAyqWQt104ERh70EZedkHZKsnNbg==",
|
||||
"dependencies": {
|
||||
"@prisma/debug": "5.7.0"
|
||||
"@prisma/debug": "5.9.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@radix-ui/number": {
|
||||
@@ -3071,12 +3058,17 @@
|
||||
"node": ">=14.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@swc/counter": {
|
||||
"version": "0.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@swc/counter/-/counter-0.1.3.tgz",
|
||||
"integrity": "sha512-e2BR4lsJkkRlKZ/qCHPw9ZaSxc0MVUd7gtbtaB7aMvHeJVYe8sOB8DBZkP2DtISHGSku9sCK6T6cnY0CtXrOCQ=="
|
||||
},
|
||||
"node_modules/@swc/helpers": {
|
||||
"version": "0.5.2",
|
||||
"resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.2.tgz",
|
||||
"integrity": "sha512-E4KcWTpoLHqwPHLxidpOqQbcrZVgi0rsmmZXUle1jXmJfuIf/UWpczUJ7MZZ5tlxytgJXyp0w4PGkkeLiuIdZw==",
|
||||
"license": "Apache-2.0",
|
||||
"version": "0.5.5",
|
||||
"resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.5.tgz",
|
||||
"integrity": "sha512-KGYxvIOXcceOAbEk4bi/dVLEK9z8sZ0uBB3Il5b1rhfClSpcX0yfRO0KmTkqR2cnQDymwLB+25ZyMzICg/cm/A==",
|
||||
"dependencies": {
|
||||
"@swc/counter": "^0.1.3",
|
||||
"tslib": "^2.4.0"
|
||||
}
|
||||
},
|
||||
@@ -6586,12 +6578,12 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/next": {
|
||||
"version": "14.1.0",
|
||||
"resolved": "https://registry.npmjs.org/next/-/next-14.1.0.tgz",
|
||||
"integrity": "sha512-wlzrsbfeSU48YQBjZhDzOwhWhGsy+uQycR8bHAOt1LY1bn3zZEcDyHQOEoN3aWzQ8LHCAJ1nqrWCc9XF2+O45Q==",
|
||||
"version": "14.2.3",
|
||||
"resolved": "https://registry.npmjs.org/next/-/next-14.2.3.tgz",
|
||||
"integrity": "sha512-dowFkFTR8v79NPJO4QsBUtxv0g9BrS/phluVpMAt2ku7H+cbcBJlopXjkWlwxrk/xGqMemr7JkGPGemPrLLX7A==",
|
||||
"dependencies": {
|
||||
"@next/env": "14.1.0",
|
||||
"@swc/helpers": "0.5.2",
|
||||
"@next/env": "14.2.3",
|
||||
"@swc/helpers": "0.5.5",
|
||||
"busboy": "1.6.0",
|
||||
"caniuse-lite": "^1.0.30001579",
|
||||
"graceful-fs": "^4.2.11",
|
||||
@@ -6605,18 +6597,19 @@
|
||||
"node": ">=18.17.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@next/swc-darwin-arm64": "14.1.0",
|
||||
"@next/swc-darwin-x64": "14.1.0",
|
||||
"@next/swc-linux-arm64-gnu": "14.1.0",
|
||||
"@next/swc-linux-arm64-musl": "14.1.0",
|
||||
"@next/swc-linux-x64-gnu": "14.1.0",
|
||||
"@next/swc-linux-x64-musl": "14.1.0",
|
||||
"@next/swc-win32-arm64-msvc": "14.1.0",
|
||||
"@next/swc-win32-ia32-msvc": "14.1.0",
|
||||
"@next/swc-win32-x64-msvc": "14.1.0"
|
||||
"@next/swc-darwin-arm64": "14.2.3",
|
||||
"@next/swc-darwin-x64": "14.2.3",
|
||||
"@next/swc-linux-arm64-gnu": "14.2.3",
|
||||
"@next/swc-linux-arm64-musl": "14.2.3",
|
||||
"@next/swc-linux-x64-gnu": "14.2.3",
|
||||
"@next/swc-linux-x64-musl": "14.2.3",
|
||||
"@next/swc-win32-arm64-msvc": "14.2.3",
|
||||
"@next/swc-win32-ia32-msvc": "14.2.3",
|
||||
"@next/swc-win32-x64-msvc": "14.2.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@opentelemetry/api": "^1.1.0",
|
||||
"@playwright/test": "^1.41.2",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"sass": "^1.3.0"
|
||||
@@ -6625,6 +6618,9 @@
|
||||
"@opentelemetry/api": {
|
||||
"optional": true
|
||||
},
|
||||
"@playwright/test": {
|
||||
"optional": true
|
||||
},
|
||||
"sass": {
|
||||
"optional": true
|
||||
}
|
||||
@@ -7430,13 +7426,12 @@
|
||||
}
|
||||
},
|
||||
"node_modules/prisma": {
|
||||
"version": "5.7.0",
|
||||
"resolved": "https://registry.npmjs.org/prisma/-/prisma-5.7.0.tgz",
|
||||
"integrity": "sha512-0rcfXO2ErmGAtxnuTNHQT9ztL0zZheQjOI/VNJzdq87C3TlGPQtMqtM+KCwU6XtmkoEr7vbCQqA7HF9IY0ST+Q==",
|
||||
"devOptional": true,
|
||||
"version": "5.9.1",
|
||||
"resolved": "https://registry.npmjs.org/prisma/-/prisma-5.9.1.tgz",
|
||||
"integrity": "sha512-Hy/8KJZz0ELtkw4FnG9MS9rNWlXcJhf98Z2QMqi0QiVMoS8PzsBkpla0/Y5hTlob8F3HeECYphBjqmBxrluUrQ==",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@prisma/engines": "5.7.0"
|
||||
"@prisma/engines": "5.9.1"
|
||||
},
|
||||
"bin": {
|
||||
"prisma": "build/index.js"
|
||||
@@ -7487,9 +7482,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/react": {
|
||||
"version": "18.2.0",
|
||||
"resolved": "https://registry.npmjs.org/react/-/react-18.2.0.tgz",
|
||||
"integrity": "sha512-/3IjMdb2L9QbBdWiW5e3P2/npwMBaU9mHCSCUzNln0ZCYbcfTsGbTJrU/kGemdH2IWmB2ioZ+zkxtmq6g09fGQ==",
|
||||
"version": "18.3.1",
|
||||
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
|
||||
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.1.0"
|
||||
},
|
||||
@@ -7498,15 +7493,15 @@
|
||||
}
|
||||
},
|
||||
"node_modules/react-dom": {
|
||||
"version": "18.2.0",
|
||||
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.2.0.tgz",
|
||||
"integrity": "sha512-6IMTriUmvsjHUjNtEDudZfuDQUoWXVxKHhlEGSk81n4YFS+r/Kl99wXiwlVXtPBtJenozv2P+hxDsw9eA7Xo6g==",
|
||||
"version": "18.3.1",
|
||||
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
|
||||
"integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.1.0",
|
||||
"scheduler": "^0.23.0"
|
||||
"scheduler": "^0.23.2"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^18.2.0"
|
||||
"react": "^18.3.1"
|
||||
}
|
||||
},
|
||||
"node_modules/react-hook-form": {
|
||||
@@ -7525,6 +7520,20 @@
|
||||
"react": "^16.8.0 || ^17 || ^18"
|
||||
}
|
||||
},
|
||||
"node_modules/react-intersection-observer": {
|
||||
"version": "9.8.0",
|
||||
"resolved": "https://registry.npmjs.org/react-intersection-observer/-/react-intersection-observer-9.8.0.tgz",
|
||||
"integrity": "sha512-wXHvMQUsTagh3X0Z6jDtGkIXc3VVCd2tjDRYR9kII3GKrZr0XF0xtpfdamo2n8BSF+zzfeeBVOTjxZWpBp9X0g==",
|
||||
"peerDependencies": {
|
||||
"react": "^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0",
|
||||
"react-dom": "^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"react-dom": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/react-is": {
|
||||
"version": "16.13.1",
|
||||
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
|
||||
@@ -7838,10 +7847,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/scheduler": {
|
||||
"version": "0.23.0",
|
||||
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.0.tgz",
|
||||
"integrity": "sha512-CtuThmgHNg7zIZWAXi3AsyIzA3n4xx7aNyjwC2VJldO2LMVDhFK+63xGqq6CsJH4rTAt6/M+N4GhZiDYPx9eUw==",
|
||||
"license": "MIT",
|
||||
"version": "0.23.2",
|
||||
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",
|
||||
"integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.1.0"
|
||||
}
|
||||
|
||||
10
package.json
10
package.json
@@ -9,6 +9,7 @@
|
||||
"lint": "next lint",
|
||||
"check-types": "tsc --noEmit",
|
||||
"check-formatting": "prettier -c src",
|
||||
"prettier": "prettier -w src",
|
||||
"postinstall": "prisma migrate deploy && prisma generate",
|
||||
"build-image": "./scripts/build-image.sh",
|
||||
"start-container": "docker compose --env-file container.env up"
|
||||
@@ -38,15 +39,17 @@
|
||||
"embla-carousel-react": "^8.0.0-rc21",
|
||||
"lucide-react": "^0.290.0",
|
||||
"nanoid": "^5.0.4",
|
||||
"next": "^14.1.0",
|
||||
"next": "^14.2.3",
|
||||
"next-s3-upload": "^0.3.4",
|
||||
"next-themes": "^0.2.1",
|
||||
"next13-progressbar": "^1.1.1",
|
||||
"openai": "^4.25.0",
|
||||
"pg": "^8.11.3",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"prisma": "^5.7.0",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-hook-form": "^7.47.0",
|
||||
"react-intersection-observer": "^9.8.0",
|
||||
"sharp": "^0.33.2",
|
||||
"tailwind-merge": "^1.14.0",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
@@ -70,7 +73,6 @@
|
||||
"postcss": "^8",
|
||||
"prettier": "^3.0.3",
|
||||
"prettier-plugin-organize-imports": "^3.2.3",
|
||||
"prisma": "^5.7.0",
|
||||
"tailwindcss": "^3",
|
||||
"tsconfig-paths": "^4.2.0",
|
||||
"typescript": "^5.3.3"
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "Expense" ADD COLUMN "notes" TEXT;
|
||||
@@ -0,0 +1,18 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "ActivityType" AS ENUM ('UPDATE_GROUP', 'CREATE_EXPENSE', 'UPDATE_EXPENSE', 'DELETE_EXPENSE');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Activity" (
|
||||
"id" TEXT NOT NULL,
|
||||
"groupId" TEXT NOT NULL,
|
||||
"time" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"activityType" "ActivityType" NOT NULL,
|
||||
"participantId" TEXT,
|
||||
"expenseId" TEXT,
|
||||
"data" TEXT,
|
||||
|
||||
CONSTRAINT "Activity_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Activity" ADD CONSTRAINT "Activity_groupId_fkey" FOREIGN KEY ("groupId") REFERENCES "Group"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
@@ -17,6 +17,7 @@ model Group {
|
||||
currency String @default("$")
|
||||
participants Participant[]
|
||||
expenses Expense[]
|
||||
activities Activity[]
|
||||
createdAt DateTime @default(now())
|
||||
}
|
||||
|
||||
@@ -52,6 +53,7 @@ model Expense {
|
||||
splitMode SplitMode @default(EVENLY)
|
||||
createdAt DateTime @default(now())
|
||||
documents ExpenseDocument[]
|
||||
notes String?
|
||||
}
|
||||
|
||||
model ExpenseDocument {
|
||||
@@ -79,3 +81,21 @@ model ExpensePaidFor {
|
||||
|
||||
@@id([expenseId, participantId])
|
||||
}
|
||||
|
||||
model Activity {
|
||||
id String @id
|
||||
group Group @relation(fields: [groupId], references: [id])
|
||||
groupId String
|
||||
time DateTime @default(now())
|
||||
activityType ActivityType
|
||||
participantId String?
|
||||
expenseId String?
|
||||
data String?
|
||||
}
|
||||
|
||||
enum ActivityType {
|
||||
UPDATE_GROUP
|
||||
CREATE_EXPENSE
|
||||
UPDATE_EXPENSE
|
||||
DELETE_EXPENSE
|
||||
}
|
||||
|
||||
@@ -5,9 +5,6 @@ SPLIIT_VERSION=$(node -p -e "require('./package.json').version")
|
||||
|
||||
# we need to set dummy data for POSTGRES env vars in order for build not to fail
|
||||
docker buildx build \
|
||||
--no-cache \
|
||||
--build-arg POSTGRES_PRISMA_URL=postgresql://build:@db \
|
||||
--build-arg POSTGRES_URL_NON_POOLING=postgresql://build:@db \
|
||||
-t ${SPLIIT_APP_NAME}:${SPLIIT_VERSION} \
|
||||
-t ${SPLIIT_APP_NAME}:latest \
|
||||
.
|
||||
|
||||
22
scripts/build.env
Normal file
22
scripts/build.env
Normal file
@@ -0,0 +1,22 @@
|
||||
# build file that contains all possible env vars with mocked values
|
||||
# as most of them are used at build time in order to have the production build to work properly
|
||||
|
||||
# db
|
||||
POSTGRES_PASSWORD=1234
|
||||
|
||||
# app
|
||||
POSTGRES_PRISMA_URL=postgresql://postgres:${POSTGRES_PASSWORD}@db
|
||||
POSTGRES_URL_NON_POOLING=postgresql://postgres:${POSTGRES_PASSWORD}@db
|
||||
|
||||
# app-minio
|
||||
NEXT_PUBLIC_ENABLE_EXPENSE_DOCUMENTS=false
|
||||
S3_UPLOAD_KEY=AAAAAAAAAAAAAAAAAAAA
|
||||
S3_UPLOAD_SECRET=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
||||
S3_UPLOAD_BUCKET=spliit
|
||||
S3_UPLOAD_REGION=eu-north-1
|
||||
S3_UPLOAD_ENDPOINT=s3://minio.example.com
|
||||
|
||||
# app-openai
|
||||
NEXT_PUBLIC_ENABLE_RECEIPT_EXTRACT=false
|
||||
OPENAI_API_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXX
|
||||
NEXT_PUBLIC_ENABLE_CATEGORY_EXTRACT=false
|
||||
@@ -1,3 +1,6 @@
|
||||
#!/bin/bash
|
||||
prisma migrate deploy
|
||||
|
||||
set -euxo pipefail
|
||||
|
||||
npx prisma migrate deploy
|
||||
npm run start
|
||||
|
||||
@@ -6,6 +6,6 @@ else
|
||||
echo "postgres is not running, starting it"
|
||||
docker rm postgres --force
|
||||
mkdir -p postgres-data
|
||||
docker run --name postgres -d -p 5432:5432 -e POSTGRES_PASSWORD=1234 -v ./postgres-data:/var/lib/postgresql/data postgres
|
||||
docker run --name postgres -d -p 5432:5432 -e POSTGRES_PASSWORD=1234 -v "/$(pwd)/postgres-data:/var/lib/postgresql/data" postgres
|
||||
sleep 5 # Wait for postgres to start
|
||||
fi
|
||||
|
||||
102
src/app/groups/[groupId]/activity/activity-item.tsx
Normal file
102
src/app/groups/[groupId]/activity/activity-item.tsx
Normal file
@@ -0,0 +1,102 @@
|
||||
'use client'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { getGroupExpenses } from '@/lib/api'
|
||||
import { DateTimeStyle, cn, formatDate } from '@/lib/utils'
|
||||
import { Activity, ActivityType, Participant } from '@prisma/client'
|
||||
import { ChevronRight } from 'lucide-react'
|
||||
import Link from 'next/link'
|
||||
import { useRouter } from 'next/navigation'
|
||||
|
||||
type Props = {
|
||||
groupId: string
|
||||
activity: Activity
|
||||
participant?: Participant
|
||||
expense?: Awaited<ReturnType<typeof getGroupExpenses>>[number]
|
||||
dateStyle: DateTimeStyle
|
||||
}
|
||||
|
||||
function getSummary(activity: Activity, participantName?: string) {
|
||||
const participant = participantName ?? 'Someone'
|
||||
const expense = activity.data ?? ''
|
||||
if (activity.activityType == ActivityType.UPDATE_GROUP) {
|
||||
return (
|
||||
<>
|
||||
Group settings were modified by <strong>{participant}</strong>
|
||||
</>
|
||||
)
|
||||
} else if (activity.activityType == ActivityType.CREATE_EXPENSE) {
|
||||
return (
|
||||
<>
|
||||
Expense <em>“{expense}”</em> created by{' '}
|
||||
<strong>{participant}</strong>.
|
||||
</>
|
||||
)
|
||||
} else if (activity.activityType == ActivityType.UPDATE_EXPENSE) {
|
||||
return (
|
||||
<>
|
||||
Expense <em>“{expense}”</em> updated by{' '}
|
||||
<strong>{participant}</strong>.
|
||||
</>
|
||||
)
|
||||
} else if (activity.activityType == ActivityType.DELETE_EXPENSE) {
|
||||
return (
|
||||
<>
|
||||
Expense <em>“{expense}”</em> deleted by{' '}
|
||||
<strong>{participant}</strong>.
|
||||
</>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export function ActivityItem({
|
||||
groupId,
|
||||
activity,
|
||||
participant,
|
||||
expense,
|
||||
dateStyle,
|
||||
}: Props) {
|
||||
const router = useRouter()
|
||||
|
||||
const expenseExists = expense !== undefined
|
||||
const summary = getSummary(activity, participant?.name)
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'flex justify-between sm:rounded-lg px-2 sm:pr-1 sm:pl-2 py-2 text-sm hover:bg-accent gap-1 items-stretch',
|
||||
expenseExists && 'cursor-pointer',
|
||||
)}
|
||||
onClick={() => {
|
||||
if (expenseExists) {
|
||||
router.push(`/groups/${groupId}/expenses/${activity.expenseId}/edit`)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex flex-col justify-between items-start">
|
||||
{dateStyle !== undefined && (
|
||||
<div className="mt-1 text-xs/5 text-muted-foreground">
|
||||
{formatDate(activity.time, { dateStyle })}
|
||||
</div>
|
||||
)}
|
||||
<div className="my-1 text-xs/5 text-muted-foreground">
|
||||
{formatDate(activity.time, { timeStyle: 'short' })}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<div className="m-1">{summary}</div>
|
||||
</div>
|
||||
{expenseExists && (
|
||||
<Button
|
||||
size="icon"
|
||||
variant="link"
|
||||
className="self-center hidden sm:flex w-5 h-5"
|
||||
asChild
|
||||
>
|
||||
<Link href={`/groups/${groupId}/expenses/${activity.expenseId}/edit`}>
|
||||
<ChevronRight className="w-4 h-4" />
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
112
src/app/groups/[groupId]/activity/activity-list.tsx
Normal file
112
src/app/groups/[groupId]/activity/activity-list.tsx
Normal file
@@ -0,0 +1,112 @@
|
||||
import { ActivityItem } from '@/app/groups/[groupId]/activity/activity-item'
|
||||
import { getGroupExpenses } from '@/lib/api'
|
||||
import { Activity, Participant } from '@prisma/client'
|
||||
import dayjs, { type Dayjs } from 'dayjs'
|
||||
|
||||
type Props = {
|
||||
groupId: string
|
||||
participants: Participant[]
|
||||
expenses: Awaited<ReturnType<typeof getGroupExpenses>>
|
||||
activities: Activity[]
|
||||
}
|
||||
|
||||
const DATE_GROUPS = {
|
||||
TODAY: 'Today',
|
||||
YESTERDAY: 'Yesterday',
|
||||
EARLIER_THIS_WEEK: 'Earlier this week',
|
||||
LAST_WEEK: 'Last week',
|
||||
EARLIER_THIS_MONTH: 'Earlier this month',
|
||||
LAST_MONTH: 'Last month',
|
||||
EARLIER_THIS_YEAR: 'Earlier this year',
|
||||
LAST_YEAR: 'Last year',
|
||||
OLDER: 'Older',
|
||||
}
|
||||
|
||||
function getDateGroup(date: Dayjs, today: Dayjs) {
|
||||
if (today.isSame(date, 'day')) {
|
||||
return DATE_GROUPS.TODAY
|
||||
} else if (today.subtract(1, 'day').isSame(date, 'day')) {
|
||||
return DATE_GROUPS.YESTERDAY
|
||||
} else if (today.isSame(date, 'week')) {
|
||||
return DATE_GROUPS.EARLIER_THIS_WEEK
|
||||
} else if (today.subtract(1, 'week').isSame(date, 'week')) {
|
||||
return DATE_GROUPS.LAST_WEEK
|
||||
} else if (today.isSame(date, 'month')) {
|
||||
return DATE_GROUPS.EARLIER_THIS_MONTH
|
||||
} else if (today.subtract(1, 'month').isSame(date, 'month')) {
|
||||
return DATE_GROUPS.LAST_MONTH
|
||||
} else if (today.isSame(date, 'year')) {
|
||||
return DATE_GROUPS.EARLIER_THIS_YEAR
|
||||
} else if (today.subtract(1, 'year').isSame(date, 'year')) {
|
||||
return DATE_GROUPS.LAST_YEAR
|
||||
} else {
|
||||
return DATE_GROUPS.OLDER
|
||||
}
|
||||
}
|
||||
|
||||
function getGroupedActivitiesByDate(activities: Activity[]) {
|
||||
const today = dayjs()
|
||||
return activities.reduce(
|
||||
(result: { [key: string]: Activity[] }, activity: Activity) => {
|
||||
const activityGroup = getDateGroup(dayjs(activity.time), today)
|
||||
result[activityGroup] = result[activityGroup] ?? []
|
||||
result[activityGroup].push(activity)
|
||||
return result
|
||||
},
|
||||
{},
|
||||
)
|
||||
}
|
||||
|
||||
export function ActivityList({
|
||||
groupId,
|
||||
participants,
|
||||
expenses,
|
||||
activities,
|
||||
}: Props) {
|
||||
const groupedActivitiesByDate = getGroupedActivitiesByDate(activities)
|
||||
|
||||
return activities.length > 0 ? (
|
||||
<>
|
||||
{Object.values(DATE_GROUPS).map((dateGroup: string) => {
|
||||
let groupActivities = groupedActivitiesByDate[dateGroup]
|
||||
if (!groupActivities || groupActivities.length === 0) return null
|
||||
const dateStyle =
|
||||
dateGroup == DATE_GROUPS.TODAY || dateGroup == DATE_GROUPS.YESTERDAY
|
||||
? undefined
|
||||
: 'medium'
|
||||
|
||||
return (
|
||||
<div key={dateGroup}>
|
||||
<div
|
||||
className={
|
||||
'text-muted-foreground text-xs py-1 font-semibold sticky top-16 bg-white dark:bg-[#1b1917]'
|
||||
}
|
||||
>
|
||||
{dateGroup}
|
||||
</div>
|
||||
{groupActivities.map((activity: Activity) => {
|
||||
const participant =
|
||||
activity.participantId !== null
|
||||
? participants.find((p) => p.id === activity.participantId)
|
||||
: undefined
|
||||
const expense =
|
||||
activity.expenseId !== null
|
||||
? expenses.find((e) => e.id === activity.expenseId)
|
||||
: undefined
|
||||
return (
|
||||
<ActivityItem
|
||||
key={activity.id}
|
||||
{...{ groupId, activity, participant, expense, dateStyle }}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</>
|
||||
) : (
|
||||
<p className="px-6 text-sm py-6">
|
||||
There is not yet any activity in your group.
|
||||
</p>
|
||||
)
|
||||
}
|
||||
51
src/app/groups/[groupId]/activity/page.tsx
Normal file
51
src/app/groups/[groupId]/activity/page.tsx
Normal file
@@ -0,0 +1,51 @@
|
||||
import { cached } from '@/app/cached-functions'
|
||||
import { ActivityList } from '@/app/groups/[groupId]/activity/activity-list'
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@/components/ui/card'
|
||||
import { getActivities, getGroupExpenses } from '@/lib/api'
|
||||
import { Metadata } from 'next'
|
||||
import { notFound } from 'next/navigation'
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Activity',
|
||||
}
|
||||
|
||||
export default async function ActivityPage({
|
||||
params: { groupId },
|
||||
}: {
|
||||
params: { groupId: string }
|
||||
}) {
|
||||
const group = await cached.getGroup(groupId)
|
||||
if (!group) notFound()
|
||||
|
||||
const expenses = await getGroupExpenses(groupId)
|
||||
const activities = await getActivities(groupId)
|
||||
|
||||
return (
|
||||
<>
|
||||
<Card className="mb-4">
|
||||
<CardHeader>
|
||||
<CardTitle>Activity</CardTitle>
|
||||
<CardDescription>
|
||||
Overview of all activity in this group.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col space-y-4">
|
||||
<ActivityList
|
||||
{...{
|
||||
groupId,
|
||||
participants: group.participants,
|
||||
expenses,
|
||||
activities,
|
||||
}}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -17,10 +17,10 @@ export default async function EditGroupPage({
|
||||
const group = await cached.getGroup(groupId)
|
||||
if (!group) notFound()
|
||||
|
||||
async function updateGroupAction(values: unknown) {
|
||||
async function updateGroupAction(values: unknown, participantId?: string) {
|
||||
'use server'
|
||||
const groupFormValues = groupFormSchema.parse(values)
|
||||
const group = await updateGroup(groupId, groupFormValues)
|
||||
const group = await updateGroup(groupId, groupFormValues, participantId)
|
||||
redirect(`/groups/${group.id}`)
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
getExpense,
|
||||
updateExpense,
|
||||
} from '@/lib/api'
|
||||
import { getRuntimeFeatureFlags } from '@/lib/featureFlags'
|
||||
import { expenseFormSchema } from '@/lib/schemas'
|
||||
import { Metadata } from 'next'
|
||||
import { notFound, redirect } from 'next/navigation'
|
||||
@@ -26,16 +27,16 @@ export default async function EditExpensePage({
|
||||
const expense = await getExpense(groupId, expenseId)
|
||||
if (!expense) notFound()
|
||||
|
||||
async function updateExpenseAction(values: unknown) {
|
||||
async function updateExpenseAction(values: unknown, participantId?: string) {
|
||||
'use server'
|
||||
const expenseFormValues = expenseFormSchema.parse(values)
|
||||
await updateExpense(groupId, expenseId, expenseFormValues)
|
||||
await updateExpense(groupId, expenseId, expenseFormValues, participantId)
|
||||
redirect(`/groups/${groupId}`)
|
||||
}
|
||||
|
||||
async function deleteExpenseAction() {
|
||||
async function deleteExpenseAction(participantId?: string) {
|
||||
'use server'
|
||||
await deleteExpense(expenseId)
|
||||
await deleteExpense(groupId, expenseId, participantId)
|
||||
redirect(`/groups/${groupId}`)
|
||||
}
|
||||
|
||||
@@ -47,6 +48,7 @@ export default async function EditExpensePage({
|
||||
categories={categories}
|
||||
onSubmit={updateExpenseAction}
|
||||
onDelete={deleteExpenseAction}
|
||||
runtimeFeatureFlags={await getRuntimeFeatureFlags()}
|
||||
/>
|
||||
</Suspense>
|
||||
)
|
||||
|
||||
43
src/app/groups/[groupId]/expenses/active-user-balance.tsx
Normal file
43
src/app/groups/[groupId]/expenses/active-user-balance.tsx
Normal file
@@ -0,0 +1,43 @@
|
||||
'use client'
|
||||
import { Money } from '@/components/money'
|
||||
import { getBalances } from '@/lib/balances'
|
||||
import { useActiveUser } from '@/lib/hooks'
|
||||
|
||||
type Props = {
|
||||
groupId: string
|
||||
currency: string
|
||||
expense: Parameters<typeof getBalances>[0][number]
|
||||
}
|
||||
|
||||
export function ActiveUserBalance({ groupId, currency, expense }: Props) {
|
||||
const activeUserId = useActiveUser(groupId)
|
||||
if (activeUserId === null || activeUserId === '' || activeUserId === 'None') {
|
||||
return null
|
||||
}
|
||||
|
||||
const balances = getBalances([expense])
|
||||
let fmtBalance = <>You are not involved</>
|
||||
if (Object.hasOwn(balances, activeUserId)) {
|
||||
const balance = balances[activeUserId]
|
||||
let balanceDetail = <></>
|
||||
if (balance.paid > 0 && balance.paidFor > 0) {
|
||||
balanceDetail = (
|
||||
<>
|
||||
{' ('}
|
||||
<Money {...{ currency, amount: balance.paid }} />
|
||||
{' - '}
|
||||
<Money {...{ currency, amount: balance.paidFor }} />
|
||||
{')'}
|
||||
</>
|
||||
)
|
||||
}
|
||||
fmtBalance = (
|
||||
<>
|
||||
Your balance:{' '}
|
||||
<Money {...{ currency, amount: balance.total }} bold colored />
|
||||
{balanceDetail}
|
||||
</>
|
||||
)
|
||||
}
|
||||
return <div className="text-xs text-muted-foreground">{fmtBalance}</div>
|
||||
}
|
||||
@@ -26,7 +26,7 @@ import {
|
||||
import { ToastAction } from '@/components/ui/toast'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { useMediaQuery } from '@/lib/hooks'
|
||||
import { formatCurrency, formatExpenseDate, formatFileSize } from '@/lib/utils'
|
||||
import { formatCurrency, formatDate, formatFileSize } from '@/lib/utils'
|
||||
import { Category } from '@prisma/client'
|
||||
import { ChevronRight, FileQuestion, Loader2, Receipt } from 'lucide-react'
|
||||
import { getImageData, usePresignedUpload } from 'next-s3-upload'
|
||||
@@ -212,9 +212,9 @@ export function CreateFromReceiptButton({
|
||||
<div>
|
||||
{receiptInfo ? (
|
||||
receiptInfo.date ? (
|
||||
formatExpenseDate(
|
||||
new Date(`${receiptInfo?.date}T12:00:00.000Z`),
|
||||
)
|
||||
formatDate(new Date(`${receiptInfo?.date}T12:00:00.000Z`), {
|
||||
dateStyle: 'medium',
|
||||
})
|
||||
) : (
|
||||
<Unknown />
|
||||
)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { cached } from '@/app/cached-functions'
|
||||
import { ExpenseForm } from '@/components/expense-form'
|
||||
import { createExpense, getCategories } from '@/lib/api'
|
||||
import { getRuntimeFeatureFlags } from '@/lib/featureFlags'
|
||||
import { expenseFormSchema } from '@/lib/schemas'
|
||||
import { Metadata } from 'next'
|
||||
import { notFound, redirect } from 'next/navigation'
|
||||
@@ -19,10 +20,10 @@ export default async function ExpensePage({
|
||||
const group = await cached.getGroup(groupId)
|
||||
if (!group) notFound()
|
||||
|
||||
async function createExpenseAction(values: unknown) {
|
||||
async function createExpenseAction(values: unknown, participantId?: string) {
|
||||
'use server'
|
||||
const expenseFormValues = expenseFormSchema.parse(values)
|
||||
await createExpense(expenseFormValues, groupId)
|
||||
await createExpense(expenseFormValues, groupId, participantId)
|
||||
redirect(`/groups/${groupId}`)
|
||||
}
|
||||
|
||||
@@ -32,6 +33,7 @@ export default async function ExpensePage({
|
||||
group={group}
|
||||
categories={categories}
|
||||
onSubmit={createExpenseAction}
|
||||
runtimeFeatureFlags={await getRuntimeFeatureFlags()}
|
||||
/>
|
||||
</Suspense>
|
||||
)
|
||||
|
||||
79
src/app/groups/[groupId]/expenses/expense-card.tsx
Normal file
79
src/app/groups/[groupId]/expenses/expense-card.tsx
Normal file
@@ -0,0 +1,79 @@
|
||||
'use client'
|
||||
import { ActiveUserBalance } from '@/app/groups/[groupId]/expenses/active-user-balance'
|
||||
import { CategoryIcon } from '@/app/groups/[groupId]/expenses/category-icon'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { getGroupExpenses } from '@/lib/api'
|
||||
import { cn, formatCurrency, formatDate } from '@/lib/utils'
|
||||
import { ChevronRight } from 'lucide-react'
|
||||
import Link from 'next/link'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { Fragment } from 'react'
|
||||
|
||||
type Props = {
|
||||
expense: Awaited<ReturnType<typeof getGroupExpenses>>[number]
|
||||
currency: string
|
||||
groupId: string
|
||||
}
|
||||
|
||||
export function ExpenseCard({ expense, currency, groupId }: Props) {
|
||||
const router = useRouter()
|
||||
|
||||
return (
|
||||
<div
|
||||
key={expense.id}
|
||||
className={cn(
|
||||
'flex justify-between sm:mx-6 px-4 sm:rounded-lg sm:pr-2 sm:pl-4 py-4 text-sm cursor-pointer hover:bg-accent gap-1 items-stretch',
|
||||
expense.isReimbursement && 'italic',
|
||||
)}
|
||||
onClick={() => {
|
||||
router.push(`/groups/${groupId}/expenses/${expense.id}/edit`)
|
||||
}}
|
||||
>
|
||||
<CategoryIcon
|
||||
category={expense.category}
|
||||
className="w-4 h-4 mr-2 mt-0.5 text-muted-foreground"
|
||||
/>
|
||||
<div className="flex-1">
|
||||
<div className={cn('mb-1', expense.isReimbursement && 'italic')}>
|
||||
{expense.title}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{expense.amount > 0 ? 'Paid by ' : 'Received by '}
|
||||
<strong>{expense.paidBy.name}</strong> for{' '}
|
||||
{expense.paidFor.map((paidFor, index) => (
|
||||
<Fragment key={index}>
|
||||
{index !== 0 && <>, </>}
|
||||
<strong>{paidFor.participant.name}</strong>
|
||||
</Fragment>
|
||||
))}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
<ActiveUserBalance {...{ groupId, currency, expense }} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col justify-between items-end">
|
||||
<div
|
||||
className={cn(
|
||||
'tabular-nums whitespace-nowrap',
|
||||
expense.isReimbursement ? 'italic' : 'font-bold',
|
||||
)}
|
||||
>
|
||||
{formatCurrency(currency, expense.amount)}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{formatDate(expense.expenseDate, { dateStyle: 'medium' })}
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
size="icon"
|
||||
variant="link"
|
||||
className="self-center hidden sm:flex"
|
||||
asChild
|
||||
>
|
||||
<Link href={`/groups/${groupId}/expenses/${expense.id}/edit`}>
|
||||
<ChevronRight className="w-4 h-4" />
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
'use server'
|
||||
|
||||
import { getGroupExpenses } from '@/lib/api'
|
||||
|
||||
export async function getGroupExpensesAction(
|
||||
groupId: string,
|
||||
options?: { offset: number; length: number },
|
||||
) {
|
||||
'use server'
|
||||
|
||||
try {
|
||||
return getGroupExpenses(groupId, options)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -1,24 +1,29 @@
|
||||
'use client'
|
||||
import { CategoryIcon } from '@/app/groups/[groupId]/expenses/category-icon'
|
||||
import { ExpenseCard } from '@/app/groups/[groupId]/expenses/expense-card'
|
||||
import { getGroupExpensesAction } from '@/app/groups/[groupId]/expenses/expense-list-fetch-action'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { SearchBar } from '@/components/ui/search-bar'
|
||||
import { getGroupExpenses } from '@/lib/api'
|
||||
import { cn, formatCurrency, formatExpenseDate } from '@/lib/utils'
|
||||
import { Expense, Participant } from '@prisma/client'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { Participant } from '@prisma/client'
|
||||
import dayjs, { type Dayjs } from 'dayjs'
|
||||
import { ChevronRight } from 'lucide-react'
|
||||
import Link from 'next/link'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { Fragment, useEffect, useState } from 'react'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useInView } from 'react-intersection-observer'
|
||||
|
||||
type ExpensesType = NonNullable<
|
||||
Awaited<ReturnType<typeof getGroupExpensesAction>>
|
||||
>
|
||||
|
||||
type Props = {
|
||||
expenses: Awaited<ReturnType<typeof getGroupExpenses>>
|
||||
expensesFirstPage: ExpensesType
|
||||
expenseCount: number
|
||||
participants: Participant[]
|
||||
currency: string
|
||||
groupId: string
|
||||
}
|
||||
|
||||
const EXPENSE_GROUPS = {
|
||||
UPCOMING: 'Upcoming',
|
||||
THIS_WEEK: 'This week',
|
||||
EARLIER_THIS_MONTH: 'Earlier this month',
|
||||
LAST_MONTH: 'Last month',
|
||||
@@ -28,7 +33,9 @@ const EXPENSE_GROUPS = {
|
||||
}
|
||||
|
||||
function getExpenseGroup(date: Dayjs, today: Dayjs) {
|
||||
if (today.isSame(date, 'week')) {
|
||||
if (today.isBefore(date)) {
|
||||
return EXPENSE_GROUPS.UPCOMING
|
||||
} else if (today.isSame(date, 'week')) {
|
||||
return EXPENSE_GROUPS.THIS_WEEK
|
||||
} else if (today.isSame(date, 'month')) {
|
||||
return EXPENSE_GROUPS.EARLIER_THIS_MONTH
|
||||
@@ -43,28 +50,32 @@ function getExpenseGroup(date: Dayjs, today: Dayjs) {
|
||||
}
|
||||
}
|
||||
|
||||
function getGroupedExpensesByDate(
|
||||
expenses: Awaited<ReturnType<typeof getGroupExpenses>>,
|
||||
) {
|
||||
function getGroupedExpensesByDate(expenses: ExpensesType) {
|
||||
const today = dayjs()
|
||||
return expenses.reduce(
|
||||
(result: { [key: string]: Expense[] }, expense: Expense) => {
|
||||
const expenseGroup = getExpenseGroup(dayjs(expense.expenseDate), today)
|
||||
result[expenseGroup] = result[expenseGroup] ?? []
|
||||
result[expenseGroup].push(expense)
|
||||
return result
|
||||
},
|
||||
{},
|
||||
)
|
||||
return expenses.reduce((result: { [key: string]: ExpensesType }, expense) => {
|
||||
const expenseGroup = getExpenseGroup(dayjs(expense.expenseDate), today)
|
||||
result[expenseGroup] = result[expenseGroup] ?? []
|
||||
result[expenseGroup].push(expense)
|
||||
return result
|
||||
}, {})
|
||||
}
|
||||
|
||||
export function ExpenseList({
|
||||
expenses,
|
||||
expensesFirstPage,
|
||||
expenseCount,
|
||||
currency,
|
||||
participants,
|
||||
groupId,
|
||||
}: Props) {
|
||||
const firstLen = expensesFirstPage.length
|
||||
const [searchText, setSearchText] = useState('')
|
||||
const [dataIndex, setDataIndex] = useState(firstLen)
|
||||
const [dataLen, setDataLen] = useState(firstLen)
|
||||
const [hasMoreData, setHasMoreData] = useState(expenseCount > firstLen)
|
||||
const [isFetching, setIsFetching] = useState(false)
|
||||
const [expenses, setExpenses] = useState(expensesFirstPage)
|
||||
const { ref, inView } = useInView()
|
||||
|
||||
useEffect(() => {
|
||||
const activeUser = localStorage.getItem('newGroup-activeUser')
|
||||
const newUser = localStorage.getItem(`${groupId}-newUser`)
|
||||
@@ -84,13 +95,46 @@ export function ExpenseList({
|
||||
}
|
||||
}, [groupId, participants])
|
||||
|
||||
const getParticipant = (id: string) => participants.find((p) => p.id === id)
|
||||
const router = useRouter()
|
||||
useEffect(() => {
|
||||
const fetchNextPage = async () => {
|
||||
setIsFetching(true)
|
||||
|
||||
const newExpenses = await getGroupExpensesAction(groupId, {
|
||||
offset: dataIndex,
|
||||
length: dataLen,
|
||||
})
|
||||
|
||||
if (newExpenses !== null) {
|
||||
const exp = expenses.concat(newExpenses)
|
||||
setExpenses(exp)
|
||||
setHasMoreData(exp.length < expenseCount)
|
||||
setDataIndex(dataIndex + dataLen)
|
||||
setDataLen(Math.ceil(1.5 * dataLen))
|
||||
}
|
||||
|
||||
setTimeout(() => setIsFetching(false), 500)
|
||||
}
|
||||
|
||||
if (inView && hasMoreData && !isFetching) fetchNextPage()
|
||||
}, [
|
||||
dataIndex,
|
||||
dataLen,
|
||||
expenseCount,
|
||||
expenses,
|
||||
groupId,
|
||||
hasMoreData,
|
||||
inView,
|
||||
isFetching,
|
||||
])
|
||||
|
||||
const groupedExpensesByDate = useMemo(
|
||||
() => getGroupedExpensesByDate(expenses),
|
||||
[expenses],
|
||||
)
|
||||
|
||||
const groupedExpensesByDate = getGroupedExpensesByDate(expenses)
|
||||
return expenses.length > 0 ? (
|
||||
<>
|
||||
<SearchBar onChange={(e) => setSearchText(e.target.value)} />
|
||||
<SearchBar onValueChange={(value) => setSearchText(value)} />
|
||||
{Object.values(EXPENSE_GROUPS).map((expenseGroup: string) => {
|
||||
let groupExpenses = groupedExpensesByDate[expenseGroup]
|
||||
if (!groupExpenses) return null
|
||||
@@ -110,73 +154,33 @@ export function ExpenseList({
|
||||
>
|
||||
{expenseGroup}
|
||||
</div>
|
||||
{groupExpenses.map((expense: any) => (
|
||||
<div
|
||||
{groupExpenses.map((expense) => (
|
||||
<ExpenseCard
|
||||
key={expense.id}
|
||||
className={cn(
|
||||
'flex justify-between sm:mx-6 px-4 sm:rounded-lg sm:pr-2 sm:pl-4 py-4 text-sm cursor-pointer hover:bg-accent gap-1 items-stretch',
|
||||
expense.isReimbursement && 'italic',
|
||||
)}
|
||||
onClick={() => {
|
||||
router.push(`/groups/${groupId}/expenses/${expense.id}/edit`)
|
||||
}}
|
||||
>
|
||||
<CategoryIcon
|
||||
category={expense.category}
|
||||
className="w-4 h-4 mr-2 mt-0.5 text-muted-foreground"
|
||||
/>
|
||||
<div className="flex-1">
|
||||
<div
|
||||
className={cn('mb-1', expense.isReimbursement && 'italic')}
|
||||
>
|
||||
{expense.title}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
Paid by{' '}
|
||||
<strong>{getParticipant(expense.paidById)?.name}</strong>{' '}
|
||||
for{' '}
|
||||
{expense.paidFor.map((paidFor: any, index: number) => (
|
||||
<Fragment key={index}>
|
||||
{index !== 0 && <>, </>}
|
||||
<strong>
|
||||
{
|
||||
participants.find(
|
||||
(p) => p.id === paidFor.participantId,
|
||||
)?.name
|
||||
}
|
||||
</strong>
|
||||
</Fragment>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col justify-between items-end">
|
||||
<div
|
||||
className={cn(
|
||||
'tabular-nums whitespace-nowrap',
|
||||
expense.isReimbursement ? 'italic' : 'font-bold',
|
||||
)}
|
||||
>
|
||||
{formatCurrency(currency, expense.amount)}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{formatExpenseDate(expense.expenseDate)}
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
size="icon"
|
||||
variant="link"
|
||||
className="self-center hidden sm:flex"
|
||||
asChild
|
||||
>
|
||||
<Link href={`/groups/${groupId}/expenses/${expense.id}/edit`}>
|
||||
<ChevronRight className="w-4 h-4" />
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
expense={expense}
|
||||
currency={currency}
|
||||
groupId={groupId}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
{expenses.length < expenseCount &&
|
||||
[0, 1, 2].map((i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="border-t flex justify-between items-center px-6 py-4 text-sm"
|
||||
ref={i === 0 ? ref : undefined}
|
||||
>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Skeleton className="h-4 w-16 rounded-full" />
|
||||
<Skeleton className="h-4 w-32 rounded-full" />
|
||||
</div>
|
||||
<div>
|
||||
<Skeleton className="h-4 w-16 rounded-full" />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
) : (
|
||||
<p className="px-6 text-sm py-6">
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { getPrisma } from '@/lib/prisma'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import contentDisposition from 'content-disposition'
|
||||
import { NextResponse } from 'next/server'
|
||||
|
||||
@@ -6,7 +6,6 @@ export async function GET(
|
||||
req: Request,
|
||||
{ params: { groupId } }: { params: { groupId: string } },
|
||||
) {
|
||||
const prisma = await getPrisma()
|
||||
const group = await prisma.group.findUnique({
|
||||
where: { id: groupId },
|
||||
select: {
|
||||
|
||||
@@ -11,7 +11,11 @@ import {
|
||||
CardTitle,
|
||||
} from '@/components/ui/card'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { getCategories, getGroupExpenses } from '@/lib/api'
|
||||
import {
|
||||
getCategories,
|
||||
getGroupExpenseCount,
|
||||
getGroupExpenses,
|
||||
} from '@/lib/api'
|
||||
import { env } from '@/lib/env'
|
||||
import { Download, Plus } from 'lucide-react'
|
||||
import { Metadata } from 'next'
|
||||
@@ -51,6 +55,7 @@ export default async function GroupExpensesPage({
|
||||
prefetch={false}
|
||||
href={`/groups/${groupId}/expenses/export/json`}
|
||||
target="_blank"
|
||||
title="Export to JSON"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
</Link>
|
||||
@@ -63,7 +68,10 @@ export default async function GroupExpensesPage({
|
||||
/>
|
||||
)}
|
||||
<Button asChild size="icon">
|
||||
<Link href={`/groups/${groupId}/expenses/create`}>
|
||||
<Link
|
||||
href={`/groups/${groupId}/expenses/create`}
|
||||
title="Create expense"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
</Link>
|
||||
</Button>
|
||||
@@ -87,7 +95,7 @@ export default async function GroupExpensesPage({
|
||||
</div>
|
||||
))}
|
||||
>
|
||||
<Expenses groupId={groupId} />
|
||||
<Expenses group={group} />
|
||||
</Suspense>
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -97,14 +105,22 @@ export default async function GroupExpensesPage({
|
||||
)
|
||||
}
|
||||
|
||||
async function Expenses({ groupId }: { groupId: string }) {
|
||||
const group = await cached.getGroup(groupId)
|
||||
if (!group) notFound()
|
||||
const expenses = await getGroupExpenses(group.id)
|
||||
type Props = {
|
||||
group: NonNullable<Awaited<ReturnType<typeof cached.getGroup>>>
|
||||
}
|
||||
|
||||
async function Expenses({ group }: Props) {
|
||||
const expenseCount = await getGroupExpenseCount(group.id)
|
||||
|
||||
const expenses = await getGroupExpenses(group.id, {
|
||||
offset: 0,
|
||||
length: 200,
|
||||
})
|
||||
|
||||
return (
|
||||
<ExpenseList
|
||||
expenses={expenses}
|
||||
expensesFirstPage={expenses}
|
||||
expenseCount={expenseCount}
|
||||
groupId={group.id}
|
||||
currency={group.currency}
|
||||
participants={group.participants}
|
||||
|
||||
@@ -15,7 +15,7 @@ export function GroupTabs({ groupId }: Props) {
|
||||
return (
|
||||
<Tabs
|
||||
value={value}
|
||||
className="[&>*]:border"
|
||||
className="[&>*]:border overflow-x-auto"
|
||||
onValueChange={(value) => {
|
||||
router.push(`/groups/${groupId}/${value}`)
|
||||
}}
|
||||
@@ -23,6 +23,8 @@ export function GroupTabs({ groupId }: Props) {
|
||||
<TabsList>
|
||||
<TabsTrigger value="expenses">Expenses</TabsTrigger>
|
||||
<TabsTrigger value="balances">Balances</TabsTrigger>
|
||||
<TabsTrigger value="stats">Stats</TabsTrigger>
|
||||
<TabsTrigger value="activity">Activity</TabsTrigger>
|
||||
<TabsTrigger value="edit">Settings</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
|
||||
@@ -35,7 +35,7 @@ export default async function GroupLayout({
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-col sm:flex-row justify-between sm:items-center gap-3">
|
||||
<div className="flex flex-col justify-between gap-3">
|
||||
<h1 className="font-bold text-2xl">
|
||||
<Link href={`/groups/${groupId}`}>{group.name}</Link>
|
||||
</h1>
|
||||
|
||||
@@ -23,7 +23,7 @@ export function ShareButton({ group }: Props) {
|
||||
return (
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button size="icon">
|
||||
<Button title="Share" size="icon" className="flex-shrink-0">
|
||||
<Share className="w-4 h-4" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
|
||||
49
src/app/groups/[groupId]/stats/page.tsx
Normal file
49
src/app/groups/[groupId]/stats/page.tsx
Normal file
@@ -0,0 +1,49 @@
|
||||
import { cached } from '@/app/cached-functions'
|
||||
import { Totals } from '@/app/groups/[groupId]/stats/totals'
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@/components/ui/card'
|
||||
import { getGroupExpenses } from '@/lib/api'
|
||||
import { getTotalGroupSpending } from '@/lib/totals'
|
||||
import { Metadata } from 'next'
|
||||
import { notFound } from 'next/navigation'
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Totals',
|
||||
}
|
||||
|
||||
export default async function TotalsPage({
|
||||
params: { groupId },
|
||||
}: {
|
||||
params: { groupId: string }
|
||||
}) {
|
||||
const group = await cached.getGroup(groupId)
|
||||
if (!group) notFound()
|
||||
|
||||
const expenses = await getGroupExpenses(groupId)
|
||||
const totalGroupSpendings = getTotalGroupSpending(expenses)
|
||||
|
||||
return (
|
||||
<>
|
||||
<Card className="mb-4">
|
||||
<CardHeader>
|
||||
<CardTitle>Totals</CardTitle>
|
||||
<CardDescription>
|
||||
Spending summary of the entire group.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col space-y-4">
|
||||
<Totals
|
||||
group={group}
|
||||
expenses={expenses}
|
||||
totalGroupSpendings={totalGroupSpendings}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</>
|
||||
)
|
||||
}
|
||||
18
src/app/groups/[groupId]/stats/totals-group-spending.tsx
Normal file
18
src/app/groups/[groupId]/stats/totals-group-spending.tsx
Normal file
@@ -0,0 +1,18 @@
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
|
||||
type Props = {
|
||||
totalGroupSpendings: number
|
||||
currency: string
|
||||
}
|
||||
|
||||
export function TotalsGroupSpending({ totalGroupSpendings, currency }: Props) {
|
||||
const balance = totalGroupSpendings < 0 ? 'earnings' : 'spendings'
|
||||
return (
|
||||
<div>
|
||||
<div className="text-muted-foreground">Total group {balance}</div>
|
||||
<div className="text-lg">
|
||||
{formatCurrency(currency, Math.abs(totalGroupSpendings))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
39
src/app/groups/[groupId]/stats/totals-your-share.tsx
Normal file
39
src/app/groups/[groupId]/stats/totals-your-share.tsx
Normal file
@@ -0,0 +1,39 @@
|
||||
'use client'
|
||||
import { getGroup, getGroupExpenses } from '@/lib/api'
|
||||
import { getTotalActiveUserShare } from '@/lib/totals'
|
||||
import { cn, formatCurrency } from '@/lib/utils'
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
type Props = {
|
||||
group: NonNullable<Awaited<ReturnType<typeof getGroup>>>
|
||||
expenses: NonNullable<Awaited<ReturnType<typeof getGroupExpenses>>>
|
||||
}
|
||||
|
||||
export function TotalsYourShare({ group, expenses }: Props) {
|
||||
const [activeUser, setActiveUser] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
const activeUser = localStorage.getItem(`${group.id}-activeUser`)
|
||||
if (activeUser) setActiveUser(activeUser)
|
||||
}, [group, expenses])
|
||||
|
||||
const totalActiveUserShare =
|
||||
activeUser === '' || activeUser === 'None'
|
||||
? 0
|
||||
: getTotalActiveUserShare(activeUser, expenses)
|
||||
const currency = group.currency
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="text-muted-foreground">Your total share</div>
|
||||
<div
|
||||
className={cn(
|
||||
'text-lg',
|
||||
totalActiveUserShare < 0 ? 'text-green-600' : 'text-red-600',
|
||||
)}
|
||||
>
|
||||
{formatCurrency(currency, Math.abs(totalActiveUserShare))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
36
src/app/groups/[groupId]/stats/totals-your-spending.tsx
Normal file
36
src/app/groups/[groupId]/stats/totals-your-spending.tsx
Normal file
@@ -0,0 +1,36 @@
|
||||
'use client'
|
||||
import { getGroup, getGroupExpenses } from '@/lib/api'
|
||||
import { useActiveUser } from '@/lib/hooks'
|
||||
import { getTotalActiveUserPaidFor } from '@/lib/totals'
|
||||
import { cn, formatCurrency } from '@/lib/utils'
|
||||
|
||||
type Props = {
|
||||
group: NonNullable<Awaited<ReturnType<typeof getGroup>>>
|
||||
expenses: NonNullable<Awaited<ReturnType<typeof getGroupExpenses>>>
|
||||
}
|
||||
|
||||
export function TotalsYourSpendings({ group, expenses }: Props) {
|
||||
const activeUser = useActiveUser(group.id)
|
||||
|
||||
const totalYourSpendings =
|
||||
activeUser === '' || activeUser === 'None'
|
||||
? 0
|
||||
: getTotalActiveUserPaidFor(activeUser, expenses)
|
||||
const currency = group.currency
|
||||
const balance = totalYourSpendings < 0 ? 'earnings' : 'spendings'
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="text-muted-foreground">Your total {balance}</div>
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
'text-lg',
|
||||
totalYourSpendings < 0 ? 'text-green-600' : 'text-red-600',
|
||||
)}
|
||||
>
|
||||
{formatCurrency(currency, Math.abs(totalYourSpendings))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
34
src/app/groups/[groupId]/stats/totals.tsx
Normal file
34
src/app/groups/[groupId]/stats/totals.tsx
Normal file
@@ -0,0 +1,34 @@
|
||||
'use client'
|
||||
import { TotalsGroupSpending } from '@/app/groups/[groupId]/stats/totals-group-spending'
|
||||
import { TotalsYourShare } from '@/app/groups/[groupId]/stats/totals-your-share'
|
||||
import { TotalsYourSpendings } from '@/app/groups/[groupId]/stats/totals-your-spending'
|
||||
import { getGroup, getGroupExpenses } from '@/lib/api'
|
||||
import { useActiveUser } from '@/lib/hooks'
|
||||
|
||||
export function Totals({
|
||||
group,
|
||||
expenses,
|
||||
totalGroupSpendings,
|
||||
}: {
|
||||
group: NonNullable<Awaited<ReturnType<typeof getGroup>>>
|
||||
expenses: NonNullable<Awaited<ReturnType<typeof getGroupExpenses>>>
|
||||
totalGroupSpendings: number
|
||||
}) {
|
||||
const activeUser = useActiveUser(group.id)
|
||||
console.log('activeUser', activeUser)
|
||||
|
||||
return (
|
||||
<>
|
||||
<TotalsGroupSpending
|
||||
totalGroupSpendings={totalGroupSpendings}
|
||||
currency={group.currency}
|
||||
/>
|
||||
{activeUser && activeUser !== 'None' && (
|
||||
<>
|
||||
<TotalsYourSpendings group={group} expenses={expenses} />
|
||||
<TotalsYourShare group={group} expenses={expenses} />
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
47
src/components/delete-popup.tsx
Normal file
47
src/components/delete-popup.tsx
Normal file
@@ -0,0 +1,47 @@
|
||||
'use client'
|
||||
|
||||
import { Trash2 } from 'lucide-react'
|
||||
import { AsyncButton } from './async-button'
|
||||
import { Button } from './ui/button'
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from './ui/dialog'
|
||||
|
||||
export function DeletePopup({ onDelete }: { onDelete: () => Promise<void> }) {
|
||||
return (
|
||||
<Dialog>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="destructive">
|
||||
<Trash2 className="w-4 h-4 mr-2" />
|
||||
Delete
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogTitle>Delete this expense?</DialogTitle>
|
||||
<DialogDescription>
|
||||
Do you really want to delete this expense? This action is
|
||||
irreversible.
|
||||
</DialogDescription>
|
||||
<DialogFooter className="flex flex-col gap-2">
|
||||
<AsyncButton
|
||||
type="button"
|
||||
variant="destructive"
|
||||
loadingContent="Deleting…"
|
||||
action={onDelete}
|
||||
>
|
||||
Yes
|
||||
</AsyncButton>
|
||||
<DialogClose asChild>
|
||||
<Button variant={'secondary'}>Cancel</Button>
|
||||
</DialogClose>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
'use client'
|
||||
import { AsyncButton } from '@/components/async-button'
|
||||
import { CategorySelector } from '@/components/category-selector'
|
||||
import { ExpenseDocumentsInput } from '@/components/expense-documents-input'
|
||||
import { SubmitButton } from '@/components/submit-button'
|
||||
@@ -35,22 +34,116 @@ import {
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import { getCategories, getExpense, getGroup, randomId } from '@/lib/api'
|
||||
import { ExpenseFormValues, expenseFormSchema } from '@/lib/schemas'
|
||||
import { RuntimeFeatureFlags } from '@/lib/featureFlags'
|
||||
import { useActiveUser } from '@/lib/hooks'
|
||||
import {
|
||||
ExpenseFormValues,
|
||||
SplittingOptions,
|
||||
expenseFormSchema,
|
||||
} from '@/lib/schemas'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { Save, Trash2 } from 'lucide-react'
|
||||
import { Save } from 'lucide-react'
|
||||
import Link from 'next/link'
|
||||
import { useSearchParams } from 'next/navigation'
|
||||
import { useState } from 'react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { match } from 'ts-pattern'
|
||||
import { DeletePopup } from './delete-popup'
|
||||
import { extractCategoryFromTitle } from './expense-form-actions'
|
||||
import { Textarea } from './ui/textarea'
|
||||
|
||||
export type Props = {
|
||||
group: NonNullable<Awaited<ReturnType<typeof getGroup>>>
|
||||
expense?: NonNullable<Awaited<ReturnType<typeof getExpense>>>
|
||||
categories: NonNullable<Awaited<ReturnType<typeof getCategories>>>
|
||||
onSubmit: (values: ExpenseFormValues) => Promise<void>
|
||||
onDelete?: () => Promise<void>
|
||||
onSubmit: (values: ExpenseFormValues, participantId?: string) => Promise<void>
|
||||
onDelete?: (participantId?: string) => Promise<void>
|
||||
runtimeFeatureFlags: RuntimeFeatureFlags
|
||||
}
|
||||
|
||||
const enforceCurrencyPattern = (value: string) =>
|
||||
value
|
||||
.replace(/^\s*-/, '_') // replace leading minus with _
|
||||
.replace(/[.,]/, '#') // replace first comma with #
|
||||
.replace(/[-.,]/g, '') // remove other minus and commas characters
|
||||
.replace(/_/, '-') // change back _ to minus
|
||||
.replace(/#/, '.') // change back # to dot
|
||||
.replace(/[^-\d.]/g, '') // remove all non-numeric characters
|
||||
|
||||
const capitalize = (value: string) =>
|
||||
value.charAt(0).toUpperCase() + value.slice(1)
|
||||
|
||||
const getDefaultSplittingOptions = (group: Props['group']) => {
|
||||
const defaultValue = {
|
||||
splitMode: 'EVENLY' as const,
|
||||
paidFor: group.participants.map(({ id }) => ({
|
||||
participant: id,
|
||||
shares: '1' as unknown as number,
|
||||
})),
|
||||
}
|
||||
|
||||
if (typeof localStorage === 'undefined') return defaultValue
|
||||
const defaultSplitMode = localStorage.getItem(
|
||||
`${group.id}-defaultSplittingOptions`,
|
||||
)
|
||||
if (defaultSplitMode === null) return defaultValue
|
||||
const parsedDefaultSplitMode = JSON.parse(
|
||||
defaultSplitMode,
|
||||
) as SplittingOptions
|
||||
|
||||
if (parsedDefaultSplitMode.paidFor === null) {
|
||||
parsedDefaultSplitMode.paidFor = defaultValue.paidFor
|
||||
}
|
||||
|
||||
// if there is a participant in the default options that does not exist anymore,
|
||||
// remove the stale default splitting options
|
||||
for (const parsedPaidFor of parsedDefaultSplitMode.paidFor) {
|
||||
if (
|
||||
!group.participants.some(({ id }) => id === parsedPaidFor.participant)
|
||||
) {
|
||||
localStorage.removeItem(`${group.id}-defaultSplittingOptions`)
|
||||
return defaultValue
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
splitMode: parsedDefaultSplitMode.splitMode,
|
||||
paidFor: parsedDefaultSplitMode.paidFor.map((paidFor) => ({
|
||||
participant: paidFor.participant,
|
||||
shares: String(paidFor.shares / 100) as unknown as number,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
async function persistDefaultSplittingOptions(
|
||||
groupId: string,
|
||||
expenseFormValues: ExpenseFormValues,
|
||||
) {
|
||||
if (localStorage && expenseFormValues.saveDefaultSplittingOptions) {
|
||||
const computePaidFor = (): SplittingOptions['paidFor'] => {
|
||||
if (expenseFormValues.splitMode === 'EVENLY') {
|
||||
return expenseFormValues.paidFor.map(({ participant }) => ({
|
||||
participant,
|
||||
shares: '100' as unknown as number,
|
||||
}))
|
||||
} else if (expenseFormValues.splitMode === 'BY_AMOUNT') {
|
||||
return null
|
||||
} else {
|
||||
return expenseFormValues.paidFor
|
||||
}
|
||||
}
|
||||
|
||||
const splittingOptions = {
|
||||
splitMode: expenseFormValues.splitMode,
|
||||
paidFor: computePaidFor(),
|
||||
} satisfies SplittingOptions
|
||||
|
||||
localStorage.setItem(
|
||||
`${groupId}-defaultSplittingOptions`,
|
||||
JSON.stringify(splittingOptions),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export function ExpenseForm({
|
||||
@@ -59,18 +152,20 @@ export function ExpenseForm({
|
||||
categories,
|
||||
onSubmit,
|
||||
onDelete,
|
||||
runtimeFeatureFlags,
|
||||
}: Props) {
|
||||
const isCreate = expense === undefined
|
||||
const searchParams = useSearchParams()
|
||||
const getSelectedPayer = (field?: { value: string }) => {
|
||||
if (isCreate && typeof window !== 'undefined') {
|
||||
const activeUser = localStorage.getItem(`${group.id}-activeUser`)
|
||||
if (activeUser && activeUser !== 'None') {
|
||||
if (activeUser && activeUser !== 'None' && field?.value === undefined) {
|
||||
return activeUser
|
||||
}
|
||||
}
|
||||
return field?.value
|
||||
}
|
||||
const defaultSplittingOptions = getDefaultSplittingOptions(group)
|
||||
const form = useForm<ExpenseFormValues>({
|
||||
resolver: zodResolver(expenseFormSchema),
|
||||
defaultValues: expense
|
||||
@@ -85,8 +180,10 @@ export function ExpenseForm({
|
||||
shares: String(shares / 100) as unknown as number,
|
||||
})),
|
||||
splitMode: expense.splitMode,
|
||||
saveDefaultSplittingOptions: false,
|
||||
isReimbursement: expense.isReimbursement,
|
||||
documents: expense.documents,
|
||||
notes: expense.notes ?? '',
|
||||
}
|
||||
: searchParams.get('reimbursement')
|
||||
? {
|
||||
@@ -99,12 +196,17 @@ export function ExpenseForm({
|
||||
paidBy: searchParams.get('from') ?? undefined,
|
||||
paidFor: [
|
||||
searchParams.get('to')
|
||||
? { participant: searchParams.get('to')!, shares: 1 }
|
||||
? {
|
||||
participant: searchParams.get('to')!,
|
||||
shares: '1' as unknown as number,
|
||||
}
|
||||
: undefined,
|
||||
],
|
||||
isReimbursement: true,
|
||||
splitMode: 'EVENLY',
|
||||
splitMode: defaultSplittingOptions.splitMode,
|
||||
saveDefaultSplittingOptions: false,
|
||||
documents: [],
|
||||
notes: '',
|
||||
}
|
||||
: {
|
||||
title: searchParams.get('title') ?? '',
|
||||
@@ -116,13 +218,11 @@ export function ExpenseForm({
|
||||
? Number(searchParams.get('categoryId'))
|
||||
: 0, // category with Id 0 is General
|
||||
// paid for all, split evenly
|
||||
paidFor: group.participants.map(({ id }) => ({
|
||||
participant: id,
|
||||
shares: 1,
|
||||
})),
|
||||
paidFor: defaultSplittingOptions.paidFor,
|
||||
paidBy: getSelectedPayer(),
|
||||
isReimbursement: false,
|
||||
splitMode: 'EVENLY',
|
||||
splitMode: defaultSplittingOptions.splitMode,
|
||||
saveDefaultSplittingOptions: false,
|
||||
documents: searchParams.get('imageUrl')
|
||||
? [
|
||||
{
|
||||
@@ -133,18 +233,27 @@ export function ExpenseForm({
|
||||
},
|
||||
]
|
||||
: [],
|
||||
notes: '',
|
||||
},
|
||||
})
|
||||
const [isCategoryLoading, setCategoryLoading] = useState(false)
|
||||
const activeUserId = useActiveUser(group.id)
|
||||
|
||||
const submit = async (values: ExpenseFormValues) => {
|
||||
await persistDefaultSplittingOptions(group.id, values)
|
||||
return onSubmit(values, activeUserId ?? undefined)
|
||||
}
|
||||
|
||||
const [isIncome, setIsIncome] = useState(Number(form.getValues().amount) < 0)
|
||||
const sExpense = isIncome ? 'income' : 'expense'
|
||||
const sPaid = isIncome ? 'received' : 'paid'
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit((values) => onSubmit(values))}>
|
||||
<form onSubmit={form.handleSubmit(submit)}>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>
|
||||
{isCreate ? <>Create expense</> : <>Edit expense</>}
|
||||
</CardTitle>
|
||||
<CardTitle>{(isCreate ? 'Create ' : 'Edit ') + sExpense}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="grid sm:grid-cols-2 gap-6">
|
||||
<FormField
|
||||
@@ -152,7 +261,7 @@ export function ExpenseForm({
|
||||
name="title"
|
||||
render={({ field }) => (
|
||||
<FormItem className="">
|
||||
<FormLabel>Expense title</FormLabel>
|
||||
<FormLabel>{capitalize(sExpense)} title</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder="Monday evening restaurant"
|
||||
@@ -160,7 +269,7 @@ export function ExpenseForm({
|
||||
{...field}
|
||||
onBlur={async () => {
|
||||
field.onBlur() // avoid skipping other blur event listeners since we overwrite `field`
|
||||
if (process.env.NEXT_PUBLIC_ENABLE_CATEGORY_EXTRACT) {
|
||||
if (runtimeFeatureFlags.enableCategoryExtract) {
|
||||
setCategoryLoading(true)
|
||||
const { categoryId } = await extractCategoryFromTitle(
|
||||
field.value,
|
||||
@@ -172,7 +281,7 @@ export function ExpenseForm({
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
Enter a description for the expense.
|
||||
Enter a description for the {sExpense}.
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -184,7 +293,7 @@ export function ExpenseForm({
|
||||
name="expenseDate"
|
||||
render={({ field }) => (
|
||||
<FormItem className="sm:order-1">
|
||||
<FormLabel>Expense date</FormLabel>
|
||||
<FormLabel>{capitalize(sExpense)} date</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
className="date-base"
|
||||
@@ -196,7 +305,7 @@ export function ExpenseForm({
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
Enter the date the expense was made.
|
||||
Enter the date the {sExpense} was {sPaid}.
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -206,7 +315,7 @@ export function ExpenseForm({
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="amount"
|
||||
render={({ field }) => (
|
||||
render={({ field: { onChange, ...field } }) => (
|
||||
<FormItem className="sm:order-3">
|
||||
<FormLabel>Amount</FormLabel>
|
||||
<div className="flex items-baseline gap-2">
|
||||
@@ -214,33 +323,46 @@ export function ExpenseForm({
|
||||
<FormControl>
|
||||
<Input
|
||||
className="text-base max-w-[120px]"
|
||||
type="number"
|
||||
type="text"
|
||||
inputMode="decimal"
|
||||
step={0.01}
|
||||
placeholder="0.00"
|
||||
onChange={(event) => {
|
||||
const v = enforceCurrencyPattern(event.target.value)
|
||||
const income = Number(v) < 0
|
||||
setIsIncome(income)
|
||||
if (income) form.setValue('isReimbursement', false)
|
||||
onChange(v)
|
||||
}}
|
||||
onFocus={(e) => {
|
||||
// we're adding a small delay to get around safaris issue with onMouseUp deselecting things again
|
||||
const target = e.currentTarget
|
||||
setTimeout(() => target.select(), 1)
|
||||
}}
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
</div>
|
||||
<FormMessage />
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="isReimbursement"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex flex-row gap-2 items-center space-y-0 pt-2">
|
||||
<FormControl>
|
||||
<Checkbox
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<div>
|
||||
<FormLabel>This is a reimbursement</FormLabel>
|
||||
</div>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
{!isIncome && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="isReimbursement"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex flex-row gap-2 items-center space-y-0 pt-2">
|
||||
<FormControl>
|
||||
<Checkbox
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<div>
|
||||
<FormLabel>This is a reimbursement</FormLabel>
|
||||
</div>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
@@ -260,7 +382,7 @@ export function ExpenseForm({
|
||||
isLoading={isCategoryLoading}
|
||||
/>
|
||||
<FormDescription>
|
||||
Select the expense category.
|
||||
Select the {sExpense} category.
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
@@ -272,7 +394,7 @@ export function ExpenseForm({
|
||||
name="paidBy"
|
||||
render={({ field }) => (
|
||||
<FormItem className="sm:order-5">
|
||||
<FormLabel>Paid by</FormLabel>
|
||||
<FormLabel>{capitalize(sPaid)} by</FormLabel>
|
||||
<Select
|
||||
onValueChange={field.onChange}
|
||||
defaultValue={getSelectedPayer(field)}
|
||||
@@ -289,19 +411,31 @@ export function ExpenseForm({
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormDescription>
|
||||
Select the participant who paid the expense.
|
||||
Select the participant who {sPaid} the {sExpense}.
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="notes"
|
||||
render={({ field }) => (
|
||||
<FormItem className="sm:order-6">
|
||||
<FormLabel>Notes</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea className="text-base" {...field} />
|
||||
</FormControl>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="mt-4">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex justify-between">
|
||||
<span>Paid for</span>
|
||||
<span>{capitalize(sPaid)} for</span>
|
||||
<Button
|
||||
variant="link"
|
||||
type="button"
|
||||
@@ -334,7 +468,7 @@ export function ExpenseForm({
|
||||
</Button>
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Select who the expense was paid for.
|
||||
Select who the {sExpense} was {sPaid} for.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
@@ -423,7 +557,7 @@ export function ExpenseForm({
|
||||
),
|
||||
)}
|
||||
className="text-base w-[80px] -my-2"
|
||||
type="number"
|
||||
type="text"
|
||||
disabled={
|
||||
!field.value?.some(
|
||||
({ participant }) =>
|
||||
@@ -443,7 +577,9 @@ export function ExpenseForm({
|
||||
? {
|
||||
participant: id,
|
||||
shares:
|
||||
event.target.value,
|
||||
enforceCurrencyPattern(
|
||||
event.target.value,
|
||||
),
|
||||
}
|
||||
: p,
|
||||
),
|
||||
@@ -486,7 +622,10 @@ export function ExpenseForm({
|
||||
)}
|
||||
/>
|
||||
|
||||
<Collapsible className="mt-5">
|
||||
<Collapsible
|
||||
className="mt-5"
|
||||
defaultOpen={form.getValues().splitMode !== 'EVENLY'}
|
||||
>
|
||||
<CollapsibleTrigger asChild>
|
||||
<Button variant="link" className="-mx-4">
|
||||
Advanced splitting options…
|
||||
@@ -498,7 +637,7 @@ export function ExpenseForm({
|
||||
control={form.control}
|
||||
name="splitMode"
|
||||
render={({ field }) => (
|
||||
<FormItem className="sm:order-2">
|
||||
<FormItem>
|
||||
<FormLabel>Split mode</FormLabel>
|
||||
<FormControl>
|
||||
<Select
|
||||
@@ -529,25 +668,44 @@ export function ExpenseForm({
|
||||
</Select>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
Select how to split the expense.
|
||||
Select how to split the {sExpense}.
|
||||
</FormDescription>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="saveDefaultSplittingOptions"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex flex-row gap-2 items-center space-y-0 pt-2">
|
||||
<FormControl>
|
||||
<Checkbox
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<div>
|
||||
<FormLabel>
|
||||
Save as default splitting options
|
||||
</FormLabel>
|
||||
</div>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{process.env.NEXT_PUBLIC_ENABLE_EXPENSE_DOCUMENTS && (
|
||||
{runtimeFeatureFlags.enableExpenseDocuments && (
|
||||
<Card className="mt-4">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex justify-between">
|
||||
<span>Attach documents</span>
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
See and attach receipts to the expense.
|
||||
See and attach receipts to the {sExpense}.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
@@ -573,16 +731,13 @@ export function ExpenseForm({
|
||||
{isCreate ? <>Create</> : <>Save</>}
|
||||
</SubmitButton>
|
||||
{!isCreate && onDelete && (
|
||||
<AsyncButton
|
||||
type="button"
|
||||
variant="destructive"
|
||||
loadingContent="Deleting…"
|
||||
action={onDelete}
|
||||
>
|
||||
<Trash2 className="w-4 h-4 mr-2" />
|
||||
Delete
|
||||
</AsyncButton>
|
||||
<DeletePopup
|
||||
onDelete={() => onDelete(activeUserId ?? undefined)}
|
||||
></DeletePopup>
|
||||
)}
|
||||
<Button variant="ghost" asChild>
|
||||
<Link href={`/groups/${group.id}`}>Cancel</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
|
||||
@@ -35,12 +35,16 @@ import { getGroup } from '@/lib/api'
|
||||
import { GroupFormValues, groupFormSchema } from '@/lib/schemas'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { Save, Trash2 } from 'lucide-react'
|
||||
import Link from 'next/link'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useFieldArray, useForm } from 'react-hook-form'
|
||||
|
||||
export type Props = {
|
||||
group?: NonNullable<Awaited<ReturnType<typeof getGroup>>>
|
||||
onSubmit: (groupFormValues: GroupFormValues) => Promise<void>
|
||||
onSubmit: (
|
||||
groupFormValues: GroupFormValues,
|
||||
participantId?: string,
|
||||
) => Promise<void>
|
||||
protectedParticipantIds?: string[]
|
||||
}
|
||||
|
||||
@@ -98,7 +102,11 @@ export function GroupForm({
|
||||
<Form {...form}>
|
||||
<form
|
||||
onSubmit={form.handleSubmit(async (values) => {
|
||||
await onSubmit(values)
|
||||
await onSubmit(
|
||||
values,
|
||||
group?.participants.find((p) => p.name === activeUser)?.id ??
|
||||
undefined,
|
||||
)
|
||||
})}
|
||||
>
|
||||
<Card className="mb-4">
|
||||
@@ -172,7 +180,11 @@ export function GroupForm({
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<div className="flex gap-2">
|
||||
<Input className="text-base" {...field} />
|
||||
<Input
|
||||
className="text-base"
|
||||
{...field}
|
||||
placeholder="New"
|
||||
/>
|
||||
{item.id &&
|
||||
protectedParticipantIds.includes(item.id) ? (
|
||||
<HoverCard>
|
||||
@@ -220,7 +232,7 @@ export function GroupForm({
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => {
|
||||
append({ name: 'New' })
|
||||
append({ name: '' })
|
||||
}}
|
||||
type="button"
|
||||
>
|
||||
@@ -272,13 +284,19 @@ export function GroupForm({
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<SubmitButton
|
||||
size="lg"
|
||||
loadingContent={group ? 'Saving…' : 'Creating…'}
|
||||
onClick={updateActiveUser}
|
||||
>
|
||||
<Save className="w-4 h-4 mr-2" /> {group ? <>Save</> : <> Create</>}
|
||||
</SubmitButton>
|
||||
<div className="flex mt-4 gap-2">
|
||||
<SubmitButton
|
||||
loadingContent={group ? 'Saving…' : 'Creating…'}
|
||||
onClick={updateActiveUser}
|
||||
>
|
||||
<Save className="w-4 h-4 mr-2" /> {group ? <>Save</> : <> Create</>}
|
||||
</SubmitButton>
|
||||
{!group && (
|
||||
<Button variant="ghost" asChild>
|
||||
<Link href="/groups">Cancel</Link>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
)
|
||||
|
||||
31
src/components/money.tsx
Normal file
31
src/components/money.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
'use client'
|
||||
import { cn, formatCurrency } from '@/lib/utils'
|
||||
|
||||
type Props = {
|
||||
currency: string
|
||||
amount: number
|
||||
bold?: boolean
|
||||
colored?: boolean
|
||||
}
|
||||
|
||||
export function Money({
|
||||
currency,
|
||||
amount,
|
||||
bold = false,
|
||||
colored = false,
|
||||
}: Props) {
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
colored && amount <= 1
|
||||
? 'text-red-600'
|
||||
: colored && amount >= 1
|
||||
? 'text-green-600'
|
||||
: '',
|
||||
bold && 'font-bold',
|
||||
)}
|
||||
>
|
||||
{formatCurrency(currency, amount)}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -1,33 +1,49 @@
|
||||
import * as React from "react"
|
||||
import * as React from 'react'
|
||||
|
||||
import {Input} from "@/components/ui/input";
|
||||
import {cn} from "@/lib/utils";
|
||||
import {
|
||||
Search
|
||||
} from 'lucide-react'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { Search, XCircle } from 'lucide-react'
|
||||
|
||||
export interface InputProps
|
||||
extends React.InputHTMLAttributes<HTMLInputElement> {}
|
||||
extends React.InputHTMLAttributes<HTMLInputElement> {
|
||||
onValueChange?: (value: string) => void
|
||||
}
|
||||
|
||||
const SearchBar = React.forwardRef<HTMLInputElement, InputProps>(
|
||||
({ className, type, ...props }, ref) => {
|
||||
({ className, type, onValueChange, ...props }, ref) => {
|
||||
const [value, _setValue] = React.useState('')
|
||||
|
||||
const setValue = (v: string) => {
|
||||
_setValue(v)
|
||||
onValueChange && onValueChange(v)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-4 sm:mx-6 flex relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
|
||||
<Input
|
||||
type={type}
|
||||
className={cn(
|
||||
"pl-10 text-sm focus:text-base bg-muted border-none text-muted-foreground",
|
||||
className
|
||||
'pl-10 text-sm focus:text-base bg-muted border-none text-muted-foreground',
|
||||
className,
|
||||
)}
|
||||
ref={ref}
|
||||
placeholder="Search for an expense…"
|
||||
value={value}
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
{...props}
|
||||
/>
|
||||
<XCircle
|
||||
className={cn(
|
||||
'absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 cursor-pointer',
|
||||
!value && 'hidden',
|
||||
)}
|
||||
onClick={() => setValue('')}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
SearchBar.displayName = "SearchBar"
|
||||
SearchBar.displayName = 'SearchBar'
|
||||
|
||||
export { SearchBar }
|
||||
|
||||
106
src/lib/api.ts
106
src/lib/api.ts
@@ -1,6 +1,6 @@
|
||||
import { getPrisma } from '@/lib/prisma'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { ExpenseFormValues, GroupFormValues } from '@/lib/schemas'
|
||||
import { Expense } from '@prisma/client'
|
||||
import { ActivityType, Expense } from '@prisma/client'
|
||||
import { nanoid } from 'nanoid'
|
||||
|
||||
export function randomId() {
|
||||
@@ -8,7 +8,6 @@ export function randomId() {
|
||||
}
|
||||
|
||||
export async function createGroup(groupFormValues: GroupFormValues) {
|
||||
const prisma = await getPrisma()
|
||||
return prisma.group.create({
|
||||
data: {
|
||||
id: randomId(),
|
||||
@@ -30,6 +29,7 @@ export async function createGroup(groupFormValues: GroupFormValues) {
|
||||
export async function createExpense(
|
||||
expenseFormValues: ExpenseFormValues,
|
||||
groupId: string,
|
||||
participantId?: string,
|
||||
): Promise<Expense> {
|
||||
const group = await getGroup(groupId)
|
||||
if (!group) throw new Error(`Invalid group ID: ${groupId}`)
|
||||
@@ -42,10 +42,16 @@ export async function createExpense(
|
||||
throw new Error(`Invalid participant ID: ${participant}`)
|
||||
}
|
||||
|
||||
const prisma = await getPrisma()
|
||||
const expenseId = randomId()
|
||||
await logActivity(groupId, ActivityType.CREATE_EXPENSE, {
|
||||
participantId,
|
||||
expenseId,
|
||||
data: expenseFormValues.title,
|
||||
})
|
||||
|
||||
return prisma.expense.create({
|
||||
data: {
|
||||
id: randomId(),
|
||||
id: expenseId,
|
||||
groupId,
|
||||
expenseDate: expenseFormValues.expenseDate,
|
||||
categoryId: expenseFormValues.category,
|
||||
@@ -72,12 +78,23 @@ export async function createExpense(
|
||||
})),
|
||||
},
|
||||
},
|
||||
notes: expenseFormValues.notes,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteExpense(expenseId: string) {
|
||||
const prisma = await getPrisma()
|
||||
export async function deleteExpense(
|
||||
groupId: string,
|
||||
expenseId: string,
|
||||
participantId?: string,
|
||||
) {
|
||||
const existingExpense = await getExpense(groupId, expenseId)
|
||||
await logActivity(groupId, ActivityType.DELETE_EXPENSE, {
|
||||
participantId,
|
||||
expenseId,
|
||||
data: existingExpense?.title,
|
||||
})
|
||||
|
||||
await prisma.expense.delete({
|
||||
where: { id: expenseId },
|
||||
include: { paidFor: true, paidBy: true },
|
||||
@@ -89,15 +106,14 @@ export async function getGroupExpensesParticipants(groupId: string) {
|
||||
return Array.from(
|
||||
new Set(
|
||||
expenses.flatMap((e) => [
|
||||
e.paidById,
|
||||
...e.paidFor.map((pf) => pf.participantId),
|
||||
e.paidBy.id,
|
||||
...e.paidFor.map((pf) => pf.participant.id),
|
||||
]),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
export async function getGroups(groupIds: string[]) {
|
||||
const prisma = await getPrisma()
|
||||
return (
|
||||
await prisma.group.findMany({
|
||||
where: { id: { in: groupIds } },
|
||||
@@ -113,6 +129,7 @@ export async function updateExpense(
|
||||
groupId: string,
|
||||
expenseId: string,
|
||||
expenseFormValues: ExpenseFormValues,
|
||||
participantId?: string,
|
||||
) {
|
||||
const group = await getGroup(groupId)
|
||||
if (!group) throw new Error(`Invalid group ID: ${groupId}`)
|
||||
@@ -128,7 +145,12 @@ export async function updateExpense(
|
||||
throw new Error(`Invalid participant ID: ${participant}`)
|
||||
}
|
||||
|
||||
const prisma = await getPrisma()
|
||||
await logActivity(groupId, ActivityType.UPDATE_EXPENSE, {
|
||||
participantId,
|
||||
expenseId,
|
||||
data: expenseFormValues.title,
|
||||
})
|
||||
|
||||
return prisma.expense.update({
|
||||
where: { id: expenseId },
|
||||
data: {
|
||||
@@ -185,6 +207,7 @@ export async function updateExpense(
|
||||
id: doc.id,
|
||||
})),
|
||||
},
|
||||
notes: expenseFormValues.notes,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -192,11 +215,13 @@ export async function updateExpense(
|
||||
export async function updateGroup(
|
||||
groupId: string,
|
||||
groupFormValues: GroupFormValues,
|
||||
participantId?: string,
|
||||
) {
|
||||
const existingGroup = await getGroup(groupId)
|
||||
if (!existingGroup) throw new Error('Invalid group ID')
|
||||
|
||||
const prisma = await getPrisma()
|
||||
await logActivity(groupId, ActivityType.UPDATE_GROUP, { participantId })
|
||||
|
||||
return prisma.group.update({
|
||||
where: { id: groupId },
|
||||
data: {
|
||||
@@ -228,7 +253,6 @@ export async function updateGroup(
|
||||
}
|
||||
|
||||
export async function getGroup(groupId: string) {
|
||||
const prisma = await getPrisma()
|
||||
return prisma.group.findUnique({
|
||||
where: { id: groupId },
|
||||
include: { participants: true },
|
||||
@@ -236,27 +260,67 @@ export async function getGroup(groupId: string) {
|
||||
}
|
||||
|
||||
export async function getCategories() {
|
||||
const prisma = await getPrisma()
|
||||
return prisma.category.findMany()
|
||||
}
|
||||
|
||||
export async function getGroupExpenses(groupId: string) {
|
||||
const prisma = await getPrisma()
|
||||
export async function getGroupExpenses(
|
||||
groupId: string,
|
||||
options?: { offset: number; length: number },
|
||||
) {
|
||||
return prisma.expense.findMany({
|
||||
where: { groupId },
|
||||
include: {
|
||||
paidFor: { include: { participant: true } },
|
||||
paidBy: true,
|
||||
select: {
|
||||
amount: true,
|
||||
category: true,
|
||||
createdAt: true,
|
||||
expenseDate: true,
|
||||
id: true,
|
||||
isReimbursement: true,
|
||||
paidBy: { select: { id: true, name: true } },
|
||||
paidFor: {
|
||||
select: {
|
||||
participant: { select: { id: true, name: true } },
|
||||
shares: true,
|
||||
},
|
||||
},
|
||||
splitMode: true,
|
||||
title: true,
|
||||
},
|
||||
where: { groupId },
|
||||
orderBy: [{ expenseDate: 'desc' }, { createdAt: 'desc' }],
|
||||
skip: options && options.offset,
|
||||
take: options && options.length,
|
||||
})
|
||||
}
|
||||
|
||||
export async function getGroupExpenseCount(groupId: string) {
|
||||
return prisma.expense.count({ where: { groupId } })
|
||||
}
|
||||
|
||||
export async function getExpense(groupId: string, expenseId: string) {
|
||||
const prisma = await getPrisma()
|
||||
return prisma.expense.findUnique({
|
||||
where: { id: expenseId },
|
||||
include: { paidBy: true, paidFor: true, category: true, documents: true },
|
||||
})
|
||||
}
|
||||
|
||||
export async function getActivities(groupId: string) {
|
||||
return prisma.activity.findMany({
|
||||
where: { groupId },
|
||||
orderBy: [{ time: 'desc' }],
|
||||
})
|
||||
}
|
||||
|
||||
export async function logActivity(
|
||||
groupId: string,
|
||||
activityType: ActivityType,
|
||||
extra?: { participantId?: string; expenseId?: string; data?: string },
|
||||
) {
|
||||
return prisma.activity.create({
|
||||
data: {
|
||||
id: randomId(),
|
||||
groupId,
|
||||
activityType,
|
||||
...extra,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ export function getBalances(
|
||||
const balances: Balances = {}
|
||||
|
||||
for (const expense of expenses) {
|
||||
const paidBy = expense.paidById
|
||||
const paidBy = expense.paidBy.id
|
||||
const paidFors = expense.paidFor
|
||||
|
||||
if (!balances[paidBy]) balances[paidBy] = { paid: 0, paidFor: 0, total: 0 }
|
||||
@@ -31,8 +31,8 @@ export function getBalances(
|
||||
)
|
||||
let remaining = expense.amount
|
||||
paidFors.forEach((paidFor, index) => {
|
||||
if (!balances[paidFor.participantId])
|
||||
balances[paidFor.participantId] = { paid: 0, paidFor: 0, total: 0 }
|
||||
if (!balances[paidFor.participant.id])
|
||||
balances[paidFor.participant.id] = { paid: 0, paidFor: 0, total: 0 }
|
||||
|
||||
const isLast = index === paidFors.length - 1
|
||||
|
||||
@@ -47,7 +47,7 @@ export function getBalances(
|
||||
? remaining
|
||||
: (expense.amount * shares) / totalShares
|
||||
remaining -= dividedAmount
|
||||
balances[paidFor.participantId].paidFor += dividedAmount
|
||||
balances[paidFor.participant.id].paidFor += dividedAmount
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { ZodIssueCode, z } from 'zod'
|
||||
|
||||
const interpretEnvVarAsBool = (val: unknown): boolean => {
|
||||
if (typeof val !== 'string') return false
|
||||
return ['true', 'yes', '1', 'on'].includes(val.toLowerCase())
|
||||
}
|
||||
|
||||
const envSchema = z
|
||||
.object({
|
||||
POSTGRES_URL_NON_POOLING: z.string().url(),
|
||||
@@ -12,14 +17,23 @@ const envSchema = z
|
||||
? `https://${process.env.VERCEL_URL}`
|
||||
: 'http://localhost:3000',
|
||||
),
|
||||
NEXT_PUBLIC_ENABLE_EXPENSE_DOCUMENTS: z.coerce.boolean().default(false),
|
||||
NEXT_PUBLIC_ENABLE_EXPENSE_DOCUMENTS: z.preprocess(
|
||||
interpretEnvVarAsBool,
|
||||
z.boolean().default(false),
|
||||
),
|
||||
S3_UPLOAD_KEY: z.string().optional(),
|
||||
S3_UPLOAD_SECRET: z.string().optional(),
|
||||
S3_UPLOAD_BUCKET: z.string().optional(),
|
||||
S3_UPLOAD_REGION: z.string().optional(),
|
||||
S3_UPLOAD_ENDPOINT: z.string().optional(),
|
||||
NEXT_PUBLIC_ENABLE_RECEIPT_EXTRACT: z.coerce.boolean().default(false),
|
||||
NEXT_PUBLIC_ENABLE_CATEGORY_EXTRACT: z.coerce.boolean().default(false),
|
||||
NEXT_PUBLIC_ENABLE_RECEIPT_EXTRACT: z.preprocess(
|
||||
interpretEnvVarAsBool,
|
||||
z.boolean().default(false),
|
||||
),
|
||||
NEXT_PUBLIC_ENABLE_CATEGORY_EXTRACT: z.preprocess(
|
||||
interpretEnvVarAsBool,
|
||||
z.boolean().default(false),
|
||||
),
|
||||
OPENAI_API_KEY: z.string().optional(),
|
||||
})
|
||||
.superRefine((env, ctx) => {
|
||||
|
||||
15
src/lib/featureFlags.ts
Normal file
15
src/lib/featureFlags.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
'use server'
|
||||
|
||||
import { env } from './env'
|
||||
|
||||
export async function getRuntimeFeatureFlags() {
|
||||
return {
|
||||
enableExpenseDocuments: env.NEXT_PUBLIC_ENABLE_EXPENSE_DOCUMENTS,
|
||||
enableReceiptExtract: env.NEXT_PUBLIC_ENABLE_RECEIPT_EXTRACT,
|
||||
enableCategoryExtract: env.NEXT_PUBLIC_ENABLE_CATEGORY_EXTRACT,
|
||||
}
|
||||
}
|
||||
|
||||
export type RuntimeFeatureFlags = Awaited<
|
||||
ReturnType<typeof getRuntimeFeatureFlags>
|
||||
>
|
||||
@@ -48,3 +48,17 @@ export function useBaseUrl() {
|
||||
}, [])
|
||||
return baseUrl
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns The active user, or `null` until it is fetched from local storage
|
||||
*/
|
||||
export function useActiveUser(groupId: string) {
|
||||
const [activeUser, setActiveUser] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const activeUser = localStorage.getItem(`${groupId}-activeUser`)
|
||||
if (activeUser) setActiveUser(activeUser)
|
||||
}, [groupId])
|
||||
|
||||
return activeUser
|
||||
}
|
||||
|
||||
@@ -1,20 +1,21 @@
|
||||
import { PrismaClient } from '@prisma/client'
|
||||
|
||||
let prisma: PrismaClient
|
||||
declare const global: Global & { prisma?: PrismaClient }
|
||||
|
||||
export async function getPrisma() {
|
||||
export let p: PrismaClient = undefined as any as PrismaClient
|
||||
|
||||
if (typeof window === 'undefined') {
|
||||
// await delay(1000)
|
||||
if (!prisma) {
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
prisma = new PrismaClient()
|
||||
} else {
|
||||
if (!(global as any).prisma) {
|
||||
;(global as any).prisma = new PrismaClient({
|
||||
// log: [{ emit: 'stdout', level: 'query' }],
|
||||
})
|
||||
}
|
||||
prisma = (global as any).prisma
|
||||
if (process.env['NODE_ENV'] === 'production') {
|
||||
p = new PrismaClient()
|
||||
} else {
|
||||
if (!global.prisma) {
|
||||
global.prisma = new PrismaClient({
|
||||
// log: [{ emit: 'stdout', level: 'query' }],
|
||||
})
|
||||
}
|
||||
p = global.prisma
|
||||
}
|
||||
return prisma
|
||||
}
|
||||
|
||||
export const prisma = p
|
||||
|
||||
@@ -51,8 +51,7 @@ export const expenseFormSchema = z
|
||||
[
|
||||
z.number(),
|
||||
z.string().transform((value, ctx) => {
|
||||
const normalizedValue = value.replace(/,/g, '.')
|
||||
const valueAsNumber = Number(normalizedValue)
|
||||
const valueAsNumber = Number(value)
|
||||
if (Number.isNaN(valueAsNumber))
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
@@ -63,7 +62,7 @@ export const expenseFormSchema = z
|
||||
],
|
||||
{ required_error: 'You must enter an amount.' },
|
||||
)
|
||||
.refine((amount) => amount >= 1, 'The amount must be higher than 0.01.')
|
||||
.refine((amount) => amount != 1, 'The amount must not be zero.')
|
||||
.refine(
|
||||
(amount) => amount <= 10_000_000_00,
|
||||
'The amount must be lower than 10,000,000.',
|
||||
@@ -106,6 +105,7 @@ export const expenseFormSchema = z
|
||||
Object.values(SplitMode) as any,
|
||||
)
|
||||
.default('EVENLY'),
|
||||
saveDefaultSplittingOptions: z.boolean(),
|
||||
isReimbursement: z.boolean(),
|
||||
documents: z
|
||||
.array(
|
||||
@@ -117,6 +117,7 @@ export const expenseFormSchema = z
|
||||
}),
|
||||
)
|
||||
.default([]),
|
||||
notes: z.string().optional(),
|
||||
})
|
||||
.superRefine((expense, ctx) => {
|
||||
let sum = 0
|
||||
@@ -161,3 +162,9 @@ export const expenseFormSchema = z
|
||||
})
|
||||
|
||||
export type ExpenseFormValues = z.infer<typeof expenseFormSchema>
|
||||
|
||||
export type SplittingOptions = {
|
||||
// Used for saving default splitting options in localStorage
|
||||
splitMode: SplitMode
|
||||
paidFor: ExpenseFormValues['paidFor'] | null
|
||||
}
|
||||
|
||||
70
src/lib/totals.ts
Normal file
70
src/lib/totals.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
import { getGroupExpenses } from '@/lib/api'
|
||||
|
||||
export function getTotalGroupSpending(
|
||||
expenses: NonNullable<Awaited<ReturnType<typeof getGroupExpenses>>>,
|
||||
): number {
|
||||
return expenses.reduce(
|
||||
(total, expense) =>
|
||||
expense.isReimbursement ? total : total + expense.amount,
|
||||
0,
|
||||
)
|
||||
}
|
||||
|
||||
export function getTotalActiveUserPaidFor(
|
||||
activeUserId: string | null,
|
||||
expenses: NonNullable<Awaited<ReturnType<typeof getGroupExpenses>>>,
|
||||
): number {
|
||||
return expenses.reduce(
|
||||
(total, expense) =>
|
||||
expense.paidBy.id === activeUserId && !expense.isReimbursement
|
||||
? total + expense.amount
|
||||
: total,
|
||||
0,
|
||||
)
|
||||
}
|
||||
|
||||
export function getTotalActiveUserShare(
|
||||
activeUserId: string | null,
|
||||
expenses: NonNullable<Awaited<ReturnType<typeof getGroupExpenses>>>,
|
||||
): number {
|
||||
let total = 0
|
||||
|
||||
expenses.forEach((expense) => {
|
||||
if (expense.isReimbursement) return
|
||||
|
||||
const paidFors = expense.paidFor
|
||||
const userPaidFor = paidFors.find(
|
||||
(paidFor) => paidFor.participant.id === activeUserId,
|
||||
)
|
||||
|
||||
if (!userPaidFor) {
|
||||
// If the active user is not involved in the expense, skip it
|
||||
return
|
||||
}
|
||||
|
||||
switch (expense.splitMode) {
|
||||
case 'EVENLY':
|
||||
// Divide the total expense evenly among all participants
|
||||
total += expense.amount / paidFors.length
|
||||
break
|
||||
case 'BY_AMOUNT':
|
||||
// Directly add the user's share if the split mode is BY_AMOUNT
|
||||
total += userPaidFor.shares
|
||||
break
|
||||
case 'BY_PERCENTAGE':
|
||||
// Calculate the user's share based on their percentage of the total expense
|
||||
total += (expense.amount * userPaidFor.shares) / 10000 // Assuming shares are out of 10000 for percentage
|
||||
break
|
||||
case 'BY_SHARES':
|
||||
// Calculate the user's share based on their shares relative to the total shares
|
||||
const totalShares = paidFors.reduce(
|
||||
(sum, paidFor) => sum + paidFor.shares,
|
||||
0,
|
||||
)
|
||||
total += (expense.amount * userPaidFor.shares) / totalShares
|
||||
break
|
||||
}
|
||||
})
|
||||
|
||||
return parseFloat(total.toFixed(2))
|
||||
}
|
||||
@@ -10,9 +10,15 @@ export function delay(ms: number) {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms))
|
||||
}
|
||||
|
||||
export function formatExpenseDate(date: Date) {
|
||||
return date.toLocaleDateString('en-US', {
|
||||
dateStyle: 'medium',
|
||||
export type DateTimeStyle = NonNullable<
|
||||
ConstructorParameters<typeof Intl.DateTimeFormat>[1]
|
||||
>['dateStyle']
|
||||
export function formatDate(
|
||||
date: Date,
|
||||
options: { dateStyle?: DateTimeStyle; timeStyle?: DateTimeStyle } = {},
|
||||
) {
|
||||
return date.toLocaleString('en-GB', {
|
||||
...options,
|
||||
timeZone: 'UTC',
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// @ts-nocheck
|
||||
import { randomId } from '@/lib/api'
|
||||
import { getPrisma } from '@/lib/prisma'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { Prisma } from '@prisma/client'
|
||||
import { Client } from 'pg'
|
||||
|
||||
@@ -8,8 +8,6 @@ process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'
|
||||
|
||||
async function main() {
|
||||
withClient(async (client) => {
|
||||
const prisma = await getPrisma()
|
||||
|
||||
// console.log('Deleting all groups…')
|
||||
// await prisma.group.deleteMany({})
|
||||
|
||||
|
||||
Reference in New Issue
Block a user