diff --git a/backend/server.js b/backend/server.js index 215ee8b..36166a8 100644 --- a/backend/server.js +++ b/backend/server.js @@ -4202,11 +4202,75 @@ app.get('/api/p/:token', async (req, res) => { eventos: ev.rows, fotos: ft.rows.map(f => ({ ...f, url: `/api/protese/os/fotos/${f.id}/raw?t=${signMedia(f.id)}` })), componentes: cm.rows, ocorrencias: oc.rows, custodia: cu.rows, - somente_leitura: true, + finalizada: os.status === 'entregue' || os.status === 'cancelado', }); } catch (err) { res.status(500).json({ error: err.message }); } }); +// Modo 1 (1b) — ações do protético PELO LINK (sem conta). Auditadas como " (link)". +async function resolveLinkToken(token) { + const { rows } = await pool.query("SELECT * FROM protese_os_link WHERE token=$1 AND revoked_at IS NULL AND (expires_at IS NULL OR expires_at > NOW())", [token]); + if (!rows.length) return null; + const { rows: os } = await pool.query("SELECT * FROM protese_os WHERE id=$1 AND deleted_at IS NULL", [rows[0].os_id]); + if (!os.length) return null; + return { link: rows[0], os: os[0] }; +} +async function logEventoLink(os, link, status, observacao) { + const nome = `${await actorNome(link.protetico_id)} (link)`; + await pool.query("INSERT INTO protese_os_evento (id, os_id, clinica_id, status, observacao, actor_id, actor_nome) VALUES ($1,$2,$3,$4,$5,$6,$7)", + [`pev_${Date.now()}_${Math.random().toString(36).slice(2, 5)}`, os.id, os.clinica_id, status, observacao, link.protetico_id, nome]); + return nome; +} + +app.post('/api/p/:token/custodia', async (req, res) => { + try { + const ctx = await resolveLinkToken(req.params.token); + if (!ctx) return res.status(404).json({ error: 'Link inválido ou expirado.' }); + const { os, link } = ctx; + const para = ['clinica', 'laboratorio'].includes(req.body?.para_local) ? req.body.para_local : null; + if (!para) return res.status(400).json({ error: 'para_local inválido.' }); + const de = os.local_atual || 'clinica'; + if (de === para) return res.status(409).json({ error: `Já está ${para === 'laboratorio' ? 'com o laboratório' : 'na clínica'}.` }); + const nome = `${await actorNome(link.protetico_id)} (link)`; + await pool.query("INSERT INTO protese_os_custodia (id, os_id, clinica_id, de_local, para_local, etapa, actor_id, actor_nome) VALUES ($1,$2,$3,$4,$5,$6,$7,$8)", + [`pcus_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`, os.id, os.clinica_id, de, para, os.status, link.protetico_id, nome]); + await pool.query("UPDATE protese_os SET local_atual=$1 WHERE id=$2", [para, os.id]); + await logEventoLink(os, link, 'custodia', para === 'laboratorio' ? 'Protético recebeu o trabalho (via link)' : 'Trabalho devolvido à clínica (via link)'); + res.json({ success: true, local_atual: para }); + } catch (err) { res.status(500).json({ error: err.message }); } +}); +app.post('/api/p/:token/status', async (req, res) => { + try { + const ctx = await resolveLinkToken(req.params.token); + if (!ctx) return res.status(404).json({ error: 'Link inválido ou expirado.' }); + const { os, link } = ctx; + const PROD = ['recebido', 'producao', 'prova', 'ajuste', 'finalizado']; + if (!PROD.includes(req.body?.status)) return res.status(400).json({ error: 'Etapa inválida (somente produção pelo link).' }); + if (os.status === 'entregue' || os.status === 'cancelado') return res.status(409).json({ error: `OS já está "${os.status}".` }); + await pool.query('UPDATE protese_os SET status=$1, updated_at=NOW() WHERE id=$2', [req.body.status, os.id]); + await logEventoLink(os, link, req.body.status, null); + res.json({ success: true, status: req.body.status }); + } catch (err) { res.status(500).json({ error: err.message }); } +}); +app.post('/api/p/:token/foto', ortoUpload.single('foto'), async (req, res) => { + try { + if (!req.file) return res.status(400).json({ error: 'foto obrigatória.' }); + const ctx = await resolveLinkToken(req.params.token); + if (!ctx) return res.status(404).json({ error: 'Link inválido ou expirado.' }); + const { os, link } = ctx; + const ext = ((req.file.originalname.split('.').pop() || 'jpg').toLowerCase().replace(/[^a-z0-9]/g, '')) || 'jpg'; + const rel = path.join('proteses', os.id, `${Date.now()}.${ext}`); + await fs.promises.mkdir(path.join(MEDIA_ROOT, 'proteses', os.id), { recursive: true }); + await fs.promises.writeFile(path.join(MEDIA_ROOT, rel), req.file.buffer); + const fid = `pof_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`; + const nome = `${await actorNome(link.protetico_id)} (link)`; + await pool.query("INSERT INTO protese_os_foto (id, os_id, clinica_id, filename, mimetype, original_name, uploaded_by, uploaded_nome) VALUES ($1,$2,$3,$4,$5,$6,$7,$8)", + [fid, os.id, os.clinica_id, rel, req.file.mimetype, req.file.originalname, link.protetico_id, nome]); + await logEventoLink(os, link, 'foto', 'Foto anexada (via link)'); + res.json({ success: true, id: fid }); + } catch (err) { res.status(500).json({ error: err.message }); } +}); + // Detalhe + histórico de eventos + fotos. app.get('/api/protese/os/:id', authGuard, async (req, res) => { try { diff --git a/doc/MODO1-LINK-SEGURO-PROTESE.md b/doc/MODO1-LINK-SEGURO-PROTESE.md index 787e877..e5fbc1a 100644 --- a/doc/MODO1-LINK-SEGURO-PROTESE.md +++ b/doc/MODO1-LINK-SEGURO-PROTESE.md @@ -88,7 +88,12 @@ marketplace/score (Fase 5) — quanto mais clínicas o usam, mais OS e melhor o interceptada no `index.tsx` antes do app autenticado); botão "Gerar link / WhatsApp / Copiar" na aba Monitoramento (modo clínica). CTA "Criar conta grátis". Validado em DEV (leitura, blindagem, token inválido→404, revogação→404). -- **1b (ação):** custódia + status + foto pelo link (escrita), com auditoria. +- **✅ 1b (ação) — IMPLEMENTADA 24/jun:** o protético, pelo link, **confirma recebimento/devolução** + (`POST /api/p/:token/custodia`), **avança a produção** (`/status`, só `recebido…finalizado` — nunca + entregue/cancelado, que são da clínica) e **anexa foto** (`/foto`). Tudo auditado como + `" (link)"`. Página pública ganha a seção "Atualizar status" (botões de custódia, etapa e foto) + enquanto a OS não está finalizada. Validado em DEV: recebimento, avanço, foto, e `entregue` pelo link + → 400 (bloqueado). - **1c (conversão):** herança de histórico ao criar conta + revogação/expiração na UI. > Nenhuma refatoração: reusa OS/eventos/custódia/ocorrências/blindagem já existentes. Só adiciona a diff --git a/frontend/services/backend.ts b/frontend/services/backend.ts index 4a5183e..3174f9f 100644 --- a/frontend/services/backend.ts +++ b/frontend/services/backend.ts @@ -1136,6 +1136,24 @@ export const HybridBackend = { if (!res.ok) throw new Error((await res.json().catch(() => ({}))).error || 'Link inválido ou expirado.'); return await res.json(); }, + // Ações PÚBLICAS pelo link (Modo 1, fatia 1b) — sem login + custodiaPublic: async (token: string, para_local: 'clinica' | 'laboratorio') => { + const res = await fetch(`${API_URL}/p/${encodeURIComponent(token)}/custodia`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ para_local }) }); + if (!res.ok) throw new Error((await res.json().catch(() => ({}))).error || 'Erro ao registrar.'); + return await res.json(); + }, + statusPublic: async (token: string, status: string) => { + const res = await fetch(`${API_URL}/p/${encodeURIComponent(token)}/status`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ status }) }); + if (!res.ok) throw new Error((await res.json().catch(() => ({}))).error || 'Erro ao avançar etapa.'); + return await res.json(); + }, + uploadFotoPublic: async (token: string, file: File) => { + const fd = new FormData(); + fd.append('foto', file); + const res = await fetch(`${API_URL}/p/${encodeURIComponent(token)}/foto`, { method: 'POST', body: fd }); + if (!res.ok) throw new Error((await res.json().catch(() => ({}))).error || 'Erro ao anexar foto.'); + return await res.json(); + }, // Agenda de uma sala (reservas + bloqueios de manutenção) — usado pelo operador da unidade. getSalaReservas: async (salaId: string): Promise => { diff --git a/frontend/views/ProtesePublicView.tsx b/frontend/views/ProtesePublicView.tsx index 5d7d8fa..7de4ccb 100644 --- a/frontend/views/ProtesePublicView.tsx +++ b/frontend/views/ProtesePublicView.tsx @@ -1,6 +1,7 @@ -import React, { useState, useEffect } from 'react'; -import { FlaskConical, Building2, Clock, ShieldCheck, AlertTriangle, CheckCircle2, Circle, Package, History, Camera, MapPin, ChevronRight, Loader2 } from 'lucide-react'; +import React, { useState, useEffect, useCallback } from 'react'; +import { FlaskConical, Building2, Clock, ShieldCheck, AlertTriangle, CheckCircle2, Circle, Package, History, Camera, MapPin, ChevronRight, Loader2, ImagePlus, Zap } from 'lucide-react'; import { HybridBackend } from '../services/backend.ts'; +import { useToast } from '../contexts/ToastContext.tsx'; const fmtBRL = (v: number) => 'R$ ' + Number(v || 0).toLocaleString('pt-BR', { minimumFractionDigits: 2 }); const dataBR = (d: string) => (d || '').slice(0, 10).split('-').reverse().join('/'); @@ -18,14 +19,30 @@ const Secao: React.FC<{ titulo: string; Icon: any; children: React.ReactNode }> ); +const PROD_FLUXO = ['recebido', 'producao', 'prova', 'ajuste', 'finalizado']; + export const ProtesePublicView: React.FC<{ token: string }> = ({ token }) => { + const toast = useToast(); const [os, setOs] = useState(null); const [erro, setErro] = useState(''); const [loading, setLoading] = useState(true); + const [busy, setBusy] = useState(false); - useEffect(() => { - HybridBackend.getProtesePublic(token).then(setOs).catch(e => setErro(e.message || 'Link inválido.')).finally(() => setLoading(false)); - }, [token]); + const recarregar = useCallback(() => HybridBackend.getProtesePublic(token).then(setOs).catch(e => setErro(e.message || 'Link inválido.')), [token]); + useEffect(() => { recarregar().finally(() => setLoading(false)); }, [recarregar]); + + const act = async (fn: () => Promise, ok: string) => { + setBusy(true); + try { await fn(); toast.success(ok); await recarregar(); } + catch (e: any) { toast.error((e.message || 'ERRO').toUpperCase()); } finally { setBusy(false); } + }; + const receber = () => act(() => HybridBackend.custodiaPublic(token, 'laboratorio'), 'RECEBIMENTO CONFIRMADO.'); + const devolver = () => act(() => HybridBackend.custodiaPublic(token, 'clinica'), 'DEVOLUÇÃO REGISTRADA.'); + const avancar = (s: string) => act(() => HybridBackend.statusPublic(token, s), 'ETAPA ATUALIZADA.'); + const anexar = (e: React.ChangeEvent) => { + const f = e.target.files?.[0]; if (!f) return; + act(() => HybridBackend.uploadFotoPublic(token, f), 'FOTO ANEXADA.'); e.target.value = ''; + }; if (loading) return
; if (erro || !os) return ( @@ -49,7 +66,7 @@ export const ProtesePublicView: React.FC<{ token: string }> = ({ token }) => {

ScoreOdonto

Acompanhamento de prótese

- Somente leitura + {os.finalizada ? 'Somente leitura' : 'Acompanhamento'}
@@ -69,6 +86,30 @@ export const ProtesePublicView: React.FC<{ token: string }> = ({ token }) => { + {/* Ações do protético (sem conta) */} + {!os.finalizada && ( + +
+ {noLab + ? + : } +
+

Etapa de produção

+
+ {PROD_FLUXO.map(s => ( + + ))} +
+
+ +
+
+ )} + {/* Etapas */} {cancelado ? (