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

92.81% Statements 310/334
85.22% Branches 248/291
97.87% Functions 46/47
92.5% Lines 296/320

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 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080                                                                                                                                    3x       3x       3x       65x                                   299x 299x     299x                 3x             172x 172x     259x                                 39x         39x 1x   40x 38x         38x                                                             37x 37x 1x   36x 36x   38x   36x                                             2x       2x     2x                                                                             10x           10x     11x 10x 1x   9x           9x                   10x                                       136x 136x 2x   134x       134x     134x     134x           134x 9x     125x 125x 3x 3x 3x     3x 3x 2x   1x 1x                       123x                   123x     123x           123x                 28x 28x 2x   26x       26x 26x         26x 26x         27x     26x 2x       24x                           3x     21x 21x 4x 4x 2x   2x 1x     18x           18x 2x       16x 16x 16x 1x   15x 1x   14x 14x 14x         14x       14x 2x   12x   3x   1x   11x                     2x         11x   1x 1x               10x 10x                 34x 34x 1x   33x 33x 1x   32x 1x   31x 31x 1x   30x           30x 1x   29x 1x   28x     12x     2x   26x             26x 1x 1x               25x         25x                 6x 6x 1x   5x 5x     5x 5x 1x   4x 1x   3x           3x 1x       1x                   2x 2x               7x 7x     7x 9x 7x     7x 7x 1x   6x 1x   5x 1x   4x 4x   5x       4x 1x   3x           3x     3x 3x     3x                       15x 15x 1x   14x 14x 1x   13x 16x 13x 13x 13x 13x 13x 5x   8x                   8x     8x       8x                         3x 3x 1x   2x 2x     2x 2x 2x 2x 1x   1x             1x     1x 1x                         11x 11x 1x   10x 10x 1x   9x         2x   7x   7x 7x       7x 3x   4x 4x                 4x     4x       4x                         3x 3x 1x   2x 2x     2x   2x 2x 2x 1x   1x             1x     1x 1x                                         35x 35x 1x   34x 34x     34x         1x     33x 33x           1x   32x       32x 1x   31x                   31x     31x 31x                         16x 16x 2x   14x 14x 14x 2x   12x                             13x 13x 1x   12x 12x 2x   10x 10x             10x 10x       10x 2x   8x     8x 8x                   8x     8x       8x                         5x 5x 1x   4x 4x 2x   2x 2x     2x 2x               2x     2x               2x                         2x 2x 2x 2x     2x 2x 2x 2x     2x                     2x    
// Tenancies: the logic behind the server functions in functions.ts, with its
// dependencies passed in so Workers tests can drive it (openspec:
// tenancies). The rules are checked here first for the reason, and each
// write checks the owner role and the overlap again in its statement. The
// tenant's details are never logged.
import type {
  DepositReturn,
  DepositReturnRepository,
} from '#/features/deposits/deposit-return.repository.server'
import type {
  DocumentRepository,
  DocumentRow,
} from '#/features/documents/document.repository.server'
import type { OwnershipRepository } from '#/features/ownership/ownership.repository.server'
import type { Property } from '#/features/properties/property'
import type { PropertyRepository } from '#/features/properties/property.repository.server'
import type { Period } from '#/features/recurring-amounts/periods'
import type { SharingRepository } from '#/features/sharing/sharing.repository.server'
import { isoDateInFinland, type IsoDate } from '#/lib/dates'
import type { AlertReason, FieldReason } from '#/lib/reasons'
import type { NoticeGiver, PropertyRole } from '#/server/db/schema'
import type { Logger } from '#/server/log/log'
import { validateEnding } from './notice'
import { paymentsOutside, validateTenancyDates } from './rules'
import {
  fillsBeforeFirst,
  feeChangesAfterEnd,
  firstPeriodMove,
  firstRentMove,
  periodAfterEnd,
  rentAfterEnd,
  validateRentDate,
  validateTenancyPeriodDate,
} from './rent'
import { MAX_AMOUNT } from '#/features/recurring-amounts/schemas'
import { MAX_CHARGE_DESCRIPTION } from '#/lib/charge-fields'
import type { ChargeBasis, ChargeKind } from '#/server/db/schema'
import { offeredFees } from './fees'
import { MAX_OCCUPANTS } from './schemas'
import { currentTenancy, flatStatus } from './status'
import type {
  Ending,
  Tenancy,
  TenancyFields,
  TenancyRepository,
  TenantFee,
} from './tenancy.repository.server'
 
export interface TenancyDeps {
  /** The signed-in user. */
  userId: string
  tenancies: TenancyRepository
  depositReturns: DepositReturnRepository
  documents: DocumentRepository
  properties: PropertyRepository
  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
const tenancyNotFound = {
  ok: false,
  reason: 'tenancy_not_found',
} as const satisfies Failure
const fail = <R extends FieldReason | AlertReason>(reason: R): Failure<R> => ({
  ok: false,
  reason,
})
 
export interface TenancyView {
  role: PropertyRole
  property: Property
  /** Today in Finland. */
  today: IsoDate
  /** Newest first. */
  tenancies: Tenancy[]
}
 
async function roleCheck(
  deps: TenancyDeps,
  propertyId: string,
): Promise<typeof notFound | typeof ownerOnly | undefined> {
  const role = await deps.sharing.roleOf(deps.userId, propertyId)
  Iif (!role) {
    return notFound
  }
  return role === 'owner' ? undefined : ownerOnly
}
 
/** Why a write that didn't apply was refused: access, or the given reason. */
async function refusal<R extends Failure<FieldReason | AlertReason>>(
  deps: TenancyDeps,
  propertyId: string,
  otherwise: R,
): Promise<R | typeof notFound | typeof ownerOnly> {
  return (await roleCheck(deps, propertyId)) ?? otherwise
}
 
async function ownershipStart(
  deps: TenancyDeps,
  propertyId: string,
): Promise<IsoDate | undefined> {
  const { periods } = await deps.ownership.history(propertyId)
  return periods.at(-1)?.validFrom
}
 
const today = (deps: TenancyDeps) => isoDateInFinland(deps.now())
 
/**
 * The flat's tenancies with their rents, occupants and tenant fees, or
 * undefined without access.
 */
async function loadView(
  deps: TenancyDeps,
  propertyId: string,
): Promise<
  | (TenancyView & {
      rents: Partial<Record<string, Period<number>[]>>
      occupants: Partial<Record<string, Period<number>[]>>
      fees: Partial<Record<string, TenantFee[]>>
    })
  | undefined
> {
  const [role, property, tenancies] = await Promise.all([
    deps.sharing.roleOf(deps.userId, propertyId),
    deps.properties.findForUser(deps.userId, propertyId),
    deps.tenancies.forProperty(propertyId),
  ])
  if (!role || !property) {
    return undefined
  }
  const ids = tenancies.map((t) => t.id)
  const [rents, occupants, fees] = await Promise.all([
    deps.tenancies.rentsFor(ids),
    deps.tenancies.occupantsFor(ids),
    deps.tenancies.feesFor(ids),
  ])
  return {
    role,
    property,
    today: today(deps),
    tenancies,
    rents,
    occupants,
    fees,
  }
}
 
/** The flat's tenancies, for everyone with access. */
export async function getTenancies(
  deps: TenancyDeps,
  propertyId: string,
): Promise<
  | ({
      ok: true
      /** Each tenancy's rent periods, oldest first. */
      rents: Partial<Record<string, Period<number>[]>>
      /** Each tenancy's occupants periods, oldest first. */
      occupants: Partial<Record<string, Period<number>[]>>
      /** Each tenancy's tenant fees. */
      fees: Partial<Record<string, TenantFee[]>>
      /** The leases naming the current tenancy, newest first. */
      leases: DocumentRow[]
      /** Each tenancy's deposit return, if recorded. */
      depositReturns: Partial<Record<string, DepositReturn>>
    } & TenancyView)
  | typeof notFound
> {
  const view = await loadView(deps, propertyId)
  if (!view) {
    return notFound
  }
  const current = currentTenancy(view.tenancies, view.today)
  const [leases, returns] = await Promise.all([
    current ? deps.documents.leasesOfTenancy(current.id) : [],
    deps.depositReturns.forTenancies(view.tenancies.map((t) => t.id)),
  ])
  return {
    ok: true,
    ...view,
    leases,
    depositReturns: Object.fromEntries(returns.map((r) => [r.tenancyId, r])),
  }
}
 
/** What the new tenant form needs: the rent periods and the limits. */
export async function getNewTenancyOptions(
  deps: TenancyDeps,
  propertyId: string,
): Promise<
  | ({
      ok: true
      /** Each tenancy's rent periods, oldest first, for the suggestion. */
      tenancyRents: Partial<Record<string, Period<number>[]>>
      /** Each tenancy's tenant fees, for the fees offered to the next. */
      tenancyFees: Partial<Record<string, TenantFee[]>>
      ownershipStart: IsoDate
    } & TenancyView)
  | typeof notFound
> {
  const [view, start] = await Promise.all([
    loadView(deps, propertyId),
    ownershipStart(deps, propertyId),
  ])
  Iif (!view || start === undefined) {
    return notFound
  }
  return {
    ok: true,
    role: view.role,
    property: view.property,
    today: view.today,
    tenancies: view.tenancies,
    tenancyRents: view.rents,
    tenancyFees: view.fees,
    ownershipStart: start,
  }
}
 
/** A tenancy of the flat, for correcting or ending it. */
export async function getTenancy(
  deps: TenancyDeps,
  propertyId: string,
  tenancyId: string,
): Promise<
  | {
      ok: true
      role: PropertyRole
      property: Property
      today: IsoDate
      tenancy: Tenancy
      /** The tenancy's rent periods, oldest first. */
      rents: Period<number>[]
      /** The tenancy's occupants periods, oldest first. */
      occupants: Period<number>[]
      /** The tenancy's tenant fees. */
      fees: TenantFee[]
      /** The flat's other tenancies, for the form's checks. */
      others: Tenancy[]
      /** The tenancy's deposit return, if recorded. */
      depositReturn: DepositReturn | undefined
      ownershipStart: IsoDate
    }
  | typeof notFound
  | typeof tenancyNotFound
> {
  const [role, property, tenancies, start] = await Promise.all([
    deps.sharing.roleOf(deps.userId, propertyId),
    deps.properties.findForUser(deps.userId, propertyId),
    deps.tenancies.forProperty(propertyId),
    ownershipStart(deps, propertyId),
  ])
  Iif (!role || !property || start === undefined) {
    return notFound
  }
  const tenancy = tenancies.find((t) => t.id === tenancyId)
  if (!tenancy) {
    return tenancyNotFound
  }
  const [rents, occupants, fees, depositReturn] = await Promise.all([
    deps.tenancies.rentsFor([tenancyId]),
    deps.tenancies.occupantsFor([tenancyId]),
    deps.tenancies.feesFor([tenancyId]),
    deps.depositReturns.forTenancy(tenancyId),
  ])
  return {
    ok: true,
    role,
    property,
    today: today(deps),
    tenancy,
    depositReturn,
    rents: rents[tenancyId] ?? [],
    occupants: occupants[tenancyId] ?? [],
    fees: fees[tenancyId] ?? [],
    others: tenancies.filter((t) => t.id !== tenancyId),
    ownershipStart: start,
  }
}
 
export async function createTenancy(
  deps: TenancyDeps,
  propertyId: string,
  fields: TenancyFields,
  /** The monthly rent in cents, the tenancy's first rent from its start. */
  rent: number,
  /** The persons living in the flat, from the tenancy's start. */
  occupants: number,
  /** An earlier tenancy's ending, recorded with it. */
  ending?: Ending,
  /** Fees of the previous tenancy to continue, by id. */
  copyFeeIds: readonly string[] = [],
): Promise<
  { ok: true; tenancyId: string } | Failure<FieldReason | AlertReason>
> {
  const refused = await roleCheck(deps, propertyId)
  if (refused) {
    return refused
  }
  const [start, others] = await Promise.all([
    ownershipStart(deps, propertyId),
    deps.tenancies.forProperty(propertyId),
  ])
  Iif (start === undefined) {
    return notFound
  }
  const day = today(deps)
  // The ending first: its reasons say more than the overlap or the end
  // before the start that a wrong ending would also cause.
  const problem =
    (ending ? validateEnding(fields, ending, day) : undefined) ??
    validateTenancyDates(
      { ...fields, validTo: ending?.lastDay ?? fields.termEnd },
      { today: day, ownershipStart: start, others },
    )
  if (problem) {
    return fail(problem)
  }
  // Only fees the form offered: the previous tenancy's, not ended.
  let copied: Parameters<TenancyRepository['createWithRent']>[7] = []
  if (copyFeeIds.length > 0) {
    const feesById = await deps.tenancies.feesFor(others.map((t) => t.id))
    const offered = offeredFees(
      others.map((t) => ({ ...t, fees: feesById[t.id] ?? [] })),
      fields.validFrom,
    )
    const wanted = copyFeeIds.map((id) => offered.find((o) => o.fee.id === id))
    if (wanted.some((o) => o === undefined)) {
      return fail('tenant_fee_not_found')
    }
    copied = wanted.flatMap((o) =>
      o
        ? [
            {
              kind: o.fee.kind,
              basis: o.fee.basis,
              description: o.fee.description,
              amount: o.amount,
            },
          ]
        : [],
    )
  }
  const created = await deps.tenancies.createWithRent(
    deps.userId,
    propertyId,
    fields,
    rent,
    deps.now(),
    ending,
    occupants,
    copied,
  )
  Iif (created.outcome === 'overlaps') {
    return refusal(deps, propertyId, fail('tenancy_overlaps'))
  }
  deps.log.info('tenancy.created', {
    propertyId,
    tenancyId: created.id,
    contractType: fields.contractType,
    ended: ending !== undefined,
  })
  return { ok: true, tenancyId: created.id }
}
 
export async function updateTenancy(
  deps: TenancyDeps,
  propertyId: string,
  tenancyId: string,
  fields: TenancyFields,
): Promise<{ ok: true } | Failure<FieldReason | AlertReason>> {
  const refused = await roleCheck(deps, propertyId)
  if (refused) {
    return refused
  }
  const [start, tenancies] = await Promise.all([
    ownershipStart(deps, propertyId),
    deps.tenancies.forProperty(propertyId),
  ])
  const existing = tenancies.find((t) => t.id === tenancyId)
  Iif (!existing || start === undefined) {
    return tenancyNotFound
  }
  // An ending already recorded keeps its last day; otherwise the term's.
  const validTo =
    existing.noticeGivenBy === null ? fields.termEnd : existing.validTo
  const problem = validateTenancyDates(
    { ...fields, validTo },
    {
      today: today(deps),
      ownershipStart: start,
      others: tenancies.filter((t) => t.id !== tenancyId),
    },
  )
  if (problem) {
    return fail(problem)
  }
  // A recorded ending must still fit the corrected contract: its type, start,
  // contract date (the landlord's notice period) and term.
  if (
    existing.noticeGivenBy !== null &&
    existing.noticeDate !== null &&
    validTo !== null &&
    validateEnding(
      fields,
      {
        noticeGivenBy: existing.noticeGivenBy,
        noticeDate: existing.noticeDate,
        lastDay: validTo,
      },
      today(deps),
    )
  ) {
    return fail('tenancy_correction_conflicts_ending')
  }
  // A recorded deposit return keeps the deposit and the last rent day.
  const depositReturn = await deps.depositReturns.forTenancy(tenancyId)
  if (depositReturn) {
    const kept = depositReturn.rentKept + depositReturn.damageKept
    if ((fields.deposit ?? 0) < kept) {
      return fail('deposit_below_kept')
    }
    if (validTo === null || validTo > depositReturn.returnedOn) {
      return fail('tenancy_has_deposit_return')
    }
  }
  const [months, rentsById, occupantsById, feesById] = await Promise.all([
    deps.tenancies.paymentMonths(tenancyId),
    deps.tenancies.rentsFor([tenancyId]),
    deps.tenancies.occupantsFor([tenancyId]),
    deps.tenancies.feesFor([tenancyId]),
  ])
  if (paymentsOutside(months, fields.validFrom, validTo)) {
    return fail('tenancy_has_payments_outside')
  }
  // The rent, the occupants and the fees stay inside the tenancy: their first
  // periods follow the start, and none starts after the last day.
  const rents = rentsById[tenancyId] ?? []
  const move = firstRentMove(rents, existing.validFrom, fields.validFrom)
  if (!move.ok) {
    return fail(move.reason)
  }
  if (rentAfterEnd(rents, validTo)) {
    return fail('tenancy_has_rent_after_end')
  }
  const occupants = occupantsById[tenancyId] ?? []
  const fees = feesById[tenancyId] ?? []
  const occupantsMove = firstPeriodMove(
    occupants,
    existing.validFrom,
    fields.validFrom,
  )
  const feeMoves = fees.map((fee) => ({
    fee,
    move: firstPeriodMove(fee.amounts, existing.validFrom, fields.validFrom),
  }))
  if (!occupantsMove.ok || feeMoves.some(({ move }) => !move.ok)) {
    return fail('tenancy_start_after_change')
  }
  if (
    periodAfterEnd(occupants, validTo) ||
    fees.some((fee) => feeChangesAfterEnd(fee.amounts, validTo))
  ) {
    return fail('tenancy_has_changes_after_end')
  }
  const updated = await deps.tenancies.update(
    deps.userId,
    propertyId,
    tenancyId,
    fields,
    {
      validTo,
      expectedValidTo: existing.validTo,
      firstRent: move.move,
      firstOccupants: occupantsMove.move,
      firstFees: feeMoves.flatMap(({ fee, move }) =>
        move.ok && move.move ? [{ feeId: fee.id, ...move.move }] : [],
      ),
    },
    deps.now(),
  )
  if (!updated) {
    // A payment recorded meanwhile is the likelier cause than a removal.
    const now = await deps.tenancies.paymentMonths(tenancyId)
    return refusal(
      deps,
      propertyId,
      paymentsOutside(now, fields.validFrom, validTo)
        ? fail('tenancy_has_payments_outside')
        : tenancyNotFound,
    )
  }
  deps.log.info('tenancy.updated', { propertyId, tenancyId })
  return { ok: true }
}
 
export async function endTenancy(
  deps: TenancyDeps,
  propertyId: string,
  tenancyId: string,
  ending: { noticeGivenBy: NoticeGiver; noticeDate: IsoDate; lastDay: IsoDate },
): Promise<{ ok: true } | Failure<FieldReason | AlertReason>> {
  const refused = await roleCheck(deps, propertyId)
  if (refused) {
    return refused
  }
  const existing = await deps.tenancies.get(tenancyId)
  if (existing?.propertyId !== propertyId) {
    return tenancyNotFound
  }
  if (existing.noticeGivenBy !== null) {
    return fail('tenancy_already_ending')
  }
  const problem = validateEnding(existing, ending, today(deps))
  if (problem) {
    return fail(problem)
  }
  const [months, rentsById, occupantsById, feesById] = await Promise.all([
    deps.tenancies.paymentMonths(tenancyId),
    deps.tenancies.rentsFor([tenancyId]),
    deps.tenancies.occupantsFor([tenancyId]),
    deps.tenancies.feesFor([tenancyId]),
  ])
  if (paymentsOutside(months, existing.validFrom, ending.lastDay)) {
    return fail('tenancy_has_payments_outside')
  }
  if (rentAfterEnd(rentsById[tenancyId] ?? [], ending.lastDay)) {
    return fail('tenancy_has_rent_after_end')
  }
  if (
    periodAfterEnd(occupantsById[tenancyId] ?? [], ending.lastDay) ||
    (feesById[tenancyId] ?? []).some((fee) =>
      feeChangesAfterEnd(fee.amounts, ending.lastDay),
    )
  ) {
    return fail('tenancy_has_changes_after_end')
  }
  const ended = await deps.tenancies.end(
    deps.userId,
    propertyId,
    tenancyId,
    ending,
    deps.now(),
  )
  if (!ended) {
    const now = await deps.tenancies.paymentMonths(tenancyId)
    return refusal(
      deps,
      propertyId,
      paymentsOutside(now, existing.validFrom, ending.lastDay)
        ? fail('tenancy_has_payments_outside')
        : fail('tenancy_already_ending'),
    )
  }
  deps.log.info('tenancy.ended', {
    propertyId,
    tenancyId,
    noticeGivenBy: ending.noticeGivenBy,
  })
  return { ok: true }
}
 
/** Removes a tenancy that hasn't started, e.g. when the tenant withdrew. */
export async function removeTenancy(
  deps: TenancyDeps,
  propertyId: string,
  tenancyId: string,
): Promise<{ ok: true } | Failure> {
  const refused = await roleCheck(deps, propertyId)
  if (refused) {
    return refused
  }
  const existing = await deps.tenancies.get(tenancyId)
  Iif (existing?.propertyId !== propertyId) {
    return tenancyNotFound
  }
  const day = today(deps)
  if (existing.validFrom <= day) {
    return fail('tenancy_already_started')
  }
  if ((await deps.tenancies.paymentMonths(tenancyId)).length > 0) {
    return fail('tenancy_has_payments')
  }
  const removed = await deps.tenancies.removeNotStarted(
    deps.userId,
    propertyId,
    tenancyId,
    day,
  )
  if (!removed) {
    const [now, months] = await Promise.all([
      deps.tenancies.get(tenancyId),
      deps.tenancies.paymentMonths(tenancyId),
    ])
    return refusal(
      deps,
      propertyId,
      now?.propertyId !== propertyId
        ? tenancyNotFound
        : months.length > 0
          ? fail('tenancy_has_payments')
          : fail('tenancy_already_started'),
    )
  }
  deps.log.info('tenancy.removed', { propertyId, tenancyId })
  return { ok: true }
}
 
export async function cancelTenancyEnding(
  deps: TenancyDeps,
  propertyId: string,
  tenancyId: string,
): Promise<{ ok: true } | Failure<FieldReason | AlertReason>> {
  const refused = await roleCheck(deps, propertyId)
  Iif (refused) {
    return refused
  }
  const tenancies = await deps.tenancies.forProperty(propertyId)
  const existing = tenancies.find((t) => t.id === tenancyId)
  Iif (!existing) {
    return tenancyNotFound
  }
  const lastDay = existing.validTo
  if (existing.noticeGivenBy === null || lastDay === null) {
    return fail('tenancy_not_ending')
  }
  if (lastDay < today(deps)) {
    return fail('tenancy_already_ended')
  }
  if (await deps.depositReturns.forTenancy(tenancyId)) {
    return fail('tenancy_has_deposit_return')
  }
  const restored = { from: existing.validFrom, to: existing.termEnd }
  const later = tenancies.some(
    (t) =>
      t.id !== tenancyId &&
      t.validFrom > lastDay &&
      (restored.to === null || t.validFrom <= restored.to),
  )
  if (later) {
    return fail('tenancy_cancel_later_tenancy')
  }
  const cancelled = await deps.tenancies.cancelEnding(
    deps.userId,
    propertyId,
    existing,
    deps.now(),
  )
  Iif (!cancelled) {
    return refusal(deps, propertyId, fail('tenancy_cancel_later_tenancy'))
  }
  deps.log.info('tenancy.ending_cancelled', { propertyId, tenancyId })
  return { ok: true }
}
 
const changedMeanwhile = fail('amount_changed')
 
/**
 * Sets a tenancy's rent from a date (openspec: tenancies, "Changing a
 * tenancy's rent"): a new period, or a correction on a period's start.
 */
export async function setTenancyRent(
  deps: TenancyDeps,
  propertyId: string,
  tenancyId: string,
  change: { amount: number; from: IsoDate },
): Promise<{ ok: true } | Failure<FieldReason | AlertReason>> {
  const refused = await roleCheck(deps, propertyId)
  if (refused) {
    return refused
  }
  const tenancy = await deps.tenancies.get(tenancyId)
  if (tenancy?.propertyId !== propertyId) {
    return tenancyNotFound
  }
  const rents = (await deps.tenancies.rentsFor([tenancyId]))[tenancyId] ?? []
  const starts = rents.map((rent) => rent.validFrom)
  const firstStart = starts.at(0)
  const latestStart = starts.at(-1)
  const corrects = starts.includes(change.from)
  const problem = validateRentDate(change.from, { tenancy, starts })
  if (problem) {
    return fail(problem)
  }
  const set = await deps.tenancies.setRent({
    actorId: deps.userId,
    propertyId,
    tenancyId,
    amount: change.amount,
    from: change.from,
    latestStart: latestStart ?? null,
    corrects,
    ...(fillsBeforeFirst(change.from, firstStart) && { firstStart }),
  })
  Iif (!set) {
    return refusal(deps, propertyId, changedMeanwhile)
  }
  deps.log.info(corrects ? 'tenancy.rent_corrected' : 'tenancy.rent_changed', {
    propertyId,
    tenancyId,
  })
  return { ok: true }
}
 
/**
 * Undoes a tenancy's latest rent change (openspec: tenancies, "Undoing a
 * tenancy's rent change"). The first rent stays: there is nothing to undo
 * with fewer than two periods.
 */
export async function undoTenancyRent(
  deps: TenancyDeps,
  propertyId: string,
  tenancyId: string,
): Promise<{ ok: true } | Failure> {
  const refused = await roleCheck(deps, propertyId)
  if (refused) {
    return refused
  }
  const tenancy = await deps.tenancies.get(tenancyId)
  Iif (tenancy?.propertyId !== propertyId) {
    return tenancyNotFound
  }
  const rents = (await deps.tenancies.rentsFor([tenancyId]))[tenancyId] ?? []
  const latest = rents.at(-1)
  const previous = rents.at(-2)
  if (!latest || !previous) {
    return fail('amount_nothing_to_undo')
  }
  const undone = await deps.tenancies.undoLatestRent({
    actorId: deps.userId,
    propertyId,
    tenancyId,
    latestStart: latest.validFrom,
    previousStart: previous.validFrom,
  })
  Iif (!undone) {
    return refusal(deps, propertyId, changedMeanwhile)
  }
  deps.log.info('tenancy.rent_change_undone', { propertyId, tenancyId })
  return { ok: true }
}
 
/**
 * Sets a tenancy's occupants from a date (openspec: tenancies, "Changing the
 * occupants"): a new period, or a correction on the latest period's start.
 */
export async function setTenancyOccupants(
  deps: TenancyDeps,
  propertyId: string,
  tenancyId: string,
  change: { persons: number; from: IsoDate },
): Promise<{ ok: true } | Failure<FieldReason | AlertReason>> {
  const refused = await roleCheck(deps, propertyId)
  if (refused) {
    return refused
  }
  const tenancy = await deps.tenancies.get(tenancyId)
  if (tenancy?.propertyId !== propertyId) {
    return tenancyNotFound
  }
  if (
    !Number.isInteger(change.persons) ||
    change.persons < 1 ||
    change.persons > MAX_OCCUPANTS
  ) {
    return fail('occupants_invalid')
  }
  const periods =
    (await deps.tenancies.occupantsFor([tenancyId]))[tenancyId] ?? []
  const latestStart = periods.at(-1)?.validFrom
  const problem = validateTenancyPeriodDate(change.from, {
    tenancy,
    latestStart,
  })
  if (problem) {
    return fail(problem)
  }
  const corrects = latestStart === change.from
  const set = await deps.tenancies.setOccupants({
    actorId: deps.userId,
    propertyId,
    tenancyId,
    persons: change.persons,
    from: change.from,
    latestStart: latestStart ?? null,
    corrects,
  })
  Iif (!set) {
    return refusal(deps, propertyId, changedMeanwhile)
  }
  deps.log.info(
    corrects ? 'tenancy.occupants_corrected' : 'tenancy.occupants_changed',
    { propertyId, tenancyId },
  )
  return { ok: true }
}
 
/**
 * Undoes a tenancy's latest occupants change (openspec: tenancies, "Changing
 * the occupants"). The first period stays: there is nothing to undo with
 * fewer than two.
 */
export async function undoTenancyOccupants(
  deps: TenancyDeps,
  propertyId: string,
  tenancyId: string,
): Promise<{ ok: true } | Failure> {
  const refused = await roleCheck(deps, propertyId)
  if (refused) {
    return refused
  }
  const tenancy = await deps.tenancies.get(tenancyId)
  Iif (tenancy?.propertyId !== propertyId) {
    return tenancyNotFound
  }
  const periods =
    (await deps.tenancies.occupantsFor([tenancyId]))[tenancyId] ?? []
  const latest = periods.at(-1)
  const previous = periods.at(-2)
  if (!latest || !previous) {
    return fail('occupants_nothing_to_undo')
  }
  const undone = await deps.tenancies.undoOccupants({
    actorId: deps.userId,
    propertyId,
    tenancyId,
    latestStart: latest.validFrom,
    previousStart: previous.validFrom,
  })
  Iif (!undone) {
    return refusal(deps, propertyId, changedMeanwhile)
  }
  deps.log.info('tenancy.occupants_change_undone', { propertyId, tenancyId })
  return { ok: true }
}
 
/** A tenant fee's kind, basis and description, as the form sends them. */
export interface FeeFields {
  kind: ChargeKind
  basis: ChargeBasis
  /** Set for the kind `other`. */
  description: string | null
}
 
/**
 * Adds a tenant fee to a tenancy with its first amount from a date (openspec:
 * tenancies, "Adding a tenant fee").
 */
export async function addTenantFee(
  deps: TenancyDeps,
  propertyId: string,
  tenancyId: string,
  fee: FeeFields & { amount: number; from: IsoDate },
): Promise<{ ok: true; feeId: string } | Failure<FieldReason | AlertReason>> {
  const refused = await roleCheck(deps, propertyId)
  if (refused) {
    return refused
  }
  const tenancy = await deps.tenancies.get(tenancyId)
  Iif (tenancy?.propertyId !== propertyId) {
    return tenancyNotFound
  }
  if (
    !Number.isInteger(fee.amount) ||
    fee.amount < 0 ||
    fee.amount > MAX_AMOUNT
  ) {
    return fail('amount_invalid')
  }
  const description =
    fee.kind === 'other' ? (fee.description?.trim() ?? '') : null
  if (
    fee.kind === 'other' &&
    (description === null ||
      description.length === 0 ||
      description.length > MAX_CHARGE_DESCRIPTION)
  ) {
    return fail('description_required')
  }
  const problem = validateTenancyPeriodDate(fee.from, {
    tenancy,
    latestStart: undefined,
  })
  if (problem) {
    return fail(problem)
  }
  const feeId = await deps.tenancies.addFee({
    actorId: deps.userId,
    propertyId,
    tenancyId,
    kind: fee.kind,
    basis: fee.basis,
    description,
    amount: fee.amount,
    from: fee.from,
  })
  Iif (feeId === null) {
    return refusal(deps, propertyId, tenancyNotFound)
  }
  deps.log.info('tenancy.fee_added', { propertyId, tenancyId, feeId })
  return { ok: true, feeId }
}
 
/**
 * The tenancy's fee, with the tenancy it must belong to, or a reason: a
 * tenancy that isn't the flat's is `tenant_fee_not_found` too.
 */
async function loadFee(
  deps: TenancyDeps,
  propertyId: string,
  tenancyId: string,
  feeId: string,
) {
  const tenancy = await deps.tenancies.get(tenancyId)
  if (tenancy?.propertyId !== propertyId) {
    return { ok: false, failure: fail('tenant_fee_not_found') } as const
  }
  const fees = (await deps.tenancies.feesFor([tenancyId]))[tenancyId] ?? []
  const fee = fees.find((f) => f.id === feeId)
  if (!fee) {
    return { ok: false, failure: fail('tenant_fee_not_found') } as const
  }
  return { ok: true, tenancy, fee } as const
}
 
/**
 * Gives a tenant fee a new amount from a date (openspec: tenancies, "Changing
 * a tenant fee"): a new period, or a correction on the latest period's start.
 * An amount of 0 ends the fee.
 */
export async function setTenantFee(
  deps: TenancyDeps,
  propertyId: string,
  tenancyId: string,
  feeId: string,
  change: { amount: number; from: IsoDate },
): Promise<{ ok: true } | Failure<FieldReason | AlertReason>> {
  const refused = await roleCheck(deps, propertyId)
  if (refused) {
    return refused
  }
  const loaded = await loadFee(deps, propertyId, tenancyId, feeId)
  if (!loaded.ok) {
    return loaded.failure
  }
  const { tenancy, fee } = loaded
  Iif (
    !Number.isInteger(change.amount) ||
    change.amount < 0 ||
    change.amount > MAX_AMOUNT
  ) {
    return fail('amount_invalid')
  }
  const latestStart = fee.amounts.at(-1)?.validFrom
  const problem = validateTenancyPeriodDate(change.from, {
    tenancy,
    latestStart,
  })
  if (problem) {
    return fail(problem)
  }
  Iif (latestStart === undefined) {
    return fail('tenant_fee_not_found')
  }
  const corrects = latestStart === change.from
  const set = await deps.tenancies.setFeeAmount({
    actorId: deps.userId,
    propertyId,
    tenancyId,
    feeId,
    amount: change.amount,
    from: change.from,
    latestStart,
    corrects,
  })
  Iif (!set) {
    return refusal(deps, propertyId, changedMeanwhile)
  }
  deps.log.info(
    corrects ? 'tenancy.fee_amount_corrected' : 'tenancy.fee_amount_set',
    { propertyId, tenancyId, feeId },
  )
  return { ok: true }
}
 
/**
 * Undoes a tenant fee's latest change (openspec: tenancies, "Undoing a tenant
 * fee change"); the fee's only amount undone removes the fee.
 */
export async function undoTenantFee(
  deps: TenancyDeps,
  propertyId: string,
  tenancyId: string,
  feeId: string,
): Promise<{ ok: true } | Failure> {
  const refused = await roleCheck(deps, propertyId)
  if (refused) {
    return refused
  }
  const loaded = await loadFee(deps, propertyId, tenancyId, feeId)
  if (!loaded.ok) {
    return loaded.failure
  }
  const latest = loaded.fee.amounts.at(-1)
  Iif (!latest) {
    return fail('amount_nothing_to_undo')
  }
  const previous = loaded.fee.amounts.at(-2)
  const undone = await deps.tenancies.undoFeeChange({
    actorId: deps.userId,
    propertyId,
    tenancyId,
    feeId,
    latestStart: latest.validFrom,
    previousStart: previous?.validFrom ?? null,
  })
  Iif (!undone) {
    return refusal(deps, propertyId, changedMeanwhile)
  }
  deps.log.info(
    previous ? 'tenancy.fee_change_undone' : 'tenancy.fee_removed',
    {
      propertyId,
      tenancyId,
      feeId,
    },
  )
  return { ok: true }
}
 
/** A flat's tenancy status for its card on the flats list. */
export type CardTenancyStatus =
  | { kind: 'let'; tenantName: string }
  | { kind: 'notice_given'; tenantName: string; on: IsoDate }
  | { kind: 'vacant'; nextStart: IsoDate | null }
 
/** The tenancy status of each of the user's flats, in one query. */
export async function listTenancyStatuses(
  deps: TenancyDeps,
): Promise<Record<string, CardTenancyStatus>> {
  const flats = await deps.properties.listForUser(deps.userId)
  const day = today(deps)
  const tenancies = await deps.tenancies.currentFor(
    flats.map((flat) => flat.id),
    day,
  )
  const statuses: Record<string, CardTenancyStatus> = {}
  for (const flat of flats) {
    const status = flatStatus(
      tenancies.filter((t) => t.propertyId === flat.id),
      day,
    )
    statuses[flat.id] =
      status.kind === 'vacant'
        ? { kind: 'vacant', nextStart: status.next?.validFrom ?? null }
        : status.kind === 'let'
          ? { kind: 'let', tenantName: status.tenancy.tenantName }
          : {
              kind: 'notice_given',
              tenantName: status.tenancy.tenantName,
              on: status.on,
            }
  }
  return statuses
}