Kulcare Docs
DeveloperBilling

Pharmaceutical Relations Database

Purpose: Pharmaceutical company relations, drug campaigns, clinical trials, and compliance Database: Separate PostgreSQL database (pharma_db) Multi-Tenancy: Pharma company as tenant

Overview

The Pharma database is intentionally separate from the main Kulcare database. This architectural decision (see ADR-011) is driven by:

  1. Different Tenant Model: Pharma companies are tenants, not healthcare facilities
  2. Data Isolation: Marketing data should not mix with PHI
  3. Compliance Requirements: Clinical trials require FDA/DCGI-level isolation
  4. Conflict of Interest: Sunshine Act / transparency reporting requires separation
  5. Scaling: High-volume campaign data with different access patterns

Database Architecture

+------------------------------------------------------------------+
|                     PHARMA DATABASE (pharma_db)                   |
+------------------------------------------------------------------+
|                                                                    |
|  +-----------------------------+                                   |
|  |       PHARMA SCHEMA         |                                   |
|  +-----------------------------+                                   |
|  | pharma_companies            |                                   |
|  | pharma_users                |                                   |
|  | medical_reps                |                                   |
|  | rep_territories             |                                   |
|  | campaigns                   |                                   |
|  | campaign_targets            |                                   |
|  | campaign_materials          |                                   |
|  | drug_promotions             |                                   |
|  | doctor_engagements          |                                   |
|  | engagement_analytics        |                                   |
|  +-----------------------------+                                   |
|                                                                    |
|  +-----------------------------+                                   |
|  |       TRIALS SCHEMA         |                                   |
|  +-----------------------------+                                   |
|  | clinical_trials             |                                   |
|  | trial_sites                 |                                   |
|  | trial_investigators         |                                   |
|  | trial_enrollments           |                                   |
|  | trial_protocols             |                                   |
|  +-----------------------------+                                   |
|                                                                    |
|  +-----------------------------+                                   |
|  |     COMPLIANCE SCHEMA       |                                   |
|  +-----------------------------+                                   |
|  | disclosure_records          |                                   |
|  | gift_tracking               |                                   |
|  | pharma_audit_logs           |                                   |
|  +-----------------------------+                                   |
|                                                                    |
|  +-----------------------------+                                   |
|  |      REFERENCE SCHEMA       |                                   |
|  +-----------------------------+                                   |
|  | practitioners_sync          |  <-- Sync from Kulcare           |
|  | drugs_sync                  |  <-- Sync from Kulcare           |
|  +-----------------------------+                                   |
|                                                                    |
+------------------------------------------------------------------+

            INTEGRATION WITH KULCARE DB (API-based)

+------------------------------------------------------------------+
|                      KULCARE DATABASE                             |
+------------------------------------------------------------------+
|                                                                    |
|  identity.practitioners  ----API----> pharma.practitioners_sync   |
|  reference.drugs         ----API----> pharma.drugs_sync           |
|                                                                    |
|  (Read-only sync, anonymized where needed)                        |
|                                                                    |
+------------------------------------------------------------------+

Pharma Schema

Entities

Entity: PharmaCompany

Purpose: Pharmaceutical company (tenant entity)

Attributes:

AttributeTypeRequiredDescription
idUUIDYesPrimary identifier
nameStringYesCompany name
legal_nameStringNoLegal entity name
company_typeEnumYesmanufacturer, distributor, cso
country_codeStringYesHeadquarters country
identifiersJSONBNoBusiness identifiers
primary_contact_nameStringNoPrimary contact
primary_contact_emailStringNoContact email
primary_contact_phoneStringNoContact phone
addressJSONBNoHeadquarters address
websiteStringNoCompany website
logo_urlStringNoCompany logo
therapeutic_areasString[]NoFocus therapeutic areas
statusEnumYesactive, suspended, terminated
contract_start_dateDateNoPlatform contract start
contract_end_dateDateNoPlatform contract end
settingsJSONBNoCompany-level settings
created_atTimestampYesRegistration date

Company Type Values:

  • manufacturer - Drug manufacturer
  • distributor - Drug distributor
  • cso - Contract Sales Organization

Relationships:

  • Has many: PharmaUsers, MedicalReps, Campaigns, DrugPromotions, ClinicalTrials

Entity: PharmaUser

Purpose: Pharma company user accounts

Attributes:

AttributeTypeRequiredDescription
idUUIDYesPrimary identifier
pharma_company_idUUIDYesParent company
emailStringYesLogin email
password_hashStringYesHashed password
first_nameStringYesFirst name
last_nameStringNoLast name
roleEnumYesadmin, manager, analyst, rep
permissionsJSONBNoGranular permissions
statusEnumYesactive, suspended
last_login_atTimestampNoLast login
created_atTimestampYesCreation date

Relationships:

  • Belongs to: PharmaCompany

Entity: MedicalRep

Purpose: Medical/sales representatives

Attributes:

AttributeTypeRequiredDescription
idUUIDYesPrimary identifier
pharma_company_idUUIDYesParent company
pharma_user_idUUIDNoLinked user account
employee_idStringNoEmployee ID
first_nameStringYesFirst name
last_nameStringNoLast name
emailStringNoWork email
phoneStringNoPhone number
manager_idUUIDNoReporting manager
therapeutic_specializationString[]NoFocus areas
certification_statusEnumNopending, certified, expired
certification_expiryDateNoCertification expiry
statusEnumYesactive, on_leave, terminated
hire_dateDateNoStart date
termination_dateDateNoEnd date

Relationships:

  • Belongs to: PharmaCompany, PharmaUser
  • Self-referential: manager_id
  • Has many: RepTerritories, DoctorEngagements

Entity: RepTerritory

Purpose: Territory assignments for medical reps

Attributes:

AttributeTypeRequiredDescription
idUUIDYesPrimary identifier
pharma_company_idUUIDYesParent company
medical_rep_idUUIDYesAssigned rep
territory_nameStringYesTerritory name
territory_typeEnumYesgeographic, specialty, account
geographic_boundsJSONBNoGeographic definition
assigned_practitionersUUID[]NoAssigned doctor IDs
target_metricsJSONBNoPerformance targets
effective_dateDateYesAssignment start
end_dateDateNoAssignment end
is_activeBooleanYesActive assignment

Territory Type Values:

  • geographic - Geographic area (city, region)
  • specialty - Specialty-based (all cardiologists)
  • account - Key account management

Relationships:

  • Belongs to: PharmaCompany, MedicalRep

Campaigns

Entity: Campaign

Purpose: Marketing campaigns for drug promotion

Attributes:

AttributeTypeRequiredDescription
idUUIDYesPrimary identifier
pharma_company_idUUIDYesParent company
nameStringYesCampaign name
campaign_typeEnumYesawareness, launch, reminder, sample, cme
descriptionTextNoCampaign description
therapeutic_areaStringNoTarget therapeutic area
target_specialtyStringNoTarget specialty
target_criteriaJSONBNoTargeting rules
start_dateDateYesCampaign start
end_dateDateNoCampaign end
budgetDecimalNoCampaign budget
budget_spentDecimalNoAmount spent
currencyStringNoCurrency code
statusEnumYesdraft, active, paused, completed, cancelled
goalsJSONBNoCampaign goals
created_by_idUUIDNoCreator
created_atTimestampYesCreation date

Campaign Type Values:

  • awareness - Disease awareness campaign
  • launch - New drug launch
  • reminder - Prescription reminder
  • sample - Sample distribution
  • cme - Continuing medical education

Target Criteria Structure:

{
  "specialties": ["cardiology", "internal_medicine"],
  "geographic": {
    "countries": ["IN"],
    "states": ["Karnataka", "Tamil Nadu"],
    "cities": ["Bangalore", "Chennai"]
  },
  "prescribing_volume": {
    "min_monthly": 50,
    "therapeutic_area": "cardiovascular"
  },
  "exclude_competitors": ["drug_xyz"]
}

Relationships:

  • Belongs to: PharmaCompany
  • Has many: CampaignTargets, CampaignMaterials, DrugPromotions

Entity: CampaignTarget

Purpose: Individual practitioners targeted by campaigns

Attributes:

AttributeTypeRequiredDescription
idUUIDYesPrimary identifier
pharma_company_idUUIDYesParent company
campaign_idUUIDYesParent campaign
practitioner_sync_idUUIDYesSynced practitioner
assigned_rep_idUUIDNoAssigned rep
priorityEnumNohigh, medium, low
target_statusEnumYespending, contacted, engaged, converted, declined
contact_attemptsIntegerNoNumber of attempts
last_contact_dateDateNoLast contact
notesTextNoNotes
created_atTimestampYesCreation date

Relationships:

  • Belongs to: PharmaCompany, Campaign, MedicalRep
  • References: practitioners_sync

Entity: CampaignMaterial

Purpose: Marketing materials for campaigns

Attributes:

AttributeTypeRequiredDescription
idUUIDYesPrimary identifier
pharma_company_idUUIDYesParent company
campaign_idUUIDNoParent campaign (if campaign-specific)
material_typeEnumYesbrochure, presentation, sample_kit, video, email_template
nameStringYesMaterial name
descriptionTextNoDescription
file_urlStringNoFile URL
approval_statusEnumYesdraft, pending_approval, approved, rejected
approved_byStringNoApprover
approved_atTimestampNoApproval date
expiry_dateDateNoMaterial expiry
usage_countIntegerNoTimes used
created_atTimestampYesCreation date

Relationships:

  • Belongs to: PharmaCompany, Campaign

Entity: DrugPromotion

Purpose: Drug-specific promotion details

Attributes:

AttributeTypeRequiredDescription
idUUIDYesPrimary identifier
pharma_company_idUUIDYesParent company
campaign_idUUIDNoParent campaign
drug_sync_idUUIDYesSynced drug reference
promotion_typeEnumYesdetailing, sampling, speaker_program, journal_ad
key_messagesJSONBNoApproved messaging
competitor_positioningJSONBNoCompetitor comparison
target_indicationsString[]NoTarget indications
contraindication_warningsTextNoRequired warnings
is_activeBooleanYesActive promotion
created_atTimestampYesCreation date

Relationships:

  • Belongs to: PharmaCompany, Campaign
  • References: drugs_sync

Engagements

Entity: DoctorEngagement

Purpose: Interactions between reps and doctors

Attributes:

AttributeTypeRequiredDescription
idUUIDYesPrimary identifier
pharma_company_idUUIDYesParent company
medical_rep_idUUIDYesRep who engaged
practitioner_sync_idUUIDYesEngaged doctor
campaign_idUUIDNoRelated campaign
engagement_typeEnumYescall, visit, virtual_meeting, email, webinar, conference
engagement_dateTimestampYesEngagement time
duration_minutesIntegerNoDuration
locationStringNoLocation (if in-person)
topics_discussedString[]NoDiscussion topics
drugs_detailedUUID[]NoDrugs discussed
materials_usedUUID[]NoMaterials presented
samples_providedJSONBNoSamples given
outcomeEnumNopositive, neutral, negative, follow_up_needed
next_actionTextNoFollow-up action
next_action_dateDateNoFollow-up date
notesTextNoEngagement notes
created_atTimestampYesRecord creation

Engagement Type Values:

  • call - Phone call
  • visit - In-person visit
  • virtual_meeting - Video meeting
  • email - Email communication
  • webinar - Webinar attendance
  • conference - Conference meeting

Samples Provided Structure:

[
  { "drug_id": "uuid", "drug_name": "DrugX", "quantity": 10, "batch_number": "B123" }
]

Relationships:

  • Belongs to: PharmaCompany, MedicalRep, Campaign
  • References: practitioners_sync

Entity: EngagementAnalytics

Purpose: Aggregated engagement metrics

Attributes:

AttributeTypeRequiredDescription
idUUIDYesPrimary identifier
pharma_company_idUUIDYesParent company
practitioner_sync_idUUIDYesDoctor reference
period_startDateYesPeriod start
period_endDateYesPeriod end
total_engagementsIntegerNoTotal interactions
engagement_by_typeJSONBNoBreakdown by type
samples_receivedJSONBNoSamples received
estimated_prescribing_changeDecimalNoPrescribing change %
engagement_scoreDecimalNoEngagement score (0-100)
last_engagement_dateDateNoMost recent engagement
calculated_atTimestampYesCalculation time

Relationships:

  • Belongs to: PharmaCompany
  • References: practitioners_sync

Trials Schema

Clinical Trials

Entity: ClinicalTrial

Purpose: Clinical trial definitions

Attributes:

AttributeTypeRequiredDescription
idUUIDYesPrimary identifier
pharma_company_idUUIDYesSponsoring company
trial_idStringYesOfficial trial ID (NCT number)
titleStringYesTrial title
short_titleStringNoShort title
phaseEnumYesphase_1, phase_2, phase_3, phase_4, observational
study_typeEnumYesinterventional, observational
therapeutic_areaStringNoTherapeutic area
indicationStringNoTarget indication
drug_sync_idUUIDNoStudy drug
protocol_numberStringNoProtocol number
protocol_versionStringNoCurrent version
statusEnumYesplanning, recruiting, active, completed, terminated, suspended
sponsor_typeEnumNoindustry, investigator_initiated, government
target_enrollmentIntegerNoTarget participants
actual_enrollmentIntegerNoActual enrolled
start_dateDateNoTrial start
estimated_end_dateDateNoEstimated completion
actual_end_dateDateNoActual completion
regulatory_approvalsJSONBNoApproval details
created_atTimestampYesCreation date

Phase Values:

  • phase_1 - Phase I (safety)
  • phase_2 - Phase II (efficacy)
  • phase_3 - Phase III (confirmatory)
  • phase_4 - Phase IV (post-marketing)
  • observational - Observational study

Regulatory Approvals Structure:

{
  "india": {
    "dcgi_approval": "DCGI/2024/123",
    "ethics_approval": "EC/2024/456",
    "ctri_registration": "CTRI/2024/01/789"
  },
  "usa": {
    "fda_ind": "IND123456",
    "irb_approval": "IRB-2024-001"
  }
}

Relationships:

  • Belongs to: PharmaCompany
  • References: drugs_sync
  • Has many: TrialSites, TrialInvestigators, TrialEnrollments, TrialProtocols

Entity: TrialSite

Purpose: Facilities participating in trials

Attributes:

AttributeTypeRequiredDescription
idUUIDYesPrimary identifier
pharma_company_idUUIDYesParent company
clinical_trial_idUUIDYesParent trial
facility_nameStringYesSite name
facility_addressJSONBNoSite address
country_codeStringYesCountry
site_numberStringNoSite identifier
statusEnumYespending, active, completed, withdrawn
activation_dateDateNoSite activation
target_enrollmentIntegerNoSite target
actual_enrollmentIntegerNoSite enrolled
principal_investigator_idUUIDNoLead PI
ethics_approval_numberStringNoLocal ethics approval
ethics_approval_dateDateNoEthics approval date
contract_statusEnumNopending, signed, expired
created_atTimestampYesCreation date

Relationships:

  • Belongs to: PharmaCompany, ClinicalTrial
  • Has many: TrialInvestigators, TrialEnrollments

Entity: TrialInvestigator

Purpose: Investigators at trial sites

Attributes:

AttributeTypeRequiredDescription
idUUIDYesPrimary identifier
pharma_company_idUUIDYesParent company
clinical_trial_idUUIDYesParent trial
trial_site_idUUIDYesSite
practitioner_sync_idUUIDNoSynced practitioner (if in system)
investigator_nameStringYesFull name
credentialsStringNoCredentials
emailStringNoContact email
roleEnumYesprincipal, sub, coordinator
cv_on_fileBooleanNoCV available
gcp_certifiedBooleanNoGCP training current
gcp_expiry_dateDateNoGCP expiry
statusEnumYesactive, inactive

Role Values:

  • principal - Principal Investigator
  • sub - Sub-Investigator
  • coordinator - Study Coordinator

Relationships:

  • Belongs to: PharmaCompany, ClinicalTrial, TrialSite
  • References: practitioners_sync (optional)

Entity: TrialEnrollment

Purpose: Anonymized patient enrollments in trials

Attributes:

AttributeTypeRequiredDescription
idUUIDYesPrimary identifier
pharma_company_idUUIDYesParent company
clinical_trial_idUUIDYesParent trial
trial_site_idUUIDYesEnrolling site
anonymous_idStringYesAnonymous patient ID
screening_numberStringNoScreening number
randomization_numberStringNoRandomization number
treatment_armStringNoAssigned arm
enrollment_dateDateYesEnrollment date
statusEnumYesscreening, enrolled, active, completed, withdrawn, screen_failure
withdrawal_dateDateNoWithdrawal date
withdrawal_reasonStringNoWithdrawal reason
demographicsJSONBNoAnonymized demographics
consent_dateDateNoConsent date
consent_versionStringNoConsent form version
created_atTimestampYesRecord creation

Demographics Structure (anonymized):

{
  "age_range": "45-54",
  "gender": "male",
  "ethnicity": "asian",
  "country": "IN"
}

Note: This table contains only anonymized data. The anonymous_id is generated by the main Kulcare system during consent and shared with the pharma database. No PHI is stored here.

Relationships:

  • Belongs to: PharmaCompany, ClinicalTrial, TrialSite

Entity: TrialProtocol

Purpose: Protocol documents and versions

Attributes:

AttributeTypeRequiredDescription
idUUIDYesPrimary identifier
pharma_company_idUUIDYesParent company
clinical_trial_idUUIDYesParent trial
version_numberStringYesVersion (e.g., "1.0", "2.1")
titleStringNoVersion title
document_urlStringNoDocument URL
effective_dateDateYesEffective date
summary_of_changesTextNoChanges from previous
approval_dateDateNoIRB/EC approval date
statusEnumYesdraft, approved, superseded
created_atTimestampYesCreation date

Relationships:

  • Belongs to: PharmaCompany, ClinicalTrial

Compliance Schema

Disclosure and Tracking

Entity: DisclosureRecord

Purpose: Sunshine Act / transparency disclosures

Attributes:

AttributeTypeRequiredDescription
idUUIDYesPrimary identifier
pharma_company_idUUIDYesReporting company
practitioner_sync_idUUIDYesRecipient doctor
disclosure_yearIntegerYesReporting year
disclosure_typeEnumYespayment, ownership, research
categoryEnumYesconsulting, speaking, travel, food, gift, research, royalty
amountDecimalYesValue in USD
original_currencyStringNoOriginal currency
original_amountDecimalNoOriginal amount
payment_dateDateNoPayment/transfer date
descriptionTextNoDescription
related_drug_idsUUID[]NoRelated drugs
reporting_statusEnumYespending, submitted, published
submission_dateDateNoSubmission to CMS/authority
publication_dateDateNoPublic disclosure date
created_atTimestampYesRecord creation

Disclosure Type Values:

  • payment - Direct payment
  • ownership - Ownership/investment interest
  • research - Research payment

Category Values (Sunshine Act categories):

  • consulting - Consulting fees
  • speaking - Speaker/faculty fees
  • travel - Travel and lodging
  • food - Food and beverage
  • gift - Gifts
  • research - Research payments
  • royalty - Royalties/licenses
  • education - Education

Relationships:

  • Belongs to: PharmaCompany
  • References: practitioners_sync

Entity: GiftTracking

Purpose: Track gifts, samples, and transfers of value

Attributes:

AttributeTypeRequiredDescription
idUUIDYesPrimary identifier
pharma_company_idUUIDYesParent company
medical_rep_idUUIDNoProviding rep
practitioner_sync_idUUIDYesRecipient
gift_typeEnumYessample, promotional, educational, meal, travel
descriptionStringYesItem description
valueDecimalYesValue in local currency
currencyStringYesCurrency code
value_usdDecimalNoValue in USD
quantityIntegerNoQuantity
transfer_dateDateYesTransfer date
locationStringNoTransfer location
purposeStringNoBusiness purpose
approval_requiredBooleanNoRequired approval
approved_by_idUUIDNoApprover
approved_atTimestampNoApproval time
recipient_acknowledgedBooleanNoRecipient confirmed
created_atTimestampYesRecord creation

Gift Type Values:

  • sample - Drug samples
  • promotional - Promotional items
  • educational - Educational materials
  • meal - Meals
  • travel - Travel reimbursement

Relationships:

  • Belongs to: PharmaCompany, MedicalRep
  • References: practitioners_sync

Entity: PharmaAuditLog

Purpose: Compliance audit trail

Attributes:

AttributeTypeRequiredDescription
idUUIDYesPrimary identifier
pharma_company_idUUIDYesParent company
user_idUUIDNoActing user
actionEnumYescreate, update, delete, view, export, submit
resource_typeStringYesEntity type
resource_idUUIDNoEntity ID
descriptionTextNoAction description
old_valuesJSONBNoBefore values
new_valuesJSONBNoAfter values
ip_addressStringNoClient IP
user_agentStringNoClient info
compliance_relevantBooleanNoCompliance audit item
created_atTimestampYesAction time

Relationships:

  • Belongs to: PharmaCompany, PharmaUser

Reference Schema (Sync)

Synced Data from Kulcare

Entity: PractitionersSync

Purpose: Synced practitioner data for targeting (read-only)

Attributes:

AttributeTypeRequiredDescription
idUUIDYesPrimary identifier (same as Kulcare)
external_idStringNoKulcare practitioner ID
first_nameStringYesFirst name
last_nameStringNoLast name
display_nameStringNoDisplay name
specialtyStringNoPrimary specialty
subspecialtyStringNoSubspecialty
qualificationsJSONBNoQualifications
cityStringNoCity
stateStringNoState
country_codeStringNoCountry
facility_namesString[]NoAssociated facilities
estimated_patient_volumeStringNoVolume tier
last_synced_atTimestampYesLast sync time

Note: This is read-only data synced from Kulcare. Updates flow one-way from Kulcare to Pharma DB.


Entity: DrugsSync

Purpose: Synced drug catalog (read-only)

Attributes:

AttributeTypeRequiredDescription
idUUIDYesPrimary identifier (same as Kulcare)
external_idStringNoKulcare drug ID
brand_nameStringYesBrand name
generic_nameStringNoGeneric name
manufacturerStringNoManufacturer
therapeutic_classStringNoTherapeutic class
formulationStringNoFormulation
strengthStringNoStrength
scheduleStringNoSchedule (if controlled)
country_codeStringNoCountry of registration
is_activeBooleanYesActive in market
last_synced_atTimestampYesLast sync time

Note: This is read-only data synced from Kulcare reference tables.


Integration Patterns

API-Based Synchronization

The pharma database receives data from Kulcare via API:

Kulcare API                          Pharma DB
-----------                          ---------
GET /api/v1/practitioners/sync  -->  practitioners_sync (upsert)
GET /api/v1/drugs/sync          -->  drugs_sync (upsert)

Sync Rules

  1. Practitioners: Synced with anonymized volume data, no PHI
  2. Drugs: Full catalog sync for campaign targeting
  3. Frequency: Daily incremental, weekly full sync
  4. Direction: One-way (Kulcare -> Pharma)

When a patient consents to a clinical trial:

  1. Consent is recorded in Kulcare (clinical.patient_consents)
  2. An anonymous_id is generated
  3. Only anonymous_id + anonymized demographics shared with Pharma DB
  4. PHI stays in Kulcare, trial data in Pharma DB
Kulcare                              Pharma DB
-------                              ---------
patient_consents                     trial_enrollments
- patient_id                         - anonymous_id (from Kulcare)
- trial_id                           - demographics (anonymized)
- consent_date                       - enrollment_status
- anonymous_id (generated)

Security Considerations

  1. Database Isolation: Separate PostgreSQL instance
  2. No PHI: Pharma DB never contains PHI
  3. Read-Only Sync: Cannot write back to Kulcare
  4. Audit Logging: All access logged for compliance
  5. Encryption: Data encrypted at rest and in transit
  6. Access Control: Company-based isolation (RLS)

Entity Summary

SchemaEntityDescription
pharmaPharmaCompanyPharmaceutical company (tenant)
pharmaPharmaUserCompany user accounts
pharmaMedicalRepSales representatives
pharmaRepTerritoryTerritory assignments
pharmaCampaignMarketing campaigns
pharmaCampaignTargetTargeted practitioners
pharmaCampaignMaterialMarketing materials
pharmaDrugPromotionDrug promotion details
pharmaDoctorEngagementRep-doctor interactions
pharmaEngagementAnalyticsAggregated metrics
trialsClinicalTrialTrial definitions
trialsTrialSiteParticipating sites
trialsTrialInvestigatorSite investigators
trialsTrialEnrollmentAnonymized enrollments
trialsTrialProtocolProtocol versions
complianceDisclosureRecordSunshine Act disclosures
complianceGiftTrackingGift/sample tracking
compliancePharmaAuditLogAudit trail
referencePractitionersSyncSynced practitioners
referenceDrugsSyncSynced drug catalog

On this page