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 | 78x 78x 78x 121x 75x 75x 341x 75x 75x 121x 121x 575x 341x 247x 1x 1x 103x 1x 119x 78x 11x 67x 35x 67x 57x 57x 75x 11x 64x 34x 15x 23x 8x 23x 41x 57x 57x 57x 57x 93x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 57x 103x 103x 103x 2x 101x 101x 17x 16x 17x 84x 84x 84x 336x 57x 57x 103x 155x 283x 57x 57x 93x 85x 41x 5x 57x 57x 7x 11x 11x 4x 16x 26x 16x 22x 22x 22x 22x 22x 16x 21x 21x 27x 21x 3x 24x 18x 18x 18x 6x 3x 3x 3x 18x 18x 18x 18x 18x 18x 18x | // The year summary: the logic behind the server functions in functions.ts,
// with its dependencies passed in so Workers tests can drive it (openspec:
// year-summary). The user's flats, archived included, are the access check;
// every other read is by their ids, so the number of queries doesn't grow
// with the flats (design decision 2). Each function returns the computed
// view only: other owners' ids, payment rows and tenancies outside the year
// never reach the browser. It only reads, so it logs nothing.
import type { DepositReturnRepository } from '#/features/deposits/deposit-return.repository.server'
import type { OwnershipRepository } from '#/features/ownership/ownership.repository.server'
import type { Period } from '#/features/ownership/periods'
import type { Property } from '#/features/properties/property'
import type { PropertyRepository } from '#/features/properties/property.repository.server'
import type { RecurringAmountRepository } from '#/features/recurring-amounts/recurring-amount.repository.server'
import type { RentPaymentRepository } from '#/features/rent-payments/rent-payment.repository.server'
import type { TenancyRepository } from '#/features/tenancies/tenancy.repository.server'
import type { TransactionRepository } from '#/features/transactions/transaction.repository.server'
import type { UsageChargeRepository } from '#/features/usage-charges/usage-charge.repository.server'
import { isoDateInFinland, type IsoDate } from '#/lib/dates'
import {
clampYear,
flatYear,
openingYear,
ownedInYear,
ownersInYear,
shareAtEnd,
summaryYears,
type FlatYear,
type FlatYearInput,
type Holder,
} from './summary'
import type {
CardOwner,
FlatCard,
FlatOwner,
FlatYearView,
HolderView,
PdfFlat,
YearSummaryPdfView,
YearSummaryView,
} from './view'
export interface YearSummaryDeps {
/** The signed-in user. */
userId: string
properties: PropertyRepository
ownership: OwnershipRepository
tenancies: TenancyRepository
payments: RentPaymentRepository
depositReturns: DepositReturnRepository
transactions: TransactionRepository
amounts: RecurringAmountRepository
usageCharges: UsageChargeRepository
now: () => Date
}
const today = (deps: YearSummaryDeps) => isoDateInFinland(deps.now())
/**
* The user's flats, archived included, and the flats they formerly owned
* (openspec: year-summary, "A former owner's year summary"): the access
* check. The former flats are read for the own share only.
*/
async function userFlats(
deps: YearSummaryDeps,
): Promise<{ accessible: Property[]; former: Property[] }> {
const [active, archived, former] = await Promise.all([
deps.properties.listForUser(deps.userId),
deps.properties.listArchivedForUser(deps.userId),
deps.properties.listFormerlyOwnedForUser(deps.userId),
])
return { accessible: [...active, ...archived], former }
}
/** Every flat's data for the year, with a fixed number of queries. */
async function loadInputs(
deps: YearSummaryDeps,
flats: readonly Property[],
year: (ownership: Partial<Record<string, Period[]>>) => number,
): Promise<{
year: number
inputs: FlatYearInput[]
names: Record<string, string>
}> {
const ids = flats.map((flat) => flat.id)
const [ownership, names, tenancies, payments, amounts, usage] =
await Promise.all([
deps.ownership.rowsFor(ids),
deps.ownership.namesFor(ids),
deps.tenancies.forProperties(ids),
deps.payments.forProperties(ids),
deps.amounts.forProperties(ids),
deps.usageCharges.forProperties(ids),
])
const chosen = year(ownership)
const tenancyIds = tenancies.map((t) => t.id)
const [entries, returns, rents, occupants, fees] = await Promise.all([
deps.transactions.forPropertiesYear(ids, chosen),
deps.depositReturns.forPropertiesYear(ids, chosen),
deps.tenancies.rentsFor(tenancyIds),
deps.tenancies.occupantsFor(tenancyIds),
deps.tenancies.feesFor(tenancyIds),
])
return {
year: chosen,
names,
inputs: flats.map((flat) => {
const flatAmounts = amounts[flat.id]
return {
propertyId: flat.id,
housingCompany: {
name: flat.housingCompanyName ?? null,
businessId: flat.businessId ?? null,
apartmentNumber: flat.apartmentNumber ?? null,
},
ownership: ownership[flat.id] ?? [],
tenancies: tenancies
.filter((t) => t.propertyId === flat.id)
.map((t) => ({
id: t.id,
tenantName: t.tenantName,
validFrom: t.validFrom,
validTo: t.validTo,
dueDay: t.dueDay,
occupants: occupants[t.id] ?? [],
rent: rents[t.id] ?? [],
fees: fees[t.id] ?? [],
})),
payments: payments.filter((p) => p.propertyId === flat.id),
entries: entries.filter((e) => e.propertyId === flat.id),
depositReturns: returns.filter((r) => r.propertyId === flat.id),
charges: {
maintenance: flatAmounts.amounts.maintenance_charge,
financing: flatAmounts.financingCharges,
},
treatments: flatAmounts.treatments,
usageCharges: usage[flat.id],
}
}),
}
}
/** The ownership of the flats with these ids. */
const pick = (
ownership: Partial<Record<string, Period[]>>,
ids: ReadonlySet<string>,
): Partial<Record<string, Period[]>> =>
Object.fromEntries(Object.entries(ownership).filter(([id]) => ids.has(id)))
/** The periods of every flat in one list. */
const periodsOf = (ownership: Partial<Record<string, Period[]>>): Period[] =>
Object.values(ownership).flat() as Period[]
/**
* Whose figures to compute: the own share unless `person` is `whole` or
* another user with a share above 0 in these flats in some year. Any other
* id gives the own share, so a guessed id shows nothing.
*/
function holderOf(
deps: YearSummaryDeps,
periods: readonly Period[],
person: string | undefined,
): Holder {
if (person === 'whole') {
return { kind: 'whole' }
}
const known =
person !== undefined &&
person !== deps.userId &&
periods.some((p) =>
p.shares.some((s) => s.userId === person && s.share > 0),
)
return { kind: 'owner', userId: known ? person : deps.userId }
}
/**
* The years of the holder's shares across the flats, oldest first. An own
* share without any (a member with no share) uses the whole flats' years,
* of `visible` (the flats with access) when given.
*/
function yearsOf(
periods: readonly Period[],
holder: Holder,
day: IsoDate,
visible: readonly Period[] = periods,
): number[] {
const years = summaryYears(periods, holder, day)
return years.length > 0
? years
: summaryYears(visible, { kind: 'whole' }, day)
}
/** The holder as the view names them. */
function holderView(
deps: YearSummaryDeps,
holder: Holder,
names: Record<string, string>,
): HolderView {
if (holder.kind === 'whole') {
return { kind: 'whole' }
}
return holder.userId === deps.userId
? { kind: 'own' }
: {
kind: 'person',
userId: holder.userId,
name: names[holder.userId] ?? '',
}
}
const isYou = (deps: YearSummaryDeps, userId: string) => userId === deps.userId
/** The owners of a flat in the year as a card shows them, you first. */
function cardOwners(
deps: YearSummaryDeps,
input: FlatYearInput,
names: Record<string, string>,
year: number,
day: IsoDate,
): CardOwner[] {
return ownersInYear(input.ownership, year, day)
.map((userId) => ({
userId,
name: names[userId] ?? '',
share: shareAtEnd(input.ownership, { kind: 'owner', userId }, year, day),
isYou: isYou(deps, userId),
}))
.sort(
(a, b) =>
Number(b.isYou) - Number(a.isYou) || a.name.localeCompare(b.name),
)
.map(({ name, share, isYou: you }) => ({ name, share, isYou: you }))
}
/**
* The year summary: a card per flat the holder had a share in during the
* year, archived flats included, and the other flats named. The holder is the
* user's own share, another owner of the user's flats (`person`: their id)
* or the whole flats (`person`: `whole`). Without `year` it opens on the
* opening year; a year outside the range opens the nearest.
*/
export async function loadYearSummary(
deps: YearSummaryDeps,
year?: number,
person?: string,
): Promise<YearSummaryView> {
return (await summarise(deps, year, person)).view
}
/** The year summary with the flat years it was computed from. */
async function summarise(
deps: YearSummaryDeps,
year: number | undefined,
person: string | undefined,
) {
const day = today(deps)
const { accessible, former } = await userFlats(deps)
const flats = [...accessible, ...former]
const formerIds = new Set(former.map((flat) => flat.id))
const accessibleIds = new Set(accessible.map((flat) => flat.id))
let years: number[] = []
let holder = { kind: 'owner', userId: deps.userId } as Holder
const loaded = await loadInputs(deps, flats, (ownership) => {
// A former flat never makes someone a known person, and only the own
// share's years count it.
const visible = periodsOf(pick(ownership, accessibleIds))
holder = holderOf(deps, visible, person)
const own = holder.kind === 'owner' && holder.userId === deps.userId
years = yearsOf(own ? periodsOf(ownership) : visible, holder, day, visible)
return year === undefined ? openingYear(years, day) : clampYear(years, year)
})
const ownShare = holder.kind === 'owner' && holder.userId === deps.userId
const cards: FlatCard[] = []
const results = new Map<string, FlatYear>()
const notIncluded: YearSummaryView['notIncluded'] = []
for (const [i, input] of loaded.inputs.entries()) {
const flat = flats[i]
const isFormer = formerIds.has(flat.id)
if (isFormer && !ownShare) {
continue
}
const result = flatYear(input, holder, loaded.year, day, {
ownDaysOnly: isFormer,
})
if (!result.included) {
if (holder.kind === 'owner' && !isFormer) {
notIncluded.push({
propertyId: flat.id,
streetAddress: flat.streetAddress,
})
}
continue
}
results.set(flat.id, result)
const { '2.1': income, ...costRows } = result.rows
cards.push({
propertyId: flat.id,
streetAddress: flat.streetAddress,
housingCompanyName: result.details.name,
businessId: result.details.businessId,
share: result.details.share,
income: income.cents,
costs: Object.values(costRows).reduce((sum, row) => sum + row.cents, 0),
checks: result.checks,
owners:
holder.kind === 'whole'
? cardOwners(deps, input, loaded.names, loaded.year, day)
: [],
})
}
const me = { kind: 'owner', userId: deps.userId } as const
const visibleInputs = loaded.inputs.filter((i) =>
accessibleIds.has(i.propertyId),
)
// Only the own share counts the flats formerly owned.
const count = (of: Holder, withFormer = false) =>
(withFormer ? loaded.inputs : visibleInputs).filter((i) =>
ownedInYear(i.ownership, of, loaded.year, day),
).length
// A chosen person without a share in the year is listed with 0 flats, so
// the selector stays and the choice stays marked.
const chosen =
holder.kind === 'owner' && holder.userId !== deps.userId
? [holder.userId]
: []
const people = [
...new Set([
...visibleInputs.flatMap((i) =>
ownersInYear(i.ownership, loaded.year, day),
),
...chosen,
]),
]
.filter((userId) => userId !== deps.userId)
.map((userId) => ({
userId,
name: loaded.names[userId] ?? '',
flats: count({ kind: 'owner', userId }),
}))
.sort((a, b) => a.name.localeCompare(b.name))
const view: YearSummaryView = {
today: day,
year: loaded.year,
years,
holder: holderView(deps, holder, loaded.names),
people,
counts: { own: count(me, true), whole: count({ kind: 'whole' }) },
flats: cards,
notIncluded,
}
return { view, holder, flats, loaded, results, day }
}
/** The owners of a whole flat with their row 2.1, you first. */
function flatOwners(
deps: YearSummaryDeps,
input: FlatYearInput,
names: Record<string, string>,
year: number,
day: IsoDate,
): FlatOwner[] {
return ownersInYear(input.ownership, year, day)
.map((userId) => {
const own = flatYear(input, { kind: 'owner', userId }, year, day)
return {
userId,
name: names[userId] ?? '',
share: own.details.share,
income: own.rows['2.1'].cents,
isYou: isYou(deps, userId),
}
})
.sort(
(a, b) =>
Number(b.isYou) - Number(a.isYou) || a.name.localeCompare(b.name),
)
}
/**
* Everything the year summary PDF shows, for the same holder and year as the
* page: the cards and each flat's full year, computed once.
* Both lists are unsorted, one flat per card in the same order: the document
* sorts them by address in the user's language. The PDF is built in the browser.
*/
export async function loadYearSummaryPdf(
deps: YearSummaryDeps,
year?: number,
person?: string,
): Promise<YearSummaryPdfView> {
const { view, holder, flats, loaded, results, day } = await summarise(
deps,
year,
person,
)
const byId = new Map(flats.map((flat, i) => [flat.id, i]))
const pdfFlats = view.flats.map((card): PdfFlat => {
const flat = flats[byId.get(card.propertyId) ?? 0]
const input = loaded.inputs[byId.get(card.propertyId) ?? 0]
const result = results.get(card.propertyId)
Iif (!result) {
throw new Error('A card without its flat year')
}
return {
propertyId: flat.id,
streetAddress: flat.streetAddress,
postcode: flat.postcode,
city: flat.city,
owners:
holder.kind === 'whole'
? flatOwners(deps, input, loaded.names, loaded.year, day)
: [],
rows: result.rows,
outside: result.outside,
details: result.details,
checks: result.checks,
}
})
return {
holder: view.holder,
holderName:
holder.kind === 'whole' ? '' : (loaded.names[holder.userId] ?? ''),
today: view.today,
year: view.year,
cards: view.flats,
notIncluded: view.notIncluded,
flats: pdfFlats,
}
}
/**
* A flat's form 7H page for the year: not found unless the user can see the
* flat (archived included), and no figures in a year without the holder's
* share. The holder is chosen as in the summary, among the owners of all
* the user's flats. Without `year` it opens on the opening year of the
* holder's years in this flat.
*/
export async function loadFlatYear(
deps: YearSummaryDeps,
propertyId: string,
year?: number,
person?: string,
): Promise<FlatYearView> {
const day = today(deps)
const { accessible, former } = await userFlats(deps)
const flat = [...accessible, ...former].find((f) => f.id === propertyId)
if (!flat) {
return { ok: false, reason: 'property_not_found' }
}
// A flat the user formerly owned opens for the own share, whatever `person`
// says, and with no owners.
const isFormer = !accessible.some((f) => f.id === propertyId)
// Another owner is known from all the user's flats, as in the summary, so
// an owner of another flat gets this flat's no-share state with their name.
let holder = holderOf(deps, [], isFormer ? undefined : person)
let names: Record<string, string> = {}
if (!isFormer && holder.kind === 'owner' && person !== undefined) {
const ids = accessible.map((f) => f.id)
const [ownership, allNames] = await Promise.all([
deps.ownership.rowsFor(ids),
deps.ownership.namesFor(ids),
])
holder = holderOf(deps, periodsOf(ownership), person)
names = allNames
}
const loaded = await loadInputs(deps, [flat], (ownership) => {
const periods = periodsOf(ownership)
return year ?? openingYear(yearsOf(periods, holder, day), day)
})
const [input] = loaded.inputs
const { included, rows, outside, details, checks } = flatYear(
input,
holder,
loaded.year,
day,
{ ownDaysOnly: isFormer },
)
const owners =
holder.kind === 'whole' && included
? flatOwners(deps, input, loaded.names, loaded.year, day)
: []
return {
ok: true,
today: day,
year: loaded.year,
property: {
id: flat.id,
streetAddress: flat.streetAddress,
postcode: flat.postcode,
city: flat.city,
},
holder: holderView(deps, holder, { ...names, ...loaded.names }),
owners,
former: isFormer,
flat: included ? { rows, outside, details, checks } : null,
}
}
|