All files / src/features/recurring-amounts recurring-amount.repository.server.ts

97.56% Statements 80/82
77.5% Branches 31/40
95.83% Functions 23/24
98.75% Lines 79/80

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 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605                                                                                                                                                    6x               290x 262x                                 290x 31x                       290x 189x 154x         35x     35x                                   178x 178x 178x 2x                               176x     176x                                                                 176x                                     176x 161x   15x                                   290x   118x 118x                   195x 5x   190x                               203x         190x   242x 334x   242x 43x 41x       62x       6x         242x         204x         20x 18x                                       152x 152x 152x                     11x 11x 11x                     11x 6x   6x                                           6x   5x                                         5x                               26x 26x                                             26x 26x                   4x 4x                         4x             16x 16x 16x 1x                           1x   15x 15x                                                         15x                             15x 11x 11x   4x                             4x         6x 6x 6x                     6x 3x 3x   3x                                         3x                
// A flat's rent, charges, financing charges and financing charge treatment
// as periods (openspec: recurring-amounts). Writes run in one atomically() batch and carry their
// checks in the statements: the actor must be an owner, and a write applies
// only to the latest period it was validated against, so two writes at once
// can't leave overlapping periods.
import {
  and,
  asc,
  eq,
  exists,
  gte,
  inArray,
  isNull,
  lt,
  notExists,
  sql,
  type SQL,
} from 'drizzle-orm'
import type { BatchItem } from 'drizzle-orm/batch'
import { dayBefore, type IsoDate } from '#/lib/dates'
import {
  financingCharges,
  financingTreatments,
  properties,
  propertyAccess,
  recurringAmounts,
  type FinancingTreatment,
  type RecurringAmountKind,
} from '#/server/db/schema'
import { atomically, type Db } from '#/server/platform/db.server'
import type { Period } from './periods'
 
/** One of a flat's financing charges with its periods, oldest first. */
export interface FinancingCharge {
  id: string
  /** Null for the charge made when financing charges became several. */
  name: string | null
  periods: Period<number>[]
}
 
export interface RecurringAmounts {
  /** The maintenance charge's periods, oldest first. */
  amounts: Record<'maintenance_charge', Period<number>[]>
  /** Ordered by their first period's start, then name. */
  financingCharges: FinancingCharge[]
  /** Oldest first. */
  treatments: Period<FinancingTreatment>[]
}
 
/**
 * A sequence of periods: the rent, the maintenance charge, or one financing
 * charge, named by `chargeId` (required for `financing_charge`).
 */
export interface Sequence {
  kind: RecurringAmountKind
  chargeId?: string
}
 
/** An undo's expectation: the latest and previous periods' starts as read. */
interface Undo {
  propertyId: string
  actorId: string
  latestStart: IsoDate
  previousStart: IsoDate | null
}
 
/** A write's expectation: the latest period's start as read, or none. */
export interface Expected {
  propertyId: string
  actorId: string
  latestStart: IsoDate | null
  from: IsoDate
}
 
const emptyAmounts = (): RecurringAmounts => ({
  amounts: { maintenance_charge: [] },
  financingCharges: [],
  treatments: [],
})
 
export function recurringAmountRepository(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'),
          ),
        ),
    )
 
  /**
   * The financing charge is the flat's, so a new period can't join another
   * flat's charge. Updates need no check: they match the flat's own rows.
   */
  const chargeOfFlat = (chargeId: string, propertyId: string) =>
    exists(
      db
        .select({ one: sql`1` })
        .from(financingCharges)
        .where(
          and(
            eq(financingCharges.id, chargeId),
            eq(financingCharges.propertyId, propertyId),
          ),
        ),
    )
 
  const amountScope = (propertyId: string, sequence: Sequence) => {
    if (sequence.kind !== 'financing_charge') {
      return and(
        eq(recurringAmounts.propertyId, propertyId),
        eq(recurringAmounts.kind, sequence.kind),
      )
    }
    Iif (sequence.chargeId === undefined) {
      throw new Error('A financing charge period needs its charge')
    }
    return and(
      eq(recurringAmounts.propertyId, propertyId),
      eq(recurringAmounts.kind, 'financing_charge'),
      eq(recurringAmounts.financingChargeId, sequence.chargeId),
    )
  }
 
  /**
   * The statements that set an amount from `from`: on the latest period's
   * start they correct that period, otherwise they close the latest period
   * the day before and add a new one. `onlyIf` joins every statement's
   * condition, so another write in the same batch can gate them. The last
   * statement returns a row when it applied.
   */
  function amountStatements(
    write: Expected & Sequence & { amount: number },
    onlyIf?: SQL,
  ): [BatchItem<'sqlite'>, ...BatchItem<'sqlite'>[]] {
    const { propertyId, actorId, kind, amount, from, latestStart } = write
    const scope = amountScope(propertyId, write)
    if (latestStart === from) {
      return [
        db
          .update(recurringAmounts)
          .set({ amount })
          .where(
            and(
              scope,
              eq(recurringAmounts.validFrom, from),
              isNull(recurringAmounts.validTo),
              isOwner(actorId, propertyId),
              onlyIf,
            ),
          )
          .returning({ id: recurringAmounts.id }),
      ]
    }
    const id = crypto.randomUUID()
    // The latest period is closed by this write (or there was none), and
    // nothing of this kind starts on or after `from`.
    const ready = and(
      eq(properties.id, propertyId),
      isOwner(actorId, propertyId),
      write.chargeId === undefined
        ? undefined
        : chargeOfFlat(write.chargeId, propertyId),
      onlyIf,
      notExists(
        db
          .select({ one: sql`1` })
          .from(recurringAmounts)
          .where(and(scope, gte(recurringAmounts.validFrom, from))),
      ),
      latestStart === null
        ? notExists(
            db
              .select({ one: sql`1` })
              .from(recurringAmounts)
              .where(scope),
          )
        : exists(
            db
              .select({ one: sql`1` })
              .from(recurringAmounts)
              .where(
                and(
                  scope,
                  eq(recurringAmounts.validFrom, latestStart),
                  eq(recurringAmounts.validTo, dayBefore(from)),
                ),
              ),
          ),
    )
    const insert = db
      .insert(recurringAmounts)
      .select(
        db
          .select({
            id: sql<string>`${id}`.as('id'),
            propertyId: properties.id,
            kind: sql<RecurringAmountKind>`${kind}`.as('kind'),
            financingChargeId: sql<string | null>`${write.chargeId ?? null}`.as(
              'financing_charge_id',
            ),
            amount: sql<number>`${amount}`.as('amount'),
            validFrom: sql<string>`${from}`.as('valid_from'),
            validTo: sql<null>`null`.as('valid_to'),
          })
          .from(properties)
          .where(ready),
      )
      .returning({ id: recurringAmounts.id })
    if (latestStart === null) {
      return [insert]
    }
    return [
      db
        .update(recurringAmounts)
        .set({ validTo: dayBefore(from) })
        .where(
          and(
            scope,
            eq(recurringAmounts.validFrom, latestStart),
            lt(recurringAmounts.validFrom, from),
            isNull(recurringAmounts.validTo),
            isOwner(actorId, propertyId),
            onlyIf,
          ),
        ),
      insert,
    ]
  }
 
  return {
    async forProperty(propertyId: string): Promise<RecurringAmounts> {
      const byFlat = await this.forProperties([propertyId])
      return byFlat[propertyId] ?? emptyAmounts()
    },
 
    /**
     * The charges, financing charges and treatments of each flat, by flat
     * id. Every id has an entry, empty for a flat without any.
     */
    async forProperties(
      propertyIds: string[],
    ): Promise<Record<string, RecurringAmounts>> {
      if (propertyIds.length === 0) {
        return {}
      }
      const [amountRows, chargeRows, treatmentRows] = await Promise.all([
        db
          .select()
          .from(recurringAmounts)
          .where(inArray(recurringAmounts.propertyId, propertyIds))
          .orderBy(asc(recurringAmounts.validFrom)),
        db
          .select()
          .from(financingCharges)
          .where(inArray(financingCharges.propertyId, propertyIds)),
        db
          .select()
          .from(financingTreatments)
          .where(inArray(financingTreatments.propertyId, propertyIds))
          .orderBy(asc(financingTreatments.validFrom)),
      ])
      const period = (row: (typeof amountRows)[number]) => ({
        validFrom: row.validFrom,
        validTo: row.validTo,
        value: row.amount,
      })
      return Object.fromEntries(
        propertyIds.map((propertyId) => {
          const flatAmounts = amountRows.filter(
            (row) => row.propertyId === propertyId,
          )
          const charges: FinancingCharge[] = chargeRows
            .filter((row) => row.propertyId === propertyId)
            .map((row) => ({
              id: row.id,
              name: row.name,
              periods: flatAmounts
                .filter((amount) => amount.financingChargeId === row.id)
                .map(period),
            }))
            .sort(
              (a, b) =>
                (a.periods[0]?.validFrom ?? '').localeCompare(
                  b.periods[0]?.validFrom ?? '',
                ) || (a.name ?? '').localeCompare(b.name ?? '', 'fi'),
            )
          return [
            propertyId,
            {
              amounts: {
                maintenance_charge: flatAmounts
                  .filter((row) => row.kind === 'maintenance_charge')
                  .map(period),
              },
              financingCharges: charges,
              treatments: treatmentRows
                .filter((row) => row.propertyId === propertyId)
                .map((row) => ({
                  validFrom: row.validFrom,
                  validTo: row.validTo,
                  value: row.treatment,
                })),
            },
          ]
        }),
      )
    },
 
    amountStatements,
 
    /**
     * Sets an amount from `from` (amountStatements). Returns whether it
     * applied.
     */
    async setAmount(
      write: Expected & Sequence & { amount: number },
    ): Promise<boolean> {
      const results = await atomically(db, amountStatements(write))
      const last = results.at(-1) as unknown[]
      return last.length > 0
    },
 
    /**
     * Deletes the latest period and makes the previous one current again;
     * with no previous period (`previousStart` null) the amount is no longer
     * set, and a financing charge is removed with its last period.
     * `latestStart` and `previousStart` are the periods the caller read.
     * Returns whether it applied.
     */
    async undoLatestAmount(undo: Undo & Sequence): Promise<boolean> {
      const { propertyId, latestStart, previousStart } = undo
      const scope = amountScope(propertyId, undo)
      const remove = db
        .delete(recurringAmounts)
        .where(
          and(
            scope,
            eq(recurringAmounts.validFrom, latestStart),
            isNull(recurringAmounts.validTo),
            isOwner(undo.actorId, propertyId),
          ),
        )
        .returning({ id: recurringAmounts.id })
      if (previousStart === null) {
        const chargeId = undo.chargeId
        const [removed] =
          chargeId === undefined
            ? await atomically(db, [remove])
            : await atomically(db, [
                remove,
                // The charge goes with its last period, only once none is
                // left, so another write's new period keeps it.
                db.delete(financingCharges).where(
                  and(
                    eq(financingCharges.id, chargeId),
                    eq(financingCharges.propertyId, propertyId),
                    isOwner(undo.actorId, propertyId),
                    notExists(
                      db
                        .select({ one: sql`1` })
                        .from(recurringAmounts)
                        .where(
                          eq(recurringAmounts.financingChargeId, chargeId),
                        ),
                    ),
                  ),
                ),
              ])
        return removed.length > 0
      }
      const [removed] = await atomically(db, [
        remove,
        db
          .update(recurringAmounts)
          .set({ validTo: null })
          .where(
            and(
              scope,
              eq(recurringAmounts.validFrom, previousStart),
              eq(recurringAmounts.validTo, dayBefore(latestStart)),
              notExists(
                db
                  .select({ one: sql`1` })
                  .from(recurringAmounts)
                  .where(
                    and(scope, eq(recurringAmounts.validFrom, latestStart)),
                  ),
              ),
            ),
          ),
      ])
      return removed.length > 0
    },
 
    /**
     * Adds a financing charge with its first period, both or neither: the
     * period's statements require the charge the first statement adds.
     * Returns whether it applied.
     */
    async addFinancingCharge(add: {
      propertyId: string
      actorId: string
      chargeId: string
      name: string
      amount: number
      from: IsoDate
    }): Promise<boolean> {
      const { propertyId, actorId, chargeId, name, amount, from } = add
      const results = await atomically(db, [
        db.insert(financingCharges).select(
          db
            .select({
              id: sql<string>`${chargeId}`.as('id'),
              propertyId: properties.id,
              name: sql<string>`${name}`.as('name'),
            })
            .from(properties)
            .where(
              and(eq(properties.id, propertyId), isOwner(actorId, propertyId)),
            ),
        ),
        ...amountStatements({
          propertyId,
          actorId,
          kind: 'financing_charge',
          chargeId,
          amount,
          from,
          latestStart: null,
        }),
      ])
      const last = results.at(-1) as unknown[]
      return last.length > 0
    },
 
    /** Renames a financing charge of the flat. Returns whether it applied. */
    async renameFinancingCharge(rename: {
      propertyId: string
      actorId: string
      chargeId: string
      name: string
    }): Promise<boolean> {
      const { propertyId, actorId, chargeId, name } = rename
      const [updated] = await atomically(db, [
        db
          .update(financingCharges)
          .set({ name })
          .where(
            and(
              eq(financingCharges.id, chargeId),
              eq(financingCharges.propertyId, propertyId),
              isOwner(actorId, propertyId),
            ),
          )
          .returning({ id: financingCharges.id }),
      ])
      return updated.length > 0
    },
 
    /** Sets the financing charge treatment from `from`, like setAmount. */
    async setTreatment(
      write: Expected & { treatment: FinancingTreatment },
    ): Promise<boolean> {
      const { propertyId, actorId, treatment, from, latestStart } = write
      const scope = eq(financingTreatments.propertyId, propertyId)
      if (latestStart === from) {
        const [updated] = await atomically(db, [
          db
            .update(financingTreatments)
            .set({ treatment })
            .where(
              and(
                scope,
                eq(financingTreatments.validFrom, from),
                isNull(financingTreatments.validTo),
                isOwner(actorId, propertyId),
              ),
            )
            .returning({ id: financingTreatments.id }),
        ])
        return updated.length > 0
      }
      const id = crypto.randomUUID()
      const ready = and(
        eq(properties.id, propertyId),
        isOwner(actorId, propertyId),
        notExists(
          db
            .select({ one: sql`1` })
            .from(financingTreatments)
            .where(and(scope, gte(financingTreatments.validFrom, from))),
        ),
        latestStart === null
          ? notExists(
              db
                .select({ one: sql`1` })
                .from(financingTreatments)
                .where(scope),
            )
          : exists(
              db
                .select({ one: sql`1` })
                .from(financingTreatments)
                .where(
                  and(
                    scope,
                    eq(financingTreatments.validFrom, latestStart),
                    eq(financingTreatments.validTo, dayBefore(from)),
                  ),
                ),
            ),
      )
      const insert = db
        .insert(financingTreatments)
        .select(
          db
            .select({
              id: sql<string>`${id}`.as('id'),
              propertyId: properties.id,
              treatment: sql<FinancingTreatment>`${treatment}`.as('treatment'),
              validFrom: sql<string>`${from}`.as('valid_from'),
              validTo: sql<null>`null`.as('valid_to'),
            })
            .from(properties)
            .where(ready),
        )
        .returning({ id: financingTreatments.id })
      if (latestStart === null) {
        const [inserted] = await atomically(db, [insert])
        return inserted.length > 0
      }
      const [, inserted] = await atomically(db, [
        db
          .update(financingTreatments)
          .set({ validTo: dayBefore(from) })
          .where(
            and(
              scope,
              eq(financingTreatments.validFrom, latestStart),
              lt(financingTreatments.validFrom, from),
              isNull(financingTreatments.validTo),
              isOwner(actorId, propertyId),
            ),
          ),
        insert,
      ])
      return inserted.length > 0
    },
 
    /** Undoes the latest treatment change, like undoLatestAmount. */
    async undoLatestTreatment(undo: Undo): Promise<boolean> {
      const { propertyId, latestStart, previousStart } = undo
      const scope = eq(financingTreatments.propertyId, propertyId)
      const remove = db
        .delete(financingTreatments)
        .where(
          and(
            scope,
            eq(financingTreatments.validFrom, latestStart),
            isNull(financingTreatments.validTo),
            isOwner(undo.actorId, propertyId),
          ),
        )
        .returning({ id: financingTreatments.id })
      if (previousStart === null) {
        const [removed] = await atomically(db, [remove])
        return removed.length > 0
      }
      const [removed] = await atomically(db, [
        remove,
        db
          .update(financingTreatments)
          .set({ validTo: null })
          .where(
            and(
              scope,
              eq(financingTreatments.validFrom, previousStart),
              eq(financingTreatments.validTo, dayBefore(latestStart)),
              notExists(
                db
                  .select({ one: sql`1` })
                  .from(financingTreatments)
                  .where(
                    and(scope, eq(financingTreatments.validFrom, latestStart)),
                  ),
              ),
            ),
          ),
      ])
      return removed.length > 0
    },
  }
}
 
export type RecurringAmountRepository = ReturnType<
  typeof recurringAmountRepository
>