Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions app/api/shared/logbooks/[[...segments]]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { NextResponse } from "next/server";
import { auth } from "../../../../../auth";
import { readSharedLogSheet } from "../../../../lib/logbook-store";

export async function GET(_request: Request, { params }: { params: Promise<{ segments?: string[] }> }) {
const { segments = [] } = await params;
const { ownerId, sheetId } = parseShareSegments(segments);
if (!sheetId) return NextResponse.json({ error: "Shared logbook not found" }, { status: 404 });

const session = await auth();
const sharedSheet = await readSharedLogSheet(sheetId, Boolean(session?.user?.id), ownerId);
if (!sharedSheet) return NextResponse.json({ error: "Shared logbook not found" }, { status: 404 });
return NextResponse.json(sharedSheet);
}

function parseShareSegments(segments: string[]) {
if (segments.length === 1) return { sheetId: segments[0] };
if (segments.length === 2) return { ownerId: segments[0], sheetId: segments[1] };
return {};
}
64 changes: 20 additions & 44 deletions app/components/LogbookApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
type LineForm,
type LogLine,
type LogSheet,
type LogSheetShareSettings,
type PersistedLogbook,
type SheetForm,
} from "../models/logbook";
Expand Down Expand Up @@ -44,6 +45,7 @@ import {
} from "./logbook/date-utils";
import { ManagerShell } from "./managers/ManagerShell";
import { courseConversionColumns } from "../domain/nautical/course-conversion";
import { calculateLogSheetMetrics, formatLogSheetDuration } from "../domain/logbook/sheet-metrics";
import { lineFormToLogLine } from "../domain/log-lines/log-line-form";
import { ModuleTabs, type ActiveView } from "../templates/ModuleTabs";
import { useI18n } from "../lib/i18n";
Expand Down Expand Up @@ -153,55 +155,17 @@ const mockSocialUsers: SocialUser[] = [
},
];

function parseLogTimeMinutes(time: string) {
const match = time.match(/^(\d{1,2}):(\d{2})/);
if (!match) return undefined;
const hours = Number.parseInt(match[1], 10);
const minutes = Number.parseInt(match[2], 10);
if (!Number.isFinite(hours) || !Number.isFinite(minutes)) return undefined;
return hours * 60 + minutes;
}

function formatDuration(minutes: number) {
const safeMinutes = Math.max(0, Math.round(minutes));
const hours = Math.floor(safeMinutes / 60);
const remainingMinutes = safeMinutes % 60;
return `${hours}h ${remainingMinutes.toString().padStart(2, "0")}m`;
}

function logLineDistanceDeltas(lines: LogLine[]) {
return lines.map((line, index) =>
Math.max(0, line.logNm - (lines[index - 1]?.logNm ?? 0)),
);
}

function calculateSheetSummary(sheet: LogSheet) {
const deltas = logLineDistanceDeltas(sheet.lines);
const motorMiles = deltas.reduce(
(sum, delta, index) =>
sum + ((sheet.lines[index]?.motorHours ?? 0) > 0 || (sheet.lines[index]?.motorMiles ?? 0) > 0 ? delta : 0),
0,
);
const totalMiles = deltas.reduce((sum, delta) => sum + delta, 0);
const sailMiles = Math.max(0, totalMiles - motorMiles);
const firstTime = parseLogTimeMinutes(sheet.lines[0]?.time ?? "");
const lastTime = parseLogTimeMinutes(sheet.lines.at(-1)?.time ?? "");
const durationMinutes =
firstTime === undefined || lastTime === undefined
? undefined
: lastTime >= firstTime
? lastTime - firstTime
: lastTime + 24 * 60 - firstTime;

const metrics = sheet.metrics ?? calculateLogSheetMetrics(sheet.lines);
return {
motorMiles,
sailMiles,
totalMiles,
duration:
durationMinutes === undefined ? "—" : formatDuration(durationMinutes),
motorMiles: metrics.motorMiles,
sailMiles: metrics.sailMiles,
totalMiles: metrics.totalMiles,
duration: formatLogSheetDuration(metrics.durationMinutes),
};
}


export function LogbookApp({
userId,
userEmail,
Expand Down Expand Up @@ -1032,6 +996,16 @@ export function LogbookApp({
setSheetForm(sheetToForm(sheet));
}

async function updateActiveSheetShare(share: LogSheetShareSettings) {
const nextLogbook = {
...logbookRef.current,
sheets: logbookRef.current.sheets.map((sheet) =>
sheet.id === activeSheet.id ? { ...sheet, share } : sheet,
),
};
await saveLogbookNow(nextLogbook);
}

async function updateActiveSheetStatus(status: LogSheet["status"]) {
if (status === "Locked") cancelSheetInlineEdit();
const nextLogbook = {
Expand Down Expand Up @@ -1694,9 +1668,11 @@ export function LogbookApp({
navigate={navigate}
cancelSheetEdit={cancelSheetEdit}
activeSheet={activeSheet}
userId={userId}
renderInlineTextField={renderInlineTextField}
isActiveSheetLocked={isActiveSheetLocked}
updateActiveSheetStatus={updateActiveSheetStatus}
updateActiveSheetShare={updateActiveSheetShare}
renderInlineBoatField={renderInlineBoatField}
activeBoat={activeBoat}
renderInlineDateField={renderInlineDateField}
Expand Down
73 changes: 73 additions & 0 deletions app/components/logbook/pages/LogbookDetailsPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type {
SheetForm,
LogLine,
LogSheet,
LogSheetShareSettings,
PersistedLogbook,
} from "../../../models/logbook";
import { coordinateToInput, decimalToDmsParts, dmsPartsToDecimal, parseCoordinate, type CoordinateFormat, type DmsParts } from "../../../domain/nautical/coordinates";
Expand All @@ -16,6 +17,7 @@ import { updateLogLineFormForInput } from "../../../domain/log-lines/log-line-ed
import { LogLinesMapView } from "../OpenSeaMapView";
import type { TranslationKey } from "../../../lib/i18n";
import { fileToStoredImage } from "../image-utils";
import { defaultLogSheetShareSettings } from "../../../models/logbook";

type CourseColumn = {
field: keyof Pick<
Expand Down Expand Up @@ -72,6 +74,7 @@ export function LogbookDetailsPage(props: LogbookDetailsPageProps) {
renderInlineTextField,
isActiveSheetLocked,
updateActiveSheetStatus,
updateActiveSheetShare,
renderInlineBoatField,
renderInlineDateField,
activeSheetSummary,
Expand All @@ -93,6 +96,8 @@ export function LogbookDetailsPage(props: LogbookDetailsPageProps) {
deleteTechnicalCheck,
} = props;
const activeBoat = props.activeBoat as Boat;
const sharingOwnerId = props.userId as string | undefined;
const updateShare = updateActiveSheetShare as (share: LogSheetShareSettings) => Promise<void>;
const activeSheet = props.activeSheet as LogSheet;
const lineForm = props.lineForm as LineForm;
const logbook = props.logbook as PersistedLogbook;
Expand All @@ -103,12 +108,33 @@ export function LogbookDetailsPage(props: LogbookDetailsPageProps) {
const onCoordinateFormatChange = props.onCoordinateFormatChange as (format: CoordinateFormat) => void;
const onShowCourseColumnsChange = props.onShowCourseColumnsChange as (show: boolean) => void;
const [isMapExpanded, setIsMapExpanded] = useState(false);
const [isShareDialogOpen, setIsShareDialogOpen] = useState(false);
const [shareDraftState, setShareDraftState] = useState<{ sheetId: string; share: LogSheetShareSettings }>({ sheetId: "", share: defaultLogSheetShareSettings });
const [newTechnicalCheck, setNewTechnicalCheck] = useState("");
const [technicalCheckDraftState, setTechnicalCheckDraftState] = useState<{ sheetId: string; drafts: Record<number, string> }>({ sheetId: "", drafts: {} });
const [openCourseTooltip, setOpenCourseTooltip] = useState<TranslationKey | null>(null);
const [courseTooltipPosition, setCourseTooltipPosition] = useState({ left: 0, top: 0 });
const technicalCheckDrafts = technicalCheckDraftState.sheetId === activeSheet.id ? technicalCheckDraftState.drafts : {};
const scannerWarnings = activeSheet.scannerWarnings ?? [];
const share = activeSheet.share ?? defaultLogSheetShareSettings;
const shareDraft = shareDraftState.sheetId === activeSheet.id ? shareDraftState.share : share;
const sharePath = sharingOwnerId ? `/share/${encodeURIComponent(sharingOwnerId)}/${encodeURIComponent(activeSheet.id)}` : `/share/${encodeURIComponent(activeSheet.id)}`;
const shareUrl = typeof window === "undefined" ? sharePath : `${window.location.origin}${sharePath}`;
const setShare = (patch: Partial<LogSheetShareSettings>) => {
const nextShare = { ...shareDraft, ...patch };
setShareDraftState({ sheetId: activeSheet.id, share: nextShare });
void updateShare(nextShare);
};
const isSharingEnabled = Object.values(shareDraft).some((privacy) => privacy !== "private");
const shareOptions = [
["masterData", "Master data (from/to/boat)"],
["picture", "Picture"],
["logLines", "Loglines"],
["metrics", "Metrics (time and miles)"],
["technicalLog", "Technical log"],
["skipper", "Skipper"],
["crew", "Crew information"],
] as const;
const showScannerDraftNotice =
activeSheet.source === "scanner" && activeSheet.status === "Draft";
const courseConversionSequence = useRef(0);
Expand Down Expand Up @@ -537,6 +563,15 @@ export function LogbookDetailsPage(props: LogbookDetailsPageProps) {
</div>
<div className="inline-edit-actions sheet-master-actions">
<span className="status-pill">{activeSheet.status}</span>
<button
type="button"
className="edit-chip compact-chip"
aria-label="Share logsheet"
title="Share"
onClick={() => setIsShareDialogOpen(true)}
>
<span aria-hidden="true">↗</span> Share
</button>
{isActiveSheetLocked ? (
<button
type="button"
Expand Down Expand Up @@ -630,6 +665,44 @@ export function LogbookDetailsPage(props: LogbookDetailsPageProps) {
</aside>
)}


{isShareDialogOpen && (
<div className="share-logsheet-modal" role="dialog" aria-modal="true" aria-labelledby="share-logsheet-title">
<div className="share-logsheet-panel">
<div className="share-logsheet-heading">
<h2 id="share-logsheet-title">Share logsheet</h2>
<button className="edit-chip" type="button" onClick={() => setIsShareDialogOpen(false)}>Close</button>
</div>
<div className="share-logsheet-url">
{isSharingEnabled ? (
<>
<span>Share URL</span>
<a href={shareUrl} target="_blank" rel="noreferrer">{shareUrl}</a>
</>
) : (
<p>Set at least one part to public or registered users to enable this share link.</p>
)}
</div>
<fieldset className="share-logsheet-options">
<legend>Privacy by logsheet part</legend>
{shareOptions.map(([field, label]) => (
<label key={field} className="share-logsheet-option">
<span>{label}</span>
<select
value={shareDraft[field]}
onChange={(event) => setShare({ [field]: event.currentTarget.value } as Partial<LogSheetShareSettings>)}
>
<option value="private">Private</option>
<option value="registered">Registered users only</option>
<option value="public">Public to everyone</option>
</select>
</label>
))}
</fieldset>
</div>
</div>
)}

<section
className="entry-metrics logbook-section"
aria-label={t("details.summaryAria")}
Expand Down
36 changes: 36 additions & 0 deletions app/domain/logbook/sheet-metrics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import type { LogLine } from "../../models/logbook";

export type LogSheetMetrics = {
motorMiles: number;
sailMiles: number;
totalMiles: number;
durationMinutes: number | null;
};

export function calculateLogSheetMetrics(lines: LogLine[]): LogSheetMetrics {
const deltas = lines.map((line, index) => Math.max(0, line.logNm - (lines[index - 1]?.logNm ?? 0)));
const motorMiles = deltas.reduce((sum, delta, index) => sum + ((lines[index]?.motorHours ?? 0) > 0 || (lines[index]?.motorMiles ?? 0) > 0 ? delta : 0), 0);
const totalMiles = deltas.reduce((sum, delta) => sum + delta, 0);
const sailMiles = Math.max(0, totalMiles - motorMiles);
const firstTime = parseLogTimeMinutes(lines[0]?.time ?? "");
const lastTime = parseLogTimeMinutes(lines.at(-1)?.time ?? "");
const durationMinutes = firstTime === undefined || lastTime === undefined ? null : lastTime >= firstTime ? lastTime - firstTime : lastTime + 24 * 60 - firstTime;
return { motorMiles, sailMiles, totalMiles, durationMinutes };
}

export function formatLogSheetDuration(durationMinutes: number | null | undefined) {
if (durationMinutes == null) return "—";
const safeMinutes = Math.max(0, Math.round(durationMinutes));
const hours = Math.floor(safeMinutes / 60);
const remainingMinutes = safeMinutes % 60;
return `${hours}h ${remainingMinutes.toString().padStart(2, "0")}m`;
}

function parseLogTimeMinutes(time: string) {
const match = time.match(/^(\d{1,2}):(\d{2})/);
if (!match) return undefined;
const hours = Number.parseInt(match[1], 10);
const minutes = Number.parseInt(match[2], 10);
if (!Number.isFinite(hours) || !Number.isFinite(minutes)) return undefined;
return hours * 60 + minutes;
}
79 changes: 79 additions & 0 deletions app/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -1226,3 +1226,82 @@ img.entity-image--preview {
.pagination-buttons button { min-height: auto; border: 1px solid var(--border); border-radius: 0.65rem; padding: 0.4rem 0.65rem; background: white; color: var(--foreground); font-weight: 800; }
.pagination-buttons button.active { border-color: var(--primary); background: rgba(15, 107, 143, 0.12); color: var(--primary); }
.pagination-buttons button:disabled { cursor: not-allowed; opacity: 0.45; }

.share-logsheet-modal {
position: fixed;
inset: 0;
z-index: 70;
display: grid;
place-items: center;
padding: 1rem;
overflow: auto;
background: rgba(12, 24, 38, 0.72);
}

.share-logsheet-panel {
display: grid;
gap: 1.1rem;
width: min(100%, 38rem);
max-height: calc(100dvh - 2rem);
border-radius: 1.5rem;
padding: clamp(1rem, 2vw, 1.5rem);
overflow: auto;
background: var(--card);
box-shadow: var(--shadow);
}

.share-logsheet-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
}

.share-logsheet-heading h2,
.share-logsheet-url p {
margin: 0;
}

.share-logsheet-url {
display: grid;
gap: 0.35rem;
padding-bottom: 1rem;
border-bottom: 1px solid var(--border);
overflow-wrap: anywhere;
}

.share-logsheet-url span,
.share-logsheet-options legend {
font-weight: 900;
}

.share-logsheet-options {
display: grid;
gap: 0.9rem;
min-width: 0;
margin: 0;
padding: 0;
border: 0;
}

.share-logsheet-options legend {
padding-bottom: 0.25rem;
}

.share-logsheet-option {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 0.35rem;
padding-bottom: 0.85rem;
border-bottom: 1px solid var(--border);
}

.share-logsheet-option:last-child {
padding-bottom: 0;
border-bottom: 0;
}

.share-logsheet-option select {
width: 100%;
min-height: 2.75rem;
}
Loading
Loading