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

89.23% Statements 58/65
78.94% Branches 30/38
100% Functions 10/10
88.88% Lines 56/63

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                                                                        1x       1x         1x                                   27x 27x 1x   26x             12x 12x     12x       12x                             22x 22x 3x   19x       38x 38x 19x 38x 1x   1x   18x 18x 1x   17x 17x     17x         17x 2x   15x                 15x     15x     30x       15x             2x 2x     2x 2x 2x 2x 1x   1x                   1x       1x               3x 3x 1x   2x 2x 2x     2x         2x 1x   1x                   1x 1x    
// Flat ownership: the logic behind the server functions in functions.ts,
// with its dependencies passed in so Workers tests can drive it (openspec:
// ownership).
import type {
  Person,
  SharingRepository,
} from '#/features/sharing/sharing.repository.server'
import { isoDateInFinland, type IsoDate } from '#/lib/dates'
import type { AlertReason, FieldReason } from '#/lib/reasons'
import type { OwnershipReason, PropertyRole } from '#/server/db/schema'
import type { Logger } from '#/server/log/log'
import type {
  OwnershipHistory,
  OwnershipRepository,
} from './ownership.repository.server'
import {
  validateChangeDate,
  validateFirstDate,
  validateSplit,
  type Share,
} from './periods'
 
export interface OwnershipDeps {
  /** The signed-in user. */
  userId: string
  ownership: OwnershipRepository
  sharing: SharingRepository
  log: Logger
  now: () => Date
}
 
interface Failure<R extends FieldReason | AlertReason = AlertReason> {
  ok: false
  reason: R
}
 
const notFound = {
  ok: false,
  reason: 'property_not_found',
} as const satisfies Failure
const ownerOnly = {
  ok: false,
  reason: 'sharing_owner_only',
} as const satisfies Failure
/** The data changed since it was read; the page reloads it. */
const changedMeanwhile = {
  ok: false,
  reason: 'ownership_invalid',
} as const satisfies Failure
 
export interface OwnershipView extends OwnershipHistory {
  /** The signed-in user's id, to show them as "You". */
  you: string
  role: PropertyRole
  /** Everyone with access now, who can be in a new split. */
  people: Person[]
}
 
/** Checks the user's role; the flat is "not found" without access. */
async function roleCheck(
  deps: OwnershipDeps,
  propertyId: string,
): Promise<typeof notFound | typeof ownerOnly | undefined> {
  const role = await deps.sharing.roleOf(deps.userId, propertyId)
  if (!role) {
    return notFound
  }
  return role === 'owner' ? undefined : ownerOnly
}
 
export async function getOwnership(
  deps: OwnershipDeps,
  propertyId: string,
): Promise<({ ok: true } & OwnershipView) | typeof notFound> {
  const role = await deps.sharing.roleOf(deps.userId, propertyId)
  Iif (!role) {
    return notFound
  }
  const [history, people] = await Promise.all([
    deps.ownership.history(propertyId),
    deps.sharing.listPeople(propertyId),
  ])
  return { ok: true, you: deps.userId, role, people, ...history }
}
 
export interface OwnershipChange {
  from: IsoDate
  reason: OwnershipReason
  split: Share[]
  removeAccess: string[]
}
 
export async function changeOwnership(
  deps: OwnershipDeps,
  propertyId: string,
  change: OwnershipChange,
): Promise<{ ok: true } | Failure<FieldReason | AlertReason>> {
  const refused = await roleCheck(deps, propertyId)
  if (refused) {
    return refused
  }
  const [{ periods }, people] = await Promise.all([
    deps.ownership.history(propertyId),
    deps.sharing.listPeople(propertyId),
  ])
  const withAccess = new Set(people.map((p) => p.userId))
  const sharesOf = new Map(change.split.map((s) => [s.userId, s.share]))
  if (
    change.split.some((s) => !withAccess.has(s.userId)) ||
    change.removeAccess.some((id) => (sharesOf.get(id) ?? 0) > 0)
  ) {
    return changedMeanwhile
  }
  const problem = validateSplit(change.split)
  if (problem) {
    return { ok: false, reason: problem }
  }
  const current = periods.at(0)
  Iif (!current) {
    return changedMeanwhile
  }
  const dateProblem = validateChangeDate(
    change.from,
    current.validFrom,
    isoDateInFinland(deps.now()),
  )
  if (dateProblem) {
    return { ok: false, reason: dateProblem }
  }
  const applied = await deps.ownership.change({
    propertyId,
    actorId: deps.userId,
    currentStart: current.validFrom,
    from: change.from,
    reason: change.reason,
    split: change.split,
    removeAccess: change.removeAccess,
  })
  Iif (!applied) {
    return changedMeanwhile
  }
  deps.log.info('ownership.changed', {
    propertyId,
    from: change.from,
    owners: change.split.filter((s) => s.share > 0).length,
    accessRemoved: change.removeAccess.length,
    corrected: change.from === current.validFrom,
  })
  return { ok: true }
}
 
export async function undoOwnershipChange(
  deps: OwnershipDeps,
  propertyId: string,
): Promise<{ ok: true } | Failure> {
  const refused = await roleCheck(deps, propertyId)
  Iif (refused) {
    return refused
  }
  const { periods } = await deps.ownership.history(propertyId)
  const latest = periods.at(0)
  const previous = periods.at(1)
  if (!latest || !previous) {
    return { ok: false, reason: 'ownership_nothing_to_undo' }
  }
  Iif (
    !(await deps.ownership.undoLatest({
      propertyId,
      actorId: deps.userId,
      latest,
      previous,
    }))
  ) {
    return changedMeanwhile
  }
  deps.log.info('ownership.change_undone', {
    propertyId,
    from: latest.validFrom,
  })
  return { ok: true }
}
 
export async function correctFirstOwnershipDate(
  deps: OwnershipDeps,
  propertyId: string,
  date: IsoDate,
): Promise<{ ok: true } | Failure<FieldReason | AlertReason>> {
  const refused = await roleCheck(deps, propertyId)
  if (refused) {
    return refused
  }
  const { periods } = await deps.ownership.history(propertyId)
  const first = periods.at(-1)
  Iif (!first) {
    return changedMeanwhile
  }
  const problem = validateFirstDate(
    date,
    periods.at(-2)?.validFrom,
    isoDateInFinland(deps.now()),
  )
  if (problem) {
    return { ok: false, reason: problem }
  }
  Iif (
    !(await deps.ownership.correctFirstDate({
      propertyId,
      actorId: deps.userId,
      firstStart: first.validFrom,
      date,
    }))
  ) {
    return changedMeanwhile
  }
  deps.log.info('ownership.first_date_corrected', { propertyId })
  return { ok: true }
}