> For the complete documentation index, see [llms.txt](https://docs.thewalletcrew.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.thewalletcrew.io/developers-guides/scripting/extensions/cegid-y2.md).

# Cegid Y2 scripts

Reference of the Cegid Retail Y2 mapper, advisor repository and connection interceptor scripts: registration, handlers, header copying and examples.

Three scripts adjust the Cegid Retail Y2 connector. The mapper maps customer data between Cegid and the wallet account, beyond the default mapping. The advisor repository narrows and reshapes the list of salespersons Cegid returns. The connection interceptor sees every call the connector makes to Cegid. This page is the reference for `extensions.cegid.y2.mapper`, `extensions.cegid.y2.advisorRepository` and `extensions.cegid.y2.connectionInterceptor`. The connector, the Cegid customer object and the recipes for the free fields are on the [Cegid connector pages](https://docs.thewalletcrew.io/connectors/pos/cegid/developer-reference/scripting-reference.md); the rules shared by every connector script are in [Connector scripts](https://docs.thewalletcrew.io/developers-guides/scripting/extensions.md).

<details>

<summary><strong>Real-world examples</strong></summary>

* A retailer writes the wallet installation state of each customer into a free table of the Cegid customer record.
* A brand maps the language of the account to the language code of its own Cegid database, and back.
* A brand hides technical salesperson accounts from the advisor list.
* A brand fronts Cegid with a gateway and rewrites the request URL.

</details>

## Registration

| Key                                         | Slot file                           | Methods (required in **bold**)              |
| ------------------------------------------- | ----------------------------------- | ------------------------------------------- |
| `extensions.cegid.y2.mapper`                | `cegid.y2.mapper.js`                | **`MapFromY2`**, **`MapToY2`**              |
| `extensions.cegid.y2.advisorRepository`     | `cegid.y2.advisorRepository.js`     | **`Filter`**, `Project`                     |
| `extensions.cegid.y2.connectionInterceptor` | `cegid.y2.connectionInterceptor.js` | **`OnBeforeRequest`**, **`OnAfterRequest`** |

The files sit in `server/scripts/`. The mapper and the advisor repository are edited in the **Advanced** tab of the Cegid Y2 page (**Customer mapper** and **Advisors** scripts). The interceptor has a slot file and an API but no tab, so it is edited in the advanced configuration. The slots are read and written with `GET` and `PUT /api/{tenantId}/admin/extensions/cegid/y2/scripts`.

When no script is registered for a key, the default behavior applies and nothing fails.

## When it runs

| Script                              | Runs                                                                                                                                              |
| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `MapFromY2`                         | After a Cegid customer is read and the standard mapping is applied                                                                                |
| `MapToY2`                           | After the consent mapping, before the customer is written. A create or an update runs both methods, because the record is read back after writing |
| `Filter`, `Project`                 | For each salesperson, on every advisor list request, after the connector has kept only the active salespersons of the requested store             |
| `OnBeforeRequest`, `OnAfterRequest` | On every call to Cegid, so anything slow in them slows the whole connector                                                                        |

A create or an update runs both mappers, in this order:

```mermaid
flowchart LR
  A[Wallet account] --> B[Default mapping]
  B --> C[MapToY2]
  C --> D[Write to Cegid]
  D --> E[Read back]
  E --> F[Default mapping]
  F --> G[MapFromY2]
  G --> H[Wallet account]
```

## Handlers

| Method            | Parameters                  | Returns                                     | Required | Sync or async                    |
| ----------------- | --------------------------- | ------------------------------------------- | -------- | -------------------------------- |
| `MapFromY2`       | `data`, `account`           | nothing                                     | Required | Synchronous                      |
| `MapToY2`         | `account`, `data`           | nothing                                     | Required | Synchronous                      |
| `Filter`          | `advisor`                   | `true` to keep the salesperson              | Required | Synchronous                      |
| `Project`         | `advisor`                   | an advisor, or `null` for the default       | Optional | Synchronous                      |
| `OnBeforeRequest` | `url`, `headers`, `content` | a promise of `{ Url, Headers, Content }`    | Required | Asynchronous: declare it `async` |
| `OnAfterRequest`  | `soapAction`, `content`     | a promise of the response body, as a string | Required | Asynchronous: declare it `async` |

* **Mapper.** `data` is the Cegid customer (`CustomerData`), with PascalCase members such as `data.EmailData.Email`; `account` is the flat wallet account. The methods change their arguments in place and return nothing. Both are required: register an empty function for the direction the script does not use. An `async` mapper is not awaited, so changes made after an `await` are lost.
* **Null entries.** Null entries the script adds to `UserDefinedBooleans`, `UserDefinedDates`, `UserDefinedTexts`, `UserDefinedValues` or `UserFields` are removed before the customer is sent. Other arrays are sent as they are.
* **Advisor repository.** `advisor` is the Cegid salesperson, with members such as `Id`, `FirstName`, `LastName` and `StoreId`. `Filter` returns a boolean. `Project` is optional and returns `{ AdvisorId, DisplayName }`; returning `null` keeps the default projection, the salesperson's `Id` and `FirstName LastName`.
* **Interceptor.** `OnBeforeRequest` must return `{ Url, Headers, Content }`. The connector **replaces the URL and all headers** with what it returns, so the script copies the headers it received, changes what it needs and keeps `SOAPAction`. `OnAfterRequest` returns the body of the response as a string.

The raw Cegid response is available while writing a mapping under `debug.y2.customer`, with equivalents for loyalty, sales documents and cash operations. These keys are a development aid and cannot be used in a pass template.

## Errors and edge cases

* **A required method is missing**: the call fails with `method <Name> missing` when the connector reaches it. A mapper that registers only one direction fails on the other.
* **A nested block is absent**: blocks the default mapping does not fill, such as `UserDefinedData`, are absent: create them before writing into them, or the whole save fails. `MapToY2` receives a new record built from the account, not the one stored in Cegid.
* **The interceptor drops a header**: the header is removed from the call. Without `SOAPAction`, the request is sent without it and the call then fails with an error, because the response step reads that header.
* **A script throws**: the error reaches the connector operation that called it.

## Example

The mapper writes the installation state of the wallet passes into a free table of the customer record, with an explicit `000` when no pass is installed, and maps the language through one table used in both directions.

```js
// Free table 3 holds the wallet installation state: Cegid labels start at 1, identifiers at 0.
const INSTALL_SLOT = 'UserDefinedTable2Value';

const LANGUAGES = { fr: 'FRA', en: 'ANG', es: 'ESP' };
const DEFAULT_LANGUAGE = 'ANG';
const LANGUAGES_REVERSE = {};
for (const locale of Object.keys(LANGUAGES)) {
  LANGUAGES_REVERSE[LANGUAGES[locale]] = locale;
}

function installCode(account) {
  // "Uninstalled" is a truthy string: compare with the literal state.
  const apple = account['neo.pass.Apple.state'] === 'Installed';
  const google = account['neo.pass.Google.state'] === 'Installed';
  if (apple && google) {
    return '003';
  }
  return apple ? '001' : google ? '002' : '000';
}

function mapToY2(account, data) {
  data.UserDefinedData = data.UserDefinedData || {};
  data.UserDefinedData[INSTALL_SLOT] = installCode(account);

  const locale = String(account['neo.lng'] ?? '').toLowerCase().split('-')[0];
  data.LanguageId = LANGUAGES[locale] || DEFAULT_LANGUAGE;
}

function mapFromY2(data, account) {
  const locale = LANGUAGES_REVERSE[data.LanguageId];
  if (locale) {
    account['language'] = locale;
  }
}

export default function (context) {
  context.register('extensions.cegid.y2.mapper', {
    MapToY2: mapToY2,
    MapFromY2: mapFromY2
  });
}
```

The entity is flat: the language is the key `neo.lng`, read with brackets, not `account.neo?.lng`. The installation keys `neo.pass.Apple.state` and `neo.pass.Google.state` exist only when the connector writes back on an installation change, which is the **Update customer on pass added / removed** setting (**Pass events**, on by default) of the [Cegid advanced configuration](https://docs.thewalletcrew.io/connectors/pos/cegid/setup-and-configuration/advanced-configuration.md). The Cegid language codes are defined per Cegid database: the ones above are placeholders. The prefix `neostore` is the platform's former name and is kept in technical identifiers.

The connection interceptor below injects a header and keeps every header it received, including `SOAPAction`:

```js
async function onBeforeRequest(url, headers, content) {
  const copy = { ...headers, 'X-Gateway-Source': 'wallet' };
  return { Url: url, Headers: copy, Content: content };
}

async function onAfterRequest(soapAction, content) {
  return content;
}

export default function (context) {
  context.register('extensions.cegid.y2.connectionInterceptor', {
    OnBeforeRequest: onBeforeRequest,
    OnAfterRequest: onAfterRequest
  });
}
```

The connector already keeps only the salespersons of the requested store. The advisor repository below also hides technical accounts whose identifier starts with `WEB`:

```js
function filter(advisor) {
  return !String(advisor?.Id ?? '').startsWith('WEB');
}

export default function (context) {
  context.register('extensions.cegid.y2.advisorRepository', {
    Filter: filter,
    Project: (advisor) => null
  });
}
```

## Common pitfalls

* Cegid identifiers start at 0 while the labels a Cegid user sees start at 1: `Id: 0` is the first free field.
* Consent values are `0` to `3`, not booleans.
* An interceptor that returns new headers without copying the received ones removes `SOAPAction`.
* A mapper writes into a block that is absent on a new customer.

## FAQ

<details>

<summary><strong>Can the mapper call an external service?</strong></summary>

No: the mapper methods are synchronous, and an `async` handler is not awaited. Data from another system is better read by a separate [pass data provider](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/pass-data-provider.md). The interceptor is asynchronous, but it runs on every call.

</details>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.thewalletcrew.io/developers-guides/scripting/extensions/cegid-y2.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
