# MeshiTrack — Large-Scale Project Plan

> **Nutrition, Medicine & Pantry Management Platform**
> A self-hosted, multi-user app for medicine tracking, nutrition tracking, pantry/fridge management, recipe management, meal planning, and price surveillance across stores.

## Project Summary

MeshiTrack helps households manage medicines and food. Medicine tracking comes first as the simpler domain: catalog medicines, track inventory in a medicine cabinet, define daily regimens, batch-dispense via a pill organizer, compare pharmacy prices, and get automatic refill alerts. Food tracking follows the same architectural patterns: product catalog, recipes, pantry tracking, meal planning, grocery lists, and price comparison. Both domains share infrastructure (auth, households, stores).

## Tech Stack

| Layer               | Technology                              |
| ------------------- | --------------------------------------- |
| **Backend**         | Fastify 5 (TypeScript, ESM)             |
| **DI Container**    | Awilix 13 + @fastify/awilix             |
| **Frontend**        | Next.js 16 (React 19, TypeScript)       |
| **Styling**         | Tailwind CSS 4 (CSS-first config)       |
| **Database**        | MongoDB (Mongoose 9)                    |
| **Auth**            | Keycloak (OIDC), jose 6 (JWT)           |
| **Validation**      | Zod 4 (shared schemas)                  |
| **Shared Code**     | TypeScript package (types, Zod schemas) |
| **Testing**         | Vitest 4 (unit + integration)           |
| **Mobile (future)** | React Native                            |
| **LLM**            | Abstracted interface (provider TBD)     |
| **Deployment**      | Docker Compose (self-hosted)            |
| **Monorepo**        | Turborepo 2                             |
| **Runtime**         | Node.js 22+ (ESM-only)                  |

## Phase Completion Criteria (Mandatory)

Every phase MUST deliver ALL of the following before being considered complete. No phase may be marked done if any layer is missing.

### 1. Shared Package (`packages/shared`)

- [ ] Types defined in `src/types/`
- [ ] Enums defined in `src/enums/` with unit tests
- [ ] Zod validation schemas in `src/validation/` with unit tests
- [ ] Barrel exports updated in `index.ts`
- [ ] 100% line/function/statement coverage, 90% branch coverage

### 2. API Package (`packages/api`)

- [ ] Mongoose schema in `src/schemas/`
- [ ] Repository with `.lean().exec()` on all reads
- [ ] Service with business logic
- [ ] Route plugin registered in `main.ts`
- [ ] Unit tests for repository, service, and routes (100% coverage)
- [ ] All queries scoped to `householdId`

### 3. Web Package (`packages/web`)

- [ ] API client service in `src/services/` with unit tests
- [ ] Page(s) in `src/app/(dashboard)/` implementing the UI spec
- [ ] Component tests (React Testing Library) for every page and interactive component
- [ ] Server Components by default; `'use client'` only where interactivity is needed

### 4. CI Gate (must pass before phase sign-off)

```bash
npm run build       # All packages compile
npm run test:cov    # Coverage thresholds enforced (100/100/100/90)
npm run lint        # Zero lint errors
```

### 5. Documentation

- [ ] Phase spec updated with `[x]` on completed tasks
- [ ] Acceptance criteria verified

---

## Phase Overview

### Medicine Tracking (Phases 1-4)

| Phase | Name                           | Description                                                      | Status | Doc                                                                                       |
| ----- | ------------------------------ | ---------------------------------------------------------------- | ------ | ----------------------------------------------------------------------------------------- |
| 0     | Foundation & Infrastructure    | Repo scaffolding, Docker, auth                                   | DONE   | [phase-0-foundation.md](phases/phase-0-foundation.md)                                     |
| 1     | Medicine Library               | Searchable medicine catalog with dosage/form info                | DONE   | [phase-1-medicine-library.md](phases/phase-1-medicine-library.md)                         |
| 2     | Medicine Cabinet               | Inventory tracking with quantity, expiry, low-stock alerts       | DONE   | [phase-2-medicine-cabinet.md](phases/phase-2-medicine-cabinet.md)                         |
| 3     | Regimens & Pill Organizer      | Daily medication schedules, batch-dispense, burn rate            | DONE   | [phase-3-regimens-pill-organizer.md](phases/phase-3-regimens-pill-organizer.md)           |
| 4     | Pharmacies, Prices & Refills   | Shared store infrastructure, price tracking, refill alerts       | DONE   | [phase-4-pharmacies-prices-refills.md](phases/phase-4-pharmacies-prices-refills.md)       |

### Food Tracking (Phases 5-9)

| Phase | Name                           | Description                                                      | Status | Doc                                                                                       |
| ----- | ------------------------------ | ---------------------------------------------------------------- | ------ | ----------------------------------------------------------------------------------------- |
| 5     | Product Library                | Searchable food product catalog with nutrition data              | DONE   | [phase-5-product-library.md](phases/phase-5-product-library.md)                           |
| 6     | Recipe Management              | Recipe CRUD, nutrition auto-calculation, import                  | DONE   | [phase-6-recipes.md](phases/phase-6-recipes.md)                                           |
| 7     | Pantry & Fridge Tracking       | Track item lifecycle, freshness, spoilage estimation             | DONE   | [phase-7-pantry.md](phases/phase-7-pantry.md)                                             |
| 8     | Meal Planning & Waste Reduction| Suggest meals from pantry, nutrition targets, weekly planning    | NOT STARTED | [phase-8-meal-planning.md](phases/phase-8-meal-planning.md)                               |
| 9     | Grocery & Price Tracking       | Shopping lists, price analytics, store comparison (reuses Phase 4 stores) | NOT STARTED | [phase-9-grocery.md](phases/phase-9-grocery.md)                               |

### Shared (Phase 10)

| Phase | Name                           | Description                                                      | Status | Doc                                                                                       |
| ----- | ------------------------------ | ---------------------------------------------------------------- | ------ | ----------------------------------------------------------------------------------------- |
| 10    | LLM Integration & Smart Features | Wire up LLM providers, enable smart features across both domains | PARTIAL | [phase-10-llm.md](phases/phase-10-llm.md)                                               |

---

## Current Status & Gaps

### Phase 8 — Meal Planning (Next Priority)

The foundation for food tracking (Phases 5-7) is fully implemented and integrated. The next major milestone is Phase 8, which introduces the meal planning calendar and the algorithmic suggestion engine.

**Immediate Goals:**
- Implement `MealPlan` and `NutritionTarget` schemas.
- Build the `SuggestionEngineService` for pantry-based recipe ranking.
- Create the weekly calendar UI with drag-and-drop support.

### Phase 10 — LLM (PARTIAL)

The `ILlmProvider` interface and `NoOpLlmProvider` are implemented. Actual provider implementations and smart features are deferred.

### Lessons Learned

Previous phases (6 & 7) were completed without finishing Phase 5's full stack (API routes + web UI). This created a gap where the Product Library has no user-facing interface despite being consumed internally. **Going forward, every phase must deliver its complete vertical slice (shared -> API -> web -> tests) before the next phase starts.**

## Cross-Cutting Concerns

See [cross-cutting.md](cross-cutting.md) for API versioning, pagination, audit trails, real-time events, testing strategy, and mobile readiness.

## Architecture Decisions

See [architecture.md](architecture.md) for key decisions and rationale.

## Monorepo Structure (Target)

```
MeshiTrack/
├── docs/                        # This documentation
├── packages/
│   ├── api/                     # Fastify backend
│   │   ├── src/
│   │   │   ├── modules/
│   │   │   │   ├── health/
│   │   │   │   ├── users/
│   │   │   │   ├── households/
│   │   │   │   ├── medicines/       # Phase 1: Medicine catalog (generic level)
│   │   │   │   ├── medicine-products/ # Phase 1: Purchasable brands/packages
│   │   │   │   ├── cabinet/         # Phase 2: Medicine inventory
│   │   │   │   ├── regimens/        # Phase 3: Medication schedules
│   │   │   │   ├── organizer/       # Phase 3: Pill organizer fills
│   │   │   │   ├── stores/          # Phase 4: Shared store infrastructure
│   │   │   │   ├── medicine-prices/ # Phase 4: Medicine price tracking
│   │   │   │   ├── refills/         # Phase 4: Refill alerts & lists
│   │   │   │   ├── products/        # Phase 5: Food product catalog
│   │   │   │   ├── recipes/         # Phase 6: Recipe management
│   │   │   │   ├── pantry/          # Phase 7: Food inventory
│   │   │   │   ├── meal-plans/      # Phase 8: Meal planning
│   │   │   │   ├── grocery/         # Phase 9: Grocery shopping
│   │   │   │   └── llm/            # Phase 10: LLM integration
│   │   │   ├── plugins/         # Fastify plugins (auth, mongoose, etc.)
│   │   │   ├── schemas/         # Mongoose schemas
│   │   │   ├── common/          # Error classes, shared types
│   │   │   └── config/
│   │   ├── vitest.config.ts
│   │   └── package.json
│   ├── web/                     # Next.js frontend
│   │   ├── src/
│   │   │   ├── app/             # App Router pages
│   │   │   ├── components/
│   │   │   ├── hooks/
│   │   │   ├── services/        # API client layer
│   │   │   └── styles/
│   │   └── package.json
│   └── shared/                  # Shared TypeScript types & validation
│       ├── src/
│       │   ├── types/
│       │   ├── enums/
│       │   └── validation/      # Zod 4 schemas
│       └── package.json
├── docker/
│   ├── docker-compose.yml
│   ├── keycloak/                # Realm export, themes
│   └── mongo/                   # Init scripts
├── .github/
│   └── workflows/
├── turbo.json                   # Turborepo config
├── package.json                 # Root workspace config
└── tsconfig.base.json
```

## Verification Strategy

### Per-Phase Gate (Blocking)

Every phase must pass these checks before sign-off:

1. **Build**: `npm run build` succeeds (all packages compile)
2. **Coverage**: `npm run test:cov` passes with thresholds:
   - `packages/api`: 100% lines/functions/statements, 90% branches
   - `packages/shared`: 100% lines/functions/statements, 90% branches
   - `packages/web`: all component tests pass
3. **Lint**: `npm run lint` reports zero errors
4. **Web UI Exists**: every phase that adds API endpoints also adds corresponding web pages with component tests
5. **Services Tested**: every `*.service.ts` in web has a corresponding `*.test.ts`

### Per-Phase Deliverable Checklist

For each phase, the task breakdown must follow this template order:

```
X.1 — Shared Types & Validation (+ tests)
X.2 — Mongoose Schema & Repository (+ tests)
X.3 — Service (+ tests)
X.4 — Routes (+ tests)
X.5 — Web: API Client Service (+ tests)
X.6 — Web: Pages & Components (+ component tests)
X.7 — CI Verification (build + test:cov + lint)
```

### Integration Testing

- Postman/Bruno collection maintained alongside API development
- E2E smoke test (medicine): creates user, adds medicines, stocks cabinet, creates regimen, fills organizer, checks refill alerts
- E2E smoke test (food): adds products, creates recipe, stocks pantry, generates meal plan, creates shopping list

### Performance

- MongoDB indexes reviewed per phase; query profiling before phase sign-off
