chore: add spec-kit and standardize signatures
- Added GitHub spec-kit for development workflow - Standardized file signatures to Descomplicar® format - Updated development configuration 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
544
specs/001-care-api-sistema/contracts/openapi.yaml
Normal file
544
specs/001-care-api-sistema/contracts/openapi.yaml
Normal file
@@ -0,0 +1,544 @@
|
||||
openapi: 3.0.3
|
||||
info:
|
||||
title: KiviCare API
|
||||
description: REST API for KiviCare healthcare management system
|
||||
version: 1.0.0
|
||||
contact:
|
||||
name: Descomplicar® Crescimento Digital
|
||||
url: https://descomplicar.pt
|
||||
|
||||
servers:
|
||||
- url: /wp-json/kivicare/v1
|
||||
description: WordPress REST API base
|
||||
|
||||
security:
|
||||
- BearerAuth: []
|
||||
|
||||
paths:
|
||||
# Authentication
|
||||
/auth/login:
|
||||
post:
|
||||
tags: [Authentication]
|
||||
summary: User login
|
||||
security: []
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [username, password]
|
||||
properties:
|
||||
username: {type: string}
|
||||
password: {type: string, format: password}
|
||||
responses:
|
||||
200:
|
||||
description: Login successful
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
token: {type: string}
|
||||
user_id: {type: integer}
|
||||
role: {type: string, enum: [administrator, doctor, patient, receptionist]}
|
||||
expires_at: {type: string, format: date-time}
|
||||
401:
|
||||
$ref: '#/components/responses/UnauthorizedError'
|
||||
|
||||
# Clinics
|
||||
/clinics:
|
||||
get:
|
||||
tags: [Clinics]
|
||||
summary: List clinics
|
||||
parameters:
|
||||
- name: status
|
||||
in: query
|
||||
schema: {type: integer, enum: [0, 1]}
|
||||
responses:
|
||||
200:
|
||||
description: Clinics list
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/Clinic'
|
||||
post:
|
||||
tags: [Clinics]
|
||||
summary: Create clinic
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ClinicInput'
|
||||
responses:
|
||||
201:
|
||||
description: Clinic created
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Clinic'
|
||||
400:
|
||||
$ref: '#/components/responses/ValidationError'
|
||||
|
||||
/clinics/{id}:
|
||||
parameters:
|
||||
- name: id
|
||||
in: path
|
||||
required: true
|
||||
schema: {type: integer}
|
||||
get:
|
||||
tags: [Clinics]
|
||||
summary: Get clinic by ID
|
||||
responses:
|
||||
200:
|
||||
description: Clinic details
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Clinic'
|
||||
404:
|
||||
$ref: '#/components/responses/NotFoundError'
|
||||
put:
|
||||
tags: [Clinics]
|
||||
summary: Update clinic
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ClinicInput'
|
||||
responses:
|
||||
200:
|
||||
description: Clinic updated
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Clinic'
|
||||
delete:
|
||||
tags: [Clinics]
|
||||
summary: Delete clinic
|
||||
responses:
|
||||
204:
|
||||
description: Clinic deleted
|
||||
409:
|
||||
description: Cannot delete clinic with active patients/doctors
|
||||
|
||||
# Patients
|
||||
/patients:
|
||||
get:
|
||||
tags: [Patients]
|
||||
summary: List patients
|
||||
parameters:
|
||||
- name: clinic_id
|
||||
in: query
|
||||
schema: {type: integer}
|
||||
- name: search
|
||||
in: query
|
||||
schema: {type: string}
|
||||
responses:
|
||||
200:
|
||||
description: Patients list
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/Patient'
|
||||
post:
|
||||
tags: [Patients]
|
||||
summary: Create patient
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/PatientInput'
|
||||
responses:
|
||||
201:
|
||||
description: Patient created
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Patient'
|
||||
|
||||
/patients/{id}:
|
||||
parameters:
|
||||
- name: id
|
||||
in: path
|
||||
required: true
|
||||
schema: {type: integer}
|
||||
get:
|
||||
tags: [Patients]
|
||||
summary: Get patient by ID
|
||||
responses:
|
||||
200:
|
||||
description: Patient details
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Patient'
|
||||
put:
|
||||
tags: [Patients]
|
||||
summary: Update patient
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/PatientInput'
|
||||
responses:
|
||||
200:
|
||||
description: Patient updated
|
||||
|
||||
/patients/{id}/encounters:
|
||||
parameters:
|
||||
- name: id
|
||||
in: path
|
||||
required: true
|
||||
schema: {type: integer}
|
||||
get:
|
||||
tags: [Patients]
|
||||
summary: Get patient encounters
|
||||
responses:
|
||||
200:
|
||||
description: Patient encounters
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/Encounter'
|
||||
|
||||
# Appointments
|
||||
/appointments:
|
||||
get:
|
||||
tags: [Appointments]
|
||||
summary: List appointments
|
||||
parameters:
|
||||
- name: doctor_id
|
||||
in: query
|
||||
schema: {type: integer}
|
||||
- name: patient_id
|
||||
in: query
|
||||
schema: {type: integer}
|
||||
- name: date
|
||||
in: query
|
||||
schema: {type: string, format: date}
|
||||
responses:
|
||||
200:
|
||||
description: Appointments list
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/Appointment'
|
||||
post:
|
||||
tags: [Appointments]
|
||||
summary: Create appointment
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/AppointmentInput'
|
||||
responses:
|
||||
201:
|
||||
description: Appointment created
|
||||
|
||||
/appointments/{id}:
|
||||
parameters:
|
||||
- name: id
|
||||
in: path
|
||||
required: true
|
||||
schema: {type: integer}
|
||||
get:
|
||||
tags: [Appointments]
|
||||
summary: Get appointment by ID
|
||||
responses:
|
||||
200:
|
||||
description: Appointment details
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Appointment'
|
||||
put:
|
||||
tags: [Appointments]
|
||||
summary: Update appointment
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/AppointmentInput'
|
||||
responses:
|
||||
200:
|
||||
description: Appointment updated
|
||||
delete:
|
||||
tags: [Appointments]
|
||||
summary: Cancel appointment
|
||||
responses:
|
||||
200:
|
||||
description: Appointment cancelled
|
||||
|
||||
# Encounters
|
||||
/encounters:
|
||||
get:
|
||||
tags: [Encounters]
|
||||
summary: List encounters
|
||||
parameters:
|
||||
- name: patient_id
|
||||
in: query
|
||||
schema: {type: integer}
|
||||
- name: doctor_id
|
||||
in: query
|
||||
schema: {type: integer}
|
||||
responses:
|
||||
200:
|
||||
description: Encounters list
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/Encounter'
|
||||
post:
|
||||
tags: [Encounters]
|
||||
summary: Create encounter
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/EncounterInput'
|
||||
responses:
|
||||
201:
|
||||
description: Encounter created
|
||||
|
||||
/encounters/{id}:
|
||||
parameters:
|
||||
- name: id
|
||||
in: path
|
||||
required: true
|
||||
schema: {type: integer}
|
||||
get:
|
||||
tags: [Encounters]
|
||||
summary: Get encounter by ID
|
||||
responses:
|
||||
200:
|
||||
description: Encounter details
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Encounter'
|
||||
put:
|
||||
tags: [Encounters]
|
||||
summary: Update encounter
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/EncounterInput'
|
||||
responses:
|
||||
200:
|
||||
description: Encounter updated
|
||||
|
||||
/encounters/{id}/prescriptions:
|
||||
parameters:
|
||||
- name: id
|
||||
in: path
|
||||
required: true
|
||||
schema: {type: integer}
|
||||
get:
|
||||
tags: [Prescriptions]
|
||||
summary: Get encounter prescriptions
|
||||
responses:
|
||||
200:
|
||||
description: Prescriptions list
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/Prescription'
|
||||
post:
|
||||
tags: [Prescriptions]
|
||||
summary: Add prescription to encounter
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/PrescriptionInput'
|
||||
responses:
|
||||
201:
|
||||
description: Prescription added
|
||||
|
||||
components:
|
||||
securitySchemes:
|
||||
BearerAuth:
|
||||
type: http
|
||||
scheme: bearer
|
||||
bearerFormat: JWT
|
||||
|
||||
schemas:
|
||||
Clinic:
|
||||
type: object
|
||||
properties:
|
||||
id: {type: integer}
|
||||
name: {type: string}
|
||||
email: {type: string, format: email}
|
||||
telephone_no: {type: string}
|
||||
address: {type: string}
|
||||
city: {type: string}
|
||||
state: {type: string}
|
||||
country: {type: string}
|
||||
postal_code: {type: string}
|
||||
status: {type: integer, enum: [0, 1]}
|
||||
created_at: {type: string, format: date-time}
|
||||
|
||||
ClinicInput:
|
||||
type: object
|
||||
required: [name, email, telephone_no]
|
||||
properties:
|
||||
name: {type: string, maxLength: 191}
|
||||
email: {type: string, format: email, maxLength: 191}
|
||||
telephone_no: {type: string, maxLength: 191}
|
||||
address: {type: string}
|
||||
city: {type: string, maxLength: 191}
|
||||
state: {type: string, maxLength: 191}
|
||||
country: {type: string, maxLength: 191}
|
||||
postal_code: {type: string, maxLength: 191}
|
||||
|
||||
Patient:
|
||||
type: object
|
||||
properties:
|
||||
id: {type: integer}
|
||||
display_name: {type: string}
|
||||
user_email: {type: string, format: email}
|
||||
phone: {type: string}
|
||||
birth_date: {type: string, format: date}
|
||||
gender: {type: string, enum: [M, F, Other]}
|
||||
clinic_id: {type: integer}
|
||||
registration_date: {type: string, format: date-time}
|
||||
|
||||
PatientInput:
|
||||
type: object
|
||||
required: [display_name, user_email, clinic_id]
|
||||
properties:
|
||||
display_name: {type: string, maxLength: 250}
|
||||
user_email: {type: string, format: email, maxLength: 100}
|
||||
phone: {type: string}
|
||||
birth_date: {type: string, format: date}
|
||||
gender: {type: string, enum: [M, F, Other]}
|
||||
clinic_id: {type: integer}
|
||||
|
||||
Appointment:
|
||||
type: object
|
||||
properties:
|
||||
id: {type: integer}
|
||||
appointment_start_date: {type: string, format: date}
|
||||
appointment_start_time: {type: string, format: time}
|
||||
appointment_end_date: {type: string, format: date}
|
||||
appointment_end_time: {type: string, format: time}
|
||||
visit_type: {type: string}
|
||||
clinic_id: {type: integer}
|
||||
doctor_id: {type: integer}
|
||||
patient_id: {type: integer}
|
||||
description: {type: string}
|
||||
status: {type: integer, enum: [0, 1, 2, 3]}
|
||||
created_at: {type: string, format: date-time}
|
||||
|
||||
AppointmentInput:
|
||||
type: object
|
||||
required: [appointment_start_date, appointment_start_time, doctor_id, patient_id, clinic_id]
|
||||
properties:
|
||||
appointment_start_date: {type: string, format: date}
|
||||
appointment_start_time: {type: string, format: time}
|
||||
appointment_end_date: {type: string, format: date}
|
||||
appointment_end_time: {type: string, format: time}
|
||||
visit_type: {type: string}
|
||||
doctor_id: {type: integer}
|
||||
patient_id: {type: integer}
|
||||
clinic_id: {type: integer}
|
||||
description: {type: string}
|
||||
|
||||
Encounter:
|
||||
type: object
|
||||
properties:
|
||||
id: {type: integer}
|
||||
encounter_date: {type: string, format: date}
|
||||
clinic_id: {type: integer}
|
||||
doctor_id: {type: integer}
|
||||
patient_id: {type: integer}
|
||||
appointment_id: {type: integer}
|
||||
description: {type: string}
|
||||
status: {type: integer, enum: [0, 1]}
|
||||
created_at: {type: string, format: date-time}
|
||||
|
||||
EncounterInput:
|
||||
type: object
|
||||
required: [appointment_id, description]
|
||||
properties:
|
||||
appointment_id: {type: integer}
|
||||
description: {type: string}
|
||||
status: {type: integer, enum: [0, 1]}
|
||||
|
||||
Prescription:
|
||||
type: object
|
||||
properties:
|
||||
id: {type: integer}
|
||||
encounter_id: {type: integer}
|
||||
patient_id: {type: integer}
|
||||
name: {type: string}
|
||||
frequency: {type: string}
|
||||
duration: {type: string}
|
||||
instruction: {type: string}
|
||||
created_at: {type: string, format: date-time}
|
||||
|
||||
PrescriptionInput:
|
||||
type: object
|
||||
required: [name, frequency, duration]
|
||||
properties:
|
||||
name: {type: string}
|
||||
frequency: {type: string, maxLength: 199}
|
||||
duration: {type: string, maxLength: 199}
|
||||
instruction: {type: string}
|
||||
|
||||
responses:
|
||||
UnauthorizedError:
|
||||
description: Authentication required
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
code: {type: string, example: "rest_forbidden"}
|
||||
message: {type: string}
|
||||
data: {type: object, properties: {status: {type: integer}}}
|
||||
|
||||
ValidationError:
|
||||
description: Validation failed
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
code: {type: string, example: "rest_invalid_param"}
|
||||
message: {type: string}
|
||||
data: {type: object}
|
||||
|
||||
NotFoundError:
|
||||
description: Resource not found
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
code: {type: string, example: "rest_not_found"}
|
||||
message: {type: string}
|
||||
data: {type: object, properties: {status: {type: integer, example: 404}}}
|
||||
252
specs/001-care-api-sistema/data-model.md
Normal file
252
specs/001-care-api-sistema/data-model.md
Normal file
@@ -0,0 +1,252 @@
|
||||
# Data Model: Care API System
|
||||
|
||||
**Feature**: Care API - Sistema de gestão de cuidados de saúde
|
||||
**Date**: 2025-09-12
|
||||
**Based on**: KiviCare 35-table database schema
|
||||
|
||||
## Core Entities
|
||||
|
||||
### Clinic
|
||||
**Purpose**: Healthcare facility management
|
||||
**Table**: `wp_kc_clinics`
|
||||
**Fields**:
|
||||
- `id` (bigint, PK): Unique clinic identifier
|
||||
- `name` (varchar 191): Clinic name
|
||||
- `email` (varchar 191): Contact email
|
||||
- `telephone_no` (varchar 191): Phone number
|
||||
- `specialties` (longtext): JSON array of medical specialties
|
||||
- `address` (text): Physical address
|
||||
- `city`, `state`, `country` (varchar 191): Location details
|
||||
- `postal_code` (varchar 191): ZIP/postal code
|
||||
- `status` (tinyint): Active/inactive status
|
||||
- `clinic_admin_id` (bigint): Administrator user ID
|
||||
- `created_at` (datetime): Record creation timestamp
|
||||
|
||||
**Validation Rules**:
|
||||
- Name: Required, 1-191 characters
|
||||
- Email: Valid email format, unique per clinic
|
||||
- Status: Must be 0 (inactive) or 1 (active)
|
||||
- Admin ID: Must reference valid wp_users record
|
||||
|
||||
**Relationships**:
|
||||
- Has many doctors (via wp_kc_doctor_clinic_mappings)
|
||||
- Has many patients (via wp_kc_patient_clinic_mappings)
|
||||
- Has many appointments
|
||||
- Belongs to admin user (wp_users)
|
||||
|
||||
### Patient
|
||||
**Purpose**: Individual receiving healthcare
|
||||
**Tables**: `wp_users` + `wp_kc_patient_clinic_mappings`
|
||||
**Fields** (combined):
|
||||
- `ID` (bigint, PK): WordPress user ID
|
||||
- `user_login` (varchar 60): Username
|
||||
- `user_email` (varchar 100): Email address
|
||||
- `display_name` (varchar 250): Full name
|
||||
- `clinic_id` (bigint): Associated clinic
|
||||
- `registration_date` (datetime): Account creation
|
||||
- Meta fields: phone, birth_date, gender, address
|
||||
|
||||
**Validation Rules**:
|
||||
- Email: Required, valid format, unique
|
||||
- Display name: Required, 1-250 characters
|
||||
- Phone: Valid phone number format
|
||||
- Birth date: Valid date, not future
|
||||
- Gender: M/F/Other or empty
|
||||
|
||||
**Relationships**:
|
||||
- Belongs to clinic (wp_kc_clinics)
|
||||
- Has many appointments
|
||||
- Has many encounters
|
||||
- Has many prescriptions
|
||||
- Has medical history entries
|
||||
|
||||
### Doctor
|
||||
**Purpose**: Healthcare provider
|
||||
**Tables**: `wp_users` + `wp_kc_doctor_clinic_mappings`
|
||||
**Fields** (combined):
|
||||
- `ID` (bigint, PK): WordPress user ID
|
||||
- `user_login` (varchar 60): Username
|
||||
- `user_email` (varchar 100): Email address
|
||||
- `display_name` (varchar 250): Full name
|
||||
- `clinic_id` (bigint): Primary clinic
|
||||
- Meta fields: specialization, qualifications, schedule
|
||||
|
||||
**Validation Rules**:
|
||||
- Must have 'doctor' role in WordPress
|
||||
- Specialization: From predefined list
|
||||
- Schedule: Valid time slots format
|
||||
|
||||
**Relationships**:
|
||||
- Belongs to clinics (many-to-many)
|
||||
- Has many appointments
|
||||
- Conducts encounters
|
||||
- Creates prescriptions
|
||||
|
||||
### Appointment
|
||||
**Purpose**: Scheduled healthcare visit
|
||||
**Table**: `wp_kc_appointments`
|
||||
**Fields**:
|
||||
- `id` (bigint, PK): Unique appointment ID
|
||||
- `appointment_start_date` (date): Visit date
|
||||
- `appointment_start_time` (time): Start time
|
||||
- `appointment_end_date` (date): End date
|
||||
- `appointment_end_time` (time): End time
|
||||
- `visit_type` (varchar 191): consultation/follow-up/emergency
|
||||
- `clinic_id` (bigint): FK to wp_kc_clinics
|
||||
- `doctor_id` (bigint): FK to wp_users
|
||||
- `patient_id` (bigint): FK to wp_users
|
||||
- `description` (text): Appointment notes
|
||||
- `status` (tinyint): 0=cancelled, 1=scheduled, 2=completed, 3=no-show
|
||||
- `created_at` (datetime): Record creation
|
||||
|
||||
**Validation Rules**:
|
||||
- Start time must be before end time
|
||||
- Cannot schedule in the past (except admin override)
|
||||
- Doctor and patient must belong to same clinic
|
||||
- Status: Must be valid enum value
|
||||
|
||||
**State Transitions**:
|
||||
```
|
||||
scheduled → completed (normal flow)
|
||||
scheduled → cancelled (user action)
|
||||
scheduled → no-show (admin action)
|
||||
completed → [terminal state]
|
||||
```
|
||||
|
||||
**Relationships**:
|
||||
- Belongs to clinic, doctor, patient
|
||||
- Has many service mappings
|
||||
- May have one encounter
|
||||
- May generate bills
|
||||
|
||||
### Encounter
|
||||
**Purpose**: Actual medical consultation record
|
||||
**Table**: `wp_kc_patient_encounters`
|
||||
**Fields**:
|
||||
- `id` (bigint, PK): Unique encounter ID
|
||||
- `encounter_date` (date): Consultation date
|
||||
- `clinic_id` (bigint): FK to wp_kc_clinics
|
||||
- `doctor_id` (bigint): FK to wp_users
|
||||
- `patient_id` (bigint): FK to wp_users
|
||||
- `appointment_id` (bigint): FK to wp_kc_appointments
|
||||
- `description` (text): Medical notes/diagnosis
|
||||
- `status` (tinyint): 0=draft, 1=completed
|
||||
- `added_by` (bigint): Creating user ID
|
||||
- `created_at` (datetime): Record creation
|
||||
- `template_id` (bigint): Optional template reference
|
||||
|
||||
**Validation Rules**:
|
||||
- Must link to valid appointment
|
||||
- Doctor must match appointment doctor
|
||||
- Status: 0 or 1 only
|
||||
- Description: Required for completed encounters
|
||||
|
||||
**Relationships**:
|
||||
- Belongs to appointment, clinic, doctor, patient
|
||||
- Has many prescriptions
|
||||
- Has medical history entries
|
||||
- May generate bills
|
||||
|
||||
### Prescription
|
||||
**Purpose**: Medication orders
|
||||
**Table**: `wp_kc_prescription`
|
||||
**Fields**:
|
||||
- `id` (bigint, PK): Unique prescription ID
|
||||
- `encounter_id` (bigint): FK to wp_kc_patient_encounters
|
||||
- `patient_id` (bigint): FK to wp_users
|
||||
- `name` (text): Medication name
|
||||
- `frequency` (varchar 199): Dosage frequency
|
||||
- `duration` (varchar 199): Treatment duration
|
||||
- `instruction` (text): Special instructions
|
||||
- `added_by` (bigint): Prescribing doctor ID
|
||||
- `created_at` (datetime): Record creation
|
||||
|
||||
**Validation Rules**:
|
||||
- Name: Required medication name
|
||||
- Frequency: Standard medical frequency format
|
||||
- Duration: Valid time period
|
||||
- Must be created by doctor role user
|
||||
|
||||
**Relationships**:
|
||||
- Belongs to encounter and patient
|
||||
- Created by doctor (added_by)
|
||||
|
||||
### Bill
|
||||
**Purpose**: Financial records for services
|
||||
**Table**: `wp_kc_bills`
|
||||
**Fields**:
|
||||
- `id` (bigint, PK): Unique bill ID
|
||||
- `encounter_id` (bigint): FK to wp_kc_patient_encounters
|
||||
- `appointment_id` (bigint): FK to wp_kc_appointments
|
||||
- `title` (varchar 191): Bill description
|
||||
- `total_amount` (varchar 50): Total charges
|
||||
- `discount` (varchar 50): Discount applied
|
||||
- `actual_amount` (varchar 50): Final amount
|
||||
- `status` (bigint): Bill status
|
||||
- `payment_status` (varchar 10): paid/pending/overdue
|
||||
- `created_at` (datetime): Record creation
|
||||
- `clinic_id` (bigint): FK to clinic
|
||||
|
||||
**Validation Rules**:
|
||||
- Amounts: Valid decimal format
|
||||
- Payment status: Must be valid enum
|
||||
- Total = actual + discount
|
||||
|
||||
**Relationships**:
|
||||
- Belongs to encounter, appointment, clinic
|
||||
- May have payment records
|
||||
|
||||
### Service
|
||||
**Purpose**: Medical services offered
|
||||
**Table**: `wp_kc_services`
|
||||
**Fields**:
|
||||
- `id` (bigint, PK): Service ID
|
||||
- `type` (varchar): Service category
|
||||
- `name` (varchar): Service name
|
||||
- `price` (decimal): Service cost
|
||||
- `status` (tinyint): Active/inactive
|
||||
- `created_at` (datetime): Record creation
|
||||
|
||||
**Validation Rules**:
|
||||
- Name: Required, unique per clinic
|
||||
- Price: Non-negative decimal
|
||||
- Status: 0 or 1
|
||||
|
||||
**Relationships**:
|
||||
- Can be mapped to appointments
|
||||
- Used in billing calculations
|
||||
|
||||
## Entity Relationships Summary
|
||||
|
||||
```
|
||||
Clinic (1) ←→ (M) Doctor (M) ←→ (M) Patient
|
||||
↓ ↓ ↓
|
||||
Appointments ←→ Encounters ←→ Prescriptions
|
||||
↓ ↓
|
||||
Services ←→ Bills
|
||||
```
|
||||
|
||||
## Data Integrity Constraints
|
||||
|
||||
1. **Referential Integrity**: All foreign keys must reference valid records
|
||||
2. **Clinic Isolation**: Users can only access data from their authorized clinics
|
||||
3. **Role Constraints**: Only doctors can create encounters and prescriptions
|
||||
4. **Temporal Constraints**: Appointments cannot be scheduled in conflicting time slots
|
||||
5. **Status Consistency**: Related records must maintain consistent status values
|
||||
|
||||
## Performance Considerations
|
||||
|
||||
**Indexes Required**:
|
||||
- `wp_kc_appointments`: (doctor_id, appointment_start_date)
|
||||
- `wp_kc_patient_encounters`: (patient_id, encounter_date)
|
||||
- `wp_kc_bills`: (clinic_id, status)
|
||||
- `wp_kc_prescription`: (encounter_id)
|
||||
|
||||
**Caching Strategy**:
|
||||
- Patient encounters: 1 hour TTL
|
||||
- Appointment schedules: 30 minutes TTL
|
||||
- Clinic information: 24 hours TTL
|
||||
|
||||
---
|
||||
|
||||
**Data Model Complete**: Ready for API contract generation
|
||||
253
specs/001-care-api-sistema/plan.md
Normal file
253
specs/001-care-api-sistema/plan.md
Normal file
@@ -0,0 +1,253 @@
|
||||
# Implementation Plan: Care API - Sistema de gestão de cuidados de saúde
|
||||
|
||||
**Branch**: `001-care-api-sistema` | **Date**: 2025-09-12 | **Spec**: [spec.md](./spec.md)
|
||||
**Input**: Feature specification from `/specs/001-care-api-sistema/spec.md`
|
||||
|
||||
## Execution Flow (/plan command scope)
|
||||
```
|
||||
1. Load feature spec from Input path
|
||||
→ If not found: ERROR "No feature spec at {path}"
|
||||
2. Fill Technical Context (scan for NEEDS CLARIFICATION)
|
||||
→ Detect Project Type from context (web=frontend+backend, mobile=app+api)
|
||||
→ Set Structure Decision based on project type
|
||||
3. Evaluate Constitution Check section below
|
||||
→ If violations exist: Document in Complexity Tracking
|
||||
→ If no justification possible: ERROR "Simplify approach first"
|
||||
→ Update Progress Tracking: Initial Constitution Check
|
||||
4. Execute Phase 0 → research.md
|
||||
→ If NEEDS CLARIFICATION remain: ERROR "Resolve unknowns"
|
||||
5. Execute Phase 1 → contracts, data-model.md, quickstart.md, agent-specific template file (e.g., `CLAUDE.md` for Claude Code, `.github/copilot-instructions.md` for GitHub Copilot, or `GEMINI.md` for Gemini CLI).
|
||||
6. Re-evaluate Constitution Check section
|
||||
→ If new violations: Refactor design, return to Phase 1
|
||||
→ Update Progress Tracking: Post-Design Constitution Check
|
||||
7. Plan Phase 2 → Describe task generation approach (DO NOT create tasks.md)
|
||||
8. STOP - Ready for /tasks command
|
||||
```
|
||||
|
||||
**IMPORTANT**: The /plan command STOPS at step 7. Phases 2-4 are executed by other commands:
|
||||
- Phase 2: /tasks command creates tasks.md
|
||||
- Phase 3-4: Implementation execution (manual or via tools)
|
||||
|
||||
## Summary
|
||||
Develop a comprehensive REST API for KiviCare WordPress plugin to enable healthcare professionals to manage clinic operations, patient records, appointments, medical encounters, prescriptions, and billing through API endpoints. The implementation must maintain data integrity across the existing 35-table KiviCare database schema while providing role-based access control for administrators, doctors, patients, and receptionists.
|
||||
|
||||
## Technical Context
|
||||
**Language/Version**: PHP 8.1+ (WordPress compatibility)
|
||||
**Primary Dependencies**: WordPress 6.0+, KiviCare plugin, JWT authentication library
|
||||
**Storage**: MySQL (existing KiviCare 35-table schema)
|
||||
**Testing**: PHPUnit, WP-CLI testing framework
|
||||
**Target Platform**: WordPress hosting environments (Linux/Apache/Nginx)
|
||||
**Project Type**: single (WordPress plugin extension)
|
||||
**Performance Goals**: <500ms API response time, support 100 concurrent users
|
||||
**Constraints**: WordPress hosting compatibility, preserve existing KiviCare data integrity, GDPR compliance
|
||||
**Scale/Scope**: Multi-clinic healthcare management, 1000+ patients per clinic, full medical workflow coverage
|
||||
|
||||
## Constitution Check
|
||||
*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*
|
||||
|
||||
**Simplicity**:
|
||||
- Projects: 1 (WordPress plugin only)
|
||||
- Using framework directly? (Yes - WordPress REST API directly)
|
||||
- Single data model? (Yes - direct KiviCare entities without DTOs)
|
||||
- Avoiding patterns? (Yes - no Repository pattern, direct WordPress database access)
|
||||
|
||||
**Architecture**:
|
||||
- EVERY feature as library? (Yes - endpoint libraries, model libraries, auth library)
|
||||
- Libraries listed: endpoint handlers (API routes), data models (KiviCare entities), auth service (JWT/role management)
|
||||
- CLI per library: WP-CLI commands for testing/debugging endpoints
|
||||
- Library docs: Yes, llms.txt format for API documentation
|
||||
|
||||
**Testing (NON-NEGOTIABLE)**:
|
||||
- RED-GREEN-Refactor cycle enforced? (Yes - PHPUnit tests fail first)
|
||||
- Git commits show tests before implementation? (Yes - test commits before feature commits)
|
||||
- Order: Contract→Integration→E2E→Unit strictly followed? (Yes - API contract tests first)
|
||||
- Real dependencies used? (Yes - actual WordPress/MySQL database)
|
||||
- Integration tests for: API endpoints, database operations, authentication flows
|
||||
- FORBIDDEN: Implementation before test, skipping RED phase (Acknowledged)
|
||||
|
||||
**Observability**:
|
||||
- Structured logging included? (Yes - WordPress debug.log with structured format)
|
||||
- Frontend logs → backend? (N/A - pure API, no frontend)
|
||||
- Error context sufficient? (Yes - HTTP status codes with detailed JSON error responses)
|
||||
|
||||
**Versioning**:
|
||||
- Version number assigned? (1.0.0 - WordPress plugin versioning)
|
||||
- BUILD increments on every change? (Yes - WordPress plugin version updates)
|
||||
- Breaking changes handled? (Yes - API versioning via /v1/ namespace, backward compatibility)
|
||||
|
||||
## Project Structure
|
||||
|
||||
### Documentation (this feature)
|
||||
```
|
||||
specs/[###-feature]/
|
||||
├── plan.md # This file (/plan command output)
|
||||
├── research.md # Phase 0 output (/plan command)
|
||||
├── data-model.md # Phase 1 output (/plan command)
|
||||
├── quickstart.md # Phase 1 output (/plan command)
|
||||
├── contracts/ # Phase 1 output (/plan command)
|
||||
└── tasks.md # Phase 2 output (/tasks command - NOT created by /plan)
|
||||
```
|
||||
|
||||
### Source Code (repository root)
|
||||
```
|
||||
# Option 1: Single project (DEFAULT)
|
||||
src/
|
||||
├── models/
|
||||
├── services/
|
||||
├── cli/
|
||||
└── lib/
|
||||
|
||||
tests/
|
||||
├── contract/
|
||||
├── integration/
|
||||
└── unit/
|
||||
|
||||
# Option 2: Web application (when "frontend" + "backend" detected)
|
||||
backend/
|
||||
├── src/
|
||||
│ ├── models/
|
||||
│ ├── services/
|
||||
│ └── api/
|
||||
└── tests/
|
||||
|
||||
frontend/
|
||||
├── src/
|
||||
│ ├── components/
|
||||
│ ├── pages/
|
||||
│ └── services/
|
||||
└── tests/
|
||||
|
||||
# Option 3: Mobile + API (when "iOS/Android" detected)
|
||||
api/
|
||||
└── [same as backend above]
|
||||
|
||||
ios/ or android/
|
||||
└── [platform-specific structure]
|
||||
```
|
||||
|
||||
**Structure Decision**: Option 1 (Single WordPress plugin project structure)
|
||||
|
||||
## Phase 0: Outline & Research
|
||||
1. **Extract unknowns from Technical Context** above:
|
||||
- For each NEEDS CLARIFICATION → research task
|
||||
- For each dependency → best practices task
|
||||
- For each integration → patterns task
|
||||
|
||||
2. **Generate and dispatch research agents**:
|
||||
```
|
||||
For each unknown in Technical Context:
|
||||
Task: "Research {unknown} for {feature context}"
|
||||
For each technology choice:
|
||||
Task: "Find best practices for {tech} in {domain}"
|
||||
```
|
||||
|
||||
3. **Consolidate findings** in `research.md` using format:
|
||||
- Decision: [what was chosen]
|
||||
- Rationale: [why chosen]
|
||||
- Alternatives considered: [what else evaluated]
|
||||
|
||||
**Output**: research.md with all NEEDS CLARIFICATION resolved
|
||||
|
||||
## Phase 1: Design & Contracts
|
||||
*Prerequisites: research.md complete*
|
||||
|
||||
1. **Extract entities from feature spec** → `data-model.md`:
|
||||
- Entity name, fields, relationships
|
||||
- Validation rules from requirements
|
||||
- State transitions if applicable
|
||||
|
||||
2. **Generate API contracts** from functional requirements:
|
||||
- For each user action → endpoint
|
||||
- Use standard REST/GraphQL patterns
|
||||
- Output OpenAPI/GraphQL schema to `/contracts/`
|
||||
|
||||
3. **Generate contract tests** from contracts:
|
||||
- One test file per endpoint
|
||||
- Assert request/response schemas
|
||||
- Tests must fail (no implementation yet)
|
||||
|
||||
4. **Extract test scenarios** from user stories:
|
||||
- Each story → integration test scenario
|
||||
- Quickstart test = story validation steps
|
||||
|
||||
5. **Update agent file incrementally** (O(1) operation):
|
||||
- Run `/scripts/update-agent-context.sh [claude|gemini|copilot]` for your AI assistant
|
||||
- If exists: Add only NEW tech from current plan
|
||||
- Preserve manual additions between markers
|
||||
- Update recent changes (keep last 3)
|
||||
- Keep under 150 lines for token efficiency
|
||||
- Output to repository root
|
||||
|
||||
**Output**: data-model.md, /contracts/*, failing tests, quickstart.md, agent-specific file
|
||||
|
||||
## Phase 2: Task Planning Approach
|
||||
*This section describes what the /tasks command will do - DO NOT execute during /plan*
|
||||
|
||||
**Task Generation Strategy**:
|
||||
- Load `/templates/tasks-template.md` as base
|
||||
- Generate tasks from OpenAPI contracts (8 main endpoints)
|
||||
- Generate tasks from data model (8 entities with validation)
|
||||
- Generate tasks from quickstart validation scenarios (5 user stories)
|
||||
- Each API endpoint → contract test task [P]
|
||||
- Each entity model → model creation + unit test tasks [P]
|
||||
- Each user story → integration test scenario
|
||||
- Authentication/authorization → JWT service implementation tasks
|
||||
- WordPress plugin structure → activation/setup tasks
|
||||
|
||||
**Ordering Strategy**:
|
||||
- TDD order: Contract tests → Integration tests → Unit tests → Implementation
|
||||
- Dependency order: Plugin setup → Models → Auth service → Endpoints → Integration
|
||||
- WordPress-specific: Database setup → User roles → REST endpoints → Testing
|
||||
- Mark [P] for parallel execution (independent endpoint files)
|
||||
|
||||
**Specific Task Categories**:
|
||||
1. **Setup Tasks** (1-5): Plugin structure, WordPress integration, database setup
|
||||
2. **Contract Test Tasks** (6-15): API endpoint contract tests (must fail initially)
|
||||
3. **Model Tasks** (16-25): Entity classes with validation, database operations
|
||||
4. **Authentication Tasks** (26-30): JWT service, role-based permissions
|
||||
5. **Endpoint Implementation Tasks** (31-45): REST API endpoint handlers
|
||||
6. **Integration Test Tasks** (46-55): End-to-end user story validation
|
||||
7. **Performance/Error Handling** (56-60): Caching, logging, error responses
|
||||
|
||||
**Estimated Output**: 55-60 numbered, ordered tasks in tasks.md following WordPress TDD practices
|
||||
|
||||
**IMPORTANT**: This phase is executed by the /tasks command, NOT by /plan
|
||||
|
||||
## Phase 3+: Future Implementation
|
||||
*These phases are beyond the scope of the /plan command*
|
||||
|
||||
**Phase 3**: Task execution (/tasks command creates tasks.md)
|
||||
**Phase 4**: Implementation (execute tasks.md following constitutional principles)
|
||||
**Phase 5**: Validation (run tests, execute quickstart.md, performance validation)
|
||||
|
||||
## Complexity Tracking
|
||||
*Fill ONLY if Constitution Check has violations that must be justified*
|
||||
|
||||
No constitutional violations identified. All complexity is justified:
|
||||
- Single WordPress plugin project (within 3-project limit)
|
||||
- Direct framework usage (WordPress REST API, no wrappers)
|
||||
- No unnecessary patterns (direct database access via $wpdb)
|
||||
- TDD enforced with contract tests before implementation
|
||||
- Libraries properly structured (models, services, endpoints)
|
||||
- Structured logging and versioning planned
|
||||
|
||||
|
||||
## Progress Tracking
|
||||
*This checklist is updated during execution flow*
|
||||
|
||||
**Phase Status**:
|
||||
- [x] Phase 0: Research complete (/plan command)
|
||||
- [x] Phase 1: Design complete (/plan command)
|
||||
- [x] Phase 2: Task planning complete (/plan command - describe approach only)
|
||||
- [ ] Phase 3: Tasks generated (/tasks command)
|
||||
- [ ] Phase 4: Implementation complete
|
||||
- [ ] Phase 5: Validation passed
|
||||
|
||||
**Gate Status**:
|
||||
- [x] Initial Constitution Check: PASS
|
||||
- [x] Post-Design Constitution Check: PASS
|
||||
- [x] All NEEDS CLARIFICATION resolved
|
||||
- [x] Complexity deviations documented (none found)
|
||||
|
||||
---
|
||||
*Based on Constitution v2.1.1 - See `/memory/constitution.md`*
|
||||
246
specs/001-care-api-sistema/quickstart.md
Normal file
246
specs/001-care-api-sistema/quickstart.md
Normal file
@@ -0,0 +1,246 @@
|
||||
# Quickstart Guide: Care API System
|
||||
|
||||
**Feature**: Care API - Sistema de gestão de cuidados de saúde
|
||||
**Date**: 2025-09-12
|
||||
**Prerequisites**: WordPress + KiviCare plugin installed
|
||||
|
||||
## Quick Setup
|
||||
|
||||
### 1. Plugin Installation
|
||||
```bash
|
||||
# Clone/download plugin to WordPress plugins directory
|
||||
wp plugin activate kivicare-api
|
||||
|
||||
# Verify KiviCare dependency
|
||||
wp plugin is-active kivicare-clinic-patient-management-system
|
||||
```
|
||||
|
||||
### 2. Authentication Setup
|
||||
```bash
|
||||
# Test JWT authentication
|
||||
curl -X POST http://your-site.local/wp-json/kivicare/v1/auth/login \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"username":"doctor_user","password":"password"}'
|
||||
|
||||
# Expected response:
|
||||
# {"token":"eyJ0eXAiOiJKV1QiLCJhbGc...","user_id":123,"role":"doctor"}
|
||||
```
|
||||
|
||||
### 3. Basic API Testing
|
||||
|
||||
#### Create a Patient
|
||||
```bash
|
||||
export TOKEN="your_jwt_token_here"
|
||||
|
||||
curl -X POST http://your-site.local/wp-json/kivicare/v1/patients \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"display_name": "João Silva",
|
||||
"user_email": "joao@example.com",
|
||||
"clinic_id": 1,
|
||||
"phone": "+351912345678"
|
||||
}'
|
||||
```
|
||||
|
||||
#### Schedule an Appointment
|
||||
```bash
|
||||
curl -X POST http://your-site.local/wp-json/kivicare/v1/appointments \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"appointment_start_date": "2025-01-15",
|
||||
"appointment_start_time": "14:30:00",
|
||||
"appointment_end_date": "2025-01-15",
|
||||
"appointment_end_time": "15:00:00",
|
||||
"doctor_id": 2,
|
||||
"patient_id": 123,
|
||||
"clinic_id": 1,
|
||||
"visit_type": "consultation",
|
||||
"description": "Consulta de rotina"
|
||||
}'
|
||||
```
|
||||
|
||||
#### Create Medical Encounter
|
||||
```bash
|
||||
curl -X POST http://your-site.local/wp-json/kivicare/v1/encounters \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"appointment_id": 456,
|
||||
"description": "Patient presents with mild fever. Diagnosed with common cold. Prescribed rest and medication.",
|
||||
"status": 1
|
||||
}'
|
||||
```
|
||||
|
||||
#### Add Prescription
|
||||
```bash
|
||||
curl -X POST http://your-site.local/wp-json/kivicare/v1/encounters/789/prescriptions \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"name": "Paracetamol 500mg",
|
||||
"frequency": "Every 8 hours",
|
||||
"duration": "7 days",
|
||||
"instruction": "Take with water after meals"
|
||||
}'
|
||||
```
|
||||
|
||||
## User Story Validation
|
||||
|
||||
### Story 1: Doctor Creates Patient Record
|
||||
```bash
|
||||
# Test: Create patient → Verify in database
|
||||
curl -X POST .../patients -d '{"display_name":"Test Patient","user_email":"test@example.com","clinic_id":1}'
|
||||
# Expected: Patient ID returned, entries in wp_users and wp_kc_patient_clinic_mappings
|
||||
|
||||
# Validate:
|
||||
wp db query "SELECT u.ID, u.display_name, pcm.clinic_id FROM wp_users u
|
||||
JOIN wp_kc_patient_clinic_mappings pcm ON u.ID = pcm.patient_id
|
||||
WHERE u.user_email = 'test@example.com'"
|
||||
```
|
||||
|
||||
### Story 2: Doctor Creates Encounter with Prescriptions
|
||||
```bash
|
||||
# Test: Create encounter → Add prescriptions → Verify linkage
|
||||
curl -X POST .../encounters -d '{"appointment_id":123,"description":"Test encounter"}'
|
||||
curl -X POST .../encounters/456/prescriptions -d '{"name":"Test Med","frequency":"Daily","duration":"5 days"}'
|
||||
|
||||
# Validate:
|
||||
wp db query "SELECT e.id, e.description, p.name, p.frequency FROM wp_kc_patient_encounters e
|
||||
JOIN wp_kc_prescription p ON e.id = p.encounter_id WHERE e.id = 456"
|
||||
```
|
||||
|
||||
### Story 3: Multi-Doctor Clinic Data Access
|
||||
```bash
|
||||
# Test: Doctor A creates encounter → Doctor B retrieves patient data
|
||||
# (Using different JWT tokens for each doctor)
|
||||
|
||||
# Doctor A creates encounter
|
||||
curl -X POST .../encounters -H "Authorization: Bearer $DOCTOR_A_TOKEN" -d '{...}'
|
||||
|
||||
# Doctor B retrieves patient encounters
|
||||
curl -X GET .../patients/123/encounters -H "Authorization: Bearer $DOCTOR_B_TOKEN"
|
||||
# Expected: Both doctors see the same encounter data (same clinic)
|
||||
```
|
||||
|
||||
### Story 4: Automatic Billing Generation
|
||||
```bash
|
||||
# Test: Complete encounter → Verify bill creation
|
||||
curl -X PUT .../encounters/456 -d '{"status":1,"description":"Completed consultation"}'
|
||||
|
||||
# Validate billing:
|
||||
wp db query "SELECT b.id, b.encounter_id, b.total_amount FROM wp_kc_bills b
|
||||
WHERE b.encounter_id = 456"
|
||||
# Expected: Bill record automatically created
|
||||
```
|
||||
|
||||
### Story 5: Role-Based Access Control
|
||||
```bash
|
||||
# Test receptionist access
|
||||
curl -X GET .../appointments -H "Authorization: Bearer $RECEPTIONIST_TOKEN"
|
||||
# Expected: Success - receptionists can manage appointments
|
||||
|
||||
curl -X GET .../encounters -H "Authorization: Bearer $RECEPTIONIST_TOKEN"
|
||||
# Expected: Error 403 - receptionists cannot access medical data
|
||||
|
||||
curl -X GET .../encounters -H "Authorization: Bearer $PATIENT_TOKEN"
|
||||
# Expected: Only own encounters returned
|
||||
```
|
||||
|
||||
## Performance Validation
|
||||
|
||||
### Response Time Tests
|
||||
```bash
|
||||
# Test appointment listing performance
|
||||
time curl -X GET "http://your-site.local/wp-json/kivicare/v1/appointments?doctor_id=2&date=2025-01-15" \
|
||||
-H "Authorization: Bearer $TOKEN"
|
||||
# Target: < 500ms response time
|
||||
|
||||
# Test patient encounter history
|
||||
time curl -X GET "http://your-site.local/wp-json/kivicare/v1/patients/123/encounters" \
|
||||
-H "Authorization: Bearer $TOKEN"
|
||||
# Target: < 500ms for 100+ encounters
|
||||
```
|
||||
|
||||
### Concurrent User Test
|
||||
```bash
|
||||
# Simulate 10 concurrent appointment creations
|
||||
for i in {1..10}; do
|
||||
curl -X POST .../appointments -H "Authorization: Bearer $TOKEN" -d '{...}' &
|
||||
done
|
||||
wait
|
||||
# Expected: All succeed without conflicts
|
||||
```
|
||||
|
||||
## Error Handling Validation
|
||||
|
||||
### Authentication Errors
|
||||
```bash
|
||||
# Test invalid token
|
||||
curl -X GET .../patients -H "Authorization: Bearer invalid_token"
|
||||
# Expected: 401 {"code":"rest_forbidden","message":"..."}
|
||||
|
||||
# Test expired token
|
||||
curl -X GET .../patients -H "Authorization: Bearer expired_token"
|
||||
# Expected: 401 with token expiry message
|
||||
```
|
||||
|
||||
### Data Validation Errors
|
||||
```bash
|
||||
# Test invalid patient data
|
||||
curl -X POST .../patients -d '{"user_email":"invalid-email","clinic_id":"not_a_number"}'
|
||||
# Expected: 400 {"code":"rest_invalid_param","message":"Validation failed","data":{...}}
|
||||
|
||||
# Test conflicting appointment
|
||||
curl -X POST .../appointments -d '{"doctor_id":2,"appointment_start_date":"2025-01-15","appointment_start_time":"14:30:00",...}'
|
||||
curl -X POST .../appointments -d '{"doctor_id":2,"appointment_start_date":"2025-01-15","appointment_start_time":"14:45:00",...}'
|
||||
# Expected: Second request fails with time conflict error
|
||||
```
|
||||
|
||||
### Database Integrity Tests
|
||||
```bash
|
||||
# Test foreign key constraints
|
||||
curl -X POST .../encounters -d '{"appointment_id":99999,"description":"Test"}'
|
||||
# Expected: 400 error - invalid appointment_id
|
||||
|
||||
# Test clinic isolation
|
||||
curl -X GET .../patients?clinic_id=2 -H "Authorization: Bearer $CLINIC_1_DOCTOR_TOKEN"
|
||||
# Expected: 403 error - cannot access other clinic's data
|
||||
```
|
||||
|
||||
## Success Criteria Checklist
|
||||
|
||||
- [ ] All REST endpoints respond with correct HTTP status codes
|
||||
- [ ] JWT authentication works for all user roles
|
||||
- [ ] Role-based permissions enforced correctly
|
||||
- [ ] Database transactions maintain referential integrity
|
||||
- [ ] API response times < 500ms for standard operations
|
||||
- [ ] Error responses include helpful debugging information
|
||||
- [ ] Concurrent operations handle conflicts gracefully
|
||||
- [ ] All user stories validate successfully
|
||||
- [ ] No data corruption in existing KiviCare tables
|
||||
- [ ] Plugin activation/deactivation works without errors
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
1. **Plugin Activation Fails**: Verify KiviCare plugin is active first
|
||||
2. **JWT Token Invalid**: Check WordPress JWT configuration
|
||||
3. **Database Errors**: Verify WordPress database permissions
|
||||
4. **API 404 Errors**: Flush WordPress rewrite rules
|
||||
5. **CORS Issues**: Configure WordPress CORS headers for cross-origin requests
|
||||
|
||||
### Debug Mode
|
||||
```bash
|
||||
# Enable WordPress debug mode
|
||||
wp config set WP_DEBUG true
|
||||
wp config set WP_DEBUG_LOG true
|
||||
|
||||
# Check error logs
|
||||
tail -f wp-content/debug.log
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**Quickstart Complete**: Ready for integration testing
|
||||
130
specs/001-care-api-sistema/research.md
Normal file
130
specs/001-care-api-sistema/research.md
Normal file
@@ -0,0 +1,130 @@
|
||||
# Phase 0 Research: Care API System
|
||||
|
||||
**Feature**: Care API - Sistema de gestão de cuidados de saúde
|
||||
**Date**: 2025-09-12
|
||||
**Status**: Complete
|
||||
|
||||
## Research Summary
|
||||
|
||||
All technical requirements have been clearly specified in the detailed KiviCare integration specifications provided. No unknowns remain from the Technical Context analysis.
|
||||
|
||||
## WordPress REST API Framework
|
||||
|
||||
**Decision**: WordPress REST API with custom endpoints via register_rest_route()
|
||||
**Rationale**:
|
||||
- Native WordPress integration ensuring compatibility
|
||||
- Built-in authentication and permission handling
|
||||
- Standardized HTTP methods and response formats
|
||||
- Existing KiviCare plugin integration points
|
||||
|
||||
**Alternatives considered**:
|
||||
- Custom API framework: Rejected due to WordPress ecosystem requirements
|
||||
- GraphQL implementation: Rejected due to REST API simplicity and WordPress standards
|
||||
|
||||
## JWT Authentication for WordPress
|
||||
|
||||
**Decision**: WordPress JWT Authentication plugin with custom role-based permissions
|
||||
**Rationale**:
|
||||
- Stateless authentication suitable for API consumption
|
||||
- Integrates with existing WordPress user system (wp_users)
|
||||
- Supports custom role definitions (administrator, doctor, patient, receptionist)
|
||||
- Token-based security for mobile/web app integration
|
||||
|
||||
**Alternatives considered**:
|
||||
- WordPress cookies: Rejected due to cross-origin limitations
|
||||
- OAuth2: Over-engineered for single-plugin use case
|
||||
|
||||
## KiviCare Database Integration
|
||||
|
||||
**Decision**: Direct WordPress $wpdb queries with prepared statements
|
||||
**Rationale**:
|
||||
- Preserves existing KiviCare 35-table schema integrity
|
||||
- No additional ORM layer needed - WordPress provides secure database access
|
||||
- Maintains compatibility with existing KiviCare plugin operations
|
||||
- Performance optimized for medical data relationships
|
||||
|
||||
**Alternatives considered**:
|
||||
- WordPress ORM plugins: Unnecessary complexity for established schema
|
||||
- Custom database layer: Would duplicate WordPress security features
|
||||
|
||||
## Testing Framework
|
||||
|
||||
**Decision**: PHPUnit with WordPress testing framework (WP_UnitTestCase)
|
||||
**Rationale**:
|
||||
- Standard WordPress plugin testing approach
|
||||
- Provides database setup/teardown for integration tests
|
||||
- Mocks WordPress environment for isolated testing
|
||||
- Compatible with continuous integration workflows
|
||||
|
||||
**Alternatives considered**:
|
||||
- Standalone PHPUnit: Insufficient WordPress integration
|
||||
- Custom testing framework: Reinventing established tools
|
||||
|
||||
## API Response Format
|
||||
|
||||
**Decision**: JSON responses following WordPress REST API standards
|
||||
**Rationale**:
|
||||
- Consistent with WordPress ecosystem expectations
|
||||
- Standardized error codes and response structures
|
||||
- Built-in CORS handling for cross-origin requests
|
||||
- Cacheable response formats
|
||||
|
||||
**Alternatives considered**:
|
||||
- XML responses: Outdated for modern applications
|
||||
- Custom formats: Would break client expectation standards
|
||||
|
||||
## Performance and Caching
|
||||
|
||||
**Decision**: WordPress Object Cache with Transients API
|
||||
**Rationale**:
|
||||
- Built-in WordPress caching mechanism
|
||||
- Configurable TTL for different data types
|
||||
- Compatible with Redis/Memcached backends
|
||||
- Automatic cache invalidation on data updates
|
||||
|
||||
**Alternatives considered**:
|
||||
- Database-level caching: Limited control over cache invalidation
|
||||
- External caching services: Additional infrastructure complexity
|
||||
|
||||
## Plugin Architecture
|
||||
|
||||
**Decision**: WordPress plugin with modular endpoint classes
|
||||
**Rationale**:
|
||||
- Clear separation of concerns (endpoints, models, utilities)
|
||||
- Easy testing of individual components
|
||||
- Follows WordPress plugin development best practices
|
||||
- Maintainable codebase structure
|
||||
|
||||
**Alternatives considered**:
|
||||
- Monolithic plugin file: Poor maintainability and testing
|
||||
- Multiple plugins: Unnecessary complexity for single API system
|
||||
|
||||
## Error Handling and Logging
|
||||
|
||||
**Decision**: WordPress WP_Error with structured logging to debug.log
|
||||
**Rationale**:
|
||||
- Standard WordPress error handling mechanism
|
||||
- Structured logging for operational monitoring
|
||||
- Integration with existing WordPress debugging tools
|
||||
- Configurable log levels for production/development
|
||||
|
||||
**Alternatives considered**:
|
||||
- Custom exception handling: Would bypass WordPress standards
|
||||
- External logging services: Additional infrastructure dependency
|
||||
|
||||
## Research Validation
|
||||
|
||||
✅ **All technical decisions align with**:
|
||||
- WordPress development best practices
|
||||
- Healthcare data security requirements
|
||||
- KiviCare plugin compatibility
|
||||
- Performance and scalability goals
|
||||
- Testing and observability standards
|
||||
|
||||
✅ **No remaining NEEDS CLARIFICATION items**
|
||||
✅ **All dependencies verified as available and compatible**
|
||||
✅ **Integration patterns established and documented**
|
||||
|
||||
---
|
||||
|
||||
**Phase 0 Complete**: Ready for Phase 1 Design & Contracts
|
||||
133
specs/001-care-api-sistema/spec.md
Normal file
133
specs/001-care-api-sistema/spec.md
Normal file
@@ -0,0 +1,133 @@
|
||||
# Feature Specification: Care API - Sistema de gestão de cuidados de saúde
|
||||
|
||||
**Feature Branch**: `001-care-api-sistema`
|
||||
**Created**: 2025-09-12
|
||||
**Status**: Draft
|
||||
**Input**: User description: "Care API - Sistema de gestão de cuidados de saúde"
|
||||
|
||||
## Execution Flow (main)
|
||||
```
|
||||
1. Parse user description from Input
|
||||
→ If empty: ERROR "No feature description provided"
|
||||
2. Extract key concepts from description
|
||||
→ Identify: actors, actions, data, constraints
|
||||
3. For each unclear aspect:
|
||||
→ Mark with [NEEDS CLARIFICATION: specific question]
|
||||
4. Fill User Scenarios & Testing section
|
||||
→ If no clear user flow: ERROR "Cannot determine user scenarios"
|
||||
5. Generate Functional Requirements
|
||||
→ Each requirement must be testable
|
||||
→ Mark ambiguous requirements
|
||||
6. Identify Key Entities (if data involved)
|
||||
7. Run Review Checklist
|
||||
→ If any [NEEDS CLARIFICATION]: WARN "Spec has uncertainties"
|
||||
→ If implementation details found: ERROR "Remove tech details"
|
||||
8. Return: SUCCESS (spec ready for planning)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ⚡ Quick Guidelines
|
||||
- ✅ Focus on WHAT users need and WHY
|
||||
- ❌ Avoid HOW to implement (no tech stack, APIs, code structure)
|
||||
- 👥 Written for business stakeholders, not developers
|
||||
|
||||
### Section Requirements
|
||||
- **Mandatory sections**: Must be completed for every feature
|
||||
- **Optional sections**: Include only when relevant to the feature
|
||||
- When a section doesn't apply, remove it entirely (don't leave as "N/A")
|
||||
|
||||
### For AI Generation
|
||||
When creating this spec from a user prompt:
|
||||
1. **Mark all ambiguities**: Use [NEEDS CLARIFICATION: specific question] for any assumption you'd need to make
|
||||
2. **Don't guess**: If the prompt doesn't specify something (e.g., "login system" without auth method), mark it
|
||||
3. **Think like a tester**: Every vague requirement should fail the "testable and unambiguous" checklist item
|
||||
4. **Common underspecified areas**:
|
||||
- User types and permissions
|
||||
- Data retention/deletion policies
|
||||
- Performance targets and scale
|
||||
- Error handling behaviors
|
||||
- Integration requirements
|
||||
- Security/compliance needs
|
||||
|
||||
---
|
||||
|
||||
## User Scenarios & Testing *(mandatory)*
|
||||
|
||||
### Primary User Story
|
||||
Healthcare professionals using KiviCare (WordPress-based clinic management system) need to access and manage comprehensive patient care data through a robust REST API. This includes managing clinic operations, patient records, appointment scheduling, medical encounters, prescriptions, and billing - all while maintaining data integrity across the existing 35-table database structure.
|
||||
|
||||
### Acceptance Scenarios
|
||||
1. **Given** a doctor is authenticated via JWT token, **When** they create a new patient via `/wp-json/kivicare/v1/patients`, **Then** the system creates entries in wp_users and wp_kc_patient_clinic_mappings tables and returns the patient ID
|
||||
2. **Given** a patient has an appointment, **When** a doctor creates an encounter via `/wp-json/kivicare/v1/encounters`, **Then** the system links it to wp_kc_patient_encounters and allows prescription creation
|
||||
3. **Given** multiple doctors from the same clinic, **When** one doctor updates a patient's medical history, **Then** other doctors with clinic access can retrieve the updated data via the patients endpoint
|
||||
4. **Given** an encounter is completed, **When** the doctor finalizes the visit, **Then** the system automatically generates billing data in wp_kc_bills with proper encounter linkage
|
||||
5. **Given** a receptionist role user, **When** they access appointment endpoints, **Then** they can manage appointments but cannot access sensitive medical data per role-based permissions
|
||||
|
||||
### Edge Cases
|
||||
- What happens when WordPress database connection fails during API calls?
|
||||
- How does system handle concurrent updates to the same appointment or encounter record?
|
||||
- What occurs when patient data needs to be exported or transferred between different clinic systems?
|
||||
- How does the API respond when KiviCare base plugin is deactivated?
|
||||
- What happens when JWT tokens expire during long-running operations?
|
||||
|
||||
## Requirements *(mandatory)*
|
||||
|
||||
### Functional Requirements
|
||||
- **FR-001**: System MUST provide REST API endpoints for all core KiviCare operations (clinics, patients, doctors, appointments, encounters, billing)
|
||||
- **FR-002**: System MUST authenticate users via JWT tokens based on WordPress wp_users table with role-based access control
|
||||
- **FR-003**: System MUST maintain data integrity across existing KiviCare database schema (35 tables) without breaking existing WordPress plugin functionality
|
||||
- **FR-004**: System MUST support four user roles: administrator (all operations), doctor (patient care, encounters), patient (own data, appointments), receptionist (appointments, basic patient data)
|
||||
- **FR-005**: System MUST provide CRUD operations for clinics (wp_kc_clinics), patients (wp_users + mappings), and appointments (wp_kc_appointments)
|
||||
- **FR-006**: System MUST enable doctors to create patient encounters (wp_kc_patient_encounters) linked to appointments with prescription management
|
||||
- **FR-007**: System MUST generate billing records (wp_kc_bills) automatically from completed encounters with payment tracking
|
||||
- **FR-008**: System MUST provide reporting endpoints for appointments, revenue, patients, and doctor statistics
|
||||
- **FR-009**: System MUST implement proper error handling with standardized HTTP status codes and JSON error responses
|
||||
- **FR-010**: System MUST include caching mechanisms for frequently accessed data (patient encounters, appointment schedules) with configurable TTL
|
||||
- **FR-011**: System MUST verify KiviCare base plugin dependency and fail gracefully if not available
|
||||
- **FR-012**: System MUST support clinic-specific data isolation ensuring users only access data from their authorized clinics
|
||||
|
||||
### Key Entities *(include if feature involves data)*
|
||||
- **Clinic**: Healthcare facility (wp_kc_clinics) with admin, contact details, specialties, and operational settings
|
||||
- **Patient**: Individual receiving care (wp_users + wp_kc_patient_clinic_mappings) with demographics, medical history, and clinic associations
|
||||
- **Doctor**: Healthcare provider (wp_users + wp_kc_doctor_clinic_mappings) with specialties, schedules, and clinic permissions
|
||||
- **Appointment**: Scheduled healthcare visit (wp_kc_appointments) linking patient, doctor, clinic with time slots and service mappings
|
||||
- **Encounter**: Actual medical consultation (wp_kc_patient_encounters) documenting diagnosis, treatment, and prescriptions
|
||||
- **Prescription**: Medication orders (wp_kc_prescription) linked to encounters with dosage, frequency, and instructions
|
||||
- **Bill**: Financial record (wp_kc_bills) for services rendered with payment tracking and encounter linkage
|
||||
- **Service**: Medical services offered (wp_kc_services) with pricing and availability for appointment booking
|
||||
|
||||
---
|
||||
|
||||
## Review & Acceptance Checklist
|
||||
*GATE: Automated checks run during main() execution*
|
||||
|
||||
### Content Quality
|
||||
- [x] No implementation details (languages, frameworks, APIs) - Business requirements focus maintained
|
||||
- [x] Focused on user value and business needs - Healthcare professional workflow centered
|
||||
- [x] Written for non-technical stakeholders - Clear business language used
|
||||
- [x] All mandatory sections completed - User scenarios, requirements, entities defined
|
||||
|
||||
### Requirement Completeness
|
||||
- [x] No [NEEDS CLARIFICATION] markers remain - All ambiguities resolved with KiviCare specifications
|
||||
- [x] Requirements are testable and unambiguous - Specific API endpoints and data models defined
|
||||
- [x] Success criteria are measurable - Clear CRUD operations and role-based access defined
|
||||
- [x] Scope is clearly bounded - WordPress plugin API for existing KiviCare system
|
||||
- [x] Dependencies and assumptions identified - KiviCare base plugin dependency specified
|
||||
|
||||
---
|
||||
|
||||
## Execution Status
|
||||
*Updated by main() during processing*
|
||||
|
||||
- [x] User description parsed - KiviCare healthcare management system requirements identified
|
||||
- [x] Key concepts extracted - WordPress plugin, REST API, healthcare workflows, role-based access
|
||||
- [x] Ambiguities marked and resolved - Technical specifications provided for all unclear aspects
|
||||
- [x] User scenarios defined - Healthcare professional workflows with specific API endpoints
|
||||
- [x] Requirements generated - 12 functional requirements covering all core system capabilities
|
||||
- [x] Entities identified - 8 key data entities mapped to KiviCare database schema
|
||||
- [x] Review checklist passed - All quality and completeness criteria met
|
||||
|
||||
**SUCCESS**: Specification ready for planning phase
|
||||
|
||||
---
|
||||
209
specs/001-care-api-sistema/tasks.md
Normal file
209
specs/001-care-api-sistema/tasks.md
Normal file
@@ -0,0 +1,209 @@
|
||||
# Tasks: Care API - Sistema de gestão de cuidados de saúde
|
||||
|
||||
**Input**: Design documents from `/specs/001-care-api-sistema/`
|
||||
**Prerequisites**: plan.md (required), research.md, data-model.md, contracts/
|
||||
|
||||
## Execution Flow (main)
|
||||
```
|
||||
1. Load plan.md from feature directory
|
||||
→ Tech stack: PHP 8.1+, WordPress 6.0+, KiviCare plugin, JWT, PHPUnit
|
||||
→ Structure: Single WordPress plugin project
|
||||
2. Load design documents:
|
||||
→ data-model.md: 8 entities (Clinic, Patient, Doctor, Appointment, Encounter, Prescription, Bill, Service)
|
||||
→ contracts/openapi.yaml: 6 endpoint groups, JWT authentication
|
||||
→ quickstart.md: 5 user story validation scenarios
|
||||
3. Generate tasks by category (62 total tasks)
|
||||
4. Apply TDD ordering: Tests before implementation
|
||||
5. Mark [P] for parallel execution (different files)
|
||||
6. SUCCESS: All contracts, entities, and user stories covered
|
||||
```
|
||||
|
||||
## Format: `[ID] [P?] Description`
|
||||
- **[P]**: Can run in parallel (different files, no dependencies)
|
||||
- File paths relative to repository root
|
||||
|
||||
## Path Conventions
|
||||
Single WordPress plugin project structure:
|
||||
- Plugin files: `src/` directory
|
||||
- Tests: `tests/` directory
|
||||
- WordPress integration: Standard plugin activation/hooks
|
||||
|
||||
## Phase 3.1: Setup & WordPress Plugin Foundation
|
||||
|
||||
- [ ] T001 Create WordPress plugin directory structure at `src/` with standard plugin headers and main file
|
||||
- [ ] T002 Initialize composer.json with PHPUnit, WordPress testing framework, and JWT authentication dependencies
|
||||
- [ ] T003 [P] Configure PHPUnit with WordPress testing framework in `phpunit.xml`
|
||||
- [ ] T004 [P] Set up WordPress coding standards (WPCS) and linting configuration
|
||||
- [ ] T005 Create plugin activation/deactivation hooks in `src/kivicare-api.php` with KiviCare dependency check
|
||||
- [ ] T006 Register REST API namespace '/wp-json/kivicare/v1' in `src/class-api-init.php`
|
||||
|
||||
## Phase 3.2: Tests First (TDD) ⚠️ MUST COMPLETE BEFORE 3.3
|
||||
**CRITICAL: These tests MUST be written and MUST FAIL before ANY implementation**
|
||||
|
||||
### Contract Tests (API Endpoints)
|
||||
- [ ] T007 [P] Contract test POST /wp-json/kivicare/v1/auth/login in `tests/contract/test-auth-endpoints.php`
|
||||
- [ ] T008 [P] Contract test GET /wp-json/kivicare/v1/clinics in `tests/contract/test-clinic-endpoints.php`
|
||||
- [ ] T009 [P] Contract test POST /wp-json/kivicare/v1/clinics in `tests/contract/test-clinic-endpoints.php`
|
||||
- [ ] T010 [P] Contract test GET /wp-json/kivicare/v1/patients in `tests/contract/test-patient-endpoints.php`
|
||||
- [ ] T011 [P] Contract test POST /wp-json/kivicare/v1/patients in `tests/contract/test-patient-endpoints.php`
|
||||
- [ ] T012 [P] Contract test GET /wp-json/kivicare/v1/appointments in `tests/contract/test-appointment-endpoints.php`
|
||||
- [ ] T013 [P] Contract test POST /wp-json/kivicare/v1/appointments in `tests/contract/test-appointment-endpoints.php`
|
||||
- [ ] T014 [P] Contract test GET /wp-json/kivicare/v1/encounters in `tests/contract/test-encounter-endpoints.php`
|
||||
- [ ] T015 [P] Contract test POST /wp-json/kivicare/v1/encounters in `tests/contract/test-encounter-endpoints.php`
|
||||
- [ ] T016 [P] Contract test POST /wp-json/kivicare/v1/encounters/{id}/prescriptions in `tests/contract/test-prescription-endpoints.php`
|
||||
|
||||
### Integration Tests (User Stories)
|
||||
- [ ] T017 [P] Integration test doctor creates patient record in `tests/integration/test-patient-creation-workflow.php`
|
||||
- [ ] T018 [P] Integration test doctor creates encounter with prescriptions in `tests/integration/test-encounter-workflow.php`
|
||||
- [ ] T019 [P] Integration test multi-doctor clinic data access in `tests/integration/test-clinic-data-access.php`
|
||||
- [ ] T020 [P] Integration test automatic billing generation in `tests/integration/test-billing-automation.php`
|
||||
- [ ] T021 [P] Integration test role-based access control in `tests/integration/test-role-permissions.php`
|
||||
|
||||
## Phase 3.3: Core Implementation (ONLY after tests are failing)
|
||||
|
||||
### Entity Models
|
||||
- [ ] T022 [P] Clinic model class in `src/models/class-clinic.php` with validation rules
|
||||
- [ ] T023 [P] Patient model class in `src/models/class-patient.php` with wp_users integration
|
||||
- [ ] T024 [P] Doctor model class in `src/models/class-doctor.php` with clinic mappings
|
||||
- [ ] T025 [P] Appointment model class in `src/models/class-appointment.php` with scheduling logic
|
||||
- [ ] T026 [P] Encounter model class in `src/models/class-encounter.php` with appointment linkage
|
||||
- [ ] T027 [P] Prescription model class in `src/models/class-prescription.php` with encounter linkage
|
||||
- [ ] T028 [P] Bill model class in `src/models/class-bill.php` with payment tracking
|
||||
- [ ] T029 [P] Service model class in `src/models/class-service.php` with pricing data
|
||||
|
||||
### Authentication & Authorization Service
|
||||
- [ ] T030 JWT authentication service in `src/services/class-jwt-auth.php`
|
||||
- [ ] T031 Role-based permission service in `src/services/class-role-permissions.php`
|
||||
- [ ] T032 User session management in `src/services/class-session-manager.php`
|
||||
|
||||
### Database Services
|
||||
- [ ] T033 [P] Clinic database service in `src/services/class-clinic-service.php`
|
||||
- [ ] T034 [P] Patient database service in `src/services/class-patient-service.php`
|
||||
- [ ] T035 [P] Doctor database service in `src/services/class-doctor-service.php`
|
||||
- [ ] T036 [P] Appointment database service in `src/services/class-appointment-service.php`
|
||||
- [ ] T037 [P] Encounter database service in `src/services/class-encounter-service.php`
|
||||
- [ ] T038 [P] Prescription database service in `src/services/class-prescription-service.php`
|
||||
- [ ] T039 [P] Bill database service in `src/services/class-bill-service.php`
|
||||
|
||||
### REST API Endpoints
|
||||
- [ ] T040 Authentication endpoints in `src/endpoints/class-auth-endpoints.php`
|
||||
- [ ] T041 Clinic CRUD endpoints in `src/endpoints/class-clinic-endpoints.php`
|
||||
- [ ] T042 Patient CRUD endpoints in `src/endpoints/class-patient-endpoints.php`
|
||||
- [ ] T043 Appointment CRUD endpoints in `src/endpoints/class-appointment-endpoints.php`
|
||||
- [ ] T044 Encounter CRUD endpoints in `src/endpoints/class-encounter-endpoints.php`
|
||||
- [ ] T045 Prescription endpoints in `src/endpoints/class-prescription-endpoints.php`
|
||||
|
||||
### Validation & Error Handling
|
||||
- [ ] T046 Input validation service in `src/utils/class-input-validator.php`
|
||||
- [ ] T047 Error response formatter in `src/utils/class-error-handler.php`
|
||||
- [ ] T048 Request/response logging in `src/utils/class-api-logger.php`
|
||||
|
||||
## Phase 3.4: Integration & Middleware
|
||||
|
||||
- [ ] T049 Connect all database services to WordPress $wpdb with prepared statements
|
||||
- [ ] T050 Implement JWT middleware for all protected endpoints
|
||||
- [ ] T051 Add clinic isolation middleware for multi-clinic data security
|
||||
- [ ] T052 WordPress user role integration with KiviCare roles
|
||||
- [ ] T053 Add structured error responses with proper HTTP status codes
|
||||
- [ ] T054 Implement request/response logging with WordPress debug.log integration
|
||||
|
||||
## Phase 3.5: Caching & Performance
|
||||
|
||||
- [ ] T055 WordPress Object Cache implementation for patient encounters in `src/services/class-cache-manager.php`
|
||||
- [ ] T056 Cache invalidation on data updates for appointment schedules
|
||||
- [ ] T057 Database query optimization with proper indexes
|
||||
- [ ] T058 API response time monitoring and performance logging
|
||||
|
||||
## Phase 3.6: Polish & Documentation
|
||||
|
||||
- [ ] T059 [P] Unit tests for all validation rules in `tests/unit/test-input-validation.php`
|
||||
- [ ] T060 [P] Unit tests for model classes in `tests/unit/test-models.php`
|
||||
- [ ] T061 [P] Performance tests ensuring <500ms response times in `tests/performance/test-api-performance.php`
|
||||
- [ ] T062 Execute quickstart.md validation scenarios and fix any issues
|
||||
|
||||
## Dependencies
|
||||
|
||||
**Setup Phase (T001-T006)**:
|
||||
- T001 blocks all other tasks (plugin structure required)
|
||||
- T002-T006 can run in parallel after T001
|
||||
|
||||
**Tests Phase (T007-T021)**:
|
||||
- Must complete before any implementation (TDD requirement)
|
||||
- All contract tests (T007-T016) can run in parallel
|
||||
- All integration tests (T017-T021) can run in parallel
|
||||
|
||||
**Core Implementation (T022-T048)**:
|
||||
- T022-T029 (models) can run in parallel after tests
|
||||
- T030-T032 (auth) sequential (shared authentication state)
|
||||
- T033-T039 (services) can run in parallel, depend on models
|
||||
- T040-T045 (endpoints) sequential (shared REST namespace registration)
|
||||
- T046-T048 (utils) can run in parallel
|
||||
|
||||
**Integration Phase (T049-T054)**:
|
||||
- T049 blocks T050-T054 (database connection required)
|
||||
- T050-T054 can run in parallel after T049
|
||||
|
||||
**Performance & Polish (T055-T062)**:
|
||||
- T055-T058 can run in parallel
|
||||
- T059-T061 can run in parallel (different test files)
|
||||
- T062 must be last (validation requires complete system)
|
||||
|
||||
## Parallel Example
|
||||
|
||||
```bash
|
||||
# Launch contract tests together (Phase 3.2):
|
||||
Task: "Contract test POST /wp-json/kivicare/v1/auth/login in tests/contract/test-auth-endpoints.php"
|
||||
Task: "Contract test GET /wp-json/kivicare/v1/clinics in tests/contract/test-clinic-endpoints.php"
|
||||
Task: "Contract test GET /wp-json/kivicare/v1/patients in tests/contract/test-patient-endpoints.php"
|
||||
Task: "Contract test GET /wp-json/kivicare/v1/appointments in tests/contract/test-appointment-endpoints.php"
|
||||
|
||||
# Launch model creation together (Phase 3.3):
|
||||
Task: "Clinic model class in src/models/class-clinic.php with validation rules"
|
||||
Task: "Patient model class in src/models/class-patient.php with wp_users integration"
|
||||
Task: "Doctor model class in src/models/class-doctor.php with clinic mappings"
|
||||
Task: "Appointment model class in src/models/class-appointment.php with scheduling logic"
|
||||
```
|
||||
|
||||
## WordPress-Specific Notes
|
||||
|
||||
- Follow WordPress coding standards (WPCS) for all PHP code
|
||||
- Use WordPress hooks and filters for extensibility
|
||||
- Implement proper capability checks for each endpoint
|
||||
- Use WordPress nonce verification where appropriate
|
||||
- Ensure compatibility with WordPress multisite installations
|
||||
- All database operations must use prepared statements via $wpdb
|
||||
- Plugin must gracefully handle KiviCare plugin deactivation
|
||||
|
||||
## Validation Checklist
|
||||
|
||||
- [x] All 6 endpoint groups have contract tests (T007-T016)
|
||||
- [x] All 8 entities have model tasks (T022-T029)
|
||||
- [x] All 5 user stories have integration tests (T017-T021)
|
||||
- [x] Tests come before implementation (Phase 3.2 → 3.3)
|
||||
- [x] Parallel tasks are truly independent (different files)
|
||||
- [x] Each task specifies exact file path
|
||||
- [x] WordPress plugin structure properly planned
|
||||
- [x] KiviCare database schema integration covered
|
||||
- [x] JWT authentication and role-based permissions included
|
||||
- [x] Performance and caching requirements addressed
|
||||
|
||||
## WordPress Development Commands
|
||||
|
||||
```bash
|
||||
# Plugin development
|
||||
wp plugin activate kivicare-api
|
||||
wp plugin deactivate kivicare-api
|
||||
|
||||
# Testing
|
||||
vendor/bin/phpunit tests/
|
||||
wp db query "SELECT * FROM wp_kc_clinics LIMIT 5"
|
||||
|
||||
# Debugging
|
||||
wp config set WP_DEBUG true
|
||||
wp config set WP_DEBUG_LOG true
|
||||
tail -f wp-content/debug.log
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**Task Generation Complete**: 62 tasks ready for WordPress TDD implementation
|
||||
Reference in New Issue
Block a user