All files / src/features/recurring-amounts FinancingChargeForm.tsx

82.92% Statements 34/41
57.14% Branches 8/14
100% Functions 13/13
82.92% Lines 34/41

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                                                                  2x         2x 2x             2x     1x     5x                                 5x 5x 5x 5x 5x 5x   5x     2x 2x 2x 2x 2x 2x               2x 1x 1x 1x                             5x           2x 2x                                                                                       22x         29x                               4x         11x                         20x         27x                                                                               171x   8x                                  
// Adding a financing charge (Design canvas: RahoitusUusi): its name, monthly
// amount and start date, and a note that the flat's treatment applies to it
// too (spec: "Adding a financing charge").
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 } from '@tanstack/react-form'
import { useState } from 'react'
import { ReasonAlert } from '#/components/ReasonAlert'
import { TextField } from '#/components/form/TextField'
import { clientLog } from '#/lib/client-log'
import { formatDate } from '#/lib/format'
import { failureReason } from '#/lib/network-error'
import type { AlertReason, FieldReason } from '#/lib/reasons'
import { m } from '#/paraglide/messages.js'
import { colors, radii } from '#/theme/tokens'
import { addFinancingCharge } from './functions'
import { treatmentLabel } from './labels'
import { periodOn } from './periods'
import type { RecurringAmountsView } from './recurring-amounts.server'
import { financingChargeName, monthStartDate, typedAmount } from './schemas'
 
interface Props {
  propertyId: string
  view: RecurringAmountsView
  address: string
  /** After adding: reload and go back to the page. */
  onDone: () => Promise<void>
  onClose: () => void
}
 
const NAME_REASONS = [
  'financing_charge_name_required',
  'financing_charge_name_too_long',
  'financing_charge_name_taken',
] as const
const AMOUNT_REASONS = ['amount_invalid'] as const
const DATE_REASONS = [
  'date_invalid',
  'amount_date_not_month_start',
  'amount_date_before_ownership',
  'amount_date_too_early',
] as const
 
const isIn = <T extends string>(
  list: readonly T[],
  value: string,
): value is T => (list as readonly string[]).includes(value)
 
function CloseIcon() {
  return (
    <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>
  )
}
 
export function FinancingChargeForm(props: Props) {
  const { view, propertyId } = props
  const [alert, setAlert] = useState<AlertReason>()
  const [nameReason, setNameReason] = useState<FieldReason>()
  const [amountReason, setAmountReason] = useState<FieldReason>()
  const [dateReason, setDateReason] = useState<FieldReason>()
  const treatment = periodOn(view.treatments, view.today)
 
  const form = useForm({
    defaultValues: { name: '', amount: '', from: '' },
    onSubmit: async ({ value }) => {
      setAlert(undefined)
      setNameReason(undefined)
      setAmountReason(undefined)
      setDateReason(undefined)
      try {
        const result = await addFinancingCharge({
          data: {
            propertyId,
            name: value.name,
            amount: value.amount,
            from: value.from,
          },
        })
        if (result.ok) {
          await props.onDone()
        } else if (isIn(NAME_REASONS, result.reason)) {
          setNameReason(result.reason)
        } else Eif (isIn(AMOUNT_REASONS, result.reason)) {
          setAmountReason(result.reason)
        } else if (isIn(DATE_REASONS, result.reason)) {
          setDateReason(result.reason)
        } else {
          setAlert(result.reason as AlertReason)
        }
      } catch (error) {
        clientLog.error('financing_charge.add_failed', {}, error)
        setAlert(failureReason(error))
      }
    },
  })
 
  return (
    <Stack
      component="form"
      noValidate
      aria-labelledby="charge-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.amounts_form_close()} onClick={props.onClose}>
          <CloseIcon />
        </IconButton>
        <Stack sx={{ alignItems: 'center', minWidth: 0 }}>
          <Typography
            id="charge-form-title"
            variant="h3"
            component="h1"
            sx={{ fontSize: 18, textAlign: 'center' }}
          >
            {m.amounts_financing_add()}
          </Typography>
          <Typography variant="body2" color="text.secondary" noWrap>
            {props.address}
          </Typography>
        </Stack>
      </Box>
      <Stack
        component="main"
        sx={{ flex: 1, gap: 2, px: 2.5, pt: 1.25, pb: 2.5 }}
      >
        <Typography sx={{ fontWeight: 700, lineHeight: 1.45 }}>
          {m.amounts_charge_form_intro()}
        </Typography>
        <form.Field
          name="name"
          validators={{ onChange: financingChargeName }}
          listeners={{
            onChange: () => {
              setNameReason(undefined)
            },
          }}
        >
          {(field) => (
            <TextField
              field={field}
              reason={nameReason}
              label={m.amounts_charge_form_name()}
              slotProps={{ htmlInput: { maxLength: 60 } }}
            />
          )}
        </form.Field>
        <Typography variant="body2" color="text.secondary" sx={{ mt: -1 }}>
          {m.amounts_charge_form_name_hint()}
        </Typography>
        <form.Field
          name="amount"
          validators={{ onChange: typedAmount }}
          listeners={{
            onChange: () => {
              setAmountReason(undefined)
            },
          }}
        >
          {(field) => (
            <TextField
              field={field}
              reason={amountReason}
              label={m.amounts_form_amount()}
              slotProps={{ htmlInput: { inputMode: 'decimal' } }}
            />
          )}
        </form.Field>
        <form.Field
          name="from"
          validators={{ onChange: monthStartDate }}
          listeners={{
            onChange: () => {
              setDateReason(undefined)
            },
          }}
        >
          {(field) => (
            <TextField
              field={field}
              reason={dateReason}
              label={m.amounts_form_from()}
              placeholder={m.date_placeholder()}
            />
          )}
        </form.Field>
        <Typography variant="body2" color="text.secondary" sx={{ mt: -1 }}>
          {m.amounts_charge_form_from_hint()}
        </Typography>
        <Box
          sx={{
            bgcolor: colors.lavenderTint,
            borderRadius: `${String(radii.input)}px`,
            px: 1.75,
            py: 1.5,
            fontSize: 13,
            fontWeight: 700,
            lineHeight: 1.4,
          }}
        >
          {treatment
            ? m.amounts_charge_form_treatment({
                treatment: treatmentLabel[treatment.value](),
                date: formatDate(treatment.validFrom),
              })
            : m.amounts_charge_form_treatment_not_set()}
        </Box>
        {alert === undefined ? null : <ReasonAlert reason={alert} />}
      </Stack>
      <Box
        component="footer"
        sx={{
          px: 2.5,
          pt: 1.5,
          pb: 3.5,
          borderTop: `1px solid ${colors.cardBorder}`,
        }}
      >
        <form.Subscribe selector={(s) => s.isSubmitting}>
          {(submitting) => (
            <Button
              type="submit"
              fullWidth
              loading={submitting}
              loadingPosition="start"
              sx={{ minHeight: 56 }}
            >
              {submitting
                ? m.amounts_form_saving()
                : m.amounts_charge_form_save()}
            </Button>
          )}
        </form.Subscribe>
      </Box>
    </Stack>
  )
}