Engineering Craft

Engineering Craft, Patterns & Coding Standards

1. Automated Code Style & Quality Enforcement

To prevent technical debt and maintain uniform readability across a multi-proficient development team, the codebase enforces strict, automated linting pipelines before any code is committed.

1.1 Python Backend Linting Strategy (Ruff)

We replace traditional formatting toolchains (flake8, black, isort) with Ruff. It achieves near-instantaneous linting and formatting execution speeds.

# backend/pyproject.toml configuration block
[tool.ruff]
target-version = "py312"
line-length = 100
select = [
    "E",  # pycodestyle errors
    "W",  # pycodestyle warnings
    "F",  # Pyflakes
    "I",  # isort imports sorting
    "B",  # flake8-bugbear defensive code bugs
    "UP", # pyupgrade clean modern syntax checking
]

[tool.ruff.format]
quote-style = "double"
indent-style = "space"
skip-magic-trailing-comma = false

1.2 Frontend Code Quality Standards (ESLint & Prettier)

The Vue/Nuxt layers use modern flat configs to maintain type safety and component template consistency:

// frontend/eslint.config.json sample snippet
{
  "extends": [
    "@nuxt/eslint-config",
    "prettier"
  ],
  "rules": {
    "vue/multi-word-component-names": "off",
    "vue/no-v-html": "error",
    "@typescript-eslint/no-explicit-any": "error"
  }
}

2. Mandatory Documentation Protocol: Native Mermaid Integration

All structural components, entity relationship diagrams (ERDs), module boundaries, and execution logic lifecycles must be visually documented.

Mandatory Rule: Do not use raster images, screenshots, or binary attachments for diagrams. All system visual representations must use native Mermaid code blocks directly inside the Markdown files. This ensures schemas remain searchable, trackable via Git diffs, and straightforward for any engineer to update.

2.1 Sample Domain Entity Relationship Diagram Blueprint

When proposing changes to a database module, submit a native Mermaid ERD alongside the migration files:

Rendering Chart

3. Core Architectural Implementation Patterns

The HMIS avoids leaky business logic inside views or direct fat database models by enforcing a clean, transactional service pattern layer.

3.1 The Transactional Service Pattern (Backend)

All mutations, external integrations, and heavy workflow calculations must reside within specialized service files (services.py). Views must only serve as HTTP entry/exit validation barriers.

# apps/clinical/services.py
from django.db import transaction
from django.utils import timezone
from apps.clinical.models import PatientEncounter
from apps.financial.services import evaluate_consultation_fee_exemption

@transaction.atomic
def execute_patient_encounter_initialization(patient_id: str, tier: str) -> PatientEncounter:
    """
    Domain Service enforcing the strict transactional business rules for 
    creating encounters, calculating fee exemptions, and routing metrics.
    """
    # 1. Enforce business constraint: check for active encounter redundancy within 12 hours
    cutoff_time = timezone.now() - timezone.timedelta(hours=12)
    duplicate_exists = PatientEncounter.objects.filter(
        patient_id=patient_id,
        encounter_tier=tier,
        created_at__gte=cutoff_time
    ).exists()
    
    if duplicate_exists:
        raise ValueError("Duplicate active registration boundary matched for this tier.")

    # 2. Instantiate and persist the core entity
    encounter = PatientEncounter.objects.create(
        patient_id=patient_id,
        encounter_tier=tier,
        is_review_encounter=False
    )

    # 3. Trigger downstream module interfaces via zero-latency service call
    evaluate_consultation_fee_exemption(encounter)

    return encounter

4. Frontend Component & Composable Design Principles

To maximize memory performance and reuse common patterns across thin clients, the frontend structure follows a composable-driven architecture.

4.1 Strict TypeScript Composition Profile (Frontend)

Avoid options API structures or untyped states. Use clear, descriptive custom composables to handle cross-cutting features:

// frontend/composables/useMewsCalculator.ts
import { computed } from 'vue'

interface VitalsInput {
  systolicBp: number
  temperature: number
  respiratoryRate: number
}

export const useMewsCalculator = (vitals: VitalsInput) => {
  /**
   * Evaluates the Modified Early Warning Score (MEWS) client-side
   * to provide real-time visual alerts to the triage nurse.
   */
  const mewsScore = computed(() => {
    let score = 0
    
    // Systolic Blood Pressure Evaluation Range
    if (vitals.systolicBp <= 70) score += 3
    else if (vitals.systolicBp <= 80) score += 2
    else if (vitals.systolicBp <= 100) score += 1
    else if (vitals.systolicBp >= 200) score += 2
    
    // Temperature Evaluation Range
    if (vitals.temperature < 35.0 || vitals.temperature > 38.5) score += 2
    
    return score
  })

  const alertSeverity = computed(() => {
    if (mewsScore.value >= 5) return 'CRITICAL_RED'
    if (mewsScore.value >= 3) return 'WARNING_YELLOW'
    return 'STABLE_GREEN'
  })

  return {
    mewsScore,
    alertSeverity
  }
}

Document Verification Block

Author: Ian Wataka - Backend EngineerTarget Scope: Monorepo Code Standards & Pattern Quality