All files / src/server/repositories/implementations ItemRepository.ts

97.05% Statements 33/34
100% Branches 32/32
94.11% Functions 16/17
96.87% Lines 31/32

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                                  748x                               621x 621x                                   621x 19x       19x         602x 602x 602x       602x         100x       100x       32x       32x                     129x         129x     282x         3x         3x             4x                   4x             604x       604x       7x               7x       8x               8x       7x             14x       14x       1040x                                                              
import { eq, isNull, isNotNull, and, sql, asc, desc } from "drizzle-orm";
import type { Database } from "@/lib/db";
import { itemsTable } from "@/lib/db/schema";
import type { Item } from "@/types";
import { generateId } from "@/lib/id";
import { allocateWithRetry } from "../allocateWithRetry";
import { isUniqueViolation } from "../pg-conflict";
 
// Optional ordering for findByCollection; omit it for the full, unordered read.
// `orderBy: "number"` sorts number ASC with an id ASC tiebreaker (number is
// nullable, so determinism can't rest on it alone); `number` is the only
// supported order key for now.
export interface FindByCollectionOptions {
  orderBy?: "number";
}
 
export class ItemRepository {
  constructor(private db: Database) {}
 
  async create(data: {
    id?: string;
    collectionId: string;
    name?: string | null;
    number?: number;
    brand?: string;
    style?: string;
    color?: string;
    material?: string;
    category?: string;
    status?: string;
    notes?: string;
    story?: string | null;
  }): Promise<Item> {
    const id = data.id || generateId("item");
    const base = {
      id,
      collectionId: data.collectionId,
      name: data.name ?? null,
      brand: data.brand || null,
      style: data.style || null,
      color: data.color || null,
      material: data.material || null,
      category: data.category || null,
      status: data.status || null,
      notes: data.notes || null,
      story: data.story || null,
      createdAt: new Date(),
      updatedAt: new Date(),
      deletedAt: null,
    };
 
    // Explicit number: single insert, let any conflict surface.
    if (data.number != null) {
      const [item] = await this.db
        .insert(itemsTable)
        .values({ ...base, number: data.number })
        .returning();
      return this.mapToItem(item);
    }
 
    // Auto-allocate MAX+1, retry on the UNIQUE(collection_id, number) race
    // (a retry-able insert — simpler than locking the max; a transaction is available but unnecessary here).
    return allocateWithRetry(async () => {
      const number = await this.getNextCatalogNumber(data.collectionId);
      const [item] = await this.db
        .insert(itemsTable)
        .values({ ...base, number })
        .returning();
      return this.mapToItem(item);
    }, isCatalogNumberConflict);
  }
 
  async findById(id: string): Promise<Item | null> {
    const [item] = await this.db
      .select()
      .from(itemsTable)
      .where(and(eq(itemsTable.id, id), isNull(itemsTable.deletedAt)));
    return item ? this.mapToItem(item) : null;
  }
 
  async findByIdIncludingDeleted(id: string): Promise<Item | null> {
    const [item] = await this.db
      .select()
      .from(itemsTable)
      .where(eq(itemsTable.id, id));
    return item ? this.mapToItem(item) : null;
  }
 
  // Non-deleted items of a collection. With no options this is the full,
  // unordered read. `orderBy: "number"` sorts number ASC; number is nullable in
  // schema (determinism rests on the app invariant that create always assigns
  // one, not a DB constraint), so id ASC is the belt-and-suspenders tiebreaker.
  async findByCollection(
    collectionId: string,
    options?: FindByCollectionOptions,
  ): Promise<Item[]> {
    const base = this.db
      .select()
      .from(itemsTable)
      .where(and(eq(itemsTable.collectionId, collectionId), isNull(itemsTable.deletedAt)));
    const ordered =
      options?.orderBy === "number"
        ? base.orderBy(asc(itemsTable.number), asc(itemsTable.id))
        : base;
    return (await ordered).map((i) => this.mapToItem(i));
  }
 
  // Soft-deleted ("archived") items of a collection, most recently archived first.
  async findArchivedByCollection(collectionId: string): Promise<Item[]> {
    const rows = await this.db
      .select()
      .from(itemsTable)
      .where(and(eq(itemsTable.collectionId, collectionId), isNotNull(itemsTable.deletedAt)))
      .orderBy(desc(itemsTable.deletedAt), asc(itemsTable.id));
    return rows.map((r) => this.mapToItem(r));
  }
 
  async findByCollectionAndNumber(
    collectionId: string,
    number: number,
  ): Promise<Item | null> {
    const [item] = await this.db
      .select()
      .from(itemsTable)
      .where(
        and(
          eq(itemsTable.collectionId, collectionId),
          eq(itemsTable.number, number),
          isNull(itemsTable.deletedAt),
        ),
      );
    return item ? this.mapToItem(item) : null;
  }
 
  async getNextCatalogNumber(collectionId: string): Promise<number> {
    // MAX over ALL rows (incl. soft-deleted) — a deleted item still holds its
    // number in the UNIQUE(collection_id, number) index, so reusing it would
    // collide. Resolution (findByCollectionAndNumber) excludes deleted rows.
    const [row] = await this.db
      .select({ max: sql<number | null>`max(${itemsTable.number})` })
      .from(itemsTable)
      .where(eq(itemsTable.collectionId, collectionId));
    return (row?.max ?? 0) + 1;
  }
 
  async update(id: string, data: Partial<Item>): Promise<Item> {
    const [item] = await this.db
      .update(itemsTable)
      .set({
        ...data,
        updatedAt: new Date(),
      })
      .where(eq(itemsTable.id, id))
      .returning();
    return this.mapToItem(item);
  }
 
  async softDelete(id: string): Promise<Item> {
    const [item] = await this.db
      .update(itemsTable)
      .set({
        deletedAt: new Date(),
        updatedAt: new Date(),
      })
      .where(eq(itemsTable.id, id))
      .returning();
    return this.mapToItem(item);
  }
 
  async hardDelete(id: string): Promise<void> {
    await this.db.delete(itemsTable).where(eq(itemsTable.id, id));
  }
 
  // Permanently DELETE every item of the collection (active AND soft-deleted),
  // returning the affected count. Caller has already removed FK-referencing
  // children (photos, result-items, preferences). Purge-only.
  async hardDeleteByCollection(collectionId: string): Promise<number> {
    const rows = await this.db
      .delete(itemsTable)
      .where(eq(itemsTable.collectionId, collectionId))
      .returning({ id: itemsTable.id });
    return rows.length;
  }
 
  private mapToItem(row: typeof itemsTable.$inferSelect): Item {
    return {
      id: row.id,
      collectionId: row.collectionId,
      name: row.name,
      brand: row.brand,
      style: row.style,
      color: row.color,
      material: row.material,
      category: row.category,
      number: row.number,
      height: row.height,
      width: row.width,
      depth: row.depth,
      weight: row.weight,
      unit: row.unit,
      status: row.status,
      notes: row.notes,
      story: row.story,
      createdAt: row.createdAt,
      updatedAt: row.updatedAt,
      deletedAt: row.deletedAt,
    };
  }
}
 
function isCatalogNumberConflict(error: unknown): boolean {
  // Retry ONLY the UNIQUE(collection_id, number) race — any other unique
  // violation is a real bug and must surface, not be masked by retries.
  // Constraint name matches the Drizzle-generated unique index; update if renamed.
  return isUniqueViolation(error, "items_collection_number_unique");
}