All files / src/features/ownership periods.ts

100% Statements 42/42
97.22% Branches 35/36
100% Functions 16/16
100% Lines 38/38

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                40x                                                     494x 494x 623x           623x 623x   494x 540x   83x   49x         15710x 21371x   15710x                                 26x   49x     3x   46x 1x   23x 1x   43x 2x   19x                       22x 2x   20x 2x   18x                       7x 1x   6x 2x   4x               139x 139x               4x 4x 9x          
// Ownership periods as pure rules (openspec: ownership): grouping stored
// rows into periods, the split on a date, and the checks on a new split and
// its date. No database access, so the year summary can reuse them.
import { parseDecimal } from '#/lib/decimal'
import type { IsoDate } from '#/lib/dates'
import type { OwnershipReason } from '#/server/db/schema'
 
/** All of a flat: shares are basis points and add up to this. */
export const WHOLE = 10000
 
export interface Share {
  userId: string
  /** Basis points: 5000 = 50 %. */
  share: number
}
 
/** One stored row: an owner's share in one period. */
export interface PeriodRow extends Share {
  validFrom: IsoDate
  /** Null for the current period. */
  validTo: IsoDate | null
  reason: OwnershipReason | null
}
 
/** The rows that share a start date: one split of the flat. */
export interface Period {
  validFrom: IsoDate
  validTo: IsoDate | null
  reason: OwnershipReason | null
  /** Larger shares first. */
  shares: Share[]
}
 
/** Groups rows into periods, newest first. */
export function groupPeriods(rows: readonly PeriodRow[]): Period[] {
  const byStart = new Map<IsoDate, Period>()
  for (const row of rows) {
    const period = byStart.get(row.validFrom) ?? {
      validFrom: row.validFrom,
      validTo: row.validTo,
      reason: row.reason,
      shares: [],
    }
    period.shares.push({ userId: row.userId, share: row.share })
    byStart.set(row.validFrom, period)
  }
  return [...byStart.values()]
    .map((p) => ({
      ...p,
      shares: [...p.shares].sort((a, b) => b.share - a.share),
    }))
    .sort((a, b) => (a.validFrom < b.validFrom ? 1 : -1))
}
 
/** The split on a date, or no shares when no period contains it. */
export function sharesOn(periods: readonly Period[], date: IsoDate): Share[] {
  const period = periods.find(
    (p) => p.validFrom <= date && (p.validTo === null || date <= p.validTo),
  )
  return period?.shares ?? []
}
 
export type SplitProblem =
  | 'ownership_shares_total'
  | 'ownership_share_invalid'
  | 'ownership_no_owner'
  | 'ownership_invalid'
 
/**
 * Checks a new split: every share a whole number of basis points between 0
 * and 10000, each person once, at least one share above 0 and the total
 * exactly 10000.
 */
export function validateSplit(
  entries: readonly Share[],
): SplitProblem | undefined {
  if (
    entries.some(
      (e) => !Number.isSafeInteger(e.share) || e.share < 0 || e.share > WHOLE,
    )
  ) {
    return 'ownership_share_invalid'
  }
  if (new Set(entries.map((e) => e.userId)).size !== entries.length) {
    return 'ownership_invalid'
  }
  if (!entries.some((e) => e.share > 0)) {
    return 'ownership_no_owner'
  }
  if (entries.reduce((sum, e) => sum + e.share, 0) !== WHOLE) {
    return 'ownership_shares_total'
  }
  return undefined
}
 
/**
 * A change starts on or after the current period's start, and not after
 * today. On the start itself it corrects the current split.
 */
export function validateChangeDate(
  from: IsoDate,
  currentStart: IsoDate,
  today: IsoDate,
): 'ownership_date_too_early' | 'ownership_date_in_future' | undefined {
  if (from > today) {
    return 'ownership_date_in_future'
  }
  if (from < currentStart) {
    return 'ownership_date_too_early'
  }
  return undefined
}
 
/**
 * The first period's start can move, but not past today or to the start of
 * the next period.
 */
export function validateFirstDate(
  date: IsoDate,
  nextStart: IsoDate | undefined,
  today: IsoDate,
): 'ownership_date_in_future' | 'ownership_date_too_late' | undefined {
  if (date > today) {
    return 'ownership_date_in_future'
  }
  if (nextStart !== undefined && date >= nextStart) {
    return 'ownership_date_too_late'
  }
  return undefined
}
 
/**
 * A share typed in percent, with a comma or a point and at most two
 * decimals, as basis points (`33,33` = 3333); undefined for anything else.
 */
export function parsePercent(text: string): number | undefined {
  const value = parseDecimal(text.replace('%', ''), 2)
  return value !== undefined && value <= WHOLE ? value : undefined
}
 
/**
 * Equal shares for everyone, the rounding remainder to the first:
 * three people get 3334, 3333 and 3333.
 */
export function equalSplit(userIds: readonly string[]): Share[] {
  const base = Math.floor(WHOLE / userIds.length)
  const remainder = WHOLE - base * userIds.length
  return userIds.map((userId, i) => ({
    userId,
    share: i === 0 ? base + remainder : base,
  }))
}