> For the complete documentation index, see [llms.txt](https://docs.digit.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.digit.org/health/ph-v1.8/design/architecture/low-level-design/services/project-factory-campaign-manager/manage-boundary-apis.md).

# Manage Boundary APIs

## **Overview**

This documentation outlines the process and components of bulk uploading boundaries for a campaign. It covers the proper format of the Excel sheet, unique code generation, functions for boundary entity creation, boundary relationship creation, localisation, and API details.

## Sequence Diagram

<figure><img src="/files/ubRo0BJzC9yTtKM8N9jA" alt=""><figcaption></figcaption></figure>

### Excel Format - Boundary Bulk Upload

The Excel sheet should be formatted as follows:

| Country | Província | Distrito | Posto Administrativo | Localidade | Aldeia |
| ------- | --------- | -------- | -------------------- | ---------- | ------ |
| INDIA   |           |          |                      |            |        |
| INDIA   | KARNATAKA |          |                      |            |        |
| INDIA   | KARNATAKA | BLR      |                      |            |        |
| INDIA   | KARNATAKA | BLR      | KORAMANGALA          |            |        |
| INDIA   | KARNATAKA | BLR      | KORAMANGALA          | 3RD BLOCK  |        |
| INDIA   | KARNATAKA | BLR      | KORAMANGALA          | 3RD BLOCK  | EGOV   |
| INDIA   | BIHAR     |          |                      |            |        |
| INDIA   | BIHAR     | PATNA    |                      |            |        |

### Unique Code Generation

Unique codes are auto-generated for each boundary level as follows:

| Boundary    | Code                              |
| ----------- | --------------------------------- |
| INDIA       | ADMIN\_IN                         |
| KARNATAKA   | ADMIN\_IN\_01\_KARNATAKA          |
| BLR         | ADMIN\_IN\_01\_01\_BLR            |
| KORAMANGALA | ADMIN\_IN\_01\_01\_01\_KORMANGALA |
| BIHAR       | ADMIN\_IN\_02\_BIHAR              |
| PATNA       | ADMIN\_IN\_02\_01\_PATNA          |

If there are two districts (boundaries at the same level) with the same name (for example, BLR) under different parent-level boundaries, the names will be updated to BLR, BLR-01, and so on.

#### getAutoGeneratedBoundaryCodes Function

**Purpose:**

Generate auto-generated boundary codes based on boundary list, child-parent mapping, element codes map, count map, and request information.

**Parameters:**

* `boundaryList`: List of boundary data.
* `childParentMap`: Map of child-parent relationships.
* `elementCodesMap`: Map of boundaries to its corresponding auto-generated unique codes.
* `countMap`: Map of counts for each boundary.
* `request`: HTTP request object.

**Returns:**

* Updated element codes map.

**Steps:**

1. **Initialise Column Data**:
   * Initialise an array to store column data.
2. **Extract Unique Elements**:
   * Iterate through each row of the boundary list.
   * Extract unique elements from each column.
3. **Generate Boundary Codes**:
   * Iterate over columns to generate boundary codes.
   * Check if the element code exists in the element codes map.
   * If not, generate a new code based on parent-child mapping and sequence.
   * Store the code of the element in the element codes map.
4. **Default Code Generation**:
   * Generate default code if parent code is not found.
5. **Updated Element Codes Map**

   Return Updated Boundary Data - Auto-Generated Code Map.

### Boundary Entities Creation

Boundary entities are created chunk-wise, with each chunk consisting of 200 codes.

#### Create Boundary Entities&#x20;

**Purpose:**

To create new boundary entities in the system from the provided boundary codes.

**Steps:**

1. **Convert Boundary Map**:
   * Change the boundary map to a list of objects with `key` and `value`.
2. **Prepare Request**:
   * Set up the request details and initialise lists for boundaries and existing codes.
3. **Chunk Boundary Codes**:
   * Divide the boundary codes into smaller groups.
4. **Fetch Existing Boundaries**:
   * Check the system for existing boundary codes and collect them.
5. **Identify New Boundaries**:
   * Determine which boundary codes are new and add them to the list of boundaries to create.
6. **Create New Boundaries**:
   * If there are new boundaries, send them to the system in groups and log the results.
7. **Handle Existing Boundaries**:
   * Log a message if all boundaries already exist.
8. **Error Handling**:
   * Manage any errors that occur and provide a relevant error message.

### Boundary Relationship Creation

#### `Create Boundary Relationship`

**Purpose:**

To create boundary relationships in the system from the provided boundary codes and their parent-child mappings.

**Steps:**

1. **Convert Boundary Map**:
   * Transform the boundary map into a list of `{key, value}` objects.
2. **Initialise Request**:
   * Prepare the request details and activity messages array.
3. **Fetch Existing Relationships**:
   * Retrieve existing boundary relationships and extract their codes.
4. **Identify and Create Relationships**:
   * For each boundary code, check if it exists. If not:
     * Prepare the boundary relationship data.
     * Confirm the parent boundary creation.
     * Create the boundary relationship.
5. **Handle Existing Relationships**:
   * If all relationships already exist, log a validation error.
6. **Attach Activity Messages**:
   * Add activity messages to the request body.
7. **Error Handling**:
   * Catch, log, and handle errors appropriately.

### Localisation Upsert of Codes

Boundary codes are localised to their corresponding names as specified in the uploaded Excel sheet.

### Boundary Bulk Upload Upsertion

To add more boundaries after the initial upload, use an Excel sheet that includes existing boundary codes. New boundaries without codes will be created in the same way as the first upload.

## API for Boundary Bulk Upload

API request for boundary bulk upload:

```
curl --location 'http://localhost:8080/project-factory/v1/data/_create' \
--header 'authority: unified-dev.digit.org' \
--header 'accept: application/json, text/plain, */*' \
--header 'accept-language: en-GB,en-US;q=0.9,en;q=0.8' \
--header 'content-type: application/json' \
--header 'cookie: _ga_XBQP06FR8V=GS1.1.1691570094.3.1.1691570094.60.0.0; _ga=GA1.1.2124364284.1689669598; _ga_P1TZCPKF6S=GS1.1.1691648339.2.0.1691648339.60.0.0; __cuid=fe28d9c8c84c4d2487b9cb6c9e4cdec1; amp_fef1e8=f4a3f3ed-50f2-409b-be4f-a1ce1dbb59f2R...1hgs4r9gr.1hgs4robc.nu.1r.pp; _ga_H9YC8FEN6F=GS1.1.1701751656.77.1.1701751677.39.0.0' \
--header 'origin: https://unified-dev.digit.org' \
--header 'referer: https://unified-dev.digit.org/works-ui/employee/measurement/update?tenantId=pg.citya&workOrderNumber=WO/2023-24/000894&mbNumber=MB/2023-24/001252' \
--header 'sec-ch-ua: "Chromium";v="116", "Not)A;Brand";v="24", "Google Chrome";v="116"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'sec-ch-ua-platform: "Linux"' \
--header 'sec-fetch-dest: empty' \
--header 'sec-fetch-mode: cors' \
--header 'sec-fetch-site: same-origin' \
--header 'user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36' \
--data-raw '{
    "RequestInfo": {
        "apiId": "Rainmaker",
        "authToken": "e45445a1-6891-4a76-a4e6-528e1dd24946",
        "userInfo": {
            "id": 1284,
            "uuid": "867ba408-1b82-4746-8274-eb916e625fea",
            "userName": "EMP57",
            "name": "Jagan",
            "mobileNumber": "6667776662",
            "emailId": "[email protected]",
            "locale": "string",
            "type": "EMPLOYEE",
            "roles": [
                {
                    "name": "System Administrator",
                    "code": "SYSTEM_ADMINISTRATOR",
                    "tenantId": "mz"
                },
                {
                    "name": "Campaign Manager",
                    "code": "CAMPAIGN_MANAGER",
                    "tenantId": "mz"
                },
                {
                    "name": "Localisation admin",
                    "code": "LOC_ADMIN",
                    "tenantId": "mz"
                },
                {
                    "name": "MDMS Admin",
                    "code": "MDMS_ADMIN",
                    "tenantId": "mz"
                }
            ],
            "active": true,
            "tenantId": "mz",
            "permanentCity": "Amritsar"
        },
        "msgId": "1710912592752|en_IN",
        "plainAccessRequest": {}
    },
    "ResourceDetails": {
        "type": "boundary",
        "tenantId": "mz",
        "fileStoreId": "be52ce1a-bc25-4328-91bc-a682079abb59",
        "action": "create",
        "hierarchyType": "ADMIN",
        "additionalDetails": {},
        "campaignId": "5d721d03-bdf5-4021-86ff-107e61eb7abb"
    }
}'
```

{% hint style="info" %}
**Note:** Ensure the API endpoint, headers, and payload are customised as per your environment and requirements.
{% endhint %}


---

# 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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.digit.org/health/ph-v1.8/design/architecture/low-level-design/services/project-factory-campaign-manager/manage-boundary-apis.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
