190 lines
6.3 KiB
TypeScript
190 lines
6.3 KiB
TypeScript
import {
|
|
SheetFailure,
|
|
classifySheetError,
|
|
getOfficialSheetAdmin,
|
|
parseSaveAnswer,
|
|
saveSheetDraft,
|
|
submitSheetReview,
|
|
type FaunosteoClient,
|
|
type OfficialSheetAdmin,
|
|
type SheetFailureKind,
|
|
} from '@faunosteo/supabase'
|
|
import { getSupabaseClient } from '@/lib/supabase'
|
|
import { sameDocument } from '../core/sameDocument'
|
|
import { blockKind } from './editorBase'
|
|
import type {
|
|
BlockKind,
|
|
Blocked,
|
|
ConfirmOption,
|
|
ConflictState,
|
|
EditorState,
|
|
SaveOutcome,
|
|
ServerRefusal,
|
|
StoreApi,
|
|
SubmitOutcome,
|
|
} from './editorTypes'
|
|
import { removeCopy } from './recovery'
|
|
|
|
function blocked(kind: BlockKind): Blocked {
|
|
return { ok: false, reason: 'blocked', kind }
|
|
}
|
|
|
|
function requireClient(): FaunosteoClient {
|
|
const client = getSupabaseClient()
|
|
if (!client) throw new SheetFailure('unavailable')
|
|
return client
|
|
}
|
|
|
|
function server(error: unknown): ServerRefusal {
|
|
return { ok: false, reason: 'server', kind: classifySheetError(error) }
|
|
}
|
|
|
|
/** The page's view of the server draft after a `draft_conflict` (plan, C29). */
|
|
function conflictFrom(admin: OfficialSheetAdmin, state: EditorState): ConflictState {
|
|
const draft = admin.draft_version
|
|
if (!draft || draft.version_id !== state.versionId) return { status: 'unknown' }
|
|
const last = admin.draft_last_save
|
|
if (!last || last.revision !== draft.revision) {
|
|
return { status: 'known', revision: draft.revision, lastSave: null }
|
|
}
|
|
const byCaller = last.saved_by !== null && last.saved_by.user_id === state.userId
|
|
const lastSave = { savedAt: last.saved_at, savedBy: last.saved_by, byCaller }
|
|
return { status: 'known', revision: draft.revision, lastSave }
|
|
}
|
|
|
|
/** Reads the conflict; a failed read or an unparsable answer is the `unknown` variant. */
|
|
export async function readConflict(api: StoreApi, session: number): Promise<void> {
|
|
const state = api.get()
|
|
const reading: ConflictState = { status: 'reading' }
|
|
api.set({ conflict: reading })
|
|
let next: ConflictState
|
|
try {
|
|
const admin = await getOfficialSheetAdmin(requireClient(), state.sheetId ?? '')
|
|
next = conflictFrom(admin, state)
|
|
} catch {
|
|
next = { status: 'unknown' }
|
|
}
|
|
// A dismissed dialog or a later save replaced the reading state: drop the late answer.
|
|
if (api.get().session === session && api.get().conflict === reading) {
|
|
api.set({ conflict: next })
|
|
}
|
|
}
|
|
|
|
interface Attempt {
|
|
session: number
|
|
sentText: string
|
|
expected: number
|
|
}
|
|
|
|
function applySaved(api: StoreApi, attempt: Attempt, revision: number): SaveOutcome {
|
|
const state = api.get()
|
|
if (state.session !== attempt.session) return blocked('session_changed')
|
|
const unsaved = !sameDocument(state.documentText, attempt.sentText)
|
|
if (!unsaved) removeCopy(state.userId ?? '', state.versionId ?? '')
|
|
api.set({
|
|
saving: false,
|
|
savedText: attempt.sentText,
|
|
savedRevision: revision,
|
|
staleBase: false,
|
|
unsaved,
|
|
conflict: null,
|
|
saveFailure: null,
|
|
...(unsaved ? {} : { copyWritten: false, copyIssue: null }),
|
|
})
|
|
return { ok: true, revision }
|
|
}
|
|
|
|
async function failedSave(
|
|
api: StoreApi,
|
|
attempt: Attempt,
|
|
error: unknown,
|
|
): Promise<SaveOutcome> {
|
|
if (api.get().session !== attempt.session) return blocked('session_changed')
|
|
const kind: SheetFailureKind = classifySheetError(error)
|
|
// Unchanged content: the saved pair is what was sent, at the revision it was sent against.
|
|
if (kind === 'draft.unchanged') return applySaved(api, attempt, attempt.expected)
|
|
api.set({ saving: false, saveFailure: kind })
|
|
if (kind === 'draft_conflict') await readConflict(api, attempt.session)
|
|
return { ok: false, reason: 'server', kind }
|
|
}
|
|
|
|
function saveBlock(state: EditorState): BlockKind | null {
|
|
if (state.saving || state.submitting) return 'busy'
|
|
return blockKind(state)
|
|
}
|
|
|
|
/** Sends `documentText` as of now; commits made while it is in flight stay unsaved. */
|
|
async function saveWith(api: StoreApi, expected: number): Promise<SaveOutcome> {
|
|
const state = api.get()
|
|
const block = saveBlock(state)
|
|
if (block) return blocked(block)
|
|
const attempt = { session: state.session, sentText: state.documentText, expected }
|
|
api.set({ saving: true, saveFailure: null })
|
|
try {
|
|
const args = {
|
|
version_id: state.versionId ?? '',
|
|
expected_revision: expected,
|
|
document: JSON.parse(attempt.sentText),
|
|
}
|
|
const answer = parseSaveAnswer(await saveSheetDraft(requireClient(), args))
|
|
return applySaved(api, attempt, answer.revision)
|
|
} catch (error) {
|
|
return failedSave(api, attempt, error)
|
|
}
|
|
}
|
|
|
|
export function save(api: StoreApi): Promise<SaveOutcome> {
|
|
return saveWith(api, api.get().savedRevision)
|
|
}
|
|
|
|
/** « Garder ma version » (confirmed): saves against N, the server decides at write time. */
|
|
export async function keepMine(
|
|
api: StoreApi,
|
|
{ confirmed }: ConfirmOption,
|
|
): Promise<SaveOutcome> {
|
|
const { conflict } = api.get()
|
|
if (conflict?.status !== 'known') return blocked('revision_unknown')
|
|
if (!confirmed) return blocked('confirmation_required')
|
|
return saveWith(api, conflict.revision)
|
|
}
|
|
|
|
/** Never re-submits by itself: a `draft_conflict` opens the conflict read only. */
|
|
export async function submit(api: StoreApi, note?: string): Promise<SubmitOutcome> {
|
|
const state = api.get()
|
|
const block = saveBlock(state)
|
|
if (block) return blocked(block)
|
|
if (state.staleBase) return blocked('stale_base')
|
|
if (state.unsaved) return blocked('unsaved')
|
|
api.set({ submitting: true })
|
|
try {
|
|
const args = {
|
|
version_id: state.versionId ?? '',
|
|
expected_revision: state.savedRevision,
|
|
...(note ? { note } : {}),
|
|
}
|
|
const reviewId = await submitSheetReview(requireClient(), args)
|
|
if (api.get().session !== state.session) return blocked('session_changed')
|
|
api.set({ submitting: false, canEdit: false })
|
|
return { ok: true, reviewId }
|
|
} catch (error) {
|
|
return failedSubmit(api, state.session, error)
|
|
}
|
|
}
|
|
|
|
async function failedSubmit(
|
|
api: StoreApi,
|
|
session: number,
|
|
error: unknown,
|
|
): Promise<SubmitOutcome> {
|
|
if (api.get().session !== session) return blocked('session_changed')
|
|
api.set({ submitting: false })
|
|
const refusal = server(error)
|
|
if (refusal.kind === 'draft_conflict') await readConflict(api, session)
|
|
return refusal
|
|
}
|
|
|
|
export async function retryConflictRead(api: StoreApi): Promise<void> {
|
|
const { conflict, session } = api.get()
|
|
if (conflict && conflict.status !== 'reading') await readConflict(api, session)
|
|
}
|