All files / src/features/properties details.server.ts

100% Statements 14/14
83.33% Branches 5/6
100% Functions 4/4
100% Lines 13/13

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                                                                                1x     1x                                                                                         1x           9x       9x 1x                     8x                   8x 8x 8x         8x                                   8x 8x                                            
// The flat details page's data in one read (openspec: properties, "The flat
// details page"): one access check, then the flat, its owners, tenancies,
// rent and charges, rent payments and latest entries. Statuses and amounts
// are computed from these by the page with the pure functions of each
// feature, as the other pages do.
import type {
  DocumentRepository,
  DocumentRow,
} from '#/features/documents/document.repository.server'
import type { OwnershipRepository } from '#/features/ownership/ownership.repository.server'
import type { RentPayment } from '#/features/rent-payments/rent-payment.repository.server'
import type { RentPaymentRepository } from '#/features/rent-payments/rent-payment.repository.server'
import type {
  FeesByTenancy,
  OccupantsByTenancy,
  RentsByTenancy,
} from '#/features/rent-payments/status'
import { accumulatedCapitalised } from '#/features/recurring-amounts/periods'
import type {
  RecurringAmountRepository,
  RecurringAmounts,
} from '#/features/recurring-amounts/recurring-amount.repository.server'
import type { SharingRepository } from '#/features/sharing/sharing.repository.server'
import type {
  Tenancy,
  TenancyRepository,
} from '#/features/tenancies/tenancy.repository.server'
import type {
  TransactionRepository,
  TransactionRow,
} from '#/features/transactions/transaction.repository.server'
import type { UsageChargePeriods } from '#/features/usage-charges/months'
import type { UsageChargeRepository } from '#/features/usage-charges/usage-charge.repository.server'
import { isoDateInFinland, type IsoDate } from '#/lib/dates'
import type { PropertyRole } from '#/server/db/schema'
import type { CardOwner } from './ownership-line'
import type { Property } from './property'
import type { PropertyRepository } from './property.repository.server'
 
/** How many entries the page lists. */
export const LATEST_ENTRIES = 3
 
/** How many documents the page lists. */
export const LATEST_DOCUMENTS = 3
 
export interface FlatDetailsDeps {
  /** The signed-in user. */
  userId: string
  properties: PropertyRepository
  sharing: SharingRepository
  ownership: OwnershipRepository
  tenancies: TenancyRepository
  amounts: RecurringAmountRepository
  payments: RentPaymentRepository
  transactions: TransactionRepository
  documents: DocumentRepository
  usageCharges: UsageChargeRepository
  now: () => Date
}
 
export interface FlatDetails extends RecurringAmounts {
  role: PropertyRole
  property: Property
  /** The day in Finland the user archived the flat, or null. */
  archivedOn: IsoDate | null
  /** The current owners, the user as `isYou`. */
  owners: CardOwner[]
  /** Today in Finland. */
  today: IsoDate
  /** Newest first. */
  tenancies: Tenancy[]
  /** Each tenancy's rent periods, oldest first. */
  tenancyRents: RentsByTenancy
  /** Each tenancy's occupants periods, oldest first. */
  tenancyOccupants: OccupantsByTenancy
  /** The flat's usage charges with their periods. */
  usageCharges: UsageChargePeriods[]
  /** Each tenancy's tenant fees. */
  tenancyFees: FeesByTenancy
  /** Cents of financing charges added to the acquisition cost so far. */
  capitalised: number
  payments: RentPayment[]
  /** Newest first. */
  latestEntries: TransactionRow[]
  /** The latest documents by date, newest first, and how many there are. */
  documents: { latest: DocumentRow[]; count: number }
}
 
const notFound = { ok: false, reason: 'property_not_found' } as const
 
export async function getFlatDetails(
  deps: FlatDetailsDeps,
  propertyId: string,
): Promise<({ ok: true } & FlatDetails) | typeof notFound> {
  const [role, property] = await Promise.all([
    deps.sharing.roleOf(deps.userId, propertyId),
    deps.properties.findForUser(deps.userId, propertyId),
  ])
  if (!role || !property) {
    return notFound
  }
  const [
    shares,
    tenancies,
    amounts,
    payments,
    latestEntries,
    usageCharges,
    latestDocuments,
    documentCount,
  ] = await Promise.all([
    deps.ownership.currentForUser(deps.userId),
    deps.tenancies.forProperty(propertyId),
    deps.amounts.forProperty(propertyId),
    deps.payments.forProperty(propertyId),
    deps.transactions.latest(propertyId, LATEST_ENTRIES),
    deps.usageCharges.forProperty(propertyId),
    deps.documents.latestForProperty(propertyId, LATEST_DOCUMENTS),
    deps.documents.countForProperty(propertyId),
  ])
  const today = isoDateInFinland(deps.now())
  const tenancyIds = tenancies.map((t) => t.id)
  const [tenancyRents, tenancyOccupants, tenancyFees] = await Promise.all([
    deps.tenancies.rentsFor(tenancyIds),
    deps.tenancies.occupantsFor(tenancyIds),
    deps.tenancies.feesFor(tenancyIds),
  ])
  return {
    ok: true,
    role,
    property: {
      id: property.id,
      streetAddress: property.streetAddress,
      postcode: property.postcode,
      city: property.city,
      roomCount: property.roomCount,
      floorArea: property.floorArea,
      housingCompanyName: property.housingCompanyName,
      businessId: property.businessId,
      apartmentNumber: property.apartmentNumber,
    },
    archivedOn: property.archivedAt
      ? isoDateInFinland(property.archivedAt)
      : null,
    owners: shares
      .filter((share) => share.propertyId === propertyId)
      .map(({ name, share, userId }) => ({
        name,
        share,
        isYou: userId === deps.userId,
      })),
    today,
    tenancies,
    tenancyRents,
    tenancyOccupants,
    tenancyFees,
    usageCharges,
    ...amounts,
    capitalised: accumulatedCapitalised(
      amounts.financingCharges,
      amounts.treatments,
      today,
    ),
    payments,
    latestEntries,
    documents: { latest: latestDocuments, count: documentCount },
  }
}