Skip to content

armgit / lyftr

Public Imported from GitHub
0

Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.

21.5 KB
Raw Blame
import { test, expect } from './fixtures'
import { API_BASE as API } from './config'
import { cleanupSeed } from './seedHelpers'

const SEED_PREFIX = 'E2EFood'
// Use local calendar date to match what todayStr() returns in the frontend.
const _now = new Date()
const _pad = (n: number) => String(n).padStart(2, '0')
const today = `${_now.getFullYear()}-${_pad(_now.getMonth() + 1)}-${_pad(_now.getDate())}`
// Local noon → UTC ISO, same anchor as dayToIsoNoon() in the app.
const todayNoon = new Date(_now.getFullYear(), _now.getMonth(), _now.getDate(), 12, 0, 0, 0).toISOString()

// The two fields the cleanup below needs off a food log or saved food. Narrower than
// the real types on purpose: this is a delete-by-name sweep, not a model.
type SeedRow = { id: number; name: string }

let authToken: string
let seedFoodIds: number[] = []
let seedSavedIds: number[] = []

test.describe('Food', () => {
  test.beforeAll(async ({ request, workerAuth }) => {
    authToken = workerAuth.token
    const h = { Authorization: `Bearer ${authToken}` }

    // Idempotent seed: beforeAll runs once per project (chromium + mobile) on the
    // shared workers:1 user, so clear our own seed names first, then create exactly
    // one set. Reset the module-level id arrays (they persist across both runs).
    seedFoodIds = []
    seedSavedIds = []
    const mealNames = [`${SEED_PREFIX}-breakfast`, `${SEED_PREFIX}-lunch`, `${SEED_PREFIX}-snacks`]
    await cleanupSeed(request, authToken, `${API}/food?date=${today}`, `${API}/food`, e => mealNames.includes(e.name))
    await cleanupSeed(request, authToken, `${API}/food/saved`, `${API}/food/saved`, s => s.name === `${SEED_PREFIX}-saved`)

    // Seed one entry per meal so meal sections have data
    for (const [name, meal] of [
      [`${SEED_PREFIX}-breakfast`, 'breakfast'],
      [`${SEED_PREFIX}-lunch`, 'lunch'],
      [`${SEED_PREFIX}-snacks`, 'snacks'],
    ]) {
      const r = await request.post(`${API}/food`, {
        headers: h,
        data: { name, meal, calories: 300, protein: 20, carbs: 40, fat: 10, logged_at: todayNoon },
      })
      const rb = await r.json()
      if (rb.data?.id) seedFoodIds.push(rb.data.id)
    }

    // Seed a saved food
    const sf = await request.post(`${API}/food/saved`, {
      headers: h,
      data: { name: `${SEED_PREFIX}-saved`, calories: 200, protein: 15, carbs: 25, fat: 8, serving_size: '100g' },
    })
    const sfb = await sf.json()
    if (sfb.data?.id) seedSavedIds.push(sfb.data.id)
  })

  test.afterAll(async ({ request }) => {
    const h = { Authorization: `Bearer ${authToken}` }

    for (const id of seedFoodIds) {
      await request.delete(`${API}/food/${id}`, { headers: h })
    }
    for (const id of seedSavedIds) {
      await request.delete(`${API}/food/saved/${id}`, { headers: h })
    }

    // Clean up any UI-created entries
    const list = await request.get(`${API}/food?date=${today}`, { headers: h })
    const lb = await list.json()
    const toDelete = (lb.data ?? []).filter((e: SeedRow) =>
      e.name.startsWith('E2ELog-') || e.name.startsWith('E2ESave-') || e.name.startsWith('E2EEdit-')
    )
    for (const e of toDelete) {
      await request.delete(`${API}/food/${e.id}`, { headers: h })
    }

    // Clean up saved foods created via UI
    const sfList = await request.get(`${API}/food/saved`, { headers: h })
    const sfb = await sfList.json()
    const sfToDelete = (sfb.data ?? []).filter((s: SeedRow) => s.name.startsWith('E2ESave-'))
    for (const s of sfToDelete) {
      await request.delete(`${API}/food/saved/${s.id}`, { headers: h })
    }
  })

  test.beforeEach(async ({ page }) => {
    await page.goto('/food')
  })

  // ─── Food page ────────────────────────────────────────────────────────────

  test('renders Nutrition heading and all four meal sections', async ({ page }) => {
    await expect(page.getByRole('heading', { name: 'Nutrition' })).toBeVisible()
    for (const meal of ['Breakfast', 'Lunch', 'Dinner', 'Snacks']) {
      await expect(page.getByText(meal).first()).toBeVisible()
    }
  })

  test('shows Today label and seeded entries', async ({ page }) => {
    await expect(page.getByText('Today')).toBeVisible()
    await expect(page.getByText(`${SEED_PREFIX}-breakfast`).first()).toBeVisible()
    await expect(page.getByText(`${SEED_PREFIX}-lunch`).first()).toBeVisible()
  })

  test('macro summary card shows calorie and macro labels', async ({ page }) => {
    await expect(page.getByText('Calories')).toBeVisible()
    await expect(page.getByText('Protein').first()).toBeVisible()
    await expect(page.getByText('Carbs').first()).toBeVisible()
    await expect(page.getByText('Fat').first()).toBeVisible()
  })

  test('previous day button shows Yesterday, next returns to Today', async ({ page }) => {
    await expect(page.getByText('Today')).toBeVisible()
    await page.getByRole('button', { name: 'Previous day' }).click()
    await expect(page.getByText('Yesterday')).toBeVisible()
    await page.getByRole('button', { name: 'Next day' }).click()
    await expect(page.getByText('Today')).toBeVisible()
  })

  test('Next day button is disabled on today', async ({ page }) => {
    await expect(page.getByRole('button', { name: 'Next day' })).toBeDisabled()
  })

  test('seeded entries are absent on a previous date', async ({ page }) => {
    // Wait for today's data to fully load before navigating, avoiding a race
    // where the in-flight today-fetch overwrites yesterday's data after the click
    await expect(page.getByText(`${SEED_PREFIX}-breakfast`).first()).toBeVisible({ timeout: 8000 })
    await page.getByRole('button', { name: 'Previous day' }).click()
    await expect(page.getByText('Yesterday')).toBeVisible()
    await expect(page.getByText(`${SEED_PREFIX}-breakfast`).first()).not.toBeVisible()
  })

  test('Macro History section renders with period selector', async ({ page }) => {
    await expect(page.getByText('Macro History')).toBeVisible()
    for (const period of ['7d', '30d', '90d']) {
      const periodBtn = page.getByRole('button', { name: period, exact: true })
      await periodBtn.click()
      // The selected period button takes the active style — a deterministic
      // signal the switch registered, with no fixed sleep or data dependency.
      await expect(periodBtn).toHaveClass(/bg-surface-raised/)
    }
  })

  test('history chart SVG renders with demo seed data', async ({ page }) => {
    // Demo user has 60 days of seed data — chart should render, not the empty state
    await expect(page.locator('.recharts-surface').first()).toBeVisible({ timeout: 10_000 })
    await expect(page.getByText('No data yet')).not.toBeVisible()
  })

  test('Log Food header button navigates to /food/log', async ({ page }) => {
    await page.getByRole('button', { name: /log food/i }).first().click()
    await expect(page).toHaveURL(/\/food\/log/)
  })

  // ─── Log food flow ─────────────────────────────────────────────────────────

  // @mobile: logging food is a core on-phone action — smoke it at phone viewport.
  test('manual entry: log food and verify it appears in meal section', { tag: '@mobile' }, async ({ page }) => {
    const name = `E2ELog-${Date.now()}`

    await page.route('**/api/v1/food/search**', route =>
      route.fulfill({ json: { data: [] } })
    )
    await page.goto(`/food/log?meal=breakfast&date=${today}`)
    await expect(page.locator('input[placeholder="Search food…"]')).toBeVisible()

    // Typing auto-switches to the Search tab
    await page.fill('input[placeholder="Search food…"]', name)
    await expect(page.getByText(`No results for "${name}"`)).toBeVisible({ timeout: 2000 })

    // Click "Enter X manually"
    await page.getByRole('button').filter({ hasText: /manually/ }).click()

    // Detail phase — sticky Log Food button
    await expect(page.getByRole('button', { name: 'Log Food' })).toBeVisible()
    await page.getByRole('button', { name: 'Log Food' }).click()

    await page.waitForURL('/food', { timeout: 5000 })
    await expect(page.getByText(name)).toBeVisible()
  })

  test('quick-add: typing a number shows quick-add shortcut row', async ({ page }) => {
    await page.route('**/api/v1/food/search**', route =>
      route.fulfill({ json: { data: [] } })
    )
    await page.goto('/food/log')
    await page.fill('input[placeholder="Search food…"]', '500')
    await expect(page.getByText('Quick add 500 kcal')).toBeVisible()

    await page.getByText('Quick add 500 kcal').click()
    // Detail phase with 500 kcal
    await expect(page.getByRole('button', { name: 'Log Food' })).toBeVisible()
    await expect(page.getByText('500').first()).toBeVisible()
  })

  // @mobile: touch stepper (+/- taps) — a phone-viewport touch interaction.
  test('servings stepper scales macros in detail phase', { tag: '@mobile' }, async ({ page }) => {
    await page.route('**/api/v1/food/search**', route =>
      route.fulfill({
        json: {
          data: [{ name: 'Test Rice', calories: 200, protein: 4, carbs: 45, fat: 1, fiber: 1, serving_size: '1 cup', source: 'off' }],
        },
      })
    )
    await page.goto('/food/log')
    await page.fill('input[placeholder="Search food…"]', 'rice')
    await page.getByText('Test Rice').click()

    // Default 1 serving = 200 kcal shown
    await expect(page.getByText('200').first()).toBeVisible()

    // Stepper increments by 0.5 — click twice to reach 2 servings → 400 kcal
    await page.getByRole('button', { name: 'Increase servings' }).click()
    await page.getByRole('button', { name: 'Increase servings' }).click()
    await expect(page.getByText('400').first()).toBeVisible()
  })

  // #171: OpenFoodFacts only has per-100ml figures for a lot of oils, and the amount
  // field used to floor at 0.5 — so the least anyone could log was 50 ml. This drives
  // the whole path: a search hit re-read through the product endpoint, then an amount
  // typed in the pack's own unit.
  test('logs a tablespoon of oil, not half of 100 ml', { tag: '@mobile' }, async ({ page }) => {
    const hit = {
      name: 'Olive Oil', brand: 'Thrive Market', calories: 800, protein: 0, carbs: 0,
      fat: 93.3, fiber: 0, serving_size: '100 ml', serving_quantity: 100,
      serving_unit: 'ml', barcode: '0085239033265', source: 'off',
    }
    await page.route('**/api/v1/food/search**', route => route.fulfill({ json: { data: [hit] } }))
    await page.route('**/api/v1/food/barcode/**', route => route.fulfill({
      json: { data: { ...hit, calories: 120, fat: 14, serving_size: '1 Tbsp (15 ml)', serving_quantity: 15 } },
    }))

    await page.goto('/food/log')
    await page.fill('input[placeholder="Search food…"]', 'olive oil')
    // Exact: the empty state that shows while the search is in flight contains the
    // query too, and a substring match resolves to it as well as the row.
    await page.getByText('Olive Oil', { exact: true }).click()

    // The pack's serving, read from the product endpoint — not the index's 100 ml.
    const amount = page.getByLabel('Amount in ml')
    await expect(amount).toHaveValue('15')
    await expect(page.getByText('120').first()).toBeVisible()

    await amount.fill('5')
    await expect(page.getByText('40').first()).toBeVisible()
    await expect(page.getByText(/0\.33 servings/)).toBeVisible()
  })

  // @mobile: touch chip selector that sets the entry's meal.
  test('meal selector in detail phase updates active meal', { tag: '@mobile' }, async ({ page }) => {
    await page.route('**/api/v1/food/search**', route =>
      route.fulfill({ json: { data: [] } })
    )
    await page.goto('/food/log?meal=breakfast')
    await page.fill('input[placeholder="Search food…"]', 'test')
    await page.getByRole('button').filter({ hasText: /manually/ }).click()

    // Should start on breakfast
    const dinnerBtn = page.getByRole('button', { name: 'Dinner' })
    await dinnerBtn.click()
    await expect(dinnerBtn).toHaveClass(/bg-brand/)
  })

  // ─── Search ───────────────────────────────────────────────────────────────

  test('search results display from mocked API', async ({ page }) => {
    await page.route('**/api/v1/food/search**', route =>
      route.fulfill({
        json: {
          data: [{ name: 'Mocked Banana', calories: 89, protein: 1, carbs: 23, fat: 0, fiber: 3, serving_size: '1 medium', source: 'off' }],
        },
      })
    )
    await page.goto('/food/log')
    await page.fill('input[placeholder="Search food…"]', 'banana')
    await expect(page.getByText('Mocked Banana')).toBeVisible({ timeout: 2000 })
  })

  test('selecting a search result goes to detail phase', async ({ page }) => {
    await page.route('**/api/v1/food/search**', route =>
      route.fulfill({
        json: {
          data: [{ name: 'Test Apple', calories: 95, protein: 0, carbs: 25, fat: 0, fiber: 4, serving_size: '1 medium', source: 'off' }],
        },
      })
    )
    await page.goto('/food/log')
    await page.fill('input[placeholder="Search food…"]', 'apple')
    await page.getByText('Test Apple').click()

    await expect(page.getByRole('button', { name: 'Log Food' })).toBeVisible()
    await expect(page.getByText('95').first()).toBeVisible()
  })

  test('429 rate limit response shows amber warning banner', async ({ page }) => {
    await page.route('**/api/v1/food/search**', route =>
      route.fulfill({ status: 429, body: 'Too Many Requests' })
    )
    await page.goto('/food/log')
    await page.fill('input[placeholder="Search food…"]', 'pizza')
    await expect(page.getByText(/too many requests/i)).toBeVisible({ timeout: 2000 })
  })

  // ─── Edit food log ─────────────────────────────────────────────────────────

  test('edit mode: URL with edit= pre-fills food name and shows Save Changes', async ({ page }) => {
    const [firstId] = seedFoodIds
    await page.goto(`/food/log?edit=${firstId}`)

    await expect(page.getByRole('button', { name: 'Save Changes' })).toBeVisible({ timeout: 5000 })
    await expect(page.getByText(`${SEED_PREFIX}-breakfast`)).toBeVisible()
  })

  test('edit mode: saving returns to food page', async ({ page }) => {
    const h = { Authorization: `Bearer ${authToken}` }
    const r = await page.request.post(`${API}/food`, {
      headers: h,
      data: { name: `E2EEdit-${Date.now()}`, meal: 'dinner', calories: 200, protein: 10, carbs: 30, fat: 5, logged_at: todayNoon },
    })
    const { data } = await r.json()
    seedFoodIds.push(data.id)

    await page.goto(`/food/log?edit=${data.id}`)
    await expect(page.getByRole('button', { name: 'Save Changes' })).toBeVisible({ timeout: 5000 })
    await page.getByRole('button', { name: 'Save Changes' }).click()
    await page.waitForURL('/food', { timeout: 5000 })
    await expect(page.getByRole('heading', { name: 'Nutrition' })).toBeVisible()
  })

  // ─── Delete food log ───────────────────────────────────────────────────────

  test('delete: trash shows confirm dialog, cancel keeps entry', async ({ page }) => {
    await expect(page.getByText(`${SEED_PREFIX}-snacks`).first()).toBeVisible()

    // Scope to the per-entry wrapper div (.divide-y > div) that contains this name
    const entryRow = page.locator('.divide-y > div').filter({
      has: page.getByText(`${SEED_PREFIX}-snacks`, { exact: true }),
    }).last()
    await entryRow.getByRole('button', { name: 'Delete' }).click()

    await expect(page.locator('button.btn-danger-solid')).toBeVisible()
    await expect(page.getByRole('button', { name: 'Cancel' })).toBeVisible()

    await page.getByRole('button', { name: 'Cancel' }).click()
    await expect(page.getByText(`${SEED_PREFIX}-snacks`).first()).toBeVisible()
  })

  test('delete: confirm removes entry from list', async ({ page }) => {
    const h = { Authorization: `Bearer ${authToken}` }
    const r = await page.request.post(`${API}/food`, {
      headers: h,
      data: { name: `E2ELog-del-${Date.now()}`, meal: 'snacks', calories: 100, protein: 5, carbs: 15, fat: 3, logged_at: todayNoon },
    })
    const { data } = await r.json()
    const deleteName = data.name
    // Don't push to seedFoodIds — UI deletion is the test

    await page.reload()
    await expect(page.getByText(deleteName)).toBeVisible({ timeout: 5000 })

    const entryRow = page.locator('.divide-y > div').filter({
      has: page.getByText(deleteName, { exact: true }),
    }).first()
    await entryRow.getByRole('button', { name: 'Delete' }).click()
    await page.locator('button.btn-danger-solid').click()

    await expect(page.getByText(deleteName)).not.toBeVisible({ timeout: 3000 })
  })

  // ─── Favorites ────────────────────────────────────────────────────────────

  test('Favorites tab shows seeded saved food', async ({ page }) => {
    await page.goto('/food/log')
    await page.getByRole('button', { name: 'Favorites', exact: true }).click()
    await expect(page.getByText(`${SEED_PREFIX}-saved`).first()).toBeVisible({ timeout: 3000 })
  })

  // Favouriting is no longer a side effect of logging: the star acts on its own, from
  // the detail view, without the food ever being logged.
  test('starring from the detail view favourites without logging', async ({ page }) => {
    const savedName = `E2ESave-${Date.now()}`

    await page.route('**/api/v1/food/search**', route =>
      route.fulfill({ json: { data: [] } })
    )
    await page.goto('/food/log')
    await page.fill('input[placeholder="Search food…"]', savedName)
    await expect(page.getByText(`No results for "${savedName}"`)).toBeVisible({ timeout: 2000 })
    await page.getByRole('button').filter({ hasText: /manually/ }).click()

    // Star it, then leave without logging.
    await page.getByRole('button', { name: `Add ${savedName} to Favorites` }).click()
    await expect(page.getByRole('button', { name: `Remove ${savedName} from Favorites` })).toBeVisible({ timeout: 5000 })

    await page.goto('/food/log')
    await page.getByRole('button', { name: 'Favorites', exact: true }).click()
    await expect(page.getByText(savedName)).toBeVisible({ timeout: 8000 })

    // And it was never logged — the diary has no entry for it.
    await page.goto('/food')
    await expect(page.getByText(savedName)).not.toBeVisible({ timeout: 3000 })
  })

  // #115: the delete endpoint and the client method both existed, but nothing called
  // them — a saved food could not be removed from either app. Creates its own row rather
  // than using the shared seed so the other Favorites tests keep theirs.
  test('unstarring removes it from Favorites', async ({ page, request }) => {
    const name = `E2EDelete-${Date.now()}`
    const created = await request.post(`${API}/food/saved`, {
      headers: { Authorization: `Bearer ${authToken}` },
      data: { name, calories: 120, protein: 10, carbs: 12, fat: 4, serving_size: '1 cup' },
    })
    expect(created.ok()).toBeTruthy()

    await page.goto('/food/log')
    await page.getByRole('button', { name: 'Favorites', exact: true }).click()
    await expect(page.getByText(name)).toBeVisible({ timeout: 5000 })

    // One click, no confirmation sheet in between.
    await page.getByRole('button', { name: `Remove ${name} from Favorites` }).click()

    await expect(page.getByText(name)).not.toBeVisible({ timeout: 5000 })

    // The row vanishing only proves local state was filtered. Reload to prove the
    // DELETE actually reached the server.
    await page.reload()
    await page.getByRole('button', { name: 'Favorites', exact: true }).click()
    await expect(page.getByText(name)).not.toBeVisible({ timeout: 5000 })
  })

  test('selecting from Favorites goes to detail phase', async ({ page }) => {
    await page.goto('/food/log')
    await page.getByRole('button', { name: 'Favorites', exact: true }).click()
    await expect(page.getByText(`${SEED_PREFIX}-saved`).first()).toBeVisible({ timeout: 3000 })
    await page.getByText(`${SEED_PREFIX}-saved`).first().click()

    await expect(page.getByRole('button', { name: 'Log Food' })).toBeVisible()
  })

  // ─── Barcode scanner ──────────────────────────────────────────────────────

  test('Scan button renders scan phase overlay with close button', { tag: '@mobile' }, async ({ page }) => {
    test.slow()
    await page.goto('/food/log')
    await page.getByRole('button', { name: /scan/i }).click()
    await expect(page.getByRole('button', { name: 'Close scanner' })).toBeVisible({ timeout: 3000 })
  })

  test('Close scanner button returns to search phase', { tag: '@mobile' }, async ({ page }) => {
    await page.goto('/food/log')
    await page.getByRole('button', { name: /scan/i }).click()
    await page.getByRole('button', { name: 'Close scanner' }).click()
    await expect(page.locator('input[placeholder="Search food…"]')).toBeVisible()
  })

  // NOTE: the food API-contract tests (GET/PATCH /food, /food/search, /food/history,
  // /food/saved, /food/stats, /food/barcode) were moved to Go integration tests
  // (controllers/food_test.go), which mock OpenFoodFacts and assert exact values
  // deterministically — no real-network flakiness. The beforeAll seeding stays for
  // the UI tests above.
})