All files / src/features/sharing sharing.repository.server.ts

100% Statements 30/30
100% Branches 8/8
100% Functions 17/17
100% Lines 30/30

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                                                                                              751x 13x                     751x 42x           751x         833x                   833x         36x                     36x 32x           7x                                             68x                       68x                     64x               64x       71x                                             74x 74x                                             74x                       6x                 6x         9x                                                                       21x                                         21x         4x                 4x                       7x                     7x         4x                   4x            
// Who can reach a flat and who is invited to it (openspec: sharing). Checks
// of the acting user's role are inside the statements that change data, as
// in the property repository, so there is no read-then-write gap.
import { and, asc, desc, eq, gt, inArray, lte, sql } from 'drizzle-orm'
import { isLocale, type Locale } from '#/paraglide/runtime.js'
import {
  properties,
  propertyAccess,
  propertyInvitations,
  user,
  type PropertyRole,
} from '#/server/db/schema'
import { atomically, type Db } from '#/server/platform/db.server'
 
export interface Person {
  userId: string
  name: string
  role: PropertyRole
  since: Date
}
 
export interface PendingInvitation {
  id: string
  email: string
  createdAt: Date
  expiresAt: Date
}
 
/** An invitation as its invitee sees it. */
export interface ReceivedInvitation {
  id: string
  propertyId: string
  streetAddress: string
  city: string
  inviterName: string
  expiresAt: Date
}
 
/** What an address means to a flat: an account's language and access. */
export interface Recipient {
  /** The language of the account with the address; null without one. */
  locale: Locale | null
  hasAccess: boolean
}
 
export function sharingRepository(db: Db) {
  /** The flats the user owns, as a subquery. */
  const owned = (userId: string) =>
    db
      .select({ id: propertyAccess.propertyId })
      .from(propertyAccess)
      .where(
        and(
          eq(propertyAccess.userId, userId),
          eq(propertyAccess.role, 'owner'),
        ),
      )
 
  /** An invitation that `email` may still accept. */
  const acceptable = (invitationId: string, email: string, now: Date) =>
    and(
      eq(propertyInvitations.id, invitationId),
      eq(propertyInvitations.email, email),
      gt(propertyInvitations.expiresAt, now),
    )
 
  return {
    async roleOf(
      userId: string,
      propertyId: string,
    ): Promise<PropertyRole | undefined> {
      const row = await db
        .select({ role: propertyAccess.role })
        .from(propertyAccess)
        .where(
          and(
            eq(propertyAccess.userId, userId),
            eq(propertyAccess.propertyId, propertyId),
          ),
        )
        .get()
      return row?.role
    },
 
    /** The users with access: the owner first, then in the order they joined. */
    async listPeople(propertyId: string): Promise<Person[]> {
      const rows = await db
        .select({
          userId: propertyAccess.userId,
          name: user.name,
          role: propertyAccess.role,
          since: propertyAccess.createdAt,
        })
        .from(propertyAccess)
        .innerJoin(user, eq(user.id, propertyAccess.userId))
        .where(eq(propertyAccess.propertyId, propertyId))
        .orderBy(asc(propertyAccess.createdAt))
      return rows.sort(
        (a, b) => Number(b.role === 'owner') - Number(a.role === 'owner'),
      )
    },
 
    /** Newest first. Expired invitations are left out. */
    listPending(propertyId: string, now: Date): Promise<PendingInvitation[]> {
      return db
        .select({
          id: propertyInvitations.id,
          email: propertyInvitations.email,
          createdAt: propertyInvitations.createdAt,
          expiresAt: propertyInvitations.expiresAt,
        })
        .from(propertyInvitations)
        .where(
          and(
            eq(propertyInvitations.propertyId, propertyId),
            gt(propertyInvitations.expiresAt, now),
          ),
        )
        .orderBy(desc(propertyInvitations.createdAt))
    },
 
    /**
     * The account with `email`, if any, and whether it has access to the
     * flat: one query, so an address with an account takes the same path as
     * one without.
     */
    async findRecipient(propertyId: string, email: string): Promise<Recipient> {
      const row = await db
        .select({ locale: user.locale, access: propertyAccess.userId })
        .from(user)
        .leftJoin(
          propertyAccess,
          and(
            eq(propertyAccess.userId, user.id),
            eq(propertyAccess.propertyId, propertyId),
          ),
        )
        .where(eq(user.email, email))
        .get()
      return {
        locale: row !== undefined && isLocale(row.locale) ? row.locale : null,
        hasAccess: row?.access != null,
      }
    },
 
    async isPending(
      propertyId: string,
      email: string,
      now: Date,
    ): Promise<boolean> {
      const count = await db.$count(
        propertyInvitations,
        and(
          eq(propertyInvitations.propertyId, propertyId),
          eq(propertyInvitations.email, email),
          gt(propertyInvitations.expiresAt, now),
        ),
      )
      return count > 0
    },
 
    countPending(propertyId: string, now: Date): Promise<number> {
      return db.$count(
        propertyInvitations,
        and(
          eq(propertyInvitations.propertyId, propertyId),
          gt(propertyInvitations.expiresAt, now),
        ),
      )
    },
 
    /**
     * Saves an invitation, replacing an expired one for the same address.
     * The caller has checked the role and that none is pending; the unique
     * key refuses a duplicate that slipped past.
     */
    async invite(invitation: {
      /** Chosen by the caller when the email needs it first. */
      id?: string
      propertyId: string
      email: string
      invitedBy: string
      now: Date
      expiresAt: Date
    }): Promise<{ id: string } | undefined> {
      const id = invitation.id ?? crypto.randomUUID()
      const [, inserted] = await atomically(db, [
        db
          .delete(propertyInvitations)
          .where(
            and(
              eq(propertyInvitations.propertyId, invitation.propertyId),
              eq(propertyInvitations.email, invitation.email),
              lte(propertyInvitations.expiresAt, invitation.now),
            ),
          ),
        db
          .insert(propertyInvitations)
          .values({
            id,
            propertyId: invitation.propertyId,
            email: invitation.email,
            invitedBy: invitation.invitedBy,
            createdAt: invitation.now,
            expiresAt: invitation.expiresAt,
          })
          .onConflictDoNothing()
          .returning({ id: propertyInvitations.id }),
      ])
      return inserted.length > 0 ? { id } : undefined
    },
 
    /**
     * Deletes an invitation to a flat the user owns. Returns its flat's id,
     * or undefined when there was no such invitation or the user isn't the
     * owner.
     */
    async cancel(
      ownerId: string,
      invitationId: string,
    ): Promise<string | undefined> {
      const deleted = await db
        .delete(propertyInvitations)
        .where(
          and(
            eq(propertyInvitations.id, invitationId),
            inArray(propertyInvitations.propertyId, owned(ownerId)),
          ),
        )
        .returning({ propertyId: propertyInvitations.propertyId })
      return deleted.at(0)?.propertyId
    },
 
    /** The invitations `email` may accept, newest first. */
    listForInvitee(email: string, now: Date): Promise<ReceivedInvitation[]> {
      return db
        .select({
          id: propertyInvitations.id,
          propertyId: propertyInvitations.propertyId,
          streetAddress: properties.streetAddress,
          city: properties.city,
          inviterName: user.name,
          expiresAt: propertyInvitations.expiresAt,
        })
        .from(propertyInvitations)
        .innerJoin(
          properties,
          eq(properties.id, propertyInvitations.propertyId),
        )
        .innerJoin(user, eq(user.id, propertyInvitations.invitedBy))
        .where(
          and(
            eq(propertyInvitations.email, email),
            gt(propertyInvitations.expiresAt, now),
          ),
        )
        .orderBy(desc(propertyInvitations.createdAt))
    },
 
    /**
     * Turns an invitation into `member` access for the user signed in with
     * `email`, and deletes it. Both statements match only an unexpired
     * invitation for that address, so anything else changes nothing.
     * Returns the flat's id, or undefined.
     */
    async accept(
      userId: string,
      email: string,
      invitationId: string,
      now: Date,
    ): Promise<string | undefined> {
      const [inserted] = await atomically(db, [
        db
          .insert(propertyAccess)
          .select(
            db
              .select({
                propertyId: propertyInvitations.propertyId,
                userId: sql<string>`${userId}`.as('user_id'),
                role: sql<PropertyRole>`'member'`.as('role'),
                createdAt: sql<Date>`${now.getTime()}`.as('created_at'),
                archivedAt: sql<Date | null>`NULL`.as('archived_at'),
              })
              .from(propertyInvitations)
              .where(acceptable(invitationId, email, now)),
          )
          .onConflictDoNothing()
          .returning({ propertyId: propertyAccess.propertyId }),
        db
          .delete(propertyInvitations)
          .where(acceptable(invitationId, email, now)),
      ])
      return inserted.at(0)?.propertyId
    },
 
    /** Deletes an invitation for `email`. Returns whether there was one. */
    async decline(email: string, invitationId: string): Promise<boolean> {
      const deleted = await db
        .delete(propertyInvitations)
        .where(
          and(
            eq(propertyInvitations.id, invitationId),
            eq(propertyInvitations.email, email),
          ),
        )
        .returning({ id: propertyInvitations.id })
      return deleted.length > 0
    },
 
    /**
     * Removes a member's access to a flat the acting user owns. Never
     * removes an owner. Returns whether access was removed.
     */
    async removeMember(
      ownerId: string,
      propertyId: string,
      memberId: string,
    ): Promise<boolean> {
      const deleted = await db
        .delete(propertyAccess)
        .where(
          and(
            eq(propertyAccess.propertyId, propertyId),
            eq(propertyAccess.userId, memberId),
            eq(propertyAccess.role, 'member'),
            inArray(propertyAccess.propertyId, owned(ownerId)),
          ),
        )
        .returning({ userId: propertyAccess.userId })
      return deleted.length > 0
    },
 
    /** Removes the user's own `member` access. Returns whether it did. */
    async leave(memberId: string, propertyId: string): Promise<boolean> {
      const deleted = await db
        .delete(propertyAccess)
        .where(
          and(
            eq(propertyAccess.propertyId, propertyId),
            eq(propertyAccess.userId, memberId),
            eq(propertyAccess.role, 'member'),
          ),
        )
        .returning({ userId: propertyAccess.userId })
      return deleted.length > 0
    },
  }
}
 
export type SharingRepository = ReturnType<typeof sharingRepository>