# openclaw-dynamics-365

Adopt this skill: https://proskills.md/skills/other/vieiradiego-openclaw-dynamics-365

Page: https://proskills.md/skills/other/vieiradiego-openclaw-dynamics-365
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: SKILL.md
size: 4934
sha: 1eae6ce00afd0bcb56159b03c9147cd748fa4361
upstream: https://github.com/vieiradiego/openclaw-dynamics-365/blob/HEAD/SKILL.md

````text
---
name: openclaw-dynamics-365
description: Create and update CRM records in Microsoft Dynamics 365 — Opportunities, Leads, Contacts, Accounts, and Tasks via Dataverse Web API with Azure AD OAuth 2.0.
metadata:
  openclaw:
    requires:
      env:
        - DYNAMICS365_CLIENT_ID
        - DYNAMICS365_CLIENT_SECRET
        - DYNAMICS365_TENANT_ID
        - DYNAMICS365_INSTANCE_URL
    primaryEnv: DYNAMICS365_INSTANCE_URL
---

# Dynamics 365 CRM Skill

## When to activate

Activate this skill when the user mentions **Microsoft Dynamics 365**, **D365**, **Dynamics CRM**, or any of the following actions directed at a Dynamics 365 CRM:

- Creating or updating an **opportunity** / deal / oportunidade
- Creating or updating a **lead**
- Creating or updating a **contact** / contacto
- Creating or updating an **account** / empresa / conta
- Creating a **task** / activity linked to a CRM record

## Credentials required

| Variable | Description |
|---|---|
| `DYNAMICS365_CLIENT_ID` | Azure AD Application (client) ID |
| `DYNAMICS365_CLIENT_SECRET` | Azure AD client secret |
| `DYNAMICS365_TENANT_ID` | Azure AD Tenant ID — use `common` for multi-tenant |
| `DYNAMICS365_INSTANCE_URL` | Dynamics 365 instance URL, e.g. `https://contoso.crm.dynamics.com` |

## Step-by-step execution

### 1 — Identify intent and entity type

Determine from the user's message which entity to create or update:

| User says | Entity | Action |
|---|---|---|
| "create deal", "new opportunity", "deal com X" | Opportunity | upsert |
| "new lead", "criar lead", "prospect X" | Lead | upsert |
| "add contact", "criar contacto", "cliente X no CRM" | Contact | upsert |
| "new account", "empresa Y no CRM", "criar conta" | Account | upsert |
| "create task", "follow-up", "lembrete para X" | Task | create |

### 2 — Extract fields from user input

**Opportunity fields:**
- `name` — deal / opportunity name (required)
- `estimatedvalue` — numeric value in local currency
- `stepname` — pipeline stage: "Qualify" / "Develop" / "Propose" / "Close"
- `actualclosedate` — expected close date (ISO: YYYY-MM-DD)

**Lead fields:**
- `fullname` — full name (required)
- `emailaddress1` — email address
- `companyname` — company name
- `telephone1` — phone number
- `jobtitle` — job title

**Contact fields:**
- `fullname` — full name (required)
- `emailaddress1` — email address
- `telephone1` — phone number
- `jobtitle` — job title

**Account fields:**
- `name` — company / account name (required)
- `emailaddress1` — email address
- `telephone1` — phone number
- `websiteurl` — website

**Task fields:**
- `subject` — task title (required)
- `description` — details / notes
- `scheduledend` — due date-time (ISO 8601)
- `prioritycode` — 0 = Low, 1 = Normal, 2 = High

### 3 — Call the appropriate method

Use the `Dynamics365Client` from the `openclaw-dynamics-365` npm package:

```typescript
import { Dynamics365Client } from "openclaw-dynamics-365";

const client = new Dynamics365Client(
  process.env.DYNAMICS365_INSTANCE_URL,
  accessToken,  // obtained via OAuth flow
);

// Opportunity
const result = await client.upsertOpportunity({ name: "Deal Contoso", estimatedvalue: 50000 });

// Lead
const result = await client.upsertLead({ fullname: "João Silva", companyname: "TechNova" });

// Contact
const result = await client.upsertContact({ fullname: "Maria Santos", emailaddress1: "maria@techno.com" });

// Account
const result = await client.upsertAccount({ name: "TechNova Ltda" });

// Task
const taskId = await client.createTask({ subject: "Follow-up call", prioritycode: 2 });
```

### 4 — Format response to the user

On success:
```
✅ [Entity] "[name]" [created/updated] in Dynamics 365.
🔗 [record URL]
```

On error:
```
❌ Could not [create/update] [entity] in Dynamics 365: [error message]
```

## OAuth setup

For initial authorization, use `getAuthorizationUrl()` to redirect the user to
Microsoft's consent screen, then `exchangeCodeForTokens()` in the callback:

```typescript
import { getAuthorizationUrl, exchangeCodeForTokens } from "openclaw-dynamics-365";

// 1. Redirect user
const url = getAuthorizationUrl(config, redirectUri, state);

// 2. In callback
const tokens = await exchangeCodeForTokens(config, code, redirectUri);

// 3. Refresh when expired (~1h)
if (isTokenExpired(tokens)) {
  tokens = await refreshAccessToken(config, tokens.refreshToken);
}
```

## Notes

- The Dataverse Web API uses **OData v4** — all queries use `$filter`, `$select`, `$top`
- Upsert operations search by name/email first to avoid duplicates
- Lookup fields (e.g. linking a Contact to an Account) use OData binding syntax:
  `"parentcustomerid_account@odata.bind": "/accounts({accountId})"`
- Rate limit: **6,000 requests / 5 minutes** per user — well within typical usage
- Access tokens expire after **~1 hour** — implement refresh logic using `refreshAccessToken()`
````

## File: README.md
size: 6551
sha: 479f37638553a339084aae2c0e28b58c8033acff
upstream: https://github.com/vieiradiego/openclaw-dynamics-365/blob/HEAD/README.md

````text
# openclaw-dynamics-365

> OpenClaw skill for **Microsoft Dynamics 365 CRM** — voice-to-CRM via Dataverse Web API.

[![npm](https://img.shields.io/npm/v/openclaw-dynamics-365)](https://www.npmjs.com/package/openclaw-dynamics-365)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
[![OpenClaw](https://img.shields.io/badge/OpenClaw-skill-blue)](https://clawhub.ai)

Create and update CRM records in Microsoft Dynamics 365 by voice — Opportunities, Leads, Contacts, Accounts, and Tasks — using the [Dataverse Web API](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/overview) with Azure AD OAuth 2.0.

## Supported entities

| Entity | Operations |
|---|---|
| Opportunity | Create, Update (upsert by name) |
| Lead | Create, Update (upsert by name or email) |
| Contact | Create, Update (upsert by name or email) |
| Account | Create, Update (upsert by name) |
| Task | Create |

## Installation

```bash
# Via ClawHub CLI
clawhub install openclaw-dynamics-365

# Or as an npm package
npm install openclaw-dynamics-365
```

## Azure AD setup

This skill requires an **Azure App Registration**. See the [Azure Portal Setup Guide](#azure-portal-setup) below.

## Environment variables

| Variable | Required | Description |
|---|---|---|
| `DYNAMICS365_CLIENT_ID` | ✅ | Azure AD Application (client) ID |
| `DYNAMICS365_CLIENT_SECRET` | ✅ | Azure AD client secret value |
| `DYNAMICS365_TENANT_ID` | ✅ | Azure AD Tenant ID (`common` for multi-tenant) |
| `DYNAMICS365_INSTANCE_URL` | ✅ | Your D365 instance URL, e.g. `https://contoso.crm.dynamics.com` |

## Quick start

```typescript
import {
  Dynamics365Client,
  getAuthorizationUrl,
  exchangeCodeForTokens,
  isTokenExpired,
  refreshAccessToken,
} from "openclaw-dynamics-365";

const config = {
  clientId: process.env.DYNAMICS365_CLIENT_ID,
  clientSecret: process.env.DYNAMICS365_CLIENT_SECRET,
  tenantId: process.env.DYNAMICS365_TENANT_ID ?? "common",
  instanceUrl: process.env.DYNAMICS365_INSTANCE_URL,
};

// 1. Start OAuth flow — redirect user to this URL
const authUrl = getAuthorizationUrl(config, "https://yourapp.com/callback", "csrf-state");

// 2. In the OAuth callback handler
const tokens = await exchangeCodeForTokens(config, code, "https://yourapp.com/callback");

// 3. Use the client
const client = new Dynamics365Client(tokens.instanceUrl, tokens.accessToken);

// Create or update an Opportunity
const result = await client.upsertOpportunity({
  name: "Deal TechNova Q2",
  estimatedvalue: 75000,
  stepname: "Propose",
  actualclosedate: "2026-06-30",
});

console.log(result.created ? "Created:" : "Updated:", result.id);
console.log(Dynamics365Client.recordUrl(tokens.instanceUrl, "opportunity", result.id));
```

## API reference

### `Dynamics365Client`

```typescript
const client = new Dynamics365Client(instanceUrl: string, accessToken: string);
```

| Method | Returns | Description |
|---|---|---|
| `upsertOpportunity(payload)` | `Promise<UpsertResult>` | Create or update an Opportunity |
| `upsertLead(payload)` | `Promise<UpsertResult>` | Create or update a Lead |
| `upsertContact(payload)` | `Promise<UpsertResult>` | Create or update a Contact |
| `upsertAccount(payload)` | `Promise<UpsertResult>` | Create or update an Account |
| `createTask(payload)` | `Promise<string>` | Create a Task — returns `activityid` |
| `searchOpportunity(name)` | `Promise<string \| null>` | Find Opportunity by name |
| `searchLead(query)` | `Promise<string \| null>` | Find Lead by name or email |
| `searchContact(query)` | `Promise<string \| null>` | Find Contact by name or email |
| `searchAccount(name)` | `Promise<string \| null>` | Find Account by name |

**Static helpers:**

```typescript
// Deep link to a record in the Dynamics 365 UI
Dynamics365Client.recordUrl(instanceUrl, "opportunity", id);

// OData binding reference for lookup fields
Dynamics365Client.bindRef("accounts", accountId); // → "/accounts(abc-123)"
```

### OAuth helpers

```typescript
getAuthorizationUrl(config, redirectUri, state): string
exchangeCodeForTokens(config, code, redirectUri): Promise<OAuthTokens>
refreshAccessToken(config, refreshToken): Promise<OAuthTokens>
isTokenExpired(tokens): boolean
```

---

## Azure Portal setup

Follow these steps to create the App Registration needed for OAuth 2.0.

### 1. Create App Registration

1. Go to [portal.azure.com](https://portal.azure.com) → **Microsoft Entra ID** → **App registrations** → **New registration**
2. Fill in:
   - **Name:** `openclaw-dynamics-365` (or any descriptive name)
   - **Supported account types:** `Accounts in any organizational directory (Any Azure AD directory - Multitenant)`
   - **Redirect URI:** Web → `https://yourapp.com/auth/dynamics365/callback`
3. Click **Register**

### 2. Note your credentials

After registration, copy:
- **Application (client) ID** → `DYNAMICS365_CLIENT_ID`
- **Directory (tenant) ID** → `DYNAMICS365_TENANT_ID` (use `common` for multi-tenant)

### 3. Create a client secret

1. Go to **Certificates & secrets** → **New client secret**
2. Set an expiry (24 months recommended)
3. Copy the **Value** immediately → `DYNAMICS365_CLIENT_SECRET`

### 4. Add API permissions

1. Go to **API permissions** → **Add a permission**
2. Select the **APIs my organization uses** tab
3. Search for `Dataverse` and select it from the results
4. Select **Delegated permissions** → `user_impersonation`
5. Click **Add permissions**
6. Click **Grant admin consent** (requires Global Admin or Application Admin role)

### 5. Get your instance URL

Your Dynamics 365 instance URL is shown in the D365 browser address bar:
`https://{org}.crm.dynamics.com` → set as `DYNAMICS365_INSTANCE_URL`

---

## Linking records (OData bindings)

To link a Contact to an Account, or a Task to an Opportunity, use `Dynamics365Client.bindRef()`:

```typescript
// Link contact to account
await client.upsertContact({
  fullname: "João Silva",
  emailaddress1: "joao@techno.com",
  "parentcustomerid_account@odata.bind": Dynamics365Client.bindRef("accounts", accountId),
});

// Link task to opportunity
await client.createTask({
  subject: "Follow-up call",
  prioritycode: 2,
  "regardingobjectid_opportunity_task@odata.bind": Dynamics365Client.bindRef("opportunities", oppId),
});
```

---

## Contributing

Contributions are welcome. Please open an issue or pull request on [GitHub](https://github.com/vieiradiego/openclaw-dynamics-365).

## License

MIT © [Diego Vieira](https://github.com/vieiradiego)
````

## File: .gitignore
size: 66
sha: 1c27b3a6952c5f434ee9a83776e62688a15db10b
upstream: https://github.com/vieiradiego/openclaw-dynamics-365/blob/HEAD/.gitignore

```text
node_modules/
dist/
*.js.map
*.d.ts.map
.env
.env.local
coverage/
```

## File: jest.config.js
size: 576
sha: e55f47fce85449867905624eae643423804bf444
upstream: https://github.com/vieiradiego/openclaw-dynamics-365/blob/HEAD/jest.config.js

```text
/** @type {import('jest').Config} */
export default {
  preset: "ts-jest/presets/default-esm",
  testEnvironment: "node",
  extensionsToTreatAsEsm: [".ts"],
  moduleNameMapper: {
    "^(\\.{1,2}/.*)\\.js$": "$1",
  },
  transform: {
    "^.+\\.tsx?$": [
      "ts-jest",
      {
        useESM: true,
        tsconfig: {
          module: "NodeNext",
          moduleResolution: "NodeNext",
        },
      },
    ],
  },
  testMatch: ["**/tests/**/*.test.ts"],
  collectCoverageFrom: ["src/**/*.ts"],
  coverageThreshold: {
    global: { lines: 80, functions: 80 },
  },
};
```

## File: LICENSE
size: 1069
sha: 4bbfe5b8fa1b26d81584bd411a8a1cf5fbfe3dac
upstream: https://github.com/vieiradiego/openclaw-dynamics-365/blob/HEAD/LICENSE

```text
MIT License

Copyright (c) 2026 Diego Vieira

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```

## File: package.json
size: 1283
sha: 1c68b13d4c2ee50c4c8ec1f4c5d17c672943fb98
upstream: https://github.com/vieiradiego/openclaw-dynamics-365/blob/HEAD/package.json

```text
{
  "name": "openclaw-dynamics-365",
  "version": "1.0.0",
  "description": "OpenClaw skill for Microsoft Dynamics 365 CRM — voice-to-CRM via Dataverse Web API (Opportunities, Leads, Contacts, Accounts, Tasks)",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "type": "module",
  "exports": {
    ".": {
      "import": "./dist/index.js",
      "types": "./dist/index.d.ts"
    }
  },
  "scripts": {
    "build": "tsc",
    "test": "node --experimental-vm-modules node_modules/.bin/jest",
    "lint": "tsc --noEmit",
    "prepublishOnly": "npm run build"
  },
  "keywords": [
    "openclaw",
    "dynamics365",
    "crm",
    "dataverse",
    "microsoft",
    "azure",
    "voice-to-crm",
    "oauth",
    "odata"
  ],
  "author": "Diego Vieira <talk@youco.io>",
  "license": "MIT",
  "repository": {
    "type": "git",
    "url": "https://github.com/vieiradiego/openclaw-dynamics-365.git"
  },
  "homepage": "https://github.com/vieiradiego/openclaw-dynamics-365#readme",
  "bugs": {
    "url": "https://github.com/vieiradiego/openclaw-dynamics-365/issues"
  },
  "engines": {
    "node": ">=20.0.0"
  },
  "devDependencies": {
    "@types/jest": "^29.5.0",
    "@types/node": "^22.0.0",
    "jest": "^29.7.0",
    "ts-jest": "^29.2.0",
    "typescript": "^5.7.0"
  }
}
```

## File: src/client.ts
size: 12428
sha: 0a4c12e7b7494f8c095f99f5135406b60245b144
upstream: https://github.com/vieiradiego/openclaw-dynamics-365/blob/HEAD/src/client.ts

```text
/**
 * openclaw-dynamics-365 — Dataverse Web API Client
 *
 * Implements CRUD operations for the five core CRM entities:
 * Opportunity, Lead, Contact, Account, Task
 *
 * API reference: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/overview
 * API version: v9.2 (latest stable as of 2026)
 *
 * HTTP behaviour per official docs:
 *  POST   → 204 No Content  | record ID in `OData-EntityId` response header
 *  PATCH  → 204 No Content  | no body; requires `If-Match: *` to prevent accidental upsert
 *  GET    → 200 OK          | body: { value: T[] }  (empty: { value: [] })
 */

import type {
  D365Account,
  D365Contact,
  D365Lead,
  D365Opportunity,
  D365Task,
  UpsertResult,
} from "./types.js";

const API_VERSION = "v9.2";

export class Dynamics365Client {
  private readonly baseUrl: string;
  private readonly headers: Record<string, string>;

  /**
   * @param instanceUrl  e.g. https://contoso.crm.dynamics.com
   * @param accessToken  Bearer token from Azure AD OAuth flow
   */
  constructor(instanceUrl: string, accessToken: string) {
    const origin = instanceUrl.replace(/\/$/, "");
    this.baseUrl = `${origin}/api/data/${API_VERSION}`;
    this.headers = {
      Authorization: `Bearer ${accessToken}`,
      "Content-Type": "application/json",
      Accept: "application/json",
      "OData-MaxVersion": "4.0",
      "OData-Version": "4.0",
    };
  }

  // ─── Opportunities ──────────────────────────────────────────────────────────

  /**
   * Find an Opportunity by exact name match.
   *
   * GET /opportunities?$select=opportunityid&$filter=name eq 'X'&$top=1
   * Response: 200 OK — { value: [{ opportunityid: "guid" }] } or { value: [] }
   */
  async searchOpportunity(name: string): Promise<string | null> {
    const filter = `name eq '${escapeSingleQuotes(name)}'`;
    const resp = await fetch(
      `${this.baseUrl}/opportunities?$select=opportunityid&$filter=${encodeURIComponent(filter)}&$top=1`,
      { headers: this.headers },
    );
    if (!resp.ok) return null;
    const data = (await resp.json()) as { value: Array<{ opportunityid: string }> };
    return data.value[0]?.opportunityid ?? null;
  }

  /**
   * Create or update an Opportunity.
   *
   * Create → POST /opportunities
   *   Response: 204 No Content
   *   ID extracted from OData-EntityId header: .../opportunities(guid)
   *
   * Update → PATCH /opportunities({id})
   *   Response: 204 No Content
   *   If-Match: * prevents accidental creation via upsert
   */
  async upsertOpportunity(payload: D365Opportunity): Promise<UpsertResult> {
    const existingId =
      payload.opportunityid ?? (await this.searchOpportunity(payload.name));

    const { opportunityid: _id, ...fields } = payload;

    if (existingId) {
      const resp = await fetch(
        `${this.baseUrl}/opportunities(${existingId})`,
        {
          method: "PATCH",
          headers: { ...this.headers, "If-Match": "*" },
          body: JSON.stringify(fields),
        },
      );
      if (!resp.ok) {
        throw new Error(`Opportunity PATCH failed: ${resp.status} ${await resp.text()}`);
      }
      return { id: existingId, created: false };
    }

    const resp = await fetch(`${this.baseUrl}/opportunities`, {
      method: "POST",
      headers: this.headers,
      body: JSON.stringify(fields),
    });
    if (!resp.ok) {
      throw new Error(`Opportunity POST failed: ${resp.status} ${await resp.text()}`);
    }
    return { id: extractGuid(resp.headers.get("OData-EntityId") ?? ""), created: true };
  }

  // ─── Leads ──────────────────────────────────────────────────────────────────

  /**
   * Find a Lead by full name or primary email address.
   *
   * GET /leads?$select=leadid&$filter=fullname eq 'X' or emailaddress1 eq 'X'&$top=1
   * Response: 200 OK — { value: [{ leadid: "guid" }] } or { value: [] }
   */
  async searchLead(query: string): Promise<string | null> {
    const escaped = escapeSingleQuotes(query);
    const filter = `fullname eq '${escaped}' or emailaddress1 eq '${escaped}'`;
    const resp = await fetch(
      `${this.baseUrl}/leads?$select=leadid&$filter=${encodeURIComponent(filter)}&$top=1`,
      { headers: this.headers },
    );
    if (!resp.ok) return null;
    const data = (await resp.json()) as { value: Array<{ leadid: string }> };
    return data.value[0]?.leadid ?? null;
  }

  /**
   * Create or update a Lead.
   * Searches by email (preferred) or full name before creating.
   */
  async upsertLead(payload: D365Lead): Promise<UpsertResult> {
    const searchKey = payload.emailaddress1 ?? payload.fullname ?? "";
    const existingId =
      payload.leadid ?? (searchKey ? await this.searchLead(searchKey) : null);

    const { leadid: _id, ...fields } = payload;

    if (existingId) {
      const resp = await fetch(`${this.baseUrl}/leads(${existingId})`, {
        method: "PATCH",
        headers: { ...this.headers, "If-Match": "*" },
        body: JSON.stringify(fields),
      });
      if (!resp.ok) {
        throw new Error(`Lead PATCH failed: ${resp.status} ${await resp.text()}`);
      }
      return { id: existingId, created: false };
    }

    const resp = await fetch(`${this.baseUrl}/leads`, {
      method: "POST",
      headers: this.headers,
      body: JSON.stringify(fields),
    });
    if (!resp.ok) {
      throw new Error(`Lead POST failed: ${resp.status} ${await resp.text()}`);
    }
    return { id: extractGuid(resp.headers.get("OData-EntityId") ?? ""), created: true };
  }

  // ─── Contacts ───────────────────────────────────────────────────────────────

  /**
   * Find a Contact by full name or primary email address.
   *
   * GET /contacts?$select=contactid&$filter=fullname eq 'X' or emailaddress1 eq 'X'&$top=1
   */
  async searchContact(query: string): Promise<string | null> {
    const escaped = escapeSingleQuotes(query);
    const filter = `fullname eq '${escaped}' or emailaddress1 eq '${escaped}'`;
    const resp = await fetch(
      `${this.baseUrl}/contacts?$select=contactid&$filter=${encodeURIComponent(filter)}&$top=1`,
      { headers: this.headers },
    );
    if (!resp.ok) return null;
    const data = (await resp.json()) as { value: Array<{ contactid: string }> };
    return data.value[0]?.contactid ?? null;
  }

  /** Create or update a Contact. */
  async upsertContact(payload: D365Contact): Promise<UpsertResult> {
    const searchKey = payload.emailaddress1 ?? payload.fullname ?? "";
    const existingId =
      payload.contactid ??
      (searchKey ? await this.searchContact(searchKey) : null);

    const { contactid: _id, ...fields } = payload;

    if (existingId) {
      const resp = await fetch(`${this.baseUrl}/contacts(${existingId})`, {
        method: "PATCH",
        headers: { ...this.headers, "If-Match": "*" },
        body: JSON.stringify(fields),
      });
      if (!resp.ok) {
        throw new Error(`Contact PATCH failed: ${resp.status} ${await resp.text()}`);
      }
      return { id: existingId, created: false };
    }

    const resp = await fetch(`${this.baseUrl}/contacts`, {
      method: "POST",
      headers: this.headers,
      body: JSON.stringify(fields),
    });
    if (!resp.ok) {
      throw new Error(`Contact POST failed: ${resp.status} ${await resp.text()}`);
    }
    return { id: extractGuid(resp.headers.get("OData-EntityId") ?? ""), created: true };
  }

  // ─── Accounts ───────────────────────────────────────────────────────────────

  /**
   * Find an Account by exact name match.
   *
   * GET /accounts?$select=accountid&$filter=name eq 'X'&$top=1
   */
  async searchAccount(name: string): Promise<string | null> {
    const filter = `name eq '${escapeSingleQuotes(name)}'`;
    const resp = await fetch(
      `${this.baseUrl}/accounts?$select=accountid&$filter=${encodeURIComponent(filter)}&$top=1`,
      { headers: this.headers },
    );
    if (!resp.ok) return null;
    const data = (await resp.json()) as { value: Array<{ accountid: string }> };
    return data.value[0]?.accountid ?? null;
  }

  /** Create or update an Account. */
  async upsertAccount(payload: D365Account): Promise<UpsertResult> {
    const existingId =
      payload.accountid ?? (await this.searchAccount(payload.name));

    const { accountid: _id, ...fields } = payload;

    if (existingId) {
      const resp = await fetch(`${this.baseUrl}/accounts(${existingId})`, {
        method: "PATCH",
        headers: { ...this.headers, "If-Match": "*" },
        body: JSON.stringify(fields),
      });
      if (!resp.ok) {
        throw new Error(`Account PATCH failed: ${resp.status} ${await resp.text()}`);
      }
      return { id: existingId, created: false };
    }

    const resp = await fetch(`${this.baseUrl}/accounts`, {
      method: "POST",
      headers: this.headers,
      body: JSON.stringify(fields),
    });
    if (!resp.ok) {
      throw new Error(`Account POST failed: ${resp.status} ${await resp.text()}`);
    }
    return { id: extractGuid(resp.headers.get("OData-EntityId") ?? ""), created: true };
  }

  // ─── Tasks ────────────────────────────────────────────────────────────────

  /**
   * Create a Task (Activity) record.
   *
   * POST /tasks
   * Response: 204 No Content — ID in OData-EntityId header
   *
   * Link to related records via odata.bind fields:
   *   "regardingobjectid_opportunity_task@odata.bind": "/opportunities(guid)"
   */
  async createTask(payload: D365Task): Promise<string> {
    const { activityid: _id, ...fields } = payload;
    const resp = await fetch(`${this.baseUrl}/tasks`, {
      method: "POST",
      headers: this.headers,
      body: JSON.stringify(fields),
    });
    if (!resp.ok) {
      throw new Error(`Task POST failed: ${resp.status} ${await resp.text()}`);
    }
    return extractGuid(resp.headers.get("OData-EntityId") ?? "");
  }

  // ─── Static utilities ────────────────────────────────────────────────────────

  /**
   * Build a deep link URL to open a Dynamics 365 record in the browser.
   *
   * @param instanceUrl   e.g. https://contoso.crm.dynamics.com
   * @param entityName    Singular entity logical name
   * @param id            Record GUID
   */
  static recordUrl(
    instanceUrl: string,
    entityName: "opportunity" | "lead" | "contact" | "account" | "task",
    id: string,
  ): string {
    const origin = instanceUrl.replace(/\/$/, "");
    return `${origin}/main.aspx?etn=${entityName}&id=${id}&pagetype=entityrecord`;
  }

  /**
   * Build an OData binding reference string for lookup fields.
   *
   * @example
   * Dynamics365Client.bindRef("accounts", accountId)
   * // → "/accounts(abc-123-...)"
   */
  static bindRef(entitySetName: string, id: string): string {
    return `/${entitySetName}(${id})`;
  }
}

// ─── Internal helpers ────────────────────────────────────────────────────────

/**
 * Escape single quotes for OData $filter strings.
 * OData spec: represent a single quote within a string by doubling it.
 * Docs: https://docs.oasis-open.org/odata/odata/v4.0/odata-v4.0-part2-url-conventions.html
 */
function escapeSingleQuotes(value: string): string {
  return value.replace(/'/g, "''");
}

/**
 * Extract GUID from an OData-EntityId header value.
 *
 * Header format: https://org.crm.dynamics.com/api/data/v9.2/accounts(guid)
 * Docs: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/create-entity-web-api
 */
function extractGuid(entityIdHeader: string): string {
  const match = entityIdHeader.match(/\(([^)]+)\)$/);
  return match?.[1] ?? "";
}
```

## File: src/index.ts
size: 522
sha: 18378a913a73f9e45790be666ce71d3cc31e03ae
upstream: https://github.com/vieiradiego/openclaw-dynamics-365/blob/HEAD/src/index.ts

```text
/**
 * openclaw-dynamics-365
 * Microsoft Dynamics 365 CRM integration skill for OpenClaw
 *
 * @example
 * import { Dynamics365Client, exchangeCodeForTokens } from "openclaw-dynamics-365";
 */

export { Dynamics365Client } from "./client.js";
export {
  getAuthorizationUrl,
  exchangeCodeForTokens,
  refreshAccessToken,
  isTokenExpired,
} from "./oauth.js";
export type {
  Dynamics365Config,
  OAuthTokens,
  D365Opportunity,
  D365Lead,
  D365Contact,
  D365Account,
  D365Task,
  UpsertResult,
} from "./types.js";
```

## File: src/oauth.ts
size: 4483
sha: 742234d21140873b01a6b487c472aa8e8003866e
upstream: https://github.com/vieiradiego/openclaw-dynamics-365/blob/HEAD/src/oauth.ts

```text
/**
 * openclaw-dynamics-365 — Azure AD OAuth 2.0 helpers
 *
 * Microsoft Dynamics 365 uses Microsoft Entra ID (Azure AD) for authentication.
 * This module implements the Authorization Code Flow with PKCE-compatible
 * redirect for server-side OAuth integrations.
 *
 * Docs: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/authenticate-oauth
 */

import type { Dynamics365Config, OAuthTokens } from "./types.js";

const AUTHORITY_BASE = "https://login.microsoftonline.com";

/**
 * Build the OAuth 2.0 scope for a given Dynamics 365 instance.
 * The resource URI is derived from the instance URL (org-specific).
 */
function buildScope(instanceUrl: string): string {
  const origin = instanceUrl.replace(/\/$/, "");
  return `${origin}/.default offline_access`;
}

/**
 * Build the Microsoft Entra ID authorization URL.
 * Redirect the user's browser to this URL to start the OAuth flow.
 *
 * @param config   App Registration credentials
 * @param redirectUri  Must match a registered Redirect URI in Azure Portal
 * @param state    CSRF token — verify on callback
 */
export function getAuthorizationUrl(
  config: Dynamics365Config,
  redirectUri: string,
  state: string,
): string {
  const tenant = config.tenantId || "common";
  const scope = buildScope(config.instanceUrl);

  const params = new URLSearchParams({
    client_id: config.clientId,
    response_type: "code",
    redirect_uri: redirectUri,
    scope,
    state,
    prompt: "select_account",
  });

  return `${AUTHORITY_BASE}/${tenant}/oauth2/v2.0/authorize?${params}`;
}

/**
 * Exchange an authorization code for access + refresh tokens.
 * Call this in the OAuth callback handler after the user is redirected back.
 *
 * @throws Error with status details if the request fails
 */
export async function exchangeCodeForTokens(
  config: Dynamics365Config,
  code: string,
  redirectUri: string,
): Promise<OAuthTokens> {
  const tenant = config.tenantId || "common";
  const scope = buildScope(config.instanceUrl);

  const resp = await fetch(
    `${AUTHORITY_BASE}/${tenant}/oauth2/v2.0/token`,
    {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: new URLSearchParams({
        client_id: config.clientId,
        client_secret: config.clientSecret,
        grant_type: "authorization_code",
        code,
        redirect_uri: redirectUri,
        scope,
      }),
    },
  );

  if (!resp.ok) {
    const body = await resp.text();
    throw new Error(`Azure AD token exchange failed: ${resp.status} ${body}`);
  }

  const data = (await resp.json()) as {
    access_token: string;
    refresh_token: string;
    expires_in: number;
  };

  return {
    accessToken: data.access_token,
    refreshToken: data.refresh_token,
    expiresAt: Date.now() + data.expires_in * 1000,
    instanceUrl: config.instanceUrl,
  };
}

/**
 * Refresh an expired access token using a stored refresh token.
 * Dynamics 365 access tokens expire after ~1 hour.
 * Refresh tokens are long-lived but can be invalidated by policy changes.
 *
 * @throws Error if the refresh fails (user must re-authorize)
 */
export async function refreshAccessToken(
  config: Dynamics365Config,
  refreshToken: string,
): Promise<OAuthTokens> {
  const tenant = config.tenantId || "common";
  const scope = buildScope(config.instanceUrl);

  const resp = await fetch(
    `${AUTHORITY_BASE}/${tenant}/oauth2/v2.0/token`,
    {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: new URLSearchParams({
        client_id: config.clientId,
        client_secret: config.clientSecret,
        grant_type: "refresh_token",
        refresh_token: refreshToken,
        scope,
      }),
    },
  );

  if (!resp.ok) {
    const body = await resp.text();
    throw new Error(`Azure AD token refresh failed: ${resp.status} ${body}`);
  }

  const data = (await resp.json()) as {
    access_token: string;
    refresh_token?: string;
    expires_in: number;
  };

  return {
    accessToken: data.access_token,
    // Microsoft may or may not rotate the refresh token
    refreshToken: data.refresh_token ?? refreshToken,
    expiresAt: Date.now() + data.expires_in * 1000,
    instanceUrl: config.instanceUrl,
  };
}

/**
 * Check whether a stored access token is expired (with a 60s buffer).
 */
export function isTokenExpired(tokens: OAuthTokens): boolean {
  return Date.now() >= tokens.expiresAt - 60_000;
}
```

## File: src/types.ts
size: 4003
sha: 7d9207d521d94b7a1f98acf286fa32874c224202
upstream: https://github.com/vieiradiego/openclaw-dynamics-365/blob/HEAD/src/types.ts

```text
/**
 * openclaw-dynamics-365
 * TypeScript types for Microsoft Dynamics 365 Dataverse Web API
 */

/** Credentials for an Azure AD App Registration (multi-tenant recommended) */
export interface Dynamics365Config {
  /** Azure AD Application (client) ID */
  clientId: string;
  /** Azure AD Client Secret */
  clientSecret: string;
  /**
   * Azure AD Tenant ID.
   * Use "common" for multi-tenant apps (recommended),
   * or a specific tenant GUID for single-tenant.
   */
  tenantId: string;
  /**
   * Dynamics 365 instance URL.
   * Format: https://{org}.crm.dynamics.com
   * e.g.  https://contoso.crm.dynamics.com
   */
  instanceUrl: string;
}

/** OAuth 2.0 tokens returned after authorization */
export interface OAuthTokens {
  accessToken: string;
  refreshToken: string;
  /** Unix timestamp (ms) when the access token expires */
  expiresAt: number;
  /** Dynamics 365 instance URL associated with these tokens */
  instanceUrl: string;
}

// ─── Dataverse Entity Types ──────────────────────────────────────────────────

/**
 * Dynamics 365 Opportunity
 * Entity set: /opportunities
 */
export interface D365Opportunity {
  /** Existing record ID — set to trigger PATCH instead of POST */
  opportunityid?: string;
  /** Opportunity name (required) */
  name: string;
  /** Estimated revenue in base currency */
  estimatedvalue?: number;
  /**
   * Sales stage / pipeline step name.
   * Common values: "Qualify", "Develop", "Propose", "Close"
   */
  stepname?: string;
  /** Expected close date (ISO 8601: YYYY-MM-DD) */
  actualclosedate?: string;
  /** Notes / description */
  description?: string;
  /**
   * Link to a parent Account via OData binding.
   * Format: /accounts({accountid})
   */
  "parentaccountid@odata.bind"?: string;
}

/**
 * Dynamics 365 Lead
 * Entity set: /leads
 */
export interface D365Lead {
  /** Existing record ID */
  leadid?: string;
  /** Full name (auto-populated from first + last name if not set) */
  fullname?: string;
  firstName?: string;
  lastName?: string;
  /** Primary email address */
  emailaddress1?: string;
  /** Job title */
  jobtitle?: string;
  /** Company name */
  companyname?: string;
  /** Primary phone number */
  telephone1?: string;
  /** Notes / description */
  description?: string;
}

/**
 * Dynamics 365 Contact
 * Entity set: /contacts
 */
export interface D365Contact {
  /** Existing record ID */
  contactid?: string;
  fullname?: string;
  firstName?: string;
  lastName?: string;
  emailaddress1?: string;
  jobtitle?: string;
  telephone1?: string;
  description?: string;
  /**
   * Link to parent Account via OData binding.
   * Format: /accounts({accountid})
   */
  "parentcustomerid_account@odata.bind"?: string;
}

/**
 * Dynamics 365 Account
 * Entity set: /accounts
 */
export interface D365Account {
  /** Existing record ID */
  accountid?: string;
  /** Account / company name (required) */
  name: string;
  emailaddress1?: string;
  telephone1?: string;
  websiteurl?: string;
  description?: string;
}

/**
 * Dynamics 365 Task (Activity)
 * Entity set: /tasks
 */
export interface D365Task {
  /** Existing record ID */
  activityid?: string;
  /** Task subject / title (required) */
  subject: string;
  description?: string;
  /** Due date-time (ISO 8601) */
  scheduledend?: string;
  /**
   * Priority:
   * 0 = Low | 1 = Normal (default) | 2 = High
   */
  prioritycode?: 0 | 1 | 2;
  /** Link to related Opportunity */
  "regardingobjectid_opportunity_task@odata.bind"?: string;
  /** Link to related Contact */
  "regardingobjectid_contact_task@odata.bind"?: string;
  /** Link to related Account */
  "regardingobjectid_account_task@odata.bind"?: string;
}

/** Result returned by upsert operations */
export interface UpsertResult {
  /** Record GUID in Dataverse */
  id: string;
  /** true = record was created; false = existing record was updated */
  created: boolean;
}
```

## File: tests/client.test.ts
size: 16776
sha: 95d8ca772170744ab607f97617c71bd5ee21ea59
upstream: https://github.com/vieiradiego/openclaw-dynamics-365/blob/HEAD/tests/client.test.ts

```text
/**
 * Dynamics365Client — unit tests with fetch mocks
 *
 * Mock behaviour matches official Dataverse Web API docs (v9.2):
 *
 *  POST   → 204 No Content | OData-EntityId header contains record URI
 *  PATCH  → 204 No Content | no body; If-Match: * sent by client
 *  GET    → 200 OK         | { value: T[] }  (empty: { value: [] })
 *
 * Docs:
 *  Create: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/create-entity-web-api
 *  Update: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/update-delete-entities-using-web-api
 *  Query:  https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/query/overview
 */

import { Dynamics365Client } from "../src/client.js";

// ─── Mock helpers ────────────────────────────────────────────────────────────

const ORG_URI = "https://contoso.crm.dynamics.com";
const API_BASE = `${ORG_URI}/api/data/v9.2`;
const TOKEN = "mock-bearer-token";

/**
 * Simulate a successful POST response (204 No Content + OData-EntityId header).
 * Matches: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/create-entity-web-api#basic-create
 */
function mockPost204(entitySet: string, guid: string): Response {
  return new Response(null, {
    status: 204,
    headers: {
      "OData-Version": "4.0",
      "OData-EntityId": `${API_BASE}/${entitySet}(${guid})`,
    },
  });
}

/**
 * Simulate a successful PATCH response (204 No Content, no body).
 * Matches: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/update-delete-entities-using-web-api#basic-update
 */
function mockPatch204(): Response {
  return new Response(null, {
    status: 204,
    headers: { "OData-Version": "4.0" },
  });
}

/**
 * Simulate a GET query response (200 OK, { value: T[] }).
 * Matches: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/query/overview#retrieve-data
 */
function mockGet200<T>(records: T[]): Response {
  return new Response(
    JSON.stringify({
      "@odata.context": `${API_BASE}/$metadata#entity/$entity`,
      value: records,
    }),
    {
      status: 200,
      headers: {
        "Content-Type": "application/json",
        "OData-Version": "4.0",
      },
    },
  );
}

/** Simulate an API error response */
function mockError(status: number, message: string): Response {
  return new Response(
    JSON.stringify({ error: { code: String(status), message } }),
    {
      status,
      headers: { "Content-Type": "application/json" },
    },
  );
}

// ─── Test setup ──────────────────────────────────────────────────────────────

let client: Dynamics365Client;

beforeEach(() => {
  client = new Dynamics365Client(ORG_URI, TOKEN);
  global.fetch = jest.fn();
});

afterEach(() => {
  jest.resetAllMocks();
});

// ─── Opportunity ─────────────────────────────────────────────────────────────

describe("upsertOpportunity", () => {
  const OPP_GUID = "aabbccdd-0000-0000-0000-000000000001";

  it("creates a new opportunity when none exists (POST → 204, ID from OData-EntityId)", async () => {
    (global.fetch as jest.Mock)
      .mockResolvedValueOnce(mockGet200([]))                     // search: no match
      .mockResolvedValueOnce(mockPost204("opportunities", OPP_GUID)); // POST

    const result = await client.upsertOpportunity({ name: "Deal TechNova Q2" });

    expect(result).toEqual({ id: OPP_GUID, created: true });

    const [searchCall, postCall] = (global.fetch as jest.Mock).mock.calls;
    expect(searchCall[0]).toContain("/opportunities?$select=opportunityid&$filter=");
    expect(searchCall[0]).toContain(encodeURIComponent("name eq 'Deal TechNova Q2'"));
    expect(postCall[1].method).toBe("POST");
    expect(JSON.parse(postCall[1].body as string).name).toBe("Deal TechNova Q2");
  });

  it("updates an existing opportunity when found (PATCH → 204, If-Match: *)", async () => {
    (global.fetch as jest.Mock)
      .mockResolvedValueOnce(mockGet200([{ opportunityid: OPP_GUID }])) // search: found
      .mockResolvedValueOnce(mockPatch204());                            // PATCH

    const result = await client.upsertOpportunity({
      name: "Deal TechNova Q2",
      estimatedvalue: 75000,
      stepname: "Propose",
    });

    expect(result).toEqual({ id: OPP_GUID, created: false });

    const [, patchCall] = (global.fetch as jest.Mock).mock.calls;
    expect(patchCall[0]).toContain(`/opportunities(${OPP_GUID})`);
    expect(patchCall[1].method).toBe("PATCH");
    expect(patchCall[1].headers["If-Match"]).toBe("*");
    const body = JSON.parse(patchCall[1].body as string);
    expect(body.estimatedvalue).toBe(75000);
    expect(body.stepname).toBe("Propose");
    expect(body.opportunityid).toBeUndefined(); // never sent in body
  });

  it("skips search when opportunityid is provided explicitly", async () => {
    (global.fetch as jest.Mock).mockResolvedValueOnce(mockPatch204());

    const result = await client.upsertOpportunity({
      opportunityid: OPP_GUID,
      name: "Deal TechNova Q2",
    });

    expect(result).toEqual({ id: OPP_GUID, created: false });
    expect(global.fetch).toHaveBeenCalledTimes(1); // only PATCH, no search
  });

  it("escapes single quotes in opportunity name for OData $filter", async () => {
    (global.fetch as jest.Mock)
      .mockResolvedValueOnce(mockGet200([]))
      .mockResolvedValueOnce(mockPost204("opportunities", OPP_GUID));

    await client.upsertOpportunity({ name: "O'Brien & Co" });

    const [searchCall] = (global.fetch as jest.Mock).mock.calls;
    expect(searchCall[0]).toContain(encodeURIComponent("name eq 'O''Brien & Co'"));
  });

  it("throws on POST error with status and body", async () => {
    (global.fetch as jest.Mock)
      .mockResolvedValueOnce(mockGet200([]))
      .mockResolvedValueOnce(mockError(401, "Unauthorized"));

    await expect(
      client.upsertOpportunity({ name: "Deal X" }),
    ).rejects.toThrow("Opportunity POST failed: 401");
  });

  it("throws on PATCH error", async () => {
    (global.fetch as jest.Mock)
      .mockResolvedValueOnce(mockGet200([{ opportunityid: OPP_GUID }]))
      .mockResolvedValueOnce(mockError(412, "Precondition Failed"));

    await expect(
      client.upsertOpportunity({ name: "Deal X" }),
    ).rejects.toThrow("Opportunity PATCH failed: 412");
  });
});

// ─── Lead ─────────────────────────────────────────────────────────────────────

describe("upsertLead", () => {
  const LEAD_GUID = "aabbccdd-0000-0000-0000-000000000002";

  it("creates a new lead when not found by email", async () => {
    (global.fetch as jest.Mock)
      .mockResolvedValueOnce(mockGet200([]))
      .mockResolvedValueOnce(mockPost204("leads", LEAD_GUID));

    const result = await client.upsertLead({
      fullname: "João Silva",
      emailaddress1: "joao@techno.com",
      companyname: "TechNova",
    });

    expect(result).toEqual({ id: LEAD_GUID, created: true });

    const [searchCall] = (global.fetch as jest.Mock).mock.calls;
    // Email is preferred over fullname as search key
    expect(searchCall[0]).toContain(
      encodeURIComponent("fullname eq 'joao@techno.com' or emailaddress1 eq 'joao@techno.com'"),
    );
  });

  it("searches by fullname when email is absent", async () => {
    (global.fetch as jest.Mock)
      .mockResolvedValueOnce(mockGet200([]))
      .mockResolvedValueOnce(mockPost204("leads", LEAD_GUID));

    await client.upsertLead({ fullname: "Maria Santos" });

    const [searchCall] = (global.fetch as jest.Mock).mock.calls;
    expect(searchCall[0]).toContain(encodeURIComponent("fullname eq 'Maria Santos'"));
  });

  it("updates existing lead found by name (PATCH → 204)", async () => {
    (global.fetch as jest.Mock)
      .mockResolvedValueOnce(mockGet200([{ leadid: LEAD_GUID }]))
      .mockResolvedValueOnce(mockPatch204());

    const result = await client.upsertLead({
      fullname: "Maria Santos",
      jobtitle: "CEO",
    });

    expect(result).toEqual({ id: LEAD_GUID, created: false });

    const [, patchCall] = (global.fetch as jest.Mock).mock.calls;
    expect(patchCall[1].headers["If-Match"]).toBe("*");
    expect(JSON.parse(patchCall[1].body as string).jobtitle).toBe("CEO");
  });

  it("skips search when neither name nor email provided", async () => {
    (global.fetch as jest.Mock).mockResolvedValueOnce(
      mockPost204("leads", LEAD_GUID),
    );

    await client.upsertLead({ telephone1: "+55 11 99999-0000" });

    expect(global.fetch).toHaveBeenCalledTimes(1); // no search call
  });
});

// ─── Contact ──────────────────────────────────────────────────────────────────

describe("upsertContact", () => {
  const CONTACT_GUID = "aabbccdd-0000-0000-0000-000000000003";

  it("creates a new contact (POST → 204)", async () => {
    (global.fetch as jest.Mock)
      .mockResolvedValueOnce(mockGet200([]))
      .mockResolvedValueOnce(mockPost204("contacts", CONTACT_GUID));

    const result = await client.upsertContact({
      fullname: "Ana Lima",
      emailaddress1: "ana@corp.com",
    });

    expect(result).toEqual({ id: CONTACT_GUID, created: true });
  });

  it("updates existing contact (PATCH → 204, If-Match: *)", async () => {
    (global.fetch as jest.Mock)
      .mockResolvedValueOnce(mockGet200([{ contactid: CONTACT_GUID }]))
      .mockResolvedValueOnce(mockPatch204());

    const result = await client.upsertContact({
      fullname: "Ana Lima",
      jobtitle: "CTO",
      "parentcustomerid_account@odata.bind": "/accounts(acc-001)",
    });

    expect(result).toEqual({ id: CONTACT_GUID, created: false });

    const [, patchCall] = (global.fetch as jest.Mock).mock.calls;
    expect(patchCall[0]).toContain(`/contacts(${CONTACT_GUID})`);
    const body = JSON.parse(patchCall[1].body as string);
    expect(body["parentcustomerid_account@odata.bind"]).toBe("/accounts(acc-001)");
  });

  it("returns null from searchContact on API error", async () => {
    (global.fetch as jest.Mock).mockResolvedValueOnce(mockError(403, "Forbidden"));

    const id = await client.searchContact("Ana Lima");
    expect(id).toBeNull();
  });
});

// ─── Account ──────────────────────────────────────────────────────────────────

describe("upsertAccount", () => {
  const ACCOUNT_GUID = "aabbccdd-0000-0000-0000-000000000004";

  it("creates a new account (POST → 204)", async () => {
    (global.fetch as jest.Mock)
      .mockResolvedValueOnce(mockGet200([]))
      .mockResolvedValueOnce(mockPost204("accounts", ACCOUNT_GUID));

    const result = await client.upsertAccount({ name: "TechNova Ltda" });

    expect(result).toEqual({ id: ACCOUNT_GUID, created: true });

    const [, postCall] = (global.fetch as jest.Mock).mock.calls;
    expect(postCall[0]).toContain("/accounts");
    expect(postCall[1].method).toBe("POST");
  });

  it("updates existing account (PATCH → 204)", async () => {
    (global.fetch as jest.Mock)
      .mockResolvedValueOnce(mockGet200([{ accountid: ACCOUNT_GUID }]))
      .mockResolvedValueOnce(mockPatch204());

    const result = await client.upsertAccount({
      name: "TechNova Ltda",
      websiteurl: "https://techno.com",
    });

    expect(result).toEqual({ id: ACCOUNT_GUID, created: false });

    const [, patchCall] = (global.fetch as jest.Mock).mock.calls;
    expect(patchCall[1].headers["If-Match"]).toBe("*");
  });

  it("uses provided accountid directly without search", async () => {
    (global.fetch as jest.Mock).mockResolvedValueOnce(mockPatch204());

    const result = await client.upsertAccount({
      accountid: ACCOUNT_GUID,
      name: "TechNova Ltda",
    });

    expect(result).toEqual({ id: ACCOUNT_GUID, created: false });
    expect(global.fetch).toHaveBeenCalledTimes(1);
  });
});

// ─── Task ─────────────────────────────────────────────────────────────────────

describe("createTask", () => {
  const TASK_GUID = "aabbccdd-0000-0000-0000-000000000005";

  it("creates a task and returns activityid from OData-EntityId header", async () => {
    (global.fetch as jest.Mock).mockResolvedValueOnce(
      mockPost204("tasks", TASK_GUID),
    );

    const id = await client.createTask({
      subject: "Follow-up call with TechNova",
      prioritycode: 2,
      scheduledend: "2026-05-01T10:00:00Z",
    });

    expect(id).toBe(TASK_GUID);

    const [call] = (global.fetch as jest.Mock).mock.calls;
    expect(call[0]).toContain("/tasks");
    expect(call[1].method).toBe("POST");
    const body = JSON.parse(call[1].body as string);
    expect(body.subject).toBe("Follow-up call with TechNova");
    expect(body.prioritycode).toBe(2);
    expect(body.activityid).toBeUndefined(); // never sent
  });

  it("creates a task linked to an opportunity via odata.bind", async () => {
    (global.fetch as jest.Mock).mockResolvedValueOnce(
      mockPost204("tasks", TASK_GUID),
    );

    await client.createTask({
      subject: "Send proposal",
      "regardingobjectid_opportunity_task@odata.bind":
        Dynamics365Client.bindRef("opportunities", "opp-guid-001"),
    });

    const body = JSON.parse(
      (global.fetch as jest.Mock).mock.calls[0][1].body as string,
    );
    expect(body["regardingobjectid_opportunity_task@odata.bind"]).toBe(
      "/opportunities(opp-guid-001)",
    );
  });

  it("throws on POST error", async () => {
    (global.fetch as jest.Mock).mockResolvedValueOnce(
      mockError(400, "Bad Request"),
    );

    await expect(
      client.createTask({ subject: "Test Task" }),
    ).rejects.toThrow("Task POST failed: 400");
  });
});

// ─── Static utilities ────────────────────────────────────────────────────────

describe("Dynamics365Client.recordUrl", () => {
  it("builds a correct deep link URL for an opportunity", () => {
    const url = Dynamics365Client.recordUrl(ORG_URI, "opportunity", "opp-001");
    expect(url).toBe(
      `${ORG_URI}/main.aspx?etn=opportunity&id=opp-001&pagetype=entityrecord`,
    );
  });

  it("strips trailing slash from instanceUrl", () => {
    const url = Dynamics365Client.recordUrl(`${ORG_URI}/`, "lead", "lead-001");
    expect(url).toBe(
      `${ORG_URI}/main.aspx?etn=lead&id=lead-001&pagetype=entityrecord`,
    );
  });
});

describe("Dynamics365Client.bindRef", () => {
  it("formats an OData binding reference correctly", () => {
    expect(Dynamics365Client.bindRef("accounts", "acc-guid-001")).toBe(
      "/accounts(acc-guid-001)",
    );
    expect(Dynamics365Client.bindRef("opportunities", "opp-001")).toBe(
      "/opportunities(opp-001)",
    );
  });
});

// ─── Request headers ─────────────────────────────────────────────────────────

describe("request headers", () => {
  it("sends required OData headers on every request", async () => {
    (global.fetch as jest.Mock).mockResolvedValue(mockGet200([]));

    await client.searchOpportunity("Test");

    const [, init] = (global.fetch as jest.Mock).mock.calls[0];
    expect(init.headers["Authorization"]).toBe(`Bearer ${TOKEN}`);
    expect(init.headers["OData-MaxVersion"]).toBe("4.0");
    expect(init.headers["OData-Version"]).toBe("4.0");
    expect(init.headers["Accept"]).toBe("application/json");
  });

  it("includes If-Match: * on all PATCH requests", async () => {
    const GUID = "aabbccdd-0000-0000-0000-000000000099";
    (global.fetch as jest.Mock)
      .mockResolvedValueOnce(mockGet200([{ opportunityid: GUID }]))
      .mockResolvedValueOnce(mockPatch204());

    await client.upsertOpportunity({ name: "Test" });

    const patchCall = (global.fetch as jest.Mock).mock.calls[1];
    expect(patchCall[1].headers["If-Match"]).toBe("*");
  });
});
```

## File: tests/oauth.test.ts
size: 11302
sha: 547d06f8a42d4893275647b85d2993042cd0248a
upstream: https://github.com/vieiradiego/openclaw-dynamics-365/blob/HEAD/tests/oauth.test.ts

```text
/**
 * OAuth helpers — unit tests with fetch mocks
 *
 * Covers Azure AD OAuth 2.0 Authorization Code Flow for Dataverse access.
 *
 * Token endpoint docs:
 *  https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-auth-code-flow
 *
 * Dataverse OAuth docs:
 *  https://learn.microsoft.com/en-us/power-apps/developer/data-platform/authenticate-oauth
 */

import {
  exchangeCodeForTokens,
  getAuthorizationUrl,
  isTokenExpired,
  refreshAccessToken,
} from "../src/oauth.js";
import type { Dynamics365Config, OAuthTokens } from "../src/types.js";

// ─── Fixtures ────────────────────────────────────────────────────────────────

const CONFIG: Dynamics365Config = {
  clientId: "10b1389b-e0e9-48da-a431-765a92216007",
  clientSecret: "mock-secret-value",
  tenantId: "common",
  instanceUrl: "https://contoso.crm.dynamics.com",
};

const REDIRECT_URI = "http://localhost:3000/auth/dynamics365/callback";

/** Simulate a successful token endpoint response */
function mockTokenResponse(overrides: Partial<{
  access_token: string;
  refresh_token: string;
  expires_in: number;
}> = {}): Response {
  return new Response(
    JSON.stringify({
      token_type: "Bearer",
      access_token: overrides.access_token ?? "mock-access-token-abc123",
      refresh_token: overrides.refresh_token ?? "mock-refresh-token-xyz789",
      expires_in: overrides.expires_in ?? 3600,
      scope: `${CONFIG.instanceUrl}/.default offline_access`,
    }),
    {
      status: 200,
      headers: { "Content-Type": "application/json" },
    },
  );
}

/** Simulate a token endpoint error (e.g. invalid_grant) */
function mockTokenError(status: number, error: string, description: string): Response {
  return new Response(
    JSON.stringify({ error, error_description: description }),
    {
      status,
      headers: { "Content-Type": "application/json" },
    },
  );
}

// ─── getAuthorizationUrl ─────────────────────────────────────────────────────

describe("getAuthorizationUrl", () => {
  it("builds a valid Microsoft Entra ID authorization URL", () => {
    const url = getAuthorizationUrl(CONFIG, REDIRECT_URI, "csrf-state-123");

    expect(url).toContain("https://login.microsoftonline.com/common/oauth2/v2.0/authorize");
    expect(url).toContain(`client_id=${CONFIG.clientId}`);
    expect(url).toContain("response_type=code");
    expect(url).toContain(encodeURIComponent(REDIRECT_URI));
    expect(url).toContain("state=csrf-state-123");
    expect(url).toContain("prompt=select_account");
  });

  it("includes the instance-specific scope (not a generic Dynamics scope)", () => {
    const url = getAuthorizationUrl(CONFIG, REDIRECT_URI, "state");

    // Scope must be derived from instanceUrl per Microsoft docs:
    // https://learn.microsoft.com/en-us/power-apps/developer/data-platform/authenticate-oauth
    // For confidential client: <environment-url>/.default
    const expectedScope = encodeURIComponent(
      `${CONFIG.instanceUrl}/.default offline_access`,
    );
    expect(url).toContain(expectedScope);
  });

  it("uses tenant-specific URL when tenantId is a GUID", () => {
    const config: Dynamics365Config = {
      ...CONFIG,
      tenantId: "ef7a8bd9-3b7a-4e32-b5d4-90ee93ca8450",
    };
    const url = getAuthorizationUrl(config, REDIRECT_URI, "state");

    expect(url).toContain(
      `https://login.microsoftonline.com/${config.tenantId}/oauth2/v2.0/authorize`,
    );
  });

  it("defaults to 'common' tenant when tenantId is empty", () => {
    const config: Dynamics365Config = { ...CONFIG, tenantId: "" };
    const url = getAuthorizationUrl(config, REDIRECT_URI, "state");

    expect(url).toContain("login.microsoftonline.com/common/");
  });
});

// ─── exchangeCodeForTokens ───────────────────────────────────────────────────

describe("exchangeCodeForTokens", () => {
  beforeEach(() => {
    global.fetch = jest.fn();
  });

  afterEach(() => {
    jest.resetAllMocks();
  });

  it("exchanges authorization code for access + refresh tokens", async () => {
    (global.fetch as jest.Mock).mockResolvedValueOnce(mockTokenResponse());

    const tokens = await exchangeCodeForTokens(CONFIG, "auth-code-xyz", REDIRECT_URI);

    expect(tokens.accessToken).toBe("mock-access-token-abc123");
    expect(tokens.refreshToken).toBe("mock-refresh-token-xyz789");
    expect(tokens.instanceUrl).toBe(CONFIG.instanceUrl);
    expect(tokens.expiresAt).toBeGreaterThan(Date.now());
  });

  it("sends a POST to the correct token endpoint", async () => {
    (global.fetch as jest.Mock).mockResolvedValueOnce(mockTokenResponse());

    await exchangeCodeForTokens(CONFIG, "auth-code-xyz", REDIRECT_URI);

    const [url, init] = (global.fetch as jest.Mock).mock.calls[0];
    expect(url).toBe(
      "https://login.microsoftonline.com/common/oauth2/v2.0/token",
    );
    expect(init.method).toBe("POST");
    expect(init.headers["Content-Type"]).toBe("application/x-www-form-urlencoded");

    const body = new URLSearchParams(init.body as string);
    expect(body.get("grant_type")).toBe("authorization_code");
    expect(body.get("client_id")).toBe(CONFIG.clientId);
    expect(body.get("client_secret")).toBe(CONFIG.clientSecret);
    expect(body.get("code")).toBe("auth-code-xyz");
    expect(body.get("redirect_uri")).toBe(REDIRECT_URI);
  });

  it("sends instance-specific scope in token request", async () => {
    (global.fetch as jest.Mock).mockResolvedValueOnce(mockTokenResponse());

    await exchangeCodeForTokens(CONFIG, "code", REDIRECT_URI);

    const [, init] = (global.fetch as jest.Mock).mock.calls[0];
    const body = new URLSearchParams(init.body as string);
    expect(body.get("scope")).toBe(
      `${CONFIG.instanceUrl}/.default offline_access`,
    );
  });

  it("sets expiresAt ~1 hour from now (expires_in = 3600)", async () => {
    const before = Date.now();
    (global.fetch as jest.Mock).mockResolvedValueOnce(
      mockTokenResponse({ expires_in: 3600 }),
    );

    const tokens = await exchangeCodeForTokens(CONFIG, "code", REDIRECT_URI);
    const after = Date.now();

    expect(tokens.expiresAt).toBeGreaterThanOrEqual(before + 3600 * 1000);
    expect(tokens.expiresAt).toBeLessThanOrEqual(after + 3600 * 1000);
  });

  it("throws on invalid_grant error (expired or already used code)", async () => {
    (global.fetch as jest.Mock).mockResolvedValueOnce(
      mockTokenError(400, "invalid_grant", "AADSTS70011: The provided authorization code expired"),
    );

    await expect(
      exchangeCodeForTokens(CONFIG, "expired-code", REDIRECT_URI),
    ).rejects.toThrow("Azure AD token exchange failed: 400");
  });

  it("throws on unauthorized_client error", async () => {
    (global.fetch as jest.Mock).mockResolvedValueOnce(
      mockTokenError(401, "unauthorized_client", "Client authentication failed"),
    );

    await expect(
      exchangeCodeForTokens(CONFIG, "code", REDIRECT_URI),
    ).rejects.toThrow("Azure AD token exchange failed: 401");
  });
});

// ─── refreshAccessToken ──────────────────────────────────────────────────────

describe("refreshAccessToken", () => {
  beforeEach(() => {
    global.fetch = jest.fn();
  });

  afterEach(() => {
    jest.resetAllMocks();
  });

  it("exchanges refresh token for new access token", async () => {
    (global.fetch as jest.Mock).mockResolvedValueOnce(
      mockTokenResponse({ access_token: "new-access-token", expires_in: 3600 }),
    );

    const tokens = await refreshAccessToken(CONFIG, "old-refresh-token");

    expect(tokens.accessToken).toBe("new-access-token");
    expect(tokens.instanceUrl).toBe(CONFIG.instanceUrl);
  });

  it("sends grant_type=refresh_token to token endpoint", async () => {
    (global.fetch as jest.Mock).mockResolvedValueOnce(mockTokenResponse());

    await refreshAccessToken(CONFIG, "refresh-token-xyz");

    const [url, init] = (global.fetch as jest.Mock).mock.calls[0];
    expect(url).toContain("/oauth2/v2.0/token");
    const body = new URLSearchParams(init.body as string);
    expect(body.get("grant_type")).toBe("refresh_token");
    expect(body.get("refresh_token")).toBe("refresh-token-xyz");
  });

  it("preserves old refresh token when Microsoft does not rotate it", async () => {
    // Microsoft may omit refresh_token from the response when it is not rotated
    (global.fetch as jest.Mock).mockResolvedValueOnce(
      new Response(
        JSON.stringify({
          access_token: "new-access-token",
          expires_in: 3600,
          // no refresh_token field
        }),
        { status: 200, headers: { "Content-Type": "application/json" } },
      ),
    );

    const tokens = await refreshAccessToken(CONFIG, "stable-refresh-token");

    expect(tokens.refreshToken).toBe("stable-refresh-token");
  });

  it("uses new refresh token when Microsoft rotates it", async () => {
    (global.fetch as jest.Mock).mockResolvedValueOnce(
      mockTokenResponse({ refresh_token: "rotated-refresh-token" }),
    );

    const tokens = await refreshAccessToken(CONFIG, "old-refresh-token");

    expect(tokens.refreshToken).toBe("rotated-refresh-token");
  });

  it("throws on invalid_grant (refresh token expired/revoked)", async () => {
    (global.fetch as jest.Mock).mockResolvedValueOnce(
      mockTokenError(400, "invalid_grant", "AADSTS700082: The refresh token has expired"),
    );

    await expect(
      refreshAccessToken(CONFIG, "expired-refresh-token"),
    ).rejects.toThrow("Azure AD token refresh failed: 400");
  });
});

// ─── isTokenExpired ──────────────────────────────────────────────────────────

describe("isTokenExpired", () => {
  const baseTokens: OAuthTokens = {
    accessToken: "token",
    refreshToken: "refresh",
    instanceUrl: CONFIG.instanceUrl,
    expiresAt: 0,
  };

  it("returns true when token is expired", () => {
    const tokens: OAuthTokens = {
      ...baseTokens,
      expiresAt: Date.now() - 1000, // 1s ago
    };
    expect(isTokenExpired(tokens)).toBe(true);
  });

  it("returns true when token expires within the 60s buffer", () => {
    const tokens: OAuthTokens = {
      ...baseTokens,
      expiresAt: Date.now() + 30_000, // expires in 30s — within 60s buffer
    };
    expect(isTokenExpired(tokens)).toBe(true);
  });

  it("returns false when token is valid with margin", () => {
    const tokens: OAuthTokens = {
      ...baseTokens,
      expiresAt: Date.now() + 600_000, // expires in 10min
    };
    expect(isTokenExpired(tokens)).toBe(false);
  });

  it("returns false when token expires exactly at the 60s boundary", () => {
    const tokens: OAuthTokens = {
      ...baseTokens,
      expiresAt: Date.now() + 61_000, // 1s beyond the buffer
    };
    expect(isTokenExpired(tokens)).toBe(false);
  });
});
```

## File: tsconfig.json
size: 459
sha: a61f26bb4f3c6dcbc4e826ff4c2899554b6e1e64
upstream: https://github.com/vieiradiego/openclaw-dynamics-365/blob/HEAD/tsconfig.json

```text
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "lib": ["ES2022"],
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "declaration": true,
    "declarationMap": true,
    "sourceMap": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist", "tests"]
}
```
