feat(vessel): Schiffsflotte im Profil und Logbuch-Auswahl
Benutzerweiter Vessel-Pool (E2E, Sync, Migration von Legacy-Yachts) mit LogbookVesselSelection und LogbookVesselPicker. Profil mit Accordion (Flotte & Crew); Demo und Onboarding-Tour inkl. profile_vessel_pool. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -1270,6 +1270,70 @@ html.scheme-dark .themed-select-option.is-selected {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.profile-accordion {
|
||||
margin-bottom: 12px;
|
||||
border: 1px solid var(--app-border-muted);
|
||||
border-radius: var(--app-radius-card);
|
||||
background: var(--app-surface);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.profile-accordion__summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 14px 16px;
|
||||
cursor: pointer;
|
||||
list-style: none;
|
||||
font-weight: 600;
|
||||
color: var(--app-text-heading);
|
||||
}
|
||||
|
||||
.profile-accordion__summary::-webkit-details-marker {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.profile-accordion__title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.profile-accordion__chevron {
|
||||
flex-shrink: 0;
|
||||
transition: transform 0.2s ease;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.profile-accordion[open] .profile-accordion__chevron {
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
|
||||
.profile-accordion__body {
|
||||
padding: 0 16px 16px;
|
||||
border-top: 1px solid var(--app-border-muted);
|
||||
}
|
||||
|
||||
.profile-accordion-inner-card {
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.profile-accordion-inner-card.form-card,
|
||||
.profile-accordion-inner-card.member-editor-card {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.btn-link {
|
||||
background: none;
|
||||
border: none;
|
||||
padding: 0;
|
||||
color: var(--app-accent, #f59e0b);
|
||||
text-decoration: underline;
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.profile-section-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
+10
-2
@@ -3,9 +3,11 @@ import { DialogProvider } from './components/ModalDialog.tsx'
|
||||
import AuthOnboarding from './components/AuthOnboarding.tsx'
|
||||
import UserProfilePage from './components/UserProfilePage.tsx'
|
||||
import LogbookDashboard from './components/LogbookDashboard.tsx'
|
||||
import VesselForm from './components/VesselForm.tsx'
|
||||
import LogbookVesselPicker from './components/LogbookVesselPicker.tsx'
|
||||
import LogbookCrewPicker from './components/LogbookCrewPicker.tsx'
|
||||
import { migrateLegacyCrewToPoolIfNeeded } from './services/crewMigration.js'
|
||||
import { migrateLegacyYachtsToPoolIfNeeded } from './services/vesselMigration.js'
|
||||
import { syncVesselPool } from './services/vesselPoolSync.js'
|
||||
import { syncPersonPool } from './services/personPoolSync.js'
|
||||
// Compass Deviation Table — für Freizeit-Skipper vorerst deaktiviert (Komponente bleibt erhalten)
|
||||
// import DeviationForm from './components/DeviationForm.tsx'
|
||||
@@ -164,6 +166,7 @@ function App() {
|
||||
if (!userId) return
|
||||
void syncAppearancePrefs(userId)
|
||||
void migrateLegacyCrewToPoolIfNeeded().then(() => syncPersonPool())
|
||||
void migrateLegacyYachtsToPoolIfNeeded().then(() => syncVesselPool())
|
||||
}, [isAuthenticated])
|
||||
|
||||
useEffect(() => {
|
||||
@@ -751,7 +754,12 @@ function App() {
|
||||
)}
|
||||
|
||||
{activeTab === 'vessel' && (
|
||||
<VesselForm logbookId={activeLogbookId} readOnly={logbookReadOnly || !isLogbookOwner} />
|
||||
<LogbookVesselPicker
|
||||
logbookId={activeLogbookId}
|
||||
readOnly={logbookReadOnly || !isLogbookOwner}
|
||||
selectionOnly={!isLogbookOwner && activeLogbookRecord?.isShared === 1}
|
||||
onOpenProfile={isLogbookOwner ? () => setShowUserProfile(true) : undefined}
|
||||
/>
|
||||
)}
|
||||
|
||||
{activeTab === 'crew' && (
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { cycleAppLanguage, getNextLanguage } from '../utils/i18nLanguages.js'
|
||||
import VesselForm from './VesselForm.tsx'
|
||||
import LogbookVesselPicker from './LogbookVesselPicker.tsx'
|
||||
import LogbookCrewPicker from './LogbookCrewPicker.tsx'
|
||||
import type { LogbookCrewSelectionData } from '../types/person.js'
|
||||
import { personToSnapshot } from '../utils/personSnapshots.js'
|
||||
import LogEntriesList from './LogEntriesList.tsx'
|
||||
import { Ship, Users, FileText, Lock, Globe, ChevronLeft, UserPlus } from 'lucide-react'
|
||||
import { buildPublicDemoFixture, type PublicDemoFixture } from '../services/demoLogbookData.js'
|
||||
import type { VesselData } from '../types/vessel.js'
|
||||
import type { LogbookVesselSelectionData } from '../types/vessel.js'
|
||||
import { useAppTour, type AppTab } from '../context/AppTourContext.tsx'
|
||||
import { PlausibleEvents, trackPlausibleEvent } from '../services/analytics.js'
|
||||
|
||||
@@ -54,8 +56,18 @@ export default function DemoViewer({ onExit }: DemoViewerProps) {
|
||||
cycleAppLanguage(i18n)
|
||||
}
|
||||
|
||||
const { title, yacht, personPool, logbookCrewSelection, entries, gpsTracks, photos, firstEntryId } =
|
||||
fixture
|
||||
const {
|
||||
title,
|
||||
yacht,
|
||||
vesselPool,
|
||||
logbookVesselSelection,
|
||||
personPool,
|
||||
logbookCrewSelection,
|
||||
entries,
|
||||
gpsTracks,
|
||||
photos,
|
||||
firstEntryId
|
||||
} = fixture
|
||||
|
||||
const demoSelection: LogbookCrewSelectionData = {
|
||||
activeSkipperId: logbookCrewSelection.activeSkipperId,
|
||||
@@ -152,7 +164,15 @@ export default function DemoViewer({ onExit }: DemoViewerProps) {
|
||||
)}
|
||||
|
||||
{activeTab === 'vessel' && (
|
||||
<VesselForm logbookId="demo" readOnly={true} preloadedData={yacht} />
|
||||
<LogbookVesselPicker
|
||||
logbookId="demo"
|
||||
readOnly={true}
|
||||
preloadedPool={vesselPool.map((v) => ({
|
||||
payloadId: v.payloadId,
|
||||
data: v.data as VesselData
|
||||
}))}
|
||||
preloadedSelection={logbookVesselSelection as LogbookVesselSelectionData}
|
||||
/>
|
||||
)}
|
||||
|
||||
{activeTab === 'crew' && (
|
||||
|
||||
@@ -20,9 +20,6 @@ import {
|
||||
Undo2,
|
||||
Zap
|
||||
} from 'lucide-react'
|
||||
import { db } from '../services/db.js'
|
||||
import { getLogbookKey } from '../services/logbookKeys.js'
|
||||
import { decryptJson } from '../services/crypto.js'
|
||||
import { PlausibleEvents, trackPlausibleEvent } from '../services/analytics.js'
|
||||
import {
|
||||
appendQuickEvent,
|
||||
@@ -243,24 +240,14 @@ export default function LiveLogView({
|
||||
if (seq !== initSeqRef.current) return
|
||||
setEntryId(id)
|
||||
|
||||
const logbookKey = await getLogbookKey(logbookId)
|
||||
if (logbookKey) {
|
||||
const yacht = await db.yachts.get(logbookId)
|
||||
if (yacht) {
|
||||
try {
|
||||
const decrypted = await decryptJson(
|
||||
yacht.encryptedData,
|
||||
yacht.iv,
|
||||
yacht.tag,
|
||||
logbookKey
|
||||
)
|
||||
if (decrypted?.sails && Array.isArray(decrypted.sails)) {
|
||||
setYachtSails(decrypted.sails as string[])
|
||||
}
|
||||
} catch {
|
||||
// Yacht profile optional for live log
|
||||
}
|
||||
try {
|
||||
const { resolveVesselForLogbook } = await import('../services/resolveVessel.js')
|
||||
const vessel = await resolveVesselForLogbook(logbookId)
|
||||
if (vessel?.sails && Array.isArray(vessel.sails)) {
|
||||
setYachtSails(vessel.sails)
|
||||
}
|
||||
} catch {
|
||||
// Vessel profile optional for live log
|
||||
}
|
||||
|
||||
const loaded = await loadEntry(logbookId, id)
|
||||
|
||||
@@ -649,33 +649,25 @@ export default function LogEntryEditor({
|
||||
}
|
||||
}, [fuelEveningMax, fuelEvening])
|
||||
|
||||
// Load yacht sails and tank capacities
|
||||
// Load vessel sails and tank capacities
|
||||
useEffect(() => {
|
||||
async function loadYachtMeta() {
|
||||
if (readOnly && preloadedYacht) {
|
||||
if (preloadedYacht.sails) setYachtSails(preloadedYacht.sails)
|
||||
setTankCapacities(extractTankCapacitiesFromYacht(preloadedYacht))
|
||||
return
|
||||
}
|
||||
try {
|
||||
const masterKey = await getLogbookKey(logbookId) || getActiveMasterKey()
|
||||
if (!masterKey) return
|
||||
|
||||
const yacht = await db.yachts.get(logbookId)
|
||||
if (yacht) {
|
||||
const decrypted = await decryptJson(yacht.encryptedData, yacht.iv, yacht.tag, masterKey)
|
||||
if (decrypted) {
|
||||
if (decrypted.sails && Array.isArray(decrypted.sails)) {
|
||||
setYachtSails(decrypted.sails)
|
||||
}
|
||||
setTankCapacities(extractTankCapacitiesFromYacht(decrypted))
|
||||
}
|
||||
const { resolveVesselForLogbook } = await import('../services/resolveVessel.js')
|
||||
const vessel =
|
||||
readOnly && preloadedYacht
|
||||
? (preloadedYacht as Record<string, unknown>)
|
||||
: await resolveVesselForLogbook(logbookId, { preloadedYacht: preloadedYacht ?? undefined })
|
||||
if (!vessel) return
|
||||
if (vessel.sails && Array.isArray(vessel.sails)) {
|
||||
setYachtSails(vessel.sails)
|
||||
}
|
||||
setTankCapacities(extractTankCapacitiesFromYacht(vessel))
|
||||
} catch (err) {
|
||||
console.error('Failed to load yacht meta in editor:', err)
|
||||
console.error('Failed to load vessel meta in editor:', err)
|
||||
}
|
||||
}
|
||||
loadYachtMeta()
|
||||
void loadYachtMeta()
|
||||
}, [logbookId, preloadedYacht, readOnly])
|
||||
|
||||
// Load entry details
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Ship, Save, Check } from 'lucide-react'
|
||||
import type { LogbookVesselSelectionData, VesselData } from '../types/vessel.js'
|
||||
import type { DecryptedVessel } from '../services/vesselPool.js'
|
||||
import { loadVesselPool } from '../services/vesselPool.js'
|
||||
import { loadLogbookVesselSelection, saveLogbookVesselSelectionFromId } from '../services/logbookVesselSelection.js'
|
||||
import { resolveVesselForLogbook } from '../services/resolveVessel.js'
|
||||
import { vesselDataFromSnapshot } from '../utils/vesselSnapshot.js'
|
||||
import { PlausibleEvents, trackPlausibleEvent } from '../services/analytics.js'
|
||||
|
||||
export interface LogbookVesselPickerProps {
|
||||
logbookId: string
|
||||
readOnly?: boolean
|
||||
preloadedPool?: Array<{ payloadId: string; data: VesselData }>
|
||||
preloadedSelection?: LogbookVesselSelectionData
|
||||
selectionOnly?: boolean
|
||||
onOpenProfile?: () => void
|
||||
}
|
||||
|
||||
export default function LogbookVesselPicker({
|
||||
logbookId,
|
||||
readOnly = false,
|
||||
preloadedPool,
|
||||
preloadedSelection,
|
||||
selectionOnly = false,
|
||||
onOpenProfile
|
||||
}: LogbookVesselPickerProps) {
|
||||
const { t } = useTranslation()
|
||||
const [loading, setLoading] = useState(!preloadedSelection)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [saved, setSaved] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [pool, setPool] = useState<DecryptedVessel[]>([])
|
||||
const [activeVesselId, setActiveVesselId] = useState<string | null>(null)
|
||||
const [resolvedVessel, setResolvedVessel] = useState<VesselData | null>(null)
|
||||
|
||||
const loadData = useCallback(async () => {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
try {
|
||||
const selection =
|
||||
preloadedSelection ??
|
||||
(logbookId === 'demo' ? null : await loadLogbookVesselSelection(logbookId))
|
||||
|
||||
if (selection) {
|
||||
setActiveVesselId(selection.activeVesselId)
|
||||
}
|
||||
|
||||
if (preloadedPool) {
|
||||
setPool(preloadedPool.map((p) => ({ payloadId: p.payloadId, data: p.data })))
|
||||
} else if (selectionOnly && selection?.vesselSnapshot) {
|
||||
const data = vesselDataFromSnapshot(selection.vesselSnapshot)
|
||||
if (data) {
|
||||
setPool([{ payloadId: selection.vesselSnapshot.id, data }])
|
||||
}
|
||||
} else {
|
||||
setPool(await loadVesselPool())
|
||||
}
|
||||
|
||||
const vessel = await resolveVesselForLogbook(logbookId, {
|
||||
preloadedSelection: selection ?? undefined
|
||||
})
|
||||
setResolvedVessel(vessel)
|
||||
} catch (err: unknown) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to load vessel selection')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [logbookId, preloadedPool, preloadedSelection, selectionOnly])
|
||||
|
||||
useEffect(() => {
|
||||
void loadData()
|
||||
}, [loadData])
|
||||
|
||||
const handleSave = async () => {
|
||||
if (readOnly || logbookId === 'demo') return
|
||||
setSaving(true)
|
||||
setError(null)
|
||||
setSaved(false)
|
||||
try {
|
||||
const selection = await saveLogbookVesselSelectionFromId(logbookId, activeVesselId)
|
||||
const vessel = vesselDataFromSnapshot(selection.vesselSnapshot)
|
||||
setResolvedVessel(vessel)
|
||||
setSaved(true)
|
||||
trackPlausibleEvent(PlausibleEvents.VESSEL_SAVED, { context: 'logbook_selection' })
|
||||
setTimeout(() => setSaved(false), 3000)
|
||||
} catch (err: unknown) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to save')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="tab-placeholder">
|
||||
<Ship className="header-logo spin" size={48} />
|
||||
<p>{t('vessel_pool.loading')}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="crew-dashboard-layout" data-tour="logbook-vessel-picker">
|
||||
<div className="form-card">
|
||||
<div className="form-header">
|
||||
<Ship size={24} className="form-icon" />
|
||||
<h2>{t('logbook_vessel.title')}</h2>
|
||||
</div>
|
||||
<p className="help-text mb-4">{t('logbook_vessel.subtitle')}</p>
|
||||
{selectionOnly && <p className="help-text mb-4">{t('logbook_vessel.selection_only_hint')}</p>}
|
||||
{!selectionOnly && !readOnly && onOpenProfile && (
|
||||
<p className="help-text mb-4">
|
||||
<button type="button" className="btn-link" onClick={onOpenProfile}>
|
||||
{t('logbook_vessel.manage_in_profile')}
|
||||
</button>
|
||||
</p>
|
||||
)}
|
||||
{error && <div className="auth-error mb-4">{error}</div>}
|
||||
|
||||
<div className="input-group mb-4">
|
||||
<label>{t('logbook_vessel.active_vessel')}</label>
|
||||
{pool.length === 0 ? (
|
||||
<p className="help-text">{t('logbook_vessel.no_vessels_in_pool')}</p>
|
||||
) : (
|
||||
<div className="crew-selection-list">
|
||||
{pool.map((v) => (
|
||||
<label key={v.payloadId} className="crew-selection-item">
|
||||
<input
|
||||
type="radio"
|
||||
name={`vessel-${logbookId}`}
|
||||
checked={activeVesselId === v.payloadId}
|
||||
onChange={() => !readOnly && setActiveVesselId(v.payloadId)}
|
||||
disabled={readOnly}
|
||||
/>
|
||||
<Ship size={16} aria-hidden="true" />
|
||||
<span>{v.data.name || t('logbook_vessel.unnamed')}</span>
|
||||
</label>
|
||||
))}
|
||||
{!readOnly && (
|
||||
<label className="crew-selection-item">
|
||||
<input
|
||||
type="radio"
|
||||
name={`vessel-${logbookId}`}
|
||||
checked={activeVesselId === null}
|
||||
onChange={() => setActiveVesselId(null)}
|
||||
/>
|
||||
<span>{t('logbook_vessel.no_vessel')}</span>
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{resolvedVessel && (
|
||||
<div className="member-editor-card glass mb-4 logbook-vessel-summary">
|
||||
<h3 className="mb-2">{resolvedVessel.name}</h3>
|
||||
<dl className="profile-dl">
|
||||
{resolvedVessel.homePort && (
|
||||
<div className="profile-dl-row">
|
||||
<dt>{t('vessel.port')}</dt>
|
||||
<dd>{resolvedVessel.homePort}</dd>
|
||||
</div>
|
||||
)}
|
||||
{resolvedVessel.registrationNumber && (
|
||||
<div className="profile-dl-row">
|
||||
<dt>{t('vessel.registration')}</dt>
|
||||
<dd>{resolvedVessel.registrationNumber}</dd>
|
||||
</div>
|
||||
)}
|
||||
{resolvedVessel.mmsi && (
|
||||
<div className="profile-dl-row">
|
||||
<dt>{t('vessel.mmsi')}</dt>
|
||||
<dd>{resolvedVessel.mmsi}</dd>
|
||||
</div>
|
||||
)}
|
||||
</dl>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!readOnly && logbookId !== 'demo' && (
|
||||
<div className="form-actions">
|
||||
{saved && (
|
||||
<div className="success-toast">
|
||||
<Check size={16} />
|
||||
<span>{t('logbook_vessel.saved')}</span>
|
||||
</div>
|
||||
)}
|
||||
<button type="button" className="btn primary" onClick={() => void handleSave()} disabled={saving}>
|
||||
<Save size={18} />
|
||||
{t('logbook_vessel.save')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { ChevronDown } from 'lucide-react'
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
interface ProfileAccordionSectionProps {
|
||||
id: string
|
||||
title: string
|
||||
icon?: ReactNode
|
||||
defaultOpen?: boolean
|
||||
/** When set, forces the section open (e.g. during onboarding tour). */
|
||||
forceOpen?: boolean
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
export default function ProfileAccordionSection({
|
||||
id,
|
||||
title,
|
||||
icon,
|
||||
defaultOpen = false,
|
||||
forceOpen,
|
||||
children
|
||||
}: ProfileAccordionSectionProps) {
|
||||
const isOpen = forceOpen !== undefined ? forceOpen : defaultOpen
|
||||
|
||||
return (
|
||||
<details className="profile-accordion" open={isOpen || undefined} data-section={id}>
|
||||
<summary className="profile-accordion__summary">
|
||||
<span className="profile-accordion__title">
|
||||
{icon}
|
||||
<span>{title}</span>
|
||||
</span>
|
||||
<ChevronDown size={20} className="profile-accordion__chevron" aria-hidden="true" />
|
||||
</summary>
|
||||
<div className="profile-accordion__body">{children}</div>
|
||||
</details>
|
||||
)
|
||||
}
|
||||
@@ -3,8 +3,10 @@ import { useTranslation } from 'react-i18next'
|
||||
import { cycleAppLanguage, getNextLanguage, isGermanLocale } from '../utils/i18nLanguages.js'
|
||||
import { decryptJson } from '../services/crypto.js'
|
||||
import { PlausibleEvents, trackPlausibleEvent } from '../services/analytics.js'
|
||||
import VesselForm from './VesselForm.tsx'
|
||||
import LogbookVesselPicker from './LogbookVesselPicker.tsx'
|
||||
import LogbookCrewPicker from './LogbookCrewPicker.tsx'
|
||||
import type { LogbookVesselSelectionData } from '../types/vessel.js'
|
||||
import { emptyLogbookVesselSelection } from '../types/vessel.js'
|
||||
import type { LogbookCrewSelectionData } from '../types/person.js'
|
||||
import { emptyLogbookCrewSelection } from '../types/person.js'
|
||||
import { legacyCrewRecordsToLogbookSelection } from '../utils/personSnapshots.js'
|
||||
@@ -38,6 +40,9 @@ export default function ReadOnlyViewer({ token, hexKey }: ReadOnlyViewerProps) {
|
||||
const [logbookCrewSelection, setLogbookCrewSelection] = useState<LogbookCrewSelectionData>(
|
||||
emptyLogbookCrewSelection()
|
||||
)
|
||||
const [logbookVesselSelection, setLogbookVesselSelection] = useState<LogbookVesselSelectionData>(
|
||||
emptyLogbookVesselSelection()
|
||||
)
|
||||
const [legacyCrews, setLegacyCrews] = useState<any[]>([])
|
||||
const [entries, setEntries] = useState<any[]>([])
|
||||
const [photos, setPhotos] = useState<any[]>([])
|
||||
@@ -97,6 +102,31 @@ export default function ReadOnlyViewer({ token, hexKey }: ReadOnlyViewerProps) {
|
||||
}
|
||||
}
|
||||
|
||||
if (data.logbookVesselSelection) {
|
||||
const decVessel = await decryptJson(
|
||||
data.logbookVesselSelection.encryptedData,
|
||||
data.logbookVesselSelection.iv,
|
||||
data.logbookVesselSelection.tag,
|
||||
keyBuffer
|
||||
)
|
||||
if (decVessel) {
|
||||
setLogbookVesselSelection({
|
||||
activeVesselId: decVessel.activeVesselId ?? null,
|
||||
vesselSnapshot: decVessel.vesselSnapshot ?? null
|
||||
})
|
||||
}
|
||||
} else if (decYacht) {
|
||||
const legacy = decYacht as Record<string, unknown>
|
||||
setLogbookVesselSelection({
|
||||
activeVesselId: 'legacy-yacht',
|
||||
vesselSnapshot: {
|
||||
id: 'legacy-yacht',
|
||||
name: typeof legacy.name === 'string' ? legacy.name : '',
|
||||
...legacy
|
||||
} as import('../types/vessel.js').VesselSnapshot
|
||||
})
|
||||
}
|
||||
|
||||
const decCrews: Array<{ payloadId: string; data: PersonData }> = []
|
||||
if (data.crews) {
|
||||
for (const c of data.crews) {
|
||||
@@ -257,10 +287,11 @@ export default function ReadOnlyViewer({ token, hexKey }: ReadOnlyViewerProps) {
|
||||
)}
|
||||
|
||||
{activeTab === 'vessel' && (
|
||||
<VesselForm
|
||||
<LogbookVesselPicker
|
||||
logbookId="shared"
|
||||
readOnly={true}
|
||||
preloadedData={yacht}
|
||||
selectionOnly={true}
|
||||
preloadedSelection={logbookVesselSelection}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
Anchor,
|
||||
Gauge,
|
||||
Sailboat,
|
||||
Ship,
|
||||
Timer,
|
||||
Share2,
|
||||
Calendar,
|
||||
@@ -31,6 +32,9 @@ import {
|
||||
import AccountDangerZone from './AccountDangerZone.tsx'
|
||||
import UserProfilePreferences from './UserProfilePreferences.tsx'
|
||||
import PersonPoolForm from './PersonPoolForm.tsx'
|
||||
import VesselPoolForm from './VesselPoolForm.tsx'
|
||||
import ProfileAccordionSection from './ProfileAccordionSection.tsx'
|
||||
import { useAppTour } from '../context/AppTourContext.tsx'
|
||||
import BetaBadge from './BetaBadge.tsx'
|
||||
import { useDialog } from './ModalDialog.tsx'
|
||||
import {
|
||||
@@ -137,6 +141,11 @@ export default function UserProfilePage({ onBack, onLogout }: UserProfilePagePro
|
||||
connStatusClassName
|
||||
} = useSyncIndicator()
|
||||
|
||||
const { isActive: tourActive, currentStepId: tourStepId } = useAppTour()
|
||||
const fleetSectionTourOpen =
|
||||
tourActive &&
|
||||
(tourStepId === 'profile_vessel_pool' || tourStepId === 'profile_crew_pool')
|
||||
|
||||
const sharedLogbookCount = useLiveQuery(
|
||||
() => db.logbooks.filter((lb) => lb.isShared === 1).count(),
|
||||
[]
|
||||
@@ -444,8 +453,14 @@ export default function UserProfilePage({ onBack, onLogout }: UserProfilePagePro
|
||||
</section>
|
||||
) : profile ? (
|
||||
<>
|
||||
<ProfileAccordionSection
|
||||
id="account"
|
||||
title={t('profile.sections.account')}
|
||||
icon={<User size={20} aria-hidden="true" />}
|
||||
defaultOpen
|
||||
>
|
||||
<div data-tour="profile-preferences">
|
||||
<section className="form-card">
|
||||
<section className="form-card profile-accordion-inner-card">
|
||||
<div className="form-header">
|
||||
<User size={24} className="form-icon" />
|
||||
<h2>{t('profile.identity_title')}</h2>
|
||||
@@ -487,10 +502,25 @@ export default function UserProfilePage({ onBack, onLogout }: UserProfilePagePro
|
||||
|
||||
<UserProfilePreferences userId={profile.userId} />
|
||||
</div>
|
||||
</ProfileAccordionSection>
|
||||
|
||||
<ProfileAccordionSection
|
||||
id="fleet"
|
||||
title={t('profile.sections.fleet')}
|
||||
icon={<Ship size={20} aria-hidden="true" />}
|
||||
defaultOpen
|
||||
forceOpen={fleetSectionTourOpen ? true : undefined}
|
||||
>
|
||||
<VesselPoolForm />
|
||||
<PersonPoolForm />
|
||||
</ProfileAccordionSection>
|
||||
|
||||
<section className="member-editor-card glass">
|
||||
<ProfileAccordionSection
|
||||
id="security"
|
||||
title={t('profile.sections.security')}
|
||||
icon={<Shield size={20} aria-hidden="true" />}
|
||||
>
|
||||
<section className="member-editor-card glass profile-accordion-inner-card">
|
||||
<div className="profile-section-header">
|
||||
<Shield size={20} />
|
||||
<h3>{t('profile.security_title')}</h3>
|
||||
@@ -729,7 +759,14 @@ export default function UserProfilePage({ onBack, onLogout }: UserProfilePagePro
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="form-card profile-stats-section">
|
||||
</ProfileAccordionSection>
|
||||
|
||||
<ProfileAccordionSection
|
||||
id="stats"
|
||||
title={t('profile.sections.stats')}
|
||||
icon={<BarChart2 size={20} aria-hidden="true" />}
|
||||
>
|
||||
<section className="form-card profile-stats-section profile-accordion-inner-card">
|
||||
<div className="form-header">
|
||||
<BarChart2 size={24} className="form-icon" />
|
||||
<div>
|
||||
@@ -791,8 +828,14 @@ export default function UserProfilePage({ onBack, onLogout }: UserProfilePagePro
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</ProfileAccordionSection>
|
||||
|
||||
<AccountDangerZone className="mt-6" />
|
||||
<ProfileAccordionSection
|
||||
id="danger"
|
||||
title={t('profile.sections.danger')}
|
||||
>
|
||||
<AccountDangerZone className="profile-accordion-inner-card" />
|
||||
</ProfileAccordionSection>
|
||||
</>
|
||||
) : null}
|
||||
</main>
|
||||
|
||||
@@ -0,0 +1,328 @@
|
||||
import React from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Ship, Camera, Trash2, Plus, X } from 'lucide-react'
|
||||
import type { VesselFormInputs } from '../utils/vesselFormUtils.js'
|
||||
|
||||
export interface VesselDataFieldsProps {
|
||||
inputs: VesselFormInputs
|
||||
onChange: (next: VesselFormInputs) => void
|
||||
readOnly?: boolean
|
||||
saving?: boolean
|
||||
newSailName: string
|
||||
onNewSailNameChange: (value: string) => void
|
||||
onAddSail: () => void
|
||||
onRemoveSail: (index: number) => void
|
||||
photoError?: string | null
|
||||
onPhotoChange: (e: React.ChangeEvent<HTMLInputElement>) => void
|
||||
onRemovePhoto: () => void
|
||||
fileInputRef: React.RefObject<HTMLInputElement | null>
|
||||
}
|
||||
|
||||
export default function VesselDataFields({
|
||||
inputs,
|
||||
onChange,
|
||||
readOnly = false,
|
||||
saving = false,
|
||||
newSailName,
|
||||
onNewSailNameChange,
|
||||
onAddSail,
|
||||
onRemoveSail,
|
||||
photoError,
|
||||
onPhotoChange,
|
||||
onRemovePhoto,
|
||||
fileInputRef
|
||||
}: VesselDataFieldsProps) {
|
||||
const { t } = useTranslation()
|
||||
const set = (patch: Partial<VesselFormInputs>) => onChange({ ...inputs, ...patch })
|
||||
|
||||
const triggerFileInput = () => {
|
||||
if (!readOnly) fileInputRef.current?.click()
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="form-grid">
|
||||
<div className="vessel-photo-wrapper">
|
||||
<div
|
||||
className="vessel-photo-preview"
|
||||
onClick={triggerFileInput}
|
||||
style={{ cursor: readOnly ? 'default' : 'pointer' }}
|
||||
>
|
||||
{inputs.photo ? (
|
||||
<img src={inputs.photo} alt={inputs.name || 'Vessel'} className="vessel-photo" />
|
||||
) : (
|
||||
<div className="vessel-photo-placeholder">
|
||||
<Ship size={48} className="placeholder-icon" />
|
||||
</div>
|
||||
)}
|
||||
{!readOnly && (
|
||||
<div className="vessel-photo-overlay">
|
||||
<Camera size={24} />
|
||||
<span>{inputs.photo ? t('vessel.photo_change') : t('vessel.photo_add')}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{!readOnly && (
|
||||
<div className="vessel-photo-actions">
|
||||
<button type="button" className="btn secondary btn-sm" onClick={triggerFileInput} disabled={saving}>
|
||||
<Camera size={16} />
|
||||
{inputs.photo ? t('vessel.photo_change') : t('vessel.photo_add')}
|
||||
</button>
|
||||
{inputs.photo && (
|
||||
<button type="button" className="btn danger btn-sm" onClick={onRemovePhoto} disabled={saving}>
|
||||
<Trash2 size={16} />
|
||||
{t('vessel.photo_delete')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<input
|
||||
type="file"
|
||||
ref={fileInputRef}
|
||||
onChange={onPhotoChange}
|
||||
accept="image/*"
|
||||
style={{ display: 'none' }}
|
||||
/>
|
||||
{photoError && <div className="auth-error mt-2">{photoError}</div>}
|
||||
</div>
|
||||
|
||||
<div className="input-group">
|
||||
<label>{t('vessel.name')}</label>
|
||||
<input
|
||||
type="text"
|
||||
className="input-text"
|
||||
value={inputs.name}
|
||||
onChange={(e) => set({ name: e.target.value })}
|
||||
disabled={saving || readOnly}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="input-group">
|
||||
<label>{t('vessel.type')}</label>
|
||||
<select
|
||||
className="input-text"
|
||||
value={inputs.vesselType}
|
||||
onChange={(e) => set({ vesselType: e.target.value })}
|
||||
disabled={saving || readOnly}
|
||||
>
|
||||
<option value="">{t('vessel.type_unset')}</option>
|
||||
<option value="sailing">{t('vessel.type_sailing')}</option>
|
||||
<option value="motor">{t('vessel.type_motor')}</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="input-group">
|
||||
<label>{t('vessel.length_m')}</label>
|
||||
<input
|
||||
type="text"
|
||||
inputMode="decimal"
|
||||
className="input-text"
|
||||
value={inputs.lengthM}
|
||||
onChange={(e) => set({ lengthM: e.target.value })}
|
||||
disabled={saving || readOnly}
|
||||
placeholder="0.00"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="input-group">
|
||||
<label>{t('vessel.draft_m')}</label>
|
||||
<input
|
||||
type="text"
|
||||
inputMode="decimal"
|
||||
className="input-text"
|
||||
value={inputs.draftM}
|
||||
onChange={(e) => set({ draftM: e.target.value })}
|
||||
disabled={saving || readOnly}
|
||||
placeholder="0.00"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="input-group">
|
||||
<label>{t('vessel.air_draft_m')}</label>
|
||||
<input
|
||||
type="text"
|
||||
inputMode="decimal"
|
||||
className="input-text"
|
||||
value={inputs.airDraftM}
|
||||
onChange={(e) => set({ airDraftM: e.target.value })}
|
||||
disabled={saving || readOnly}
|
||||
placeholder="0.00"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="input-group">
|
||||
<label>{t('vessel.port')}</label>
|
||||
<input
|
||||
type="text"
|
||||
className="input-text"
|
||||
value={inputs.homePort}
|
||||
onChange={(e) => set({ homePort: e.target.value })}
|
||||
disabled={saving || readOnly}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="input-group">
|
||||
<label>{t('vessel.owner')}</label>
|
||||
<input
|
||||
type="text"
|
||||
className="input-text"
|
||||
value={inputs.owner}
|
||||
onChange={(e) => set({ owner: e.target.value })}
|
||||
disabled={saving || readOnly}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="input-group">
|
||||
<label>{t('vessel.charter')}</label>
|
||||
<input
|
||||
type="text"
|
||||
className="input-text"
|
||||
value={inputs.charterCompany}
|
||||
onChange={(e) => set({ charterCompany: e.target.value })}
|
||||
disabled={saving || readOnly}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="input-group">
|
||||
<label>{t('vessel.registration')}</label>
|
||||
<input
|
||||
type="text"
|
||||
className="input-text"
|
||||
value={inputs.registrationNumber}
|
||||
onChange={(e) => set({ registrationNumber: e.target.value })}
|
||||
disabled={saving || readOnly}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="input-group">
|
||||
<label>{t('vessel.callsign')}</label>
|
||||
<input
|
||||
type="text"
|
||||
className="input-text"
|
||||
value={inputs.callSign}
|
||||
onChange={(e) => set({ callSign: e.target.value })}
|
||||
disabled={saving || readOnly}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="input-group">
|
||||
<label>{t('vessel.atis')}</label>
|
||||
<input
|
||||
type="text"
|
||||
className="input-text"
|
||||
value={inputs.atis}
|
||||
onChange={(e) => set({ atis: e.target.value })}
|
||||
disabled={saving || readOnly}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="input-group">
|
||||
<label>{t('vessel.mmsi')}</label>
|
||||
<input
|
||||
type="text"
|
||||
className="input-text"
|
||||
value={inputs.mmsi}
|
||||
onChange={(e) => set({ mmsi: e.target.value })}
|
||||
disabled={saving || readOnly}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="vessel-tanks-section">
|
||||
<h3>{t('vessel.tanks_section')}</h3>
|
||||
<p className="vessel-tanks-help">{t('vessel.tanks_help')}</p>
|
||||
<div className="vessel-tanks-grid">
|
||||
<div className="input-group">
|
||||
<label>{t('vessel.freshwater_capacity_l')}</label>
|
||||
<input
|
||||
type="text"
|
||||
inputMode="decimal"
|
||||
className="input-text"
|
||||
value={inputs.freshwaterCapacityL}
|
||||
onChange={(e) => set({ freshwaterCapacityL: e.target.value })}
|
||||
disabled={saving || readOnly}
|
||||
placeholder="0"
|
||||
/>
|
||||
</div>
|
||||
<div className="input-group">
|
||||
<label>{t('vessel.fuel_capacity_l')}</label>
|
||||
<input
|
||||
type="text"
|
||||
inputMode="decimal"
|
||||
className="input-text"
|
||||
value={inputs.fuelCapacityL}
|
||||
onChange={(e) => set({ fuelCapacityL: e.target.value })}
|
||||
disabled={saving || readOnly}
|
||||
placeholder="0"
|
||||
/>
|
||||
</div>
|
||||
<div className="input-group">
|
||||
<label>{t('vessel.greywater_capacity_l')}</label>
|
||||
<input
|
||||
type="text"
|
||||
inputMode="decimal"
|
||||
className="input-text"
|
||||
value={inputs.greywaterCapacityL}
|
||||
onChange={(e) => set({ greywaterCapacityL: e.target.value })}
|
||||
disabled={saving || readOnly}
|
||||
placeholder="0"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="sails-section">
|
||||
<h3>{t('vessel.sails_list')}</h3>
|
||||
<p className="help-text">{t('vessel.sails_help')}</p>
|
||||
<div className="sails-badges-grid">
|
||||
{inputs.sails.length === 0 ? (
|
||||
<span className="no-sails-msg">{t('vessel.no_sails')}</span>
|
||||
) : (
|
||||
inputs.sails.map((sail, idx) => (
|
||||
<span key={idx} className="sail-badge">
|
||||
{sail}
|
||||
{!readOnly && (
|
||||
<button
|
||||
type="button"
|
||||
className="remove-btn"
|
||||
onClick={() => onRemoveSail(idx)}
|
||||
disabled={saving}
|
||||
>
|
||||
<X size={14} />
|
||||
</button>
|
||||
)}
|
||||
</span>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
{!readOnly && (
|
||||
<div className="add-sail-form">
|
||||
<input
|
||||
type="text"
|
||||
className="input-text"
|
||||
placeholder={t('vessel.sail_name_placeholder')}
|
||||
value={newSailName}
|
||||
onChange={(e) => onNewSailNameChange(e.target.value)}
|
||||
disabled={saving}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault()
|
||||
onAddSail()
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="btn secondary"
|
||||
onClick={onAddSail}
|
||||
disabled={saving || !newSailName.trim()}
|
||||
style={{ width: 'auto' }}
|
||||
>
|
||||
<Plus size={16} />
|
||||
{t('vessel.add_sail')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Ship, Plus, Trash2, Edit2, X, Save } from 'lucide-react'
|
||||
import { useDialog } from './ModalDialog.tsx'
|
||||
import VesselDataFields from './VesselDataFields.tsx'
|
||||
import type { VesselFormInputs } from '../utils/vesselFormUtils.js'
|
||||
import { parseVesselFormInputs, vesselDataToFormInputs } from '../utils/vesselFormUtils.js'
|
||||
import { emptyVesselData } from '../types/vessel.js'
|
||||
import { loadVesselPool, saveVessel, deleteVessel, type DecryptedVessel } from '../services/vesselPool.js'
|
||||
import { PlausibleEvents, trackPlausibleEvent } from '../services/analytics.js'
|
||||
|
||||
export default function VesselPoolForm() {
|
||||
const { t } = useTranslation()
|
||||
const { showConfirm } = useDialog()
|
||||
const [vessels, setVessels] = useState<DecryptedVessel[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [showForm, setShowForm] = useState(false)
|
||||
const [editingId, setEditingId] = useState<string | null>(null)
|
||||
const [inputs, setInputs] = useState<VesselFormInputs>(vesselDataToFormInputs(emptyVesselData()))
|
||||
const [newSailName, setNewSailName] = useState('')
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [photoError, setPhotoError] = useState<string | null>(null)
|
||||
const fileRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const reload = useCallback(async () => {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
try {
|
||||
setVessels(await loadVesselPool())
|
||||
} catch (err: unknown) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to load')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
void reload()
|
||||
}, [reload])
|
||||
|
||||
const openAdd = () => {
|
||||
setEditingId(null)
|
||||
setInputs(vesselDataToFormInputs(emptyVesselData()))
|
||||
setNewSailName('')
|
||||
setPhotoError(null)
|
||||
setShowForm(true)
|
||||
}
|
||||
|
||||
const openEdit = (vessel: DecryptedVessel) => {
|
||||
setEditingId(vessel.payloadId)
|
||||
setInputs(vesselDataToFormInputs(vessel.data))
|
||||
setNewSailName('')
|
||||
setPhotoError(null)
|
||||
setShowForm(true)
|
||||
}
|
||||
|
||||
const handleAddSail = () => {
|
||||
const trimmed = newSailName.trim()
|
||||
if (trimmed && !inputs.sails.includes(trimmed)) {
|
||||
setInputs((prev) => ({ ...prev, sails: [...prev.sails, trimmed] }))
|
||||
}
|
||||
setNewSailName('')
|
||||
}
|
||||
|
||||
const handlePhotoChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0]
|
||||
if (!file) return
|
||||
setPhotoError(null)
|
||||
const reader = new FileReader()
|
||||
reader.onload = (event) => {
|
||||
const img = new Image()
|
||||
img.onload = () => {
|
||||
try {
|
||||
const canvas = document.createElement('canvas')
|
||||
const ctx = canvas.getContext('2d')
|
||||
if (!ctx) throw new Error('Could not get canvas context')
|
||||
let width = img.width
|
||||
let height = img.height
|
||||
const MAX_WIDTH = 800
|
||||
const MAX_HEIGHT = 600
|
||||
if (width > MAX_WIDTH || height > MAX_HEIGHT) {
|
||||
const ratio = Math.min(MAX_WIDTH / width, MAX_HEIGHT / height)
|
||||
width = Math.round(width * ratio)
|
||||
height = Math.round(height * ratio)
|
||||
}
|
||||
canvas.width = width
|
||||
canvas.height = height
|
||||
ctx.drawImage(img, 0, 0, width, height)
|
||||
setInputs((prev) => ({ ...prev, photo: canvas.toDataURL('image/jpeg', 0.7) }))
|
||||
} catch (err: unknown) {
|
||||
setPhotoError(err instanceof Error ? err.message : 'Failed to process image')
|
||||
}
|
||||
}
|
||||
img.onerror = () => setPhotoError('Invalid image file')
|
||||
img.src = event.target?.result as string
|
||||
}
|
||||
reader.readAsDataURL(file)
|
||||
}
|
||||
|
||||
const handleSave = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!inputs.name.trim()) return
|
||||
setSaving(true)
|
||||
setError(null)
|
||||
try {
|
||||
const data = parseVesselFormInputs(inputs)
|
||||
const id = editingId ?? window.crypto.randomUUID()
|
||||
await saveVessel(id, data, !editingId)
|
||||
setShowForm(false)
|
||||
trackPlausibleEvent(PlausibleEvents.VESSEL_SAVED, { context: 'vessel_pool' })
|
||||
await reload()
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof Error && err.message === 'MAX_VESSELS') {
|
||||
setError(t('vessel_pool.max_vessels'))
|
||||
} else if (err instanceof Error && err.message === 'invalid_metric') {
|
||||
setError(t('vessel.invalid_metric'))
|
||||
} else if (err instanceof Error && err.message === 'invalid_tank_liters') {
|
||||
setError(t('vessel.invalid_tank_liters'))
|
||||
} else {
|
||||
setError(err instanceof Error ? err.message : 'Failed to save')
|
||||
}
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
if (
|
||||
!(await showConfirm(
|
||||
t('vessel_pool.delete_confirm'),
|
||||
t('vessel_pool.title'),
|
||||
t('logs.confirm_yes'),
|
||||
t('logs.confirm_no')
|
||||
))
|
||||
) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
await deleteVessel(id)
|
||||
await reload()
|
||||
} catch (err: unknown) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to delete')
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="tab-placeholder">
|
||||
<Ship className="header-logo spin" size={48} />
|
||||
<p>{t('vessel_pool.loading')}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div data-tour="profile-vessel-pool">
|
||||
<div className="section-title-bar mb-4">
|
||||
<h3>{t('vessel_pool.section_title')}</h3>
|
||||
{!showForm && (
|
||||
<button type="button" className="btn primary" style={{ width: 'auto', padding: '8px 16px' }} onClick={openAdd}>
|
||||
<Plus size={16} />
|
||||
{t('vessel_pool.add_vessel')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<p className="help-text mb-4">{t('vessel_pool.subtitle')}</p>
|
||||
{error && <div className="auth-error mb-4">{error}</div>}
|
||||
|
||||
{vessels.length === 0 ? (
|
||||
<p className="help-text mb-4">{t('vessel_pool.no_vessels')}</p>
|
||||
) : (
|
||||
<div className="crew-grid mb-6">
|
||||
{vessels.map((v) => (
|
||||
<div key={v.payloadId} className="crew-member-card glass">
|
||||
<div className="crew-card-header">
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
|
||||
{v.data.photo ? (
|
||||
<img src={v.data.photo} alt="" className="crew-card-avatar" />
|
||||
) : (
|
||||
<div className="crew-card-avatar-placeholder">
|
||||
<Ship size={18} />
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<h4>{v.data.name}</h4>
|
||||
{v.data.homePort && <p className="help-text">{v.data.homePort}</p>}
|
||||
</div>
|
||||
</div>
|
||||
<div className="card-actions">
|
||||
<button type="button" className="btn-icon" onClick={() => openEdit(v)}>
|
||||
<Edit2 size={14} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn-icon logout"
|
||||
onClick={() => void handleDelete(v.payloadId)}
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showForm && (
|
||||
<form onSubmit={(e) => void handleSave(e)} className="member-editor-card glass">
|
||||
<div className="editor-header mb-4">
|
||||
<h3>{editingId ? t('vessel_pool.edit_vessel') : t('vessel_pool.add_vessel')}</h3>
|
||||
<button type="button" className="btn-icon" onClick={() => setShowForm(false)}>
|
||||
<X size={16} />
|
||||
</button>
|
||||
</div>
|
||||
<VesselDataFields
|
||||
inputs={inputs}
|
||||
onChange={setInputs}
|
||||
saving={saving}
|
||||
newSailName={newSailName}
|
||||
onNewSailNameChange={setNewSailName}
|
||||
onAddSail={handleAddSail}
|
||||
onRemoveSail={(idx) =>
|
||||
setInputs((prev) => ({ ...prev, sails: prev.sails.filter((_, i) => i !== idx) }))
|
||||
}
|
||||
photoError={photoError}
|
||||
onPhotoChange={handlePhotoChange}
|
||||
onRemovePhoto={() => {
|
||||
setInputs((prev) => ({ ...prev, photo: null }))
|
||||
if (fileRef.current) fileRef.current.value = ''
|
||||
}}
|
||||
fileInputRef={fileRef}
|
||||
/>
|
||||
<div className="form-actions mt-4">
|
||||
<button type="submit" className="btn primary" disabled={saving || !inputs.name.trim()}>
|
||||
<Save size={18} />
|
||||
{saving ? t('vessel.saving') : t('vessel.save')}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -17,9 +17,13 @@ describe('AppTourContext step order', () => {
|
||||
expect(profileIndex).toBeGreaterThan(FULL_STEP_ORDER.indexOf('nav_feedback'))
|
||||
expect(prefsIndex).toBe(profileIndex + 1)
|
||||
expect(finishIndex).toBe(prefsIndex + 1)
|
||||
expect(FULL_STEP_ORDER).toContain('profile_vessel_pool')
|
||||
expect(FULL_STEP_ORDER).toContain('profile_crew_pool')
|
||||
expect(FULL_STEP_ORDER).toContain('nav_logbook_crew')
|
||||
expect(FULL_STEP_ORDER).toHaveLength(13)
|
||||
expect(FULL_STEP_ORDER.indexOf('profile_vessel_pool')).toBeLessThan(
|
||||
FULL_STEP_ORDER.indexOf('profile_crew_pool')
|
||||
)
|
||||
expect(FULL_STEP_ORDER).toHaveLength(14)
|
||||
})
|
||||
|
||||
it('excludes profile, stats and feedback from demo tour', () => {
|
||||
|
||||
@@ -26,6 +26,7 @@ export type TourStepId =
|
||||
| 'entry_open'
|
||||
| 'entry_track'
|
||||
| 'nav_vessel'
|
||||
| 'profile_vessel_pool'
|
||||
| 'profile_crew_pool'
|
||||
| 'nav_logbook_crew'
|
||||
| 'nav_stats'
|
||||
@@ -72,6 +73,7 @@ export const FULL_STEP_ORDER: TourStepId[] = [
|
||||
'entry_open',
|
||||
'entry_track',
|
||||
'nav_vessel',
|
||||
'profile_vessel_pool',
|
||||
'profile_crew_pool',
|
||||
'nav_logbook_crew',
|
||||
'nav_stats',
|
||||
@@ -115,6 +117,7 @@ const TARGET_BY_STEP: Partial<Record<TourStepId, string>> = {
|
||||
entry_open: '[data-tour="entry-first"]',
|
||||
entry_track: '[data-tour="entry-track"]',
|
||||
nav_vessel: '[data-tour="nav-vessel"]',
|
||||
profile_vessel_pool: '[data-tour="profile-vessel-pool"]',
|
||||
profile_crew_pool: '[data-tour="profile-crew-pool"]',
|
||||
nav_logbook_crew: '[data-tour="nav-logbook-crew"]',
|
||||
nav_stats: '[data-tour="stats-dashboard"]',
|
||||
@@ -131,7 +134,12 @@ export function tourStepOpensEntry(stepId: TourStepId): boolean {
|
||||
export function getTourTargetDelay(stepId: TourStepId): number {
|
||||
if (stepId === 'entry_track') return 400
|
||||
if (stepId === 'nav_feedback') return 180
|
||||
if (stepId === 'nav_profile' || stepId === 'profile_preferences' || stepId === 'profile_crew_pool') {
|
||||
if (
|
||||
stepId === 'nav_profile' ||
|
||||
stepId === 'profile_preferences' ||
|
||||
stepId === 'profile_vessel_pool' ||
|
||||
stepId === 'profile_crew_pool'
|
||||
) {
|
||||
return 250
|
||||
}
|
||||
return 0
|
||||
@@ -189,7 +197,7 @@ export function AppTourProvider({ children }: { children: ReactNode }) {
|
||||
nav.setSelectedEntryId(null)
|
||||
nav.setActiveTab('vessel')
|
||||
}
|
||||
if (stepId === 'profile_crew_pool') {
|
||||
if (stepId === 'profile_vessel_pool' || stepId === 'profile_crew_pool') {
|
||||
nav.setSelectedEntryId(null)
|
||||
nav.setLogbookActive(false)
|
||||
nav.setProfileOpen(true)
|
||||
|
||||
@@ -606,7 +606,37 @@
|
||||
"push_unsupported": "Push-meddelelser understøttes ikke i denne browser.",
|
||||
"push_denied_hint": "Notifikationer er blokeret. Tillad dem i browserens eller enhedens indstillinger.",
|
||||
"push_ios_install_hint": "På iPhone/iPad: Føj app til startskærmen (iOS 16.4+) for at bruge push.",
|
||||
"push_error": "Push-meddelelser kunne ikke aktiveres."
|
||||
"push_error": "Push-meddelelser kunne ikke aktiveres.",
|
||||
"sections": {
|
||||
"account": "Konto og indstillinger",
|
||||
"fleet": "Flåde og besætning",
|
||||
"security": "Sikkerhed og enhed",
|
||||
"stats": "Statistik",
|
||||
"danger": "Farezone"
|
||||
}
|
||||
},
|
||||
"vessel_pool": {
|
||||
"title": "Skibsflåde",
|
||||
"section_title": "Dine skibe",
|
||||
"subtitle": "Hold alle skibe til dine logbøger her. Vælg aktivt skib per logbog fra listen.",
|
||||
"loading": "Indlæser skibsflåde…",
|
||||
"add_vessel": "Tilføj skib",
|
||||
"edit_vessel": "Rediger skib",
|
||||
"no_vessels": "Ingen skibe i puljen endnu.",
|
||||
"delete_confirm": "Fjerne dette skib fra flåden?",
|
||||
"max_vessels": "Højst 20 skibe i puljen."
|
||||
},
|
||||
"logbook_vessel": {
|
||||
"title": "Skib for denne logbog",
|
||||
"subtitle": "Vælg skib for denne logbog. Rejsedage bruger sejl- og tankdata fra valgt skib.",
|
||||
"active_vessel": "Skib for denne logbog",
|
||||
"no_vessels_in_pool": "Intet skib i flåden – tilføj i brugerprofilen først.",
|
||||
"no_vessel": "Intet skib valgt",
|
||||
"unnamed": "Uden navn",
|
||||
"save": "Gem skib",
|
||||
"saved": "Logbog-skib gemt.",
|
||||
"selection_only_hint": "Du ser skibet ejeren har valgt (delt logbog).",
|
||||
"manage_in_profile": "Administrer skibe i brugerprofilen"
|
||||
},
|
||||
"person_pool": {
|
||||
"title": "Stamm-Crew og skippere",
|
||||
@@ -883,7 +913,7 @@
|
||||
},
|
||||
"welcome_public": {
|
||||
"title": "Velkommen om bord!",
|
||||
"body": "Udforsk vores demo-logbog med tre dages rejse i Kielerfjorden - uden en konto. Denne korte tur viser dig skibsdata, crew og logbogsposter."
|
||||
"body": "Udforsk vores demo-logbog med tre dages rejse i Kielerfjorden – uden konto. Turen viser logbogsposter samt valg af skib og besætning for denne logbog. Flåde og stamm-besætning vedligeholder du senere i brugerprofilen."
|
||||
},
|
||||
"nav_logs": {
|
||||
"title": "Indlæg i logbogen",
|
||||
@@ -902,8 +932,12 @@
|
||||
"body": "Upload GPX-filer, eller se allerede gemte ruter på kortet - inklusive afstand og hastighed."
|
||||
},
|
||||
"nav_vessel": {
|
||||
"title": "Skibsdata",
|
||||
"body": "Indtast navn, dimensioner og tekniske data for din yacht - udfyld én gang, tilgængelig for alle rejsedage."
|
||||
"title": "Skib for logbog",
|
||||
"body": "Vælg skib fra flåden for denne logbog. Administrer skibe i brugerprofilen under Flåde og besætning."
|
||||
},
|
||||
"profile_vessel_pool": {
|
||||
"title": "Skibsflåde",
|
||||
"body": "I brugerprofilen opretter du alle dine skibe – charter, eget skib osv. Vælg derefter det rigtige skib per logbog."
|
||||
},
|
||||
"profile_crew_pool": {
|
||||
"title": "Stamm-Crew og skippere",
|
||||
|
||||
@@ -606,7 +606,37 @@
|
||||
"push_unsupported": "Push-Benachrichtigungen werden in diesem Browser nicht unterstützt.",
|
||||
"push_denied_hint": "Benachrichtigungen sind blockiert. Erlaube sie in den Browser- oder Geräteeinstellungen.",
|
||||
"push_ios_install_hint": "Auf dem iPhone/iPad: App zum Home-Bildschirm hinzufügen (iOS 16.4+), um Push zu nutzen.",
|
||||
"push_error": "Push-Benachrichtigungen konnten nicht aktiviert werden."
|
||||
"push_error": "Push-Benachrichtigungen konnten nicht aktiviert werden.",
|
||||
"sections": {
|
||||
"account": "Konto & Einstellungen",
|
||||
"fleet": "Flotte & Crew",
|
||||
"security": "Sicherheit & Gerät",
|
||||
"stats": "Statistik",
|
||||
"danger": "Gefahrenzone"
|
||||
}
|
||||
},
|
||||
"vessel_pool": {
|
||||
"title": "Schiffsflotte",
|
||||
"section_title": "Deine Schiffe",
|
||||
"subtitle": "Pflege hier alle Schiffe für deine Logbücher. Pro Logbuch wählst du das aktive Schiff aus dieser Liste.",
|
||||
"loading": "Schiffsflotte wird geladen…",
|
||||
"add_vessel": "Schiff hinzufügen",
|
||||
"edit_vessel": "Schiff bearbeiten",
|
||||
"no_vessels": "Noch keine Schiffe im Pool.",
|
||||
"delete_confirm": "Dieses Schiff wirklich aus der Flotte entfernen?",
|
||||
"max_vessels": "Maximale Anzahl von 20 Schiffen im Pool erreicht."
|
||||
},
|
||||
"logbook_vessel": {
|
||||
"title": "Schiff für dieses Logbuch",
|
||||
"subtitle": "Wähle das Schiff für dieses Logbuch. Reisetage nutzen Segel- und Tankdaten des gewählten Schiffs.",
|
||||
"active_vessel": "Schiff für dieses Logbuch",
|
||||
"no_vessels_in_pool": "Kein Schiff in der Flotte – zuerst im Benutzerprofil anlegen.",
|
||||
"no_vessel": "Kein Schiff gewählt",
|
||||
"unnamed": "Unbenannt",
|
||||
"save": "Schiff speichern",
|
||||
"saved": "Schiff für das Logbuch gespeichert.",
|
||||
"selection_only_hint": "Du siehst das vom Eigner gewählte Schiff (geteiltes Logbuch).",
|
||||
"manage_in_profile": "Schiffe im Benutzerprofil verwalten"
|
||||
},
|
||||
"person_pool": {
|
||||
"title": "Stammcrew & Skipper",
|
||||
@@ -883,7 +913,7 @@
|
||||
},
|
||||
"welcome_public": {
|
||||
"title": "Willkommen an Bord!",
|
||||
"body": "Erkunde unser Demo-Logbuch mit drei Reisetagen in der Kieler Förde – ganz ohne Account. Diese Tour zeigt dir Schiffsdaten, Crew-Auswahl und Logbucheinträge. Die Stammcrew pflegst du später im Benutzerprofil."
|
||||
"body": "Erkunde unser Demo-Logbuch mit drei Reisetagen in der Kieler Förde – ganz ohne Account. Die Tour zeigt dir Logbucheinträge, die Schiff- und Crew-Auswahl für dieses Logbuch. Flotte und Stammcrew pflegst du später im Benutzerprofil."
|
||||
},
|
||||
"nav_logs": {
|
||||
"title": "Logbucheinträge",
|
||||
@@ -902,8 +932,12 @@
|
||||
"body": "Lade GPX-Dateien hoch oder sieh bereits gespeicherte Routen auf der Karte – inklusive Distanz und Geschwindigkeit."
|
||||
},
|
||||
"nav_vessel": {
|
||||
"title": "Schiffsdaten",
|
||||
"body": "Hinterlege Name, Maße und technische Daten deiner Yacht – einmal ausfüllen, für alle Reisetage verfügbar."
|
||||
"title": "Schiff fürs Logbuch",
|
||||
"body": "Wähle aus deiner Schiffsflotte das Schiff für dieses Logbuch. Schiffe pflegst du im Benutzerprofil unter Flotte & Crew."
|
||||
},
|
||||
"profile_vessel_pool": {
|
||||
"title": "Schiffsflotte",
|
||||
"body": "Im Benutzerprofil legst du alle deine Schiffe an – Charteryachten, eigenes Boot usw. Pro Logbuch wählst du dann das passende Schiff."
|
||||
},
|
||||
"profile_crew_pool": {
|
||||
"title": "Stammcrew & Skipper",
|
||||
|
||||
@@ -606,7 +606,37 @@
|
||||
"push_unsupported": "Push notifications are not supported in this browser.",
|
||||
"push_denied_hint": "Notifications are blocked. Allow them in your browser or device settings.",
|
||||
"push_ios_install_hint": "On iPhone/iPad: add the app to your Home Screen (iOS 16.4+) to use push notifications.",
|
||||
"push_error": "Could not enable push notifications."
|
||||
"push_error": "Could not enable push notifications.",
|
||||
"sections": {
|
||||
"account": "Account & settings",
|
||||
"fleet": "Fleet & crew",
|
||||
"security": "Security & device",
|
||||
"stats": "Statistics",
|
||||
"danger": "Danger zone"
|
||||
}
|
||||
},
|
||||
"vessel_pool": {
|
||||
"title": "Vessel fleet",
|
||||
"section_title": "Your vessels",
|
||||
"subtitle": "Maintain all vessels for your logbooks here. Select the active vessel per logbook from this list.",
|
||||
"loading": "Loading vessel fleet…",
|
||||
"add_vessel": "Add vessel",
|
||||
"edit_vessel": "Edit vessel",
|
||||
"no_vessels": "No vessels in the pool yet.",
|
||||
"delete_confirm": "Remove this vessel from the fleet?",
|
||||
"max_vessels": "Maximum of 20 vessels in the pool reached."
|
||||
},
|
||||
"logbook_vessel": {
|
||||
"title": "Vessel for this logbook",
|
||||
"subtitle": "Choose the vessel for this logbook. Travel days use sails and tank data from the selected vessel.",
|
||||
"active_vessel": "Vessel for this logbook",
|
||||
"no_vessels_in_pool": "No vessel in the fleet — add one in your user profile first.",
|
||||
"no_vessel": "No vessel selected",
|
||||
"unnamed": "Unnamed",
|
||||
"save": "Save vessel",
|
||||
"saved": "Logbook vessel saved.",
|
||||
"selection_only_hint": "You see the vessel chosen by the owner (shared logbook).",
|
||||
"manage_in_profile": "Manage vessels in user profile"
|
||||
},
|
||||
"person_pool": {
|
||||
"title": "Core Crew & skippers",
|
||||
@@ -883,7 +913,7 @@
|
||||
},
|
||||
"welcome_public": {
|
||||
"title": "Welcome aboard!",
|
||||
"body": "Explore our demo logbook with three travel days in Kiel Bay — no account required. This short tour shows vessel data, crew, and log entries."
|
||||
"body": "Explore our demo logbook with three travel days in Kiel Bay — no account required. The tour covers log entries and vessel and crew selection for this logbook. Manage your fleet and core crew later in your user profile."
|
||||
},
|
||||
"nav_logs": {
|
||||
"title": "Log entries",
|
||||
@@ -902,8 +932,12 @@
|
||||
"body": "Upload GPX files or view saved routes on the map – including distance and speed stats."
|
||||
},
|
||||
"nav_vessel": {
|
||||
"title": "Vessel data",
|
||||
"body": "Enter your yacht's name, dimensions, and technical details – fill once, use on every travel day."
|
||||
"title": "Vessel for logbook",
|
||||
"body": "Choose a vessel from your fleet for this logbook. Manage vessels in your user profile under Fleet & crew."
|
||||
},
|
||||
"profile_vessel_pool": {
|
||||
"title": "Vessel fleet",
|
||||
"body": "In your user profile you add all your vessels — charter yachts, your own boat, etc. Then pick the right vessel per logbook."
|
||||
},
|
||||
"profile_crew_pool": {
|
||||
"title": "Core Crew & skippers",
|
||||
|
||||
@@ -606,7 +606,37 @@
|
||||
"push_unsupported": "Push-varsler støttes ikke i denne nettleseren.",
|
||||
"push_denied_hint": "Varsler er blokkert. Tillat dem i innstillingene i nettleseren eller på enheten.",
|
||||
"push_ios_install_hint": "På iPhone/iPad: Legg til app på startskjermen (iOS 16.4+) for å bruke push.",
|
||||
"push_error": "Push-varsler kunne ikke aktiveres."
|
||||
"push_error": "Push-varsler kunne ikke aktiveres.",
|
||||
"sections": {
|
||||
"account": "Konto og innstillinger",
|
||||
"fleet": "Flåte og crew",
|
||||
"security": "Sikkerhet og enhet",
|
||||
"stats": "Statistikk",
|
||||
"danger": "Faresone"
|
||||
}
|
||||
},
|
||||
"vessel_pool": {
|
||||
"title": "Skipsflåte",
|
||||
"section_title": "Dine skip",
|
||||
"subtitle": "Hold alle skip for loggbøkene dine her. Velg aktivt skip per loggbok fra listen.",
|
||||
"loading": "Laster skipsflåte…",
|
||||
"add_vessel": "Legg til skip",
|
||||
"edit_vessel": "Rediger skip",
|
||||
"no_vessels": "Ingen skip i poolen ennå.",
|
||||
"delete_confirm": "Fjerne dette skipet fra flåten?",
|
||||
"max_vessels": "Maksimalt 20 skip i poolen."
|
||||
},
|
||||
"logbook_vessel": {
|
||||
"title": "Skip for denne loggboken",
|
||||
"subtitle": "Velg skip for denne loggboken. Reisedager bruker seil- og tankdata fra valgt skip.",
|
||||
"active_vessel": "Skip for denne loggboken",
|
||||
"no_vessels_in_pool": "Ingen skip i flåten – legg til i brukerprofilen først.",
|
||||
"no_vessel": "Ingen skip valgt",
|
||||
"unnamed": "Uten navn",
|
||||
"save": "Lagre skip",
|
||||
"saved": "Loggbok-skip lagret.",
|
||||
"selection_only_hint": "Du ser skipet eieren har valgt (delt loggbok).",
|
||||
"manage_in_profile": "Administrer skip i brukerprofilen"
|
||||
},
|
||||
"person_pool": {
|
||||
"title": "Stamm-Crew og skippere",
|
||||
@@ -883,7 +913,7 @@
|
||||
},
|
||||
"welcome_public": {
|
||||
"title": "Velkommen om bord!",
|
||||
"body": "Utforsk vår demologgbok med tre dagers reise i Kielfjorden - uten konto. Denne korte omvisningen viser deg skipsdata, crew og loggbokoppføringer."
|
||||
"body": "Utforsk vår demologgbok med tre dagers reise i Kielfjorden – uten konto. Omvisningen viser loggbokoppføringer og valg av skip og crew for denne loggboken. Flåte og stamm-crew legger du inn senere i brukerprofilen."
|
||||
},
|
||||
"nav_logs": {
|
||||
"title": "Loggbokoppføringer",
|
||||
@@ -902,8 +932,12 @@
|
||||
"body": "Last opp GPX-filer eller se allerede lagrede ruter på kartet - inkludert avstand og hastighet."
|
||||
},
|
||||
"nav_vessel": {
|
||||
"title": "Skipsdata",
|
||||
"body": "Skriv inn navn, dimensjoner og tekniske data for båten din - fyll inn én gang, tilgjengelig for alle reisedager."
|
||||
"title": "Skip for loggbok",
|
||||
"body": "Velg skip fra flåten for denne loggboken. Administrer skip i brukerprofilen under Flåte og crew."
|
||||
},
|
||||
"profile_vessel_pool": {
|
||||
"title": "Skipsflåte",
|
||||
"body": "I brukerprofilen legger du inn alle skip – charter, eget båt osv. Velg deretter riktig skip per loggbok."
|
||||
},
|
||||
"profile_crew_pool": {
|
||||
"title": "Stamm-Crew og skippere",
|
||||
|
||||
@@ -606,7 +606,37 @@
|
||||
"push_unsupported": "Push-meddelanden stöds inte i den här webbläsaren.",
|
||||
"push_denied_hint": "Meddelanden är blockerade. Tillåt dem i webbläsarens eller enhetens inställningar.",
|
||||
"push_ios_install_hint": "På iPhone/iPad: Lägg till app på startskärmen (iOS 16.4+) för att använda push.",
|
||||
"push_error": "Push-meddelanden kunde inte aktiveras."
|
||||
"push_error": "Push-meddelanden kunde inte aktiveras.",
|
||||
"sections": {
|
||||
"account": "Konto och inställningar",
|
||||
"fleet": "Flotta och besättning",
|
||||
"security": "Säkerhet och enhet",
|
||||
"stats": "Statistik",
|
||||
"danger": "Riskzon"
|
||||
}
|
||||
},
|
||||
"vessel_pool": {
|
||||
"title": "Skipsflotta",
|
||||
"section_title": "Dina fartyg",
|
||||
"subtitle": "Underhåll alla fartyg för dina loggböcker här. Välj aktivt fartyg per loggbok från listan.",
|
||||
"loading": "Laddar fartygsflotta…",
|
||||
"add_vessel": "Lägg till fartyg",
|
||||
"edit_vessel": "Redigera fartyg",
|
||||
"no_vessels": "Inga fartyg i poolen ännu.",
|
||||
"delete_confirm": "Ta bort detta fartyg från flottan?",
|
||||
"max_vessels": "Högst 20 fartyg i poolen."
|
||||
},
|
||||
"logbook_vessel": {
|
||||
"title": "Fartyg för denna loggbok",
|
||||
"subtitle": "Välj fartyg för denna loggbok. Resdagar använder segel- och tankdata från valt fartyg.",
|
||||
"active_vessel": "Fartyg för denna loggbok",
|
||||
"no_vessels_in_pool": "Inget fartyg i flottan – lägg till i användarprofilen först.",
|
||||
"no_vessel": "Inget fartyg valt",
|
||||
"unnamed": "Namnlös",
|
||||
"save": "Spara fartyg",
|
||||
"saved": "Loggbok-fartyg sparat.",
|
||||
"selection_only_hint": "Du ser fartyget ägaren valt (delad loggbok).",
|
||||
"manage_in_profile": "Hantera fartyg i användarprofilen"
|
||||
},
|
||||
"person_pool": {
|
||||
"title": "Stamm-Crew och skeppare",
|
||||
@@ -883,7 +913,7 @@
|
||||
},
|
||||
"welcome_public": {
|
||||
"title": "Välkommen ombord!",
|
||||
"body": "Utforska vår demologgbok med tre dagars resor i Kielfjorden - utan konto. Den här korta rundturen visar dig fartygsdata, crew och loggboksanteckningar."
|
||||
"body": "Utforska vår demologgbok med tre dagars resor i Kielfjorden – utan konto. Rundturen visar loggboksanteckningar samt val av fartyg och besättning för denna loggbok. Flotta och stamm-besättning hanterar du senare i användarprofilen."
|
||||
},
|
||||
"nav_logs": {
|
||||
"title": "Loggboksanteckningar",
|
||||
@@ -902,8 +932,12 @@
|
||||
"body": "Ladda upp GPX-filer eller visa redan sparade rutter på kartan - inklusive avstånd och hastighet."
|
||||
},
|
||||
"nav_vessel": {
|
||||
"title": "Fartygsdata",
|
||||
"body": "Ange namn, dimensioner och tekniska data för din yacht - fyll i en gång, tillgänglig för alla resdagar."
|
||||
"title": "Fartyg för loggbok",
|
||||
"body": "Välj fartyg från flottan för denna loggbok. Hantera fartyg i användarprofilen under Flotta och besättning."
|
||||
},
|
||||
"profile_vessel_pool": {
|
||||
"title": "Fartygsflotta",
|
||||
"body": "I användarprofilen lägger du in alla fartyg – charter, egen båt m.m. Välj sedan rätt fartyg per loggbok."
|
||||
},
|
||||
"profile_crew_pool": {
|
||||
"title": "Stamm-Crew och skeppare",
|
||||
|
||||
@@ -558,7 +558,12 @@ export async function deleteAccount(): Promise<boolean> {
|
||||
db.photos.clear(),
|
||||
db.gpsTracks.clear(),
|
||||
db.syncQueue.clear(),
|
||||
db.logbookKeys.clear()
|
||||
db.logbookKeys.clear(),
|
||||
db.personPool.clear(),
|
||||
db.vesselPool.clear(),
|
||||
db.logbookCrewSelections.clear(),
|
||||
db.logbookVesselSelections.clear(),
|
||||
db.userSyncQueue.clear()
|
||||
])
|
||||
|
||||
// Wipe localStorage and session variables
|
||||
|
||||
@@ -37,22 +37,17 @@ export async function exportLogbookToCsv(logbookId: string, preloadedData?: { ya
|
||||
throw new Error('Encryption key not found. User must log in.')
|
||||
}
|
||||
|
||||
// 1. Fetch Yacht details
|
||||
const yachtRecord = await db.yachts.get(logbookId);
|
||||
if (yachtRecord) {
|
||||
try {
|
||||
const yacht = await decryptJson(yachtRecord.encryptedData, yachtRecord.iv, yachtRecord.tag, masterKey);
|
||||
yachtName = yacht.name || '';
|
||||
homePort = yacht.port || '';
|
||||
owner = yacht.owner || '';
|
||||
charter = yacht.charter || '';
|
||||
registration = yacht.registration || '';
|
||||
callsign = yacht.callsign || '';
|
||||
atis = yacht.atis || '';
|
||||
mmsi = yacht.mmsi || '';
|
||||
} catch (e) {
|
||||
console.error('Failed to decrypt yacht details for CSV:', e);
|
||||
}
|
||||
const { resolveVesselForLogbook } = await import('./resolveVessel.js')
|
||||
const yacht = await resolveVesselForLogbook(logbookId)
|
||||
if (yacht) {
|
||||
yachtName = yacht.name || ''
|
||||
homePort = yacht.homePort || ''
|
||||
owner = yacht.owner || ''
|
||||
charter = yacht.charterCompany || ''
|
||||
registration = yacht.registrationNumber || ''
|
||||
callsign = yacht.callSign || ''
|
||||
atis = yacht.atis || ''
|
||||
mmsi = yacht.mmsi || ''
|
||||
}
|
||||
|
||||
// 2. Fetch logbook entries
|
||||
|
||||
@@ -88,6 +88,14 @@ export interface LocalPerson {
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export interface LocalVessel {
|
||||
payloadId: string
|
||||
encryptedData: string
|
||||
iv: string
|
||||
tag: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export interface LocalLogbookCrewSelection {
|
||||
logbookId: string
|
||||
encryptedData: string
|
||||
@@ -96,10 +104,27 @@ export interface LocalLogbookCrewSelection {
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export interface LocalLogbookVesselSelection {
|
||||
logbookId: string
|
||||
encryptedData: string
|
||||
iv: string
|
||||
tag: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export interface SyncQueueItem {
|
||||
id?: number
|
||||
action: 'create' | 'update' | 'delete'
|
||||
type: 'yacht' | 'crew' | 'deviation' | 'entry' | 'logbook' | 'photo' | 'gpsTrack' | 'logbookCrew'
|
||||
type:
|
||||
| 'yacht'
|
||||
| 'crew'
|
||||
| 'deviation'
|
||||
| 'entry'
|
||||
| 'logbook'
|
||||
| 'photo'
|
||||
| 'gpsTrack'
|
||||
| 'logbookCrew'
|
||||
| 'logbookVessel'
|
||||
payloadId: string // payloadId or logbookId depending on the type
|
||||
logbookId: string
|
||||
data: string // JSON representation of the local record
|
||||
@@ -109,7 +134,7 @@ export interface SyncQueueItem {
|
||||
export interface UserSyncQueueItem {
|
||||
id?: number
|
||||
action: 'create' | 'update' | 'delete'
|
||||
type: 'person'
|
||||
type: 'person' | 'vessel'
|
||||
payloadId: string
|
||||
data: string
|
||||
updatedAt: string
|
||||
@@ -135,7 +160,9 @@ class DaagboxDatabase extends Dexie {
|
||||
nmeaArchives!: Table<LocalNmeaArchive>
|
||||
logbookKeys!: Table<LocalLogbookKey>
|
||||
personPool!: Table<LocalPerson>
|
||||
vesselPool!: Table<LocalVessel>
|
||||
logbookCrewSelections!: Table<LocalLogbookCrewSelection>
|
||||
logbookVesselSelections!: Table<LocalLogbookVesselSelection>
|
||||
syncQueue!: Table<SyncQueueItem>
|
||||
userSyncQueue!: Table<UserSyncQueueItem>
|
||||
entryDrafts!: Table<EntryDraftRecord, [string, string]>
|
||||
@@ -234,6 +261,24 @@ class DaagboxDatabase extends Dexie {
|
||||
userSyncQueue: '++id, action, type, payloadId',
|
||||
entryDrafts: '[logbookId+entryId], updatedAt'
|
||||
})
|
||||
this.version(9).stores({
|
||||
logbooks: 'id, encryptedTitle, updatedAt, isSynced, isShared, isDemo',
|
||||
yachts: 'logbookId, updatedAt',
|
||||
crews: 'payloadId, logbookId, updatedAt',
|
||||
deviations: 'logbookId, updatedAt',
|
||||
entries: 'payloadId, logbookId, updatedAt',
|
||||
syncQueue: '++id, action, type, payloadId, logbookId',
|
||||
photos: 'payloadId, entryId, logbookId, updatedAt',
|
||||
gpsTracks: 'entryId, logbookId, updatedAt',
|
||||
nmeaArchives: 'entryId, logbookId, updatedAt',
|
||||
logbookKeys: 'logbookId',
|
||||
personPool: 'payloadId, updatedAt',
|
||||
vesselPool: 'payloadId, updatedAt',
|
||||
logbookCrewSelections: 'logbookId, updatedAt',
|
||||
logbookVesselSelections: 'logbookId, updatedAt',
|
||||
userSyncQueue: '++id, action, type, payloadId',
|
||||
entryDrafts: '[logbookId+entryId], updatedAt'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ const PUBLIC_DEMO_ENTRY_IDS = [
|
||||
] as const
|
||||
|
||||
export const PUBLIC_DEMO_SKIPPER_ID = 'skipper'
|
||||
export const PUBLIC_DEMO_VESSEL_ID = 'demo-vessel-1'
|
||||
const PUBLIC_DEMO_CREW_MEMBER_ID = 'a0000001-0000-4000-8000-000000000010'
|
||||
|
||||
export interface DemoDaySpec {
|
||||
@@ -50,9 +51,19 @@ export interface DemoCrewRecord {
|
||||
}
|
||||
}
|
||||
|
||||
export interface DemoVesselRecord {
|
||||
payloadId: string
|
||||
data: Record<string, unknown> & { name: string }
|
||||
}
|
||||
|
||||
export interface PublicDemoFixture {
|
||||
title: string
|
||||
yacht: Record<string, unknown>
|
||||
vesselPool: DemoVesselRecord[]
|
||||
logbookVesselSelection: {
|
||||
activeVesselId: string | null
|
||||
vesselSnapshot: Record<string, unknown> | null
|
||||
}
|
||||
/** @deprecated legacy share payload */
|
||||
crews: DemoCrewRecord[]
|
||||
personPool: DemoCrewRecord[]
|
||||
@@ -238,6 +249,24 @@ export function buildDemoCrewRecords(): DemoCrewRecord[] {
|
||||
]
|
||||
}
|
||||
|
||||
function buildDemoVesselPool(yacht: Record<string, unknown>): DemoVesselRecord[] {
|
||||
return [
|
||||
{
|
||||
payloadId: PUBLIC_DEMO_VESSEL_ID,
|
||||
data: { name: String(yacht.name ?? 'Demo'), ...yacht }
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
function buildDemoLogbookVesselSelection(
|
||||
yacht: Record<string, unknown>
|
||||
): PublicDemoFixture['logbookVesselSelection'] {
|
||||
return {
|
||||
activeVesselId: PUBLIC_DEMO_VESSEL_ID,
|
||||
vesselSnapshot: { id: PUBLIC_DEMO_VESSEL_ID, ...yacht }
|
||||
}
|
||||
}
|
||||
|
||||
function buildDemoLogbookCrewSelection(pool: DemoCrewRecord[]) {
|
||||
const skipper = pool.find((p) => p.data.role === 'skipper')
|
||||
const crew = pool.filter((p) => p.data.role === 'crew')
|
||||
@@ -255,6 +284,8 @@ function buildDemoLogbookCrewSelection(pool: DemoCrewRecord[]) {
|
||||
export function buildPublicDemoFixture(): PublicDemoFixture {
|
||||
const title = i18n.t('demo.logbook_title')
|
||||
const yacht = buildDemoYachtData()
|
||||
const vesselPool = buildDemoVesselPool(yacht)
|
||||
const logbookVesselSelection = buildDemoLogbookVesselSelection(yacht)
|
||||
const personPool = buildDemoPersonPool()
|
||||
const crews = personPool
|
||||
const logbookCrewSelection = buildDemoLogbookCrewSelection(personPool)
|
||||
@@ -310,6 +341,8 @@ export function buildPublicDemoFixture(): PublicDemoFixture {
|
||||
return {
|
||||
title,
|
||||
yacht,
|
||||
vesselPool,
|
||||
logbookVesselSelection,
|
||||
crews,
|
||||
personPool,
|
||||
logbookCrewSelection,
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { db } from './db.js'
|
||||
import { getActiveMasterKey } from './auth.js'
|
||||
import { getLogbookKey } from './logbookKeys.js'
|
||||
import { decryptJson, encryptJson } from './crypto.js'
|
||||
import { syncLogbook } from './sync.js'
|
||||
import type { LogbookVesselSelectionData } from '../types/vessel.js'
|
||||
import { emptyLogbookVesselSelection } from '../types/vessel.js'
|
||||
import { buildLogbookVesselSelection } from '../utils/vesselSnapshot.js'
|
||||
import type { VesselData } from '../types/vessel.js'
|
||||
import { loadVesselPoolMap } from './vesselPool.js'
|
||||
|
||||
async function resolveLogbookKey(logbookId: string): Promise<ArrayBuffer> {
|
||||
const key = (await getLogbookKey(logbookId)) || getActiveMasterKey()
|
||||
if (!key) throw new Error('Encryption key not found. Please log in.')
|
||||
return key
|
||||
}
|
||||
|
||||
export async function loadLogbookVesselSelection(
|
||||
logbookId: string
|
||||
): Promise<LogbookVesselSelectionData> {
|
||||
const record = await db.logbookVesselSelections.get(logbookId)
|
||||
if (!record) return emptyLogbookVesselSelection()
|
||||
|
||||
const key = await resolveLogbookKey(logbookId)
|
||||
const data = (await decryptJson(record.encryptedData, record.iv, record.tag, key)) as
|
||||
| LogbookVesselSelectionData
|
||||
| null
|
||||
if (!data) return emptyLogbookVesselSelection()
|
||||
|
||||
return {
|
||||
activeVesselId: data.activeVesselId ?? null,
|
||||
vesselSnapshot: data.vesselSnapshot ?? null
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveLogbookVesselSelection(
|
||||
logbookId: string,
|
||||
selection: LogbookVesselSelectionData
|
||||
): Promise<void> {
|
||||
const key = await resolveLogbookKey(logbookId)
|
||||
const encrypted = await encryptJson(selection, key)
|
||||
const now = new Date().toISOString()
|
||||
|
||||
await db.logbookVesselSelections.put({
|
||||
logbookId,
|
||||
encryptedData: encrypted.ciphertext,
|
||||
iv: encrypted.iv,
|
||||
tag: encrypted.tag,
|
||||
updatedAt: now
|
||||
})
|
||||
|
||||
await db.syncQueue.put({
|
||||
action: 'update',
|
||||
type: 'logbookVessel',
|
||||
payloadId: logbookId,
|
||||
logbookId,
|
||||
data: JSON.stringify(encrypted),
|
||||
updatedAt: now
|
||||
})
|
||||
|
||||
syncLogbook(logbookId).catch((err) => console.warn('Background sync failed:', err))
|
||||
}
|
||||
|
||||
export async function saveLogbookVesselSelectionFromId(
|
||||
logbookId: string,
|
||||
activeVesselId: string | null,
|
||||
poolOverride?: Map<string, VesselData>
|
||||
): Promise<LogbookVesselSelectionData> {
|
||||
const pool = poolOverride ?? (await loadVesselPoolMap())
|
||||
const selection = buildLogbookVesselSelection(activeVesselId, pool)
|
||||
await saveLogbookVesselSelection(logbookId, selection)
|
||||
return selection
|
||||
}
|
||||
@@ -31,20 +31,15 @@ export async function generateLogbookPagePdf(logbookId: string, entryId: string,
|
||||
throw new Error('Encryption key not found. Please log in.')
|
||||
}
|
||||
|
||||
// 1. Fetch Yacht details
|
||||
const yachtRecord = await db.yachts.get(logbookId);
|
||||
if (yachtRecord) {
|
||||
try {
|
||||
const yacht = await decryptJson(yachtRecord.encryptedData, yachtRecord.iv, yachtRecord.tag, masterKey);
|
||||
yachtName = yacht.name || '';
|
||||
homePort = yacht.port || '';
|
||||
registration = yacht.registrationNumber || yacht.registration || '';
|
||||
callsign = yacht.callSign || '';
|
||||
atis = yacht.atis || '';
|
||||
mmsi = yacht.mmsi || '';
|
||||
} catch (e) {
|
||||
console.error('Failed to decrypt yacht details for PDF:', e);
|
||||
}
|
||||
const { resolveVesselForLogbook } = await import('./resolveVessel.js')
|
||||
const yacht = await resolveVesselForLogbook(logbookId)
|
||||
if (yacht) {
|
||||
yachtName = yacht.name || ''
|
||||
homePort = yacht.homePort || ''
|
||||
registration = yacht.registrationNumber || ''
|
||||
callsign = yacht.callSign || ''
|
||||
atis = yacht.atis || ''
|
||||
mmsi = yacht.mmsi || ''
|
||||
}
|
||||
|
||||
// 2. Fetch active Entry
|
||||
|
||||
@@ -16,7 +16,7 @@ export async function syncPersonPool(): Promise<void> {
|
||||
}
|
||||
|
||||
async function pushPersonPool(): Promise<void> {
|
||||
const pending = await db.userSyncQueue.toArray()
|
||||
const pending = (await db.userSyncQueue.toArray()).filter((item) => item.type === 'person')
|
||||
if (pending.length === 0) return
|
||||
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { db } from './db.js'
|
||||
import { getActiveMasterKey } from './auth.js'
|
||||
import { getLogbookKey } from './logbookKeys.js'
|
||||
import { decryptJson } from './crypto.js'
|
||||
import type { VesselData } from '../types/vessel.js'
|
||||
import { vesselDataFromSnapshot } from '../utils/vesselSnapshot.js'
|
||||
import { loadLogbookVesselSelection } from './logbookVesselSelection.js'
|
||||
import { loadVesselPoolMap } from './vesselPool.js'
|
||||
|
||||
/** Resolved vessel for a logbook: selection snapshot, pool, or legacy per-logbook yacht. */
|
||||
export async function resolveVesselForLogbook(
|
||||
logbookId: string,
|
||||
options?: {
|
||||
preloadedYacht?: VesselData | Record<string, unknown> | null
|
||||
preloadedSelection?: import('../types/vessel.js').LogbookVesselSelectionData
|
||||
}
|
||||
): Promise<VesselData | null> {
|
||||
if (options?.preloadedYacht) {
|
||||
return options.preloadedYacht as VesselData
|
||||
}
|
||||
|
||||
const selection =
|
||||
options?.preloadedSelection ?? (logbookId === 'demo' ? null : await loadLogbookVesselSelection(logbookId))
|
||||
|
||||
if (selection?.vesselSnapshot) {
|
||||
return vesselDataFromSnapshot(selection.vesselSnapshot)
|
||||
}
|
||||
|
||||
if (selection?.activeVesselId && logbookId !== 'demo') {
|
||||
const pool = await loadVesselPoolMap()
|
||||
const fromPool = pool.get(selection.activeVesselId)
|
||||
if (fromPool) return fromPool
|
||||
}
|
||||
|
||||
const legacy = await db.yachts.get(logbookId)
|
||||
if (!legacy) return null
|
||||
|
||||
const key = (await getLogbookKey(logbookId)) || getActiveMasterKey()
|
||||
if (!key) return null
|
||||
|
||||
const decrypted = (await decryptJson(legacy.encryptedData, legacy.iv, legacy.tag, key)) as
|
||||
| VesselData
|
||||
| null
|
||||
return decrypted
|
||||
}
|
||||
@@ -64,6 +64,8 @@ async function entityExistsLocally(item: SyncQueueItem): Promise<boolean> {
|
||||
return !!(await db.gpsTracks.get(item.payloadId))
|
||||
case 'logbookCrew':
|
||||
return !!(await db.logbookCrewSelections.get(item.logbookId))
|
||||
case 'logbookVessel':
|
||||
return !!(await db.logbookVesselSelections.get(item.logbookId))
|
||||
default:
|
||||
return false
|
||||
}
|
||||
@@ -228,6 +230,7 @@ type PulledServerPayload = {
|
||||
yacht?: { updatedAt: string } | null
|
||||
deviation?: { updatedAt: string } | null
|
||||
logbookCrewSelection?: { updatedAt: string } | null
|
||||
logbookVesselSelection?: { updatedAt: string } | null
|
||||
crews?: Array<{ payloadId: string; updatedAt: string }>
|
||||
entries?: Array<{ payloadId: string; updatedAt: string }>
|
||||
photos?: Array<{ payloadId: string; updatedAt: string }>
|
||||
@@ -248,6 +251,9 @@ async function pruneAcknowledgedQueueItems(
|
||||
if (server.logbookCrewSelection) {
|
||||
serverTimes.set('logbookCrew:' + logbookId, server.logbookCrewSelection.updatedAt)
|
||||
}
|
||||
if (server.logbookVesselSelection) {
|
||||
serverTimes.set('logbookVessel:' + logbookId, server.logbookVesselSelection.updatedAt)
|
||||
}
|
||||
for (const c of server.crews ?? []) serverTimes.set('crew:' + c.payloadId, c.updatedAt)
|
||||
for (const e of server.entries ?? []) serverTimes.set('entry:' + e.payloadId, e.updatedAt)
|
||||
for (const p of server.photos ?? []) serverTimes.set('photo:' + p.payloadId, p.updatedAt)
|
||||
@@ -269,7 +275,9 @@ async function pruneAcknowledgedQueueItems(
|
||||
? 'yacht:' + logbookId
|
||||
: item.type === 'logbookCrew'
|
||||
? 'logbookCrew:' + logbookId
|
||||
: `${item.type}:${item.payloadId}`
|
||||
: item.type === 'logbookVessel'
|
||||
? 'logbookVessel:' + logbookId
|
||||
: `${item.type}:${item.payloadId}`
|
||||
const serverUpdatedAt = serverTimes.get(key)
|
||||
if (serverUpdatedAt && !isNewer(item.updatedAt, serverUpdatedAt)) {
|
||||
if (item.id !== undefined) staleIds.push(item.id)
|
||||
@@ -295,12 +303,13 @@ async function pullChanges(logbookId: string): Promise<boolean> {
|
||||
return false
|
||||
}
|
||||
|
||||
const { yacht, deviation, crews, logbookCrewSelection, entries, photos, gpsTracks } =
|
||||
const { yacht, deviation, crews, logbookCrewSelection, logbookVesselSelection, entries, photos, gpsTracks } =
|
||||
await response.json()
|
||||
const serverSnapshot: PulledServerPayload = {
|
||||
yacht,
|
||||
deviation,
|
||||
logbookCrewSelection,
|
||||
logbookVesselSelection,
|
||||
crews,
|
||||
entries,
|
||||
photos,
|
||||
@@ -349,6 +358,20 @@ async function pullChanges(logbookId: string): Promise<boolean> {
|
||||
}
|
||||
}
|
||||
|
||||
// 2c. Sync Logbook Vessel Selection
|
||||
if (logbookVesselSelection) {
|
||||
const local = await db.logbookVesselSelections.get(logbookId)
|
||||
if (!local || isNewer(logbookVesselSelection.updatedAt, local.updatedAt)) {
|
||||
await db.logbookVesselSelections.put({
|
||||
logbookId,
|
||||
encryptedData: logbookVesselSelection.encryptedData,
|
||||
iv: logbookVesselSelection.iv,
|
||||
tag: logbookVesselSelection.tag,
|
||||
updatedAt: logbookVesselSelection.updatedAt
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Sync Crew List Payloads (legacy)
|
||||
const serverCrewMap = new Map<string, any>()
|
||||
if (crews && Array.isArray(crews)) {
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { db } from './db.js'
|
||||
import { getActiveMasterKey } from './auth.js'
|
||||
import { decryptJson, encryptJson } from './crypto.js'
|
||||
import { getLogbookKey } from './logbookKeys.js'
|
||||
import type { VesselData } from '../types/vessel.js'
|
||||
import { buildLogbookVesselSelection } from '../utils/vesselSnapshot.js'
|
||||
import { saveLogbookVesselSelection } from './logbookVesselSelection.js'
|
||||
|
||||
const MIGRATION_FLAG = 'vessel_pool_migration_v1_done'
|
||||
|
||||
function dedupeKey(data: VesselData): string {
|
||||
const reg = (data.registrationNumber || '').trim().toLowerCase()
|
||||
const name = (data.name || '').trim().toLowerCase()
|
||||
return `${reg}|${name}`
|
||||
}
|
||||
|
||||
export async function migrateLegacyYachtsToPoolIfNeeded(): Promise<void> {
|
||||
const userId = localStorage.getItem('active_userid')
|
||||
if (!userId || localStorage.getItem(MIGRATION_FLAG) === userId) return
|
||||
|
||||
const masterKey = getActiveMasterKey()
|
||||
if (!masterKey) return
|
||||
|
||||
try {
|
||||
const ownedLogbooks = await db.logbooks.filter((lb) => lb.isShared !== 1).toArray()
|
||||
const poolByKey = new Map<string, string>()
|
||||
const poolData = new Map<string, VesselData>()
|
||||
|
||||
for (const logbook of ownedLogbooks) {
|
||||
const logbookKey = (await getLogbookKey(logbook.id)) || masterKey
|
||||
const legacyYacht = await db.yachts.get(logbook.id)
|
||||
if (!legacyYacht) continue
|
||||
|
||||
const data = (await decryptJson(
|
||||
legacyYacht.encryptedData,
|
||||
legacyYacht.iv,
|
||||
legacyYacht.tag,
|
||||
logbookKey
|
||||
)) as VesselData | null
|
||||
if (!data?.name?.trim()) continue
|
||||
|
||||
const key = dedupeKey(data)
|
||||
let poolId = poolByKey.get(key)
|
||||
if (!poolId) {
|
||||
poolId = crypto.randomUUID()
|
||||
const existing = await db.vesselPool.get(poolId)
|
||||
if (!existing) {
|
||||
const encrypted = await encryptJson(data, masterKey)
|
||||
const now = new Date().toISOString()
|
||||
await db.vesselPool.put({
|
||||
payloadId: poolId,
|
||||
encryptedData: encrypted.ciphertext,
|
||||
iv: encrypted.iv,
|
||||
tag: encrypted.tag,
|
||||
updatedAt: now
|
||||
})
|
||||
await db.userSyncQueue.put({
|
||||
action: 'create',
|
||||
type: 'vessel',
|
||||
payloadId: poolId,
|
||||
data: JSON.stringify(encrypted),
|
||||
updatedAt: now
|
||||
})
|
||||
}
|
||||
poolByKey.set(key, poolId)
|
||||
poolData.set(poolId, data)
|
||||
}
|
||||
|
||||
const existingSelection = await db.logbookVesselSelections.get(logbook.id)
|
||||
if (!existingSelection) {
|
||||
const selection = buildLogbookVesselSelection(poolId, poolData)
|
||||
await saveLogbookVesselSelection(logbook.id, selection)
|
||||
}
|
||||
}
|
||||
|
||||
localStorage.setItem(MIGRATION_FLAG, userId)
|
||||
} catch (err) {
|
||||
console.warn('Vessel pool migration failed:', err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { db } from './db.js'
|
||||
import { getActiveMasterKey } from './auth.js'
|
||||
import { decryptJson, encryptJson } from './crypto.js'
|
||||
import type { VesselData } from '../types/vessel.js'
|
||||
import { MAX_POOL_VESSELS } from '../types/vessel.js'
|
||||
import { syncVesselPool } from './vesselPoolSync.js'
|
||||
|
||||
export interface DecryptedVessel {
|
||||
payloadId: string
|
||||
data: VesselData
|
||||
}
|
||||
|
||||
function requireMasterKey(): ArrayBuffer {
|
||||
const key = getActiveMasterKey()
|
||||
if (!key) throw new Error('Encryption key not found. Please log in.')
|
||||
return key
|
||||
}
|
||||
|
||||
export async function loadVesselPool(): Promise<DecryptedVessel[]> {
|
||||
const masterKey = requireMasterKey()
|
||||
const records = await db.vesselPool.toArray()
|
||||
const result: DecryptedVessel[] = []
|
||||
|
||||
for (const record of records) {
|
||||
const data = (await decryptJson(record.encryptedData, record.iv, record.tag, masterKey)) as
|
||||
| VesselData
|
||||
| null
|
||||
if (data?.name) {
|
||||
result.push({ payloadId: record.payloadId, data })
|
||||
}
|
||||
}
|
||||
|
||||
result.sort((a, b) =>
|
||||
a.data.name.localeCompare(b.data.name, undefined, { sensitivity: 'base' })
|
||||
)
|
||||
return result
|
||||
}
|
||||
|
||||
export async function loadVesselPoolMap(): Promise<Map<string, VesselData>> {
|
||||
const vessels = await loadVesselPool()
|
||||
return new Map(vessels.map((v) => [v.payloadId, v.data]))
|
||||
}
|
||||
|
||||
export async function saveVessel(
|
||||
payloadId: string,
|
||||
data: VesselData,
|
||||
isNew: boolean
|
||||
): Promise<void> {
|
||||
if (isNew) {
|
||||
const count = await db.vesselPool.count()
|
||||
if (count >= MAX_POOL_VESSELS) {
|
||||
throw new Error('MAX_VESSELS')
|
||||
}
|
||||
}
|
||||
|
||||
const masterKey = requireMasterKey()
|
||||
const encrypted = await encryptJson(data, masterKey)
|
||||
const now = new Date().toISOString()
|
||||
|
||||
await db.vesselPool.put({
|
||||
payloadId,
|
||||
encryptedData: encrypted.ciphertext,
|
||||
iv: encrypted.iv,
|
||||
tag: encrypted.tag,
|
||||
updatedAt: now
|
||||
})
|
||||
|
||||
await db.userSyncQueue.put({
|
||||
action: isNew ? 'create' : 'update',
|
||||
type: 'vessel',
|
||||
payloadId,
|
||||
data: JSON.stringify(encrypted),
|
||||
updatedAt: now
|
||||
})
|
||||
|
||||
syncVesselPool().catch((err) => console.warn('Vessel pool sync failed:', err))
|
||||
}
|
||||
|
||||
export async function deleteVessel(payloadId: string): Promise<void> {
|
||||
const now = new Date().toISOString()
|
||||
await db.vesselPool.delete(payloadId)
|
||||
await db.userSyncQueue.put({
|
||||
action: 'delete',
|
||||
type: 'vessel',
|
||||
payloadId,
|
||||
data: '',
|
||||
updatedAt: now
|
||||
})
|
||||
syncVesselPool().catch((err) => console.warn('Vessel pool sync failed:', err))
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { db } from './db.js'
|
||||
import { getActiveMasterKey } from './auth.js'
|
||||
import { apiFetch } from './api.js'
|
||||
|
||||
const API_BASE = '/api/auth/vessel-pool'
|
||||
|
||||
function isNewer(timeA: string | Date, timeB: string | Date): boolean {
|
||||
return new Date(timeA).getTime() > new Date(timeB).getTime()
|
||||
}
|
||||
|
||||
export async function syncVesselPool(): Promise<void> {
|
||||
if (!navigator.onLine || !getActiveMasterKey() || !localStorage.getItem('active_userid')) return
|
||||
|
||||
await pushVesselPool()
|
||||
await pullVesselPool()
|
||||
}
|
||||
|
||||
async function pushVesselPool(): Promise<void> {
|
||||
const pending = (await db.userSyncQueue.toArray()).filter((item) => item.type === 'vessel')
|
||||
if (pending.length === 0) return
|
||||
|
||||
try {
|
||||
const response = await apiFetch(`${API_BASE}/push`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ items: pending })
|
||||
})
|
||||
if (!response.ok) {
|
||||
console.warn('Vessel pool push rejected')
|
||||
return
|
||||
}
|
||||
|
||||
const { results } = await response.json()
|
||||
for (let i = 0; i < results.length; i++) {
|
||||
const res = results[i]
|
||||
const item = pending[i]
|
||||
if (!item) continue
|
||||
if (res.status === 'success' && item.id !== undefined) {
|
||||
await db.userSyncQueue.delete(item.id)
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('Vessel pool push failed:', err)
|
||||
}
|
||||
}
|
||||
|
||||
async function pullVesselPool(): Promise<void> {
|
||||
try {
|
||||
const response = await apiFetch(API_BASE, { method: 'GET' })
|
||||
if (!response.ok) return
|
||||
|
||||
const { vessels } = await response.json()
|
||||
if (!Array.isArray(vessels)) return
|
||||
|
||||
const serverMap = new Map<string, (typeof vessels)[0]>()
|
||||
for (const v of vessels) {
|
||||
serverMap.set(v.payloadId, v)
|
||||
const local = await db.vesselPool.get(v.payloadId)
|
||||
if (!local || isNewer(v.updatedAt, local.updatedAt)) {
|
||||
await db.vesselPool.put({
|
||||
payloadId: v.payloadId,
|
||||
encryptedData: v.encryptedData,
|
||||
iv: v.iv,
|
||||
tag: v.tag,
|
||||
updatedAt: v.updatedAt
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const localAll = await db.vesselPool.toArray()
|
||||
for (const local of localAll) {
|
||||
if (!serverMap.has(local.payloadId)) {
|
||||
const pendingCreate = await db.userSyncQueue
|
||||
.where({ payloadId: local.payloadId, action: 'create' })
|
||||
.first()
|
||||
if (!pendingCreate) {
|
||||
await db.vesselPool.delete(local.payloadId)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('Vessel pool pull failed:', err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
export interface VesselData {
|
||||
name: string
|
||||
vesselType?: string
|
||||
lengthM?: number
|
||||
draftM?: number
|
||||
airDraftM?: number
|
||||
homePort?: string
|
||||
charterCompany?: string
|
||||
owner?: string
|
||||
registrationNumber?: string
|
||||
callSign?: string
|
||||
atis?: string
|
||||
mmsi?: string
|
||||
sails?: string[]
|
||||
photo?: string | null
|
||||
freshwaterCapacityL?: number
|
||||
fuelCapacityL?: number
|
||||
greywaterCapacityL?: number
|
||||
}
|
||||
|
||||
export interface VesselSnapshot extends VesselData {
|
||||
id: string
|
||||
}
|
||||
|
||||
export interface LogbookVesselSelectionData {
|
||||
activeVesselId: string | null
|
||||
/** Denormalized for collaborators / offline without account pool */
|
||||
vesselSnapshot: VesselSnapshot | null
|
||||
}
|
||||
|
||||
export const MAX_POOL_VESSELS = 20
|
||||
|
||||
export function emptyLogbookVesselSelection(): LogbookVesselSelectionData {
|
||||
return {
|
||||
activeVesselId: null,
|
||||
vesselSnapshot: null
|
||||
}
|
||||
}
|
||||
|
||||
export function emptyVesselData(): VesselData {
|
||||
return {
|
||||
name: '',
|
||||
vesselType: '',
|
||||
homePort: '',
|
||||
charterCompany: '',
|
||||
owner: '',
|
||||
registrationNumber: '',
|
||||
callSign: '',
|
||||
atis: '',
|
||||
mmsi: '',
|
||||
sails: [],
|
||||
photo: null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { parseOptionalTankLiters, tankCapacityInputFromStored } from './tankCapacity.js'
|
||||
import type { VesselData } from '../types/vessel.js'
|
||||
|
||||
export function metricInputFromStored(value: unknown): string {
|
||||
if (value == null || value === '') return ''
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return String(value)
|
||||
if (typeof value === 'string') return value.trim()
|
||||
return ''
|
||||
}
|
||||
|
||||
export function parseOptionalMetricMeters(input: string): number | undefined {
|
||||
const trimmed = input.trim().replace(',', '.')
|
||||
if (!trimmed) return undefined
|
||||
const parsed = Number(trimmed)
|
||||
if (!Number.isFinite(parsed) || parsed < 0) {
|
||||
throw new Error('invalid_metric')
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
export interface VesselFormInputs {
|
||||
name: string
|
||||
vesselType: string
|
||||
lengthM: string
|
||||
draftM: string
|
||||
airDraftM: string
|
||||
homePort: string
|
||||
charterCompany: string
|
||||
owner: string
|
||||
registrationNumber: string
|
||||
callSign: string
|
||||
atis: string
|
||||
mmsi: string
|
||||
sails: string[]
|
||||
photo: string | null
|
||||
freshwaterCapacityL: string
|
||||
fuelCapacityL: string
|
||||
greywaterCapacityL: string
|
||||
}
|
||||
|
||||
export function vesselDataToFormInputs(data: Partial<VesselData>): VesselFormInputs {
|
||||
return {
|
||||
name: data.name || '',
|
||||
vesselType: data.vesselType || '',
|
||||
lengthM: metricInputFromStored(data.lengthM),
|
||||
draftM: metricInputFromStored(data.draftM),
|
||||
airDraftM: metricInputFromStored(data.airDraftM),
|
||||
homePort: data.homePort || '',
|
||||
charterCompany: data.charterCompany || '',
|
||||
owner: data.owner || '',
|
||||
registrationNumber: data.registrationNumber || '',
|
||||
callSign: data.callSign || '',
|
||||
atis: data.atis || '',
|
||||
mmsi: data.mmsi || '',
|
||||
sails: data.sails || [],
|
||||
photo: data.photo ?? null,
|
||||
freshwaterCapacityL: tankCapacityInputFromStored(data.freshwaterCapacityL),
|
||||
fuelCapacityL: tankCapacityInputFromStored(data.fuelCapacityL),
|
||||
greywaterCapacityL: tankCapacityInputFromStored(data.greywaterCapacityL)
|
||||
}
|
||||
}
|
||||
|
||||
export function parseVesselFormInputs(inputs: VesselFormInputs): VesselData {
|
||||
const parsedLengthM = parseOptionalMetricMeters(inputs.lengthM)
|
||||
const parsedDraftM = parseOptionalMetricMeters(inputs.draftM)
|
||||
const parsedAirDraftM = parseOptionalMetricMeters(inputs.airDraftM)
|
||||
const parsedFreshwaterCapacityL = parseOptionalTankLiters(inputs.freshwaterCapacityL)
|
||||
const parsedFuelCapacityL = parseOptionalTankLiters(inputs.fuelCapacityL)
|
||||
const parsedGreywaterCapacityL = parseOptionalTankLiters(inputs.greywaterCapacityL)
|
||||
|
||||
return {
|
||||
name: inputs.name.trim(),
|
||||
vesselType: inputs.vesselType || undefined,
|
||||
lengthM: parsedLengthM,
|
||||
draftM: parsedDraftM,
|
||||
airDraftM: parsedAirDraftM,
|
||||
freshwaterCapacityL: parsedFreshwaterCapacityL,
|
||||
fuelCapacityL: parsedFuelCapacityL,
|
||||
greywaterCapacityL: parsedGreywaterCapacityL,
|
||||
homePort: inputs.homePort.trim(),
|
||||
charterCompany: inputs.charterCompany.trim(),
|
||||
owner: inputs.owner.trim(),
|
||||
registrationNumber: inputs.registrationNumber.trim(),
|
||||
callSign: inputs.callSign.trim(),
|
||||
atis: inputs.atis.trim(),
|
||||
mmsi: inputs.mmsi.trim(),
|
||||
sails: inputs.sails,
|
||||
photo: inputs.photo
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { buildLogbookVesselSelection, vesselDataFromSnapshot, vesselToSnapshot } from './vesselSnapshot.js'
|
||||
import type { VesselData } from '../types/vessel.js'
|
||||
|
||||
const sampleVessel: VesselData = {
|
||||
name: 'Sea Breeze',
|
||||
homePort: 'Kiel',
|
||||
sails: ['Genoa'],
|
||||
registrationNumber: 'DE-123'
|
||||
}
|
||||
|
||||
describe('vesselSnapshot', () => {
|
||||
it('builds selection with snapshot from pool', () => {
|
||||
const pool = new Map<string, VesselData>([['v1', sampleVessel]])
|
||||
const sel = buildLogbookVesselSelection('v1', pool)
|
||||
expect(sel.activeVesselId).toBe('v1')
|
||||
expect(sel.vesselSnapshot?.name).toBe('Sea Breeze')
|
||||
expect(sel.vesselSnapshot?.id).toBe('v1')
|
||||
})
|
||||
|
||||
it('returns empty selection when no vessel id', () => {
|
||||
const sel = buildLogbookVesselSelection(null, new Map())
|
||||
expect(sel.activeVesselId).toBeNull()
|
||||
expect(sel.vesselSnapshot).toBeNull()
|
||||
})
|
||||
|
||||
it('round-trips snapshot to vessel data', () => {
|
||||
const snap = vesselToSnapshot('v1', sampleVessel)
|
||||
const data = vesselDataFromSnapshot(snap)
|
||||
expect(data?.name).toBe('Sea Breeze')
|
||||
expect(data?.homePort).toBe('Kiel')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { LogbookVesselSelectionData, VesselData, VesselSnapshot } from '../types/vessel.js'
|
||||
|
||||
export function vesselToSnapshot(id: string, data: VesselData): VesselSnapshot {
|
||||
return {
|
||||
id,
|
||||
name: data.name,
|
||||
vesselType: data.vesselType,
|
||||
lengthM: data.lengthM,
|
||||
draftM: data.draftM,
|
||||
airDraftM: data.airDraftM,
|
||||
homePort: data.homePort,
|
||||
charterCompany: data.charterCompany,
|
||||
owner: data.owner,
|
||||
registrationNumber: data.registrationNumber,
|
||||
callSign: data.callSign,
|
||||
atis: data.atis,
|
||||
mmsi: data.mmsi,
|
||||
sails: data.sails ? [...data.sails] : [],
|
||||
photo: data.photo ?? null,
|
||||
freshwaterCapacityL: data.freshwaterCapacityL,
|
||||
fuelCapacityL: data.fuelCapacityL,
|
||||
greywaterCapacityL: data.greywaterCapacityL
|
||||
}
|
||||
}
|
||||
|
||||
export function buildLogbookVesselSelection(
|
||||
activeVesselId: string | null,
|
||||
pool: Map<string, VesselData>
|
||||
): LogbookVesselSelectionData {
|
||||
if (!activeVesselId) {
|
||||
return { activeVesselId: null, vesselSnapshot: null }
|
||||
}
|
||||
const data = pool.get(activeVesselId)
|
||||
if (!data) {
|
||||
return { activeVesselId, vesselSnapshot: null }
|
||||
}
|
||||
return {
|
||||
activeVesselId,
|
||||
vesselSnapshot: vesselToSnapshot(activeVesselId, data)
|
||||
}
|
||||
}
|
||||
|
||||
export function vesselDataFromSnapshot(snapshot: VesselSnapshot | null): VesselData | null {
|
||||
if (!snapshot) return null
|
||||
const { id: _id, ...data } = snapshot
|
||||
return data
|
||||
}
|
||||
Reference in New Issue
Block a user