Slack Integration

Overview

Orcha integrates with Slack to provide a conversational interface for data queries, approvals, document uploads, and proactive notifications. Slack acts purely as the UI layer—all processing, classification, and workflow orchestration happens in the Orcha backend.


Architecture

Hybrid Routing Model

The integration uses a hybrid approach combining deterministic routing for structured actions with an LLM-powered agent for conversational queries:

┌─────────────────────────────────────────────────────────────────────┐
│                         SLACK WORKSPACE                              │
├─────────────────────────────────────────────────────────────────────┤
│                                                                      │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────────────────┐  │
│  │ Slash Cmds   │  │ File Uploads │  │ Natural Language Msgs    │  │
│  │ /purchase    │  │ (images,docs)│  │ "@orcha what invoices..."│  │
│  │ /budget      │  │              │  │                          │  │
│  │ /report      │  │              │  │                          │  │
│  └──────┬───────┘  └──────┬───────┘  └────────────┬─────────────┘  │
│         │                 │                        │                 │
│  ┌──────┴─────────────────┴────────────────────────┴─────────────┐  │
│  │                    Slack Bot (Orcha)                          │  │
│  │              Receives events, forwards to backend              │  │
│  └──────────────────────────┬────────────────────────────────────┘  │
│                             │                                        │
└─────────────────────────────┼────────────────────────────────────────┘
                              │ HTTPS / WebSocket
                              ▼
┌─────────────────────────────────────────────────────────────────────┐
│                        ORCHA BACKEND                                 │
├─────────────────────────────────────────────────────────────────────┤
│                                                                      │
│  ┌────────────────────────────────────────────────────────────────┐ │
│  │                    Slack Gateway Service                        │ │
│  │  - Authenticates requests (maps Slack user → Orcha user)       │ │
│  │  - Routes by interaction type                                   │ │
│  │  - Enforces role-based permissions                              │ │
│  └───────┬──────────────────┬──────────────────┬──────────────────┘ │
│          │                  │                  │                     │
│          ▼                  ▼                  ▼                     │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────────────────┐  │
│  │ Command      │  │ Document     │  │ Conversational Agent     │  │
│  │ Handlers     │  │ Processor    │  │ (LLM + Constrained Tools)│  │
│  │ (determin.)  │  │ (OCR, class.)│  │                          │  │
│  └──────────────┘  └──────────────┘  └──────────────────────────┘  │
│          │                  │                  │                     │
│          └──────────────────┴──────────────────┘                     │
│                             │                                        │
│                             ▼                                        │
│  ┌────────────────────────────────────────────────────────────────┐ │
│  │                 Slack Response Builder                          │ │
│  │  - Formats Block Kit messages                                   │ │
│  │  - Attaches action buttons (approve/reject)                     │ │
│  │  - Includes source links and citations                          │ │
│  └────────────────────────────────────────────────────────────────┘ │
│                                                                      │
└─────────────────────────────────────────────────────────────────────┘

Why Hybrid?

Interaction Type Routing Rationale
Slash commands Deterministic Predictable UX, no LLM latency, clear user intent
Button clicks (approve/reject) Deterministic Actions are unambiguous
File uploads Deterministic → Backend classification Mobile UX: no slash command needed, backend handles classification
Natural language queries LLM Agent Flexible search, entity resolution, multi-turn conversations

Multi-Tenancy

Workspace Connection Flow

  1. Orcha admin initiates Slack connection from Orcha settings
  2. OAuth flow grants Orcha bot access to workspace
  3. Users link their Slack accounts to Orcha accounts (SSO or manual)
  4. Bot is added to relevant channels or users interact via DM

Role-Based Access Control

The Slack integration mirrors Orcha's existing role system. The Slack Gateway Service enforces permissions before executing any action or query.

Role Query Scope Actions Proactive Messages
Employee Own expenses, own purchase requests, contracts they're party to Upload expenses, create purchase requests Own approval requests, expense status
Manager Team expenses, team purchase requests, department contracts Approve/reject for direct reports Pending approvals for team
Finance Manager All invoices, all expenses, all purchase requests, all contracts, budgets Approve/reject financial items, budget queries Financial summaries, budget alerts
Executive/CEO Full organization visibility All approvals, executive reports Monthly executive reports, critical alerts

Slash Commands (Deterministic Routing)

Slash commands provide structured entry points for common actions. These bypass the LLM entirely for speed and predictability.

/purchase - Create Purchase Request

Opens a modal to create a new purchase request.

/purchase

Modal Fields:

Response: Confirmation with request ID, assigned approver, and status tracker.

/budget - Check Budget Status

Quick view of budget utilization.

/budget [cost-center]

Response (example):

📊 Marketing Budget (Q1 2026)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Budget:    €50,000
Spent:     €32,450 (65%)
Committed: €8,200
Available: €9,350
━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▓▓▓▓▓▓▓▓▓▓▓▓▓░░░░░░░ 65%

[View Details in Orcha]

Permission: Only shown to users with budget visibility for the requested cost center.

/report - Request Report

Generate or retrieve reports on-demand.

/report [report-type]

Available report types:

/approvals - List Pending Approvals

Quick view of items awaiting user's approval.

/approvals

Response: List of pending items with inline approve/reject buttons.

/help - Command Reference

/help

Shows available commands and example natural language queries.


Natural Language Queries (LLM Agent)

For conversational interactions, users mention the bot or send DMs. The LLM agent processes these with constrained tools.

Triggering the Agent

Agent Architecture

┌─────────────────────────────────────────────────────────────┐
│                  Conversational Agent                        │
├─────────────────────────────────────────────────────────────┤
│                                                              │
│  ┌────────────────────────────────────────────────────────┐ │
│  │                   System Prompt                         │ │
│  │  - Role: Orcha assistant for financial/procurement     │ │
│  │  - Constraints: Only use provided tools, cite sources  │ │
│  │  - Context: User role, permissions, tenant             │ │
│  └────────────────────────────────────────────────────────┘ │
│                                                              │
│  ┌────────────────────────────────────────────────────────┐ │
│  │                   Tool Definitions                      │ │
│  │                                                         │ │
│  │  search_invoices(query, status?, date_range?)          │ │
│  │  search_contracts(query, status?, renewal_date?)       │ │
│  │  search_suppliers(query)                                │ │
│  │  search_expenses(query, status?, submitter?)           │ │
│  │  search_purchase_requests(query, status?)              │ │
│  │  get_budget_status(cost_center)                        │ │
│  │  get_pending_approvals()                                │ │
│  │  get_contract_details(contract_id)                     │ │
│  │  get_invoice_details(invoice_id)                       │ │
│  │  get_supplier_details(supplier_id)                     │ │
│  │                                                         │ │
│  └────────────────────────────────────────────────────────┘ │
│                                                              │
│  ┌────────────────────────────────────────────────────────┐ │
│  │              Permission Enforcement                     │ │
│  │  Tools are filtered based on user's role               │ │
│  │  Query results are scoped to user's access             │ │
│  └────────────────────────────────────────────────────────┘ │
│                                                              │
└─────────────────────────────────────────────────────────────┘

Example Queries

User Query Tool Calls Response
"What invoices are open?" search_invoices(status="open") List with amounts, suppliers, due dates
"Find the Amazon contract" search_contracts(query="Amazon") Matches "Amazon Limited", "Amazon Web Services GmbH", etc.
"Which contracts renew in the next 3 months?" search_contracts(renewal_date="next_3_months") List with renewal dates, values, owners
"What's the status of my laptop request?" search_purchase_requests(query="laptop", submitter=current_user) Status, approver, timeline
"How much have we spent with Acme Corp?" search_suppliers(query="Acme Corp")get_supplier_details(id) Total spend, invoice history, contract summary

Hallucination Prevention

  1. Tool-only responses: Agent can only answer using tool results; no fabricated data
  2. Source citations: Every response includes links to source documents in Orcha
  3. Explicit uncertainty: If no results found, agent says so clearly rather than guessing
  4. Scoped results: All queries are automatically filtered by user permissions
  5. Structured output: Agent returns data in consistent formats, not free-form prose for factual queries

Thread-Based Conversations


File Uploads (Document Processing)

Users can upload documents directly without slash commands—critical for mobile UX.

Supported Upload Types

Document Type Detection Method Resulting Workflow
Expense receipt Image/PDF + expense keywords or no context → Expense submission flow
Invoice PDF with invoice structure → Invoice ingestion pipeline
Contract PDF with contract structure → Contract upload flow
Generic document Fallback → Ask user to classify

Upload Flow

┌─────────────┐     ┌─────────────┐     ┌─────────────────────┐
│ User drops  │────▶│ Slack sends │────▶│ Orcha Backend       │
│ photo/PDF   │     │ file event  │     │                     │
└─────────────┘     └─────────────┘     │ 1. Download file    │
                                         │ 2. OCR extraction   │
                                         │ 3. Classification   │
                                         │ 4. Data extraction  │
                                         │ 5. Workflow trigger │
                                         └──────────┬──────────┘
                                                    │
                                                    ▼
                                         ┌─────────────────────┐
                                         │ Response to Slack   │
                                         │ (confirmation or    │
                                         │  approval request)  │
                                         └─────────────────────┘

Expense Upload Example

User action: Drops photo of restaurant receipt in DM with Orcha bot

Backend processing:

  1. Downloads image from Slack
  2. Runs OCR + extraction (existing Orcha pipeline)
  3. Classifies as expense receipt
  4. Extracts: merchant, amount, date, category (meal)

Bot response:

🧾 Expense Receipt Detected
━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Merchant:  Restaurant Zur Linde
Amount:    €47.80
Date:      January 21, 2026
Category:  Meals & Entertainment

Is this correct?

[✓ Submit Expense]  [✎ Edit Details]  [✗ Cancel]

Clicking "Submit Expense" creates the expense and routes to approver.


Approval Workflows

Approvals happen entirely within Slack—no need to open Orcha.

Approval Notification Format

When an item requires approval, the approver receives a threaded message:

🔔 Approval Required: Purchase Request
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Requester:   @maria.schmidt
Item:        MacBook Pro 14"
Amount:      €2,499.00
Supplier:    Apple Store
Cost Center: Engineering
Justification: Current laptop 4+ years old, performance issues

📎 Attachments: quote.pdf

[✓ Approve]  [✗ Reject]  [💬 Ask Question]  [View in Orcha]

Approval Actions

Button Behavior
Approve Approves immediately, notifies requester, updates Orcha
Reject Opens modal for rejection reason (required), notifies requester
Ask Question Opens thread, notifies requester, approval paused
View in Orcha Deep link to item in Orcha for full details

Multi-Level Approvals

For items requiring multiple approvers:


Proactive Messages

Scheduled Executive Reports

Recipients: Executives, Finance Managers (configurable per tenant)

Frequency: Monthly (first Monday of month, 9:00 AM tenant timezone)

Content:

📊 Monthly Financial Summary - December 2025
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

💰 Budget vs. Actual
┌────────────────┬──────────┬──────────┬─────────┐
│ Department     │ Budget   │ Actual   │ Var     │
├────────────────┼──────────┼──────────┼─────────┤
│ Engineering    │ €120,000 │ €115,420 │ -4%  ✓  │
│ Marketing      │ €50,000  │ €62,300  │ +25% ⚠️ │
│ Operations     │ €80,000  │ €78,900  │ -1%  ✓  │
│ Sales          │ €45,000  │ €44,200  │ -2%  ✓  │
└────────────────┴──────────┴──────────┴─────────┘

📄 Invoices
• Processed: 142 (€485,200)
• Pending approval: 8 (€23,400)
• Overdue: 3 (€12,100) ⚠️

📝 Contracts
• Active: 47
• Expiring in 30 days: 2
• New this month: 5

[View Full Report in Orcha]

Approval Reminders

Aggressiveness: Medium

Time Since Request Action
4 hours First reminder (if working hours)
24 hours Second reminder, slightly more urgent
48 hours Escalation warning: "Will escalate to @manager in 24h"
72 hours Auto-escalate to next approver in chain

Reminder message:

⏰ Reminder: Pending Approval
━━━━━━━━━━━━━━━━━━━━━━━━━━━━
You have 3 items awaiting your approval:

1. Expense €127.50 from @john.doe (2 days ago)
2. Purchase Request €890 from @anna.lee (1 day ago)  
3. Invoice €2,340 from Supplier XYZ (4 hours ago)

[Review All Approvals]

Context-aware urgency:

Event-Driven Notifications

Event Recipients Message
Contract expiring in 30 days Contract owner, Finance Renewal reminder with details
Budget threshold reached (80%, 100%) Cost center owner, Finance Budget alert
Invoice overdue Finance Manager Overdue notice with aging
Expense approved/rejected Submitter Status update
Purchase request status change Requester Progress notification

Technical Implementation

Slack App Configuration

Required Scopes:

Event Subscriptions:

Database Schema Additions

-- Slack workspace connections
CREATE TABLE slack_workspaces (
    id UUID PRIMARY KEY,
    tenant_id UUID REFERENCES tenants(id),
    slack_team_id TEXT UNIQUE NOT NULL,
    slack_team_name TEXT,
    bot_token TEXT ENCRYPTED,
    bot_user_id TEXT,
    connected_at TIMESTAMPTZ DEFAULT NOW(),
    connected_by UUID REFERENCES users(id)
);

-- Slack user mappings
CREATE TABLE slack_user_mappings (
    id UUID PRIMARY KEY,
    workspace_id UUID REFERENCES slack_workspaces(id),
    slack_user_id TEXT NOT NULL,
    orcha_user_id UUID REFERENCES users(id),
    linked_at TIMESTAMPTZ DEFAULT NOW(),
    UNIQUE(workspace_id, slack_user_id)
);

-- Message tracking for threads/context
CREATE TABLE slack_conversations (
    id UUID PRIMARY KEY,
    workspace_id UUID REFERENCES slack_workspaces(id),
    channel_id TEXT NOT NULL,
    thread_ts TEXT,
    orcha_user_id UUID REFERENCES users(id),
    context JSONB, -- Conversation history for agent
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- Pending approval messages (for button callbacks)
CREATE TABLE slack_approval_messages (
    id UUID PRIMARY KEY,
    workspace_id UUID REFERENCES slack_workspaces(id),
    channel_id TEXT NOT NULL,
    message_ts TEXT NOT NULL,
    approvable_type TEXT NOT NULL, -- 'expense', 'purchase_request', 'invoice'
    approvable_id UUID NOT NULL,
    approver_user_id UUID REFERENCES users(id),
    status TEXT DEFAULT 'pending',
    created_at TIMESTAMPTZ DEFAULT NOW()
);

API Endpoints

POST /api/slack/events          -- Slack event webhook
POST /api/slack/interactions    -- Button clicks, modal submissions
POST /api/slack/commands        -- Slash command handler
GET  /api/slack/oauth/callback  -- OAuth completion
POST /api/slack/oauth/initiate  -- Start OAuth flow

Backend Services

  1. SlackGatewayService - Receives all Slack events, authenticates, routes
  2. SlackCommandHandler - Processes slash commands
  3. SlackAgentService - Manages LLM agent for natural language queries
  4. SlackNotificationService - Sends proactive messages
  5. SlackApprovalService - Handles approval button interactions
  6. SlackDocumentService - Processes file uploads

Error Handling

Scenario User Experience
User not linked to Orcha "Please link your Slack account to Orcha first: [Link Account]"
Permission denied "You don't have access to this information. Contact your admin."
Backend timeout "Taking longer than expected... [Retry] or [View in Orcha]"
LLM error Falls back to: "I couldn't process that. Try a slash command or [Open Orcha]"
File processing failed "Couldn't process this file. Please upload to Orcha directly: [Upload Link]"

Security Considerations

  1. Token storage: Bot tokens encrypted at rest
  2. Request verification: All Slack requests verified using signing secret
  3. Permission enforcement: Every action checks Orcha RBAC before execution
  4. Audit logging: All Slack actions logged with user, action, timestamp
  5. Data minimization: Conversation context purged after 24h of inactivity
  6. No sensitive data in logs: Slack message content not logged, only metadata

Metrics & Monitoring

Metric Purpose
Commands per day (by type) Usage patterns
Agent query latency (p50, p95) Performance
Approval response time Workflow efficiency
File upload success rate Document processing health
Error rate by type Reliability

Future Enhancements (Out of Scope for Initial Release)