All files / lib/supabase/services additive.ts

80.35% Statements 45/56
91.66% Branches 33/36
80% Functions 4/5
80.35% Lines 45/56

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 352 353 354 355 356 357 358                                                                                                                                                                                                                                          4x   4x   4x             4x 1x 1x                         3x           3x 1x 1x           2x 1x 1x                     1x 1x 1x                                                                           3x   3x   3x             2x 1x 1x                       1x             1x 1x 1x                                         1x 1x                       2x   2x 2x                     2x 1x 1x     1x 1x                                     2x   2x 2x                     2x 1x 1x     1x 1x                                 16x      
/**
 * Supabase 添加剂/营养成分服务
 *
 * - 管理 `additives` 和 `ingredients` 表
 * - 支持模糊搜索和精确匹配
 * - 统一错误处理
 */
 
import { supabase } from '../client';
import { convertKeysToCamel, logger, wrapResponse, type SupabaseResponse } from '../helpers';
 
// ==================== 类型定义 ====================
 
/**
 * 添加剂数据库 Schema
 */
export interface AdditiveDB {
  id: number;
  name: string;
  en_name: string | null;
  type: string | null;
  applicable_range: string | null;
  created_at: string;
  updated_at: string;
}
 
/**
 * 添加剂(前端使用)
 */
export interface Additive {
  id: number;
  name: string;
  enName: string | null;
  type: string | null;
  applicableRange: string | null;
  createdAt: string;
  updatedAt: string;
}
 
/**
 * 营养成分/原料数据库 Schema
 */
export interface IngredientDB {
  id: number;
  name: string;
  type: string | null;
  label: string | null;
  desc: string | null;
  created_at: string;
  updated_at: string;
}
 
/**
 * 营养成分/原料(前端使用)
 */
export interface Ingredient {
  id: number;
  name: string;
  type: string | null;
  label: string | null;
  desc: string | null;
  createdAt: string;
  updatedAt: string;
}
 
/**
 * 添加剂搜索响应
 */
export interface AdditiveSearchResponse {
  /** 匹配类型: exact/fuzzy/fuzzy_single/multiple/not_found */
  matchType: 'exact' | 'fuzzy' | 'fuzzy_single' | 'multiple' | 'not_found';
  /** 单个添加剂(exact/fuzzy/fuzzy_single 时返回) */
  additive?: Additive;
  /** 多个添加剂(multiple 时返回) */
  additives?: Additive[];
  /** 查询关键词 */
  query: string;
  /** 是否未找到 */
  notFound: boolean;
}
 
/**
 * 营养成分搜索响应
 */
export interface IngredientSearchResponse {
  ingredient?: Ingredient;
  query: string;
  notFound: boolean;
}
 
/**
 * 添加剂输入参数
 */
export interface AddAdditiveParams {
  name: string;
  enName?: string;
  type?: string;
  applicableRange?: string;
}
 
/**
 * 营养成分输入参数
 */
export interface AddIngredientParams {
  name: string;
  type?: string;
  label?: string;
  desc?: string;
}
 
// ==================== Additive 服务 ====================
 
class SupabaseAdditiveService {
  /**
   * 搜索添加剂
   */
  async searchAdditive(query: string): Promise<SupabaseResponse<AdditiveSearchResponse>> {
    logger.query('additives', 'search', { query });
 
    try {
      // 1. 尝试精确匹配
      const { data: exactMatch, error: exactError } = await supabase
        .from('additives')
        .select('*')
        .ilike('name', query)
        .limit(1)
        .single();
 
      if (!exactError && exactMatch) {
        logger.success('additives', 'search - exact match');
        return {
          data: {
            matchType: 'exact',
            additive: convertKeysToCamel(exactMatch) as Additive,
            query,
            notFound: false,
          },
          error: null,
          success: true,
        };
      }
 
      // 2. 尝试模糊匹配(包含)
      const { data: fuzzyMatches, error: fuzzyError } = await supabase
        .from('additives')
        .select('*')
        .ilike('name', `%${query}%`)
        .limit(10);
 
      if (fuzzyError) {
        logger.error('additives', 'search', fuzzyError);
        return wrapResponse(
          null,
          fuzzyError
        ) as unknown as SupabaseResponse<AdditiveSearchResponse>;
      }
 
      if (!fuzzyMatches || fuzzyMatches.length === 0) {
        logger.success('additives', 'search - not found');
        return {
          data: {
            matchType: 'not_found',
            query,
            notFound: true,
          },
          error: null,
          success: true,
        };
      }
 
      Eif (fuzzyMatches.length === 1) {
        logger.success('additives', 'search - fuzzy single');
        return {
          data: {
            matchType: 'fuzzy_single',
            additive: convertKeysToCamel(fuzzyMatches[0]) as Additive,
            query,
            notFound: false,
          },
          error: null,
          success: true,
        };
      }
 
      // 多个匹配结果
      logger.success('additives', 'search - multiple');
      return {
        data: {
          matchType: 'multiple',
          additives: fuzzyMatches.map((item) => convertKeysToCamel(item) as Additive),
          query,
          notFound: false,
        },
        error: null,
        success: true,
      };
    } catch (err) {
      logger.error('additives', 'search', err);
      return {
        data: null,
        error: { message: String(err), code: 'UNKNOWN', details: '', hint: '' } as any,
        success: false,
      };
    }
  }
 
  /**
   * 搜索营养成分/原料
   */
  async searchIngredient(query: string): Promise<SupabaseResponse<IngredientSearchResponse>> {
    logger.query('ingredients', 'search', { query });
 
    try {
      // 先尝试精确匹配
      const { data: exactMatch, error: exactError } = await supabase
        .from('ingredients')
        .select('*')
        .ilike('name', query)
        .limit(1)
        .single();
 
      if (!exactError && exactMatch) {
        logger.success('ingredients', 'search - exact match');
        return {
          data: {
            ingredient: convertKeysToCamel(exactMatch) as Ingredient,
            query,
            notFound: false,
          },
          error: null,
          success: true,
        };
      }
 
      // 尝试模糊匹配
      const { data: fuzzyMatch, error: fuzzyError } = await supabase
        .from('ingredients')
        .select('*')
        .ilike('name', `%${query}%`)
        .limit(1)
        .single();
 
      Eif (fuzzyError || !fuzzyMatch) {
        logger.success('ingredients', 'search - not found');
        return {
          data: {
            query,
            notFound: true,
          },
          error: null,
          success: true,
        };
      }
 
      logger.success('ingredients', 'search - fuzzy match');
      return {
        data: {
          ingredient: convertKeysToCamel(fuzzyMatch) as Ingredient,
          query,
          notFound: false,
        },
        error: null,
        success: true,
      };
    } catch (err) {
      logger.error('ingredients', 'search', err);
      return {
        data: null,
        error: { message: String(err), code: 'UNKNOWN', details: '', hint: '' } as any,
        success: false,
      };
    }
  }
 
  /**
   * 添加添加剂
   */
  async addAdditive(params: AddAdditiveParams): Promise<SupabaseResponse<Additive>> {
    logger.query('additives', 'add', params);
 
    try {
      const { data, error } = await supabase
        .from('additives')
        .insert({
          name: params.name,
          en_name: params.enName || null,
          type: params.type || null,
          applicable_range: params.applicableRange || null,
        })
        .select()
        .single();
 
      if (error) {
        logger.error('additives', 'add', error);
        return wrapResponse(null, error) as unknown as SupabaseResponse<Additive>;
      }
 
      logger.success('additives', 'add');
      return {
        data: convertKeysToCamel(data) as Additive,
        error: null,
        success: true,
      };
    } catch (err) {
      logger.error('additives', 'add', err);
      return {
        data: null,
        error: { message: String(err), code: 'UNKNOWN', details: '', hint: '' } as any,
        success: false,
      };
    }
  }
 
  /**
   * 添加营养成分/原料
   */
  async addIngredient(params: AddIngredientParams): Promise<SupabaseResponse<Ingredient>> {
    logger.query('ingredients', 'add', params);
 
    try {
      const { data, error } = await supabase
        .from('ingredients')
        .insert({
          name: params.name,
          type: params.type || null,
          label: params.label || null,
          desc: params.desc || null,
        })
        .select()
        .single();
 
      if (error) {
        logger.error('ingredients', 'add', error);
        return wrapResponse(null, error) as unknown as SupabaseResponse<Ingredient>;
      }
 
      logger.success('ingredients', 'add');
      return {
        data: convertKeysToCamel(data) as Ingredient,
        error: null,
        success: true,
      };
    } catch (err) {
      logger.error('ingredients', 'add', err);
      return {
        data: null,
        error: { message: String(err), code: 'UNKNOWN', details: '', hint: '' } as any,
        success: false,
      };
    }
  }
}
 
// 导出单例
export const supabaseAdditiveService = new SupabaseAdditiveService();
 
export default supabaseAdditiveService;