Compare commits
8 Commits
c11a7d47b7
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| d4d886c91f | |||
| 0eccf479e6 | |||
| 00da4d2abc | |||
| 1bc4b0fb50 | |||
| 768359ad62 | |||
| cbb10361df | |||
| 23cdc27ffd | |||
| 5afd604e85 |
21
.dockerignore
Normal file
21
.dockerignore
Normal file
@@ -0,0 +1,21 @@
|
||||
# ignore node_modules, build artifacts, git metadata
|
||||
**/node_modules
|
||||
frontend/dist
|
||||
backend/node_modules
|
||||
.git
|
||||
.vscode
|
||||
.idea
|
||||
.env
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
pnpm-debug.log*
|
||||
Dockerfile*
|
||||
docker-compose*.yml
|
||||
|
||||
# Do NOT include runtime backend data in the build context
|
||||
backend/data/
|
||||
backend/data/**
|
||||
|
||||
# keep local dev artifacts out
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
48
.gitea/workflows/publish.yaml
Normal file
48
.gitea/workflows/publish.yaml
Normal file
@@ -0,0 +1,48 @@
|
||||
name: Build and publish Docker image
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
|
||||
env:
|
||||
REGISTRY: gitea.kanawave.net
|
||||
REGISTRY_USERNAME: sebastas
|
||||
IMAGE_NAME: ${{ gitea.repository }}
|
||||
|
||||
jobs:
|
||||
build-and-push:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
# Permissions are not yet supported in Gitea Actions -> https://github.com/go-gitea/gitea/issues/23642#issuecomment-2119876692
|
||||
# permissions:
|
||||
# contents: read
|
||||
# packages: write
|
||||
# attestations: write
|
||||
# id-token: write
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Login to registry
|
||||
uses: docker/login-action@v2
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ env.REGISTRY_USERNAME }}
|
||||
password: ${{ secrets.REGISTRY_TOKEN }}
|
||||
|
||||
- name: Extract metadata (tags, labels)
|
||||
id: meta
|
||||
uses: docker/metadata-action@v4
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||
|
||||
- name: Build and push
|
||||
id: push
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
# file: ./Dockerfile
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
42
Dockerfile
Normal file
42
Dockerfile
Normal file
@@ -0,0 +1,42 @@
|
||||
# Build frontend in a dedicated stage
|
||||
FROM node:24-alpine AS frontend-build
|
||||
WORKDIR /app/frontend
|
||||
COPY frontend/package*.json frontend/package-lock*.json ./
|
||||
RUN npm ci --silent
|
||||
COPY frontend/ .
|
||||
RUN npm run build
|
||||
|
||||
# Final runtime image
|
||||
FROM node:24-alpine
|
||||
WORKDIR /app
|
||||
|
||||
# ensure su-exec present to drop privileges later
|
||||
RUN apk add --no-cache ca-certificates su-exec
|
||||
|
||||
# copy package manifests and install deps (leverage Docker cache)
|
||||
COPY backend/package*.json backend/package-lock*.json ./backend/
|
||||
RUN cd backend && npm ci --silent
|
||||
# copy backend source (schema, migrations, source)
|
||||
COPY backend ./backend
|
||||
# generate Prisma client against a harmless temp DB path (does not apply migrations)
|
||||
RUN cd backend && DATABASE_URL="file:./data/sqlite.db" npx prisma generate --schema=./prisma/schema.prisma || true
|
||||
# remove devDependencies to slim image
|
||||
RUN cd backend && npm prune --production --silent
|
||||
# install prisma CLI into final image so entrypoint can run migrate deploy at runtime
|
||||
RUN cd backend && npm i --no-audit --no-fund prisma --silent || true
|
||||
# copy entrypoint and make executable
|
||||
COPY docker/entrypoint.sh /usr/local/bin/entrypoint.sh
|
||||
RUN chmod +x /usr/local/bin/entrypoint.sh
|
||||
# Copy built frontend into the expected location: /app/frontend/dist
|
||||
COPY --from=frontend-build /app/frontend/dist ./frontend/dist
|
||||
|
||||
# runtime environment (DATA_DIR used at runtime; DATABASE_URL points to it)
|
||||
ENV NODE_ENV=production
|
||||
ENV DATA_DIR=/data
|
||||
ENV DATABASE_URL="file:${DATA_DIR}/sqlite.db"
|
||||
|
||||
WORKDIR /app/backend
|
||||
EXPOSE 3000
|
||||
|
||||
ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
|
||||
CMD ["node", "server.js"]
|
||||
31
README.md
Normal file
31
README.md
Normal file
@@ -0,0 +1,31 @@
|
||||
# Tally Counter
|
||||
|
||||
Run the app with Docker Compose (recommended). The container startup/entrypoint will create the runtime folders and apply migrations; pass numeric PUID/PGID via environment to run as a non-root user.
|
||||
|
||||
|
||||
```yaml
|
||||
services:
|
||||
tally-counter:
|
||||
image: gitea.kanawave.net/sebastas/tally-counter:latest #this image
|
||||
container_name: tally-counter
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- proxy # connect any proxy networks (for traefik)
|
||||
environment:
|
||||
- PUID=1000 # host uid forwarded to container
|
||||
- PGID=1000 # host gid forwarded to container
|
||||
ports:
|
||||
- "3000:3000" # Set whatever port you want on the left side (host)
|
||||
volumes:
|
||||
- ./tally-counter:/data # persistent DB + uploads (bind mount)
|
||||
```
|
||||
|
||||
Add any `labels` for traefik
|
||||
|
||||
### Notes & tips
|
||||
|
||||
The entrypoint will:
|
||||
- ensure `$DATA_DIR` exists,
|
||||
- create `sqlite.db` if missing,
|
||||
- run `prisma migrate deploy` (if CLI available and migrations exist),
|
||||
- then drop privileges to the provided `PUID:PGID` and exec the app.
|
||||
@@ -7,7 +7,10 @@
|
||||
"dev": "nodemon server.js",
|
||||
"start": "node server.js",
|
||||
"prisma:generate": "prisma generate",
|
||||
"prisma:migrate": "prisma migrate dev --name init"
|
||||
"prisma:migrate-dev": "prisma migrate dev --name init",
|
||||
"prisma:migrate-deploy": "prisma migrate deploy",
|
||||
"prisma:studio": "prisma studio",
|
||||
"prisma:deploy": "npx prisma migrate deploy && npx prisma generate"
|
||||
},
|
||||
"dependencies": {
|
||||
"@prisma/client": "^6.19.0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
datasource db {
|
||||
provider = "sqlite"
|
||||
url = "file:../data/sqlite.db"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
generator client {
|
||||
|
||||
@@ -5,8 +5,6 @@ const path = require('path')
|
||||
const cors = require('cors')
|
||||
const { PrismaClient } = require('@prisma/client')
|
||||
|
||||
const prisma = new PrismaClient()
|
||||
|
||||
// small, configurable logger used across the app
|
||||
const LOG_LEVEL = (process.env.LOG_LEVEL || 'info').toLowerCase() // 'error'|'info'|'debug'
|
||||
const levels = { error: 0, info: 1, debug: 2 }
|
||||
@@ -22,14 +20,25 @@ const log = {
|
||||
},
|
||||
}
|
||||
|
||||
// store all runtime data under backend/data
|
||||
const DATA_DIR = path.join(__dirname, 'data')
|
||||
// store runtime data under DATA_DIR env if provided, else backend/data
|
||||
const DATA_DIR = process.env.DATA_DIR
|
||||
? path.resolve(process.env.DATA_DIR)
|
||||
: path.join(__dirname, 'data')
|
||||
|
||||
const UPLOAD_DIR = path.join(DATA_DIR, 'uploads')
|
||||
|
||||
// ensure data and upload dirs exist
|
||||
if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true })
|
||||
if (!fs.existsSync(UPLOAD_DIR)) fs.mkdirSync(UPLOAD_DIR, { recursive: true })
|
||||
|
||||
// ensure DATABASE_URL points to the DB under DATA_DIR for Prisma at runtime
|
||||
if (!process.env.DATABASE_URL) {
|
||||
process.env.DATABASE_URL = `file:${path.join(DATA_DIR, 'sqlite.db')}`
|
||||
}
|
||||
|
||||
// instantiate Prisma client AFTER DATA_DIR / DATABASE_URL are ready
|
||||
const prisma = new PrismaClient()
|
||||
|
||||
const upload = multer({ dest: UPLOAD_DIR }) // local storage for uploads
|
||||
|
||||
const app = express()
|
||||
|
||||
52
docker/entrypoint.sh
Normal file
52
docker/entrypoint.sh
Normal file
@@ -0,0 +1,52 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
DATA_DIR="${DATA_DIR:-/data}"
|
||||
SCHEMA_PATH="./prisma/schema.prisma"
|
||||
PUID="${PUID:-}"
|
||||
PGID="${PGID:-$PUID}"
|
||||
|
||||
mkdir -p "$DATA_DIR"
|
||||
chmod 0775 "$DATA_DIR" || true
|
||||
|
||||
: "${DATABASE_URL:=file:${DATA_DIR}/sqlite.db}"
|
||||
export DATABASE_URL
|
||||
|
||||
SQLITE_DB_PATH="${DATA_DIR}/sqlite.db"
|
||||
if [ ! -f "$SQLITE_DB_PATH" ]; then
|
||||
touch "$SQLITE_DB_PATH"
|
||||
chmod 0664 "$SQLITE_DB_PATH" || true
|
||||
fi
|
||||
|
||||
# run migrations if prisma CLI available
|
||||
if command -v npx >/dev/null 2>&1 && [ -f "$SCHEMA_PATH" ]; then
|
||||
echo "Running prisma migrate deploy..."
|
||||
npx prisma migrate deploy --schema="$SCHEMA_PATH" || echo "prisma migrate deploy failed or no migrations to apply"
|
||||
fi
|
||||
|
||||
# If root and numeric PUID supplied, create/reuse group by GID then create user and chown
|
||||
if [ "$(id -u)" = "0" ] && [ -n "$PUID" ]; then
|
||||
# try find an existing group with this GID
|
||||
existing_group="$(getent group | awk -F: -v gid="$PGID" '$3==gid{print $1; exit}')"
|
||||
if [ -n "$existing_group" ]; then
|
||||
grp="$existing_group"
|
||||
else
|
||||
grp="appgroup"
|
||||
addgroup -g "${PGID}" "$grp" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
if ! id -u app >/dev/null 2>&1; then
|
||||
adduser -D -u "${PUID}" -G "$grp" -s /bin/sh app 2>/dev/null || true
|
||||
fi
|
||||
|
||||
# ensure runtime paths writable by numeric ids
|
||||
chown -R "${PUID}:${PGID}" "$DATA_DIR" /app/backend /app/frontend/dist 2>/dev/null || true
|
||||
|
||||
# drop privileges and run command
|
||||
echo "Running as user: "${PUID}""
|
||||
echo "Running as group: "${PGID}""
|
||||
exec su-exec "${PUID}:${PGID}" "$@"
|
||||
fi
|
||||
|
||||
# otherwise run as current user
|
||||
exec "$@"
|
||||
@@ -415,6 +415,37 @@ html, body, #root {
|
||||
outline-offset: 8px;
|
||||
}
|
||||
|
||||
/* container grid */
|
||||
.counters-grid {
|
||||
display: grid;
|
||||
gap: 16px;
|
||||
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
|
||||
max-width: var(--max-width);
|
||||
margin: 0 auto;
|
||||
justify-content: center;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
/* keep each card centered in its cell and center its inner content */
|
||||
.counters-grid > .counter-card {
|
||||
justify-self: center;
|
||||
width: 100%;
|
||||
max-width: 460px;
|
||||
box-sizing: border-box;
|
||||
padding: 12px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
/* ensure the actual counter element stays centered and doesn't stretch awkwardly */
|
||||
.counter-card .counter {
|
||||
width: 100%;
|
||||
max-width: 420px;
|
||||
margin: 0 auto;
|
||||
display: flex;
|
||||
}
|
||||
|
||||
/* ---------------------------
|
||||
Utilities / footer
|
||||
--------------------------- */
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useEffect, useState, useCallback } from 'react'
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import Counter from './components/Counter'
|
||||
import CreateCounter from './components/CreateCounter'
|
||||
import { apiUrl } from './utils/api'
|
||||
@@ -6,6 +6,13 @@ import './App.css'
|
||||
|
||||
type CounterRecord = { id: number; value: number; name?: string; imageUrl?: string; position?: number }
|
||||
|
||||
// small pure helper kept outside the component so it's stable
|
||||
const swapInArray = (arr: CounterRecord[], i: number, j: number) => {
|
||||
const copy = arr.slice()
|
||||
;[copy[i], copy[j]] = [copy[j], copy[i]]
|
||||
return copy
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
const [counters, setCounters] = useState<CounterRecord[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
@@ -13,33 +20,46 @@ export default function App() {
|
||||
const [draggingId, setDraggingId] = useState<number | null>(null)
|
||||
const [dragOverId, setDragOverId] = useState<number | null>(null)
|
||||
|
||||
// track which modal ids are currently open (idempotent)
|
||||
const [modalOpenSet, setModalOpenSet] = useState<Set<number>>(new Set())
|
||||
const draggingEnabled = useMemo(() => modalOpenSet.size === 0, [modalOpenSet])
|
||||
|
||||
// helper: idempotently add/remove modal id
|
||||
const handleEditingChange = useCallback((id: number, editing: boolean) => {
|
||||
setModalOpenSet((prev) => {
|
||||
const next = new Set(prev)
|
||||
if (editing) next.add(id)
|
||||
else next.delete(id)
|
||||
return next
|
||||
})
|
||||
}, [])
|
||||
|
||||
// mounted ref to avoid setting state on unmounted component
|
||||
const mountedRef = useRef(true)
|
||||
useEffect(() => {
|
||||
mountedRef.current = true
|
||||
return () => {
|
||||
mountedRef.current = false
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
let mounted = true
|
||||
;(async () => {
|
||||
try {
|
||||
const res = await fetch(apiUrl('/api/counters'))
|
||||
const list: CounterRecord[] = await res.json()
|
||||
if (!mounted) return
|
||||
if (!mountedRef.current) return
|
||||
setCounters(Array.isArray(list) ? list : [])
|
||||
} catch (err) {
|
||||
// keep minimal logging here
|
||||
console.error('failed to load counters', err)
|
||||
if (mounted) setCounters([])
|
||||
if (mountedRef.current) setCounters([])
|
||||
} finally {
|
||||
if (mounted) setLoading(false)
|
||||
if (mountedRef.current) setLoading(false)
|
||||
}
|
||||
})()
|
||||
return () => {
|
||||
mounted = false
|
||||
}
|
||||
}, [])
|
||||
|
||||
// swap two items in an array (keeps array length and only swaps the two indexes)
|
||||
const swapInArray = (arr: CounterRecord[], i: number, j: number) => {
|
||||
const copy = arr.slice()
|
||||
;[copy[i], copy[j]] = [copy[j], copy[i]]
|
||||
return copy
|
||||
}
|
||||
|
||||
const clearDragState = useCallback(() => {
|
||||
setDraggingId(null)
|
||||
setDragOverId(null)
|
||||
@@ -121,7 +141,8 @@ export default function App() {
|
||||
clearDragState()
|
||||
}, [clearDragState])
|
||||
|
||||
const handleChange = async (id: number, next: number) => {
|
||||
const handleChange = useCallback(
|
||||
async (id: number, next: number) => {
|
||||
// enforce non-negative values
|
||||
const safeNext = Math.max(0, next)
|
||||
|
||||
@@ -159,14 +180,16 @@ export default function App() {
|
||||
return n
|
||||
})
|
||||
}
|
||||
}
|
||||
},
|
||||
[counters]
|
||||
)
|
||||
|
||||
const handleCreated = (c: CounterRecord) => {
|
||||
const handleCreated = useCallback((c: CounterRecord) => {
|
||||
setCounters((prev) => [...prev, c])
|
||||
}
|
||||
}, [])
|
||||
|
||||
// onUpdate: upload file (if present), then PATCH name/imageUrl for given id
|
||||
const handleUpdate = async (id: number, payload: { name?: string; file?: File | null }) => {
|
||||
const handleUpdate = useCallback(
|
||||
async (id: number, payload: { name?: string; file?: File | null }) => {
|
||||
setSavingIds((s) => {
|
||||
const n = new Set(s)
|
||||
n.add(id)
|
||||
@@ -219,10 +242,12 @@ export default function App() {
|
||||
return n
|
||||
})
|
||||
}
|
||||
}
|
||||
},
|
||||
[]
|
||||
)
|
||||
|
||||
// added delete handler
|
||||
const handleDelete = async (id: number) => {
|
||||
const handleDelete = useCallback(
|
||||
async (id: number) => {
|
||||
setSavingIds((s) => {
|
||||
const n = new Set(s)
|
||||
n.add(id)
|
||||
@@ -244,7 +269,9 @@ export default function App() {
|
||||
return n
|
||||
})
|
||||
}
|
||||
}
|
||||
},
|
||||
[]
|
||||
)
|
||||
|
||||
if (loading) return <div className="loading">Loading counters…</div>
|
||||
|
||||
@@ -267,17 +294,18 @@ export default function App() {
|
||||
<p>Create your first counter to begin tracking.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="counters-grid" style={{ display: 'grid', gap: 16, gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))' }}>
|
||||
{counters.map((c) => (
|
||||
<div className="counters-grid">
|
||||
{counters.map((c) => {
|
||||
return (
|
||||
<div
|
||||
key={c.id}
|
||||
className={`counter-card card ${draggingId === c.id ? 'dragging' : ''} ${dragOverId === c.id ? 'drag-over' : ''}`}
|
||||
draggable={true}
|
||||
onDragStart={(e) => handleDragStart(e, c.id)}
|
||||
onDragEnter={(e) => handleDragOver(e, c.id)}
|
||||
onDragOver={(e) => handleDragOver(e, c.id)}
|
||||
onDrop={(e) => handleDropOnCard(e, c.id)}
|
||||
onDragEnd={handleDragEnd}
|
||||
draggable={draggingEnabled}
|
||||
onDragStart={draggingEnabled ? (e) => handleDragStart(e, c.id) : undefined}
|
||||
onDragEnter={draggingEnabled ? (e) => handleDragOver(e, c.id) : undefined}
|
||||
onDragOver={draggingEnabled ? (e) => handleDragOver(e, c.id) : undefined}
|
||||
onDrop={draggingEnabled ? (e) => handleDropOnCard(e, c.id) : undefined}
|
||||
onDragEnd={draggingEnabled ? handleDragEnd : undefined}
|
||||
>
|
||||
<Counter
|
||||
id={String(c.id)}
|
||||
@@ -289,9 +317,11 @@ export default function App() {
|
||||
onChange={(next) => handleChange(c.id, next)}
|
||||
onUpdate={(payload) => handleUpdate(c.id, payload)}
|
||||
onDelete={() => handleDelete(c.id)}
|
||||
onEditingChange={(editing: boolean) => handleEditingChange(c.id, editing)}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
|
||||
@@ -15,6 +15,7 @@ interface CounterProps {
|
||||
|
||||
onUpdate?: (payload: { name?: string; file?: File | null }) => Promise<void> | void
|
||||
onDelete?: () => Promise<void> | void // added delete prop
|
||||
onEditingChange?: (editing: boolean) => void
|
||||
}
|
||||
|
||||
const clamp = (v: number, min?: number, max?: number) => {
|
||||
@@ -36,6 +37,7 @@ const Counter: React.FC<CounterProps> = ({
|
||||
isSaving = false,
|
||||
onUpdate,
|
||||
onDelete,
|
||||
onEditingChange,
|
||||
}) => {
|
||||
const setValue = useCallback(
|
||||
(next: number) => {
|
||||
@@ -97,23 +99,26 @@ const Counter: React.FC<CounterProps> = ({
|
||||
setEditName(label ?? '')
|
||||
setEditFile(null)
|
||||
setEditing(true)
|
||||
}, [label])
|
||||
}, [label, onEditingChange])
|
||||
|
||||
const closeEdit = useCallback(() => {
|
||||
setEditing(false)
|
||||
setEditFile(null)
|
||||
setPreviewUrl(null)
|
||||
}, [])
|
||||
}, [onEditingChange])
|
||||
|
||||
const handleSave = useCallback(async () => {
|
||||
if (!onUpdate) {
|
||||
// close and notify parent
|
||||
setEditing(false)
|
||||
onEditingChange?.(false)
|
||||
return
|
||||
}
|
||||
try {
|
||||
setSavingLocal(true)
|
||||
await onUpdate({ name: editName || undefined, file: editFile })
|
||||
setEditing(false)
|
||||
onEditingChange?.(false)
|
||||
} catch (err) {
|
||||
console.error('update failed', err)
|
||||
} finally {
|
||||
@@ -128,6 +133,7 @@ const Counter: React.FC<CounterProps> = ({
|
||||
await onDelete()
|
||||
// close modal locally (parent will remove the card)
|
||||
setEditing(false)
|
||||
onEditingChange?.(false)
|
||||
} catch (err) {
|
||||
console.error('delete failed', err)
|
||||
} finally {
|
||||
@@ -135,6 +141,20 @@ const Counter: React.FC<CounterProps> = ({
|
||||
}
|
||||
}, [onDelete])
|
||||
|
||||
// Call the latest onEditingChange but only re-run when `editing` toggles.
|
||||
// This avoids re-running the effect when the parent's callback identity changes.
|
||||
const onEditingChangeRef = useRef(onEditingChange)
|
||||
useEffect(() => {
|
||||
onEditingChangeRef.current = onEditingChange
|
||||
}, [onEditingChange])
|
||||
|
||||
useEffect(() => {
|
||||
onEditingChangeRef.current?.(editing)
|
||||
return () => {
|
||||
if (editing) onEditingChangeRef.current?.(false)
|
||||
}
|
||||
}, [editing])
|
||||
|
||||
return (
|
||||
<div
|
||||
className={className ?? 'counter'}
|
||||
|
||||
Reference in New Issue
Block a user