Toggle menu
Toggle preferences menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

About:Pharmacopedia.ext: Difference between revisions

From Pharmacopedia
[checked revision][checked revision]
Migrate <indication> tags to <problem> (Phase 2 of indications-to-problems rebuild)
Refresh: reflect current extension state (problems renaming, 0-100 sliders, ±100 valence, ICD ingest, autosave, rich reports, demographics rebuild)
Line 1: Line 1:
{{TOC right}}
{{TOC right}}
= Pharmacopedia extension specification =
= Pharmacopedia extension specification =


'''Version:''' 0.7.10  ·  '''Requires:''' MediaWiki ≥ 1.45.0
'''Requires:''' MediaWiki ≥ 1.46.0 · PHP ≥ 8.5
'''Author:''' MDElliottMD · '''License:''' GPL-2.0-or-later
'''Author:''' MDElliottMD · '''License:''' GPL-2.0-or-later
'''Source:''' <code>/var/www/mediawiki/extensions/Pharmacopedia/</code>
'''Source:''' <code>/var/www/mediawiki/extensions/Pharmacopedia/</code>


The Pharmacopedia extension turns a MediaWiki install into a structured, community-edited med reference. It adds parser tags, special pages, API modules, and a database schema that together support:
The Pharmacopedia extension turns a MediaWiki install into a structured, community-edited medicine reference with rich user-profile and assessment infrastructure. It adds parser tags, special pages, API modules, a chip-picker / autosave UI framework, and a database schema that together support:


* Structured med pages via the <code>{{tlx|MedTemplate}}</code> template
* Structured medicine pages via the <code><nowiki>{{MedTemplate}}</nowiki></code> template
* Per-user rating, voting, and reporting on effects, indications, titration strategies, anecdotes, and interactions
* Per-user rating on effects, problems, titration strategies, anecdotes, and drug-drug interactions (continuous 0–100 sliders, ±100 valence; no 0–5 likert anywhere)
* Two-perspective data capture (personal vs. provider) wherever clinically meaningful
* Two-perspective data capture (personal vs. provider) wherever clinically meaningful
* Curated med-class categories used as interaction endpoints
* User profile with dimensional personality / autism assessments (CATI, CAT-Q, MBTI, Enneagram, PID-5-BF, OCEAN/BFI-10) and rich auto-generated reports
* A verified-provider role with document-based verification
* Diagnosis autocomplete backed by ~25,500 ICD-10-CM and ~15,800 ICD-11 codes
* Chip-picker / autosave / slider-precise-input UI framework shared across editor surfaces
* Verified-provider role with document-based verification
 
== Precision doctrine ==
 
A standing design rule (memorialised 2026-05-17) that shapes every storage / UI decision in the extension:
 
* '''No bucketing where a number or free-text will do.''' Income is numeric + currency, not a 5-band dropdown. Education keeps the bucketed dropdown ''and'' adds numeric years of schooling + free-text field of study.
* '''No single-select where multi-select reflects reality.''' Languages, gender identities, ethnicities, pronouns, religion, marital status, stop-reasons, all use chip-pickers (with optional severity per chip where relevant).
* '''No forced category where a continuous score works.''' All assessments (Enneagram 9 type sliders, MBTI 4 dichotomy sliders, OCEAN 5 trait sliders, CATI/CAT-Q/PID-5-BF items) use continuous 0–100 sliders, never radio buttons or button rows. Valence is ±100, not ±3.
* '''Storage in canonical form, UI converts at display.''' Heights stored cm regardless of user's preferred unit (cm or ft+in); ICD codes stored as ISO; date capture as range / possibility-mix JSON.
* '''Browser auto-fill as suggestion only.''' Country chip pre-fills from <code>navigator.language</code>; languages from <code>navigator.languages</code>; time zone from <code>Intl.DateTimeFormat().resolvedOptions().timeZone</code>. User can always edit or remove.
* '''Always allow custom free-text where the curated list might miss someone.''' Chip-pickers accept Enter-to-add custom chips for all picklists except ISO-coded ones (country, language).


== High-level architecture ==
== High-level architecture ==


* '''Backend (PHP):''' <code>includes/</code> one class per parser tag, store, special page, or API module. Auto-loaded under <code>MediaWiki\Extension\Pharmacopedia\</code>.
* '''Backend (PHP):''' <code>includes/</code>, one class per parser tag, store, special page, or API module. Auto-loaded under <code>MediaWiki\Extension\Pharmacopedia\</code>. Assessment classes under <code>includes/Assessments/</code>.
* '''Frontend (JS):''' <code>resources/ext.pharmacopedia.js</code> single IIFE binding click handlers, modals, and inline AJAX submits.
* '''Frontend (JS):''' <code>resources/ext.pharmacopedia.js</code>, single IIFE binding click handlers, modals, chip-pickers, autocomplete, autosave debouncer, slider-precise click-to-type. <code>resources/ext.pharmacopedia.blocksave.js</code> is the autosave infrastructure (debounced AJAX per block, race-safe).
* '''Styles (CSS):''' <code>resources/ext.pharmacopedia.css</code> shared row layout, per-tag chrome, dark-theme-friendly colors.
* '''Styles (CSS):''' <code>resources/ext.pharmacopedia.css</code>, shared row layout, per-tag chrome, dark-theme palette (black / dark-grey / purple / white primary; red / green / blue / teal sparingly for semantic distinction).
* '''Schema:''' <code>sql/</code> — ten core tables plus four migration patches. Picked up via the <code>LoadExtensionSchemaUpdates</code> hook.
* '''Datepicker:''' <code>resources/ext.pharmacopedia.datepicker.js</code> + <code>.css</code>, supports single dates, ranges, and possibility-mixed dates (e.g. "1995 or 1996").
* '''Schema:''' <code>sql/</code>, ~20 core tables plus migration patches. Picked up via <code>LoadExtensionSchemaUpdates</code> hook.


== Parser tags ==
== Parser tags ==


All eight tags are registered via <code>Hooks::onParserFirstCallInit</code>:
Registered via <code>Hooks::onParserFirstCallInit</code>:


{| class="wikitable"
{| class="wikitable"
Line 30: Line 44:
| <code>&lt;vote&gt;</code> || Generic up/down binary vote on an arbitrary slug || <code>VoteTag</code>
| <code>&lt;vote&gt;</code> || Generic up/down binary vote on an arbitrary slug || <code>VoteTag</code>
|-
|-
| <code>&lt;effect&gt;</code> || Therapeutic or adverse effect, dual patient/provider perspectives || <code>EffectTag</code>
| <code>&lt;effect&gt;</code> || Therapeutic or adverse effect; patient + provider perspectives; provider freq slider 0–100; shared valence slider ±100 || <code>EffectTag</code>
|-
|-
| <code>&lt;discuss&gt;</code> || Threaded comment widget || <code>CommentTag</code>
| <code>&lt;discuss&gt;</code> || Threaded comment widget || <code>CommentTag</code>
Line 40: Line 54:
| <code>&lt;anecdote&gt;</code> || Personal or provider story with up/down vote || <code>AnecdoteTag</code>
| <code>&lt;anecdote&gt;</code> || Personal or provider story with up/down vote || <code>AnecdoteTag</code>
|-
|-
| <code>&lt;indication&gt;</code> || Condition the med is used for, 0–5 likert rating || <code>IndicationTag</code>
| <code>&lt;problem&gt;</code> || A problem (formerly "indication") the medicine addresses; 0–100 efficacy likert slider + "don't know" toggle || <code>ProblemTag</code>
|-
|-
| <code>&lt;pharmaInteractions/&gt;</code> || Self-closing; renders the Interactions section for the current page || <code>InteractionTag</code>
| <code>&lt;pharmaInteractions/&gt;</code> || Self-closing; renders the Interactions section for the current page || <code>InteractionTag</code>
|-
| <code>&lt;pharmaExperience/&gt;</code> || Self-closing; renders the Experience report form (efficacy, burden, dose, route, schedule, stop-reasons) || <code>ExperienceTag</code>
|}
|}


All tags except <code>&lt;pharmaInteractions/&gt;</code> take a <code>slug</code> argument and (where relevant) a <code>title</code>, <code>label</code>, <code>author</code>, <code>ref</code>, or <code>perspective</code>.
All non-self-closing tags take a <code>slug</code> argument and (where relevant) a <code>title</code>, <code>label</code>, <code>author</code>, <code>ref</code>, or <code>perspective</code>.


=== Tag wikitext examples ===
=== Tag wikitext examples ===


<pre>
<pre>
<problem slug="ssri-depression" title="Major depressive disorder"
<problem slug="depression" title="Major depressive disorder"
   author="MDElliottMD">Use cautiously in adolescents.</problem>
   author="MDElliottMD">First-line for moderate to severe MDD.</problem>


<effect slug="nausea" label="Nausea"/>
<effect slug="nausea" label="Nausea"/>
Line 64: Line 80:


<pharmaInteractions/>
<pharmaInteractions/>
<pharmaExperience/>
</pre>
</pre>
== The unified compact row layout ==
Indication, Effect, Interaction, Titration, and Anecdote all render through a shared row pattern:
<pre>
<div class="pcp-row pcp-row-{type} pcp-{type}" ...data-*>
  <div class="pcp-row-head">
    <span class="pcp-row-title">...</span>
    <span class="pcp-row-aggs">...</span>
    <span class="pcp-row-actions">
      <button class="pcp-row-action pcp-row-action-toggle" data-target="rate">Rate</button>
      [<button data-target="notes">Notes (N)</button>]    # only for Interaction
      [× delete button]                                  # only for sysop/admin
    </span>
  </div>
  [<div class="pcp-row-panel pcp-row-rate-panel"  hidden>...</div>]
  [<div class="pcp-row-panel pcp-row-notes-panel"  hidden>...</div>]
  [<div class="pcp-row-body">...wikitext body, always visible if present...</div>]
</div>
</pre>
* Rate / Notes panels are hidden by default; the shared <code>.pcp-row-action-toggle</code> JS handler reveals them inline on click.
* Bodies (page-specific descriptions for Indication / Effect / Titration / Anecdote) are always visible.
* The <code>×</code> admin delete button uses the established <code>.pcp-del-btn</code> pattern (or <code>.pcp-ix-del-row</code> for interactions).
* Each row sits in its own block-formatting context (<code>display: flow-root</code>) so its border-box respects floated infoboxes.


== Voting / rating semantics ==
== Voting / rating semantics ==
Line 101: Line 92:
| Titration || +1 / −1 binary || single || <code>pcp_votes</code>
| Titration || +1 / −1 binary || single || <code>pcp_votes</code>
|-
|-
| Anecdote || +1 / −1 binary || single (perspective is a metadata label, not a separate aggregate) || <code>pcp_votes</code>
| Anecdote || +1 / −1 binary || single (perspective is metadata) || <code>pcp_votes</code>
|-
|-
| Indication || 0–5 likert + "don't know" || single || <code>pcp_likert_reports</code>
| Problem (efficacy likert) || 0–100 continuous slider, optional "Don't know" (-1) || single || <code>pcp_likert_reports</code>
|-
|-
| Effect (patient) || experienced ∈ {yes, no, unsure} + valence −3..+3 || patient || <code>pcp_effect_reports</code> (perspective=1)
| Effect (patient) || experienced ∈ {yes, no, unsure} + valence ±100 slider || patient || <code>pcp_effect_reports</code> (perspective=1)
|-
|-
| Effect (provider) || frequency ∈ {0, 5, 20, 33, 50, 66, 80, 95, −1 don't know} + valence −3..+3 || provider || <code>pcp_effect_reports</code> (perspective=2)
| Effect (provider) || frequency 0–100 continuous slider + "Don't know" (-1) + valence ±100 slider || provider || <code>pcp_effect_reports</code> (perspective=2)
|-
|-
| Interaction || experience 1–5 + outcome −3..+3 + optional free-text note || user + provider, separate aggregates || <code>pcp_interaction_reports</code>
| Interaction || experience 1–5 + valence ±100 slider + optional note || user + provider, separate aggregates || <code>pcp_interaction_reports</code>
|}
|}


Server-side aggregates: <code>n</code>, mean of the rating field, and (where applicable) <code>severe = (vmean ≤ −2.5)</code>.
Server-side aggregates: <code>n</code>, mean of the rating field, and (for interactions) <code>severe = (vmean ≤ −83.0)</code> (rescaled from the original ±3-scale −2.5).


Aggregates are recomputed and returned by every report-submit API call so the row re-renders in place without a page reload.
Aggregates are recomputed and returned by every report-submit API call so the row re-renders in place without a page reload.
Line 127: Line 118:
| '''Uncommon''' || > 5 and ≤ 20 || collapsed
| '''Uncommon''' || > 5 and ≤ 20 || collapsed
|-
|-
| '''Rare''' || ≤ 5, provider vmean > −2.5 || collapsed
| '''Rare''' || ≤ 5, provider vmean > −83 || collapsed
|-
|-
| '''Rare but Severe''' || ≤ 5 and vmean ≤ −2.5 || '''expanded by default''', red highlight
| '''Rare but Severe''' || ≤ 5 and vmean ≤ −83 || '''expanded by default''', red highlight
|-
|-
| '''Not yet rated''' || no provider data (n=0) || collapsed, only renders if non-empty
| '''Not yet rated''' || no provider data (n=0) || collapsed, only renders if non-empty
|}
|}


The vmean ≤ −2.5 threshold is also the trip-wire for the "severe" red treatment on interaction rows.
The vmean ≤ −83 threshold is also the trip-wire for the "severe" red treatment on interaction rows.


== Interactions feature ==
== User profile ==
 
<code>Special:MyProfile</code> is the user-facing editor for everything personal. Every block on it autosaves on a 800 ms debounce (see [[#Autosave infrastructure|Autosave infrastructure]]).
 
=== Block list ===
 
* '''Identity''' (display alias, default attribution, experience-report visibility)
* '''Demographics''' (full chip-picker rebuild, see below)
* '''Personality''' (Big Five OCEAN sliders + collapsible assessments)
* '''Enneagram''' (9 type sliders + 45-item screening test)
* '''MBTI''' (4 dichotomy sliders + 32-item OEJTS test)
* '''Personality / autism assessments''' (PID-5-BF, CATI, CAT-Q, each as a collapsible inline test)
* '''Diagnoses''' (multi-row with ICD-10-CM + ICD-11 autocomplete, severity slider 0–100, disability slider 0–100, status, origin, dates, notes)
* '''Medicines I have tried''' (multi-row with med-name autocomplete, dose, route 16-option dropdown, schedule with datalist suggestions, efficacy + burden sliders 0–100, periods via date-picker)
 
=== Demographics (chip-picker / structured-widget rebuild) ===
 
All categorical demographics use the chip-picker widget (single or multi, with optional primary marker, optional custom free-text). All quantitative demographics use numeric inputs or structured composite widgets.
 
* '''Birthday''' DatePicker (single / range / possibility-mix)
* '''Sex assigned at birth''' single-select (clinical category)
* '''Gender identity''' multi-select chip-picker, 27 common terms + custom
* '''Pronouns''' multi-select chip-picker, 17 common sets + custom
* '''Ethnicity / race''' multi-select chip-picker, 23 broad categories + custom
* '''Country of residence''' chip-picker single-value, ISO 3166 list (~100 entries), auto-suggested from <code>navigator.language</code>
* '''Languages''' chip-picker multi-select with ★ primary marker, ISO 639-1 list (~70 entries with endonyms), auto-suggested from <code>navigator.languages</code>
* '''Height / weight''' unit toggle (Metric cm/kg or US ft+in/lb); stored canonically as cm/kg regardless
* '''Handedness''' single-select (3 options)
* '''Smoking''' structured widget: status + cigs/day + years smoked + quit date; auto-computes pack-years
* '''Alcohol''' structured widget: drinks/week + typical drink type + max one occasion
* '''Education''' bucketed highest-level + numeric years + free-text field of study
* '''Employment''' bucketed status + free-text occupation + numeric hours/week
* '''Income''' numeric amount + currency selector (20 options) + individual/household scope
* '''Marital / relationship status''' chip-picker single + custom
* '''Religion / spirituality''' chip-picker single + custom, 36 traditions + secular stances
* '''Housing''' chip-picker single + custom
* '''Number of children''' numeric
* '''Time zone''' free text, auto-detects IANA TZ on first load if empty
* '''Chronotype / sleep schedule''' two time inputs (typical bedtime, typical wake)
* '''Political orientation''' two-axis compass sliders (economic ±100, social ±100)
 
=== Diagnosis subsystem ===
 
Diagnoses are stored in <code>pcp_profile_diagnoses</code> with autocomplete backed by <code>pcp_diagnosis_abbreviations</code> (~41,500 rows):
 
{| class="wikitable"
! System !! Rows !! Notes
|-
| '''ICD-10-CM''' || 25,542 || CMS FY2026 valid-codes file, chapters A B C D E F G H I J K L M N O P Q R U + 553 friendly-alias rows (mdd, adhd, stroke, htn, etc.)
|-
| '''ICD-11''' || 15,823 || WHO MMS Apr 2026 linearization, chapters 01–24 except billing (22) / external causes (23) / extension modifiers (X) / functioning assessment (V) + 361 friendly-alias rows
|-
| '''DSM-5''' || 32 || Legacy hand-seed for codes without ICD equivalents
|-
| Other || 34 || somatic, unofficial, ICD-10 (WHO), instrument
|}
 
Skipped intentionally: ICD-10-CM S/T (injury body) ~41k codes, V/W/X/Y (external causes) ~7.5k codes; ICD-11 chapter 22 (injury), 23 (external causes), 25 (special purposes), V (functioning scales), X (17.7k extension modifiers). These are billing scaffolding, not diagnoses.
 
Autocomplete via <code>action=pharmacopediadxsearch</code>, multi-token AND search (e.g. "ADHD inattentive" matches the F90.0 row that contains both substrings); ORDER BY <code>FIELD(da_system, 'ICD-10-CM', 'ICD-11', 'DSM-5', ...)</code> so ICD-10-CM leads, then ICD-11, then everything else.
 
=== Personality / autism assessments ===


The Interactions section is rendered by placing <code>&lt;pharmaInteractions/&gt;</code> anywhere in the wikitext of a med article ('''NS_MAIN''') or a Category page ('''NS_CATEGORY''').
Six assessments, all with continuous-slider items, "Not sure" toggle per item, auto-computed subscale + total scores, and a rich auto-generated report at <code>Special:MyAssessment/{key}</code>:


=== Entity model ===
{| class="wikitable"
! Assessment !! Items !! Score range !! Cutoffs / threshold !! Report
|-
| '''CATI''' || 42 (6 subscales) || 1–5 per item, sum per subscale || 148 / 139 / 141 / 156 (English 2025 gender-specific) || gender-specific scoring against English 2025 normative tables (12,253-row CatiNorms.php from OSF supplementary)
|-
| '''CAT-Q''' || 25 (3 subscales) || 1–7 per item, sum per subscale || Total ≥ 110 + per-subscale cutoffs (NeurodivUrgent recalibration) || subscale narratives, top-item analysis
|-
| '''PID-5-BF''' || 25 (5 domains) || 0–3 per item, mean per domain || mean ≥ 2.0 per domain || domain narratives, cross-system mapping (DSM-5 AMPD ↔ ICD-11 PD ↔ Big Five)
|-
| '''MBTI''' || 32 OEJTS items + 4 direct dichotomy sliders || ±2 per axis || none (dimensional treatment, no forced categorisation) || 4-axis Position column with letter + strength + bar, cognitive function stack, Big Five mapping, top-item analysis
|-
| '''Enneagram''' || 45 (5 per type × 9 types) || 0–100 per type || none (no clinical cutoffs for typology) || hero banner (primary + wing + tritype), 9-bar profile, primary deep-dive, wing analysis, centers, Hornevian + Harmonic groups, stress / growth lines, cross-system map (Big Five, MBTI)
|-
| '''OCEAN (Big Five)''' || 5 direct sliders + optional BFI-10 (10 items) || 0–100 per trait || none (personality, not pathology) || trait deep-dives (high / mid / low at your score), BFI-10 item table, cross-system mapping (MBTI ↔ Enneagram ↔ PID-5-BF) pulling live data from the profile
|}


An interaction is an undirected edge between two endpoints. Each endpoint has a '''type''' (<code>med</code> or <code>category</code>) and a '''slug''' (DB-key form of the page title).
All assessment items submit raw responses to <code>pcp_user_profile_fields</code> under namespace <code>{key}_raw</code> (e.g. <code>cati_raw</code>); the computed scores live under namespace <code>{key}</code> with keys like <code>subscale_SOC</code>, <code>total</code>, plus a <code>taken_at</code> timestamp. Re-scoring happens automatically on every save (autosave fires `scoreResponses()` on the full raw set, skipping "unsure" rows).


Pairs are stored in canonical order: smaller <code>(type, slug)</code> tuple on the left. This collapses A↔B and B↔A into a single row.
== Autosave infrastructure ==


=== Tables ===
Every block on <code>Special:MyProfile</code> is wrapped in <code>&lt;div data-pcp-save-block="block-name"&gt;</code>. The blocksave.js library:


<code>pcp_interactions</code>: one row per interaction edge.
# Listens for <code>input</code> and <code>change</code> events on every input inside any save-block
# 800 ms after the last event, POSTs the block's serialized form data to <code>Special:SaveProfileBlock</code> with <code>block=block-name</code>
# Shows a transient chip (top-right and bottom of the block): pending… → saving… → ✓ saved (fades after 1.2 s) or ✗ error (sticks, clickable to retry)
# Race-safe: if user keeps typing during an in-flight save, the in-flight save records what it sent; newer changes mark the block dirty again and schedule another save when the response returns
# Diagnosis + medicines "Add a row" slots are exempted from autosave (would create duplicates); they require an explicit + Add button
# Programmatic widgets (chip-pickers, units, smoking, alcohol, chronotype) fire <code>change</code> events on their hidden fields so the listener notices


  pi_id              auto-increment
Slider numbers are also clickable: a single delegated handler on every <code>&lt;output&gt;</code> next to a range slider swaps it for a number input on click, accepts a precise typed value (clamps to the slider's <code>min</code>/<code>max</code>), commits with Enter, cancels with Escape.
  pi_element_id      FK -> pcp_votable_elements (reuse votes/comments infra)
  pi_left_type      'med' | 'category'
  pi_left_slug      VARBINARY(255)
  pi_right_type      'med' | 'category'
  pi_right_slug      VARBINARY(255)
  pi_created_user_id INT
  pi_created        BINARY(14)
  UNIQUE (pi_left_type, pi_left_slug, pi_right_type, pi_right_slug)


<code>pcp_interaction_reports</code>: one row per (interaction, user, perspective).
Scroll position is preserved across the rare reloads (delete operations on diagnoses / medicines / experience reports, and the auto-reload after a new diagnosis or medicine is added) via <code>sessionStorage</code>.


  pir_element_id  FK -> pcp_votable_elements
== Special pages ==
  pir_user_id      INT
 
  pir_perspective  1 = user, 2 = provider
{| class="wikitable"
  pir_experience  TINYINT (1..5, nullable)
! Page !! Purpose
  pir_valence      TINYINT (-3..+3, nullable)
|-
  pir_note        MEDIUMBLOB (nullable)
| <code>Special:MyProfile</code> || Edit your full profile (identity, demographics, personality, dx, meds). Autosave throughout.
  pir_created      BINARY(14)
|-
  pir_updated      BINARY(14)
| <code>Special:UserProfile/&lt;name&gt;</code> || Public profile view (filtered by per-field visibility)
  UNIQUE (pir_element_id, pir_user_id, pir_perspective)
|-
| <code>Special:MyAssessment</code> || Index of rich assessment reports
|-
| <code>Special:MyAssessment/cati</code>, <code>/catq</code>, <code>/pid5bf</code>, <code>/mbti</code>, <code>/enneagram</code>, <code>/ocean</code> || Rich report per assessment
|-
| <code>Special:SaveProfileBlock</code> || AJAX endpoint for autosave (POST-only, JSON response)
|-
| <code>Special:Problems</code> || Browse the problems repository (165+ entries, 18 categories)
|-
| <code>Special:Problem/&lt;slug&gt;</code> || Individual problem page
|-
| <code>Special:SuggestProblem</code> || User-facing form to suggest a new problem
|-
| <code>Special:ManageProblems</code> || Sysop tool for problem-repository moderation
|-
| <code>Special:ReviewExperience</code> || Sysop queue for pending experience reports
|-
| <code>Special:ManageInteractions</code> || Sysop bulk-edit interaction reports
|-
| <code>Special:DeletePharmaElement</code> || Sysop delete tool for any votable element
|}
 
== API modules ==
 
{| class="wikitable"
! Action !! Purpose
|-
| <code>pharmacopediavote</code> || Submit / clear binary vote on votable element
|-
| <code>pharmacopedialikert</code> || Submit problem-efficacy likert (0–100 + −1 DK)
|-
| <code>pharmacopediaeffect</code> || Submit effect report (patient or provider perspective)
|-
| <code>pharmacopediainteractionreport</code> || Submit interaction report
|-
| <code>pharmacopediainteractionadd</code> || Create a new interaction edge
|-
| <code>pharmacopediacomment</code> || Threaded discussion ops (add / edit / delete / reply)
|-
| <code>pharmacopediaexperiencesubmit</code> || Submit experience report (multi-field form)
|-
| <code>pharmacopediaexperiencereview</code> || Sysop approve / reject experience report
|-
| <code>pharmacopediadxsearch</code> || Diagnosis autocomplete against the 41k-row abbreviation table
|-
| <code>pharmacopediaproblemsearch</code> || Problem-repository autocomplete
|-
| <code>pharmacopediaeffectslookup</code>, <code>indicationslookup</code> || Pickers used by the experience-submit form
|-
| <code>pharmacopedialiteratureadd</code>, <code>literaturedelete</code> || Literature attachment ops
|}
 
== Interactions feature ==
 
The Interactions section is rendered by placing <code>&lt;pharmaInteractions/&gt;</code> anywhere in the wikitext of a med article ('''NS_MAIN''') or a Category page ('''NS_CATEGORY''').
 
=== Entity model ===
 
An interaction is an undirected edge between two endpoints. Each endpoint has a '''type''' (<code>med</code> or <code>category</code>) and a '''slug''' (DB-key form of the page title). Pairs are stored in canonical order: smaller <code>(type, slug)</code> tuple on the left.


=== Rendering rules ===
=== Rendering rules ===
Line 180: Line 301:
* On a '''Category''' page, list direct edges only (no transitive walk).
* On a '''Category''' page, list direct edges only (no transitive walk).
* Sort: pooled <code>valence_mean</code> ascending (most negative on top). Nulls sink. Tiebreakers: <code>n</code> desc, then alphabetic.
* Sort: pooled <code>valence_mean</code> ascending (most negative on top). Nulls sink. Tiebreakers: <code>n</code> desc, then alphabetic.
* Severe (any of pooled / user / provider vmean ≤ −2.5): red 4 px left border + red-tinted background + "severe" pill + counterparty title in red.
* Severe (any of pooled / user / provider vmean ≤ −83.0): red 4 px left border + red-tinted background + "severe" pill + counterparty title in red.


=== Add-interaction modal ===
=== Add-interaction modal ===


Triggered by the <code>+ Add interaction</code> button at the bottom of the section. Two-stage UX:
Triggered by the <code>+ Add interaction</code> button at the bottom of the section. Two-stage UX: search → click Use → confirm with Add interaction → POST to <code>pharmacopediainteractionadd</code>. Categories appear in the modal only if tagged with the marker category (default <code>Category:MedCategory</code>, configurable via <code>$wgPharmacopediaInteractionCategoryMarker</code>).
 
== Experience reports ==
 
User-submitted reports of personal or clinical experience with a medicine, via <code>&lt;pharmaExperience/&gt;</code> on a med page. Stored pending in <code>pcp_experience_reports</code>; visible publicly only after sysop approval through <code>Special:ReviewExperience</code>.
 
Captured fields:
* Perspective (personal / clinical)
* Currently taking it (yes / no, stopped)
* Duration (value + unit)
* Dose (mg, decimal-precise)
* Route (16-option dropdown: PO, IV, IM, SC, SL, buccal, inhaled, intranasal, topical, transdermal, PR, ophthalmic, otic, vaginal, insufflated, other)
* Schedule (free text with datalist of QD / BID / TID / QID / q4h / q6h / q8h / q12h / qHS / qAM / qPM / PRN)
* Patient count (clinical only): min + optional max for ranges
* Efficacy (0–100 slider)
* Side-effect burden (0–100 slider)
* Stop reasons (personal + stopped only): JSON multi-select with optional severity slider per reason — codes: side_effects / ineffective / cost / no_longer_needed / clinician_advised / other
* Free-text anecdote
* Problems addressed (multi-pick with per-problem efficacy)
* Effects experienced (multi-pick with per-effect valence + frequency)
 
== Storage tables (selected) ==
 
{| class="wikitable"
! Table !! Purpose
|-
| <code>pcp_votable_elements</code> || Stable per-(page, slug) handle reused by votes / likert / comments
|-
| <code>pcp_votes</code> || Binary +1/−1 votes
|-
| <code>pcp_likert_reports</code> || Problem efficacy (0–100 + −1 DK), TINYINT signed
|-
| <code>pcp_effect_reports</code> || Effect ratings: experienced / frequency / valence (±100); perspective 1/2
|-
| <code>pcp_interaction_reports</code> || Interaction ratings: experience 1–5 / valence ±100 / note; perspective 1/2
|-
| <code>pcp_interactions</code> || Interaction edges (canonical-ordered pair)
|-
| <code>pcp_comments</code> || Threaded discussions
|-
| <code>pcp_user_profiles</code> || Per-user profile meta (alias, attribution, voter hash)
|-
| <code>pcp_user_profile_fields</code> || Generic key-value field store: (namespace, key, num, text, visibility)
|-
| <code>pcp_profile_diagnoses</code> || Per-user diagnoses (system, code, description, status, origin, severity 0–100, disability 0–100, dates, notes, visibility)
|-
| <code>pcp_user_meds</code> || Per-user medicines (name, page_id, efficacy 0–100, burden 0–100, dose_mg, route, schedule, duration, periods JSON, current, notes, visibility)
|-
| <code>pcp_diagnosis_abbreviations</code> || ICD-10-CM + ICD-11 + DSM-5 + aliases (~41,500 rows, VARCHAR/utf8mb4 for native case-insensitive search)
|-
| <code>pcp_problem</code>, <code>pcp_problem_alias</code> || Problems repository + alias lookup
|-
| <code>pcp_experience_reports</code> || Experience reports (pending → approved); efficacy + burden 0–100; route + schedule; stop-reasons JSON; patient-count min + max
|-
| <code>pcp_life_events</code>, <code>pcp_life_traits</code>, <code>pcp_life_images</code> || Life Story keyframes (auto-generated from assessments, manually authorable)
|-
| <code>pcp_literature</code> || Citation attachments
|}
 
== Notable lessons learned ==
 
* '''Cargo string fields cap at ~300 chars.''' <code>structure</code> and <code>mechanism</code> on MedTemplate are short VARCHARs; long prose goes in MEDIUMBLOB sections (pharmacokinetics, pharmacodynamics, intro). Overruns silently lose Cargo data (MySQL Error 1406).
* '''VARBINARY + LOWER() is a no-op.''' MariaDB's LOWER() returns binary types unchanged. <code>pcp_diagnosis_abbreviations</code> was migrated VARBINARY → VARCHAR/utf8mb4 (2026-05-17) so case-insensitive LIKE works natively without CONVERT() wrappers.
* '''FlaggedRevs locks template inclusions by default.''' Config fix: <code>$wgFlaggedRevsHandleIncludes=0</code> + remove NS_TEMPLATE from <code>$wgFlaggedRevsNamespaces</code> via an extension-function callback (MW 1.46 array config concatenation behavior).
* '''CSP must allow Cloudflare Turnstile and any other 3rd-party widget script source.''' Symptom: generic "There are problems with some of your input" on form submit. Audit script-src / frame-src / connect-src / style-src whenever adding any 3rd-party JS widget.
* '''Sidebar cache must be purged after CLI <code>maintenance/edit.php</code> writes''' to <code>MediaWiki:Sidebar</code> or other chrome pages: <code>curl -X POST .../api.php?action=purge&titles=MediaWiki:Sidebar</code>.
* '''CLI E_USER_DEPRECATED suppressed in LocalSettings.php''' (EmbedVideo / FlaggedRevs spam ~6 lines per maintenance/run.php call on MW 1.46). Web behavior unaffected.
 
== Hooks ==
 
* <code>ParserFirstCallInit</code>: register all parser tags
* <code>LoadExtensionSchemaUpdates</code>: install / migrate schema (the sql/ directory + patches)
* <code>BeforePageDisplay</code>: inject the ext.pharmacopedia.* ResourceLoader modules
* <code>UserGetRights</code> + <code>UserEffectiveGroups</code>: verified-provider role wiring
* Various special-page registrations via <code>SpecialPage_initList</code>
 
== Configuration globals ==


# Search input → results split into '''Meds''' (teal chip) and '''Categories''' (amber chip).
* <code>$wgPharmacopediaInteractionCategoryMarker</code> (default <code>Category:MedCategory</code>): only categories tagged with this marker appear in the add-interaction modal
# Click <code>Use</code> → confirm via <code>Add interaction</code> button → POST to <code>pharmacopediainteractionadd</code>.
* (Various permission-grant arrays via standard MW <code>$wgGroupPermissions</code>)


Categories appear in the modal '''only if tagged with the marker category''' (default <code>Category:MedCategory</code>, configurable via <code>$wgPharmacopediaInteractionCategoryMarker</code>). The transitive walk during rendering, however, uses all of a page's categories regardless of marker — historic data isn't hidden by changing the marker policy.
== Source layout ==


=== Delete ===
  extensions/Pharmacopedia/
  |-- extension.json
  |-- includes/
  |  |-- Hooks.php
  |  |-- *Tag.php                  (parser tags: VoteTag, EffectTag, ProblemTag, ...)
  |  |-- *Store.php                (data access: EffectStore, ProblemStore, ...)
  |  |-- UserProfileStore.php      (the big one; profile / dx / meds / abbreviations)
  |  |-- SpecialMyProfile.php      (the user profile editor; large)
  |  |-- SpecialMyAssessment.php  (rich reports for all 6 assessments; large)
  |  |-- SpecialSaveProfileBlock.php (autosave AJAX endpoint)
  |  |-- Special*.php              (other special pages)
  |  |-- ProfileDatasets.php      (countries, languages, genders, religions, etc.)
  |  |-- DatePicker.php            (range / possibility-mix date widget backend)
  |  |-- Assessments/
  |  |  |-- Cati.php, CatiNorms.php
  |  |  |-- Catq.php
  |  |  |-- Pid5bf.php
  |  |  |-- Mbti.php
  |  |  |-- Enneagram.php
  |  |  `-- Raadsr.php            (deprecated 2026-05-17 in favor of CATI, kept for archival reads)
  |  `-- Api/
  |      `-- (one class per API module)
  |-- resources/
  |  |-- ext.pharmacopedia.js          (single IIFE: chip-picker, dx autocomplete, BFI-10 compute, ...)
  |  |-- ext.pharmacopedia.blocksave.js (debounced autosave per block)
  |  |-- ext.pharmacopedia.css
  |  |-- ext.pharmacopedia.datepicker.js + .css
  |-- sql/
  |  |-- (one .sql per table; patches as patch-*.sql)
  `-- i18n/
      `-- en.json


Two a
[[Category:Pharmacopedia documentation]]