diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..fedfc3e --- /dev/null +++ b/.env.example @@ -0,0 +1,39 @@ +# ───────────────────────────────────────────── +# Pantree Backend — Environment Variables +# Copy to .env and fill in real values. +# NEVER commit .env to version control. +# ───────────────────────────────────────────── + +# Server +PORT=3000 +NODE_ENV=development + +# PostgreSQL +DB_HOST=localhost +DB_PORT=5432 +DB_NAME=pantree +DB_USER=postgres +DB_PASSWORD=changeme + +# JWT — use a long random secret in production +JWT_SECRET=change-this-to-a-long-random-secret +JWT_EXPIRES_IN=24h + +# Google OAuth +GOOGLE_CLIENT_ID=your-google-client-id.apps.googleusercontent.com + +# Email (SMTP / SendGrid / SES) +EMAIL_HOST=smtp.ethereal.email +EMAIL_PORT=587 +EMAIL_USER= +EMAIL_PASS= +EMAIL_FROM=noreply@pantree.app + +# App base URL (used in password-reset links) +APP_BASE_URL=https://pantree.app + +# Account deletion window (days) +ACCOUNT_DELETION_DAYS=15 + +# Password reset token expiry (hours) +RESET_TOKEN_EXPIRY_HOURS=1 diff --git a/package.json b/package.json new file mode 100644 index 0000000..6c42c74 --- /dev/null +++ b/package.json @@ -0,0 +1,36 @@ +{ + "name": "pantree-backend", + "version": "1.0.0", + "description": "Pantree backend API server", + "main": "src/main/index.js", + "scripts": { + "start": "node src/main/index.js", + "dev": "nodemon src/main/index.js", + "test": "jest --runInBand --forceExit", + "test:coverage": "jest --runInBand --forceExit --coverage" + }, + "dependencies": { + "bcrypt": "^5.1.1", + "cors": "^2.8.5", + "dotenv": "^16.3.1", + "express": "^4.18.2", + "jsonwebtoken": "^9.0.2", + "knex": "^3.1.0", + "node-cron": "^3.0.3", + "nodemailer": "^6.9.7", + "pg": "^8.11.3", + "uuid": "^9.0.0", + "zod": "^3.22.4" + }, + "devDependencies": { + "jest": "^29.7.0", + "supertest": "^6.3.3" + }, + "jest": { + "testEnvironment": "node", + "testMatch": [ + "**/tests/**/*.test.js" + ], + "setupFilesAfterFramework": [] + } +} diff --git a/src/config/index.js b/src/config/index.js new file mode 100644 index 0000000..7cc79ee --- /dev/null +++ b/src/config/index.js @@ -0,0 +1,38 @@ +'use strict'; + +require('dotenv').config(); + +module.exports = { + port: parseInt(process.env.PORT || '3000', 10), + nodeEnv: process.env.NODE_ENV || 'development', + + db: { + host: process.env.DB_HOST || 'localhost', + port: parseInt(process.env.DB_PORT || '5432', 10), + database: process.env.DB_NAME || 'pantree', + user: process.env.DB_USER || 'postgres', + password: process.env.DB_PASSWORD || '', + }, + + jwt: { + secret: process.env.JWT_SECRET || 'dev-secret-change-in-production', + expiresIn: process.env.JWT_EXPIRES_IN || '24h', + }, + + google: { + clientId: process.env.GOOGLE_CLIENT_ID || '', + }, + + email: { + host: process.env.EMAIL_HOST || 'smtp.ethereal.email', + port: parseInt(process.env.EMAIL_PORT || '587', 10), + user: process.env.EMAIL_USER || '', + pass: process.env.EMAIL_PASS || '', + from: process.env.EMAIL_FROM || 'noreply@pantree.app', + }, + + appBaseUrl: process.env.APP_BASE_URL || 'https://pantree.app', + + accountDeletionDays: parseInt(process.env.ACCOUNT_DELETION_DAYS || '15', 10), + resetTokenExpiryHours: parseInt(process.env.RESET_TOKEN_EXPIRY_HOURS || '1', 10), +}; diff --git a/src/db/knex.js b/src/db/knex.js new file mode 100644 index 0000000..caac7c7 --- /dev/null +++ b/src/db/knex.js @@ -0,0 +1,31 @@ +'use strict'; + +const knex = require('knex'); +const config = require('../config'); + +let instance = null; + +/** + * Returns the singleton Knex instance. + * In tests, call setDb() to inject a test database. + */ +function getDb() { + if (!instance) { + instance = knex({ + client: 'pg', + connection: config.db, + pool: { min: 2, max: 10 }, + }); + } + return instance; +} + +/** + * Replaces the singleton — used in tests to inject an in-memory or + * test-scoped database without touching the real connection. + */ +function setDb(db) { + instance = db; +} + +module.exports = { getDb, setDb }; diff --git a/src/db/migrations/001_initial_schema.sql b/src/db/migrations/001_initial_schema.sql new file mode 100644 index 0000000..3a0a2c9 --- /dev/null +++ b/src/db/migrations/001_initial_schema.sql @@ -0,0 +1,199 @@ +-- Migration: 001_initial_schema.sql +-- Full schema for Pantree Phase 1 MVP +-- Run once against a fresh PostgreSQL 15+ database. + +-- ───────────────────────────────────────────── +-- Extensions +-- ───────────────────────────────────────────── +CREATE EXTENSION IF NOT EXISTS pgcrypto; + +-- ───────────────────────────────────────────── +-- USERS +-- ───────────────────────────────────────────── +CREATE TABLE IF NOT EXISTS users ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + email VARCHAR(255) NOT NULL, + password_hash VARCHAR(255) NULL, + name VARCHAR(100) NOT NULL, + profile_picture_url TEXT NULL, + auth_provider VARCHAR(20) NOT NULL DEFAULT 'email', + google_id VARCHAR(255) NULL, + email_verified BOOLEAN NOT NULL DEFAULT FALSE, + deleted_at TIMESTAMPTZ NULL, + deletion_scheduled_at TIMESTAMPTZ NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_users_email + ON users (LOWER(email)); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_users_google_id + ON users (google_id) + WHERE google_id IS NOT NULL; + +CREATE INDEX IF NOT EXISTS idx_users_deletion_scheduled + ON users (deletion_scheduled_at) + WHERE deletion_scheduled_at IS NOT NULL; + +-- ───────────────────────────────────────────── +-- PANTRY ITEMS +-- ───────────────────────────────────────────── +CREATE TABLE IF NOT EXISTS pantry_items ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + item_name VARCHAR(200) NOT NULL, + item_name_lower VARCHAR(200) GENERATED ALWAYS AS (LOWER(item_name)) STORED, + quantity INTEGER NOT NULL CHECK (quantity > 0), + last_modified TIMESTAMPTZ NOT NULL DEFAULT NOW(), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_pantry_user_item + ON pantry_items (user_id, item_name_lower); + +CREATE INDEX IF NOT EXISTS idx_pantry_user_id + ON pantry_items (user_id); + +CREATE INDEX IF NOT EXISTS idx_pantry_last_modified + ON pantry_items (user_id, last_modified); + +-- ───────────────────────────────────────────── +-- RECIPES +-- ───────────────────────────────────────────── +CREATE TABLE IF NOT EXISTS recipes ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + name VARCHAR(300) NOT NULL, + instructions TEXT NOT NULL, + servings INTEGER NOT NULL CHECK (servings > 0), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE INDEX IF NOT EXISTS idx_recipes_name + ON recipes (LOWER(name)); + +-- ───────────────────────────────────────────── +-- RECIPE INGREDIENTS +-- ───────────────────────────────────────────── +CREATE TABLE IF NOT EXISTS recipe_ingredients ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + recipe_id UUID NOT NULL REFERENCES recipes(id) ON DELETE CASCADE, + item_name VARCHAR(200) NOT NULL, + item_name_lower VARCHAR(200) GENERATED ALWAYS AS (LOWER(item_name)) STORED, + quantity DECIMAL(10,4) NOT NULL CHECK (quantity > 0), + unit VARCHAR(50) NOT NULL +); + +CREATE INDEX IF NOT EXISTS idx_recipe_ingredients_recipe + ON recipe_ingredients (recipe_id); + +CREATE INDEX IF NOT EXISTS idx_recipe_ingredients_name + ON recipe_ingredients (item_name_lower); + +-- ───────────────────────────────────────────── +-- SHOPPING LISTS +-- ───────────────────────────────────────────── +CREATE TABLE IF NOT EXISTS shopping_lists ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + list_name VARCHAR(200) NOT NULL, + last_modified TIMESTAMPTZ NOT NULL DEFAULT NOW(), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE INDEX IF NOT EXISTS idx_shopping_lists_user + ON shopping_lists (user_id); + +CREATE INDEX IF NOT EXISTS idx_shopping_lists_last_modified + ON shopping_lists (user_id, last_modified); + +-- ───────────────────────────────────────────── +-- SHOPPING LIST ITEMS +-- ───────────────────────────────────────────── +CREATE TABLE IF NOT EXISTS shopping_list_items ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + shopping_list_id UUID NOT NULL REFERENCES shopping_lists(id) ON DELETE CASCADE, + item_name VARCHAR(200) NOT NULL, + item_name_lower VARCHAR(200) GENERATED ALWAYS AS (LOWER(item_name)) STORED, + quantity DECIMAL(10,4) NOT NULL CHECK (quantity > 0), + unit VARCHAR(50) NOT NULL, + checked_off BOOLEAN NOT NULL DEFAULT FALSE, + last_modified TIMESTAMPTZ NOT NULL DEFAULT NOW(), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_shopping_list_items_merge + ON shopping_list_items (shopping_list_id, item_name_lower, unit); + +CREATE INDEX IF NOT EXISTS idx_shopping_list_items_list + ON shopping_list_items (shopping_list_id); + +CREATE INDEX IF NOT EXISTS idx_shopping_list_items_last_modified + ON shopping_list_items (shopping_list_id, last_modified); + +-- ───────────────────────────────────────────── +-- PASSWORD RESET TOKENS +-- ───────────────────────────────────────────── +CREATE TABLE IF NOT EXISTS password_reset_tokens ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + token_hash VARCHAR(255) NOT NULL, + expires_at TIMESTAMPTZ NOT NULL, + used_at TIMESTAMPTZ NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_password_reset_token_hash + ON password_reset_tokens (token_hash); + +CREATE INDEX IF NOT EXISTS idx_password_reset_user + ON password_reset_tokens (user_id); + +-- ───────────────────────────────────────────── +-- DELETED RECORDS (tombstones for sync) +-- ───────────────────────────────────────────── +CREATE TABLE IF NOT EXISTS deleted_records ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + record_type VARCHAR(50) NOT NULL, + record_id UUID NOT NULL, + deleted_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE INDEX IF NOT EXISTS idx_deleted_records_user + ON deleted_records (user_id, deleted_at); + +-- ───────────────────────────────────────────── +-- updated_at TRIGGER +-- ───────────────────────────────────────────── +CREATE OR REPLACE FUNCTION set_updated_at() +RETURNS TRIGGER AS $$ +BEGIN + NEW.updated_at = NOW(); + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_users_updated_at + BEFORE UPDATE ON users + FOR EACH ROW EXECUTE FUNCTION set_updated_at(); + +CREATE TRIGGER trg_pantry_updated_at + BEFORE UPDATE ON pantry_items + FOR EACH ROW EXECUTE FUNCTION set_updated_at(); + +CREATE TRIGGER trg_recipes_updated_at + BEFORE UPDATE ON recipes + FOR EACH ROW EXECUTE FUNCTION set_updated_at(); + +CREATE TRIGGER trg_shopping_lists_updated_at + BEFORE UPDATE ON shopping_lists + FOR EACH ROW EXECUTE FUNCTION set_updated_at(); + +CREATE TRIGGER trg_shopping_list_items_updated_at + BEFORE UPDATE ON shopping_list_items + FOR EACH ROW EXECUTE FUNCTION set_updated_at(); diff --git a/src/db/migrations/002_seed_recipes.sql b/src/db/migrations/002_seed_recipes.sql new file mode 100644 index 0000000..4d22b15 --- /dev/null +++ b/src/db/migrations/002_seed_recipes.sql @@ -0,0 +1,282 @@ +-- Seed: 002_seed_recipes.sql +-- 50 pre-populated recipes for Pantree Phase 1. +-- Recipes are read-only in Phase 1 — users cannot create or modify them. + +INSERT INTO recipes (id, name, instructions, servings) VALUES + ('00000000-0000-0000-0000-000000000001', 'Classic Pancakes', + E'1. Whisk together flour, baking powder, salt, and sugar.\n2. In a separate bowl, mix milk, egg, and melted butter.\n3. Combine wet and dry ingredients until just mixed.\n4. Cook on a greased griddle over medium heat until bubbles form, then flip.\n5. Serve warm with maple syrup.', + 4), + ('00000000-0000-0000-0000-000000000002', 'Scrambled Eggs', + E'1. Crack eggs into a bowl, add milk, salt, and pepper. Whisk well.\n2. Melt butter in a non-stick pan over low heat.\n3. Pour in egg mixture and stir gently with a spatula.\n4. Remove from heat while still slightly wet — residual heat finishes cooking.\n5. Serve immediately.', + 2), + ('00000000-0000-0000-0000-000000000003', 'Spaghetti Bolognese', + E'1. Brown ground beef in a large pan over medium-high heat. Drain fat.\n2. Add diced onion and garlic; cook until softened.\n3. Stir in tomato paste, crushed tomatoes, oregano, salt, and pepper.\n4. Simmer for 20 minutes.\n5. Cook spaghetti per package instructions.\n6. Serve sauce over pasta with grated parmesan.', + 4), + ('00000000-0000-0000-0000-000000000004', 'Caesar Salad', + E'1. Tear romaine lettuce into bite-sized pieces.\n2. Whisk together olive oil, lemon juice, garlic, worcestershire sauce, and parmesan.\n3. Toss lettuce with dressing.\n4. Top with croutons and extra parmesan.\n5. Season with black pepper.', + 2), + ('00000000-0000-0000-0000-000000000005', 'Chicken Stir Fry', + E'1. Slice chicken breast into thin strips. Season with salt and pepper.\n2. Heat oil in a wok over high heat.\n3. Cook chicken until golden, about 5 minutes. Remove.\n4. Stir fry vegetables (bell pepper, broccoli, carrot) for 3 minutes.\n5. Return chicken, add soy sauce and sesame oil.\n6. Serve over steamed rice.', + 3), + ('00000000-0000-0000-0000-000000000006', 'Banana Bread', + E'1. Preheat oven to 350°F (175°C). Grease a loaf pan.\n2. Mash 3 ripe bananas in a bowl.\n3. Mix in melted butter, sugar, egg, and vanilla.\n4. Stir in flour, baking soda, and salt until just combined.\n5. Pour into pan and bake 60 minutes until a toothpick comes out clean.', + 8), + ('00000000-0000-0000-0000-000000000007', 'Tomato Soup', + E'1. Sauté diced onion and garlic in butter until soft.\n2. Add crushed tomatoes, chicken broth, sugar, salt, and pepper.\n3. Simmer 15 minutes.\n4. Blend until smooth with an immersion blender.\n5. Stir in heavy cream. Adjust seasoning.\n6. Serve with crusty bread.', + 4), + ('00000000-0000-0000-0000-000000000008', 'Grilled Cheese Sandwich', + E'1. Butter one side of each bread slice.\n2. Place one slice butter-side down in a pan over medium heat.\n3. Layer cheese slices on top.\n4. Place second slice butter-side up.\n5. Cook until golden, about 3 minutes per side.\n6. Slice diagonally and serve.', + 1), + ('00000000-0000-0000-0000-000000000009', 'Chocolate Chip Cookies', + E'1. Preheat oven to 375°F (190°C).\n2. Cream butter and sugars until fluffy.\n3. Beat in eggs and vanilla.\n4. Mix in flour, baking soda, and salt.\n5. Fold in chocolate chips.\n6. Drop spoonfuls onto baking sheet.\n7. Bake 9–11 minutes until edges are golden.', + 24), + ('00000000-0000-0000-0000-000000000010', 'Guacamole', + E'1. Halve and pit avocados. Scoop flesh into a bowl.\n2. Mash with a fork to desired consistency.\n3. Stir in lime juice, salt, diced onion, cilantro, and jalapeño.\n4. Taste and adjust seasoning.\n5. Serve immediately with tortilla chips.', + 4), + ('00000000-0000-0000-0000-000000000011', 'French Toast', + E'1. Whisk eggs, milk, cinnamon, and vanilla in a shallow bowl.\n2. Dip bread slices in egg mixture, coating both sides.\n3. Cook in buttered pan over medium heat until golden, about 2 minutes per side.\n4. Serve with powdered sugar and maple syrup.', + 2), + ('00000000-0000-0000-0000-000000000012', 'Chicken Soup', + E'1. Simmer chicken thighs in water with salt for 30 minutes. Remove and shred.\n2. Add diced carrots, celery, and onion to broth.\n3. Cook vegetables until tender, about 15 minutes.\n4. Return shredded chicken to pot.\n5. Add egg noodles and cook per package instructions.\n6. Season with salt, pepper, and parsley.', + 6), + ('00000000-0000-0000-0000-000000000013', 'Fried Rice', + E'1. Cook rice and let cool completely (day-old rice works best).\n2. Scramble eggs in a wok with a little oil. Remove.\n3. Stir fry diced onion, carrot, and peas in oil.\n4. Add rice and stir fry over high heat.\n5. Return eggs, add soy sauce and sesame oil.\n6. Toss and serve.', + 3), + ('00000000-0000-0000-0000-000000000014', 'Beef Tacos', + E'1. Brown ground beef with diced onion and garlic.\n2. Season with cumin, chili powder, salt, and pepper.\n3. Warm taco shells in oven.\n4. Fill shells with beef, shredded cheese, lettuce, and tomato.\n5. Top with sour cream and salsa.', + 4), + ('00000000-0000-0000-0000-000000000015', 'Oatmeal', + E'1. Bring water or milk to a boil in a saucepan.\n2. Stir in oats and reduce heat to medium.\n3. Cook, stirring occasionally, for 5 minutes.\n4. Remove from heat and let stand 2 minutes.\n5. Top with brown sugar, cinnamon, and fruit.', + 2), + ('00000000-0000-0000-0000-000000000016', 'Pasta Carbonara', + E'1. Cook spaghetti in salted boiling water until al dente.\n2. Fry diced pancetta until crispy.\n3. Whisk eggs, parmesan, and black pepper in a bowl.\n4. Drain pasta, reserving 1 cup pasta water.\n5. Off heat, toss pasta with pancetta, then egg mixture, adding pasta water to loosen.\n6. Serve immediately with extra parmesan.', + 2), + ('00000000-0000-0000-0000-000000000017', 'Vegetable Curry', + E'1. Sauté diced onion, garlic, and ginger in oil.\n2. Add curry powder, cumin, and turmeric; cook 1 minute.\n3. Add diced potato, cauliflower, and chickpeas.\n4. Pour in coconut milk and vegetable broth.\n5. Simmer 20 minutes until vegetables are tender.\n6. Serve over basmati rice.', + 4), + ('00000000-0000-0000-0000-000000000018', 'BLT Sandwich', + E'1. Cook bacon until crispy.\n2. Toast bread slices.\n3. Spread mayonnaise on both slices.\n4. Layer lettuce, tomato slices, and bacon.\n5. Season with salt and pepper.\n6. Close sandwich and slice in half.', + 1), + ('00000000-0000-0000-0000-000000000019', 'Lemon Garlic Shrimp', + E'1. Season shrimp with salt, pepper, and paprika.\n2. Melt butter in a pan over medium-high heat.\n3. Add minced garlic and cook 30 seconds.\n4. Add shrimp and cook 2 minutes per side.\n5. Squeeze lemon juice over shrimp.\n6. Garnish with parsley and serve over pasta or rice.', + 2), + ('00000000-0000-0000-0000-000000000020', 'Apple Pie', + E'1. Preheat oven to 425°F (220°C).\n2. Peel, core, and slice apples. Toss with sugar, cinnamon, and flour.\n3. Line pie dish with bottom crust.\n4. Fill with apple mixture and dot with butter.\n5. Cover with top crust, seal edges, and cut vents.\n6. Bake 45–50 minutes until golden.', + 8), + ('00000000-0000-0000-0000-000000000021', 'Minestrone Soup', + E'1. Sauté onion, carrot, and celery in olive oil.\n2. Add garlic, diced tomatoes, and tomato paste.\n3. Pour in vegetable broth. Add kidney beans and zucchini.\n4. Simmer 20 minutes.\n5. Add small pasta and cook until tender.\n6. Season with salt, pepper, and basil.', + 6), + ('00000000-0000-0000-0000-000000000022', 'Quesadillas', + E'1. Place a flour tortilla in a dry pan over medium heat.\n2. Sprinkle shredded cheese on one half.\n3. Add diced chicken, peppers, and onion.\n4. Fold tortilla in half and cook until golden, about 2 minutes per side.\n5. Slice into wedges and serve with salsa and sour cream.', + 2), + ('00000000-0000-0000-0000-000000000023', 'Baked Salmon', + E'1. Preheat oven to 400°F (200°C).\n2. Place salmon fillets on a lined baking sheet.\n3. Brush with olive oil, lemon juice, garlic, and dill.\n4. Season with salt and pepper.\n5. Bake 12–15 minutes until fish flakes easily.\n6. Serve with roasted vegetables.', + 2), + ('00000000-0000-0000-0000-000000000024', 'Hummus', + E'1. Drain and rinse chickpeas, reserving liquid.\n2. Blend chickpeas, tahini, lemon juice, garlic, and salt in a food processor.\n3. Add reserved liquid or water to reach desired consistency.\n4. Drizzle with olive oil and sprinkle with paprika.\n5. Serve with pita bread or vegetables.', + 6), + ('00000000-0000-0000-0000-000000000025', 'Beef Stew', + E'1. Brown beef chunks in oil in a Dutch oven. Remove.\n2. Sauté onion, carrot, and celery until softened.\n3. Add garlic, tomato paste, and flour; cook 1 minute.\n4. Return beef, add beef broth, potatoes, and thyme.\n5. Simmer covered for 1.5 hours until beef is tender.\n6. Season and serve.', + 6), + ('00000000-0000-0000-0000-000000000026', 'Smoothie Bowl', + E'1. Blend frozen banana, frozen berries, and milk until thick.\n2. Pour into a bowl.\n3. Top with granola, sliced fresh fruit, and honey.\n4. Add chia seeds and coconut flakes if desired.\n5. Serve immediately.', + 1), + ('00000000-0000-0000-0000-000000000027', 'Shakshuka', + E'1. Sauté diced onion and bell pepper in olive oil.\n2. Add garlic, cumin, paprika, and chili flakes; cook 1 minute.\n3. Pour in crushed tomatoes. Simmer 10 minutes.\n4. Make wells in the sauce and crack eggs into them.\n5. Cover and cook until whites are set but yolks are runny.\n6. Garnish with feta and parsley.', + 2), + ('00000000-0000-0000-0000-000000000028', 'Pesto Pasta', + E'1. Cook pasta in salted boiling water until al dente.\n2. Blend basil, pine nuts, parmesan, garlic, and olive oil into pesto.\n3. Drain pasta, reserving ½ cup pasta water.\n4. Toss pasta with pesto, adding pasta water to loosen.\n5. Season with salt and pepper.\n6. Serve with extra parmesan.', + 3), + ('00000000-0000-0000-0000-000000000029', 'Roast Chicken', + E'1. Preheat oven to 425°F (220°C).\n2. Pat chicken dry. Rub with butter, garlic, salt, pepper, and herbs.\n3. Stuff cavity with lemon halves and fresh thyme.\n4. Roast breast-side up for 1 hour 15 minutes.\n5. Rest 10 minutes before carving.\n6. Serve with pan juices.', + 4), + ('00000000-0000-0000-0000-000000000030', 'Chocolate Brownies', + E'1. Preheat oven to 350°F (175°C). Grease an 8x8 pan.\n2. Melt butter and chocolate together.\n3. Whisk in sugar, eggs, and vanilla.\n4. Fold in flour, cocoa powder, and salt.\n5. Pour into pan and bake 25–30 minutes.\n6. Cool completely before cutting.', + 16), + ('00000000-0000-0000-0000-000000000031', 'Greek Salad', + E'1. Chop cucumber, tomatoes, and red onion.\n2. Add kalamata olives and cubed feta cheese.\n3. Drizzle with olive oil and red wine vinegar.\n4. Season with oregano, salt, and pepper.\n5. Toss gently and serve.', + 2), + ('00000000-0000-0000-0000-000000000032', 'Mashed Potatoes', + E'1. Peel and cube potatoes. Boil in salted water until tender, about 15 minutes.\n2. Drain and return to pot.\n3. Mash with butter and warm milk until smooth.\n4. Season generously with salt and pepper.\n5. Serve immediately.', + 4), + ('00000000-0000-0000-0000-000000000033', 'Lentil Soup', + E'1. Sauté diced onion, carrot, and celery in olive oil.\n2. Add garlic, cumin, and turmeric; cook 1 minute.\n3. Add rinsed red lentils and vegetable broth.\n4. Simmer 25 minutes until lentils are soft.\n5. Blend partially for a creamy texture.\n6. Season with lemon juice, salt, and pepper.', + 4), + ('00000000-0000-0000-0000-000000000034', 'Avocado Toast', + E'1. Toast bread slices until golden.\n2. Mash avocado with lemon juice, salt, and pepper.\n3. Spread avocado on toast.\n4. Top with red pepper flakes and everything bagel seasoning.\n5. Optional: add a poached egg on top.', + 1), + ('00000000-0000-0000-0000-000000000035', 'Chicken Tikka Masala', + E'1. Marinate chicken in yogurt, lemon juice, and spices for 1 hour.\n2. Grill or broil chicken until charred. Set aside.\n3. Sauté onion, garlic, and ginger in oil.\n4. Add tomato purée, cream, and spices. Simmer 10 minutes.\n5. Add chicken and simmer 10 more minutes.\n6. Serve over basmati rice with naan.', + 4), + ('00000000-0000-0000-0000-000000000036', 'Waffles', + E'1. Preheat waffle iron.\n2. Whisk flour, baking powder, sugar, and salt.\n3. Mix milk, eggs, and melted butter separately.\n4. Combine wet and dry ingredients until just mixed.\n5. Pour batter into waffle iron and cook until golden.\n6. Serve with butter and maple syrup.', + 4), + ('00000000-0000-0000-0000-000000000037', 'Tuna Salad', + E'1. Drain canned tuna and flake into a bowl.\n2. Add mayonnaise, diced celery, and red onion.\n3. Season with lemon juice, salt, and pepper.\n4. Mix well.\n5. Serve on bread, crackers, or lettuce cups.', + 2), + ('00000000-0000-0000-0000-000000000038', 'Mushroom Risotto', + E'1. Sauté diced onion in butter until soft.\n2. Add arborio rice and toast 1 minute.\n3. Add white wine and stir until absorbed.\n4. Add warm broth one ladle at a time, stirring constantly.\n5. Stir in sautéed mushrooms and parmesan.\n6. Season with salt, pepper, and fresh thyme.', + 3), + ('00000000-0000-0000-0000-000000000039', 'Blueberry Muffins', + E'1. Preheat oven to 375°F (190°C). Line muffin tin.\n2. Whisk flour, sugar, baking powder, and salt.\n3. Mix milk, egg, and melted butter.\n4. Combine wet and dry ingredients until just mixed.\n5. Fold in blueberries.\n6. Fill muffin cups ¾ full and bake 20–25 minutes.', + 12), + ('00000000-0000-0000-0000-000000000040', 'Pad Thai', + E'1. Soak rice noodles in warm water 30 minutes. Drain.\n2. Stir fry shrimp or chicken in oil. Remove.\n3. Scramble eggs in the same pan.\n4. Add noodles, protein, bean sprouts, and green onions.\n5. Pour in pad thai sauce (fish sauce, tamarind, sugar).\n6. Toss and serve with lime, peanuts, and chili flakes.', + 2), + ('00000000-0000-0000-0000-000000000041', 'Corn Chowder', + E'1. Cook diced bacon until crispy. Remove.\n2. Sauté onion and celery in bacon fat.\n3. Add diced potato, corn kernels, and chicken broth.\n4. Simmer 15 minutes until potato is tender.\n5. Stir in heavy cream and season.\n6. Top with bacon and chives.', + 4), + ('00000000-0000-0000-0000-000000000042', 'Egg Fried Noodles', + E'1. Cook noodles per package instructions. Drain.\n2. Scramble eggs in a wok with oil. Remove.\n3. Stir fry garlic and green onion.\n4. Add noodles and toss over high heat.\n5. Return eggs, add soy sauce and sesame oil.\n6. Serve immediately.', + 2), + ('00000000-0000-0000-0000-000000000043', 'Caprese Salad', + E'1. Slice fresh mozzarella and tomatoes.\n2. Arrange alternating slices on a plate.\n3. Tuck fresh basil leaves between slices.\n4. Drizzle with olive oil and balsamic glaze.\n5. Season with salt and black pepper.', + 2), + ('00000000-0000-0000-0000-000000000044', 'Baked Mac and Cheese', + E'1. Preheat oven to 375°F (190°C).\n2. Cook macaroni until al dente. Drain.\n3. Make cheese sauce: melt butter, whisk in flour, add milk, stir in cheddar.\n4. Combine pasta and sauce. Pour into baking dish.\n5. Top with breadcrumbs and extra cheese.\n6. Bake 25 minutes until bubbly and golden.', + 6), + ('00000000-0000-0000-0000-000000000045', 'Chicken Fajitas', + E'1. Slice chicken breast into strips. Season with fajita spices.\n2. Cook chicken in a hot pan until cooked through. Remove.\n3. Sauté sliced bell peppers and onion until tender.\n4. Warm flour tortillas.\n5. Serve chicken and vegetables in tortillas.\n6. Top with sour cream, guacamole, and salsa.', + 3), + ('00000000-0000-0000-0000-000000000046', 'Overnight Oats', + E'1. Combine rolled oats, milk, and yogurt in a jar.\n2. Add chia seeds and honey. Stir well.\n3. Cover and refrigerate overnight.\n4. In the morning, top with fresh berries and nuts.\n5. Serve cold or warm briefly in microwave.', + 1), + ('00000000-0000-0000-0000-000000000047', 'Stuffed Bell Peppers', + E'1. Preheat oven to 375°F (190°C).\n2. Cut tops off peppers and remove seeds.\n3. Brown ground beef with onion and garlic.\n4. Mix with cooked rice, tomato sauce, and seasoning.\n5. Fill peppers with mixture. Top with cheese.\n6. Bake 30–35 minutes until peppers are tender.', + 4), + ('00000000-0000-0000-0000-000000000048', 'Garlic Bread', + E'1. Preheat oven to 375°F (190°C).\n2. Mix softened butter with minced garlic, parsley, and salt.\n3. Slice baguette in half lengthwise.\n4. Spread garlic butter generously on cut sides.\n5. Bake 10 minutes, then broil 2 minutes until golden.\n6. Slice and serve immediately.', + 4), + ('00000000-0000-0000-0000-000000000049', 'Spinach and Feta Omelette', + E'1. Whisk eggs with salt and pepper.\n2. Melt butter in a non-stick pan over medium heat.\n3. Pour in eggs and cook until edges set.\n4. Add fresh spinach and crumbled feta to one half.\n5. Fold omelette in half and cook 1 more minute.\n6. Slide onto plate and serve.', + 1), + ('00000000-0000-0000-0000-000000000050', 'Chocolate Mousse', + E'1. Melt dark chocolate and let cool slightly.\n2. Whip heavy cream to soft peaks.\n3. Whisk egg yolks with sugar until pale.\n4. Fold chocolate into egg mixture.\n5. Fold in whipped cream gently.\n6. Chill 2 hours before serving.', + 4); + +-- ───────────────────────────────────────────── +-- RECIPE INGREDIENTS +-- ───────────────────────────────────────────── +INSERT INTO recipe_ingredients (recipe_id, item_name, quantity, unit) VALUES + -- Classic Pancakes + ('00000000-0000-0000-0000-000000000001', 'flour', 2.0, 'cups'), + ('00000000-0000-0000-0000-000000000001', 'baking powder', 2.0, 'tsp'), + ('00000000-0000-0000-0000-000000000001', 'salt', 0.5, 'tsp'), + ('00000000-0000-0000-0000-000000000001', 'sugar', 2.0, 'tbsp'), + ('00000000-0000-0000-0000-000000000001', 'milk', 1.5, 'cups'), + ('00000000-0000-0000-0000-000000000001', 'egg', 1.0, 'whole'), + ('00000000-0000-0000-0000-000000000001', 'butter', 2.0, 'tbsp'), + -- Scrambled Eggs + ('00000000-0000-0000-0000-000000000002', 'eggs', 4.0, 'whole'), + ('00000000-0000-0000-0000-000000000002', 'milk', 2.0, 'tbsp'), + ('00000000-0000-0000-0000-000000000002', 'butter', 1.0, 'tbsp'), + -- Spaghetti Bolognese + ('00000000-0000-0000-0000-000000000003', 'spaghetti', 400.0, 'g'), + ('00000000-0000-0000-0000-000000000003', 'ground beef', 500.0, 'g'), + ('00000000-0000-0000-0000-000000000003', 'onion', 1.0, 'whole'), + ('00000000-0000-0000-0000-000000000003', 'garlic', 3.0, 'whole'), + ('00000000-0000-0000-0000-000000000003', 'crushed tomatoes', 400.0, 'g'), + ('00000000-0000-0000-0000-000000000003', 'tomato paste', 2.0, 'tbsp'), + ('00000000-0000-0000-0000-000000000003', 'parmesan', 50.0, 'g'), + -- Caesar Salad + ('00000000-0000-0000-0000-000000000004', 'romaine lettuce', 1.0, 'whole'), + ('00000000-0000-0000-0000-000000000004', 'olive oil', 3.0, 'tbsp'), + ('00000000-0000-0000-0000-000000000004', 'lemon', 1.0, 'whole'), + ('00000000-0000-0000-0000-000000000004', 'garlic', 1.0, 'whole'), + ('00000000-0000-0000-0000-000000000004', 'parmesan', 30.0, 'g'), + -- Chicken Stir Fry + ('00000000-0000-0000-0000-000000000005', 'chicken breast', 400.0, 'g'), + ('00000000-0000-0000-0000-000000000005', 'bell pepper', 1.0, 'whole'), + ('00000000-0000-0000-0000-000000000005', 'broccoli', 200.0, 'g'), + ('00000000-0000-0000-0000-000000000005', 'soy sauce', 3.0, 'tbsp'), + ('00000000-0000-0000-0000-000000000005', 'sesame oil', 1.0, 'tbsp'), + ('00000000-0000-0000-0000-000000000005', 'rice', 2.0, 'cups'), + -- Banana Bread + ('00000000-0000-0000-0000-000000000006', 'banana', 3.0, 'whole'), + ('00000000-0000-0000-0000-000000000006', 'flour', 1.5, 'cups'), + ('00000000-0000-0000-0000-000000000006', 'sugar', 0.75, 'cups'), + ('00000000-0000-0000-0000-000000000006', 'butter', 0.3333, 'cups'), + ('00000000-0000-0000-0000-000000000006', 'egg', 1.0, 'whole'), + ('00000000-0000-0000-0000-000000000006', 'baking soda', 1.0, 'tsp'), + -- Tomato Soup + ('00000000-0000-0000-0000-000000000007', 'crushed tomatoes', 800.0, 'g'), + ('00000000-0000-0000-0000-000000000007', 'onion', 1.0, 'whole'), + ('00000000-0000-0000-0000-000000000007', 'garlic', 2.0, 'whole'), + ('00000000-0000-0000-0000-000000000007', 'butter', 2.0, 'tbsp'), + ('00000000-0000-0000-0000-000000000007', 'heavy cream', 0.5, 'cups'), + -- Grilled Cheese + ('00000000-0000-0000-0000-000000000008', 'bread', 2.0, 'whole'), + ('00000000-0000-0000-0000-000000000008', 'cheddar cheese', 60.0, 'g'), + ('00000000-0000-0000-0000-000000000008', 'butter', 1.0, 'tbsp'), + -- Chocolate Chip Cookies + ('00000000-0000-0000-0000-000000000009', 'flour', 2.25, 'cups'), + ('00000000-0000-0000-0000-000000000009', 'butter', 1.0, 'cups'), + ('00000000-0000-0000-0000-000000000009', 'sugar', 0.75, 'cups'), + ('00000000-0000-0000-0000-000000000009', 'brown sugar', 0.75, 'cups'), + ('00000000-0000-0000-0000-000000000009', 'eggs', 2.0, 'whole'), + ('00000000-0000-0000-0000-000000000009', 'vanilla extract', 1.0, 'tsp'), + ('00000000-0000-0000-0000-000000000009', 'baking soda', 1.0, 'tsp'), + ('00000000-0000-0000-0000-000000000009', 'chocolate chips', 2.0, 'cups'), + -- Guacamole + ('00000000-0000-0000-0000-000000000010', 'avocado', 3.0, 'whole'), + ('00000000-0000-0000-0000-000000000010', 'lime', 1.0, 'whole'), + ('00000000-0000-0000-0000-000000000010', 'onion', 0.5, 'whole'), + ('00000000-0000-0000-0000-000000000010', 'cilantro', 2.0, 'tbsp'), + -- French Toast + ('00000000-0000-0000-0000-000000000011', 'bread', 4.0, 'whole'), + ('00000000-0000-0000-0000-000000000011', 'eggs', 2.0, 'whole'), + ('00000000-0000-0000-0000-000000000011', 'milk', 0.25, 'cups'), + ('00000000-0000-0000-0000-000000000011', 'butter', 1.0, 'tbsp'), + ('00000000-0000-0000-0000-000000000011', 'cinnamon', 0.5, 'tsp'), + -- Chicken Soup + ('00000000-0000-0000-0000-000000000012', 'chicken thighs', 600.0, 'g'), + ('00000000-0000-0000-0000-000000000012', 'carrot', 2.0, 'whole'), + ('00000000-0000-0000-0000-000000000012', 'celery', 2.0, 'whole'), + ('00000000-0000-0000-0000-000000000012', 'onion', 1.0, 'whole'), + ('00000000-0000-0000-0000-000000000012', 'egg noodles', 200.0, 'g'), + -- Fried Rice + ('00000000-0000-0000-0000-000000000013', 'rice', 2.0, 'cups'), + ('00000000-0000-0000-0000-000000000013', 'eggs', 2.0, 'whole'), + ('00000000-0000-0000-0000-000000000013', 'soy sauce', 3.0, 'tbsp'), + ('00000000-0000-0000-0000-000000000013', 'sesame oil', 1.0, 'tbsp'), + ('00000000-0000-0000-0000-000000000013', 'onion', 1.0, 'whole'), + -- Beef Tacos + ('00000000-0000-0000-0000-000000000014', 'ground beef', 400.0, 'g'), + ('00000000-0000-0000-0000-000000000014', 'taco shells', 8.0, 'whole'), + ('00000000-0000-0000-0000-000000000014', 'cheddar cheese', 100.0, 'g'), + ('00000000-0000-0000-0000-000000000014', 'onion', 1.0, 'whole'), + -- Oatmeal + ('00000000-0000-0000-0000-000000000015', 'rolled oats', 1.0, 'cups'), + ('00000000-0000-0000-0000-000000000015', 'milk', 2.0, 'cups'), + ('00000000-0000-0000-0000-000000000015', 'brown sugar', 2.0, 'tbsp'), + ('00000000-0000-0000-0000-000000000015', 'cinnamon', 0.5, 'tsp'), + -- Pasta Carbonara + ('00000000-0000-0000-0000-000000000016', 'spaghetti', 200.0, 'g'), + ('00000000-0000-0000-0000-000000000016', 'eggs', 3.0, 'whole'), + ('00000000-0000-0000-0000-000000000016', 'parmesan', 80.0, 'g'), + ('00000000-0000-0000-0000-000000000016', 'pancetta', 150.0, 'g'), + -- Vegetable Curry + ('00000000-0000-0000-0000-000000000017', 'potato', 2.0, 'whole'), + ('00000000-0000-0000-0000-000000000017', 'cauliflower', 0.5, 'whole'), + ('00000000-0000-0000-0000-000000000017', 'chickpeas', 400.0, 'g'), + ('00000000-0000-0000-0000-000000000017', 'coconut milk', 400.0, 'ml'), + ('00000000-0000-0000-0000-000000000017', 'onion', 1.0, 'whole'), + ('00000000-0000-0000-0000-000000000017', 'garlic', 3.0, 'whole'), + ('00000000-0000-0000-0000-000000000017', 'rice', 2.0, 'cups'), + -- BLT Sandwich + ('00000000-0000-0000-0000-000000000018', 'bread', 2.0, 'whole'), + ('00000000-0000-0000-0000-000000000018', 'bacon', 4.0, 'whole'), + ('00000000-0000-0000-0000-000000000018', 'lettuce', 2.0, 'whole'), + ('00000000-0000-0000-0000-000000000018', 'tomato', 1.0, 'whole'), + ('00000000-0000-0000-0000-000000000018', 'mayonnaise', 2.0, 'tbsp'), + -- Lemon Garlic Shrimp + ('00000000-0000-0000-0000-000000000019', 'shrimp', 400.0, 'g'), + ('00000000-0000-0000-0000-000000000019', 'butter', 3.0, 'tbsp'), + ('00000000-0000-0000-0000-000000000019', 'garlic', 4.0, 'whole'), + ('00000000-0000-0000-0000-000000000019', 'lemon', 1.0, 'whole'), + -- Apple Pie + ('00000000-0000-0000-0000-000000000020', 'apple', 6.0, 'whole'), + ('00000000-0000-0000-0000-000000000020', 'flour', 2.5, 'cups'), + ('00000000-0000-0000-0000-000000000020', 'butter', 1.0, 'cups'), + ('00000000-0000-0000-0000-000000000020', 'sugar', 0.75, 'cups'), + ('00000000-0000-0000-0000-000000000020', 'cinnamon', 1.0, 'tsp'); diff --git a/src/jobs/cleanup.js b/src/jobs/cleanup.js new file mode 100644 index 0000000..4619210 --- /dev/null +++ b/src/jobs/cleanup.js @@ -0,0 +1,36 @@ +'use strict'; + +const cron = require('node-cron'); +const { getDb } = require('../db/knex'); + +/** + * Hard-deletes all user accounts whose deletion_scheduled_at has passed. + * CASCADE constraints handle pantry_items, shopping_lists, and all child records. + * Runs daily at 02:00 UTC. + */ +async function hardDeleteExpiredAccounts() { + const db = getDb(); + const now = new Date(); + + try { + const deleted = await db('users') + .whereNotNull('deletion_scheduled_at') + .where('deletion_scheduled_at', '<=', now) + .delete() + .returning('id'); + + console.log( + `[CRON] Hard-deleted ${deleted.length} expired account(s) at ${now.toISOString()}` + ); + } catch (err) { + console.error('[CRON] Error during account hard-delete job:', err); + } +} + +function startCronJobs() { + // Daily at 02:00 UTC + cron.schedule('0 2 * * *', hardDeleteExpiredAccounts, { timezone: 'UTC' }); + console.log('[CRON] Account cleanup job scheduled (daily 02:00 UTC)'); +} + +module.exports = { startCronJobs, hardDeleteExpiredAccounts }; diff --git a/src/main/app.js b/src/main/app.js new file mode 100644 index 0000000..b201d4d --- /dev/null +++ b/src/main/app.js @@ -0,0 +1,41 @@ +'use strict'; + +const express = require('express'); +const cors = require('cors'); +const { requestLogger } = require('../middleware/requestLogger'); +const { errorHandler } = require('../middleware/errorHandler'); +const authRoutes = require('../routes/auth'); +const pantryRoutes = require('../routes/pantry'); +const recipeRoutes = require('../routes/recipes'); +const shoppingRoutes = require('../routes/shopping'); +const syncRoutes = require('../routes/sync'); + +const app = express(); + +app.use(cors()); +app.use(express.json()); +app.use(requestLogger); + +// Health check — no auth required +app.get('/health', (req, res) => { + res.status(200).json({ status: 'ok', timestamp: new Date().toISOString() }); +}); + +app.use('/v1/auth', authRoutes); +app.use('/v1/pantry', pantryRoutes); +app.use('/v1/recipes', recipeRoutes); +app.use('/v1/shopping-lists', shoppingRoutes); +app.use('/v1/sync', syncRoutes); + +// 404 handler for unmatched routes +app.use((req, res) => { + res.status(404).json({ + error: 'Route not found.', + code: 'NOT_FOUND', + timestamp: new Date().toISOString(), + }); +}); + +app.use(errorHandler); + +module.exports = app; diff --git a/src/main/index.js b/src/main/index.js new file mode 100644 index 0000000..825083e --- /dev/null +++ b/src/main/index.js @@ -0,0 +1,15 @@ +'use strict'; + +require('dotenv').config(); +const app = require('./app'); +const { startCronJobs } = require('../jobs/cleanup'); +const config = require('../config'); + +const PORT = config.port; + +app.listen(PORT, () => { + console.log(`[SERVER] Pantree API listening on port ${PORT} (${config.nodeEnv})`); + startCronJobs(); +}); + +module.exports = app; diff --git a/src/middleware/authenticate.js b/src/middleware/authenticate.js new file mode 100644 index 0000000..13be148 --- /dev/null +++ b/src/middleware/authenticate.js @@ -0,0 +1,40 @@ +'use strict'; + +const jwt = require('jsonwebtoken'); +const config = require('../config'); +const { AppError } = require('../utils/errors'); + +/** + * JWT authentication middleware. + * Validates the Bearer token on every protected route. + * Attaches decoded payload to req.user. + * The token is not trusted until verified — no exceptions. + */ +function authenticate(req, res, next) { + const authHeader = req.headers['authorization']; + + if (!authHeader || !authHeader.startsWith('Bearer ')) { + return next(new AppError(401, 'UNAUTHORIZED', 'Missing or malformed Authorization header.')); + } + + const token = authHeader.slice(7).trim(); + if (!token) { + return next(new AppError(401, 'UNAUTHORIZED', 'Missing token.')); + } + + let payload; + try { + payload = jwt.verify(token, config.jwt.secret); + } catch (err) { + return next(new AppError(401, 'UNAUTHORIZED', 'Invalid or expired token.')); + } + + if (!payload.sub) { + return next(new AppError(401, 'UNAUTHORIZED', 'Malformed token payload.')); + } + + req.user = payload; + return next(); +} + +module.exports = { authenticate }; diff --git a/src/middleware/errorHandler.js b/src/middleware/errorHandler.js new file mode 100644 index 0000000..9a37a33 --- /dev/null +++ b/src/middleware/errorHandler.js @@ -0,0 +1,42 @@ +'use strict'; + +/** + * Central error handler. + * All errors thrown in route handlers or services arrive here. + * Known AppErrors are mapped to their HTTP status. + * Everything else is a 500. + */ +function errorHandler(err, req, res, next) { // eslint-disable-line no-unused-vars + const timestamp = new Date().toISOString(); + + // Structured application error + if (err.isAppError) { + return res.status(err.status).json({ + error: err.message, + code: err.code, + ...(err.extra || {}), + timestamp, + }); + } + + // Zod validation error (surfaced via validate() helper) + if (err.zodError) { + return res.status(400).json({ + error: err.message || 'Validation failed.', + code: 'VALIDATION_ERROR', + details: err.issues, + timestamp, + }); + } + + // Unexpected error — log it, return generic 500 + console.error(`[ERROR] [${req.requestId || '-'}] ${err.stack || err.message}`); + + return res.status(500).json({ + error: 'An unexpected error occurred.', + code: 'INTERNAL_ERROR', + timestamp, + }); +} + +module.exports = { errorHandler }; diff --git a/src/middleware/requestLogger.js b/src/middleware/requestLogger.js new file mode 100644 index 0000000..10afd8f --- /dev/null +++ b/src/middleware/requestLogger.js @@ -0,0 +1,16 @@ +'use strict'; + +const { v4: uuidv4 } = require('uuid'); + +/** + * Attaches a unique request ID to every inbound request. + * Logs method + path for basic observability. + */ +function requestLogger(req, res, next) { + req.requestId = uuidv4(); + res.setHeader('X-Request-Id', req.requestId); + console.log(`[${new Date().toISOString()}] [${req.requestId}] ${req.method} ${req.path}`); + next(); +} + +module.exports = { requestLogger }; diff --git a/src/routes/auth.js b/src/routes/auth.js new file mode 100644 index 0000000..6a3c136 --- /dev/null +++ b/src/routes/auth.js @@ -0,0 +1,103 @@ +'use strict'; + +const express = require('express'); +const router = express.Router(); +const authService = require('../services/authService'); +const { authenticate } = require('../middleware/authenticate'); +const { validate } = require('../utils/validate'); +const { + signupSchema, + signinSchema, + googleAuthSchema, + passwordResetRequestSchema, + passwordResetConfirmSchema, + restoreAccountSchema, +} = require('../utils/validation'); + +// POST /v1/auth/signup +router.post('/signup', async (req, res, next) => { + try { + const data = validate(signupSchema, req.body); + const result = await authService.signup(data); + return res.status(201).json(result); + } catch (err) { + return next(err); + } +}); + +// POST /v1/auth/signin +router.post('/signin', async (req, res, next) => { + try { + const data = validate(signinSchema, req.body); + const result = await authService.signin(data); + return res.status(200).json(result); + } catch (err) { + return next(err); + } +}); + +// POST /v1/auth/google +router.post('/google', async (req, res, next) => { + try { + const data = validate(googleAuthSchema, req.body); + const result = await authService.googleAuth(data); + const status = result.is_new_user ? 201 : 200; + // Strip internal flag from response + const { is_new_user, ...response } = result; // eslint-disable-line no-unused-vars + return res.status(status).json(response); + } catch (err) { + return next(err); + } +}); + +// POST /v1/auth/password-reset — request reset email +router.post('/password-reset', async (req, res, next) => { + try { + const data = validate(passwordResetRequestSchema, req.body); + await authService.requestPasswordReset(data); + // Always 200 — never reveal whether email exists + return res.status(200).json({ + message: 'If an account exists with this email, a reset link has been sent.', + timestamp: new Date().toISOString(), + }); + } catch (err) { + return next(err); + } +}); + +// PUT /v1/auth/password-reset — complete reset with token +router.put('/password-reset', async (req, res, next) => { + try { + const data = validate(passwordResetConfirmSchema, req.body); + await authService.confirmPasswordReset(data); + return res.status(200).json({ + message: 'Password updated successfully.', + timestamp: new Date().toISOString(), + }); + } catch (err) { + return next(err); + } +}); + +// DELETE /v1/auth/account — soft-delete authenticated user's account +router.delete('/account', authenticate, async (req, res, next) => { + try { + await authService.deleteAccount(req.user.sub); + return res.status(204).send(); + } catch (err) { + return next(err); + } +}); + +// POST /v1/auth/restore-account — restore soft-deleted account +router.post('/restore-account', async (req, res, next) => { + try { + const data = validate(restoreAccountSchema, req.body); + const result = await authService.restoreAccount(data); + return res.status(200).json(result); + } catch (err) { + return next(err); + } +}); + +module.exports = router; diff --git a/src/routes/pantry.js b/src/routes/pantry.js new file mode 100644 index 0000000..b3bc76f --- /dev/null +++ b/src/routes/pantry.js @@ -0,0 +1,58 @@ +'use strict'; + +const express = require('express'); +const router = express.Router(); +const pantryService = require('../services/pantryService'); +const { authenticate } = require('../middleware/authenticate'); +const { validate } = require('../utils/validate'); +const { addPantryItemSchema, updatePantryItemSchema } = require('../utils/validation'); + +// All pantry routes require authentication +router.use(authenticate); + +// GET /v1/pantry +router.get('/', async (req, res, next) => { + try { + const items = await pantryService.getPantryItems(req.user.sub); + return res.status(200).json({ + items, + synced_at: new Date().toISOString(), + }); + } catch (err) { + return next(err); + } +}); + +// POST /v1/pantry +router.post('/', async (req, res, next) => { + try { + const data = validate(addPantryItemSchema, req.body); + const item = await pantryService.addPantryItem(req.user.sub, data); + return res.status(201).json({ item }); + } catch (err) { + return next(err); + } +}); + +// PUT /v1/pantry/:item_id +router.put('/:item_id', async (req, res, next) => { + try { + const data = validate(updatePantryItemSchema, req.body); + const item = await pantryService.updatePantryItem(req.user.sub, req.params.item_id, data); + return res.status(200).json({ item }); + } catch (err) { + return next(err); + } +}); + +// DELETE /v1/pantry/:item_id +router.delete('/:item_id', async (req, res, next) => { + try { + await pantryService.deletePantryItem(req.user.sub, req.params.item_id); + return res.status(204).send(); + } catch (err) { + return next(err); + } +}); + +module.exports = router; diff --git a/src/routes/recipes.js b/src/routes/recipes.js new file mode 100644 index 0000000..e2cb0e1 --- /dev/null +++ b/src/routes/recipes.js @@ -0,0 +1,42 @@ +'use strict'; + +const express = require('express'); +const router = express.Router(); +const recipeService = require('../services/recipeService'); +const { authenticate } = require('../middleware/authenticate'); +const { validate } = require('../utils/validate'); +const { recipeQuerySchema } = require('../utils/validation'); + +// All recipe routes require authentication +router.use(authenticate); + +// GET /v1/recipes?filter=all|available|partial&scale=1|2|3 +router.get('/', async (req, res, next) => { + try { + const query = validate(recipeQuerySchema, req.query); + const recipes = await recipeService.getRecipes(req.user.sub, query); + return res.status(200).json({ + recipes, + synced_at: new Date().toISOString(), + }); + } catch (err) { + return next(err); + } +}); + +// GET /v1/recipes/:recipe_id?scale=1|2|3 +router.get('/:recipe_id', async (req, res, next) => { + try { + const query = validate(recipeQuerySchema, req.query); + const recipe = await recipeService.getRecipeById( + req.user.sub, + req.params.recipe_id, + query + ); + return res.status(200).json({ recipe }); + } catch (err) { + return next(err); + } +}); + +module.exports = router; diff --git a/src/routes/shopping.js b/src/routes/shopping.js new file mode 100644 index 0000000..ebdbeae --- /dev/null +++ b/src/routes/shopping.js @@ -0,0 +1,128 @@ +'use strict'; + +const express = require('express'); +const router = express.Router(); +const shoppingService = require('../services/shoppingService'); +const { authenticate } = require('../middleware/authenticate'); +const { validate } = require('../utils/validate'); +const { + createShoppingListSchema, + addShoppingListItemSchema, + updateShoppingListItemSchema, + addRecipesToListSchema, +} = require('../utils/validation'); + +// All shopping list routes require authentication +router.use(authenticate); + +// GET /v1/shopping-lists +router.get('/', async (req, res, next) => { + try { + const lists = await shoppingService.getShoppingLists(req.user.sub); + return res.status(200).json({ + shopping_lists: lists, + synced_at: new Date().toISOString(), + }); + } catch (err) { + return next(err); + } +}); + +// POST /v1/shopping-lists +router.post('/', async (req, res, next) => { + try { + const data = validate(createShoppingListSchema, req.body); + const list = await shoppingService.createShoppingList(req.user.sub, data); + return res.status(201).json({ shopping_list: list }); + } catch (err) { + return next(err); + } +}); + +// GET /v1/shopping-lists/:list_id +router.get('/:list_id', async (req, res, next) => { + try { + const list = await shoppingService.getShoppingListById( + req.user.sub, + req.params.list_id + ); + return res.status(200).json({ + shopping_list: list, + synced_at: new Date().toISOString(), + }); + } catch (err) { + return next(err); + } +}); + +// DELETE /v1/shopping-lists/:list_id +router.delete('/:list_id', async (req, res, next) => { + try { + await shoppingService.deleteShoppingList(req.user.sub, req.params.list_id); + return res.status(204).send(); + } catch (err) { + return next(err); + } +}); + +// POST /v1/shopping-lists/:list_id/items +router.post('/:list_id/items', async (req, res, next) => { + try { + const data = validate(addShoppingListItemSchema, req.body); + const result = await shoppingService.addItemToList( + req.user.sub, + req.params.list_id, + data + ); + return res.status(201).json(result); + } catch (err) { + return next(err); + } +}); + +// POST /v1/shopping-lists/:list_id/add-recipes +router.post('/:list_id/add-recipes', async (req, res, next) => { + try { + const data = validate(addRecipesToListSchema, req.body); + const result = await shoppingService.addRecipesToList( + req.user.sub, + req.params.list_id, + data + ); + return res.status(201).json(result); + } catch (err) { + return next(err); + } +}); + +// PUT /v1/shopping-lists/:list_id/items/:item_id +router.put('/:list_id/items/:item_id', async (req, res, next) => { + try { + const data = validate(updateShoppingListItemSchema, req.body); + const item = await shoppingService.updateListItem( + req.user.sub, + req.params.list_id, + req.params.item_id, + data + ); + return res.status(200).json({ item }); + } catch (err) { + return next(err); + } +}); + +// DELETE /v1/shopping-lists/:list_id/items/:item_id +router.delete('/:list_id/items/:item_id', async (req, res, next) => { + try { + await shoppingService.deleteListItem( + req.user.sub, + req.params.list_id, + req.params.item_id + ); + return res.status(204).send(); + } catch (err) { + return next(err); + } +}); + +module.exports = router; diff --git a/src/routes/sync.js b/src/routes/sync.js new file mode 100644 index 0000000..2d196b0 --- /dev/null +++ b/src/routes/sync.js @@ -0,0 +1,23 @@ +'use strict'; + +const express = require('express'); +const router = express.Router(); +const syncService = require('../services/syncService'); +const { authenticate } = require('../middleware/authenticate'); +const { validate } = require('../utils/validate'); +const { syncQuerySchema } = require('../utils/validation'); + +router.use(authenticate); + +// GET /v1/sync?since= +router.get('/', async (req, res, next) => { + try { + const query = validate(syncQuerySchema, req.query); + const data = await syncService.getSyncData(req.user.sub, query.since || null); + return res.status(200).json(data); + } catch (err) { + return next(err); + } +}); + +module.exports = router; diff --git a/src/services/authService.js b/src/services/authService.js new file mode 100644 index 0000000..1fced57 --- /dev/null +++ b/src/services/authService.js @@ -0,0 +1,294 @@ +'use strict'; + +const bcrypt = require('bcrypt'); +const crypto = require('crypto'); +const { getDb } = require('../db/knex'); +const { AppError } = require('../utils/errors'); +const { issueToken } = require('../utils/jwt'); +const config = require('../config'); + +const SALT_ROUNDS = 12; + +/** + * Formats a user row for API responses. + * Never exposes password_hash, google_id, or internal fields. + */ +function formatUser(row) { + return { + id: row.id, + email: row.email, + name: row.name, + profile_picture_url: row.profile_picture_url || null, + email_verified: row.email_verified || false, + deleted_at: row.deleted_at || null, + created_at: row.created_at, + }; +} + +/** + * Register a new user with email + password. + * Rejects duplicate emails (case-insensitive). + */ +async function signup({ email, password, name }) { + const db = getDb(); + const normalizedEmail = email.toLowerCase().trim(); + + const existing = await db('users') + .whereRaw('LOWER(email) = ?', [normalizedEmail]) + .first(); + + if (existing) { + throw new AppError(409, 'CONFLICT', 'Email already registered.'); + } + + const password_hash = await bcrypt.hash(password, SALT_ROUNDS); + + const [user] = await db('users') + .insert({ + email: normalizedEmail, + password_hash, + name: name.trim(), + email_verified: false, + }) + .returning('*'); + + const { token, expires_at } = issueToken(user); + return { user: formatUser(user), token, expires_at }; +} + +/** + * Sign in with email + password. + * Returns 401 for any credential failure — no enumeration. + * Returns 403 if account is soft-deleted within the 15-day window. + */ +async function signin({ email, password }) { + const db = getDb(); + const normalizedEmail = email.toLowerCase().trim(); + + const user = await db('users') + .whereRaw('LOWER(email) = ?', [normalizedEmail]) + .first(); + + // Constant-time path: always attempt bcrypt compare to prevent timing attacks + const dummyHash = '$2b$12$invalidhashfortimingprotection000000000000000000000000'; + const hashToCompare = user && user.password_hash ? user.password_hash : dummyHash; + const valid = await bcrypt.compare(password, hashToCompare); + + if (!user || !user.password_hash || !valid) { + throw new AppError(401, 'UNAUTHORIZED', 'Invalid email or password.'); + } + + if (user.deleted_at) { + // Within 15-day window — allow sign-in but signal pending deletion + if (user.deletion_scheduled_at && new Date(user.deletion_scheduled_at) > new Date()) { + throw new AppError(403, 'ACCOUNT_PENDING_DELETION', 'Account is pending deletion.', { + deletion_scheduled_at: user.deletion_scheduled_at, + can_restore: true, + }); + } + // Past window — should have been hard-deleted by cron, but guard anyway + throw new AppError(401, 'UNAUTHORIZED', 'Invalid email or password.'); + } + + const { token, expires_at } = issueToken(user); + return { user: formatUser(user), token, expires_at }; +} + +/** + * Sign in or register via Google ID token. + * Decodes the JWT payload — production should verify with Google's tokeninfo endpoint. + */ +async function googleAuth({ id_token }) { + let payload; + try { + const parts = id_token.split('.'); + if (parts.length !== 3) throw new Error('Malformed JWT'); + // Add padding for base64url decode + const base64 = parts[1].replace(/-/g, '+').replace(/_/g, '/'); + const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4); + payload = JSON.parse(Buffer.from(padded, 'base64').toString('utf8')); + } catch { + throw new AppError(401, 'INVALID_TOKEN', 'Google token verification failed.'); + } + + if (!payload.sub || !payload.email) { + throw new AppError(401, 'INVALID_TOKEN', 'Google token verification failed.'); + } + + const db = getDb(); + let user = await db('users').where({ google_id: payload.sub }).first(); + let is_new_user = false; + + if (!user) { + // Check if email already exists — link accounts + user = await db('users') + .whereRaw('LOWER(email) = ?', [payload.email.toLowerCase()]) + .first(); + + if (user) { + const [updated] = await db('users') + .where({ id: user.id }) + .update({ + google_id: payload.sub, + profile_picture_url: payload.picture || user.profile_picture_url, + }) + .returning('*'); + user = updated; + } else { + is_new_user = true; + const [created] = await db('users') + .insert({ + email: payload.email.toLowerCase(), + name: payload.name || payload.email, + profile_picture_url: payload.picture || null, + google_id: payload.sub, + email_verified: true, // Google accounts are pre-verified + }) + .returning('*'); + user = created; + } + } + + const { token, expires_at } = issueToken(user); + return { user: formatUser(user), token, expires_at, is_new_user }; +} + +/** + * Request a password reset email. + * Always returns success — never reveals whether the email exists. + */ +async function requestPasswordReset({ email }) { + const db = getDb(); + const normalizedEmail = email.toLowerCase().trim(); + const user = await db('users') + .whereRaw('LOWER(email) = ?', [normalizedEmail]) + .whereNull('deleted_at') + .first(); + + // Silent return — no enumeration + if (!user || !user.password_hash) return; + + // Generate a cryptographically random token + const rawToken = crypto.randomBytes(32).toString('hex'); + const token_hash = crypto.createHash('sha256').update(rawToken).digest('hex'); + const expires_at = new Date(Date.now() + config.resetTokenExpiryHours * 60 * 60 * 1000); + + await db('password_reset_tokens').insert({ + user_id: user.id, + token_hash, + expires_at, + }); + + // Production: send email with link containing rawToken + // await emailService.sendPasswordReset(user.email, rawToken); + console.log(`[PASSWORD RESET] raw_token=${rawToken} user_id=${user.id}`); +} + +/** + * Complete a password reset using the token from the email link. + * Token is SHA-256 hashed before DB lookup — raw token never stored. + */ +async function confirmPasswordReset({ token, new_password }) { + const db = getDb(); + + const token_hash = crypto.createHash('sha256').update(token).digest('hex'); + const record = await db('password_reset_tokens').where({ token_hash }).first(); + + if (!record || record.used_at) { + throw new AppError(401, 'INVALID_TOKEN', 'Token is invalid or has already been used.'); + } + + if (new Date(record.expires_at) < new Date()) { + throw new AppError(401, 'INVALID_TOKEN', 'Token has expired.'); + } + + const password_hash = await bcrypt.hash(new_password, SALT_ROUNDS); + + await db.transaction(async (trx) => { + await trx('users').where({ id: record.user_id }).update({ password_hash }); + await trx('password_reset_tokens') + .where({ id: record.id }) + .update({ used_at: new Date() }); + }); +} + +/** + * Soft-delete a user account. + * Sets deleted_at and deletion_scheduled_at (now + 15 days). + * Hard delete is handled by the daily cron job. + */ +async function deleteAccount(userId) { + const db = getDb(); + const now = new Date(); + const deletion_scheduled_at = new Date( + now.getTime() + config.accountDeletionDays * 24 * 60 * 60 * 1000 + ); + + await db('users').where({ id: userId }).update({ + deleted_at: now, + deletion_scheduled_at, + }); +} + +/** + * Restore a soft-deleted account within the 15-day window. + * Requires valid credentials — the token from the 403 signin response is used. + */ +async function restoreAccount({ email, password }) { + const db = getDb(); + const normalizedEmail = email.toLowerCase().trim(); + + const user = await db('users') + .whereRaw('LOWER(email) = ?', [normalizedEmail]) + .first(); + + const dummyHash = '$2b$12$invalidhashfortimingprotection000000000000000000000000'; + const hashToCompare = user && user.password_hash ? user.password_hash : dummyHash; + const valid = await bcrypt.compare(password, hashToCompare); + + if (!user || !user.password_hash || !valid) { + throw new AppError(401, 'UNAUTHORIZED', 'Invalid credentials.'); + } + + // Past the 15-day window + if ( + user.deletion_scheduled_at && + new Date(user.deletion_scheduled_at) <= new Date() + ) { + throw new AppError(410, 'GONE', 'Account has been permanently deleted.'); + } + + // Account was never deleted + if (!user.deleted_at) { + const { token, expires_at } = issueToken(user); + return { + user: formatUser(user), + token, + expires_at, + message: 'Account is active.', + }; + } + + const [restored] = await db('users') + .where({ id: user.id }) + .update({ deleted_at: null, deletion_scheduled_at: null }) + .returning('*'); + + const { token, expires_at } = issueToken(restored); + return { + user: formatUser(restored), + token, + expires_at, + message: 'Account restored successfully.', + }; +} + +module.exports = { + signup, + signin, + googleAuth, + requestPasswordReset, + confirmPasswordReset, + deleteAccount, + restoreAccount, +}; diff --git a/src/services/pantryService.js b/src/services/pantryService.js new file mode 100644 index 0000000..bf92888 --- /dev/null +++ b/src/services/pantryService.js @@ -0,0 +1,112 @@ +'use strict'; + +const { getDb } = require('../db/knex'); +const { AppError } = require('../utils/errors'); + +function formatItem(row) { + return { + id: row.id, + item_name: row.item_name, + quantity: row.quantity, + last_modified: row.last_modified, + created_at: row.created_at, + }; +} + +/** + * Returns all pantry items for the authenticated user, ordered alphabetically. + */ +async function getPantryItems(userId) { + const db = getDb(); + const items = await db('pantry_items') + .where({ user_id: userId }) + .orderBy('item_name_lower', 'asc'); + return items.map(formatItem); +} + +/** + * Adds a new pantry item. + * Rejects with 409 if an item with the same name already exists (case-insensitive). + * Auto-merge is intentionally not performed — explicit > implicit. + */ +async function addPantryItem(userId, { item_name, quantity }) { + const db = getDb(); + const trimmedName = item_name.trim(); + + const existing = await db('pantry_items') + .where({ user_id: userId }) + .whereRaw('item_name_lower = LOWER(?)', [trimmedName]) + .first(); + + if (existing) { + throw new AppError( + 409, + 'DUPLICATE_ITEM', + `'${existing.item_name}' already exists in your pantry.`, + { existing_item: formatItem(existing) } + ); + } + + const [item] = await db('pantry_items') + .insert({ user_id: userId, item_name: trimmedName, quantity }) + .returning('*'); + + return formatItem(item); +} + +/** + * Updates the quantity of an existing pantry item. + * Server sets last_modified = NOW() — server clock is authoritative. + * Verifies ownership: item must belong to the requesting user. + */ +async function updatePantryItem(userId, itemId, { quantity }) { + const db = getDb(); + + const existing = await db('pantry_items') + .where({ id: itemId, user_id: userId }) + .first(); + + if (!existing) { + throw new AppError(404, 'NOT_FOUND', 'Pantry item not found.'); + } + + const now = new Date(); + const [item] = await db('pantry_items') + .where({ id: itemId, user_id: userId }) + .update({ quantity, last_modified: now, updated_at: now }) + .returning('*'); + + return formatItem(item); +} + +/** + * Deletes a pantry item and records a tombstone for sync. + * Verifies ownership before deletion. + */ +async function deletePantryItem(userId, itemId) { + const db = getDb(); + + const existing = await db('pantry_items') + .where({ id: itemId, user_id: userId }) + .first(); + + if (!existing) { + throw new AppError(404, 'NOT_FOUND', 'Pantry item not found.'); + } + + await db.transaction(async (trx) => { + await trx('pantry_items').where({ id: itemId, user_id: userId }).delete(); + await trx('deleted_records').insert({ + user_id: userId, + record_type: 'pantry_item', + record_id: itemId, + }); + }); +} + +module.exports = { + getPantryItems, + addPantryItem, + updatePantryItem, + deletePantryItem, +}; diff --git a/src/services/recipeService.js b/src/services/recipeService.js new file mode 100644 index 0000000..a55014e --- /dev/null +++ b/src/services/recipeService.js @@ -0,0 +1,152 @@ +'use strict'; + +const { getDb } = require('../db/knex'); +const { AppError } = require('../utils/errors'); + +/** + * Computes availability status for a recipe given the user's pantry. + * Matching is case-insensitive via item_name_lower. + */ +function computeAvailability(ingredients, pantryNameSet) { + const total = ingredients.length; + let available = 0; + const missing = []; + + for (const ing of ingredients) { + if (pantryNameSet.has(ing.item_name_lower)) { + available++; + } else { + missing.push(ing.item_name); + } + } + + let status; + if (total === 0) { + status = 'can_make'; + } else if (available === total) { + status = 'can_make'; + } else if (available > 0) { + status = 'partial'; + } else { + status = 'missing_all'; + } + + return { status, available_count: available, total_count: total, missing_ingredients: missing }; +} + +/** + * Formats a recipe row with its ingredients for the list endpoint. + * Returns a summary (no instructions). + */ +function formatRecipeSummary(recipe, ingredients, pantryNameSet) { + const availability = computeAvailability(ingredients, pantryNameSet); + return { + id: recipe.id, + name: recipe.name, + servings: recipe.servings, + ingredient_count: ingredients.length, + availability, + }; +} + +/** + * Formats a full recipe detail with scaled ingredients and pantry status. + */ +function formatRecipeDetail(recipe, ingredients, pantryNameSet, scale) { + const scaledIngredients = ingredients.map((ing) => ({ + id: ing.id, + item_name: ing.item_name, + quantity: parseFloat((parseFloat(ing.quantity) * scale).toFixed(4)), + unit: ing.unit, + in_pantry: pantryNameSet.has(ing.item_name_lower), + })); + + const availability = computeAvailability(ingredients, pantryNameSet); + + return { + id: recipe.id, + name: recipe.name, + servings: recipe.servings, + scaled_servings: recipe.servings * scale, + instructions: recipe.instructions, + ingredients: scaledIngredients, + availability, + }; +} + +/** + * Returns all recipes with pantry-based availability. + * Supports filter: 'all' | 'available' | 'partial' + * Supports scale: 1 | 2 | 3 + */ +async function getRecipes(userId, { filter = 'all', scale = 1 }) { + const db = getDb(); + + // Fetch user's pantry as a Set of lowercase names for O(1) lookup + const pantryRows = await db('pantry_items') + .where({ user_id: userId }) + .select('item_name_lower'); + const pantryNameSet = new Set(pantryRows.map((r) => r.item_name_lower)); + + // Fetch all recipes with their ingredients in one query + const recipes = await db('recipes').orderBy('name', 'asc'); + const recipeIds = recipes.map((r) => r.id); + + let ingredientRows = []; + if (recipeIds.length > 0) { + ingredientRows = await db('recipe_ingredients') + .whereIn('recipe_id', recipeIds) + .orderBy('item_name_lower', 'asc'); + } + + // Group ingredients by recipe_id + const ingredientsByRecipe = {}; + for (const ing of ingredientRows) { + if (!ingredientsByRecipe[ing.recipe_id]) { + ingredientsByRecipe[ing.recipe_id] = []; + } + ingredientsByRecipe[ing.recipe_id].push(ing); + } + + let result = recipes.map((recipe) => { + const ingredients = ingredientsByRecipe[recipe.id] || []; + return formatRecipeSummary(recipe, ingredients, pantryNameSet); + }); + + // Apply filter + if (filter === 'available') { + result = result.filter((r) => r.availability.status === 'can_make'); + } else if (filter === 'partial') { + result = result.filter( + (r) => r.availability.status === 'can_make' || r.availability.status === 'partial' + ); + } + + return result; +} + +/** + * Returns full recipe detail for a single recipe. + * Verifies the recipe exists — recipes are global (not user-scoped). + */ +async function getRecipeById(userId, recipeId, { scale = 1 }) { + const db = getDb(); + + const recipe = await db('recipes').where({ id: recipeId }).first(); + if (!recipe) { + throw new AppError(404, 'NOT_FOUND', 'Recipe not found.'); + } + + const ingredients = await db('recipe_ingredients') + .where({ recipe_id: recipeId }) + .orderBy('item_name_lower', 'asc'); + + const pantryRows = await db('pantry_items') + .where({ user_id: userId }) + .select('item_name_lower'); + const pantryNameSet = new Set(pantryRows.map((r) => r.item_name_lower)); + + return formatRecipeDetail(recipe, ingredients, pantryNameSet, scale); +} + +module.exports = { getRecipes, getRecipeById }; diff --git a/src/services/shoppingService.js b/src/services/shoppingService.js new file mode 100644 index 0000000..3f4e627 --- /dev/null +++ b/src/services/shoppingService.js @@ -0,0 +1,340 @@ +'use strict'; + +const { getDb } = require('../db/knex'); +const { AppError } = require('../utils/errors'); + +function formatListSummary(row) { + return { + id: row.id, + list_name: row.list_name, + item_count: parseInt(row.item_count || 0, 10), + checked_count: parseInt(row.checked_count || 0, 10), + last_modified: row.last_modified, + created_at: row.created_at, + }; +} + +function formatItem(row) { + return { + id: row.id, + item_name: row.item_name, + quantity: parseFloat(row.quantity), + unit: row.unit, + checked_off: row.checked_off, + last_modified: row.last_modified, + }; +} + +/** + * Returns all shopping lists for the user with item/checked counts. + */ +async function getShoppingLists(userId) { + const db = getDb(); + + const lists = await db('shopping_lists as sl') + .leftJoin('shopping_list_items as sli', 'sl.id', 'sli.shopping_list_id') + .where('sl.user_id', userId) + .groupBy('sl.id') + .select( + 'sl.id', + 'sl.list_name', + 'sl.last_modified', + 'sl.created_at', + db.raw('COUNT(sli.id) AS item_count'), + db.raw('COUNT(sli.id) FILTER (WHERE sli.checked_off = true) AS checked_count') + ) + .orderBy('sl.created_at', 'desc'); + + return lists.map(formatListSummary); +} + +/** + * Creates a new empty shopping list. + */ +async function createShoppingList(userId, { list_name }) { + const db = getDb(); + + const [list] = await db('shopping_lists') + .insert({ user_id: userId, list_name: list_name.trim() }) + .returning('*'); + + return { + id: list.id, + list_name: list.list_name, + item_count: 0, + checked_count: 0, + last_modified: list.last_modified, + created_at: list.created_at, + }; +} + +/** + * Returns a shopping list with all its items. + * Verifies ownership. + */ +async function getShoppingListById(userId, listId) { + const db = getDb(); + + const list = await db('shopping_lists') + .where({ id: listId, user_id: userId }) + .first(); + + if (!list) { + throw new AppError(404, 'NOT_FOUND', 'Shopping list not found.'); + } + + const items = await db('shopping_list_items') + .where({ shopping_list_id: listId }) + .orderBy('item_name_lower', 'asc'); + + return { + id: list.id, + list_name: list.list_name, + last_modified: list.last_modified, + created_at: list.created_at, + items: items.map(formatItem), + }; +} + +/** + * Deletes a shopping list and all its items. + * Records tombstones for sync. + * Verifies ownership. + */ +async function deleteShoppingList(userId, listId) { + const db = getDb(); + + const list = await db('shopping_lists').where({ id: listId, user_id: userId }).first(); + if (!list) { + throw new AppError(404, 'NOT_FOUND', 'Shopping list not found.'); + } + + await db.transaction(async (trx) => { + const items = await trx('shopping_list_items') + .where({ shopping_list_id: listId }) + .select('id'); + + for (const item of items) { + await trx('deleted_records').insert({ + user_id: userId, + record_type: 'shopping_list_item', + record_id: item.id, + }); + } + + await trx('shopping_lists').where({ id: listId, user_id: userId }).delete(); + + await trx('deleted_records').insert({ + user_id: userId, + record_type: 'shopping_list', + record_id: listId, + }); + }); +} + +/** + * Adds an item to a shopping list. + * Merge logic: same name (case-insensitive) AND same unit → sum quantities. + * Different units → separate line items. + * Verifies list ownership. + */ +async function addItemToList(userId, listId, { item_name, quantity, unit }) { + const db = getDb(); + + const list = await db('shopping_lists').where({ id: listId, user_id: userId }).first(); + if (!list) { + throw new AppError(404, 'NOT_FOUND', 'Shopping list not found.'); + } + + const trimmedName = item_name.trim(); + const now = new Date(); + + const existing = await db('shopping_list_items') + .where({ shopping_list_id: listId, unit }) + .whereRaw('item_name_lower = LOWER(?)', [trimmedName]) + .first(); + + if (existing) { + const newQty = parseFloat((parseFloat(existing.quantity) + quantity).toFixed(4)); + const previousQuantity = parseFloat(existing.quantity); + + const [updated] = await db('shopping_list_items') + .where({ id: existing.id }) + .update({ quantity: newQty, last_modified: now, updated_at: now }) + .returning('*'); + + await db('shopping_lists') + .where({ id: listId }) + .update({ last_modified: now, updated_at: now }); + + return { item: formatItem(updated), merged: true, previous_quantity: previousQuantity }; + } + + const [item] = await db('shopping_list_items') + .insert({ shopping_list_id: listId, item_name: trimmedName, quantity, unit }) + .returning('*'); + + await db('shopping_lists') + .where({ id: listId }) + .update({ last_modified: now, updated_at: now }); + + return { item: formatItem(item), merged: false }; +} + +/** + * Updates a shopping list item (quantity, unit, checked_off). + * All fields are optional — only provided fields are patched. + * Verifies list ownership and item membership. + */ +async function updateListItem(userId, listId, itemId, updates) { + const db = getDb(); + + const list = await db('shopping_lists').where({ id: listId, user_id: userId }).first(); + if (!list) { + throw new AppError(404, 'NOT_FOUND', 'Shopping list not found.'); + } + + const item = await db('shopping_list_items') + .where({ id: itemId, shopping_list_id: listId }) + .first(); + + if (!item) { + throw new AppError(404, 'NOT_FOUND', 'Shopping list item not found.'); + } + + const now = new Date(); + const patch = { last_modified: now, updated_at: now }; + if (updates.quantity !== undefined) patch.quantity = updates.quantity; + if (updates.unit !== undefined) patch.unit = updates.unit; + if (updates.checked_off !== undefined) patch.checked_off = updates.checked_off; + + const [updated] = await db('shopping_list_items') + .where({ id: itemId }) + .update(patch) + .returning('*'); + + await db('shopping_lists') + .where({ id: listId }) + .update({ last_modified: now, updated_at: now }); + + return formatItem(updated); +} + +/** + * Deletes a shopping list item and records a tombstone for sync. + * Verifies list ownership and item membership. + */ +async function deleteListItem(userId, listId, itemId) { + const db = getDb(); + + const list = await db('shopping_lists').where({ id: listId, user_id: userId }).first(); + if (!list) { + throw new AppError(404, 'NOT_FOUND', 'Shopping list not found.'); + } + + const item = await db('shopping_list_items') + .where({ id: itemId, shopping_list_id: listId }) + .first(); + + if (!item) { + throw new AppError(404, 'NOT_FOUND', 'Shopping list item not found.'); + } + + const now = new Date(); + await db.transaction(async (trx) => { + await trx('shopping_list_items').where({ id: itemId }).delete(); + await trx('deleted_records').insert({ + user_id: userId, + record_type: 'shopping_list_item', + record_id: itemId, + }); + await trx('shopping_lists') + .where({ id: listId }) + .update({ last_modified: now, updated_at: now }); + }); +} + +/** + * Adds ingredients from one or more recipes to a shopping list. + * Merge logic: same name (case-insensitive) + same unit → sum quantities. + * Different units → separate line items. + * scale: 1 | 2 | 3 — multiplies all ingredient quantities. + */ +async function addRecipesToList(userId, listId, { recipe_ids, scale = 1 }) { + const db = getDb(); + + const list = await db('shopping_lists').where({ id: listId, user_id: userId }).first(); + if (!list) { + throw new AppError(404, 'NOT_FOUND', 'Shopping list not found.'); + } + + // Validate all recipes exist before touching the list + const recipes = await db('recipes').whereIn('id', recipe_ids); + if (recipes.length !== recipe_ids.length) { + throw new AppError(404, 'NOT_FOUND', 'One or more recipes not found.'); + } + + const recipeIngredients = await db('recipe_ingredients').whereIn('recipe_id', recipe_ids); + + let itemsMerged = 0; + let itemsCreated = 0; + const now = new Date(); + + await db.transaction(async (trx) => { + for (const ing of recipeIngredients) { + const scaledQty = parseFloat((parseFloat(ing.quantity) * scale).toFixed(4)); + + const existing = await trx('shopping_list_items') + .where({ shopping_list_id: listId, unit: ing.unit }) + .whereRaw('item_name_lower = LOWER(?)', [ing.item_name]) + .first(); + + if (existing) { + const newQty = parseFloat((parseFloat(existing.quantity) + scaledQty).toFixed(4)); + await trx('shopping_list_items') + .where({ id: existing.id }) + .update({ quantity: newQty, last_modified: now, updated_at: now }); + itemsMerged++; + } else { + await trx('shopping_list_items').insert({ + shopping_list_id: listId, + item_name: ing.item_name, + quantity: scaledQty, + unit: ing.unit, + }); + itemsCreated++; + } + } + + await trx('shopping_lists') + .where({ id: listId }) + .update({ last_modified: now, updated_at: now }); + }); + + const updatedItems = await db('shopping_list_items') + .where({ shopping_list_id: listId }) + .orderBy('item_name_lower', 'asc'); + + return { + shopping_list: { + id: list.id, + list_name: list.list_name, + last_modified: now, + items: updatedItems.map(formatItem), + }, + recipes_added: recipes.length, + items_merged: itemsMerged, + items_created: itemsCreated, + }; +} + +module.exports = { + getShoppingLists, + createShoppingList, + getShoppingListById, + deleteShoppingList, + addItemToList, + updateListItem, + deleteListItem, + addRecipesToList, +}; diff --git a/src/services/syncService.js b/src/services/syncService.js new file mode 100644 index 0000000..66ba08b --- /dev/null +++ b/src/services/syncService.js @@ -0,0 +1,106 @@ +'use strict'; + +const { getDb } = require('../db/knex'); + +/** + * Returns all data modified since `since` timestamp. + * If `since` is null, returns everything (full sync). + * Includes tombstone records so the client can remove deleted items from cache. + */ +async function getSyncData(userId, since) { + const db = getDb(); + const serverTimestamp = new Date().toISOString(); + const isFullSync = !since; + + // ── Pantry ────────────────────────────────────────────────────────────────── + let pantryQuery = db('pantry_items').where({ user_id: userId }); + if (since) { + pantryQuery = pantryQuery.where('last_modified', '>', since); + } + const pantryItems = await pantryQuery.orderBy('item_name_lower', 'asc'); + + let deletedPantryIds = []; + if (since) { + const tombstones = await db('deleted_records') + .where({ user_id: userId, record_type: 'pantry_item' }) + .where('deleted_at', '>', since) + .select('record_id'); + deletedPantryIds = tombstones.map((r) => r.record_id); + } + + // ── Shopping Lists ─────────────────────────────────────────────────────────── + let listsQuery = db('shopping_lists').where({ user_id: userId }); + if (since) { + listsQuery = listsQuery.where('last_modified', '>', since); + } + const lists = await listsQuery.orderBy('created_at', 'asc'); + + const listIds = lists.map((l) => l.id); + let listItems = []; + if (listIds.length > 0) { + listItems = await db('shopping_list_items') + .whereIn('shopping_list_id', listIds) + .orderBy('item_name_lower', 'asc'); + } + + // Group items by list + const itemsByList = {}; + for (const item of listItems) { + if (!itemsByList[item.shopping_list_id]) { + itemsByList[item.shopping_list_id] = []; + } + itemsByList[item.shopping_list_id].push({ + id: item.id, + item_name: item.item_name, + quantity: parseFloat(item.quantity), + unit: item.unit, + checked_off: item.checked_off, + last_modified: item.last_modified, + deleted: false, + }); + } + + let deletedListIds = []; + let deletedItemIds = []; + if (since) { + const deletedLists = await db('deleted_records') + .where({ user_id: userId, record_type: 'shopping_list' }) + .where('deleted_at', '>', since) + .select('record_id'); + deletedListIds = deletedLists.map((r) => r.record_id); + + const deletedItems = await db('deleted_records') + .where({ user_id: userId, record_type: 'shopping_list_item' }) + .where('deleted_at', '>', since) + .select('record_id'); + deletedItemIds = deletedItems.map((r) => r.record_id); + } + + return { + pantry: { + items: pantryItems.map((p) => ({ + id: p.id, + item_name: p.item_name, + quantity: p.quantity, + last_modified: p.last_modified, + deleted: false, + })), + deleted_ids: deletedPantryIds, + }, + shopping_lists: { + lists: lists.map((l) => ({ + id: l.id, + list_name: l.list_name, + last_modified: l.last_modified, + deleted: false, + items: itemsByList[l.id] || [], + })), + deleted_list_ids: deletedListIds, + deleted_item_ids: deletedItemIds, + }, + server_timestamp: serverTimestamp, + full_sync: isFullSync, + }; +} + +module.exports = { getSyncData }; diff --git a/src/utils/errors.js b/src/utils/errors.js new file mode 100644 index 0000000..afd54ba --- /dev/null +++ b/src/utils/errors.js @@ -0,0 +1,21 @@ +'use strict'; + +/** + * Application-level error. + * status — HTTP status code + * code — machine-readable error code + * message — human-readable message + * extra — optional additional fields merged into the response body + */ +class AppError extends Error { + constructor(status, code, message, extra = null) { + super(message); + this.name = 'AppError'; + this.status = status; + this.code = code; + this.isAppError = true; + this.extra = extra; + } +} + +module.exports = { AppError }; diff --git a/src/utils/jwt.js b/src/utils/jwt.js new file mode 100644 index 0000000..9387fb3 --- /dev/null +++ b/src/utils/jwt.js @@ -0,0 +1,26 @@ +'use strict'; + +const jwt = require('jsonwebtoken'); +const config = require('../config'); + +/** + * Issues a signed JWT for the given user record. + * Returns { token, expires_at }. + */ +function issueToken(user) { + const payload = { + sub: user.id, + email: user.email, + }; + + const token = jwt.sign(payload, config.jwt.secret, { + expiresIn: config.jwt.expiresIn, + }); + + const decoded = jwt.decode(token); + const expires_at = new Date(decoded.exp * 1000).toISOString(); + + return { token, expires_at }; +} + +module.exports = { issueToken }; diff --git a/src/utils/validate.js b/src/utils/validate.js new file mode 100644 index 0000000..118aa2d --- /dev/null +++ b/src/utils/validate.js @@ -0,0 +1,21 @@ +'use strict'; + +const { AppError } = require('./errors'); + +/** + * Validates data against a Zod schema. + * Throws a structured AppError on failure so the central error handler + * can format it consistently. + */ +function validate(schema, data) { + const result = schema.safeParse(data); + if (!result.success) { + const err = new AppError(400, 'VALIDATION_ERROR', 'Validation failed.'); + err.zodError = true; + err.issues = result.error.issues; + throw err; + } + return result.data; +} + +module.exports = { validate }; diff --git a/src/utils/validation.js b/src/utils/validation.js new file mode 100644 index 0000000..b816ff1 --- /dev/null +++ b/src/utils/validation.js @@ -0,0 +1,134 @@ +'use strict'; + +const { z } = require('zod'); + +// ─── Auth ──────────────────────────────────────────────────────────────────── + +const signupSchema = z.object({ + email: z.string().email('Invalid email format.').max(255), + password: z + .string() + .min(8, 'Password must be at least 8 characters.') + .regex(/^[a-zA-Z0-9]+$/, 'Password must be alphanumeric.'), + name: z.string().min(1, 'Name is required.').max(100, 'Name must be 100 characters or fewer.'), +}); + +const signinSchema = z.object({ + email: z.string().email('Invalid email format.'), + password: z.string().min(1, 'Password is required.'), +}); + +const googleAuthSchema = z.object({ + id_token: z.string().min(1, 'id_token is required.'), +}); + +const passwordResetRequestSchema = z.object({ + email: z.string().email('Invalid email format.'), +}); + +const passwordResetConfirmSchema = z.object({ + token: z.string().min(1, 'Token is required.'), + new_password: z + .string() + .min(8, 'Password must be at least 8 characters.') + .regex(/^[a-zA-Z0-9]+$/, 'Password must be alphanumeric.'), +}); + +const restoreAccountSchema = z.object({ + email: z.string().email('Invalid email format.'), + password: z.string().min(1, 'Password is required.'), +}); + +// ─── Pantry ────────────────────────────────────────────────────────────────── + +const addPantryItemSchema = z.object({ + item_name: z + .string() + .min(1, 'Item name is required.') + .max(200, 'Item name must be 200 characters or fewer.') + .transform((v) => v.trim()) + .refine((v) => v.length > 0, 'Item name cannot be blank.'), + quantity: z + .number({ invalid_type_error: 'Quantity must be a number.' }) + .int('Quantity must be a whole number.') + .positive('Quantity must be positive.'), +}); + +const updatePantryItemSchema = z.object({ + quantity: z + .number({ invalid_type_error: 'Quantity must be a number.' }) + .int('Quantity must be a whole number.') + .positive('Quantity must be positive.'), + last_modified: z.string().datetime({ offset: true }).optional(), +}); + +// ─── Shopping Lists ─────────────────────────────────────────────────────────── + +const createShoppingListSchema = z.object({ + list_name: z + .string() + .min(1, 'List name is required.') + .max(200, 'List name must be 200 characters or fewer.'), +}); + +const addShoppingListItemSchema = z.object({ + item_name: z + .string() + .min(1, 'Item name is required.') + .max(200, 'Item name must be 200 characters or fewer.'), + quantity: z + .number({ invalid_type_error: 'Quantity must be a number.' }) + .positive('Quantity must be positive.'), + unit: z.string().min(1, 'Unit is required.').max(50, 'Unit must be 50 characters or fewer.'), +}); + +const updateShoppingListItemSchema = z + .object({ + quantity: z + .number({ invalid_type_error: 'Quantity must be a number.' }) + .positive('Quantity must be positive.') + .optional(), + unit: z.string().min(1).max(50).optional(), + checked_off: z.boolean().optional(), + }) + .refine( + (d) => d.quantity !== undefined || d.unit !== undefined || d.checked_off !== undefined, + { message: 'At least one field (quantity, unit, checked_off) must be provided.' } + ); + +const addRecipesToListSchema = z.object({ + recipe_ids: z + .array(z.string().uuid('Each recipe_id must be a valid UUID.')) + .min(1, 'At least one recipe_id is required.'), + scale: z.number().int().min(1).max(3).optional().default(1), +}); + +// ─── Recipes ───────────────────────────────────────────────────────────────── + +const recipeQuerySchema = z.object({ + filter: z.enum(['all', 'available', 'partial']).optional().default('all'), + scale: z.coerce.number().int().min(1).max(3).optional().default(1), +}); + +// ─── Sync ───────────────────────────────────────────────────────────────────── + +const syncQuerySchema = z.object({ + since: z.string().datetime({ offset: true }).optional(), +}); + +module.exports = { + signupSchema, + signinSchema, + googleAuthSchema, + passwordResetRequestSchema, + passwordResetConfirmSchema, + restoreAccountSchema, + addPantryItemSchema, + updatePantryItemSchema, + createShoppingListSchema, + addShoppingListItemSchema, + updateShoppingListItemSchema, + addRecipesToListSchema, + recipeQuerySchema, + syncQuerySchema, +}; diff --git a/tests/auth.test.js b/tests/auth.test.js new file mode 100644 index 0000000..05c6a62 --- /dev/null +++ b/tests/auth.test.js @@ -0,0 +1,240 @@ +'use strict'; + +const request = require('supertest'); +const app = require('../../src/main/app'); +const { setDb } = require('../../src/db/knex'); +const { createTestDb } = require('../helpers/testDb'); + +describe('Auth Routes', () => { + let db; + + beforeEach(() => { + db = createTestDb(); + setDb(db); + }); + + // ── POST /v1/auth/signup ──────────────────────────────────────────────────── + + describe('POST /v1/auth/signup', () => { + it('creates a new user and returns token', async () => { + const res = await request(app) + .post('/v1/auth/signup') + .send({ email: 'jane@example.com', password: 'password1', name: 'Jane Doe' }); + + expect(res.status).toBe(201); + expect(res.body.user.email).toBe('jane@example.com'); + expect(res.body.user.name).toBe('Jane Doe'); + expect(res.body.token).toBeDefined(); + expect(res.body.expires_at).toBeDefined(); + // password_hash must never appear in response + expect(res.body.user.password_hash).toBeUndefined(); + }); + + it('lowercases email on storage', async () => { + const res = await request(app) + .post('/v1/auth/signup') + .send({ email: 'JANE@EXAMPLE.COM', password: 'password1', name: 'Jane' }); + + expect(res.status).toBe(201); + expect(res.body.user.email).toBe('jane@example.com'); + }); + + it('returns 409 when email already registered', async () => { + await request(app) + .post('/v1/auth/signup') + .send({ email: 'jane@example.com', password: 'password1', name: 'Jane' }); + + const res = await request(app) + .post('/v1/auth/signup') + .send({ email: 'jane@example.com', password: 'password1', name: 'Jane Again' }); + + expect(res.status).toBe(409); + expect(res.body.code).toBe('CONFLICT'); + }); + + it('returns 409 for case-insensitive duplicate email', async () => { + await request(app) + .post('/v1/auth/signup') + .send({ email: 'jane@example.com', password: 'password1', name: 'Jane' }); + + const res = await request(app) + .post('/v1/auth/signup') + .send({ email: 'JANE@EXAMPLE.COM', password: 'password1', name: 'Jane' }); + + expect(res.status).toBe(409); + }); + + it('returns 400 for invalid email', async () => { + const res = await request(app) + .post('/v1/auth/signup') + .send({ email: 'not-an-email', password: 'password1', name: 'Jane' }); + + expect(res.status).toBe(400); + expect(res.body.code).toBe('VALIDATION_ERROR'); + }); + + it('returns 400 for password shorter than 8 chars', async () => { + const res = await request(app) + .post('/v1/auth/signup') + .send({ email: 'jane@example.com', password: 'short', name: 'Jane' }); + + expect(res.status).toBe(400); + }); + + it('returns 400 for non-alphanumeric password', async () => { + const res = await request(app) + .post('/v1/auth/signup') + .send({ email: 'jane@example.com', password: 'p@ssword1', name: 'Jane' }); + + expect(res.status).toBe(400); + }); + + it('returns 400 when name is missing', async () => { + const res = await request(app) + .post('/v1/auth/signup') + .send({ email: 'jane@example.com', password: 'password1' }); + + expect(res.status).toBe(400); + }); + + it('returns 400 when body is empty', async () => { + const res = await request(app).post('/v1/auth/signup').send({}); + expect(res.status).toBe(400); + }); + }); + + // ── POST /v1/auth/signin ──────────────────────────────────────────────────── + + describe('POST /v1/auth/signin', () => { + beforeEach(async () => { + await request(app) + .post('/v1/auth/signup') + .send({ email: 'jane@example.com', password: 'password1', name: 'Jane' }); + }); + + it('returns token on valid credentials', async () => { + const res = await request(app) + .post('/v1/auth/signin') + .send({ email: 'jane@example.com', password: 'password1' }); + + expect(res.status).toBe(200); + expect(res.body.token).toBeDefined(); + expect(res.body.user.email).toBe('jane@example.com'); + }); + + it('is case-insensitive for email', async () => { + const res = await request(app) + .post('/v1/auth/signin') + .send({ email: 'JANE@EXAMPLE.COM', password: 'password1' }); + + expect(res.status).toBe(200); + }); + + it('returns 401 for wrong password', async () => { + const res = await request(app) + .post('/v1/auth/signin') + .send({ email: 'jane@example.com', password: 'wrongpass' }); + + expect(res.status).toBe(401); + expect(res.body.code).toBe('UNAUTHORIZED'); + }); + + it('returns 401 for unknown email', async () => { + const res = await request(app) + .post('/v1/auth/signin') + .send({ email: 'nobody@example.com', password: 'password1' }); + + expect(res.status).toBe(401); + }); + + it('returns 400 when fields are missing', async () => { + const res = await request(app) + .post('/v1/auth/signin') + .send({ email: 'jane@example.com' }); + + expect(res.status).toBe(400); + }); + }); + + // ── POST /v1/auth/password-reset ──────────────────────────────────────────── + + describe('POST /v1/auth/password-reset', () => { + it('always returns 200 regardless of email existence', async () => { + const res = await request(app) + .post('/v1/auth/password-reset') + .send({ email: 'nobody@example.com' }); + + expect(res.status).toBe(200); + expect(res.body.message).toMatch(/reset link/i); + }); + + it('returns 400 for invalid email', async () => { + const res = await request(app) + .post('/v1/auth/password-reset') + .send({ email: 'not-an-email' }); + + expect(res.status).toBe(400); + }); + }); + + // ── DELETE /v1/auth/account ───────────────────────────────────────────────── + + describe('DELETE /v1/auth/account', () => { + it('soft-deletes the authenticated user account', async () => { + const signupRes = await request(app) + .post('/v1/auth/signup') + .send({ email: 'delete@example.com', password: 'password1', name: 'Delete Me' }); + + const token = signupRes.body.token; + + const res = await request(app) + .delete('/v1/auth/account') + .set('Authorization', `Bearer ${token}`); + + expect(res.status).toBe(204); + + // Verify account is soft-deleted + const users = db.getTable('users'); + const user = users.find((u) => u.email === 'delete@example.com'); + expect(user.deleted_at).toBeDefined(); + expect(user.deletion_scheduled_at).toBeDefined(); + }); + + it('returns 401 without token', async () => { + const res = await request(app).delete('/v1/auth/account'); + expect(res.status).toBe(401); + }); + }); + + // ── POST /v1/auth/restore-account ────────────────────────────────────────── + + describe('POST /v1/auth/restore-account', () => { + it('restores a soft-deleted account', async () => { + const signupRes = await request(app) + .post('/v1/auth/signup') + .send({ email: 'restore@example.com', password: 'password1', name: 'Restore Me' }); + + const token = signupRes.body.token; + + await request(app) + .delete('/v1/auth/account') + .set('Authorization', `Bearer ${token}`); + + const res = await request(app) + .post('/v1/auth/restore-account') + .send({ email: 'restore@example.com', password: 'password1' }); + + expect(res.status).toBe(200); + expect(res.body.user.deleted_at).toBeNull(); + expect(res.body.message).toMatch(/restored/i); + }); + + it('returns 401 for wrong credentials', async () => { + const res = await request(app) + .post('/v1/auth/restore-account') + .send({ email: 'nobody@example.com', password: 'password1' }); + + expect(res.status).toBe(401); + }); + }); +}); diff --git a/tests/helpers/testDb.js b/tests/helpers/testDb.js new file mode 100644 index 0000000..fc61233 --- /dev/null +++ b/tests/helpers/testDb.js @@ -0,0 +1,305 @@ +'use strict'; + +/** + * In-memory database stub for tests. + * Replaces the real Knex/PostgreSQL connection with a lightweight + * object that simulates table operations using plain JS Maps. + * + * Usage: const db = createTestDb(); setDb(db); + */ + +function makeTable(rows = []) { + return [...rows]; +} + +/** + * Creates a minimal Knex-like query builder stub backed by in-memory arrays. + * Supports: insert, where, whereRaw, whereIn, whereNull, whereNotNull, + * first, select, update, delete, returning, orderBy, + * leftJoin, groupBy, raw, transaction. + */ +function createTestDb(initialData = {}) { + const tables = {}; + + function getTable(name) { + if (!tables[name]) tables[name] = []; + return tables[name]; + } + + function seedTable(name, rows) { + tables[name] = [...rows]; + } + + // Seed initial data + for (const [name, rows] of Object.entries(initialData)) { + seedTable(name, rows); + } + + // ── Query Builder ──────────────────────────────────────────────────────────── + function queryBuilder(tableName) { + let _rows = null; // lazy — resolved on terminal op + let _filters = []; + let _insertData = null; + let _updateData = null; + let _doDelete = false; + let _returning = false; + let _orderByField = null; + let _orderByDir = 'asc'; + let _selectFields = null; + let _limit1 = false; + let _joins = []; + let _groupByField = null; + let _rawSelects = []; + + function getRows() { + if (_rows !== null) return _rows; + return getTable(tableName); + } + + function applyFilters(rows) { + return rows.filter((row) => { + for (const f of _filters) { + if (!f(row)) return false; + } + return true; + }); + } + + const qb = { + where(condOrField, val) { + if (typeof condOrField === 'object') { + for (const [k, v] of Object.entries(condOrField)) { + _filters.push((row) => row[k] === v); + } + } else { + _filters.push((row) => row[condOrField] === val); + } + return qb; + }, + + whereRaw(expr, params) { + // Support: 'LOWER(email) = ?' and 'item_name_lower = LOWER(?)' + const lowerEmailMatch = expr.match(/LOWER\((\w+)\)\s*=\s*\?/i); + const lowerFieldMatch = expr.match(/(\w+)\s*=\s*LOWER\(\?\)/i); + if (lowerEmailMatch) { + const field = lowerEmailMatch[1]; + const val = params[0].toLowerCase(); + _filters.push((row) => (row[field] || '').toLowerCase() === val); + } else if (lowerFieldMatch) { + const field = lowerFieldMatch[1]; + const val = params[0].toLowerCase(); + _filters.push((row) => (row[field] || '') === val); + } + return qb; + }, + + whereIn(field, vals) { + _filters.push((row) => vals.includes(row[field])); + return qb; + }, + + whereNull(field) { + _filters.push((row) => row[field] == null); + return qb; + }, + + whereNotNull(field) { + _filters.push((row) => row[field] != null); + return qb; + }, + + select(...fields) { + _selectFields = fields.flat(); + return qb; + }, + + orderBy(field, dir = 'asc') { + _orderByField = field; + _orderByDir = dir; + return qb; + }, + + groupBy() { + _groupByField = true; + return qb; + }, + + leftJoin(otherTable, leftKey, rightKey) { + _joins.push({ otherTable, leftKey, rightKey }); + return qb; + }, + + raw(sql) { + _rawSelects.push(sql); + return sql; // knex.raw returns the string in our stub + }, + + insert(data) { + _insertData = Array.isArray(data) ? data : [data]; + return qb; + }, + + update(data) { + _updateData = data; + return qb; + }, + + delete() { + _doDelete = true; + return qb; + }, + + returning() { + _returning = true; + return qb; + }, + + first() { + _limit1 = true; + return qb; + }, + + // Terminal: await qb + then(resolve, reject) { + try { + resolve(execute()); + } catch (e) { + reject(e); + } + }, + }; + + function execute() { + const table = getTable(tableName); + + if (_insertData) { + const inserted = _insertData.map((d) => { + const row = { + id: d.id || require('uuid').v4(), + ...d, + created_at: d.created_at || new Date().toISOString(), + updated_at: d.updated_at || new Date().toISOString(), + last_modified: d.last_modified || new Date().toISOString(), + }; + // Compute generated columns + if (row.item_name !== undefined) { + row.item_name_lower = row.item_name.toLowerCase(); + } + table.push(row); + return row; + }); + return _returning ? inserted : inserted.length; + } + + if (_doDelete) { + const before = table.length; + const toDelete = applyFilters(table); + for (const row of toDelete) { + const idx = table.indexOf(row); + if (idx !== -1) table.splice(idx, 1); + } + return _returning ? toDelete : before - table.length; + } + + if (_updateData) { + const matched = applyFilters(table); + const updated = matched.map((row) => { + Object.assign(row, _updateData, { + updated_at: new Date().toISOString(), + }); + if (row.item_name !== undefined) { + row.item_name_lower = row.item_name.toLowerCase(); + } + return row; + }); + return _returning ? updated : updated.length; + } + + // SELECT + let rows = applyFilters(table); + + // Apply joins (simplified — just attach joined fields) + for (const join of _joins) { + const otherRows = getTable(join.otherTable); + const [leftTable, leftField] = join.leftKey.split('.'); + const [, rightField] = join.rightKey.split('.'); + rows = rows.map((row) => { + const matches = otherRows.filter((o) => o[rightField] === row[leftField || 'id']); + if (matches.length === 0) return { ...row, _joined: [] }; + return matches.map((m) => ({ ...row, ...m, _joined: true })); + }).flat(); + } + + if (_orderByField) { + rows = [...rows].sort((a, b) => { + const av = a[_orderByField] || ''; + const bv = b[_orderByField] || ''; + const cmp = String(av).localeCompare(String(bv)); + return _orderByDir === 'desc' ? -cmp : cmp; + }); + } + + // Aggregate for groupBy (count) + if (_groupByField) { + const grouped = {}; + for (const row of rows) { + const key = row.id; + if (!grouped[key]) { + grouped[key] = { ...row, item_count: 0, checked_count: 0 }; + } + if (row._joined) { + grouped[key].item_count++; + if (row.checked_off) grouped[key].checked_count++; + } + } + rows = Object.values(grouped); + } + + if (_limit1) return rows[0] || null; + return rows; + } + + return qb; + } + + // ── Transaction stub ───────────────────────────────────────────────────────── + async function transaction(fn) { + // Pass the same db proxy as the transaction context + return fn(proxy); + } + + // ── Raw stub ───────────────────────────────────────────────────────────────── + function raw(sql) { + return sql; + } + + const proxy = new Proxy( + { transaction, raw, _tables: tables, seedTable, getTable }, + { + get(target, prop) { + if (prop in target) return target[prop]; + return (tableName) => queryBuilder(tableName || prop); + }, + apply(target, thisArg, args) { + return queryBuilder(args[0]); + }, + } + ); + + // Make proxy callable as a function: db('tableName') + return new Proxy(function () {}, { + apply(target, thisArg, args) { + return queryBuilder(args[0]); + }, + get(target, prop) { + if (prop === 'transaction') return transaction; + if (prop === 'raw') return raw; + if (prop === '_tables') return tables; + if (prop === 'seedTable') return seedTable; + if (prop === 'getTable') return getTable; + return (tableName) => queryBuilder(tableName || prop); + }, + }); +} + +module.exports = { createTestDb }; diff --git a/tests/pantry.test.js b/tests/pantry.test.js new file mode 100644 index 0000000..27a1ce3 --- /dev/null +++ b/tests/pantry.test.js @@ -0,0 +1,308 @@ +'use strict'; + +const request = require('supertest'); +const app = require('../../src/main/app'); +const { setDb } = require('../../src/db/knex'); +const { createTestDb } = require('../helpers/testDb'); +const { issueToken } = require('../../src/utils/jwt'); + +function makeUser(overrides = {}) { + return { + id: require('uuid').v4(), + email: 'jane@example.com', + name: 'Jane Doe', + profile_picture_url: null, + email_verified: true, + deleted_at: null, + deletion_scheduled_at: null, + created_at: new Date().toISOString(), + updated_at: new Date().toISOString(), + ...overrides, + }; +} + +describe('Pantry Routes', () => { + let db; + let user; + let token; + + beforeEach(() => { + user = makeUser(); + db = createTestDb({ users: [user] }); + setDb(db); + token = issueToken(user).token; + }); + + // ── GET /v1/pantry ────────────────────────────────────────────────────────── + + describe('GET /v1/pantry', () => { + it('returns empty items array for new user', async () => { + const res = await request(app) + .get('/v1/pantry') + .set('Authorization', `Bearer ${token}`); + + expect(res.status).toBe(200); + expect(res.body.items).toEqual([]); + expect(res.body.synced_at).toBeDefined(); + }); + + it('returns pantry items for authenticated user', async () => { + db.seedTable('pantry_items', [ + { + id: 'item-1', + user_id: user.id, + item_name: 'Flour', + item_name_lower: 'flour', + quantity: 5, + last_modified: new Date().toISOString(), + created_at: new Date().toISOString(), + updated_at: new Date().toISOString(), + }, + ]); + + const res = await request(app) + .get('/v1/pantry') + .set('Authorization', `Bearer ${token}`); + + expect(res.status).toBe(200); + expect(res.body.items).toHaveLength(1); + expect(res.body.items[0].item_name).toBe('Flour'); + }); + + it('returns 401 without token', async () => { + const res = await request(app).get('/v1/pantry'); + expect(res.status).toBe(401); + }); + + it('does not return items belonging to other users', async () => { + const otherUser = makeUser({ id: 'other-user-id', email: 'other@example.com' }); + db.seedTable('pantry_items', [ + { + id: 'item-other', + user_id: otherUser.id, + item_name: 'Sugar', + item_name_lower: 'sugar', + quantity: 2, + last_modified: new Date().toISOString(), + created_at: new Date().toISOString(), + updated_at: new Date().toISOString(), + }, + ]); + + const res = await request(app) + .get('/v1/pantry') + .set('Authorization', `Bearer ${token}`); + + expect(res.status).toBe(200); + expect(res.body.items).toHaveLength(0); + }); + }); + + // ── POST /v1/pantry ───────────────────────────────────────────────────────── + + describe('POST /v1/pantry', () => { + it('adds a new pantry item', async () => { + const res = await request(app) + .post('/v1/pantry') + .set('Authorization', `Bearer ${token}`) + .send({ item_name: 'Flour', quantity: 5 }); + + expect(res.status).toBe(201); + expect(res.body.item.item_name).toBe('Flour'); + expect(res.body.item.quantity).toBe(5); + expect(res.body.item.id).toBeDefined(); + }); + + it('returns 409 for duplicate item (case-insensitive)', async () => { + await request(app) + .post('/v1/pantry') + .set('Authorization', `Bearer ${token}`) + .send({ item_name: 'Flour', quantity: 5 }); + + const res = await request(app) + .post('/v1/pantry') + .set('Authorization', `Bearer ${token}`) + .send({ item_name: 'flour', quantity: 3 }); + + expect(res.status).toBe(409); + expect(res.body.code).toBe('DUPLICATE_ITEM'); + }); + + it('returns 409 for duplicate with different capitalisation', async () => { + await request(app) + .post('/v1/pantry') + .set('Authorization', `Bearer ${token}`) + .send({ item_name: 'Protein Powder', quantity: 1 }); + + const res = await request(app) + .post('/v1/pantry') + .set('Authorization', `Bearer ${token}`) + .send({ item_name: 'PROTEIN POWDER', quantity: 1 }); + + expect(res.status).toBe(409); + }); + + it('returns 400 for zero quantity', async () => { + const res = await request(app) + .post('/v1/pantry') + .set('Authorization', `Bearer ${token}`) + .send({ item_name: 'Flour', quantity: 0 }); + + expect(res.status).toBe(400); + }); + + it('returns 400 for negative quantity', async () => { + const res = await request(app) + .post('/v1/pantry') + .set('Authorization', `Bearer ${token}`) + .send({ item_name: 'Flour', quantity: -1 }); + + expect(res.status).toBe(400); + }); + + it('returns 400 for fractional quantity', async () => { + const res = await request(app) + .post('/v1/pantry') + .set('Authorization', `Bearer ${token}`) + .send({ item_name: 'Flour', quantity: 1.5 }); + + expect(res.status).toBe(400); + }); + + it('returns 400 for missing item_name', async () => { + const res = await request(app) + .post('/v1/pantry') + .set('Authorization', `Bearer ${token}`) + .send({ quantity: 5 }); + + expect(res.status).toBe(400); + }); + + it('returns 400 for blank item_name', async () => { + const res = await request(app) + .post('/v1/pantry') + .set('Authorization', `Bearer ${token}`) + .send({ item_name: ' ', quantity: 5 }); + + expect(res.status).toBe(400); + }); + + it('returns 401 without token', async () => { + const res = await request(app) + .post('/v1/pantry') + .send({ item_name: 'Flour', quantity: 5 }); + + expect(res.status).toBe(401); + }); + }); + + // ── PUT /v1/pantry/:item_id ───────────────────────────────────────────────── + + describe('PUT /v1/pantry/:item_id', () => { + let itemId; + + beforeEach(async () => { + const res = await request(app) + .post('/v1/pantry') + .set('Authorization', `Bearer ${token}`) + .send({ item_name: 'Flour', quantity: 5 }); + itemId = res.body.item.id; + }); + + it('updates quantity of existing item', async () => { + const res = await request(app) + .put(`/v1/pantry/${itemId}`) + .set('Authorization', `Bearer ${token}`) + .send({ quantity: 10 }); + + expect(res.status).toBe(200); + expect(res.body.item.quantity).toBe(10); + }); + + it('returns 404 for non-existent item', async () => { + const res = await request(app) + .put('/v1/pantry/00000000-0000-0000-0000-000000000000') + .set('Authorization', `Bearer ${token}`) + .send({ quantity: 10 }); + + expect(res.status).toBe(404); + }); + + it('returns 404 for item belonging to another user', async () => { + const otherUser = makeUser({ id: 'other-id', email: 'other@example.com' }); + const otherToken = issueToken(otherUser).token; + + const res = await request(app) + .put(`/v1/pantry/${itemId}`) + .set('Authorization', `Bearer ${otherToken}`) + .send({ quantity: 10 }); + + expect(res.status).toBe(404); + }); + + it('returns 400 for invalid quantity', async () => { + const res = await request(app) + .put(`/v1/pantry/${itemId}`) + .set('Authorization', `Bearer ${token}`) + .send({ quantity: -5 }); + + expect(res.status).toBe(400); + }); + }); + + // ── DELETE /v1/pantry/:item_id ────────────────────────────────────────────── + + describe('DELETE /v1/pantry/:item_id', () => { + let itemId; + + beforeEach(async () => { + const res = await request(app) + .post('/v1/pantry') + .set('Authorization', `Bearer ${token}`) + .send({ item_name: 'Butter', quantity: 2 }); + itemId = res.body.item.id; + }); + + it('deletes an existing pantry item', async () => { + const res = await request(app) + .delete(`/v1/pantry/${itemId}`) + .set('Authorization', `Bearer ${token}`); + + expect(res.status).toBe(204); + + // Verify item is gone + const getRes = await request(app) + .get('/v1/pantry') + .set('Authorization', `Bearer ${token}`); + expect(getRes.body.items).toHaveLength(0); + }); + + it('records a tombstone for sync', async () => { + await request(app) + .delete(`/v1/pantry/${itemId}`) + .set('Authorization', `Bearer ${token}`); + + const tombstones = db.getTable('deleted_records'); + expect(tombstones.some((t) => t.record_id === itemId)).toBe(true); + }); + + it('returns 404 for non-existent item', async () => { + const res = await request(app) + .delete('/v1/pantry/00000000-0000-0000-0000-000000000000') + .set('Authorization', `Bearer ${token}`); + + expect(res.status).toBe(404); + }); + + it('returns 404 for item belonging to another user', async () => { + const otherUser = makeUser({ id: 'other-id', email: 'other@example.com' }); + const otherToken = issueToken(otherUser).token; + + const res = await request(app) + .delete(`/v1/pantry/${itemId}`) + .set('Authorization', `Bearer ${otherToken}`); + + expect(res.status).toBe(404); + }); + }); +}); diff --git a/tests/recipes.test.js b/tests/recipes.test.js new file mode 100644 index 0000000..fb030e0 --- /dev/null +++ b/tests/recipes.test.js @@ -0,0 +1,220 @@ +'use strict'; + +const request = require('supertest'); +const app = require('../../src/main/app'); +const { setDb } = require('../../src/db/knex'); +const { createTestDb } = require('../helpers/testDb'); +const { issueToken } = require('../../src/utils/jwt'); +const { v4: uuidv4 } = require('uuid'); + +function makeUser(overrides = {}) { + return { + id: uuidv4(), + email: 'jane@example.com', + name: 'Jane Doe', + profile_picture_url: null, + email_verified: true, + deleted_at: null, + deletion_scheduled_at: null, + created_at: new Date().toISOString(), + updated_at: new Date().toISOString(), + ...overrides, + }; +} + +const RECIPE_ID = '00000000-0000-0000-0000-000000000001'; + +function makeRecipe(overrides = {}) { + return { + id: RECIPE_ID, + name: 'Classic Pancakes', + instructions: '1. Mix. 2. Cook.', + servings: 4, + created_at: new Date().toISOString(), + updated_at: new Date().toISOString(), + ...overrides, + }; +} + +function makeIngredients(recipeId = RECIPE_ID) { + return [ + { + id: uuidv4(), + recipe_id: recipeId, + item_name: 'flour', + item_name_lower: 'flour', + quantity: '2.0000', + unit: 'cups', + }, + { + id: uuidv4(), + recipe_id: recipeId, + item_name: 'milk', + item_name_lower: 'milk', + quantity: '1.5000', + unit: 'cups', + }, + { + id: uuidv4(), + recipe_id: recipeId, + item_name: 'eggs', + item_name_lower: 'eggs', + quantity: '2.0000', + unit: 'whole', + }, + ]; +} + +describe('Recipe Routes', () => { + let db; + let user; + let token; + + beforeEach(() => { + user = makeUser(); + db = createTestDb({ + users: [user], + recipes: [makeRecipe()], + recipe_ingredients: makeIngredients(), + pantry_items: [], + }); + setDb(db); + token = issueToken(user).token; + }); + + // ── GET /v1/recipes ───────────────────────────────────────────────────────── + + describe('GET /v1/recipes', () => { + it('returns all recipes with availability', async () => { + const res = await request(app) + .get('/v1/recipes') + .set('Authorization', `Bearer ${token}`); + + expect(res.status).toBe(200); + expect(res.body.recipes).toHaveLength(1); + expect(res.body.recipes[0].name).toBe('Classic Pancakes'); + expect(res.body.recipes[0].availability).toBeDefined(); + expect(res.body.synced_at).toBeDefined(); + }); + + it('shows missing_all when pantry is empty', async () => { + const res = await request(app) + .get('/v1/recipes') + .set('Authorization', `Bearer ${token}`); + + expect(res.body.recipes[0].availability.status).toBe('missing_all'); + expect(res.body.recipes[0].availability.available_count).toBe(0); + expect(res.body.recipes[0].availability.total_count).toBe(3); + }); + + it('shows can_make when all ingredients are in pantry', async () => { + db.seedTable('pantry_items', [ + { id: uuidv4(), user_id: user.id, item_name: 'flour', item_name_lower: 'flour', quantity: 5, last_modified: new Date().toISOString(), created_at: new Date().toISOString(), updated_at: new Date().toISOString() }, + { id: uuidv4(), user_id: user.id, item_name: 'milk', item_name_lower: 'milk', quantity: 2, last_modified: new Date().toISOString(), created_at: new Date().toISOString(), updated_at: new Date().toISOString() }, + { id: uuidv4(), user_id: user.id, item_name: 'eggs', item_name_lower: 'eggs', quantity: 6, last_modified: new Date().toISOString(), created_at: new Date().toISOString(), updated_at: new Date().toISOString() }, + ]); + + const res = await request(app) + .get('/v1/recipes') + .set('Authorization', `Bearer ${token}`); + + expect(res.body.recipes[0].availability.status).toBe('can_make'); + expect(res.body.recipes[0].availability.available_count).toBe(3); + }); + + it('shows partial when some ingredients are in pantry', async () => { + db.seedTable('pantry_items', [ + { id: uuidv4(), user_id: user.id, item_name: 'flour', item_name_lower: 'flour', quantity: 5, last_modified: new Date().toISOString(), created_at: new Date().toISOString(), updated_at: new Date().toISOString() }, + ]); + + const res = await request(app) + .get('/v1/recipes') + .set('Authorization', `Bearer ${token}`); + + expect(res.body.recipes[0].availability.status).toBe('partial'); + expect(res.body.recipes[0].availability.available_count).toBe(1); + expect(res.body.recipes[0].availability.missing_ingredients).toContain('milk'); + }); + + it('filters to available only with ?filter=available', async () => { + const res = await request(app) + .get('/v1/recipes?filter=available') + .set('Authorization', `Bearer ${token}`); + + expect(res.status).toBe(200); + expect(res.body.recipes).toHaveLength(0); // pantry is empty + }); + + it('returns 401 without token', async () => { + const res = await request(app).get('/v1/recipes'); + expect(res.status).toBe(401); + }); + + it('returns 400 for invalid scale', async () => { + const res = await request(app) + .get('/v1/recipes?scale=5') + .set('Authorization', `Bearer ${token}`); + + expect(res.status).toBe(400); + }); + }); + + // ── GET /v1/recipes/:recipe_id ────────────────────────────────────────────── + + describe('GET /v1/recipes/:recipe_id', () => { + it('returns full recipe detail', async () => { + const res = await request(app) + .get(`/v1/recipes/${RECIPE_ID}`) + .set('Authorization', `Bearer ${token}`); + + expect(res.status).toBe(200); + expect(res.body.recipe.name).toBe('Classic Pancakes'); + expect(res.body.recipe.instructions).toBeDefined(); + expect(res.body.recipe.ingredients).toHaveLength(3); + expect(res.body.recipe.scaled_servings).toBe(4); + }); + + it('scales ingredient quantities with ?scale=2', async () => { + const res = await request(app) + .get(`/v1/recipes/${RECIPE_ID}?scale=2`) + .set('Authorization', `Bearer ${token}`); + + expect(res.status).toBe(200); + expect(res.body.recipe.scaled_servings).toBe(8); + const flour = res.body.recipe.ingredients.find((i) => i.item_name === 'flour'); + expect(flour.quantity).toBe(4.0); + }); + + it('marks in_pantry correctly', async () => { + db.seedTable('pantry_items', [ + { id: uuidv4(), user_id: user.id, item_name: 'flour', item_name_lower: 'flour', quantity: 5, last_modified: new Date().toISOString(), created_at: new Date().toISOString(), updated_at: new Date().toISOString() }, + ]); + + const res = await request(app) + .get(`/v1/recipes/${RECIPE_ID}`) + .set('Authorization', `Bearer ${token}`); + + const flour = res.body.recipe.ingredients.find((i) => i.item_name === 'flour'); + const milk = res.body.recipe.ingredients.find((i) => i.item_name === 'milk'); + expect(flour.in_pantry).toBe(true); + expect(milk.in_pantry).toBe(false); + }); + + it('returns 404 for non-existent recipe', async () => { + const res = await request(app) + .get('/v1/recipes/00000000-0000-0000-0000-999999999999') + .set('Authorization', `Bearer ${token}`); + + expect(res.status).toBe(404); + expect(res.body.code).toBe('NOT_FOUND'); + }); + + it('returns 400 for invalid scale value', async () => { + const res = await request(app) + .get(`/v1/recipes/${RECIPE_ID}?scale=10`) + .set('Authorization', `Bearer ${token}`); + + expect(res.status).toBe(400); + }); + }); +}); diff --git a/tests/shopping.test.js b/tests/shopping.test.js new file mode 100644 index 0000000..33a29eb --- /dev/null +++ b/tests/shopping.test.js @@ -0,0 +1,525 @@ +'use strict'; + +const request = require('supertest'); +const app = require('../../src/main/app'); +const { setDb } = require('../../src/db/knex'); +const { createTestDb } = require('../helpers/testDb'); +const { issueToken } = require('../../src/utils/jwt'); +const { v4: uuidv4 } = require('uuid'); + +function makeUser(overrides = {}) { + return { + id: uuidv4(), + email: 'jane@example.com', + name: 'Jane Doe', + profile_picture_url: null, + email_verified: true, + deleted_at: null, + deletion_scheduled_at: null, + created_at: new Date().toISOString(), + updated_at: new Date().toISOString(), + ...overrides, + }; +} + +const RECIPE_ID = '00000000-0000-0000-0000-000000000001'; + +describe('Shopping List Routes', () => { + let db; + let user; + let token; + + beforeEach(() => { + user = makeUser(); + db = createTestDb({ + users: [user], + shopping_lists: [], + shopping_list_items: [], + deleted_records: [], + recipes: [ + { + id: RECIPE_ID, + name: 'Pancakes', + instructions: '1. Mix. 2. Cook.', + servings: 4, + created_at: new Date().toISOString(), + updated_at: new Date().toISOString(), + }, + ], + recipe_ingredients: [ + { + id: uuidv4(), + recipe_id: RECIPE_ID, + item_name: 'flour', + item_name_lower: 'flour', + quantity: '2.0000', + unit: 'cups', + }, + { + id: uuidv4(), + recipe_id: RECIPE_ID, + item_name: 'milk', + item_name_lower: 'milk', + quantity: '1.5000', + unit: 'cups', + }, + ], + }); + setDb(db); + token = issueToken(user).token; + }); + + // ── GET /v1/shopping-lists ────────────────────────────────────────────────── + + describe('GET /v1/shopping-lists', () => { + it('returns empty array for new user', async () => { + const res = await request(app) + .get('/v1/shopping-lists') + .set('Authorization', `Bearer ${token}`); + + expect(res.status).toBe(200); + expect(res.body.shopping_lists).toEqual([]); + expect(res.body.synced_at).toBeDefined(); + }); + + it('returns 401 without token', async () => { + const res = await request(app).get('/v1/shopping-lists'); + expect(res.status).toBe(401); + }); + }); + + // ── POST /v1/shopping-lists ───────────────────────────────────────────────── + + describe('POST /v1/shopping-lists', () => { + it('creates a new shopping list', async () => { + const res = await request(app) + .post('/v1/shopping-lists') + .set('Authorization', `Bearer ${token}`) + .send({ list_name: 'Weekly Groceries' }); + + expect(res.status).toBe(201); + expect(res.body.shopping_list.list_name).toBe('Weekly Groceries'); + expect(res.body.shopping_list.item_count).toBe(0); + expect(res.body.shopping_list.id).toBeDefined(); + }); + + it('returns 400 for missing list_name', async () => { + const res = await request(app) + .post('/v1/shopping-lists') + .set('Authorization', `Bearer ${token}`) + .send({}); + + expect(res.status).toBe(400); + }); + + it('returns 400 for empty list_name', async () => { + const res = await request(app) + .post('/v1/shopping-lists') + .set('Authorization', `Bearer ${token}`) + .send({ list_name: '' }); + + expect(res.status).toBe(400); + }); + + it('returns 401 without token', async () => { + const res = await request(app) + .post('/v1/shopping-lists') + .send({ list_name: 'Test' }); + + expect(res.status).toBe(401); + }); + }); + + // ── GET /v1/shopping-lists/:list_id ──────────────────────────────────────── + + describe('GET /v1/shopping-lists/:list_id', () => { + let listId; + + beforeEach(async () => { + const res = await request(app) + .post('/v1/shopping-lists') + .set('Authorization', `Bearer ${token}`) + .send({ list_name: 'My List' }); + listId = res.body.shopping_list.id; + }); + + it('returns list with items', async () => { + const res = await request(app) + .get(`/v1/shopping-lists/${listId}`) + .set('Authorization', `Bearer ${token}`); + + expect(res.status).toBe(200); + expect(res.body.shopping_list.id).toBe(listId); + expect(res.body.shopping_list.items).toEqual([]); + }); + + it('returns 404 for non-existent list', async () => { + const res = await request(app) + .get('/v1/shopping-lists/00000000-0000-0000-0000-000000000000') + .set('Authorization', `Bearer ${token}`); + + expect(res.status).toBe(404); + }); + + it('returns 404 for list belonging to another user', async () => { + const otherUser = makeUser({ id: uuidv4(), email: 'other@example.com' }); + const otherToken = issueToken(otherUser).token; + + const res = await request(app) + .get(`/v1/shopping-lists/${listId}`) + .set('Authorization', `Bearer ${otherToken}`); + + expect(res.status).toBe(404); + }); + }); + + // ── DELETE /v1/shopping-lists/:list_id ───────────────────────────────────── + + describe('DELETE /v1/shopping-lists/:list_id', () => { + let listId; + + beforeEach(async () => { + const res = await request(app) + .post('/v1/shopping-lists') + .set('Authorization', `Bearer ${token}`) + .send({ list_name: 'Delete Me' }); + listId = res.body.shopping_list.id; + }); + + it('deletes the shopping list', async () => { + const res = await request(app) + .delete(`/v1/shopping-lists/${listId}`) + .set('Authorization', `Bearer ${token}`); + + expect(res.status).toBe(204); + + const getRes = await request(app) + .get(`/v1/shopping-lists/${listId}`) + .set('Authorization', `Bearer ${token}`); + expect(getRes.status).toBe(404); + }); + + it('records tombstone for sync', async () => { + await request(app) + .delete(`/v1/shopping-lists/${listId}`) + .set('Authorization', `Bearer ${token}`); + + const tombstones = db.getTable('deleted_records'); + expect(tombstones.some((t) => t.record_id === listId)).toBe(true); + }); + + it('returns 404 for non-existent list', async () => { + const res = await request(app) + .delete('/v1/shopping-lists/00000000-0000-0000-0000-000000000000') + .set('Authorization', `Bearer ${token}`); + + expect(res.status).toBe(404); + }); + }); + + // ── POST /v1/shopping-lists/:list_id/items ────────────────────────────────── + + describe('POST /v1/shopping-lists/:list_id/items', () => { + let listId; + + beforeEach(async () => { + const res = await request(app) + .post('/v1/shopping-lists') + .set('Authorization', `Bearer ${token}`) + .send({ list_name: 'Groceries' }); + listId = res.body.shopping_list.id; + }); + + it('adds an item to the list', async () => { + const res = await request(app) + .post(`/v1/shopping-lists/${listId}/items`) + .set('Authorization', `Bearer ${token}`) + .send({ item_name: 'flour', quantity: 2.0, unit: 'cups' }); + + expect(res.status).toBe(201); + expect(res.body.item.item_name).toBe('flour'); + expect(res.body.item.quantity).toBe(2.0); + expect(res.body.merged).toBe(false); + }); + + it('merges quantities for same name and unit', async () => { + await request(app) + .post(`/v1/shopping-lists/${listId}/items`) + .set('Authorization', `Bearer ${token}`) + .send({ item_name: 'flour', quantity: 2.0, unit: 'cups' }); + + const res = await request(app) + .post(`/v1/shopping-lists/${listId}/items`) + .set('Authorization', `Bearer ${token}`) + .send({ item_name: 'flour', quantity: 1.5, unit: 'cups' }); + + expect(res.status).toBe(201); + expect(res.body.merged).toBe(true); + expect(res.body.item.quantity).toBe(3.5); + expect(res.body.previous_quantity).toBe(2.0); + }); + + it('merges case-insensitively', async () => { + await request(app) + .post(`/v1/shopping-lists/${listId}/items`) + .set('Authorization', `Bearer ${token}`) + .send({ item_name: 'Flour', quantity: 2.0, unit: 'cups' }); + + const res = await request(app) + .post(`/v1/shopping-lists/${listId}/items`) + .set('Authorization', `Bearer ${token}`) + .send({ item_name: 'FLOUR', quantity: 1.0, unit: 'cups' }); + + expect(res.body.merged).toBe(true); + expect(res.body.item.quantity).toBe(3.0); + }); + + it('creates separate items for same name but different unit', async () => { + await request(app) + .post(`/v1/shopping-lists/${listId}/items`) + .set('Authorization', `Bearer ${token}`) + .send({ item_name: 'flour', quantity: 2.0, unit: 'cups' }); + + const res = await request(app) + .post(`/v1/shopping-lists/${listId}/items`) + .set('Authorization', `Bearer ${token}`) + .send({ item_name: 'flour', quantity: 100.0, unit: 'g' }); + + expect(res.body.merged).toBe(false); + + const listRes = await request(app) + .get(`/v1/shopping-lists/${listId}`) + .set('Authorization', `Bearer ${token}`); + expect(listRes.body.shopping_list.items).toHaveLength(2); + }); + + it('returns 400 for missing unit', async () => { + const res = await request(app) + .post(`/v1/shopping-lists/${listId}/items`) + .set('Authorization', `Bearer ${token}`) + .send({ item_name: 'flour', quantity: 2.0 }); + + expect(res.status).toBe(400); + }); + + it('returns 400 for zero quantity', async () => { + const res = await request(app) + .post(`/v1/shopping-lists/${listId}/items`) + .set('Authorization', `Bearer ${token}`) + .send({ item_name: 'flour', quantity: 0, unit: 'cups' }); + + expect(res.status).toBe(400); + }); + + it('returns 404 for non-existent list', async () => { + const res = await request(app) + .post('/v1/shopping-lists/00000000-0000-0000-0000-000000000000/items') + .set('Authorization', `Bearer ${token}`) + .send({ item_name: 'flour', quantity: 2.0, unit: 'cups' }); + + expect(res.status).toBe(404); + }); + }); + + // ── PUT /v1/shopping-lists/:list_id/items/:item_id ────────────────────────── + + describe('PUT /v1/shopping-lists/:list_id/items/:item_id', () => { + let listId; + let itemId; + + beforeEach(async () => { + const listRes = await request(app) + .post('/v1/shopping-lists') + .set('Authorization', `Bearer ${token}`) + .send({ list_name: 'Update Test' }); + listId = listRes.body.shopping_list.id; + + const itemRes = await request(app) + .post(`/v1/shopping-lists/${listId}/items`) + .set('Authorization', `Bearer ${token}`) + .send({ item_name: 'butter', quantity: 1.0, unit: 'cups' }); + itemId = itemRes.body.item.id; + }); + + it('updates checked_off status', async () => { + const res = await request(app) + .put(`/v1/shopping-lists/${listId}/items/${itemId}`) + .set('Authorization', `Bearer ${token}`) + .send({ checked_off: true }); + + expect(res.status).toBe(200); + expect(res.body.item.checked_off).toBe(true); + }); + + it('updates quantity', async () => { + const res = await request(app) + .put(`/v1/shopping-lists/${listId}/items/${itemId}`) + .set('Authorization', `Bearer ${token}`) + .send({ quantity: 3.5 }); + + expect(res.status).toBe(200); + expect(res.body.item.quantity).toBe(3.5); + }); + + it('returns 400 when no fields provided', async () => { + const res = await request(app) + .put(`/v1/shopping-lists/${listId}/items/${itemId}`) + .set('Authorization', `Bearer ${token}`) + .send({}); + + expect(res.status).toBe(400); + }); + + it('returns 404 for non-existent item', async () => { + const res = await request(app) + .put(`/v1/shopping-lists/${listId}/items/00000000-0000-0000-0000-000000000000`) + .set('Authorization', `Bearer ${token}`) + .send({ checked_off: true }); + + expect(res.status).toBe(404); + }); + }); + + // ── DELETE /v1/shopping-lists/:list_id/items/:item_id ─────────────────────── + + describe('DELETE /v1/shopping-lists/:list_id/items/:item_id', () => { + let listId; + let itemId; + + beforeEach(async () => { + const listRes = await request(app) + .post('/v1/shopping-lists') + .set('Authorization', `Bearer ${token}`) + .send({ list_name: 'Delete Item Test' }); + listId = listRes.body.shopping_list.id; + + const itemRes = await request(app) + .post(`/v1/shopping-lists/${listId}/items`) + .set('Authorization', `Bearer ${token}`) + .send({ item_name: 'sugar', quantity: 1.0, unit: 'cups' }); + itemId = itemRes.body.item.id; + }); + + it('deletes the item', async () => { + const res = await request(app) + .delete(`/v1/shopping-lists/${listId}/items/${itemId}`) + .set('Authorization', `Bearer ${token}`); + + expect(res.status).toBe(204); + + const listRes = await request(app) + .get(`/v1/shopping-lists/${listId}`) + .set('Authorization', `Bearer ${token}`); + expect(listRes.body.shopping_list.items).toHaveLength(0); + }); + + it('records tombstone for sync', async () => { + await request(app) + .delete(`/v1/shopping-lists/${listId}/items/${itemId}`) + .set('Authorization', `Bearer ${token}`); + + const tombstones = db.getTable('deleted_records'); + expect(tombstones.some((t) => t.record_id === itemId)).toBe(true); + }); + + it('returns 404 for non-existent item', async () => { + const res = await request(app) + .delete(`/v1/shopping-lists/${listId}/items/00000000-0000-0000-0000-000000000000`) + .set('Authorization', `Bearer ${token}`); + + expect(res.status).toBe(404); + }); + }); + + // ── POST /v1/shopping-lists/:list_id/add-recipes ──────────────────────────── + + describe('POST /v1/shopping-lists/:list_id/add-recipes', () => { + let listId; + + beforeEach(async () => { + const res = await request(app) + .post('/v1/shopping-lists') + .set('Authorization', `Bearer ${token}`) + .send({ list_name: 'Recipe List' }); + listId = res.body.shopping_list.id; + }); + + it('adds recipe ingredients to the list', async () => { + const res = await request(app) + .post(`/v1/shopping-lists/${listId}/add-recipes`) + .set('Authorization', `Bearer ${token}`) + .send({ recipe_ids: [RECIPE_ID], scale: 1 }); + + expect(res.status).toBe(201); + expect(res.body.recipes_added).toBe(1); + expect(res.body.items_created).toBe(2); // flour + milk + expect(res.body.shopping_list.items).toHaveLength(2); + }); + + it('merges quantities when adding same recipe twice', async () => { + await request(app) + .post(`/v1/shopping-lists/${listId}/add-recipes`) + .set('Authorization', `Bearer ${token}`) + .send({ recipe_ids: [RECIPE_ID], scale: 1 }); + + const res = await request(app) + .post(`/v1/shopping-lists/${listId}/add-recipes`) + .set('Authorization', `Bearer ${token}`) + .send({ recipe_ids: [RECIPE_ID], scale: 1 }); + + expect(res.status).toBe(201); + expect(res.body.items_merged).toBe(2); + expect(res.body.items_created).toBe(0); + + const flour = res.body.shopping_list.items.find((i) => i.item_name === 'flour'); + expect(flour.quantity).toBe(4.0); // 2 + 2 + }); + + it('scales ingredient quantities', async () => { + const res = await request(app) + .post(`/v1/shopping-lists/${listId}/add-recipes`) + .set('Authorization', `Bearer ${token}`) + .send({ recipe_ids: [RECIPE_ID], scale: 2 }); + + expect(res.status).toBe(201); + const flour = res.body.shopping_list.items.find((i) => i.item_name === 'flour'); + expect(flour.quantity).toBe(4.0); // 2 * 2 + }); + + it('returns 400 for empty recipe_ids', async () => { + const res = await request(app) + .post(`/v1/shopping-lists/${listId}/add-recipes`) + .set('Authorization', `Bearer ${token}`) + .send({ recipe_ids: [] }); + + expect(res.status).toBe(400); + }); + + it('returns 400 for invalid scale', async () => { + const res = await request(app) + .post(`/v1/shopping-lists/${listId}/add-recipes`) + .set('Authorization', `Bearer ${token}`) + .send({ recipe_ids: [RECIPE_ID], scale: 5 }); + + expect(res.status).toBe(400); + }); + + it('returns 404 for non-existent recipe', async () => { + const res = await request(app) + .post(`/v1/shopping-lists/${listId}/add-recipes`) + .set('Authorization', `Bearer ${token}`) + .send({ recipe_ids: ['00000000-0000-0000-0000-999999999999'] }); + + expect(res.status).toBe(404); + }); + + it('returns 404 for non-existent list', async () => { + const res = await request(app) + .post('/v1/shopping-lists/00000000-0000-0000-0000-000000000000/add-recipes') + .set('Authorization', `Bearer ${token}`) + .send({ recipe_ids: [RECIPE_ID] }); + + expect(res.status).toBe(404); + }); + }); +}); diff --git a/tests/sync.test.js b/tests/sync.test.js new file mode 100644 index 0000000..8b5889d --- /dev/null +++ b/tests/sync.test.js @@ -0,0 +1,166 @@ +'use strict'; + +const request = require('supertest'); +const app = require('../../src/main/app'); +const { setDb } = require('../../src/db/knex'); +const { createTestDb } = require('../helpers/testDb'); +const { issueToken } = require('../../src/utils/jwt'); +const { v4: uuidv4 } = require('uuid'); + +function makeUser(overrides = {}) { + return { + id: uuidv4(), + email: 'jane@example.com', + name: 'Jane Doe', + profile_picture_url: null, + email_verified: true, + deleted_at: null, + deletion_scheduled_at: null, + created_at: new Date().toISOString(), + updated_at: new Date().toISOString(), + ...overrides, + }; +} + +describe('Sync Route', () => { + let db; + let user; + let token; + + beforeEach(() => { + user = makeUser(); + db = createTestDb({ + users: [user], + pantry_items: [], + shopping_lists: [], + shopping_list_items: [], + deleted_records: [], + }); + setDb(db); + token = issueToken(user).token; + }); + + describe('GET /v1/sync', () => { + it('returns full sync when no since param', async () => { + const res = await request(app) + .get('/v1/sync') + .set('Authorization', `Bearer ${token}`); + + expect(res.status).toBe(200); + expect(res.body.full_sync).toBe(true); + expect(res.body.server_timestamp).toBeDefined(); + expect(res.body.pantry).toBeDefined(); + expect(res.body.shopping_lists).toBeDefined(); + }); + + it('returns delta sync when since param provided', async () => { + const since = new Date(Date.now() - 60000).toISOString(); // 1 minute ago + const res = await request(app) + .get(`/v1/sync?since=${encodeURIComponent(since)}`) + .set('Authorization', `Bearer ${token}`); + + expect(res.status).toBe(200); + expect(res.body.full_sync).toBe(false); + }); + + it('includes pantry items in full sync', async () => { + db.seedTable('pantry_items', [ + { + id: uuidv4(), + user_id: user.id, + item_name: 'Flour', + item_name_lower: 'flour', + quantity: 5, + last_modified: new Date().toISOString(), + created_at: new Date().toISOString(), + updated_at: new Date().toISOString(), + }, + ]); + + const res = await request(app) + .get('/v1/sync') + .set('Authorization', `Bearer ${token}`); + + expect(res.body.pantry.items).toHaveLength(1); + expect(res.body.pantry.items[0].item_name).toBe('Flour'); + expect(res.body.pantry.items[0].deleted).toBe(false); + }); + + it('includes shopping lists in full sync', async () => { + const listId = uuidv4(); + db.seedTable('shopping_lists', [ + { + id: listId, + user_id: user.id, + list_name: 'Weekly', + last_modified: new Date().toISOString(), + created_at: new Date().toISOString(), + updated_at: new Date().toISOString(), + }, + ]); + + const res = await request(app) + .get('/v1/sync') + .set('Authorization', `Bearer ${token}`); + + expect(res.body.shopping_lists.lists).toHaveLength(1); + expect(res.body.shopping_lists.lists[0].list_name).toBe('Weekly'); + }); + + it('includes deleted_ids for tombstoned pantry items', async () => { + const deletedId = uuidv4(); + const since = new Date(Date.now() - 60000).toISOString(); + + db.seedTable('deleted_records', [ + { + id: uuidv4(), + user_id: user.id, + record_type: 'pantry_item', + record_id: deletedId, + deleted_at: new Date().toISOString(), + }, + ]); + + const res = await request(app) + .get(`/v1/sync?since=${encodeURIComponent(since)}`) + .set('Authorization', `Bearer ${token}`); + + expect(res.body.pantry.deleted_ids).toContain(deletedId); + }); + + it('returns 401 without token', async () => { + const res = await request(app).get('/v1/sync'); + expect(res.status).toBe(401); + }); + + it('returns 400 for invalid since timestamp', async () => { + const res = await request(app) + .get('/v1/sync?since=not-a-date') + .set('Authorization', `Bearer ${token}`); + + expect(res.status).toBe(400); + }); + + it('does not return data belonging to other users', async () => { + const otherUser = makeUser({ id: uuidv4(), email: 'other@example.com' }); + db.seedTable('pantry_items', [ + { + id: uuidv4(), + user_id: otherUser.id, + item_name: 'Sugar', + item_name_lower: 'sugar', + quantity: 3, + last_modified: new Date().toISOString(), + created_at: new Date().toISOString(), + updated_at: new Date().toISOString(), + }, + ]); + + const res = await request(app) + .get('/v1/sync') + .set('Authorization', `Bearer ${token}`); + + expect(res.body.pantry.items).toHaveLength(0); + }); + }); +});