> ## Documentation Index
> Fetch the complete documentation index at: https://docs.noxus.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Dynamics 365 Integration

> Automate Microsoft Dynamics 365 CRM, ERP, and business process workflows

Dynamics 365 integration enables powerful automation for customer relationship management, enterprise resource planning, and business process automation across Microsoft's business applications platform. This guide covers setup, operations, and common enterprise patterns.

## Capabilities

**Dynamics 365 Sales**:

* Lead and opportunity management
* Contact and account operations
* Sales pipeline automation
* Quote and order processing
* Activity tracking

**Dynamics 365 Customer Service**:

* Case management
* Knowledge base integration
* Service level agreements (SLAs)
* Customer support workflows
* Omnichannel routing

**Dynamics 365 Field Service**:

* Work order management
* Resource scheduling
* Inventory management
* Service agreements

**Dynamics 365 Finance & Operations**:

* Financial management
* Supply chain operations
* Project management
* Asset management

## Setup

### Step 1: Register Application in Azure AD

1. Go to **Azure Portal → Azure Active Directory → App registrations**
2. Click **New registration**
3. Configure:
   * **Name**: Noxus Integration
   * **Supported account types**: Accounts in this organizational directory only
   * **Redirect URI**: Web - `https://app.noxus.ai/integrations/dynamics365/callback`
4. Click **Register**
5. Note **Application (client) ID** and **Directory (tenant) ID**

### Step 2: Create Client Secret

1. In your app registration, go to **Certificates & secrets**
2. Click **New client secret**
3. Add description: "Noxus Integration"
4. Set expiration (e.g., 24 months)
5. Click **Add**
6. Copy **Value** (secret) immediately

### Step 3: Configure API Permissions

1. Go to **API permissions**
2. Click **Add a permission**
3. Select **Dynamics CRM**
4. Select **Delegated permissions**:
   * `user_impersonation`
5. Click **Add permissions**
6. Click **Grant admin consent** (if you have admin rights)

### Step 4: Add to Noxus

1. Open **Connections** in the sidebar and click **Add connection**
2. Find **Dynamics 365**
3. Enter:
   * **Environment URL**: `https://your-org.crm.dynamics.com`
   * **Client ID**: Application (client) ID
   * **Client Secret**: Secret value
   * **Tenant ID**: Directory (tenant) ID
4. Click **Connect**
5. Authorize access

### Step 5: Verify Connection

Test by querying Account or Contact records.

## Nodes Available

**Dynamics 365: Query Records**

* Execute FetchXML or OData queries
* Filter and sort results
* Returns list of records

**Dynamics 365: Get Record**

* Retrieve single record by ID
* Returns full record data

**Dynamics 365: Create Record**

* Create new record (Lead, Contact, Account, etc.)
* Set attributes
* Returns record ID

**Dynamics 365: Update Record**

* Update existing record
* Modify attributes
* Returns success status

**Dynamics 365: Upsert Record**

* Create or update based on alternate key
* Prevents duplicates
* Returns record ID

**Dynamics 365: Delete Record**

* Delete record by ID
* Returns success status

**Dynamics 365: Associate Records**

* Create relationship between records
* Link related records

**Dynamics 365: Execute Action**

* Execute custom action
* Run business logic
* Returns action result

## Triggers

A flow can start on a Dynamics 365 event. In the flow editor, open **Triggers**, then the trigger library, and search for "Dynamics".

| Triggers | Connection | Starts the flow on |
| :- | :- | :- |
| Dynamics CRM Account, Contact and Lead Event | Dynamics 365 CRM | An account, contact or lead event |
| Field Service Work Order and Booking Event | Dynamics 365 Field Service | A work order or booking event |
| Dynamics 365 Invoice, Customer and Sales Order Event | Microsoft Dynamics 365 | An invoice, customer or sales order event |

## OData Query Syntax

### Basic Query Structure

```
entities?$filter=attribute eq 'value'&$select=attribute1,attribute2&$orderby=attribute desc&$top=10
```

### Common Queries

**Leads**:

```
# New leads from last 7 days
leads?$filter=createdon ge 2024-01-01&$select=leadid,fullname,emailaddress1,companyname,statuscode

# Hot leads
leads?$filter=leadqualitycode eq 1 and statecode eq 0&$orderby=createdon desc

# Leads by owner
leads?$filter=_ownerid_value eq 'user-guid'
```

**Opportunities**:

```
# Open opportunities
opportunities?$filter=statecode eq 0&$select=opportunityid,name,estimatedvalue,stepname,estimatedclosedate

# High-value deals
opportunities?$filter=estimatedvalue gt 100000 and statecode eq 0&$orderby=estimatedvalue desc

# Opportunities closing this month
opportunities?$filter=estimatedclosedate ge 2024-01-01 and estimatedclosedate le 2024-01-31
```

**Accounts**:

```
# Active accounts
accounts?$filter=statecode eq 0&$select=accountid,name,revenue,numberofemployees

# Enterprise accounts
accounts?$filter=revenue gt 10000000&$select=accountid,name,revenue,industrycode

# Accounts with open opportunities
accounts?$expand=opportunity_customer_accounts($filter=statecode eq 0)
```

**Cases**:

```
# High priority open cases
incidents?$filter=prioritycode eq 1 and statecode eq 0&$orderby=createdon asc

# Escalated cases
incidents?$filter=isescalated eq true and statecode eq 0

# Cases by customer
incidents?$filter=_customerid_value eq 'account-guid'
```

### Advanced Queries

**Expand (Include Related Data)**:

```
# Account with contacts and opportunities
accounts('account-guid')?$expand=contact_customer_accounts,opportunity_customer_accounts

# Opportunity with products
opportunities('opp-guid')?$expand=opportunityproducts_association
```

**Filtering with Lookup Fields**:

```
# Leads owned by specific user
leads?$filter=_ownerid_value eq 'user-guid'

# Opportunities for specific account
opportunities?$filter=_parentaccountid_value eq 'account-guid'
```

**Option Set Values**:

```
# Filter by option set (picklist)
leads?$filter=industrycode eq 1 # Manufacturing

# Multiple status codes
incidents?$filter=statuscode eq 1 or statuscode eq 2
```

## Common Patterns

### Pattern 1: Lead Scoring and Routing

```
Dynamics 365 Webhook: Lead Created
  Output: lead
    ↓
Extract Lead Information:
  Name: ((lead.fullname))
  Email: ((lead.emailaddress1))
  Company: ((lead.companyname))
  Phone: ((lead.telephone1))
  Industry: ((lead.industrycode))
    ↓
Web Enrichment:
  Clearbit API: Company Lookup
    Domain: ((extract_domain(lead.emailaddress1)))
    Output: company_data
    ↓
LinkedIn API: Person Lookup
  Email: ((lead.emailaddress1))
  Output: person_data
    ↓
Calculate Lead Score:
  Factors:
    - Company size: ((company_data.employees))
    - Revenue: ((company_data.annual_revenue))
    - Industry match: ((industry_match_score))
    - Job title seniority: ((title_score(person_data.title)))
    - Email engagement: ((lead.emailengagement__c))
  Formula: weighted_sum
  Output: lead_score (0-100)
    ↓
Determine Lead Grade:
  Score >= 80 → Hot (1)
  Score >= 60 → Warm (2)
  Score >= 40 → Cold (3)
  Score < 40 → Unqualified (4)
  Output: lead_quality_code
    ↓
Dynamics 365: Update Record
  Entity: lead
  ID: ((lead.leadid))
  Attributes:
    leadqualitycode: ((lead_quality_code))
    leadscore: ((lead_score))
    companysize: ((company_data.employees))
    annualrevenue: ((company_data.annual_revenue))
    jobtitle: ((person_data.title))
    linkedin: ((person_data.linkedin_url))
    description: """
      Enriched lead data:
      - Company: ((company_data.name))
      - Employees: ((company_data.employees))
      - Revenue: $((company_data.annual_revenue))
      - Industry: ((company_data.industry))
      - Title: ((person_data.title))

      Lead score: ((lead_score))/100
    """
    ↓
Conditional: lead_quality_code eq 1
    └─ True → Hot lead, immediate assignment
        ↓
        Dynamics 365: Query Records (Find Available Rep)
          Entity: systemuser
          Filter: """
            isdisabled eq false
            and businessunitid/name eq 'Sales'
          """
          OrderBy: activeleadcount asc
          Top: 1
          Output: available_rep
        ↓
        Dynamics 365: Update Record (Assign Lead)
          Entity: lead
          ID: ((lead.leadid))
          Attributes:
            ownerid: ((available_rep.systemuserid))
            statuscode: 2 # Contacted
        ↓
        Dynamics 365: Create Record (Task)
          Entity: task
          Attributes:
            subject: "Follow up on hot lead: ((lead.companyname))"
            description: """
              High-value lead assigned to you.

              Lead: ((lead.fullname))
              Company: ((lead.companyname))
              Score: ((lead_score))/100
              Email: ((lead.emailaddress1))
            """
            regardingobjectid: ((lead.leadid))
            ownerid: ((available_rep.systemuserid))
            scheduledstart: ((now + 30 minutes))
            scheduledend: ((now + 1 hour))
            prioritycode: 2 # High
        ↓
        Send Teams Message:
          User: ((available_rep.email))
          Message: """
            🔥 **Hot Lead Assigned**

            **Company**: ((lead.companyname))
            **Contact**: ((lead.fullname))
            **Score**: ((lead_score))/100
            **Email**: ((lead.emailaddress1))

            [Open in Dynamics](https://your-org.crm.dynamics.com/main.aspx?etc=4&id=((lead.leadid)))
          """
        ↓
        Send Slack Alert:
          Channel: #sales-hot-leads
          Message: """
            🔥 **Hot Lead**

            **Company**: ((lead.companyname))
            **Assigned to**: ((available_rep.fullname))
            **Score**: ((lead_score))/100
          """
```

### Pattern 2: Opportunity Stage Automation

```
Dynamics 365 Webhook: Opportunity Updated
  Field: stepname (Stage changed)
  Output: opportunity
    ↓
Extract Opportunity Details:
  Name: ((opportunity.name))
  Stage: ((opportunity.stepname))
  Value: ((opportunity.estimatedvalue))
  Close Date: ((opportunity.estimatedclosedate))
  Account: ((opportunity.parentaccountid.name))
    ↓
Switch: Stage
    ├─ Case "Propose" → Generate proposal
    │   ↓
    │   Dynamics 365: Query Records (Get Products)
    │     Entity: opportunityproduct
    │     Filter: _opportunityid_value eq '((opportunity.opportunityid))'
    │     Expand: productid
    │     Output: opportunity_products
    │   ↓
    │   Dynamics 365: Get Record (Account Details)
    │     Entity: account
    │     ID: ((opportunity._parentaccountid_value))
    │     Output: account
    │   ↓
    │   AI Generate Proposal:
    │     Prompt: "Generate a professional sales proposal"
    │     Context:
    │       - Opportunity: ((opportunity))
    │       - Account: ((account))
    │       - Products: ((opportunity_products))
    │       - Company info: ((company_profile))
    │     Output: proposal_content
    │   ↓
    │   Create Word Document:
    │     OneDrive: Create File
    │       Path: /Sales Proposals/
    │       Name: "Proposal - ((account.name)) - ((date)).docx"
    │       Content: ((proposal_content))
    │       Output: doc_url
    │   ↓
    │   Dynamics 365: Create Record (SharePoint Document)
    │     Entity: sharepointdocument
    │     Attributes:
    │       relativelocation: "Proposals"
    │       fullname: "Proposal - ((account.name)).docx"
    │       regardingobjectid: ((opportunity.opportunityid))
    │   ↓
    │   Send Email:
    │     To: ((opportunity.ownerid.internalemailaddress))
    │     Subject: "Proposal Generated: ((opportunity.name))"
    │     Body: "Your proposal is ready: ((doc_url))"
    │
    ├─ Case "Negotiate" → High-value deal alert
    │   ↓
    │   Conditional: estimated value > 500000
    │       └─ True → Notify leadership
    │           ↓
    │           Dynamics 365: Query Records (Get Sales VP)
    │             Entity: systemuser
    │             Filter: title eq 'VP of Sales'
    │             Output: vp_sales
    │           ↓
    │           Send Teams Message:
    │             User: ((vp_sales.email))
    │             Message: """
    │               💼 **Large Deal in Negotiation**
    │
    │               **Opportunity**: ((opportunity.name))
    │               **Value**: $((opportunity.estimatedvalue))
    │               **Account**: ((account.name))
    │               **Owner**: ((opportunity.ownerid.fullname))
    │
    │               [View Opportunity](https://your-org.crm.dynamics.com/main.aspx?etc=3&id=((opportunity.opportunityid)))
    │             """
    │
    ├─ Case "Close" → Process closed deal
    │   ↓
    │   Conditional: opportunity.statecode eq 1 AND opportunity.statuscode eq 3
    │       └─ True → Won deal
    │           ↓
    │           Dynamics 365: Update Record (Account)
    │             Entity: account
    │             ID: ((opportunity._parentaccountid_value))
    │             Attributes:
    │               customertypecode: 3 # Customer
    │               lastusedincampaign: ((today))
    │           ↓
    │           Dynamics 365: Create Record (Order)
    │             Entity: salesorder
    │             Attributes:
    │               name: "Order - ((opportunity.name))"
    │               customerid: ((opportunity._parentaccountid_value))
    │               opportunityid: ((opportunity.opportunityid))
    │               pricelevelid: ((opportunity._pricelevelid_value))
    │               totalamount: ((opportunity.estimatedvalue))
    │           ↓
    │           Create Onboarding Project:
    │             Linear: Create Issue
    │               Title: "Onboard ((account.name))"
    │               Description: """
    │                 **Deal Value**: $((opportunity.estimatedvalue))
    │                 **Close Date**: ((opportunity.actualclosedate))
    │                 **Products**: ((list_products(opportunity_products)))
    │
    │                 **Onboarding Tasks**:
    │                 - [ ] Schedule kickoff call
    │                 - [ ] Provision accounts
    │                 - [ ] Configure integrations
    │                 - [ ] Assign CSM
    │                 - [ ] Send welcome package
    │               """
    │               Labels: ['onboarding', 'high-priority']
    │               Assignee: ((cs_manager))
    │           ↓
    │           Send Teams Celebration:
    │             Channel: Sales Team
    │             Message: """
    │               🎉 **DEAL CLOSED!**
    │
    │               **Account**: ((account.name))
    │               **Value**: $((opportunity.estimatedvalue))
    │               **Owner**: ((opportunity.ownerid.fullname))
    │
    │               Amazing work team! 🚀
    │             """
    │
    └─ Case default → Log stage change
        ↓
        Dynamics 365: Create Record (Note)
          Entity: annotation
          Attributes:
            objectid: ((opportunity.opportunityid))
            subject: "Stage Changed"
            notetext: "Opportunity moved to ((opportunity.stepname)) on ((now))"
```

### Pattern 3: Case Management and Auto-Routing

```
Dynamics 365 Webhook: Case Created
  Output: case
    ↓
Extract Case Information:
  Title: ((case.title))
  Description: ((case.description))
  Priority: ((case.prioritycode))
  Customer: ((case.customerid.name))
  Origin: ((case.caseorigincode))
    ↓
AI Classify Case:
  Prompt: "Classify this support case by category, urgency, and required expertise"
  Input: ((case.title)) ((case.description))
  Schema:
    - category: string (Technical, Billing, Product, General)
    - subcategory: string
    - urgency: string (Critical, High, Medium, Low)
    - required_skills: list[string]
    - estimated_resolution_time: number (hours)
    - sentiment: string (Positive, Neutral, Negative, Angry)
    - summary: string
  Output: classification
    ↓
Map Category to Dynamics:
  Technical → 1
  Billing → 2
  Product → 3
  General → 4
  Output: category_code
    ↓
Dynamics 365: Update Record
  Entity: incident
  ID: ((case.incidentid))
  Attributes:
    casetypecode: ((category_code))
    subjectid: ((subcategory_lookup))
    customersatisfactioncode: ((sentiment_to_code))
    description: """
      ((case.description))

      ---
      AI Analysis:
      Category: ((classification.category)) / ((classification.subcategory))
      Urgency: ((classification.urgency))
      Required Skills: ((classification.required_skills))
      Est. Resolution: ((classification.estimated_resolution_time))h
      Sentiment: ((classification.sentiment))

      Summary: ((classification.summary))
    """
    ↓
Conditional: classification.urgency equals "Critical"
    ├─ True → Escalate immediately
    │   ↓
    │   Dynamics 365: Update Record
    │     Entity: incident
    │     ID: ((case.incidentid))
    │     Attributes:
    │       prioritycode: 1 # High
    │       isescalated: true
    │       severitycode: 1 # Critical
    │   ↓
    │   Dynamics 365: Query Records (Get Manager)
    │     Entity: systemuser
    │     Filter: title eq 'Support Manager'
    │     Output: support_manager
    │   ↓
    │   Dynamics 365: Create Record (Phone Call Activity)
    │     Entity: phonecall
    │     Attributes:
    │       subject: "URGENT: ((case.title))"
    │       description: "Critical case escalated"
    │       regardingobjectid: ((case.incidentid))
    │       ownerid: ((support_manager.systemuserid))
    │       scheduledstart: ((now))
    │       prioritycode: 2 # High
    │   ↓
    │   Send Teams Alert:
    │     Channel: #support-critical
    │     Message: """
    │       🚨 **CRITICAL CASE**
    │
    │       **Case**: ((case.ticketnumber))
    │       **Customer**: ((case.customerid.name))
    │       **Subject**: ((case.title))
    │       **Sentiment**: ((classification.sentiment))
    │
    │       [Open Case](https://your-org.crm.dynamics.com/main.aspx?etc=112&id=((case.incidentid)))
    │
    │       @support-team
    │     """
    │
    └─ False → Auto-assign by skills
        ↓
        Dynamics 365: Query Records (Find Agent with Skills)
          Entity: systemuser
          Filter: """
            isdisabled eq false
            and businessunitid/name eq 'Customer Support'
          """
          Expand: systemuser_skills
          Output: available_agents
        ↓
        Match Agent to Required Skills:
          Required: ((classification.required_skills))
          Available: ((available_agents))
          Sort by: skill_match_score desc, active_cases asc
          Output: best_agent
        ↓
        Dynamics 365: Update Record (Assign Case)
          Entity: incident
          ID: ((case.incidentid))
          Attributes:
            ownerid: ((best_agent.systemuserid))
            statuscode: 2 # In Progress
        ↓
        Send Teams Notification:
          User: ((best_agent.email))
          Message: """
            📋 **New Case Assigned**

            **Case**: ((case.ticketnumber))
            **Customer**: ((case.customerid.name))
            **Category**: ((classification.category))
            **Est. Time**: ((classification.estimated_resolution_time))h

            [Open Case](https://your-org.crm.dynamics.com/main.aspx?etc=112&id=((case.incidentid)))
          """
```

### Pattern 4: Quote Generation and Approval

```
Dynamics 365 Webhook: Quote Requested
  Output: opportunity
    ↓
Dynamics 365: Query Records (Get Products)
  Entity: opportunityproduct
  Filter: _opportunityid_value eq '((opportunity.opportunityid))'
  Expand: productid, uomid
  Output: products
    ↓
Dynamics 365: Get Record (Price List)
  Entity: pricelevel
  ID: ((opportunity._pricelevelid_value))
  Output: price_list
    ↓
Dynamics 365: Get Record (Account)
  Entity: account
  ID: ((opportunity._parentaccountid_value))
  Output: account
    ↓
Calculate Totals:
  For each product:
    Extended Amount = Quantity × Price Per Unit
  Subtotal = Sum of Extended Amounts
  Discount = Subtotal × ((opportunity.discountpercentage / 100))
  Tax = (Subtotal - Discount) × Tax Rate
  Total = Subtotal - Discount + Tax
  Output: quote_totals
    ↓
Dynamics 365: Create Record (Quote)
  Entity: quote
  Attributes:
    name: "Quote - ((account.name)) - ((date))"
    opportunityid: ((opportunity.opportunityid))
    customerid: ((opportunity._parentaccountid_value))
    pricelevelid: ((opportunity._pricelevelid_value))
    effectivefrom: ((today))
    effectiveto: ((today + 30 days))
    totaldiscountamount: ((quote_totals.discount))
    totalamount: ((quote_totals.total))
    description: "Quote generated from opportunity ((opportunity.name))"
  Output: quote_id, quote_number
    ↓
For Each Product:
    Dynamics 365: Create Record (Quote Product)
      Entity: quotedetail
      Attributes:
        quoteid: ((quote_id))
        productid: ((product.productid))
        uomid: ((product.uomid))
        quantity: ((product.quantity))
        priceperunit: ((product.priceperunit))
        manualdiscountamount: ((product.manualdiscountamount))
        tax: ((product.tax))
        extendedamount: ((product.extendedamount))
    ↓
Generate Quote PDF:
  AI Generate Document:
    Template: Quote Template
    Data:
      quote: ((quote))
      products: ((products))
      account: ((account))
      totals: ((quote_totals))
    Output: quote_pdf
    ↓
Dynamics 365: Create Record (Annotation/Note with Attachment)
  Entity: annotation
  Attributes:
    objectid: ((quote_id))
    subject: "Quote PDF"
    filename: "Quote-((quote_number)).pdf"
    documentbody: ((base64_encode(quote_pdf)))
    mimetype: "application/pdf"
    ↓
Conditional: quote_totals.total > 100000
    ├─ True → Requires approval
    │   ↓
    │   Dynamics 365: Query Records (Get Sales Director)
    │     Entity: systemuser
    │     Filter: title eq 'Sales Director'
    │     Output: approver
    │   ↓
    │   Human in the Loop: Approve Quote
    │     Title: "Quote Approval Required"
    │     Context:
    │       Customer: ((account.name))
    │       Amount: $((quote_totals.total))
    │       Products: ((products.length)) items
    │       Discount: ((opportunity.discountpercentage))%
    │     Actions: [Approve, Reject, Request Changes]
    │     Assigned To: ((approver.email))
    │     Output: approval_decision
    │   ↓
    │   Conditional: approval_decision equals "Approve"
    │       ├─ True → Activate quote
    │       │   ↓
    │       │   Dynamics 365: Execute Action
    │       │     Action: WinQuote
    │       │     Target: quote/((quote_id))
    │       │     Parameters:
    │       │       Status: 4 # Active
    │       │
    │       └─ False → Update quote status
    │           Dynamics 365: Update Record
    │             Entity: quote
    │             ID: ((quote_id))
    │             Attributes:
    │               statuscode: 6 # Pending Approval
    │
    └─ False → Auto-approve, send to customer
        ↓
        Dynamics 365: Execute Action
          Action: WinQuote
          Target: quote/((quote_id))
          Parameters:
            Status: 4 # Active
    ↓
Send Quote to Customer:
  To: ((account.emailaddress1))
  CC: ((opportunity.ownerid.internalemailaddress))
  Subject: "Quote ((quote_number)) - ((account.name))"
  Body: """
    Dear ((account.name)),

    Thank you for your interest. Please find attached your quote.

    **Quote Number**: ((quote_number))
    **Valid Until**: ((quote.effectiveto))
    **Total**: $((quote_totals.total))

    Please review and let us know if you have any questions.

    Best regards,
    ((opportunity.ownerid.fullname))
  """
  Attachments: [((quote_pdf))]
    ↓
Dynamics 365: Create Record (Email Activity)
  Entity: email
  Attributes:
    subject: "Quote ((quote_number)) - ((account.name))"
    description: "Quote sent to customer"
    regardingobjectid: ((quote_id))
    to: [((account.contactid))]
    directioncode: true # Outgoing
    statuscode: 3 # Sent
```

### Pattern 5: Account Data Enrichment

```
Scheduled Trigger: Weekly, Sunday 02:00
    ↓
Dynamics 365: Query Records (Accounts Missing Data)
  Entity: account
  Filter: """
    statecode eq 0
    and (revenue eq null or numberofemployees eq null or industrycode eq null)
  """
  Select: accountid,name,websiteurl,emailaddress1
  Output: accounts_to_enrich
    ↓
For Each Account:
    ↓
    Conditional: websiteurl is not null
        └─ True → Enrich from website
            ↓
            Clearbit API: Company Enrichment
              Domain: ((account.websiteurl))
              Output: company_data
            ↓
            Conditional: company_data found
                └─ True → Update account
                    ↓
                    Map Industry:
                      Clearbit Industry → Dynamics Industry Code
                      Output: industry_code
                    ↓
                    Dynamics 365: Update Record
                      Entity: account
                      ID: ((account.accountid))
                      Attributes:
                        revenue: ((company_data.metrics.annual_revenue))
                        numberofemployees: ((company_data.metrics.employees))
                        industrycode: ((industry_code))
                        sic: ((company_data.category.sic_code))
                        description: """
                          ((account.description))

                          Enriched data (((now))):
                          - Industry: ((company_data.category.industry))
                          - Employees: ((company_data.metrics.employees))
                          - Revenue: $((company_data.metrics.annual_revenue))
                          - Founded: ((company_data.founded_year))
                          - Location: ((company_data.geo.city)), ((company_data.geo.state))
                        """
                        address1_city: ((company_data.geo.city))
                        address1_stateorprovince: ((company_data.geo.state))
                        address1_country: ((company_data.geo.country))
                        telephone1: ((company_data.phone))
                    ↓
                    Dynamics 365: Create Record (Note)
                      Entity: annotation
                      Attributes:
                        objectid: ((account.accountid))
                        subject: "Account Enriched"
                        notetext: "Account data enriched from Clearbit on ((now))"
                    ↓
                    Log Success:
                      Database: Enrichment Log
                      Record:
                        account_id: ((account.accountid))
                        account_name: ((account.name))
                        status: 'enriched'
                        timestamp: ((now))
```

### Pattern 6: SLA Monitoring and Escalation

```
Scheduled Trigger: Every 15 minutes
    ↓
Dynamics 365: Query Records (Cases Approaching SLA)
  Entity: incident
  Filter: """
    statecode eq 0
    and slainvokedid ne null
  """
  Expand: slainvokedid
  Output: active_cases
    ↓
For Each Case:
    ↓
    Calculate Time to SLA Breach:
      SLA Target: ((case.slainvokedid.failuretime))
      Current Time: ((now))
      Remaining: ((sla_target - current_time))
      Output: time_remaining (minutes)
    ↓
    Conditional: time_remaining < 30 AND time_remaining > 0
        └─ True → SLA at risk
            ↓
            Dynamics 365: Get Record (Case Owner)
              Entity: systemuser
              ID: ((case._ownerid_value))
              Output: owner
            ↓
            Send Teams Alert:
              User: ((owner.email))
              Message: """
                ⚠️ **SLA Warning**

                **Case**: ((case.ticketnumber))
                **Customer**: ((case.customerid.name))
                **SLA Breach in**: ((time_remaining)) minutes

                Please update the case immediately!

                [Open Case](https://your-org.crm.dynamics.com/main.aspx?etc=112&id=((case.incidentid)))
              """
            ↓
            Conditional: time_remaining < 15
                └─ True → Escalate to manager
                    ↓
                    Dynamics 365: Query Records (Get Manager)
                      Entity: systemuser
                      ID: ((owner._parentsystemuserid_value))
                      Output: manager
                    ↓
                    Dynamics 365: Update Record (Mark as Escalated)
                      Entity: incident
                      ID: ((case.incidentid))
                      Attributes:
                        isescalated: true
                        escalatedon: ((now))
                    ↓
                    Send Teams Alert:
                      User: ((manager.email))
                      Message: """
                        🚨 **SLA ESCALATION**

                        Case ((case.ticketnumber)) is about to breach SLA in ((time_remaining)) minutes.

                        **Owner**: ((owner.fullname))
                        **Customer**: ((case.customerid.name))

                        [Open Case](https://your-org.crm.dynamics.com/main.aspx?etc=112&id=((case.incidentid)))
                      """
```

### Pattern 7: Marketing Campaign Response Tracking

```
Dynamics 365 Webhook: Campaign Response Received
  Output: campaign_response
    ↓
Dynamics 365: Get Record (Campaign)
  Entity: campaign
  ID: ((campaign_response._regardingobjectid_value))
  Output: campaign
    ↓
Dynamics 365: Get Record (Contact/Lead)
  Entity: ((campaign_response.customer_entity))
  ID: ((campaign_response._customer_value))
  Output: contact
    ↓
Analyze Response Type:
  Response Code: ((campaign_response.responsecode))
  Channel: ((campaign_response.channelcode))
  Output: response_type
    ↓
Switch: Response Type
    ├─ Case "Interested" → Create opportunity
    │   ↓
    │   Dynamics 365: Create Record (Opportunity)
    │     Entity: opportunity
    │     Attributes:
    │       name: "Campaign Lead - ((contact.fullname)) - ((campaign.name))"
    │       customerid: ((contact.contactid))
    │       campaignid: ((campaign.campaignid))
    │       estimatedvalue: ((campaign.expectedrevenue))
    │       estimatedclosedate: ((today + 90 days))
    │       originatingleadid: ((contact.leadid if lead))
    │       stepname: "Qualify"
    │       description: "Generated from campaign ((campaign.name))"
    │     Output: opp_id
    │   ↓
    │   Dynamics 365: Create Record (Task)
    │     Entity: task
    │     Attributes:
    │       subject: "Follow up on campaign response"
    │       regardingobjectid: ((opp_id))
    │       scheduledstart: ((now + 1 day))
    │       scheduledend: ((now + 1 day + 1 hour))
    │       prioritycode: 2 # High
    │
    ├─ Case "Not Interested" → Update lead status
    │   ↓
    │   Conditional: customer is lead
    │       └─ True →
    │           Dynamics 365: Update Record
    │             Entity: lead
    │             ID: ((contact.leadid))
    │             Attributes:
    │               statuscode: 7 # Lost
    │               description: "Not interested in campaign ((campaign.name))"
    │
    └─ Case "Do Not Contact" → Opt out
        ↓
        Dynamics 365: Update Record
          Entity: ((customer_entity))
          ID: ((contact.id))
          Attributes:
            donotemail: true
            donotbulkemail: true
            donotphone: true
        ↓
        Dynamics 365: Create Record (Note)
          Entity: annotation
          Attributes:
            objectid: ((contact.id))
            subject: "Opted Out"
            notetext: "Customer opted out from campaign ((campaign.name)) on ((now))"
    ↓
Update Campaign Statistics:
  Dynamics 365: Query Records (All Responses)
    Entity: campaignresponse
    Filter: _regardingobjectid_value eq '((campaign.campaignid))'
    Output: all_responses
    ↓
  Calculate Stats:
    Total Responses: ((all_responses.length))
    Interested: ((count where responsecode = interested))
    Response Rate: ((total_responses / campaign.targetaudience * 100))%
    ↓
  Dynamics 365: Update Record (Campaign)
    Entity: campaign
    ID: ((campaign.campaignid))
    Attributes:
      totalcampaignactivitycount: ((total_responses))
      budgetedcost: ((campaign.budgetedcost))
      actualcost: ((campaign.actualcost))
```

## Custom Entities and Fields

Work with custom entities just like standard entities:

```
# Query custom entity
customentity?$filter=custom_field eq 'value'

# Create custom entity record
Dynamics 365: Create Record
  Entity: new_customentity
  Attributes:
    new_name: "Record Name"
    new_customfield: "Value"
    new_accountid: account-guid
```

## Batch Operations

For multiple operations, use batch requests:

```
Dynamics 365: Batch Operation
  Operations:
    - Create: lead (data1)
    - Update: account (data2)
    - Delete: contact (id3)
  Output: batch_results
```

## Rate Limits

**Service Protection Limits**:

* 6,000 API requests per 5 minutes per user
* 52,000 API requests per 24 hours per user
* Concurrent request limit: 52 per user

**Best Practices**:

* Use batch operations
* Implement exponential backoff (429 retry-after header)
* Cache reference data
* Monitor API usage

## Webhooks

Configure webhooks via **Power Automate** or **Plugin Registration**:

**Common Triggers**:

* Record created
* Record updated
* Record deleted
* Field changed
* Status changed

## Troubleshooting

### "401 Unauthorized"

**Problem**: Authentication failed

**Solutions**:

1. Verify Azure AD app credentials
2. Check token expiration
3. Regenerate client secret
4. Verify API permissions

### "403 Forbidden"

**Problem**: Insufficient privileges

**Solutions**:

1. Check security roles
2. Verify record-level permissions
3. Check field-level security
4. Grant necessary privileges

### "404 Not Found"

**Problem**: Entity or record not found

**Solutions**:

1. Verify entity name (use plural)
2. Check record ID format (GUID)
3. Verify record exists
4. Check environment URL

### "429 Too Many Requests"

**Problem**: Rate limit exceeded

**Solutions**:

1. Implement retry with exponential backoff
2. Use batch operations
3. Reduce request frequency
4. Contact Microsoft for limit increase

## Best Practices

**Use Alternate Keys**: Define alternate keys for upsert operations

**Security Roles**: Assign appropriate security roles to integration user

**Batch Operations**: Batch multiple operations to reduce API calls

**Error Handling**: Implement comprehensive error handling with retries

**Audit Trail**: Enable auditing for critical entities

**Testing**: Always test in sandbox environment first

**Change Management**: Use solutions for deployment

**Performance**: Cache lookup data and use selective queries

**Documentation**: Document all customizations and integration points

**Monitoring**: Track integration health and API usage

***

Dynamics 365 integration enables enterprise-grade CRM and ERP automation, streamlining business processes across Microsoft's business applications platform.

> [card] [Integration Authentication](https://docs.noxus.ai/integrations/authentication.md)
>
> Setup Azure AD OAuth

> [card] [Data Transformations](https://docs.noxus.ai/building/data/transformations)
>
> Transform Dynamics 365 data

> [card] [Human-in-the-Loop](https://docs.noxus.ai/building/automation/hitl)
>
> Build approval workflows

> [card] [Text Generation](https://docs.noxus.ai/building/ai/text-generation)
>
> AI-powered CRM operations


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.