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 | 189x 129x 189x 62x 189x 35x 189x 8x 8x 77x 5x 72x 8x 8x 5x 5x 7x 9x 7x 30x 30x 3x 27x 27x 67x 67x 67x 35x 35x 32x 32x 10x 10x 10x 3x 3x 7x 7x 4x 4x 3x 3x 3x 3x 5x 5x 3x 7x 7x 2x 5x 5x 31x | // A flat's entries and their receipts (openspec: transactions). Writes run in
// one atomically() batch and carry the owner check in their statements, so a
// role lost between the read and the write changes nothing. The caller stores
// and deletes the receipt files; this module returns the keys it removed.
import {
and,
count,
desc,
eq,
exists,
gte,
inArray,
lte,
sql,
sum,
} from 'drizzle-orm'
import type { IsoDate } from '#/lib/dates'
import {
properties,
propertyAccess,
receipts,
transactions,
user,
type TransactionCategory,
type TransactionType,
} from '#/server/db/schema'
import { fitsStorageQuota, storageUsage } from '#/server/db/storage-usage'
import { atomically, type Db } from '#/server/platform/db.server'
export interface TransactionFields {
type: TransactionType
category: TransactionCategory
/** Positive, in cents. */
amount: number
date: IsoDate
note: string | null
}
export interface ReceiptFields {
key: string
contentType: string
size: number
filename: string
}
export interface TransactionRow extends TransactionFields {
id: string
hasReceipt: boolean
}
/** An entry of one of several flats, for the year summary. */
export interface FlatTransaction extends TransactionFields {
id: string
propertyId: string
}
export interface Receipt {
id: string
contentType: string
size: number
filename: string
createdAt: Date
}
export interface TransactionDetails extends TransactionFields {
id: string
propertyId: string
createdBy: { id: string; name: string }
createdAt: Date
receipt: Receipt | null
}
/** What happens to an entry's receipt in an update. */
export type ReceiptChange =
| { kind: 'keep' }
| { kind: 'remove' }
| { kind: 'replace'; receipt: ReceiptFields }
export function transactionRepository(db: Db) {
/** The actor owns the flat: the check inside each write. */
const isOwner = (actorId: string, propertyId: string) =>
exists(
db
.select({ one: sql`1` })
.from(propertyAccess)
.where(
and(
eq(propertyAccess.propertyId, propertyId),
eq(propertyAccess.userId, actorId),
eq(propertyAccess.role, 'owner'),
),
),
)
/** The entry belongs to the flat and the actor owns it. */
const ownedEntry = (actorId: string, propertyId: string, id: string) =>
and(
eq(transactions.id, id),
eq(transactions.propertyId, propertyId),
isOwner(actorId, propertyId),
)
/** Inserts a receipt for an entry that exists in the actor's flat. */
const insertReceipt = (
actorId: string,
propertyId: string,
transactionId: string,
receipt: ReceiptFields,
now: Date,
) =>
db.insert(receipts).select(
db
.select({
id: sql<string>`${crypto.randomUUID()}`.as('id'),
transactionId: transactions.id,
key: sql<string>`${receipt.key}`.as('key'),
contentType: sql<string>`${receipt.contentType}`.as('content_type'),
size: sql<number>`${receipt.size}`.as('size'),
filename: sql<string>`${receipt.filename}`.as('filename'),
uploadedBy: sql<string>`${actorId}`.as('uploaded_by'),
createdAt: sql<number>`${now.getTime()}`.as('created_at'),
})
.from(transactions)
.where(
and(
ownedEntry(actorId, propertyId, transactionId),
fitsStorageQuota(db, actorId, receipt.size, transactionId),
),
),
)
return {
/** The year's entries, newest first. */
async forPropertyYear(
propertyId: string,
year: number,
): Promise<TransactionRow[]> {
const rows = await db
.select({
id: transactions.id,
type: transactions.type,
category: transactions.category,
amount: transactions.amount,
date: transactions.date,
note: transactions.note,
receiptId: receipts.id,
})
.from(transactions)
.leftJoin(receipts, eq(receipts.transactionId, transactions.id))
.where(
and(
eq(transactions.propertyId, propertyId),
gte(transactions.date, `${String(year)}-01-01`),
lte(transactions.date, `${String(year)}-12-31`),
),
)
.orderBy(desc(transactions.date), desc(transactions.createdAt))
return rows.map(({ receiptId, ...row }) => ({
...row,
hasReceipt: receiptId !== null,
}))
},
/** The year's entries of the flats, newest first, with no receipts. */
async forPropertiesYear(
propertyIds: string[],
year: number,
): Promise<FlatTransaction[]> {
if (propertyIds.length === 0) {
return []
}
return db
.select({
id: transactions.id,
propertyId: transactions.propertyId,
type: transactions.type,
category: transactions.category,
amount: transactions.amount,
date: transactions.date,
note: transactions.note,
})
.from(transactions)
.where(
and(
inArray(transactions.propertyId, propertyIds),
gte(transactions.date, `${String(year)}-01-01`),
lte(transactions.date, `${String(year)}-12-31`),
),
)
.orderBy(desc(transactions.date), desc(transactions.createdAt))
},
/** The flat's latest entries by date, newest first. */
async latest(propertyId: string, limit: number): Promise<TransactionRow[]> {
const rows = await db
.select({
id: transactions.id,
type: transactions.type,
category: transactions.category,
amount: transactions.amount,
date: transactions.date,
note: transactions.note,
receiptId: receipts.id,
})
.from(transactions)
.leftJoin(receipts, eq(receipts.transactionId, transactions.id))
.where(eq(transactions.propertyId, propertyId))
.orderBy(desc(transactions.date), desc(transactions.createdAt))
.limit(limit)
return rows.map(({ receiptId, ...row }) => ({
...row,
hasReceipt: receiptId !== null,
}))
},
/**
* How many entries of `category` the flat has dated on or after `from`,
* and their total in cents (openspec: "Water charge entries are warned
* about").
*/
async categoryTotalSince(
propertyId: string,
category: TransactionCategory,
from: IsoDate,
): Promise<{ count: number; total: number }> {
const [row] = await db
.select({ count: count(), total: sum(transactions.amount) })
.from(transactions)
.where(
and(
eq(transactions.propertyId, propertyId),
eq(transactions.category, category),
gte(transactions.date, from),
),
)
return { count: row.count, total: Number(row.total ?? 0) }
},
/** The years that have entries, newest first. */
async years(propertyId: string): Promise<number[]> {
const rows = await db
.selectDistinct({ date: transactions.date })
.from(transactions)
.where(eq(transactions.propertyId, propertyId))
const years = new Set(rows.map((row) => Number(row.date.slice(0, 4))))
return [...years].sort((a, b) => b - a)
},
/** An entry with its author and receipt, or null. */
async get(transactionId: string): Promise<TransactionDetails | null> {
const row = await db
.select({
entry: transactions,
authorName: user.name,
receipt: receipts,
})
.from(transactions)
.innerJoin(user, eq(user.id, transactions.createdBy))
.leftJoin(receipts, eq(receipts.transactionId, transactions.id))
.where(eq(transactions.id, transactionId))
.get()
if (!row) {
return null
}
const { entry, receipt } = row
return {
id: entry.id,
propertyId: entry.propertyId,
type: entry.type,
category: entry.category,
amount: entry.amount,
date: entry.date,
note: entry.note,
createdBy: { id: entry.createdBy, name: row.authorName },
createdAt: entry.createdAt,
receipt: receipt
? {
id: receipt.id,
contentType: receipt.contentType,
size: receipt.size,
filename: receipt.filename,
createdAt: receipt.createdAt,
}
: null,
}
},
/**
* Logs an entry, with its receipt. Null when the actor isn't an owner or
* the receipt doesn't fit their storage quota; nothing is written then.
*/
async create(
actorId: string,
propertyId: string,
fields: TransactionFields,
receipt: ReceiptFields | null,
now: Date,
): Promise<string | null> {
const id = crypto.randomUUID()
const insert = db
.insert(transactions)
.select(
db
.select({
id: sql<string>`${id}`.as('id'),
propertyId: properties.id,
type: sql<TransactionType>`${fields.type}`.as('type'),
category: sql<TransactionCategory>`${fields.category}`.as(
'category',
),
amount: sql<number>`${fields.amount}`.as('amount'),
date: sql<string>`${fields.date}`.as('date'),
note: sql<string | null>`${fields.note}`.as('note'),
createdBy: sql<string>`${actorId}`.as('created_by'),
createdAt: sql<number>`${now.getTime()}`.as('created_at'),
updatedAt: sql<number>`${now.getTime()}`.as('updated_at'),
})
.from(properties)
.where(
and(
eq(properties.id, propertyId),
isOwner(actorId, propertyId),
receipt
? fitsStorageQuota(db, actorId, receipt.size)
: undefined,
),
),
)
.returning({ id: transactions.id })
if (!receipt) {
const [inserted] = await atomically(db, [insert])
return inserted.length > 0 ? id : null
}
const [inserted] = await atomically(db, [
insert,
insertReceipt(actorId, propertyId, id, receipt, now),
])
return inserted.length > 0 ? id : null
},
/**
* Updates an entry of the flat and its receipt; a replacement that
* doesn't fit the storage quota changes nothing. Returns whether it
* applied and the keys of the receipt files it removed, which the caller
* deletes from storage.
*/
async update(
actorId: string,
propertyId: string,
transactionId: string,
fields: TransactionFields,
change: ReceiptChange,
now: Date,
): Promise<{ applied: boolean; removedKeys: string[] }> {
// A replacement must fit the quota, or nothing changes.
const fits =
change.kind === 'replace'
? fitsStorageQuota(db, actorId, change.receipt.size, transactionId)
: undefined
const update = db
.update(transactions)
.set({ ...fields, updatedAt: now })
.where(and(ownedEntry(actorId, propertyId, transactionId), fits))
.returning({ id: transactions.id })
if (change.kind === 'keep') {
const [updated] = await atomically(db, [update])
return { applied: updated.length > 0, removedKeys: [] }
}
const remove = db
.delete(receipts)
.where(
and(
eq(receipts.transactionId, transactionId),
exists(
db
.select({ one: sql`1` })
.from(transactions)
.where(ownedEntry(actorId, propertyId, transactionId)),
),
fits,
),
)
.returning({ key: receipts.key })
if (change.kind === 'remove') {
const [updated, removed] = await atomically(db, [update, remove])
return {
applied: updated.length > 0,
removedKeys: removed.map((row) => row.key),
}
}
const [updated, removed] = await atomically(db, [
update,
remove,
insertReceipt(actorId, propertyId, transactionId, change.receipt, now),
])
return {
applied: updated.length > 0,
removedKeys: removed.map((row) => row.key),
}
},
/** Deletes an entry of the flat; returns whether it applied and its file. */
async delete(
actorId: string,
propertyId: string,
transactionId: string,
): Promise<{ applied: boolean; removedKeys: string[] }> {
const [removed, deleted] = await atomically(db, [
db
.delete(receipts)
.where(
and(
eq(receipts.transactionId, transactionId),
exists(
db
.select({ one: sql`1` })
.from(transactions)
.where(ownedEntry(actorId, propertyId, transactionId)),
),
),
)
.returning({ key: receipts.key }),
db
.delete(transactions)
.where(ownedEntry(actorId, propertyId, transactionId))
.returning({ id: transactions.id }),
])
return {
applied: deleted.length > 0,
removedKeys: removed.map((row) => row.key),
}
},
/** A receipt with its file key and its entry's flat, for serving it. */
async receiptForAccess(
receiptId: string,
): Promise<
| (Receipt & { key: string; propertyId: string; transactionId: string })
| null
> {
const row = await db
.select({
receipt: receipts,
propertyId: transactions.propertyId,
})
.from(receipts)
.innerJoin(transactions, eq(transactions.id, receipts.transactionId))
.where(eq(receipts.id, receiptId))
.get()
if (!row) {
return null
}
const { receipt } = row
return {
id: receipt.id,
key: receipt.key,
contentType: receipt.contentType,
size: receipt.size,
filename: receipt.filename,
createdAt: receipt.createdAt,
transactionId: receipt.transactionId,
propertyId: row.propertyId,
}
},
/**
* The bytes and number of files the user has uploaded, receipts and
* documents, not counting the receipt of `replacing`.
*/
storageUsage(userId: string, replacing?: string) {
return storageUsage(db, userId, replacing)
},
}
}
export type TransactionRepository = ReturnType<typeof transactionRepository>
|