Documentation page — not a working feature. This describes what a WordPress developer must build in the Sara Care plugin. All prototypes in this staff area are static designs.

Custom plugin integration specification

Developer-ready brief for the Sara Care plugin (Phase 2b). Written against the Phase 1–3 preview pages, so every screen already exists as a design to implement.

1. Scope, status and what exists today

Feature status
AreaIn the preview todayNeeds the plugin
Public pages, branding, navigationBuilt and completeNothing
5-step booking formWorking form (Kreebi), saves submissions, emails adminServer-side ID generation, patient lookup, real test catalogue, status writes
Test selectionFree-text field plus the published catalogue pageDynamic checkbox selection bound to the catalogue table
Reception, patients, visits, reports, billing, staff, portalStatic prototypes with demo dataEvery data operation, auth and file storage

2. Required database tables

Use dbDelta() with {$wpdb->prefix}sc_ tables. Times stored as datetime in site timezone (Asia/Kolkata), never as strings.

Database schema
TableKey columnsRelationships
sc_patientsid, patient_code (UNIQUE), full_name, mobile, mobile_norm, email, age, gender, address, notes, created_at, created_by, updated_at, updated_by1→many visits, bookings, invoices
sc_bookingsid, booking_ref (UNIQUE), patient_id, source (online/walkin/reception), status, requested_date, requested_slot, visit_type, collection_address, collection_slot, contact_person, collection_instructions, notes, categories_json, consent_at, created_at, created_by, updated_at, updated_bypatient_id → sc_patients; 0..1 → visits
sc_visitsid, visit_code (UNIQUE), patient_id, booking_id (NULL for walk-in), visit_type, visit_status, workflow_colour (orange/blue/green), scheduled_at, sample_collected_at, collected_by, created_at, updated_at, updated_bypatient_id, booking_id; 1→many test_orders; 1→many status_history
sc_test_ordersid, order_code (UNIQUE), visit_id, test_id, category, price_snapshot, status, report_status, sample_status, ordered_at, performed_by, authorised_by, authorised_atvisit_id → sc_visits; test_id → sc_tests
sc_testsid, test_code, name, category, description, preparation, report_time, price, is_package, is_active, enquiry_only (bool), updated_by, updated_atreferenced by test_orders and packages
sc_packages / sc_package_itemspackage id, name, price, description, is_active / package_id, test_idMany-to-many with sc_tests
sc_status_historyid, visit_id, test_order_id (NULL), from_status, to_status, colour, note, staff_id, created_atvisit_id, staff_id
sc_reportsid, test_order_id, version, file_path (private), mime, file_size, uploaded_by, uploaded_at, review_status, authorised_by, authorised_at, published_at, replaces_id, is_currenttest_order_id; was replaced by another row
sc_report_handoverid, report_id, receiver_name, receiver_type, handed_by, handed_at, print_count, last_printed_at, remarksreport_id → sc_reports
sc_invoices / sc_invoice_items / sc_paymentsinvoice id, invoice_no, patient_id, visit_id, subtotal, discount, total, paid, balance, method, created_by / item lines / payment rows with txn refpatient_id, visit_id
sc_staff_logid, staff_id, action, object_type, object_id, detail_json, ip, created_atstaff_id → wp_users
sc_login_logid, staff_id, event (login/logout/failed), ip, user_agent, created_atstaff_id
sc_messagesid, booking_id/visit_id, channel (whatsapp/email), template, body, queued_at, sent_at, status (queued/sent/failed), provider_ref, staff_idbooking_id, visit_id

3. Identifiers (server-generated only)

  • Patient ID SC-{YYYY}-{000001} — sequence per calendar year, allocated in the same DB transaction as the patient insert, retried on unique-key collision. Never generated in the browser.
  • Booking Reference SCB-{YYYY}-{000001}
  • Visit ID SCV-{YYYY}-{000001}
  • Test Order ID TO-{YYYY}-{000001}
  • Invoice number INV-{YYYY}-{000001}
  • Use a dedicated sc_sequences row per prefix/year with SELECT … FOR UPDATE, or MySQL auto-increment plus a formatted code column. Return 409 and retry on collision.

4. Staff roles and permissions

Role matrix
CapabilityReceptionistTechnicianClinical reviewerAdministrator
Register patient / walk-inYesNoNoYes
Confirm, reschedule, cancel bookingYesNoNoYes
Update sample statusYesYesNoYes
Upload reportNoYesYesYes
Clinically authorise / publish reportNoNoYes (only)Yes with reviewer flag
Hand over report, reprintYesNoNoYes
Billing, receipts, daily closingYesNoNoYes
Test catalogue and pricesNoNoNoYes
Staff management, roles, logsNoNoNoYes

Map to sc_receptionist, sc_technician, sc_reviewer, sc_admin. Enforce with current_user_can() on every admin-post/REST callback plus a nonce; never hide UI only. Authorisation additionally requires a stored qualification flag on the user (registration number of the medical council) that an administrator sets.

5. Booking form wiring (existing Kreebi form)

The live form is the Kreebi form test-booking on page /book-a-test/. Kreebi emails submissions; the plugin must additionally capture them.

Field mapping
Kreebi field label (exact)TypeMaps toRule
Which services do you need?checkboxbookings.categories_jsonRequired; multiple allowed; X-Ray stored as enquiry only
I am not sure which test I need. Please contact me.checkboxbookings.contact_me_onlyIf set, test selection not required
Tests or package you needtextbookings.tests_free_textKept as fallback; replaced by test_ids when the dynamic picker lands
Doctor's advice or notes about the testtextareabookings.notesOptional
Full nametextpatients.full_nameRequired
Mobile numbertextpatients.mobile / mobile_normRequired; normalise to E.164; reject invalid Indian numbers
Email addressemailpatients.emailOptional everywhere; never block submission
Agenumberpatients.ageOptional, 0–120
Genderdropdownpatients.genderOptional
Existing Patient IDtextbookings.claimed_patient_codeLook up; if found attach to patient, else create new patient and flag for staff review
Additional notestextareapatients.notesOptional
Preferred appointment datetext (currently)bookings.requested_dateChange to a date field in Kreebi; store as date, must be today or later
Preferred appointment timedropdownbookings.requested_slotSlot enum: 8-11, 11-14, 14-17, 17-20
Visit typeradiobookings.visit_typeRequired: centre | home_collection
Collection address / Preferred collection time / Contact person at address / Additional instructions for our collectortextarea, dropdown, text, textareabookings.collection_*Required when visit_type = home_collection; availability confirmed by staff
Consent checkbox (privacy)checkboxbookings.consent_atRequired; store timestamp and the wording version
Requests-until-confirmed checkboxcheckboxbookings.ack_request_onlyRequired

Other Kreebi forms to integrate: report-request on /download-report/ (fields: Patient full name, Registered mobile number, Lab, bill or registration number, Date of sample collection, Tests done, How would you like the report, Email address, Who is requesting the report, Additional notes) and contact on /contact-us/.

6. Endpoints

REST namespace sara-care/v1, all requiring a valid session plus nonce or an application password. Every write validates with a schema and writes an audit row.

REST endpoints
Method + routePurposePermission
POST /bookingsCreate booking from the public form: create/match patient, allocate codes, status pending_confirmationpublic + rate limit + honeypot
GET /bookingsFiltered list for the dashboard (date, status, source, search)receptionist
PATCH /bookings/{ref}Confirm, reschedule, cancel, add reception notereceptionist
GET /catalogueActive tests and packages for the picker, grouped by categorypublic (no prices unless configured)
POST /patients, GET /patients?q=Register and search patientsreceptionist
POST /visitsCreate visit + test orders (walk-in or from a confirmed booking)receptionist
PATCH /visits/{code}/statusSample and workflow transitions with staff name and timestampreceptionist / technician
POST /reports, POST /reports/{id}/authoriseUpload a version; authorise and publishtechnician uploads; reviewer authorises
POST /invoices, GET /reports/dailyBilling and daily collection summaryreceptionist
POST /portal/verify, GET /portal/summaryIdentity check then booking/visit/report summarypatient, verified per request
POST /messages/whatsappBuild a wa.me deep link for a verified mobile number; log queued/sentreceptionist

7. Status workflows

Workflow states
StageStatesColourWho sets it
Bookingpending_confirmation → confirmed → rescheduled / cancelled / completed / no_showGrey → orange on arrivalReceptionist
Samplesample_pending, collected, rejected, recollection_required, outside_lab_dispatchOrange #D97706Receptionist / technician
Processingreceived, processing, report_pending, partial_reportBlue #2563EBTechnician
Reportuploaded → pending_review → authorised → published → handed_overGreen #16A34A when every order on the visit is publishedReviewer publishes; receptionist hands over

Store workflow state on the visit and each test order, never on the patient. The visit colour is derived: orange while any order is sample pending, blue while any order is processing or report pending, green only when every required order is authorised and published. Every transition inserts into sc_status_history with the logged-in staff id and timestamp.

8. Report files, privacy and patient access

  • Upload to wp-content/uploads/sara-care-reports/ outside the public media library, or to a bucket; serve only through a PHP endpoint that checks capability or a short-lived signed token.
  • Accept PDF only, verify MIME by content, max 20 MB, randomise filenames, block PHP execution in that directory (.htaccess deny or nginx rule).
  • Never reuse a file row: replacing a report inserts a new version with replaces_id and keeps the old row as history.
  • Authorisation is a separate action from upload and requires the reviewer role plus the qualification flag; store reviewer id, timestamp and version.
  • Patient access: verify identity with booking reference + registered mobile (+ optional date of birth) before returning anything; rate limit to 5 attempts per 15 minutes per IP and per mobile; issue a token valid 15 minutes; log every access attempt.
  • Handover records receiver name, receiver type, staff, timestamp, version and remarks; reprints increment a counter rather than overwriting history.

9. WhatsApp and email

  • Phase 1 uses click-to-chat only: the plugin builds https://wa.me/91<verified mobile>?text=<urlencoded message> and the receptionist sends it manually. No automated WhatsApp sending is assumed.
  • Templates: booking received, appointment confirmed, reminder, report ready, rescheduled, cancellation, payment reminder. Message text includes patient name, Patient ID, booking reference, requested date/time, status and the centre's phone number.
  • Log every generated message with staff id and status queued/sent/failed; treat "opened in WhatsApp" as queued, since delivery cannot be confirmed by click-to-chat.
  • Email: use wp_mail() and record the actual return value and provider response. Acknowledgement email only when the patient supplied an address and delivery is configured; a missing or failed email never blocks a booking.

10. X-Ray and clinical safeguards

  • X-Ray rows carry enquiry_only = 1: the public form can record an enquiry but must not create a confirmed appointment or take payment.
  • Guard with a setting the administrator enables only after AERB authorisation and operational readiness; the UI keeps showing the enquiry path meanwhile.
  • No clinical interpretation is generated anywhere on the site; reports are uploaded documents authorised by a qualified reviewer.
  • Prices are shown only where an administrator has configured them; an empty price renders "Price on enquiry".

11. Security checklist

  • Nonces on every state change, capability checks server-side, prepared statements through $wpdb->prepare(), sanitise on input and escape on output.
  • Never trust a client-supplied patient id, status or price; re-read from the database inside the transaction.
  • Two-factor optional for staff, forced password reset on first login, lockout after 5 failures, session expiry, full login/logout log.
  • Rate limit the public booking and portal endpoints; honeypot plus time-trap on the public form.
  • Daily database backup before go-live, and a staging copy for testing; keep medical data retention rules documented in the privacy policy.

12. Files, slugs and components to hand over

Kreebi draft files
FileWhat it isIntegration note
pages/index.htmlPublic home pageNo data binding
pages/book-a-test.htmlBooking page + Kreebi form markerReplace free-text test field with the picker component
pages/laboratory-tests.htmlPublished test catalogueDrive from sc_tests when dynamic
pages/download-report.htmlReport request formRoute to plugin instead of email only
pages/staff-login.htmlStaff sign-in designUse wp_login_form() or a custom login with rate limiting
pages/reception-dashboard.htmlDashboard prototypeReplace demo rows with GET /bookings
pages/patient-registration.htmlAdd patient, search, profile, walk-in, visitBind to patient and visit endpoints
pages/visit-status.htmlSample and visit boardBind to visit status transitions
pages/report-management.htmlUpload, versions, review, handoverBind to report endpoints and private storage
pages/billing.htmlBill, receipt, daily closing, WhatsAppBind to invoice endpoints; INR formatting
pages/patient-portal.htmlPublic patient status and reportsPublic page; data only after verification
pages/admin-dashboard.htmlAdmin, staff, roles, logsMap to WordPress users and capabilities
pages/test-catalogue.htmlPicker demo + catalogue admin UIReference implementation for the picker
assets/staff.css, assets/staff.jsStaff styling and picker behaviourReuse inside plugin admin screens
forms/test-booking.json, report-request.json, contact.jsonKreebi form definitions with exact field labelsMap labels per section 5

Suggested plugin layout: sara-care-core/ with sara-care-core.php, includes/db.php, includes/ids.php, includes/roles.php, includes/rest-bookings.php, includes/rest-reports.php, includes/audit.php, admin/dashboard.php, assets/. Page templates for the staff area should be reachable only to logged-in staff.

13. Suggested build order

  1. Tables, roles and the ID allocator, with unit tests for collision behaviour.
  2. Patient create/search and booking intake hooked to the Kreebi form.
  3. Reception dashboard list plus confirm/reschedule/cancel.
  4. Visit and test order creation, including walk-ins.
  5. Sample and workflow status transitions with history.
  6. Report upload, review, publish, handover and version history.
  7. Billing, receipts and daily closing.
  8. Patient portal verification and report access.
  9. Staff management, activity log and login history.
  10. Dynamic test picker replacing the free-text field on the public form.

Acceptance for go-live: no personal or clinical data is reachable without a capability check or a verified portal session; every write appears in the audit log with a staff id; and X-Ray stays enquiry-only until an administrator enables it.