All files / src/features/ownership ownership.repository.server.ts

100% Statements 47/47
78.57% Branches 11/14
100% Functions 20/20
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 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                                                                                        738x 92x                           738x 172x                           738x                                             738x   361x                       361x   402x                       81x 5x   76x                     76x 76x 215x   76x 131x                         80x 5x   75x         137x         10x                                                                               86x 165x 153x     86x                               86x     86x       86x           86x           86x                       153x 153x                                 153x                 153x           86x                           3x 3x                     3x                                                 3x         3x                   3x                                           3x            
// A flat's ownership periods and the roles that follow them (openspec:
// ownership). Writes run in one atomically() batch and carry their checks
// in the statements: the actor must be an owner, and a change applies only
// to the period it was validated against, so two changes at once can't
// leave overlapping periods.
import {
  and,
  eq,
  exists,
  gte,
  inArray,
  isNull,
  lt,
  notExists,
  notInArray,
  sql,
  type SQL,
} from 'drizzle-orm'
import { dayBefore, type IsoDate } from '#/lib/dates'
import {
  ownershipPeriods,
  properties,
  propertyAccess,
  user,
  type OwnershipReason,
} from '#/server/db/schema'
import { atomically, type Db } from '#/server/platform/db.server'
import { groupPeriods, type Period, type Share } from './periods'
 
/** An owner's current share of a flat, with their name, for flat cards. */
export interface CurrentShare extends Share {
  propertyId: string
  name: string
}
 
export interface OwnershipHistory {
  /** Newest first. */
  periods: Period[]
  /** Everyone in the history, also people who no longer have access. */
  names: Record<string, string>
}
 
export function ownershipRepository(db: Db) {
  /** The actor owns the flat: the check inside each write. */
  const isOwner = (actorId: string, propertyId: string) =>
    exists(
      db
        .select({ one: sql`1` })
        .from(propertyAccess)
        .where(
          and(
            eq(propertyAccess.propertyId, propertyId),
            eq(propertyAccess.userId, actorId),
            eq(propertyAccess.role, 'owner'),
          ),
        ),
    )
 
  /** Rows of the flat starting on a date, other than `except`. */
  const startingOn = (propertyId: string, date: IsoDate, except: string[]) =>
    db
      .select({ one: sql`1` })
      .from(ownershipPeriods)
      .where(
        and(
          eq(ownershipPeriods.propertyId, propertyId),
          gte(ownershipPeriods.validFrom, date),
          except.length > 0
            ? notInArray(ownershipPeriods.id, except)
            : undefined,
        ),
      )
 
  /** Sets `owner` for `owners` and `member` for everyone else with access. */
  const setRoles = (propertyId: string, owners: string[], when: SQL) => [
    db
      .update(propertyAccess)
      .set({ role: 'owner' })
      .where(
        and(
          eq(propertyAccess.propertyId, propertyId),
          inArray(propertyAccess.userId, owners),
          when,
        ),
      ),
    db
      .update(propertyAccess)
      .set({ role: 'member' })
      .where(
        and(
          eq(propertyAccess.propertyId, propertyId),
          notInArray(propertyAccess.userId, owners),
          when,
        ),
      ),
  ]
 
  return {
    async history(propertyId: string): Promise<OwnershipHistory> {
      const rows = await db
        .select({
          userId: ownershipPeriods.userId,
          name: user.name,
          share: ownershipPeriods.share,
          validFrom: ownershipPeriods.validFrom,
          validTo: ownershipPeriods.validTo,
          reason: ownershipPeriods.reason,
        })
        .from(ownershipPeriods)
        .innerJoin(user, eq(user.id, ownershipPeriods.userId))
        .where(eq(ownershipPeriods.propertyId, propertyId))
      return {
        periods: groupPeriods(rows),
        names: Object.fromEntries(rows.map((r) => [r.userId, r.name])),
      }
    },
 
    /**
     * The ownership periods of the flats by flat id, newest first, with no
     * access check: the caller passes the ids of flats the user can see. A
     * flat without periods has no entry.
     */
    async rowsFor(
      propertyIds: string[],
    ): Promise<Partial<Record<string, Period[]>>> {
      if (propertyIds.length === 0) {
        return {}
      }
      const rows = await db
        .select({
          propertyId: ownershipPeriods.propertyId,
          userId: ownershipPeriods.userId,
          share: ownershipPeriods.share,
          validFrom: ownershipPeriods.validFrom,
          validTo: ownershipPeriods.validTo,
          reason: ownershipPeriods.reason,
        })
        .from(ownershipPeriods)
        .where(inArray(ownershipPeriods.propertyId, propertyIds))
      const byFlat: Partial<Record<string, typeof rows>> = {}
      for (const row of rows) {
        ;(byFlat[row.propertyId] ??= []).push(row)
      }
      return Object.fromEntries(
        Object.entries(byFlat).map(([propertyId, flatRows]) => [
          propertyId,
          groupPeriods(flatRows ?? []),
        ]),
      )
    },
 
    /**
     * The names of everyone in the ownership periods of the flats, also people
     * who no longer have access, by user id. No access check: the caller
     * passes the ids of flats the user can see.
     */
    async namesFor(propertyIds: string[]): Promise<Record<string, string>> {
      if (propertyIds.length === 0) {
        return {}
      }
      const rows = await db
        .selectDistinct({ userId: ownershipPeriods.userId, name: user.name })
        .from(ownershipPeriods)
        .innerJoin(user, eq(user.id, ownershipPeriods.userId))
        .where(inArray(ownershipPeriods.propertyId, propertyIds))
      return Object.fromEntries(rows.map((r) => [r.userId, r.name]))
    },
 
    /** Current shares of every flat the user has access to. */
    currentForUser(userId: string): Promise<CurrentShare[]> {
      return db
        .select({
          propertyId: ownershipPeriods.propertyId,
          userId: ownershipPeriods.userId,
          name: user.name,
          share: ownershipPeriods.share,
        })
        .from(ownershipPeriods)
        .innerJoin(user, eq(user.id, ownershipPeriods.userId))
        .where(
          and(
            isNull(ownershipPeriods.validTo),
            inArray(
              ownershipPeriods.propertyId,
              db
                .select({ id: propertyAccess.propertyId })
                .from(propertyAccess)
                .where(eq(propertyAccess.userId, userId)),
            ),
          ),
        )
    },
 
    /**
     * Records a new split from `from`: ends the current period the day
     * before, adds the new one, sets the roles from it and removes the
     * access of `removeAccess` (people going to 0 %). On the current
     * period's start it replaces that period's split instead (design
     * decision 7). Returns whether it applied: not when the actor isn't an
     * owner or the current period no longer starts at `currentStart`.
     */
    async change(change: {
      propertyId: string
      actorId: string
      currentStart: IsoDate
      from: IsoDate
      reason: OwnershipReason
      split: Share[]
      removeAccess: string[]
    }): Promise<boolean> {
      const { propertyId, from } = change
      const owners = change.split.filter((s) => s.share > 0)
      const ids = owners.map(() => crypto.randomUUID())
      // The current period was closed by this change, and no other change
      // has started on or after `from`.
      const closed = and(
        exists(
          db
            .select({ one: sql`1` })
            .from(ownershipPeriods)
            .where(
              and(
                eq(ownershipPeriods.propertyId, propertyId),
                eq(ownershipPeriods.validFrom, change.currentStart),
                eq(ownershipPeriods.validTo, dayBefore(from)),
              ),
            ),
        ),
        notExists(startingOn(propertyId, from, ids)),
        eq(properties.id, propertyId),
      )
      const correcting = from === change.currentStart
      // A correction deleted the current rows, and nothing else starts on
      // or after `from`.
      const corrected = and(
        notExists(startingOn(propertyId, from, ids)),
        eq(properties.id, propertyId),
      )
      const applied = exists(
        db
          .select({ one: sql`1` })
          .from(ownershipPeriods)
          .where(inArray(ownershipPeriods.id, ids)),
      )
      const current = and(
        eq(ownershipPeriods.propertyId, propertyId),
        isNull(ownershipPeriods.validTo),
        eq(ownershipPeriods.validFrom, change.currentStart),
        isOwner(change.actorId, propertyId),
      )
      const results = await atomically(db, [
        correcting
          ? db
              .delete(ownershipPeriods)
              .where(current)
              .returning({ id: ownershipPeriods.id })
          : db
              .update(ownershipPeriods)
              .set({ validTo: dayBefore(from) })
              .where(and(current, lt(ownershipPeriods.validFrom, from)))
              .returning({ id: ownershipPeriods.id }),
        ...owners.map((owner, i) => {
          const id = ids[i] ?? ''
          return db.insert(ownershipPeriods).select(
            db
              .select({
                id: sql<string>`${id}`.as('id'),
                propertyId: properties.id,
                userId: sql<string>`${owner.userId}`.as('user_id'),
                share: sql<number>`${owner.share}`.as('share'),
                validFrom: sql<string>`${from}`.as('valid_from'),
                validTo: sql<null>`null`.as('valid_to'),
                reason: sql<OwnershipReason>`${change.reason}`.as('reason'),
              })
              .from(properties)
              .where(correcting ? corrected : closed),
          )
        }),
        ...setRoles(
          propertyId,
          owners.map((o) => o.userId),
          applied,
        ),
        db.delete(propertyAccess).where(
          and(
            eq(propertyAccess.propertyId, propertyId),
            inArray(propertyAccess.userId, change.removeAccess),
            notInArray(
              propertyAccess.userId,
              owners.map((o) => o.userId),
            ),
            applied,
          ),
        ),
      ])
      return results[0].length > 0
    },
 
    /**
     * Deletes the latest period and makes the previous one current again,
     * with its roles. `latest` and `previous` are the periods the caller
     * read. Returns whether it applied.
     */
    async undoLatest(undo: {
      propertyId: string
      actorId: string
      latest: Period
      previous: Period
    }): Promise<boolean> {
      const { propertyId, latest, previous } = undo
      const gone = notExists(
        db
          .select({ one: sql`1` })
          .from(ownershipPeriods)
          .where(
            and(
              eq(ownershipPeriods.propertyId, propertyId),
              eq(ownershipPeriods.validFrom, latest.validFrom),
            ),
          ),
      )
      const results = await atomically(db, [
        db
          .delete(ownershipPeriods)
          .where(
            and(
              eq(ownershipPeriods.propertyId, propertyId),
              eq(ownershipPeriods.validFrom, latest.validFrom),
              isNull(ownershipPeriods.validTo),
              isOwner(undo.actorId, propertyId),
            ),
          )
          .returning({ id: ownershipPeriods.id }),
        db
          .update(ownershipPeriods)
          .set({ validTo: null })
          .where(
            and(
              eq(ownershipPeriods.propertyId, propertyId),
              eq(ownershipPeriods.validFrom, previous.validFrom),
              eq(ownershipPeriods.validTo, dayBefore(latest.validFrom)),
              gone,
            ),
          ),
        ...setRoles(
          propertyId,
          previous.shares.map((s) => s.userId),
          // Only when this undo deleted the latest period.
          gone,
        ),
      ])
      return results[0].length > 0
    },
 
    /** Moves the first period's start. Returns whether it applied. */
    async correctFirstDate(correction: {
      propertyId: string
      actorId: string
      firstStart: IsoDate
      date: IsoDate
    }): Promise<boolean> {
      const changed = await db
        .update(ownershipPeriods)
        .set({ validFrom: correction.date })
        .where(
          and(
            eq(ownershipPeriods.propertyId, correction.propertyId),
            eq(ownershipPeriods.validFrom, correction.firstStart),
            isOwner(correction.actorId, correction.propertyId),
            notExists(
              db
                .select({ one: sql`1` })
                .from(ownershipPeriods)
                .where(
                  and(
                    eq(ownershipPeriods.propertyId, correction.propertyId),
                    lt(ownershipPeriods.validFrom, correction.firstStart),
                  ),
                ),
            ),
          ),
        )
        .returning({ id: ownershipPeriods.id })
      return changed.length > 0
    },
  }
}
 
export type OwnershipRepository = ReturnType<typeof ownershipRepository>