All files / src/features/deposits deposit.ts

100% Statements 43/43
100% Branches 48/48
100% Functions 12/12
100% Lines 43/43

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                              7x     7x                                   31x           91x     91x                                   20x 20x 20x 20x 1x   19x 19x 19x   20x                   45x                       7x                                         31x 3x   28x 2x   26x             30x 3x   27x 2x   25x 2x   23x 2x   21x 1x   20x         4x               17x 17x                                     42x 47x                                                         13x 13x 5x   8x 3x             5x        
// A tenancy's deposit and its return (openspec: deposits). Pure: the rent
// kept is allocated to the months with rent missing, the amount returned
// computed, the deadline and the reminder worked out from the dates; nothing
// here is stored.
import { addDays, type IsoDate } from '#/lib/dates'
import { monthOf, type Month } from '#/features/recurring-amounts/periods'
import {
  rentMonth,
  tenancyMonths,
  type AmountsData,
  type PaymentOfMonth,
  type RentTenancy,
} from '#/features/rent-payments/status'
 
/** The days after the contract's end within which a deposit is settled. */
export const RETURN_DAYS = 14
 
/** The most a deposit may be, in months' rent (Act on Residential Leases § 8). */
export const MAX_DEPOSIT_MONTHS = 3
 
/** A month of a tenancy with rent missing. */
export interface MissingMonth {
  month: Month
  /** Cents, above zero. */
  missing: number
}
 
/**
 * The months of the tenancy, from its start to its last rent day, whose
 * payments are less than their expected rent, oldest first. `payments` are
 * the tenancy's payments to count: a correction leaves out the return's own.
 */
export function missingRent(
  tenancy: RentTenancy & { validTo: IsoDate },
  data: AmountsData & { payments: readonly PaymentOfMonth[] },
): MissingMonth[] {
  return tenancyMonths(
    tenancy,
    monthOf(tenancy.validFrom),
    monthOf(tenancy.validTo),
  )
    .map((month) =>
      rentMonth(tenancy, month, { ...data, today: tenancy.validTo }),
    )
    .flatMap((row) =>
      row.missing === undefined || row.missing === 0
        ? []
        : [{ month: row.month, missing: row.missing }],
    )
}
 
export type AllocationResult =
  | { ok: true; payments: { month: Month; amount: number }[] }
  | { ok: false; reason: 'deposit_rent_exceeds_unpaid' }
 
/**
 * Spreads the rent kept over the months with rent missing, oldest first,
 * each up to its missing amount. Refused when it is more than all of them.
 */
export function allocateRentKept(
  months: readonly MissingMonth[],
  kept: number,
): AllocationResult {
  const payments: { month: Month; amount: number }[] = []
  let left = kept
  for (const { month, missing } of months) {
    if (left === 0) {
      break
    }
    const amount = Math.min(left, missing)
    payments.push({ month, amount })
    left -= amount
  }
  return left > 0
    ? { ok: false, reason: 'deposit_rent_exceeds_unpaid' }
    : { ok: true, payments }
}
 
/** What is paid back: the deposit less the amounts kept, in cents. */
export function amountReturned(
  deposit: number,
  kept: { rentKept: number; damageKept: number },
): number {
  return deposit - kept.rentKept - kept.damageKept
}
 
export type ReturnReason =
  | 'deposit_not_set'
  | 'deposit_return_exists'
  | 'deposit_return_before_end'
  | 'deposit_return_date_in_future'
  | 'deposit_kept_exceeds_deposit'
  | 'deposit_kept_required'
  | 'deposit_note_too_long'
 
export const NOTE_MAX = 200
 
export interface ReturnInput {
  deposit: number | null
  /** The tenancy's last rent day; null while it has none. */
  lastRentDay: IsoDate | null
  hasReturn: boolean
  returnedOn: IsoDate
  /** With deductions (*Vähennyksin*): then something has to be kept. */
  deductions: boolean
  rentKept: number
  damageKept: number
  note: string | null
  today: IsoDate
}
 
/**
 * The first rule a new return breaks, or null. Access, the tenancy's
 * existence and the rent missing are checked elsewhere.
 */
export function checkReturn(input: ReturnInput): ReturnReason | null {
  if (input.deposit === null || input.lastRentDay === null) {
    return 'deposit_not_set'
  }
  if (input.hasReturn) {
    return 'deposit_return_exists'
  }
  return checkReturnFields({ ...input, deposit: input.deposit })
}
 
/** The rules a recorded return keeps too, when it is corrected. */
export function checkReturnFields(
  input: Omit<ReturnInput, 'deposit' | 'hasReturn'> & { deposit: number },
): ReturnReason | null {
  if (input.lastRentDay !== null && input.returnedOn < input.lastRentDay) {
    return 'deposit_return_before_end'
  }
  if (input.returnedOn > input.today) {
    return 'deposit_return_date_in_future'
  }
  if (input.rentKept + input.damageKept > input.deposit) {
    return 'deposit_kept_exceeds_deposit'
  }
  if (input.deductions && input.rentKept + input.damageKept === 0) {
    return 'deposit_kept_required'
  }
  if (input.note !== null && input.note.length > NOTE_MAX) {
    return 'deposit_note_too_long'
  }
  return null
}
 
/** The last day to return the deposit or notify its keeping. */
export function returnDeadline(lastRentDay: IsoDate): IsoDate {
  return addDays(lastRentDay, RETURN_DAYS)
}
 
/** The most the law allows, when the deposit is above it; else null. */
export function depositOverLimit(
  deposit: number,
  monthlyRent: number,
): number | null {
  const limit = MAX_DEPOSIT_MONTHS * monthlyRent
  return deposit > limit ? limit : null
}
 
export interface DepositTenancy {
  id: string
  validTo: IsoDate | null
  deposit?: number | null
}
 
/**
 * The tenancies whose deposit is not returned although their last rent day
 * has come: a deposit, no return, a last rent day of today or earlier. In the
 * order given.
 */
export function pendingReturns<T extends DepositTenancy>(
  tenancies: readonly T[],
  returned: ReadonlySet<string>,
  today: IsoDate,
): T[] {
  return tenancies.filter(
    (tenancy) =>
      (tenancy.deposit ?? 0) > 0 &&
      !returned.has(tenancy.id) &&
      tenancy.validTo !== null &&
      tenancy.validTo <= today,
  )
}
 
export type DepositStatus =
  | { kind: 'none' }
  /** A deposit, and the tenancy's last rent day hasn't come. */
  | { kind: 'held'; amount: number }
  | { kind: 'pending'; amount: number }
  | {
      kind: 'returned'
      on: IsoDate
      /** Cents paid back. */
      returned: number
      /** Cents kept, both reasons. */
      kept: number
    }
 
/** A tenancy's deposit status on `today`. */
export function depositStatus(
  tenancy: DepositTenancy,
  depositReturn:
    { returnedOn: IsoDate; rentKept: number; damageKept: number } | undefined,
  today: IsoDate,
): DepositStatus {
  const deposit = tenancy.deposit ?? 0
  if (deposit <= 0) {
    return { kind: 'none' }
  }
  if (depositReturn) {
    return {
      kind: 'returned',
      on: depositReturn.returnedOn,
      returned: amountReturned(deposit, depositReturn),
      kept: depositReturn.rentKept + depositReturn.damageKept,
    }
  }
  return tenancy.validTo !== null && tenancy.validTo <= today
    ? { kind: 'pending', amount: deposit }
    : { kind: 'held', amount: deposit }
}