Compare commits
42 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f4d6b11414 | |||
| 968e81f4fb | |||
| 10835c9def | |||
| cdbc618521 | |||
| f75fe42910 | |||
| 212775ffdc | |||
| c80760db02 | |||
| cd1dd12c15 | |||
| 43cf589613 | |||
| e1cb2754c4 | |||
| 5dedb8fac0 | |||
| 78f1659db4 | |||
| 935c263648 | |||
| 29ac96f892 | |||
| 4d3b7210b3 | |||
| 369bca2ef1 | |||
| 2fcc741f5e | |||
| 27722186d1 | |||
| 5710c74706 | |||
| cd27dfa27d | |||
| c4c7d42de4 | |||
| 71025b3d61 | |||
| f790a6adcc | |||
| de5a46938b | |||
| 16944c1a26 | |||
| fae7b20f90 | |||
| 73e7613a1b | |||
| 6c8aa5af4c | |||
| 9554f4b66e | |||
| 5c77bbfdc3 | |||
| 979b572136 | |||
| f189317dfc | |||
| c54f834311 | |||
| 9d05005bb7 | |||
| 40c4874156 | |||
| 2de0636608 | |||
| 9e7c6f4397 | |||
| 6600ceafce | |||
| d7a497a4a2 | |||
| 4c04086d63 | |||
| 79ce42bec6 | |||
| 72c956162c |
@@ -36,6 +36,10 @@ ORIGIN=http://localhost:5173
|
||||
# Generate: openssl rand -base64 48
|
||||
SESSION_SECRET=
|
||||
|
||||
# Admin dashboard access — comma-separated list of User IDs (UUIDs)
|
||||
# Example: ADMIN_USER_IDS=11111111-2222-3333-4444-555555555555,22222222-3333-4444-5555-666666666666
|
||||
ADMIN_USER_IDS=
|
||||
|
||||
# Web Push (VAPID) — generate with: npx web-push generate-vapid-keys
|
||||
# Public key may also be set on the client as VITE_VAPID_PUBLIC_KEY
|
||||
VAPID_PUBLIC_KEY=
|
||||
|
||||
+1
-1
@@ -29,4 +29,4 @@ EXPOSE 80
|
||||
|
||||
# Health check to verify Nginx is actively running
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=3s --retries=3 \
|
||||
CMD wget --no-verbose --tries=1 --spider http://localhost:80/ || exit 1
|
||||
CMD wget --no-verbose --tries=1 --spider http://127.0.0.1:80/ || exit 1
|
||||
|
||||
+3
-3
@@ -8,7 +8,7 @@ server {
|
||||
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||
add_header Permissions-Policy "camera=(self), geolocation=(self), microphone=(self)" always;
|
||||
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://plausible.elpatron.me; connect-src 'self' https://plausible.elpatron.me; img-src 'self' data: blob: https://*.tile.openstreetmap.org; style-src 'self' 'unsafe-inline'; font-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'self';" always;
|
||||
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://plausible.elpatron.me; connect-src 'self' https://plausible.elpatron.me; img-src 'self' data: blob: https://*.tile.openstreetmap.org; media-src 'self' blob: data:; style-src 'self' 'unsafe-inline'; font-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'self';" always;
|
||||
|
||||
# Service worker and app shell must revalidate so PWA updates are detected
|
||||
location ~* ^/(sw\.js|workbox-.*\.js|manifest\.webmanifest|version\.json)$ {
|
||||
@@ -18,7 +18,7 @@ server {
|
||||
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||
add_header Permissions-Policy "camera=(self), geolocation=(self), microphone=(self)" always;
|
||||
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://plausible.elpatron.me; connect-src 'self' https://plausible.elpatron.me; img-src 'self' data: blob: https://*.tile.openstreetmap.org; style-src 'self' 'unsafe-inline'; font-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'self';" always;
|
||||
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://plausible.elpatron.me; connect-src 'self' https://plausible.elpatron.me; img-src 'self' data: blob: https://*.tile.openstreetmap.org; media-src 'self' blob: data:; style-src 'self' 'unsafe-inline'; font-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'self';" always;
|
||||
}
|
||||
|
||||
location = /index.html {
|
||||
@@ -28,7 +28,7 @@ server {
|
||||
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||
add_header Permissions-Policy "camera=(self), geolocation=(self), microphone=(self)" always;
|
||||
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://plausible.elpatron.me; connect-src 'self' https://plausible.elpatron.me; img-src 'self' data: blob: https://*.tile.openstreetmap.org; style-src 'self' 'unsafe-inline'; font-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'self';" always;
|
||||
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://plausible.elpatron.me; connect-src 'self' https://plausible.elpatron.me; img-src 'self' data: blob: https://*.tile.openstreetmap.org; media-src 'self' blob: data:; style-src 'self' 'unsafe-inline'; font-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'self';" always;
|
||||
}
|
||||
|
||||
location / {
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
"generate:flyer:png": "node ../scripts/generate-beta-flyer.mjs --png",
|
||||
"generate:flyer:all": "node ../scripts/generate-beta-flyer.mjs --all",
|
||||
"generate:flyer:setup": "playwright install chromium",
|
||||
"generate:sharepic": "node ../scripts/generate-sharepic.mjs",
|
||||
"translate:locales": "node ../scripts/translate-locales.mjs",
|
||||
"translate:flyer": "node ../scripts/translate-flyer.mjs",
|
||||
"validate:i18n": "node ../scripts/validate-i18n-keys.mjs"
|
||||
|
||||
+255
-4
@@ -4919,6 +4919,177 @@ html.theme-cupertino .events-scroll-container {
|
||||
padding-bottom: 8px;
|
||||
}
|
||||
|
||||
.admin-page {
|
||||
width: 100%;
|
||||
max-width: 1200px;
|
||||
min-height: 100vh;
|
||||
margin: 0 auto;
|
||||
padding: 24px;
|
||||
box-sizing: border-box;
|
||||
color: var(--app-text);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 24px;
|
||||
}
|
||||
|
||||
.admin-header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
padding-bottom: 16px;
|
||||
border-bottom: 1px solid var(--app-header-border);
|
||||
}
|
||||
|
||||
.admin-header-left {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 20px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.admin-title {
|
||||
margin: 0;
|
||||
font-size: 24px;
|
||||
font-weight: 700;
|
||||
background: var(--app-accent-gradient);
|
||||
-webkit-background-clip: text;
|
||||
background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
}
|
||||
|
||||
.admin-subtitle {
|
||||
margin: 6px 0 0;
|
||||
font-size: 14px;
|
||||
color: var(--app-text-muted);
|
||||
}
|
||||
|
||||
.admin-main {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 24px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.admin-kpi-grid {
|
||||
margin-top: 0;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.admin-controls {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 24px;
|
||||
padding: 16px 20px;
|
||||
border-radius: var(--app-radius-card);
|
||||
border: 1px solid var(--app-border-subtle);
|
||||
background: var(--app-surface);
|
||||
}
|
||||
|
||||
.admin-control-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.admin-control-label {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--app-text-muted);
|
||||
}
|
||||
|
||||
.admin-control-buttons {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.admin-control-buttons .btn {
|
||||
width: auto;
|
||||
padding: 8px 16px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.admin-charts-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(100%, 320px), 1fr));
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.dashboard-subtitle {
|
||||
margin-top: 4px;
|
||||
font-size: 14px;
|
||||
color: var(--app-text-muted);
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.admin-page {
|
||||
padding: 12px 12px 20px;
|
||||
gap: 16px;
|
||||
min-height: auto;
|
||||
}
|
||||
|
||||
.admin-header {
|
||||
padding-bottom: 12px;
|
||||
}
|
||||
|
||||
.admin-header-left {
|
||||
display: grid;
|
||||
grid-template-columns: auto 1fr;
|
||||
grid-template-rows: auto auto;
|
||||
align-items: center;
|
||||
column-gap: 10px;
|
||||
row-gap: 2px;
|
||||
}
|
||||
|
||||
.admin-header-left .btn-back {
|
||||
grid-row: 1 / -1;
|
||||
align-self: center;
|
||||
padding: 6px 10px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.admin-title {
|
||||
font-size: 18px;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.admin-subtitle {
|
||||
font-size: 11px;
|
||||
margin: 0;
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.admin-main {
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.admin-controls {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 12px;
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
.admin-control-buttons {
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.admin-control-label {
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.admin-control-buttons .btn {
|
||||
padding: 6px 8px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.admin-charts-grid {
|
||||
gap: 14px;
|
||||
}
|
||||
}
|
||||
|
||||
.stats-consumption-chart .stats-bar-column--grouped {
|
||||
display: inline-flex;
|
||||
white-space: normal;
|
||||
@@ -5018,6 +5189,36 @@ html.theme-cupertino .events-scroll-container {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
/* Admin dashboard: keep 2-column KPI grid on mobile (overrides rule above) */
|
||||
.stats-kpi-grid.admin-kpi-grid {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.admin-kpi-grid .stats-kpi-card {
|
||||
padding: 10px 12px;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.admin-kpi-grid .stats-kpi-icon {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.admin-kpi-grid .stats-kpi-icon svg {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
}
|
||||
|
||||
.admin-kpi-grid .stats-kpi-label {
|
||||
font-size: 11px;
|
||||
line-height: 1.25;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.admin-kpi-grid .stats-kpi-value {
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.stats-kpi-value {
|
||||
font-size: 20px;
|
||||
}
|
||||
@@ -5297,8 +5498,9 @@ html.theme-cupertino .events-scroll-container {
|
||||
/* PWA install prompt */
|
||||
.pwa-install-banner {
|
||||
position: fixed;
|
||||
left: 16px;
|
||||
right: 16px;
|
||||
left: 0;
|
||||
right: 0;
|
||||
width: calc(100% - 32px);
|
||||
bottom: calc(36px + env(safe-area-inset-bottom, 0px));
|
||||
z-index: 1200;
|
||||
display: grid;
|
||||
@@ -5461,8 +5663,9 @@ html.theme-cupertino .events-scroll-container {
|
||||
.pwa-update-banner {
|
||||
position: fixed;
|
||||
top: calc(12px + env(safe-area-inset-top, 0px));
|
||||
left: 16px;
|
||||
right: 16px;
|
||||
left: 0;
|
||||
right: 0;
|
||||
width: calc(100% - 32px);
|
||||
z-index: 1300;
|
||||
display: grid;
|
||||
grid-template-columns: auto 1fr auto;
|
||||
@@ -5585,6 +5788,12 @@ html.theme-cupertino .events-scroll-container {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
body:has(.app-bottom-nav) .app-version-footer {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
.app-version-footer a,
|
||||
.app-version-footer button {
|
||||
pointer-events: auto;
|
||||
@@ -5634,6 +5843,48 @@ html.theme-cupertino .events-scroll-container {
|
||||
border-color: rgba(255, 94, 91, 0.32);
|
||||
}
|
||||
|
||||
.mail-footer-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 2px 8px;
|
||||
border-radius: 999px;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: #94a3b8;
|
||||
text-decoration: none;
|
||||
background: rgba(56, 189, 248, 0.08);
|
||||
border: 1px solid rgba(56, 189, 248, 0.18);
|
||||
transition: color 0.15s ease, background 0.15s ease, border-color 0.15s ease;
|
||||
}
|
||||
|
||||
.mail-footer-badge:hover {
|
||||
color: #bae6fd;
|
||||
background: rgba(56, 189, 248, 0.14);
|
||||
border-color: rgba(56, 189, 248, 0.32);
|
||||
}
|
||||
|
||||
.knorrlabs-footer-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 2px 8px;
|
||||
border-radius: 999px;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: #94a3b8;
|
||||
text-decoration: none;
|
||||
background: rgba(139, 92, 246, 0.08);
|
||||
border: 1px solid rgba(139, 92, 246, 0.18);
|
||||
transition: color 0.15s ease, background 0.15s ease, border-color 0.15s ease;
|
||||
}
|
||||
|
||||
.knorrlabs-footer-badge:hover {
|
||||
color: #ddd6fe;
|
||||
background: rgba(139, 92, 246, 0.14);
|
||||
border-color: rgba(139, 92, 246, 0.32);
|
||||
}
|
||||
|
||||
.demo-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
|
||||
+79
-4
@@ -36,6 +36,7 @@ import { syncAppearancePrefs } from './services/appearancePrefs.js'
|
||||
import { startBackgroundSync, stopBackgroundSync, syncAllLogbooks, subscribeToSyncState } from './services/sync.js'
|
||||
import ReadOnlyViewer from './components/ReadOnlyViewer.tsx'
|
||||
import DemoViewer from './components/DemoViewer.tsx'
|
||||
import AdminDashboard from './admin/AdminDashboard.tsx'
|
||||
import PwaInstallPrompt from './components/PwaInstallPrompt.tsx'
|
||||
import PwaUpdatePrompt from './components/PwaUpdatePrompt.tsx'
|
||||
import AppFooter from './components/AppFooter.tsx'
|
||||
@@ -49,6 +50,8 @@ import { Ship, LogOut, ChevronLeft, Users, FileText, Settings, Wifi, WifiOff, La
|
||||
import DisclaimerHeaderButton from './components/DisclaimerHeaderButton.tsx'
|
||||
import FeedbackHeaderButton from './components/FeedbackHeaderButton.tsx'
|
||||
import ProfileHeaderButton from './components/ProfileHeaderButton.tsx'
|
||||
import AdminHeaderButton from './components/AdminHeaderButton.tsx'
|
||||
import { checkAdminAccess } from './services/adminApi.js'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { cycleAppLanguage } from './utils/i18nLanguages.js'
|
||||
import {
|
||||
@@ -92,6 +95,10 @@ function App() {
|
||||
|
||||
// Public demo mode (no account required)
|
||||
const [isDemoMode, setIsDemoMode] = useState(() => window.location.pathname === '/demo')
|
||||
const [isAdminRoute, setIsAdminRoute] = useState(() => window.location.pathname.startsWith('/admin'))
|
||||
const [isAdminUser, setIsAdminUser] = useState(false)
|
||||
const [sessionChecked, setSessionChecked] = useState(false)
|
||||
const [serverSessionActive, setServerSessionActive] = useState(false)
|
||||
|
||||
const syncQueueCount = useLiveQuery(
|
||||
() => activeLogbookId ? db.syncQueue.where({ logbookId: activeLogbookId }).count() : db.syncQueue.count(),
|
||||
@@ -160,14 +167,23 @@ function App() {
|
||||
})
|
||||
}, [])
|
||||
|
||||
const refreshAdminAccess = useCallback(async () => {
|
||||
const isAdmin = await checkAdminAccess()
|
||||
setIsAdminUser(isAdmin)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAuthenticated) return
|
||||
if (!isAuthenticated) {
|
||||
setIsAdminUser(false)
|
||||
return
|
||||
}
|
||||
const userId = localStorage.getItem('active_userid')
|
||||
if (!userId) return
|
||||
void syncAppearancePrefs(userId)
|
||||
void migrateLegacyCrewToPoolIfNeeded().then(() => syncPersonPool())
|
||||
void migrateLegacyYachtsToPoolIfNeeded().then(() => syncVesselPool())
|
||||
}, [isAuthenticated])
|
||||
void refreshAdminAccess()
|
||||
}, [isAuthenticated, refreshAdminAccess])
|
||||
|
||||
useEffect(() => {
|
||||
const handleOnline = () => {
|
||||
@@ -199,6 +215,13 @@ function App() {
|
||||
const hashParams = new URLSearchParams(window.location.hash.substring(1))
|
||||
const path = window.location.pathname
|
||||
|
||||
if (path.startsWith('/admin')) {
|
||||
setIsAdminRoute(true)
|
||||
return
|
||||
}
|
||||
|
||||
setIsAdminRoute(false)
|
||||
|
||||
if (path === '/demo') {
|
||||
setIsDemoMode(true)
|
||||
setIsViewerMode(false)
|
||||
@@ -240,6 +263,7 @@ function App() {
|
||||
|
||||
const clearAuthenticatedAppState = useCallback(() => {
|
||||
setIsAuthenticated(false)
|
||||
setIsAdminUser(false)
|
||||
setActiveLogbookId(null)
|
||||
setActiveLogbookTitle(null)
|
||||
setShowUserProfile(false)
|
||||
@@ -249,7 +273,7 @@ function App() {
|
||||
|
||||
/** After PWA/bfcache resume, React state may still say "logged in" while the master key is gone. */
|
||||
const enforceUnlockedSession = useCallback(() => {
|
||||
if (isViewerMode || isDemoMode || isAcceptingInvite) return
|
||||
if (isViewerMode || isDemoMode || isAcceptingInvite || isAdminRoute) return
|
||||
// Require full local session (incl. userId) so API calls are not left headless.
|
||||
if (isAuthenticated && !hasUnlockedLocalSession()) {
|
||||
clearAuthenticatedAppState()
|
||||
@@ -259,6 +283,7 @@ function App() {
|
||||
isViewerMode,
|
||||
isDemoMode,
|
||||
isAcceptingInvite,
|
||||
isAdminRoute,
|
||||
clearAuthenticatedAppState
|
||||
])
|
||||
|
||||
@@ -293,6 +318,8 @@ function App() {
|
||||
const session = await checkServerSession()
|
||||
if (cancelled) return
|
||||
|
||||
setServerSessionActive(session.authenticated)
|
||||
|
||||
if (session.authenticated) {
|
||||
persistSessionUserId(session.userId)
|
||||
}
|
||||
@@ -312,6 +339,10 @@ function App() {
|
||||
if (!cancelled) {
|
||||
console.warn('Session restore failed:', err)
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) {
|
||||
setSessionChecked(true)
|
||||
}
|
||||
}
|
||||
})()
|
||||
|
||||
@@ -333,6 +364,14 @@ function App() {
|
||||
setIsAcceptingInvite(false)
|
||||
}, [])
|
||||
|
||||
const openAdmin = useCallback(() => {
|
||||
window.history.pushState({}, document.title, '/admin')
|
||||
setIsAdminRoute(true)
|
||||
setIsDemoMode(false)
|
||||
setIsViewerMode(false)
|
||||
setIsAcceptingInvite(false)
|
||||
}, [])
|
||||
|
||||
const selectLogbook = useCallback((id: string, title: string) => {
|
||||
setActiveLogbookId(id)
|
||||
setActiveLogbookTitle(title)
|
||||
@@ -497,6 +536,7 @@ function App() {
|
||||
if (!(await confirmLeave())) return
|
||||
void logoutUser()
|
||||
setIsAuthenticated(false)
|
||||
setIsAdminUser(false)
|
||||
setActiveLogbookId(null)
|
||||
setActiveLogbookTitle(null)
|
||||
setShowUserProfile(false)
|
||||
@@ -524,6 +564,28 @@ function App() {
|
||||
syncRouteFromLocation()
|
||||
}
|
||||
|
||||
const handleBackFromAdmin = () => {
|
||||
window.history.replaceState({}, document.title, '/')
|
||||
setIsAdminRoute(false)
|
||||
syncRouteFromLocation()
|
||||
}
|
||||
|
||||
if (isAdminRoute) {
|
||||
if (!isAuthenticated) {
|
||||
return (
|
||||
<div className="auth-screen">
|
||||
<AuthOnboarding onAuthenticated={handleAuthenticated} onOpenDemo={openDemo} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ display: 'contents' }}>
|
||||
<AdminDashboard onBack={handleBackFromAdmin} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (isDemoMode) {
|
||||
return (
|
||||
<div style={{ display: 'contents' }}>
|
||||
@@ -564,7 +626,17 @@ function App() {
|
||||
if (!isAuthenticated) {
|
||||
return (
|
||||
<div className="auth-screen">
|
||||
<AuthOnboarding onAuthenticated={handleAuthenticated} onOpenDemo={openDemo} />
|
||||
{!sessionChecked ? (
|
||||
<div className="auth-card glass">
|
||||
<p className="dashboard-status-msg">{t('auth.restore_checking')}</p>
|
||||
</div>
|
||||
) : (
|
||||
<AuthOnboarding
|
||||
restoreSession={serverSessionActive}
|
||||
onAuthenticated={handleAuthenticated}
|
||||
onOpenDemo={openDemo}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -597,6 +669,7 @@ function App() {
|
||||
onSelectLogbook={selectLogbook}
|
||||
onLogout={handleLogout}
|
||||
onOpenProfile={() => setShowUserProfile(true)}
|
||||
onOpenAdmin={isAdminUser ? openAdmin : undefined}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
@@ -647,6 +720,8 @@ function App() {
|
||||
<Languages size={18} />
|
||||
</button>
|
||||
|
||||
{isAdminUser && <AdminHeaderButton onClick={openAdmin} />}
|
||||
|
||||
<ProfileHeaderButton onClick={() => setShowUserProfile(true)} />
|
||||
|
||||
<DisclaimerHeaderButton />
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
import { useEffect, useState, type ReactNode } from 'react'
|
||||
import {
|
||||
fetchAdminMe,
|
||||
fetchAdminSummary,
|
||||
fetchAdminTimeSeries,
|
||||
type AdminSummary,
|
||||
type AdminTimeSeriesResponse,
|
||||
type AdminTimeBucket
|
||||
} from '../services/adminApi.js'
|
||||
import { BarChart2, Bookmark, ChevronLeft, Image, MapPin, Mic, Users } from 'lucide-react'
|
||||
|
||||
function formatNumber(value: number): string {
|
||||
return value.toLocaleString()
|
||||
}
|
||||
|
||||
function KpiCard({
|
||||
icon,
|
||||
label,
|
||||
value
|
||||
}: {
|
||||
icon: ReactNode
|
||||
label: string
|
||||
value: number
|
||||
}) {
|
||||
return (
|
||||
<div className="stats-kpi-card glass">
|
||||
<div className="stats-kpi-icon">{icon}</div>
|
||||
<div className="stats-kpi-body">
|
||||
<span className="stats-kpi-label">{label}</span>
|
||||
<span className="stats-kpi-value">{formatNumber(value)}</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function TimeSeriesChart({
|
||||
title,
|
||||
seriesKey,
|
||||
data
|
||||
}: {
|
||||
title: string
|
||||
seriesKey: string
|
||||
data: AdminTimeSeriesResponse | null
|
||||
}) {
|
||||
if (!data) {
|
||||
return null
|
||||
}
|
||||
|
||||
const metric = data.series.find((s) => s.metric === seriesKey)
|
||||
if (!metric || metric.points.length === 0) {
|
||||
return (
|
||||
<div className="form-card glass">
|
||||
<div className="form-header">
|
||||
<BarChart2 className="form-icon" />
|
||||
<h2>{title}</h2>
|
||||
</div>
|
||||
<p className="dashboard-status-msg">Keine Daten im gewählten Zeitraum.</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const max = metric.points.reduce((acc, p) => (p.count > acc ? p.count : acc), 0) || 1
|
||||
|
||||
return (
|
||||
<div className="form-card glass">
|
||||
<div className="form-header">
|
||||
<BarChart2 className="form-icon" />
|
||||
<h2>{title}</h2>
|
||||
</div>
|
||||
<div className="stats-bar-chart" role="img" aria-label={title}>
|
||||
{metric.points.map((point) => {
|
||||
const heightPct = Math.max(2, (point.count / max) * 100)
|
||||
return (
|
||||
<div key={point.date} className="stats-bar-column" title={`${point.date}: ${point.count}`}>
|
||||
<span className="stats-bar-value">{point.count > 0 ? String(point.count) : ''}</span>
|
||||
<div className="stats-bar-track">
|
||||
<div className="stats-bar stats-bar--distance" style={{ height: `${heightPct}%` }} />
|
||||
</div>
|
||||
<span className="stats-bar-label">{point.date.slice(5)}</span>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
interface AdminDashboardProps {
|
||||
onBack: () => void
|
||||
}
|
||||
|
||||
export default function AdminDashboard({ onBack }: AdminDashboardProps) {
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [summary, setSummary] = useState<AdminSummary | null>(null)
|
||||
const [timeSeries, setTimeSeries] = useState<AdminTimeSeriesResponse | null>(null)
|
||||
const [bucket, setBucket] = useState<AdminTimeBucket>('day')
|
||||
const [windowDays, setWindowDays] = useState(90)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
|
||||
await fetchAdminMe()
|
||||
const [summaryRes, tsRes] = await Promise.all([
|
||||
fetchAdminSummary(),
|
||||
fetchAdminTimeSeries({ bucket, windowDays })
|
||||
])
|
||||
|
||||
if (!cancelled) {
|
||||
setSummary(summaryRes)
|
||||
setTimeSeries(tsRes)
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
if (!cancelled) {
|
||||
const message =
|
||||
err instanceof Error && err.message ? err.message : 'Fehler beim Laden des Admin-Dashboards'
|
||||
setError(message)
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void load()
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [bucket, windowDays])
|
||||
|
||||
if (loading && !summary) {
|
||||
return (
|
||||
<div className="admin-page">
|
||||
<p className="dashboard-status-msg">Admin-Dashboard wird geladen…</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="admin-page">
|
||||
<header className="admin-header">
|
||||
<button type="button" className="btn-back" onClick={onBack}>
|
||||
<ChevronLeft size={16} />
|
||||
Zur App
|
||||
</button>
|
||||
</header>
|
||||
<p className="dashboard-status-msg">{error}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!summary) {
|
||||
return (
|
||||
<div className="admin-page">
|
||||
<p className="dashboard-status-msg">Keine Admin-Daten verfügbar.</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="admin-page">
|
||||
<header className="admin-header">
|
||||
<div className="admin-header-left">
|
||||
<button type="button" className="btn-back" onClick={onBack}>
|
||||
<ChevronLeft size={16} />
|
||||
Zur App
|
||||
</button>
|
||||
<div>
|
||||
<h1 className="admin-title">Admin-Dashboard</h1>
|
||||
<p className="admin-subtitle">
|
||||
Übersicht über Nutzung und Wachstum von Kapteins Daagbok.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main className="admin-main">
|
||||
<section className="stats-kpi-grid admin-kpi-grid">
|
||||
<KpiCard icon={<Users size={20} />} label="Registrierte Benutzer" value={summary.totalUsers} />
|
||||
<KpiCard icon={<Bookmark size={20} />} label="Logbücher" value={summary.totalLogbooks} />
|
||||
<KpiCard icon={<Image size={20} />} label="Fotos" value={summary.totalPhotos} />
|
||||
<KpiCard icon={<Mic size={20} />} label="Sprachmemos" value={summary.totalVoiceMemos} />
|
||||
<KpiCard icon={<MapPin size={20} />} label="GPS-Tracks" value={summary.totalGpsTracks} />
|
||||
<KpiCard
|
||||
icon={<BarChart2 size={20} />}
|
||||
label="Einträge mit AI-Zusammenfassung"
|
||||
value={summary.aiSummaryEntries}
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section className="admin-controls">
|
||||
<div className="admin-control-group">
|
||||
<span className="admin-control-label">Zeitraum</span>
|
||||
<div className="admin-control-buttons">
|
||||
{[30, 90, 365].map((days) => (
|
||||
<button
|
||||
key={days}
|
||||
type="button"
|
||||
className={days === windowDays ? 'btn primary' : 'btn secondary'}
|
||||
onClick={() => setWindowDays(days)}
|
||||
>
|
||||
{days} Tage
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="admin-control-group">
|
||||
<span className="admin-control-label">Aggregation</span>
|
||||
<div className="admin-control-buttons">
|
||||
{(['day', 'week', 'month'] as AdminTimeBucket[]).map((b) => (
|
||||
<button
|
||||
key={b}
|
||||
type="button"
|
||||
className={b === bucket ? 'btn primary' : 'btn secondary'}
|
||||
onClick={() => setBucket(b)}
|
||||
>
|
||||
{b === 'day' ? 'Tag' : b === 'week' ? 'Woche' : 'Monat'}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="admin-charts-grid">
|
||||
<TimeSeriesChart title="Neue Benutzer" seriesKey="users_created" data={timeSeries} />
|
||||
<TimeSeriesChart title="Neue Logbücher" seriesKey="logbooks_created" data={timeSeries} />
|
||||
<TimeSeriesChart title="Foto-Aktivität" seriesKey="photos_updated" data={timeSeries} />
|
||||
</section>
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { LayoutDashboard } from 'lucide-react'
|
||||
|
||||
interface AdminHeaderButtonProps {
|
||||
onClick: () => void
|
||||
}
|
||||
|
||||
export default function AdminHeaderButton({ onClick }: AdminHeaderButtonProps) {
|
||||
const { t } = useTranslation()
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="btn-icon skipper-badge"
|
||||
onClick={onClick}
|
||||
title={t('nav.admin')}
|
||||
aria-label={t('nav.admin')}
|
||||
>
|
||||
<LayoutDashboard size={18} aria-hidden="true" />
|
||||
<span className="skipper-badge__name">{t('nav.admin')}</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Coffee } from 'lucide-react'
|
||||
import { Coffee, Mail, Compass } from 'lucide-react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { PlausibleEvents, trackPlausibleEvent } from '../services/analytics.js'
|
||||
|
||||
@@ -15,17 +15,35 @@ export default function AppFooter() {
|
||||
·
|
||||
</span>
|
||||
<span className="app-version-footer__copyright">
|
||||
© 2026 KnorrLabs/
|
||||
<a
|
||||
href="mailto:elpatron+kd@mailbox.org"
|
||||
onClick={() => trackPlausibleEvent(PlausibleEvents.FOOTER_LINK_CLICKED)}
|
||||
>
|
||||
Markus F.J. Busche
|
||||
</a>
|
||||
© 2026
|
||||
</span>
|
||||
<span className="app-version-footer__sep" aria-hidden="true">
|
||||
·
|
||||
</span>
|
||||
<a
|
||||
className="knorrlabs-footer-badge"
|
||||
href="https://dashy.elpatron.me/"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
onClick={() => trackPlausibleEvent(PlausibleEvents.FOOTER_LINK_CLICKED)}
|
||||
>
|
||||
<Compass size={14} aria-hidden="true" />
|
||||
<span>KnorrLabs</span>
|
||||
</a>
|
||||
<span className="app-version-footer__sep" aria-hidden="true">
|
||||
·
|
||||
</span>
|
||||
<a
|
||||
className="mail-footer-badge"
|
||||
href="mailto:moin@kapteins-daagbok.eu"
|
||||
onClick={() => trackPlausibleEvent(PlausibleEvents.FOOTER_LINK_CLICKED)}
|
||||
>
|
||||
<Mail size={14} aria-hidden="true" />
|
||||
<span>moin@kapteins-daagbok.eu</span>
|
||||
</a>
|
||||
<span className="app-version-footer__sep" aria-hidden="true">
|
||||
·
|
||||
</span>
|
||||
<a
|
||||
className="kofi-footer-badge"
|
||||
href={KOFI_URL}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState } from 'react'
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { cycleAppLanguage, getNextLanguage } from '../utils/i18nLanguages.js'
|
||||
import {
|
||||
@@ -12,7 +12,8 @@ import {
|
||||
getKnownUsernames,
|
||||
forgetUsername,
|
||||
hasUnlockedLocalSession,
|
||||
logoutUser
|
||||
logoutUser,
|
||||
resolveRestoreUsername
|
||||
} from '../services/auth.js'
|
||||
import { KeyRound, ShieldAlert, Languages, HelpCircle, UserRound, X } from 'lucide-react'
|
||||
import RegistrationDisclaimer from './RegistrationDisclaimer.tsx'
|
||||
@@ -27,9 +28,15 @@ import {
|
||||
interface AuthOnboardingProps {
|
||||
onAuthenticated: () => void
|
||||
onOpenDemo?: () => void
|
||||
/** Server session cookie is valid but the in-memory master key was lost (e.g. after reload). */
|
||||
restoreSession?: boolean
|
||||
}
|
||||
|
||||
export default function AuthOnboarding({ onAuthenticated, onOpenDemo }: AuthOnboardingProps) {
|
||||
export default function AuthOnboarding({
|
||||
onAuthenticated,
|
||||
onOpenDemo,
|
||||
restoreSession = false
|
||||
}: AuthOnboardingProps) {
|
||||
const { t, i18n } = useTranslation()
|
||||
const [username, setUsername] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
@@ -60,7 +67,10 @@ export default function AuthOnboarding({ onAuthenticated, onOpenDemo }: AuthOnbo
|
||||
const [isNewRegistration, setIsNewRegistration] = useState(false)
|
||||
const [showDisclaimer, setShowDisclaimer] = useState(false)
|
||||
const [showHelp, setShowHelp] = useState(false)
|
||||
const [showStandardLogin, setShowStandardLogin] = useState(false)
|
||||
const autoUnlockAttempted = useRef(false)
|
||||
|
||||
const isRestoreFlow = restoreSession && !showStandardLogin
|
||||
const passkeyHostOk = isPasskeyCompatibleLocation()
|
||||
const passkeyCompatibleUrl = passkeyHostOk ? null : toPasskeyCompatibleUrl(window.location.href)
|
||||
|
||||
@@ -144,6 +154,23 @@ export default function AuthOnboarding({ onAuthenticated, onOpenDemo }: AuthOnbo
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!isRestoreFlow || autoUnlockAttempted.current) return
|
||||
|
||||
const user = resolveRestoreUsername()
|
||||
if (user && hasLocalPin(user)) {
|
||||
autoUnlockAttempted.current = true
|
||||
setUsername(user)
|
||||
setShowPinLogin(true)
|
||||
return
|
||||
}
|
||||
|
||||
if (user && passkeyHostOk) {
|
||||
autoUnlockAttempted.current = true
|
||||
void handleLogin(user)
|
||||
}
|
||||
}, [isRestoreFlow, passkeyHostOk])
|
||||
|
||||
const handleRecoverySubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!recoveryInput.trim() || !encryptedPayloads) return
|
||||
@@ -347,10 +374,10 @@ export default function AuthOnboarding({ onAuthenticated, onOpenDemo }: AuthOnbo
|
||||
<div className="auth-card glass">
|
||||
<div className="auth-header">
|
||||
<KeyRound className="auth-icon accent" size={48} />
|
||||
<h2>{t('auth.enter_pin_title')}</h2>
|
||||
<h2>{isRestoreFlow ? t('auth.restore_title') : t('auth.enter_pin_title')}</h2>
|
||||
</div>
|
||||
<p className="recovery-warning">
|
||||
{t('auth.enter_pin_warning')}
|
||||
{isRestoreFlow ? t('auth.restore_pin_warning') : t('auth.enter_pin_warning')}
|
||||
</p>
|
||||
|
||||
<form onSubmit={handlePinLoginSubmit} className="auth-form">
|
||||
@@ -397,6 +424,12 @@ export default function AuthOnboarding({ onAuthenticated, onOpenDemo }: AuthOnbo
|
||||
type="button"
|
||||
className="btn secondary"
|
||||
onClick={() => {
|
||||
if (isRestoreFlow) {
|
||||
setShowPinLogin(false)
|
||||
setPinLoginInput('')
|
||||
setError(null)
|
||||
return
|
||||
}
|
||||
void (async () => {
|
||||
setShowPinLogin(false)
|
||||
setPinLoginInput('')
|
||||
@@ -480,6 +513,101 @@ export default function AuthOnboarding({ onAuthenticated, onOpenDemo }: AuthOnbo
|
||||
)
|
||||
}
|
||||
|
||||
// Render: Session restore (active server cookie, master key lost after reload)
|
||||
if (isRestoreFlow) {
|
||||
const restoreUser = resolveRestoreUsername()
|
||||
const restoreKnownUsers = getKnownUsernames()
|
||||
|
||||
return (
|
||||
<div className="auth-card glass">
|
||||
<div className="auth-header">
|
||||
<KeyRound className="auth-icon accent" size={48} />
|
||||
<h2>{t('auth.restore_title')}</h2>
|
||||
</div>
|
||||
<p className="recovery-warning">{t('auth.restore_subtitle')}</p>
|
||||
|
||||
{loading && (
|
||||
<p className="dashboard-status-msg" style={{ marginTop: '12px' }}>
|
||||
{t('auth.restore_unlocking')}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{error && <div className="auth-error">{error}</div>}
|
||||
|
||||
{!loading && (
|
||||
<div className="auth-actions" style={{ flexDirection: 'column', gap: '10px', marginTop: '16px' }}>
|
||||
{restoreUser && passkeyHostOk && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn primary"
|
||||
onClick={() => handleLogin(restoreUser)}
|
||||
style={{ width: '100%' }}
|
||||
>
|
||||
{t('auth.restore_with_passkey', { name: restoreUser })}
|
||||
</button>
|
||||
)}
|
||||
|
||||
{restoreUser && hasLocalPin(restoreUser) && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn secondary"
|
||||
onClick={() => {
|
||||
setUsername(restoreUser)
|
||||
setShowPinLogin(true)
|
||||
}}
|
||||
style={{ width: '100%' }}
|
||||
>
|
||||
{t('auth.restore_with_pin')}
|
||||
</button>
|
||||
)}
|
||||
|
||||
{restoreKnownUsers.length > 1 && (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px', width: '100%' }}>
|
||||
<span style={{ fontSize: '12px', color: '#64748b', textTransform: 'uppercase' }}>
|
||||
{t('auth.quick_login')}
|
||||
</span>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px', width: '100%' }}>
|
||||
{restoreKnownUsers.map((name) => (
|
||||
<button
|
||||
key={name}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
if (hasLocalPin(name)) {
|
||||
setUsername(name)
|
||||
setShowPinLogin(true)
|
||||
} else {
|
||||
void handleLogin(name)
|
||||
}
|
||||
}}
|
||||
disabled={loading}
|
||||
className="btn secondary"
|
||||
style={{ display: 'flex', alignItems: 'center', gap: '6px' }}
|
||||
>
|
||||
<UserRound size={16} />
|
||||
{name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="btn secondary"
|
||||
onClick={() => {
|
||||
setShowStandardLogin(true)
|
||||
setError(null)
|
||||
}}
|
||||
style={{ width: '100%' }}
|
||||
>
|
||||
{t('auth.restore_other_account')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Render 3: Standard Login / Registration options form
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import React from 'react'
|
||||
|
||||
interface PersonSnapshot {
|
||||
name: string
|
||||
photo?: string | null
|
||||
role?: string
|
||||
}
|
||||
|
||||
interface CreatorAvatarProps {
|
||||
creatorId?: string
|
||||
crewSnapshotsById?: Record<string, PersonSnapshot>
|
||||
fallbackName?: string
|
||||
size?: number
|
||||
}
|
||||
|
||||
const colors = [
|
||||
'#2563eb', // blue
|
||||
'#059669', // emerald
|
||||
'#d97706', // amber
|
||||
'#dc2626', // red
|
||||
'#7c3aed', // violet
|
||||
'#db2777', // pink
|
||||
'#0891b2', // cyan
|
||||
'#4f46e5', // indigo
|
||||
'#0f766e', // teal
|
||||
'#9333ea', // purple
|
||||
]
|
||||
|
||||
function getAvatarColor(name: string): string {
|
||||
let hash = 0
|
||||
for (let i = 0; i < name.length; i++) {
|
||||
hash = name.charCodeAt(i) + ((hash << 5) - hash)
|
||||
}
|
||||
const index = Math.abs(hash) % colors.length
|
||||
return colors[index]
|
||||
}
|
||||
|
||||
export default function CreatorAvatar({
|
||||
creatorId,
|
||||
crewSnapshotsById,
|
||||
fallbackName,
|
||||
size = 28
|
||||
}: CreatorAvatarProps) {
|
||||
let name = ''
|
||||
let photo: string | null = null
|
||||
let role = ''
|
||||
|
||||
if (creatorId && crewSnapshotsById && crewSnapshotsById[creatorId]) {
|
||||
const snap = crewSnapshotsById[creatorId]
|
||||
name = snap.name || ''
|
||||
photo = snap.photo || null
|
||||
role = snap.role || ''
|
||||
}
|
||||
|
||||
// Fallback to active username if owner or no crew pool matches
|
||||
if (!name) {
|
||||
if (creatorId === 'skipper') {
|
||||
name = fallbackName || localStorage.getItem('active_username') || 'Skipper'
|
||||
role = 'skipper'
|
||||
} else if (fallbackName) {
|
||||
name = fallbackName
|
||||
} else if (creatorId) {
|
||||
// If creatorId is a username itself (fallback from LiveLogView)
|
||||
name = creatorId
|
||||
} else {
|
||||
name = '?'
|
||||
}
|
||||
}
|
||||
|
||||
const initial = name ? name.trim().split(/\s+/)[0]?.charAt(0).toUpperCase() || '?' : '?'
|
||||
const bgColor = name === '?' ? '#64748b' : getAvatarColor(name)
|
||||
|
||||
const style: React.CSSProperties = {
|
||||
width: `${size}px`,
|
||||
height: `${size}px`,
|
||||
borderRadius: '50%',
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
fontSize: `${Math.round(size * 0.45)}px`,
|
||||
fontWeight: 'bold',
|
||||
color: '#ffffff',
|
||||
backgroundColor: bgColor,
|
||||
flexShrink: 0,
|
||||
verticalAlign: 'middle',
|
||||
overflow: 'hidden',
|
||||
border: '1px solid rgba(255, 255, 255, 0.15)',
|
||||
boxSizing: 'border-box'
|
||||
}
|
||||
|
||||
const roleText = role ? (role === 'skipper' ? 'Skipper' : 'Crew') : ''
|
||||
const tooltip = name + (roleText ? ` (${roleText})` : '')
|
||||
|
||||
if (photo) {
|
||||
return (
|
||||
<img
|
||||
src={photo}
|
||||
alt={name}
|
||||
title={tooltip}
|
||||
style={{
|
||||
...style,
|
||||
objectFit: 'cover',
|
||||
backgroundColor: 'transparent'
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={style} title={tooltip} className="creator-avatar-fallback">
|
||||
{initial}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -23,13 +23,14 @@ import {
|
||||
} from 'lucide-react'
|
||||
import { PlausibleEvents, trackPlausibleEvent } from '../services/analytics.js'
|
||||
import {
|
||||
appendQuickEvent,
|
||||
appendQuickEvents,
|
||||
appendTankRefill,
|
||||
appendQuickEvent as apiAppendQuickEvent,
|
||||
appendQuickEvents as apiAppendQuickEvents,
|
||||
appendTankRefill as apiAppendTankRefill,
|
||||
findOrCreateTodayEntry,
|
||||
loadEntry,
|
||||
removeLastEvent
|
||||
} from '../services/quickEventLog.js'
|
||||
import CreatorAvatar from './CreatorAvatar.tsx'
|
||||
import { formatEventSummary } from '../utils/formatEventSummary.js'
|
||||
import {
|
||||
getLastAutoPositionMs,
|
||||
@@ -160,6 +161,24 @@ function gpsFailureAlertBody(
|
||||
return `${t(geolocationErrorI18nKey(reason))}\n\n${t('logs.live_position_manual_hint')}`
|
||||
}
|
||||
|
||||
function findActiveCreatorId(
|
||||
activeUsername: string | null,
|
||||
crewSnapshotsById: Record<string, any>,
|
||||
selectedSkipperId: string | null
|
||||
): string {
|
||||
const username = (activeUsername || '').trim()
|
||||
if (username) {
|
||||
const matchEntry = Object.entries(crewSnapshotsById).find(
|
||||
([_, snap]) => (snap?.name || '').trim().toLowerCase() === username.toLowerCase()
|
||||
)
|
||||
if (matchEntry) {
|
||||
return matchEntry[0]
|
||||
}
|
||||
return username
|
||||
}
|
||||
return selectedSkipperId || 'skipper'
|
||||
}
|
||||
|
||||
export default function LiveLogView({
|
||||
logbookId,
|
||||
onOpenEditor,
|
||||
@@ -173,6 +192,8 @@ export default function LiveLogView({
|
||||
const [dayOfTravel, setDayOfTravel] = useState('')
|
||||
const [date, setDate] = useState('')
|
||||
const [events, setEvents] = useState<LogEventPayload[]>([])
|
||||
const [crewSnapshotsById, setCrewSnapshotsById] = useState<Record<string, any>>({})
|
||||
const [selectedSkipperId, setSelectedSkipperId] = useState<string | null>(null)
|
||||
const [yachtSails, setYachtSails] = useState<string[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [busy, setBusy] = useState(false)
|
||||
@@ -214,6 +235,51 @@ export default function LiveLogView({
|
||||
dateRef.current = date
|
||||
busyRef.current = busy
|
||||
|
||||
const getActiveCreatorId = useCallback(() => {
|
||||
const activeUsername = localStorage.getItem('active_username')
|
||||
return findActiveCreatorId(activeUsername, crewSnapshotsById, selectedSkipperId)
|
||||
}, [crewSnapshotsById, selectedSkipperId])
|
||||
|
||||
const appendQuickEvent = useCallback((
|
||||
logbookId: string,
|
||||
entryId: string,
|
||||
partialEvent: Partial<LogEventPayload>,
|
||||
headerPatch?: { departure?: string; destination?: string }
|
||||
) => {
|
||||
return apiAppendQuickEvent(
|
||||
logbookId,
|
||||
entryId,
|
||||
{ creatorId: getActiveCreatorId(), ...partialEvent },
|
||||
headerPatch
|
||||
)
|
||||
}, [getActiveCreatorId])
|
||||
|
||||
const appendQuickEvents = useCallback((
|
||||
logbookId: string,
|
||||
entryId: string,
|
||||
partialEvents: Partial<LogEventPayload>[]
|
||||
) => {
|
||||
const creatorId = getActiveCreatorId()
|
||||
const mapped = partialEvents.map((p) => ({ creatorId, ...p }))
|
||||
return apiAppendQuickEvents(logbookId, entryId, mapped)
|
||||
}, [getActiveCreatorId])
|
||||
|
||||
const appendTankRefill = useCallback((
|
||||
logbookId: string,
|
||||
entryId: string,
|
||||
tank: 'fuel' | 'freshwater',
|
||||
addLiters: number,
|
||||
event: Partial<LogEventPayload>
|
||||
) => {
|
||||
return apiAppendTankRefill(
|
||||
logbookId,
|
||||
entryId,
|
||||
tank,
|
||||
addLiters,
|
||||
{ creatorId: getActiveCreatorId(), ...event }
|
||||
)
|
||||
}, [getActiveCreatorId])
|
||||
|
||||
const defaultSails = useMemo(
|
||||
() => (i18n.language === 'de'
|
||||
? ['Großsegel', 'Genua', 'Fock', 'Spinnaker', 'Gennaker']
|
||||
@@ -237,6 +303,8 @@ export default function LiveLogView({
|
||||
setDayOfTravel(String(loaded.data.dayOfTravel || ''))
|
||||
setDate(String(loaded.data.date || ''))
|
||||
setEvents(sortLogEventsByTime(entryEvents.map((e) => ({ ...e }))))
|
||||
setCrewSnapshotsById((loaded.data.crewSnapshotsById as Record<string, any>) || {})
|
||||
setSelectedSkipperId(typeof loaded.data.selectedSkipperId === 'string' ? loaded.data.selectedSkipperId : null)
|
||||
}, [])
|
||||
|
||||
const refreshEntry = useCallback(async (id: string) => {
|
||||
@@ -1152,6 +1220,11 @@ export default function LiveLogView({
|
||||
return (
|
||||
<li key={`${event.time}-${index}`} className="live-log-entry">
|
||||
<time className="live-log-time">{event.time}</time>
|
||||
<CreatorAvatar
|
||||
creatorId={event.creatorId}
|
||||
crewSnapshotsById={crewSnapshotsById}
|
||||
size={24}
|
||||
/>
|
||||
<div className="live-log-summary-block">
|
||||
<span className="live-log-summary">{summary}</span>
|
||||
{voiceId && (
|
||||
|
||||
@@ -43,6 +43,53 @@ export default function LiveVoiceCapture({
|
||||
const [previewMime, setPreviewMime] = useState('audio/webm')
|
||||
const [previewDurationSec, setPreviewDurationSec] = useState(0)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const log = useCallback((msg: string) => {
|
||||
console.log(`[VoiceDebug] ${msg}`)
|
||||
}, [])
|
||||
|
||||
const previewAudioRef = useRef<HTMLAudioElement | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const el = previewAudioRef.current
|
||||
if (!el) {
|
||||
log('previewAudioRef is null')
|
||||
return
|
||||
}
|
||||
|
||||
log('Preview audio player loaded. readyState=' + el.readyState + ', duration=' + el.duration + ', src=' + el.src)
|
||||
|
||||
const handleLoadedMetadata = () => {
|
||||
log('loadedmetadata event fired. readyState=' + el.readyState + ', duration=' + el.duration)
|
||||
if (el.duration === Infinity || isNaN(el.duration) || el.duration === 0) {
|
||||
log('Duration correction hack triggered (duration=' + el.duration + '). Seeking to 1e10...')
|
||||
el.currentTime = 1e10
|
||||
const onTimeUpdate = () => {
|
||||
log('timeupdate event. currentTime=' + el.currentTime + ', duration=' + el.duration)
|
||||
el.currentTime = 0
|
||||
el.removeEventListener('timeupdate', onTimeUpdate)
|
||||
log('currentTime reset to 0. Final duration=' + el.duration)
|
||||
}
|
||||
el.addEventListener('timeupdate', onTimeUpdate)
|
||||
} else {
|
||||
log('Duration correction skipped (duration is valid)')
|
||||
}
|
||||
}
|
||||
|
||||
if (el.readyState >= 1) {
|
||||
log('readyState >= 1. Executing hack immediately...')
|
||||
handleLoadedMetadata()
|
||||
} else {
|
||||
log('readyState = 0. Adding loadedmetadata event listener...')
|
||||
el.addEventListener('loadedmetadata', handleLoadedMetadata)
|
||||
}
|
||||
|
||||
log('Calling el.load() to force loading of the media resource...')
|
||||
el.load()
|
||||
|
||||
return () => {
|
||||
el.removeEventListener('loadedmetadata', handleLoadedMetadata)
|
||||
}
|
||||
}, [previewUrl, log])
|
||||
|
||||
const stopStream = useCallback(() => {
|
||||
for (const track of streamRef.current?.getTracks() ?? []) {
|
||||
@@ -115,22 +162,46 @@ export default function LiveVoiceCapture({
|
||||
const startRecording = async () => {
|
||||
setMicError(null)
|
||||
chunksRef.current = []
|
||||
log('startRecording flow triggered')
|
||||
if (!navigator.mediaDevices?.getUserMedia) {
|
||||
log('navigator.mediaDevices.getUserMedia is unavailable')
|
||||
setMicError(t('logs.live_voice_mic_denied'))
|
||||
return
|
||||
}
|
||||
try {
|
||||
log('Requesting getUserMedia audio stream...')
|
||||
const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
|
||||
streamRef.current = stream
|
||||
log('Stream obtained successfully. active=' + stream.active)
|
||||
stream.getTracks().forEach((track, i) => {
|
||||
log(`Track ${i}: label="${track.label}" enabled=${track.enabled} readyState=${track.readyState} muted=${track.muted}`)
|
||||
})
|
||||
|
||||
const mimeType = pickMediaRecorderMimeType()
|
||||
log('MIME type candidates support check:')
|
||||
const MIME_CANDIDATES = [
|
||||
'audio/webm;codecs=opus',
|
||||
'audio/webm',
|
||||
'audio/mp4',
|
||||
'audio/ogg;codecs=opus'
|
||||
]
|
||||
MIME_CANDIDATES.forEach(mime => {
|
||||
log(` - ${mime}: ${MediaRecorder.isTypeSupported(mime) ? 'SUPPORTED' : 'UNSUPPORTED'}`)
|
||||
})
|
||||
log('Selected MIME from picker: ' + mimeType)
|
||||
|
||||
const recorder = mimeType
|
||||
? new MediaRecorder(stream, { mimeType })
|
||||
: new MediaRecorder(stream)
|
||||
mediaRecorderRef.current = recorder
|
||||
const resolvedMime = recorder.mimeType || mimeType || 'audio/webm'
|
||||
log('MediaRecorder created. Resolved mime=' + resolvedMime)
|
||||
|
||||
recorder.ondataavailable = (ev) => {
|
||||
if (ev.data.size > 0) chunksRef.current.push(ev.data)
|
||||
log(`ondataavailable event: data size=${ev.data?.size} bytes`)
|
||||
if (ev.data && ev.data.size > 0) {
|
||||
chunksRef.current.push(ev.data)
|
||||
}
|
||||
}
|
||||
|
||||
recorder.onstop = () => {
|
||||
@@ -138,45 +209,67 @@ export default function LiveVoiceCapture({
|
||||
VOICE_MEMO_MAX_DURATION_SEC,
|
||||
Math.max(1, Math.round((Date.now() - startedAtRef.current) / 1000))
|
||||
)
|
||||
const blob = new Blob(chunksRef.current, { type: resolvedMime })
|
||||
chunksRef.current = []
|
||||
stopStream()
|
||||
try {
|
||||
assertVoiceMemoBlobSize(blob)
|
||||
finishRecording(blob, resolvedMime, durationSec)
|
||||
} catch {
|
||||
setMicError(t('logs.live_voice_too_large'))
|
||||
setPhase('idle')
|
||||
}
|
||||
log(`onstop triggered. durationSec=${durationSec}. Wrapping in 50ms timeout...`)
|
||||
setTimeout(() => {
|
||||
log(`Creating Blob from ${chunksRef.current.length} chunks. Resolved mime=${resolvedMime}`)
|
||||
const totalChunksSize = chunksRef.current.reduce((acc, chunk) => acc + chunk.size, 0)
|
||||
log(`Total raw chunks size: ${totalChunksSize} bytes`)
|
||||
const blob = new Blob(chunksRef.current, { type: resolvedMime })
|
||||
chunksRef.current = []
|
||||
stopStream()
|
||||
log(`Blob finalized: size=${blob.size} bytes, type=${blob.type}`)
|
||||
try {
|
||||
assertVoiceMemoBlobSize(blob)
|
||||
log('Blob size assertion passed. Calling finishRecording...')
|
||||
finishRecording(blob, resolvedMime, durationSec)
|
||||
} catch (err) {
|
||||
log('Blob size assertion failed (too large)')
|
||||
setMicError(t('logs.live_voice_too_large'))
|
||||
setPhase('idle')
|
||||
}
|
||||
}, 50)
|
||||
}
|
||||
|
||||
recorder.onerror = () => {
|
||||
recorder.onerror = (ev) => {
|
||||
log('MediaRecorder onerror triggered: ' + JSON.stringify(ev))
|
||||
setMicError(t('logs.live_voice_record_failed'))
|
||||
resetAll()
|
||||
}
|
||||
|
||||
startedAtRef.current = Date.now()
|
||||
recorder.start(200)
|
||||
log('Calling recorder.start()...')
|
||||
recorder.start()
|
||||
log('recorder.start() called. State=' + recorder.state)
|
||||
setPhase('recording')
|
||||
setElapsedSec(0)
|
||||
timerRef.current = window.setInterval(() => {
|
||||
const sec = Math.floor((Date.now() - startedAtRef.current) / 1000)
|
||||
setElapsedSec(sec)
|
||||
if (sec >= VOICE_MEMO_MAX_DURATION_SEC) {
|
||||
log('Max duration reached. Stopping recording...')
|
||||
stopRecording()
|
||||
}
|
||||
}, 250)
|
||||
} catch {
|
||||
} catch (err: any) {
|
||||
log('Error in startRecording try-catch block: ' + (err instanceof Error ? err.stack || err.message : String(err)))
|
||||
setMicError(t('logs.live_voice_mic_denied'))
|
||||
stopStream()
|
||||
}
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!previewBlob || saving || busy) return
|
||||
if (!previewBlob || saving || busy) {
|
||||
log('handleSave ignored. previewBlob=' + (previewBlob ? 'PRESENT' : 'NULL') + ' saving=' + saving + ' busy=' + busy)
|
||||
return
|
||||
}
|
||||
log('handleSave triggered. Saving blob size=' + previewBlob.size + ' mime=' + previewMime + ' duration=' + previewDurationSec)
|
||||
setSaving(true)
|
||||
try {
|
||||
onSave(previewBlob, previewMime, previewDurationSec)
|
||||
log('Invoking onSave callback...')
|
||||
await onSave(previewBlob, previewMime, previewDurationSec)
|
||||
log('onSave callback successfully finished!')
|
||||
} catch (err: any) {
|
||||
log('Error during onSave execution: ' + (err instanceof Error ? err.stack || err.message : String(err)))
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
@@ -241,7 +334,7 @@ export default function LiveVoiceCapture({
|
||||
|
||||
{phase === 'preview' && previewUrl && (
|
||||
<>
|
||||
<audio className="voice-memo-player" controls src={previewUrl} preload="auto" />
|
||||
<audio ref={previewAudioRef} className="voice-memo-player" controls src={previewUrl} preload="auto" />
|
||||
{onCaptionChange && (
|
||||
<label className="live-voice-caption-field">
|
||||
<span>{t('logs.live_voice_caption_label')}</span>
|
||||
@@ -278,6 +371,8 @@ export default function LiveVoiceCapture({
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -11,6 +11,7 @@ import { downloadLogbookPagePdf } from '../services/pdfExport.js'
|
||||
import { FileText, Save, ChevronLeft, Check, Compass, Plus, Trash2, MapPin, CloudSun, Clock, Download, Upload, Pencil, X, ChevronDown, ChevronUp, Sparkles } from 'lucide-react'
|
||||
import PhotoCapture from './PhotoCapture.tsx'
|
||||
import EventRemarksCell from './EventRemarksCell.tsx'
|
||||
import CreatorAvatar from './CreatorAvatar.tsx'
|
||||
import { useEntryVoiceMemos } from '../hooks/useEntryVoiceMemos.js'
|
||||
import { parseLiveVoiceRemark } from '../utils/liveEventCodes.js'
|
||||
import { deleteEntryVoiceMemo } from '../services/voiceAttachments.js'
|
||||
@@ -173,6 +174,24 @@ function fingerprintFromStoredEntry(decrypted: Record<string, unknown>): string
|
||||
})
|
||||
}
|
||||
|
||||
function findActiveCreatorId(
|
||||
activeUsername: string | null,
|
||||
crewSnapshotsById: Record<string, any>,
|
||||
selectedSkipperId: string | null
|
||||
): string {
|
||||
const username = (activeUsername || '').trim()
|
||||
if (username) {
|
||||
const matchEntry = Object.entries(crewSnapshotsById).find(
|
||||
([_, snap]) => (snap?.name || '').trim().toLowerCase() === username.toLowerCase()
|
||||
)
|
||||
if (matchEntry) {
|
||||
return matchEntry[0]
|
||||
}
|
||||
return username
|
||||
}
|
||||
return selectedSkipperId || 'skipper'
|
||||
}
|
||||
|
||||
interface LogEntryEditorProps {
|
||||
entryId: string
|
||||
logbookId: string
|
||||
@@ -418,8 +437,17 @@ export default function LogEntryEditor({
|
||||
})
|
||||
}, [buildPayloadForSigning, signSkipper, signCrew])
|
||||
|
||||
const buildEventFromForm = (): LogEvent =>
|
||||
normalizeLogEvent({
|
||||
const buildEventFromForm = (): LogEvent => {
|
||||
let creatorId: string | undefined = undefined
|
||||
if (editingEventIndex !== null && events[editingEventIndex]) {
|
||||
creatorId = events[editingEventIndex].creatorId
|
||||
}
|
||||
if (!creatorId) {
|
||||
const activeUsername = localStorage.getItem('active_username')
|
||||
creatorId = findActiveCreatorId(activeUsername, entryCrew.crewSnapshotsById, entryCrew.selectedSkipperId)
|
||||
}
|
||||
|
||||
return normalizeLogEvent({
|
||||
time: evTime,
|
||||
mgk: evMgk,
|
||||
rwk: evRwk,
|
||||
@@ -436,8 +464,10 @@ export default function LogEntryEditor({
|
||||
distance: evDistance,
|
||||
gpsLat: evGpsLat,
|
||||
gpsLng: evGpsLng,
|
||||
remarks: evRemarks
|
||||
remarks: evRemarks,
|
||||
creatorId
|
||||
})
|
||||
}
|
||||
|
||||
const applyEventFormToEvents = (eventData: LogEvent): LogEvent[] => {
|
||||
if (editingEventIndex !== null) {
|
||||
@@ -1815,6 +1845,7 @@ export default function LogEntryEditor({
|
||||
<thead>
|
||||
<tr>
|
||||
<th>{t('logs.event_time')}</th>
|
||||
<th>{t('logs.event_creator')}</th>
|
||||
<th>{t('logs.event_mgk')}</th>
|
||||
<th>{t('logs.event_rwk')}</th>
|
||||
<th>{t('logs.event_wind_direction')}</th>
|
||||
@@ -1831,6 +1862,13 @@ export default function LogEntryEditor({
|
||||
{events.map((ev, idx) => (
|
||||
<tr key={idx}>
|
||||
<td className="font-mono">{ev.time}</td>
|
||||
<td style={{ textAlign: 'center', width: '40px', verticalAlign: 'middle' }}>
|
||||
<CreatorAvatar
|
||||
creatorId={ev.creatorId}
|
||||
crewSnapshotsById={entryCrew.crewSnapshotsById}
|
||||
size={24}
|
||||
/>
|
||||
</td>
|
||||
<td>{ev.mgk ? `${ev.mgk}°` : '—'}</td>
|
||||
<td>{ev.rwk ? `${ev.rwk}°` : '—'}</td>
|
||||
<td>{ev.windDirection || '—'}</td>
|
||||
|
||||
@@ -15,11 +15,13 @@ import { BookOpen, Plus, Trash2, LogOut, Languages, RefreshCw, Ship, Wifi, WifiO
|
||||
import DisclaimerHeaderButton from './DisclaimerHeaderButton.tsx'
|
||||
import FeedbackHeaderButton from './FeedbackHeaderButton.tsx'
|
||||
import ProfileHeaderButton from './ProfileHeaderButton.tsx'
|
||||
import AdminHeaderButton from './AdminHeaderButton.tsx'
|
||||
|
||||
interface LogbookDashboardProps {
|
||||
onSelectLogbook: (id: string, title: string) => void
|
||||
onLogout: () => void
|
||||
onOpenProfile: () => void
|
||||
onOpenAdmin?: () => void
|
||||
}
|
||||
|
||||
type LogbookSortKey = 'name' | 'date'
|
||||
@@ -42,7 +44,7 @@ function sortLogbooks(
|
||||
return sorted
|
||||
}
|
||||
|
||||
export default function LogbookDashboard({ onSelectLogbook, onLogout, onOpenProfile }: LogbookDashboardProps) {
|
||||
export default function LogbookDashboard({ onSelectLogbook, onLogout, onOpenProfile, onOpenAdmin }: LogbookDashboardProps) {
|
||||
const { t, i18n } = useTranslation()
|
||||
const { showConfirm } = useDialog()
|
||||
const [logbooks, setLogbooks] = useState<DecryptedLogbook[]>([])
|
||||
@@ -388,6 +390,8 @@ export default function LogbookDashboard({ onSelectLogbook, onLogout, onOpenProf
|
||||
|
||||
<ProfileHeaderButton onClick={onOpenProfile} />
|
||||
|
||||
{onOpenAdmin && <AdminHeaderButton onClick={onOpenAdmin} />}
|
||||
|
||||
{/* Lang toggle */}
|
||||
<button className="btn-icon" onClick={toggleLanguage} title="Switch Language">
|
||||
<Languages size={18} />
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useEffect, useState, useRef } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { db } from '../services/db.js'
|
||||
import { getActiveMasterKey } from '../services/auth.js'
|
||||
@@ -30,6 +30,38 @@ export default function VoiceMemoPlayer({
|
||||
const [src, setSrc] = useState<string | null>(preloaded?.audio ?? null)
|
||||
const [error, setError] = useState(false)
|
||||
|
||||
const audioRef = useRef<HTMLAudioElement | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const el = audioRef.current
|
||||
if (!el) return
|
||||
|
||||
const handleLoadedMetadata = () => {
|
||||
if (el.duration === Infinity || isNaN(el.duration) || el.duration === 0) {
|
||||
el.currentTime = 1e10
|
||||
const onTimeUpdate = () => {
|
||||
el.currentTime = 0
|
||||
el.removeEventListener('timeupdate', onTimeUpdate)
|
||||
}
|
||||
el.addEventListener('timeupdate', onTimeUpdate)
|
||||
}
|
||||
}
|
||||
|
||||
if (el.readyState >= 1) {
|
||||
handleLoadedMetadata()
|
||||
} else {
|
||||
el.addEventListener('loadedmetadata', handleLoadedMetadata)
|
||||
}
|
||||
|
||||
if (src) {
|
||||
el.load()
|
||||
}
|
||||
|
||||
return () => {
|
||||
el.removeEventListener('loadedmetadata', handleLoadedMetadata)
|
||||
}
|
||||
}, [src])
|
||||
|
||||
useEffect(() => {
|
||||
if (preloaded?.audio) {
|
||||
setSrc(preloaded.audio)
|
||||
@@ -75,7 +107,7 @@ export default function VoiceMemoPlayer({
|
||||
|
||||
return (
|
||||
<div className="voice-memo-player-shell">
|
||||
<audio className={playerClass} controls preload="none" src={src} />
|
||||
<audio ref={audioRef} className={playerClass} controls preload="metadata" src={src} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -43,7 +43,8 @@
|
||||
"deviation": "Tabel over distraktioner",
|
||||
"logs": "Indlæg i logbogen",
|
||||
"stats": "Statistik",
|
||||
"settings": "Indstillinger"
|
||||
"settings": "Indstillinger",
|
||||
"admin": "Admin"
|
||||
},
|
||||
"auth": {
|
||||
"welcome": "Velkommen til Kapteins Daagbok.",
|
||||
@@ -90,7 +91,15 @@
|
||||
"use_localhost_link": "Skift til localhost",
|
||||
"error_passkey_cancelled": "Passkey-login blev annulleret eller udløb. Prøv igen.",
|
||||
"error_invalid_rp_id": "Passkey-domæne matcher ikke (RP ID). Brug http://localhost:5173 med RP_ID=localhost i .env til lokal udvikling.",
|
||||
"error_session_incomplete": "Login ufuldstændig. Log ind med passkey igen."
|
||||
"error_session_incomplete": "Login ufuldstændig. Log ind med passkey igen.",
|
||||
"restore_checking": "Tjekker session…",
|
||||
"restore_title": "Gendan session",
|
||||
"restore_subtitle": "Du er stadig logget ind. Lås din logbog op med passkey eller PIN.",
|
||||
"restore_unlocking": "Låser op…",
|
||||
"restore_with_passkey": "Lås op med passkey ({{name}})",
|
||||
"restore_with_pin": "Lås op med PIN",
|
||||
"restore_pin_warning": "Indtast din lokale PIN for at låse logbogen op efter genindlæsning.",
|
||||
"restore_other_account": "Log ind med en anden konto"
|
||||
},
|
||||
"pwa": {
|
||||
"title": "Installer app",
|
||||
@@ -344,6 +353,7 @@
|
||||
"carry_over_tanks_yes": "Tag over",
|
||||
"carry_over_tanks_no": "Start med 0",
|
||||
"event_title": "Kronologisk hændelseslog",
|
||||
"event_creator": "Indtastet af",
|
||||
"no_events": "Der er endnu ikke indtastet nogen begivenheder for denne rejsedag.",
|
||||
"event_time": "Tidspunkt på dagen",
|
||||
"event_mgk": "MgK-kursus",
|
||||
|
||||
@@ -43,7 +43,8 @@
|
||||
"deviation": "Ablenkungstabelle",
|
||||
"logs": "Logbucheinträge",
|
||||
"stats": "Statistik",
|
||||
"settings": "Einstellungen"
|
||||
"settings": "Einstellungen",
|
||||
"admin": "Admin"
|
||||
},
|
||||
"auth": {
|
||||
"welcome": "Willkommen bei Kapteins Daagbok",
|
||||
@@ -90,7 +91,15 @@
|
||||
"use_localhost_link": "Zu localhost wechseln",
|
||||
"error_passkey_cancelled": "Passkey-Anmeldung abgebrochen oder abgelaufen. Bitte erneut versuchen.",
|
||||
"error_invalid_rp_id": "Passkey-Domain passt nicht (RP ID). Lokal nur http://localhost:5173 mit RP_ID=localhost in .env verwenden.",
|
||||
"error_session_incomplete": "Anmeldung unvollständig. Bitte erneut mit Passkey anmelden."
|
||||
"error_session_incomplete": "Anmeldung unvollständig. Bitte erneut mit Passkey anmelden.",
|
||||
"restore_checking": "Session wird geprüft…",
|
||||
"restore_title": "Session wiederherstellen",
|
||||
"restore_subtitle": "Deine Anmeldung ist noch aktiv. Entsperre dein Logbuch mit Passkey oder PIN.",
|
||||
"restore_unlocking": "Wird entsperrt…",
|
||||
"restore_with_passkey": "Mit Passkey entsperren ({{name}})",
|
||||
"restore_with_pin": "Mit PIN entsperren",
|
||||
"restore_pin_warning": "Gib deine lokale PIN ein, um dein Logbuch nach dem Neuladen zu entsperren.",
|
||||
"restore_other_account": "Anderer Account anmelden"
|
||||
},
|
||||
"pwa": {
|
||||
"title": "App installieren",
|
||||
@@ -344,6 +353,7 @@
|
||||
"carry_over_tanks_yes": "Übernehmen",
|
||||
"carry_over_tanks_no": "Mit 0 starten",
|
||||
"event_title": "Chronologisches Ereignisprotokoll",
|
||||
"event_creator": "Eingetragen von",
|
||||
"no_events": "Noch keine Ereignisse für diesen Reisetag eingetragen.",
|
||||
"event_time": "Uhrzeit",
|
||||
"event_mgk": "MgK Kurs",
|
||||
|
||||
@@ -43,7 +43,8 @@
|
||||
"deviation": "Deviation Table",
|
||||
"logs": "Logbook Entries",
|
||||
"stats": "Statistics",
|
||||
"settings": "Settings"
|
||||
"settings": "Settings",
|
||||
"admin": "Admin"
|
||||
},
|
||||
"auth": {
|
||||
"welcome": "Welcome to Kapteins Daagbok",
|
||||
@@ -90,7 +91,15 @@
|
||||
"use_localhost_link": "Switch to localhost",
|
||||
"error_passkey_cancelled": "Passkey sign-in was cancelled or timed out. Please try again.",
|
||||
"error_invalid_rp_id": "Passkey domain mismatch (RP ID). For local dev use http://localhost:5173 with RP_ID=localhost in .env.",
|
||||
"error_session_incomplete": "Sign-in incomplete. Please sign in with your passkey again."
|
||||
"error_session_incomplete": "Sign-in incomplete. Please sign in with your passkey again.",
|
||||
"restore_checking": "Checking session…",
|
||||
"restore_title": "Restore session",
|
||||
"restore_subtitle": "You are still signed in. Unlock your logbook with passkey or PIN.",
|
||||
"restore_unlocking": "Unlocking…",
|
||||
"restore_with_passkey": "Unlock with passkey ({{name}})",
|
||||
"restore_with_pin": "Unlock with PIN",
|
||||
"restore_pin_warning": "Enter your local PIN to unlock your logbook after reload.",
|
||||
"restore_other_account": "Sign in with another account"
|
||||
},
|
||||
"pwa": {
|
||||
"title": "Install app",
|
||||
@@ -344,6 +353,7 @@
|
||||
"carry_over_tanks_yes": "Carry over",
|
||||
"carry_over_tanks_no": "Start at 0",
|
||||
"event_title": "Chronological Event Logbook",
|
||||
"event_creator": "Entered by",
|
||||
"no_events": "No events logged for this travel day yet.",
|
||||
"event_time": "Time",
|
||||
"event_mgk": "MgK Course",
|
||||
|
||||
@@ -43,7 +43,8 @@
|
||||
"deviation": "Tabell over distraksjoner",
|
||||
"logs": "Loggbokoppføringer",
|
||||
"stats": "Statistikk",
|
||||
"settings": "Innstillinger"
|
||||
"settings": "Innstillinger",
|
||||
"admin": "Admin"
|
||||
},
|
||||
"auth": {
|
||||
"welcome": "Velkommen til Kapteins Daagbok",
|
||||
@@ -90,7 +91,15 @@
|
||||
"use_localhost_link": "Bytt til localhost",
|
||||
"error_passkey_cancelled": "Passkey-innlogging ble avbrutt eller utløp. Prøv igjen.",
|
||||
"error_invalid_rp_id": "Passkey-domene stemmer ikke (RP ID). Bruk http://localhost:5173 med RP_ID=localhost i .env for lokal utvikling.",
|
||||
"error_session_incomplete": "Innlogging ufullstendig. Logg inn med passkey igjen."
|
||||
"error_session_incomplete": "Innlogging ufullstendig. Logg inn med passkey igjen.",
|
||||
"restore_checking": "Sjekker økt…",
|
||||
"restore_title": "Gjenopprett økt",
|
||||
"restore_subtitle": "Du er fortsatt innlogget. Lås opp loggboken med passkey eller PIN.",
|
||||
"restore_unlocking": "Låser opp…",
|
||||
"restore_with_passkey": "Lås opp med passkey ({{name}})",
|
||||
"restore_with_pin": "Lås opp med PIN",
|
||||
"restore_pin_warning": "Skriv inn din lokale PIN for å låse opp loggboken etter omlasting.",
|
||||
"restore_other_account": "Logg inn med en annen konto"
|
||||
},
|
||||
"pwa": {
|
||||
"title": "Installer app",
|
||||
@@ -344,6 +353,7 @@
|
||||
"carry_over_tanks_yes": "Ta over",
|
||||
"carry_over_tanks_no": "Begynn med 0",
|
||||
"event_title": "Kronologisk hendelseslogg",
|
||||
"event_creator": "Registrert av",
|
||||
"no_events": "Ingen arrangementer lagt inn for denne reisedagen ennå.",
|
||||
"event_time": "Tid på døgnet",
|
||||
"event_mgk": "MgK-kurs",
|
||||
|
||||
@@ -43,7 +43,8 @@
|
||||
"deviation": "Distraktionsbord",
|
||||
"logs": "Loggboksanteckningar",
|
||||
"stats": "Statistik",
|
||||
"settings": "Inställningar"
|
||||
"settings": "Inställningar",
|
||||
"admin": "Admin"
|
||||
},
|
||||
"auth": {
|
||||
"welcome": "Välkommen till Kapteins Daagbok",
|
||||
@@ -90,7 +91,15 @@
|
||||
"use_localhost_link": "Byt till localhost",
|
||||
"error_passkey_cancelled": "Passkey-inloggning avbröts eller gick ut. Försök igen.",
|
||||
"error_invalid_rp_id": "Passkey-domänen matchar inte (RP ID). Använd http://localhost:5173 med RP_ID=localhost i .env för lokal utveckling.",
|
||||
"error_session_incomplete": "Inloggning ofullständig. Logga in med passkey igen."
|
||||
"error_session_incomplete": "Inloggning ofullständig. Logga in med passkey igen.",
|
||||
"restore_checking": "Kontrollerar session…",
|
||||
"restore_title": "Återställ session",
|
||||
"restore_subtitle": "Du är fortfarande inloggad. Lås upp din loggbok med passkey eller PIN.",
|
||||
"restore_unlocking": "Låser upp…",
|
||||
"restore_with_passkey": "Lås upp med passkey ({{name}})",
|
||||
"restore_with_pin": "Lås upp med PIN",
|
||||
"restore_pin_warning": "Ange din lokala PIN för att låsa upp loggboken efter omladdning.",
|
||||
"restore_other_account": "Logga in med ett annat konto"
|
||||
},
|
||||
"pwa": {
|
||||
"title": "Installera app",
|
||||
@@ -344,6 +353,7 @@
|
||||
"carry_over_tanks_yes": "Ta över",
|
||||
"carry_over_tanks_no": "Börja med 0",
|
||||
"event_title": "Kronologisk händelselogg",
|
||||
"event_creator": "Registrerad av",
|
||||
"no_events": "Inga händelser inlagda för denna resdag ännu.",
|
||||
"event_time": "Tid på dygnet",
|
||||
"event_mgk": "MgK-kurs",
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { ApiError, apiJson } from './api.js'
|
||||
|
||||
const ADMIN_BASE = '/api/admin'
|
||||
|
||||
export interface AdminMe {
|
||||
isAdmin: boolean
|
||||
userId: string
|
||||
}
|
||||
|
||||
export interface AdminSummary {
|
||||
totalUsers: number
|
||||
totalLogbooks: number
|
||||
totalPhotos: number
|
||||
totalVoiceMemos: number
|
||||
totalGpsTracks: number
|
||||
totalCollaborations: number
|
||||
totalInvitations: number
|
||||
aiSummaryEntries: number
|
||||
}
|
||||
|
||||
export type AdminTimeBucket = 'day' | 'week' | 'month'
|
||||
|
||||
export interface AdminTimeSeriesPoint {
|
||||
date: string
|
||||
count: number
|
||||
}
|
||||
|
||||
export interface AdminTimeSeriesMetric {
|
||||
metric: string
|
||||
points: AdminTimeSeriesPoint[]
|
||||
}
|
||||
|
||||
export interface AdminTimeSeriesResponse {
|
||||
bucket: AdminTimeBucket
|
||||
windowDays: number
|
||||
series: AdminTimeSeriesMetric[]
|
||||
}
|
||||
|
||||
export async function fetchAdminMe(): Promise<AdminMe> {
|
||||
return await apiJson<AdminMe>(`${ADMIN_BASE}/me`)
|
||||
}
|
||||
|
||||
/** Returns true only for users listed in server ADMIN_USER_IDS. */
|
||||
export async function checkAdminAccess(): Promise<boolean> {
|
||||
try {
|
||||
await fetchAdminMe()
|
||||
return true
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && (err.status === 401 || err.status === 403)) {
|
||||
return false
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchAdminSummary(): Promise<AdminSummary> {
|
||||
return await apiJson<AdminSummary>(`${ADMIN_BASE}/summary`)
|
||||
}
|
||||
|
||||
export async function fetchAdminTimeSeries(
|
||||
params: { bucket?: AdminTimeBucket; windowDays?: number } = {}
|
||||
): Promise<AdminTimeSeriesResponse> {
|
||||
const search = new URLSearchParams()
|
||||
if (params.bucket) {
|
||||
search.set('bucket', params.bucket)
|
||||
}
|
||||
if (params.windowDays && Number.isFinite(params.windowDays)) {
|
||||
search.set('window', String(params.windowDays))
|
||||
}
|
||||
const query = search.toString()
|
||||
const url = query ? `${ADMIN_BASE}/timeseries?${query}` : `${ADMIN_BASE}/timeseries`
|
||||
return await apiJson<AdminTimeSeriesResponse>(url)
|
||||
}
|
||||
|
||||
@@ -64,6 +64,15 @@ export function persistSessionUserId(userId: string | undefined): void {
|
||||
}
|
||||
}
|
||||
|
||||
/** Username to use when re-unlocking after reload (active account or sole remembered user). */
|
||||
export function resolveRestoreUsername(): string | null {
|
||||
const stored = localStorage.getItem('active_username')
|
||||
if (stored) return stored
|
||||
const known = getKnownUsernames()
|
||||
if (known.length === 1) return known[0]
|
||||
return null
|
||||
}
|
||||
|
||||
export async function reauthWithPasskey(): Promise<boolean> {
|
||||
const options = await apiJson<any>(`${API_BASE}/reauth-options`, {
|
||||
method: 'POST'
|
||||
|
||||
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it } from 'vitest'
|
||||
import {
|
||||
hasUnlockedLocalCrypto,
|
||||
hasUnlockedLocalSession,
|
||||
resolveRestoreUsername,
|
||||
setActiveMasterKey
|
||||
} from './auth.js'
|
||||
|
||||
@@ -33,6 +34,28 @@ describe('local session unlock checks', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveRestoreUsername', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear()
|
||||
})
|
||||
|
||||
it('prefers active_username from storage', () => {
|
||||
localStorage.setItem('active_username', 'captain')
|
||||
localStorage.setItem('daagbox_known_users', JSON.stringify(['other']))
|
||||
expect(resolveRestoreUsername()).toBe('captain')
|
||||
})
|
||||
|
||||
it('falls back to a single remembered user', () => {
|
||||
localStorage.setItem('daagbox_known_users', JSON.stringify(['solo']))
|
||||
expect(resolveRestoreUsername()).toBe('solo')
|
||||
})
|
||||
|
||||
it('returns null when multiple users and no active username', () => {
|
||||
localStorage.setItem('daagbox_known_users', JSON.stringify(['alpha', 'beta']))
|
||||
expect(resolveRestoreUsername()).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('persistSessionUserId', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear()
|
||||
|
||||
@@ -77,7 +77,7 @@ export async function exportLogbookToCsv(logbookId: string, preloadedData?: { ya
|
||||
'Date', 'Day of Travel', 'Departure Port', 'Destination Port', 'AI Summary',
|
||||
'Skipper Signature', 'Crew Signature',
|
||||
'Track Distance (nm)', 'Track Max Speed (kn)', 'Track Avg Speed (kn)', 'Motor Hours (h)',
|
||||
'Event Time', 'MgK Course', 'RwK Course',
|
||||
'Event Time', 'Event Creator', 'MgK Course', 'RwK Course',
|
||||
'Wind Dir', 'Wind Str', 'Barometer (hPa)', 'Sea State', 'Visibility',
|
||||
'Current', 'Heel Angle', 'Sails/Motor', 'Log (nm)', 'Distance (nm)',
|
||||
'Latitude', 'Longitude', 'Remarks',
|
||||
@@ -122,6 +122,7 @@ export async function exportLogbookToCsv(logbookId: string, preloadedData?: { ya
|
||||
const greywaterLevel = entry.greywater?.level ?? '';
|
||||
const aiSummary = entry.aiSummary ?? '';
|
||||
|
||||
const crewSnapshots = (entry.crewSnapshotsById as Record<string, any>) || {};
|
||||
const eventsList = entry.events || [];
|
||||
if (eventsList.length === 0) {
|
||||
// Create one row even if there are no events for the day
|
||||
@@ -129,7 +130,7 @@ export async function exportLogbookToCsv(logbookId: string, preloadedData?: { ya
|
||||
dateVal, travelDay, dep, dest, aiSummary,
|
||||
signS, signC,
|
||||
trackDist, trackMax, trackAvg, motorH,
|
||||
'', '', '',
|
||||
'', '', '', '',
|
||||
'', '', '', '', '',
|
||||
'', '', '', '', '',
|
||||
'', '', '',
|
||||
@@ -142,11 +143,21 @@ export async function exportLogbookToCsv(logbookId: string, preloadedData?: { ya
|
||||
// Sort events chronologically by time
|
||||
const sortedEvents = sortLogEventsByTime(eventsList);
|
||||
for (const ev of sortedEvents) {
|
||||
const creatorSnap = ev.creatorId ? crewSnapshots[ev.creatorId] : null;
|
||||
let creatorName = '';
|
||||
if (creatorSnap) {
|
||||
creatorName = creatorSnap.name || '';
|
||||
} else if (ev.creatorId === 'skipper') {
|
||||
creatorName = 'Skipper';
|
||||
} else if (ev.creatorId) {
|
||||
creatorName = ev.creatorId;
|
||||
}
|
||||
|
||||
rows.push([
|
||||
dateVal, travelDay, dep, dest, aiSummary,
|
||||
signS, signC,
|
||||
trackDist, trackMax, trackAvg, motorH,
|
||||
ev.time || '', ev.mgk || '', ev.rwk || '',
|
||||
ev.time || '', creatorName, ev.mgk || '', ev.rwk || '',
|
||||
ev.windDirection || '', ev.windStrength || '', ev.windPressure || '', ev.seaState || '',
|
||||
ev.visibility || '',
|
||||
ev.current || '', ev.heel || '', ev.sailsOrMotor || '', ev.logReading || '', ev.distance || '',
|
||||
|
||||
@@ -13,12 +13,13 @@ function formatPasskeySignDate(signedAt: string): string {
|
||||
}
|
||||
|
||||
export async function generateLogbookPagePdf(logbookId: string, entryId: string, preloadedData?: { yacht: any; entry: any }): Promise<jsPDF> {
|
||||
let yachtName = '', homePort = '', registration = '', callsign = '', atis = '', mmsi = '';
|
||||
let yachtName = '', owner = '', homePort = '', registration = '', callsign = '', atis = '', mmsi = '';
|
||||
let entry: any = null;
|
||||
|
||||
if (preloadedData) {
|
||||
const yacht = preloadedData.yacht || {};
|
||||
yachtName = yacht.name || '';
|
||||
owner = yacht.owner || '';
|
||||
homePort = yacht.port || '';
|
||||
registration = yacht.registrationNumber || yacht.registration || '';
|
||||
callsign = yacht.callSign || '';
|
||||
@@ -35,6 +36,7 @@ export async function generateLogbookPagePdf(logbookId: string, entryId: string,
|
||||
const yacht = await resolveVesselForLogbook(logbookId)
|
||||
if (yacht) {
|
||||
yachtName = yacht.name || ''
|
||||
owner = yacht.owner || ''
|
||||
homePort = yacht.homePort || ''
|
||||
registration = yacht.registrationNumber || ''
|
||||
callsign = yacht.callSign || ''
|
||||
@@ -74,24 +76,56 @@ export async function generateLogbookPagePdf(logbookId: string, entryId: string,
|
||||
doc.setFontSize(8.5);
|
||||
doc.setFont('Helvetica', 'normal');
|
||||
doc.text(`Yachtname: ${yachtName || '—'}`, 10, 21);
|
||||
doc.text(`Heimathafen: ${homePort || '—'}`, 60, 21);
|
||||
doc.text(`Kennzeichen: ${registration || '—'}`, 110, 21);
|
||||
doc.text(`Rufzeichen: ${callsign || '—'}`, 160, 21);
|
||||
doc.text(`ATIS: ${atis || '—'}`, 210, 21);
|
||||
doc.text(`MMSI: ${mmsi || '—'}`, 250, 21);
|
||||
doc.text(`Eigner: ${owner || '—'}`, 55, 21);
|
||||
doc.text(`Heimathafen: ${homePort || '—'}`, 100, 21);
|
||||
doc.text(`Kennzeichen: ${registration || '—'}`, 145, 21);
|
||||
doc.text(`Rufzeichen: ${callsign || '—'}`, 190, 21);
|
||||
doc.text(`ATIS: ${atis || '—'}`, 230, 21);
|
||||
doc.text(`MMSI: ${mmsi || '—'}`, 260, 21);
|
||||
|
||||
doc.text(`Datum: ${entry.date || '—'}`, 10, 23);
|
||||
doc.text(`Reisetag: ${entry.dayOfTravel || '—'}`, 60, 23);
|
||||
doc.text(`Reise von (Departure): ${entry.departure || '—'}`, 110, 23);
|
||||
doc.text(`nach (Destination): ${entry.destination || '—'}`, 200, 23);
|
||||
doc.text(`Datum: ${entry.date || '—'}`, 10, 24);
|
||||
doc.text(`Reisetag: ${entry.dayOfTravel || '—'}`, 60, 24);
|
||||
doc.text(`Reise von (Departure): ${entry.departure || '—'}`, 110, 24);
|
||||
doc.text(`nach (Destination): ${entry.destination || '—'}`, 200, 24);
|
||||
|
||||
// Format Crew names with initials
|
||||
const crewSnapshots = (entry.crewSnapshotsById as Record<string, any>) || {}
|
||||
const crewList: string[] = []
|
||||
|
||||
if (entry.selectedSkipperId && crewSnapshots[entry.selectedSkipperId]) {
|
||||
const name = crewSnapshots[entry.selectedSkipperId].name || 'Skipper'
|
||||
const initial = name.trim().split(/\s+/)[0]?.charAt(0).toUpperCase() || 'S'
|
||||
crewList.push(`${name} [${initial}] (Skipper)`)
|
||||
} else if (crewSnapshots['skipper']) {
|
||||
const name = crewSnapshots['skipper'].name || 'Skipper'
|
||||
crewList.push(`${name} [S] (Skipper)`)
|
||||
}
|
||||
|
||||
if (Array.isArray(entry.selectedCrewIds)) {
|
||||
for (const crewId of entry.selectedCrewIds) {
|
||||
const snap = crewSnapshots[crewId]
|
||||
if (snap) {
|
||||
const name = snap.name || ''
|
||||
const initial = name.trim().split(/\s+/)[0]?.charAt(0).toUpperCase() || '?'
|
||||
crewList.push(`${name} [${initial}]`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const crewText = crewList.length > 0 ? `Besatzung (Crew): ${crewList.join(', ')}` : ''
|
||||
|
||||
doc.setFont('Helvetica', 'normal');
|
||||
if (entry.trackDistanceNm) {
|
||||
doc.setFont('Helvetica', 'normal');
|
||||
doc.text(
|
||||
`GPS-Track: ${entry.trackDistanceNm} sm · max. ${entry.trackSpeedMaxKn ?? '—'} kn · Ø ${entry.trackSpeedAvgKn ?? '—'} kn`,
|
||||
10,
|
||||
27
|
||||
);
|
||||
if (crewText) {
|
||||
doc.text(crewText, 140, 27);
|
||||
}
|
||||
} else if (crewText) {
|
||||
doc.text(crewText, 10, 27);
|
||||
}
|
||||
|
||||
// Divider line
|
||||
@@ -175,8 +209,28 @@ export async function generateLogbookPagePdf(logbookId: string, entryId: string,
|
||||
doc.text(gps, writeX + 1, y + 4.2);
|
||||
writeX += colWidths[11];
|
||||
|
||||
const crewSnapshots = (entry.crewSnapshotsById as Record<string, any>) || {};
|
||||
let initial = '';
|
||||
if (ev.creatorId) {
|
||||
const snap = crewSnapshots[ev.creatorId];
|
||||
let name = '';
|
||||
if (snap) {
|
||||
name = snap.name || '';
|
||||
} else if (ev.creatorId === 'skipper') {
|
||||
name = 'Skipper';
|
||||
} else {
|
||||
name = ev.creatorId;
|
||||
}
|
||||
if (name) {
|
||||
initial = name.trim().split(/\s+/)[0]?.charAt(0).toUpperCase() || '';
|
||||
}
|
||||
}
|
||||
|
||||
// Clip remarks to fit within the 94mm bounds
|
||||
const remarks = ev.remarks || '';
|
||||
let remarks = ev.remarks || '';
|
||||
if (initial) {
|
||||
remarks = `[${initial}] ${remarks}`;
|
||||
}
|
||||
const maxChars = 65;
|
||||
const clippedRemarks = remarks.length > maxChars ? remarks.substring(0, maxChars) + '...' : remarks;
|
||||
doc.text(clippedRemarks, writeX + 1, y + 4.2);
|
||||
|
||||
@@ -97,6 +97,14 @@ function buildEncryptedPayload(
|
||||
consumption: fuel.consumption ?? 0
|
||||
}
|
||||
|
||||
const entryCrew = data.selectedSkipperId
|
||||
? {
|
||||
selectedSkipperId: String(data.selectedSkipperId),
|
||||
selectedCrewIds: Array.isArray(data.selectedCrewIds) ? data.selectedCrewIds.map(String) : [],
|
||||
crewSnapshotsById: (data.crewSnapshotsById as Record<string, any>) || {}
|
||||
}
|
||||
: undefined
|
||||
|
||||
const payload = buildLogEntryPayload({
|
||||
date: String(data.date || ''),
|
||||
dayOfTravel: String(data.dayOfTravel || ''),
|
||||
@@ -121,7 +129,8 @@ function buildEncryptedPayload(
|
||||
motorHoursRaw != null && motorHoursRaw !== ''
|
||||
? parseFloat(String(motorHoursRaw))
|
||||
: undefined,
|
||||
events: options.events
|
||||
events: options.events,
|
||||
entryCrew
|
||||
})
|
||||
|
||||
const clear = options.clearSignatures
|
||||
|
||||
@@ -22,6 +22,7 @@ export interface LogEventPayload {
|
||||
gpsLat: string
|
||||
gpsLng: string
|
||||
remarks: string
|
||||
creatorId?: string
|
||||
}
|
||||
|
||||
/** Calendar date YYYY-MM-DD in local timezone (matches logbook entry `date` field). */
|
||||
@@ -85,7 +86,7 @@ export function joinTimeHHMM(hours: string, minutes: string): string {
|
||||
const LOG_EVENT_FIELDS: (keyof LogEventPayload)[] = [
|
||||
'time', 'mgk', 'rwk', 'windPressure', 'windDirection', 'windStrength', 'seaState',
|
||||
'visibility', 'weatherIcon', 'current', 'heel', 'sailsOrMotor', 'logReading', 'distance',
|
||||
'gpsLat', 'gpsLng', 'remarks'
|
||||
'gpsLat', 'gpsLng', 'remarks', 'creatorId'
|
||||
]
|
||||
|
||||
/** Normalize partial/legacy events so all fields are strings (safe for form + save). */
|
||||
@@ -109,10 +110,11 @@ export function normalizeLogEvent(event: Partial<LogEventPayload> | Record<strin
|
||||
distance: '',
|
||||
gpsLat: '',
|
||||
gpsLng: '',
|
||||
remarks: ''
|
||||
remarks: '',
|
||||
creatorId: e.creatorId ? String(e.creatorId).trim() : undefined
|
||||
}
|
||||
for (const key of LOG_EVENT_FIELDS) {
|
||||
if (key === 'time' || key === 'mgk' || key === 'rwk' || key === 'windDirection') continue
|
||||
if (key === 'time' || key === 'mgk' || key === 'rwk' || key === 'windDirection' || key === 'creatorId') continue
|
||||
normalized[key] = String(e[key] ?? '').trim()
|
||||
}
|
||||
return normalized
|
||||
@@ -122,7 +124,7 @@ export function logEventsEqual(a: LogEventPayload, b: LogEventPayload): boolean
|
||||
return LOG_EVENT_FIELDS.every((key) => a[key] === b[key])
|
||||
}
|
||||
|
||||
const LOG_EVENT_CONTENT_FIELDS = LOG_EVENT_FIELDS.filter((key) => key !== 'time')
|
||||
const LOG_EVENT_CONTENT_FIELDS = LOG_EVENT_FIELDS.filter((key) => key !== 'time' && key !== 'creatorId')
|
||||
|
||||
/** Draft with only a time (or empty fields) — not an unsaved log entry change. */
|
||||
export function isLogEventDraftEmpty(event: LogEventPayload): boolean {
|
||||
|
||||
@@ -35,6 +35,7 @@ services:
|
||||
OpenRouterAPIKey: ${OpenRouterAPIKey:-}
|
||||
OpenRouterModel: ${OpenRouterModel:-anthropic/claude-3.5-haiku}
|
||||
SESSION_SECRET: ${SESSION_SECRET:-}
|
||||
ADMIN_USER_IDS: ${ADMIN_USER_IDS:-}
|
||||
NTFY_SERVER: ${NTFY_SERVER:-https://ntfy.sh}
|
||||
NTFY_TOPIC: ${NTFY_TOPIC:-}
|
||||
NTFY_TOKEN: ${NTFY_TOKEN:-}
|
||||
|
||||
BIN
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 2.8 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.4 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 621 KiB |
@@ -0,0 +1,318 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>Kapteins Daagbok — Sharepic (Portrait)</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
body {
|
||||
width: 1080px;
|
||||
height: 1920px;
|
||||
font-family: 'Plus Jakarta Sans', sans-serif;
|
||||
color: #e2e8f0;
|
||||
background: #0f172a;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 100px 80px;
|
||||
background:
|
||||
radial-gradient(circle at 50% 10%, rgba(56, 189, 248, 0.18) 0%, transparent 45%),
|
||||
radial-gradient(circle at 50% 90%, rgba(134, 59, 255, 0.22) 0%, transparent 45%),
|
||||
linear-gradient(180deg, #090d16 0%, #111827 50%, #090d16 100%);
|
||||
position: relative;
|
||||
}
|
||||
|
||||
/* Subtle background grid pattern */
|
||||
body::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background-image: linear-gradient(rgba(148, 163, 184, 0.03) 1px, transparent 1px),
|
||||
linear-gradient(90deg, rgba(148, 163, 184, 0.03) 1px, transparent 1px);
|
||||
background-size: 40px 40px;
|
||||
pointer-events: none;
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
/* Outer border */
|
||||
.outer-border {
|
||||
position: absolute;
|
||||
inset: 40px;
|
||||
border: 1px solid rgba(148, 163, 184, 0.1);
|
||||
border-radius: 30px;
|
||||
pointer-events: none;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.brand {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 30px;
|
||||
z-index: 2;
|
||||
text-align: center;
|
||||
margin-top: 40px;
|
||||
}
|
||||
|
||||
.logo {
|
||||
width: 140px;
|
||||
height: 140px;
|
||||
object-fit: contain;
|
||||
filter: drop-shadow(0 8px 24px rgba(56, 189, 248, 0.3));
|
||||
}
|
||||
|
||||
.title-group h1 {
|
||||
font-size: 64px;
|
||||
font-weight: 800;
|
||||
letter-spacing: -0.03em;
|
||||
color: #ffffff;
|
||||
line-height: 1.1;
|
||||
background: linear-gradient(135deg, #ffffff 60%, #94a3b8 100%);
|
||||
-webkit-background-clip: text;
|
||||
background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
}
|
||||
|
||||
.title-group p {
|
||||
font-size: 26px;
|
||||
color: #38bdf8;
|
||||
font-weight: 600;
|
||||
margin-top: 8px;
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
|
||||
.main-content {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 50px;
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
.intro-text {
|
||||
font-size: 26px;
|
||||
line-height: 1.6;
|
||||
color: #cbd5e1;
|
||||
font-weight: 400;
|
||||
text-align: center;
|
||||
padding: 0 20px;
|
||||
}
|
||||
|
||||
.intro-text strong {
|
||||
color: #ffffff;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.features-card {
|
||||
background: rgba(30, 41, 59, 0.45);
|
||||
backdrop-filter: blur(16px);
|
||||
-webkit-backdrop-filter: blur(16px);
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
border-radius: 24px;
|
||||
padding: 50px 60px;
|
||||
box-shadow: 0 30px 60px rgba(0, 0, 0, 0.4);
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.features-card::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border-radius: 24px;
|
||||
padding: 1px;
|
||||
background: linear-gradient(to bottom, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.02));
|
||||
-webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
|
||||
mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
|
||||
-webkit-mask-composite: xor;
|
||||
mask-composite: exclude;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.card-title {
|
||||
font-size: 20px;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.08em;
|
||||
color: #94a3b8;
|
||||
margin-bottom: 35px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.card-title::after {
|
||||
content: "";
|
||||
flex: 1;
|
||||
height: 1px;
|
||||
background: rgba(148, 163, 184, 0.15);
|
||||
}
|
||||
|
||||
.badge-premium {
|
||||
background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%);
|
||||
color: #1e293b;
|
||||
font-size: 16px;
|
||||
font-weight: 800;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.1em;
|
||||
padding: 6px 14px;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.features-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 30px;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.feature-item {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 20px;
|
||||
font-size: 24px;
|
||||
line-height: 1.4;
|
||||
color: #cbd5e1;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.feature-icon {
|
||||
color: #38bdf8;
|
||||
font-size: 26px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin-top: 3px;
|
||||
text-shadow: 0 0 10px rgba(56, 189, 248, 0.6);
|
||||
}
|
||||
|
||||
.bottom-section {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 50px;
|
||||
z-index: 2;
|
||||
margin-bottom: 40px;
|
||||
}
|
||||
|
||||
.cta-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 30px;
|
||||
}
|
||||
|
||||
.cta-badge {
|
||||
background: linear-gradient(135deg, #38bdf8 0%, #0284c7 100%);
|
||||
color: #0f172a;
|
||||
font-size: 32px;
|
||||
font-weight: 800;
|
||||
padding: 20px 45px;
|
||||
border-radius: 16px;
|
||||
letter-spacing: -0.02em;
|
||||
box-shadow: 0 10px 30px rgba(56, 189, 248, 0.25);
|
||||
}
|
||||
|
||||
.qr-code {
|
||||
width: 160px;
|
||||
height: 160px;
|
||||
background: #ffffff;
|
||||
padding: 10px;
|
||||
border-radius: 16px;
|
||||
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.qr-code img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
footer {
|
||||
font-size: 18px;
|
||||
color: #64748b;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
footer strong {
|
||||
color: #94a3b8;
|
||||
font-weight: 600;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="outer-border"></div>
|
||||
|
||||
<div class="brand">
|
||||
<img class="logo" src="../../client/public/logo.png" alt="Kapteins Daagbok" />
|
||||
<div class="title-group">
|
||||
<h1>Kapteins Daagbok</h1>
|
||||
<p>Digitales Yacht-Logbuch</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="main-content">
|
||||
<p class="intro-text">
|
||||
Führe dein Bordlogbuch modern & digital: Reisetage, GPS-Tracks, Crew- und Schiffsdaten —
|
||||
<strong>Ende-zu-Ende-verschlüsselt</strong>, als App installierbar und <strong>auch offline</strong> auf See nutzbar.
|
||||
</p>
|
||||
|
||||
<div class="features-card">
|
||||
<div class="card-title">Top Features <span class="badge-premium">Kostenlos & Werbefrei</span></div>
|
||||
<ul class="features-list">
|
||||
<li class="feature-item">
|
||||
<span class="feature-icon">✦</span>
|
||||
<span>Nautisches Logbuch-Format & Streckenstatistik</span>
|
||||
</li>
|
||||
<li class="feature-item">
|
||||
<span class="feature-icon">✦</span>
|
||||
<span>Offline-first PWA — läuft auf allen Smartphones & Tablets</span>
|
||||
</li>
|
||||
<li class="feature-item">
|
||||
<span class="feature-icon">✦</span>
|
||||
<span>Ende-zu-Ende Verschlüsselung (Zero-Knowledge)</span>
|
||||
</li>
|
||||
<li class="feature-item">
|
||||
<span class="feature-icon">✦</span>
|
||||
<span>Einfache passwortlose Passkey-Anmeldung</span>
|
||||
</li>
|
||||
<li class="feature-item">
|
||||
<span class="feature-icon">✦</span>
|
||||
<span>GPS-Track-Upload & automatische NMEA-Erfassung</span>
|
||||
</li>
|
||||
<li class="feature-item">
|
||||
<span class="feature-icon">✦</span>
|
||||
<span>Crew-Einladung zur gemeinsamen Logbuch-Arbeit</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="bottom-section">
|
||||
<div class="cta-container">
|
||||
<div class="cta-badge">
|
||||
kapteins-daagbok.eu
|
||||
</div>
|
||||
<div class="qr-code">
|
||||
<img src="assets/qr-kapteins-daagbok.eu.png" alt="QR Code" />
|
||||
</div>
|
||||
</div>
|
||||
<footer>
|
||||
<strong>Kapteins Daagbok</strong> ist ein werbefreies, privates Hobbyprojekt.
|
||||
</footer>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,320 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>Kapteins Daagbok — Sharepic</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
body {
|
||||
width: 1200px;
|
||||
height: 630px;
|
||||
font-family: 'Plus Jakarta Sans', sans-serif;
|
||||
color: #e2e8f0;
|
||||
background: #0f172a;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: space-between;
|
||||
padding: 60px 80px;
|
||||
background:
|
||||
radial-gradient(circle at 90% 10%, rgba(56, 189, 248, 0.15) 0%, transparent 45%),
|
||||
radial-gradient(circle at 10% 90%, rgba(134, 59, 255, 0.18) 0%, transparent 45%),
|
||||
linear-gradient(165deg, #090d16 0%, #111827 50%, #090d16 100%);
|
||||
position: relative;
|
||||
}
|
||||
|
||||
/* Subtle background grid pattern */
|
||||
body::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background-image: linear-gradient(rgba(148, 163, 184, 0.03) 1px, transparent 1px),
|
||||
linear-gradient(90deg, rgba(148, 163, 184, 0.03) 1px, transparent 1px);
|
||||
background-size: 40px 40px;
|
||||
pointer-events: none;
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
/* Outer border */
|
||||
.outer-border {
|
||||
position: absolute;
|
||||
inset: 30px;
|
||||
border: 1px solid rgba(148, 163, 184, 0.1);
|
||||
border-radius: 20px;
|
||||
pointer-events: none;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.content-wrapper {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
z-index: 2;
|
||||
position: relative;
|
||||
gap: 50px;
|
||||
}
|
||||
|
||||
.left-col {
|
||||
flex: 1.1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
gap: 30px;
|
||||
}
|
||||
|
||||
.brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.logo {
|
||||
width: 80px;
|
||||
height: 80px;
|
||||
object-fit: contain;
|
||||
filter: drop-shadow(0 4px 12px rgba(56, 189, 248, 0.3));
|
||||
}
|
||||
|
||||
.title-group h1 {
|
||||
font-size: 44px;
|
||||
font-weight: 800;
|
||||
letter-spacing: -0.03em;
|
||||
color: #ffffff;
|
||||
line-height: 1.1;
|
||||
background: linear-gradient(135deg, #ffffff 60%, #94a3b8 100%);
|
||||
-webkit-background-clip: text;
|
||||
background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
}
|
||||
|
||||
.title-group p {
|
||||
font-size: 18px;
|
||||
color: #38bdf8;
|
||||
font-weight: 600;
|
||||
margin-top: 4px;
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
|
||||
.intro-text {
|
||||
font-size: 20px;
|
||||
line-height: 1.6;
|
||||
color: #cbd5e1;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.intro-text strong {
|
||||
color: #ffffff;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.cta-container {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.cta-badge {
|
||||
background: linear-gradient(135deg, #38bdf8 0%, #0284c7 100%);
|
||||
color: #0f172a;
|
||||
font-size: 22px;
|
||||
font-weight: 800;
|
||||
padding: 14px 28px;
|
||||
border-radius: 12px;
|
||||
letter-spacing: -0.02em;
|
||||
box-shadow: 0 4px 20px rgba(56, 189, 248, 0.25);
|
||||
}
|
||||
|
||||
.qr-code {
|
||||
width: 60px;
|
||||
height: 60px;
|
||||
background: #ffffff;
|
||||
padding: 4px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.qr-code img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.right-col {
|
||||
flex: 0.9;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.features-card {
|
||||
background: rgba(30, 41, 59, 0.45);
|
||||
backdrop-filter: blur(16px);
|
||||
-webkit-backdrop-filter: blur(16px);
|
||||
border: 1px solid rgba(255, 255, 255, 0.08);
|
||||
border-radius: 20px;
|
||||
padding: 35px;
|
||||
box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.features-card::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border-radius: 20px;
|
||||
padding: 1px;
|
||||
background: linear-gradient(to bottom, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.02));
|
||||
-webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
|
||||
mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
|
||||
-webkit-mask-composite: xor;
|
||||
mask-composite: exclude;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.features-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.feature-item {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 14px;
|
||||
font-size: 16px;
|
||||
line-height: 1.4;
|
||||
color: #cbd5e1;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.feature-icon {
|
||||
color: #38bdf8;
|
||||
font-size: 18px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin-top: 2px;
|
||||
text-shadow: 0 0 8px rgba(56, 189, 248, 0.6);
|
||||
}
|
||||
|
||||
.badge-premium {
|
||||
background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%);
|
||||
color: #1e293b;
|
||||
font-size: 12px;
|
||||
font-weight: 800;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.1em;
|
||||
padding: 4px 10px;
|
||||
border-radius: 6px;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.card-title {
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.08em;
|
||||
color: #94a3b8;
|
||||
margin-bottom: 20px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.card-title::after {
|
||||
content: "";
|
||||
flex: 1;
|
||||
height: 1px;
|
||||
background: rgba(148, 163, 184, 0.15);
|
||||
}
|
||||
|
||||
footer {
|
||||
position: absolute;
|
||||
bottom: 45px;
|
||||
left: 80px;
|
||||
font-size: 12px;
|
||||
color: #64748b;
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
footer strong {
|
||||
color: #94a3b8;
|
||||
font-weight: 600;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="outer-border"></div>
|
||||
<div class="content-wrapper">
|
||||
<div class="left-col">
|
||||
<div class="brand">
|
||||
<img class="logo" src="../../client/public/logo.png" alt="Kapteins Daagbok" />
|
||||
<div class="title-group">
|
||||
<h1>Kapteins Daagbok</h1>
|
||||
<p>Digitales Yacht-Logbuch</p>
|
||||
</div>
|
||||
</div>
|
||||
<p class="intro-text">
|
||||
Führe dein Bordlogbuch modern & digital: Reisetage, GPS-Tracks, Crew- und Schiffsdaten —
|
||||
<strong>Ende-zu-Ende-verschlüsselt</strong>, als App installierbar und <strong>auch offline</strong> auf See nutzbar.
|
||||
</p>
|
||||
<div class="cta-container">
|
||||
<div class="cta-badge">
|
||||
kapteins-daagbok.eu
|
||||
</div>
|
||||
<div class="qr-code">
|
||||
<img src="assets/qr-kapteins-daagbok.eu.png" alt="QR Code" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="right-col">
|
||||
<div class="features-card">
|
||||
<div class="card-title">Top Features <span class="badge-premium">Kostenlos & Werbefrei</span></div>
|
||||
<ul class="features-list">
|
||||
<li class="feature-item">
|
||||
<span class="feature-icon">✦</span>
|
||||
<span>Nautisches Logbuch-Format & Streckenstatistik</span>
|
||||
</li>
|
||||
<li class="feature-item">
|
||||
<span class="feature-icon">✦</span>
|
||||
<span>Offline-first PWA — läuft auf allen Smartphones & Tablets</span>
|
||||
</li>
|
||||
<li class="feature-item">
|
||||
<span class="feature-icon">✦</span>
|
||||
<span>Ende-zu-Ende Verschlüsselung (Zero-Knowledge)</span>
|
||||
</li>
|
||||
<li class="feature-item">
|
||||
<span class="feature-icon">✦</span>
|
||||
<span>Einfache passwortlose Passkey-Anmeldung</span>
|
||||
</li>
|
||||
<li class="feature-item">
|
||||
<span class="feature-icon">✦</span>
|
||||
<span>GPS-Track-Upload & automatische NMEA-Erfassung</span>
|
||||
</li>
|
||||
<li class="feature-item">
|
||||
<span class="feature-icon">✦</span>
|
||||
<span>Crew-Einladung zur gemeinsamen Logbuch-Arbeit</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<footer>
|
||||
<strong>Kapteins Daagbok</strong> ist ein werbefreies, privates Hobbyprojekt.
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
Executable
+95
@@ -0,0 +1,95 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Generates the sharepic PNGs (landscape & portrait) from HTML files
|
||||
*
|
||||
* Usage:
|
||||
* node scripts/generate-sharepic.mjs
|
||||
*/
|
||||
|
||||
import { execSync } from 'node:child_process'
|
||||
import { dirname, resolve } from 'node:path'
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url'
|
||||
import { createRequire } from 'node:module'
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url))
|
||||
const repoRoot = resolve(__dirname, '..')
|
||||
const clientDir = resolve(repoRoot, 'client')
|
||||
const marketingDir = resolve(repoRoot, 'docs/marketing')
|
||||
|
||||
const require = createRequire(resolve(clientDir, 'package.json'))
|
||||
|
||||
function isMissingBrowserError(err) {
|
||||
const msg = err instanceof Error ? err.message : String(err)
|
||||
return msg.includes("Executable doesn't exist") || msg.includes('browserType.launch')
|
||||
}
|
||||
|
||||
async function ensurePlaywrightChromium(playwright) {
|
||||
try {
|
||||
const browser = await playwright.chromium.launch({ headless: true })
|
||||
await browser.close()
|
||||
return
|
||||
} catch (err) {
|
||||
if (!isMissingBrowserError(err)) throw err
|
||||
}
|
||||
|
||||
console.log('Playwright Chromium fehlt — installiere Browser (einmalig)…')
|
||||
execSync('npx playwright install chromium', {
|
||||
cwd: clientDir,
|
||||
stdio: 'inherit'
|
||||
})
|
||||
}
|
||||
|
||||
function loadPlaywright() {
|
||||
try {
|
||||
return require('playwright')
|
||||
} catch {
|
||||
console.error('Fehlende Abhängigkeit: "npm install -D playwright" in client/ ausführen.')
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
async function renderSharepic(browser, htmlName, pngName, width, height) {
|
||||
const htmlPath = resolve(marketingDir, htmlName)
|
||||
const pngPath = resolve(marketingDir, pngName)
|
||||
|
||||
console.log(`Generating sharepic (${width}x${height}) from ${htmlName}...`)
|
||||
|
||||
const context = await browser.newContext({
|
||||
viewport: { width, height },
|
||||
deviceScaleFactor: 2 // High-DPI for crisp text
|
||||
})
|
||||
const page = await context.newPage()
|
||||
|
||||
try {
|
||||
await page.goto(pathToFileURL(htmlPath).href, { waitUntil: 'networkidle' })
|
||||
await page.screenshot({
|
||||
path: pngPath,
|
||||
type: 'png'
|
||||
})
|
||||
console.log('Successfully wrote:', pngPath)
|
||||
} finally {
|
||||
await page.close()
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const playwright = loadPlaywright()
|
||||
await ensurePlaywrightChromium(playwright)
|
||||
|
||||
const browser = await playwright.chromium.launch({ headless: true })
|
||||
|
||||
try {
|
||||
// Landscape 1200x630
|
||||
await renderSharepic(browser, 'sharepic.html', 'kapteins-daagbok-sharepic.png', 1200, 630)
|
||||
|
||||
// Portrait 1080x1920
|
||||
await renderSharepic(browser, 'sharepic-portrait.html', 'kapteins-daagbok-sharepic-portrait.png', 1080, 1920)
|
||||
} finally {
|
||||
await browser.close()
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error('Error generating sharepics:', err)
|
||||
process.exit(1)
|
||||
})
|
||||
@@ -0,0 +1,25 @@
|
||||
const ADMIN_ENV_KEY = 'ADMIN_USER_IDS'
|
||||
|
||||
export function getAdminUserIds(): Set<string> {
|
||||
const raw = process.env[ADMIN_ENV_KEY]
|
||||
if (!raw) {
|
||||
return new Set()
|
||||
}
|
||||
|
||||
const ids = raw
|
||||
.split(',')
|
||||
.map((id) => id.trim())
|
||||
.filter((id) => id.length > 0)
|
||||
|
||||
if (ids.length === 0) {
|
||||
return new Set()
|
||||
}
|
||||
|
||||
return new Set(ids)
|
||||
}
|
||||
|
||||
export function isAdminUserId(userId: string): boolean {
|
||||
const adminIds = getAdminUserIds()
|
||||
return adminIds.has(userId)
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import pushRouter from './routes/push.js'
|
||||
import weatherRouter from './routes/weather.js'
|
||||
import aiRouter from './routes/ai.js'
|
||||
import feedbackRouter from './routes/feedback.js'
|
||||
import adminRouter from './routes/admin.js'
|
||||
import { prisma } from './db.js'
|
||||
import { buildCorsOptions } from './cors.js'
|
||||
|
||||
@@ -121,6 +122,7 @@ export function createApp(): express.Express {
|
||||
app.use('/api/weather', weatherRouter)
|
||||
app.use('/api/ai', aiRouter)
|
||||
app.use('/api/feedback', feedbackRouter)
|
||||
app.use('/api/admin', adminRouter)
|
||||
|
||||
app.get('/api/health', async (_req, res) => {
|
||||
try {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { Request, Response, NextFunction } from 'express'
|
||||
import { hasValidReauth, readSessionFromRequest } from '../session.js'
|
||||
import { isAdminUserId } from '../adminConfig.js'
|
||||
|
||||
export interface AuthedRequest extends Request {
|
||||
userId: string
|
||||
@@ -31,3 +32,21 @@ export function requireReauth(req: Request, res: Response, next: NextFunction):
|
||||
;(req as AuthedRequest).session = session
|
||||
next()
|
||||
}
|
||||
|
||||
export function requireAdmin(req: Request, res: Response, next: NextFunction): void {
|
||||
const session = readSessionFromRequest(req)
|
||||
if (!session) {
|
||||
res.status(401).json({ error: 'Unauthorized: valid session required' })
|
||||
return
|
||||
}
|
||||
|
||||
if (!isAdminUserId(session.userId)) {
|
||||
res.status(403).json({ error: 'Forbidden: admin access required' })
|
||||
return
|
||||
}
|
||||
|
||||
;(req as AuthedRequest).userId = session.userId
|
||||
;(req as AuthedRequest).session = session
|
||||
next()
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
import { Router } from 'express'
|
||||
import { prisma } from '../db.js'
|
||||
import { requireUser, requireAdmin, type AuthedRequest } from '../middleware/auth.js'
|
||||
|
||||
const router = Router()
|
||||
|
||||
router.get('/me', requireUser, requireAdmin, (req, res) => {
|
||||
const { userId } = req as AuthedRequest
|
||||
res.json({ isAdmin: true, userId })
|
||||
})
|
||||
|
||||
router.get('/summary', requireUser, requireAdmin, async (_req, res) => {
|
||||
try {
|
||||
const [totalUsers, totalLogbooks, totalPhotos, totalVoiceMemos, totalGpsTracks, totalCollaborations, totalInvitations, aiSummaryEntries] =
|
||||
await Promise.all([
|
||||
prisma.user.count(),
|
||||
prisma.logbook.count(),
|
||||
prisma.photoPayload.count(),
|
||||
prisma.voiceMemoPayload.count(),
|
||||
prisma.gpsTrackPayload.count(),
|
||||
prisma.collaboration.count(),
|
||||
prisma.invitation.count(),
|
||||
prisma.aiSummaryUsage.count()
|
||||
])
|
||||
|
||||
res.json({
|
||||
totalUsers,
|
||||
totalLogbooks,
|
||||
totalPhotos,
|
||||
totalVoiceMemos,
|
||||
totalGpsTracks,
|
||||
totalCollaborations,
|
||||
totalInvitations,
|
||||
aiSummaryEntries
|
||||
})
|
||||
} catch (error: unknown) {
|
||||
console.error('admin/summary error', error)
|
||||
res.status(500).json({ error: 'Failed to load admin summary' })
|
||||
}
|
||||
})
|
||||
|
||||
type TimeBucket = 'day' | 'week' | 'month'
|
||||
|
||||
interface TimeSeriesPoint {
|
||||
date: string
|
||||
count: number
|
||||
}
|
||||
|
||||
interface TimeSeries {
|
||||
metric: string
|
||||
points: TimeSeriesPoint[]
|
||||
}
|
||||
|
||||
function normalizeBucket(value: string | undefined | null): TimeBucket {
|
||||
if (value === 'week' || value === 'month') return value
|
||||
return 'day'
|
||||
}
|
||||
|
||||
function parseWindowDays(raw: string | undefined | null): number {
|
||||
const n = raw ? Number.parseInt(raw, 10) : NaN
|
||||
if (!Number.isFinite(n) || n <= 0) return 90
|
||||
return Math.min(n, 365)
|
||||
}
|
||||
|
||||
function startOfDay(date: Date): Date {
|
||||
const d = new Date(date)
|
||||
d.setUTCHours(0, 0, 0, 0)
|
||||
return d
|
||||
}
|
||||
|
||||
function startOfWeek(date: Date): Date {
|
||||
const d = startOfDay(date)
|
||||
const day = d.getUTCDay() || 7
|
||||
d.setUTCDate(d.getUTCDate() - (day - 1))
|
||||
return d
|
||||
}
|
||||
|
||||
function startOfMonth(date: Date): Date {
|
||||
const d = startOfDay(date)
|
||||
d.setUTCDate(1)
|
||||
return d
|
||||
}
|
||||
|
||||
function bucketDate(date: Date, bucket: TimeBucket): string {
|
||||
const base =
|
||||
bucket === 'week' ? startOfWeek(date) : bucket === 'month' ? startOfMonth(date) : startOfDay(date)
|
||||
return base.toISOString().slice(0, 10)
|
||||
}
|
||||
|
||||
async function buildTimeSeries(bucket: TimeBucket, windowDays: number): Promise<TimeSeries[]> {
|
||||
const since = new Date()
|
||||
since.setUTCDate(since.getUTCDate() - windowDays)
|
||||
|
||||
const [users, logbooks, photos] = await Promise.all([
|
||||
prisma.user.findMany({
|
||||
where: { createdAt: { gte: since } },
|
||||
select: { createdAt: true }
|
||||
}),
|
||||
prisma.logbook.findMany({
|
||||
where: { createdAt: { gte: since } },
|
||||
select: { createdAt: true }
|
||||
}),
|
||||
prisma.photoPayload.findMany({
|
||||
where: { updatedAt: { gte: since } },
|
||||
select: { updatedAt: true }
|
||||
})
|
||||
])
|
||||
|
||||
function aggregate(dates: Date[], metric: string): TimeSeries {
|
||||
const map = new Map<string, number>()
|
||||
for (const d of dates) {
|
||||
const key = bucketDate(d, bucket)
|
||||
map.set(key, (map.get(key) ?? 0) + 1)
|
||||
}
|
||||
const points = Array.from(map.entries())
|
||||
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
|
||||
.map(([date, count]) => ({ date, count }))
|
||||
return { metric, points }
|
||||
}
|
||||
|
||||
return [
|
||||
aggregate(
|
||||
users.map((u) => u.createdAt),
|
||||
'users_created'
|
||||
),
|
||||
aggregate(
|
||||
logbooks.map((l) => l.createdAt),
|
||||
'logbooks_created'
|
||||
),
|
||||
aggregate(
|
||||
photos.map((p) => p.updatedAt),
|
||||
'photos_updated'
|
||||
)
|
||||
]
|
||||
}
|
||||
|
||||
router.get('/timeseries', requireUser, requireAdmin, async (req, res) => {
|
||||
try {
|
||||
const bucket = normalizeBucket(typeof req.query.bucket === 'string' ? req.query.bucket : undefined)
|
||||
const windowDays = parseWindowDays(typeof req.query.window === 'string' ? req.query.window : undefined)
|
||||
|
||||
const series = await buildTimeSeries(bucket, windowDays)
|
||||
res.json({ bucket, windowDays, series })
|
||||
} catch (error: unknown) {
|
||||
console.error('admin/timeseries error', error)
|
||||
res.status(500).json({ error: 'Failed to load admin time series' })
|
||||
}
|
||||
})
|
||||
|
||||
export default router
|
||||
|
||||
Reference in New Issue
Block a user