feat(protese): Modo 1 fatia 1b — ações do protético pelo link (sem conta)
Pelo link /p/TOKEN o protético (sem conta) passa a ATUAR na OS, tudo auditado como "<nome> (link)": - POST /api/p/:token/custodia — confirmar recebimento / devolução (clínica↔lab) - POST /api/p/:token/status — avançar a produção (recebido…finalizado); entregue/cancelado seguem exclusivos da clínica (400 pelo link) - POST /api/p/:token/foto — anexar foto do trabalho Página pública ganha a seção "Atualizar status" (custódia/etapa/foto) enquanto a OS não está finalizada; header alterna Acompanhamento/Somente leitura. Validado em DEV: recebimento, avanço de etapa, foto; entregue pelo link → 400. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
+65
-1
@@ -4202,11 +4202,75 @@ app.get('/api/p/:token', async (req, res) => {
|
|||||||
eventos: ev.rows,
|
eventos: ev.rows,
|
||||||
fotos: ft.rows.map(f => ({ ...f, url: `/api/protese/os/fotos/${f.id}/raw?t=${signMedia(f.id)}` })),
|
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,
|
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 }); }
|
} catch (err) { res.status(500).json({ error: err.message }); }
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Modo 1 (1b) — ações do protético PELO LINK (sem conta). Auditadas como "<nome> (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.
|
// Detalhe + histórico de eventos + fotos.
|
||||||
app.get('/api/protese/os/:id', authGuard, async (req, res) => {
|
app.get('/api/protese/os/:id', authGuard, async (req, res) => {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -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
|
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,
|
aba Monitoramento (modo clínica). CTA "Criar conta grátis". Validado em DEV (leitura, blindagem,
|
||||||
token inválido→404, revogação→404).
|
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
|
||||||
|
`"<nome> (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.
|
- **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
|
> Nenhuma refatoração: reusa OS/eventos/custódia/ocorrências/blindagem já existentes. Só adiciona a
|
||||||
|
|||||||
@@ -1136,6 +1136,24 @@ export const HybridBackend = {
|
|||||||
if (!res.ok) throw new Error((await res.json().catch(() => ({}))).error || 'Link inválido ou expirado.');
|
if (!res.ok) throw new Error((await res.json().catch(() => ({}))).error || 'Link inválido ou expirado.');
|
||||||
return await res.json();
|
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.
|
// Agenda de uma sala (reservas + bloqueios de manutenção) — usado pelo operador da unidade.
|
||||||
getSalaReservas: async (salaId: string): Promise<any[]> => {
|
getSalaReservas: async (salaId: string): Promise<any[]> => {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect, useCallback } from 'react';
|
||||||
import { FlaskConical, Building2, Clock, ShieldCheck, AlertTriangle, CheckCircle2, Circle, Package, History, Camera, MapPin, ChevronRight, Loader2 } from 'lucide-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 { 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 fmtBRL = (v: number) => 'R$ ' + Number(v || 0).toLocaleString('pt-BR', { minimumFractionDigits: 2 });
|
||||||
const dataBR = (d: string) => (d || '').slice(0, 10).split('-').reverse().join('/');
|
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 }>
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const PROD_FLUXO = ['recebido', 'producao', 'prova', 'ajuste', 'finalizado'];
|
||||||
|
|
||||||
export const ProtesePublicView: React.FC<{ token: string }> = ({ token }) => {
|
export const ProtesePublicView: React.FC<{ token: string }> = ({ token }) => {
|
||||||
|
const toast = useToast();
|
||||||
const [os, setOs] = useState<any>(null);
|
const [os, setOs] = useState<any>(null);
|
||||||
const [erro, setErro] = useState('');
|
const [erro, setErro] = useState('');
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
|
||||||
useEffect(() => {
|
const recarregar = useCallback(() => HybridBackend.getProtesePublic(token).then(setOs).catch(e => setErro(e.message || 'Link inválido.')), [token]);
|
||||||
HybridBackend.getProtesePublic(token).then(setOs).catch(e => setErro(e.message || 'Link inválido.')).finally(() => setLoading(false));
|
useEffect(() => { recarregar().finally(() => setLoading(false)); }, [recarregar]);
|
||||||
}, [token]);
|
|
||||||
|
const act = async (fn: () => Promise<any>, 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<HTMLInputElement>) => {
|
||||||
|
const f = e.target.files?.[0]; if (!f) return;
|
||||||
|
act(() => HybridBackend.uploadFotoPublic(token, f), 'FOTO ANEXADA.'); e.target.value = '';
|
||||||
|
};
|
||||||
|
|
||||||
if (loading) return <div className="min-h-screen flex items-center justify-center bg-gray-50"><Loader2 className="animate-spin text-teal-600" size={32} /></div>;
|
if (loading) return <div className="min-h-screen flex items-center justify-center bg-gray-50"><Loader2 className="animate-spin text-teal-600" size={32} /></div>;
|
||||||
if (erro || !os) return (
|
if (erro || !os) return (
|
||||||
@@ -49,7 +66,7 @@ export const ProtesePublicView: React.FC<{ token: string }> = ({ token }) => {
|
|||||||
<p className="font-black text-sm leading-tight">ScoreOdonto</p>
|
<p className="font-black text-sm leading-tight">ScoreOdonto</p>
|
||||||
<p className="text-[10px] text-white/70 uppercase tracking-wide leading-tight">Acompanhamento de prótese</p>
|
<p className="text-[10px] text-white/70 uppercase tracking-wide leading-tight">Acompanhamento de prótese</p>
|
||||||
</div>
|
</div>
|
||||||
<span className="text-[9px] font-black px-2 py-0.5 rounded-full bg-white/15 uppercase">Somente leitura</span>
|
<span className="text-[9px] font-black px-2 py-0.5 rounded-full bg-white/15 uppercase">{os.finalizada ? 'Somente leitura' : 'Acompanhamento'}</span>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<main className="max-w-lg mx-auto p-3 space-y-3">
|
<main className="max-w-lg mx-auto p-3 space-y-3">
|
||||||
@@ -69,6 +86,30 @@ export const ProtesePublicView: React.FC<{ token: string }> = ({ token }) => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Ações do protético (sem conta) */}
|
||||||
|
{!os.finalizada && (
|
||||||
|
<Secao titulo="Atualizar status" Icon={Zap}>
|
||||||
|
<div className="space-y-2">
|
||||||
|
{noLab
|
||||||
|
? <button disabled={busy} onClick={devolver} className="w-full py-2.5 rounded-xl bg-blue-600 text-white font-black text-xs uppercase disabled:opacity-50">Devolvi à clínica</button>
|
||||||
|
: <button disabled={busy} onClick={receber} className="w-full py-2.5 rounded-xl bg-[#2d6a4f] text-white font-black text-xs uppercase disabled:opacity-50">Recebi o trabalho</button>}
|
||||||
|
<div>
|
||||||
|
<p className="text-[9px] font-black text-gray-400 uppercase mb-1">Etapa de produção</p>
|
||||||
|
<div className="flex flex-wrap gap-1.5">
|
||||||
|
{PROD_FLUXO.map(s => (
|
||||||
|
<button key={s} disabled={busy || os.status === s} onClick={() => avancar(s)}
|
||||||
|
className={`px-2.5 py-1.5 rounded-lg text-[10px] font-black uppercase disabled:opacity-40 ${os.status === s ? 'bg-[#2d6a4f] text-white' : 'border border-gray-200 text-gray-500'}`}>{STATUS_LABEL[s]}</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<label className={`w-full flex items-center justify-center gap-2 py-2.5 rounded-xl border border-dashed border-gray-200 text-gray-500 text-xs font-bold uppercase cursor-pointer ${busy ? 'opacity-50 pointer-events-none' : ''}`}>
|
||||||
|
<ImagePlus size={15} /> Anexar foto do trabalho
|
||||||
|
<input type="file" accept="image/*" className="hidden" onChange={anexar} />
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</Secao>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Etapas */}
|
{/* Etapas */}
|
||||||
<Secao titulo="Etapas" Icon={Clock}>
|
<Secao titulo="Etapas" Icon={Clock}>
|
||||||
{cancelado ? (
|
{cancelado ? (
|
||||||
|
|||||||
Reference in New Issue
Block a user