All files / src/services/db store.db.ts

44.68% Statements 122/273
88.46% Branches 23/26
60% Functions 9/15
49.55% Lines 111/224

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 2252x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 25x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 47x 47x 2x 2x     47x   47x 46x   1x                                 2x 2x 2x 6x 6x 6x   6x 2x     4x   2x                                 2x 2x 2x 2x 2x                                   2x 2x 2x 2x 2x 2x 2x 4x 4x 4x 4x   4x 3x 3x     4x 2x 2x     4x         4x     4x   4x           4x   4x 1x     1x                     2x 2x 2x 2x 2x 2x 2x 2x 2x     2x 2x 2x   2x 1x     1x                 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   4x 4x           4x 4x               2x 2x 2x 2x 2x 2x  
// src/services/db/store.db.ts
import type { Pool, PoolClient } from 'pg';
import { getPool } from './connection.db';
import type { Logger } from 'pino';
import { NotFoundError, handleDbError } from './errors.db';
import type { Store } from '../../types';
 
export class StoreRepository {
  private db: Pick<Pool | PoolClient, 'query'>;
 
  constructor(db: Pick<Pool | PoolClient, 'query'> = getPool()) {
    this.db = db;
  }
 
  /**
   * Creates a new store in the database.
   * @param name Store name (must be unique)
   * @param logger Logger instance
   * @param logoUrl Optional logo URL
   * @param createdBy Optional user ID who created the store
   * @returns The ID of the newly created store
   */
  async createStore(
    name: string,
    logger: Logger,
    logoUrl?: string | null,
    createdBy?: string | null,
  ): Promise<number> {
    try {
      const query = `
        INSERT INTO public.stores (name, logo_url, created_by)
        VALUES ($1, $2, $3)
        RETURNING store_id
      `;
      const values = [name, logoUrl || null, createdBy || null];

      const result = await this.db.query<{ store_id: number }>(query, values);
      return result.rows[0].store_id;
    } catch (error) {
      handleDbError(
        error,
        logger,
        'Database error in createStore',
        { name, logoUrl, createdBy },
        {
          uniqueMessage: `A store with the name "${name}" already exists.`,
          defaultMessage: 'Failed to create store.',
        },
      );
    }
  }

  /**
   * Retrieves a single store by its ID (basic info only, no addresses).
   * @param storeId The store ID
   * @param logger Logger instance
   * @returns The Store object
   */
  async getStoreById(storeId: number, logger: Logger): Promise<Store> {
    try {
      const query = 'SELECT * FROM public.stores WHERE store_id = $1';
      const result = await this.db.query<Store>(query, [storeId]);

      if (result.rowCount === 0) {
        throw new NotFoundError(`Store with ID ${storeId} not found.`);
      }

      return result.rows[0];
    } catch (error) {
      handleDbError(
        error,
        logger,
        'Database error in getStoreById',
        { storeId },
        {
          defaultMessage: 'Failed to retrieve store.',
        },
      );
    }
  }

  /**
   * Retrieves all stores (basic info only, no addresses).
   * @param logger Logger instance
   * @returns Array of Store objects
   */
  async getAllStores(logger: Logger): Promise<Store[]> {
    try {
      const query = 'SELECT * FROM public.stores ORDER BY name ASC';
      const result = await this.db.query<Store>(query);
      return result.rows;
    } catch (error) {
      handleDbError(
        error,
        logger,
        'Database error in getAllStores',
        {},
        {
          defaultMessage: 'Failed to retrieve stores.',
        },
      );
    }
  }

  /**
   * Updates a store's name and/or logo URL.
   * @param storeId The store ID to update
   * @param updates Object containing fields to update
   * @param logger Logger instance
   */
  async updateStore(
    storeId: number,
    updates: { name?: string; logo_url?: string | null },
    logger: Logger,
  ): Promise<void> {
    try {
      const fields: string[] = [];
      const values: (string | number | null)[] = [];
      let paramIndex = 1;

      if (updates.name !== undefined) {
        fields.push(`name = $${paramIndex++}`);
        values.push(updates.name);
      }

      if (updates.logo_url !== undefined) {
        fields.push(`logo_url = $${paramIndex++}`);
        values.push(updates.logo_url);
      }

      Iif (fields.length === 0) {
        throw new Error('No fields provided for update');
      }

      // Add updated_at
      fields.push(`updated_at = now()`);

      // Add store_id for WHERE clause
      values.push(storeId);

      const query = `
        UPDATE public.stores
        SET ${fields.join(', ')}
        WHERE store_id = $${paramIndex}
      `;

      const result = await this.db.query(query, values);

      if (result.rowCount === 0) {
        throw new NotFoundError(`Store with ID ${storeId} not found.`);
      }
    } catch (error) {
      handleDbError(
        error,
        logger,
        'Database error in updateStore',
        { storeId, updates },
        {
          uniqueMessage: updates.name
            ? `A store with the name "${updates.name}" already exists.`
            : undefined,
          defaultMessage: 'Failed to update store.',
        },
      );
    }
  }
 
  /**
   * Deletes a store from the database.
   * Note: This will cascade delete to store_locations if any exist.
   * @param storeId The store ID to delete
   * @param logger Logger instance
   */
  async deleteStore(storeId: number, logger: Logger): Promise<void> {
    try {
      const query = 'DELETE FROM public.stores WHERE store_id = $1';
      const result = await this.db.query(query, [storeId]);

      if (result.rowCount === 0) {
        throw new NotFoundError(`Store with ID ${storeId} not found.`);
      }
    } catch (error) {
      handleDbError(
        error,
        logger,
        'Database error in deleteStore',
        { storeId },
        {
          defaultMessage: 'Failed to delete store.',
        },
      );
    }
  }
 
  /**
   * Searches for stores by name (case-insensitive partial match).
   * @param query Search query
   * @param logger Logger instance
   * @param limit Maximum number of results (default: 10)
   * @returns Array of matching Store objects
   */
  async searchStoresByName(query: string, logger: Logger, limit: number = 10): Promise<Store[]> {
    try {
      const sql = `
        SELECT * FROM public.stores
        WHERE name ILIKE $1
        ORDER BY name ASC
        LIMIT $2
      `;
      const result = await this.db.query<Store>(sql, [`%${query}%`, limit]);
      return result.rows;
    } catch (error) {
      handleDbError(
        error,
        logger,
        'Database error in searchStoresByName',
        { query, limit },
        {
          defaultMessage: 'Failed to search stores.',
        },
      );
    }
  }
}