> For the complete documentation index, see [llms.txt](https://docs.revenium.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.revenium.io/track-and-control-costs/attribute-spend-to-departments.md).

# Attribute Spend to Departments

Once AI spend is being metered per developer, the next question is always the same one: which department is that spend coming from? Finance wants a chargeback line per department. Engineering leadership wants to know whether the Payments department's usage justifies its seat count. Neither question is answerable from a flat list of individual developers.

Departments are Revenium's answer. You describe your reporting structure once, map each person to a department, and every cost report can then be grouped by department. The structure lives in Revenium, not in your telemetry, which means you can build it after the data is already flowing, without re-sending or reprocessing a single event.

You build the department tree by uploading a CSV file or by calling the API, and you can add departments and move people by hand in the app. You can also keep the tree in sync with your directory by scheduling a job on your side that sends your roster to the import API (see [Keep Departments in Sync Automatically](#keep-departments-in-sync-automatically)). Spend from people you have not mapped is never dropped. It appears under **No department assigned**, and the app lists those people so you can assign them (see [Where Unmapped Spend Appears](#where-unmapped-spend-appears)).

Set up departments and assign people to them before department charts and filters show their spend.

***

### <i class="fa-sitemap">:sitemap:</i> What a Department Is

A department is one node in a tree that mirrors how your organization actually reports. `Engineering`, `Engineering/Platform`, and `Engineering/Platform/Payments` are three departments, each a child of the one before it.

Each person is assigned to exactly one department as their **primary** membership, and that assignment is dated. Departments can nest as many levels as your reporting lines need. Because the whole tree carries a path, a rollup at `Engineering` includes every sub-department beneath it, so you can look at one department or drill into a single sub-department without maintaining two different structures.

Two ideas do the work here, and both matter for the sections below:

* **A person is not a user account.** People in a department are directory records. Creating one does not create a Revenium login, does not send an invitation, and does not require the person to have sent any telemetry yet. You can load your entire roster on day one, before a single developer has been onboarded.
* **Attribution is resolved when you run the report, not when the event arrives.** Nothing about a department is stamped onto a usage event. The department is worked out at query time by looking up who the person was reporting to at the moment the event happened. This is what makes the two behaviours described in **Retroactive Attribution** and **When Someone Changes Departments** below possible.

***

### <i class="fa-list-ol">:list-ol:</i> Set Up Departments for the First Time

When your team has no departments yet, **Settings > Departments** opens on **Set up departments in three steps**. The upload creates every department named in the file and files each person into theirs, so there is no tree to build first.

1. **Download your people.** Select **Download the people we found** for a file with one row for each person Revenium has seen using AI, with an empty `department_path`. If nobody on the team has used AI yet, select **Download a template** instead and add your people's work emails.
2. **Fill in each person's department.** Write it in `department_path`, with slashes for nesting, for example `Engineering/Platform`.
3. **Upload the file.** Select **Open the importer** and choose your file. You see what the file will change before anything is saved (see [Importing in the App](#importing-in-the-app)).

Once your first departments exist, the page leads with the people who still need a department. Your departments sit in a **Departments** card beside them.

An admin whose team has AI assistant data and no departments also sees a **Set up your departments** card on **Home**. Select **Set up departments** to open **Settings > Departments**. Close the card to dismiss it for that team. The card goes away once a department exists.

***

### <i class="fa-file-csv">:file-csv:</i> The CSV Contract

Bulk import takes a CSV with this header:

```
email,department_path
```

An optional `is_primary` column is accepted. Columns are read **by name**, so their order in the file does not matter. Files written against the older header `org_unit_path` keep working: it is accepted as another name for `department_path`.

| Column            | Required | Meaning                                                                                          |
| ----------------- | -------- | ------------------------------------------------------------------------------------------------ |
| `email`           | Yes      | The developer's email address, matching the identity their tooling reports.                      |
| `department_path` | Yes      | Slash-separated department **names** from the root, for example `Engineering/Platform/Payments`. |
| `is_primary`      | No       | Only primary memberships are supported. Omit it, or set it to `true`.                            |

A realistic file:

```csv
email,department_path
ada.lovelace@example.com,Engineering/Platform/Payments
alan.turing@example.com,Engineering/Platform/Payments
grace.hopper@example.com,Engineering/Platform/Identity
katherine.johnson@example.com,Engineering/Developer Experience
margaret.hamilton@example.com,Engineering/Developer Experience
barbara.liskov@example.com,Data/Analytics Engineering
edsger.dijkstra@example.com,Data/Analytics Engineering
sophie.wilson@example.com,Product/Design Systems
```

You do not create the tree first. Every department along each path is created if it does not already exist, so the eight rows above build the whole structure on their own, including the intermediate `Engineering/Platform` node that no row names directly. Likewise, a person who is not yet known to Revenium is created and linked automatically.

Repeat imports are safe. A row whose person is already in the department it names is reported as unchanged rather than written again, so running the import again with a slightly edited roster does not duplicate anything.

{% hint style="info" %}
**File limits.** Uploads are capped at 5 MB and 20,000 rows. A file that exceeds either is rejected with an error rather than partially applied.
{% endhint %}

***

### <i class="fa-upload">:upload:</i> Importing in the App

Under **Settings > Departments**, select **Import**. In the **Import departments from a CSV** card, choose your file and select **Check file**. The check is the dry run described below: it shows how many departments and assignments the file would add, names any row that needs fixing by line number, and saves nothing. When the preview looks right, select **Import**. A template with the two columns is available from the same card under **Download a template**.

Rows with an email and an empty `department_path` are listed under the preview as rows left as they are, grouped by the reason, each with its line number in your file. The groups you may need to act on come first. These rows never block the import.

After **Import**, an undo, or deleting a department, the page says your changes are saved and how many of the changed email addresses it has caught up with. The department figures on the page come from an analytics copy that catches up shortly after a change; the page reloads them once every change has arrived. A deleted department's people show as Unknown department until then.

Tick **This file is my full list** when the file is your whole roster rather than a list of additions. See [When someone leaves](#when-someone-leaves) for what that does.

### <i class="fa-play">:play:</i> Importing over the API: Dry Run First, Then For Real

The import endpoint accepts `multipart/form-data` with a file part named `file`.

Start with a dry run:

```bash
curl -X POST "https://api.revenium.ai/profitstream/v2/api/departments/import/csv?teamId=YOUR_TEAM_ID&dryRun=true" \
  -H "x-api-key: YOUR_API_KEY" \
  -F "file=@roster.csv"
```

A dry run is not a separate validation routine that might drift from the real thing. It runs the genuine import (the same department lookups, the same person resolution, the same membership planning) inside a transaction that is rolled back at the end. It is therefore both a true rehearsal and guaranteed to write nothing.

Both dry and real runs return the same report. Department ids in this example will differ from yours:

```json
{
  "rowsProcessed": 8,
  "unitsCreated": [
    "Engineering (/12/)",
    "Platform (/12/40/)",
    "Payments (/12/40/173/)",
    "Identity (/12/40/174/)",
    "Developer Experience (/12/41/)",
    "Data (/50/)",
    "Analytics Engineering (/50/51/)",
    "Product (/60/)",
    "Design Systems (/60/61/)"
  ],
  "membershipsCreated": 8,
  "membershipsUnchanged": 0,
  "personsCreated": ["ada.lovelace@example.com", "alan.turing@example.com"],
  "errors": [],
  "membershipsRemoved": [],
  "removalsSkipped": false,
  "rowsSkipped": [],
  "syncing": []
}
```

Read `errors` before doing anything else. Each entry carries the 1-based line number in your file (the header is line 1) and a human-readable reason, so a malformed roster tells you exactly which rows to fix.

`rowsSkipped` lists the rows with an email and an empty `department_path` that the import does not apply, with the line, the email and one of these reasons:

| Reason                        | What it means                                                                                                                                                                                                                        |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `INVALID_EMAIL`               | The email is not a valid address.                                                                                                                                                                                                    |
| `NO_MATCHING_PERSON`          | The email matches no single person in your directory.                                                                                                                                                                                |
| `NO_DEPARTMENT`               | People not in the file are left as they are, and this person has no department.                                                                                                                                                      |
| `EMAIL_ON_ANOTHER_ROW`        | Another row gives this person a department, under this email or another of theirs, and that row decides.                                                                                                                             |
| `EMPTY_PATH_KEEPS_DEPARTMENT` | People not in the file are left as they are, so this person keeps their department. To remove them, tick **This file is my full list** (`removeMissing=true`), or, in a correction, end or erase the people who are not in the file. |
| `MANAGED_BY_DIRECTORY_SYNC`   | People not in the file are ended or erased, but this person's department comes from directory sync, so it stays.                                                                                                                     |

`syncing` is empty in a dry run and in a run with errors, which is not applied. After an applied run it lists every email of each person whose department the import changed, with the department id they now have (`null` for none). Reports and dashboards catch up with these changes shortly after the import.

When the report looks right, run the same command with `dryRun=false`.

To move a single person later, without preparing a file, you need the numeric id of the destination department. List the tree to find it:

```bash
curl "https://api.revenium.ai/profitstream/v2/api/departments?teamId=YOUR_TEAM_ID" \
  -H "x-api-key: YOUR_API_KEY"
```

Each entry carries its `id`, `name`, `parentId` and `path`. The path is a chain of department ids, such as `/12/40/173/`, rather than the names in your CSV. Find the department by name, confirm its parent chain using `parentId`, and read its `id` from that record. Then assign:

```bash
curl -X PUT "https://api.revenium.ai/profitstream/v2/api/departments/assignments?teamId=YOUR_TEAM_ID" \
  -H "x-api-key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"email": "ada.lovelace@example.com", "departmentId": 42}'
```

Listing works with a read-only (`rev_rk_`) or write key; importing and assigning require a [write key (`rev_sk_`)](https://docs.revenium.io/integrations/api-key-permissions.md).

***

### <i class="fa-folder-tree">:folder-tree:</i> Browsing Departments and Their People

**Settings > Departments** opens with your people list and, beside it, a **Departments** card that shows each department with its people and spend. A long list shows its first departments and loads the next set with **Show more**. Add a top-level department with **New department** at the top of the page.

Select a department to open it. Its page is titled with the department name, and the path above the title lets you move back up. Select **Departments** in that path to return to the full list. Below the title, tiles show **People**, **Spend**, **Sub-departments** and, when department admins are turned on, **Admins**. When the department has sub-departments, the **People** figure includes everyone in them. Under the tiles you see a **Department admins** card when department admins are turned on, a **Sub-departments** card, and **People in** the department's name.

The **People in** list shows the people placed directly in that department. Find one person by typing a name or an email in **Search by name or email**, and narrow the list to one assistant with the **Tool** filter. People in a sub-department are listed on that sub-department's page.

Add a department under the one you have open with **New sub-department** in the **Sub-departments** card. A name box opens in the card. Type the name and select **Add**. You can also create a department while filing people: type a new name in a department picker and select **Create**.

To change the open department, use the buttons at the top of its page: **Rename**, **Move** or **Delete**. **Move** opens a **Move under** picker, where you choose the new parent or **Top level**. The picker has **Search departments…**. When more departments match than it lists, it says how many and asks you to type to narrow the list.

#### Department admins

If your organization has department admins turned on, the open department shows an **Admins** tile and a **Department admins** card. The card lists who administers the department. Admins see this department's usage and can set its budgets. Anyone with a login can be a department admin, except a person whose only role is Read Only.

To add one, type a name or an email under **Add an admin** and pick the person from the results. Someone whose only role is Read Only is greyed out and carries the line **Read Only users cannot be a department admin.** Give them another role first, then add them. Someone who is already in a department becomes an admin of this one without being moved. Someone who is not in a department yet is added to the department you choose, and made an admin of this one, when you select **Add and make admin**. A confirmation shows who was added and offers **Undo**. When the person sits in a different department, it says which one.

You can add someone who has no Revenium login yet. They show with **No Revenium account** and an **Invite** button, which opens the invitation so they can sign in. Select **Remove** beside an admin to take them off the department.

You can also name a department admin when you add a user. Under **Settings > Revenium Users**, select **Add User** and pick the department in **Department admin of** (optional). One save creates the login, places the person in that department if they are not in one yet, and makes them its admin. The picker shows for every role except Read Only.

### <i class="fa-arrows-left-right">:arrows-left-right:</i> Moving People in the App

People are filed and moved in the people lists under **Settings > Departments**. The same controls work for someone with no department and for someone you are moving.

On the main page, three tabs above the list choose who it shows. **Need a department** lists people with recent coding-assistant usage and no department. It also lists people with no department who use AI through a gateway under an email address, even if they have never used a coding assistant. **Other identities** lists other identities that used your API keys without a department. **Everyone** lists both groups and people who already have a department. **Search by name or email** looks across everyone, and the number on each tab then shows how many matches that tab holds. When the open tab has no match, the list offers a **Show all** button, with the number of matches, that switches to **Everyone**. The **Email domain** menu narrows the list to one domain.

To move one person:

1. Find the person's row. Use the tabs, or type a name or an email in **Search by name or email**. On a department's page, the list under **People in** shows its people.
2. Open the department picker on the row. It reads **Choose department** when the person has none.
3. Pick the destination. The change is saved as soon as you pick it.

To move several people at once, tick the checkbox on each row, or the checkbox in the header whose label starts **Select all** and ends with **in view**. A bar appears with a **Department for the selection** picker. Its button reads **Assign N people** when nobody selected has a department, **Move N people** when everyone selected already has one, and **Set department for N people** for a mix. When the selection includes people who already have a department, the button asks for a second click to confirm the move. Select **Clear** to drop the selection, or use **Remove from department** as described below.

To take several people out of their departments at once, tick them and select **Remove from department** in the same bar. The button asks for a second click and then reads **Remove N from their department**; select it again to remove them. People who are not in a department are skipped, and the message says how many: for example, "1 was not in a department and was skipped." People whose department Revenium could not read are skipped too: "1 was skipped because their department could not be read." Anyone Revenium could not remove stays ticked, with the reason. The button is off when nobody ticked can be removed. It says **No one selected is in a department.** when everyone ticked has none, and **The department of the people selected could not be read.** when some could not be read. Removal works the same as removing one person: their earlier spend stays where it was.

A move made here follows the same rule as a CSV or API move: a person's first assignment covers their whole history, and a later move counts only from the moment you make it. See [When Someone Changes Departments](#when-someone-changes-departments).

#### Assign people in bulk

To place people you already have as a list, select **Assign people in bulk** beside the search box on the main page. Paste work emails, one per line or separated by commas, pick their department, and select **Assign N people**. Anyone already in another department moves to the one you pick. Each address is assigned once, however often it appears in the list. The dialog says how many people it assigned, and every address it did not assign stays in the box with the reason, such as an entry that is not an email address. If different people belong in different departments, the dialog's **Go to Import** button opens the importer.

***

### <i class="fa-gauge-high">:gauge-high:</i> Set a Budget or Guardrail for a Department

Use a department budget to cap the metered AI spend of one part of your organization: when the limit is reached, Revenium blocks matching requests once **Enforce the limit** is set to **Live**; **Shadow** records simulated events first, see step 5. If your organization has department alert budgets turned on, a department budget can also only alert, without stopping anything (see below). First, set up departments and assign people so Revenium can attribute their usage.

1. Open **Guardrails** in the sidebar and select **New budget or alert**.
2. In **3. Respond**, set **Enforce the limit** to **Shadow** or **Live** so the budget limits spend. A capped department budget uses a Budget period limit. If your organization has department alert budgets turned on, a department budget can instead only alert (see below).
3. In **1. Watch**, choose **Metered**. Under **Filter data by (optional)**, select **Add filter**, choose **Department** as the dimension, select **Is**, and pick a department.
4. Choose the metric and budget condition. You can also turn on **Notify** to get an alert as well as the cap.
5. **Shadow** blocks nobody and records the requests it would have blocked as simulated events. To start blocking requests, choose **Live** and confirm **Switch to live**. Review the budget before saving.

The selected department includes its sub-departments, which the form calls sub-teams: it says **Department budgets always include sub-teams.** There is no switch to exclude them.

To give every department its own limit with one rule, choose **Department** under **Group by (optional)** and leave the Department filter empty. Each department is compared with the full limit independently, rather than sharing one pool. A rule uses either a Department filter or Group by Department, not both.

Filtering by Department and grouping by Department need **Enforce the limit** set to **Shadow** or **Live**, with exceptions when your organization has department alert budgets turned on: a **Total cost** budget over a day, week, month or quarter, from metered data, can filter by one department, or group by Department, without it. These budgets only alert and never block. A filter budget alerts when the department and its sub-departments pass the amount. The Department filter then works alone: every other filter, every grouping and every other limit type reads as unavailable, with the reason shown in the option, or on hover or keyboard focus for Add filter and Billed.

Without department alert budgets, the Department option reads **Not available on your account for budgets that only send alerts**. With them, when the budget does not fit, the option explains what is needed: a Total cost budget over a day, week, month or quarter, from metered data, with no other filter or grouping.

You cannot remove a department that a switched-on rule filters on. The app refuses and lists those rules; change their department, switch them off or delete them first. A switched-off rule whose department was removed cannot be switched back on until you pick another department.

{% hint style="info" %}
**Good to know.** Department choices appear for Metered rules. A user with read-only access can inspect Guardrails but cannot create or edit them. If your directory has no departments or assignments yet, the picker prompts you to set those up.
{% endhint %}

See [Set Budgets & Alerts](https://docs.revenium.io/track-and-control-costs/set-budgets-and-alerts.md) for the remaining Guardrail settings.

***

### <i class="fa-circle-question">:circle-question:</i> Where Unmapped Spend Appears

Spend that cannot be placed in a department is kept and shown in one of two buckets, so department totals never quietly lose money.

| Bucket                     | What it holds                                                                                                                                                    | How to clear it                                                                                                                                                                                                                                                         |
| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **No department assigned** | Spend from people Revenium can identify by email, who are not in any department. This includes people removed from their department, from the moment of removal. | Assign those people to a department. For someone who never had a department, all of their spend moves into it. For someone who was removed earlier, only spend from the moment you assign them moves. Spend from between the removal and the new assignment stays here. |
| **Unattributed**           | Spend that arrived without a developer's email, for example from a direct API key, a gateway or a proxy that sends no user identity.                             | Assigning departments does not change it. Send the developer's email with the usage so that new usage is attributed. Usage that already arrived without an email stays here.                                                                                            |

To see and fix the first bucket:

1. Open **AI Assistants** and the **Overview** tab. The page heading is **AI Assistants by Department**. **No department assigned** appears there as its own row, next to your departments.
2. When people with no department hold 5% or more of the spend, a notice on that page states how many there are and how much of the spend they hold. It appears only when you have created at least one department and no department filter is applied. If you cannot assign departments, select **Dismiss** to hide the notice for seven days while an admin updates the roster. Admins keep seeing it because they can assign the people whose spend is missing from department comparisons. Select **See who** to list them, or **Assign departments →** to go straight to the list in **Settings > Departments**. When the notice is not showing, use the **No department assigned** row instead.
3. Under **Settings > Departments**, choose the **Need a department** tab and assign people as described in [Moving People in the App](#moving-people-in-the-app).

On the **By Employee** tab, choosing **Department** in **Group by:** shows the same **No department assigned** group.

Assigning departments requires an organization admin. Other users see the same counts and a **Copy request for your admin** button in place of **Assign departments →**.

***

### <i class="fa-clock-rotate-left">:clock-rotate-left:</i> Retroactive Attribution: The First Import Covers All History

**This is the most useful property of the design, and it is worth planning your rollout around.**

The first time a person is imported, their membership is backdated to the beginning of time rather than starting on the day you uploaded the file. Every event they have ever sent therefore attributes to the department you just assigned them.

In practice this means you can run the rollout in the order that is easiest for you:

1. Turn on metering and let developers work. Spend accumulates, attributed to individuals.
2. Weeks later, when you have your roster sorted out, upload the CSV.
3. Every historical report is now broken down by department, including the weeks before the file existed.

There is no backfill job, no reprocessing window, and no need to re-send telemetry. Because departments are resolved when the report runs, the data was never missing. Only the structure to interpret it was.

Backdating applies only to a person's **first** assignment. Once someone has a mapping, a normal move takes effect from the moment you make it and leaves their earlier history where it was, exactly as a transfer does. A developer imported into the wrong department and moved a week later therefore ends up with that week attributed to the wrong department and everything after it attributed correctly. To change earlier reports, see [Correct past departments](#correct-past-departments).

That is worth knowing before the first import rather than after it. Run a dry run, read the report, and confirm the tree is right while backdating is still available to you.

{% hint style="info" %}
**The one prerequisite.** Retroactive attribution works on the identity the events already carry, which is the developer's email address. Events that arrived without an email cannot be attributed later, because there is nothing to match the roster against. See [Identity must be an email address](#identity-must-be-an-email-address).
{% endhint %}

***

### <i class="fa-arrows-turn-right">:arrows-turn-right:</i> When Someone Changes Departments

When you reassign a person who already has a mapping, their **historical spend stays with their old department**. Only usage from the moment of the change forward counts against the new one.

This is deliberate, and it is usually the opposite of what people expect, so it is worth being explicit:

> A developer who spends six months on Payments and then moves to Identity leaves six months of spend on the Payments line. Identity's line starts at zero on the day of the move.

That is the correct behaviour for cost accounting. A department's reported spend for a past quarter should not change because somebody transferred afterwards; if it did, no closed period would ever stay closed and chargebacks already issued would stop reconciling.

The boundary is exact. An event landing precisely at the moment of a transfer counts against the **new** department.

Note the distinction from the previous section, since the two can look contradictory. A **first** assignment is backdated, because before it the person had no department at all and there is no history to protect. A **subsequent** change is not backdated, because there is history, and it belongs where it was earned.

The same rule holds everywhere a department appears, in the app and over the API: usage counts in the department the person was in when the usage happened, for whatever date range you select. A person who moved inside the range appears under both departments, each with the usage that happened there.

***

### <i class="fa-user-minus">:user-minus:</i> When Someone Leaves

Removing a person ends their department from that moment. **Their earlier spend stays on the department**, for the same reason a transfer leaves it there. Anything they are metered for afterwards shows under **No department assigned**.

In the app, find the person under **Settings > Departments**. On a wide table, select the **Remove from** *department* button at the end of their row. On a narrower one, open the actions menu on their row and select **Remove from** their department. Then confirm. To remove several people at once, see [Moving People in the App](#moving-people-in-the-app). Over the API:

```bash
curl -X DELETE "https://api.revenium.ai/profitstream/v2/api/departments/assignments?teamId=YOUR_TEAM_ID&email=ada.lovelace@example.com" \
  -H "x-api-key: YOUR_API_KEY"
```

To remove everyone who has left in one step, upload your whole roster as the full list: tick **This file is my full list** in the app, or add `removeMissing=true` to the import call. Everyone who is in a department and is not in the file is removed from it, keeping their earlier spend where it was. The dry run lists them in `membershipsRemoved` before anything is saved. Nobody is removed if any row in the file fails (`removalsSkipped` is then `true`), because a person whose row was rejected would otherwise look absent. Without the option, an import only adds and moves people and never removes anyone.

***

### <i class="fa-rotate-left">:rotate-left:</i> Redoing a Wrong Upload

Because a first assignment covers all of a person's history, and a later change does not, moving a wrongly uploaded person leaves their earlier spend on the wrong department. To correct that history with a CSV, see [Correct past departments](#correct-past-departments). You can also **delete** the person and upload them again. Deleting removes the person from your department list and takes **all** of their usage, past usage included, off the department; when they are uploaded again they are new, so their first assignment covers all of their history on the right department.

In the app, find the person under **Settings > Departments**, select the **Delete person** button at the end of their row (on a narrower table, open the actions menu on their row and select **Delete person**), and confirm. People who were uploaded and have never used AI are listed under their department too, so a wrong file can be cleaned up from the same screen. Over the API:

```bash
curl -X DELETE "https://api.revenium.ai/profitstream/v2/api/departments/persons?teamId=YOUR_TEAM_ID&email=ada.lovelace@example.com" \
  -H "x-api-key: YOUR_API_KEY"
```

Use Remove for someone who left, and Delete only to undo a mistake.

***

### <i class="fa-clock-rotate-left">:clock-rotate-left:</i> Correct past departments

A CSV correction changes which departments past usage appears under, so use it after a wrong upload or when a reorganization should appear in past reports.

1. Under **Settings > Departments**, select **Import**. In **Import departments from a CSV**, choose your file.
2. Under **What is this file?**, select **A correction of the past**. Choose **From the beginning** or **From a date** and, if needed, set the **Effective date**. Under **People who are not in this file**, choose **Leave them as they are**, **End their department today**, or **Erase their past**.
3. Select **Check file**. Review each person's **Before** and **After** departments and the past usage moving in the preview. When prompted, type the number of people the correction changes, then select **Import**.

**History**, at the top of the page, opens **Import history**. It shows when each upload or correction ran, who ran it, the file and the number of people changed. To reverse an eligible correction, select **Undo**, then **Undo this correction**. Undo puts the affected people's department history back as it was before that import. A later change to the same people can prevent undo.

An organization admin can make corrections and undo imports.

***

### <i class="fa-file-invoice">:file-invoice:</i> Allocating billed Claude Enterprise spend to departments

Revenium links spend to people by email, and people to departments through your department tree. [**Intelligence > Providers > Users**](https://docs.revenium.io/pages/Nxs4x0Ovc4ZMJHO6zLAP#id-4.-users-who-is-spending-on-claude-enterprise) shows the Claude Enterprise spend Anthropic billed for each person, without seat fees.

To allocate the billed amount:

1. Map people to departments with a CSV upload, the import API or a scheduled directory sync.
2. Add up the per-person billed amounts by department. This step is manual.

Department reports built from AI Assistant usage add up the telemetry estimate, not the invoice. Use them for usage detail rather than for invoice allocation. [How Revenium Prices a Transaction](https://docs.revenium.io/track-and-control-costs/how-revenium-prices-a-transaction.md#claude-code-and-cowork-on-a-claude-enterprise-invoice) explains the difference.

Revenium does not split seat fees, credits or spend that Anthropic links to no person. Allocate those by your own rule, for example by seat count per department.

For per-person usage detail on Claude Code, turn on Claude Code telemetry to Revenium. Set `CLAUDE_CODE_ENABLE_TELEMETRY=1` and the Revenium OTLP endpoint through managed settings or the Revenium CLI. See [Setup Claude Code](https://docs.revenium.io/track-and-control-costs/analyze-ai-tooling-spend/setup-claude-code.md).

***

### <i class="fa-circle-info">:circle-info:</i> Good to Know

#### Departments follow your directory when you schedule the API job

Each import reflects your roster at the moment it runs. To keep departments current as people join, move and leave, schedule the API job described in [Keep Departments in Sync Automatically](#keep-departments-in-sync-automatically). Anyone who starts using AI between runs appears under **No department assigned** until the next run, so that bucket also shows when the roster needs a refresh.

#### Ambiguous emails are never guessed

If more than one active directory person claims the same email address, the import does not choose between them. The row is reported as ambiguous and left for an administrator to resolve. This is intentional: silently picking one would attribute somebody's spend to the wrong person, and that error is invisible once it is made.

#### Only primary memberships

Each person belongs to exactly one department. Matrix organizations, dotted-line reporting, and splitting one developer's cost across two departments are not supported. A row that explicitly asks for a non-primary membership is reported as an error rather than being quietly ignored.

#### Identity must be an email address

Attribution matches on email at every stage. A fleet that reports only an opaque identifier and no email address cannot be mapped to a department, no matter how complete the roster is. Those events are still metered, still costed, and still attributed to your organization. In department rollups they appear under **Unattributed**.

Unattributed and No department assigned are real buckets, not dropped rows. When you group the By Employee table by department, its footer shows whether the rows reconcile with the filtered total and displays any gap. See [Where Unmapped Spend Appears](#where-unmapped-spend-appears).

If you are configuring Claude Code, the stock configuration already reports developer email correctly, and no extra attribution setup is needed for departments to work. See [Setup Claude Code](https://docs.revenium.io/track-and-control-costs/analyze-ai-tooling-spend/setup-claude-code.md).

#### Link an email your directory does not list

Revenium matches the email your AI tools report to a person in your directory. When a developer's tools report a different address, such as an alias, their spend is not tied to their directory record or their department. A manual mapping links that email to the right person, and a directory sync never overrides it.

1. [List the mappings](https://revenium.readme.io/reference/listdirectorylinkmappings). Every email Revenium has matched appears with its `directoryPersonId`. Find the person's usual email to get their id.
2. [Create the mapping](https://revenium.readme.io/reference/upsertdirectorylinkmapping) from the other email to that id.
3. [Delete a mapping](https://revenium.readme.io/reference/deletedirectorylinkmapping) by its `id` when it is no longer needed.

Listing works with a read-only or full-access key and needs no other parameter. Creating and deleting need a full-access key and your team id as `teamId`.

#### Emails that match more than one person cannot be removed or deleted by email

Remove and Delete by email refuse, and change nothing, when the address matches more than one directory person. Resolve the duplicate first, or use the person's id.

***

### <i class="fa-file-export">:file-export:</i> Producing the CSV From Your Directory

Your IT administrators can generate the file directly from your existing directory. Both recipes below emit the exact two-column format the importer expects. Treat them as starting points: the attribute you use for the department path depends on how your directory is organized, and you will likely want to filter to the population that actually uses AI tooling.

#### Microsoft Entra ID (Azure AD)

Using the Microsoft Graph PowerShell SDK:

```powershell
Connect-MgGraph -Scopes "User.Read.All"

Get-MgUser -All -Property UserPrincipalName,Mail,Department,CompanyName,AccountEnabled |
  Where-Object { $_.AccountEnabled -and $_.Department -and $_.Mail } |
  Select-Object `
    @{Name = 'email';         Expression = { $_.Mail }},
    @{Name = 'department_path'; Expression = { $_.Department }} |
  Export-Csv -Path roster.csv -NoTypeInformation -Encoding utf8NoBOM
```

`Department` is a single value, which produces a flat one-level tree. To build a hierarchy, compose the path from whichever attributes carry your structure, for example a company or division and a department. Swap the `department_path` expression above for:

```powershell
@{Name = 'department_path'; Expression = { "$($_.CompanyName)/$($_.Department)" }}
```

Any attribute you reference in an expression must also appear in `-Property`, which is why `CompanyName` is requested above even though the flat version does not use it. Graph returns nothing for an unrequested attribute, and an empty leading segment would quietly collapse the hierarchy back to a flat tree rather than failing.

#### On-premises Active Directory

Using the ActiveDirectory module on a domain-joined machine:

```powershell
Import-Module ActiveDirectory

Get-ADUser -Filter { Enabled -eq $true } -Properties mail,department,division |
  Where-Object { $_.mail -and $_.department } |
  Select-Object `
    @{Name = 'email';         Expression = { $_.mail }},
    @{Name = 'department_path'; Expression = { if ($_.division) { "$($_.division)/$($_.department)" } else { $_.department } }} |
  Export-Csv -Path roster.csv -NoTypeInformation -Encoding utf8NoBOM
```

If your reporting structure is expressed through Active Directory organizational units (OUs) rather than a `department` attribute, derive the path from each user's distinguished name instead, reversing the OU components into a root-first path.

{% hint style="info" %}
**Check the file before uploading it.** Confirm the header is exactly `email,department_path` and that no value contains a stray comma. Then run the import with `dryRun=true` and read the error list. Between them, those two steps catch essentially every formatting problem before anything is written.
{% endhint %}

***

### <i class="fa-rotate">:rotate:</i> Keep Departments in Sync Automatically

You can keep departments in step with your directory automatically. Schedule a job on your side that exports your roster with one of the recipes above and sends it to the [import API](#importing-over-the-api-dry-run-first-then-for-real) with `removeMissing=true`. Each run adds new joiners, moves people who changed departments and removes people who left, with no one uploading a file by hand.

Anyone missing from the file has their department cleared, so the export must include everyone who should keep a department. The recipes above leave out people whose department is blank in your directory, so fill in their department there before the first run. Start with a dry run and confirm the removals it reports are people who left:

```bash
curl -X POST "https://api.revenium.ai/profitstream/v2/api/departments/import/csv?teamId=YOUR_TEAM_ID&removeMissing=true&dryRun=true" \
  -H "x-api-key: YOUR_API_KEY" \
  -F "file=@roster.csv"
```

Once the dry run shows only the changes you expect, remove `dryRun=true` from the job. Have the job read `errors` in each report: when any row fails, the run removes nobody and sets `removalsSkipped` to `true` (see [When Someone Leaves](#when-someone-leaves)).

Where the app offers to sync your directory, it opens **Settings > Departments**.

***

### <i class="fa-list-check">:list-check:</i> Rollout Checklist

1. Confirm your AI tooling reports developer **email**. Everything else depends on it.
2. Export a roster from your directory using one of the recipes above.
3. Check the file first (**Check file** in the app, or `dryRun=true`) and resolve every entry in `errors`.
4. Import for real, then check `unitsCreated` matches the structure you intended.
5. Group cost reports by department, in the app or over the API. Historical periods are included automatically.
6. Check **No department assigned** on the **AI Assistants by Department** page and assign anyone listed.
7. Schedule the API job in [Keep Departments in Sync Automatically](#keep-departments-in-sync-automatically) so departments follow your directory as people join, move and leave.


---

# 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.revenium.io/track-and-control-costs/attribute-spend-to-departments.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.
