All files / munch-ease-frontend/src/api sdk.ts

81.71% Statements 277/339
59.52% Branches 50/84
73.07% Functions 19/26
81.71% Lines 277/339

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 3401x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 9x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 2x 2x 2x 2x 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 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x                         1x 2x 2x 2x 1x 1x 1x           1x         1x 2x 2x 2x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 1x 1x 1x 1x 3x 3x 3x 3x 3x 1x 2x 2x 2x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 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 2x 2x 2x 2x 2x 2x 2x 2x               2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
import { api } from '@/api/client'
import type { components } from '@/api/types'
import { toDate, decodeMeal, decodeRecipe, decodeIngredients, decodeShoppingList, decodeShoppingListItems, decodeIngredient, decodeLookup } from '@/domain/decoders'
import type {
  Recipe,
  Meal,
  Ingredient,
  ShoppingList,
  ShoppingListItemWithRefs,
  CurrentShoppingListDTO,
  PurchasedShoppingListDTO,
  ShoppingLookups,
} from '@/domain/types'
import { fromOpenApiPage, type Page } from '@/domain/pagination'
 
function httpError(response: Response, error: unknown): Error {
  if (error instanceof Error) return error
  if (typeof error === 'string') return new Error(error)
  return new Error(`${response.status} ${response.statusText || 'HTTP error'}`)
}
 
// decodeLookup moved to domain/decoders to be reused across SDK and other modules
 
// Shopping list mapped view types now come from domain/types
 
function attachItemRefs(
  items: Array<ShoppingListItemWithRefs> | null | undefined,
  lookups: ShoppingLookups
): void {
  if (!Array.isArray(items)) return
  for (const item of items) {
    const ingredientId = item.ingredientId ?? undefined
    const mealId = item.mealId ?? undefined
    const recipeId = item.recipeId ?? undefined
    const listId = item.listId ?? undefined
    const created = item.createdDate
 
    if (ingredientId !== undefined && lookups.ingredientsLookup && lookups.ingredientsLookup[String(ingredientId)] !== undefined) {
      item.ingredient = lookups.ingredientsLookup[String(ingredientId)]
    }
    if (mealId !== undefined && lookups.mealsLookup && lookups.mealsLookup[String(mealId)] !== undefined) {
      item.meal = lookups.mealsLookup[String(mealId)]
    }
    if (recipeId !== undefined && lookups.recipesLookup && lookups.recipesLookup[String(recipeId)] !== undefined) {
      item.recipe = lookups.recipesLookup[String(recipeId)]
    }
    if (listId !== undefined && lookups.shoppingListLookup && lookups.shoppingListLookup[String(listId)] !== undefined) {
      item.list = lookups.shoppingListLookup[String(listId)]
    }
    if (created !== undefined) item.createdDate = toDate(created)
  }
}
 
export function mapPurchasedShoppingList(dto: components['schemas']['PurchasedShoppingList'] | null | undefined): PurchasedShoppingListDTO | null {
  if (!dto) return null
 
  const mealsLookupRaw = dto.mealsLookup
  const recipesLookupRaw = dto.recipesLookup
  const ingredientsLookupRaw = dto.ingredientsLookup
  const listRaw = dto.list
 
  const mealsLookup = decodeLookup(mealsLookupRaw, decodeMeal)
  const recipesLookup = decodeLookup(recipesLookupRaw, decodeRecipe)
  const ingredientsLookup = decodeLookup(ingredientsLookupRaw, decodeIngredient)
 
  let list: import('@/domain/types').ShoppingListWithRefs | undefined
  if (listRaw) {
    const base = decodeShoppingList(listRaw)
    if (base) {
      const items = Array.isArray(listRaw.items) ? decodeShoppingListItems(listRaw.items) : []
      list = { ...base, items }
      const lookups: ShoppingLookups = {
        ...(ingredientsLookup && { ingredientsLookup }),
        ...(mealsLookup && { mealsLookup }),
        ...(recipesLookup && { recipesLookup }),
        shoppingListLookup: { [String(list.id)]: list },
      }
      attachItemRefs(list.items, lookups)
    }
  }
 
  return {
    ...(ingredientsLookup && { ingredientsLookup }),
    ...(mealsLookup && { mealsLookup }),
    ...(recipesLookup && { recipesLookup }),
    ...(list && { list }),
  }
}
 
export function mapCurrentShoppingList(dto: components['schemas']['CurrentShoppingList'] | null | undefined): CurrentShoppingListDTO | null {
  if (!dto) return null
 
  const outstandingRaw = dto.outstandingItems
  const requestedRaw = dto.requestedMeals
  const purchasedRaw = dto.purchasedItems
 
  const ingredientsLookupRaw = dto.ingredientsLookup
  const mealsLookupRaw = dto.mealsLookup
  const recipesLookupRaw = dto.recipesLookup
  const shoppingListLookupRaw = dto.shoppingListLookup
 
  const ingredientsLookup = decodeLookup(ingredientsLookupRaw, decodeIngredient)
  const mealsLookup = decodeLookup(mealsLookupRaw, decodeMeal)
  const recipesLookup = decodeLookup(recipesLookupRaw, decodeRecipe)
 
  let shoppingListLookup: Record<string, ShoppingList> | undefined
  if (shoppingListLookupRaw) {
    shoppingListLookup = decodeLookup(shoppingListLookupRaw, decodeShoppingList)
  }
 
  const dtoOut: CurrentShoppingListDTO = {
    outstandingItems: decodeShoppingListItems(outstandingRaw ?? []),
    requestedMeals: decodeShoppingListItems(requestedRaw ?? []),
    purchasedItems: decodeShoppingListItems(purchasedRaw ?? []),
    ...(ingredientsLookup && { ingredientsLookup }),
    ...(mealsLookup && { mealsLookup }),
    ...(recipesLookup && { recipesLookup }),
    ...(shoppingListLookup && { shoppingListLookup }),
  }
 
  const lookups: ShoppingLookups = {
    ...(ingredientsLookup && { ingredientsLookup }),
    ...(mealsLookup && { mealsLookup }),
    ...(recipesLookup && { recipesLookup }),
    ...(shoppingListLookup && { shoppingListLookup }),
  }
  attachItemRefs(dtoOut.outstandingItems ?? null, lookups)
  attachItemRefs(dtoOut.requestedMeals ?? null, lookups)
  attachItemRefs(dtoOut.purchasedItems ?? null, lookups)
 
  return dtoOut
}
 
export async function listRecipes(params?: { q?: string | null; cursor?: string | null; limit?: number }): Promise<Page<Recipe>> {
  const query: Record<string, unknown> = {}
  if (params) {
    if (params.q !== undefined) query.q = params.q
    if (params.cursor !== undefined) query.cursor = params.cursor
    if (typeof params.limit === 'number') query.limit = params.limit
  }
  const { data, error, response } = await api.GET('/api/v1/recipes', { params: { query } })
  if (!response.ok) throw httpError(response, error)
  const mapped = fromOpenApiPage(data ?? null, (r) => decodeRecipe(r))
  return { ...mapped, items: mapped.items.filter((r): r is Recipe => !!r) }
}
 
export async function getRecipe(id: number | string): Promise<Recipe | null> {
  const { data, error, response } = await api.GET('/api/v1/recipes/{recipe_id}', { params: { path: { recipe_id: Number(id) } } })
  if (!response.ok) throw httpError(response, error)
  return decodeRecipe(data)
}
 
export async function saveRecipe(recipe: components['schemas']['Recipe-Input']): Promise<Recipe | null> {
  const { data, error, response } = await api.POST('/api/v1/recipes', { body: recipe, params: { cookie: { user_id: 0 } } })
  if (!response.ok) throw httpError(response, error)
  return decodeRecipe(data)
}
 
export async function deleteRecipe(id: number | string): Promise<void> {
  const { error, response } = await api.DELETE('/api/v1/recipes/{recipe_id}', { params: { path: { recipe_id: Number(id) }, cookie: { user_id: 0 } } })
  if (!response.ok) throw httpError(response, error)
}
 
export async function parseRecipe(url: string): Promise<Recipe | null> {
  const { data, error, response } = await api.GET('/api/v1/recipes/parse', { params: { query: { url }, cookie: { user_id: 0 } } })
  if (!response.ok) throw httpError(response, error)
  return decodeRecipe(data)
}
 
export async function parseIngredients(lines: string[]): Promise<Ingredient[]> {
  const { data, error, response } = await api.GET('/api/v1/recipes/ingredients/parse', {
    params: { query: { ingredients: lines } },
  })
  if (!response.ok) throw httpError(response, error)
  return decodeIngredients(data ?? [])
}
 
export async function parseProduct(
  ingredient: Pick<components['schemas']['Ingredient'], 'name' | 'line'>,
  url: string
): Promise<components['schemas']['Product'] | null> {
  const body: components['schemas']['ProductUrl'] = { url, tags: [ingredient.name, ingredient.line] }
  const res = await api.POST('/api/v1/products', { body })
  if (!res.response.ok) throw httpError(res.response, res.error)
  return res.data ?? null
}
 
// Persons
export async function listPersons(params?: { q?: string | null; cursor?: string | null; limit?: number }): Promise<Page<components['schemas']['Person']>> {
  const query: Record<string, unknown> = {}
  if (params) {
    if (params.q !== undefined) query.q = params.q
    if (params.cursor !== undefined) query.cursor = params.cursor
    if (typeof params.limit === 'number') query.limit = params.limit
  }
  const { data, error, response } = await api.GET('/api/v1/persons', { params: { query } })
  if (!response.ok) throw httpError(response, error)
  const normalized = Array.isArray(data) ? { items: data } : (data ?? null)
  return fromOpenApiPage<components['schemas']['Person'], components['schemas']['Person']>(normalized, (p) => p)
}
 
export async function getPersonsInHome(): Promise<Page<components['schemas']['Person']>> {
  return listPersons()
}
 
export async function searchPersons(name: string): Promise<Page<components['schemas']['Person']>> {
  return listPersons({ q: name })
}
 
// Meals
export async function getUpcomingMeals(from: Date, to: Date): Promise<Meal[]> {
  const { data, error, response } = await api.GET('/api/v1/meals/upcoming', {
    params: { query: { from: from.toISOString(), to: to.toISOString() } },
  })
  if (!response.ok) throw httpError(response, error)
  const list = Array.isArray(data) ? data : []
  return list
    .map((m) => decodeMeal(m))
    .filter((m): m is Meal => !!m)
    .sort((a, b) => ((a.suggestedDate?.getTime() ?? 0) - (b.suggestedDate?.getTime() ?? 0)))
}
 
export async function getMeal(id: number | string): Promise<Meal | null> {
  const { data, error, response } = await api.GET('/api/v1/meals/{meal_id}', { params: { path: { meal_id: Number(id) } } })
  if (!response.ok) throw httpError(response, error)
  return decodeMeal(data)
}
 
export async function saveMeal(meal: components['schemas']['Meal-Input']): Promise<Meal | null> {
  const hasId = typeof meal.id === 'number' && meal.id >= 0
  if (hasId) {
    const { data, error, response } = await api.PUT('/api/v1/meals/{meal_id}', {
      params: { path: { meal_id: Number(meal.id) } },
      body: meal,
    })
    if (!response.ok) throw httpError(response, error)
    return decodeMeal(data)
  } else {
    const { data, error, response } = await api.POST('/api/v1/meals', { body: meal })
    if (!response.ok) throw httpError(response, error)
    return decodeMeal(data)
  }
}
 
export async function markMealConsumed(mealId: number | string): Promise<Meal | null> {
  const { data, error, response } = await api.POST('/api/v1/meals/{meal_id}/consumed', {
    params: { path: { meal_id: Number(mealId) }, cookie: { user_id: 0 } },
  })
  if (!response.ok) throw httpError(response, error)
  return decodeMeal(data)
}
 
export async function deleteMeal(mealId: number | string): Promise<void> {
  const { error, response } = await api.DELETE('/api/v1/meals/{meal_id}', {
    params: { path: { meal_id: Number(mealId) }, cookie: { user_id: 0 } },
  })
  if (!response.ok) throw httpError(response, error)
}
 
// Shopping
export async function getMyShoppingList(): Promise<Ingredient[]> {
  const { data, error, response } = await api.GET('/api/v1/shopping/current/me/ingredients', { params: { cookie: { user_id: 0 } } })
  if (!response.ok) throw httpError(response, error)
  return decodeIngredients(data ?? [])
}
 
export async function saveMyShoppingList(items: components['schemas']['Ingredient'][]): Promise<Ingredient[]> {
  const { data, error, response } = await api.POST('/api/v1/shopping/current/me/ingredients', {
    body: items,
    params: { cookie: { user_id: 0 } },
  })
  if (!response.ok) throw httpError(response, error)
  return decodeIngredients(data ?? [])
}
 
export async function getShoppingList(id: number | string) {
  const { data, error, response } = await api.GET('/api/v1/shopping/{list_id}', { params: { path: { list_id: Number(id) } } })
  if (!response.ok) throw httpError(response, error)
  const mapped = mapPurchasedShoppingList(data)
  return mapped?.list ?? null
}
 
export async function getCurrentShoppingList() {
  const { data, error, response } = await api.GET('/api/v1/shopping/current')
  if (!response.ok) throw httpError(response, error)
  return mapCurrentShoppingList(data)
}
 
export type PurchaseExisting = { type: 'existing'; id: number; personId: number; ingredientId?: number | null }
export type PurchaseRefs = { type: 'refs'; personId: number; ingredientId?: number | null; recipeId?: number | null; mealId?: number | null }
 
export async function purchaseShoppingList(
  completedRequests: Array<PurchaseExisting | PurchaseRefs>
): Promise<import('@/domain/types').ShoppingListWithRefs | null> {
  if (!Array.isArray(completedRequests) || completedRequests.length === 0) return null
  // Map incoming requests: if id provided and >= 0, use it; otherwise send identifiers for ingredient/recipe/meal
  const items: components['schemas']['ShoppingListItem'][] = completedRequests.map((i) =>
    i.type === 'existing'
      ? { id: i.id, personId: i.personId, ingredientId: i.ingredientId ?? null }
      : {
          id: -1,
          personId: i.personId,
          ingredientId: i.ingredientId ?? null,
          recipeId: i.recipeId ?? null,
          mealId: i.mealId ?? null,
        }
  )
 
  if (items.length === 0) return null
 
  const body: components['schemas']['ShoppingList'] = {
    id: -1,
    storeName: '',
    purchasedById: -1,
    items,
  }
  const { data, error, response } = await api.POST('/api/v1/shopping', {
    body,
    params: { cookie: { user_id: 0 } },
  })
  if (!response.ok) throw httpError(response, error)
  const mapped = mapPurchasedShoppingList(data)
  return mapped?.list ?? null
}
 
export async function requestMeal(mealId: number | string): Promise<void> {
  const { error, response } = await api.POST('/api/v1/shopping/current/meals/me', {
    body: { mealId: Number(mealId) },
    params: { cookie: { user_id: 0 } },
  })
  if (!response.ok) throw httpError(response, error)
}
 
export async function unrequestMeal(mealId: number | string): Promise<void> {
  const { error, response } = await api.DELETE('/api/v1/shopping/current/meals/{meal_id}', {
    params: { path: { meal_id: Number(mealId) }, cookie: { user_id: 0 } },
  })
  if (!response.ok) throw httpError(response, error)
}