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:
Emanuel Almeida
2025-09-12 01:27:34 +01:00
parent 4a60be990e
commit 38bb926742
118 changed files with 40694 additions and 0 deletions

View File

@@ -0,0 +1,335 @@
# Admin API Contracts: Care Booking Block Plugin
**Feature**: WordPress Plugin para Controlo Seguro de Agendamentos KiviCare
**Date**: 2025-09-10
**Type**: WordPress AJAX API Contracts
## AJAX Endpoints
### 1. Get Restrictions List
**Endpoint**: `wp_ajax_care_booking_get_restrictions`
**Method**: POST
**Auth**: WordPress nonce verification
**Capability**: `manage_options`
**Request**:
```json
{
"action": "care_booking_get_restrictions",
"nonce": "wp_nonce_string",
"restriction_type": "doctor|service|all",
"doctor_id": 123 // Optional: for service restrictions
}
```
**Response Success (200)**:
```json
{
"success": true,
"data": {
"restrictions": [
{
"id": 1,
"restriction_type": "doctor",
"target_id": 123,
"doctor_id": null,
"is_blocked": true,
"created_at": "2025-09-10 10:00:00",
"updated_at": "2025-09-10 10:00:00"
}
],
"total": 1
}
}
```
**Response Error (400/403)**:
```json
{
"success": false,
"data": {
"message": "Invalid nonce" | "Insufficient permissions" | "Invalid parameters"
}
}
```
### 2. Toggle Restriction
**Endpoint**: `wp_ajax_care_booking_toggle_restriction`
**Method**: POST
**Auth**: WordPress nonce verification
**Capability**: `manage_options`
**Request**:
```json
{
"action": "care_booking_toggle_restriction",
"nonce": "wp_nonce_string",
"restriction_type": "doctor|service",
"target_id": 123,
"doctor_id": 456, // Required for service restrictions
"is_blocked": true
}
```
**Response Success (200)**:
```json
{
"success": true,
"data": {
"message": "Restriction updated successfully",
"restriction": {
"id": 1,
"restriction_type": "doctor",
"target_id": 123,
"doctor_id": null,
"is_blocked": true,
"updated_at": "2025-09-10 10:05:00"
}
}
}
```
**Response Error (400/403/500)**:
```json
{
"success": false,
"data": {
"message": "Failed to update restriction" | "Target not found" | "Database error"
}
}
```
### 3. Bulk Update Restrictions
**Endpoint**: `wp_ajax_care_booking_bulk_update`
**Method**: POST
**Auth**: WordPress nonce verification
**Capability**: `manage_options`
**Request**:
```json
{
"action": "care_booking_bulk_update",
"nonce": "wp_nonce_string",
"restrictions": [
{
"restriction_type": "doctor",
"target_id": 123,
"is_blocked": true
},
{
"restriction_type": "service",
"target_id": 456,
"doctor_id": 123,
"is_blocked": false
}
]
}
```
**Response Success (200)**:
```json
{
"success": true,
"data": {
"message": "Bulk update completed",
"updated": 2,
"errors": []
}
}
```
**Response Error (400/500)**:
```json
{
"success": false,
"data": {
"message": "Partial failure in bulk update",
"updated": 1,
"errors": [
{
"restriction": {
"target_id": 456,
"restriction_type": "service"
},
"error": "Target not found in KiviCare"
}
]
}
}
```
### 4. Get KiviCare Entities
**Endpoint**: `wp_ajax_care_booking_get_entities`
**Method**: POST
**Auth**: WordPress nonce verification
**Capability**: `manage_options`
**Request**:
```json
{
"action": "care_booking_get_entities",
"nonce": "wp_nonce_string",
"entity_type": "doctors|services",
"doctor_id": 123 // Optional: for services by doctor
}
```
**Response Success (200)**:
```json
{
"success": true,
"data": {
"entities": [
{
"id": 123,
"name": "Dr. João Silva",
"email": "joao@clinic.com",
"is_blocked": true // Current restriction status
}
],
"total": 1
}
}
```
## WordPress Hooks Integration Contracts
### 1. KiviCare Doctor List Filter
**Hook**: `kc_get_doctors_for_booking`
**Type**: WordPress Filter
**Priority**: 10
**Input**:
```php
$doctors = [
['id' => 123, 'name' => 'Dr. João Silva', 'email' => 'joao@clinic.com'],
['id' => 124, 'name' => 'Dr. Maria Santos', 'email' => 'maria@clinic.com']
];
```
**Output** (filtered):
```php
$doctors = [
['id' => 124, 'name' => 'Dr. Maria Santos', 'email' => 'maria@clinic.com']
// Dr. João Silva removed if blocked
];
```
### 2. KiviCare Service List Filter
**Hook**: `kc_get_services_by_doctor`
**Type**: WordPress Filter
**Priority**: 10
**Input**:
```php
$services = [
['id' => 456, 'name' => 'Consulta Geral', 'doctor_id' => 123],
['id' => 457, 'name' => 'Revisão', 'doctor_id' => 123]
];
$doctor_id = 123;
```
**Output** (filtered):
```php
$services = [
['id' => 456, 'name' => 'Consulta Geral', 'doctor_id' => 123]
// 'Revisão' removed if blocked for this doctor
];
```
## CSS Injection Contract
### Dynamic CSS Generation
**Hook**: `wp_head`
**Priority**: 20 (after theme styles)
**Generated CSS**:
```css
/* Dynamic CSS based on current restrictions */
.kivicare-doctor[data-doctor-id="123"],
.kivicare-service[data-service-id="456"][data-doctor-id="123"] {
display: none !important;
}
/* Fallback for different KiviCare markup patterns */
#doctor-123,
#service-456-doctor-123,
.doctor-selection option[value="123"],
.service-selection option[value="456"] {
display: none !important;
}
```
## Validation Contracts
### Input Validation Rules
**Doctor/Service Target Validation**:
```php
function validate_target_exists($target_id, $type) {
// Must return boolean
// true if target exists in KiviCare
// false if target not found
}
```
**Nonce Validation**:
```php
function validate_nonce($nonce, $action) {
// WordPress standard nonce verification
return wp_verify_nonce($nonce, $action);
}
```
**Capability Validation**:
```php
function validate_user_capability() {
// Check if user can manage options
return current_user_can('manage_options');
}
```
## Error Response Contracts
### Standard Error Codes
- `400`: Bad Request (invalid parameters)
- `403`: Forbidden (insufficient permissions, invalid nonce)
- `404`: Not Found (target entity not found)
- `500`: Internal Server Error (database error, KiviCare not available)
### Error Message Format
All error responses follow WordPress AJAX standard:
```json
{
"success": false,
"data": {
"message": "Human readable error message",
"code": "ERROR_CODE_CONSTANT", // Optional
"details": {} // Optional additional error context
}
}
```
## Performance Contracts
### Response Time Targets
- **Get Restrictions**: < 200ms
- **Toggle Restriction**: < 300ms (includes cache invalidation)
- **Bulk Update**: < 500ms for up to 50 items
- **Get Entities**: < 400ms (with KiviCare data fetch)
### Cache Invalidation Contract
When any restriction is modified:
1. Clear `care_booking_doctors_blocked` transient
2. Clear all `care_booking_services_blocked_{doctor_id}` transients
3. Update `care_booking_restrictions_hash` with new hash
4. Trigger WordPress action: `care_booking_restrictions_updated`
These contracts define the exact interface between the admin panel, the WordPress backend, and the frontend filtering system.

View File

@@ -0,0 +1,177 @@
# Data Model: WordPress Plugin para Controlo Seguro de Agendamentos KiviCare
**Feature**: WordPress Plugin para Controlo Seguro de Agendamentos KiviCare
**Date**: 2025-09-10
**Phase**: Data Model Design
## Core Entities
### 1. Restriction Entity
**Table**: `wp_care_booking_restrictions`
| Field | Type | Constraints | Description |
|-------|------|-------------|-------------|
| `id` | BIGINT(20) UNSIGNED | AUTO_INCREMENT, PRIMARY KEY | Unique restriction identifier |
| `restriction_type` | ENUM('doctor', 'service') | NOT NULL | Type of restriction being applied |
| `target_id` | BIGINT(20) UNSIGNED | NOT NULL | ID of the doctor or service being restricted |
| `doctor_id` | BIGINT(20) UNSIGNED | NULL | For service restrictions, which doctor it applies to |
| `is_blocked` | BOOLEAN | DEFAULT FALSE | Whether the item is blocked from public view |
| `created_at` | TIMESTAMP | DEFAULT CURRENT_TIMESTAMP | When restriction was created |
| `updated_at` | TIMESTAMP | DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP | When restriction was last modified |
**Indexes**:
- `PRIMARY KEY (id)`
- `INDEX idx_type_target (restriction_type, target_id)`
- `INDEX idx_doctor_service (doctor_id, target_id)` - For service restrictions by doctor
- `INDEX idx_blocked (is_blocked)` - For filtering active restrictions
### 2. WordPress Integration Entities
**Cache Keys** (WordPress Transients):
- `care_booking_doctors_blocked` - List of blocked doctor IDs
- `care_booking_services_blocked_{doctor_id}` - Blocked services for specific doctor
- `care_booking_restrictions_hash` - Hash of current restrictions for cache validation
**WordPress Options**:
- `care_booking_plugin_version` - Plugin version for migration handling
- `care_booking_cache_timeout` - Cache timeout in seconds (default: 3600)
## Entity Relationships
### Doctor Restrictions
```
Restriction (restriction_type = 'doctor')
├── target_id → KiviCare Doctor ID
├── doctor_id → NULL (not applicable)
└── is_blocked → TRUE/FALSE
```
### Service Restrictions
```
Restriction (restriction_type = 'service')
├── target_id → KiviCare Service ID
├── doctor_id → KiviCare Doctor ID (which doctor this applies to)
└── is_blocked → TRUE/FALSE
```
## Data Validation Rules
### Restriction Entity Validation
1. **restriction_type**: Must be either 'doctor' or 'service'
2. **target_id**: Must be positive integer, must exist in KiviCare
3. **doctor_id**:
- Must be NULL for doctor restrictions
- Must be positive integer for service restrictions
- Must exist in KiviCare doctors table
4. **is_blocked**: Boolean only (0 or 1)
### Business Logic Validation
1. **Doctor Restriction**:
- target_id must exist in KiviCare doctors
- Only one restriction per doctor (unique constraint on target_id for doctor type)
2. **Service Restriction**:
- target_id must exist in KiviCare services
- doctor_id must exist in KiviCare doctors
- Service must be assignable to the specified doctor
- Only one restriction per service-doctor combination
### Data Integrity Rules
1. **Orphan Prevention**: Before creating restriction, verify target exists in KiviCare
2. **Cascade Cleanup**: When KiviCare entity is deleted, cleanup related restrictions
3. **Cache Invalidation**: When any restriction changes, invalidate related cache keys
## State Transitions
### Restriction Lifecycle
```
[Non-existent] → [Created (is_blocked=false)] → [Blocked (is_blocked=true)] → [Unblocked (is_blocked=false)] → [Deleted]
↗ ↙
[Blocked (is_blocked=true)] ←→ [Unblocked (is_blocked=false)]
```
### Admin Interface States
1. **New Restriction**: Create with is_blocked=true (default blocked)
2. **Toggle Restriction**: Update is_blocked value
3. **Remove Restriction**: DELETE from database (not soft delete)
## Query Patterns
### Common Queries
```sql
-- Get all blocked doctors
SELECT target_id FROM wp_care_booking_restrictions
WHERE restriction_type = 'doctor' AND is_blocked = 1;
-- Get blocked services for specific doctor
SELECT target_id FROM wp_care_booking_restrictions
WHERE restriction_type = 'service' AND doctor_id = ? AND is_blocked = 1;
-- Check if specific doctor is blocked
SELECT 1 FROM wp_care_booking_restrictions
WHERE restriction_type = 'doctor' AND target_id = ? AND is_blocked = 1 LIMIT 1;
-- Get all restrictions for admin interface
SELECT * FROM wp_care_booking_restrictions
ORDER BY restriction_type, target_id;
```
### Performance Considerations
- Use prepared statements for all queries
- Leverage indexes for common query patterns
- Cache frequently accessed data using WordPress transients
- Batch operations for bulk updates
## Database Schema Migration
### Version 1.0.0 Initial Schema
```sql
CREATE TABLE IF NOT EXISTS {$wpdb->prefix}care_booking_restrictions (
id BIGINT(20) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
restriction_type ENUM('doctor', 'service') NOT NULL,
target_id BIGINT(20) UNSIGNED NOT NULL,
doctor_id BIGINT(20) UNSIGNED NULL,
is_blocked BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_type_target (restriction_type, target_id),
INDEX idx_doctor_service (doctor_id, target_id),
INDEX idx_blocked (is_blocked)
);
```
### Migration Strategy
1. **Plugin Activation**: Check if table exists, create if needed
2. **Version Updates**: Compare plugin version, run migrations if needed
3. **Plugin Deactivation**: Keep data (user might reactivate)
4. **Plugin Uninstall**: Drop table and clean up options (permanent removal)
## WordPress Integration Data Flow
### Admin Interface Data Flow
```
WordPress Admin Panel
↓ (User Action)
AJAX Request with Nonce
↓ (Validation)
Database Update (wp_care_booking_restrictions)
↓ (Cache Invalidation)
WordPress Transients Cleared
↓ (Response)
JSON Response to Admin Interface
```
### Frontend Filtering Data Flow
```
KiviCare Hook Triggered
↓ (Check Cache)
WordPress Transients (if exists)
↓ (If cache miss)
Database Query (wp_care_booking_restrictions)
↓ (Filter Data)
Modified Doctor/Service List
↓ (CSS Injection)
Hidden Elements via CSS
```
This data model provides a robust foundation for the WordPress plugin while maintaining simplicity and performance through appropriate indexing and caching strategies.

View File

@@ -0,0 +1,244 @@
# Implementation Plan: WordPress Plugin para Controlo Seguro de Agendamentos KiviCare
**Branch**: `001-wordpress-plugin-para` | **Date**: 2025-09-10 | **Spec**: [spec.md](./spec.md)
**Input**: Feature specification from `/specs/001-wordpress-plugin-para/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
WordPress plugin que permite controlo granular sobre a visibilidade de médicos e serviços no sistema de agendamento público do KiviCare, mantendo acesso total no painel administrativo. Utiliza abordagem CSS-first para evitar instabilidade crítica identificada em versões anteriores, com integração segura via hooks WordPress e KiviCare.
## Technical Context
**Language/Version**: PHP 7.4+ (WordPress compatibility requirement)
**Primary Dependencies**: WordPress 5.0+, KiviCare Plugin 3.0.0+, MySQL 5.7+
**Storage**: MySQL via WordPress $wpdb API (custom table wp_care_booking_restrictions)
**Testing**: PHPUnit with WordPress testing framework
**Target Platform**: WordPress hosting environment (Linux servers with PHP/MySQL stack)
**Project Type**: single (WordPress plugin with admin interface and frontend filtering)
**Performance Goals**: <5% overhead on appointment page loading, <2 minutes admin configuration time
**Constraints**: CSS-first approach to avoid shortcode conflicts, zero website downtime during operation
**Scale/Scope**: Support clinics with thousands of doctors/services, 100% compatibility with KiviCare updates
## Constitution Check
*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*
**Simplicity**:
- Projects: 1 (WordPress plugin with admin panel + frontend filtering)
- Using framework directly? YES (WordPress hooks/filters, no wrapper classes)
- Single data model? YES (wp_care_booking_restrictions table, no DTOs)
- Avoiding patterns? YES (Direct WordPress $wpdb access, no Repository/UoW)
**Architecture**:
- EVERY feature as library? N/A (WordPress plugin architecture - classes with hooks)
- Libraries listed: N/A (WordPress plugin with core classes)
- CLI per library: N/A (WordPress admin interface, no CLI needed)
- Library docs: WordPress plugin documentation format planned
**Testing (NON-NEGOTIABLE)**:
- RED-GREEN-Refactor cycle enforced? YES (PHPUnit tests before implementation)
- Git commits show tests before implementation? YES (will be enforced)
- Order: Contract→Integration→E2E→Unit strictly followed? YES
- Real dependencies used? YES (actual WordPress/KiviCare installation)
- Integration tests for: KiviCare hooks, WordPress database, admin interface
- FORBIDDEN: Implementation before test, skipping RED phase - ENFORCED
**Observability**:
- Structured logging included? YES (WordPress debug.log integration)
- Frontend logs → backend? YES (admin actions logged to WordPress)
- Error context sufficient? YES (detailed error messages and recovery)
**Versioning**:
- Version number assigned? 1.0.0 (WordPress plugin versioning)
- BUILD increments on every change? YES (plugin version updates)
- Breaking changes handled? YES (WordPress activation/deactivation hooks)
## 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) - Standard WordPress plugin structure with admin interface and frontend integration
## 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 WordPress plugin task base
- Generate tasks from Phase 1 design docs (contracts, data-model.md, quickstart.md)
- Database schema → table creation task with activation hook [P]
- Admin API contracts → AJAX endpoint test tasks [P]
- KiviCare hook contracts → integration test tasks
- Admin interface → UI component tasks
- Frontend filtering → CSS injection and hook implementation tasks
- Each quickstart scenario → end-to-end validation task
**WordPress-Specific Ordering Strategy**:
1. **Foundation**: Plugin structure, autoloader, activation hooks
2. **Database**: Table creation, model classes [P]
3. **Contract Tests**: AJAX endpoints, KiviCare hooks [P]
4. **Core Logic**: Restriction management, caching, validation
5. **Admin Interface**: UI components, AJAX handlers
6. **Frontend Integration**: CSS injection, KiviCare hooks
7. **Integration Tests**: End-to-end scenarios from quickstart.md
8. **Performance & Security**: Optimization, security validation
**Estimated Output**: 20-25 numbered WordPress plugin tasks in tasks.md
**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*
| Violation | Why Needed | Simpler Alternative Rejected Because |
|-----------|------------|-------------------------------------|
| [e.g., 4th project] | [current need] | [why 3 projects insufficient] |
| [e.g., Repository pattern] | [specific problem] | [why direct DB access insufficient] |
## Progress Tracking
*This checklist is updated during execution flow*
**Phase Status**:
- [x] Phase 0: Research complete (/plan command) - research.md created
- [x] Phase 1: Design complete (/plan command) - data-model.md, contracts/, quickstart.md, CLAUDE.md created
- [x] Phase 2: Task planning complete (/plan command - approach described)
- [ ] 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 required)
---
*Based on Constitution v2.1.1 - See `/memory/constitution.md`*

View File

@@ -0,0 +1,317 @@
# Quickstart Guide: Care Booking Block Plugin
**Feature**: WordPress Plugin para Controlo Seguro de Agendamentos KiviCare
**Date**: 2025-09-10
**Purpose**: End-to-end validation scenarios for testing
## Prerequisites Validation
### Environment Setup
```bash
# 1. WordPress 5.0+ installation
wp core version --allow-root
# Expected: 5.0.0 or higher
# 2. KiviCare plugin active
wp plugin status kivicare --allow-root
# Expected: Status: Active
# 3. PHP version check
php -v
# Expected: PHP 7.4+
# 4. Database access
wp db check --allow-root
# Expected: Success
```
### Test Data Setup
```sql
-- Ensure test doctors exist in KiviCare
INSERT INTO wp_kc_doctors (id, name, email) VALUES
(999, 'Test Doctor 1', 'test1@clinic.com'),
(998, 'Test Doctor 2', 'test2@clinic.com');
-- Ensure test services exist
INSERT INTO wp_kc_services (id, name, doctor_id) VALUES
(888, 'Test Service 1', 999),
(887, 'Test Service 2', 999);
```
## Installation & Activation Test
### Step 1: Plugin Installation
```bash
# Upload plugin to WordPress
cp -r care-booking-block/ /wp-content/plugins/
# Activate plugin via WP-CLI
wp plugin activate care-booking-block --allow-root
```
**Expected Outcome**:
- Plugin activates without errors
- Database table `wp_care_booking_restrictions` created
- Admin menu "Care Booking Control" appears
**Validation**:
```sql
-- Check table creation
DESCRIBE wp_care_booking_restrictions;
-- Check WordPress options
SELECT option_value FROM wp_options WHERE option_name = 'care_booking_plugin_version';
```
### Step 2: Admin Interface Access
```bash
# Navigate to admin interface
# URL: /wp-admin/admin.php?page=care-booking-control
```
**Expected Outcome**:
- Admin page loads without errors
- List of doctors from KiviCare displayed
- Toggle switches for each doctor visible
- No PHP errors in debug.log
## Core Functionality Tests
### Test Scenario 1: Block Doctor from Public Booking
**User Story**: Administrator blocks Dr. Test Doctor 1 from public appointments
**Steps**:
1. Navigate to Care Booking Control admin page
2. Find "Test Doctor 1" in the list
3. Click toggle to block doctor
4. Save changes
**Expected Outcome**:
```json
// AJAX Response
{
"success": true,
"data": {
"message": "Restriction updated successfully",
"restriction": {
"restriction_type": "doctor",
"target_id": 999,
"is_blocked": true
}
}
}
```
**Database Validation**:
```sql
SELECT * FROM wp_care_booking_restrictions
WHERE restriction_type = 'doctor' AND target_id = 999;
-- Expected: 1 row with is_blocked = 1
```
**Frontend Validation**:
```javascript
// Check if CSS is injected
const hiddenDoctor = document.querySelector('.kivicare-doctor[data-doctor-id="999"]');
const computedStyle = window.getComputedStyle(hiddenDoctor);
console.log(computedStyle.display); // Expected: 'none'
```
### Test Scenario 2: Hide Service for Specific Doctor
**User Story**: Administrator hides "Test Service 2" for "Test Doctor 1"
**Steps**:
1. In admin interface, expand "Test Doctor 1" services
2. Find "Test Service 2" checkbox
3. Uncheck to hide service
4. Save changes
**Expected Outcome**:
```json
// AJAX Response
{
"success": true,
"data": {
"restriction": {
"restriction_type": "service",
"target_id": 887,
"doctor_id": 999,
"is_blocked": true
}
}
}
```
**Frontend Test**:
```php
// KiviCare filter test
$services = apply_filters('kc_get_services_by_doctor', [
['id' => 888, 'name' => 'Test Service 1'],
['id' => 887, 'name' => 'Test Service 2']
], 999);
// Expected: Only Service 1 in array
assert(count($services) === 1);
assert($services[0]['id'] === 888);
```
### Test Scenario 3: Frontend Booking Form Validation
**User Story**: Patient tries to book appointment and sees filtered options
**Steps**:
1. Navigate to KiviCare booking form on frontend
2. Open doctor selection dropdown
3. Verify blocked doctors not visible
4. Select remaining doctor
5. Check service options for selected doctor
**Expected Outcome**:
- Test Doctor 1 (ID: 999) not in dropdown
- Test Doctor 2 (ID: 998) visible and selectable
- When Test Doctor 1 was selected before blocking, only Test Service 1 visible
**DOM Validation**:
```javascript
// Check doctor dropdown
const doctorOptions = document.querySelectorAll('#doctor-select option');
const blockedDoctorOption = Array.from(doctorOptions)
.find(option => option.value === '999');
// Expected: undefined (not found)
// Check CSS injection
const injectedCSS = document.querySelector('style[data-care-booking]');
// Expected: Contains .kivicare-doctor[data-doctor-id="999"] { display: none !important; }
```
## Performance Validation
### Response Time Test
```bash
# Test admin AJAX endpoints
time curl -X POST "http://site.com/wp-admin/admin-ajax.php" \
-d "action=care_booking_get_restrictions&nonce=test_nonce"
# Expected: < 200ms
time curl -X POST "http://site.com/wp-admin/admin-ajax.php" \
-d "action=care_booking_toggle_restriction&nonce=test_nonce&target_id=999&restriction_type=doctor&is_blocked=true"
# Expected: < 300ms
```
### Page Load Impact Test
```javascript
// Measure frontend page load impact
const startTime = performance.now();
// Load KiviCare booking form page
const loadTime = performance.now() - startTime;
// Expected: < 5% increase over baseline (without plugin)
```
### Cache Validation
```php
// Test cache invalidation
set_transient('care_booking_doctors_blocked', [999], 3600);
// Trigger restriction update
do_action('care_booking_restriction_updated');
// Check cache cleared
$cached = get_transient('care_booking_doctors_blocked');
// Expected: false (cache cleared)
```
## Error Handling Tests
### Test Scenario 4: KiviCare Plugin Deactivated
**Steps**:
1. Deactivate KiviCare plugin
2. Access Care Booking Control admin page
3. Try to access frontend booking form
**Expected Outcome**:
- Admin page shows warning message
- Frontend continues working without errors
- No fatal PHP errors in debug.log
### Test Scenario 5: Database Connection Error
**Steps**:
1. Temporarily block database access
2. Try to load admin interface
3. Try to toggle restriction
**Expected Outcome**:
```json
{
"success": false,
"data": {
"message": "Database error occurred. Please try again.",
"code": "DB_CONNECTION_ERROR"
}
}
```
### Test Scenario 6: Invalid Nonce
**Steps**:
1. Send AJAX request with invalid nonce
2. Check response
**Expected Outcome**:
```json
{
"success": false,
"data": {
"message": "Invalid nonce",
"code": "INVALID_NONCE"
}
}
```
## Compatibility Tests
### Test Scenario 7: Cache Plugin Compatibility
**Setup**: Install WP Rocket or W3 Total Cache
**Steps**:
1. Enable page caching
2. Block a doctor
3. View frontend booking form
4. Check if changes are visible immediately
**Expected Outcome**:
- Changes visible within cache invalidation timeout
- No cached restrictions shown to users
### Test Scenario 8: Theme Compatibility
**Setup**: Switch to popular WordPress theme
**Steps**:
1. Activate different theme (Twenty Twenty-Three, Astra, etc.)
2. Test admin interface styling
3. Test frontend CSS injection
**Expected Outcome**:
- Admin interface maintains WordPress native styling
- Frontend CSS selectors work across themes
## Success Criteria Validation
### Metrics to Verify
1. **100% restriction compliance**: Blocked doctors/services never appear
2. **<2 minute configuration**: Time administrator to set up restrictions
3. **<5% performance impact**: Page load time increase
4. **Zero critical errors**: No fatal errors in debug.log for 24 hours
### Final Validation Checklist
- [ ] All test scenarios pass
- [ ] Performance targets met
- [ ] Error handling works correctly
- [ ] Compatibility verified
- [ ] Success metrics achieved
- [ ] Documentation complete
This quickstart guide provides comprehensive validation scenarios to ensure the plugin meets all functional requirements while maintaining system stability.

View File

@@ -0,0 +1,144 @@
# Research: WordPress Plugin para Controlo Seguro de Agendamentos KiviCare
**Feature**: WordPress Plugin para Controlo Seguro de Agendamentos KiviCare
**Date**: 2025-09-10
**Research Phase**: Technical decisions and best practices
## Key Technical Decisions
### 1. CSS-First Approach vs PHP Filtering
**Decision**: Hybrid approach - CSS-first for immediate hiding, PHP hooks for data filtering
**Rationale**: Previous versions failed due to shortcode conflicts. CSS provides immediate visual hiding while PHP hooks ensure clean data without conflicts
**Alternatives considered**:
- Pure CSS approach (insufficient - doesn't prevent form submissions)
- Pure PHP hooks (caused instability in previous versions)
- Theme modification (not portable across themes)
### 2. Database Storage Strategy
**Decision**: Custom WordPress table `wp_care_booking_restrictions`
**Rationale**: Clean separation from KiviCare data, survives plugin updates, optimized indexes
**Alternatives considered**:
- WordPress options table (not scalable for large datasets)
- KiviCare database modification (breaks on updates)
- External database (adds complexity)
### 3. WordPress Integration Pattern
**Decision**: Standard WordPress plugin with hooks and filters
**Rationale**: Follows WordPress best practices, compatible with plugin ecosystem
**Alternatives considered**:
- Must-use plugin (too intrusive)
- Theme functions (not portable)
- Custom solution outside WordPress (breaks ecosystem)
### 4. KiviCare Integration Strategy
**Decision**: Hook into KiviCare's WordPress filters and actions, not direct database access
**Rationale**: Maintains compatibility with KiviCare updates, respects plugin boundaries
**Alternatives considered**:
- Direct database queries (brittle to schema changes)
- KiviCare code modification (impossible to maintain)
- API interception (complex and fragile)
### 5. Admin Interface Framework
**Decision**: Native WordPress admin with AJAX for real-time updates
**Rationale**: Consistent with WordPress UX, no additional dependencies, familiar to users
**Alternatives considered**:
- React admin interface (overkill for this functionality)
- Custom framework (reinventing wheel)
- Third-party admin framework (additional dependency)
### 6. Performance Optimization Strategy
**Decision**: WordPress transients for caching with selective invalidation
**Rationale**: Built-in WordPress caching, automatic expiration, integrates with object cache
**Alternatives considered**:
- File-based caching (not portable across hosting)
- Redis/Memcached direct (not always available)
- No caching (performance impact)
### 7. Error Handling and Recovery
**Decision**: Graceful degradation with detailed WordPress debug logging
**Rationale**: System continues working if KiviCare is unavailable, detailed logs for troubleshooting
**Alternatives considered**:
- Hard failures (breaks website)
- Silent failures (difficult to debug)
- External error tracking (additional dependency)
## WordPress-Specific Best Practices Research
### Plugin Architecture
- **Activation/Deactivation hooks**: For database table creation/cleanup
- **Uninstall hook**: For complete data removal when plugin is deleted
- **WordPress coding standards**: PSR-4 autoloading, proper sanitization
- **Security**: Nonces for forms, capability checks, prepared statements
### Database Schema Design
- **Indexes**: Primary key on id, composite index on (restriction_type, target_id)
- **WordPress prefixes**: Use $wpdb->prefix for table names
- **Data types**: WordPress-compatible field types and constraints
- **Migration strategy**: Version checks and schema updates
### Frontend Integration
- **wp_enqueue_script/style**: Proper asset loading with dependencies
- **wp_localize_script**: For passing PHP data to JavaScript
- **WordPress AJAX**: wp_ajax_* actions for admin interface
- **Conditional loading**: Only load admin assets in admin, frontend assets on frontend
### Caching Strategy
- **WordPress Transients API**: set_transient/get_transient for temporary data
- **Object Cache**: Integration with wp_cache_* functions
- **Cache invalidation**: Clear related caches when restrictions change
- **Plugin compatibility**: Works with popular caching plugins
## Performance Considerations
### Database Optimization
- **Query optimization**: Use WordPress $wpdb with prepared statements
- **Index strategy**: Optimize for common query patterns
- **Batch operations**: For bulk restriction updates
- **Connection pooling**: Rely on WordPress database connection management
### Frontend Performance
- **Asset minification**: Minified CSS/JS for production
- **Conditional loading**: Load assets only when needed
- **Cache-friendly**: Generate cache-friendly CSS selectors
- **No render blocking**: Non-critical CSS loaded asynchronously
## Security Analysis
### WordPress Security Best Practices
- **Data sanitization**: sanitize_text_field, intval for all inputs
- **Data validation**: Validate all form inputs before database operations
- **Capability checks**: current_user_can for all admin actions
- **Nonces**: wp_nonce_field for all forms, wp_verify_nonce for validation
- **SQL injection prevention**: Always use $wpdb->prepare
### KiviCare Integration Security
- **Hook priorities**: Use appropriate priorities to avoid conflicts
- **Data filtering**: Filter data, don't modify KiviCare's database
- **Capability respect**: Respect KiviCare's user capabilities
- **Plugin detection**: Check if KiviCare is active before integration
## Compatibility Analysis
### WordPress Version Compatibility
- **Minimum version**: WordPress 5.0+ for block editor and modern APIs
- **PHP version**: PHP 7.4+ for modern syntax and performance
- **MySQL version**: MySQL 5.7+ for modern database features
### KiviCare Plugin Compatibility
- **Version support**: KiviCare 3.0.0+ for stable hook system
- **Hook compatibility**: Use documented hooks where available
- **Graceful degradation**: Handle missing hooks gracefully
- **Update resilience**: Avoid depending on internal KiviCare functions
### Theme and Plugin Compatibility
- **Popular caching plugins**: WP Rocket, W3 Total Cache, WP Super Cache
- **Popular themes**: Compatibility with major WordPress themes
- **Page builders**: Elementor, Gutenberg, classic editor
- **Other healthcare plugins**: Avoid conflicts with similar functionality
## Research Conclusions
All technical unknowns have been resolved with specific implementation strategies that address the critical stability requirements learned from previous versions. The hybrid CSS-first + PHP hooks approach provides both immediate visual feedback and robust data filtering while maintaining system stability.
**Status**: ✅ All NEEDS CLARIFICATION items resolved
**Next Phase**: Phase 1 - Design & Contracts

View File

@@ -0,0 +1,172 @@
# Feature Specification: WordPress Plugin para Controlo Seguro de Agendamentos KiviCare
**Feature Branch**: `001-wordpress-plugin-para`
**Created**: 2025-09-10
**Status**: Draft
**Input**: User description: "WordPress plugin para controlo seguro de agendamentos KiviCare com abordagem CSS-first e theme-level integration para evitar instabilidade crítica identificada em versões anteriores"
## Execution Flow (main)
```
1. Parse user description from Input
→ Extracted: WordPress plugin, KiviCare integration, CSS-first approach, stability focus
2. Extract key concepts from description
→ Actors: clinic administrators, patients, staff
→ Actions: control appointment visibility, secure integration
→ Data: doctor/service restrictions, appointment forms
→ Constraints: avoid system instability, CSS-first approach
3. For each unclear aspect:
→ Marked with [NEEDS CLARIFICATION: specific question]
4. Fill User Scenarios & Testing section
→ Primary user journey: administrator configures restrictions
5. Generate Functional Requirements
→ Each requirement focused on safe appointment control
6. Identify Key Entities
→ Doctor restrictions, service restrictions, appointments
7. Run Review Checklist
→ Focus on business value and stability requirements
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")
---
## User Scenarios & Testing *(mandatory)*
### Primary User Story
O plugin KiviCare para WordPress não permite um controlo granular sobre a visibilidade de médicos e serviços no sistema de agendamento público. Este projeto resolve essa limitação, permitindo ocultar seletivamente médicos e/ou serviços específicos do frontend, sem afetar a gestão no painel de administração.
**Utilizadores Finais:**
- **Administradores da Clínica (Utilizadores do Painel WP):** Gestores que configuram a plataforma, definindo quais médicos e serviços devem estar visíveis para agendamento online
- **Pacientes/Clientes (Utilizadores do Site Público):** Pessoas que acedem ao site para marcar consultas e que verão uma lista filtrada de opções
**Valor de Negócio:**
Aumentar a flexibilidade operacional das clínicas que usam KiviCare, permitindo-lhes gerir a sua oferta de serviços online de forma mais estratégica (ex: ocultar médicos sem disponibilidade, oferecer serviços específicos apenas presencialmente). Melhora a experiência do cliente final e otimiza a gestão interna.
### Jornadas de Utilizador Detalhadas
**Jornada do Administrador:**
1. O administrador acede ao painel do WordPress
2. Navega para o novo menu "Care Booking Control"
3. Numa interface simples (com checkboxes), seleciona os médicos que deseja ocultar do agendamento público
4. Expande a configuração de um médico específico e seleciona os serviços desse médico que devem ser ocultados
5. Grava as alterações. O sistema invalida a cache relevante automaticamente
6. O administrador pode, a qualquer momento, reverter estas alterações
**Jornada do Paciente/Cliente:**
1. O paciente acede à página de agendamento do site
2. Interage com o formulário de agendamento do KiviCare
3. As listas de seleção de médicos e serviços já não mostram as opções que o administrador ocultou
4. O paciente consegue completar o seu agendamento apenas com as combinações permitidas
### Acceptance Scenarios
1. **Given** múltiplos médicos no KiviCare, **When** administrador marca médicos específicos como "bloqueados", **Then** esses médicos não aparecem no formulário público mas mantêm-se acessíveis no admin
2. **Given** médico oferece múltiplos serviços, **When** administrador oculta serviços específicos, **Then** apenas serviços visíveis aparecem quando pacientes selecionam esse médico
3. **Given** plugin ativo, **When** KiviCare é atualizado, **Then** sistema de restrições continua funcionando sem instabilidade
4. **Given** alterações nas configurações, **When** paciente visualiza formulário, **Then** alterações refletem-se imediatamente (cache invalidado automaticamente)
### Cenários Extremos e Limitações
**Cenários de Erro:**
- **KiviCare desativado**: Site não deve quebrar; funcionalidade de restrição simplesmente deixa de funcionar
- **Médico/serviço eliminado no KiviCare**: Regras de restrição associadas devem ser limpas ou ignoradas para evitar IDs órfãos
- **Conflitos com plugins de cache**: Cache do site (ex: WP Rocket) deve ser limpa quando restrições são atualizadas
- **Todos os médicos bloqueados para um serviço**: Sistema deve mostrar mensagem apropriada
- **Base de dados corrompida**: Sistema deve ter mecanismo de recovery
**Limitações Técnicas:**
- Restrições dependem da estrutura e hooks do KiviCare; atualizações majoritárias podem quebrar funcionalidade
- Performance pode ser fator em sites com milhares de médicos/serviços, exigindo otimização
- Deve ser desenvolvido como plugin WordPress standard seguindo boas práticas
- Manter compatibilidade com versões mais recentes do WordPress e KiviCare
## Requirements *(mandatory)*
### Functional Requirements
**Core Obrigatórios:**
- **FR-001**: System MUST provide admin panel to activate/deactivate doctor visibility
- **FR-002**: System MUST provide admin panel to activate/deactivate service visibility per doctor
- **FR-003**: Restrictions MUST apply only to frontend (public booking); backend MUST maintain full visibility
- **FR-004**: System MUST integrate transparently with KiviCare hooks to filter doctor and service lists
- **FR-005**: System MUST create database table (`wp_care_booking_restrictions`) to persist rules
- **FR-006**: System MUST use CSS-first approach to avoid shortcode conflicts from previous versions
- **FR-007**: System MUST provide visual confirmation when restriction changes are saved
- **FR-008**: System MUST gracefully handle KiviCare plugin deactivation without breaking website
- **FR-009**: System MUST have <5% performance overhead on appointment page loading
- **FR-010**: System MUST restrict management to WordPress administrators and editors
**Nice-to-Have (Roadmap):**
- **FR-011**: System SHOULD log all restriction changes (who changed what and when)
- **FR-012**: System SHOULD provide Import/Export functionality for restriction configurations
- **FR-013**: System SHOULD show admin notifications about recent changes
**Success Metrics:**
- 100% reduction of bookings for doctors/services that should be hidden
- <2 minutes configuration time for administrators
- 100% adoption by platform administrators in first month
- 0 support tickets for "cannot find doctor X" when intentionally hidden
### Key Entities *(include if feature involves data)*
**wp_care_booking_restrictions Table:**
- **id**: Auto-increment primary key
- **restriction_type**: ENUM('doctor', 'service') - Type of restriction
- **target_id**: INT - ID of doctor or service being restricted
- **doctor_id**: INT - For service restrictions, which doctor it applies to
- **is_blocked**: BOOLEAN - Whether the item is blocked from public view
- **created_at**: TIMESTAMP - When restriction was created
- **updated_at**: TIMESTAMP - When restriction was last modified
**Future Entities (Nice-to-Have):**
- **wp_care_booking_logs**: Audit trail of all changes
- **Scheduling Data**: Start/end dates for temporary restrictions
---
## Review & Acceptance Checklist
*GATE: Automated checks run during main() execution*
### Content Quality
- [x] No implementation details (languages, frameworks, APIs)
- [x] Focused on user value and business needs
- [x] Written for non-technical stakeholders
- [x] All mandatory sections completed
### Requirement Completeness
- [x] No [NEEDS CLARIFICATION] markers remain
- [x] Requirements are testable and unambiguous
- [x] Success criteria are measurable
- [x] Scope is clearly bounded
- [x] Dependencies and assumptions identified
### Technical Constraints
- WordPress 5.0+ required
- KiviCare Plugin 3.0.0+ required
- PHP 7.4+ required
- MySQL database access required
---
## Execution Status
*Updated by main() during processing*
- [x] User description parsed
- [x] Key concepts extracted
- [x] Ambiguities marked
- [x] User scenarios defined
- [x] Requirements generated
- [x] Entities identified
- [x] Review checklist passed
---

View File

@@ -0,0 +1,197 @@
# Tasks: WordPress Plugin para Controlo Seguro de Agendamentos KiviCare
**Input**: Design documents from `/specs/001-wordpress-plugin-para/`
**Prerequisites**: plan.md, research.md, data-model.md, contracts/admin-api.md, quickstart.md
**Project Type**: WordPress Plugin (Single Project Structure)
## Execution Flow (main)
```
1. Load plan.md from feature directory
→ Extract: PHP 7.4+, WordPress 5.0+, KiviCare 3.0.0+, MySQL 5.7+
→ Structure: Single WordPress plugin project
2. Load design documents:
→ data-model.md: wp_care_booking_restrictions entity → model tasks
→ contracts/admin-api.md: 4 AJAX endpoints → contract test tasks
→ quickstart.md: 8 test scenarios → integration test tasks
3. Generate WordPress plugin tasks:
→ Setup: plugin structure, activation hooks, autoloader
→ Tests: AJAX contract tests, KiviCare integration tests
→ Core: database models, admin interface, frontend filtering
→ Integration: KiviCare hooks, cache system, CSS injection
→ Polish: validation tests, performance optimization
4. Applied task rules:
→ Different PHP files = mark [P] for parallel
→ Same file modifications = sequential (no [P])
→ Tests before implementation (WordPress TDD)
5. Numbered tasks sequentially (T001-T025)
6. WordPress-specific dependencies validated
7. SUCCESS (tasks ready for WordPress development)
```
## Format: `[ID] [P?] Description`
- **[P]**: Can run in parallel (different files, no dependencies)
- All paths relative to WordPress plugin root directory
## Path Conventions (WordPress Plugin Structure)
```
care-booking-block/ # Plugin root
├── care-booking-block.php # Main plugin file
├── includes/ # Core classes
│ ├── class-care-booking-core.php
│ ├── class-database-handler.php
│ ├── class-admin-interface.php
│ └── class-kivicare-integration.php
├── admin/ # Admin interface
│ ├── css/admin-style.css
│ ├── js/admin-script.js
│ └── partials/
├── public/ # Frontend assets
│ ├── css/public-style.css
│ └── js/frontend-script.js
└── tests/ # PHPUnit tests
├── unit/
├── integration/
└── bootstrap.php
```
## Phase 3.1: WordPress Plugin Setup
- [ ] T001 Create WordPress plugin directory structure per WordPress standards
- [ ] T002 Initialize main plugin file care-booking-block.php with headers and activation hooks
- [ ] T003 [P] Configure PHPUnit for WordPress testing with WP_UnitTestCase
- [ ] T004 [P] Set up WordPress coding standards and PHPCS configuration
## Phase 3.2: Database & Models (TDD) ⚠️ MUST COMPLETE BEFORE 3.3
**CRITICAL: These tests MUST be written and MUST FAIL before ANY implementation**
- [ ] T005 [P] Database schema test for wp_care_booking_restrictions table in tests/unit/test-database-schema.php
- [ ] T006 [P] Restriction model CRUD test in tests/unit/test-restriction-model.php
- [ ] T007 [P] WordPress cache integration test in tests/unit/test-cache-integration.php
## Phase 3.3: Contract Tests (WordPress AJAX) ⚠️ MUST COMPLETE BEFORE 3.4
**CRITICAL: These tests MUST be written and MUST FAIL before implementing AJAX handlers**
- [ ] T008 [P] Contract test wp_ajax_care_booking_get_restrictions in tests/unit/test-ajax-get-restrictions.php
- [ ] T009 [P] Contract test wp_ajax_care_booking_toggle_restriction in tests/unit/test-ajax-toggle-restriction.php
- [ ] T010 [P] Contract test wp_ajax_care_booking_bulk_update in tests/unit/test-ajax-bulk-update.php
- [ ] T011 [P] Contract test wp_ajax_care_booking_get_entities in tests/unit/test-ajax-get-entities.php
## Phase 3.4: KiviCare Integration Tests ⚠️ MUST COMPLETE BEFORE 3.5
**CRITICAL: These tests MUST be written and MUST FAIL before implementing hooks**
- [ ] T012 [P] Integration test KiviCare doctor filtering in tests/integration/test-doctor-filtering.php
- [ ] T013 [P] Integration test KiviCare service filtering in tests/integration/test-service-filtering.php
- [ ] T014 [P] Integration test CSS injection on wp_head in tests/integration/test-css-injection.php
## Phase 3.5: Core Implementation (ONLY after tests are failing)
- [ ] T015 [P] Database handler class in includes/class-database-handler.php
- [ ] T016 [P] Restriction model class in includes/class-restriction-model.php
- [ ] T017 [P] Cache manager class in includes/class-cache-manager.php
- [ ] T018 WordPress plugin activation hook with database table creation
- [ ] T019 WordPress plugin deactivation hook with cleanup
- [ ] T020 PSR-4 autoloader implementation in care-booking-block.php
## Phase 3.6: Admin Interface Implementation
- [ ] T021 Admin menu registration and capability checks
- [ ] T022 [P] Admin page HTML template in admin/partials/admin-display.php
- [ ] T023 [P] Admin CSS styling in admin/css/admin-style.css
- [ ] T024 [P] Admin JavaScript for AJAX in admin/js/admin-script.js
- [ ] T025 AJAX handler wp_ajax_care_booking_get_restrictions implementation
- [ ] T026 AJAX handler wp_ajax_care_booking_toggle_restriction implementation
- [ ] T027 AJAX handler wp_ajax_care_booking_bulk_update implementation
- [ ] T028 AJAX handler wp_ajax_care_booking_get_entities implementation
## Phase 3.7: Frontend Integration
- [ ] T029 KiviCare doctor list filter hook implementation
- [ ] T030 KiviCare service list filter hook implementation
- [ ] T031 [P] Dynamic CSS generation for blocked elements
- [ ] T032 [P] Frontend JavaScript for graceful degradation in public/js/frontend-script.js
- [ ] T033 WordPress wp_head hook for CSS injection
## Phase 3.8: Security & Validation
- [ ] T034 WordPress nonce validation for all AJAX endpoints
- [ ] T035 User capability checks (manage_options) for admin functions
- [ ] T036 [P] Input sanitization using WordPress functions
- [ ] T037 [P] Output escaping for XSS prevention
- [ ] T038 SQL injection prevention with $wpdb->prepare()
## Phase 3.9: Performance & Caching
- [ ] T039 WordPress transients integration for restriction caching
- [ ] T040 Cache invalidation on restriction changes
- [ ] T041 [P] Database query optimization with proper indexes
- [ ] T042 [P] Asset minification for production
## Phase 3.10: Integration Validation (From quickstart.md)
- [ ] T043 [P] End-to-end test: Block doctor from public booking in tests/integration/test-e2e-block-doctor.php
- [ ] T044 [P] End-to-end test: Hide service for specific doctor in tests/integration/test-e2e-hide-service.php
- [ ] T045 [P] End-to-end test: Frontend booking form validation in tests/integration/test-e2e-frontend-validation.php
- [ ] T046 [P] Performance validation test (<5% overhead) in tests/integration/test-performance.php
- [ ] T047 [P] Error handling test (KiviCare deactivated) in tests/integration/test-error-handling.php
- [ ] T048 [P] Cache plugin compatibility test in tests/integration/test-cache-compatibility.php
## Phase 3.11: Polish & Documentation
- [ ] T049 [P] WordPress plugin readme.txt with installation instructions
- [ ] T050 [P] Inline PHP documentation following WordPress standards
- [ ] T051 Code cleanup and WordPress coding standards validation
- [ ] T052 Final security audit and vulnerability testing
## Dependencies
**Critical WordPress TDD Flow:**
- Database/Model tests (T005-T007) before implementation (T015-T020)
- Contract tests (T008-T011) before AJAX implementation (T025-T028)
- Integration tests (T012-T014) before hook implementation (T029-T033)
**Sequential Dependencies:**
- T001 blocks T002-T004 (structure before setup)
- T015 blocks T025-T028 (database before AJAX)
- T016 blocks T025-T028 (models before AJAX)
- T018-T020 block T021-T024 (core before admin)
- T025-T028 block T029-T033 (AJAX before hooks)
- All implementation before validation (T043-T048)
## WordPress Plugin Parallel Execution Examples
```bash
# Phase 3.2: Database tests (run together)
Task: "Database schema test for wp_care_booking_restrictions in tests/unit/test-database-schema.php"
Task: "Restriction model CRUD test in tests/unit/test-restriction-model.php"
Task: "WordPress cache integration test in tests/unit/test-cache-integration.php"
# Phase 3.3: Contract tests (run together)
Task: "Contract test wp_ajax_care_booking_get_restrictions in tests/unit/test-ajax-get-restrictions.php"
Task: "Contract test wp_ajax_care_booking_toggle_restriction in tests/unit/test-ajax-toggle-restriction.php"
Task: "Contract test wp_ajax_care_booking_bulk_update in tests/unit/test-ajax-bulk-update.php"
Task: "Contract test wp_ajax_care_booking_get_entities in tests/unit/test-ajax-get-entities.php"
# Phase 3.5: Core classes (run together)
Task: "Database handler class in includes/class-database-handler.php"
Task: "Restriction model class in includes/class-restriction-model.php"
Task: "Cache manager class in includes/class-cache-manager.php"
```
## WordPress-Specific Notes
- Follow WordPress Plugin Development Guidelines
- Use WordPress hooks and filters, never modify core files
- All database operations use $wpdb with prepared statements
- Admin interface uses WordPress native styling
- Frontend integration respects theme compatibility
- Security follows WordPress standards (nonces, capabilities, sanitization)
- Performance targets: <5% overhead, <300ms AJAX responses
## Validation Checklist
*Applied during task execution*
**WordPress Plugin Requirements:**
- [x] All AJAX endpoints have contract tests
- [x] All database entities have model tasks
- [x] All hooks have integration tests
- [x] All tests come before implementation (TDD)
- [x] Parallel tasks use different files
- [x] Each task specifies exact file path
- [x] WordPress coding standards enforced
- [x] Security best practices included
- [x] Performance requirements addressed
- [x] KiviCare compatibility maintained
**Task Generation Sources:**
- From contracts/admin-api.md: 4 AJAX endpoints → 4 contract tests + 4 implementations
- From data-model.md: wp_care_booking_restrictions → database + model tasks
- From quickstart.md: 8 test scenarios → 6 integration validation tasks
- From plan.md: WordPress plugin structure → setup and architecture tasks
**Total Tasks**: 52 WordPress plugin development tasks following TDD methodology