All files / src/features/properties property.repository.server.ts

100% Statements 50/50
95.45% Branches 21/22
100% Functions 23/23
100% Lines 46/46

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                                                                                    29x                           29x 401x 401x                   1113x                                             1712x 9x         1712x       125x                     125x     1712x                     1104x 1104x                                         1104x                         9x                   9x             147x                       147x                     125x                   86x                                               86x         95x                     95x                               33x       33x                       33x 24x   9x                         25x                   25x                       25x   15x         18x   9x 63x 9x                                                   9x       9x                     9x         2x           9x         9x       9x                   14x                                                               14x       46x            
// Flats and who can reach them (openspec: properties). Every read and write
// goes through the user's access row, so a flat without access looks the
// same as one that doesn't exist.
import type { AnySQLiteColumn } from 'drizzle-orm/sqlite-core'
import {
  and,
  asc,
  count,
  eq,
  exists,
  gt,
  inArray,
  isNotNull,
  isNull,
  ne,
  notExists,
} from 'drizzle-orm'
import type { IsoDate } from '#/lib/dates'
import {
  financingCharges,
  financingTreatments,
  ownershipPeriods,
  properties,
  propertyAccess,
  propertyDocuments,
  receipts,
  recurringAmounts,
  rentPayments,
  tenancies,
  transactions,
  usageCharges,
  user,
  type PropertyRole,
} from '#/server/db/schema'
import { atomically, type Db } from '#/server/platform/db.server'
import type {
  Property,
  PropertyDetails,
  RoomCount,
  UserProperty,
} from './property'
 
const columns = {
  id: properties.id,
  streetAddress: properties.streetAddress,
  postcode: properties.postcode,
  city: properties.city,
  roomCount: properties.roomCount,
  floorArea: properties.floorArea,
  housingCompanyName: properties.housingCompanyName,
  businessId: properties.businessId,
  apartmentNumber: properties.apartmentNumber,
}
 
type Row = Pick<typeof properties.$inferSelect, keyof typeof columns>
 
const toProperty = (row: Row): Property => {
  const { housingCompanyName, businessId, apartmentNumber, ...rest } = row
  return {
    ...rest,
    roomCount: row.roomCount as RoomCount,
    ...(housingCompanyName !== null && { housingCompanyName }),
    ...(businessId !== null && { businessId }),
    ...(apartmentNumber !== null && { apartmentNumber }),
  }
}
 
/** The housing company details as columns: missing is null. */
const housingCompanyValues = (details: PropertyDetails) => ({
  housingCompanyName: details.housingCompanyName ?? null,
  businessId: details.businessId ?? null,
  apartmentNumber: details.apartmentNumber ?? null,
})
 
/** What deleting a flat removes, for the confirmation. */
export interface DeletionSummary {
  /** A tenancy, charge, financing charge, treatment, usage charge or entry. */
  hasData: boolean
  counts: {
    tenancies: number
    rentPayments: number
    transactions: number
    receipts: number
    documents: number
  }
  /** The members, who lose their access. */
  members: string[]
}
 
export function propertyRepository(db: Db) {
  /** The ids of the flats the user has access to, as a subquery. */
  const accessible = (userId: string) =>
    db
      .select({ id: propertyAccess.propertyId })
      .from(propertyAccess)
      .where(eq(propertyAccess.userId, userId))
 
  const listWhere = async (
    userId: string,
    archived: ReturnType<typeof isNull>,
  ): Promise<Property[]> => {
    const rows = await db
      .select(columns)
      .from(properties)
      .innerJoin(
        propertyAccess,
        and(
          eq(propertyAccess.propertyId, properties.id),
          eq(propertyAccess.userId, userId),
          archived,
        ),
      )
    return rows.map(toProperty)
  }
 
  return {
    /**
     * Adds a flat with the user as its owner, owning 100 % from `ownedSince`
     * (openspec: ownership, "The first ownership period").
     */
    async create(
      userId: string,
      details: PropertyDetails,
      now: Date,
      ownedSince: IsoDate,
    ): Promise<Property> {
      const id = crypto.randomUUID()
      await atomically(db, [
        db.insert(properties).values({
          id,
          ...details,
          ...housingCompanyValues(details),
          createdAt: now,
          updatedAt: now,
        }),
        db
          .insert(propertyAccess)
          .values({ propertyId: id, userId, role: 'owner', createdAt: now }),
        db.insert(ownershipPeriods).values({
          id: crypto.randomUUID(),
          propertyId: id,
          userId,
          share: 10000,
          validFrom: ownedSince,
          validTo: null,
          reason: null,
        }),
      ])
      return { id, ...details }
    },
 
    /**
     * Changes a flat's details if the user has access to it. The access is
     * checked in the same statement. Returns whether a flat was changed.
     */
    async update(
      userId: string,
      id: string,
      details: PropertyDetails,
      now: Date,
    ): Promise<boolean> {
      const changed = await db
        .update(properties)
        .set({ ...details, ...housingCompanyValues(details), updatedAt: now })
        .where(
          and(
            eq(properties.id, id),
            inArray(properties.id, accessible(userId)),
          ),
        )
        .returning({ id: properties.id })
      return changed.length > 0
    },
 
    async findForUser(
      userId: string,
      id: string,
    ): Promise<UserProperty | undefined> {
      const row = await db
        .select({ ...columns, archivedAt: propertyAccess.archivedAt })
        .from(properties)
        .innerJoin(
          propertyAccess,
          and(
            eq(propertyAccess.propertyId, properties.id),
            eq(propertyAccess.userId, userId),
          ),
        )
        .where(eq(properties.id, id))
        .get()
      return row === undefined
        ? undefined
        : { ...toProperty(row), archivedAt: row.archivedAt }
    },
 
    /**
     * The flats the user hasn't archived. Unsorted: sort for display with
     * sortByStreetAddress(). The list, the rent summary and the new entry
     * options all read through this, so an archived flat is left out of all.
     */
    async listForUser(userId: string): Promise<Property[]> {
      return listWhere(userId, isNull(propertyAccess.archivedAt))
    },
 
    /**
     * The flats the user has no access to but had a share above 0 in on some
     * day (openspec: year-summary, "A former owner's year summary"). Only the
     * year summary reads these; every other access check stays on the access
     * row. Unsorted.
     */
    async listFormerlyOwnedForUser(userId: string): Promise<Property[]> {
      const rows = await db
        .selectDistinct(columns)
        .from(properties)
        .innerJoin(
          ownershipPeriods,
          and(
            eq(ownershipPeriods.propertyId, properties.id),
            eq(ownershipPeriods.userId, userId),
            gt(ownershipPeriods.share, 0),
          ),
        )
        .where(
          notExists(
            db
              .select({ one: propertyAccess.userId })
              .from(propertyAccess)
              .where(
                and(
                  eq(propertyAccess.propertyId, properties.id),
                  eq(propertyAccess.userId, userId),
                ),
              ),
          ),
        )
      return rows.map(toProperty)
    },
 
    /** The flats the user has archived, with when. Unsorted. */
    async listArchivedForUser(userId: string): Promise<UserProperty[]> {
      const rows = await db
        .select({ ...columns, archivedAt: propertyAccess.archivedAt })
        .from(properties)
        .innerJoin(
          propertyAccess,
          and(
            eq(propertyAccess.propertyId, properties.id),
            eq(propertyAccess.userId, userId),
            isNotNull(propertyAccess.archivedAt),
          ),
        )
      return rows.map((row) => ({
        ...toProperty(row),
        archivedAt: row.archivedAt,
      }))
    },
 
    /**
     * Archives (`at`) or restores (`null`) the flat for the user, on their own
     * access row. An archived flat keeps its first date. Returns whether it
     * changed, was already so (`unchanged`), or the user has no access.
     */
    async setArchived(
      userId: string,
      propertyId: string,
      at: Date | null,
    ): Promise<'changed' | 'unchanged' | 'not_found'> {
      const own = and(
        eq(propertyAccess.propertyId, propertyId),
        eq(propertyAccess.userId, userId),
      )
      const changed = await db
        .update(propertyAccess)
        .set({ archivedAt: at })
        .where(
          and(
            own,
            at === null
              ? isNotNull(propertyAccess.archivedAt)
              : isNull(propertyAccess.archivedAt),
          ),
        )
        .returning({ id: propertyAccess.propertyId })
      if (changed.length > 0) {
        return 'changed'
      }
      return (await db.$count(propertyAccess, own)) > 0
        ? 'unchanged'
        : 'not_found'
    },
 
    /**
     * The user's role in the flat (undefined without access) and the names of
     * everyone else who has had a share above 0 % in any ownership period.
     */
    async deletionCheck(
      userId: string,
      propertyId: string,
    ): Promise<{ role: PropertyRole | undefined; otherOwners: string[] }> {
      const access = await db
        .select({ role: propertyAccess.role })
        .from(propertyAccess)
        .where(
          and(
            eq(propertyAccess.propertyId, propertyId),
            eq(propertyAccess.userId, userId),
          ),
        )
        .get()
      const others = await db
        .selectDistinct({ name: user.name })
        .from(ownershipPeriods)
        .innerJoin(user, eq(user.id, ownershipPeriods.userId))
        .where(
          and(
            eq(ownershipPeriods.propertyId, propertyId),
            ne(ownershipPeriods.userId, userId),
            gt(ownershipPeriods.share, 0),
          ),
        )
        .orderBy(asc(user.name))
      return {
        role: access?.role,
        otherOwners: others.map((other) => other.name),
      }
    },
 
    async deletionSummary(propertyId: string): Promise<DeletionSummary> {
      const total = async (query: Promise<{ n: number }[]>): Promise<number> =>
        (await query)[0]?.n ?? 0
      const ofFlat = (table: { propertyId: AnySQLiteColumn }) =>
        eq(table.propertyId, propertyId)
      const counts = {
        tenancies: await db.$count(tenancies, ofFlat(tenancies)),
        rentPayments: await total(
          db
            .select({ n: count() })
            .from(rentPayments)
            .innerJoin(tenancies, eq(tenancies.id, rentPayments.tenancyId))
            .where(eq(tenancies.propertyId, propertyId)),
        ),
        transactions: await db.$count(transactions, ofFlat(transactions)),
        receipts: await total(
          db
            .select({ n: count() })
            .from(receipts)
            .innerJoin(
              transactions,
              eq(transactions.id, receipts.transactionId),
            )
            .where(eq(transactions.propertyId, propertyId)),
        ),
        documents: await db.$count(
          propertyDocuments,
          ofFlat(propertyDocuments),
        ),
      }
      const others =
        (await db.$count(recurringAmounts, ofFlat(recurringAmounts))) +
        (await db.$count(financingCharges, ofFlat(financingCharges))) +
        (await db.$count(financingTreatments, ofFlat(financingTreatments))) +
        (await db.$count(usageCharges, ofFlat(usageCharges)))
      const members = await db
        .select({ name: user.name })
        .from(propertyAccess)
        .innerJoin(user, eq(user.id, propertyAccess.userId))
        .where(
          and(
            eq(propertyAccess.propertyId, propertyId),
            eq(propertyAccess.role, 'member'),
          ),
        )
        .orderBy(asc(user.name))
      return {
        hasData:
          counts.tenancies + counts.transactions + counts.documents + others >
          0,
        counts,
        members: members.map((member) => member.name),
      }
    },
 
    /** The storage keys of every receipt and document file of the flat. */
    async fileKeys(propertyId: string): Promise<string[]> {
      const receiptRows = await db
        .select({ key: receipts.key })
        .from(receipts)
        .innerJoin(transactions, eq(transactions.id, receipts.transactionId))
        .where(eq(transactions.propertyId, propertyId))
      const documentRows = await db
        .select({ key: propertyDocuments.key })
        .from(propertyDocuments)
        .where(eq(propertyDocuments.propertyId, propertyId))
      return [...receiptRows, ...documentRows].map((row) => row.key)
    },
 
    /**
     * Deletes the flat and, through ON DELETE CASCADE, everything recorded
     * for it, in one statement: only when the user is an owner and nobody
     * else has had a share above 0 % (so the rule holds even if ownership
     * changed since it was checked). Returns whether the flat was deleted.
     */
    async deleteGuarded(userId: string, propertyId: string): Promise<boolean> {
      const deleted = await db
        .delete(properties)
        .where(
          and(
            eq(properties.id, propertyId),
            exists(
              db
                .select({ one: propertyAccess.userId })
                .from(propertyAccess)
                .where(
                  and(
                    eq(propertyAccess.propertyId, propertyId),
                    eq(propertyAccess.userId, userId),
                    eq(propertyAccess.role, 'owner'),
                  ),
                ),
            ),
            notExists(
              db
                .select({ one: ownershipPeriods.id })
                .from(ownershipPeriods)
                .where(
                  and(
                    eq(ownershipPeriods.propertyId, propertyId),
                    ne(ownershipPeriods.userId, userId),
                    gt(ownershipPeriods.share, 0),
                  ),
                ),
            ),
          ),
        )
        .returning({ id: properties.id })
      return deleted.length > 0
    },
 
    countForUser(userId: string): Promise<number> {
      return db.$count(propertyAccess, eq(propertyAccess.userId, userId))
    },
  }
}
 
export type PropertyRepository = ReturnType<typeof propertyRepository>