diff --git a/susconecta/Documentação API.md b/susconecta/Documentação API.md index b9138c8..b1b9604 100644 --- a/susconecta/Documentação API.md +++ b/susconecta/Documentação API.md @@ -1188,3 +1188,1378 @@ security: ``` +# Listar perfis de usuários + +## OpenAPI Specification + +```yaml +openapi: 3.0.1 +info: + title: '' + description: '' + version: 1.0.0 +paths: + /rest/v1/profiles: + get: + summary: Listar perfis de usuários + deprecated: false + description: '' + tags: + - Perfis + - Perfis + parameters: + - name: apikey + in: header + description: Chave da API Supabase + required: true + example: '' + schema: + type: string + responses: + '200': + description: Lista de perfis + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Profile' + headers: {} + x-apidog-name: OK + security: + - bearer: [] + x-apidog-folder: Perfis + x-apidog-status: released + x-run-in-apidog: https://app.apidog.com/web/project/1053378/apis/api-21940522-run +components: + schemas: + Profile: + type: object + properties: + id: + type: string + format: uuid + full_name: + type: string + examples: + - Dr. João Silva + nullable: true + email: + type: string + format: email + nullable: true + phone: + type: string + examples: + - '+5511999999999' + nullable: true + avatar_url: + type: string + format: uri + nullable: true + disabled: + type: boolean + examples: + - false + created_at: + type: string + format: date-time + updated_at: + type: string + format: date-time + x-apidog-orders: + - id + - full_name + - email + - phone + - avatar_url + - disabled + - created_at + - updated_at + x-apidog-ignore-properties: [] + nullable: true + x-apidog-folder: '' + securitySchemes: + bearerAuth: + type: jwt + scheme: bearer + bearerFormat: JWT + description: Token JWT obtido no login + bearer: + type: http + scheme: bearer +servers: + - url: https://yuanqfswhberkoevtmfr.supabase.co + description: Prod Env + - url: '' + description: Cloud Mock +security: + - bearer: [] + +``` + +# Atualizar perfil do usuário + +## OpenAPI Specification + +```yaml +openapi: 3.0.1 +info: + title: '' + description: '' + version: 1.0.0 +paths: + /rest/v1/profiles: + patch: + summary: Atualizar perfil do usuário + deprecated: false + description: '' + tags: + - Perfis + - Perfis + parameters: + - name: apikey + in: header + description: Chave da API Supabase + required: true + example: '' + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/ProfileInput' + responses: + '200': + description: Perfil atualizado + content: + application/json: + schema: + $ref: '#/components/schemas/Profile' + headers: {} + x-apidog-name: OK + security: + - bearer: [] + x-apidog-folder: Perfis + x-apidog-status: released + x-run-in-apidog: https://app.apidog.com/web/project/1053378/apis/api-21940523-run +components: + schemas: + ProfileInput: + type: object + properties: + full_name: + type: string + avatar_url: + type: string + phone: + type: string + x-apidog-orders: + - full_name + - avatar_url + - phone + x-apidog-ignore-properties: [] + x-apidog-folder: '' + Profile: + type: object + properties: + id: + type: string + format: uuid + full_name: + type: string + examples: + - Dr. João Silva + nullable: true + email: + type: string + format: email + nullable: true + phone: + type: string + examples: + - '+5511999999999' + nullable: true + avatar_url: + type: string + format: uri + nullable: true + disabled: + type: boolean + examples: + - false + created_at: + type: string + format: date-time + updated_at: + type: string + format: date-time + x-apidog-orders: + - id + - full_name + - email + - phone + - avatar_url + - disabled + - created_at + - updated_at + x-apidog-ignore-properties: [] + nullable: true + x-apidog-folder: '' + securitySchemes: + bearerAuth: + type: jwt + scheme: bearer + bearerFormat: JWT + description: Token JWT obtido no login + bearer: + type: http + scheme: bearer +servers: + - url: https://yuanqfswhberkoevtmfr.supabase.co + description: Prod Env + - url: '' + description: Cloud Mock +security: + - bearer: [] + +``` + +# Obter paciente por ID + +## OpenAPI Specification + +```yaml +openapi: 3.0.1 +info: + title: '' + description: '' + version: 1.0.0 +paths: + /rest/v1/patients/{id}: + get: + summary: Obter paciente por ID + deprecated: false + description: Retorna dados de um paciente específico + tags: + - Pacientes + - Pacientes + parameters: + - name: id + in: path + description: ID do paciente + required: true + example: '' + schema: + type: string + format: uuid + - name: apikey + in: header + description: Chave da API Supabase + required: true + example: '' + schema: + type: string + responses: + '200': + description: Dados do paciente + content: + application/json: + schema: + $ref: '#/components/schemas/Patient' + headers: {} + x-apidog-name: OK + '401': + description: Não autorizado + content: + application/json: + schema: &ref_0 + $ref: '#/components/schemas/Error' + headers: {} + x-apidog-name: Unauthorized + '404': + description: Paciente não encontrado + content: + application/json: + schema: *ref_0 + headers: {} + x-apidog-name: Not Found + security: + - bearer: [] + x-apidog-folder: Pacientes + x-apidog-status: released + x-run-in-apidog: https://app.apidog.com/web/project/1053378/apis/api-21940515-run +components: + schemas: + Patient: + type: object + properties: + id: + type: string + format: uuid + examples: + - 12345678-1234-1234-1234-123456789012 + full_name: + type: string + examples: + - Maria Santos Silva + cpf: + type: string + examples: + - '12345678901' + email: + type: string + format: email + examples: + - maria@email.com + phone_mobile: + type: string + examples: + - (11) 99999-9999 + birth_date: + type: string + format: date + examples: + - '1980-01-15' + social_name: + type: string + examples: + - Maria Santos + sex: + type: string + examples: + - F + blood_type: + type: string + examples: + - A+ + weight_kg: + type: number + examples: + - 65.5 + height_m: + type: number + examples: + - 1.65 + bmi: + type: number + examples: + - 24.1 + street: + type: string + examples: + - Rua das Flores, 123 + number: + type: string + examples: + - '123' + complement: + type: string + examples: + - Apt 45 + neighborhood: + type: string + examples: + - Centro + city: + type: string + examples: + - São Paulo + state: + type: string + examples: + - SP + cep: + type: string + examples: + - 01234-567 + created_at: + type: string + format: date-time + examples: + - '2024-01-15T10:30:00Z' + updated_at: + type: string + format: date-time + examples: + - '2024-01-15T10:30:00Z' + created_by: + type: string + format: uuid + examples: + - 12345678-1234-1234-1234-123456789012 + x-apidog-orders: + - id + - full_name + - cpf + - email + - phone_mobile + - birth_date + - social_name + - sex + - blood_type + - weight_kg + - height_m + - bmi + - street + - number + - complement + - neighborhood + - city + - state + - cep + - created_at + - updated_at + - created_by + x-apidog-ignore-properties: [] + x-apidog-folder: '' + Error: + type: object + properties: + error: + type: string + message: + type: string + code: + type: string + x-apidog-orders: + - error + - message + - code + x-apidog-ignore-properties: [] + x-apidog-folder: '' + securitySchemes: + bearerAuth: + type: jwt + scheme: bearer + bearerFormat: JWT + description: Token JWT obtido no login + bearer: + type: http + scheme: bearer +servers: + - url: https://yuanqfswhberkoevtmfr.supabase.co + description: Prod Env + - url: '' + description: Cloud Mock +security: + - bearer: [] + +``` + +# Atualizar paciente + +## OpenAPI Specification + +```yaml +openapi: 3.0.1 +info: + title: '' + description: '' + version: 1.0.0 +paths: + /rest/v1/patients/{id}: + patch: + summary: Atualizar paciente + deprecated: false + description: Atualizar dados de um paciente existente + tags: + - Pacientes + - Pacientes + parameters: + - name: id + in: path + description: ID do paciente + required: true + example: '' + schema: + type: string + format: uuid + - name: apikey + in: header + description: Chave da API Supabase + required: true + example: '' + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/PatientInput' + responses: + '200': + description: Paciente atualizado com sucesso + content: + application/json: + schema: + $ref: '#/components/schemas/Patient' + headers: {} + x-apidog-name: OK + '401': + description: Não autorizado + content: + application/json: + schema: &ref_0 + $ref: '#/components/schemas/Error' + headers: {} + x-apidog-name: Unauthorized + '404': + description: Paciente não encontrado + content: + application/json: + schema: *ref_0 + headers: {} + x-apidog-name: Not Found + security: + - bearer: [] + x-apidog-folder: Pacientes + x-apidog-status: released + x-run-in-apidog: https://app.apidog.com/web/project/1053378/apis/api-21940516-run +components: + schemas: + PatientInput: + type: object + required: + - full_name + - cpf + - email + - phone_mobile + properties: + full_name: + type: string + examples: + - Maria Santos Silva + cpf: + type: string + examples: + - '12345678901' + email: + type: string + format: email + examples: + - maria@email.com + phone_mobile: + type: string + examples: + - (11) 99999-9999 + birth_date: + type: string + format: date + examples: + - '1980-01-15' + social_name: + type: string + sex: + type: string + examples: + - F + blood_type: + type: string + weight_kg: + type: number + height_m: + type: number + street: + type: string + number: + type: string + complement: + type: string + neighborhood: + type: string + city: + type: string + state: + type: string + cep: + type: string + x-apidog-orders: + - full_name + - cpf + - email + - phone_mobile + - birth_date + - social_name + - sex + - blood_type + - weight_kg + - height_m + - street + - number + - complement + - neighborhood + - city + - state + - cep + x-apidog-ignore-properties: [] + x-apidog-folder: '' + Patient: + type: object + properties: + id: + type: string + format: uuid + examples: + - 12345678-1234-1234-1234-123456789012 + full_name: + type: string + examples: + - Maria Santos Silva + cpf: + type: string + examples: + - '12345678901' + email: + type: string + format: email + examples: + - maria@email.com + phone_mobile: + type: string + examples: + - (11) 99999-9999 + birth_date: + type: string + format: date + examples: + - '1980-01-15' + social_name: + type: string + examples: + - Maria Santos + sex: + type: string + examples: + - F + blood_type: + type: string + examples: + - A+ + weight_kg: + type: number + examples: + - 65.5 + height_m: + type: number + examples: + - 1.65 + bmi: + type: number + examples: + - 24.1 + street: + type: string + examples: + - Rua das Flores, 123 + number: + type: string + examples: + - '123' + complement: + type: string + examples: + - Apt 45 + neighborhood: + type: string + examples: + - Centro + city: + type: string + examples: + - São Paulo + state: + type: string + examples: + - SP + cep: + type: string + examples: + - 01234-567 + created_at: + type: string + format: date-time + examples: + - '2024-01-15T10:30:00Z' + updated_at: + type: string + format: date-time + examples: + - '2024-01-15T10:30:00Z' + created_by: + type: string + format: uuid + examples: + - 12345678-1234-1234-1234-123456789012 + x-apidog-orders: + - id + - full_name + - cpf + - email + - phone_mobile + - birth_date + - social_name + - sex + - blood_type + - weight_kg + - height_m + - bmi + - street + - number + - complement + - neighborhood + - city + - state + - cep + - created_at + - updated_at + - created_by + x-apidog-ignore-properties: [] + x-apidog-folder: '' + Error: + type: object + properties: + error: + type: string + message: + type: string + code: + type: string + x-apidog-orders: + - error + - message + - code + x-apidog-ignore-properties: [] + x-apidog-folder: '' + securitySchemes: + bearerAuth: + type: jwt + scheme: bearer + bearerFormat: JWT + description: Token JWT obtido no login + bearer: + type: http + scheme: bearer +servers: + - url: https://yuanqfswhberkoevtmfr.supabase.co + description: Prod Env + - url: '' + description: Cloud Mock +security: + - bearer: [] + +``` + +# Deletar paciente + +## OpenAPI Specification + +```yaml +openapi: 3.0.1 +info: + title: '' + description: '' + version: 1.0.0 +paths: + /rest/v1/patients/{id}: + delete: + summary: Deletar paciente + deprecated: false + description: Remover um paciente do sistema (apenas admins/gestores) + tags: + - Pacientes + - Pacientes + parameters: + - name: id + in: path + description: ID do paciente + required: true + example: '' + schema: + type: string + format: uuid + - name: apikey + in: header + description: Chave da API Supabase + required: true + example: '' + schema: + type: string + responses: + '204': + description: Paciente deletado com sucesso + headers: {} + x-apidog-name: No Content + '401': + description: Não autorizado + content: + application/json: + schema: &ref_0 + $ref: '#/components/schemas/Error' + headers: {} + x-apidog-name: Unauthorized + '403': + description: Sem permissão + content: + application/json: + schema: *ref_0 + headers: {} + x-apidog-name: Forbidden + '404': + description: Paciente não encontrado + content: + application/json: + schema: *ref_0 + headers: {} + x-apidog-name: Not Found + security: + - bearer: [] + x-apidog-folder: Pacientes + x-apidog-status: released + x-run-in-apidog: https://app.apidog.com/web/project/1053378/apis/api-21940517-run +components: + schemas: + Error: + type: object + properties: + error: + type: string + message: + type: string + code: + type: string + x-apidog-orders: + - error + - message + - code + x-apidog-ignore-properties: [] + x-apidog-folder: '' + securitySchemes: + bearerAuth: + type: jwt + scheme: bearer + bearerFormat: JWT + description: Token JWT obtido no login + bearer: + type: http + scheme: bearer +servers: + - url: https://yuanqfswhberkoevtmfr.supabase.co + description: Prod Env + - url: '' + description: Cloud Mock +security: + - bearer: [] + +``` + +# Criar novo paciente + +## OpenAPI Specification + +```yaml +openapi: 3.0.1 +info: + title: '' + description: '' + version: 1.0.0 +paths: + /rest/v1/patients: + post: + summary: Criar novo paciente + deprecated: false + description: Cadastrar um novo paciente no sistema + tags: + - Pacientes + - Pacientes + parameters: + - name: apikey + in: header + description: Chave da API Supabase + required: true + example: '{{API_KEY}}' + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/PatientInput' + example: + full_name: Maria Santos + cpf: '12345678901' + email: maria@email.com + phone_mobile: (11) 99999-9999 + birth_date: '1980-01-15' + responses: + '201': + description: Paciente criado com sucesso + content: + application/json: + schema: + $ref: '#/components/schemas/Patient' + headers: {} + x-apidog-name: Created + '400': + description: Dados inválidos + content: + application/json: + schema: &ref_0 + $ref: '#/components/schemas/Error' + headers: {} + x-apidog-name: Bad Request + '401': + description: Não autorizado + content: + application/json: + schema: *ref_0 + headers: {} + x-apidog-name: Unauthorized + security: + - bearer: [] + x-apidog-folder: Pacientes + x-apidog-status: released + x-run-in-apidog: https://app.apidog.com/web/project/1053378/apis/api-21940514-run +components: + schemas: + PatientInput: + type: object + required: + - full_name + - cpf + - email + - phone_mobile + properties: + full_name: + type: string + examples: + - Maria Santos Silva + cpf: + type: string + examples: + - '12345678901' + email: + type: string + format: email + examples: + - maria@email.com + phone_mobile: + type: string + examples: + - (11) 99999-9999 + birth_date: + type: string + format: date + examples: + - '1980-01-15' + social_name: + type: string + sex: + type: string + examples: + - F + blood_type: + type: string + weight_kg: + type: number + height_m: + type: number + street: + type: string + number: + type: string + complement: + type: string + neighborhood: + type: string + city: + type: string + state: + type: string + cep: + type: string + x-apidog-orders: + - full_name + - cpf + - email + - phone_mobile + - birth_date + - social_name + - sex + - blood_type + - weight_kg + - height_m + - street + - number + - complement + - neighborhood + - city + - state + - cep + x-apidog-ignore-properties: [] + x-apidog-folder: '' + Patient: + type: object + properties: + id: + type: string + format: uuid + examples: + - 12345678-1234-1234-1234-123456789012 + full_name: + type: string + examples: + - Maria Santos Silva + cpf: + type: string + examples: + - '12345678901' + email: + type: string + format: email + examples: + - maria@email.com + phone_mobile: + type: string + examples: + - (11) 99999-9999 + birth_date: + type: string + format: date + examples: + - '1980-01-15' + social_name: + type: string + examples: + - Maria Santos + sex: + type: string + examples: + - F + blood_type: + type: string + examples: + - A+ + weight_kg: + type: number + examples: + - 65.5 + height_m: + type: number + examples: + - 1.65 + bmi: + type: number + examples: + - 24.1 + street: + type: string + examples: + - Rua das Flores, 123 + number: + type: string + examples: + - '123' + complement: + type: string + examples: + - Apt 45 + neighborhood: + type: string + examples: + - Centro + city: + type: string + examples: + - São Paulo + state: + type: string + examples: + - SP + cep: + type: string + examples: + - 01234-567 + created_at: + type: string + format: date-time + examples: + - '2024-01-15T10:30:00Z' + updated_at: + type: string + format: date-time + examples: + - '2024-01-15T10:30:00Z' + created_by: + type: string + format: uuid + examples: + - 12345678-1234-1234-1234-123456789012 + x-apidog-orders: + - id + - full_name + - cpf + - email + - phone_mobile + - birth_date + - social_name + - sex + - blood_type + - weight_kg + - height_m + - bmi + - street + - number + - complement + - neighborhood + - city + - state + - cep + - created_at + - updated_at + - created_by + x-apidog-ignore-properties: [] + x-apidog-folder: '' + Error: + type: object + properties: + error: + type: string + message: + type: string + code: + type: string + x-apidog-orders: + - error + - message + - code + x-apidog-ignore-properties: [] + x-apidog-folder: '' + securitySchemes: + bearerAuth: + type: jwt + scheme: bearer + bearerFormat: JWT + description: Token JWT obtido no login + bearer: + type: http + scheme: bearer +servers: + - url: https://yuanqfswhberkoevtmfr.supabase.co + description: Prod Env + - url: '' + description: Cloud Mock +security: + - bearer: [] + +``` + +# Listar pacientes + +## OpenAPI Specification + +```yaml +openapi: 3.0.1 +info: + title: '' + description: '' + version: 1.0.0 +paths: + /rest/v1/patients: + get: + summary: Listar pacientes + deprecated: false + description: Retorna lista de pacientes com base nas permissões do usuário + tags: + - Pacientes + - Pacientes + parameters: + - name: apikey + in: header + description: '' + required: false + example: '{{apikey}}' + schema: + type: string + responses: + '200': + description: Lista de pacientes + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Patient' + headers: {} + x-apidog-name: OK + '401': + description: Não autorizado + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + headers: {} + x-apidog-name: Unauthorized + security: + - bearer: [] + x-apidog-folder: Pacientes + x-apidog-status: released + x-run-in-apidog: https://app.apidog.com/web/project/1053378/apis/api-21940513-run +components: + schemas: + Patient: + type: object + properties: + id: + type: string + format: uuid + examples: + - 12345678-1234-1234-1234-123456789012 + full_name: + type: string + examples: + - Maria Santos Silva + cpf: + type: string + examples: + - '12345678901' + email: + type: string + format: email + examples: + - maria@email.com + phone_mobile: + type: string + examples: + - (11) 99999-9999 + birth_date: + type: string + format: date + examples: + - '1980-01-15' + social_name: + type: string + examples: + - Maria Santos + sex: + type: string + examples: + - F + blood_type: + type: string + examples: + - A+ + weight_kg: + type: number + examples: + - 65.5 + height_m: + type: number + examples: + - 1.65 + bmi: + type: number + examples: + - 24.1 + street: + type: string + examples: + - Rua das Flores, 123 + number: + type: string + examples: + - '123' + complement: + type: string + examples: + - Apt 45 + neighborhood: + type: string + examples: + - Centro + city: + type: string + examples: + - São Paulo + state: + type: string + examples: + - SP + cep: + type: string + examples: + - 01234-567 + created_at: + type: string + format: date-time + examples: + - '2024-01-15T10:30:00Z' + updated_at: + type: string + format: date-time + examples: + - '2024-01-15T10:30:00Z' + created_by: + type: string + format: uuid + examples: + - 12345678-1234-1234-1234-123456789012 + x-apidog-orders: + - id + - full_name + - cpf + - email + - phone_mobile + - birth_date + - social_name + - sex + - blood_type + - weight_kg + - height_m + - bmi + - street + - number + - complement + - neighborhood + - city + - state + - cep + - created_at + - updated_at + - created_by + x-apidog-ignore-properties: [] + x-apidog-folder: '' + Error: + type: object + properties: + error: + type: string + message: + type: string + code: + type: string + x-apidog-orders: + - error + - message + - code + x-apidog-ignore-properties: [] + x-apidog-folder: '' + securitySchemes: + bearerAuth: + type: jwt + scheme: bearer + bearerFormat: JWT + description: Token JWT obtido no login + bearer: + type: http + scheme: bearer +servers: + - url: https://yuanqfswhberkoevtmfr.supabase.co + description: Prod Env + - url: '' + description: Cloud Mock +security: + - bearer: [] + +``` diff --git a/susconecta/app/(main-routes)/pacientes/page.tsx b/susconecta/app/(main-routes)/pacientes/page.tsx index 6b8193a..76b8682 100644 --- a/susconecta/app/(main-routes)/pacientes/page.tsx +++ b/susconecta/app/(main-routes)/pacientes/page.tsx @@ -12,6 +12,7 @@ import { MoreHorizontal, Plus, Search, Eye, Edit, Trash2, ArrowLeft } from "luci import { Paciente, Endereco, listarPacientes, buscarPacientes, buscarPacientePorId, excluirPaciente } from "@/lib/api"; import { PatientRegistrationForm } from "@/components/forms/patient-registration-form"; +import AssignmentForm from "@/components/admin/AssignmentForm"; function normalizePaciente(p: any): Paciente { @@ -46,6 +47,8 @@ export default function PacientesPage() { const [showForm, setShowForm] = useState(false); const [editingId, setEditingId] = useState(null); const [viewingPatient, setViewingPatient] = useState(null); + const [assignDialogOpen, setAssignDialogOpen] = useState(false); + const [assignPatientId, setAssignPatientId] = useState(null); async function loadAll() { try { @@ -254,6 +257,10 @@ export default function PacientesPage() { Excluir + { setAssignPatientId(String(p.id)); setAssignDialogOpen(true); }}> + + Atribuir profissional + diff --git a/susconecta/components/ProtectedRoute.tsx b/susconecta/components/ProtectedRoute.tsx index ee49112..31e9633 100644 --- a/susconecta/components/ProtectedRoute.tsx +++ b/susconecta/components/ProtectedRoute.tsx @@ -1,5 +1,5 @@ 'use client' -import { useEffect, useRef } from 'react' +import { useEffect, useRef, useState } from 'react' import { useRouter } from 'next/navigation' import { useAuth } from '@/hooks/useAuth' import type { UserType } from '@/types/auth' @@ -17,8 +17,12 @@ export default function ProtectedRoute({ const { authStatus, user } = useAuth() const router = useRouter() const isRedirecting = useRef(false) + const [mounted, setMounted] = useState(false) useEffect(() => { + // marca que o componente já montou no cliente + setMounted(true) + // Evitar múltiplos redirects if (isRedirecting.current) return @@ -85,6 +89,9 @@ export default function ProtectedRoute({ // Durante loading, mostrar spinner if (authStatus === 'loading') { + // evitar render no servidor para não causar mismatch de hidratação + if (!mounted) return null + return (
@@ -97,6 +104,9 @@ export default function ProtectedRoute({ // Se não autenticado ou redirecionando, mostrar spinner if (authStatus === 'unauthenticated' || isRedirecting.current) { + // evitar render no servidor para não causar mismatch de hidratação + if (!mounted) return null + return (
diff --git a/susconecta/components/admin/AssignmentForm.tsx b/susconecta/components/admin/AssignmentForm.tsx new file mode 100644 index 0000000..66e0d2c --- /dev/null +++ b/susconecta/components/admin/AssignmentForm.tsx @@ -0,0 +1,113 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"; +import { Label } from "@/components/ui/label"; +import { Button } from "@/components/ui/button"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; +import { Input } from "@/components/ui/input"; +import { useToast } from "@/hooks/use-toast"; + +import { assignRoleToUser, listAssignmentsForPatient } from "@/lib/assignment"; +import { listarProfissionais } from "@/lib/api"; + +type Props = { + patientId: string; + open: boolean; + onClose: () => void; + onSaved?: () => void; +}; + +export default function AssignmentForm({ patientId, open, onClose, onSaved }: Props) { + const { toast } = useToast(); + const [professionals, setProfessionals] = useState([]); + const [selectedProfessional, setSelectedProfessional] = useState(null); + const [role, setRole] = useState("doctor"); + const [loading, setLoading] = useState(false); + const [existing, setExisting] = useState([]); + + useEffect(() => { + async function load() { + try { + const pros = await listarProfissionais(); + setProfessionals(pros || []); + } catch (e) { + console.warn('Erro ao carregar profissionais', e); + setProfessionals([]); + } + + try { + const a = await listAssignmentsForPatient(patientId); + setExisting(a || []); + } catch (e) { + setExisting([]); + } + } + + if (open) load(); + }, [open, patientId]); + + async function handleSave() { + if (!selectedProfessional) return toast({ title: 'Selecione um profissional', variant: 'warning' }); + setLoading(true); + try { + await assignRoleToUser({ patient_id: patientId, user_id: selectedProfessional, role }); + toast({ title: 'Atribuição criada', variant: 'success' }); + onSaved && onSaved(); + onClose(); + } catch (err: any) { + console.error(err); + toast({ title: 'Erro ao criar atribuição', description: err?.message }); + } finally { + setLoading(false); + } + } + + return ( + { if (!v) onClose(); }}> + + + Atribuir profissional ao paciente + + +
+
+ + +
+ +
+ + setRole(e.target.value)} /> +
Ex: doctor, nurse
+
+ + {existing && existing.length > 0 && ( +
+ +
    + {existing.map((it) => ( +
  • {it.user_id} — {it.role}
  • + ))} +
+
+ )} +
+ + + + + +
+
+ ); +} diff --git a/susconecta/lib/api.ts b/susconecta/lib/api.ts index 05bcad8..2554f2f 100644 --- a/susconecta/lib/api.ts +++ b/susconecta/lib/api.ts @@ -1481,12 +1481,67 @@ export async function uploadFotoMedico(_id: string | number, _file: File): Promi export async function removerFotoMedico(_id: string | number): Promise {} // ===== PERFIS DE USUÁRIOS ===== -export async function listarPerfis(): Promise { - const url = `https://yuanq1/1053378-0-default/rest/v1/profiles`; +export async function listarPerfis(params?: { page?: number; limit?: number; q?: string; }): Promise { + const qs = new URLSearchParams(); + if (params?.q) qs.set('q', params.q); + const url = `${REST}/profiles${qs.toString() ? `?${qs.toString()}` : ''}`; const res = await fetch(url, { - method: "GET", - headers: baseHeaders(), + method: 'GET', + headers: { ...baseHeaders(), ...rangeHeaders(params?.page, params?.limit) }, }); return await parse(res); } +export async function buscarPerfilPorId(id: string | number): Promise { + const idParam = String(id); + const headers = baseHeaders(); + + // 1) tentar por id + try { + const url = `${REST}/profiles?id=eq.${encodeURIComponent(idParam)}`; + const arr = await fetchWithFallback(url, headers); + if (arr && arr.length) return arr[0]; + } catch (e) { + // continuar para próxima estratégia + } + + // 2) tentar por full_name quando for string legível + if (typeof id === 'string' && isNaN(Number(id))) { + const q = encodeURIComponent(String(id)); + const url = `${REST}/profiles?full_name=ilike.*${q}*&limit=5`; + const alt = `${REST}/profiles?email=ilike.*${q}*&limit=5`; + const arr2 = await fetchWithFallback(url, headers, [alt]); + if (arr2 && arr2.length) return arr2[0]; + } + + throw new Error('404: Perfil não encontrado'); +} + +export async function criarPerfil(input: ProfileInput): Promise { + const url = `${REST}/profiles`; + const res = await fetch(url, { + method: 'POST', + headers: withPrefer({ ...baseHeaders(), 'Content-Type': 'application/json' }, 'return=representation'), + body: JSON.stringify(input), + }); + const arr = await parse(res); + return Array.isArray(arr) ? arr[0] : (arr as Profile); +} + +export async function atualizarPerfil(id: string | number, input: ProfileInput): Promise { + const url = `${REST}/profiles?id=eq.${id}`; + const res = await fetch(url, { + method: 'PATCH', + headers: withPrefer({ ...baseHeaders(), 'Content-Type': 'application/json' }, 'return=representation'), + body: JSON.stringify(input), + }); + const arr = await parse(res); + return Array.isArray(arr) ? arr[0] : (arr as Profile); +} + +export async function excluirPerfil(id: string | number): Promise { + const url = `${REST}/profiles?id=eq.${id}`; + const res = await fetch(url, { method: 'DELETE', headers: baseHeaders() }); + await parse(res); +} +