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 | 1x 1x 1x 57x 57x 1x 56x 48x 48x 48x 48x 48x 25x 25x 2x 2x 2x 23x 23x 4x 19x 19x 19x 5x 5x 9x 6x 6x 5x 6x 7x 7x 1x 6x 6x 6x 6x 3x 6x 1x 3x 1x 2x 2x 10x 10x 10x 10x 7x 7x 4x 7x 7x 5x 5x 3x 5x 2x 2x 43x 43x 4x 39x 39x 22x 22x 5x 17x 34x 34x 16x 33x 1x 32x 32x 9x 9x 1x 8x 8x 1x 7x 7x 7x 3x 3x 1x 2x 6x 6x 2x 6x 6x 6x 6x 6x 4x 4x 1x 3x 3x 3x 3x 3x | // Entries and their receipts: the logic behind the server functions in
// functions.ts, with its dependencies passed in so Workers tests can drive it
// (openspec: transactions). A receipt is checked and stored before the
// database write and deleted again if that write doesn't apply, so a refused
// or failed save leaves no file behind (design.md, "The receipt is uploaded
// with the save").
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 { SharingRepository } from '#/features/sharing/sharing.repository.server'
import { isoDateInFinland, type IsoDate } from '#/lib/dates'
import type { AlertReason, FieldReason } from '#/lib/reasons'
import type { PropertyRole } from '#/server/db/schema'
import { deleteStoredFiles } from '#/server/files/delete'
import { fitsQuota } from '#/server/files/quota'
import { newFileKey, type FileStorage } from '#/server/files/storage'
import { uploadFilename, withStoredFile } from '#/server/files/stored'
import { checkUpload, UploadError } from '#/server/files/upload'
import type { Logger } from '#/server/log/log'
import { validateTransactionDate } from './rules'
import type {
ReceiptFields,
TransactionDetails,
TransactionFields,
TransactionRepository,
TransactionRow,
} from './transaction.repository.server'
export interface TransactionDeps {
/** The signed-in user. */
userId: string
transactions: TransactionRepository
properties: PropertyRepository
ownership: OwnershipRepository
sharing: SharingRepository
storage: FileStorage
log: Logger
now: () => Date
}
/** A receipt file as it arrived. */
export interface Upload {
bytes: Uint8Array
/** The browser's file name. */
filename: string
}
export type ReceiptUpdate =
| { action: 'keep' }
| { action: 'remove' }
| { action: 'replace'; upload: Upload }
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 entryNotFound = {
ok: false,
reason: 'transaction_not_found',
} as const satisfies Failure
async function roleCheck(
deps: TransactionDeps,
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
}
async function ownershipStart(
deps: TransactionDeps,
propertyId: string,
): Promise<IsoDate | undefined> {
const { periods } = await deps.ownership.history(propertyId)
return periods.at(-1)?.validFrom
}
async function dateProblem(
deps: TransactionDeps,
propertyId: string,
date: IsoDate,
): Promise<Failure<FieldReason> | undefined> {
const start = await ownershipStart(deps, propertyId)
const problem = validateTransactionDate(date, {
today: isoDateInFinland(deps.now()),
ownershipStart: start ?? date,
})
return problem ? { ok: false, reason: problem } : undefined
}
/**
* Checks and stores a receipt file. Returns its fields, or why it was
* refused; nothing is stored then.
*/
async function storeReceipt(
deps: TransactionDeps,
propertyId: string,
upload: Upload,
replacing?: string,
): Promise<
{ ok: true; receipt: ReceiptFields } | Failure<FieldReason | AlertReason>
> {
let checked: ReturnType<typeof checkUpload>
try {
checked = checkUpload(upload.bytes)
} catch (error) {
Iif (!(error instanceof UploadError)) {
throw error
}
deps.log.warn('transaction.receipt_refused', {
propertyId,
problem: error.problem,
})
return {
ok: false,
reason:
error.problem === 'too_large'
? 'receipt_too_large'
: 'receipt_unsupported_type',
}
}
// A first check, so a full quota stores no file; the write checks again.
// A replaced receipt doesn't count, as in the write.
const usage = await deps.transactions.storageUsage(deps.userId, replacing)
if (!fitsQuota(usage, checked.size)) {
return quotaFull(deps, propertyId)
}
const key = newFileKey('receipts')
await deps.storage.put(key, upload.bytes, checked.contentType)
return {
ok: true,
receipt: {
key,
contentType: checked.contentType,
size: checked.size,
filename: uploadFilename(upload.filename, checked.contentType, 'receipt'),
},
}
}
function quotaFull(
deps: TransactionDeps,
propertyId: string,
): Failure<'storage_quota_full'> {
deps.log.warn('transaction.quota_exceeded', { propertyId })
return { ok: false, reason: 'storage_quota_full' }
}
/** Deletes stored files; a failure leaves an orphan and is logged. */
function deleteFiles(
deps: TransactionDeps,
keys: readonly string[],
): Promise<void> {
return deleteStoredFiles(
deps.storage,
deps.log,
keys,
'transaction.receipt_delete_failed',
)
}
export interface TransactionsView {
role: PropertyRole
property: Property
year: number
/** The current year, the year shown and the years with entries, newest first. */
years: number[]
/** The year's entries, newest first. */
entries: TransactionRow[]
/** In cents. */
totals: { income: number; expense: number }
}
/** Sums a year's entries by type. */
export function totalsOf(
entries: readonly Pick<TransactionRow, 'type' | 'amount'>[],
): TransactionsView['totals'] {
const totals = { income: 0, expense: 0 }
for (const entry of entries) {
totals[entry.type] += entry.amount
}
return totals
}
export async function getTransactions(
deps: TransactionDeps,
propertyId: string,
requestedYear: number | undefined,
): Promise<({ ok: true } & TransactionsView) | typeof notFound> {
const [role, property] = await Promise.all([
deps.sharing.roleOf(deps.userId, propertyId),
deps.properties.findForUser(deps.userId, propertyId),
])
if (!role || !property) {
return notFound
}
const currentYear = Number(isoDateInFinland(deps.now()).slice(0, 4))
const year = requestedYear ?? currentYear
const [entries, withEntries] = await Promise.all([
deps.transactions.forPropertyYear(propertyId, year),
deps.transactions.years(propertyId),
])
// The year shown is always among them, also once its last entry is gone.
const years = [...new Set([currentYear, year, ...withEntries])].sort(
(a, b) => b - a,
)
return {
ok: true,
role,
property,
year,
years,
entries,
totals: totalsOf(entries),
}
}
/** The water charge categories a new charge or fee warns about. */
export const WATER_CATEGORIES = ['water_charge', 'tenant_water_charge'] as const
/**
* The flat's entries of a water category from a date on, for the warning the
* usage charge and tenant fee forms show (openspec: "Water charge entries are
* warned about"). For everyone with access.
*/
export async function getEntriesSince(
deps: TransactionDeps,
propertyId: string,
category: (typeof WATER_CATEGORIES)[number],
from: IsoDate,
): Promise<{ ok: true; count: number; total: number } | typeof notFound> {
if ((await deps.sharing.roleOf(deps.userId, propertyId)) === undefined) {
return notFound
}
const found = await deps.transactions.categoryTotalSince(
propertyId,
category,
from,
)
return { ok: true, ...found }
}
export async function getTransaction(
deps: TransactionDeps,
propertyId: string,
transactionId: string,
): Promise<
| {
ok: true
role: PropertyRole
property: Property
entry: TransactionDetails
/** Whether the signed-in user logged it ("You"). */
loggedByYou: boolean
/** Today in Finland, for the edit form's date check. */
today: IsoDate
}
| typeof notFound
| typeof entryNotFound
> {
const [role, property, entry] = await Promise.all([
deps.sharing.roleOf(deps.userId, propertyId),
deps.properties.findForUser(deps.userId, propertyId),
deps.transactions.get(transactionId),
])
Iif (!role || !property) {
return notFound
}
Iif (entry?.propertyId !== propertyId) {
return entryNotFound
}
return {
ok: true,
role,
property,
entry,
loggedByYou: entry.createdBy.id === deps.userId,
today: isoDateInFinland(deps.now()),
}
}
/**
* The flats the user may log entries for, and whether they have any. With
* `propertyId` (a flat's own Entries page), that flat as `fixed` if the user
* owns it, archived or not: archiving leaves a flat out of the choice only.
*/
export async function getNewTransactionOptions(
deps: TransactionDeps,
propertyId?: string,
): Promise<{
ok: true
/** Owned flats, unsorted: the page sorts them in the user's language. */
owned: Property[]
/** The flat of `propertyId`, when the user owns it; else null. */
fixed: Property | null
hasFlats: boolean
/** Whether the user owns a flat they have archived. */
ownsArchived: boolean
today: IsoDate
}> {
const [flats, fixed] = await Promise.all([
deps.properties.listForUser(deps.userId),
propertyId === undefined ? null : ownedFlat(deps, propertyId),
])
const roles = await Promise.all(
flats.map((flat) => deps.sharing.roleOf(deps.userId, flat.id)),
)
const owned = flats.filter((_, i) => roles[i] === 'owner')
return {
ok: true,
owned,
fixed,
hasFlats: flats.length > 0,
// Asked only when there is nothing to offer: it explains why.
ownsArchived:
owned.length === 0 && fixed === null && (await ownsArchivedFlat(deps)),
today: isoDateInFinland(deps.now()),
}
}
async function ownsArchivedFlat(deps: TransactionDeps): Promise<boolean> {
const archived = await deps.properties.listArchivedForUser(deps.userId)
const roles = await Promise.all(
archived.map((flat) => deps.sharing.roleOf(deps.userId, flat.id)),
)
return roles.includes('owner')
}
/** The flat, archived or not, if the user owns it; else null. */
async function ownedFlat(
deps: TransactionDeps,
propertyId: string,
): Promise<Property | null> {
const [role, found] = await Promise.all([
deps.sharing.roleOf(deps.userId, propertyId),
deps.properties.findForUser(deps.userId, propertyId),
])
return role === 'owner' && found ? found : null
}
export async function createTransaction(
deps: TransactionDeps,
propertyId: string,
fields: TransactionFields,
upload: Upload | null,
): Promise<
{ ok: true; transactionId: string } | Failure<FieldReason | AlertReason>
> {
const refused =
(await roleCheck(deps, propertyId)) ??
(await dateProblem(deps, propertyId, fields.date))
if (refused) {
return refused
}
let receipt: ReceiptFields | null = null
if (upload) {
const stored = await storeReceipt(deps, propertyId, upload)
if (!stored.ok) {
return stored
}
receipt = stored.receipt
}
const id = await withStoredFile(
deps,
'transaction.receipt_delete_failed',
receipt?.key,
() =>
deps.transactions.create(
deps.userId,
propertyId,
fields,
receipt,
deps.now(),
),
(created) => created !== null,
)
if (id === null) {
return receipt && (await roleCheck(deps, propertyId)) === undefined
? quotaFull(deps, propertyId)
: ownerOnly
}
deps.log.info('transaction.created', {
propertyId,
transactionId: id,
type: fields.type,
category: fields.category,
hasReceipt: receipt !== null,
})
return { ok: true, transactionId: id }
}
export async function updateTransaction(
deps: TransactionDeps,
propertyId: string,
transactionId: string,
fields: TransactionFields,
update: ReceiptUpdate,
): Promise<{ ok: true } | Failure<FieldReason | AlertReason>> {
const refused = await roleCheck(deps, propertyId)
if (refused) {
return refused
}
const existing = await deps.transactions.get(transactionId)
if (existing?.propertyId !== propertyId) {
return entryNotFound
}
const problem = await dateProblem(deps, propertyId, fields.date)
Iif (problem) {
return problem
}
let receipt: ReceiptFields | undefined
if (update.action === 'replace') {
const stored = await storeReceipt(
deps,
propertyId,
update.upload,
transactionId,
)
if (!stored.ok) {
return stored
}
receipt = stored.receipt
}
const result = await withStoredFile(
deps,
'transaction.receipt_delete_failed',
receipt?.key,
() =>
deps.transactions.update(
deps.userId,
propertyId,
transactionId,
fields,
receipt
? { kind: 'replace', receipt }
: update.action === 'remove'
? { kind: 'remove' }
: { kind: 'keep' },
deps.now(),
),
(updated) => updated.applied,
)
Iif (!result.applied) {
const stillThere =
receipt !== undefined &&
(await roleCheck(deps, propertyId)) === undefined &&
(await deps.transactions.get(transactionId))?.propertyId === propertyId
return stillThere ? quotaFull(deps, propertyId) : entryNotFound
}
await deleteFiles(deps, result.removedKeys)
const hadReceipt = existing.receipt !== null
deps.log.info('transaction.updated', {
propertyId,
transactionId,
receiptChange:
update.action === 'keep'
? 'none'
: update.action === 'remove'
? hadReceipt
? 'removed'
: 'none'
: hadReceipt
? 'replaced'
: 'added',
})
return { ok: true }
}
export async function deleteTransaction(
deps: TransactionDeps,
propertyId: string,
transactionId: string,
): Promise<{ ok: true } | Failure> {
const refused = await roleCheck(deps, propertyId)
if (refused) {
return refused
}
const result = await deps.transactions.delete(
deps.userId,
propertyId,
transactionId,
)
Iif (!result.applied) {
return entryNotFound
}
await deleteFiles(deps, result.removedKeys)
deps.log.info('transaction.deleted', { propertyId, transactionId })
return { ok: true }
}
|