All files / routes/admin/taxonomy standard-taxonomy-strategy.ts

100% Statements 11/11
100% Branches 6/6
100% Functions 9/9
100% Lines 11/11

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                                                                                                                          129x             47x               14x               28x                                   12x                                         34x                                                             11x   11x                                                         6x 6x                                                     10x            
/**
 * Standard Taxonomy Strategy
 *
 * Handles the majority of taxonomy types that follow the standard structure:
 * { id, name, sortOrder, isActive, ... }
 *
 * @module taxonomy/standard-taxonomy-strategy
 */
 
import { eq } from "drizzle-orm";
import type { SQL } from "drizzle-orm";
import type {
	SQLiteColumn,
	SQLiteTableWithColumns,
} from "drizzle-orm/sqlite-core";
import { generateId } from "../../../lib/utils";
import type { TaxonomyStrategy } from "./taxonomy-strategy.types";
 
/**
 * Standard taxonomy strategy for types with id/name fields
 *
 * This is the default strategy used by most taxonomy tables that follow
 * the standard structure: { id, name, sortOrder, isActive, ... }
 *
 * Handles the following taxonomy types:
 * - businessTypes
 * - executionModels
 * - timelineCategories
 * - customerSegments
 * - projectScales
 * - serviceCategories
 * - materialTags
 * - brands
 * - cities
 * - zones
 * - localities
 *
 * Key characteristics:
 * - Uses 'id' as the primary key (auto-generated with generateId())
 * - Uses 'name' as the display field
 * - Returns database items as-is (no transformation needed)
 * - Supports standard CRUD operations with consistent field naming
 *
 * @template TTable - The SQLite table type (e.g., typeof schema.businessTypes)
 *
 * @example
 * ```ts
 * const strategy = new StandardTaxonomyStrategy(schema.businessTypes);
 * const data = strategy.prepareInsertData({ name: 'Retailer' });
 * // Returns: { id: 'generated-id', name: 'Retailer', sortOrder: 0, isActive: true }
 * ```
 */
export class StandardTaxonomyStrategy<
	// biome-ignore lint/suspicious/noExplicitAny: Drizzle ORM generic table type requires any for dynamic column access
	TTable extends SQLiteTableWithColumns<any>,
> implements TaxonomyStrategy<TTable>
{
	/**
	 * Creates a new StandardTaxonomyStrategy instance
	 * @param table - The Drizzle ORM table reference
	 */
	constructor(private table: TTable) {}
 
	/**
	 * Returns the database table reference
	 * @returns The table this strategy operates on
	 */
	getTable(): TTable {
		return this.table;
	}
 
	/**
	 * Returns the primary key column (always 'id' for standard types)
	 * @returns The table.id column
	 */
	getPrimaryKeyField(): SQLiteColumn {
		return this.table.id;
	}
 
	/**
	 * Returns the name field column (always 'name' for standard types)
	 * @returns The table.name column
	 */
	getNameField(): SQLiteColumn {
		return this.table.name;
	}
 
	/**
	 * Builds a SQL WHERE condition to find an item by ID
	 *
	 * For standard types, this queries the 'id' column
	 *
	 * @param id - The ID value to search for
	 * @returns SQL condition: WHERE id = 'value'
	 *
	 * @example
	 * ```ts
	 * const condition = strategy.buildFindByIdQuery('abc123');
	 * const item = await db.select().from(table).where(condition);
	 * ```
	 */
	buildFindByIdQuery(id: string): SQL {
		return eq(this.table.id, id);
	}
 
	/**
	 * Transforms a database item for API response
	 *
	 * Standard types already have id/name fields, so no transformation is needed.
	 * The item is returned as-is.
	 *
	 * @param item - The raw database item
	 * @returns The same item unchanged
	 *
	 * @example
	 * ```ts
	 * const dbItem = { id: '123', name: 'Test', sortOrder: 0 };
	 * const apiItem = strategy.transformItem(dbItem);
	 * // Returns: { id: '123', name: 'Test', sortOrder: 0 }
	 * ```
	 */
	transformItem<T>(item: T): T {
		// Standard types return as-is (already have id/name fields)
		return item;
	}
 
	/**
	 * Prepares data for INSERT operation
	 *
	 * This method:
	 * 1. Generates an ID if not provided (using generateId())
	 * 2. Sets default sortOrder to 0 if not provided
	 * 3. Sets default isActive to true if not provided
	 * 4. Spreads all other fields from the request body
	 *
	 * @param body - The request body data from the API client
	 * @returns Data ready for database insertion with defaults applied
	 *
	 * @example
	 * ```ts
	 * const data = strategy.prepareInsertData({ name: 'New Item' });
	 * // Returns: { id: 'generated-id', name: 'New Item', sortOrder: 0, isActive: true }
	 *
	 * const data2 = strategy.prepareInsertData({
	 *   id: 'custom-id',
	 *   name: 'Custom',
	 *   sortOrder: 5,
	 *   isActive: false
	 * });
	 * // Returns: { id: 'custom-id', name: 'Custom', sortOrder: 5, isActive: false }
	 * ```
	 */
	prepareInsertData(body: Record<string, unknown>): Record<string, unknown> {
		// Generate ID if not provided
		const id = (body.id as string) || generateId();
 
		return {
			id,
			...body,
			sortOrder: body.sortOrder ?? 0,
			isActive: body.isActive ?? true,
		};
	}
 
	/**
	 * Prepares data for UPDATE operation
	 *
	 * Removes the 'id' field from the request body since primary keys
	 * cannot be updated. All other fields are passed through.
	 *
	 * @param body - The request body data from the API client
	 * @returns Data ready for database update (without the id field)
	 *
	 * @example
	 * ```ts
	 * const data = strategy.prepareUpdateData({
	 *   id: 'should-be-removed',
	 *   name: 'Updated Name',
	 *   sortOrder: 10
	 * });
	 * // Returns: { name: 'Updated Name', sortOrder: 10 }
	 * ```
	 */
	prepareUpdateData(body: Record<string, unknown>): Record<string, unknown> {
		// Remove id from body (can't update primary key)
		const { id: _bodyId, ...updateData } = body;
		return updateData;
	}
 
	/**
	 * Builds an update query for a single item in a reorder operation
	 *
	 * Used when reordering items to update only the sortOrder field.
	 * Returns both the WHERE condition and the update data.
	 *
	 * @param itemId - The ID of the item to update
	 * @param sortOrder - The new sort order value
	 * @returns Object containing the SQL condition and update data
	 *
	 * @example
	 * ```ts
	 * const { condition, data } = strategy.buildReorderUpdate('item-123', 5);
	 * await db.update(table).set(data).where(condition);
	 * // Executes: UPDATE table SET sortOrder = 5 WHERE id = 'item-123'
	 * ```
	 */
	buildReorderUpdate(
		itemId: string,
		sortOrder: number,
	): {
		condition: SQL;
		data: Record<string, unknown>;
	} {
		return {
			condition: eq(this.table.id, itemId),
			data: { sortOrder },
		};
	}
}