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 | 12x 1x 1x 1x 34x 29x 29x 1x 28x 27x 27x 27x 77x 11x 11x 11x 11x 11x 14x 22x 22x 2x 20x 20x 1x 19x 19x 19x 6x 13x 13x 1x 12x 12x 12x 12x 12x 5x 5x 1x 4x 4x 4x 4x 4x 4x 4x 1x 3x 3x 1x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x | // Deposit returns: the logic behind the server functions in functions.ts,
// with its dependencies passed in so Workers tests can drive it (openspec:
// deposits). The rules are checked here first for the reason, and each write
// checks the owner role and the tenancy again in its statements. Amounts,
// notes and names are never logged.
import type { Property } from '#/features/properties/property'
import type { PropertyRepository } from '#/features/properties/property.repository.server'
import type { RentPaymentRepository } from '#/features/rent-payments/rent-payment.repository.server'
import type { SharingRepository } from '#/features/sharing/sharing.repository.server'
import type {
Tenancy,
TenancyRepository,
} from '#/features/tenancies/tenancy.repository.server'
import { isoDateInFinland, type IsoDate } from '#/lib/dates'
import type { AlertReason, FieldReason } from '#/lib/reasons'
import type { PropertyRole } from '#/server/db/schema'
import type { Logger } from '#/server/log/log'
import {
allocateRentKept,
checkReturn,
checkReturnFields,
missingRent,
type MissingMonth,
} from './deposit'
import type {
DepositReturn,
DepositReturnFields,
DepositReturnRepository,
} from './deposit-return.repository.server'
export interface DepositDeps {
/** The signed-in user. */
userId: string
deposits: DepositReturnRepository
payments: RentPaymentRepository
tenancies: TenancyRepository
properties: PropertyRepository
sharing: SharingRepository
log: Logger
now: () => Date
}
interface Failure<R extends FieldReason | AlertReason = AlertReason> {
ok: false
reason: R
}
const fail = <R extends FieldReason | AlertReason>(reason: R): Failure<R> => ({
ok: false,
reason,
})
const notFound = fail('property_not_found')
const ownerOnly = fail('sharing_owner_only')
const tenancyNotFound = fail('tenancy_not_found')
const today = (deps: DepositDeps) => isoDateInFinland(deps.now())
async function roleCheck(
deps: DepositDeps,
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
}
/** What the return page shows. */
export interface DepositReturnView {
role: PropertyRole
property: Property
/** Today in Finland. */
today: IsoDate
tenancy: Tenancy
/** The recorded return, if any. */
depositReturn: DepositReturn | undefined
/**
* The rent missing from the tenancy's months, oldest first, without the
* return's own payments. Empty while the tenancy has no last rent day.
*/
missing: MissingMonth[]
}
/** The months with rent missing, leaving out the return's own payments. */
async function missingFor(
deps: DepositDeps,
propertyId: string,
tenancy: Tenancy,
returnId: string | undefined,
): Promise<MissingMonth[]> {
Iif (tenancy.validTo === null) {
return []
}
const [rents, occupants, fees, payments] = await Promise.all([
deps.tenancies.rentsFor([tenancy.id]),
deps.tenancies.occupantsFor([tenancy.id]),
deps.tenancies.feesFor([tenancy.id]),
deps.payments.forProperty(propertyId),
])
return missingRent(
{ ...tenancy, validTo: tenancy.validTo },
{
rents,
occupants,
fees,
payments: payments.filter(
(p) =>
p.tenancyId === tenancy.id &&
(returnId === undefined || p.depositReturnId !== returnId),
),
},
)
}
/** A tenancy of the flat with its return and the rent missing. */
export async function getDepositReturn(
deps: DepositDeps,
propertyId: string,
tenancyId: string,
): Promise<
({ ok: true } & DepositReturnView) | typeof notFound | typeof tenancyNotFound
> {
const [role, property, tenancy] = await Promise.all([
deps.sharing.roleOf(deps.userId, propertyId),
deps.properties.findForUser(deps.userId, propertyId),
deps.tenancies.get(tenancyId),
])
Iif (!role || !property) {
return notFound
}
Iif (tenancy?.propertyId !== propertyId) {
return tenancyNotFound
}
const depositReturn = await deps.deposits.forTenancy(tenancyId)
return {
ok: true,
role,
property,
today: today(deps),
tenancy,
depositReturn,
missing: await missingFor(deps, propertyId, tenancy, depositReturn?.id),
}
}
export interface ReturnInputFields extends DepositReturnFields {
deductions: boolean
}
/** The stored fields of an input. */
const fieldsOf = (input: ReturnInputFields): DepositReturnFields => ({
returnedOn: input.returnedOn,
rentKept: input.rentKept,
damageKept: input.damageKept,
note: input.note,
})
/** Records the return of a tenancy's deposit. Owners only. */
export async function recordDepositReturn(
deps: DepositDeps,
propertyId: string,
tenancyId: string,
input: ReturnInputFields,
): Promise<
{ ok: true; returnId: string } | 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 existing = await deps.deposits.forTenancy(tenancyId)
const problem = checkReturn({
...input,
deposit: tenancy.deposit ?? null,
lastRentDay: tenancy.validTo,
hasReturn: existing !== undefined,
today: today(deps),
})
if (problem) {
return fail(problem)
}
const allocation = allocateRentKept(
await missingFor(deps, propertyId, tenancy, undefined),
input.rentKept,
)
if (!allocation.ok) {
return fail(allocation.reason)
}
const fields = fieldsOf(input)
const returnId = await deps.deposits.record(
deps.userId,
propertyId,
tenancyId,
fields,
allocation.payments,
deps.now(),
)
Iif (returnId === null) {
// The role, the tenancy or a return recorded meanwhile.
return (await roleCheck(deps, propertyId)) ?? fail('deposit_return_exists')
}
deps.log.info('deposit.return_recorded', { propertyId, tenancyId, returnId })
return { ok: true, returnId }
}
/** Corrects the recorded return of a tenancy. Owners only. */
export async function updateDepositReturn(
deps: DepositDeps,
propertyId: string,
tenancyId: string,
input: ReturnInputFields,
): Promise<{ ok: true } | 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
}
const existing = await deps.deposits.forTenancy(tenancyId)
Iif (existing === undefined) {
return tenancyNotFound
}
Iif (tenancy.deposit == null || tenancy.validTo === null) {
return fail('deposit_not_set')
}
const problem = checkReturnFields({
...input,
deposit: tenancy.deposit,
lastRentDay: tenancy.validTo,
today: today(deps),
})
if (problem) {
return fail(problem)
}
const allocation = allocateRentKept(
await missingFor(deps, propertyId, tenancy, existing.id),
input.rentKept,
)
if (!allocation.ok) {
return fail(allocation.reason)
}
const fields = fieldsOf(input)
const updated = await deps.deposits.update(
deps.userId,
propertyId,
existing.id,
fields,
allocation.payments,
deps.now(),
)
Iif (!updated) {
return (await roleCheck(deps, propertyId)) ?? tenancyNotFound
}
deps.log.info('deposit.return_updated', {
propertyId,
tenancyId,
returnId: existing.id,
})
return { ok: true }
}
/** Deletes the recorded return of a tenancy, and its payments. Owners only. */
export async function deleteDepositReturn(
deps: DepositDeps,
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 existing = await deps.deposits.forTenancy(tenancyId)
Iif (existing === undefined) {
return tenancyNotFound
}
const removed = await deps.deposits.remove(
deps.userId,
propertyId,
existing.id,
)
Iif (!removed) {
return (await roleCheck(deps, propertyId)) ?? tenancyNotFound
}
deps.log.info('deposit.return_deleted', {
propertyId,
tenancyId,
returnId: existing.id,
})
return { ok: true }
}
|