# GWT AAF SDK — `globalEvent`, `globalData`, `contextData`, `lifeCycle`, `interface`, `httpRequest`

This template aligns with **`aaf_sdk.js`** (`AmeyoClient.init()`, `globalData`, `globalEvent`, `contextData`, `lifeCycle`, `interface`, `httpRequest`).

Authoritative **server-side** event names for many builds: ECC `GlobalEventService.GlobalEventEnum` (`com.drishti.ameyo.application.app.impl.GlobalEventService`). The tables below merge **product docs**, **ECC**, and **aliases** seen in the field.

## `globalEvent` API

| Method | Returns | Notes |
|--------|---------|--------|
| `register(eventName, callback)` | `Promise` | Rejects with `{ code, message }` on failure (see error codes). |
| `unRegister(eventName, callback)` | `void` | Pass the **same** callback reference you registered. |

```ts
import { initAafClient, registerGlobalEvent, GwtGlobalEventNames } from "./aaf/gwtAafSdk";

const client = initAafClient();
await registerGlobalEvent(client, GwtGlobalEventNames.campaignSelectionChange, (data) => {
  console.log(data);
});
```

### Failure payload (register)

| Field | Type | Meaning |
|-------|------|---------|
| `code` | number | e.g. `100` timeout, `121` unknown event, `122` event not allowed at this app **location** |
| `message` | string | Short description |

Common codes from integration docs: **100** SDK timeout (~10s), **101** invalid input, **102** internal failure, **121** event does not exist, **122** event not accessible at current slot (workbench vs navBar, etc.).

---

## `lifeCycle` service

Used for **app iframe lifecycle** (not CTI global events).

| Method | Returns | Notes |
|--------|---------|--------|
| `register(eventName, callback)` | `Promise` | Same failure shape `{ code, message }` as other services. |
| `unRegister(eventName, callback)` | `void` | Same callback reference as at register. |

### `appModalClose`

| | |
|--|--|
| **When** | Host user clicks the **modal close** control for your app. |
| **Where** | Apps hosted in a **modal** slot only. |
| **Register** | `client.lifeCycle.register("appModalClose", callback)` |
| **Payload** | `{}` |
| **Response window** | Within about **5 seconds**, the app may call **`client.interface.trigger("modalCloseConfirmation", { title, message })`** so the agent sees a confirmation. If the app does not respond in time, the modal **closes anyway**. |

**Failure example:** `{ "code": 122, "message": "appInstance must be present in modal slot to register for this event" }` — registering `appModalClose` when the instance is **not** in a modal slot.

### `appUnload`

| | |
|--|--|
| **When** | App is unloading or the iframe is being removed. |
| **Where** | All locations. |
| **Register** | `client.lifeCycle.register("appUnload", callback)` |
| **Payload** | `{}` |

### TypeScript helpers

```ts
import {
  initAafClient,
  onAppModalClose,
  triggerModalCloseConfirmation
} from "./aaf/gwtAafSdk";

const client = initAafClient();
await onAppModalClose(client, () => {
  void triggerModalCloseConfirmation(client, {
    title: "Operation in progress",
    message: "Please wait until the operation completes."
  });
});
```

Constants: **`GwtLifeCycleEventNames.appModalClose`**, **`GwtLifeCycleEventNames.appUnload`**, plus **`registerLifeCycleEvent` / `unregisterLifeCycleEvent`** in `gwtLifeCycle.ts`.

---

## Campaign & visibility

### `campaignSelectionChange`

| | |
|--|--|
| **Description** | Array of all currently selected campaigns |
| **Typical locations** | All |
| **Register** | `client.globalEvent.register("campaignSelectionChange", callback)` |
| **Sample payload** | `[{ "campaignId": 3, "campaignName": "…", "campaignType": "…", "processId": 1 }, …]` |

### `pageVisibilityChange`

| | |
|--|--|
| **Description** | Tab visibility for the page hosting the iframe |
| **Register** | `client.globalEvent.register("pageVisibilityChange", callback)` |
| **Sample payload** | `{ "visible": false }` |

---

## Chat

### `customerChatMemberCreated`

Workbench / workbenchBackground / navBar — payload includes `chatId`, `customerCrtId`, `campaignId`, `queueId`, `customerInfo`, etc.

### `newChatMessageAdded`

Workbench / workbenchBackground — adds `messageType` (`CONTENT` / `FILE_TRANSFER`), `message`, `source`, etc.

### `chatConnected` / `chatHungup`

| Event | Use |
|-------|-----|
| `chatConnected` | Chat session established |
| `chatHungup` | Chat ended (**ECC enum** `CHAT_HUNGUP`) |

Some listings also mention **`chatEnded`**. It is **not** in `GlobalEventEnum` in the ECC tree we indexed; keep it in `GwtGlobalEventNames` as a **doc alias** for older samples — if registration fails with `121`, use `chatHungup` instead.

### `chatDialogFocus`

Fired when the agent focuses the chat compose area. Payload may include `dialogId`, `customerData`, `linkedCustomerInfo`, etc.

---

## Voice / PSTN

### `callRinging`

Ringing leg — sample payload may be `{}` until details are populated.

### `customerCallMemberCreated`

Call connected / member joined — `callId`, `associationType`, `customerCrtId`, `campaignId`, `customerInfo`, …

### `callConnected`

Same family of fields as `customerCallMemberCreated` for the connected call.

### `voiceCustomerLinked`

Multiple customers match the same phone; agent picks a customer on inbound.

### `callHungup` vs `callEnded`

| String | Source |
|--------|--------|
| **`callHungup`** | ECC `GlobalEventEnum.CALL_HUNGUP` — **use this** for voice teardown in current ECC. |
| **`callEnded`** | Legacy / toolbar samples (`parent.js`) — kept as **alias** in `GwtGlobalEventNames`; only register if your deployment still emits it. |

### Hold

| String | Note |
|--------|------|
| **`callHold`** | ECC `GlobalEventEnum.CALL_HOLD` |
| **`callStageHold`** | Appears in some **external** docs; **not** found in ECC Java grep for this tree — included as alias; prefer `callHold` unless verified on your build. |

### `callStageHold` sample (doc)

`callId`, `associationType`, `customerCrtId`, `campaignId`, `status`, `isOnHold`, `customerInfo`, …

### `customerCallMemberDeleted`

Disposed call / member removed — e.g. `customerCrtId`, `campaignId`.

---

## Agent / user state

### `userStateChange` vs `userStateBreak`

ECC enum: **`userStateChange`**. One doc incorrectly shows `register("userStateBreak", …)` under a “userStateChange” heading — **`userStateBreak`** is exported as an **alias** so you can try the string your doc uses; prefer **`userStateChange`** for ECC-aligned builds.

Sample: `isAvailable`, `autoCallStatus`, `description`, `stateChangeCause`, …

---

## Missed calls

| Event | Role |
|-------|------|
| `missedCallAdded` | New missed call row |
| `missedCallModified` | Retry outcome (`TRIED_FAILED` / `TRIED_SUCCESS`, etc.) |
| `missedCallRemoved` | Row removed |

---

## CRM

### `crmStateChange`

CRM / disposition context — may include `customerInfo`, `campaignId`, `queueId`, `crtObjectId`, `additionalData` (JSON string from flow metadata), etc.

---

## Video

| Event | Typical payload keys |
|-------|-------------------------|
| `videoCallRinging` | `videoCallState`, `roomID`, `campaignId`, `queueNAME`, `participantId`, … |
| `videoCallConnected` | Same shape with `CONNECTED` |
| `videoCallEnded` | Same shape with `ENDED` |
| `canDisposeVideoStateChange` | `roomID`, `canDispose` |

---

## Attachments

### `attachmentAddedInTicket`

Video client / ticket attachment — `attachmentId`, `attachmentName`, `tag`, …

---

## ECC-only events (not in short doc list)

These exist on **`GlobalEventEnum`** and are included in `GWT_GLOBAL_EVENTS_ECC` / `GWT_ALL_GLOBAL_EVENT_NAMES`:

- `aqRequestAdded`, `aqRequestRemoved`
- `userCallMemberDeleted`, `userCallMemberCreated`
- `attachmentMetadataUpdated`, `customerStateChange`, `callHungupStatus`

---

## `globalData` (agent session + call ticket)

| Helper in `gwtAafSdk.ts` | Request |
|--------------------------|---------|
| `getAgentSession(client)` | `{ dataObject: "getAgentSession" }` |
| `getOngoingCallTicket(client)` | `{ dataObject: "ongingCallTicket" }` (ECC spelling) |

---

## `contextData` service — `action` & `trigger`

**`action`** mutates context objects (e.g. **`customer`** / **`changeCustomer`**). **`trigger`** starts host-side flows such as **manual dial** and **add customer**. Distinct from **`globalData`**, which reads global/session objects like `getAgentSession`.

```ts
client.contextData.action(dataObject, actionName, actionData).then(…).catch(…);
```

### `customer` → `changeCustomer`

Updates which **customer** is bound to the current context (e.g. after CRM link or selection).

| Parameter | Layer | Required | Type | Description |
|-----------|--------|----------|------|-------------|
| `dataObject` | 1st arg | yes | string | `"customer"` |
| `actionName` | 2nd arg | yes | string | `"changeCustomer"` |
| `actionData.customerId` | 3rd arg | yes | number (Double server-side) | Target customer id |

**Example**

```ts
import { initAafClient, changeCustomerInContext } from "./aaf/gwtAafSdk";

const client = initAafClient();
const res = await changeCustomerInContext(client, 231);
// res ≈ { customerId: 231 }
```

**Low-level call** (same behaviour):

```ts
await client.contextData.action("customer", "changeCustomer", { customerId: 231 });
```

**Sample success payload:** `{ "customerId": 231 }`

Helpers: **`changeCustomerInContext(client, customerId)`**, generic **`contextDataAction(client, dataObject, actionType, actionData)`** for other object/action pairs documented on your Ameyo version.

### `contextData.trigger` — dial / add customer

```ts
client.contextData.trigger(operation, operationData).then(…).catch(…);
```

| Operation | Purpose |
|-----------|---------|
| **`dialPhone`** | Dial any **phone** in a campaign. |
| **`dialCustomer`** | Dial a number belonging to a **customer** (`customerId` + `phone`). |
| **`dialCustomerOnAltPhone`** | Dial customer on an **alternate** line (same payload shape as `dialCustomer` in examples). |
| **`addCustomer`** | Add customer through the app (payload is flow-specific — use **`addCustomerThroughContext`** or **`contextDataTrigger`**). |

**`dialPhone` — `operationData`**

| Field | Required | Type | Notes |
|-------|----------|------|--------|
| `phone` | yes | string | Number to dial |
| `campaignId` | yes | string \| number | Campaign the agent is assigned to (integer-parseable) |
| `userCrtObjectId` | no | string | Agent CRT (shown in samples) |
| `additionalParams` | no | `Record<string, string>` | Optional Node flow data |

**`dialCustomer` / `dialCustomerOnAltPhone` — `operationData`**

| Field | Required | Type | Notes |
|-------|----------|------|--------|
| `phone` | yes | string | Customer’s phone (e.g. phone1) |
| `campaignId` | yes | string \| number | Assigned campaign |
| `customerId` | yes | string \| number | Customer id (Long-parseable server-side) |
| `userCrtObjectId` | no | string | |
| `additionalParams` | no | `Record<string, string>` | |

#### Where do `campaignId` and `userCrtObjectId` come from?

They are **not** invented by the SDK — your app should take them from **host context** you already subscribe to or fetch:

| Value | Typical sources |
|-------|-------------------|
| **`campaignId`** | **`globalEvent`** **`campaignSelectionChange`** — payload is an array of selected campaigns, each with **`campaignId`** (and name/type/processId). Also often present on **interaction/call/chat payloads** (e.g. `callConnected`, `chatConnected`, `crmStateChange`, …). You can also read assigned campaigns via `client.globalData.get("selectedCampaigns")` and pick the one that matches the dial intent (e.g. the voice campaign the agent is using). |
| **`userCrtObjectId`** | **Optional** for dial APIs in the docs. When needed, it is the **agent user CRT** string for “who is placing the call”. It may appear on **`crmStateChange`** (and similar CRM/session payloads) depending on your Ameyo version and flow. If your deployment does not expose it to the iframe, try **`omit`** first and only add it once you confirm the host requires it. |

Practical pattern: on **`campaignSelectionChange`**, cache `campaignId` for the row the agent selected; merge with **`customerId` / `phone`** from your CRM screen or from **`callConnected`** / **`customerCallMemberCreated`** when dialing from an active interaction.

**Success (dial ops):** response is commonly a **request id string**, e.g. `"manual-dial9436680b-5f92-70f1-ab18-b7da0016789a"`.

**TypeScript:** **`dialPhone`**, **`dialCustomer`**, **`dialCustomerOnAltPhone`** (return **`Promise<string>`**), **`addCustomerThroughContext`**, **`contextDataTrigger`**, constants **`GwtContextDataTriggerOperation`**, types **`DialPhoneOperationData`**, **`DialCustomerOperationData`**.

---

## TypeScript in this template

- **`GwtGlobalEventNames`**, **`registerGlobalEvent` / `unregisterGlobalEvent`**, **`GWT_ALL_GLOBAL_EVENT_NAMES`**
- **`GwtLifeCycleEventNames`**, **`registerLifeCycleEvent`**, **`onAppModalClose` / `onAppUnload`**
- **`GwtInterfaceTriggerOperation`**, **`GwtInterfaceOpenContext`**, **`triggerToastNotification`**, **`triggerDesktopNotification`**, **`triggerModalCloseConfirmation`**, **`openNewTicketForm`**, **`openNewCustomerForm`**, **`openCustomerDetail`**, **`interfaceTrigger`**, **`interfaceOpen`**
- **`invokeAmeyoHttp`**, **`invokeThirdPartyHttp`**, **`invokeAmeyoMultiPartHttp`**, types **`AafHttpRequestObject`**, **`AafHttpResponse`**, **`AafHttpMethod`**
- **`changeCustomerInContext`**, **`contextDataAction`**, **`contextDataTrigger`**, **`dialPhone`**, **`dialCustomer`**, **`dialCustomerOnAltPhone`**, **`addCustomerThroughContext`**, **`GwtContextDataObject`**, **`GwtCustomerContextAction`**, **`GwtContextDataTriggerOperation`**

Pick only the events your slot needs; registering unavailable events at the current **location** yields **122** and should be handled in your `catch`.

---

## `interface` service (`trigger` + `open`)

Drives **host UI** actions. In `aaf_sdk.js` this is `client.interface`. Documented as available at **all** app locations.

| Method | Role |
|--------|------|
| **`trigger(operation, operationData)`** | Fire a host action (toast, desktop notification, modal confirmation, …). Returns a **Promise**. |
| **`open(contextName, contextData)`** | Open an agent UI form/page or screen (e.g. **newTicketForm**, **newCustomerForm**, **openCustomerDetail**). The second argument may be an object **or** a primitive (see **openCustomerDetail**). Returns a **Promise**. |

Some older SDK bundles (e.g. certain `ameyo.ui` builds) expose **`trigger` only** — **`open`** may be absent. In that case helpers that use **`open`** reject with a clear error; use an **`application.ui`** / `sdk/1.0.0` style `aaf_sdk.js` when you need `open`.

### Failure payload (`trigger` / `open`)

| Code | Typical meaning |
|------|-----------------|
| **100** | SDK request timeout (~10s) |
| **101** | Invalid input (e.g. **openCustomerDetail**: empty customer id → “Customer id cannot be null”; non-numeric id → “Invalid customer id”) |
| **102** | Internal application failure |
| **121** | Invalid operation / action (e.g. unknown `operation` or `contextName`) |
| **122** | e.g. desktop notification not supported by browser |

---

### `trigger("toastNotification", data)`

| Field | Required | Type | Notes |
|-------|----------|------|--------|
| `type` | yes | `success` \| `alert` \| `error` | Toast style |
| `content` | yes | string | Body text |

Helper: **`triggerToastNotification(client, { type, content })`**.

---

### `trigger("desktopNotification", data)`

| Field | Required | Type | Notes |
|-------|----------|------|--------|
| `title` | yes | string | Notification title |
| `body` | no | string | |
| `tag` | no | string | Same tag replaces an existing visible notification |
| `imageUrl` | no | string | Image in notification |
| `iconUrl` | no | string | If set, **`notificationIcon`** is ignored |
| `clickAction` | no | string | `focusWindow` (default) \| `noAction` |
| `autoClose` | no | boolean | Default **true** |
| `notificationIcon` | no | string | `chat`, `call`, `wechat`, `messenger`, `twitter`, `line`, `viber`, `webchat`, `android`, `default` |
| `showIfPageVisible` | no | boolean | Default **true**; if **false**, only show when page is hidden |

Helper: **`triggerDesktopNotification(client, data)`**.

---

### `trigger("modalCloseConfirmation", data)`

Used after **`appModalClose`** (see **lifeCycle** section): show a confirmation within the host timeout (~5s).

| Field | Required | Type |
|-------|----------|------|
| `title` | no | string |
| `message` | no | string |

Helper: **`triggerModalCloseConfirmation(client, { title?, message? })`**.

> Product bullet lists sometimes group **newTicketForm** with triggers; the supported API is **`open("newTicketForm", …)`**, not `trigger`.

---

### `open("newTicketForm", contextData)`

Opens the **create ticket** flow with optional pre-fill.

Top-level **`contextData`** (all optional unless nested rules apply):

| Field | Type | Purpose |
|-------|------|---------|
| `customerId` | number | Pre-attach customer when found |
| `customerInfo` | object | Pre-fill customer columns if id missing / unknown |
| `ticketInfo` | object | `campaignId`, `queueId`, `priority`, `externalState`, `customFields` (id → value) |
| `messageInfo` | object | When present, **`messageInfo.messageType`** is **mandatory** (`MANUAL_MESSAGE`, `EMAIL`, `VOICE`, … — string or array of strings per server). Optional: `subject`, `message`, `target`, `cc`, `bcc` (strings or string arrays for email-style fields). |

Helper: **`openNewTicketForm(client, contextData)`** (uses `GwtInterfaceOpenContext.newTicketForm`).

---

### `open("newCustomerForm", contextData)`

Opens a **prefilled new-customer** form in the agent UI.

| Field | Required | Type | Description |
|-------|----------|------|-------------|
| `campaignId` | **yes** | string | Campaign the agent is logged into; drives column mapping for the form. |
| `customerInfo` | **yes** | object (map) | Column name → value for all fields to pre-fill (labels/keys per campaign). |

Common optional entries inside **`customerInfo`** (extend with any column keys your campaign defines):

| Key | Required | Type |
|-----|----------|------|
| `phone1` | no | string | Primary phone |
| `name` | no | string | Customer name |
| `email` | no | string | Email |
| … | no | string | e.g. `twitter`, other profile columns |

Example:

```ts
await openNewCustomerForm(client, {
  campaignId: "4",
  customerInfo: {
    name: "ajit",
    phone1: "1234567890",
    email: "ajitn@gmail.com",
    twitter: "myTwitterId"
  }
});
```

Helper: **`openNewCustomerForm(client, contextData)`** (`GwtInterfaceOpenContext.newCustomerForm`). Same **`interface.open`** SDK requirement as **newTicketForm**.

---

### `open("openCustomerDetail", customerId)`

Opens the **customer detail** page for an existing customer.

| Parameter | Required | Type | Description |
|-----------|----------|------|-------------|
| (2nd arg to `open`) | **yes** | **string** (parsed to long server-side) | Real **customer id** — pass `"1203"` or a numeric id (helpers stringify). |

```ts
await openCustomerDetail(client, "1203");
// or
await openCustomerDetail(client, 1203);
```

**Success:** host may resolve with `"Success"` when the event is delivered to the presenter (exact shape can vary by build).

**Errors (examples):**

| Condition | Code | Message (typical) |
|-------------|------|-------------------|
| `null` / empty id | **101** | Customer id cannot be null |
| Invalid / non-digit id | **101** | Invalid customer id |

Helper: **`openCustomerDetail(client, customerId)`** — rejects locally if `customerId` is an empty string after trim (avoids a round trip for obvious bad input).

---

### Escape hatches

- **`interfaceTrigger(client, operation, operationData)`** — any `trigger` operation not typed above.
- **`interfaceOpen(client, contextName, contextData)`** — any `open` target once your SDK exposes `open`.

---

## `httpRequest` service

Invokes HTTP through the **host** so calls run with Ameyo session / routing (not from the iframe origin alone). Documented as available at **all** app locations.

| Method | Use |
|--------|-----|
| **`invokeAmeyo(requestObject)`** | Ameyo REST/command APIs — `url` is **endpoint path only** (e.g. `ameyorestapi/systemintegration/getAllAppInfo`). |
| **`invoke(requestObject)`** | **Third-party** APIs — `url` must be the **full** `https://…` URL. |
| **`invokeAmeyoMultiPart(endpoint, formData, method)`** | Ameyo **multipart** (uploads, bulk ops). Optional on some older SDKs; use **`application.ui`** style `aaf_sdk.js` when missing. |

### Request object (`invokeAmeyo` / `invoke`)

| Field | Required | Type | Notes |
|-------|----------|------|--------|
| `url` | **yes** | string | Ameyo path **or** full external URL (see method above). |
| `method` | **yes** | string | Exactly one of: `HEAD`, `GET`, `POST`, `PUT`, `DELETE`, `OPTIONS`. |
| `headers` | no | `Record<string, string>` | If `content-type` omitted, host may default to `application/json`. |
| `body` | no | string | Often `JSON.stringify(payload)` for JSON POST/PUT. |

### Success response shape

| Field | Type |
|-------|------|
| `statusCode` | number |
| `statusText` | string |
| `response` | string (body; parse JSON if applicable) |
| `headers` | object of string properties |

### Failure (`catch`)

| Field | Type |
|-------|------|
| `code` | number |
| `message` | string |

| Code | Meaning |
|------|---------|
| **100** | SDK / bridge timeout waiting for host |
| **101** | Invalid input (e.g. missing `url` / `method` — *“url not provided. url and method is mandatory in http request”*) |
| **102** | Host internal failure |
| **121** | HTTP request timeout (per docs) |

### TypeScript helpers (`gwtHttpRequest.ts`)

```ts
import { initAafClient, invokeAmeyoHttp, invokeThirdPartyHttp } from "./aaf/gwtAafSdk";

const client = initAafClient();

const ameyoRes = await invokeAmeyoHttp(client, {
  url: "ameyorestapi/systemintegration/getAllAppInfo",
  headers: { "content-type": "application/json" },
  method: "GET"
});

const extRes = await invokeThirdPartyHttp(client, {
  url: "https://example.com/api/v2/resource/1",
  headers: { "content-type": "application/json", Authorization: "Bearer …" },
  method: "GET"
});
```

> Some older docs mistakenly call **`invokeAmeyo`** for full external URLs — use **`invoke` / `invokeThirdPartyHttp`** for third-party hosts.

### `invokeAmeyoMultiPart(endpoint, formData, method)`

| Argument | Required | Description |
|----------|----------|-------------|
| `endpoint` | yes | Ameyo path + optional query, e.g. `ameyorestapi/systemintegration/uploadAppData?title=kk` |
| `formData` | yes | Object: file field(s) per API (`formData.file = …`), plus stringified extra fields as required. Nested JSON params should be **stringified** before attaching. |
| `method` | yes | Same HTTP verb set as above. |

```ts
import { initAafClient, invokeAmeyoMultiPartHttp } from "./aaf/gwtAafSdk";

const client = initAafClient();
const formData: Record<string, unknown> = {};
// formData.file = fileInput.files?.[0]; // per API contract
await invokeAmeyoMultiPartHttp(
  client,
  "ameyorestapi/systemintegration/uploadAppData?title=kk",
  formData,
  "POST"
);
```

Multipart responses use the same **`AafHttpResponse`** shape as JSON/text HTTP helpers.
