frontend
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
node_modules
|
||||
.angular
|
||||
.npm-cache
|
||||
.git
|
||||
data
|
||||
test-results
|
||||
@@ -0,0 +1,6 @@
|
||||
node_modules/
|
||||
dist/
|
||||
.angular/
|
||||
.npm-cache/
|
||||
data/
|
||||
test-results/
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
FROM node:24-bookworm-slim
|
||||
ENV NODE_ENV=production PORT=3000 DATA_DIR=/app/data
|
||||
WORKDIR /app
|
||||
COPY dist ./dist
|
||||
COPY server ./server
|
||||
RUN mkdir -p /app/data && chown node:node /app/data
|
||||
USER node
|
||||
EXPOSE 3000
|
||||
CMD ["node", "server/server.mjs"]
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
# À Mesa — refeições partilhadas
|
||||
|
||||
## Editar receitas e lista de compras
|
||||
|
||||
Abra uma receita e escolha **Editar receita** para alterar nome, imagem, ingredientes ou preparação. A receita mantém o identificador e as ligações ao plano. Se outra pessoa a alterar enquanto o formulário estiver aberto, a gravação é recusada com uma mensagem para reabrir a versão atual.
|
||||
|
||||
Na **Lista de compras**, utilize **Adicionar produto**, **Editar** e **Remover**. Os ajustes são partilhados e guardados por semana, sem alterar os ingredientes das receitas. Uma quantidade editada substitui o total calculado desse produto, mesmo que o plano mude depois. Em **Ajustes desta semana** pode repor o cálculo automático ou descartar produtos manuais. Os produtos automáticos são identificados pelo nome e unidade: se editar estes campos nos ingredientes de uma receita, o novo ingrediente é calculado separadamente dos ajustes antigos.
|
||||
|
||||
## Atualizar a instalação existente sem perder dados
|
||||
|
||||
Esta versão adiciona uma tabela com `CREATE TABLE IF NOT EXISTS`; não elimina nem substitui receitas ou o plano existentes. Utilize a mesma pasta de instalação, o mesmo projeto Compose e o volume `meals-data` atual. Não copie uma base de dados local por cima da base de dados do servidor.
|
||||
|
||||
Antes de atualizar, faça uma cópia de segurança no servidor:
|
||||
|
||||
```sh
|
||||
cd /docker/angular/amesa
|
||||
docker compose stop app
|
||||
docker compose cp app:/app/data ./backup-amesa-antes-edicao
|
||||
docker compose start app
|
||||
```
|
||||
|
||||
Compile no computador de desenvolvimento com `npm run build`. Copie a pasta `dist` completa, a pasta `server` e o `nginx.conf` atualizado para `/docker/angular/amesa/`, mantendo o projeto Compose e o volume existentes. O limite de upload do Nginx passa a 8 MB para permitir editar receitas com imagens. O Dockerfile utiliza os ficheiros já compilados; `.dockerignore` não deve excluir `dist`. Depois execute no servidor:
|
||||
|
||||
```sh
|
||||
cd /docker/angular/amesa
|
||||
docker compose up -d --build
|
||||
docker compose restart nginx
|
||||
```
|
||||
|
||||
Não utilize `docker compose down -v`: elimina o volume de dados. Aceda à porta 6969 e atualize a página. A migração e a persistência são verificadas em testes com uma base de dados no formato antigo; o servidor remoto não é alterado automaticamente pelo desenvolvimento local.
|
||||
|
||||
Angular com backend Node.js e SQLite. Todas as pessoas que acedem ao mesmo servidor veem a mesma coleção de receitas e o mesmo plano semanal. A página procura alterações a cada 5 segundos. As gravações são feitas no servidor.
|
||||
|
||||
## Publicar em Docker
|
||||
|
||||
Instale Docker com Compose no servidor e execute nesta pasta:
|
||||
|
||||
```sh
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
Abra `http://IP-DO-SERVIDOR:6969` nos dispositivos com acesso ao servidor. O `docker-compose.yml` inicia o Nginx com a configuração de `nginx.conf` e o backend; apenas a porta do Nginx fica publicada. O backend serve os ficheiros Angular e a API. Para acesso pela Internet, configure o domínio e HTTPS no proxy.
|
||||
|
||||
O volume `meals-data` guarda `/app/data/amesa.sqlite`, incluindo imagens carregadas. Reiniciar ou reconstruir o container mantém os dados. Não execute `docker compose down -v` se quiser manter os dados: essa opção elimina o volume. Utilize apenas uma instância da aplicação sobre este volume SQLite.
|
||||
|
||||
É um espaço partilhado sem contas: qualquer pessoa com acesso pode consultar e adicionar receitas e alterar o plano. Restrinja o acesso no proxy/VPN se o espaço for privado.
|
||||
|
||||
## Executar sem Docker
|
||||
|
||||
Requer Node.js 24 ou superior.
|
||||
|
||||
```sh
|
||||
npm install
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
Abra `http://localhost:3000` ou `http://IP-DO-SERVIDOR:3000`. O servidor serve a aplicação e a API. Guarda a base de dados em `data/amesa.sqlite`. As variáveis `PORT` e `DATA_DIR` permitem alterar a porta e a pasta.
|
||||
|
||||
Para desenvolver, mantenha `npm start` num terminal e execute `npm run dev` noutro. Abra `http://localhost:4200`; o proxy encaminha `/api` para o backend na porta 3000. Em PowerShell com scripts desativados, utilize `npm.cmd`.
|
||||
|
||||
## Receitas anteriores
|
||||
|
||||
A aba **Lista de compras** soma os ingredientes de todas as refeições da semana selecionada. Cada ocorrência de um prato conta uma receita completa. Aceita quantidades no início de cada linha (por exemplo, `200 g de arroz`, `0,5 kg de arroz`, `2 ovos`, `½ abacate`). Converte kg/g e l/ml e mantém medidas incompatíveis separadas. Ingredientes sem quantidade ou com intervalos ficam indicados para confirmação; não são estimados. Use nomes consistentes para o mesmo ingrediente. A lista acompanha automaticamente as alterações ao plano partilhado.
|
||||
|
||||
Se existirem receitas no localStorage `amesa-v1`, aparece um botão para importar para a coleção partilhada. Abra a aplicação no navegador e no endereço/porta antigos para encontrar esses dados; por exemplo, use o servidor de desenvolvimento na porta 4200. A importação conserva os dados locais e pode ser repetida sem duplicar receitas já importadas. O plano local antigo não é importado; o novo plano é comum a todos.
|
||||
|
||||
Fotografias carregadas (PNG, JPEG, GIF ou WebP, até 2 MB) ficam na base de dados. Para fotografias por URL, guarda-se o endereço; a imagem depende do site externo. Inclui seis receitas iniciais e começa com o plano partilhado vazio.
|
||||
|
||||
## Cópia de segurança
|
||||
|
||||
Pare a aplicação antes de copiar a pasta de dados completa, incluindo eventuais ficheiros SQLite `-wal` e `-shm`. Em Docker:
|
||||
|
||||
```sh
|
||||
docker compose stop app
|
||||
docker compose cp app:/app/data ./backup-amesa
|
||||
docker compose start app
|
||||
```
|
||||
|
||||
Para restaurar, pare a aplicação e reponha o conteúdo da pasta de dados a partir da cópia, preservando as permissões de escrita do utilizador `node` no container.
|
||||
|
||||
## Validação
|
||||
|
||||
```sh
|
||||
npm run build
|
||||
npm test
|
||||
```
|
||||
|
||||
Os testes verificam gravações simultâneas, leitura partilhada, imagens, repetição de pedidos, remoção por identificador, validação e persistência após reiniciar o servidor.
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"version": 1,
|
||||
"projects": {
|
||||
"a-mesa": {
|
||||
"projectType": "application",
|
||||
"root": "",
|
||||
"sourceRoot": "src",
|
||||
"architect": {
|
||||
"build": {
|
||||
"builder": "@angular/build:application",
|
||||
"options": {
|
||||
"outputPath": "dist/a-mesa",
|
||||
"index": "src/index.html",
|
||||
"browser": "src/main.ts",
|
||||
"polyfills": [
|
||||
"zone.js"
|
||||
],
|
||||
"tsConfig": "tsconfig.json",
|
||||
"styles": [
|
||||
"src/styles.css"
|
||||
],
|
||||
"optimization": {
|
||||
"scripts": true,
|
||||
"styles": true,
|
||||
"fonts": false
|
||||
}
|
||||
}
|
||||
},
|
||||
"serve": {
|
||||
"builder": "@angular/build:dev-server",
|
||||
"options": {
|
||||
"buildTarget": "a-mesa:build"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"cli": {
|
||||
"analytics": "3363099e-a8c9-4742-83c0-90dd1f11804a"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
services:
|
||||
nginx:
|
||||
image: nginx:stable-alpine
|
||||
ports:
|
||||
- "6969:80"
|
||||
volumes:
|
||||
- ./nginx.conf:/etc/nginx/nginx.conf:ro
|
||||
depends_on:
|
||||
app:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
|
||||
app:
|
||||
build: .
|
||||
environment:
|
||||
NODE_ENV: production
|
||||
PORT: "3000"
|
||||
DATA_DIR: /app/data
|
||||
expose:
|
||||
- "3000"
|
||||
volumes:
|
||||
- meals-data:/app/data
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD", "node", "-e", "fetch('http://localhost:3000/api/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 10s
|
||||
|
||||
volumes:
|
||||
meals-data:
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
worker_processes auto;
|
||||
|
||||
events {
|
||||
worker_connections 1024;
|
||||
}
|
||||
|
||||
http {
|
||||
include /etc/nginx/mime.types;
|
||||
default_type application/octet-stream;
|
||||
sendfile on;
|
||||
server_tokens off;
|
||||
|
||||
# DNS interno do Docker; acompanha a recriação do container app.
|
||||
resolver 127.0.0.11 valid=10s ipv6=off;
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name _;
|
||||
|
||||
# As imagens são enviadas em JSON/base64 (máximo de 2 MB por imagem).
|
||||
# A edição inclui a versão anterior para detetar alterações simultâneas.
|
||||
client_max_body_size 8m;
|
||||
|
||||
location / {
|
||||
set $backend http://app:3000;
|
||||
proxy_pass $backend;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Connection "";
|
||||
proxy_connect_timeout 10s;
|
||||
proxy_read_timeout 30s;
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
+7386
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "a-mesa",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"start": "node server/server.mjs",
|
||||
"build": "ng build",
|
||||
"dev": "ng serve --host 0.0.0.0 --proxy-config proxy.conf.json",
|
||||
"test": "node --test server/*.test.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@angular/common": "^20.0.0",
|
||||
"@angular/compiler": "^20.0.0",
|
||||
"@angular/core": "^20.0.0",
|
||||
"@angular/forms": "^20.0.0",
|
||||
"@angular/platform-browser": "^20.0.0",
|
||||
"rxjs": "~7.8.2",
|
||||
"tslib": "^2.8.1",
|
||||
"zone.js": "~0.15.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@angular/build": "^20.0.0",
|
||||
"@angular/cli": "^20.0.0",
|
||||
"typescript": "~5.8.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=24.0.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"/api/**":{"target":"http://127.0.0.1:3000","secure":false}}
|
||||
@@ -0,0 +1,47 @@
|
||||
import {test} from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {DatabaseSync} from 'node:sqlite';
|
||||
import {mkdtempSync,rmSync} from 'node:fs';
|
||||
import {tmpdir} from 'node:os';
|
||||
import {join} from 'node:path';
|
||||
import {createApp} from './server.mjs';
|
||||
import {applyShoppingOverrides} from '../src/shopping.ts';
|
||||
|
||||
test('upgrade old database preserves recipes and plans, edits and weekly products survive restart',async()=>{
|
||||
const dir=mkdtempSync(join(tmpdir(),'amesa-upgrade-'));
|
||||
const old=new DatabaseSync(join(dir,'amesa.sqlite'));
|
||||
old.exec(`CREATE TABLE recipes(id TEXT PRIMARY KEY,name TEXT NOT NULL,image TEXT NOT NULL,ingredients TEXT NOT NULL,preparation TEXT NOT NULL);
|
||||
CREATE TABLE entries(id TEXT PRIMARY KEY,slot TEXT NOT NULL,recipeId TEXT NOT NULL REFERENCES recipes(id));
|
||||
CREATE TABLE metadata(key TEXT PRIMARY KEY,value TEXT NOT NULL);INSERT INTO metadata VALUES('seeded','1');`);
|
||||
const r={id:'mine',name:'Receita guardada',image:'https://example.com/image.jpg',ingredients:'100 g de arroz',preparation:'Cozer.'};
|
||||
old.prepare('INSERT INTO recipes VALUES(?,?,?,?,?)').run(...Object.values(r));
|
||||
old.prepare('INSERT INTO entries VALUES(?,?,?)').run('planned','2026-9-7:1','mine');old.close();
|
||||
let app,url;
|
||||
const start=async()=>{app=createApp({dataDir:dir});await new Promise(r=>app.listen(0,'127.0.0.1',r));url=`http://127.0.0.1:${app.address().port}/api/`;};
|
||||
const stop=()=>new Promise(r=>app.close(r));
|
||||
const call=async(path,method='GET',data)=>{const response=await fetch(url+path,{method,headers:{'Content-Type':'application/json'},body:data?JSON.stringify(data):undefined});return {status:response.status,data:await response.json()};};
|
||||
try{
|
||||
await start();let state=(await call('state')).data;
|
||||
assert.deepEqual(state.recipes,[r]);assert.equal(state.entries[0].recipeId,'mine');
|
||||
const changed={...r,name:'Receita editada',ingredients:'200 g de arroz'};
|
||||
assert.equal((await call('recipes/mine','PUT',{...changed,previous:r})).status,200);
|
||||
assert.equal((await call('recipes/mine','PUT',{...r,previous:r})).status,409);
|
||||
assert.equal((await call('recipes/mine','PUT',{...changed,name:'',previous:changed})).status,400);
|
||||
const product={week:'2026-9-7',key:'arroz|g',name:'arroz',quantity:300,unit:'g',removed:false};
|
||||
const manual={...product,key:'manual:milk',name:'leite',unit:'l',quantity:2};
|
||||
assert.equal((await call('shopping','PUT',product)).status,200);
|
||||
assert.equal((await call('shopping','PUT',manual)).status,200);
|
||||
assert.equal((await call('shopping','PUT',{...product,quantity:-2})).status,400);
|
||||
assert.equal((await call('shopping','PUT',{...product,week:'2026-9-8'})).status,400);
|
||||
await call('shopping','PUT',{...product,week:'2026-9-14',removed:true});
|
||||
await stop();await start();state=(await call('state')).data;
|
||||
assert.deepEqual(state.recipes,[changed]);assert.equal(state.entries.length,1);assert.equal(state.shoppingOverrides.length,3);
|
||||
const base=[{key:'arroz|g',name:'arroz',unit:'g',quantity:200,occurrences:1,recipes:['Receita editada']}];
|
||||
const rows=applyShoppingOverrides(base,state.shoppingOverrides,'2026-9-7');
|
||||
assert.equal(rows.find(r=>r.name==='arroz').quantity,300);assert.equal(rows.find(r=>r.name==='leite').quantity,2);
|
||||
assert.deepEqual(applyShoppingOverrides(base,state.shoppingOverrides,'2026-9-14'),[]);
|
||||
assert.equal((await call('shopping','DELETE',product)).status,200);
|
||||
state=(await call('state')).data;
|
||||
assert.equal(applyShoppingOverrides(base,state.shoppingOverrides,'2026-9-7').find(r=>r.name==='arroz').quantity,200);
|
||||
}finally{if(app?.listening)await stop();rmSync(dir,{recursive:true,force:true});}
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
[
|
||||
{
|
||||
"id": "1",
|
||||
"name": "Tosta de abacate e ovo",
|
||||
"image": "https://images.unsplash.com/photo-1525351484163-7529414344d8?auto=format&fit=crop&w=600&q=80",
|
||||
"ingredients": "1 fatia de pão\n½ abacate\n1 ovo\nSal e pimenta",
|
||||
"preparation": "Torre o pão. Esmague o abacate e tempere. Cozinhe o ovo numa frigideira e coloque sobre a tosta com o abacate."
|
||||
},
|
||||
{
|
||||
"id": "2",
|
||||
"name": "Bowl de iogurte e frutos",
|
||||
"image": "https://images.unsplash.com/photo-1511690743698-d9d85f2fbf38?auto=format&fit=crop&w=600&q=80",
|
||||
"ingredients": "150 g de iogurte natural\n3 colheres de granola\nFrutos vermelhos\n1 colher de mel",
|
||||
"preparation": "Coloque o iogurte numa taça. Acrescente a granola e os frutos lavados. Finalize com um fio de mel."
|
||||
},
|
||||
{
|
||||
"id": "3",
|
||||
"name": "Salada mediterrânica",
|
||||
"image": "https://images.unsplash.com/photo-1512621776951-a57141f2eefd?auto=format&fit=crop&w=600&q=80",
|
||||
"ingredients": "Alface\nTomate cherry\nPepino\nQueijo feta\nAzeite e limão",
|
||||
"preparation": "Lave e corte os vegetais. Misture numa taça com o queijo. Tempere com azeite e sumo de limão antes de servir."
|
||||
},
|
||||
{
|
||||
"id": "4",
|
||||
"name": "Salmão com legumes",
|
||||
"image": "https://images.unsplash.com/photo-1467003909585-2f8a72700288?auto=format&fit=crop&w=600&q=80",
|
||||
"ingredients": "1 lombo de salmão\nBrócolos\nCenoura\nAzeite\nLimão e sal",
|
||||
"preparation": "Aqueça o forno a 200 °C. Coloque o salmão e os legumes num tabuleiro, tempere e regue com azeite. Asse durante cerca de 20 minutos, até estar cozinhado."
|
||||
},
|
||||
{
|
||||
"id": "5",
|
||||
"name": "Massa com tomate e manjericão",
|
||||
"image": "https://images.unsplash.com/photo-1473093295043-cdd812d0e601?auto=format&fit=crop&w=600&q=80",
|
||||
"ingredients": "100 g de massa\n150 g de tomate\n1 dente de alho\nManjericão\nAzeite",
|
||||
"preparation": "Coza a massa. Salteie o alho e o tomate em azeite. Envolva a massa no molho e termine com manjericão fresco."
|
||||
},
|
||||
{
|
||||
"id": "6",
|
||||
"name": "Panquecas de banana",
|
||||
"image": "https://images.unsplash.com/photo-1528207776546-365bb710ee93?auto=format&fit=crop&w=600&q=80",
|
||||
"ingredients": "1 banana\n1 ovo\n3 colheres de aveia\nCanela",
|
||||
"preparation": "Esmague a banana e misture com o ovo, a aveia e a canela. Cozinhe pequenas porções numa frigideira antiaderente, dos dois lados."
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,133 @@
|
||||
import http from 'node:http';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import { mkdirSync, readFileSync, existsSync, statSync } from 'node:fs';
|
||||
import { resolve, extname, sep } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const fail = (status, message) => Object.assign(new Error(message), { status });
|
||||
export function createApp({ dataDir = process.env.DATA_DIR || './data', staticDir = './dist/a-mesa/browser' } = {}) {
|
||||
mkdirSync(dataDir, { recursive: true });
|
||||
const db = new DatabaseSync(resolve(dataDir, 'amesa.sqlite'));
|
||||
db.exec(`PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;
|
||||
CREATE TABLE IF NOT EXISTS recipes (id TEXT PRIMARY KEY, name TEXT NOT NULL, image TEXT NOT NULL, ingredients TEXT NOT NULL, preparation TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS entries (id TEXT PRIMARY KEY, slot TEXT NOT NULL, recipeId TEXT NOT NULL REFERENCES recipes(id));
|
||||
CREATE INDEX IF NOT EXISTS entries_slot ON entries(slot);
|
||||
CREATE TABLE IF NOT EXISTS shopping_overrides (week TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL, PRIMARY KEY(week, key));
|
||||
CREATE TABLE IF NOT EXISTS metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL);`);
|
||||
const insert = db.prepare('INSERT INTO recipes VALUES (?, ?, ?, ?, ?)');
|
||||
if (!db.prepare("SELECT value FROM metadata WHERE key='seeded'").get()) {
|
||||
const seed = JSON.parse(readFileSync(new URL('./seed.json', import.meta.url), 'utf8'));
|
||||
db.exec('BEGIN');
|
||||
try {
|
||||
for (const r of seed) insert.run(r.id, r.name, r.image, r.ingredients, r.preparation);
|
||||
db.prepare('INSERT INTO metadata VALUES (?, ?)').run('seeded', '1');
|
||||
db.exec('COMMIT');
|
||||
} catch (error) { db.exec('ROLLBACK'); throw error; }
|
||||
}
|
||||
function state() {
|
||||
return { recipes: db.prepare('SELECT * FROM recipes ORDER BY rowid').all(), entries: db.prepare('SELECT * FROM entries ORDER BY rowid').all(), shoppingOverrides: db.prepare('SELECT * FROM shopping_overrides').all().map(r => ({week:r.week,key:r.key,...JSON.parse(r.value)})) };
|
||||
}
|
||||
function recipe(input) {
|
||||
if (!input || typeof input !== 'object') throw fail(400, 'Receita inválida.');
|
||||
const result = {};
|
||||
for (const [key, max] of Object.entries({ id: 100, name: 100, image: 2900000, ingredients: 20000, preparation: 30000 })) {
|
||||
if (typeof input[key] !== 'string' || !input[key].trim() || input[key].length > max) throw fail(400, `Campo inválido: ${key}.`);
|
||||
result[key] = input[key].trim();
|
||||
}
|
||||
if (!/^[a-zA-Z0-9-]+$/.test(result.id)) throw fail(400, 'Identificador inválido.');
|
||||
const data = result.image.match(/^data:image\/(png|jpeg|gif|webp);base64,([A-Za-z0-9+/]+={0,2})$/);
|
||||
if (data) {
|
||||
if (Buffer.from(data[2], 'base64').length > 2 * 1024 * 1024) throw fail(413, 'A imagem deve ter menos de 2 MB.');
|
||||
} else {
|
||||
let url; try { url = new URL(result.image); } catch { throw fail(400, 'Imagem inválida.'); }
|
||||
if (!['http:', 'https:'].includes(url.protocol) || result.image.length > 4096) throw fail(400, 'Utilize uma imagem PNG, JPEG, GIF, WebP ou um URL HTTP/HTTPS.');
|
||||
}
|
||||
return result;
|
||||
}
|
||||
async function body(req) {
|
||||
if (!req.headers['content-type']?.startsWith('application/json')) throw fail(415, 'Envie dados JSON.');
|
||||
const chunks = []; let size = 0;
|
||||
const limit = req.method === 'PUT' && req.url?.startsWith('/api/recipes/') ? 6000000 : 3000000;
|
||||
for await (const chunk of req) { size += chunk.length; if (size > limit) throw fail(413, 'Pedido demasiado grande.'); chunks.push(chunk); }
|
||||
try { return JSON.parse(Buffer.concat(chunks).toString()); } catch { throw fail(400, 'JSON inválido.'); }
|
||||
}
|
||||
function json(res, status, value) { res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' }); res.end(JSON.stringify(value)); }
|
||||
const root = resolve(staticDir);
|
||||
const server = http.createServer(async (req, res) => {
|
||||
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||
try {
|
||||
const path = new URL(req.url, 'http://localhost').pathname;
|
||||
if (path === '/api/health' && req.method === 'GET') return json(res, 200, { ok: true });
|
||||
if (path === '/api/state' && req.method === 'GET') return json(res, 200, state());
|
||||
if (path.startsWith('/api/recipes/') && req.method === 'PUT') {
|
||||
const input = await body(req), r = recipe(input), previous = recipe(input.previous);
|
||||
if (r.id !== decodeURIComponent(path.slice('/api/recipes/'.length)) || previous.id !== r.id) throw fail(400, 'Identificador inválido.');
|
||||
const result = db.prepare('UPDATE recipes SET name=?, image=?, ingredients=?, preparation=? WHERE id=? AND name=? AND image=? AND ingredients=? AND preparation=?').run(r.name,r.image,r.ingredients,r.preparation,r.id,previous.name,previous.image,previous.ingredients,previous.preparation);
|
||||
if (!result.changes) throw fail(409, 'Esta receita foi alterada entretanto. Feche e volte a abrir a receita para editar a versão atual.');
|
||||
return json(res, 200, r);
|
||||
}
|
||||
if (path === '/api/shopping' && ['PUT','DELETE'].includes(req.method)) {
|
||||
const input = await body(req);
|
||||
if (!input || typeof input.week !== 'string' || !/^\d{4}-\d{1,2}-\d{1,2}$/.test(input.week) || typeof input.key !== 'string' || !input.key.trim() || input.key.length > 21000) throw fail(400,'Lista inválida.');
|
||||
const [y,m,d] = input.week.split('-').map(Number), date = new Date(Date.UTC(y,m-1,d));
|
||||
if (date.getUTCFullYear()!==y || date.getUTCMonth()!==m-1 || date.getUTCDate()!==d || date.getUTCDay()!==1) throw fail(400,'Semana inválida.');
|
||||
if (req.method === 'DELETE') {
|
||||
db.prepare('DELETE FROM shopping_overrides WHERE week=? AND key=?').run(input.week,input.key);
|
||||
} else {
|
||||
if(typeof input.name!=='string'||!input.name.trim()||input.name.length>20000||typeof input.unit!=='string'||input.unit.length>100||typeof input.removed!=='boolean'||(input.quantity!==null&&(typeof input.quantity!=='number'||!Number.isFinite(input.quantity)||input.quantity<0||input.quantity>1e9))) throw fail(400,'Produto ou quantidade inválidos.');
|
||||
const value=JSON.stringify({name:input.name.trim(),unit:input.unit.trim(),quantity:input.quantity,removed:input.removed});
|
||||
db.prepare('INSERT INTO shopping_overrides VALUES (?,?,?) ON CONFLICT(week,key) DO UPDATE SET value=excluded.value').run(input.week,input.key,value);
|
||||
}
|
||||
return json(res,200,{ok:true});
|
||||
}
|
||||
if (path === '/api/recipes' && req.method === 'POST') {
|
||||
const r = recipe(await body(req));
|
||||
const existing = db.prepare('SELECT * FROM recipes WHERE id=?').get(r.id);
|
||||
if (existing) {
|
||||
if (Object.keys(r).some(key => r[key] !== existing[key])) throw fail(409, 'Já existe uma receita diferente com este identificador.');
|
||||
return json(res, 200, existing);
|
||||
}
|
||||
insert.run(r.id, r.name, r.image, r.ingredients, r.preparation);
|
||||
return json(res, 201, r);
|
||||
}
|
||||
if (path === '/api/entries' && req.method === 'POST') {
|
||||
const data = await body(req);
|
||||
if (!data || typeof data.slot !== 'string' || !/^\d{4}-\d{1,2}-\d{1,2}:[012]$/.test(data.slot)) throw fail(400, 'Dia ou refeição inválidos.');
|
||||
const [year, month, day] = data.slot.split(':')[0].split('-').map(Number);
|
||||
const date = new Date(Date.UTC(year, month - 1, day));
|
||||
if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) throw fail(400, 'Data inválida.');
|
||||
if (typeof data.recipeId !== 'string' || !db.prepare('SELECT id FROM recipes WHERE id=?').get(data.recipeId)) throw fail(404, 'Receita não encontrada.');
|
||||
if (typeof data.id !== 'string' || !/^[a-zA-Z0-9-]{1,100}$/.test(data.id)) throw fail(400, 'Identificador inválido.');
|
||||
const existing = db.prepare('SELECT * FROM entries WHERE id=?').get(data.id);
|
||||
if (existing && (existing.slot !== data.slot || existing.recipeId !== data.recipeId)) throw fail(409, 'Identificador já utilizado.');
|
||||
if (!existing) db.prepare('INSERT INTO entries VALUES (?, ?, ?)').run(data.id, data.slot, data.recipeId);
|
||||
return json(res, existing ? 200 : 201, { id: data.id, slot: data.slot, recipeId: data.recipeId });
|
||||
}
|
||||
if (path.startsWith('/api/entries/') && req.method === 'DELETE') {
|
||||
db.prepare('DELETE FROM entries WHERE id=?').run(decodeURIComponent(path.slice('/api/entries/'.length)));
|
||||
return json(res, 200, { ok: true });
|
||||
}
|
||||
if (path.startsWith('/api/')) throw fail(404, 'Operação não encontrada.');
|
||||
if (!['GET', 'HEAD'].includes(req.method)) throw fail(405, 'Método não permitido.');
|
||||
let file = resolve(root, '.' + decodeURIComponent(path));
|
||||
if (file !== root && !file.startsWith(root + sep)) throw fail(403, 'Caminho inválido.');
|
||||
if (!existsSync(file) || statSync(file).isDirectory()) file = resolve(root, 'index.html');
|
||||
if (!existsSync(file)) throw fail(404, 'Compile a aplicação com npm run build.');
|
||||
const types = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.woff2': 'font/woff2' };
|
||||
res.writeHead(200, { 'Content-Type': types[extname(file)] || 'application/octet-stream', 'Cache-Control': 'no-cache' });
|
||||
res.end(req.method === 'HEAD' ? undefined : readFileSync(file));
|
||||
} catch (error) {
|
||||
if (!error.status) console.error(error);
|
||||
if (!res.headersSent) json(res, error.status || 500, { error: error.status ? error.message : 'Não foi possível guardar os dados. Tente novamente.' });
|
||||
else res.end();
|
||||
}
|
||||
});
|
||||
server.on('close', () => db.close());
|
||||
return server;
|
||||
}
|
||||
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
const server = createApp();
|
||||
const port = Number(process.env.PORT || 3000);
|
||||
server.listen(port, '0.0.0.0', () => console.log(`À Mesa disponível na porta ${port}`));
|
||||
for (const signal of ['SIGTERM', 'SIGINT']) process.on(signal, () => server.close());
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtempSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { createApp } from './server.mjs';
|
||||
|
||||
test('shared concurrent writes, validation and persistence after restart', async () => {
|
||||
const dataDir=mkdtempSync(join(tmpdir(),'amesa-test-'));let server;
|
||||
async function start(){server=createApp({dataDir});await new Promise(r=>server.listen(0,'127.0.0.1',r));return `http://127.0.0.1:${server.address().port}`;}
|
||||
async function stop(){await new Promise(r=>server.close(r));}
|
||||
try{
|
||||
let url=await start();
|
||||
const call=async(path,method='GET',body)=>{const r=await fetch(url+'/api/'+path,{method,headers:{'Content-Type':'application/json'},body:body?JSON.stringify(body):undefined});return {status:r.status,data:await r.json()};};
|
||||
const image='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=';
|
||||
const a={id:'device-a',name:'Sopa da Ana',image,ingredients:'Cenoura\nÁgua',preparation:'Cozer e triturar.'},b={...a,id:'device-b',name:'Sopa do João'};
|
||||
assert.deepEqual((await Promise.all([call('recipes','POST',a),call('recipes','POST',b)])).map(r=>r.status),[201,201]);
|
||||
let shared=(await call('state')).data;
|
||||
assert.ok(shared.recipes.some(r=>r.id===a.id));assert.ok(shared.recipes.some(r=>r.id===b.id));
|
||||
assert.equal(shared.recipes.find(r=>r.id===a.id).image,image);
|
||||
assert.equal((await call('recipes','POST',a)).status,200);
|
||||
assert.equal((await call('recipes','POST',{...a,name:'Overwrite'})).status,409);
|
||||
const slot='2026-9-7:1';
|
||||
await Promise.all([call('entries','POST',{id:'entry-a',slot,recipeId:a.id}),call('entries','POST',{id:'entry-b',slot,recipeId:b.id})]);
|
||||
assert.equal((await call('state')).data.entries.length,2);
|
||||
await call('entries','POST',{id:'entry-a',slot,recipeId:a.id});assert.equal((await call('state')).data.entries.length,2);
|
||||
await call('entries/entry-a','DELETE');shared=(await call('state')).data;assert.deepEqual(shared.entries.map(e=>e.id),['entry-b']);
|
||||
assert.equal((await call('recipes','POST',{...a,id:'bad',image:'javascript:alert(1)'})).status,400);
|
||||
assert.equal((await call('entries','POST',{id:'bad',slot:'2026-2-30:1',recipeId:a.id})).status,400);
|
||||
assert.equal((await call('entries','POST',{id:'bad',slot,recipeId:'missing'})).status,404);
|
||||
assert.equal((await call('recipes','POST',{...a,id:'bad',name:''})).status,400);
|
||||
assert.equal((await call('recipes','POST',{...a,id:'big',image:'data:image/png;base64,'+Buffer.alloc(2*1024*1024+1).toString('base64')})).status,413);
|
||||
await stop();url=await start();assert.deepEqual((await call('state')).data,shared);
|
||||
const page=await fetch(url);assert.equal(page.status,200);assert.match(await page.text(),/<app-root>/);
|
||||
}finally{if(server?.listening)await stop();rmSync(dataDir,{recursive:true,force:true});}
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { shoppingList, quantityLabel } from '../src/shopping.ts';
|
||||
test('weekly totals include repeated recipes and compatible quantities only',()=>{
|
||||
const recipes=[{id:'a',name:'A',ingredients:'150 g de arroz\n1 ovo\n½ abacate\nSal\n1 colher de sopa de azeite'},{id:'b',name:'B',ingredients:'0,5 kg de arroz\n2 ovos\n1/2 abacate\nSal\n20 ml de azeite'}];
|
||||
const entries=[{slot:'week',recipeId:'a'},{slot:'week',recipeId:'a'},{slot:'week',recipeId:'b'},{slot:'other',recipeId:'b'}];
|
||||
const rows=shoppingList(recipes,entries,['week']);
|
||||
assert.equal(rows.find(r=>r.name==='arroz').quantity,800);
|
||||
assert.equal(rows.find(r=>r.name==='ovo').quantity,4);
|
||||
assert.equal(rows.find(r=>r.name==='abacate').quantity,1.5);
|
||||
assert.equal(rows.find(r=>r.name==='Sal').quantity,null);
|
||||
assert.equal(rows.find(r=>r.name==='Sal').occurrences,3);
|
||||
assert.equal(rows.filter(r=>r.name==='azeite').length,2);
|
||||
assert.deepEqual(shoppingList(recipes,entries,['empty']),[]);
|
||||
});
|
||||
test('fractions, unit conversions, ambiguous quantities and line breaks',()=>{
|
||||
const rows=shoppingList([{id:'r',name:'Receita',ingredients:'1½ l de água\r\n250ml de água\n1 1/2 kg de farinha\n500 g de farinha\n1 a 2 ovos\n1/0 ovos\n\n- 2 bananas'}],[{slot:'s',recipeId:'r'}],['s']);
|
||||
assert.equal(rows.find(r=>r.name==='água').quantity,1750);
|
||||
assert.equal(quantityLabel(rows.find(r=>r.name==='farinha')),'2 kg');
|
||||
assert.equal(rows.find(r=>r.name==='1 a 2 ovos').quantity,null);
|
||||
assert.equal(rows.find(r=>r.name==='1/0 ovos').quantity,null);
|
||||
assert.equal(rows.find(r=>r.name==='banana').quantity,2);
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
<!doctype html><html lang="pt"><head><meta charset="utf-8"><title>À Mesa — A sua semana, bem servida</title><base href="/"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="theme-color" content="#314d3e"></head><body><app-root></app-root></body></html>
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
import { Component, HostListener } from '@angular/core';
|
||||
import { bootstrapApplication } from '@angular/platform-browser';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { shoppingList, quantityLabel, applyShoppingOverrides, ShoppingOverride, ShoppingRow } from './shopping';
|
||||
|
||||
interface Recipe { id: string; name: string; image: string; ingredients: string; preparation: string; }
|
||||
interface Entry { id: string; slot: string; recipeId: string; }
|
||||
@Component({selector:'app-root',standalone:true,imports:[FormsModule],template:`
|
||||
<header class="topbar"><a class="brand" href="./"><span class="brand-icon">♧</span> à mesa<span class="brand-dot">.</span></a><nav><button [class.active]="view === 'planner'" (click)="view='planner'">▦ <span>Plano semanal</span></button><button [class.active]="view === 'recipes'" (click)="view='recipes'">▤ <span>Receitas partilhadas</span><small>{{recipes.length}}</small></button><button [class.active]="view === 'shopping'" (click)="view='shopping'">☷ <span>Lista de compras</span></button></nav><div class="profile"><span>O nosso espaço</span><b>M</b></div></header>
|
||||
<main>@if(!connected&&!loading){<div class="connection-banner" role="alert">Não foi possível contactar o servidor. <button (click)="refresh()">Tentar novamente</button></div>}@if(legacy.length){<div class="connection-banner">Tem receitas guardadas neste navegador. <button [disabled]="busy||!connected" (click)="importLegacy()">Importar para a coleção partilhada</button></div>}<section class="intro"><div><div class="eyebrow">MENOS INDECISÃO, MAIS SABOR</div><h1>{{view === 'planner' ? 'A sua semana, bem servida.' : view === 'shopping' ? 'Tudo o que precisa para a semana.' : 'As suas receitas favoritas.'}}</h1><p>{{view === 'planner' ? 'Um pouco de organização. Mais tempo para saborear.' : view === 'shopping' ? 'Os ingredientes da sua ementa, reunidos numa só lista.' : 'Os pratos de sempre e as próximas descobertas, num só lugar.'}}</p></div><button class="primary" (click)="newRecipe()"><span>+</span> Nova receita</button></section>
|
||||
@if (view === 'planner') {
|
||||
<section class="planner"><div class="planner-toolbar"><div class="week-navigation"><button aria-label="Semana anterior" (click)="changeWeek(-1)">‹</button><h2>{{weekLabel}}</h2><button aria-label="Semana seguinte" (click)="changeWeek(1)">›</button><button class="today" (click)="offset=0">Esta semana</button></div><div class="planned"><span></span>{{count}} refeições planeadas</div></div>
|
||||
<div class="calendar-scroll"><div class="calendar"><div class="corner">A SUA EMENTA</div>@for(day of days; track $index; let d=$index){<div class="day" [class.current]="isToday(d)"><span>{{day}}</span><b>{{dateFor(d).getDate()}}</b>@if(isToday(d)){<i>HOJE</i>}</div>}
|
||||
@for(meal of meals;track $index;let m=$index){<div class="meal-label"><span>{{meal.icon}}</span><strong>{{meal.name}}</strong><small>{{meal.caption}}</small></div>@for(day of days;track $index;let d=$index){<div class="meal-cell" [class.weekend]="d > 4">@for(recipe of slotRecipes(d,m);track $index;let r=$index){<article class="meal-card"><button class="meal-open" (click)="detail=recipe"><img [src]="recipe.image" [alt]="recipe.name" (error)="imageError($event)"><strong>{{recipe.name}}</strong></button><button class="remove" aria-label="Remover do plano" (click)="remove(d,m,r)">×</button></article>}<button class="add-slot" [class.empty]="slotRecipes(d,m).length === 0" (click)="openPicker(d,m)"><span>+</span><span>Adicionar</span></button></div>}}
|
||||
</div></div><div class="planner-footer"><span>✧ Uma semana organizada começa com uma boa refeição.</span><span>{{loading ? 'A carregar…' : connected ? 'Partilhado · atualização automática' : 'Sem ligação ao servidor'}} <span class="save-dot">●</span></span></div></section>
|
||||
<section class="collection-heading"><div><div class="eyebrow">UM POUCO DE INSPIRAÇÃO</div><h2>O que vamos cozinhar?</h2><p>As suas receitas, sempre à mão.</p></div><button class="text-button" (click)="view='recipes'">Ver todas as receitas <span>↗</span></button></section>
|
||||
} @else if (view === 'recipes') {<div class="library-toolbar"><span>{{recipes.length}} receitas na sua coleção</span><input class="search" placeholder="Pesquisar receitas…" [(ngModel)]="search"></div>}
|
||||
@if(view === 'shopping') {
|
||||
<section class="planner shopping-panel"><div class="planner-toolbar"><div class="week-navigation"><button aria-label="Semana anterior" (click)="changeWeek(-1)">‹</button><h2>{{weekLabel}}</h2><button aria-label="Semana seguinte" (click)="changeWeek(1)">›</button><button class="today" (click)="offset=0">Esta semana</button></div><div class="planned">{{count}} refeições planeadas · {{shopping.length}} ingredientes</div></div>
|
||||
<p class="shopping-note">Cada prato no plano conta uma vez com as quantidades da receita. Somamos unidades compatíveis; ingredientes sem quantidade ficam assinalados para confirmar. As alterações manuais ficam guardadas apenas nesta semana e substituem os totais automáticos dos produtos editados.</p><div class="shopping-actions"><button class="primary" [disabled]="busy||!connected" (click)="editProduct()">+ Adicionar produto</button></div>
|
||||
@if(loading){<p class="empty-message">A carregar os ingredientes…</p>} @else if(shopping.length){
|
||||
<div class="shopping-scroll"><table class="shopping-table"><thead><tr><th>Ingrediente</th><th>Total da semana</th><th>Utilização nas receitas</th><th>Ações</th></tr></thead><tbody>@for(item of shopping;track item.key){<tr><td><strong>{{item.name}}</strong></td><td><span [class.unspecified]="item.quantity === null">{{formatQuantity(item)}}</span></td><td>{{item.occurrences ? item.occurrences + ' ×' : 'Adicionado à lista'}} <small>{{item.recipes.join(' · ')}}</small></td><td><button class="text-button" [disabled]="busy" (click)="editProduct(item)">Editar</button><button class="text-button" [disabled]="busy" (click)="removeProduct(item)">Remover</button></td></tr>}</tbody></table></div>
|
||||
} @else {<div class="empty-message"><p>Ainda não há ingredientes para esta semana.</p><button class="primary" (click)="view='planner'">Planear refeições</button></div>}
|
||||
<details class="shopping-adjustments"><summary>Ajustes desta semana ({{weekChanges.length}})</summary>@for(change of weekChanges;track change.key){<div><span>{{change.name}} — {{change.removed ? 'removido' : 'ajustado / adicionado'}}</span><button class="text-button" [disabled]="busy" (click)="restoreProduct(change)">{{change.key.startsWith('manual:') ? 'Descartar ajuste' : 'Repor cálculo automático'}}</button></div>}<p>Repor um produto volta a usar os ingredientes do plano atual. Os restantes ajustes são mantidos.</p></details></section>
|
||||
} @else {
|
||||
<section class="recipe-grid">@for(recipe of visibleRecipes;track recipe.id){<button class="recipe-card" (click)="detail=recipe"><div class="recipe-image"><img [src]="recipe.image" [alt]="recipe.name" (error)="imageError($event)"><span>↗</span></div><div class="recipe-text"><small>FEITO EM CASA</small><h3>{{recipe.name}}</h3><span>Ver ingredientes e preparação <b>→</b></span></div></button>}@empty{<p class="empty-message">Não foram encontradas receitas. Experimente outro nome ou crie uma nova.</p>}</section>}
|
||||
<footer class="page-footer"><span class="footer-brand">à mesa.</span><span>Planeie com calma. Cozinhe com gosto.</span><span>Feito para o seu dia a dia ♡</span></footer></main>
|
||||
@if(picker){<div class="overlay" (click)="picker=null"><section class="modal" role="dialog" aria-modal="true" aria-label="Adicionar refeição" (click)="$event.stopPropagation()"><button class="close" aria-label="Fechar" (click)="picker=null">×</button><div class="eyebrow">COMPOR A EMENTA</div><h2>O que lhe apetece?</h2><p>{{days[picker.day]}} · {{meals[picker.meal].name}}</p><input class="search" autofocus placeholder="Pesquisar uma receita…" [(ngModel)]="pickerSearch"><div class="picker-list">@for(recipe of pickerRecipes;track recipe.id){<button (click)="add(recipe)"><img [src]="recipe.image" [alt]="recipe.name" (error)="imageError($event)"><strong>{{recipe.name}}</strong><span>+</span></button>}@empty{<p>Nenhuma receita encontrada.</p>}</div><button class="primary full" (click)="newRecipe()">+ Criar uma nova receita</button></section></div>}
|
||||
@if(editing){<div class="overlay" (click)="editing=null"><section class="modal" role="dialog" aria-modal="true" [attr.aria-label]="originalRecipe ? 'Editar receita' : 'Nova receita'" (click)="$event.stopPropagation()"><button class="close" aria-label="Fechar" (click)="editing=null">×</button><div class="eyebrow">DA SUA COZINHA PARA A COLEÇÃO</div><h2>{{originalRecipe ? 'Editar receita' : 'Nova receita'}}</h2><form (ngSubmit)="saveRecipe()"><label>Nome da receita<input name="name" required maxlength="100" [(ngModel)]="editing.name" placeholder="Ex.: Sopa de legumes"></label><label>Imagem da refeição<input type="file" accept="image/png,image/jpeg,image/webp,image/gif" (change)="upload($event)"></label><label class="url-label">Ou utilize um endereço de imagem<input name="image" type="text" [(ngModel)]="editing.image" placeholder="https://…"></label>@if(editing.image){<img class="preview" [src]="editing.image" alt="Pré-visualização" (error)="imageError($event)">}<label>Ingredientes<textarea name="ingredients" required rows="4" [(ngModel)]="editing.ingredients" placeholder="Um ingrediente por linha: 200 g de arroz, 2 ovos…"></textarea></label><label>Modo de preparação<textarea name="preparation" required rows="4" [(ngModel)]="editing.preparation" placeholder="Explique como preparar a refeição…"></textarea></label>@if(formError){<p class="error">{{formError}}</p>}<button class="primary full" type="submit" [disabled]="busy">{{busy ? 'A guardar…' : 'Guardar receita'}}</button></form></section></div>}
|
||||
@if(detail){<div class="overlay" (click)="detail=null"><section class="modal detail" role="dialog" aria-modal="true" [attr.aria-label]="detail.name" (click)="$event.stopPropagation()"><button class="close" aria-label="Fechar" (click)="detail=null">×</button><img class="detail-image" [src]="detail.image" [alt]="detail.name" (error)="imageError($event)"><div class="detail-body"><div class="eyebrow">FEITO EM CASA</div><h2>{{detail.name}}</h2><button class="primary" [disabled]="busy" (click)="editRecipe(detail)">Editar receita</button><h3>Ingredientes</h3><ul>@for(ingredient of detail.ingredients.split('\\n');track $index){<li>{{ingredient}}</li>}</ul><h3>Modo de preparação</h3><p class="preparation">{{detail.preparation}}</p></div></section></div>}
|
||||
@if(product){<div class="overlay" (click)="product=null"><section class="modal" role="dialog" aria-modal="true" aria-label="Produto da lista de compras" (click)="$event.stopPropagation()"><button class="close" aria-label="Fechar" (click)="product=null">×</button><h2>Produto da lista de compras</h2><form (ngSubmit)="saveProduct()"><label>Produto<input name="productName" required maxlength="20000" [(ngModel)]="product.name"></label><label>Quantidade<input name="quantity" type="number" min="0" max="1000000000" step="any" [(ngModel)]="product.quantity" placeholder="Sem quantidade definida"></label><label>Unidade<input name="unit" maxlength="100" [(ngModel)]="product.unit" placeholder="Ex.: g, kg, l, un."></label><p>Este ajuste aplica-se apenas à semana selecionada ao abrir o formulário.</p>@if(productError){<p class="error">{{productError}}</p>}<button type="submit" class="primary full" [disabled]="busy">{{busy ? 'A guardar…' : 'Guardar produto'}}</button></form></section></div>}
|
||||
@if(notice){<div class="toast" role="status">{{notice}}</div>}
|
||||
`})
|
||||
class App {
|
||||
originalRecipe:Recipe|null=null; shoppingOverrides:ShoppingOverride[]=[]; product:ShoppingOverride|null=null; productError='';
|
||||
recipes:Recipe[]=[]; entries:Entry[]=[]; busy=false; connected=false; loading=true; private refreshing=false; private revision=0; private timer:ReturnType<typeof setInterval>; legacy:Recipe[]=[]; view='planner'; offset=0; search=''; pickerSearch=''; picker:{day:number;meal:number}|null=null; editing:Recipe|null=null; detail:Recipe|null=null; notice=''; formError='';
|
||||
days=['SEGUNDA','TERÇA','QUARTA','QUINTA','SEXTA','SÁBADO','DOMINGO']; meals=[{name:'Pequeno-almoço',icon:'☀',caption:'Começar bem o dia'},{name:'Almoço',icon:'◒',caption:'Uma pausa com sabor'},{name:'Jantar',icon:'☾',caption:'Terminar em beleza'}];
|
||||
constructor(){
|
||||
try { const saved=JSON.parse(localStorage.getItem('amesa-v1')||'null'); if(Array.isArray(saved?.recipes)) this.legacy=saved.recipes; } catch {}
|
||||
void this.refresh(); this.timer=setInterval(()=>void this.refresh(),5000);
|
||||
}
|
||||
ngOnDestroy(){clearInterval(this.timer);}
|
||||
private id(){return globalThis.crypto?.randomUUID?.() || 'r-'+Date.now().toString(36)+'-'+Math.random().toString(36).slice(2);}
|
||||
private async request(path:string,method='GET',data?:unknown){
|
||||
const response=await fetch('/api/'+path,{method,headers:data?{'Content-Type':'application/json'}:{},body:data?JSON.stringify(data):undefined,signal:AbortSignal.timeout(15000)});
|
||||
const result=await response.json(); if(!response.ok)throw new Error(result.error||'Erro ao comunicar com o servidor.'); return result;
|
||||
}
|
||||
async refresh(){
|
||||
if(this.refreshing||this.busy)return; this.refreshing=true; const revision=this.revision;
|
||||
try{const data=await this.request('state');if(revision===this.revision&&!this.busy){this.recipes=data.recipes;this.entries=data.entries;this.shoppingOverrides=data.shoppingOverrides||[];this.connected=true;}}
|
||||
catch{this.connected=false;} finally{this.refreshing=false;this.loading=false;}
|
||||
}
|
||||
async importLegacy(){
|
||||
if(this.busy)return;this.busy=true;this.revision++;let imported=0;
|
||||
try{for(const recipe of this.legacy){await this.request('recipes','POST',recipe);imported++;}this.legacy=[];this.notice='Receitas deste navegador importadas.';}
|
||||
catch(error){this.notice='Importadas '+imported+' receitas. '+(error instanceof Error?error.message:'Falha na importação.');}
|
||||
finally{this.busy=false;await this.refresh();}
|
||||
}
|
||||
dateFor(day:number){const date=new Date();date.setHours(12,0,0,0);date.setDate(date.getDate()-((date.getDay()+6)%7)+this.offset*7+day);return date;}
|
||||
key(day:number,meal:number){const date=this.dateFor(day);return `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()}:${meal}`;}
|
||||
get weekLabel(){const a=this.dateFor(0),b=this.dateFor(6);const month=new Intl.DateTimeFormat('pt-PT',{month:'long'});return a.getMonth()===b.getMonth()?`${a.getDate()} – ${b.getDate()} de ${month.format(b)} ${b.getFullYear()}`:`${a.getDate()} ${month.format(a)} – ${b.getDate()} ${month.format(b)} ${b.getFullYear()}`;}
|
||||
isToday(day:number){return this.dateFor(day).toDateString()===new Date().toDateString();}
|
||||
changeWeek(amount:number){this.offset+=amount;}
|
||||
slotRecipes(day:number,meal:number){return this.entries.filter(e=>e.slot===this.key(day,meal)).map(e=>this.recipes.find(r=>r.id===e.recipeId)).filter((r):r is Recipe=>!!r);}
|
||||
get count(){return this.days.reduce((total,_,d)=>total+this.meals.reduce((n,_,m)=>n+this.slotRecipes(d,m).length,0),0);}
|
||||
get baseShopping(){return shoppingList(this.recipes,this.entries,this.days.flatMap((_,d)=>this.meals.map((_,m)=>this.key(d,m))));}
|
||||
get weekKey(){return this.key(0,0).split(':')[0];}
|
||||
get shopping(){return applyShoppingOverrides(this.baseShopping,this.shoppingOverrides,this.weekKey);}
|
||||
get weekChanges(){return this.shoppingOverrides.filter(o=>o.week===this.weekKey);}
|
||||
editProduct(item?:ShoppingRow){this.productError='';this.product={week:this.weekKey,key:item?.key||'manual:'+this.id(),name:item?.name||'',quantity:item?.quantity??null,unit:item?.unit||'',removed:false};}
|
||||
async saveProduct(){if(!this.product||this.busy)return;if(!this.product.name.trim()){this.productError='Indique o nome do produto.';return;}this.busy=true;this.revision++;
|
||||
try{await this.request('shopping','PUT',this.product);this.product=null;this.notice='';}catch(e){this.productError=e instanceof Error?e.message:'Não foi possível guardar.';}finally{this.busy=false;await this.refresh();}
|
||||
}
|
||||
async removeProduct(item:ShoppingRow){if(this.busy)return;this.busy=true;this.revision++;try{await this.request('shopping','PUT',{week:this.weekKey,key:item.key,name:item.name,quantity:item.quantity,unit:item.unit,removed:true});this.notice='';}catch(e){this.notice=e instanceof Error?e.message:'Não foi possível remover.';}finally{this.busy=false;await this.refresh();}}
|
||||
async restoreProduct(item:ShoppingOverride){if(this.busy)return;this.busy=true;this.revision++;try{await this.request('shopping','DELETE',{week:item.week,key:item.key});this.notice='';}catch(e){this.notice=e instanceof Error?e.message:'Não foi possível repor.';}finally{this.busy=false;await this.refresh();}}
|
||||
editRecipe(recipe:Recipe){this.originalRecipe={...recipe};this.editing={...recipe};this.detail=null;this.picker=null;this.formError='';}
|
||||
formatQuantity=quantityLabel;
|
||||
get visibleRecipes(){return this.view==='planner'?this.recipes.slice(0,6):this.recipes.filter(r=>r.name.toLocaleLowerCase().includes(this.search.toLocaleLowerCase()));}
|
||||
get pickerRecipes(){return this.recipes.filter(r=>r.name.toLocaleLowerCase().includes(this.pickerSearch.toLocaleLowerCase()));}
|
||||
openPicker(day:number,meal:number){this.picker={day,meal};this.pickerSearch='';}
|
||||
async add(recipe:Recipe){
|
||||
if(!this.picker||this.busy)return;const slot=this.key(this.picker.day,this.picker.meal);this.busy=true;this.revision++;
|
||||
try{await this.request('entries','POST',{id:this.id(),slot,recipeId:recipe.id});this.picker=null;this.notice='';}
|
||||
catch(error){this.notice=error instanceof Error?error.message:'Não foi possível adicionar.';}
|
||||
finally{this.busy=false;await this.refresh();}
|
||||
}
|
||||
async remove(day:number,meal:number,index:number){
|
||||
if(this.busy)return;const entry=this.entries.filter(e=>e.slot===this.key(day,meal))[index];if(!entry)return;this.busy=true;this.revision++;
|
||||
try{await this.request('entries/'+encodeURIComponent(entry.id),'DELETE');this.notice='';}
|
||||
catch(error){this.notice=error instanceof Error?error.message:'Não foi possível remover.';}
|
||||
finally{this.busy=false;await this.refresh();}
|
||||
}
|
||||
newRecipe(){this.originalRecipe=null;this.editing={id:this.id(),name:'',image:'',ingredients:'',preparation:''};this.formError='';}
|
||||
async saveRecipe(){
|
||||
if(!this.editing||this.busy)return;
|
||||
if(!this.editing.name.trim()||!this.editing.ingredients.trim()||!this.editing.preparation.trim()||!this.editing.image){this.formError='Preencha o nome, a imagem, os ingredientes e a preparação.';return;}
|
||||
this.busy=true;this.revision++;const recipe={...this.editing,name:this.editing.name.trim()};
|
||||
try{
|
||||
await this.request(this.originalRecipe?'recipes/'+encodeURIComponent(recipe.id):'recipes',this.originalRecipe?'PUT':'POST',this.originalRecipe?{...recipe,previous:this.originalRecipe}:recipe);this.editing=null;this.originalRecipe=null;this.notice='';
|
||||
if(this.picker){
|
||||
try{await this.request('entries','POST',{id:this.id(),slot:this.key(this.picker.day,this.picker.meal),recipeId:recipe.id});this.picker=null;}
|
||||
catch{this.notice='A receita foi guardada. Não foi possível adicioná-la ao plano; selecione-a novamente.';}
|
||||
}
|
||||
}catch(error){this.formError=error instanceof Error?error.message:'Não foi possível guardar. Tente novamente.';}
|
||||
finally{this.busy=false;await this.refresh();}
|
||||
}
|
||||
upload(event:Event){const file=(event.target as HTMLInputElement).files?.[0];if(!file)return;if(!['image/png','image/jpeg','image/webp','image/gif'].includes(file.type)){this.formError='Escolha uma imagem PNG, JPEG, WebP ou GIF.';return;}if(file.size>2*1024*1024){this.formError='Escolha uma imagem com menos de 2 MB.';return;}const reader=new FileReader();reader.onload=()=>{if(this.editing){this.editing.image=String(reader.result);this.formError='';}};reader.readAsDataURL(file);}
|
||||
imageError(event:Event){const img=event.target as HTMLImageElement;img.onerror=null;img.src='data:image/svg+xml,'+encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="600" height="400"><rect width="600" height="400" fill="#e7e9df"/><text x="300" y="220" text-anchor="middle" font-size="64" fill="#637661">♧</text></svg>');}
|
||||
@HostListener('document:keydown.escape') escape(){if(this.product)this.product=null;else if(this.editing)this.editing=null;else if(this.detail)this.detail=null;else this.picker=null;}
|
||||
}
|
||||
bootstrapApplication(App).catch(console.error);
|
||||
@@ -0,0 +1,72 @@
|
||||
export interface ShoppingRow { key: string; name: string; unit: string; quantity: number | null; occurrences: number; recipes: string[]; }
|
||||
export interface ShoppingOverride { week:string; key:string; name:string; unit:string; quantity:number|null; removed:boolean; }
|
||||
export function applyShoppingOverrides(base:ShoppingRow[], changes:ShoppingOverride[], week:string):ShoppingRow[] {
|
||||
const rows=new Map(base.map(r=>[r.key,{...r}]));
|
||||
for(const item of changes.filter(c=>c.week===week)){
|
||||
if(item.removed)rows.delete(item.key);
|
||||
else rows.set(item.key,{...rows.get(item.key),...item,occurrences:rows.get(item.key)?.occurrences||0,recipes:rows.get(item.key)?.recipes||[]});
|
||||
}
|
||||
return [...rows.values()].sort((a,b)=>a.name.localeCompare(b.name,'pt'));
|
||||
}
|
||||
interface ShoppingRecipe { id: string; name: string; ingredients: string; }
|
||||
interface ShoppingEntry { slot: string; recipeId: string; }
|
||||
const normalize = (value: string) => value.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/\s+/g, ' ').trim();
|
||||
const names: Record<string,string> = { ovos:'ovo', bananas:'banana', abacates:'abacate', cenouras:'cenoura', tomates:'tomate', cebolas:'cebola', batatas:'batata', limoes:'limão', macas:'maçã', pepinos:'pepino' };
|
||||
const units: [RegExp,string,number][] = [
|
||||
[/^(?:quilogramas?|quilos?|kg)\b\.?\s*/i,'g',1000],
|
||||
[/^(?:gramas?|gr|g)\b\.?\s*/i,'g',1],
|
||||
[/^(?:mililitros?|ml)\b\.?\s*/i,'ml',1],
|
||||
[/^(?:litros?|l)\b\.?\s*/i,'ml',1000],
|
||||
[/^(?:colher(?:es)?|c\.)\s+(?:de\s+)?sopa\b\s*/i,'colher de sopa',1],
|
||||
[/^(?:colher(?:es)?|c\.)\s+(?:de\s+)?ch[aá]\b\s*/i,'colher de chá',1],
|
||||
[/^colher(?:es)?\b\s*/i,'colher (tamanho não indicado)',1],
|
||||
[/^(?:ch[aá]venas?|x[ií]caras?)\b\s*/i,'chávena',1],
|
||||
[/^dentes?\b\s*/i,'dente',1], [/^fatias?\b\s*/i,'fatia',1],
|
||||
[/^latas?\b\s*/i,'lata',1], [/^lombos?\b\s*/i,'lombo',1],
|
||||
[/^unidades?\b\s*/i,'un.',1]
|
||||
];
|
||||
function parse(line: string) {
|
||||
const original=line.replace(/^\s*[-•]\s*/, '').trim();
|
||||
let text=original.replace(/(\d)\s*([½¼¾⅓⅔])/g,'$1 $2');
|
||||
const fractions:Record<string,string>={'½':'1/2','¼':'1/4','¾':'3/4','⅓':'1/3','⅔':'2/3'};
|
||||
text=text.replace(/[½¼¾⅓⅔]/g,c=>fractions[c]);
|
||||
const match=text.match(/^(\d+\s+\d+\s*\/\s*\d+|\d+\s*\/\s*\d+|\d+(?:[.,]\d+)?)(?:\s+|(?=[a-zA-Z]))(.+)$/);
|
||||
let name=original, quantity:number|null=null, unit='';
|
||||
if(match){
|
||||
const parts=match[1].trim().split(/\s+(?=\d+\s*\/)/);
|
||||
const amount=parts.reduce((sum,p)=>{const f=p.split('/');return sum+(f.length===2?Number(f[0])/Number(f[1]):Number(p.replace(',','.')));},0);
|
||||
let rest=match[2].trim();
|
||||
// Ranges and alternatives need a human decision, rather than a guessed total.
|
||||
if(Number.isFinite(amount)&&amount>0&&!/^(?:a\s+\d|ou\s+\d|[-–\d/])/.test(rest)){
|
||||
quantity=amount;unit='un.';
|
||||
for(const [pattern,label,factor] of units){if(pattern.test(rest)){rest=rest.replace(pattern,'');unit=label;quantity*=factor;break;}}
|
||||
name=rest.replace(/^de\s+/i,'').trim();
|
||||
if(!name){name=original;quantity=null;unit='';}
|
||||
}
|
||||
}
|
||||
name=names[normalize(name)]||name;
|
||||
return {name,quantity,unit};
|
||||
}
|
||||
export function shoppingList(recipes: ShoppingRecipe[], entries: ShoppingEntry[], slots: string[]): ShoppingRow[] {
|
||||
const wanted=new Set(slots), byId=new Map(recipes.map(r=>[r.id,r])), rows=new Map<string,ShoppingRow>();
|
||||
for(const entry of entries){
|
||||
if(!wanted.has(entry.slot))continue;
|
||||
const recipe=byId.get(entry.recipeId);if(!recipe)continue;
|
||||
for(const line of recipe.ingredients.split(/\r?\n/).filter(l=>l.trim())){
|
||||
const item=parse(line), key=normalize(item.name)+'|'+item.unit;
|
||||
let row=rows.get(key);
|
||||
if(!row){row={...item,key,occurrences:0,recipes:[]};rows.set(key,row);}
|
||||
else if(item.quantity!==null&&row.quantity!==null)row.quantity+=item.quantity;
|
||||
row.occurrences++;
|
||||
if(!row.recipes.includes(recipe.name))row.recipes.push(recipe.name);
|
||||
}
|
||||
}
|
||||
return [...rows.values()].sort((a,b)=>a.name.localeCompare(b.name,'pt'));
|
||||
}
|
||||
export function quantityLabel(row:ShoppingRow):string {
|
||||
if(row.quantity===null)return 'Quantidade não indicada';
|
||||
let amount=row.quantity,unit=row.unit;
|
||||
if(unit==='g'&&amount>=1000){amount/=1000;unit='kg';}
|
||||
if(unit==='ml'&&amount>=1000){amount/=1000;unit='l';}
|
||||
return new Intl.NumberFormat('pt-PT',{maximumFractionDigits:3}).format(amount)+' '+unit;
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
{"compilerOptions":{"target":"ES2022","module":"ES2022","moduleResolution":"bundler","experimentalDecorators":true,"strict":true,"skipLibCheck":true,"lib":["ES2022","dom"]},"angularCompilerOptions":{"strictTemplates":true},"files":["src/main.ts"]}
|
||||
Reference in New Issue
Block a user