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

89.52% Statements 94/105
86.11% Branches 93/108
96.66% Functions 29/30
89.21% Lines 91/102

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 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617                                                                                                                  3x   15x 60x                       119x 44x   75x     3x 3x             3x     3x     118x                                               9x 6x   3x 3x                       10x     10x         10x 10x   4x       5x       1x                   103x                                   164x                                                 3x                             55x 55x 55x 55x 55x     2x 2x       2x 2x 2x 2x 2x             2x 1x 1x 1x               2x       55x           8x 8x                       2x                         119x 119x 119x     119x 119x 119x 119x 119x 119x 119x 119x 119x   119x             3x 3x 3x 3x 3x                 3x 2x 1x   1x 1x                     450x 450x 450x 119x 119x 119x   119x     119x   119x           4x 4x                                                                                                                                                             1x 1x         42x                                                                     18x         112x                                                                               81x         121x                                               3x                             448x   122x                                                                         3x                  
// Setting or changing the maintenance charge or one financing charge
// (Design canvas: VastikeMuutos, VastikeEnsimmainen, VastikePeru,
// RahoitusMuutos): the new amount, its start date, the difference and its
// effect on that year, the history, and undoing the latest change, which
// removes a financing charge with its only amount. A financing charge's form
// also renames it and ends it (spec: "Setting a charge", "Undoing the latest
// charge change", "Renaming a financing charge", "Ending 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 MuiTextField from '@mui/material/TextField'
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 { TextField } from '#/components/form/TextField'
import { clientLog } from '#/lib/client-log'
import { parseFiDate } from '#/lib/dates'
import { parseDecimal } from '#/lib/decimal'
import {
  formatDate,
  formatMoney,
  formatMoneyChange,
  formatPercentChange,
} from '#/lib/format'
import { failureReason } from '#/lib/network-error'
import { reasonText, type AlertReason, type FieldReason } from '#/lib/reasons'
import { m } from '#/paraglide/messages.js'
import type { RecurringAmountKind } from '#/server/db/schema'
import { colors, radii } from '#/theme/tokens'
import {
  renameFinancingCharge,
  setRecurringAmount,
  undoRecurringAmount,
} from './functions'
import { chargeLabel, type SingleKind } from './labels'
import { isEnded, periodOn, yearEffect, type Period } from './periods'
import type { FinancingCharge } from './recurring-amount.repository.server'
import type { RecurringAmountsView } from './recurring-amounts.server'
import { financingChargeName, monthStartDate, typedAmount } from './schemas'
import { UndoButton, UndoDialog } from './UndoDialog'
 
interface Props {
  propertyId: string
  /** The maintenance charge, or one of the financing charges. */
  what: SingleKind | FinancingCharge
  view: RecurringAmountsView
  address: string
  /** After saving or undoing: reload and go back to the page. */
  onDone: () => Promise<void>
  onClose: () => void
}
 
const titles: Record<SingleKind, { set: () => string; change: () => string }> =
  {
    maintenance_charge: {
      set: () => m.amounts_form_set_maintenance_charge(),
      change: () => m.amounts_form_change_maintenance_charge(),
    },
  }
 
/**
 * The form's title: "Set …" before the first amount, then "Change …"; a
 * financing charge's name.
 */
export function amountFormTitle(
  what: SingleKind | FinancingCharge,
  set: boolean,
) {
  if (typeof what !== 'string') {
    return chargeLabel(what)
  }
  return set ? titles[what].change() : titles[what].set()
}
 
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>
  )
}
 
type Target = 'rental_income' | 'expenses' | 'acquisition_cost' | undefined
 
/** What a change of this kind adds to or takes from, from a date. */
function targetOf(
  kind: RecurringAmountKind,
  view: RecurringAmountsView,
  from: string,
): Target {
  if (kind === 'maintenance_charge') {
    return 'expenses'
  }
  const treatment = periodOn(view.treatments, from)?.value
  return treatment === 'capitalised'
    ? 'acquisition_cost'
    : treatment === 'income_recognised'
      ? 'expenses'
      : undefined
}
 
/** "In 2027, deductible expenses go up by €144.00 over 12 months". */
export function effectText(
  target: Target,
  effect: { year: number; months: number; total: number },
) {
  Iif (target === undefined || effect.total === 0) {
    return m.amounts_effect_neutral()
  }
  const params = {
    year: String(effect.year),
    amount: formatMoney(Math.abs(effect.total)),
    months: effect.months,
  }
  const up = effect.total > 0
  switch (target) {
    case 'rental_income':
      return up
        ? m.amounts_effect_rent_up(params)
        : m.amounts_effect_rent_down(params)
    case 'expenses':
      return up
        ? m.amounts_effect_expense_up(params)
        : m.amounts_effect_expense_down(params)
    case 'acquisition_cost':
      return up
        ? m.amounts_effect_acquisition_up(params)
        : m.amounts_effect_acquisition_down(params)
  }
}
 
function History(props: {
  periods: readonly Period<number>[]
  onUndo: () => void
}) {
  return (
    <Stack component="section" sx={{ gap: 0.75 }}>
      <Typography variant="h4" component="h2" sx={{ fontWeight: 900 }}>
        {m.amounts_form_history()}
      </Typography>
      <Box
        component="ul"
        aria-label={m.amounts_form_history()}
        sx={{
          listStyle: 'none',
          m: 0,
          px: 2,
          bgcolor: 'background.paper',
          border: `1px solid ${colors.cardBorder}`,
          borderRadius: `${String(radii.card)}px`,
        }}
      >
        {[...props.periods].reverse().map((p) => (
          <Box
            component="li"
            key={p.validFrom}
            sx={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              minHeight: 52,
              '& + &': { borderTop: `1px solid ${colors.divider}` },
            }}
          >
            <Typography component="span" sx={{ fontWeight: 800 }}>
              {m.amounts_from({ date: formatDate(p.validFrom) })}
            </Typography>
            <Typography component="span" sx={{ fontWeight: 900 }}>
              {formatMoney(p.value)}
            </Typography>
          </Box>
        ))}
      </Box>
      <UndoButton onClick={props.onUndo} />
    </Stack>
  )
}
 
const NAME_REASONS = [
  'financing_charge_name_required',
  'financing_charge_name_too_long',
  'financing_charge_name_taken',
] as const
 
/**
 * A financing charge's name, saved on its own: a name is not a period, so it
 * changes without a date (spec: "Renaming a financing charge").
 */
function ChargeName(props: {
  propertyId: string
  charge: FinancingCharge
  onDone: () => Promise<void>
}) {
  const [name, setName] = useState(props.charge.name ?? '')
  const [reason, setReason] = useState<FieldReason>()
  const [alert, setAlert] = useState<AlertReason>()
  const [saving, setSaving] = useState(false)
  const changed = name.trim() !== (props.charge.name ?? '')
 
  async function save() {
    const parsed = financingChargeName.safeParse(name)
    Iif (!parsed.success) {
      setReason(parsed.error.issues[0]?.message as FieldReason)
      return
    }
    setReason(undefined)
    setAlert(undefined)
    setSaving(true)
    try {
      const result = await renameFinancingCharge({
        data: {
          propertyId: props.propertyId,
          chargeId: props.charge.id,
          name: parsed.data,
        },
      })
      if (result.ok) {
        await props.onDone()
      } else if (isIn(NAME_REASONS, result.reason)) {
        setReason(result.reason)
      } else E{
        setAlert(result.reason as AlertReason)
      }
    } catch (error) {
      clientLog.error('financing_charge.rename_failed', {}, error)
      setAlert(failureReason(error))
    } finally {
      setSaving(false)
    }
  }
 
  return (
    <Stack sx={{ gap: 1 }}>
      <MuiTextField
        label={m.amounts_charge_form_name()}
        value={name}
        onChange={(e) => {
          setName(e.target.value)
          setReason(undefined)
        }}
        error={reason !== undefined}
        helperText={reason === undefined ? undefined : reasonText(reason).text}
        disabled={saving}
        slotProps={{ htmlInput: { maxLength: 60 } }}
      />
      {changed ? (
        <Button
          variant="outlined"
          loading={saving}
          onClick={() => {
            void save()
          }}
          sx={{ alignSelf: 'flex-start', minHeight: 44, borderRadius: 999 }}
        >
          {m.amounts_charge_rename_save()}
        </Button>
      ) : null}
      {alert === undefined ? null : <ReasonAlert reason={alert} />}
    </Stack>
  )
}
 
export function AmountForm(props: Props) {
  const { what, view, propertyId } = props
  const charge = typeof what === 'string' ? undefined : what
  const kind: RecurringAmountKind = charge
    ? 'financing_charge'
    : (what as SingleKind)
  const chargeId = charge?.id
  const periods = charge ? charge.periods : view.amounts[what as SingleKind]
  const latest = periods.at(-1)
  const previous = periods.at(-2)
  const ended = charge !== undefined && isEnded(charge.periods, view.today)
  const [alert, setAlert] = useState<AlertReason>()
  const [amountReason, setAmountReason] = useState<FieldReason>()
  const [dateReason, setDateReason] = useState<FieldReason>()
  const [undoing, setUndoing] = useState(false)
 
  const form = useForm({
    defaultValues: {
      change: 'amount' as 'amount' | 'end',
      amount: '',
      from: '',
    },
    onSubmit: async ({ value }) => {
      setAlert(undefined)
      setAmountReason(undefined)
      setDateReason(undefined)
      try {
        const result = await setRecurringAmount({
          data: {
            propertyId,
            kind,
            chargeId,
            amount: value.amount,
            from: value.from,
          },
        })
        if (result.ok) {
          await props.onDone()
        } else Iif (isIn(AMOUNT_REASONS, result.reason)) {
          setAmountReason(result.reason)
        } else if (isIn(DATE_REASONS, result.reason)) {
          setDateReason(result.reason)
        } else E{
          setAlert(result.reason as AlertReason)
        }
      } catch (error) {
        clientLog.error('recurring_amount.save_failed', {}, error)
        setAlert(failureReason(error))
      }
    },
  })
 
  const ending = useSelector(form.store, (s) => s.values.change === 'end')
  const amountText = useSelector(form.store, (s) => s.values.amount)
  const fromText = useSelector(form.store, (s) => s.values.from)
  const newCents = parseDecimal(amountText, 2)
  const from = parseFiDate(fromText)
  const latestIsUpcoming = latest !== undefined && latest.validFrom > view.today
  const effect =
    latest !== undefined && newCents !== undefined && from?.endsWith('-01')
      ? yearEffect(latest.value, newCents, from)
      : undefined
  const target = from === undefined ? undefined : targetOf(kind, view, from)
 
  return (
    <Stack
      component="form"
      noValidate
      aria-labelledby="amount-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="amount-form-title"
            variant="h3"
            component="h1"
            sx={{ fontSize: 18, textAlign: 'center' }}
          >
            {amountFormTitle(what, latest !== undefined)}
          </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 }}
      >
        {charge ? (
          <ChargeName
            propertyId={propertyId}
            charge={charge}
            onDone={props.onDone}
          />
        ) : null}
        {ended ? (
          <Typography sx={{ fontWeight: 700 }}>
            {m.amounts_charge_ended_note()}
          </Typography>
        ) : (
          <>
            {latest ? (
              <Box
                sx={{
                  bgcolor: 'background.paper',
                  border: `1px solid ${colors.cardBorder}`,
                  borderRadius: `${String(radii.input)}px`,
                  px: 1.75,
                  py: 1.5,
                }}
              >
                <Typography
                  variant="body2"
                  sx={{ fontWeight: 800 }}
                  color="text.secondary"
                >
                  {latestIsUpcoming
                    ? m.amounts_form_latest_upcoming()
                    : m.amounts_form_current()}
                </Typography>
                <Typography sx={{ fontSize: 22, fontWeight: 900 }}>
                  {m.amounts_per_month({ amount: formatMoney(latest.value) })}
                </Typography>
              </Box>
            ) : null}
            {charge && latest ? (
              <form.Field
                name="change"
                listeners={{
                  onChange: ({ value }) => {
                    // Ending sets 0 from the date; the amount field is hidden.
                    form.setFieldValue('amount', value === 'end' ? '0' : '')
                    setAmountReason(undefined)
                  },
                }}
              >
                {(field) => (
                  <ChoiceField
                    field={field}
                    label={m.amounts_charge_choice()}
                    choices={[
                      {
                        value: 'amount',
                        label: m.amounts_charge_change_amount(),
                      },
                      { value: 'end', label: m.amounts_charge_end() },
                    ]}
                  />
                )}
              </form.Field>
            ) : null}
            {ending ? (
              <Box
                sx={{
                  bgcolor: colors.yellowTint,
                  borderRadius: `${String(radii.input)}px`,
                  px: 1.75,
                  py: 1.5,
                  fontSize: 13,
                  fontWeight: 700,
                  lineHeight: 1.4,
                }}
              >
                {m.amounts_charge_end_note()}
              </Box>
            ) : (
              <>
                <form.Field
                  name="amount"
                  validators={{ onChange: typedAmount }}
                  listeners={{
                    onChange: () => {
                      setAmountReason(undefined)
                    },
                  }}
                >
                  {(field) => (
                    <TextField
                      field={field}
                      reason={amountReason}
                      label={
                        latest ? m.amounts_form_new() : m.amounts_form_amount()
                      }
                      slotProps={{ htmlInput: { inputMode: 'decimal' } }}
                    />
                  )}
                </form.Field>
                {effect ? (
                  <Box
                    role="status"
                    sx={{
                      bgcolor: colors.yellowTint,
                      borderRadius: `${String(radii.input)}px`,
                      px: 1.75,
                      py: 1.5,
                    }}
                  >
                    <Typography sx={{ fontWeight: 900 }}>
                      {m.amounts_per_month({
                        amount: formatMoneyChange(effect.difference),
                      })}
                      {effect.percent === undefined
                        ? ''
                        : ` (${formatPercentChange(effect.percent)})`}
                    </Typography>
                    <Typography variant="body2" sx={{ fontWeight: 700 }}>
                      {effectText(target, effect)}
                    </Typography>
                  </Box>
                ) : null}
              </>
            )}
            <form.Field
              name="from"
              validators={{ onChange: monthStartDate }}
              listeners={{
                onChange: () => {
                  setDateReason(undefined)
                },
              }}
            >
              {(field) => (
                <TextField
                  field={field}
                  reason={dateReason}
                  label={
                    ending ? m.amounts_charge_end_from() : m.amounts_form_from()
                  }
                  placeholder={m.date_placeholder()}
                />
              )}
            </form.Field>
            <Typography variant="body2" color="text.secondary" sx={{ mt: -1 }}>
              {ending
                ? m.amounts_charge_end_hint()
                : latest === undefined
                  ? m.amounts_form_hint_first()
                  : m.amounts_form_hint_charge()}
            </Typography>
          </>
        )}
        {alert === undefined ? null : <ReasonAlert reason={alert} />}
        {latest ? (
          <History
            periods={periods}
            onUndo={() => {
              setUndoing(true)
            }}
          />
        ) : null}
      </Stack>
      {ended ? null : (
        <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()
                  : ending
                    ? m.amounts_charge_end_save()
                    : latest
                      ? m.amounts_form_save_change()
                      : m.amounts_form_save_first()}
              </Button>
            )}
          </form.Subscribe>
        </Box>
      )}
      {latest ? (
        <UndoDialog
          open={undoing}
          onClose={() => {
            setUndoing(false)
          }}
          title={m.amounts_undo_title({ date: formatDate(latest.validFrom) })}
          text={
            previous
              ? m.amounts_undo_text({
                  amount: formatMoney(previous.value),
                  date: formatDate(previous.validFrom),
                })
              : charge
                ? m.amounts_undo_remove_charge_text()
                : m.amounts_undo_only_text()
          }
          undo={() =>
            undoRecurringAmount({ data: { propertyId, kind, chargeId } })
          }
          failureEvent="recurring_amount.undo_failed"
          onDone={props.onDone}
        />
      ) : null}
    </Stack>
  )
}