All files / src/features/rent-payments rent-payments.server.ts

97.05% Statements 66/68
88.88% Branches 32/36
100% Functions 18/18
96.82% Lines 61/63

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                                                                                          11x         2x 2x 2x 2x   25x                                                 9x           9x 1x   8x 8x         8x                                                       7x 7x 7x 5x   7x       7x 7x         7x   5x   6x         2x 2x                     2x 11x                           3x 3x     3x 3x 1x   2x 1x   1x         2x                 19x 19x 1x   18x                     13x 13x 2x   11x 11x 1x   10x 1x   9x 1x   8x           8x       8x         8x                 4x 4x 1x   3x 3x 2x             1x 1x    
// Rent payments: the logic behind the server functions in functions.ts,
// with its dependencies passed in so Workers tests can drive it (openspec:
// rent-payments). The rules are checked here first for the reason, and each
// write checks the owner role and the tenancy's months again in its
// statement. Amounts and names are never logged.
import type { Property } from '#/features/properties/property'
import type { PropertyRepository } from '#/features/properties/property.repository.server'
import type { SharingRepository } from '#/features/sharing/sharing.repository.server'
import type {
  Tenancy,
  TenancyRepository,
} from '#/features/tenancies/tenancy.repository.server'
import { isoDateInFinland, type IsoDate } from '#/lib/dates'
import type { AlertReason, FieldReason } from '#/lib/reasons'
import type { PropertyRole } from '#/server/db/schema'
import type { Logger } from '#/server/log/log'
import type {
  NewRentPayment,
  RentPayment,
  RentPaymentRepository,
} from './rent-payment.repository.server'
import {
  tenancyMonths,
  type FeesByTenancy,
  type FlatRentData,
  type OccupantsByTenancy,
  type RentsByTenancy,
} from './status'
 
export interface RentPaymentDeps {
  /** The signed-in user. */
  userId: string
  payments: RentPaymentRepository
  tenancies: TenancyRepository
  properties: PropertyRepository
  sharing: SharingRepository
  log: Logger
  now: () => Date
}
 
interface Failure<R extends FieldReason | AlertReason = AlertReason> {
  ok: false
  reason: R
}
 
const fail = <R extends FieldReason | AlertReason>(reason: R): Failure<R> => ({
  ok: false,
  reason,
})
 
const notFound = fail('property_not_found')
const ownerOnly = fail('sharing_owner_only')
const tenancyNotFound = fail('tenancy_not_found')
const outsideTenancy = fail('rent_payment_month_outside_tenancy')
 
const today = (deps: RentPaymentDeps) => isoDateInFinland(deps.now())
 
/** What the rent pages compute the months and statuses from. */
export interface RentPaymentsView {
  role: PropertyRole
  property: Property
  /** Today in Finland. */
  today: IsoDate
  /** Newest first. */
  tenancies: Tenancy[]
  /** Each tenancy's rent periods, oldest first. */
  rents: RentsByTenancy
  /** Each tenancy's occupants periods, oldest first. */
  occupants: OccupantsByTenancy
  /** Each tenancy's tenant fees. */
  fees: FeesByTenancy
  /** Every payment of the flat's tenancies, by month and payment date. */
  payments: RentPayment[]
}
 
/** The flat's tenancies, rent and payments, for everyone with access. */
export async function getRentPayments(
  deps: RentPaymentDeps,
  propertyId: string,
): Promise<({ ok: true } & RentPaymentsView) | typeof notFound> {
  const [role, property, tenancies, payments] = await Promise.all([
    deps.sharing.roleOf(deps.userId, propertyId),
    deps.properties.findForUser(deps.userId, propertyId),
    deps.tenancies.forProperty(propertyId),
    deps.payments.forProperty(propertyId),
  ])
  if (!role || !property) {
    return notFound
  }
  const ids = tenancies.map((t) => t.id)
  const [rents, occupants, fees] = await Promise.all([
    deps.tenancies.rentsFor(ids),
    deps.tenancies.occupantsFor(ids),
    deps.tenancies.feesFor(ids),
  ])
  return {
    ok: true,
    role,
    property,
    today: today(deps),
    tenancies,
    rents,
    occupants,
    fees,
    payments,
  }
}
 
/** This month's rent data of every flat the user has access to. */
export interface RentThisMonthView {
  today: IsoDate
  flats: FlatRentData<Tenancy>[]
}
 
/**
 * For the flats list: the user's flats with the tenancies running this
 * month, their rent periods and this month's payments (openspec:
 * rent-payments, "The rent summary on the flats list"). Access is checked
 * once by listing the user's flats; every other read is by their ids.
 */
export async function listRentThisMonth(
  deps: RentPaymentDeps,
): Promise<RentThisMonthView> {
  const day = today(deps)
  const month = day.slice(0, 7)
  const ids = (await deps.properties.listForUser(deps.userId)).map(
    (flat) => flat.id,
  )
  const [tenancies, payments] = await Promise.all([
    deps.tenancies.currentFor(ids, `${month}-01`),
    deps.payments.forMonth(ids, month),
  ])
  const tenancyIds = tenancies.map((t) => t.id)
  const [rents, occupants, fees] = await Promise.all([
    deps.tenancies.rentsFor(tenancyIds),
    deps.tenancies.occupantsFor(tenancyIds),
    deps.tenancies.feesFor(tenancyIds),
  ])
  return {
    today: day,
    flats: ids.map((propertyId) => ({
      propertyId,
      tenancies: tenancies.filter((t) => t.propertyId === propertyId),
      rents,
      occupants,
      fees,
      payments: payments
        .filter((p) => p.propertyId === propertyId)
        .map(({ tenancyId, month, amount, paidOn }) => ({
          tenancyId,
          month,
          amount,
          paidOn,
        })),
    })),
  }
}
 
/** Whether the tenancy runs in `month`. */
const runsIn = (tenancy: Tenancy, month: string) =>
  tenancyMonths(tenancy, month, month).length > 0
 
/** One month of a tenancy: the view narrowed to it. */
export async function getRentMonth(
  deps: RentPaymentDeps,
  propertyId: string,
  tenancyId: string,
  month: string,
): Promise<
  | ({ ok: true; tenancy: Tenancy; month: string } & RentPaymentsView)
  | typeof notFound
  | typeof tenancyNotFound
  | typeof outsideTenancy
> {
  const view = await getRentPayments(deps, propertyId)
  Iif (!view.ok) {
    return view
  }
  const tenancy = view.tenancies.find((t) => t.id === tenancyId)
  if (!tenancy) {
    return tenancyNotFound
  }
  if (!runsIn(tenancy, month)) {
    return outsideTenancy
  }
  return {
    ...view,
    tenancy,
    month,
    payments: view.payments.filter(
      (p) => p.tenancyId === tenancyId && p.month === month,
    ),
  }
}
 
async function roleCheck(
  deps: RentPaymentDeps,
  propertyId: string,
): Promise<typeof notFound | typeof ownerOnly | undefined> {
  const role = await deps.sharing.roleOf(deps.userId, propertyId)
  if (!role) {
    return notFound
  }
  return role === 'owner' ? undefined : ownerOnly
}
 
/** Records a payment for a month of a tenancy. Owners only. */
export async function recordRentPayment(
  deps: RentPaymentDeps,
  propertyId: string,
  payment: NewRentPayment,
): Promise<
  { ok: true; paymentId: string } | Failure<FieldReason | AlertReason>
> {
  const refused = await roleCheck(deps, propertyId)
  if (refused) {
    return refused
  }
  const tenancy = await deps.tenancies.get(payment.tenancyId)
  if (tenancy?.propertyId !== propertyId) {
    return tenancyNotFound
  }
  if (payment.paidOn > today(deps)) {
    return fail('rent_payment_date_in_future')
  }
  if (!runsIn(tenancy, payment.month)) {
    return outsideTenancy
  }
  const paymentId = await deps.payments.record(
    deps.userId,
    propertyId,
    payment,
    deps.now(),
  )
  Iif (paymentId === null) {
    // The role or the tenancy changed between the checks and the write.
    return (await roleCheck(deps, propertyId)) ?? outsideTenancy
  }
  deps.log.info('rent_payment.recorded', {
    propertyId,
    tenancyId: payment.tenancyId,
    paymentId,
  })
  return { ok: true, paymentId }
}
 
/** Deletes a payment of one of the flat's tenancies. Owners only. */
export async function deleteRentPayment(
  deps: RentPaymentDeps,
  propertyId: string,
  paymentId: string,
): Promise<{ ok: true } | Failure> {
  const refused = await roleCheck(deps, propertyId)
  if (refused) {
    return refused
  }
  const removed = await deps.payments.remove(deps.userId, propertyId, paymentId)
  if (!removed) {
    return (
      (await roleCheck(deps, propertyId)) ??
      ((await deps.payments.isFromDeposit(propertyId, paymentId))
        ? fail('rent_payment_from_deposit')
        : fail('rent_payment_not_found'))
    )
  }
  deps.log.info('rent_payment.deleted', { propertyId, paymentId })
  return { ok: true }
}