Compare commits
No commits in common. "fd35640fd84749338a94652133f91a11a71d1386" and "bd99d90c0973e90066ddf45b286f6cae3e13ef81" have entirely different histories.
fd35640fd8
...
bd99d90c09
78 changed files with 1783 additions and 6951 deletions
45
.github/workflows/ci.yml
vendored
45
.github/workflows/ci.yml
vendored
|
|
@ -1,45 +0,0 @@
|
||||||
name: CI
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: [ main, master ]
|
|
||||||
pull_request:
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
build-test:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Setup Node.js
|
|
||||||
uses: actions/setup-node@v4
|
|
||||||
with:
|
|
||||||
node-version: '20'
|
|
||||||
cache: 'npm'
|
|
||||||
|
|
||||||
- name: Install dependencies
|
|
||||||
run: npm ci
|
|
||||||
|
|
||||||
- name: Codegen check
|
|
||||||
run: npm run codegen:check || true
|
|
||||||
|
|
||||||
- name: Generate OpenAPI types
|
|
||||||
run: |
|
|
||||||
if [ -f "../munch-ease-backend/openapi.json" ]; then
|
|
||||||
npm run codegen
|
|
||||||
else
|
|
||||||
echo "Backend openapi.json not found. Skipping codegen."
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: Typecheck
|
|
||||||
run: npm run -s typecheck
|
|
||||||
|
|
||||||
- name: Typecheck Vue SFC templates
|
|
||||||
run: npm run -s typecheck:vue
|
|
||||||
|
|
||||||
- name: Lint
|
|
||||||
run: npm run -s lint
|
|
||||||
|
|
||||||
- name: Test
|
|
||||||
run: npm run -s test
|
|
||||||
|
|
@ -1,59 +0,0 @@
|
||||||
# Contributing to Munch Ease
|
|
||||||
|
|
||||||
Thanks for helping make Munch Ease better! This repo aims for a lean, predictable codebase. Please keep changes small, typed, and well‑scoped.
|
|
||||||
|
|
||||||
## Core axioms (must follow)
|
|
||||||
|
|
||||||
- OpenAPI is the single source of truth for shapes (generated in `src/api/types.ts`).
|
|
||||||
- The SDK (`src/api/sdk.ts`) is the only data access surface.
|
|
||||||
- Domain types live in `src/domain/types.ts`; minimal normalization in `src/domain/decoders.ts`.
|
|
||||||
- No casts (`as`, angle brackets) in app code. Generated files are exempt. Boundary-only normalization allowed.
|
|
||||||
- No `any`/`unknown` in app code. Prefer precise types, `Pick`/`Omit`, and inference.
|
|
||||||
- Arrays declared in OpenAPI as required are non-nullable in domain types (e.g., `Meal.recipes` is always an array).
|
|
||||||
- Disallow runtime type checks in app code (`typeof`, `in`, broad `instanceof`).
|
|
||||||
- Acceptable exceptions: DOM event narrowing (e.g., `HTMLInputElement`), error normalization in SDK, env detection.
|
|
||||||
- CamelCase across `src/`; no snake_case.
|
|
||||||
|
|
||||||
## Architecture quick tour
|
|
||||||
|
|
||||||
- SDK + decoders boundary
|
|
||||||
- `src/api/sdk.ts`: All network calls; returns domain-safe types. Normalize errors via `httpError`.
|
|
||||||
- `src/domain/decoders.ts`: Convert date strings → `Date`, normalize arrays, and decode nested structures.
|
|
||||||
- Domain and DTOs
|
|
||||||
- Prefer domain aliases from `src/domain/types.ts` over raw `components['schemas'][...]`.
|
|
||||||
- Use discriminated unions for UI shapes where needed (e.g., `Group` has `type: 'product' | 'name'`).
|
|
||||||
- Composables
|
|
||||||
- UI logic in `src/composables/*`. Keep components thin.
|
|
||||||
- Routing
|
|
||||||
- Use helpers from `src/router/helpers.ts` (`parseRouteId`, `parseQueryString`) instead of ad-hoc `typeof` checks.
|
|
||||||
|
|
||||||
## Coding guidelines
|
|
||||||
|
|
||||||
- Keep changes small and incremental. Write a quick unit test when behavior changes.
|
|
||||||
- Prefer `computed` over ad-hoc recalculation; avoid prop mutation.
|
|
||||||
- No ad-hoc mappers. If a slimmer shape is needed, use `Pick`/`Omit` with a descriptive name (e.g., `*Summary`).
|
|
||||||
- Keep runtime guards in the boundary only. UI assumes decoded, normalized types.
|
|
||||||
|
|
||||||
## Tooling
|
|
||||||
|
|
||||||
- TypeScript strict; ESLint with type-aware rules; Prettier formatting.
|
|
||||||
- Tests: Vitest + MSW. Keep tests fast and focused.
|
|
||||||
- Node 18+ recommended.
|
|
||||||
|
|
||||||
## Useful scripts
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npm run serve # Dev server
|
|
||||||
npm run test # Unit tests (Vitest)
|
|
||||||
npm run lint # ESLint
|
|
||||||
npm run typecheck # TS + vue-tsc
|
|
||||||
npm run build # Production build
|
|
||||||
```
|
|
||||||
|
|
||||||
## PR checklist
|
|
||||||
|
|
||||||
- [ ] Types first: no casts in app code, no `any`/`unknown`
|
|
||||||
- [ ] Boundary-only normalization in decoders/SDK
|
|
||||||
- [ ] Arrays reflect OpenAPI nullability in domain types
|
|
||||||
- [ ] No new mappers; use domain aliases or `Pick`/`Omit`
|
|
||||||
- [ ] Tests updated/added if behavior changed
|
|
||||||
76
README.md
76
README.md
|
|
@ -39,35 +39,49 @@ Environment
|
||||||
|
|
||||||
## Architecture and conventions
|
## Architecture and conventions
|
||||||
|
|
||||||
Strict TypeScript, Vue 3 Composition API, and a single typed API boundary.
|
The codebase follows clear boundaries and Vue 3 Composition API throughout.
|
||||||
|
|
||||||
Key axioms
|
- Routing and auth
|
||||||
- OpenAPI (generated `src/api/types.ts`) is the single source of truth for shapes.
|
- Centralized in `src/router/index.js` with named routes and an auth guard via route meta `requiresAuth`.
|
||||||
- SDK (`src/api/sdk.ts`) is the only data access surface; UI uses domain types from `src/domain/types.ts`.
|
- Components use `useRouter/useRoute` for navigation and route access.
|
||||||
- Domain normalization is minimal in `src/domain/decoders.ts` (e.g., date strings → `Date`).
|
|
||||||
- No casts (`as`, angle brackets) and no `any`/`unknown` in app code. Generated files are exempt.
|
|
||||||
- Arrays that are required in OpenAPI are non-nullable in domain types (e.g., `Meal.recipes`).
|
|
||||||
- Disallow runtime type checks in app code; acceptable exceptions: DOM event narrowing, error/env handling in the boundary.
|
|
||||||
|
|
||||||
Layout
|
- API layer and mappers
|
||||||
- `src/api/` — Typed client and SDK boundary
|
- `src/api/http.js` is a tiny JSON fetch wrapper that honors `VUE_APP_API_BASE`.
|
||||||
- `src/domain/` — Domain types and decoders
|
- Feature services live in `src/api/*` (meals, recipes, shopping, auth, persons).
|
||||||
- `src/composables/` — Reusable app logic (auth, meals, shopping, pagination, alert)
|
- Normalization lives in `src/api/mappers/*` (e.g., date parsing, shape cleanup).
|
||||||
- `src/components/` — UI components and pages
|
|
||||||
- `src/router/` — Routes and helpers (`parseRouteId`, `parseQueryString`)
|
|
||||||
|
|
||||||
Testing and tooling
|
- Composables (UI-facing logic)
|
||||||
- Vitest + MSW under `tests/`
|
- Reusable logic in `src/composables/*` (useAuth, useMeals, useShopping).
|
||||||
- ESLint (type-aware) + Prettier + Volar
|
- Components stay thin: data via refs/reactive, effects via computed/watch.
|
||||||
|
|
||||||
|
- Components
|
||||||
|
- All Single File Components use `<script setup>`.
|
||||||
|
- Props via `defineProps`, events via `defineEmits`, routing via `useRouter`.
|
||||||
|
- Event bus for alerts is in `src/alert.js` with `AlertToast` subscribing; can evolve into a `useAlert` composable.
|
||||||
|
|
||||||
|
- Testing
|
||||||
|
- Vitest configured (`vitest.config.js`) with `@` alias to `src`.
|
||||||
|
- Targeted unit tests cover units and API mappers under `tests/`.
|
||||||
|
|
||||||
|
- Formatting and linting
|
||||||
|
- Prettier is the source of truth; Husky + lint-staged auto-format on commit.
|
||||||
|
- ESLint configured for Vue 3 and Composition API macros.
|
||||||
|
- Recommended: use Volar in your editor for Vue intelligence.
|
||||||
|
|
||||||
|
Folder highlights
|
||||||
|
- `src/api/` — HTTP wrapper, feature services, and data mappers
|
||||||
|
- `src/composables/` — Reusable app logic (auth, meals, shopping)
|
||||||
|
- `src/components/` — UI components and pages (all in `<script setup>`)
|
||||||
|
- `src/router/` — Route definitions and auth guard
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Development tips
|
## Development tips
|
||||||
|
|
||||||
- Prefer composables for shared logic; keep components thin.
|
- Prefer composables for shared logic; keep components presentational where possible.
|
||||||
- Use computed for derived values; avoid mutating props directly.
|
- Use computed for derived values; avoid mutating props directly.
|
||||||
- Use discriminated unions for UI-only shapes when helpful (e.g., shopping `Group`).
|
- When navigating, prefer named routes for stability.
|
||||||
- Add/adjust tests when changing behavior.
|
- Keep tests small and fast; add a test when you add a new mapper or unit.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
@ -76,25 +90,3 @@ Testing and tooling
|
||||||
- API errors: verify `VUE_APP_API_BASE` is set and reachable.
|
- API errors: verify `VUE_APP_API_BASE` is set and reachable.
|
||||||
- Type/IDE help: ensure Volar is enabled and ESLint is not conflicting with Prettier.
|
- Type/IDE help: ensure Volar is enabled and ESLint is not conflicting with Prettier.
|
||||||
- Build issues: this project uses Vue CLI 5. If migrating to Vite, update scripts and configs accordingly.
|
- Build issues: this project uses Vue CLI 5. If migrating to Vite, update scripts and configs accordingly.
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Type checking and codegen
|
|
||||||
|
|
||||||
- Type check (TS strict + vue-tsc):
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npm run typecheck
|
|
||||||
```
|
|
||||||
|
|
||||||
- Generate API types (consumed by SDK):
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npm run codegen
|
|
||||||
```
|
|
||||||
|
|
||||||
Environment
|
|
||||||
- VUE_APP_API_BASE (Vue CLI) or VITE_API_BASE_URL (Vite) for API base URL
|
|
||||||
|
|
||||||
Testing
|
|
||||||
- Unit tests use MSW; the client defaults to a localhost base in tests for easy mocking
|
|
||||||
|
|
|
||||||
3913
package-lock.json
generated
3913
package-lock.json
generated
File diff suppressed because it is too large
Load diff
68
package.json
68
package.json
|
|
@ -10,12 +10,7 @@
|
||||||
"prepare": "husky install",
|
"prepare": "husky install",
|
||||||
"test": "vitest run",
|
"test": "vitest run",
|
||||||
"test:watch": "vitest",
|
"test:watch": "vitest",
|
||||||
"test:coverage": "vitest run --coverage",
|
"test:coverage": "vitest run --coverage"
|
||||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
||||||
"typecheck:vue": "vue-tsc --noEmit",
|
|
||||||
"codegen:api": "openapi-typescript ../munch-ease-backend/openapi.json -o src/api/types.ts",
|
|
||||||
"codegen": "npm run codegen:api",
|
|
||||||
"codegen:check": "node scripts/codegen-check.js"
|
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"core-js": "^3.8.3",
|
"core-js": "^3.8.3",
|
||||||
|
|
@ -25,26 +20,15 @@
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@babel/core": "^7.12.16",
|
"@babel/core": "^7.12.16",
|
||||||
"@babel/eslint-parser": "^7.12.16",
|
"@babel/eslint-parser": "^7.12.16",
|
||||||
"@types/node": "^20.19.22",
|
|
||||||
"@typescript-eslint/eslint-plugin": "^7.18.0",
|
|
||||||
"@typescript-eslint/parser": "^7.18.0",
|
|
||||||
"@vue/cli-plugin-babel": "~5.0.0",
|
"@vue/cli-plugin-babel": "~5.0.0",
|
||||||
"@vue/cli-plugin-eslint": "~5.0.0",
|
"@vue/cli-plugin-eslint": "~5.0.0",
|
||||||
"@vue/cli-plugin-typescript": "~5.0.0",
|
|
||||||
"@vue/cli-service": "~5.0.0",
|
"@vue/cli-service": "~5.0.0",
|
||||||
"eslint": "^8.57.0",
|
"eslint": "^7.32.0",
|
||||||
"eslint-plugin-vue": "^9.27.0",
|
"eslint-plugin-vue": "^8.0.3",
|
||||||
"husky": "^8.0.0",
|
"husky": "^8.0.0",
|
||||||
"lint-staged": "^13.3.0",
|
"lint-staged": "^13.3.0",
|
||||||
"msw": "^2.5.2",
|
|
||||||
"node-fetch": "^2.6.9",
|
|
||||||
"openapi-fetch": "^0.9.5",
|
|
||||||
"openapi-typescript": "^7.4.2",
|
|
||||||
"prettier": "^3.3.3",
|
"prettier": "^3.3.3",
|
||||||
"typescript": "~5.5.4",
|
"vitest": "^1.6.0"
|
||||||
"undici": "^6.19.8",
|
|
||||||
"vitest": "^1.6.0",
|
|
||||||
"vue-tsc": "^2.0.29"
|
|
||||||
},
|
},
|
||||||
"lint-staged": {
|
"lint-staged": {
|
||||||
"*.{js,vue,css,scss,md}": [
|
"*.{js,vue,css,scss,md}": [
|
||||||
|
|
@ -59,53 +43,15 @@
|
||||||
},
|
},
|
||||||
"extends": [
|
"extends": [
|
||||||
"plugin:vue/vue3-recommended",
|
"plugin:vue/vue3-recommended",
|
||||||
"eslint:recommended",
|
"eslint:recommended"
|
||||||
"plugin:@typescript-eslint/recommended"
|
|
||||||
],
|
],
|
||||||
"parser": "vue-eslint-parser",
|
|
||||||
"parserOptions": {
|
"parserOptions": {
|
||||||
"parser": "@typescript-eslint/parser",
|
"parser": "@babel/eslint-parser"
|
||||||
"sourceType": "module",
|
|
||||||
"ecmaVersion": 2020,
|
|
||||||
"extraFileExtensions": [
|
|
||||||
".vue"
|
|
||||||
]
|
|
||||||
},
|
},
|
||||||
"plugins": [
|
|
||||||
"@typescript-eslint"
|
|
||||||
],
|
|
||||||
"rules": {
|
"rules": {
|
||||||
"vue/multi-word-component-names": "off",
|
"vue/multi-word-component-names": "off",
|
||||||
"vue/no-mutating-props": "error"
|
"vue/no-mutating-props": "error"
|
||||||
},
|
}
|
||||||
"overrides": [
|
|
||||||
{
|
|
||||||
"files": ["src/**/*.ts", "src/**/*.vue", "src/**/*.d.ts"],
|
|
||||||
"excludedFiles": ["src/api/types.ts", "src/**/*.d.ts"],
|
|
||||||
"parserOptions": {
|
|
||||||
"project": ["./tsconfig.eslint.json"],
|
|
||||||
"tsconfigRootDir": "."
|
|
||||||
},
|
|
||||||
"rules": {
|
|
||||||
"@typescript-eslint/no-explicit-any": "error",
|
|
||||||
"@typescript-eslint/no-unsafe-assignment": "error",
|
|
||||||
"@typescript-eslint/no-unsafe-call": "error",
|
|
||||||
"@typescript-eslint/no-unsafe-member-access": "error",
|
|
||||||
"@typescript-eslint/no-unsafe-return": "error",
|
|
||||||
"no-restricted-syntax": [
|
|
||||||
"error",
|
|
||||||
{
|
|
||||||
"selector": "TSAsExpression[typeAnnotation.type!='TSConstKeyword']",
|
|
||||||
"message": "Disallow 'as' type assertions in app code. Prefer precise typing and helpers."
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"selector": "TSTypeAssertion",
|
|
||||||
"message": "Disallow angle-bracket type assertions in app code. Prefer precise typing and helpers."
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
},
|
||||||
"browserslist": [
|
"browserslist": [
|
||||||
"> 1%",
|
"> 1%",
|
||||||
|
|
|
||||||
|
|
@ -1,32 +0,0 @@
|
||||||
#!/usr/bin/env node
|
|
||||||
/**
|
|
||||||
* Warn if backend openapi.json is newer than generated src/api/types.ts
|
|
||||||
*/
|
|
||||||
const { statSync, existsSync } = require('fs')
|
|
||||||
const { resolve } = require('path')
|
|
||||||
|
|
||||||
const backendSpec = resolve(__dirname, '..', '..', 'munch-ease-backend', 'openapi.json')
|
|
||||||
const generated = resolve(__dirname, '..', 'src', 'api', 'types.ts')
|
|
||||||
|
|
||||||
if (!existsSync(backendSpec)) {
|
|
||||||
console.log('codegen-check: Skipping (backend openapi.json not found).')
|
|
||||||
process.exit(0)
|
|
||||||
}
|
|
||||||
if (!existsSync(generated)) {
|
|
||||||
console.log('codegen-check: src/api/types.ts not found. Run: npm run codegen')
|
|
||||||
process.exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const specMtime = statSync(backendSpec).mtimeMs
|
|
||||||
const genMtime = statSync(generated).mtimeMs
|
|
||||||
if (specMtime > genMtime) {
|
|
||||||
console.log('codegen-check: OpenAPI spec is newer than generated types. Consider running: npm run codegen')
|
|
||||||
process.exit(2)
|
|
||||||
} else {
|
|
||||||
console.log('codegen-check: OK (generated types up to date).')
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
console.error('codegen-check: Error reading timestamps:', e.message)
|
|
||||||
process.exit(3)
|
|
||||||
}
|
|
||||||
11
src/alert.js
Normal file
11
src/alert.js
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
const subscribers = []
|
||||||
|
|
||||||
|
export default {
|
||||||
|
subscribe(callback) {
|
||||||
|
subscribers.push(callback)
|
||||||
|
},
|
||||||
|
show(message) {
|
||||||
|
// { message, heading, type: ["success", "error", "info"] }
|
||||||
|
subscribers.forEach((callback) => callback(message))
|
||||||
|
},
|
||||||
|
}
|
||||||
21
src/api/auth.js
Normal file
21
src/api/auth.js
Normal file
|
|
@ -0,0 +1,21 @@
|
||||||
|
import { http } from './http'
|
||||||
|
|
||||||
|
let cachedUser = null
|
||||||
|
|
||||||
|
export async function currentUser() {
|
||||||
|
if (cachedUser) return cachedUser
|
||||||
|
// Try a refresh if a cookie exists (browser will send it automatically)
|
||||||
|
try {
|
||||||
|
const user = await http.post('/auth/refresh')
|
||||||
|
cachedUser = user
|
||||||
|
} catch (_) {
|
||||||
|
cachedUser = null
|
||||||
|
}
|
||||||
|
return cachedUser
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function login(username) {
|
||||||
|
const user = await http.post('/auth/login', { username })
|
||||||
|
cachedUser = user
|
||||||
|
return user
|
||||||
|
}
|
||||||
|
|
@ -1,30 +0,0 @@
|
||||||
import { api } from '@/api/client'
|
|
||||||
import type { Person } from '@/domain/types'
|
|
||||||
|
|
||||||
let cachedUser: Person | null = null
|
|
||||||
|
|
||||||
export async function currentUser(): Promise<Person | null> {
|
|
||||||
if (cachedUser) return cachedUser
|
|
||||||
try {
|
|
||||||
const res = await api.POST('/api/v1/auth/refresh', { params: { cookie: { user_id: 0 } } })
|
|
||||||
if (!res.response.ok) return null
|
|
||||||
cachedUser = res.data ?? null
|
|
||||||
} catch (_) {
|
|
||||||
cachedUser = null
|
|
||||||
}
|
|
||||||
return cachedUser
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function login(username: string): Promise<Person> {
|
|
||||||
const res = await api.POST('/api/v1/auth/login', { body: { username } })
|
|
||||||
if (!res.response.ok) {
|
|
||||||
const err = res.error
|
|
||||||
throw (
|
|
||||||
(err instanceof Error && err) ||
|
|
||||||
(typeof err === 'string' ? new Error(err) : new Error(`${res.response.status} ${res.response.statusText || 'HTTP error'}`))
|
|
||||||
)
|
|
||||||
}
|
|
||||||
cachedUser = res.data ?? null
|
|
||||||
if (!cachedUser) throw new Error('Login failed: empty response')
|
|
||||||
return cachedUser
|
|
||||||
}
|
|
||||||
|
|
@ -1,20 +0,0 @@
|
||||||
import createClient from 'openapi-fetch'
|
|
||||||
import type { paths } from './types'
|
|
||||||
|
|
||||||
// Vue CLI uses process.env.VUE_APP_*
|
|
||||||
const vueCliBase: string | undefined = typeof process !== 'undefined' ? (process.env?.VUE_APP_API_BASE ?? undefined) : undefined
|
|
||||||
const isTest = typeof process !== 'undefined' && (process.env?.VITEST === 'true' || process.env?.NODE_ENV === 'test')
|
|
||||||
// Prefer absolute http URL in tests to avoid TLS issues and ease MSW interception
|
|
||||||
// Use host-only base URL; always pass full "/api/v1/..." paths to the client methods
|
|
||||||
const defaultBase = ''
|
|
||||||
const baseUrl: string = isTest ? 'http://localhost' : (vueCliBase || defaultBase)
|
|
||||||
|
|
||||||
export const api = createClient<paths>({
|
|
||||||
baseUrl,
|
|
||||||
fetch: (input: RequestInfo | URL, init?: RequestInit) => {
|
|
||||||
return globalThis.fetch(input, {
|
|
||||||
credentials: 'include',
|
|
||||||
...init,
|
|
||||||
})
|
|
||||||
},
|
|
||||||
})
|
|
||||||
35
src/api/http.js
Normal file
35
src/api/http.js
Normal file
|
|
@ -0,0 +1,35 @@
|
||||||
|
const BASE = process.env.VUE_APP_API_BASE || '/api'
|
||||||
|
|
||||||
|
async function request(path, options = {}) {
|
||||||
|
const url = path.startsWith('http') ? path : `${BASE}${path}`
|
||||||
|
const resp = await fetch(url, {
|
||||||
|
credentials: 'include',
|
||||||
|
...options,
|
||||||
|
headers: {
|
||||||
|
Accept: 'application/json',
|
||||||
|
...(options.body ? { 'Content-Type': 'application/json' } : {}),
|
||||||
|
...(options.headers || {}),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if (!resp.ok) {
|
||||||
|
let message = `${resp.status} ${resp.statusText}`
|
||||||
|
try {
|
||||||
|
const err = await resp.json()
|
||||||
|
message = err.message || message
|
||||||
|
} catch (_) {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
const error = new Error(message)
|
||||||
|
error.status = resp.status
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
if (resp.status === 204) return null
|
||||||
|
return resp.json()
|
||||||
|
}
|
||||||
|
|
||||||
|
export const http = {
|
||||||
|
get: (p) => request(p),
|
||||||
|
post: (p, body) => request(p, { method: 'POST', body: JSON.stringify(body) }),
|
||||||
|
put: (p, body) => request(p, { method: 'PUT', body: JSON.stringify(body) }),
|
||||||
|
del: (p) => request(p, { method: 'DELETE' }),
|
||||||
|
}
|
||||||
16
src/api/mappers/mealMapper.js
Normal file
16
src/api/mappers/mealMapper.js
Normal file
|
|
@ -0,0 +1,16 @@
|
||||||
|
function toDate(value) {
|
||||||
|
return value ? new Date(value) : value
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapMeal(meal) {
|
||||||
|
if (!meal) return meal
|
||||||
|
meal.suggested_date = toDate(meal.suggested_date)
|
||||||
|
meal.purchase_date = toDate(meal.purchase_date)
|
||||||
|
meal.consumed_date = toDate(meal.consumed_date)
|
||||||
|
return meal
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapMeals(list) {
|
||||||
|
if (!Array.isArray(list)) return []
|
||||||
|
return list.map(mapMeal)
|
||||||
|
}
|
||||||
15
src/api/mappers/recipeMapper.js
Normal file
15
src/api/mappers/recipeMapper.js
Normal file
|
|
@ -0,0 +1,15 @@
|
||||||
|
function toDate(value) {
|
||||||
|
return value ? new Date(value) : value
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapRecipe(recipe) {
|
||||||
|
if (!recipe) return recipe
|
||||||
|
recipe.date_created = toDate(recipe.date_created)
|
||||||
|
recipe.date_hidden = toDate(recipe.date_hidden)
|
||||||
|
return recipe
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapRecipes(list) {
|
||||||
|
if (!Array.isArray(list)) return []
|
||||||
|
return list.map(mapRecipe)
|
||||||
|
}
|
||||||
73
src/api/mappers/shoppingListMapper.js
Normal file
73
src/api/mappers/shoppingListMapper.js
Normal file
|
|
@ -0,0 +1,73 @@
|
||||||
|
import { mapMeal } from './mealMapper'
|
||||||
|
import { mapRecipe } from './recipeMapper'
|
||||||
|
|
||||||
|
function toDate(value) {
|
||||||
|
return value ? new Date(value) : value
|
||||||
|
}
|
||||||
|
|
||||||
|
function attachItemRefs(
|
||||||
|
items,
|
||||||
|
{ ingredients_lookup, meals_lookup, recipes_lookup, shopping_list_lookup }
|
||||||
|
) {
|
||||||
|
if (!Array.isArray(items)) return
|
||||||
|
for (const item of items) {
|
||||||
|
if (item.ingredient_id && ingredients_lookup)
|
||||||
|
item.ingredient = ingredients_lookup[item.ingredient_id]
|
||||||
|
if (item.meal_id && meals_lookup) item.meal = meals_lookup[item.meal_id]
|
||||||
|
if (item.recipe_id && recipes_lookup) item.recipe = recipes_lookup[item.recipe_id]
|
||||||
|
if (item.list_id && shopping_list_lookup) item.list = shopping_list_lookup[item.list_id]
|
||||||
|
if (item.created_date) item.created_date = toDate(item.created_date)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapPurchasedShoppingList(dto) {
|
||||||
|
if (!dto) return dto
|
||||||
|
// Map lookups
|
||||||
|
if (dto.meals_lookup) {
|
||||||
|
for (const [k, v] of Object.entries(dto.meals_lookup)) dto.meals_lookup[k] = mapMeal(v)
|
||||||
|
}
|
||||||
|
if (dto.recipes_lookup) {
|
||||||
|
for (const [k, v] of Object.entries(dto.recipes_lookup)) dto.recipes_lookup[k] = mapRecipe(v)
|
||||||
|
}
|
||||||
|
if (dto.ingredients_lookup) {
|
||||||
|
// no date fields expected on ingredient based on current usage
|
||||||
|
}
|
||||||
|
if (dto.list) {
|
||||||
|
if (dto.list.created_date) dto.list.created_date = toDate(dto.list.created_date)
|
||||||
|
if (Array.isArray(dto.list.items)) {
|
||||||
|
attachItemRefs(dto.list.items, {
|
||||||
|
ingredients_lookup: dto.ingredients_lookup,
|
||||||
|
meals_lookup: dto.meals_lookup,
|
||||||
|
recipes_lookup: dto.recipes_lookup,
|
||||||
|
shopping_list_lookup: { [dto.list.id]: dto.list },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return dto
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mapCurrentShoppingList(dto) {
|
||||||
|
if (!dto) return dto
|
||||||
|
if (dto.meals_lookup) {
|
||||||
|
for (const [k, v] of Object.entries(dto.meals_lookup)) dto.meals_lookup[k] = mapMeal(v)
|
||||||
|
}
|
||||||
|
if (dto.recipes_lookup) {
|
||||||
|
for (const [k, v] of Object.entries(dto.recipes_lookup)) dto.recipes_lookup[k] = mapRecipe(v)
|
||||||
|
}
|
||||||
|
if (dto.shopping_list_lookup) {
|
||||||
|
for (const [, v] of Object.entries(dto.shopping_list_lookup)) {
|
||||||
|
if (v?.created_date) v.created_date = toDate(v.created_date)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const lookups = {
|
||||||
|
ingredients_lookup: dto.ingredients_lookup,
|
||||||
|
meals_lookup: dto.meals_lookup,
|
||||||
|
recipes_lookup: dto.recipes_lookup,
|
||||||
|
shopping_list_lookup: dto.shopping_list_lookup,
|
||||||
|
}
|
||||||
|
attachItemRefs(dto.outstanding_items, lookups)
|
||||||
|
attachItemRefs(dto.requested_meals, lookups)
|
||||||
|
attachItemRefs(dto.purchased_items, lookups)
|
||||||
|
return dto
|
||||||
|
}
|
||||||
31
src/api/meals.js
Normal file
31
src/api/meals.js
Normal file
|
|
@ -0,0 +1,31 @@
|
||||||
|
import { http } from './http'
|
||||||
|
import { mapMeal, mapMeals } from './mappers/mealMapper'
|
||||||
|
|
||||||
|
export async function getUpcomingMeals(from, to) {
|
||||||
|
const params = `?from=${encodeURIComponent(from.toISOString())}&to=${encodeURIComponent(to.toISOString())}`
|
||||||
|
const meals = await http.get(`/meals/upcoming${params}`)
|
||||||
|
const normalized = mapMeals(meals)
|
||||||
|
return normalized.sort((a, b) => a.suggested_date - b.suggested_date)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function markMealConsumed(mealId) {
|
||||||
|
const meal = await http.post(`/meals/${encodeURIComponent(mealId)}/consumed`)
|
||||||
|
return mapMeal(meal)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteMeal(mealId) {
|
||||||
|
return http.del(`/meals/${encodeURIComponent(mealId)}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getMeal(id) {
|
||||||
|
const meal = await http.get(`/meals/${encodeURIComponent(id)}`)
|
||||||
|
return mapMeal(meal)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function saveMeal(meal) {
|
||||||
|
const hasId = meal.id >= 0
|
||||||
|
const path = hasId ? `/meals/${encodeURIComponent(meal.id)}` : '/meals'
|
||||||
|
const method = hasId ? http.put : http.post
|
||||||
|
const saved = await method(path, meal)
|
||||||
|
return mapMeal(saved)
|
||||||
|
}
|
||||||
9
src/api/persons.js
Normal file
9
src/api/persons.js
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
import { http } from './http'
|
||||||
|
|
||||||
|
export async function getPersonsInHome() {
|
||||||
|
return http.get('/persons')
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function searchPerson(name) {
|
||||||
|
return http.get(`/persons?q=${encodeURIComponent(name)}`)
|
||||||
|
}
|
||||||
36
src/api/recipes.js
Normal file
36
src/api/recipes.js
Normal file
|
|
@ -0,0 +1,36 @@
|
||||||
|
import { http } from './http'
|
||||||
|
import { mapRecipe, mapRecipes } from './mappers/recipeMapper'
|
||||||
|
|
||||||
|
export async function searchRecipes(query) {
|
||||||
|
const recipes = await http.get(`/recipes?q=${encodeURIComponent(query)}`)
|
||||||
|
return mapRecipes(recipes)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getRecipe(id) {
|
||||||
|
const recipe = await http.get(`/recipes/${encodeURIComponent(id)}`)
|
||||||
|
return mapRecipe(recipe)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function saveRecipe(recipe) {
|
||||||
|
const saved = await http.post('/recipes', recipe)
|
||||||
|
return mapRecipe(saved)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteRecipe(id) {
|
||||||
|
return http.del(`/recipes/${encodeURIComponent(id)}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function parseRecipe(url) {
|
||||||
|
const recipe = await http.get(`/recipes/parse?url=${encodeURIComponent(url)}`)
|
||||||
|
return mapRecipe(recipe)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function parseIngredients(lines) {
|
||||||
|
const params = lines.map((line) => `ingredients=${encodeURIComponent(line)}`).join('&')
|
||||||
|
return http.get(`/recipes/ingredients/parse?${params}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function parseProduct(ingredient, url) {
|
||||||
|
const body = { url, tags: [ingredient.name, ingredient.line] }
|
||||||
|
return http.post('/products', body)
|
||||||
|
}
|
||||||
354
src/api/sdk.ts
354
src/api/sdk.ts
|
|
@ -1,354 +0,0 @@
|
||||||
import { api } from '@/api/client'
|
|
||||||
import type { components } from '@/api/types'
|
|
||||||
import { toDate, decodeMeal, decodeRecipe, decodeIngredients, decodeShoppingList, decodeShoppingListItems, decodeIngredient } 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'}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Small helper to decode optional lookup maps without repeating loops everywhere
|
|
||||||
function decodeLookup<TIn, TOut>(
|
|
||||||
raw: Record<string, TIn> | null | undefined,
|
|
||||||
decode: (v: TIn) => TOut | null
|
|
||||||
): Record<string, TOut> | undefined {
|
|
||||||
if (!raw) return undefined
|
|
||||||
const out: Record<string, TOut> = {}
|
|
||||||
for (const key of Object.keys(raw)) {
|
|
||||||
if (!Object.prototype.hasOwnProperty.call(raw, key)) continue
|
|
||||||
const maybe = raw[key]
|
|
||||||
if (maybe === undefined) continue
|
|
||||||
const decoded = decode(maybe)
|
|
||||||
if (decoded) out[String(key)] = decoded
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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)
|
|
||||||
}
|
|
||||||
|
|
||||||
type PurchaseExisting = { type: 'existing'; id: number; personId: number; ingredientId?: number | null }
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
38
src/api/shopping.js
Normal file
38
src/api/shopping.js
Normal file
|
|
@ -0,0 +1,38 @@
|
||||||
|
import { http } from './http'
|
||||||
|
import { mapPurchasedShoppingList, mapCurrentShoppingList } from './mappers/shoppingListMapper'
|
||||||
|
|
||||||
|
export async function getMyShoppingList() {
|
||||||
|
const ingredients = await http.get('/shopping/current/me/ingredients')
|
||||||
|
return ingredients
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function saveMyShoppingList(list) {
|
||||||
|
const ingredients = await http.post('/shopping/current/me/ingredients', list)
|
||||||
|
return ingredients
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getShoppingList(id) {
|
||||||
|
const dto = await http.get(`/shopping/${encodeURIComponent(id)}`)
|
||||||
|
const mapped = mapPurchasedShoppingList(dto)
|
||||||
|
return mapped.list
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getCurrentShoppingList() {
|
||||||
|
const dto = await http.get('/shopping/current')
|
||||||
|
return mapCurrentShoppingList(dto)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function purchaseShoppingList(completedRequests) {
|
||||||
|
const dto = await http.post('/shopping/', { items: completedRequests })
|
||||||
|
const mapped = mapPurchasedShoppingList(dto)
|
||||||
|
return mapped.list
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function requestMeal(mealId) {
|
||||||
|
const items = await http.post('/shopping/current/meals/me', { meal_id: mealId })
|
||||||
|
return items
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function unrequestMeal(mealId) {
|
||||||
|
await http.del(`/shopping/current/meals/${encodeURIComponent(mealId)}`)
|
||||||
|
}
|
||||||
1634
src/api/types.ts
1634
src/api/types.ts
File diff suppressed because it is too large
Load diff
|
|
@ -25,9 +25,9 @@ import { computed, watch } from 'vue'
|
||||||
import { useAlert } from '@/composables/useAlert'
|
import { useAlert } from '@/composables/useAlert'
|
||||||
|
|
||||||
const alertIcons = {
|
const alertIcons = {
|
||||||
error: new URL('@/assets/notification-error.svg', import.meta.url).toString(),
|
error: require('@/assets/notification-error.svg'),
|
||||||
success: new URL('@/assets/notification-success.svg', import.meta.url).toString(),
|
success: require('@/assets/notification-success.svg'),
|
||||||
info: new URL('@/assets/notification-info.svg', import.meta.url).toString(),
|
info: require('@/assets/notification-info.svg'),
|
||||||
}
|
}
|
||||||
|
|
||||||
const { current, clear, scheduleAutoDismiss } = useAlert()
|
const { current, clear, scheduleAutoDismiss } = useAlert()
|
||||||
|
|
|
||||||
|
|
@ -3,8 +3,8 @@
|
||||||
<h1>Login Page</h1>
|
<h1>Login Page</h1>
|
||||||
<ul class="button-group">
|
<ul class="button-group">
|
||||||
<li
|
<li
|
||||||
v-for="(person, index) in persons"
|
v-for="person in persons"
|
||||||
:key="person.id ?? index"
|
:key="person.id"
|
||||||
>
|
>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
|
|
@ -18,26 +18,24 @@
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup>
|
||||||
import { ref, onMounted } from 'vue'
|
import { ref, onMounted } from 'vue'
|
||||||
import { useRouter } from 'vue-router'
|
import { useRouter } from 'vue-router'
|
||||||
import { getPersonsInHome } from '@/api/sdk'
|
import { getPersonsInHome } from '@/api/persons'
|
||||||
import { login as loginApi } from '@/api/auth'
|
import { login as loginApi } from '@/api/auth'
|
||||||
import type { Person } from '@/domain/types'
|
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
redirect: { type: String, default: '/' },
|
redirect: { type: String, default: '/' },
|
||||||
})
|
})
|
||||||
|
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const persons = ref<Person[]>([])
|
const persons = ref([])
|
||||||
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
const page = await getPersonsInHome()
|
persons.value = await getPersonsInHome()
|
||||||
persons.value = page.items
|
|
||||||
})
|
})
|
||||||
|
|
||||||
async function onLogin(selectedPerson: Person) {
|
async function onLogin(selectedPerson) {
|
||||||
const person = await loginApi(selectedPerson.name)
|
const person = await loginApi(selectedPerson.name)
|
||||||
if (person?.id >= 0) {
|
if (person?.id >= 0) {
|
||||||
router.push(props.redirect)
|
router.push(props.redirect)
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
<template>
|
<template>
|
||||||
<div class="compact-parse-results">
|
<div class="compact-parse-results">
|
||||||
<p class="parse-element teaser-image">
|
<p class="parse-element teaser-image">
|
||||||
<img :src="ingredient.product?.imgSmall ?? missingProduct">
|
<img :src="ingredient.product?.img_small ?? require('@/assets/missing-product.svg')">
|
||||||
</p>
|
</p>
|
||||||
<p class="ingredient-details">
|
<p class="ingredient-details">
|
||||||
<span
|
<span
|
||||||
|
|
@ -34,7 +34,7 @@
|
||||||
>
|
>
|
||||||
( {{ ingredient?.product?.name }}
|
( {{ ingredient?.product?.name }}
|
||||||
<img
|
<img
|
||||||
:src="externalLink"
|
src="@/assets/external-link.svg"
|
||||||
style="
|
style="
|
||||||
width: 1em;
|
width: 1em;
|
||||||
height: 1em;
|
height: 1em;
|
||||||
|
|
@ -58,8 +58,6 @@
|
||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
import { computed } from 'vue'
|
import { computed } from 'vue'
|
||||||
const missingProduct = new URL('@/assets/missing-product.svg', import.meta.url).toString()
|
|
||||||
const externalLink = new URL('@/assets/external-link.svg', import.meta.url).toString()
|
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
ingredient: { type: Object, required: true },
|
ingredient: { type: Object, required: true },
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,7 @@
|
||||||
>
|
>
|
||||||
<img
|
<img
|
||||||
class="icon"
|
class="icon"
|
||||||
:src="addCart"
|
:src="require('@/assets/add-cart.svg')"
|
||||||
> <br>
|
> <br>
|
||||||
Add Ingredient
|
Add Ingredient
|
||||||
</button>
|
</button>
|
||||||
|
|
@ -17,14 +17,14 @@
|
||||||
<span v-if="editing">
|
<span v-if="editing">
|
||||||
<img
|
<img
|
||||||
class="icon"
|
class="icon"
|
||||||
:src="editOff"
|
:src="require('@/assets/edit-off.svg')"
|
||||||
> <br>
|
> <br>
|
||||||
Done Editing
|
Done Editing
|
||||||
</span>
|
</span>
|
||||||
<span v-else>
|
<span v-else>
|
||||||
<img
|
<img
|
||||||
class="icon"
|
class="icon"
|
||||||
:src="editOn"
|
:src="require('@/assets/edit.svg')"
|
||||||
> <br>
|
> <br>
|
||||||
Edit My List
|
Edit My List
|
||||||
</span>
|
</span>
|
||||||
|
|
@ -45,7 +45,7 @@
|
||||||
<button @click="emit('on-delete', ingredient)">
|
<button @click="emit('on-delete', ingredient)">
|
||||||
<img
|
<img
|
||||||
class="icon"
|
class="icon"
|
||||||
:src="trash"
|
:src="require('@/assets/trash.svg')"
|
||||||
>
|
>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -59,13 +59,9 @@
|
||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
import { ref } from 'vue'
|
import { ref } from 'vue'
|
||||||
import { parseProduct, parseIngredients } from '@/api/sdk'
|
import { parseProduct, parseIngredients } from '@/api/recipes'
|
||||||
import IngredientLine from './IngredientLine.vue'
|
import IngredientLine from './IngredientLine.vue'
|
||||||
import CompactParsedIngredient from './CompactParsedIngredient.vue'
|
import CompactParsedIngredient from './CompactParsedIngredient.vue'
|
||||||
const addCart = new URL('@/assets/add-cart.svg', import.meta.url).toString()
|
|
||||||
const editOff = new URL('@/assets/edit-off.svg', import.meta.url).toString()
|
|
||||||
const editOn = new URL('@/assets/edit.svg', import.meta.url).toString()
|
|
||||||
const trash = new URL('@/assets/trash.svg', import.meta.url).toString()
|
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
ingredients: { type: Array, required: true },
|
ingredients: { type: Array, required: true },
|
||||||
|
|
|
||||||
|
|
@ -23,19 +23,17 @@
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup>
|
||||||
import { ref, watch } from 'vue'
|
import { ref, watch } from 'vue'
|
||||||
import CompactParsedIngredient from './CompactParsedIngredient.vue'
|
import CompactParsedIngredient from './CompactParsedIngredient.vue'
|
||||||
import type { Ingredient } from '@/domain/types'
|
|
||||||
|
|
||||||
const props = defineProps<{ ingredient: Ingredient }>()
|
const props = defineProps({
|
||||||
const emit = defineEmits<{
|
ingredient: { type: Object, required: true },
|
||||||
(e: 'update-ingredient', ingredient: Ingredient, newLine: string): void
|
})
|
||||||
(e: 'update-product-link', ingredient: Ingredient, link: string): void
|
const emit = defineEmits(['update-ingredient', 'update-product-link'])
|
||||||
}>()
|
|
||||||
|
|
||||||
const ingredientText = ref<string>(props.ingredient?.line ?? '')
|
const ingredientText = ref(props.ingredient?.line ?? '')
|
||||||
const productLink = ref<string>(props.ingredient.product?.link ?? '')
|
const productLink = ref(props.ingredient.product?.link ?? '')
|
||||||
|
|
||||||
watch(
|
watch(
|
||||||
() => props.ingredient,
|
() => props.ingredient,
|
||||||
|
|
|
||||||
|
|
@ -24,31 +24,32 @@
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup>
|
||||||
import { ref, computed, watch } from 'vue'
|
import { ref, computed, watch } from 'vue'
|
||||||
|
|
||||||
const props = defineProps<{ date?: Date }>()
|
const props = defineProps({
|
||||||
const emit = defineEmits<{ (e: 'date-selected', date: Date): void }>()
|
date: { type: Date, default: () => new Date() },
|
||||||
|
})
|
||||||
|
const emit = defineEmits(['date-selected'])
|
||||||
|
|
||||||
function formatDay(date: Date): string {
|
function formatDay(date) {
|
||||||
const options: Intl.DateTimeFormatOptions = { weekday: 'long', day: 'numeric', month: 'numeric' }
|
const options = { weekday: 'long', day: 'numeric', month: 'numeric' }
|
||||||
return date.toLocaleDateString('en-AU', options)
|
return date.toLocaleDateString('en-AU', options)
|
||||||
}
|
}
|
||||||
|
|
||||||
const initialDate = props.date ?? new Date()
|
const selectedDate = ref(formatDay(props.date))
|
||||||
const selectedDate = ref<string>(formatDay(initialDate))
|
|
||||||
const showDatePicker = ref(false)
|
const showDatePicker = ref(false)
|
||||||
|
|
||||||
watch(
|
watch(
|
||||||
() => props.date,
|
() => props.date,
|
||||||
(newDate) => {
|
(newDate) => {
|
||||||
if (newDate) selectedDate.value = formatDay(newDate)
|
selectedDate.value = formatDay(newDate)
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
const days = computed<Date[]>(() => {
|
const days = computed(() => {
|
||||||
const today = new Date()
|
const today = new Date()
|
||||||
const result: Date[] = []
|
const result = []
|
||||||
for (let i = 0; i < 15; i++) {
|
for (let i = 0; i < 15; i++) {
|
||||||
const d = new Date(today)
|
const d = new Date(today)
|
||||||
d.setDate(today.getDate() + i)
|
d.setDate(today.getDate() + i)
|
||||||
|
|
@ -57,7 +58,7 @@ const days = computed<Date[]>(() => {
|
||||||
return result
|
return result
|
||||||
})
|
})
|
||||||
|
|
||||||
function selectDate(date: Date) {
|
function selectDate(date) {
|
||||||
selectedDate.value = formatDay(date)
|
selectedDate.value = formatDay(date)
|
||||||
showDatePicker.value = false
|
showDatePicker.value = false
|
||||||
emit('date-selected', date)
|
emit('date-selected', date)
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
<div class="container">
|
<div class="container">
|
||||||
<div class="fields">
|
<div class="fields">
|
||||||
<date-picker
|
<date-picker
|
||||||
:date="meal.suggestedDate ?? new Date()"
|
:date="meal.suggested_date"
|
||||||
@date-selected="selectDate"
|
@date-selected="selectDate"
|
||||||
/>
|
/>
|
||||||
<div class="persons-list">
|
<div class="persons-list">
|
||||||
|
|
@ -28,15 +28,12 @@
|
||||||
</div>
|
</div>
|
||||||
<div class="recipes">
|
<div class="recipes">
|
||||||
<h2>Recipes</h2>
|
<h2>Recipes</h2>
|
||||||
<ul v-if="meal.recipes.length">
|
<ul v-if="meal.recipes && meal.recipes.length">
|
||||||
<li
|
<li
|
||||||
v-for="mealRecipe in meal.recipes"
|
v-for="mealRecipe in meal.recipes"
|
||||||
:key="mealRecipe.recipe?.id ?? mealRecipe.recipeId"
|
:key="mealRecipe.recipe.id"
|
||||||
>
|
>
|
||||||
<div
|
<div class="saved-recipe">
|
||||||
v-if="mealRecipe.recipe"
|
|
||||||
class="saved-recipe"
|
|
||||||
>
|
|
||||||
<p class="recipe-card">
|
<p class="recipe-card">
|
||||||
<recipe-card :recipe="mealRecipe.recipe" />
|
<recipe-card :recipe="mealRecipe.recipe" />
|
||||||
</p>
|
</p>
|
||||||
|
|
@ -61,7 +58,7 @@
|
||||||
>
|
>
|
||||||
<img
|
<img
|
||||||
class="icon"
|
class="icon"
|
||||||
:src="showIngredientsIcon"
|
:src="require('@/assets/show-ingredients.svg')"
|
||||||
>
|
>
|
||||||
</label>
|
</label>
|
||||||
<button
|
<button
|
||||||
|
|
@ -70,7 +67,7 @@
|
||||||
>
|
>
|
||||||
<img
|
<img
|
||||||
class="icon"
|
class="icon"
|
||||||
:src="trash"
|
:src="require('@/assets/trash.svg')"
|
||||||
>
|
>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -98,7 +95,7 @@
|
||||||
<div class="ingredients">
|
<div class="ingredients">
|
||||||
<h2>Sides & Additional Ingredients</h2>
|
<h2>Sides & Additional Ingredients</h2>
|
||||||
<editable-ingredients-panel
|
<editable-ingredients-panel
|
||||||
:ingredients="meal.extraIngredients"
|
:ingredients="meal.extra_ingredients"
|
||||||
@on-add="addIngredient"
|
@on-add="addIngredient"
|
||||||
@on-delete="deleteIngredient"
|
@on-delete="deleteIngredient"
|
||||||
@on-update-ingredient="updateIngredient"
|
@on-update-ingredient="updateIngredient"
|
||||||
|
|
@ -109,23 +106,21 @@
|
||||||
<button @click="onSaveMeal">
|
<button @click="onSaveMeal">
|
||||||
Save
|
Save
|
||||||
</button>
|
</button>
|
||||||
<p v-if="meal.purchaseDate">
|
<p v-if="meal.purchase_date">
|
||||||
<em>Purchased {{ ago(meal.purchaseDate) }}</em>
|
<em>Purchased {{ ago(meal.purchase_date) }}</em>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup>
|
||||||
import { reactive, onBeforeMount } from 'vue'
|
import { reactive, onBeforeMount } from 'vue'
|
||||||
import { useRoute, useRouter } from 'vue-router'
|
import { useRoute, useRouter } from 'vue-router'
|
||||||
import { getMeal, saveMeal, toMealInput } from '@/composables/useMeals'
|
import { getMeal, saveMeal } from '@/composables/useMeals'
|
||||||
import { getRecipe } from '@/api/sdk'
|
import { getRecipe } from '@/api/recipes'
|
||||||
import { currentUser } from '@/api/auth'
|
import { currentUser } from '@/api/auth'
|
||||||
import { useAlert } from '@/composables/useAlert'
|
import { useAlert } from '@/composables/useAlert'
|
||||||
import { parseRouteId } from '@/router/helpers'
|
|
||||||
import type { Person, Ingredient, Meal, MealRecipe } from '@/domain/types'
|
|
||||||
|
|
||||||
import { ago } from '@/dateformats'
|
import { ago } from '@/dateformats.js'
|
||||||
|
|
||||||
import RecipeSearchBox from '@/components/recipes/RecipeSearchBox.vue'
|
import RecipeSearchBox from '@/components/recipes/RecipeSearchBox.vue'
|
||||||
import RecipeCard from '@/components/recipes/RecipeCard.vue'
|
import RecipeCard from '@/components/recipes/RecipeCard.vue'
|
||||||
|
|
@ -133,257 +128,241 @@ import DatePicker from './DatePicker.vue'
|
||||||
import EditableIngredientsPanel from '../ingredients/EditableIngredientsPanel.vue'
|
import EditableIngredientsPanel from '../ingredients/EditableIngredientsPanel.vue'
|
||||||
import PersonList from './PersonList.vue'
|
import PersonList from './PersonList.vue'
|
||||||
import CompactParsedIngredient from '../ingredients/CompactParsedIngredient.vue'
|
import CompactParsedIngredient from '../ingredients/CompactParsedIngredient.vue'
|
||||||
const showIngredientsIcon = new URL('@/assets/show-ingredients.svg', import.meta.url).toString()
|
|
||||||
const trash = new URL('@/assets/trash.svg', import.meta.url).toString()
|
|
||||||
|
|
||||||
function addPersonIfNotExists(list: Person[], person: Person | null | undefined) {
|
function addPersonIfNotExists(list, person) {
|
||||||
if (!person) return
|
if (!list.find((p) => p.id === person.id)) {
|
||||||
if (!list.find((p) => p.id === person.id)) {
|
list.push(person)
|
||||||
list.push(person)
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const route = useRoute()
|
const route = useRoute()
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const { show: showAlert } = useAlert()
|
const { show: showAlert } = useAlert()
|
||||||
|
|
||||||
type PeopleKey = 'chefs' | 'consumers' | 'cleanup'
|
const showIngredients = reactive({})
|
||||||
|
const meal = reactive({
|
||||||
const meal = reactive<Meal>({
|
id: -1,
|
||||||
id: -1,
|
suggested_date: new Date(),
|
||||||
suggestedDate: new Date(),
|
recipes: [],
|
||||||
consumedDate: null,
|
extra_ingredients: [],
|
||||||
purchaseDate: null,
|
chefs: [],
|
||||||
recipes: [],
|
consumers: [],
|
||||||
extraIngredients: [],
|
cleanup: [],
|
||||||
chefs: [],
|
|
||||||
consumers: [],
|
|
||||||
cleanup: [],
|
|
||||||
})
|
})
|
||||||
|
|
||||||
onBeforeMount(async () => {
|
onBeforeMount(async () => {
|
||||||
const id = parseRouteId(route.params.id)
|
const idParam = route.params.id
|
||||||
if (id !== null) {
|
const id = typeof idParam === 'string' ? parseInt(idParam) : idParam
|
||||||
const loaded = await getMeal(id)
|
if (id >= 0) {
|
||||||
if (loaded) {
|
const loaded = await getMeal(id)
|
||||||
Object.assign(meal, loaded)
|
Object.assign(meal, loaded)
|
||||||
}
|
} else {
|
||||||
} else {
|
const self = await currentUser()
|
||||||
const self = await currentUser()
|
Object.assign(meal, { chefs: [self], consumers: [self], cleanup: [self] })
|
||||||
if (self) {
|
}
|
||||||
meal.chefs = [self]
|
|
||||||
meal.consumers = [self]
|
|
||||||
meal.cleanup = [self]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
|
|
||||||
function selectDate(date: Date) {
|
function selectDate(date) {
|
||||||
meal.suggestedDate = date
|
meal.suggested_date = date
|
||||||
}
|
}
|
||||||
|
|
||||||
function removeRecipe(mealRecipe: MealRecipe) {
|
function removeRecipe(mealRecipe) {
|
||||||
if (
|
if (
|
||||||
confirm(
|
confirm(
|
||||||
`Are you sure you want to remove ${mealRecipe.servings} servings of ${mealRecipe.recipe?.name ?? 'this recipe'} from this meal?`
|
`Are you sure you want to remove ${mealRecipe.servings} servings of ${mealRecipe.recipe.name} from this meal?`
|
||||||
)
|
)
|
||||||
) {
|
) {
|
||||||
meal.recipes = meal.recipes.filter((r) => r !== mealRecipe)
|
meal.recipes = meal.recipes.filter((r) => r != mealRecipe)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function addIngredient() {
|
function addIngredient() {
|
||||||
meal.extraIngredients = [{ id: -1, name: '', line: '', unit: 'Items', quantity: 0, preparation: '', productId: null, recipeId: null, mealId: null, product: null }, ...meal.extraIngredients]
|
meal.extra_ingredients = [{ line: '', product: null }, ...meal.extra_ingredients]
|
||||||
}
|
}
|
||||||
|
|
||||||
function deleteIngredient(ingredient: Ingredient) {
|
function deleteIngredient(ingredient) {
|
||||||
meal.extraIngredients = meal.extraIngredients.filter((i) => i !== ingredient)
|
meal.extra_ingredients = meal.extra_ingredients.filter((i) => i != ingredient)
|
||||||
}
|
}
|
||||||
|
|
||||||
function updateIngredient(ingredient: Ingredient, newIngredient: Ingredient) {
|
function updateIngredient(ingredient, newIngredient) {
|
||||||
meal.extraIngredients = meal.extraIngredients.map((i) => (i === ingredient ? newIngredient : i))
|
meal.extra_ingredients = meal.extra_ingredients.map((i) => (i == ingredient ? newIngredient : i))
|
||||||
}
|
}
|
||||||
|
|
||||||
function removePerson(list: PeopleKey, person: Person) {
|
function removePerson(list, person) {
|
||||||
meal[list] = meal[list].filter((p) => p.id !== person.id)
|
meal[list] = meal[list].filter((p) => p.id !== person.id)
|
||||||
}
|
}
|
||||||
|
|
||||||
function addPerson(list: PeopleKey, person: Person) {
|
function addPerson(list, person) {
|
||||||
addPersonIfNotExists(meal[list], person)
|
addPersonIfNotExists(meal[list], person)
|
||||||
}
|
}
|
||||||
|
|
||||||
async function selectRecipe(recipe: { id: number | string }) {
|
async function selectRecipe(recipe) {
|
||||||
// Refetch to get additional details
|
// Refetch to get additional details
|
||||||
const r = await getRecipe(recipe.id)
|
recipe = await getRecipe(recipe.id)
|
||||||
if (!r) return
|
|
||||||
|
|
||||||
if (r.createdBy) {
|
if (recipe.created_by) {
|
||||||
addPersonIfNotExists(meal.chefs, r.createdBy)
|
addPersonIfNotExists(meal.chefs, recipe.created_by)
|
||||||
addPersonIfNotExists(meal.consumers, r.createdBy)
|
addPersonIfNotExists(meal.consumers, recipe.created_by)
|
||||||
|
|
||||||
if (meal.cleanup.length === 0) {
|
if (meal.cleanup.length === 0) {
|
||||||
addPersonIfNotExists(meal.cleanup, r.createdBy)
|
addPersonIfNotExists(meal.cleanup, recipe.created_by)
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
meal.recipes.push({ recipe: r, recipeId: r.id, mealId: meal.id, servings: r.serves })
|
meal.recipes.push({ recipe, recipe_id: recipe.id, meal_id: meal.id, servings: recipe.serves })
|
||||||
}
|
}
|
||||||
|
|
||||||
async function onEditAdditionalIngredients(editing: boolean) {
|
async function onEditAdditionalIngredients(editing) {
|
||||||
if (editing && meal.extraIngredients.length === 0) {
|
if (editing && meal.extra_ingredients.length === 0) {
|
||||||
addIngredient()
|
addIngredient()
|
||||||
} else {
|
} else {
|
||||||
meal.extraIngredients = meal.extraIngredients.filter((i) => !!i.line)
|
meal.extra_ingredients = meal.extra_ingredients.filter((i) => i.line)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function showIngredient(mealRecipe, value) {
|
||||||
|
const index = meal.recipes.indexOf(mealRecipe)
|
||||||
|
const key = `${mealRecipe.recipe.id}-${index}`
|
||||||
|
if (value === undefined) {
|
||||||
|
return showIngredients[key]
|
||||||
|
}
|
||||||
|
return (showIngredients[key] = value)
|
||||||
|
}
|
||||||
|
|
||||||
|
function scaleIngredients(mealRecipe) {
|
||||||
|
return mealRecipe.recipe.ingredients.map((i) => {
|
||||||
|
return {
|
||||||
|
...i,
|
||||||
|
quantity: (i.quantity * mealRecipe.servings) / mealRecipe.recipe.serves,
|
||||||
}
|
}
|
||||||
}
|
})
|
||||||
|
|
||||||
const showMap = reactive<Record<string, boolean>>({})
|
|
||||||
function showIngredient(mealRecipe: MealRecipe, value?: boolean): boolean {
|
|
||||||
const index = meal.recipes.indexOf(mealRecipe)
|
|
||||||
const key = `${mealRecipe.recipe?.id ?? 'unknown'}-${index}`
|
|
||||||
if (value === undefined) {
|
|
||||||
return !!showMap[key]
|
|
||||||
}
|
|
||||||
showMap[key] = value
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
|
|
||||||
function scaleIngredients(mealRecipe: MealRecipe) {
|
|
||||||
const ing = mealRecipe.recipe?.ingredients ?? []
|
|
||||||
const serves = mealRecipe.recipe?.serves ?? 1
|
|
||||||
return ing.map((i) => {
|
|
||||||
return {
|
|
||||||
...i,
|
|
||||||
quantity: (i.quantity * mealRecipe.servings) / serves,
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function onSaveMeal() {
|
async function onSaveMeal() {
|
||||||
const saved = await saveMeal(toMealInput(meal))
|
const saved = await saveMeal(meal)
|
||||||
if (saved && saved.id >= 0) {
|
if (saved?.id >= 0) {
|
||||||
Object.assign(meal, saved)
|
Object.assign(meal, saved)
|
||||||
router.push(`/meals/${saved.id}`)
|
router.push(`/meals/${saved.id}`)
|
||||||
showAlert({ heading: 'Meal saved', message: 'Meal saved successfully', type: 'success' })
|
showAlert({ heading: 'Meal saved', message: 'Meal saved successfully', type: 'success' })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
showAlert({
|
showAlert({
|
||||||
heading: 'Error saving meal',
|
heading: 'Error saving meal',
|
||||||
message: 'An error occurred while saving the meal',
|
message: 'An error occurred while saving the meal',
|
||||||
type: 'error',
|
type: 'error',
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
img.icon {
|
img.icon {
|
||||||
width: 2em;
|
width: 2em;
|
||||||
height: 2em;
|
height: 2em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.persons-list {
|
.persons-list {
|
||||||
text-align: left;
|
text-align: left;
|
||||||
padding: 1ex 2em;
|
padding: 1ex 2em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.persons-list p {
|
.persons-list p {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
padding-bottom: 1em;
|
padding-bottom: 1em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.person-list li {
|
.person-list li {
|
||||||
display: inline-block;
|
display: inline-block;
|
||||||
padding-right: 1em;
|
padding-right: 1em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.container {
|
.container {
|
||||||
margin: 1em auto;
|
margin: 1em auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
ul {
|
ul {
|
||||||
list-style-type: none;
|
list-style-type: none;
|
||||||
margin: 0;
|
margin: 0;
|
||||||
padding: 0;
|
padding: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
li {
|
li {
|
||||||
padding-bottom: 0.5vh;
|
padding-bottom: 0.5vh;
|
||||||
}
|
}
|
||||||
|
|
||||||
.saved-ingredient {
|
.saved-ingredient {
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
.saved-recipe {
|
.saved-recipe {
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
.saved-ingredient p {
|
.saved-ingredient p {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
margin: 0;
|
margin: 0;
|
||||||
margin-right: 1em;
|
margin-right: 1em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.saved-recipe button:hover {
|
.saved-recipe button:hover {
|
||||||
background: #eee;
|
background: #eee;
|
||||||
}
|
}
|
||||||
|
|
||||||
.saved-recipe .recipe-card {
|
.saved-recipe .recipe-card {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.recipe-card {
|
.recipe-card {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
.servings {
|
.servings {
|
||||||
display: inline-block;
|
display: inline-block;
|
||||||
margin-right: 1em;
|
margin-right: 1em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.servings input {
|
.servings input {
|
||||||
width: 3em;
|
width: 3em;
|
||||||
border: none;
|
border: none;
|
||||||
border-bottom: 1px solid #000;
|
border-bottom: 1px solid #000;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
font-size: large;
|
font-size: large;
|
||||||
font-style: italic;
|
font-style: italic;
|
||||||
}
|
}
|
||||||
|
|
||||||
.icon-button {
|
.icon-button {
|
||||||
background: none;
|
background: none;
|
||||||
border: none;
|
border: none;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
border-radius: 1em;
|
border-radius: 1em;
|
||||||
padding: 0.5em;
|
padding: 0.5em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.icon-button:hover {
|
.icon-button:hover {
|
||||||
/* Invert the colors of the trash icon */
|
/* Invert the colors of the trash icon */
|
||||||
filter: invert(1);
|
filter: invert(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
.show-ingredient-checkbox {
|
.show-ingredient-checkbox {
|
||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.show-ingredient-checkbox+label {
|
.show-ingredient-checkbox + label {
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
background-color: #fff;
|
background-color: #fff;
|
||||||
padding: 0.5em;
|
padding: 0.5em;
|
||||||
border-radius: 1em;
|
border-radius: 1em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.show-ingredient-checkbox+label:hover {
|
.show-ingredient-checkbox + label:hover {
|
||||||
background-color: #eee;
|
background-color: #eee;
|
||||||
}
|
}
|
||||||
|
|
||||||
.show-ingredient-checkbox:checked+label {
|
.show-ingredient-checkbox:checked + label {
|
||||||
filter: invert(1);
|
filter: invert(1);
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|
|
||||||
|
|
@ -25,31 +25,21 @@
|
||||||
</span>
|
</span>
|
||||||
<span v-if="!meal.consumers.length">somebody?</span>
|
<span v-if="!meal.consumers.length">somebody?</span>
|
||||||
</p>
|
</p>
|
||||||
<p v-if="meal.purchaseDate">
|
<p v-if="meal.purchase_date">
|
||||||
Purchased {{ ago(meal.purchaseDate) }}
|
Purchased {{ ago(meal.purchase_date) }}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup>
|
||||||
import { computed } from 'vue'
|
import { computed } from 'vue'
|
||||||
import { ago } from '@/dateformats'
|
import { ago } from '@/dateformats.js'
|
||||||
|
|
||||||
type Person = { id: number; name: string }
|
const props = defineProps({
|
||||||
type MealRecipe = { recipe: { name: string } }
|
meal: { type: Object, required: true },
|
||||||
type Ingredient = { name: string }
|
})
|
||||||
type Meal = {
|
|
||||||
suggestedDate: Date | null
|
|
||||||
chefs: Person[]
|
|
||||||
consumers: Person[]
|
|
||||||
recipes?: MealRecipe[]
|
|
||||||
extraIngredients?: Ingredient[]
|
|
||||||
purchaseDate?: Date | null
|
|
||||||
}
|
|
||||||
|
|
||||||
const props = defineProps<{ meal: Meal }>()
|
function englishSeperator(index, list) {
|
||||||
|
|
||||||
function englishSeperator(index: number, list: Array<unknown>) {
|
|
||||||
switch (index) {
|
switch (index) {
|
||||||
case list.length - 1:
|
case list.length - 1:
|
||||||
return ''
|
return ''
|
||||||
|
|
@ -60,7 +50,7 @@ function englishSeperator(index: number, list: Array<unknown>) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function englishList(list: string[]) {
|
function englishList(list) {
|
||||||
switch (list.length) {
|
switch (list.length) {
|
||||||
case 0:
|
case 0:
|
||||||
return ''
|
return ''
|
||||||
|
|
@ -74,20 +64,19 @@ function englishList(list: string[]) {
|
||||||
}
|
}
|
||||||
|
|
||||||
const date = computed(() =>
|
const date = computed(() =>
|
||||||
props.meal.suggestedDate
|
props.meal.suggested_date.toLocaleDateString('en-au', {
|
||||||
? props.meal.suggestedDate.toLocaleDateString('en-au', { month: 'numeric', day: 'numeric' })
|
month: 'numeric',
|
||||||
: ''
|
day: 'numeric',
|
||||||
|
})
|
||||||
)
|
)
|
||||||
|
|
||||||
const dayOfWeek = computed(() =>
|
const dayOfWeek = computed(() =>
|
||||||
props.meal.suggestedDate ? props.meal.suggestedDate.toLocaleDateString('en-au', { weekday: 'long' }) : ''
|
props.meal.suggested_date.toLocaleDateString('en-au', { weekday: 'long' })
|
||||||
)
|
)
|
||||||
|
|
||||||
const mealTitle = computed(() => {
|
const mealTitle = computed(() => {
|
||||||
const recipes = props.meal.recipes ?? []
|
const recipesText = englishList(props.meal.recipes.map((mr) => mr.recipe.name))
|
||||||
const extras = props.meal.extraIngredients ?? []
|
const ingredientsText = englishList(props.meal.extra_ingredients.map((i) => i.name))
|
||||||
const recipesText = englishList(recipes.map((mr) => mr.recipe.name))
|
|
||||||
const ingredientsText = englishList(extras.map((i) => i.name))
|
|
||||||
|
|
||||||
if (recipesText && ingredientsText) return `${recipesText} with ${ingredientsText}`
|
if (recipesText && ingredientsText) return `${recipesText} with ${ingredientsText}`
|
||||||
if (recipesText || ingredientsText) return recipesText || ingredientsText
|
if (recipesText || ingredientsText) return recipesText || ingredientsText
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,13 @@
|
||||||
class="toggle-actions"
|
class="toggle-actions"
|
||||||
@click="selectedMeal = meal == selectedMeal ? null : meal"
|
@click="selectedMeal = meal == selectedMeal ? null : meal"
|
||||||
>
|
>
|
||||||
<img :src="meal == selectedMeal ? chevronDown : chevronUp">
|
<img
|
||||||
|
:src="
|
||||||
|
meal == selectedMeal
|
||||||
|
? require('@/assets/chevron-down.svg')
|
||||||
|
: require('@/assets/chevron-up.svg')
|
||||||
|
"
|
||||||
|
>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<ul
|
<ul
|
||||||
|
|
@ -44,7 +50,7 @@
|
||||||
</div>
|
</div>
|
||||||
<action-item
|
<action-item
|
||||||
title="Plan Meal"
|
title="Plan Meal"
|
||||||
:image="planMeal"
|
:image="require('@/assets/plan-meal.svg')"
|
||||||
@click="() => $router.push('/meals/add')"
|
@click="() => $router.push('/meals/add')"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -55,9 +61,6 @@ import { ref, onBeforeMount } from 'vue'
|
||||||
import ActionItem from '@/components/ActionItem.vue'
|
import ActionItem from '@/components/ActionItem.vue'
|
||||||
import MealCard from '@/components/meals/MealCard.vue'
|
import MealCard from '@/components/meals/MealCard.vue'
|
||||||
import { getUpcomingMeals, markMealConsumed, deleteMeal } from '@/composables/useMeals'
|
import { getUpcomingMeals, markMealConsumed, deleteMeal } from '@/composables/useMeals'
|
||||||
const chevronDown = new URL('@/assets/chevron-down.svg', import.meta.url).toString()
|
|
||||||
const chevronUp = new URL('@/assets/chevron-up.svg', import.meta.url).toString()
|
|
||||||
const planMeal = new URL('@/assets/plan-meal.svg', import.meta.url).toString()
|
|
||||||
|
|
||||||
const from = new Date()
|
const from = new Date()
|
||||||
from.setTime(0)
|
from.setTime(0)
|
||||||
|
|
|
||||||
|
|
@ -48,47 +48,34 @@
|
||||||
</span>
|
</span>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup>
|
||||||
import { ref, watch } from 'vue'
|
import { ref, watch } from 'vue'
|
||||||
import { searchPersons } from '@/api/sdk'
|
import { searchPerson } from '@/api/persons'
|
||||||
import type { Person } from '@/domain/types'
|
|
||||||
const props = withDefaults(defineProps<{ people?: Person[] }>(), { people: () => [] })
|
const props = defineProps({
|
||||||
const emit = defineEmits<{
|
people: { type: Array, default: () => [] },
|
||||||
(e: 'add-person', person: Person): void
|
})
|
||||||
(e: 'remove-person', person: Person): void
|
const emit = defineEmits(['add-person', 'remove-person'])
|
||||||
}>()
|
|
||||||
|
|
||||||
const isAddingPerson = ref(false)
|
const isAddingPerson = ref(false)
|
||||||
const searchName = ref('')
|
const searchName = ref('')
|
||||||
const searchResults = ref<Person[]>([])
|
const searchResults = ref([])
|
||||||
|
|
||||||
// Template refs for DOM elements
|
// Template refs for DOM elements
|
||||||
const searchNameInput = ref<HTMLInputElement | null>(null)
|
const searchNameInput = ref(null)
|
||||||
const persondroplist = ref<HTMLUListElement | null>(null)
|
const persondroplist = ref(null)
|
||||||
|
|
||||||
async function updateSearchResults() {
|
async function updateSearchResults() {
|
||||||
const q = searchName.value.trim()
|
const results = await searchPerson(searchName.value)
|
||||||
if (!q) {
|
|
||||||
searchResults.value = []
|
|
||||||
return
|
|
||||||
}
|
|
||||||
const page = await searchPersons(q)
|
|
||||||
const results: Person[] = page.items.map((p) => ({ id: p.id, name: p.name }))
|
|
||||||
const idSet = new Set(props.people.map((p) => p.id))
|
const idSet = new Set(props.people.map((p) => p.id))
|
||||||
searchResults.value = results.filter((p: Person) => !idSet.has(p.id))
|
searchResults.value = results.filter((p) => !idSet.has(p.id))
|
||||||
}
|
}
|
||||||
|
|
||||||
function addPerson(person?: Person) {
|
function addPerson(person) {
|
||||||
if (!person && searchResults.value.length > 0) {
|
if (!person && searchResults.value.length > 0) {
|
||||||
person = searchResults.value[0]
|
person = searchResults.value[0]
|
||||||
}
|
}
|
||||||
if (!person) {
|
if (person?.id >= 0 && !props.people.find((p) => p.id === person.id)) {
|
||||||
searchName.value = ''
|
|
||||||
searchResults.value = []
|
|
||||||
isAddingPerson.value = false
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (!props.people.find((p) => p.id === person.id)) {
|
|
||||||
emit('add-person', person)
|
emit('add-person', person)
|
||||||
}
|
}
|
||||||
searchName.value = ''
|
searchName.value = ''
|
||||||
|
|
@ -96,7 +83,7 @@ function addPerson(person?: Person) {
|
||||||
isAddingPerson.value = false
|
isAddingPerson.value = false
|
||||||
}
|
}
|
||||||
|
|
||||||
function removePerson(person: Person) {
|
function removePerson(person) {
|
||||||
emit('remove-person', person)
|
emit('remove-person', person)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -68,31 +68,28 @@
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup>
|
||||||
import { ref, computed, onMounted, watch } from 'vue'
|
import { ref, computed, onMounted, watch } from 'vue'
|
||||||
import { useRouter, useRoute } from 'vue-router'
|
import { useRouter, useRoute } from 'vue-router'
|
||||||
import { useAlert } from '@/composables/useAlert'
|
import { useAlert } from '@/composables/useAlert'
|
||||||
import { parseQueryString } from '@/router/helpers'
|
import { getRecipe, parseRecipe, saveRecipe as saveRecipeApi, deleteRecipe as deleteRecipeApi } from '@/api/recipes'
|
||||||
import { getRecipe, parseRecipe, saveRecipe as saveRecipeApi, deleteRecipe as deleteRecipeApi } from '@/api/sdk'
|
|
||||||
import EditableIngredientsPanel from '@/components/ingredients/EditableIngredientsPanel.vue'
|
import EditableIngredientsPanel from '@/components/ingredients/EditableIngredientsPanel.vue'
|
||||||
import type { Recipe as DomainRecipe, Ingredient, RecipeInput } from '@/domain/types'
|
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
id: { type: String, required: false, default: undefined },
|
id: { type: Number, required: false },
|
||||||
})
|
})
|
||||||
|
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const route = useRoute()
|
const route = useRoute()
|
||||||
const { show: showAlert } = useAlert()
|
const { show: showAlert } = useAlert()
|
||||||
|
|
||||||
const link = ref<string>(parseQueryString(route.query.url))
|
const link = ref(route.query.url ?? '')
|
||||||
const parse_failed = ref(false)
|
const parse_failed = ref(false)
|
||||||
const recipe = ref<DomainRecipe | null>(null)
|
const recipe = ref(null)
|
||||||
|
|
||||||
const image_styling = computed(() => {
|
const image_styling = computed(() => {
|
||||||
const urls = recipe.value?.imageUrls ?? []
|
if (recipe.value?.image_urls && recipe.value.image_urls[0]) {
|
||||||
if (urls.length && urls[0]) {
|
const image = recipe.value.image_urls[0]
|
||||||
const image = urls[0]!
|
|
||||||
return {
|
return {
|
||||||
background: `linear-gradient(to bottom, rgba(255, 255, 255, 0.8) 0%, rgba(255, 255, 255, 0) 100%), url('${image}') center/cover no-repeat`,
|
background: `linear-gradient(to bottom, rgba(255, 255, 255, 0.8) 0%, rgba(255, 255, 255, 0) 100%), url('${image}') center/cover no-repeat`,
|
||||||
}
|
}
|
||||||
|
|
@ -106,36 +103,31 @@ function parseLink() {
|
||||||
}
|
}
|
||||||
|
|
||||||
async function refreshRecipe() {
|
async function refreshRecipe() {
|
||||||
const id = props.id ? parseInt(props.id) : null
|
if (props.id >= 0) {
|
||||||
if (id !== null && id >= 0) {
|
recipe.value = await getRecipe(props.id)
|
||||||
const r = await getRecipe(id)
|
link.value = recipe.value.link
|
||||||
recipe.value = r
|
|
||||||
link.value = r?.link ?? ''
|
|
||||||
return
|
return
|
||||||
} else if (link.value) {
|
} else if (link.value) {
|
||||||
const r = await parseRecipe(link.value)
|
recipe.value = await parseRecipe(link.value)
|
||||||
recipe.value = r
|
parse_failed.value = !recipe.value
|
||||||
parse_failed.value = !r
|
|
||||||
} else {
|
} else {
|
||||||
recipe.value = null
|
recipe.value = null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function updateIngredient(ingredient: Ingredient, newIngredient: Ingredient) {
|
async function updateIngredient(ingredient, newIngredient) {
|
||||||
if (!recipe.value) return
|
recipe.value.ingredients = recipe.value.ingredients.map((i) =>
|
||||||
const list = recipe.value.ingredients ?? []
|
i == ingredient ? newIngredient : i
|
||||||
recipe.value = { ...recipe.value, ingredients: list.map((i) => (i === ingredient ? newIngredient : i)) }
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function deleteIngredient(ingredient: Ingredient) {
|
function deleteIngredient(ingredient) {
|
||||||
if (!recipe.value) return
|
recipe.value.ingredients = recipe.value.ingredients.filter((i) => i != ingredient)
|
||||||
const list = recipe.value.ingredients ?? []
|
|
||||||
recipe.value = { ...recipe.value, ingredients: list.filter((i) => i !== ingredient) }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function saveRecipe() {
|
async function saveRecipe() {
|
||||||
const saved = recipe.value ? await saveRecipeApi(toRecipeInput(recipe.value)) : null
|
const saved = await saveRecipeApi(recipe.value)
|
||||||
if (saved && saved.id >= 0) {
|
if (saved?.id >= 0) {
|
||||||
showAlert({ heading: 'Recipe saved', message: 'Your recipe has been saved', type: 'success' })
|
showAlert({ heading: 'Recipe saved', message: 'Your recipe has been saved', type: 'success' })
|
||||||
router.push(`/recipes/${saved.id}`)
|
router.push(`/recipes/${saved.id}`)
|
||||||
return
|
return
|
||||||
|
|
@ -147,26 +139,19 @@ function createFromScratch() {
|
||||||
recipe.value = {
|
recipe.value = {
|
||||||
id: -1,
|
id: -1,
|
||||||
name: 'My new recipe',
|
name: 'My new recipe',
|
||||||
createdById: -1,
|
created_by_id: -1,
|
||||||
link: '',
|
link: '',
|
||||||
ingredients: [],
|
ingredients: [],
|
||||||
imageUrls: [],
|
image_urls: [],
|
||||||
serves: 1,
|
|
||||||
dateCreated: new Date(),
|
|
||||||
dateHidden: null,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function addIngredient() {
|
function addIngredient() {
|
||||||
if (!recipe.value) return
|
recipe.value.ingredients = [{ line: '', product: null }, ...recipe.value.ingredients]
|
||||||
const list = recipe.value.ingredients ?? []
|
|
||||||
const draft: Ingredient = { id: -1, name: '', line: '', unit: 'Items', quantity: 0, preparation: '', productId: null, recipeId: null, mealId: null, product: null }
|
|
||||||
recipe.value = { ...recipe.value, ingredients: [draft, ...list] }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function deleteRecipe() {
|
async function deleteRecipe() {
|
||||||
if (confirm('Are you sure you want to delete this recipe?')) {
|
if (confirm('Are you sure you want to delete this recipe?')) {
|
||||||
if (!recipe.value) return
|
|
||||||
await deleteRecipeApi(recipe.value.id)
|
await deleteRecipeApi(recipe.value.id)
|
||||||
router.push('/recipes')
|
router.push('/recipes')
|
||||||
}
|
}
|
||||||
|
|
@ -180,32 +165,14 @@ onMounted(() => {
|
||||||
watch(
|
watch(
|
||||||
() => route.query.url,
|
() => route.query.url,
|
||||||
(newUrl) => {
|
(newUrl) => {
|
||||||
const parsed = parseQueryString(newUrl)
|
if (typeof newUrl === 'string') {
|
||||||
if (parsed) {
|
link.value = newUrl
|
||||||
link.value = parsed
|
|
||||||
refreshRecipe()
|
refreshRecipe()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
// expose functions for template binding names (automatic in <script setup>)
|
// expose functions for template binding names (automatic in <script setup>)
|
||||||
function toRecipeInput(r: DomainRecipe): RecipeInput {
|
|
||||||
return {
|
|
||||||
id: r.id,
|
|
||||||
name: r.name,
|
|
||||||
link: r.link,
|
|
||||||
serves: r.serves,
|
|
||||||
imageUrls: r.imageUrls ?? [],
|
|
||||||
ingredients: r.ingredients ?? [],
|
|
||||||
basedOnRecipe: r.basedOnRecipe ?? null,
|
|
||||||
// let backend set created/hidden dates
|
|
||||||
createdById: r.createdById,
|
|
||||||
createdBy: r.createdBy ?? null,
|
|
||||||
// dateHidden omitted
|
|
||||||
hiddenById: r.hiddenById ?? null,
|
|
||||||
hiddenBy: r.hiddenBy ?? null,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
|
|
|
||||||
|
|
@ -2,12 +2,12 @@
|
||||||
<div class="recipe-card">
|
<div class="recipe-card">
|
||||||
<p>
|
<p>
|
||||||
<img
|
<img
|
||||||
v-if="recipe.imageUrls && recipe.imageUrls.length"
|
v-if="recipe.image_urls"
|
||||||
:src="recipe.imageUrls[0] || fallbackEgg"
|
:src="recipe.image_urls[0]"
|
||||||
>
|
>
|
||||||
<img
|
<img
|
||||||
v-else
|
v-else
|
||||||
:src="fallbackEgg"
|
src="@/assets/egg.svg"
|
||||||
>
|
>
|
||||||
</p>
|
</p>
|
||||||
<p class="recipe-name">
|
<p class="recipe-name">
|
||||||
|
|
@ -16,12 +16,10 @@
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup>
|
||||||
import type { RecipeOut } from '@/domain/types'
|
defineProps({
|
||||||
type RecipeCardItem = Pick<RecipeOut, 'id' | 'name' | 'imageUrls'>
|
recipe: { type: Object, required: true },
|
||||||
|
})
|
||||||
defineProps<{ recipe: RecipeCardItem }>()
|
|
||||||
const fallbackEgg = new URL('@/assets/egg.svg', import.meta.url).toString()
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
|
|
|
||||||
|
|
@ -6,91 +6,42 @@
|
||||||
<input
|
<input
|
||||||
v-model="searchTerm"
|
v-model="searchTerm"
|
||||||
type="text"
|
type="text"
|
||||||
:placeholder="placeholderText"
|
:placeholder="placeholder"
|
||||||
@keyup.enter="search"
|
@keyup.enter="search"
|
||||||
@keyup.esc="clear"
|
@keyup.esc="clear"
|
||||||
@focusin="search"
|
@focusin="search"
|
||||||
>
|
>
|
||||||
<ul
|
<ul
|
||||||
v-if="dropdownVisible"
|
v-if="recipes?.length"
|
||||||
class="dropdown"
|
class="dropdown"
|
||||||
>
|
>
|
||||||
<template v-if="recipes.length">
|
|
||||||
<li
|
|
||||||
v-for="recipe in recipes"
|
|
||||||
:key="recipe.id"
|
|
||||||
class="recipe"
|
|
||||||
@mousedown="selectRecipe(recipe)"
|
|
||||||
>
|
|
||||||
<recipe-card :recipe="recipe" />
|
|
||||||
</li>
|
|
||||||
<li
|
|
||||||
v-if="prevCursor || nextCursor"
|
|
||||||
class="pager"
|
|
||||||
>
|
|
||||||
<button
|
|
||||||
class="pager-btn"
|
|
||||||
:disabled="!prevCursor"
|
|
||||||
@mousedown.prevent="loadPrev"
|
|
||||||
>
|
|
||||||
Prev
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
class="pager-btn"
|
|
||||||
:disabled="!nextCursor"
|
|
||||||
@mousedown.prevent="loadNext"
|
|
||||||
>
|
|
||||||
Next
|
|
||||||
</button>
|
|
||||||
</li>
|
|
||||||
</template>
|
|
||||||
<li
|
<li
|
||||||
v-else
|
v-for="recipe in recipes"
|
||||||
class="empty"
|
:key="recipe.id"
|
||||||
|
class="recipe"
|
||||||
|
@mousedown="selectRecipe(recipe)"
|
||||||
>
|
>
|
||||||
No recipes found
|
<recipe-card :recipe="recipe" />
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup>
|
||||||
import { ref, watch, onBeforeUnmount, computed } from 'vue'
|
import { ref, watch, onBeforeUnmount } from 'vue'
|
||||||
import { listRecipes } from '@/api/sdk'
|
import { searchRecipes } from '@/api/recipes'
|
||||||
import type { Recipe } from '@/domain/types'
|
|
||||||
import { useAlert } from '@/composables/useAlert'
|
|
||||||
import { usePagination } from '@/composables/usePagination'
|
|
||||||
import RecipeCard from './RecipeCard.vue'
|
import RecipeCard from './RecipeCard.vue'
|
||||||
|
|
||||||
const props = withDefaults(defineProps<{ placeholder?: string }>(), {
|
defineProps({
|
||||||
placeholder: 'Add a recipe...',
|
placeholder: { type: String, default: 'Add a recipe...' },
|
||||||
})
|
})
|
||||||
const placeholderText: string = props.placeholder ?? 'Add a recipe...'
|
|
||||||
|
|
||||||
type RecipeItem = Pick<Recipe, 'id' | 'name' | 'imageUrls'>
|
const emit = defineEmits(['select-recipe'])
|
||||||
const emit = defineEmits<{
|
|
||||||
(e: 'select-recipe', recipe: RecipeItem): void
|
|
||||||
}>()
|
|
||||||
|
|
||||||
const searchTerm = ref('')
|
const searchTerm = ref('')
|
||||||
const pageSize = 10
|
const recipes = ref([])
|
||||||
const { items: recipes, next: nextCursor, prev: prevCursor, load, loadNext: loadNextPage, loadPrev: loadPrevPage, reset } = usePagination<RecipeItem>(
|
|
||||||
async (params) => {
|
|
||||||
const page = await listRecipes(params)
|
|
||||||
return {
|
|
||||||
items: (page.items ?? []).map(toRecipeItem),
|
|
||||||
next: page.next ?? null,
|
|
||||||
prev: page.prev ?? null,
|
|
||||||
total: page.total ?? null,
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{ pageSize }
|
|
||||||
)
|
|
||||||
const dropdownVisible = computed(() => recipes.value.length > 0 || (searchTerm.value.length > 0))
|
|
||||||
|
|
||||||
const { show: showAlert, scheduleAutoDismiss } = useAlert()
|
let debounceId = null
|
||||||
|
|
||||||
let debounceId: ReturnType<typeof setTimeout> | null = null
|
|
||||||
|
|
||||||
watch(
|
watch(
|
||||||
searchTerm,
|
searchTerm,
|
||||||
|
|
@ -110,41 +61,11 @@ watch(
|
||||||
)
|
)
|
||||||
|
|
||||||
async function search() {
|
async function search() {
|
||||||
try {
|
const result = await searchRecipes(searchTerm.value)
|
||||||
await load({ q: searchTerm.value })
|
recipes.value = result ?? recipes.value
|
||||||
} catch {
|
|
||||||
// swallow errors and clear suggestions on failures, also notify user
|
|
||||||
reset()
|
|
||||||
showAlert({ type: 'error', heading: 'Recipe search failed', message: 'Please try again shortly.' })
|
|
||||||
scheduleAutoDismiss()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadNext() {
|
function selectRecipe(recipe) {
|
||||||
if (!nextCursor.value) return
|
|
||||||
try {
|
|
||||||
await loadNextPage()
|
|
||||||
} catch {
|
|
||||||
showAlert({ type: 'error', heading: 'Unable to load more', message: 'Could not fetch the next page.' })
|
|
||||||
scheduleAutoDismiss()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function loadPrev() {
|
|
||||||
if (!prevCursor.value) return
|
|
||||||
try {
|
|
||||||
await loadPrevPage()
|
|
||||||
} catch {
|
|
||||||
showAlert({ type: 'error', heading: 'Unable to load more', message: 'Could not fetch the previous page.' })
|
|
||||||
scheduleAutoDismiss()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function toRecipeItem(r: Recipe): RecipeItem {
|
|
||||||
return { id: r.id, name: r.name, imageUrls: r.imageUrls ?? [] }
|
|
||||||
}
|
|
||||||
|
|
||||||
function selectRecipe(recipe: RecipeItem) {
|
|
||||||
emit('select-recipe', recipe)
|
emit('select-recipe', recipe)
|
||||||
searchTerm.value = ''
|
searchTerm.value = ''
|
||||||
recipes.value = []
|
recipes.value = []
|
||||||
|
|
@ -152,12 +73,11 @@ function selectRecipe(recipe: RecipeItem) {
|
||||||
|
|
||||||
function clear() {
|
function clear() {
|
||||||
searchTerm.value = ''
|
searchTerm.value = ''
|
||||||
reset()
|
recipes.value = []
|
||||||
}
|
}
|
||||||
|
|
||||||
function onFocusOut() {
|
function onFocusOut() {
|
||||||
// keep results while focused; on blur, clear all
|
recipes.value = []
|
||||||
reset()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
onBeforeUnmount(() => {
|
onBeforeUnmount(() => {
|
||||||
|
|
@ -209,19 +129,4 @@ onBeforeUnmount(() => {
|
||||||
.recipe-search-box .dropdown li:hover {
|
.recipe-search-box .dropdown li:hover {
|
||||||
background-color: #eee;
|
background-color: #eee;
|
||||||
}
|
}
|
||||||
|
|
||||||
.recipe-search-box .dropdown .pager {
|
|
||||||
display: flex;
|
|
||||||
justify-content: space-between;
|
|
||||||
gap: 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.recipe-search-box .dropdown .pager-btn {
|
|
||||||
width: 48%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.recipe-search-box .dropdown .empty {
|
|
||||||
padding: 8px;
|
|
||||||
color: #666;
|
|
||||||
}
|
|
||||||
</style>
|
</style>
|
||||||
|
|
|
||||||
|
|
@ -6,22 +6,19 @@
|
||||||
/>
|
/>
|
||||||
<action-item
|
<action-item
|
||||||
title="Add new Recipe"
|
title="Add new Recipe"
|
||||||
:image="addRecipe"
|
:image="require('@/assets/add-recipe.svg')"
|
||||||
@click="onAddRecipe"
|
@click="onAddRecipe"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
<script setup lang="ts">
|
<script setup>
|
||||||
import { useRouter } from 'vue-router'
|
import { useRouter } from 'vue-router'
|
||||||
import ActionItem from '@/components/ActionItem.vue'
|
import ActionItem from '@/components/ActionItem.vue'
|
||||||
import RecipeSearchBox from './RecipeSearchBox.vue'
|
import RecipeSearchBox from './RecipeSearchBox.vue'
|
||||||
import type { Recipe } from '@/domain/types'
|
|
||||||
|
|
||||||
const addRecipe = new URL('@/assets/add-recipe.svg', import.meta.url).toString()
|
|
||||||
|
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
|
|
||||||
function onSelectRecipe(r: Pick<Recipe, 'id'>) {
|
function onSelectRecipe(r) {
|
||||||
router.push(`/recipes/${r.id}`)
|
router.push(`/recipes/${r.id}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -12,7 +12,7 @@
|
||||||
<ul class="full-shopping-list">
|
<ul class="full-shopping-list">
|
||||||
<li
|
<li
|
||||||
v-for="group in outstandingItemGroups"
|
v-for="group in outstandingItemGroups"
|
||||||
:key="groupKey(group)"
|
:key="group.id"
|
||||||
class="selectable"
|
class="selectable"
|
||||||
:class="{ selected: isSelected(group) }"
|
:class="{ selected: isSelected(group) }"
|
||||||
@click="toggleSelect(group)"
|
@click="toggleSelect(group)"
|
||||||
|
|
@ -53,7 +53,7 @@
|
||||||
<ul class="full-shopping-list">
|
<ul class="full-shopping-list">
|
||||||
<li
|
<li
|
||||||
v-for="item in purchasedItemGroups"
|
v-for="item in purchasedItemGroups"
|
||||||
:key="groupKey(item)"
|
:key="item.id"
|
||||||
>
|
>
|
||||||
<shopping-list-item :shopping-list-item-group="item" />
|
<shopping-list-item :shopping-list-item-group="item" />
|
||||||
</li>
|
</li>
|
||||||
|
|
@ -74,7 +74,7 @@
|
||||||
class="footer-buttons"
|
class="footer-buttons"
|
||||||
>
|
>
|
||||||
<p v-if="selected.length === 1">
|
<p v-if="selected.length === 1">
|
||||||
Mark '{{ selected[0] ? groupLabel(selected[0]) : '' }}' as
|
Mark '{{ selected[0].product?.name ?? selected[0].name }}' as
|
||||||
</p>
|
</p>
|
||||||
<p v-else>
|
<p v-else>
|
||||||
Mark {{ selected.length }} items as
|
Mark {{ selected.length }} items as
|
||||||
|
|
@ -82,87 +82,80 @@
|
||||||
|
|
||||||
<div class="button-group">
|
<div class="button-group">
|
||||||
<button @click="markFound">
|
<button @click="markFound">
|
||||||
<img :src="houseCheck"><br>
|
<img src="@/assets/house-check.svg"><br>
|
||||||
Found
|
Found
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<button @click="markPurchased">
|
<button @click="markPurchased">
|
||||||
<img :src="shoppingCart"><br>
|
<img src="@/assets/shopping-cart.svg"><br>
|
||||||
Purchased
|
Purchased
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<button @click="selected = []">
|
<button @click="selected = []">
|
||||||
<img :src="closeIcon"><br>
|
<img src="@/assets/close.svg"><br>
|
||||||
Cancel
|
Cancel
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup>
|
||||||
import { ref, computed, onBeforeMount } from 'vue'
|
import { ref, computed, onBeforeMount } from 'vue'
|
||||||
import { useRouter } from 'vue-router'
|
import { useRouter } from 'vue-router'
|
||||||
import { useAlert } from '@/composables/useAlert'
|
import { useAlert } from '@/composables/useAlert'
|
||||||
import { useShopping } from '@/composables/useShopping'
|
import { useShopping } from '@/composables/useShopping'
|
||||||
import { useMeals } from '@/composables/useMeals'
|
import { getUpcomingMeals } from '@/api/meals'
|
||||||
import { type Group } from '@/composables/useShopping'
|
import { itemsToGroups, uniqueMeals } from './shopping.js'
|
||||||
type UIMeal = import('@/domain/types').Meal
|
|
||||||
import MealSelectionList from './MealSelectionList.vue'
|
import MealSelectionList from './MealSelectionList.vue'
|
||||||
import ShoppingListItem from './ShoppingListItem.vue'
|
import ShoppingListItem from './ShoppingListItem.vue'
|
||||||
|
|
||||||
const houseCheck = new URL('@/assets/house-check.svg', import.meta.url).toString()
|
|
||||||
const shoppingCart = new URL('@/assets/shopping-cart.svg', import.meta.url).toString()
|
|
||||||
const closeIcon = new URL('@/assets/close.svg', import.meta.url).toString()
|
|
||||||
|
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const { show: showAlert } = useAlert()
|
const { show: showAlert } = useAlert()
|
||||||
const { getCurrentShoppingList, requestMeal, unrequestMeal, purchaseFromGroups, groupsFrom, mealsFrom } = useShopping()
|
const { getCurrentShoppingList, requestMeal, unrequestMeal, purchaseFromGroups } = useShopping()
|
||||||
const { getUpcomingMeals } = useMeals()
|
|
||||||
|
|
||||||
const from = new Date()
|
const from = new Date()
|
||||||
from.setTime(0)
|
from.setTime(0)
|
||||||
const to = new Date()
|
const to = new Date()
|
||||||
to.setDate(to.getDate() + 7)
|
to.setDate(to.getDate() + 7)
|
||||||
|
|
||||||
type Meal = import('@/domain/types').Meal
|
const shoppingList = ref(null)
|
||||||
const shoppingList = ref<import('@/domain/types').CurrentShoppingListDTO | null>(null)
|
const upcomingMeals = ref([])
|
||||||
const upcomingMeals = ref<Meal[]>([])
|
const selected = ref([])
|
||||||
const selected = ref<Group[]>([])
|
|
||||||
const showPurchased = ref(false)
|
const showPurchased = ref(false)
|
||||||
|
|
||||||
const groupsMatch = (a: Group, b: Group) => {
|
const groupsMatch = (a, b) => {
|
||||||
if (a.type !== b.type) return false
|
if (!!a.product != !!b.product) return false
|
||||||
if (a.type === 'name' && b.type === 'name') return a.name === b.name
|
if (a.name) return a.name === b.name
|
||||||
if (a.type === 'product' && b.type === 'product') return a.product.id === b.product.id
|
return a.product.id === b.product.id
|
||||||
return false
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const outstandingItemGroups = computed<Group[]>(() => groupsFrom(shoppingList.value?.outstandingItems))
|
const outstandingItemGroups = computed(() =>
|
||||||
const purchasedItemGroups = computed<Group[]>(() => groupsFrom(shoppingList.value?.purchasedItems))
|
itemsToGroups(shoppingList.value?.outstanding_items ?? [])
|
||||||
const purchasedMeals = computed<UIMeal[]>(() => mealsFrom(shoppingList.value?.purchasedItems))
|
)
|
||||||
|
const purchasedItemGroups = computed(() => itemsToGroups(shoppingList.value?.purchased_items ?? []))
|
||||||
|
const purchasedMeals = computed(() => uniqueMeals(shoppingList.value?.purchased_items ?? []))
|
||||||
const availableMeals = computed(() => {
|
const availableMeals = computed(() => {
|
||||||
const lookup: Record<string | number, Meal> = shoppingList.value?.mealsLookup ?? {}
|
const meals = { ...(shoppingList.value?.meals_lookup ?? {}) }
|
||||||
const meals: Record<string | number, Meal> = { ...lookup }
|
|
||||||
upcomingMeals.value?.forEach((m) => {
|
upcomingMeals.value?.forEach((m) => {
|
||||||
if (!meals[m.id]) meals[m.id] = m
|
if (!meals[m.id]) meals[m.id] = m
|
||||||
})
|
})
|
||||||
return Object.values(meals)
|
return Object.values(meals)
|
||||||
.filter((m) => !m.purchaseDate)
|
.filter((m) => !m.purchase_date)
|
||||||
.sort((a, b) => ((a.suggestedDate && a.suggestedDate.getTime()) || 0) - ((b.suggestedDate && b.suggestedDate.getTime()) || 0))
|
.sort((a, b) => a.suggested_date - b.suggested_date)
|
||||||
})
|
})
|
||||||
const includedMeals = computed(() => (shoppingList.value?.requestedMeals ?? []).map((i) => i.meal).filter((m): m is Meal => !!m))
|
const includedMeals = computed(() => shoppingList.value?.requested_meals.map((m) => m.meal) ?? [])
|
||||||
|
|
||||||
async function loadData() {
|
async function loadData() {
|
||||||
upcomingMeals.value = await getUpcomingMeals(from, to)
|
upcomingMeals.value = await getUpcomingMeals(from, to)
|
||||||
shoppingList.value = await getCurrentShoppingList()
|
shoppingList.value = await getCurrentShoppingList()
|
||||||
}
|
}
|
||||||
|
|
||||||
async function mealSelected(meal: { id: number }) {
|
async function mealSelected(meal) {
|
||||||
await requestMeal(meal.id)
|
await requestMeal(meal.id)
|
||||||
await loadData()
|
await loadData()
|
||||||
}
|
}
|
||||||
|
|
||||||
async function mealUnselected(meal: { id: number }) {
|
async function mealUnselected(meal) {
|
||||||
await unrequestMeal(meal.id)
|
await unrequestMeal(meal.id)
|
||||||
await loadData()
|
await loadData()
|
||||||
}
|
}
|
||||||
|
|
@ -187,28 +180,16 @@ async function markPurchased() {
|
||||||
router.push(`/shopping/${shopping.id}`)
|
router.push(`/shopping/${shopping.id}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
function toggleSelect(item: Group) {
|
function toggleSelect(item) {
|
||||||
const index = selected.value.findIndex((i) => groupsMatch(i, item))
|
const index = selected.value.findIndex((i) => groupsMatch(i, item))
|
||||||
if (index === -1) selected.value.push(item)
|
if (index === -1) selected.value.push(item)
|
||||||
else selected.value.splice(index, 1)
|
else selected.value.splice(index, 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
function isSelected(item: Group) {
|
function isSelected(item) {
|
||||||
return selected.value.some((i) => groupsMatch(i, item))
|
return selected.value.some((i) => groupsMatch(i, item))
|
||||||
}
|
}
|
||||||
|
|
||||||
function groupKey(group: Group) {
|
|
||||||
if (group.type === 'product') return `p-${group.product.id}`
|
|
||||||
if (group.type === 'name') return `n-${group.name}`
|
|
||||||
return Math.random().toString(36)
|
|
||||||
}
|
|
||||||
|
|
||||||
function groupLabel(group: Group) {
|
|
||||||
if (group.type === 'product') return group.product.name ?? 'item'
|
|
||||||
if (group.type === 'name') return group.name
|
|
||||||
return 'item'
|
|
||||||
}
|
|
||||||
|
|
||||||
onBeforeMount(loadData)
|
onBeforeMount(loadData)
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -7,35 +7,31 @@
|
||||||
<!-- Have a checkbox and card for each meal, show the image and name -->
|
<!-- Have a checkbox and card for each meal, show the image and name -->
|
||||||
<!-- Emit meal-selected event on checked and meal-unselected on unchecked -->
|
<!-- Emit meal-selected event on checked and meal-unselected on unchecked -->
|
||||||
<input
|
<input
|
||||||
:id="String(meal.id)"
|
:id="meal.id"
|
||||||
type="checkbox"
|
type="checkbox"
|
||||||
:checked="isChecked(meal)"
|
:checked="isChecked(meal)"
|
||||||
:disabled="!!disabled"
|
:disabled="disabled"
|
||||||
@change="mealCheckChanged"
|
@change="mealCheckChanged"
|
||||||
>
|
>
|
||||||
<label
|
<label
|
||||||
:for="String(meal.id)"
|
:for="meal.id"
|
||||||
:style="getImageStyling(meal)"
|
:style="getImageStyling(meal)"
|
||||||
>
|
>
|
||||||
{{ formatDate(meal.suggestedDate) }}
|
{{ formatDate(meal.suggested_date) }}
|
||||||
</label>
|
</label>
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup>
|
||||||
import type { Meal } from '@/domain/types'
|
const props = defineProps({
|
||||||
|
meals: { type: Array, required: true },
|
||||||
|
checked: { type: Array, required: true },
|
||||||
|
disabled: { type: Boolean, default: false },
|
||||||
|
})
|
||||||
|
const emit = defineEmits(['meal-selected', 'meal-unselected'])
|
||||||
|
|
||||||
// MealSelectionList only needs minimal fields from Meal; recipes and extraIngredients are optional for image lookup
|
const nth = (d) => {
|
||||||
type MealDisplay = Pick<Meal, 'id' | 'suggestedDate'> & Partial<Pick<Meal, 'recipes' | 'extraIngredients'>>
|
|
||||||
|
|
||||||
const props = defineProps<{ meals: MealDisplay[]; checked: MealDisplay[]; disabled?: boolean }>()
|
|
||||||
const emit = defineEmits<{
|
|
||||||
(e: 'meal-selected', meal: MealDisplay): void
|
|
||||||
(e: 'meal-unselected', meal: MealDisplay): void
|
|
||||||
}>()
|
|
||||||
|
|
||||||
const nth = (d: number) => {
|
|
||||||
if (d > 3 && d < 21) return 'th'
|
if (d > 3 && d < 21) return 'th'
|
||||||
switch (d % 10) {
|
switch (d % 10) {
|
||||||
case 1:
|
case 1:
|
||||||
|
|
@ -49,36 +45,29 @@ const nth = (d: number) => {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const formatDate = (date) =>
|
||||||
|
`${date.toLocaleDateString('en-AU', { weekday: 'short' })} ${date.getDate()}${nth(date.getDate())}`
|
||||||
|
|
||||||
const formatDate = (date: Date | null) => {
|
const getUrl = (meal) => {
|
||||||
if (!date) return ''
|
// First non empty value in meal.recipe/image_urls
|
||||||
const day = date.getDate()
|
for (const mr of meal.recipes) {
|
||||||
return `${date.toLocaleDateString('en-AU', { weekday: 'short' })} ${day}${nth(day)}`
|
const recipe = mr.recipe
|
||||||
}
|
if (recipe.image_urls.length && recipe.image_urls[0]) {
|
||||||
|
return recipe.image_urls[0]
|
||||||
const getUrl = (meal: MealDisplay) => {
|
|
||||||
// First non empty value in meal.recipes[*].recipe image URLs
|
|
||||||
if (meal.recipes) {
|
|
||||||
for (const mr of meal.recipes) {
|
|
||||||
const imgs = mr.recipe?.imageUrls
|
|
||||||
if (imgs && imgs.length && imgs[0]) {
|
|
||||||
return imgs[0]
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// First meal.extraIngredients with a product with an image
|
// First meal.extra_ingredient with a product with an image
|
||||||
if (meal.extraIngredients) {
|
for (const ingredient of meal.extra_ingredients) {
|
||||||
for (const ingredient of meal.extraIngredients) {
|
if (ingredient.product) {
|
||||||
const p = ingredient.product
|
if (ingredient.product.img_large) return ingredient.product.img_large
|
||||||
if (p?.imgLarge) return p.imgLarge
|
if (ingredient.product.img_small) return ingredient.product.img_small
|
||||||
if (p?.imgSmall) return p.imgSmall
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
function getImageStyling(meal: MealDisplay) {
|
function getImageStyling(meal) {
|
||||||
const imageUrl = getUrl(meal)
|
const imageUrl = getUrl(meal)
|
||||||
if (!imageUrl) return null
|
if (!imageUrl) return null
|
||||||
const opacity = 0.7
|
const opacity = 0.7
|
||||||
|
|
@ -87,17 +76,14 @@ function getImageStyling(meal: MealDisplay) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function mealCheckChanged(event: Event) {
|
function mealCheckChanged(event) {
|
||||||
const target = event.target
|
const mealId = parseInt(event.target.id)
|
||||||
if (!target || !(target instanceof HTMLInputElement)) return
|
|
||||||
const mealId = parseInt(target.id)
|
|
||||||
const meal = props.meals.find((m) => m.id === mealId)
|
const meal = props.meals.find((m) => m.id === mealId)
|
||||||
if (!meal) return
|
if (event.target.checked) emit('meal-selected', meal)
|
||||||
if (target.checked) emit('meal-selected', meal)
|
|
||||||
else emit('meal-unselected', meal)
|
else emit('meal-unselected', meal)
|
||||||
}
|
}
|
||||||
|
|
||||||
function isChecked(meal: MealDisplay) {
|
function isChecked(meal) {
|
||||||
return props.checked.some((m) => m.id === meal.id)
|
return props.checked.some((m) => m.id === meal.id)
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
|
||||||
|
|
@ -39,42 +39,42 @@
|
||||||
-->
|
-->
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup>
|
||||||
import { ref, onBeforeMount } from 'vue'
|
import { ref, onBeforeMount } from 'vue'
|
||||||
import { useRouter } from 'vue-router'
|
import { useRouter } from 'vue-router'
|
||||||
import { useAuth } from '@/composables/useAuth'
|
import { useAuth } from '@/composables/useAuth'
|
||||||
import { useShopping } from '@/composables/useShopping'
|
import { useShopping } from '@/composables/useShopping'
|
||||||
import type { Ingredient } from '@/domain/types'
|
|
||||||
import EditableIngredientsPanel from '@/components/ingredients/EditableIngredientsPanel.vue'
|
import EditableIngredientsPanel from '@/components/ingredients/EditableIngredientsPanel.vue'
|
||||||
|
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const { loadUser } = useAuth()
|
const { loadUser } = useAuth()
|
||||||
const { getMyShoppingList, saveMyShoppingList } = useShopping()
|
const { getMyShoppingList, saveMyShoppingList } = useShopping()
|
||||||
|
|
||||||
const person = ref<{ id?: number; name?: string } | null>(null)
|
const person = ref(null)
|
||||||
const ingredients = ref<Ingredient[]>([])
|
const ingredients = ref([])
|
||||||
|
|
||||||
async function updateShoppingList(save = false) {
|
async function updateShoppingList(save = false) {
|
||||||
const newIngredients = save ? await saveMyShoppingList(ingredients.value) : await getMyShoppingList()
|
const newIngredients = save
|
||||||
ingredients.value = newIngredients.map((i) => ({ ...i }))
|
? await saveMyShoppingList(ingredients.value)
|
||||||
|
: await getMyShoppingList()
|
||||||
|
ingredients.value = newIngredients
|
||||||
}
|
}
|
||||||
|
|
||||||
function addIngredient() {
|
function addIngredient() {
|
||||||
ingredients.value = [
|
ingredients.value = [{ id: -1 }, ...ingredients.value]
|
||||||
{ id: -1, name: '', line: '', quantity: 1, unit: 'Items', preparation: '', product: null },
|
|
||||||
...ingredients.value,
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function deleteIngredient(ingredient: Ingredient) {
|
function deleteIngredient(ingredient) {
|
||||||
ingredients.value = ingredients.value.filter((i) => i !== ingredient)
|
ingredients.value = ingredients.value.filter((i) => i !== ingredient)
|
||||||
}
|
}
|
||||||
|
|
||||||
function updateIngredient(oldIngredient: Ingredient, newIngredient: Ingredient) {
|
function updateIngredient(oldIngredient, newIngredient) {
|
||||||
ingredients.value = ingredients.value.map((source) => (source === oldIngredient ? newIngredient : source))
|
ingredients.value = ingredients.value.map((source) =>
|
||||||
|
source === oldIngredient ? newIngredient : source
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
async function onEditing(isStartingEdit: boolean) {
|
async function onEditing(isStartingEdit) {
|
||||||
await updateShoppingList(!isStartingEdit)
|
await updateShoppingList(!isStartingEdit)
|
||||||
if (isStartingEdit && ingredients.value.length === 0) addIngredient()
|
if (isStartingEdit && ingredients.value.length === 0) addIngredient()
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
<template>
|
<template>
|
||||||
<h3>Purchased {{ shoppingList?.createdDate ? ago(shoppingList.createdDate) : '' }}</h3>
|
<h3>Purchased {{ shoppingList ? ago(shoppingList.created_date) : '' }}</h3>
|
||||||
|
|
||||||
<div v-if="includedMeals.length > 0">
|
<div v-if="includedMeals.length > 0">
|
||||||
<h4>Included Meals</h4>
|
<h4>Included Meals</h4>
|
||||||
|
|
@ -13,43 +13,37 @@
|
||||||
<ul class="full-shopping-list">
|
<ul class="full-shopping-list">
|
||||||
<li
|
<li
|
||||||
v-for="item in listByProduct"
|
v-for="item in listByProduct"
|
||||||
:key="groupKey(item)"
|
:key="item.id"
|
||||||
>
|
>
|
||||||
<shopping-list-item-comp :shopping-list-item-group="item" />
|
<shopping-list-item :shopping-list-item-group="item" />
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup>
|
||||||
import { ref, computed, onBeforeMount } from 'vue'
|
import { ref, computed, onBeforeMount } from 'vue'
|
||||||
import { useRoute } from 'vue-router'
|
import { useRoute } from 'vue-router'
|
||||||
import { ago } from '@/dateformats'
|
import { ago } from '@/dateformats.js'
|
||||||
import { useShopping } from '@/composables/useShopping'
|
import { getShoppingList } from '@/api/shopping'
|
||||||
import { parseRouteId } from '@/router/helpers'
|
import { itemsToGroups, uniqueMeals } from './shopping.js'
|
||||||
import type { Group } from '@/composables/useShopping'
|
|
||||||
import type { Meal } from '@/domain/types'
|
|
||||||
import MealSelectionList from './MealSelectionList.vue'
|
import MealSelectionList from './MealSelectionList.vue'
|
||||||
import ShoppingListItemComp from './ShoppingListItem.vue'
|
import ShoppingListItem from './ShoppingListItem.vue'
|
||||||
|
|
||||||
const route = useRoute()
|
const route = useRoute()
|
||||||
const { getShoppingList, groupsFrom, mealsFrom } = useShopping()
|
const shoppingList = ref(null)
|
||||||
const shoppingList = ref<import('@/domain/types').ShoppingListWithRefs | null>(null)
|
|
||||||
|
|
||||||
const includedMeals = computed<Meal[]>(() => mealsFrom(shoppingList.value?.items))
|
const includedMeals = computed(() =>
|
||||||
const listByProduct = computed(() => groupsFrom(shoppingList.value?.items))
|
shoppingList.value ? uniqueMeals(shoppingList.value.items) : []
|
||||||
|
)
|
||||||
|
const listByProduct = computed(() =>
|
||||||
|
shoppingList.value ? itemsToGroups(shoppingList.value.items) : []
|
||||||
|
)
|
||||||
|
|
||||||
onBeforeMount(async () => {
|
onBeforeMount(async () => {
|
||||||
const id = parseRouteId(route.params.id)
|
const idParam = route.params.id
|
||||||
if (id !== null) {
|
const id = typeof idParam === 'string' ? parseInt(idParam) : idParam
|
||||||
shoppingList.value = await getShoppingList(id)
|
shoppingList.value = await getShoppingList(id)
|
||||||
}
|
|
||||||
})
|
})
|
||||||
|
|
||||||
function groupKey(group: Group) {
|
|
||||||
if (group.type === 'product') return `p-${group.product.id}`
|
|
||||||
if (group.type === 'name') return `n-${group.name}`
|
|
||||||
return Math.random().toString(36)
|
|
||||||
}
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
|
|
|
||||||
|
|
@ -2,21 +2,21 @@
|
||||||
<!-- Show a card of the product with the total, taking up the available space and have an expanding section to view sources -->
|
<!-- Show a card of the product with the total, taking up the available space and have an expanding section to view sources -->
|
||||||
<div class="shopping-list-item">
|
<div class="shopping-list-item">
|
||||||
<img
|
<img
|
||||||
:src="imageSrc"
|
:src="`${shoppingListItemGroup.product?.img_small ?? require('@/assets/missing-product.svg')}`"
|
||||||
class="product-image"
|
class="product-image"
|
||||||
>
|
>
|
||||||
<div class="product-details">
|
<div class="product-details">
|
||||||
<h3 class="header">
|
<h3 class="header">
|
||||||
<strong>
|
<strong>
|
||||||
<a
|
<a
|
||||||
v-if="shoppingListItemGroup.type === 'product' && shoppingListItemGroup.product?.link"
|
v-if="shoppingListItemGroup.product?.link"
|
||||||
:href="shoppingListItemGroup.product?.link"
|
:href="shoppingListItemGroup.product?.link"
|
||||||
>{{ shoppingListItemGroup.product?.name }}</a>
|
>{{ shoppingListItemGroup.product?.name }}</a>
|
||||||
<span v-else>{{ shoppingListItemGroup.type === 'name' ? shoppingListItemGroup.name : '' }}</span> </strong>,
|
<span v-else>{{ shoppingListItemGroup.name }}</span> </strong>,
|
||||||
<small>
|
<small>
|
||||||
<span
|
<span
|
||||||
v-for="(total, index) in remainingRequiredTotals"
|
v-for="(total, index) in remainingRequiredTotals"
|
||||||
:key="index"
|
:key="total.id"
|
||||||
>
|
>
|
||||||
<span v-if="index">, </span>
|
<span v-if="index">, </span>
|
||||||
<span>{{ formatQuantity(total.quantity) }} {{ total.unit }}</span>
|
<span>{{ formatQuantity(total.quantity) }} {{ total.unit }}</span>
|
||||||
|
|
@ -47,26 +47,22 @@
|
||||||
source.recipe.name
|
source.recipe.name
|
||||||
}}</router-link>
|
}}</router-link>
|
||||||
for
|
for
|
||||||
<router-link :to="`/meals/${source.meal?.id}/`">{{
|
<router-link :to="`/meals/${source.meal.id}/`">{{
|
||||||
source.meal?.suggestedDate
|
source.meal.suggested_date.toLocaleDateString('en-AU', {
|
||||||
? source.meal.suggestedDate.toLocaleDateString('en-AU', {
|
weekday: 'long',
|
||||||
weekday: 'long',
|
month: 'long',
|
||||||
month: 'long',
|
day: 'numeric',
|
||||||
day: 'numeric',
|
})
|
||||||
})
|
|
||||||
: ''
|
|
||||||
}}</router-link>
|
}}</router-link>
|
||||||
</span>
|
</span>
|
||||||
<span v-else-if="source.meal">
|
<span v-else-if="source.meal">
|
||||||
{{ source.ingredient.line }} for
|
{{ source.ingredient.line }} for
|
||||||
<router-link :to="`/meals/${source.meal?.id}/`">{{
|
<router-link :to="`/meals/${source.meal.id}/`">{{
|
||||||
source.meal?.suggestedDate
|
source.meal.suggested_date.toLocaleDateString('en-AU', {
|
||||||
? source.meal.suggestedDate.toLocaleDateString('en-AU', {
|
weekday: 'long',
|
||||||
weekday: 'long',
|
month: 'long',
|
||||||
month: 'long',
|
day: 'numeric',
|
||||||
day: 'numeric',
|
})
|
||||||
})
|
|
||||||
: ''
|
|
||||||
}}</router-link>
|
}}</router-link>
|
||||||
</span>
|
</span>
|
||||||
</span>
|
</span>
|
||||||
|
|
@ -88,26 +84,22 @@
|
||||||
source.recipe.name
|
source.recipe.name
|
||||||
}}</router-link>
|
}}</router-link>
|
||||||
for
|
for
|
||||||
<router-link :to="`/meals/${source.meal?.id ?? ''}/`">{{
|
<router-link :to="`/meals/${source.meal.id}/`">{{
|
||||||
source.meal?.suggestedDate
|
source.meal.suggested_date.toLocaleDateString('en-AU', {
|
||||||
? source.meal.suggestedDate.toLocaleDateString('en-AU', {
|
weekday: 'long',
|
||||||
weekday: 'long',
|
month: 'long',
|
||||||
month: 'long',
|
day: 'numeric',
|
||||||
day: 'numeric',
|
})
|
||||||
})
|
|
||||||
: ''
|
|
||||||
}}</router-link>
|
}}</router-link>
|
||||||
</span>
|
</span>
|
||||||
<span v-else-if="source.meal">
|
<span v-else-if="source.meal">
|
||||||
{{ source.ingredient.line }} for
|
{{ source.ingredient.line }} for
|
||||||
<router-link :to="`/meals/${source.meal.id}/`">{{
|
<router-link :to="`/meals/${source.meal.id}/`">{{
|
||||||
source.meal.suggestedDate
|
source.meal.suggested_date.toLocaleDateString('en-AU', {
|
||||||
? source.meal.suggestedDate.toLocaleDateString('en-AU', {
|
weekday: 'long',
|
||||||
weekday: 'long',
|
month: 'long',
|
||||||
month: 'long',
|
day: 'numeric',
|
||||||
day: 'numeric',
|
})
|
||||||
})
|
|
||||||
: ''
|
|
||||||
}}</router-link>
|
}}</router-link>
|
||||||
</span>
|
</span>
|
||||||
</span>
|
</span>
|
||||||
|
|
@ -116,50 +108,43 @@
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup>
|
||||||
import { computed } from 'vue'
|
import { computed } from 'vue'
|
||||||
import { ago } from '@/dateformats'
|
import { ago } from '@/dateformats.js'
|
||||||
import { calculateTotals } from '@/units'
|
import { calculateTotals } from '@/units.js'
|
||||||
import type { Group } from '@/composables/useShopping'
|
|
||||||
|
|
||||||
const props = defineProps<{ shoppingListItemGroup: Group }>()
|
const props = defineProps({
|
||||||
|
// { product: { ... }, OR name: 'string', shoppingListItems: [...] }
|
||||||
const fallbackImg = new URL('@/assets/missing-product.svg', import.meta.url).toString()
|
shoppingListItemGroup: { type: Object, required: true },
|
||||||
const imageSrc = computed(() => {
|
|
||||||
if (props.shoppingListItemGroup.type === 'product') {
|
|
||||||
return props.shoppingListItemGroup.product?.imgSmall ?? fallbackImg
|
|
||||||
}
|
|
||||||
return fallbackImg
|
|
||||||
})
|
})
|
||||||
|
|
||||||
const remainingRequiredTotals = computed(() =>
|
const remainingRequiredTotals = computed(() =>
|
||||||
calculateTotals(
|
calculateTotals(props.shoppingListItemGroup.shoppingListItems.map((item) => item.ingredient))
|
||||||
props.shoppingListItemGroup.shoppingListItems.map((item) => ({
|
|
||||||
quantity: item.ingredient.quantity,
|
|
||||||
unit: String(item.ingredient.unit || 'items'),
|
|
||||||
}))
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const required = computed(() => props.shoppingListItemGroup.shoppingListItems.filter((item) => !item.listId))
|
const required = computed(() =>
|
||||||
|
props.shoppingListItemGroup.shoppingListItems.filter((item) => !item.list_id)
|
||||||
|
)
|
||||||
|
|
||||||
const purchased = computed(() => props.shoppingListItemGroup.shoppingListItems.filter((item) => item.listId))
|
const purchased = computed(() =>
|
||||||
|
props.shoppingListItemGroup.shoppingListItems.filter((item) => item.list_id)
|
||||||
|
)
|
||||||
|
|
||||||
const lastPurchased = computed(() => {
|
const lastPurchased = computed(() => {
|
||||||
const purchasedItems = props.shoppingListItemGroup.shoppingListItems.filter((item) => item.listId)
|
const purchasedItems = props.shoppingListItemGroup.shoppingListItems.filter((item) => item.list_id)
|
||||||
if (purchasedItems.length === 0) return null
|
if (purchasedItems.length === 0) return null
|
||||||
return purchasedItems.reduce<Date | null>((latest, item) => {
|
return purchasedItems.reduce((latest, item) => {
|
||||||
const itemDate: Date | null = (item?.meal?.suggestedDate ?? item?.createdDate) || null
|
const itemDate = item?.meal?.suggested_date || item?.created_at
|
||||||
return !latest || (itemDate && itemDate > latest) ? itemDate : latest
|
return !latest || (itemDate && itemDate > latest) ? itemDate : latest
|
||||||
}, null)
|
}, null)
|
||||||
})
|
})
|
||||||
|
|
||||||
function getFriendlyDate(date: Date | null) {
|
function getFriendlyDate(date) {
|
||||||
if (!date) return ''
|
if (!date) return ''
|
||||||
return ago(date)
|
return ago(date)
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatQuantity(quantity: number) {
|
function formatQuantity(quantity) {
|
||||||
const log10 = Math.log10(quantity)
|
const log10 = Math.log10(quantity)
|
||||||
if (log10 < 0) return quantity.toPrecision(2)
|
if (log10 < 0) return quantity.toPrecision(2)
|
||||||
if (log10 < 1) return quantity.toFixed(1)
|
if (log10 < 1) return quantity.toFixed(1)
|
||||||
|
|
|
||||||
42
src/components/shopping/shopping.js
Normal file
42
src/components/shopping/shopping.js
Normal file
|
|
@ -0,0 +1,42 @@
|
||||||
|
export function groupsToItems(groups) {
|
||||||
|
return groups.map((group) => group.shoppingListItems).flat()
|
||||||
|
}
|
||||||
|
|
||||||
|
export function uniqueMeals(shoppingListItems) {
|
||||||
|
const mealsWithDuplicates = shoppingListItems.map((item) => item.meal).filter((m) => m)
|
||||||
|
|
||||||
|
const mealsLookup = mealsWithDuplicates.reduce((acc, meal) => {
|
||||||
|
acc[meal.id] ??= meal
|
||||||
|
return acc
|
||||||
|
}, {})
|
||||||
|
|
||||||
|
return Object.values(mealsLookup)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function itemsToGroups(shoppingListItems) {
|
||||||
|
const ingredients_by_product_id = {}
|
||||||
|
const ingredients_by_name = {}
|
||||||
|
for (const item of shoppingListItems) {
|
||||||
|
if (item.ingredient.product) {
|
||||||
|
let group = ingredients_by_product_id[item.ingredient.product.id]
|
||||||
|
if (!group) {
|
||||||
|
group = ingredients_by_product_id[item.ingredient.product.id] = {
|
||||||
|
product: item.ingredient.product,
|
||||||
|
shoppingListItems: [],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
group.shoppingListItems.push(item)
|
||||||
|
} else {
|
||||||
|
let group = ingredients_by_name[item.ingredient.name]
|
||||||
|
if (!group) {
|
||||||
|
group = ingredients_by_name[item.ingredient.name] = {
|
||||||
|
name: item.ingredient.name,
|
||||||
|
shoppingListItems: [],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
group.shoppingListItems.push(item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return [...Object.values(ingredients_by_product_id), ...Object.values(ingredients_by_name)]
|
||||||
|
}
|
||||||
|
|
@ -1,13 +1,11 @@
|
||||||
import { ref } from 'vue'
|
import { ref } from 'vue'
|
||||||
|
|
||||||
type AlertType = 'success' | 'error' | 'info'
|
|
||||||
export type AlertMessage = { heading?: string; message: string; type: AlertType }
|
|
||||||
|
|
||||||
// Singleton reactive alert state for the app
|
// Singleton reactive alert state for the app
|
||||||
const current = ref<(AlertMessage & { _ts: number }) | null>(null)
|
const current = ref(null)
|
||||||
let timeoutId: ReturnType<typeof setTimeout> | null = null
|
let timeoutId = null
|
||||||
|
|
||||||
function show(message: AlertMessage) {
|
function show(message) {
|
||||||
|
// message: { heading, message, type: 'success' | 'error' | 'info' }
|
||||||
current.value = { ...message, _ts: Date.now() }
|
current.value = { ...message, _ts: Date.now() }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1,8 +1,7 @@
|
||||||
import { ref } from 'vue'
|
import { ref } from 'vue'
|
||||||
import { currentUser as apiCurrentUser, login as apiLogin } from '@/api/auth'
|
import { currentUser as apiCurrentUser, login as apiLogin } from '@/api/auth'
|
||||||
import type { Person } from '@/domain/types'
|
|
||||||
|
|
||||||
const user = ref<Person | null>(null)
|
const user = ref(null)
|
||||||
let initialized = false
|
let initialized = false
|
||||||
|
|
||||||
export async function loadUser() {
|
export async function loadUser() {
|
||||||
|
|
@ -13,7 +12,7 @@ export async function loadUser() {
|
||||||
return user.value
|
return user.value
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function login(username: string) {
|
export async function login(username) {
|
||||||
user.value = await apiLogin(username)
|
user.value = await apiLogin(username)
|
||||||
return user.value
|
return user.value
|
||||||
}
|
}
|
||||||
25
src/composables/useMeals.js
Normal file
25
src/composables/useMeals.js
Normal file
|
|
@ -0,0 +1,25 @@
|
||||||
|
import * as api from '@/api/meals'
|
||||||
|
|
||||||
|
export async function getUpcomingMeals(from, to) {
|
||||||
|
return api.getUpcomingMeals(from, to)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getMeal(id) {
|
||||||
|
return api.getMeal(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function saveMeal(meal) {
|
||||||
|
return api.saveMeal(meal)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function markMealConsumed(mealId) {
|
||||||
|
return api.markMealConsumed(mealId)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteMeal(mealId) {
|
||||||
|
return api.deleteMeal(mealId)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useMeals() {
|
||||||
|
return { getUpcomingMeals, getMeal, saveMeal, markMealConsumed, deleteMeal }
|
||||||
|
}
|
||||||
|
|
@ -1,46 +0,0 @@
|
||||||
import * as sdk from '@/api/sdk'
|
|
||||||
import type { MealInput, Meal } from '@/domain/types'
|
|
||||||
|
|
||||||
export async function getUpcomingMeals(from: Date, to: Date) {
|
|
||||||
return sdk.getUpcomingMeals(from, to)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getMeal(id: number | string) {
|
|
||||||
return sdk.getMeal(id)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function saveMeal(meal: MealInput) {
|
|
||||||
return sdk.saveMeal(meal)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function markMealConsumed(mealId: number | string) {
|
|
||||||
return sdk.markMealConsumed(mealId)
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function deleteMeal(mealId: number | string) {
|
|
||||||
return sdk.deleteMeal(mealId)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Helper to convert domain Meal to MealInput, keeping Date→string conversion in boundary
|
|
||||||
export function toMealInput(meal: Meal): MealInput {
|
|
||||||
return {
|
|
||||||
id: meal.id,
|
|
||||||
suggestedDate: meal.suggestedDate ? meal.suggestedDate.toISOString() : new Date().toISOString(),
|
|
||||||
consumedDate: meal.consumedDate ? meal.consumedDate.toISOString() : null,
|
|
||||||
purchaseDate: meal.purchaseDate ? meal.purchaseDate.toISOString() : null,
|
|
||||||
chefs: meal.chefs,
|
|
||||||
cleanup: meal.cleanup,
|
|
||||||
consumers: meal.consumers,
|
|
||||||
recipes: meal.recipes.map((r) => ({
|
|
||||||
mealId: r.mealId,
|
|
||||||
recipeId: r.recipeId,
|
|
||||||
servings: r.servings,
|
|
||||||
recipe: null
|
|
||||||
})),
|
|
||||||
extraIngredients: meal.extraIngredients,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useMeals() {
|
|
||||||
return { getUpcomingMeals, getMeal, saveMeal, markMealConsumed, deleteMeal, toMealInput }
|
|
||||||
}
|
|
||||||
|
|
@ -1,107 +0,0 @@
|
||||||
import { ref, shallowRef, type Ref, type ShallowRef } from 'vue'
|
|
||||||
import type { Page } from '@/domain/pagination'
|
|
||||||
|
|
||||||
export type PageParams = { cursor?: string | null; limit?: number } & Record<string, unknown>
|
|
||||||
export type PageFetcher<T> = (params: PageParams) => Promise<Page<T>>
|
|
||||||
|
|
||||||
export function usePagination<T>(
|
|
||||||
fetchPage: PageFetcher<T>,
|
|
||||||
options?: { pageSize?: number }
|
|
||||||
): {
|
|
||||||
items: Ref<T[]>
|
|
||||||
next: Ref<string | null>
|
|
||||||
prev: Ref<string | null>
|
|
||||||
total: Ref<number | null>
|
|
||||||
loading: Ref<boolean>
|
|
||||||
error: Ref<unknown>
|
|
||||||
load: (baseParams?: PageParams) => Promise<void>
|
|
||||||
loadNext: () => Promise<void>
|
|
||||||
loadPrev: () => Promise<void>
|
|
||||||
reset: () => void
|
|
||||||
} {
|
|
||||||
function makeItemsRef<U>(): ShallowRef<U[]> {
|
|
||||||
return shallowRef<U[]>([])
|
|
||||||
}
|
|
||||||
const items: Ref<T[]> = makeItemsRef<T>()
|
|
||||||
const next: Ref<string | null> = ref<string | null>(null)
|
|
||||||
const prev: Ref<string | null> = ref<string | null>(null)
|
|
||||||
const total: Ref<number | null> = ref<number | null>(null)
|
|
||||||
const loading: Ref<boolean> = ref<boolean>(false)
|
|
||||||
const error: Ref<unknown> = ref<unknown>(null)
|
|
||||||
|
|
||||||
const pageSize = options?.pageSize
|
|
||||||
const lastBaseParams = ref<PageParams>({})
|
|
||||||
|
|
||||||
function assignFromPage(page: Page<T>) {
|
|
||||||
items.value = page.items ?? []
|
|
||||||
next.value = page.next ?? null
|
|
||||||
prev.value = page.prev ?? null
|
|
||||||
total.value = page.total ?? null
|
|
||||||
}
|
|
||||||
|
|
||||||
async function load(baseParams: PageParams = {}) {
|
|
||||||
loading.value = true
|
|
||||||
error.value = null
|
|
||||||
// keep base params without cursor; limit comes from options unless explicitly provided
|
|
||||||
const { limit: _l, ...rest } = baseParams
|
|
||||||
lastBaseParams.value = rest
|
|
||||||
try {
|
|
||||||
const params: PageParams = { ...rest }
|
|
||||||
if (typeof _l === 'number') params.limit = _l
|
|
||||||
else if (typeof pageSize === 'number') params.limit = pageSize
|
|
||||||
const page = await fetchPage(params)
|
|
||||||
assignFromPage(page)
|
|
||||||
} catch (e) {
|
|
||||||
error.value = e
|
|
||||||
items.value = []
|
|
||||||
next.value = null
|
|
||||||
prev.value = null
|
|
||||||
total.value = null
|
|
||||||
} finally {
|
|
||||||
loading.value = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function loadWithCursor(cursor: string | null) {
|
|
||||||
if (!cursor) return
|
|
||||||
loading.value = true
|
|
||||||
error.value = null
|
|
||||||
try {
|
|
||||||
const params: PageParams = {
|
|
||||||
...lastBaseParams.value,
|
|
||||||
cursor,
|
|
||||||
}
|
|
||||||
if (typeof pageSize === 'number') params.limit = pageSize
|
|
||||||
const page = await fetchPage(params)
|
|
||||||
assignFromPage(page)
|
|
||||||
} catch (e) {
|
|
||||||
error.value = e
|
|
||||||
items.value = []
|
|
||||||
next.value = null
|
|
||||||
prev.value = null
|
|
||||||
total.value = null
|
|
||||||
} finally {
|
|
||||||
loading.value = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function loadNext() {
|
|
||||||
await loadWithCursor(next.value)
|
|
||||||
}
|
|
||||||
|
|
||||||
async function loadPrev() {
|
|
||||||
await loadWithCursor(prev.value)
|
|
||||||
}
|
|
||||||
|
|
||||||
function reset() {
|
|
||||||
items.value = []
|
|
||||||
next.value = null
|
|
||||||
prev.value = null
|
|
||||||
total.value = null
|
|
||||||
loading.value = false
|
|
||||||
error.value = null
|
|
||||||
lastBaseParams.value = {}
|
|
||||||
}
|
|
||||||
|
|
||||||
return { items, next, prev, total, loading, error, load, loadNext, loadPrev, reset }
|
|
||||||
}
|
|
||||||
27
src/composables/useShopping.js
Normal file
27
src/composables/useShopping.js
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
import {
|
||||||
|
getCurrentShoppingList,
|
||||||
|
getShoppingList,
|
||||||
|
purchaseShoppingList,
|
||||||
|
requestMeal,
|
||||||
|
unrequestMeal,
|
||||||
|
getMyShoppingList,
|
||||||
|
saveMyShoppingList,
|
||||||
|
} from '@/api/shopping'
|
||||||
|
import { groupsToItems } from '@/components/shopping/shopping.js'
|
||||||
|
|
||||||
|
export function useShopping() {
|
||||||
|
return {
|
||||||
|
getCurrentShoppingList,
|
||||||
|
getShoppingList,
|
||||||
|
purchaseShoppingList,
|
||||||
|
requestMeal,
|
||||||
|
unrequestMeal,
|
||||||
|
getMyShoppingList,
|
||||||
|
saveMyShoppingList,
|
||||||
|
async purchaseFromGroups(groups) {
|
||||||
|
const items = groupsToItems(groups)
|
||||||
|
if (!items?.length) return null
|
||||||
|
return purchaseShoppingList(items)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,116 +0,0 @@
|
||||||
import * as sdk from '@/api/sdk'
|
|
||||||
import type { ShoppingListItemWithRefs, Product, Meal, Ingredient, Person, Recipe } from '@/domain/types'
|
|
||||||
|
|
||||||
export type UIShoppingListItem = {
|
|
||||||
id: number
|
|
||||||
ingredient: Ingredient
|
|
||||||
person?: Person | null
|
|
||||||
personId: number
|
|
||||||
recipe?: Recipe | null
|
|
||||||
meal?: Meal | null
|
|
||||||
ingredientId?: number | null
|
|
||||||
listId?: number | null
|
|
||||||
createdDate?: Date | null
|
|
||||||
}
|
|
||||||
|
|
||||||
export type GroupByProduct = { type: 'product'; product: Product; shoppingListItems: UIShoppingListItem[] }
|
|
||||||
export type GroupByName = { type: 'name'; name: string; shoppingListItems: UIShoppingListItem[] }
|
|
||||||
export type Group = GroupByProduct | GroupByName
|
|
||||||
|
|
||||||
export function groupsToItems(groups: Group[]): UIShoppingListItem[] {
|
|
||||||
return groups.map((g) => g.shoppingListItems).flat()
|
|
||||||
}
|
|
||||||
|
|
||||||
export function uniqueMeals(shoppingListItems: UIShoppingListItem[]): Meal[] {
|
|
||||||
const mealsWithDuplicates = shoppingListItems.map((item) => item.meal).filter((m): m is Meal => !!m)
|
|
||||||
const mealsLookup: Record<string | number, Meal> = mealsWithDuplicates.reduce<Record<string | number, Meal>>(
|
|
||||||
(acc, meal) => {
|
|
||||||
acc[meal.id] ??= meal
|
|
||||||
return acc
|
|
||||||
},
|
|
||||||
{}
|
|
||||||
)
|
|
||||||
return Object.values(mealsLookup)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function itemsToGroups(shoppingListItems: UIShoppingListItem[]): Group[] {
|
|
||||||
const ingredients_by_product_id: Record<string | number, GroupByProduct> = {}
|
|
||||||
const ingredients_by_name: Record<string, GroupByName> = {}
|
|
||||||
for (const item of shoppingListItems) {
|
|
||||||
if (item.ingredient.product) {
|
|
||||||
let group = ingredients_by_product_id[item.ingredient.product.id]
|
|
||||||
if (!group) {
|
|
||||||
group = ingredients_by_product_id[item.ingredient.product.id] = {
|
|
||||||
type: 'product',
|
|
||||||
product: item.ingredient.product,
|
|
||||||
shoppingListItems: [],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
group.shoppingListItems.push(item)
|
|
||||||
} else {
|
|
||||||
let group = ingredients_by_name[item.ingredient.name]
|
|
||||||
if (!group) {
|
|
||||||
group = ingredients_by_name[item.ingredient.name] = {
|
|
||||||
type: 'name',
|
|
||||||
name: item.ingredient.name,
|
|
||||||
shoppingListItems: [],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
group.shoppingListItems.push(item)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return [...Object.values(ingredients_by_product_id), ...Object.values(ingredients_by_name)]
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useShopping() {
|
|
||||||
// Request shapes expected by sdk.purchaseShoppingList
|
|
||||||
type PurchaseExisting = { type: 'existing'; id: number; personId: number; ingredientId?: number | null }
|
|
||||||
type PurchaseRefs = { type: 'refs'; personId: number; ingredientId?: number | null; recipeId?: number | null; mealId?: number | null }
|
|
||||||
const toExisting = (id: number, personId: number, ingredientId?: number | null): PurchaseExisting => ({ type: 'existing', id, personId, ingredientId: ingredientId ?? null })
|
|
||||||
const toRefs = (personId: number, ingredientId?: number | null, recipeId?: number | null, mealId?: number | null): PurchaseRefs => ({
|
|
||||||
type: 'refs',
|
|
||||||
personId,
|
|
||||||
ingredientId: ingredientId ?? null,
|
|
||||||
recipeId: recipeId ?? null,
|
|
||||||
mealId: mealId ?? null,
|
|
||||||
})
|
|
||||||
const mapItemToUI = (i: ShoppingListItemWithRefs): UIShoppingListItem => ({
|
|
||||||
id: Number(i.id),
|
|
||||||
ingredient: i.ingredient!,
|
|
||||||
person: null,
|
|
||||||
personId: i.personId,
|
|
||||||
recipe: i.recipe ?? null,
|
|
||||||
meal: i.meal ?? null,
|
|
||||||
ingredientId: i.ingredient?.id ?? null,
|
|
||||||
listId: i.listId ?? null,
|
|
||||||
createdDate: i.createdDate,
|
|
||||||
})
|
|
||||||
const groupsFrom = (items?: ShoppingListItemWithRefs[]): Group[] => {
|
|
||||||
return itemsToGroups((items ?? []).map(mapItemToUI))
|
|
||||||
}
|
|
||||||
const mealsFrom = (items?: ShoppingListItemWithRefs[]): Meal[] => {
|
|
||||||
return uniqueMeals((items ?? []).map(mapItemToUI))
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
getCurrentShoppingList: sdk.getCurrentShoppingList,
|
|
||||||
getShoppingList: sdk.getShoppingList,
|
|
||||||
purchaseShoppingList: sdk.purchaseShoppingList,
|
|
||||||
requestMeal: sdk.requestMeal,
|
|
||||||
unrequestMeal: sdk.unrequestMeal,
|
|
||||||
getMyShoppingList: sdk.getMyShoppingList,
|
|
||||||
saveMyShoppingList: sdk.saveMyShoppingList,
|
|
||||||
// View-model helpers
|
|
||||||
mapItemToUI,
|
|
||||||
groupsFrom,
|
|
||||||
mealsFrom,
|
|
||||||
async purchaseFromGroups(groups: Group[]) {
|
|
||||||
const items = groupsToItems(groups).map((i) =>
|
|
||||||
typeof i.id === 'number' && i.id >= 0
|
|
||||||
? toExisting(i.id, i.personId, i.ingredientId)
|
|
||||||
: toRefs(i.personId, i.ingredient?.id ?? null, i.recipe?.id ?? null, i.meal?.id ?? null)
|
|
||||||
)
|
|
||||||
if (!items?.length) return null
|
|
||||||
return sdk.purchaseShoppingList(items)
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
25
src/dateformats.js
Normal file
25
src/dateformats.js
Normal file
|
|
@ -0,0 +1,25 @@
|
||||||
|
function plural(num, unit) {
|
||||||
|
num = Math.floor(num)
|
||||||
|
return num + ' ' + unit + (num === 1 ? '' : 's')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ago(date) {
|
||||||
|
const now = new Date()
|
||||||
|
const diff = now - date
|
||||||
|
if (diff < 1000) {
|
||||||
|
return 'just now'
|
||||||
|
}
|
||||||
|
if (diff < 60 * 1000) {
|
||||||
|
return plural(diff / 1000, 'second') + ' ago'
|
||||||
|
}
|
||||||
|
if (diff < 60 * 60 * 1000) {
|
||||||
|
return plural(diff / (60 * 1000), 'minute') + ' ago'
|
||||||
|
}
|
||||||
|
if (diff < 24 * 60 * 60 * 1000) {
|
||||||
|
return plural(diff / (60 * 60 * 1000), 'hour') + ' ago'
|
||||||
|
}
|
||||||
|
if (diff < 7 * 24 * 60 * 60 * 1000) {
|
||||||
|
return plural(diff / (24 * 60 * 60 * 1000), 'day') + ' ago'
|
||||||
|
}
|
||||||
|
return date.toLocaleDateString()
|
||||||
|
}
|
||||||
|
|
@ -1,15 +0,0 @@
|
||||||
function plural(num: number, unit: string): string {
|
|
||||||
const whole = Math.floor(num)
|
|
||||||
return whole + ' ' + unit + (whole === 1 ? '' : 's')
|
|
||||||
}
|
|
||||||
|
|
||||||
export function ago(date: Date): string {
|
|
||||||
const now = new Date()
|
|
||||||
const diff = now.getTime() - date.getTime()
|
|
||||||
if (diff < 1000) return 'just now'
|
|
||||||
if (diff < 60 * 1000) return plural(diff / 1000, 'second') + ' ago'
|
|
||||||
if (diff < 60 * 60 * 1000) return plural(diff / (60 * 1000), 'minute') + ' ago'
|
|
||||||
if (diff < 24 * 60 * 60 * 1000) return plural(diff / (60 * 60 * 1000), 'hour') + ' ago'
|
|
||||||
if (diff < 7 * 24 * 60 * 60 * 1000) return plural(diff / (24 * 60 * 60 * 1000), 'day') + ' ago'
|
|
||||||
return date.toLocaleDateString()
|
|
||||||
}
|
|
||||||
|
|
@ -1,83 +0,0 @@
|
||||||
import type { RecipeOut, Recipe, MealOut, Meal, MealRecipe, Ingredient as DomainIngredient, ShoppingList, ShoppingListItem } from './types'
|
|
||||||
import type { components } from '@/api/types'
|
|
||||||
|
|
||||||
export function toDate(value: string | Date | null | undefined): Date | null {
|
|
||||||
if (value === null || value === undefined) return null
|
|
||||||
return typeof value === 'string' ? new Date(value) : value
|
|
||||||
}
|
|
||||||
|
|
||||||
export function decodeRecipe(r: RecipeOut | null | undefined): Recipe | null {
|
|
||||||
if (!r) return null
|
|
||||||
return {
|
|
||||||
...r,
|
|
||||||
dateCreated: toDate(r.dateCreated),
|
|
||||||
dateHidden: toDate(r.dateHidden),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function decodeRecipes(list: RecipeOut[] | null | undefined): Recipe[] {
|
|
||||||
if (!Array.isArray(list)) return []
|
|
||||||
return list.map((r) => decodeRecipe(r)).filter((r): r is Recipe => !!r)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function decodeMeal(m: MealOut | null | undefined): Meal | null {
|
|
||||||
if (!m) return null
|
|
||||||
const recipes = Array.isArray(m.recipes)
|
|
||||||
? m.recipes.map(mr => decodeMealRecipe(mr)).filter((r): r is MealRecipe => !!r)
|
|
||||||
: []
|
|
||||||
|
|
||||||
return {
|
|
||||||
...m,
|
|
||||||
suggestedDate: toDate(m.suggestedDate),
|
|
||||||
purchaseDate: toDate(m.purchaseDate),
|
|
||||||
consumedDate: toDate(m.consumedDate),
|
|
||||||
recipes,
|
|
||||||
chefs: m.chefs ?? [],
|
|
||||||
consumers: m.consumers ?? [],
|
|
||||||
cleanup: m.cleanup ?? [],
|
|
||||||
extraIngredients: m.extraIngredients ?? [],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function decodeMealRecipe(mr: components['schemas']['MealRecipe-Output'] | null | undefined): MealRecipe | null {
|
|
||||||
if (!mr) return null
|
|
||||||
return {
|
|
||||||
...mr,
|
|
||||||
recipe: mr.recipe ? decodeRecipe(mr.recipe) : null,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function decodeIngredient(i: components['schemas']['Ingredient'] | null | undefined): DomainIngredient | null {
|
|
||||||
if (!i) return null
|
|
||||||
// API guarantees quantity is a number; pass through
|
|
||||||
return { ...i }
|
|
||||||
}
|
|
||||||
|
|
||||||
export function decodeIngredients(list: components['schemas']['Ingredient'][] | null | undefined): DomainIngredient[] {
|
|
||||||
if (!Array.isArray(list)) return []
|
|
||||||
return list.map((i) => decodeIngredient(i)).filter((x): x is DomainIngredient => !!x)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function decodeShoppingListItem(i: components['schemas']['ShoppingListItem'] | null | undefined): ShoppingListItem | null {
|
|
||||||
if (!i) return null
|
|
||||||
return {
|
|
||||||
...i,
|
|
||||||
createdDate: toDate(i.createdDate),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function decodeShoppingListItems(list: components['schemas']['ShoppingListItem'][] | null | undefined): ShoppingListItem[] {
|
|
||||||
if (!Array.isArray(list)) return []
|
|
||||||
return list.map((i) => decodeShoppingListItem(i)).filter((x): x is ShoppingListItem => !!x)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function decodeShoppingList(v: components['schemas']['ShoppingList'] | null | undefined): ShoppingList | null {
|
|
||||||
if (!v) return null
|
|
||||||
const { items: rawItems, ...rest } = v
|
|
||||||
const items = Array.isArray(rawItems) ? decodeShoppingListItems(rawItems) : undefined
|
|
||||||
return {
|
|
||||||
...rest,
|
|
||||||
createdDate: toDate(v.createdDate),
|
|
||||||
...(items ? { items } : {}),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,13 +0,0 @@
|
||||||
export type Page<T> = { items: T[]; next?: string | null; prev?: string | null; total?: number | null }
|
|
||||||
|
|
||||||
type PageLike<T> = { items?: T[]; nextCursor?: string | null; prevCursor?: string | null; total?: number | null }
|
|
||||||
|
|
||||||
export function fromOpenApiPage<TIn, TOut>(page: PageLike<TIn> | null | undefined, mapItem: (i: TIn) => TOut): Page<TOut> {
|
|
||||||
if (!page) return { items: [] }
|
|
||||||
return {
|
|
||||||
items: (page.items ?? []).map((i) => mapItem(i)),
|
|
||||||
next: page.nextCursor ?? null,
|
|
||||||
prev: page.prevCursor ?? null,
|
|
||||||
total: page.total ?? null,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,69 +0,0 @@
|
||||||
import type { components } from '@/api/types'
|
|
||||||
|
|
||||||
// Utility mapped types
|
|
||||||
export type Replace<T, M> = Omit<T, keyof M> & M
|
|
||||||
export type WithDates<T, K extends keyof T> = Replace<T, { [P in K]: Date | null }>
|
|
||||||
|
|
||||||
// Common helpers
|
|
||||||
export type Maybe<T> = T | null | undefined
|
|
||||||
export type NonNull<T> = Exclude<T, null | undefined>
|
|
||||||
export type Lookup<T> = Record<string, T>
|
|
||||||
export type WithRefs<T, Refs extends object> = T & { [K in keyof Refs]?: Refs[K] | undefined }
|
|
||||||
|
|
||||||
// Domain type aliases
|
|
||||||
export type RecipeOut = components['schemas']['Recipe-Output']
|
|
||||||
export type MealOut = components['schemas']['Meal-Output']
|
|
||||||
export type Ingredient = components['schemas']['Ingredient']
|
|
||||||
export type Product = components['schemas']['Product']
|
|
||||||
export type Person = components['schemas']['Person']
|
|
||||||
export type RecipeInput = components['schemas']['Recipe-Input']
|
|
||||||
export type MealInput = components['schemas']['Meal-Input']
|
|
||||||
export type MealRecipeOut = components['schemas']['MealRecipe-Output']
|
|
||||||
|
|
||||||
// Domain shapes: only adjust where UI needs Dates
|
|
||||||
export type Recipe = WithDates<RecipeOut, 'dateCreated' | 'dateHidden'>
|
|
||||||
|
|
||||||
// MealRecipe with decoded recipe dates
|
|
||||||
export type MealRecipe = Replace<MealRecipeOut, { recipe: Recipe | null }>
|
|
||||||
|
|
||||||
// Meal with decoded dates and nested MealRecipe with decoded recipe dates
|
|
||||||
// Arrays (chefs, consumers, cleanup, recipes, extraIngredients) are non-nullable per OpenAPI spec
|
|
||||||
export type Meal = Replace<
|
|
||||||
WithDates<MealOut, 'suggestedDate' | 'consumedDate' | 'purchaseDate'>,
|
|
||||||
{
|
|
||||||
recipes: MealRecipe[]
|
|
||||||
chefs: Person[]
|
|
||||||
consumers: Person[]
|
|
||||||
cleanup: Person[]
|
|
||||||
extraIngredients: Ingredient[]
|
|
||||||
}
|
|
||||||
>
|
|
||||||
|
|
||||||
// Shopping domain shapes with dates normalized
|
|
||||||
export type ShoppingListItem = WithDates<components['schemas']['ShoppingListItem'], 'createdDate'>
|
|
||||||
type ShoppingListBase = WithDates<components['schemas']['ShoppingList'], 'createdDate'>
|
|
||||||
export type ShoppingList = Replace<ShoppingListBase, { items?: ShoppingListItem[] | undefined }>
|
|
||||||
|
|
||||||
// Refs attached to shopping list items
|
|
||||||
export type ShoppingListItemWithRefs = WithRefs<ShoppingListItem, { ingredient: Ingredient; recipe: Recipe; meal: Meal; list: ShoppingList }>
|
|
||||||
|
|
||||||
export type ShoppingListWithRefs = Replace<ShoppingList, { items?: ShoppingListItemWithRefs[] }>
|
|
||||||
|
|
||||||
// Lookup maps used by shopping mappings
|
|
||||||
export type ShoppingLookups = {
|
|
||||||
ingredientsLookup?: Lookup<Ingredient>
|
|
||||||
mealsLookup?: Lookup<Meal>
|
|
||||||
recipesLookup?: Lookup<Recipe>
|
|
||||||
shoppingListLookup?: Lookup<ShoppingList>
|
|
||||||
}
|
|
||||||
|
|
||||||
// DTO shapes returned by SDK for shopping pages
|
|
||||||
export type CurrentShoppingListDTO = {
|
|
||||||
outstandingItems: ShoppingListItemWithRefs[]
|
|
||||||
requestedMeals: ShoppingListItemWithRefs[]
|
|
||||||
purchasedItems: ShoppingListItemWithRefs[]
|
|
||||||
} & ShoppingLookups
|
|
||||||
|
|
||||||
export type PurchasedShoppingListDTO = ShoppingLookups & {
|
|
||||||
list?: (ShoppingList & { items?: ShoppingListItemWithRefs[] }) | undefined
|
|
||||||
}
|
|
||||||
17
src/env.d.ts
vendored
17
src/env.d.ts
vendored
|
|
@ -1,17 +0,0 @@
|
||||||
/* Ambient env typing for optional Vite-style env access */
|
|
||||||
declare interface ImportMeta {
|
|
||||||
env?: {
|
|
||||||
VITE_API_BASE_URL?: string
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export {}
|
|
||||||
/// <reference types="vite/client" />
|
|
||||||
|
|
||||||
interface ImportMetaEnv {
|
|
||||||
readonly VITE_API_BASE_URL?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ImportMeta {
|
|
||||||
readonly env: ImportMetaEnv
|
|
||||||
}
|
|
||||||
|
|
@ -1,27 +0,0 @@
|
||||||
/**
|
|
||||||
* Route parameter and query parsing helpers
|
|
||||||
* Centralizes route param type handling to avoid runtime checks in components
|
|
||||||
*/
|
|
||||||
|
|
||||||
import type { LocationQueryValue } from 'vue-router'
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parse a route param (string | string[] | undefined) to a number ID
|
|
||||||
* Returns null if param is missing or invalid
|
|
||||||
*/
|
|
||||||
export function parseRouteId(param: string | string[] | undefined): number | null {
|
|
||||||
if (!param) return null
|
|
||||||
const str = Array.isArray(param) ? param[0] : param
|
|
||||||
if (!str) return null
|
|
||||||
const id = parseInt(str, 10)
|
|
||||||
return isNaN(id) || id < 0 ? null : id
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parse a route query param to a string
|
|
||||||
* Returns empty string if param is missing, null, or is an array
|
|
||||||
*/
|
|
||||||
export function parseQueryString(param: LocationQueryValue | LocationQueryValue[] | undefined): string {
|
|
||||||
if (!param) return ''
|
|
||||||
return Array.isArray(param) ? '' : param
|
|
||||||
}
|
|
||||||
|
|
@ -1,18 +1,18 @@
|
||||||
import { createRouter, createWebHashHistory, Router } from 'vue-router'
|
import { createRouter, createWebHashHistory } from 'vue-router'
|
||||||
import type { RouteRecordRaw } from 'vue-router'
|
|
||||||
|
|
||||||
// Lazy-loaded route components
|
// Lazy-loaded route components
|
||||||
const LoginPage = () => import('@/components/LoginPage.vue')
|
const LoginPage = () => import('@/components/LoginPage.vue')
|
||||||
const RecipesPage = () => import('@/components/recipes/RecipesPage.vue')
|
const RecipesPage = () => import('@/components/recipes/RecipesPage.vue')
|
||||||
const MealPlanPage = () => import('@/components/meals/MealPlanPage.vue')
|
const MealPlanPage = () => import('@/components/meals/MealPlanPage.vue')
|
||||||
const MyShoppingPage = () => import('@/components/shopping/MyShoppingPage.vue')
|
const MyShoppingPage = () => import('@/components/shopping/MyShoppingPage.vue')
|
||||||
const PurchasedShoppingListPage = () => import('@/components/shopping/PurchasedShoppingListPage.vue')
|
const PurchasedShoppingListPage = () =>
|
||||||
|
import('@/components/shopping/PurchasedShoppingListPage.vue')
|
||||||
const CurrentShoppingListPage = () => import('@/components/shopping/CurrentShoppingListPage.vue')
|
const CurrentShoppingListPage = () => import('@/components/shopping/CurrentShoppingListPage.vue')
|
||||||
const EditMealPage = () => import('@/components/meals/EditMealPage.vue')
|
const EditMealPage = () => import('@/components/meals/EditMealPage.vue')
|
||||||
const EditRecipePage = () => import('@/components/recipes/EditRecipePage.vue')
|
const EditRecipePage = () => import('@/components/recipes/EditRecipePage.vue')
|
||||||
|
|
||||||
export function createAppRouter(getCurrentUser: () => Promise<unknown> | unknown): Router {
|
export function createAppRouter(getCurrentUser) {
|
||||||
const routes: RouteRecordRaw[] = [
|
const routes = [
|
||||||
{ path: '/', redirect: { name: 'mealplan' } },
|
{ path: '/', redirect: { name: 'mealplan' } },
|
||||||
{ path: '/login', name: 'login', component: LoginPage },
|
{ path: '/login', name: 'login', component: LoginPage },
|
||||||
{ path: '/mealplan', name: 'mealplan', component: MealPlanPage, meta: { requiresAuth: true } },
|
{ path: '/mealplan', name: 'mealplan', component: MealPlanPage, meta: { requiresAuth: true } },
|
||||||
|
|
@ -64,6 +64,7 @@ export function createAppRouter(getCurrentUser: () => Promise<unknown> | unknown
|
||||||
routes,
|
routes,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// Simple auth guard using provided getter
|
||||||
router.beforeEach(async (to) => {
|
router.beforeEach(async (to) => {
|
||||||
if (!to.meta.requiresAuth) return true
|
if (!to.meta.requiresAuth) return true
|
||||||
try {
|
try {
|
||||||
10
src/shims-vue.d.ts
vendored
10
src/shims-vue.d.ts
vendored
|
|
@ -1,10 +0,0 @@
|
||||||
declare module '*.vue' {
|
|
||||||
import type { DefineComponent } from 'vue'
|
|
||||||
// Use safer defaults to satisfy strict eslint rules (no banned {} or any)
|
|
||||||
const component: DefineComponent<
|
|
||||||
Record<string, unknown>,
|
|
||||||
Record<string, unknown>,
|
|
||||||
unknown
|
|
||||||
>
|
|
||||||
export default component
|
|
||||||
}
|
|
||||||
4
src/units.d.ts
vendored
4
src/units.d.ts
vendored
|
|
@ -1,4 +0,0 @@
|
||||||
export type QuantityTotal = { quantity: number; unit: string }
|
|
||||||
export declare function calculateTotals(
|
|
||||||
parts: Array<{ quantity: number; unit: string }>
|
|
||||||
): QuantityTotal[]
|
|
||||||
|
|
@ -1,7 +1,4 @@
|
||||||
const UNIT_KEYS_ARRAY: readonly ['kg', 'litres', 'items'] = ['kg', 'litres', 'items']
|
export const equivalentUnits = {
|
||||||
export type UnitKey = typeof UNIT_KEYS_ARRAY[number]
|
|
||||||
|
|
||||||
export const equivalentUnits: Record<UnitKey, Record<string, number>> = {
|
|
||||||
kg: {
|
kg: {
|
||||||
kgs: 1,
|
kgs: 1,
|
||||||
kilograms: 1,
|
kilograms: 1,
|
||||||
|
|
@ -88,52 +85,58 @@ export const equivalentUnits: Record<UnitKey, Record<string, number>> = {
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
const UNIT_KEYS_SET: ReadonlySet<string> = new Set(UNIT_KEYS_ARRAY)
|
function getBaseUnit(unit) {
|
||||||
function isUnitKey(value: string): value is UnitKey {
|
for (const unitType in equivalentUnits) {
|
||||||
return UNIT_KEYS_SET.has(value)
|
if (unit in equivalentUnits[unitType]) {
|
||||||
}
|
return unitType
|
||||||
|
}
|
||||||
function getBaseUnit(unit: string): UnitKey | null {
|
|
||||||
for (const type of UNIT_KEYS_ARRAY) {
|
|
||||||
const group = equivalentUnits[type]
|
|
||||||
if (unit in group) return type
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getConversionFactor(unit: string): { unit: UnitKey | string; factor: number } | null {
|
export function getConversionFactor(unit) {
|
||||||
if (isUnitKey(unit)) return { unit, factor: 1 }
|
if (unit in equivalentUnits) {
|
||||||
|
return { unit, factor: 1 }
|
||||||
|
}
|
||||||
|
|
||||||
const unitLower = String(unit).toLowerCase()
|
const unitLower = unit.toLowerCase()
|
||||||
if (isUnitKey(unitLower)) return { unit: unitLower, factor: 1 }
|
if (unitLower in equivalentUnits) {
|
||||||
|
return { unit: unitLower, factor: 1 }
|
||||||
|
}
|
||||||
|
|
||||||
const baseUnit = getBaseUnit(unit)
|
const baseUnit = getBaseUnit(unit)
|
||||||
if (baseUnit) {
|
if (baseUnit) {
|
||||||
const factor = equivalentUnits[baseUnit]?.[unit]
|
return {
|
||||||
if (typeof factor === 'number') return { unit: baseUnit, factor }
|
unit: baseUnit,
|
||||||
return null
|
factor: equivalentUnits[baseUnit][unit],
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const baseUnitLower = getBaseUnit(unitLower)
|
const baseUnitLower = getBaseUnit(unitLower)
|
||||||
if (baseUnitLower) {
|
if (baseUnitLower) {
|
||||||
const factor = equivalentUnits[baseUnitLower]?.[unitLower]
|
return {
|
||||||
if (typeof factor === 'number') return { unit: baseUnitLower, factor }
|
unit: baseUnitLower,
|
||||||
return null
|
factor: equivalentUnits[baseUnitLower][unitLower],
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
export type Quantity = { quantity: number; unit: string }
|
export function calculateTotals(quantityList) {
|
||||||
export type Total = { unit: string; quantity: number }
|
const totals = {}
|
||||||
|
|
||||||
export function calculateTotals(quantityList: Quantity[]): Total[] {
|
|
||||||
const totals: Record<string, number> = {}
|
|
||||||
for (const quantity of quantityList) {
|
for (const quantity of quantityList) {
|
||||||
const baseUnit = getConversionFactor(quantity.unit) ?? { unit: quantity.unit, factor: 1 }
|
const baseUnit = getConversionFactor(quantity.unit) ?? { unit: quantity.unit, factor: 1 }
|
||||||
const factor = baseUnit.factor
|
const factor = baseUnit.factor
|
||||||
const unit = String(baseUnit.unit)
|
const unit = baseUnit.unit
|
||||||
totals[unit] = (totals[unit] ?? 0) + quantity.quantity / factor
|
|
||||||
|
if (!totals[unit]) {
|
||||||
|
totals[unit] = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
totals[unit] += quantity.quantity / factor
|
||||||
}
|
}
|
||||||
return Object.keys(totals).map((unit) => ({ unit, quantity: totals[unit] ?? 0 }))
|
|
||||||
|
return Object.keys(totals).map((unit) => ({ unit, quantity: totals[unit] }))
|
||||||
}
|
}
|
||||||
|
|
@ -1,27 +1,27 @@
|
||||||
import { describe, it, expect } from 'vitest'
|
import { describe, it, expect } from 'vitest'
|
||||||
import { decodeMeal } from '@/domain/decoders'
|
import { mapMeal, mapMeals } from '@/api/mappers/mealMapper'
|
||||||
|
|
||||||
describe('mealMapper', () => {
|
describe('mealMapper', () => {
|
||||||
it('maps individual meal date fields to Date instances', () => {
|
it('maps individual meal date fields to Date instances', () => {
|
||||||
const input = {
|
const input = {
|
||||||
id: 1,
|
id: 1,
|
||||||
suggestedDate: '2025-01-01T00:00:00Z',
|
suggested_date: '2025-01-01T00:00:00Z',
|
||||||
purchaseDate: '2025-01-02T00:00:00Z',
|
purchase_date: '2025-01-02T00:00:00Z',
|
||||||
consumedDate: '2025-01-03T00:00:00Z',
|
consumed_date: '2025-01-03T00:00:00Z',
|
||||||
}
|
}
|
||||||
const result = decodeMeal({ ...input })
|
const result = mapMeal({ ...input })
|
||||||
expect(result.suggestedDate).toBeInstanceOf(Date)
|
expect(result.suggested_date).toBeInstanceOf(Date)
|
||||||
expect(result.purchaseDate).toBeInstanceOf(Date)
|
expect(result.purchase_date).toBeInstanceOf(Date)
|
||||||
expect(result.consumedDate).toBeInstanceOf(Date)
|
expect(result.consumed_date).toBeInstanceOf(Date)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('maps lists of meals', () => {
|
it('maps lists of meals', () => {
|
||||||
const input = [
|
const input = [
|
||||||
{ id: 1, suggestedDate: '2025-01-01T00:00:00Z' },
|
{ id: 1, suggested_date: '2025-01-01T00:00:00Z' },
|
||||||
{ id: 2, suggestedDate: '2025-01-02T00:00:00Z' },
|
{ id: 2, suggested_date: '2025-01-02T00:00:00Z' },
|
||||||
]
|
]
|
||||||
const result = input.map((m) => decodeMeal(m)).filter((m) => m)
|
const result = mapMeals(input)
|
||||||
expect(result).toHaveLength(2)
|
expect(result).toHaveLength(2)
|
||||||
expect(result[0].suggestedDate).toBeInstanceOf(Date)
|
expect(result[0].suggested_date).toBeInstanceOf(Date)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -1,14 +0,0 @@
|
||||||
import { describe, it, expect } from 'vitest'
|
|
||||||
import { server, http, HttpResponse } from './test-setup'
|
|
||||||
import { getUpcomingMeals } from '@/api/sdk'
|
|
||||||
|
|
||||||
describe('meals api (errors)', () => {
|
|
||||||
it('propagates errors on invalid upcoming range', async () => {
|
|
||||||
server.use(
|
|
||||||
http.get('*/api/v1/meals/upcoming', () => new HttpResponse(null, { status: 400 }))
|
|
||||||
)
|
|
||||||
await expect(
|
|
||||||
getUpcomingMeals(new Date('2025-01-03T00:00:00Z'), new Date('2025-01-01T00:00:00Z'))
|
|
||||||
).rejects.toBeTruthy()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
@ -1,43 +0,0 @@
|
||||||
import { describe, it, expect } from 'vitest'
|
|
||||||
import { server, http, HttpResponse } from './test-setup'
|
|
||||||
import { getMeal, markMealConsumed, getUpcomingMeals } from '@/api/sdk'
|
|
||||||
|
|
||||||
describe('meals api (typed client)', () => {
|
|
||||||
it('gets a meal by id', async () => {
|
|
||||||
server.use(
|
|
||||||
http.get('*/api/v1/meals/:id', ({ params }) => {
|
|
||||||
return HttpResponse.json({ id: params.id, suggestedDate: '2025-01-01T00:00:00Z' })
|
|
||||||
})
|
|
||||||
)
|
|
||||||
const meal = await getMeal(10)
|
|
||||||
expect(meal.id).toBeDefined()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('marks a meal consumed', async () => {
|
|
||||||
server.use(
|
|
||||||
http.post('*/api/v1/meals/:id/consumed', () => {
|
|
||||||
return HttpResponse.json({ id: 10, consumedDate: '2025-01-02T00:00:00Z' })
|
|
||||||
})
|
|
||||||
)
|
|
||||||
const meal = await markMealConsumed(10)
|
|
||||||
expect(meal.consumedDate).toBeInstanceOf(Date)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('lists upcoming meals', async () => {
|
|
||||||
server.use(
|
|
||||||
http.get('*/api/v1/meals/upcoming', ({ request }) => {
|
|
||||||
const url = new URL(request.url)
|
|
||||||
if (!url.searchParams.get('from') || !url.searchParams.get('to')) {
|
|
||||||
return new HttpResponse(null, { status: 400 })
|
|
||||||
}
|
|
||||||
return HttpResponse.json([
|
|
||||||
{ id: 1, suggestedDate: '2025-01-01T00:00:00Z' },
|
|
||||||
{ id: 2, suggestedDate: '2025-01-02T00:00:00Z' },
|
|
||||||
])
|
|
||||||
})
|
|
||||||
)
|
|
||||||
const list = await getUpcomingMeals(new Date('2025-01-01T00:00:00Z'), new Date('2025-01-03T00:00:00Z'))
|
|
||||||
expect(Array.isArray(list)).toBe(true)
|
|
||||||
expect(list[0].suggestedDate).toBeInstanceOf(Date)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
@ -1,19 +0,0 @@
|
||||||
import { describe, it, expect } from 'vitest'
|
|
||||||
import { server, http, HttpResponse } from './test-setup'
|
|
||||||
import { parseIngredients, parseRecipe } from '@/api/sdk'
|
|
||||||
|
|
||||||
describe('parse api errors', () => {
|
|
||||||
it('returns 422 for invalid ingredient lines', async () => {
|
|
||||||
server.use(
|
|
||||||
http.get('*/api/v1/recipes/ingredients/parse', () => new HttpResponse(null, { status: 422 }))
|
|
||||||
)
|
|
||||||
await expect(parseIngredients([''])).rejects.toBeTruthy()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('returns 422 for invalid recipe URL', async () => {
|
|
||||||
server.use(
|
|
||||||
http.get('*/api/v1/recipes/parse', () => new HttpResponse(null, { status: 422 }))
|
|
||||||
)
|
|
||||||
await expect(parseRecipe('not-a-url')).rejects.toBeTruthy()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
@ -1,48 +0,0 @@
|
||||||
import { describe, it, expect } from 'vitest'
|
|
||||||
import { server, http, HttpResponse } from './test-setup'
|
|
||||||
import { parseIngredients, parseProduct, parseRecipe } from '@/api/sdk'
|
|
||||||
|
|
||||||
// Parse endpoints: ingredients, product, recipe
|
|
||||||
|
|
||||||
describe('parse api (typed client)', () => {
|
|
||||||
it('parses ingredient lines', async () => {
|
|
||||||
server.use(
|
|
||||||
http.get('*/api/v1/recipes/ingredients/parse', () => {
|
|
||||||
return HttpResponse.json([
|
|
||||||
{ id: 1, name: 'Eggs', line: '2 eggs', unit: 'Items', quantity: 2 },
|
|
||||||
])
|
|
||||||
})
|
|
||||||
)
|
|
||||||
const result = await parseIngredients(['2 eggs'])
|
|
||||||
expect(result[0].name).toBe('Eggs')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('parses a recipe from URL', async () => {
|
|
||||||
server.use(
|
|
||||||
http.get('*/api/v1/recipes/parse', () => {
|
|
||||||
return HttpResponse.json({ id: 10, name: 'Pancakes', ingredients: [] })
|
|
||||||
})
|
|
||||||
)
|
|
||||||
const recipe = await parseRecipe('https://example.com/pancakes')
|
|
||||||
expect(recipe?.name).toBe('Pancakes')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('parses/creates a product from URL', async () => {
|
|
||||||
server.use(
|
|
||||||
http.post('*/api/v1/products', async ({ request }) => {
|
|
||||||
const body = await request.json()
|
|
||||||
if (!body?.url) return new HttpResponse(null, { status: 422 })
|
|
||||||
return HttpResponse.json({
|
|
||||||
id: 99,
|
|
||||||
name: 'Sample Product',
|
|
||||||
link: body.url,
|
|
||||||
unit: 'Items',
|
|
||||||
imgSmall: '',
|
|
||||||
imgLarge: '',
|
|
||||||
})
|
|
||||||
})
|
|
||||||
)
|
|
||||||
const product = await parseProduct({ name: 'Eggs', line: '2 eggs' }, 'https://store/item')
|
|
||||||
expect(product?.name).toBe('Sample Product')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
@ -1,12 +0,0 @@
|
||||||
import { describe, it, expect } from 'vitest'
|
|
||||||
import { server, http, HttpResponse } from './test-setup'
|
|
||||||
import { getPersonsInHome } from '@/api/sdk'
|
|
||||||
|
|
||||||
describe('persons api errors', () => {
|
|
||||||
it('propagates non-2xx errors', async () => {
|
|
||||||
server.use(
|
|
||||||
http.get('*/api/v1/persons', () => new HttpResponse(null, { status: 422 }))
|
|
||||||
)
|
|
||||||
await expect(getPersonsInHome()).rejects.toBeTruthy()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
@ -1,30 +0,0 @@
|
||||||
import { describe, it, expect } from 'vitest'
|
|
||||||
import { server, http, HttpResponse } from './test-setup'
|
|
||||||
import { getPersonsInHome, searchPersons } from '@/api/sdk'
|
|
||||||
|
|
||||||
// Persons API tests
|
|
||||||
|
|
||||||
describe('persons api (typed client)', () => {
|
|
||||||
it('lists persons in home', async () => {
|
|
||||||
server.use(
|
|
||||||
http.get('*/api/v1/persons', () => {
|
|
||||||
return HttpResponse.json([{ id: 1, name: 'Ada Lovelace' }])
|
|
||||||
})
|
|
||||||
)
|
|
||||||
const page = await getPersonsInHome()
|
|
||||||
expect(Array.isArray(page.items)).toBe(true)
|
|
||||||
expect(page.items[0].name).toBe('Ada Lovelace')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('searches persons by name', async () => {
|
|
||||||
server.use(
|
|
||||||
http.get('*/api/v1/persons', ({ request }) => {
|
|
||||||
const url = new URL(request.url)
|
|
||||||
const q = url.searchParams.get('q')
|
|
||||||
return HttpResponse.json(q ? [{ id: 2, name: 'Alan Turing' }] : [])
|
|
||||||
})
|
|
||||||
)
|
|
||||||
const page = await searchPersons('alan')
|
|
||||||
expect(page.items[0].name.toLowerCase()).toContain('alan')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
@ -1,12 +0,0 @@
|
||||||
import { describe, it, expect } from 'vitest'
|
|
||||||
import { server, http, HttpResponse } from './test-setup'
|
|
||||||
import { getRecipe } from '@/api/sdk'
|
|
||||||
|
|
||||||
describe('recipes api (errors)', () => {
|
|
||||||
it('throws on 404 getRecipe', async () => {
|
|
||||||
server.use(
|
|
||||||
http.get('*/api/v1/recipes/:id', () => new HttpResponse(null, { status: 404 }))
|
|
||||||
)
|
|
||||||
await expect(getRecipe('999')).rejects.toBeTruthy()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
@ -1,22 +0,0 @@
|
||||||
import { describe, it, expect } from 'vitest'
|
|
||||||
import { server, http, HttpResponse } from './test-setup'
|
|
||||||
import { getRecipe } from '@/api/sdk'
|
|
||||||
|
|
||||||
// Tests validate the typed client wrapper behavior without needing the backend
|
|
||||||
|
|
||||||
describe('recipes api (typed client)', () => {
|
|
||||||
it('gets a recipe by id', async () => {
|
|
||||||
server.use(
|
|
||||||
http.get('*/api/v1/recipes/:id', ({ params }) => {
|
|
||||||
// eslint-disable-next-line no-console
|
|
||||||
console.log('MSW handler hit with params:', params)
|
|
||||||
const { id } = params
|
|
||||||
return HttpResponse.json({ id, name: 'Pancakes', ingredients: [] }, { status: 200 })
|
|
||||||
})
|
|
||||||
)
|
|
||||||
|
|
||||||
const data = await getRecipe('123')
|
|
||||||
expect(data).toBeTruthy()
|
|
||||||
expect(data.name).toBe('Pancakes')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
@ -1,12 +0,0 @@
|
||||||
import { describe, it, expect } from 'vitest'
|
|
||||||
import { server, http, HttpResponse } from './test-setup'
|
|
||||||
import { purchaseShoppingList } from '@/api/sdk'
|
|
||||||
|
|
||||||
describe('shopping api (errors)', () => {
|
|
||||||
it('propagates errors on purchase failure', async () => {
|
|
||||||
server.use(
|
|
||||||
http.post('*/api/v1/shopping', () => new HttpResponse(null, { status: 422 }))
|
|
||||||
)
|
|
||||||
await expect(purchaseShoppingList([{ type: 'existing', id: 1, personId: 42 }])).rejects.toBeTruthy()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
@ -1,31 +0,0 @@
|
||||||
import { describe, it, expect } from 'vitest'
|
|
||||||
import { server, http, HttpResponse } from './test-setup'
|
|
||||||
import { getCurrentShoppingList, getShoppingList, requestMeal, unrequestMeal, purchaseShoppingList } from '@/api/sdk'
|
|
||||||
|
|
||||||
describe('shopping api (typed client)', () => {
|
|
||||||
it('gets current shopping list', async () => {
|
|
||||||
server.use(http.get('*/api/v1/shopping/current', () => HttpResponse.json({ outstandingItems: [] })))
|
|
||||||
const list = await getCurrentShoppingList()
|
|
||||||
expect(list).toBeTruthy()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('gets a purchased shopping list by id', async () => {
|
|
||||||
server.use(http.get('*/api/v1/shopping/:id', () => HttpResponse.json({ list: { id: 99, items: [] } })))
|
|
||||||
const list = await getShoppingList(99)
|
|
||||||
expect(list.id).toBe(99)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('requests and unrequests a meal', async () => {
|
|
||||||
server.use(http.post('*/api/v1/shopping/current/meals/me', () => HttpResponse.json([{ id: 1 }])))
|
|
||||||
await requestMeal(44)
|
|
||||||
|
|
||||||
server.use(http.delete('*/api/v1/shopping/current/meals/:id', () => new HttpResponse(null, { status: 204 })))
|
|
||||||
await unrequestMeal(44)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('purchases a list', async () => {
|
|
||||||
server.use(http.post('*/api/v1/shopping', () => HttpResponse.json({ list: { id: 1, items: [] } })))
|
|
||||||
const list = await purchaseShoppingList([{ type: 'existing', id: 1, personId: 42 }])
|
|
||||||
expect(list.id).toBe(1)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
@ -1,39 +1,33 @@
|
||||||
import { describe, it, expect } from 'vitest'
|
import { describe, it, expect } from 'vitest'
|
||||||
import { mapCurrentShoppingList, mapPurchasedShoppingList } from '@/api/sdk'
|
import { mapCurrentShoppingList, mapPurchasedShoppingList } from '@/api/mappers/shoppingListMapper'
|
||||||
|
|
||||||
describe('shoppingListMapper', () => {
|
describe('shoppingListMapper', () => {
|
||||||
it('maps current shopping list and wires references', () => {
|
it('maps current shopping list and wires references', () => {
|
||||||
const dto = {
|
const dto = {
|
||||||
ingredientsLookup: { 10: { id: 10, name: 'Eggs' } },
|
ingredients_lookup: { 10: { id: 10, name: 'Eggs' } },
|
||||||
mealsLookup: { 1: { id: 1, suggestedDate: '2025-01-01T00:00:00Z', recipes: [], extraIngredients: [], chefs: [], consumers: [], cleanup: [] } },
|
meals_lookup: { 1: { id: 1, suggested_date: '2025-01-01T00:00:00Z', recipes: [], extra_ingredients: [], chefs: [], consumers: [], cleanup: [] } },
|
||||||
recipesLookup: { 5: { id: 5, name: 'Omelette' } },
|
recipes_lookup: { 5: { id: 5, name: 'Omelette' } },
|
||||||
shoppingListLookup: { 7: { id: 7, createdDate: '2025-01-01T00:00:00Z' } },
|
shopping_list_lookup: { 7: { id: 7, created_date: '2025-01-01T00:00:00Z' } },
|
||||||
outstandingItems: [{ ingredientId: 10, mealId: 1, recipeId: 5, listId: 7, createdDate: '2025-01-01T00:00:00Z' }],
|
outstanding_items: [{ ingredient_id: 10, meal_id: 1, recipe_id: 5, list_id: 7, created_date: '2025-01-01T00:00:00Z' }],
|
||||||
requestedMeals: [],
|
requested_meals: [],
|
||||||
purchasedItems: [],
|
purchased_items: [],
|
||||||
}
|
}
|
||||||
const mapped = mapCurrentShoppingList(dto)
|
const mapped = mapCurrentShoppingList(dto)
|
||||||
// DEBUG
|
const item = mapped.outstanding_items[0]
|
||||||
// eslint-disable-next-line no-console
|
|
||||||
console.log('mapped current keys:', Object.keys(mapped || {}))
|
|
||||||
const item = mapped.outstandingItems[0]
|
|
||||||
expect(item.ingredient.name).toBe('Eggs')
|
expect(item.ingredient.name).toBe('Eggs')
|
||||||
expect(item.meal.suggestedDate).toBeInstanceOf(Date)
|
expect(item.meal.suggested_date).toBeInstanceOf(Date)
|
||||||
expect(mapped.shoppingListLookup['7'].createdDate).toBeInstanceOf(Date)
|
expect(mapped.shopping_list_lookup['7'].created_date).toBeInstanceOf(Date)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('maps purchased shopping list with list dates and item refs', () => {
|
it('maps purchased shopping list with list dates and item refs', () => {
|
||||||
const dto = {
|
const dto = {
|
||||||
ingredientsLookup: { 10: { id: 10, name: 'Eggs' } },
|
ingredients_lookup: { 10: { id: 10, name: 'Eggs' } },
|
||||||
mealsLookup: { 1: { id: 1, suggestedDate: '2025-01-01T00:00:00Z', recipes: [], extraIngredients: [], chefs: [], consumers: [], cleanup: [] } },
|
meals_lookup: { 1: { id: 1, suggested_date: '2025-01-01T00:00:00Z', recipes: [], extra_ingredients: [], chefs: [], consumers: [], cleanup: [] } },
|
||||||
recipesLookup: { 5: { id: 5, name: 'Omelette' } },
|
recipes_lookup: { 5: { id: 5, name: 'Omelette' } },
|
||||||
list: { id: 9, createdDate: '2025-02-02T00:00:00Z', items: [{ ingredientId: 10, mealId: 1, recipeId: 5, listId: 9 }] },
|
list: { id: 9, created_date: '2025-02-02T00:00:00Z', items: [{ ingredient_id: 10, meal_id: 1, recipe_id: 5, list_id: 9 }] },
|
||||||
}
|
}
|
||||||
const mapped = mapPurchasedShoppingList(dto)
|
const mapped = mapPurchasedShoppingList(dto)
|
||||||
// DEBUG
|
expect(mapped.list.created_date).toBeInstanceOf(Date)
|
||||||
// eslint-disable-next-line no-console
|
|
||||||
console.log('mapped purchased keys:', Object.keys(mapped || {}))
|
|
||||||
expect(mapped.list.createdDate).toBeInstanceOf(Date)
|
|
||||||
expect(mapped.list.items[0].recipe.name).toBe('Omelette')
|
expect(mapped.list.items[0].recipe.name).toBe('Omelette')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -1,24 +0,0 @@
|
||||||
import { afterAll, afterEach, beforeAll } from 'vitest'
|
|
||||||
import { setupServer } from 'msw/node'
|
|
||||||
import { http, HttpResponse } from 'msw'
|
|
||||||
|
|
||||||
// Ensure global fetch is available in Node tests
|
|
||||||
// Use Node 18+ global fetch (undici). Do not override so MSW can intercept.
|
|
||||||
|
|
||||||
// Some CI envs inject corporate roots causing TLS issues; disable cert checks in tests only
|
|
||||||
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'
|
|
||||||
// Ensure MSW intercepts local requests without going through a proxy
|
|
||||||
process.env.HTTP_PROXY = ''
|
|
||||||
process.env.HTTPS_PROXY = ''
|
|
||||||
process.env.ALL_PROXY = ''
|
|
||||||
process.env.NO_PROXY = '*'
|
|
||||||
|
|
||||||
export const server = setupServer()
|
|
||||||
|
|
||||||
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))
|
|
||||||
|
|
||||||
afterEach(() => server.resetHandlers())
|
|
||||||
|
|
||||||
afterAll(() => server.close())
|
|
||||||
|
|
||||||
export { http, HttpResponse }
|
|
||||||
|
|
@ -1,7 +1,26 @@
|
||||||
// Legacy JS test shim: the authoritative tests live in tests/useAlert.test.ts
|
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||||
// Keep a trivial passing test here so Vitest doesn't fail this file collection.
|
import { useAlert } from '@/composables/useAlert'
|
||||||
import { it, expect } from 'vitest'
|
|
||||||
|
|
||||||
it('noop shim (see useAlert.test.ts)', () => {
|
describe('useAlert', () => {
|
||||||
expect(true).toBe(true)
|
beforeEach(() => {
|
||||||
|
vi.useFakeTimers()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('shows and clears alerts', () => {
|
||||||
|
const { current, show, clear } = useAlert()
|
||||||
|
expect(current.value).toBeNull()
|
||||||
|
show({ heading: 'Hello', message: 'World', type: 'info' })
|
||||||
|
expect(current.value).toMatchObject({ heading: 'Hello', message: 'World', type: 'info' })
|
||||||
|
clear()
|
||||||
|
expect(current.value).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('auto-dismisses after scheduleAutoDismiss', () => {
|
||||||
|
const { current, show, scheduleAutoDismiss } = useAlert()
|
||||||
|
show({ heading: 'Auto', message: 'Dismiss', type: 'success' })
|
||||||
|
scheduleAutoDismiss(5000)
|
||||||
|
expect(current.value).not.toBeNull()
|
||||||
|
vi.advanceTimersByTime(5000)
|
||||||
|
expect(current.value).toBeNull()
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -1,26 +0,0 @@
|
||||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
|
||||||
import { useAlert } from '@/composables/useAlert'
|
|
||||||
|
|
||||||
describe('useAlert', () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
vi.useFakeTimers()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('shows and clears alerts', () => {
|
|
||||||
const { current, show, clear } = useAlert()
|
|
||||||
expect(current.value).toBeNull()
|
|
||||||
show({ heading: 'Hello', message: 'World', type: 'info' })
|
|
||||||
expect(current.value).toMatchObject({ heading: 'Hello', message: 'World', type: 'info' })
|
|
||||||
clear()
|
|
||||||
expect(current.value).toBeNull()
|
|
||||||
})
|
|
||||||
|
|
||||||
it('auto-dismisses after scheduleAutoDismiss', () => {
|
|
||||||
const { current, show, scheduleAutoDismiss } = useAlert()
|
|
||||||
show({ heading: 'Auto', message: 'Dismiss', type: 'success' })
|
|
||||||
scheduleAutoDismiss(5000)
|
|
||||||
expect(current.value).not.toBeNull()
|
|
||||||
vi.advanceTimersByTime(5000)
|
|
||||||
expect(current.value).toBeNull()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
@ -1,20 +0,0 @@
|
||||||
{
|
|
||||||
"extends": "./tsconfig.json",
|
|
||||||
"compilerOptions": {
|
|
||||||
"noEmit": true
|
|
||||||
},
|
|
||||||
"include": [
|
|
||||||
"src/**/*.ts",
|
|
||||||
"src/**/*.vue",
|
|
||||||
"src/**/*.d.ts"
|
|
||||||
],
|
|
||||||
"exclude": [
|
|
||||||
"node_modules",
|
|
||||||
"dist",
|
|
||||||
"tests/**/*.js",
|
|
||||||
"*.config.js",
|
|
||||||
"babel.config.js",
|
|
||||||
"vitest.config.js",
|
|
||||||
"vue.config.js"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
@ -1,20 +0,0 @@
|
||||||
{
|
|
||||||
"compilerOptions": {
|
|
||||||
"target": "ES2022",
|
|
||||||
"module": "ESNext",
|
|
||||||
"strict": true,
|
|
||||||
"exactOptionalPropertyTypes": true,
|
|
||||||
"noUncheckedIndexedAccess": true,
|
|
||||||
"moduleResolution": "Bundler",
|
|
||||||
"jsx": "preserve",
|
|
||||||
"allowJs": false,
|
|
||||||
"checkJs": false,
|
|
||||||
"skipLibCheck": true,
|
|
||||||
"types": ["node", "vite/client"],
|
|
||||||
"baseUrl": ".",
|
|
||||||
"paths": {
|
|
||||||
"@/*": ["src/*"]
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.vue"]
|
|
||||||
}
|
|
||||||
|
|
@ -12,6 +12,5 @@ export default defineConfig({
|
||||||
include: ['tests/**/*.{test,spec}.js'],
|
include: ['tests/**/*.{test,spec}.js'],
|
||||||
globals: true,
|
globals: true,
|
||||||
reporters: 'default',
|
reporters: 'default',
|
||||||
setupFiles: ['tests/test-setup.js'],
|
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,4 @@
|
||||||
/* eslint-disable @typescript-eslint/no-var-requires */
|
|
||||||
const { defineConfig } = require('@vue/cli-service')
|
const { defineConfig } = require('@vue/cli-service')
|
||||||
/* eslint-enable @typescript-eslint/no-var-requires */
|
|
||||||
module.exports = defineConfig({
|
module.exports = defineConfig({
|
||||||
transpileDependencies: true,
|
transpileDependencies: true,
|
||||||
})
|
})
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue