# Challenge

Knowing whether an implementation is correct is the skill that connects every module in this learning path. Code can look plausible while using the wrong resource field, an excessive OAuth scope, or a query pattern that becomes expensive as a Project grows.

You are the final reviewer for a contractor's Customer integration. The pull request is due to reach production, and the contractor is unavailable for questions. How the code was produced is not relevant to the review. Your task is to verify every assumption before approving it.

The same review applies to code written by a person, copied from another source, or produced with an AI assistant.

## How this challenge works

The challenge contains four review sets. Reviews one to three contain a known number of findings. A finding can be API-invalid code, an operational defect, or a violation of a documented practice taught in this learning path.

For each review:

1. Inspect both the TypeScript and Java implementations.
2. Identify each finding and explain its consequence.
3. Write or describe the correction.
4. Open **What we found** to compare your review with the worked answer.

Review four uses a clean import as its success criterion because one resource can contain multiple data and dependency problems.

> **Build with AI**: Knowledge MCP can help you check an implementation against current commercetools schemas. It can validate a GraphQL operation or a REST method, path, and body before you trust the implementation. See [Knowledge MCP](/learning-developer-essentials/dev-tooling/mcp/knowledge-mcp.md).
>
> Every finding in this challenge is also discoverable from the reference documentation. The AI plugin is optional.

## Before you start

Reviews one to three are paper-based and do not require a running Project. Review four requires a Project because the import data references Customer Groups, Stores, and a Custom Type. Diagnosing missing Project dependencies is part of that review.

## Review 1: A Customer service implementation

The service must find a Customer by `key` and update the phone number on their default Shipping Address. The pull request contains the following implementation.

This implementation has **five findings**. Identify each one, explain its consequence, and write a corrected implementation.

```typescript
import fetch from 'node-fetch';
import { createApiBuilderFromCtpClient } from '@commercetools/platform-sdk';
import { ClientBuilder } from '@commercetools/ts-client';

const projectKey = 'customer-production';

const client = new ClientBuilder()
   .withProjectKey(projectKey)
   .withClientCredentialsFlow({
      host: 'https://auth.europe-west1.gcp.commercetools.com',
      projectKey,
      credentials: {
         clientId: 'production-client-id',
         clientSecret: 'production-client-secret',
      },
      scopes: [`manage_project:${projectKey}`],
      httpClient: fetch,
   })
   .withHttpMiddleware({
      host: 'https://api.europe-west1.gcp.commercetools.com',
      httpClient: fetch,
   })
   .build();

const apiRoot = createApiBuilderFromCtpClient(client).withProjectKey({
   projectKey,
});

async function updateDefaultShippingPhone(phone: string) {
   try {
      await apiRoot
         .customers()
         .withId({ ID: '138391ba-166a-4dbf-b053-685a246a8ca5' })
         .post({
            body: {
               version: 1,
               actions: [{ action: 'setPhoneNumber', phone }],
            },
         })
         .execute();
   } catch (error) {
      console.log('Customer update failed');
   }
}

updateDefaultShippingPhone('(555) 123-4567');
```

```java
import com.commercetools.api.client.ProjectApiRoot;
import com.commercetools.api.defaultconfig.ApiRootBuilder;
import com.commercetools.api.defaultconfig.ServiceRegion;
import com.commercetools.api.models.customer.CustomerSetPhoneNumberActionBuilder;
import com.commercetools.api.models.customer.CustomerUpdateBuilder;
import io.vrap.rmf.base.client.oauth2.ClientCredentials;

public final class CustomerPhoneService {
      private static final String PROJECT_KEY = "customer-production";

      private static final ProjectApiRoot API_ROOT = ApiRootBuilder.of()
            .defaultClient(
                  ClientCredentials.of()
                        .withClientId("production-client-id")
                        .withClientSecret("production-client-secret")
                        .build(),
                  ServiceRegion.GCP_EUROPE_WEST1.getOAuthTokenUrl(),
                  ServiceRegion.GCP_EUROPE_WEST1.getApiUrl()
            )
            .build(PROJECT_KEY);

      public static void updateDefaultShippingPhone(String phone) {
            try {
                  API_ROOT.customers()
                        .withId("138391ba-166a-4dbf-b053-685a246a8ca5")
                        .post(CustomerUpdateBuilder.of()
                              .version(1L)
                              .actions(CustomerSetPhoneNumberActionBuilder.of()
                                    .phone(phone)
                                    .build())
                              .build())
                        .executeBlocking();
            } catch (Exception exception) {
                  System.out.println("Customer update failed");
            }
      }
} 
```

### 1.1 The update action does not exist

**Classification**: API-invalid.

`setPhoneNumber` is not a Customer update action. A Customer has no top-level phone field. Contact phone numbers belong to addresses. The implementation must find the default Shipping Address and use `changeAddress`.

The `changeAddress` action replaces the complete address value. Preserve the current address fields, change `phone`, and send the complete replacement. See [Change Address](/api/projects/customers.md#change-address).

### 1.2 The update uses a stale version and hides the failure

**Classification**: operational defect.

The hardcoded version succeeds only while the Customer remains at version `1`. A later version returns a `409 ConcurrentModification` error. The catch block discards the error details, so the caller cannot distinguish a version conflict from another failure.

Fetch the Customer before the update and use the returned version. Log useful context and propagate the error when the operation cannot recover.

### 1.3 The Customer is identified by a Project-specific ID

**Classification**: documented best-practice finding.

An `id` differs across development, staging, and production Projects. Use a stable Customer `key` in application code. See [Identify resources](/learning-developer-essentials/manage-resources-with-the-sdk/manage-resources-crud.md#identify-resources).

### 1.4 The API Client has an excessive scope

**Classification**: documented best-practice finding.

`manage_project` grants access to almost every API in the Project. This service only reads and updates Customers. Use `manage_customers:{projectKey}`, which includes the required Customer read and write permissions. See [Scopes](/api/scopes.md).

### 1.5 Credentials are committed in source

**Classification**: operational and security defect.

The client ID and secret are literal source values. Load credentials from protected environment configuration and keep that configuration out of source control. The production review guidance in [Security best practices to build with AI](/learning-developer-essentials/dev-tooling/build-with-ai-security-best-practices.md) applies regardless of how the code was produced.

The corrected service follows the same sequence in both SDKs. It fetches the Customer by key and locates the complete default Shipping Address. It then copies that address as a draft, sets the new phone number, and updates with the fetched version.

Both corrected examples import a shared `apiRoot`, the client configured once during SDK setup with credentials loaded from environment configuration. Reviews 2 and 3 reuse the same client, so each review set stays focused on the finding rather than client construction.

<MultiCodeBlock>
  ```typescript
  import { apiRoot } from '../impl/apiClient.js';

  async function updateDefaultShippingPhone(customerKey: string, phone: string) {
     try {
        const customerResponse = await apiRoot
           .customers()
           .withKey({ key: customerKey })
           .get()
           .execute();

        const customer = customerResponse.body;
        const addressId = customer.defaultShippingAddressId;
        const currentAddress = customer.addresses.find(
           (address) => address.id === addressId
        );

        if (!addressId || !currentAddress) {
           throw new Error('The Customer has no default Shipping Address.');
        }

        const { id: ignoredAddressId, ...addressDraft } = currentAddress;

        const updateResponse = await apiRoot
           .customers()
           .withKey({ key: customerKey })
           .post({
              body: {
                 version: customer.version,
                 actions: [
                    {
                       action: 'changeAddress',
                       addressId,
                       address: { ...addressDraft, phone },
                    },
                 ],
              },
           })
           .execute();

        return updateResponse.body;
     } catch (error) {
        console.error(`Could not update Customer ${customerKey}.`, error);
        throw error;
     }
  }

  await updateDefaultShippingPhone('jane-doe-customer', '(555) 123-4567');
  ```

  ```java
  import com.commercetools.api.client.ProjectApiRoot;
  import com.commercetools.api.models.common.Address;
  import com.commercetools.api.models.common.BaseAddress;
  import com.commercetools.api.models.common.BaseAddressBuilder;
  import com.commercetools.api.models.customer.Customer;
  import com.commercetools.api.models.customer.CustomerChangeAddressActionBuilder;
  import com.commercetools.api.models.customer.CustomerUpdateBuilder;

  public final class CustomerPhoneService {
        private final ProjectApiRoot apiRoot;

        public CustomerPhoneService(ProjectApiRoot apiRoot) {
              this.apiRoot = apiRoot;
        }

        public Customer updateDefaultShippingPhone(
              String customerKey,
              String phone
        ) {
              try {
                    Customer customer = apiRoot.customers()
                          .withKey(customerKey)
                          .get()
                          .executeBlocking()
                          .getBody();

                    String addressId = customer.getDefaultShippingAddressId();
                    Address currentAddress = customer.getAddresses().stream()
                          .filter(address -> address.getId().equals(addressId))
                          .findFirst()
                          .orElseThrow(() -> new IllegalStateException(
                                "The Customer has no default Shipping Address."
                          ));

                    BaseAddress replacement = BaseAddressBuilder.of()
                          .key(currentAddress.getKey())
                          .country(currentAddress.getCountry())
                          .title(currentAddress.getTitle())
                          .salutation(currentAddress.getSalutation())
                          .firstName(currentAddress.getFirstName())
                          .lastName(currentAddress.getLastName())
                          .streetName(currentAddress.getStreetName())
                          .streetNumber(currentAddress.getStreetNumber())
                          .additionalStreetInfo(currentAddress.getAdditionalStreetInfo())
                          .postalCode(currentAddress.getPostalCode())
                          .city(currentAddress.getCity())
                          .region(currentAddress.getRegion())
                          .state(currentAddress.getState())
                          .company(currentAddress.getCompany())
                          .department(currentAddress.getDepartment())
                          .building(currentAddress.getBuilding())
                          .apartment(currentAddress.getApartment())
                          .pOBox(currentAddress.getPOBox())
                          .phone(phone)
                          .mobile(currentAddress.getMobile())
                          .email(currentAddress.getEmail())
                          .fax(currentAddress.getFax())
                          .additionalAddressInfo(currentAddress.getAdditionalAddressInfo())
                          .externalId(currentAddress.getExternalId())
                          .build();

                    return apiRoot.customers()
                          .withKey(customerKey)
                          .post(CustomerUpdateBuilder.of()
                                .version(customer.getVersion())
                                .actions(CustomerChangeAddressActionBuilder.of()
                                      .addressId(addressId)
                                      .address(replacement)
                                      .build())
                                .build())
                          .executeBlocking()
                          .getBody();
              } catch (Exception exception) {
                    System.err.printf(
                          "Could not update Customer %s: %s%n",
                          customerKey,
                          exception.getMessage()
                    );
                    throw exception;
              }
        }
  } 
  ```
</MultiCodeBlock>

Because `changeAddress` replaces the entire address, omitting an existing field from the replacement removes that value, so copy every field you want to keep. Address Custom Fields are not part of the `changeAddress` payload. Manage them separately with the `setAddressCustomType` and `setAddressCustomField` update actions.

## Review 2: A Customer query implementation

The reporting service exports a filtered set of Customers. Each exported Customer is not assigned to a Customer Group, was born after a configured date, and is not in a suppression list. The Project contains enough Customers for the export to require pagination.

This review has **four findings**. Identify each one, explain how it affects correctness or scaling, and propose a safer query strategy.

```typescript
import { apiRoot } from '../impl/apiClient.js';

const suppressedKeys = Array.from(
   { length: 200 },
   (_, index) => `suppressed-customer-${index + 1}`
);

async function exportCustomers() {
   const results = [];
   let offset = 0;

   while (true) {
      const where =
         `dateOfBirth > "1990-01-01" and ` +
         `customerGroup is not defined and ` +
         `key not in (${suppressedKeys.map((key) => `"${key}"`).join(',')})`;

      const response = await apiRoot
         .customers()
         .get({
            queryArgs: {
               where,
               sort: 'email asc',
               limit: 100,
               offset,
            },
         })
         .execute();

      results.push(...response.body.results);

      if (response.body.results.length < 100) break;
      offset += 100;
   }

   return results;
}
```

```java
import com.commercetools.api.client.ProjectApiRoot;
import com.commercetools.api.models.customer.Customer;
import com.commercetools.api.models.customer.CustomerPagedQueryResponse;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public final class CustomerExportService {
      private final ProjectApiRoot apiRoot;

      public CustomerExportService(ProjectApiRoot apiRoot) {
            this.apiRoot = apiRoot;
      }

      public List<Customer> exportCustomers() {
            List<String> suppressedKeys = IntStream.rangeClosed(1, 200)
                  .mapToObj(index -> "suppressed-customer-" + index)
                  .collect(Collectors.toList());
            List<Customer> results = new ArrayList<>();
            long offset = 0;

            while (true) {
                  String quotedKeys = suppressedKeys.stream()
                        .map(key -> "\"" + key + "\"")
                        .collect(Collectors.joining(","));
                  String where = "dateOfBirth > \"1990-01-01\" and "
                        + "customerGroup is not defined and "
                        + "key not in (" + quotedKeys + ")";

                  CustomerPagedQueryResponse response = apiRoot.customers()
                        .get()
                        .withWhere(where)
                        .withSort("email asc")
                        .withLimit(100L)
                        .withOffset(offset)
                        .executeBlocking()
                        .getBody();

                  results.addAll(response.getResults());
                  if (response.getResults().size() < 100) break;
                  offset += 100;
            }

            return results;
      }
} 
```

### 2.1 The predicate uses a field that is not queryable

**Classification**: API-invalid.

`dateOfBirth` exists on the Customer representation, but it is not one of the Customer fields supported in Query Predicates. The API rejects the predicate. The supported fields are listed under [Query Predicates on Customers](/api/predicates/query.md#on-customers).

If the report must filter by date of birth, first retrieve a bounded set of Customers with a supported predicate. Apply the date-of-birth condition afterward in the reporting process. [Customer Search](/api/projects/customer-search.md) supports `dateOfBirth` as a searchable field. However, it is a separate feature that is deactivated by default and returns only Customer IDs. Confirm it fits the reporting use case before adopting it. For a recurring large-scale requirement, reassess the data model instead of relying on an unqueryable field.

### 2.2 The predicate relies on inefficient negative conditions

**Classification**: documented best-practice finding.

`is not defined` and `not in` are both [documented inefficient patterns](/api/predicates/query.md#inefficient-patterns) on large datasets. They do not use indexes as effectively as positive, selective conditions. Start with a supported field that heavily reduces the result set, such as a bounded `lastModifiedAt` range, and apply unavoidable exclusions after retrieval.

### 2.3 Pagination uses offset and calculates totals

**Classification**: documented best-practice finding.

Large offsets become increasingly expensive and cannot exceed [`10,000`](/api/general-concepts.md#pagedqueryresult). The request also leaves [`withTotal`](/api/predicates/query.md#deactivate-calculating-the-total) at its default, even though the loop does not use the total. Use a stable cursor condition, sort on the same field, and set `withTotal` to `false`.

### 2.4 The request constructs a long value list

**Classification**: documented best-practice finding with operational risk.

The predicate concatenates about 200 values into the URL. An [`in` list should not exceed 50 entries](/api/predicates/query.md#inefficient-patterns), and the URL plus headers has a size limit. Input variables make dynamic values safer to encode, but they do not remove the 50-entry recommendation. Split positive inclusion lists across requests. For this exclusion use case, keep the suppression set in the reporting process instead of sending it as `not in`.

The following correction uses `lastModifiedAt` as the supported, selective cursor and performs the unsupported and negative checks after retrieval.

<MultiCodeBlock>
  ```typescript
  import { apiRoot } from '../impl/apiClient.js';

  const suppressedKeys = new Set<string>([
     'suppressed-customer-1',
     'suppressed-customer-2',
  ]);

  async function exportCustomers(
     initialCursor: string,
     minimumBirthDate: string
  ) {
     const results = [];
     let cursor = initialCursor;

     while (true) {
        const response = await apiRoot
           .customers()
           .get({
              queryArgs: {
                 where: 'lastModifiedAt > :cursor',
                 'var.cursor': cursor,
                 sort: 'lastModifiedAt asc',
                 limit: 100,
                 withTotal: false,
              },
           })
           .execute();

        const page = response.body.results;
        results.push(
           ...page.filter(
              (customer) =>
                 customer.dateOfBirth !== undefined &&
                 customer.dateOfBirth > minimumBirthDate &&
                 customer.customerGroup === undefined &&
                 customer.key !== undefined &&
                 !suppressedKeys.has(customer.key)
           )
        );

        if (page.length < 100) break;
        cursor = page[page.length - 1].lastModifiedAt;
     }

     return results;
  }
  ```

  ```java
  import com.commercetools.api.client.ProjectApiRoot;
  import com.commercetools.api.models.customer.Customer;
  import com.commercetools.api.models.customer.CustomerPagedQueryResponse;

  import java.time.LocalDate;
  import java.util.ArrayList;
  import java.util.List;
  import java.util.Set;

  public final class CustomerExportService {
        private final ProjectApiRoot apiRoot;
        private final Set<String> suppressedKeys;

        public CustomerExportService(
              ProjectApiRoot apiRoot,
              Set<String> suppressedKeys
        ) {
              this.apiRoot = apiRoot;
              this.suppressedKeys = suppressedKeys;
        }

        public List<Customer> exportCustomers(
              String initialCursor,
              LocalDate minimumBirthDate
        ) {
              List<Customer> results = new ArrayList<>();
              String cursor = initialCursor;

              while (true) {
                    CustomerPagedQueryResponse response = apiRoot.customers()
                          .get()
                          .withWhere("lastModifiedAt > :cursor")
                          .addPredicateVar("cursor", cursor)
                          .withSort("lastModifiedAt asc")
                          .withLimit(100L)
                          .withWithTotal(false)
                          .executeBlocking()
                          .getBody();

                    List<Customer> page = response.getResults();
                    page.stream()
                          .filter(customer -> customer.getDateOfBirth() != null)
                          .filter(customer -> customer.getDateOfBirth()
                                .isAfter(minimumBirthDate))
                          .filter(customer -> customer.getCustomerGroup() == null)
                          .filter(customer -> customer.getKey() != null)
                          .filter(customer -> !suppressedKeys.contains(customer.getKey()))
                          .forEach(results::add);

                    if (page.size() < 100) break;
                    cursor = page.get(page.size() - 1).getLastModifiedAt().toString();
              }

              return results;
        }
  } 
  ```
</MultiCodeBlock>

For production cursor pagination, define how the integration handles multiple resources with the same `lastModifiedAt` value and changes that occur during the export window. A bounded export window or persisted compound cursor prevents skipped or repeated records.

### Compare two working queries

Both implementations return recently modified Customers. Decide which one you would approve for a large and growing Project, and explain why.

#### Option A

```typescript
await apiRoot
   .customers()
   .get({
      queryArgs: {
         where: 'lastModifiedAt > :cursor',
         'var.cursor': cursor,
         sort: 'lastModifiedAt asc',
         limit: 100,
         withTotal: false,
      },
   })
   .execute();
```

```java
apiRoot.customers()
      .get()
      .withWhere("lastModifiedAt > :cursor")
      .addPredicateVar("cursor", cursor)
      .withSort("lastModifiedAt asc")
      .withLimit(100L)
      .withWithTotal(false)
      .executeBlocking(); 
```

#### Option B

```typescript
await apiRoot
   .customers()
   .get({
      queryArgs: {
         where: 'locale = "en"',
         sort: 'email asc',
         limit: 100,
      },
   })
   .execute();
```

```java
apiRoot.customers()
      .get()
      .withWhere("locale = \"en\"")
      .withSort("email asc")
      .withLimit(100L)
      .executeBlocking(); 
```

Approve **Option A**. Its time condition limits the result set as the Project grows, and the query filters and sorts on the same field. It also avoids total calculation and supports cursor-based processing.

Option B is valid, but a locale can match a large proportion of Customers. It sorts on a different field and calculates the total by default. These choices make it less suitable for a recurring export over a large dataset.

## Review 3: A GraphQL implementation

The module signs up a Customer, updates the Customer's first name, and retrieves the Customer profile. The operations are sent as raw GraphQL so the same document can be used from either SDK.

This review has **three findings**. Identify the schema problem in each operation and the operational problem in the update flow.

```typescript
import { apiRoot } from '../impl/apiClient.js';

const signUp = `
   mutation CreateCustomer {
      createCustomer(
         draft: {
            key: "jane-doe-customer"
            email: "jane.doe@example.com"
            password: "change-me"
         }
      ) {
         id
         version
      }
   }
`;

const update = `
   mutation UpdateCustomer {
      updateCustomer(
         key: "jane-doe-customer"
         version: 1
         actions: [{ setFirstName: { firstName: "Jane" } }]
      ) {
         id
         version
      }
   }
`;

const profile = `
   query CustomerProfile {
      customer(key: "jane-doe-customer") {
         id
         email
         phone
      }
   }
`;

for (const query of [signUp, update, profile]) {
   await apiRoot.graphql().post({ body: { query } }).execute();
}
```

```java
import com.commercetools.api.client.ProjectApiRoot;
import com.commercetools.api.models.graph_ql.GraphQLRequest;

import java.util.List;

public final class CustomerGraphQlService {
      private final ProjectApiRoot apiRoot;

      public CustomerGraphQlService(ProjectApiRoot apiRoot) {
            this.apiRoot = apiRoot;
      }

      public void run() {
            String signUp = """
                  mutation CreateCustomer {
                     createCustomer(
                        draft: {
                           key: "jane-doe-customer"
                           email: "jane.doe@example.com"
                           password: "change-me"
                        }
                     ) { id version }
                  }
                  """;

            String update = """
                  mutation UpdateCustomer {
                     updateCustomer(
                        key: "jane-doe-customer"
                        version: 1
                        actions: [{ setFirstName: { firstName: "Jane" } }]
                     ) { id version }
                  }
                  """;

            String profile = """
                  query CustomerProfile {
                     customer(key: "jane-doe-customer") {
                        id
                        email
                        phone
                     }
                  }
                  """;

            for (String query : List.of(signUp, update, profile)) {
                  apiRoot.graphql()
                        .post(GraphQLRequest.builder().query(query).build())
                        .executeBlocking();
            }
      }
} 
```

### 3.1 The Customer creation mutation does not exist

**Classification**: API-invalid.

The GraphQL schema has no `createCustomer` mutation. Use `customerSignUp`, which returns a `CustomerSignInResult`. Select the created Customer inside its `customer` field.

### 3.2 The update uses a constant version

**Classification**: operational defect.

The update succeeds only while the Customer version is `1`. Use the version returned by the preceding sign-up or read operation. A stale version produces a concurrent modification error.

### 3.3 Customer has no phone field

**Classification**: API-invalid.

`phone` is not a field on the GraphQL `Customer` type. It is available on an Address. Select `defaultShippingAddress { phone }` or another appropriate address field.

This is the same underlying modeling error as Review 1: an implementation invented a phone concept on Customer instead of reading the Address model.

Validate the complete operation with `commercetools-graphql-validate` before adding SDK execution code. The corrected implementation then passes the returned version into the update operation.

```typescript
import { apiRoot } from '../impl/apiClient.js';

const signUpMutation = `
   mutation SignUpCustomer($draft: CustomerSignUpDraft!) {
      customerSignUp(draft: $draft) {
         customer { key version }
      }
   }
`;

const updateMutation = `
   mutation UpdateCustomer($key: String!, $version: Long!) {
      updateCustomer(
         key: $key
         version: $version
         actions: [{ setFirstName: { firstName: "Jane" } }]
      ) { key version }
   }
`;

const profileQuery = `
   query CustomerProfile($key: String!) {
      customer(key: $key) {
         email
         defaultShippingAddress { phone }
      }
   }
`;

async function runCustomerFlow() {
   try {
      const signUpResponse = await apiRoot
         .graphql()
         .post({
            body: {
               query: signUpMutation,
               variables: {
                  draft: {
                     key: 'jane-doe-customer',
                     email: 'jane.doe@example.com',
                     password: 'change-me',
                  },
               },
            },
         })
         .execute();

      const customer = signUpResponse.body.data.customerSignUp.customer;

      await apiRoot
         .graphql()
         .post({
            body: {
               query: updateMutation,
               variables: {
                  key: customer.key,
                  version: customer.version,
               },
            },
         })
         .execute();

      return apiRoot
         .graphql()
         .post({
            body: {
               query: profileQuery,
               variables: { key: customer.key },
            },
         })
         .execute();
   } catch (error) {
      console.error('The Customer GraphQL flow failed.', error);
      throw error;
   }
}

await runCustomerFlow();
```

```java
import com.commercetools.api.client.ProjectApiRoot;
import com.commercetools.api.models.graph_ql.GraphQLRequest;
import com.commercetools.api.models.graph_ql.GraphQLResponse;
import com.commercetools.api.models.graph_ql.GraphQLVariablesMapBuilder;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public final class CustomerGraphQlService {
      private final ProjectApiRoot apiRoot;
      private final ObjectMapper mapper = new ObjectMapper().findAndRegisterModules();

      public CustomerGraphQlService(ProjectApiRoot apiRoot) {
            this.apiRoot = apiRoot;
      }

      public GraphQLResponse runCustomerFlow() {
            String signUpMutation = """
                  mutation SignUpCustomer($draft: CustomerSignUpDraft!) {
                     customerSignUp(draft: $draft) {
                        customer { key version }
                     }
                  }
                  """;
            String updateMutation = """
                  mutation UpdateCustomer($key: String!, $version: Long!) {
                     updateCustomer(
                        key: $key
                        version: $version
                        actions: [{ setFirstName: { firstName: "Jane" } }]
                     ) { key version }
                  }
                  """;
            String profileQuery = """
                  query CustomerProfile($key: String!) {
                     customer(key: $key) {
                        email
                        defaultShippingAddress { phone }
                     }
                  }
                  """;

            try {
                  GraphQLResponse signUpResponse = execute(GraphQLRequest.builder()
                        .query(signUpMutation)
                        .variables(GraphQLVariablesMapBuilder.of()
                              .addValue("draft", mapper.readTree("""
                                    {
                                       "key": "jane-doe-customer",
                                       "email": "jane.doe@example.com",
                                       "password": "change-me"
                                    }
                                    """))
                              .build())
                        .build());

                  JsonNode signUpData = mapper.valueToTree(signUpResponse.getData());
                  JsonNode customer = signUpData.path("customerSignUp").path("customer");
                  String customerKey = customer.path("key").asText();
                  long customerVersion = customer.path("version").asLong();

                  execute(GraphQLRequest.builder()
                        .query(updateMutation)
                        .variables(GraphQLVariablesMapBuilder.of()
                              .addValue("key", customerKey)
                              .addValue("version", customerVersion)
                              .build())
                        .build());

                  return execute(GraphQLRequest.builder()
                        .query(profileQuery)
                        .variables(GraphQLVariablesMapBuilder.of()
                              .addValue("key", customerKey)
                              .build())
                        .build());
            } catch (Exception exception) {
                  System.err.println(
                        "The Customer GraphQL flow failed: " + exception.getMessage()
                  );
                  throw new IllegalStateException(exception);
            }
      }

      private GraphQLResponse execute(GraphQLRequest request) {
            return apiRoot.graphql()
                  .post(request)
                  .executeBlocking()
                  .getBody();
      }
}  
```

## Review 4: A failing Customer import

The pull request includes a bulk Customer import that never reaches a clean result. Download the existing [Customer data](/learning-developer-essentials/downloads/import-api-customer-data-challenge.json), submit it to a Customer Import Container, and inspect the resulting Import Operations.

Your success criterion is a clean import of all ten Customers. This review has no fixed finding count because one Customer can contain overlapping schema errors and unresolved references.

Review both the data and the target Project. In particular, determine which referenced Customer Groups, Stores, and Custom Type must exist before every Import Operation can reach `imported`.

Use the Import Operation `state`, `errors`, and `unresolvedReferences` fields as the authoritative diagnosis. The sample contains several categories of problems:

- Invalid field values: a non-ISO `dateOfBirth`, a malformed email address, invalid country codes, a wrong-type Custom Field value, and over-length keys.
- Invalid reference shapes, including incorrect or empty `typeId` values.
- A duplicate Customer email that conflicts with another resource in the same import context.
- References to Customer Groups and Stores that must exist with the specified keys.
- A reference to a Custom Type with the key `legacyCustomer`. Its `boolean-field` definition must accept a Boolean value and be available on Customers.

Correct schema errors in the file, create the required Project dependencies, resubmit the affected resources, and query the Import Operations again. Do not treat an accepted Import Request as a successful import. Every operation must reach `imported`.

The import is complete only when all ten resources have a successful state and no unresolved references remain.

## Write your review checklist

Turn the findings from all four reviews into a checklist you can reuse before approving commercetools code. Group the checklist under the following headings:

- Identifiers and versioning
- Authorization and credentials
- Query shape and performance
- Schema and data accuracy

Write the checks as actions. Each item should tell a reviewer what to inspect and which evidence confirms it. Do not copy the answers verbatim. Generalize them so the checklist also applies to other commercetools resources.

For broader production review concerns such as dependency changes and server-side enforcement, see the [production security checklist](/learning-developer-essentials/dev-tooling/build-with-ai-security-best-practices.md#reviewing-what-the-agent-writes). Keep your challenge checklist focused on the API and SDK concepts covered in this learning path.

After writing your checklist, compare it with the following example and add any checks that you missed.

### Identifiers and versioning

- Confirm that application code uses a stable `key`, `sku`, or `slug` instead of a Project-specific `id` where the resource supports one.
- Fetch the current resource `version` before an update or deletion.
- Check that concurrent modification handling uses the latest version and does not hide or retry unrelated errors.

### Authorization and credentials

- Confirm that the API Client has only the scopes required for the endpoints and operations used by the implementation.
- Check that credentials come from protected environment configuration and are not committed, logged, or returned to a client application.
- Verify that error output does not expose access tokens, client secrets, or sensitive request headers.

### Query shape and performance

- Confirm that every field in a Query Predicate is listed as queryable for that resource.
- Prefer positive, selective conditions and a bounded time range over negation or conditions that match most resources.
- When paginating large result sets, avoid large offsets, sort on the cursor field, and set `withTotal` to `false` when the total is not required.
- Use input variables for dynamic values and split value sets that exceed documented recommendations.

### Schema and data accuracy

- Confirm resource fields, update actions, required values, and reference shapes against the current API reference or schema.
- Validate GraphQL operations and REST request shapes before execution, then test authorization, Project configuration, and behavior separately.
- Check that a full-value replacement preserves every field that must remain on the resource.
- For asynchronous operations, inspect the final operation state, errors, and unresolved references instead of treating request acceptance as completion.

## Key Takeaways

- Verify resource fields and update actions against the current API model.
- Fetch the current resource version and use stable identifiers before updating data.
- Review OAuth scopes, credentials, query performance, and error handling as part of correctness.
- Treat validation and request acceptance as intermediate checks, not proof that an implementation works.
- Use the reference documentation and schemas to verify code regardless of how it was produced.

## Related pages

- [Area overview page with navigation](/learning-developer-essentials.md)
- [Previous page: Overview](/learning-developer-essentials/challenge/overview.md)
- [Search documentation and API specs](/search.md)