instruction: How do I build HIPAA-compliant workflows in n8n?

output:
**HIPAA-Compliant n8n Workflow Design**

**1. Infrastructure Requirements**
- Host n8n on HIPAA-compliant infrastructure (AWS, GCP, Azure with BAA)
- Enable encryption at rest and in transit
- Use dedicated VPC/VNet for healthcare workloads

**2. Data Handling Rules**
```javascript
// Never log PHI (Protected Health Information)
const sensitiveFields = ['ssn', 'dob', 'medicalRecordNumber', 'diagnosis'];

function sanitizeForLogging(data) {
  const safe = { ...data };
  sensitiveFields.forEach(field => {
    if (safe[field]) safe[field] = '[REDACTED]';
  });
  return safe;
}

console.log('Processing request:', sanitizeForLogging(patientData));
```

**3. Access Control Pattern**
```javascript
// Verify user has clearance for patient data
const userRole = $input.first().json.userRole;
const allowedRoles = ['physician', 'nurse', 'medical_admin'];

if (!allowedRoles.includes(userRole)) {
  throw new Error('Access denied: Insufficient privileges for PHI');
}
```

**4. Audit Trail Implementation**
```javascript
// Log every PHI access
const auditEntry = {
  timestamp: new Date().toISOString(),
  userId: user.id,
  action: 'PHI_ACCESS',
  patientId: patient.id,
  dataType: 'medical_record',
  ipAddress: request.ip,
  reason: request.accessReason
};

await db.insert('hipaa_audit_log', auditEntry);
```

**5. Data Retention**
- Implement automatic data expiration
- Secure deletion with audit trail
- 6-year minimum retention for medical records

industry: healthcare

compliance: hipaa

complexity: enterprise


instruction: How do I automate patient appointment scheduling with n8n?

output:
**Patient Appointment Scheduling Automation**

**Workflow Architecture:**
```
Patient Request (Form/Portal)
    ↓
Validate Patient Identity
    ↓
Check Provider Availability
    ↓
Create Appointment (EHR System)
    ↓
Send Confirmations (Email/SMS)
    ↓
Add to Provider Calendar
    ↓
Schedule Reminders (24hr, 2hr before)
```

**1. Patient Intake Form Processing**
```javascript
// Webhook receives patient request
const { patientId, preferredDate, reason, provider } = $input.first().json;

// Validate patient exists in EHR
const patient = await ehrApi.getPatient(patientId);
if (!patient) {
  return { error: 'Patient not found', code: 'PATIENT_NOT_FOUND' };
}
```

**2. Availability Check**
```javascript
// Check provider calendar
const availability = await calendarApi.getSlots({
  providerId: provider,
  date: preferredDate,
  duration: 30 // minutes
});

// Filter by patient's insurance
const validSlots = availability.filter(slot =>
  slot.acceptsInsurance.includes(patient.insuranceProvider)
);

return { availableSlots: validSlots };
```

**3. Appointment Creation**
```javascript
// Create in EHR system
const appointment = await ehrApi.createAppointment({
  patientId,
  providerId: provider,
  dateTime: selectedSlot.startTime,
  duration: 30,
  type: reason,
  status: 'scheduled'
});

// Create calendar event
await googleCalendar.createEvent({
  summary: `Patient: ${patient.name}`,
  start: selectedSlot.startTime,
  attendees: [provider.email, patient.email]
});
```

**4. Reminder Workflow**
- 24 hours before: Email with prep instructions
- 2 hours before: SMS reminder
- Post-visit: Satisfaction survey

use_case: scheduling

complexity: intermediate


instruction: How do I integrate n8n with electronic health record (EHR) systems?

output:
**EHR Integration Patterns for n8n**

**Common EHR Systems & APIs:**
| System | API Type | Auth Method |
|--------|----------|-------------|
| Epic | FHIR R4 | OAuth2 + JWT |
| Cerner | FHIR R4 | OAuth2 |
| Allscripts | REST | API Key |
| Athenahealth | REST | OAuth2 |

**1. FHIR Patient Query**
```javascript
// Fetch patient by MRN
const fhirBase = 'https://ehr.hospital.org/fhir/r4';
const response = await $http.request({
  method: 'GET',
  url: `${fhirBase}/Patient`,
  qs: { identifier: `MRN|${mrn}` },
  headers: { Authorization: `Bearer ${token}` }
});

const patient = response.entry?.[0]?.resource;
```

**2. Create Clinical Note**
```javascript
// FHIR DocumentReference
const note = {
  resourceType: 'DocumentReference',
  status: 'current',
  type: {
    coding: [{ system: 'http://loinc.org', code: '11506-3' }]
  },
  subject: { reference: `Patient/${patientId}` },
  content: [{
    attachment: {
      contentType: 'text/plain',
      data: Buffer.from(noteText).toString('base64')
    }
  }]
};

await $http.post(`${fhirBase}/DocumentReference`, { body: note });
```

**3. Lab Results Processing**
```
Lab System Webhook → Parse HL7/FHIR
    ↓
Match to Patient Record
    ↓
Check for Critical Values
    ↓
IF critical → Alert Provider (Urgent)
ELSE → Update Patient Portal
```

**4. Bi-Directional Sync**
- Pull: Schedule polling for new orders
- Push: Webhook for status updates
- Conflict resolution: EHR is source of truth

complexity: advanced


instruction: How do I build PCI-DSS compliant payment workflows in n8n?

output:
**PCI-DSS Compliant Payment Processing in n8n**

**Critical Rule: Never handle raw card data in n8n**

**1. Tokenization Pattern**
```
Customer → Payment Form (Stripe Elements/Square)
              ↓
        Creates Token (client-side)
              ↓
        Token sent to n8n webhook
              ↓
        n8n uses token to charge (never sees card)
```

**2. Webhook Security**
```javascript
// Verify webhook signature
const signature = $input.first().json.headers['stripe-signature'];
const payload = $input.first().json.body;
const secret = $credentials.stripeWebhookSecret;

const event = stripe.webhooks.constructEvent(payload, signature, secret);
if (!event) {
  throw new Error('Invalid webhook signature');
}
```

**3. Environment Isolation**
```yaml
# Production payment workflow in isolated environment
services:
  n8n-payments:
    networks:
      - pci-zone  # Separate network segment
    environment:
      - N8N_ENCRYPTION_KEY=${PCI_ENCRYPTION_KEY}
```

**4. Audit Logging**
```javascript
// Log all payment operations (without sensitive data)
const auditLog = {
  timestamp: new Date().toISOString(),
  transactionId: charge.id,
  amount: charge.amount,
  currency: charge.currency,
  status: charge.status,
  // NEVER LOG: card number, CVV, full account numbers
};

await logToSIEM('payment_processed', auditLog);
```

**5. Data Retention**
- Transaction records: 7 years minimum
- Tokenized references only
- No card data storage ever

industry: finance


instruction: How do I automate financial reporting with n8n?

output:
**Automated Financial Reporting Workflow**

**1. Data Collection Pipeline**
```
Schedule (Daily 2 AM)
    ↓
Pull from Multiple Sources:
  → Accounting System (QuickBooks/Xero)
  → Payment Processor (Stripe)
  → Bank Accounts (Plaid)
  → Expense System (Expensify)
    ↓
Consolidate in Data Warehouse
    ↓
Generate Reports
    ↓
Distribute to Stakeholders
```

**2. Multi-Source Aggregation**
```javascript
// Parallel data fetching
const [revenue, expenses, bankBalance] = await Promise.all([
  stripe.balanceTransactions.list({ created: { gte: startDate } }),
  quickbooks.expenses.query({ date: { $gte: startDate } }),
  plaid.accounts.getBalance({ access_token: bankToken })
]);

return {
  totalRevenue: revenue.reduce((s, t) => s + t.amount, 0),
  totalExpenses: expenses.reduce((s, e) => s + e.amount, 0),
  cashPosition: bankBalance.accounts[0].balances.current
};
```

**3. Report Generation**
```javascript
// Create Excel report
const workbook = new ExcelJS.Workbook();
const sheet = workbook.addWorksheet('Monthly P&L');

sheet.addRow(['Category', 'Amount', 'YoY Change']);
sheet.addRow(['Revenue', revenue, `${yoyChange}%`]);
sheet.addRow(['Expenses', expenses, `${expenseChange}%`]);
sheet.addRow(['Net Income', revenue - expenses, '']);

const buffer = await workbook.xlsx.writeBuffer();
return { binary: { report: { data: buffer, mimeType: 'application/xlsx' } } };
```

**4. Executive Dashboard Update**
- Push KPIs to Google Sheets
- Update Tableau/Looker extracts
- Slack summary to finance channel

**5. Variance Alerts**
```javascript
// Alert on significant variances
if (Math.abs(actualVsBudget) > 0.1) {
  await slack.send({
    channel: '#finance-alerts',
    text: `⚠ Budget variance alert: ${category} is ${variance}% off target`
  });
}
```

use_case: reporting


instruction: How do I build fraud detection workflows in n8n?

output:
**Fraud Detection Automation with n8n**

**1. Real-Time Transaction Scoring**
```
Payment Webhook
    ↓
Extract Transaction Features
    ↓
Call ML Model (Fraud Score)
    ↓
Decision Engine:
  - Score < 30: Auto-approve
  - Score 30-70: Queue for review
  - Score > 70: Auto-block + Alert
```

**2. Feature Extraction**
```javascript
const transaction = $input.first().json;

const features = {
  amount: transaction.amount,
  isNewDevice: !knownDevices.includes(transaction.deviceId),
  isNewLocation: !usualLocations.includes(transaction.country),
  velocityLast1h: await getTransactionCount(userId, '1h'),
  velocityLast24h: await getTransactionCount(userId, '24h'),
  isUnusualMerchant: !frequentMerchants.includes(transaction.merchantId),
  hourOfDay: new Date().getHours(),
  dayOfWeek: new Date().getDay(),
  accountAge: daysSinceAccountCreation(user.createdAt)
};

return features;
```

**3. ML Model Integration**
```javascript
// Call fraud detection API
const score = await $http.post('https://ml.company.com/fraud/score', {
  body: features,
  headers: { 'X-API-Key': $credentials.mlApiKey }
});

return {
  fraudScore: score.probability,
  riskFactors: score.top_factors
};
```

**4. Alert & Action Workflow**
```javascript
if (fraudScore > 70) {
  // Block transaction
  await paymentGateway.declineTransaction(transactionId);

  // Alert fraud team
  await pagerDuty.trigger({
    severity: 'critical',
    summary: `Blocked suspicious transaction: $${amount}`,
    details: { transactionId, userId, riskFactors }
  });

  // Lock user account pending review
  await userService.suspendAccount(userId, 'fraud_review');
}
```

**5. Feedback Loop**
- Track false positives/negatives
- Retrain model monthly
- Update rules based on new patterns


instruction: How do I automate contract management with n8n?

output:
**Contract Management Automation**

**1. Contract Lifecycle Workflow**
```
New Contract Request
    ↓
Generate from Template (with variables)
    ↓
Internal Review Queue
    ↓
Send for Signature (DocuSign/PandaDoc)
    ↓
Track Signature Status
    ↓
Store Executed Contract
    ↓
Set Renewal Reminders
```

**2. Template Generation**
```javascript
// Merge template with contract data
const template = await getTemplate(contractType);
const merged = template
  .replace('{{client_name}}', client.name)
  .replace('{{effective_date}}', effectiveDate)
  .replace('{{term_length}}', termMonths)
  .replace('{{monthly_fee}}', formatCurrency(monthlyFee))
  .replace('{{payment_terms}}', paymentTerms);

// Generate PDF
const pdf = await pdfService.htmlToPdf(merged);
return { binary: { contract: { data: pdf } } };
```

**3. eSignature Integration**
```javascript
// Send via DocuSign
const envelope = await docusign.createEnvelope({
  emailSubject: `Please sign: ${contractName}`,
  documents: [{
    documentBase64: contractPdf,
    name: contractName
  }],
  recipients: {
    signers: [
      { email: client.email, name: client.name, routingOrder: 1 },
      { email: company.legalEmail, name: 'Legal Team', routingOrder: 2 }
    ]
  },
  status: 'sent'
});
```

**4. Status Tracking**
```
DocuSign Webhook (status change)
    ↓
Update CRM Deal Stage
    ↓
IF signed:
  → Store in Document Management
  → Create recurring billing
  → Notify account team
```

**5. Renewal Management**
```javascript
// 90-day renewal reminder
const expiringContracts = await db.query(`
  SELECT * FROM contracts
  WHERE end_date BETWEEN NOW() AND NOW() + INTERVAL '90 days'
  AND renewal_notified = false
`);

for (const contract of expiringContracts) {
  await sendRenewalReminder(contract);
  await updateNotificationStatus(contract.id);
}
```

industry: legal

use_case: contracts


instruction: How do I implement audit trails and compliance logging in n8n?

output:
**Audit Trail Implementation for Compliance**

**1. Central Logging Architecture**
```
Any Workflow Action
    ↓
Execute Sub-Workflow: Log Audit Event
    ↓
Write to Immutable Log Store
    ↓
Index in Search System
```

**2. Audit Event Structure**
```javascript
// Standard audit event format
const auditEvent = {
  // WHO
  userId: $execution.customData.userId,
  userEmail: $execution.customData.userEmail,
  userRole: $execution.customData.userRole,
  ipAddress: $input.first().json.headers?.['x-forwarded-for'],

  // WHAT
  action: 'RECORD_UPDATED',
  resourceType: 'customer',
  resourceId: customerId,

  // WHEN
  timestamp: new Date().toISOString(),
  executionId: $execution.id,
  workflowId: $workflow.id,

  // DETAILS
  changes: {
    before: previousState,
    after: newState
  }
};
```

**3. Immutable Storage**
```javascript
// Write to append-only log
await s3.putObject({
  Bucket: 'audit-logs',
  Key: `${date}/${nanoid()}.json`,
  Body: JSON.stringify(auditEvent),
  ObjectLockMode: 'COMPLIANCE',
  ObjectLockRetainUntilDate: futureDate(7, 'years')
});

// Also index for search
await elasticsearch.index({
  index: 'audit-logs',
  body: auditEvent
});
```

**4. Compliance Queries**
```javascript
// Who accessed this record in last 30 days?
const accessLog = await elasticsearch.search({
  index: 'audit-logs',
  body: {
    query: {
      bool: {
        must: [
          { match: { resourceId: recordId } },
          { range: { timestamp: { gte: 'now-30d' } } }
        ]
      }
    }
  }
});
```

**5. Compliance Report Generation**
- Scheduled weekly/monthly reports
- Export to PDF for auditors
- Anomaly detection (unusual access patterns)


instruction: How do I automate student enrollment workflows with n8n?

output:
**Student Enrollment Automation**

**1. Enrollment Pipeline**
```
Application Submission (Form/Portal)
    ↓
Document Verification
    ↓
Eligibility Check
    ↓
Acceptance Decision
    ↓
Course Registration
    ↓
LMS Account Creation
    ↓
Welcome Communication
```

**2. Application Processing**
```javascript
// Receive application
const application = $input.first().json;

// Verify required documents
const requiredDocs = ['transcript', 'id_proof', 'photo'];
const missingDocs = requiredDocs.filter(doc => !application.documents[doc]);

if (missingDocs.length > 0) {
  await sendEmail({
    to: application.email,
    subject: 'Missing Documents for Your Application',
    body: `Please submit: ${missingDocs.join(', ')}`
  });
  return { status: 'pending_documents', missing: missingDocs };
}

return { status: 'complete', readyForReview: true };
```

**3. LMS Integration (Canvas/Moodle)**
```javascript
// Create student in LMS
const lmsUser = await canvas.createUser({
  user: {
    name: `${student.firstName} ${student.lastName}`,
    short_name: student.firstName,
    email: student.email,
    sis_user_id: student.studentId
  }
});

// Enroll in courses
for (const courseId of selectedCourses) {
  await canvas.enrollUser({
    enrollment: {
      user_id: lmsUser.id,
      type: 'StudentEnrollment',
      enrollment_state: 'active'
    }
  }, courseId);
}
```

**4. Welcome Sequence**
```
Day 0: Welcome email + credentials
Day 1: Campus tour video
Day 3: Academic advisor intro
Day 7: First week check-in
```

**5. Status Dashboard Update**
- Push enrollment stats to admin dashboard
- Update capacity tracking
- Notify departments of new students

industry: education

use_case: enrollment


instruction: How do I automate grading and notifications for students?

output:
**Automated Grading & Notification System**

**1. Assignment Submission Pipeline**
```
Student Submits Assignment (LMS)
    ↓
LMS Webhook to n8n
    ↓
IF auto-gradeable:
  → Run auto-grader
  → Record score
ELSE:
  → Queue for instructor review
    ↓
Post grade to LMS
    ↓
Student notification
    ↓
IF grade < passing:
  → Trigger support intervention
```

**2. Auto-Grading Integration**
```javascript
// For coding assignments
const submission = $input.first().json;

// Run tests in sandbox
const result = await codeRunner.evaluate({
  code: submission.studentCode,
  language: 'python',
  testCases: assignment.testCases,
  timeout: 30000
});

const score = (result.passed / result.total) * 100;

return {
  score,
  feedback: result.feedback,
  passedTests: result.passed,
  totalTests: result.total
};
```

**3. Grade Posting**
```javascript
// Post to Canvas gradebook
await canvas.postGrade({
  courseId: course.id,
  assignmentId: assignment.id,
  studentId: student.sisId,
  grade: score,
  comment: feedback
});

// Notify student
await sendEmail({
  to: student.email,
  subject: `Grade Posted: ${assignment.name}`,
  body: `Your score: ${score}%\n\n${feedback}`
});
```

**4. At-Risk Student Detection**
```javascript
// Check for struggling students
const atRiskStudents = await db.query(`
  SELECT student_id, AVG(score) as avg_score
  FROM grades
  WHERE course_id = $1
  GROUP BY student_id
  HAVING AVG(score) < 70
`, [courseId]);

// Alert academic advisors
for (const student of atRiskStudents) {
  await notifyAdvisor(student.student_id, 'low_performance');
}
```

**5. Parent/Guardian Notifications**
- Weekly progress summaries
- Alert on failing grades
- Attendance reports

use_case: grading