All files / src/features/usage-charges usage-charge.repository.server.ts

100% Statements 36/36
83.33% Branches 15/18
100% Functions 15/15
100% Lines 35/35

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                                                                                                                  243x     243x 282x                           243x 146x                             243x     39x 39x                   116x 5x   111x       111x 13x   98x                           98x   150x 283x 153x           295x 159x             150x     4x                             134x 134x 134x                                                             134x 134x         10x                     10x               4x 4x 2x                 2x   2x                                                                   2x            
// A flat's usage charges with their amount periods (openspec: usage-charges).
// Each write carries the owner check and the expected latest start in its
// statements (src/server/db/periods.ts), so a role lost or a period changed
// between the read and the write applies nothing. The server checks the
// same rules first to give the reason.
import { and, asc, eq, exists, inArray, ne, notExists, sql } from 'drizzle-orm'
import type { BatchItem } from 'drizzle-orm/batch'
import type { IsoDate } from '#/lib/dates'
import {
  periodUndoStatements,
  periodWriteStatements,
  usageChargePeriods,
} from '#/server/db/periods'
import {
  properties,
  propertyAccess,
  usageChargeAmounts,
  usageCharges,
  type ChargeBasis,
  type ChargeKind,
} from '#/server/db/schema'
import { atomically, type Db } from '#/server/platform/db.server'
import type { UsageChargePeriods } from './months'
 
export interface NewUsageCharge {
  actorId: string
  propertyId: string
  kind: ChargeKind
  basis: ChargeBasis
  /** Set for the kind `other`. */
  description: string | null
  /** Cents per month, or per occupant per month. */
  amount: number
  from: IsoDate
}
 
export interface UsageChargeWrite {
  actorId: string
  propertyId: string
  chargeId: string
  amount: number
  from: IsoDate
  latestStart: IsoDate
  /** True when `from` is the latest period's start: it is corrected. */
  corrects?: boolean
}
 
/** An undo's expectation; no previous start means removing the charge. */
export interface UsageChargeUndo {
  actorId: string
  propertyId: string
  chargeId: string
  latestStart: IsoDate
  previousStart: IsoDate | null
}
 
export function usageChargeRepository(db: Db) {
  const one = sql`1`
 
  /** The actor owns the flat. */
  const isOwner = (actorId: string, propertyId: string) =>
    exists(
      db
        .select({ one })
        .from(propertyAccess)
        .where(
          and(
            eq(propertyAccess.propertyId, propertyId),
            eq(propertyAccess.userId, actorId),
            eq(propertyAccess.role, 'owner'),
          ),
        ),
    )
 
  /** The charge is the flat's and the actor owns the flat. */
  const ownsCharge = (actorId: string, propertyId: string, chargeId: string) =>
    and(
      isOwner(actorId, propertyId),
      exists(
        db
          .select({ one })
          .from(usageCharges)
          .where(
            and(
              eq(usageCharges.id, chargeId),
              eq(usageCharges.propertyId, propertyId),
            ),
          ),
      ),
    )
 
  return {
    /** The flat's usage charges with their periods, oldest first. */
    async forProperty(propertyId: string): Promise<UsageChargePeriods[]> {
      const byFlat = await this.forProperties([propertyId])
      return byFlat[propertyId] ?? []
    },
 
    /**
     * The usage charges of each flat with their periods, by flat id, in the
     * order `forProperty` gives. Every id has an entry.
     */
    async forProperties(
      propertyIds: string[],
    ): Promise<Record<string, UsageChargePeriods[]>> {
      if (propertyIds.length === 0) {
        return {}
      }
      const charges = await db
        .select()
        .from(usageCharges)
        .where(inArray(usageCharges.propertyId, propertyIds))
      if (charges.length === 0) {
        return Object.fromEntries(propertyIds.map((id) => [id, []]))
      }
      const amounts = await db
        .select({
          chargeId: usageChargeAmounts.usageChargeId,
          validFrom: usageChargeAmounts.validFrom,
          validTo: usageChargeAmounts.validTo,
          value: usageChargeAmounts.amount,
        })
        .from(usageChargeAmounts)
        .innerJoin(
          usageCharges,
          eq(usageCharges.id, usageChargeAmounts.usageChargeId),
        )
        .where(inArray(usageCharges.propertyId, propertyIds))
        .orderBy(asc(usageChargeAmounts.validFrom))
      return Object.fromEntries(
        propertyIds.map((propertyId) => {
          const result = charges
            .filter((charge) => charge.propertyId === propertyId)
            .map((charge) => ({
              id: charge.id,
              kind: charge.kind,
              basis: charge.basis,
              description: charge.description,
              periods: amounts
                .filter((a) => a.chargeId === charge.id)
                .map(({ validFrom, validTo, value }) => ({
                  validFrom,
                  validTo,
                  value,
                })),
            }))
          // In the order they were started, so the pages keep a stable order.
          return [
            propertyId,
            result.sort(
              (a, b) =>
                (a.periods[0]?.validFrom ?? '').localeCompare(
                  b.periods[0]?.validFrom ?? '',
                ) || a.id.localeCompare(b.id),
            ),
          ]
        }),
      )
    },
 
    /**
     * Adds a usage charge with its first period, both or neither. Returns
     * its id, or null when the actor isn't an owner.
     */
    async add(charge: NewUsageCharge): Promise<string | null> {
      const { actorId, propertyId } = charge
      const chargeId = crypto.randomUUID()
      const statements: [BatchItem<'sqlite'>, ...BatchItem<'sqlite'>[]] = [
        db
          .insert(usageCharges)
          .select(
            db
              .select({
                id: sql<string>`${chargeId}`.as('id'),
                propertyId: properties.id,
                kind: sql<ChargeKind>`${charge.kind}`.as('kind'),
                basis: sql<ChargeBasis>`${charge.basis}`.as('basis'),
                description: sql<string | null>`${charge.description}`.as(
                  'description',
                ),
              })
              .from(properties)
              .where(
                and(
                  eq(properties.id, propertyId),
                  isOwner(actorId, propertyId),
                ),
              ),
          )
          .returning({ id: usageCharges.id }),
        ...periodWriteStatements(db, usageChargePeriods, {
          parentId: chargeId,
          value: charge.amount,
          from: charge.from,
          latestStart: null,
          owned: ownsCharge(actorId, propertyId, chargeId),
        }),
      ]
      const results = await atomically(db, statements)
      return (results[0] as unknown[]).length > 0 ? chargeId : null
    },
 
    /** A new amount from `write.from`, or a correction of the latest. */
    async setAmount(write: UsageChargeWrite): Promise<boolean> {
      const results = await atomically(
        db,
        periodWriteStatements(db, usageChargePeriods, {
          parentId: write.chargeId,
          value: write.amount,
          from: write.from,
          latestStart: write.latestStart,
          corrects: write.corrects ?? false,
          owned: ownsCharge(write.actorId, write.propertyId, write.chargeId),
        }),
      )
      return (results.at(-1) as unknown[]).length > 0
    },
 
    /**
     * Undoes the latest change: deletes the latest period and reopens the
     * previous one, or removes the charge with its only period.
     */
    async undoLatest(undo: UsageChargeUndo): Promise<boolean> {
      const { actorId, propertyId, chargeId, latestStart } = undo
      if (undo.previousStart !== null) {
        const results = await atomically(
          db,
          periodUndoStatements(db, usageChargePeriods, {
            parentId: chargeId,
            latestStart,
            previousStart: undo.previousStart,
            owned: ownsCharge(actorId, propertyId, chargeId),
          }),
        )
        return (results[0] as unknown[]).length > 0
      }
      const results = await atomically(db, [
        db
          .delete(usageCharges)
          .where(
            and(
              eq(usageCharges.id, chargeId),
              eq(usageCharges.propertyId, propertyId),
              isOwner(actorId, propertyId),
              exists(
                db
                  .select({ one })
                  .from(usageChargeAmounts)
                  .where(
                    and(
                      eq(usageChargeAmounts.usageChargeId, chargeId),
                      eq(usageChargeAmounts.validFrom, latestStart),
                    ),
                  ),
              ),
              notExists(
                db
                  .select({ one })
                  .from(usageChargeAmounts)
                  .where(
                    and(
                      eq(usageChargeAmounts.usageChargeId, chargeId),
                      ne(usageChargeAmounts.validFrom, latestStart),
                    ),
                  ),
              ),
            ),
          )
          .returning({ id: usageCharges.id }),
      ])
      return (results[0] as unknown[]).length > 0
    },
  }
}
 
export type UsageChargeRepository = ReturnType<typeof usageChargeRepository>