All files / src/features/documents DocumentForm.tsx

79.76% Statements 67/84
80.35% Branches 45/56
95% Functions 19/20
79.01% Lines 64/81

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344                                                                                              2x                 2x       6x       14x 14x       42x 42x     42x 42x     42x 42x 23x     42x   42x   42x 2x 2x 1x   1x       42x               4x 4x 4x 4x       4x 4x               4x       4x 4x             4x 1x     1x 1x 1x         3x 3x 15x   3x 3x   3x 3x 1x 1x   2x                       189x 189x   42x           5x 5x                                                                                                 40x       200x                   7x         14x                             16x         41x                               40x                             7x 7x 7x 7x 6x 6x 6x       1x                                                                            
// Adding or editing a document (Design canvas: "Lisää dokumentti", "Muokkaa
// dokumenttia"): the file (when adding), kind, name, date and, for a lease,
// its tenancy (openspec: documents, "Adding a document", "Editing a
// document"). Adding sends the file with the fields as form data.
import Box from '@mui/material/Box'
import Button from '@mui/material/Button'
import IconButton from '@mui/material/IconButton'
import Stack from '@mui/material/Stack'
import Typography from '@mui/material/Typography'
import { useForm, useSelector } from '@tanstack/react-form'
import { useState } from 'react'
import { ReasonAlert } from '#/components/ReasonAlert'
import { ChoiceField } from '#/components/form/ChoiceField'
import { FileField } from '#/components/form/FileField'
import { TextField } from '#/components/form/TextField'
import { clientLog } from '#/lib/client-log'
import { parseFiDate, type IsoDate } from '#/lib/dates'
import { formatDate } from '#/lib/format'
import { failureReason } from '#/lib/network-error'
import type { AlertReason, FieldReason } from '#/lib/reasons'
import { ImageProblem, prepareUpload } from '#/lib/resize-image'
import { m } from '#/paraglide/messages.js'
import type { DocumentKind } from '#/server/db/schema'
import type { DocumentDetails } from './document.repository.server'
import type { TenancyChoice } from './documents.server'
import { addDocument, updateDocument } from './functions'
import { DOCUMENT_KINDS, kindLabel } from './kinds'
import { documentFields } from './schemas'
 
interface Props {
  propertyId: string
  streetAddress: string
  tenancies: readonly TenancyChoice[]
  today: IsoDate
  /** Adding: the kind to start with, e.g. a lease from the Tenancy page. */
  defaultKind?: DocumentKind
  /** Adding: the tenancy to start with, one of `tenancies`. */
  defaultTenancyId?: string
  /** The document being edited; without it the form adds one. */
  editing?: DocumentDetails
  onClose: () => void
  /** After saving: reload and show the document. */
  onSaved: (documentId: string) => Promise<void>
}
 
type FieldName = 'file' | 'name' | 'date'
 
const FIELD_OF: Partial<Record<FieldReason, FieldName>> = {
  document_unsupported_type: 'file',
  document_too_large: 'file',
  document_unreadable: 'file',
  document_name_required: 'name',
  document_name_too_long: 'name',
  date_invalid: 'date',
}
 
const NO_TENANCY = ''
 
/** The file's name without its extension. */
function nameOf(file: File): string {
  return file.name.replace(/\.[^.]*$/, '')
}
 
function tenancyLabel(tenancy: TenancyChoice): string {
  const to = tenancy.validTo ? formatDate(tenancy.validTo) : ''
  return `${tenancy.tenantName} · ${formatDate(tenancy.validFrom)}–${to}`
}
 
export function DocumentForm(props: Props) {
  const editing = props.editing
  const [file, setFile] = useState<File>()
  // The name suggested from the chosen file, replaced while the user hasn't
  // typed their own.
  const [suggested, setSuggested] = useState('')
  const [reasons, setReasons] = useState<
    Partial<Record<FieldName, FieldReason>>
  >({})
  const [alert, setAlert] = useState<AlertReason>()
  const clearReason = (name: FieldName) => {
    setReasons((current) => ({ ...current, [name]: undefined }))
  }
  // The current tenancy is first and preselected for a new lease.
  const currentTenancyId = props.tenancies.at(0)?.id
  const defaultTenancy =
    props.defaultTenancyId ?? currentTenancyId ?? NO_TENANCY
 
  const showReason = (reason: FieldReason | AlertReason) => {
    const field = FIELD_OF[reason as FieldReason]
    if (field) {
      setReasons({ [field]: reason as FieldReason })
    } else {
      setAlert(reason as AlertReason)
    }
  }
 
  const form = useForm({
    defaultValues: {
      kind: editing?.kind ?? props.defaultKind ?? 'other',
      name: editing?.name ?? '',
      date: formatDate(editing?.date ?? props.today),
      tenancyId: editing ? (editing.tenancyId ?? NO_TENANCY) : defaultTenancy,
    },
    onSubmit: async ({ value }) => {
      setAlert(undefined)
      setReasons({})
      const date = parseFiDate(value.date)
      Iif (date === undefined) {
        setReasons({ date: 'date_invalid' })
        return
      }
      const parsed = documentFields.safeParse({ ...value, date: value.date })
      Iif (!parsed.success) {
        const reason = parsed.error.issues[0]?.message as FieldReason
        const field = FIELD_OF[reason]
        if (field) {
          setReasons({ [field]: reason })
        }
        return
      }
      Iif (!editing && !file) {
        setReasons({ file: 'document_unsupported_type' })
        return
      }
      try {
        const fields = {
          propertyId: props.propertyId,
          kind: value.kind,
          name: value.name,
          date: value.date,
          tenancyId: value.kind === 'lease' ? value.tenancyId : '',
        }
        if (editing) {
          const result = await updateDocument({
            data: { ...fields, documentId: editing.id },
          })
          Eif (result.ok) {
            await props.onSaved(editing.id)
            return
          }
          showReason(result.reason)
          return
        }
        const data = new FormData()
        for (const [key, text] of Object.entries(fields)) {
          data.set(key, text)
        }
        Eif (file) {
          data.set('file', await prepareUpload(file))
        }
        const result = await addDocument({ data })
        if (result.ok) {
          await props.onSaved(result.documentId)
          return
        }
        showReason(result.reason)
      } catch (error) {
        if (error instanceof ImageProblem) {
          setReasons({ file: `document_${error.problem}` })
          return
        }
        clientLog.error('document.save_failed', {}, error)
        setAlert(failureReason(error))
      }
    },
  })
 
  const kind = useSelector(form.store, (s) => s.values.kind)
  const submitting = useSelector(form.store, (s) => s.isSubmitting)
 
  return (
    <Stack
      component="form"
      noValidate
      aria-labelledby="document-form-title"
      onSubmit={(e) => {
        e.preventDefault()
        void form.handleSubmit()
      }}
      sx={{ minHeight: '100dvh' }}
    >
      <Box
        component="header"
        sx={{
          display: 'grid',
          gridTemplateColumns: '44px 1fr 44px',
          alignItems: 'center',
          px: 1.5,
          pt: 2,
          pb: 0.5,
        }}
      >
        <IconButton aria-label={m.documents_close()} onClick={props.onClose}>
          <svg
            width="22"
            height="22"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2.6"
            strokeLinecap="round"
            aria-hidden="true"
          >
            <path d="M6 6 L18 18 M18 6 L6 18" />
          </svg>
        </IconButton>
        <Stack sx={{ alignItems: 'center', minWidth: 0 }}>
          <Typography
            id="document-form-title"
            variant="h3"
            component="h1"
            sx={{ fontSize: 18 }}
          >
            {editing ? m.documents_edit_title() : m.documents_new()}
          </Typography>
          <Typography variant="body2" color="text.secondary" noWrap>
            {props.streetAddress}
          </Typography>
        </Stack>
      </Box>
      <Stack
        component="main"
        sx={{ flex: 1, gap: 1.75, px: 2.5, pt: 1, pb: 2.5 }}
      >
        <form.Field name="kind">
          {(field) => (
            <ChoiceField
              field={field}
              label={m.documents_kind()}
              wrap
              choices={DOCUMENT_KINDS.map((value) => ({
                value,
                label: kindLabel[value](),
              }))}
            />
          )}
        </form.Field>
        {kind === 'lease' && props.tenancies.length > 0 ? (
          <form.Field name="tenancyId">
            {(field) => (
              <ChoiceField
                field={field}
                label={m.documents_tenancy()}
                stacked
                choices={[
                  ...props.tenancies.map((tenancy) => ({
                    value: tenancy.id,
                    label: tenancyLabel(tenancy),
                  })),
                  { value: NO_TENANCY, label: m.documents_no_tenancy() },
                ]}
              />
            )}
          </form.Field>
        ) : null}
        <form.Field
          name="name"
          validators={{ onChange: documentFields.shape.name }}
          listeners={{
            onChange: () => {
              clearReason('name')
            },
          }}
        >
          {(field) => (
            <TextField
              field={field}
              reason={reasons.name}
              label={m.documents_name()}
            />
          )}
        </form.Field>
        <form.Field
          name="date"
          listeners={{
            onChange: () => {
              clearReason('date')
            },
          }}
        >
          {(field) => (
            <TextField
              field={field}
              reason={reasons.date}
              label={m.documents_date()}
              placeholder={m.date_placeholder()}
            />
          )}
        </form.Field>
        {editing ? null : (
          <FileField
            title={m.documents_file()}
            file={file}
            reason={reasons.file}
            submitting={submitting}
            onChoose={(chosen) => {
              setFile(chosen)
              clearReason('file')
              const current = form.getFieldValue('name')
              if (current === '' || current === suggested) {
                const next = nameOf(chosen)
                setSuggested(next)
                form.setFieldValue('name', next)
              }
            }}
            onRemove={() => {
              setFile(undefined)
            }}
            labels={{
              attach: m.documents_attach(),
              hint: m.documents_attach_hint(),
              saving: m.documents_saving(),
              remove: m.documents_remove_file(),
              replace: m.documents_attach(),
            }}
          />
        )}
        {alert === undefined ? null : <ReasonAlert reason={alert} />}
      </Stack>
      <Stack
        component="footer"
        sx={{
          position: 'sticky',
          bottom: 0,
          px: 2.5,
          pt: 1.5,
          pb: 3.5,
          bgcolor: 'background.default',
          borderTop: '1px solid',
          borderColor: 'divider',
        }}
      >
        <Button
          type="submit"
          variant="contained"
          disabled={submitting}
          sx={{ minHeight: 56, borderRadius: 999, fontSize: 17 }}
        >
          {submitting ? m.documents_saving() : m.documents_save()}
        </Button>
      </Stack>
    </Stack>
  )
}