All files / src/common/api tagApi.ts

87.12% Statements 203/233
83.92% Branches 47/56
92.85% Functions 13/14
87.12% Lines 203/233

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  1x               1x   1x 3x 3x   3x 3x 3x 3x 3x   3x 3x 3x 3x     1x 3x 3x   3x 3x 3x 3x 3x 3x   3x 2x 1x 1x 1x 1x   1x 3x 3x     1x 2x 2x   2x 2x 2x 2x 2x   2x 1x 2x 2x     1x 2x 2x   2x 2x 2x 2x 2x 2x 2x 2x   2x 1x 2x 2x     1x 3x 3x   3x   3x 2x 3x 3x     1x 1x 1x   1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x   1x 1x     1x 3x 3x 3x   3x 3x 3x 3x 3x   3x 2x 3x 3x     1x 3x 3x   3x 3x 3x 3x 3x 3x   3x 2x 3x 3x     1x 1x 1x   1x 1x 1x 1x 1x 1x   1x 1x 1x 1x     1x 1x 1x     1x 1x 1x 1x 1x 1x   1x 1x 1x                   1x 1x 1x 1x 1x 1x     1x 1x 1x   1x 1x 1x 1x   1x 1x 1x 1x     1x 4x 4x   4x 4x 4x   4x 4x 4x 4x     1x 1x 1x   1x 1x 1x 1x 1x 1x   1x 1x 1x 1x     1x                                                                             1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x  
import { Tag, TagCreate, TagUpdate } from '../types';
import {
  handleSupabaseError,
  requireAuth,
  supabase,
  withPerformanceLogging,
} from './supabaseClient';
 
// Tag API Service
export const tagApi = {
  // Get all tags for the current user
  async getAll(): Promise<Tag[]> {
    return withPerformanceLogging('tags.getAll', async () => {
      const user = await requireAuth();
 
      const { data, error } = await supabase
        .from('tags')
        .select('id, name, color, created_at, updated_at, user_id')
        .eq('user_id', user.id)
        .order('name');
 
      if (error) handleSupabaseError(error);
      return data || [];
    });
  },
 
  // Get tag by ID
  async getById(id: string): Promise<Tag | null> {
    return withPerformanceLogging('tags.getById', async () => {
      const user = await requireAuth();
 
      const { data, error } = await supabase
        .from('tags')
        .select('id, name, color, created_at, updated_at, user_id')
        .eq('id', id)
        .eq('user_id', user.id)
        .single();
 
      if (error) {
        if (error.code === 'PGRST116') {
          return null; // Not found
        }
        handleSupabaseError(error);
      }
 
      return data;
    });
  },
 
  // Create a new tag
  async create(tag: TagCreate): Promise<Tag> {
    return withPerformanceLogging('tags.create', async () => {
      const user = await requireAuth();
 
      const { data, error } = await supabase
        .from('tags')
        .insert([{ ...tag, user_id: user.id }])
        .select()
        .single();
 
      if (error) handleSupabaseError(error);
      return data;
    });
  },
 
  // Update an existing tag
  async update(tag: TagUpdate): Promise<Tag> {
    return withPerformanceLogging('tags.update', async () => {
      const user = await requireAuth();
 
      const { id, ...updates } = tag;
      const { data, error } = await supabase
        .from('tags')
        .update(updates)
        .eq('id', id)
        .eq('user_id', user.id)
        .select()
        .single();
 
      if (error) handleSupabaseError(error);
      return data;
    });
  },
 
  // Delete a tag
  async delete(tagId: string): Promise<boolean> {
    return withPerformanceLogging('tags.delete', async () => {
      const user = await requireAuth();
 
      const { error } = await supabase.from('tags').delete().eq('id', tagId).eq('user_id', user.id);
 
      if (error) handleSupabaseError(error);
      return true;
    });
  },
 
  // Get tags for a specific newsletter
  async getTagsForNewsletter(newsletterId: string): Promise<Tag[]> {
    return withPerformanceLogging('tags.getTagsForNewsletter', async () => {
      const user = await requireAuth();
 
      const { data, error } = await supabase
        .from('newsletter_tags')
        .select('tag:tags(*)')
        .eq('newsletter_id', newsletterId)
        .eq('user_id', user.id);
 
      if (error) handleSupabaseError(error);
      return (
        data
          ?.map((item: { tag: any }) => {
            if (item.tag && typeof item.tag === 'object') {
              return {
                id: item.tag.id as string,
                name: item.tag.name as string,
                color: item.tag.color as string,
                user_id: item.tag.user_id as string,
                created_at: item.tag.created_at as string,
                newsletter_count: item.tag.newsletter_count,
              } as Tag;
            }
            return null;
          })
          .filter((tag): tag is Tag => tag !== null) || []
      );
    });
  },
 
  // Update tags for a newsletter
  async updateNewsletterTags(newsletterId: string, tags: Tag[]): Promise<boolean> {
    return withPerformanceLogging('tags.updateNewsletterTags', async () => {
      const user = await requireAuth();
      const tagIds = tags.map((t) => t.id);
 
      const { error } = await supabase.rpc('set_newsletter_tags', {
        p_newsletter_id: newsletterId,
        p_user_id: user.id,
        p_tag_ids: tagIds,
      });
 
      if (error) handleSupabaseError(error);
      return true;
    });
  },
 
  // Add a tag to a newsletter
  async addToNewsletter(newsletterId: string, tagId: string): Promise<boolean> {
    return withPerformanceLogging('tags.addToNewsletter', async () => {
      const user = await requireAuth();
 
      const { error } = await supabase
        .from('newsletter_tags')
        .upsert(
          { newsletter_id: newsletterId, tag_id: tagId, user_id: user.id },
          { onConflict: 'newsletter_id,tag_id', ignoreDuplicates: true }
        );
 
      if (error) handleSupabaseError(error);
      return true;
    });
  },
 
  // Remove a tag from a newsletter
  async removeFromNewsletter(newsletterId: string, tagId: string): Promise<boolean> {
    return withPerformanceLogging('tags.removeFromNewsletter', async () => {
      const user = await requireAuth();
 
      const { error } = await supabase
        .from('newsletter_tags')
        .delete()
        .eq('newsletter_id', newsletterId)
        .eq('tag_id', tagId)
        .eq('user_id', user.id);
 
      if (error) handleSupabaseError(error);
      return true;
    });
  },
 
  // Get or create a tag by name
  async getOrCreate(name: string, color?: string): Promise<Tag> {
    return withPerformanceLogging('tags.getOrCreate', async () => {
      const user = await requireAuth();
 
      // Try to find existing tag
      const { data: existingTag } = await supabase
        .from('tags')
        .select('id, name, color, created_at, updated_at, user_id')
        .eq('name', name.trim())
        .eq('user_id', user.id)
        .single();
 
      if (existingTag) {
        return existingTag;
      }
 
      // Create new tag if not found
      const tagColor =
        color ||
        '#' +
          Math.floor(Math.random() * 16777215)
            .toString(16)
            .padStart(6, '0');
 
      return this.create({
        name: name.trim(),
        color: tagColor,
      });
    });
  },
 
  // Bulk create tags
  async bulkCreate(tags: TagCreate[]): Promise<Tag[]> {
    return withPerformanceLogging('tags.bulkCreate', async () => {
      const user = await requireAuth();
 
      const { data, error } = await supabase
        .from('tags')
        .insert(tags.map((tag) => ({ ...tag, user_id: user.id })))
        .select();
 
      if (error) handleSupabaseError(error);
      return data || [];
    });
  },
 
  // Get newsletter count for each tag using the same logic as filtering
  async getTagUsageStats(): Promise<Array<Tag & { newsletter_count: number }>> {
    return withPerformanceLogging('tags.getTagUsageStats', async () => {
      const user = await requireAuth();
 
      const { data, error } = await supabase.rpc('get_tags_with_counts', {
        p_user_id: user.id,
      });
 
      if (error) handleSupabaseError(error);
      return data ?? [];
    });
  },
 
  // Search tags by name
  async search(query: string): Promise<Tag[]> {
    return withPerformanceLogging('tags.search', async () => {
      const user = await requireAuth();
 
      const { data, error } = await supabase
        .from('tags')
        .select('id, name, color, created_at, updated_at, user_id')
        .eq('user_id', user.id)
        .ilike('name', `%${query}%`)
        .order('name');
 
      if (error) handleSupabaseError(error);
      return data || [];
    });
  },
 
  // Get tags with pagination
  async getPaginated(
    options: {
      limit?: number;
      offset?: number;
      search?: string;
      orderBy?: 'name' | 'created_at';
      ascending?: boolean;
    } = {}
  ): Promise<{
    data: Tag[];
    count: number;
    hasMore: boolean;
  }> {
    return withPerformanceLogging('tags.getPaginated', async () => {
      const user = await requireAuth();
      const { limit = 50, offset = 0, search, orderBy = 'name', ascending = true } = options;
 
      let query = supabase
        .from('tags')
        .select('id, name, color, created_at, updated_at, user_id', { count: 'exact' })
        .eq('user_id', user.id);
 
      if (search) {
        query = query.ilike('name', `%${search}%`);
      }
 
      query = query.order(orderBy, { ascending }).range(offset, offset + limit - 1);
 
      const { data, error, count } = await query;
 
      if (error) handleSupabaseError(error);
 
      return {
        data: data || [],
        count: count || 0,
        hasMore: (data?.length || 0) === limit,
      };
    });
  },
};
 
// Export individual functions for backward compatibility
export const {
  getAll: getAllTags,
  getById: getTagById,
  create: createTag,
  update: updateTag,
  delete: deleteTag,
  getTagsForNewsletter,
  updateNewsletterTags,
  addToNewsletter: addTagToNewsletter,
  removeFromNewsletter: removeTagFromNewsletter,
  getOrCreate: getOrCreateTag,
  bulkCreate: bulkCreateTags,
  getTagUsageStats,
  search: searchTags,
  getPaginated: getPaginatedTags,
} = tagApi;
 
export default tagApi;