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 | 3x 3x 9x 9x 3x 18x 18x 8x 10x 37x 2x 2x 35x 35x 35x 35x 5x 1x 4x 4x 13x 13x 1x 12x 10x 12x 3x 3x 1x 2x 1x 2x 23x 23x 3x 20x 2x 18x 7x 11x 6x 6x 1x 5x 2x 3x 12x 5x 5x 1x 4x 4x 12x 4x 8x 8x 1x 7x 7x 7x | // Flats: the logic behind the server functions in functions.ts, with its
// dependencies passed in so Workers tests can drive it (openspec: properties).
import { isoDateInFinland, type IsoDate } from '#/lib/dates'
import type { AlertReason } from '#/lib/reasons'
import { deleteStoredFiles } from '#/server/files/delete'
import type { FileStorage } from '#/server/files/storage'
import type { Logger } from '#/server/log/log'
import {
sortByStreetAddress,
type ArchivedProperty,
type Property,
type PropertyDetails,
} from './property'
import type {
DeletionSummary,
PropertyRepository,
} from './property.repository.server'
export interface PropertyDeps {
/** The signed-in user. */
userId: string
properties: PropertyRepository
/** Where the receipt files are, for deleting a flat. */
storage: FileStorage
log: Logger
now: () => Date
/** The Intl locale to sort addresses in. */
collation: string
}
/**
* Kotivalo is made for 1–10 flats; this bounds what one account can store
* under open sign-up (spec: "Limiting the number of flats").
*/
export const PROPERTY_LIMIT = 100
type Result<T> =
| ({ ok: true } & T)
| { ok: false; reason: Extract<AlertReason, `property_${string}`> }
const notFound = { ok: false, reason: 'property_not_found' } as const
export interface PropertyLists {
/** The flats the user hasn't archived, by street address. */
properties: Property[]
/** The flats the user has archived, by street address. */
archived: ArchivedProperty[]
}
export async function listProperties(
deps: PropertyDeps,
): Promise<PropertyLists> {
const [active, archived] = await Promise.all([
deps.properties.listForUser(deps.userId),
deps.properties.listArchivedForUser(deps.userId),
])
return {
properties: sortByStreetAddress(active, deps.collation),
archived: sortByStreetAddress(
archived.map(({ archivedAt, ...flat }) => ({
...flat,
archivedOn: isoDateInFinland(archivedAt ?? deps.now()),
})),
deps.collation,
),
}
}
export async function getProperty(
deps: PropertyDeps,
id: string,
): Promise<Result<{ property: Property }>> {
const found = await deps.properties.findForUser(deps.userId, id)
if (!found) {
return notFound
}
return {
ok: true,
property: {
id: found.id,
streetAddress: found.streetAddress,
postcode: found.postcode,
city: found.city,
roomCount: found.roomCount,
floorArea: found.floorArea,
housingCompanyName: found.housingCompanyName,
businessId: found.businessId,
apartmentNumber: found.apartmentNumber,
},
}
}
/**
* Adds a flat owned 100 % by the user from `ownedSince`, today in Finland
* when not given (spec: "The first ownership period").
*/
export async function createProperty(
deps: PropertyDeps,
details: PropertyDetails,
ownedSince?: IsoDate,
): Promise<Result<{ id: string }>> {
// The count and the insert are separate statements, so two requests at
// once can pass 100 by one; the limit bounds abuse, it is not a rule
// (design decision 4).
if ((await deps.properties.countForUser(deps.userId)) >= PROPERTY_LIMIT) {
deps.log.warn('property.limit_reached', { limit: PROPERTY_LIMIT })
return { ok: false, reason: 'property_limit_reached' }
}
const now = deps.now()
const { id } = await deps.properties.create(
deps.userId,
details,
now,
ownedSince ?? isoDateInFinland(now),
)
deps.log.info('property.created', { propertyId: id })
return { ok: true, id }
}
export async function updateProperty(
deps: PropertyDeps,
id: string,
details: PropertyDetails,
): Promise<Result<{ id: string }>> {
if (!(await deps.properties.update(deps.userId, id, details, deps.now()))) {
return notFound
}
deps.log.info('property.updated', { propertyId: id })
return { ok: true, id }
}
/** Archives the flat for the user only (spec: "Archiving a flat"). */
export async function archiveProperty(
deps: PropertyDeps,
id: string,
): Promise<Result<object>> {
const result = await deps.properties.setArchived(deps.userId, id, deps.now())
if (result === 'not_found') {
return notFound
}
if (result === 'changed') {
deps.log.info('property.archived', { propertyId: id })
}
return { ok: true }
}
/** Brings an archived flat back to the user's views. */
export async function restoreProperty(
deps: PropertyDeps,
id: string,
): Promise<Result<object>> {
const result = await deps.properties.setArchived(deps.userId, id, null)
if (result === 'not_found') {
return notFound
}
if (result === 'changed') {
deps.log.info('property.restored', { propertyId: id })
}
return { ok: true }
}
type DeletionRefusal =
| { allowed: false; reason: 'sharing_owner_only'; otherOwners: string[] }
| {
allowed: false
reason: 'property_delete_other_owners'
otherOwners: string[]
}
export type PropertyDeletion =
| ({ ok: true; allowed: true } & DeletionSummary)
| ({ ok: true } & DeletionRefusal)
| typeof notFound
/** Whether the user may delete the flat, as `allowed` with its reason. */
async function refusalFor(
deps: PropertyDeps,
id: string,
): Promise<DeletionRefusal | 'not_found' | undefined> {
const { role, otherOwners } = await deps.properties.deletionCheck(
deps.userId,
id,
)
if (role === undefined) {
return 'not_found'
}
if (role !== 'owner') {
return { allowed: false, reason: 'sharing_owner_only', otherOwners: [] }
}
if (otherOwners.length > 0) {
return {
allowed: false,
reason: 'property_delete_other_owners',
otherOwners,
}
}
return undefined
}
/** What the deletion confirmation shows (spec: "Confirming the deletion of a flat"). */
export async function getPropertyDeletion(
deps: PropertyDeps,
id: string,
): Promise<PropertyDeletion> {
const refusal = await refusalFor(deps, id)
if (refusal === 'not_found') {
return notFound
}
if (refusal) {
return { ok: true, ...refusal }
}
return {
ok: true,
allowed: true,
...(await deps.properties.deletionSummary(id)),
}
}
/**
* Deletes the flat with everything recorded for it, then its receipt files
* (spec: "Deleting a flat"). The rows go in one guarded statement that
* repeats the rule, so a change made after the check can't get through; a
* failed file delete is logged and doesn't undo the deletion.
*/
export async function deleteProperty(
deps: PropertyDeps,
id: string,
): Promise<
| { ok: true }
| {
ok: false
reason:
| 'property_not_found'
| 'property_delete_other_owners'
| 'sharing_owner_only'
}
> {
const refuse = async () => {
const refusal = await refusalFor(deps, id)
if (refusal === 'not_found' || refusal === undefined) {
return notFound
}
deps.log.warn('property.delete_refused', {
propertyId: id,
reason: refusal.reason,
})
return { ok: false, reason: refusal.reason } as const
}
if (await refusalFor(deps, id)) {
return refuse()
}
const keys = await deps.properties.fileKeys(id)
if (!(await deps.properties.deleteGuarded(deps.userId, id))) {
return refuse()
}
await deleteStoredFiles(
deps.storage,
deps.log,
keys,
'property.file_delete_failed',
)
deps.log.info('property.deleted', { propertyId: id })
return { ok: true }
}
|