[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of salesforce-connector/node/service/SalesforceOpportunityService.ts from the salesforce-connector VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { AxiosInstance } from 'axios'

import type { AbandonedCartResponse } from '../schemas/AbandonedCartResponse'
import type { Item } from '../schemas/orderVtexResponse'
import type { ParameterList } from '../schemas/Parameter'
import { Result } from '../schemas/Result'
import {
  ACCOUNT_ID,
  CODE_STATUS_200,
  CODE_STATUS_201,
  LIST_PRICE_ID,
  PATH_API_SALESFORCE,
  PATH_ASSOCIATE_OPPORTUNITY_PRODUCT_SALESFORCE,
  PATH_OPPORTUNITY_SALESFORCE,
} from '../utils/constans'

export default class SalesforceOpportunityService {
  public createOpportunity = async (
    request: AbandonedCartResponse,
    parameterList: ParameterList,
    userSalesforceId: string,
    http: AxiosInstance
  ) => {
    const fullDate = new Date(request.rclastsessiondate)
    const date = `${fullDate.getFullYear()}-${
      fullDate.getMonth() + 1
    }-${fullDate.getDate()}`

    const accountId = parameterList.get(ACCOUNT_ID)
    const listPriceId = parameterList.get(LIST_PRICE_ID)
    const body = {
      Name: `${request.firstName} ${request.lastName}`,
      Description: `Abandoned cart by ${request.firstName} ${request.lastName}`,
      StageName: 'Abandoned Cart',
      CloseDate: date,
      Pricebook2Id: listPriceId,
      AccountId: accountId,
      OwnerId: userSalesforceId,
    }

    const url = `${PATH_API_SALESFORCE}${PATH_OPPORTUNITY_SALESFORCE}`

    try {
      const { data, status } = await http.post(url, body)

      if (status === CODE_STATUS_200 || status === CODE_STATUS_201) {
        return Result.TaskOk(data)
      }

      return Result.TaskResult(
        status,
        'Opportunity could not be created in salesforce',
        data
      )
    } catch (error) {
      return Result.TaskResult(
        500,
        'An error occurred when creating opportunity in salesforce',
        error
      )
    }
  }

  public associateOpportunityAndProduct = async (
    opportunityId: string,
    pricebookEntryId: string,
    item: Item,
    http: AxiosInstance
  ): Promise<Result> => {
    const body = {
      OpportunityId: opportunityId,
      PricebookEntryId: pricebookEntryId,
      quantity: item.quantity,
      unitPrice: item.price / 100,
    }

    const url = `${PATH_API_SALESFORCE}${PATH_ASSOCIATE_OPPORTUNITY_PRODUCT_SALESFORCE}`

    try {
      const { data, status } = await http.post(url, body)

      if (status === CODE_STATUS_200 || status === CODE_STATUS_201) {
        return Result.TaskOk(data)
      }

      return Result.TaskResult(
        status,
        'OpportunityLineItem could not be created in salesforce',
        data
      )
    } catch (error) {
      return Result.TaskResult(
        500,
        'An error occurred when creating OpportunityLineItem in salesforce',
        error
      )
    }
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of salesforce-connector/node/service/CreateEntitiesMasterDataV2Service.ts from the salesforce-connector VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { AxiosInstance } from 'axios'

import { Result } from '../schemas/Result'
import {
  CODE_STATUS_200,
  CODE_STATUS_201,
  CODE_STATUS_204,
  CODE_STATUS_500,
  ENTITY_ORDER_V2,
  ENTITY_PARAMETER_V2,
  ENTITY_PRICEBOOKENTRY_V2,
} from '../utils/constans'

export default class CreateEntitiesMasterDataV2Service {
  public createEntity = async (
    accountVtex: string,
    http: AxiosInstance
  ): Promise<Result> => {
    try {
      const request = [
        {
          dataEntityName: ENTITY_PARAMETER_V2,
          schemaName: 'parameterSchema',
          body: {
            properties: {
              description: {
                type: 'string',
              },
              groupName: {
                type: 'string',
              },
              parameterValue: {
                type: 'string',
              },
            },
          },
        },
        {
          dataEntityName: ENTITY_ORDER_V2,
          schemaName: 'orderSalesforceSchema',
          body: {
            properties: {
              idSfc: {
                type: 'string',
              },
              statusOrder: {
                type: 'string',
              },
              updateDate: {
                type: 'string',
              },
            },
          },
        },
        {
          dataEntityName: ENTITY_PRICEBOOKENTRY_V2,
          schemaName: 'pricebookEntrySchema',
          body: {
            properties: {
              priceBookEntryId: {
                type: 'string',
              },
            },
          },
        },
      ]

      request.forEach(async (element) => {
        const response = await http.put(
          `http://${accountVtex}.myvtex.com/api/dataentities/${element.dataEntityName}/schemas/${element.schemaName}`,
          element.body
        )

        if (
          response.status === CODE_STATUS_200 ||
          response.status === CODE_STATUS_201 ||
          response.status === CODE_STATUS_204
        ) {
          Result.TaskOk(`Entity ${element.dataEntityName} registered in MTDT`)
        } else {
          Result.TaskResult(
            response.status,
            `The ${element.dataEntityName} was already created in MTDT and had no modifications`,
            response.data
          )
        }
      })

      return Result.TaskOk('Entities registered in MTDT')
    } catch (error) {
      return Result.TaskResult(
        CODE_STATUS_500,
        'An error has occurred in createEntity',
        error
      )
    }
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of salesforce-connector/node/service/SalesforceConfigurationService.ts from the salesforce-connector VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { AxiosInstance } from 'axios'

import { Result } from '../schemas/Result'
import {
  CODE_STATUS_200,
  CODE_STATUS_201,
  PATH_ACCOUNT_SALESFORCE,
  PATH_API_SALESFORCE,
  PATH_CUSTOMFIELD_SALESFORCE,
  PATH_FIELDS_ORDER_SALESFORCE,
  PATH_PRICEBOOK2_SALESFORCE,
} from '../utils/constans'

export default class SalesforceConfigurationService {
  public createPricebook = async (http: AxiosInstance) => {
    const newPricebook = {
      Name: 'Lista de Precio VTEX',
      Description: 'Lista de Precio VTEX',
      IsActive: true,
    }

    const url = `${PATH_API_SALESFORCE}${PATH_PRICEBOOK2_SALESFORCE}`

    try {
      const { data, status } = await http.post(url, newPricebook)

      if (status === CODE_STATUS_200 || status === CODE_STATUS_201) {
        return Result.TaskOk(data)
      }

      return Result.TaskResult(
        status,
        'Pricebook could not be created in salesforce',
        data
      )
    } catch (error) {
      return Result.TaskResult(
        500,
        'An error occurred when creating pricebook in salesforce',
        error
      )
    }
  }

  public createAccount = async (http: AxiosInstance): Promise<Result> => {
    const newAccount = {
      Name: 'VTEX Account',
      Industry: 'VTEX',
      Phone: '545455484',
      Website: 'www.test.myvtex.com',
    }

    const url = `${PATH_API_SALESFORCE}${PATH_ACCOUNT_SALESFORCE}`

    try {
      const { data, status } = await http.post(url, newAccount)

      if (status === CODE_STATUS_200 || status === CODE_STATUS_201) {
        return Result.TaskOk(data)
      }

      return Result.TaskResult(
        status,
        'Account could not be created in salesforce',
        data
      )
    } catch (error) {
      return Result.TaskResult(
        500,
        'An error occurred when creating account in salesforce',
        error
      )
    }
  }

  public createCustomField = async (
    http: AxiosInstance,
    access_token: string
  ): Promise<Result> => {
    const orderStatusField = `
      <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
        <s:Header>
          <h:SessionHeader xmlns:h="http://soap.sforce.com/2006/04/metadata"
            xmlns="http://soap.sforce.com/2006/04/metadata"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema">
            <sessionId>${access_token}</sessionId>
          </h:SessionHeader>
        </s:Header>
        <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:xsd="http://www.w3.org/2001/XMLSchema">
          <createMetadata xmlns="http://soap.sforce.com/2006/04/metadata">
            <metadata xsi:type="CustomField">
              <fullName>Order.Order_Status__c</fullName>
              <label>Estado de la orden</label>
              <type>Text</type>
              <length>50</length>
              <required>true</required>
            </metadata>
          </createMetadata>
        </s:Body>
      </s:Envelope>
    `

    const paymentMethodField = `
      <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
        <s:Header>
          <h:SessionHeader xmlns:h="http://soap.sforce.com/2006/04/metadata"
            xmlns="http://soap.sforce.com/2006/04/metadata"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema">
            <sessionId>${access_token}</sessionId>
          </h:SessionHeader>
        </s:Header>
        <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:xsd="http://www.w3.org/2001/XMLSchema">
          <createMetadata xmlns="http://soap.sforce.com/2006/04/metadata">
            <metadata xsi:type="CustomField">
              <fullName>Order.Payment_Method__c</fullName>
              <label>Medio de pago</label>
              <type>Text</type>
              <length>50</length>
              <required>true</required>
            </metadata>
          </createMetadata>
        </s:Body>
      </s:Envelope>
    `

    const discountField = `
      <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
        <s:Header>
          <h:SessionHeader xmlns:h="http://soap.sforce.com/2006/04/metadata"
            xmlns="http://soap.sforce.com/2006/04/metadata"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema">
            <sessionId>${access_token}</sessionId>
          </h:SessionHeader>
        </s:Header>
        <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:xsd="http://www.w3.org/2001/XMLSchema">
          <createMetadata xmlns="http://soap.sforce.com/2006/04/metadata">
            <metadata xsi:type="CustomField">
              <fullName>Order.Discounts__c</fullName>
              <label>Descuentos</label>
              <type>Currency</type>
              <precision>18</precision>
              <scale>2</scale>
              <required>true</required>
            </metadata>
          </createMetadata>
        </s:Body>
      </s:Envelope>
    `

    const promotionNameField = `
      <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
        <s:Header>
          <h:SessionHeader xmlns:h="http://soap.sforce.com/2006/04/metadata"
            xmlns="http://soap.sforce.com/2006/04/metadata"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema">
            <sessionId>${access_token}</sessionId>
          </h:SessionHeader>
        </s:Header>
        <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:xsd="http://www.w3.org/2001/XMLSchema">
          <createMetadata xmlns="http://soap.sforce.com/2006/04/metadata">
            <metadata xsi:type="CustomField">
              <fullName>Order.Promotions__c</fullName>
              <label>Promociones y asociaciones</label>
              <type>TextArea</type>
              <required>true</required>
            </metadata>
          </createMetadata>
        </s:Body>
      </s:Envelope>
    `

    const createdBy = `
      <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
        <s:Header>
          <h:SessionHeader xmlns:h="http://soap.sforce.com/2006/04/metadata"
            xmlns="http://soap.sforce.com/2006/04/metadata"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema">
            <sessionId>${access_token}</sessionId>
          </h:SessionHeader>
        </s:Header>
        <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:xsd="http://www.w3.org/2001/XMLSchema">
          <createMetadata xmlns="http://soap.sforce.com/2006/04/metadata">
            <metadata xsi:type="CustomField">
              <fullName>Order.Created_By__c</fullName>
              <label>Pedido VTEX creado por</label>
              <type>Lookup</type>
              <referenceTo>Contact</referenceTo>
              <relationshipName>Order_CreatedBy_Rel</relationshipName>
              <required>true</required>
              <deleteConstraint>Restrict</deleteConstraint>
            </metadata>
          </createMetadata>
        </s:Body>
      </s:Envelope>
    `

    const shippingType = `
      <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
        <s:Header>
          <h:SessionHeader xmlns:h="http://soap.sforce.com/2006/04/metadata"
            xmlns="http://soap.sforce.com/2006/04/metadata"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema">
            <sessionId>${access_token}</sessionId>
          </h:SessionHeader>
        </s:Header>
        <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:xsd="http://www.w3.org/2001/XMLSchema">
          <createMetadata xmlns="http://soap.sforce.com/2006/04/metadata">
            <metadata xsi:type="CustomField">
              <fullName>Order.Shipping_Type__c</fullName>
              <label>Tipo de envío</label>
              <type>Text</type>
              <length>50</length>
              <required>true</required>
            </metadata>
          </createMetadata>
        </s:Body>
      </s:Envelope>
    `

    const priceList = `
      <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
        <s:Header>
          <h:SessionHeader xmlns:h="http://soap.sforce.com/2006/04/metadata"
            xmlns="http://soap.sforce.com/2006/04/metadata"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema">
            <sessionId>${access_token}</sessionId>
          </h:SessionHeader>
        </s:Header>
        <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:xsd="http://www.w3.org/2001/XMLSchema">
          <createMetadata xmlns="http://soap.sforce.com/2006/04/metadata">
            <metadata xsi:type="CustomField">
              <fullName>OrderItem.Price_List__c</fullName>
              <label>Precio sin descuento</label>
              <type>Currency</type>
              <precision>18</precision>
              <scale>2</scale>
              <required>true</required>
            </metadata>
          </createMetadata>
        </s:Body>
      </s:Envelope>
    `

    const fields = [
      orderStatusField,
      paymentMethodField,
      discountField,
      promotionNameField,
      createdBy,
      shippingType,
      priceList,
    ]

    const url = `${PATH_CUSTOMFIELD_SALESFORCE}`

    try {
      fields.forEach(async (field) => {
        const { data, status } = await http.post(url, field)

        if (status === CODE_STATUS_200 || status === CODE_STATUS_201) {
          return Result.TaskOk(data)
        }

        return Result.TaskResult(
          status,
          'Custom field could not be created in salesforce',
          data
        )
      })

      return Result.TaskOk('Custom fields created successfully')
    } catch (error) {
      return Result.TaskResult(
        500,
        'An error occurred when creating Custom field in salesforce',
        error
      )
    }
  }

  public getFiels = async (
    http: AxiosInstance,
    nameEntity: string
  ): Promise<Result> => {
    const url = `${PATH_API_SALESFORCE}/${nameEntity}${PATH_FIELDS_ORDER_SALESFORCE}`

    try {
      const { data, status } = await http.get(url)

      if (status === CODE_STATUS_200) {
        return Result.TaskOk(data)
      }

      return Result.TaskResult(
        status,
        'Order fields could not be queried in salesforce',
        data
      )
    } catch (error) {
      return Result.TaskResult(
        500,
        'an error occurred while viewing the Order fields',
        error
      )
    }
  }
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of salesforce-connector/node/resolvers/oms/index.ts from the salesforce-connector VTEX app.

[Assistant]
Here's the implementation:

```typescript
export const queries = {
  getOrder: async (
    _: unknown,
    { orderId }: any,
    ctx: Context
  ): Promise<any> => {
    return ctx.clients.omsClient.getOrder(orderId)
  },
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of salesforce-connector/node/resolvers/masterData/index.ts from the salesforce-connector VTEX app.

[Assistant]
Here's the implementation:

```typescript
export const queries = {
  getData: async (_: unknown, { orderId }: any, ctx: Context): Promise<any> => {
    return ctx.clients.masterDataClient.getClient(orderId, 'V1')
  },
}

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of salesforce-connector/node/__tests__/middlewares/getConfigurationHookTest.ts from the salesforce-connector VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { getConfigurationHook } from '../../middlewares/getConfigurationHook'
import type { Parameter } from '../../schemas/Parameter'
import { Result } from '../../schemas/Result'
import { ACCOUNT_ID, LIST_PRICE_ID } from '../../utils/constans'

let mockMasterDataService: any
let mockSalesforceConfigurationService: any

jest.mock('../../service/masterDataService', () =>
  jest.fn().mockImplementation(() => mockMasterDataService)
)

jest.mock('../../service/SalesforceConfigurationService', () =>
  jest.fn().mockImplementation(() => mockSalesforceConfigurationService)
)

describe('getConfigurationHook', () => {
  let ctx: any
  const parameters: Parameter[] = []
  const data: any = { fields: [] }

  beforeEach(() => {
    ctx = {
      vtex: {
        authToken: 'vtexappkey-xxx-xxx-xxx-xxx',
      },
    }
    const parameterListPrice = {
      id: LIST_PRICE_ID,
      parameterValue: 'listPriceId',
    }

    const parameterAccountId = {
      id: ACCOUNT_ID,
      parameterValue: 'accountId',
    }

    parameters.push(parameterListPrice)
    parameters.push(parameterAccountId)

    data.fields = [
      {
        name: 'Order_Status__c',
      },
      {
        name: 'Payment_Method__c',
      },
      {
        name: 'Discounts__c',
      },
      {
        name: 'Promotions__c',
      },
      {
        name: 'Order_Status__c',
      },
    ]
  })

  test('Success to get configuration', async () => {
    mockMasterDataService = {
      getParameters: jest.fn().mockResolvedValue(Result.TaskOk(parameters)),
    }

    mockSalesforceConfigurationService = {
      getFielsOrder: jest.fn().mockResolvedValue(Result.TaskOk(data)),
    }

    const response = await getConfigurationHook(ctx, () => Promise.resolve())

    expect(response).toBeUndefined()
  })

  test('Error to get configuration', async () => {
    mockMasterDataService = {
      getParameters: jest.fn().mockRejectedValue(Result.TaskError('error')),
    }
    const response = await getConfigurationHook(ctx, () => Promise.resolve())

    expect(response).toBeUndefined()
  })
})

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of salesforce-connector/node/__tests__/middlewares/configurationHookTest.ts from the salesforce-connector VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { configurationHook } from '../../middlewares/configurationHook'
import type { Parameter } from '../../schemas/Parameter'
import { Result } from '../../schemas/Result'
import { ACCESS_TOKEN_SALEFORCE } from '../../utils/constans'

let mockCreateEntitiesMasterDataV2Service: any
let mockMasterDataService: any
let mockSalesforceConfigurationService: any
let mockSalesforceClient: any

jest.mock('../../service/CreateEntitiesMasterDataV2Service', () =>
  jest.fn().mockImplementation(() => mockCreateEntitiesMasterDataV2Service)
)
jest.mock('../../service/MasterDataService', () =>
  jest.fn().mockImplementation(() => mockMasterDataService)
)
jest.mock('../../service/SalesforceConfigurationService', () =>
  jest.fn().mockImplementation(() => mockSalesforceConfigurationService)
)
jest.mock('../../service/SalesforceClientService', () =>
  jest.fn().mockImplementation(() => mockSalesforceClient)
)

describe('configurationHook', () => {
  let ctx: any
  const parameters: Parameter[] = []

  beforeEach(() => {
    ctx = {
      vtex: {
        authToken: 'vtexappkey-xxx-xxx-xxx-xxx',
      },
      clients: {
        masterDataClient: {
          createTrigger: jest.fn().mockResolvedValue(Result.TaskOk({})),
        },
      },
    }
    const parameterToken = {
      id: ACCESS_TOKEN_SALEFORCE,
      parameterValue: 'token',
    }

    parameters.push(parameterToken)
  })

  test('Success to execute configuration', async () => {
    mockCreateEntitiesMasterDataV2Service = {
      createEntity: jest.fn().mockResolvedValue(Result.TaskOk({})),
    }
    mockMasterDataService = {
      getParameters: jest.fn().mockResolvedValue(Result.TaskOk(parameters)),
    }
    mockSalesforceConfigurationService = {
      getFielsOrder: jest
        .fn()
        .mockResolvedValue(
          Result.TaskOk({ fields: [{ name: 'Order_Status__c' }] })
        ),
    }
    mockSalesforceClient = {
      login: jest
        .fn()
        .mockResolvedValue(Result.TaskOk({ access_token: 'token' })),
    }
    const response = await configurationHook(ctx, () => Promise.resolve())

    expect(response).toBeUndefined()
  })

  test('Error to execute configuration', async () => {
    mockMasterDataService = {
      getParameters: jest.fn().mockRejectedValue(Result.TaskError('error')),
    }
    const response = await configurationHook(ctx, () => Promise.resolve())

    expect(response).toBeUndefined()
  })
})

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of salesforce-connector/node/__tests__/middlewares/getParametersHookTest.ts from the salesforce-connector VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { getParametersHook } from '../../middlewares/getParametersHook'
import type { Parameter } from '../../schemas/Parameter'
import { Result } from '../../schemas/Result'
import { ACCOUNT_SALESFORCE } from '../../utils/constans'

let mockMasterDataService: any

jest.mock('../../service/masterDataService', () =>
  jest.fn().mockImplementation(() => mockMasterDataService)
)

describe('getParametersHook', () => {
  let ctx: any
  const parameters: Parameter[] = []

  beforeEach(() => {
    ctx = {
      vtex: {
        authToken: 'vtexappkey-xxx-xxx-xxx-xxx',
      },
    }
    const parameter = {
      id: ACCOUNT_SALESFORCE,
      parameterValue: 'token',
    }

    parameters.push(parameter)
  })

  test('Success to get parameters', async () => {
    mockMasterDataService = {
      getParameters: jest.fn().mockResolvedValue(Result.TaskOk(parameters)),
    }

    const response = await getParametersHook(ctx, () => Promise.resolve())

    expect(response).toBeUndefined()
  })

  test('Error to get parameters', async () => {
    mockMasterDataService = {
      getParameters: jest.fn().mockRejectedValue(Result.TaskError('error')),
    }
    const response = await getParametersHook(ctx, () => Promise.resolve())

    expect(response).toBeUndefined()
  })
})

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of salesforce-connector/node/__tests__/middlewares/orderStateTest.ts from the salesforce-connector VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { orderState } from '../../middlewares/orderState'
import type { Parameter } from '../../schemas/Parameter'
import { Result } from '../../schemas/Result'
import { ACCESS_TOKEN_SALEFORCE } from '../../utils/constans'

let mockMasterDataService: any
let mockSalesforceClient: any
let mockSalesforceOrderService: any

jest.mock('../../service/MasterDataService', () =>
  jest.fn().mockImplementation(() => mockMasterDataService)
)
jest.mock('../../service/SalesforceClientService', () =>
  jest.fn().mockImplementation(() => mockSalesforceClient)
)
jest.mock('../../service/SalesforceOrderService', () =>
  jest.fn().mockImplementation(() => mockSalesforceOrderService)
)

describe('orderState', () => {
  let ctx: any
  const parameters: Parameter[] = []

  beforeEach(() => {
    ctx = {
      vtex: {
        authToken: 'vtexappkey-xxx-xxx-xxx-xxx',
      },
      clients: {
        masterDataClient: {
          getClient: jest.fn().mockResolvedValue({
            id: '123456',
            email: 'email',
          }),
          getAddresses: jest.fn().mockResolvedValue({
            id: '123456',
            addressName: 'addressName',
          }),
        },
        omsClient: {
          getOrder: jest.fn().mockResolvedValue({
            clientProfileData: {
              userProfileId: '123456',
            },
          }),
        },
      },
      body: {
        orderId: '123456',
        currentState: 'payment-pending',
        lastState: 'payment-pending',
      },
    }
    const parameterToken = {
      id: ACCESS_TOKEN_SALEFORCE,
      parameterValue: 'token',
    }

    parameters.push(parameterToken)
  })

  test('Create order in Salesforce', async () => {
    mockMasterDataService = {
      getParameters: jest.fn().mockResolvedValue(Result.TaskOk(parameters)),
    }
    mockSalesforceClient = {
      login: jest
        .fn()
        .mockResolvedValue(Result.TaskOk({ access_token: 'token' })),
      get: jest.fn().mockResolvedValue({
        data: {
          records: [
            {
              Id: '123456',
              Email: 'email',
            },
          ],
        },
      }),
      update: jest.fn().mockResolvedValue({
        data: {
          id: '123456',
        },
      }),
    }
    mockSalesforceOrderService = {
      getOrderById: jest.fn().mockResolvedValue(
        Result.TaskOk({
          records: [
            {
              Id: '123456',
            },
          ],
        })
      ),
      updateStatusOrder: jest.fn().mockResolvedValue(
        Result.TaskOk({
          status: 200,
          data: {
            id: '123456',
          },
        })
      ),
    }
    const response = await orderState(ctx, () => Promise.resolve())

    expect(response).toBeUndefined()
  })

  test('Create client in Salesforce', async () => {
    mockMasterDataService = {
      getParameters: jest.fn().mockResolvedValue(Result.TaskOk(parameters)),
    }
    mockSalesforceClient = {
      login: jest
        .fn()
        .mockResolvedValue(Result.TaskOk({ access_token: 'token' })),
      get: jest.fn().mockResolvedValue({
        data: {
          records: [],
        },
      }),
      create: jest.fn().mockResolvedValue({
        data: {
          id: '123456',
        },
      }),
    }
    mockSalesforceOrderService = {
      getOrderById: jest.fn().mockResolvedValue(
        Result.TaskOk({
          records: [
            {
              Id: '123456',
            },
          ],
        })
      ),
      updateStatusOrder: jest.fn().mockResolvedValue(
        Result.TaskOk({
          status: 200,
          data: {
            id: '123456',
          },
        })
      ),
    }
    const response = await orderState(ctx, () => Promise.resolve())

    expect(response).toBeUndefined()
  })

  test('Create order when not found in Salesforce', async () => {
    mockMasterDataService = {
      getParameters: jest.fn().mockResolvedValue(Result.TaskOk(parameters)),
    }
    mockSalesforceClient = {
      login: jest
        .fn()
        .mockResolvedValue(Result.TaskOk({ access_token: 'token' })),
      get: jest.fn().mockResolvedValue({
        data: {
          records: [],
        },
      }),
      create: jest.fn().mockResolvedValue({
        data: {
          id: '123456',
        },
      }),
    }
    mockSalesforceOrderService = {
      getOrderById: jest.fn().mockResolvedValue(
        Result.TaskOk({
          records: [],
        })
      ),
      updateStatusOrder: jest.fn().mockResolvedValue(
        Result.TaskOk({
          status: 200,
          data: {
            id: '123456',
          },
        })
      ),
    }
    const response = await orderState(ctx, () => Promise.resolve())

    expect(response).toBeUndefined()
  })

  test('Error to create order in Salesforce', async () => {
    mockMasterDataService = {
      getParameters: jest.fn().mockRejectedValue(Result.TaskError('Error')),
    }
    const response = await orderState(ctx, () => Promise.resolve())

    expect(response).toBeUndefined()
  })
})

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of salesforce-connector/node/__tests__/middlewares/updateClientHookTest.ts from the salesforce-connector VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { updateClientHook } from '../../middlewares/UpdateClientHook'
import type { Parameter } from '../../schemas/Parameter'
import { Result } from '../../schemas/Result'
import { ACCESS_TOKEN_SALEFORCE } from '../../utils/constans'

let mockMasterDataService: any
let mockSalesforceClient: any

jest.mock('../../service/MasterDataService', () =>
  jest.fn().mockImplementation(() => mockMasterDataService)
)
jest.mock('../../service/SalesforceClientService', () =>
  jest.fn().mockImplementation(() => mockSalesforceClient)
)

jest.mock('co-body', () => ({
  json: jest.fn().mockReturnValue({ email: 'email' }),
}))

describe('orderState', () => {
  let ctx: any
  const parameters: Parameter[] = []

  beforeEach(() => {
    ctx = {
      vtex: {
        authToken: 'vtexappkey-xxx-xxx-xxx-xxx',
      },
      clients: {
        masterDataClient: {
          getClient: jest.fn().mockResolvedValue({
            id: '123456',
            email: 'email',
          }),
          getAddresses: jest.fn().mockResolvedValue({
            id: '123456',
            addressName: 'addressName',
          }),
        },
      },
      req: {
        version: 'V1',
      },
    }
    const parameterToken = {
      id: ACCESS_TOKEN_SALEFORCE,
      parameterValue: 'token',
    }

    parameters.push(parameterToken)
  })

  test('Update client in Salesforce', async () => {
    mockMasterDataService = {
      getParameters: jest.fn().mockResolvedValue(Result.TaskOk(parameters)),
    }
    mockSalesforceClient = {
      login: jest
        .fn()
        .mockResolvedValue(Result.TaskOk({ access_token: 'token' })),
      get: jest.fn().mockResolvedValue({
        data: {
          records: [
            {
              Id: '123456',
              Email: 'email',
            },
          ],
        },
      }),
      update: jest.fn().mockResolvedValue({
        data: {
          records: [
            {
              Id: '123456',
              Email: 'email',
            },
          ],
        },
      }),
    }
    const response = await updateClientHook(ctx, () => Promise.resolve())

    expect(response).toBeUndefined()
  })

  test('Create client when not found in Salesforce', async () => {
    mockMasterDataService = {
      getParameters: jest.fn().mockResolvedValue(Result.TaskOk(parameters)),
    }
    mockSalesforceClient = {
      login: jest
        .fn()
        .mockResolvedValue(Result.TaskOk({ access_token: 'token' })),
      get: jest.fn().mockResolvedValue({
        data: {
          records: [],
        },
      }),
      create: jest.fn().mockResolvedValue({
        data: {
          records: [
            {
              Id: '123456',
              Email: 'email',
            },
          ],
        },
      }),
    }
    const response = await updateClientHook(ctx, () => Promise.resolve())

    expect(response).toBeUndefined()
  })

  test('Error to update client in Salesforce', async () => {
    mockMasterDataService = {
      getParameters: jest.fn().mockRejectedValue(Result.TaskError('error')),
    }
    const response = await updateClientHook(ctx, () => Promise.resolve())

    expect(response).toBeUndefined()
  })
})

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of salesforce-connector/node/__tests__/middlewares/abandonedCartHookTest.ts from the salesforce-connector VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { abandonedCartHook } from '../../middlewares/AbandonedCartHook'
import type { Parameter } from '../../schemas/Parameter'
import { Result } from '../../schemas/Result'
import { ACCESS_TOKEN_SALEFORCE } from '../../utils/constans'

let mockMasterDataService: any
let mockSalesforceClientService: any
let mockSalesforceOpportunityService: any
let mockOpportunityService: any

jest.mock('co-body', () => ({
  json: jest.fn().mockReturnValue({ email: 'email' }),
}))

jest.mock('../../service/masterDataService', () =>
  jest.fn().mockImplementation(() => mockMasterDataService)
)
jest.mock('../../service/SalesforceClientService', () =>
  jest.fn().mockImplementation(() => mockSalesforceClientService)
)
jest.mock('../../service/SalesforceOpportunityService', () =>
  jest.fn().mockImplementation(() => mockSalesforceOpportunityService)
)
jest.mock('../../service/OpportunityService', () =>
  jest.fn().mockImplementation(() => mockOpportunityService)
)

describe('abandonedCartHook', () => {
  let ctx: any
  const parameters: Parameter[] = []

  beforeEach(() => {
    ctx = {
      vtex: {
        authToken: 'vtexappkey-xxx-xxx-xxx-xxx',
      },
      req: {
        email: 'email',
      },
    }
    const parameterToken = {
      id: ACCESS_TOKEN_SALEFORCE,
      parameterValue: 'token',
    }

    parameters.push(parameterToken)
  })

  test('Success execute abandoned cart', async () => {
    mockMasterDataService = {
      getParameters: jest.fn().mockResolvedValue(Result.TaskOk(parameters)),
    }
    mockSalesforceClientService = {
      login: jest
        .fn()
        .mockResolvedValue(Result.TaskOk({ access_token: 'token' })),
      getUser: jest
        .fn()
        .mockResolvedValue(Result.TaskOk({ records: [{ Id: 'id' }] })),
    }
    mockSalesforceOpportunityService = {
      createOpportunity: jest
        .fn()
        .mockResolvedValue(Result.TaskOk({ id: 'id' })),
    }
    mockOpportunityService = {
      processOpporunity: jest
        .fn()
        .mockResolvedValue(Result.TaskOk({ data: 'data' })),
    }
    const response = await abandonedCartHook(ctx, () => Promise.resolve())

    expect(response).toBeUndefined()
  })

  test('Error execute abandoned cart', async () => {
    mockMasterDataService = {
      getParameters: jest.fn().mockRejectedValue(Result.TaskError('error')),
    }
    const response = await abandonedCartHook(ctx, () => Promise.resolve())

    expect(response).toBeUndefined()
  })
})

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of salesforce-connector/node/__tests__/middlewares/addCredentialsHookTest.ts from the salesforce-connector VTEX app.

[Assistant]
Here's the implementation:

```typescript
import { addCredentialsHook } from '../../middlewares/addCredentialsHook'
import type { Parameter } from '../../schemas/Parameter'
import { Result } from '../../schemas/Result'
import { ACCOUNT_SALESFORCE } from '../../utils/constans'

let mockMasterDataService: any
let mockCreateEntitiesMasterDataV2Service: any

jest.mock('co-body', () => ({
  json: jest.fn().mockReturnValue({
    accountSalesforce: 'accountSalesforce',
    clientId: 'clientId',
    clientSecret: 'clientSecret',
  }),
}))

jest.mock('../../service/masterDataService', () =>
  jest.fn().mockImplementation(() => mockMasterDataService)
)
jest.mock('../../service/CreateEntitiesMasterDataV2Service', () =>
  jest.fn().mockImplementation(() => mockCreateEntitiesMasterDataV2Service)
)

describe('addCredentialsHook', () => {
  let ctx: any
  const parameters: Parameter[] = []

  beforeEach(() => {
    ctx = {
      vtex: {
        authToken: 'vtexappkey-xxx-xxx-xxx-xxx',
      },
      clients: {
        masterDataClient: {
          createTrigger: jest.fn().mockResolvedValue({}),
        },
      },
      req: {
        email: 'email',
      },
    }
    const parameter = {
      id: ACCOUNT_SALESFORCE,
      parameterValue: 'token',
    }

    parameters.push(parameter)
  })

  test('Success to add credentials', async () => {
    mockMasterDataService = {
      saveUpdateParameter: jest.fn().mockResolvedValue(Result.TaskOk({})),
    }

    mockCreateEntitiesMasterDataV2Service = {
      createEntity: jest.fn().mockResolvedValue(Result.TaskOk({})),
    }

    const response = await addCredentialsHook(ctx, () => Promise.resolve())

    expect(response).toBeUndefined()
  })

  test('Error to add credentials', async () => {
    mockMasterDataService = {
      saveUpdateParameter: jest
        .fn()
        .mockRejectedValue(Result.TaskError('Error')),
    }

    const response = await addCredentialsHook(ctx, () => Promise.resolve())

    expect(response).toBeUndefined()
  })
})

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of salesforce-connector/node/__tests__/service/SalesforceClientServiceTest.ts from the salesforce-connector VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { AxiosInstance } from 'axios'
import axios from 'axios'

import type { AddressVtexResponse } from '../../schemas/AddressVtexResponse'
import type { ClientVtexResponse } from '../../schemas/ClientVtexResponse'
import SalesforceClient from '../../service/SalesforceClientService'
import type { Parameter } from '../../schemas/Parameter'
import { ParameterList } from '../../schemas/Parameter'
import {
  ACCOUNT_SALESFORCE,
  CLIENT_ID,
  CLIENT_SECRET,
} from '../../utils/constans'

describe('SalesforceClient', () => {
  let service: SalesforceClient
  let client: ClientVtexResponse
  let address: AddressVtexResponse
  let mockAxiosInstance: AxiosInstance
  let parameterList: ParameterList

  beforeEach(() => {
    service = new SalesforceClient()
    mockAxiosInstance = axios.create()
    client = {
      id: 'id',
      firstName: 'firstName',
      lastName: 'lastName',
      document: 'document',
      email: 'email',
      phone: 'phone',
      homePhone: 'homePhone',
      birthDate: 'birthDate',
    }
    address = {
      street: 'street',
      city: 'city',
      state: 'state',
      postalCode: 'postalCode',
      country: 'country',
    }
    const parameterAccountSalesforce: Parameter = {
      id: ACCOUNT_SALESFORCE,
      parameterValue: 'accountSalesforce',
    }

    const parameterClientId: Parameter = {
      id: CLIENT_ID,
      parameterValue: 'clientId',
    }

    const parameterClientSecret: Parameter = {
      id: CLIENT_SECRET,
      parameterValue: 'clientSecret',
    }

    const parameters: Parameter[] = []

    parameters.push(parameterAccountSalesforce)
    parameters.push(parameterClientId)
    parameters.push(parameterClientSecret)
    parameterList = new ParameterList(parameters)
  })
  describe('login', () => {
    test('Success to login in Salesforce', async () => {
      jest.spyOn(mockAxiosInstance, 'post').mockResolvedValue({ status: 201 })
      const response = await service.login(parameterList, mockAxiosInstance)

      expect(response).toEqual({
        status: 200,
        message: 'OK',
        data: undefined,
      })
    })

    test('Success to login without client id and client secret in Salesforce', async () => {
      jest.spyOn(mockAxiosInstance, 'post').mockResolvedValue({ status: 201 })
      parameterList.remove(CLIENT_ID)
      parameterList.remove(CLIENT_SECRET)
      const response = await service.login(parameterList, mockAxiosInstance)

      expect(response).toEqual({
        status: 200,
        message: 'OK',
        data: undefined,
      })
    })

    test('Failure to login in Salesforce', async () => {
      jest.spyOn(mockAxiosInstance, 'post').mockResolvedValue({ status: 500 })
      const response = await service.login(parameterList, mockAxiosInstance)

      expect(response).toEqual({
        status: 500,
        message: 'Could not login to salesforce',
        data: undefined,
      })
    })

    test('Error to login in Salesforce', async () => {
      jest.spyOn(mockAxiosInstance, 'post').mockRejectedValue({ status: 500 })
      const response = await service.login(parameterList, mockAxiosInstance)

      expect(response).toEqual({
        status: 500,
        message: 'An error occurred while logging in',
        data: undefined,
      })
    })
  })

  describe('get', () => {
    test('Get client in Salesforce', async () => {
      jest.spyOn(mockAxiosInstance, 'get').mockResolvedValue({ status: 200 })
      const response = await service.get('', mockAxiosInstance)

      expect(response).toEqual({
        status: 200,
        message: 'OK',
        data: undefined,
      })
    })

    test('Failure to get client in Salesforce', async () => {
      jest.spyOn(mockAxiosInstance, 'get').mockResolvedValue({ status: 404 })
      const response = await service.get('', mockAxiosInstance)

      expect(response).toEqual({
        status: 404,
        message: 'Client could not be queried in salesforce',
        data: undefined,
      })
    })

    test('Error to get client in Salesforce', async () => {
      jest.spyOn(mockAxiosInstance, 'get').mockRejectedValue({ status: 500 })
      const response = await service.get('', mockAxiosInstance)

      expect(response).toEqual({
        status: 500,
        message: 'An error occurred while viewing the client',
        data: undefined,
      })
    })

    test('Get user in Salesforce', async () => {
      jest.spyOn(mockAxiosInstance, 'get').mockResolvedValue({ status: 200 })
      const response = await service.getUser('', mockAxiosInstance)

      expect(response).toEqual({
        status: 200,
        message: 'OK',
        data: undefined,
      })
    })

    test('Failure to get user in Salesforce', async () => {
      jest.spyOn(mockAxiosInstance, 'get').mockResolvedValue({ status: 404 })
      const response = await service.getUser('', mockAxiosInstance)

      expect(response).toEqual({
        status: 404,
        message: 'User could not be queried in salesforce',
        data: undefined,
      })
    })

    test('Error to get user in Salesforce', async () => {
      jest.spyOn(mockAxiosInstance, 'get').mockRejectedValue({ status: 500 })
      const response = await service.getUser('', mockAxiosInstance)

      expect(response).toEqual({
        status: 500,
        message: 'An error occurred while viewing the user',
        data: undefined,
      })
    })

    describe('create', () => {
      test('create client in Salesforce', async () => {
        jest.spyOn(mockAxiosInstance, 'post').mockResolvedValue({ status: 201 })
        const response = await service.create(
          client,
          address,
          mockAxiosInstance
        )

        expect(response).toEqual({
          status: 200,
          message: 'OK',
          data: undefined,
        })
      })

      test('Failure to create client in Salesforce', async () => {
        jest.spyOn(mockAxiosInstance, 'post').mockResolvedValue({ status: 500 })
        const response = await service.create(
          client,
          address,
          mockAxiosInstance
        )

        expect(response).toEqual({
          status: 500,
          message: 'Client could not be created in salesforce',
          data: undefined,
        })
      })

      test('Error to create client in Salesforce', async () => {
        jest.spyOn(mockAxiosInstance, 'post').mockRejectedValue({ status: 500 })
        const response = await service.create(
          client,
          address,
          mockAxiosInstance
        )

        expect(response).toEqual({
          status: 500,
          message: 'An error occurred when creating client in salesforce',
          data: undefined,
        })
      })
    })

    describe('update', () => {
      test('update client in Salesforce', async () => {
        jest
          .spyOn(mockAxiosInstance, 'patch')
          .mockResolvedValue({ status: 200 })
        const response = await service.update(
          client,
          address,
          'id',
          mockAxiosInstance
        )

        expect(response).toEqual({
          status: 200,
          message: 'OK',
          data: undefined,
        })
      })

      test('Failure to update client in Salesforce', async () => {
        jest
          .spyOn(mockAxiosInstance, 'patch')
          .mockResolvedValue({ status: 500 })
        const response = await service.update(
          client,
          address,
          'id',
          mockAxiosInstance
        )

        expect(response).toEqual({
          status: 500,
          message: 'Client could not be updated in salesforce',
          data: undefined,
        })
      })

      test('Error to update client in Salesforce', async () => {
        jest
          .spyOn(mockAxiosInstance, 'patch')
          .mockRejectedValue({ status: 500 })
        const response = await service.update(
          client,
          address,
          'id',
          mockAxiosInstance
        )

        expect(response).toEqual({
          status: 500,
          message: 'An error occurred when updating client in salesforce',
          data: undefined,
        })
      })
    })
  })
})

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of salesforce-connector/node/__tests__/service/SalesforceConfigurationServiceTest.ts from the salesforce-connector VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { AxiosInstance } from 'axios'
import axios from 'axios'

import SalesforceConfigurationService from '../../service/SalesforceConfigurationService'

describe('SalesforceConfigurationService', () => {
  let service: SalesforceConfigurationService
  let mockAxiosInstance: AxiosInstance
  const accessToken = 'access_token'

  beforeEach(() => {
    service = new SalesforceConfigurationService()
    mockAxiosInstance = axios.create()
  })
  describe('createPricebook', () => {
    test('create pricebook in SalesForce', async () => {
      jest.spyOn(mockAxiosInstance, 'post').mockResolvedValue({ status: 201 })
      const response = await service.createPricebook(mockAxiosInstance)

      expect(response).toEqual({
        status: 200,
        message: 'OK',
        data: undefined,
      })
    })

    test('Failed to create pricebook in salesforce', async () => {
      jest.spyOn(mockAxiosInstance, 'post').mockResolvedValue({ status: 500 })
      const response = await service.createPricebook(mockAxiosInstance)

      expect(response).toEqual({
        status: 500,
        message: 'Pricebook could not be created in salesforce',
        data: undefined,
      })
    })

    test('Error to create pricebook in salesforce', async () => {
      jest
        .spyOn(mockAxiosInstance, 'post')
        .mockRejectedValue(new Error('Request failed with status code 400'))
      const response = await service.createPricebook(mockAxiosInstance)

      expect(response).toEqual({
        status: 500,
        message: 'An error occurred when creating pricebook in salesforce',
        data: new Error('Request failed with status code 400'),
      })
    })
  })

  describe('createAccount', () => {
    test('create account in SalesForce', async () => {
      jest.spyOn(mockAxiosInstance, 'post').mockResolvedValue({ status: 201 })
      const response = await service.createAccount(mockAxiosInstance)

      expect(response).toEqual({
        status: 200,
        message: 'OK',
        data: undefined,
      })
    })

    test('Failed to create account in salesforce', async () => {
      jest.spyOn(mockAxiosInstance, 'post').mockResolvedValue({ status: 500 })
      const response = await service.createAccount(mockAxiosInstance)

      expect(response).toEqual({
        status: 500,
        message: 'Account could not be created in salesforce',
        data: undefined,
      })
    })

    test('Error to create account in salesforce', async () => {
      jest
        .spyOn(mockAxiosInstance, 'post')
        .mockRejectedValue(new Error('Request failed with status code 400'))
      const response = await service.createAccount(mockAxiosInstance)

      expect(response).toEqual({
        status: 500,
        message: 'An error occurred when creating account in salesforce',
        data: new Error('Request failed with status code 400'),
      })
    })
  })

  describe('createCustomField', () => {
    test('create custom field in SalesForce', async () => {
      jest.spyOn(mockAxiosInstance, 'post').mockResolvedValue({ status: 201 })
      const response = await service.createCustomField(
        mockAxiosInstance,
        accessToken
      )

      expect(response).toEqual({
        status: 200,
        message: 'OK',
        data: 'Custom fields created successfully',
      })
    })

    test('Failed to create custom field in salesforce', async () => {
      jest.spyOn(mockAxiosInstance, 'post').mockResolvedValue({ status: 500 })
      const response = await service.createCustomField(
        mockAxiosInstance,
        accessToken
      )

      expect(response).toEqual({
        status: 200,
        message: 'OK',
        data: 'Custom fields created successfully',
      })
    })
  })

  describe('getFielsOrder', () => {
    test('get fiels order of SalesForce', async () => {
      jest.spyOn(mockAxiosInstance, 'get').mockResolvedValue({ status: 200 })
      const response = await service.getFielsOrder(mockAxiosInstance)

      expect(response).toEqual({
        status: 200,
        message: 'OK',
        data: undefined,
      })
    })

    test('Failed to get fiels order of SalesForce', async () => {
      jest.spyOn(mockAxiosInstance, 'get').mockResolvedValue({ status: 404 })
      const response = await service.getFielsOrder(mockAxiosInstance)

      expect(response).toEqual({
        status: 404,
        message: 'Order fields could not be queried in salesforce',
        data: undefined,
      })
    })

    test('Error to get fiels order of SalesForce', async () => {
      jest
        .spyOn(mockAxiosInstance, 'get')
        .mockRejectedValue(new Error('Request failed with status code 400'))
      const response = await service.getFielsOrder(mockAxiosInstance)

      expect(response).toEqual({
        status: 500,
        message: 'an error occurred while viewing the Order fields',
        data: new Error('Request failed with status code 400'),
      })
    })
  })
})

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of salesforce-connector/node/__tests__/service/SalesforceOpportunityServiceTest.ts from the salesforce-connector VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { AxiosInstance } from 'axios'
import axios from 'axios'

import SalesforceOpportunityService from '../../service/SalesforceOpportunityService'
import type { AbandonedCartResponse } from '../../schemas/AbandonedCartResponse'
import type { Parameter } from '../../schemas/Parameter'
import { ParameterList } from '../../schemas/Parameter'
import type { Item } from '../../schemas/orderVtexResponse'

describe('SalesforceOpportunityService', () => {
  let service: SalesforceOpportunityService
  let mockAxiosInstance: AxiosInstance
  let request: AbandonedCartResponse
  let parameterList: ParameterList
  let item: Item

  beforeEach(() => {
    service = new SalesforceOpportunityService()
    mockAxiosInstance = axios.create()
    request = {
      email: 'email',
      firstName: 'firstName',
      lastName: 'lastName',
      rclastsessiondate: 'rclastsessiondate',
      items: [],
    }
    const parameter: Parameter = {
      id: 'id',
      parameterValue: 'parameterValue',
    }

    const parameters: Parameter[] = []

    parameters.push(parameter)
    parameterList = new ParameterList(parameters)
    item = {
      id: '',
      productId: '',
      uniqueId: '',
      name: '',
      quantity: 0,
      measurementUnit: '',
      price: 0,
      imageUrl: '',
      refId: '',
      sellingPrice: 0,
    }
  })
  describe('createOpportunity', () => {
    test('create opportunity in Saleforce', async () => {
      jest.spyOn(mockAxiosInstance, 'post').mockResolvedValue({ status: 201 })
      const response = await service.createOpportunity(
        request,
        parameterList,
        'userIdSaleforce',
        mockAxiosInstance
      )

      expect(response).toEqual({
        status: 200,
        message: 'OK',
        data: undefined,
      })
    })

    test('Failed to create opportunity in salesforce', async () => {
      jest.spyOn(mockAxiosInstance, 'post').mockResolvedValue({ status: 500 })
      const response = await service.createOpportunity(
        request,
        parameterList,
        'userIdSaleforce',
        mockAxiosInstance
      )

      expect(response).toEqual({
        status: 500,
        message: 'Opportunity could not be created in salesforce',
        data: undefined,
      })
    })

    test('Error to create opportunity in salesforce', async () => {
      jest
        .spyOn(mockAxiosInstance, 'post')
        .mockRejectedValue(new Error('Request failed with status code 400'))
      const response = await service.createOpportunity(
        request,
        parameterList,
        'userIdSaleforce',
        mockAxiosInstance
      )

      expect(response).toEqual({
        status: 500,
        message: 'An error occurred when creating opportunity in salesforce',
        data: new Error('Request failed with status code 400'),
      })
    })
  })

  describe('associateOpportunityAndProduct', () => {
    test('create associate opportunity and product in Saleforce', async () => {
      jest.spyOn(mockAxiosInstance, 'post').mockResolvedValue({ status: 201 })
      const response = await service.associateOpportunityAndProduct(
        '',
        '',
        item,
        mockAxiosInstance
      )

      expect(response).toEqual({
        status: 200,
        message: 'OK',
        data: undefined,
      })
    })

    test('Failed to create associate opportunity and product in Saleforce', async () => {
      jest.spyOn(mockAxiosInstance, 'post').mockResolvedValue({ status: 500 })
      const response = await service.associateOpportunityAndProduct(
        '',
        '',
        item,
        mockAxiosInstance
      )

      expect(response).toEqual({
        status: 500,
        message: 'OpportunityLineItem could not be created in salesforce',
        data: undefined,
      })
    })

    test('Error to create associate opportunity and product in Saleforce', async () => {
      jest
        .spyOn(mockAxiosInstance, 'post')
        .mockRejectedValue(new Error('Request failed with status code 400'))
      const response = await service.associateOpportunityAndProduct(
        '',
        '',
        item,
        mockAxiosInstance
      )

      expect(response).toEqual({
        status: 500,
        message:
          'An error occurred when creating OpportunityLineItem in salesforce',
        data: new Error('Request failed with status code 400'),
      })
    })
  })
})

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of salesforce-connector/node/__tests__/service/MasterDataServiceTest.ts from the salesforce-connector VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { AxiosInstance } from 'axios'
import axios from 'axios'

import MasterDataService from '../../service/MasterDataService'
import type {
  OrderSalesforce,
  PriceBookEntryOrderSalesforce,
} from '../../schemas/OrderSalesforce'
import type { Parameter } from '../../schemas/Parameter'

describe('MasterDataService', () => {
  let service: MasterDataService
  let mockAxiosInstance: AxiosInstance

  beforeEach(() => {
    service = new MasterDataService()
    mockAxiosInstance = axios.create()
  })
  describe('saveUpdateOrder', () => {
    test('Save or update order in MTDT', async () => {
      jest.spyOn(mockAxiosInstance, 'put').mockResolvedValue({ status: 200 })
      const order: OrderSalesforce = {
        id: 'id',
        idSfc: 'idSfc',
        statusOrder: 'statusOrder',
        updateDate: 'updateDate',
      }

      const response = await service.saveUpdateOrder(
        order,
        'accountVtex',
        mockAxiosInstance
      )

      expect(response).toEqual({
        status: 200,
        message: 'OK',
        data: undefined,
      })
    })

    test('No register order in MTDT', async () => {
      jest.spyOn(mockAxiosInstance, 'put').mockResolvedValue({ status: 404 })
      const order: OrderSalesforce = {
        id: 'id',
        idSfc: 'idSfc',
        statusOrder: 'statusOrder',
        updateDate: 'updateDate',
      }

      const response = await service.saveUpdateOrder(
        order,
        'accountVtex',
        mockAxiosInstance
      )

      expect(response).toEqual({
        status: 404,
        message: 'could not be registered Order in MTDT',
        data: undefined,
      })
    })

    test('Error to register order in MTDT', async () => {
      jest
        .spyOn(mockAxiosInstance, 'put')
        .mockRejectedValue(new Error('Request failed with status code 400'))
      const order: OrderSalesforce = {
        id: 'id',
        idSfc: 'idSfc',
        statusOrder: 'statusOrder',
        updateDate: 'updateDate',
      }

      const response = await service.saveUpdateOrder(
        order,
        'accountVtex',
        mockAxiosInstance
      )

      expect(response).toEqual({
        status: 500,
        message: 'an error has occurred  in saveUpdateOrder',
        data: new Error('Request failed with status code 400'),
      })
    })
  })

  describe('saveUpdateParameter', () => {
    test('Save or update order in MTDT', async () => {
      jest.spyOn(mockAxiosInstance, 'put').mockResolvedValue({ status: 200 })
      const parameter: Parameter = {
        id: 'id',
        parameterValue: 'parameterValue',
      }

      const response = await service.saveUpdateParameter(
        parameter,
        'accountVtex',
        mockAxiosInstance
      )

      expect(response).toEqual({
        status: 200,
        message: 'OK',
        data: undefined,
      })
    })

    test('No register parameter in MTDT', async () => {
      jest.spyOn(mockAxiosInstance, 'put').mockResolvedValue({ status: 404 })
      const parameter: Parameter = {
        id: 'id',
        parameterValue: 'parameterValue',
      }

      const response = await service.saveUpdateParameter(
        parameter,
        'accountVtex',
        mockAxiosInstance
      )

      expect(response).toEqual({
        status: 404,
        message: 'could not be registered Parameters in MTDT',
        data: undefined,
      })
    })

    test('Error to register parameter in MTDT', async () => {
      jest
        .spyOn(mockAxiosInstance, 'put')
        .mockRejectedValue(new Error('Request failed with status code 400'))
      const parameter: Parameter = {
        id: 'id',
        parameterValue: 'parameterValue',
      }

      const response = await service.saveUpdateParameter(
        parameter,
        'accountVtex',
        mockAxiosInstance
      )

      expect(response).toEqual({
        status: 500,
        message: 'an error has occurred  in saveParameters',
        data: new Error('Request failed with status code 400'),
      })
    })
  })

  describe('saveUpdatePriceBookEntry', () => {
    test('Save or update priceBookEntry in MTDT', async () => {
      jest.spyOn(mockAxiosInstance, 'put').mockResolvedValue({ status: 200 })
      const priceBookEntry: PriceBookEntryOrderSalesforce = {
        id: 'id',
        priceBookEntryId: 'priceBookEntryId',
      }

      const response = await service.saveUpdatePriceBookEntry(
        priceBookEntry,
        'accountVtex',
        mockAxiosInstance
      )

      expect(response).toEqual({
        status: 200,
        message: 'OK',
        data: undefined,
      })
    })

    test('No register priceBookEntry in MTDT', async () => {
      jest.spyOn(mockAxiosInstance, 'put').mockResolvedValue({ status: 404 })
      const priceBookEntry: PriceBookEntryOrderSalesforce = {
        id: 'id',
        priceBookEntryId: 'priceBookEntryId',
      }

      const response = await service.saveUpdatePriceBookEntry(
        priceBookEntry,
        'accountVtex',
        mockAxiosInstance
      )

      expect(response).toEqual({
        status: 404,
        message: 'could not be registered PriceBookEntry in MTDT',
        data: undefined,
      })
    })

    test('Error to register priceBookEntry in MTDT', async () => {
      jest
        .spyOn(mockAxiosInstance, 'put')
        .mockRejectedValue(new Error('Request failed with status code 400'))
      const priceBookEntry: PriceBookEntryOrderSalesforce = {
        id: 'id',
        priceBookEntryId: 'priceBookEntryId',
      }

      const response = await service.saveUpdatePriceBookEntry(
        priceBookEntry,
        'accountVtex',
        mockAxiosInstance
      )

      expect(response).toEqual({
        status: 500,
        message: 'an error has occurred  in saveUpdatePriceBookEntry',
        data: new Error('Request failed with status code 400'),
      })
    })
  })

  describe('getParameters', () => {
    test('get parameters from MTDT', async () => {
      jest
        .spyOn(mockAxiosInstance, 'get')
        .mockResolvedValue({ status: 200, data: [{}] })
      const response = await service.getParameters(
        'accontVtex',
        mockAxiosInstance
      )

      expect(response).toEqual({
        status: 200,
        message: 'OK',
        data: [{}],
      })
    })

    test('Failed to get parameters from MTDT', async () => {
      jest.spyOn(mockAxiosInstance, 'get').mockResolvedValue({ status: 404 })
      const response = await service.getParameters(
        'accountVtex',
        mockAxiosInstance
      )

      expect(response).toEqual({
        status: 404,
        message: 'could not be get Parameters in MTDT',
        data: undefined,
      })
    })

    test('Error to get parameters from MTDT', async () => {
      jest
        .spyOn(mockAxiosInstance, 'get')
        .mockRejectedValue(new Error('Request failed with status code 400'))
      const response = await service.getParameters(
        'accountVtex',
        mockAxiosInstance
      )

      expect(response).toEqual({
        status: 500,
        message: 'an error has occurred  in getParameters',
        data: new Error('Request failed with status code 400'),
      })
    })
  })

  describe('getPriceBookEntry', () => {
    test('get priceBookEntry from MTDT', async () => {
      jest
        .spyOn(mockAxiosInstance, 'get')
        .mockResolvedValue({ status: 200, data: [{}] })
      const response = await service.getPriceBookEntry(
        'id',
        'accontVtex',
        mockAxiosInstance
      )

      expect(response).toEqual({
        status: 200,
        message: 'OK',
        data: [{}],
      })
    })

    test('Failed to get priceBookEntry from MTDT', async () => {
      jest.spyOn(mockAxiosInstance, 'get').mockResolvedValue({ status: 404 })
      const response = await service.getPriceBookEntry(
        'id',
        'accountVtex',
        mockAxiosInstance
      )

      expect(response).toEqual({
        status: 404,
        message: 'not found PriceBookEntry in MTDT',
        data: undefined,
      })
    })

    test('Error to get priceBookEntry from MTDT', async () => {
      jest
        .spyOn(mockAxiosInstance, 'get')
        .mockRejectedValue(new Error('Request failed with status code 400'))
      const response = await service.getPriceBookEntry(
        'id',
        'accountVtex',
        mockAxiosInstance
      )

      expect(response).toEqual({
        status: 500,
        message: 'an error has occurred  in PriceBookEntry',
        data: new Error('Request failed with status code 400'),
      })
    })
  })

  describe('getSku', () => {
    test('get sku from MTDT', async () => {
      jest
        .spyOn(mockAxiosInstance, 'get')
        .mockResolvedValue({ status: 200, data: [{}] })
      const response = await service.getSku(
        'skuId',
        'accontVtex',
        mockAxiosInstance
      )

      expect(response).toEqual({
        status: 200,
        message: 'OK',
        data: [{}],
      })
    })

    test('Failed to get sku from MTDT', async () => {
      jest.spyOn(mockAxiosInstance, 'get').mockResolvedValue({ status: 404 })
      const response = await service.getSku(
        'skuId',
        'accountVtex',
        mockAxiosInstance
      )

      expect(response).toEqual({
        status: 404,
        message: 'not found Sku in MTDT',
        data: undefined,
      })
    })

    test('Error to get sku from MTDT', async () => {
      jest
        .spyOn(mockAxiosInstance, 'get')
        .mockRejectedValue(new Error('Request failed with status code 400'))
      const response = await service.getSku(
        'skuId',
        'accountVtex',
        mockAxiosInstance
      )

      expect(response).toEqual({
        status: 500,
        message: 'an error has occurred in Sku',
        data: new Error('Request failed with status code 400'),
      })
    })
  })

  describe('getProduct', () => {
    test('get product from MTDT', async () => {
      jest
        .spyOn(mockAxiosInstance, 'get')
        .mockResolvedValue({ status: 200, data: [{}] })
      const response = await service.getProduct(
        1,
        'accontVtex',
        mockAxiosInstance
      )

      expect(response).toEqual({
        status: 200,
        message: 'OK',
        data: [{}],
      })
    })

    test('Failed to get product from MTDT', async () => {
      jest.spyOn(mockAxiosInstance, 'get').mockResolvedValue({ status: 404 })
      const response = await service.getProduct(
        1,
        'accountVtex',
        mockAxiosInstance
      )

      expect(response).toEqual({
        status: 404,
        message: 'not found Product in MTDT',
        data: undefined,
      })
    })

    test('Error to get product from MTDT', async () => {
      jest
        .spyOn(mockAxiosInstance, 'get')
        .mockRejectedValue(new Error('Request failed with status code 400'))
      const response = await service.getProduct(
        1,
        'accountVtex',
        mockAxiosInstance
      )

      expect(response).toEqual({
        status: 500,
        message: 'an error has occurred in Product',
        data: new Error('Request failed with status code 400'),
      })
    })
  })
})

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of salesforce-connector/node/__tests__/service/OpportunityServiceTest.ts from the salesforce-connector VTEX app.

[Assistant]
Here's the implementation:

```typescript
import OpportunityService from '../../service/OpportunityService'
import type { AbandonedCartResponse } from '../../schemas/AbandonedCartResponse'
import type { Parameter } from '../../schemas/Parameter'
import { ParameterList } from '../../schemas/Parameter'
import { LIST_PRICE_ID } from '../../utils/constans'
import type { Item } from '../../schemas/orderVtexResponse'
import { Result } from '../../schemas/Result'

let mockSalesforceOrderService: any
let mockSalesforceOpportunityService: any
let mockMasterDataService: any
let mockSalesforceClient: any

jest.mock('../../service/SalesforceOrderService', () =>
  jest.fn().mockImplementation(() => mockSalesforceOrderService)
)

jest.mock('../../service/SalesforceOpportunityService', () =>
  jest.fn().mockImplementation(() => mockSalesforceOpportunityService)
)

jest.mock('../../service/masterDataService', () =>
  jest.fn().mockImplementation(() => mockMasterDataService)
)
jest.mock('../../service/SalesforceClientService', () =>
  jest.fn().mockImplementation(() => mockSalesforceClient)
)

describe('OpportunityService', () => {
  let service: OpportunityService
  let opportunity: AbandonedCartResponse
  let parameterList: ParameterList

  beforeEach(() => {
    service = new OpportunityService()
    const item: Item = {
      id: '',
      productId: '',
      uniqueId: '',
      name: '',
      quantity: 0,
      measurementUnit: '',
      price: 0,
      imageUrl: '',
      refId: '',
      sellingPrice: 0,
    }

    opportunity = {
      email: 'email',
      firstName: 'firstName',
      lastName: 'lastName',
      rclastsessiondate: 'rclastsessiondate',
      items: [item],
    }
    const parameterListPrice = {
      id: LIST_PRICE_ID,
      parameterValue: 'LIST_PRICE_ID',
    }

    const parameters: Parameter[] = []

    parameters.push(parameterListPrice)
    parameterList = new ParameterList(parameters)
  })
  describe('processOpporunity', () => {
    test('create opportunity in Salesforce', async () => {
      mockSalesforceOrderService = {
        getProductByExternalId: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({ records: [] })),
        createProduct: jest.fn().mockResolvedValue(Result.TaskOk({ id: 'id' })),
        createPricebookEntry: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({ id: 'id' })),
      }

      mockSalesforceOpportunityService = {
        associateOpportunityAndProduct: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({})),
      }

      mockMasterDataService = {
        saveUpdatePriceBookEntry: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({})),
      }

      mockSalesforceClient = {
        login: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({ access_token: 'token' })),
      }

      const response = await service.processOpporunity(
        opportunity,
        '',
        parameterList,
        '',
        ''
      )

      expect(response).toEqual({
        status: 200,
        message: 'OK',
        data: '',
      })
    })

    test('Failure to list price id in MTDT', async () => {
      parameterList.remove(LIST_PRICE_ID)
      const response = await service.processOpporunity(
        opportunity,
        '',
        parameterList,
        '',
        ''
      )

      expect(response).toEqual({
        status: 500,
        message: 'Parameter not found: STANDARD_PRICEBOOK_ID',
        data: undefined,
      })
    })

    test('Failure to get product by external id in Salesforce', async () => {
      mockSalesforceOrderService = {
        getProductByExternalId: jest
          .fn()
          .mockResolvedValue(Result.TaskError('error')),
      }
      const response = await service.processOpporunity(
        opportunity,
        '',
        parameterList,
        '',
        ''
      )

      expect(response).toEqual({
        status: 500,
        message: 'error',
        data: undefined,
      })
    })

    test('Failure to create product in Salesforce', async () => {
      mockSalesforceOrderService = {
        getProductByExternalId: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({ records: [] })),
        createProduct: jest.fn().mockResolvedValue(Result.TaskError('error')),
      }
      const response = await service.processOpporunity(
        opportunity,
        '',
        parameterList,
        '',
        ''
      )

      expect(response).toEqual({
        status: 500,
        message: 'error',
        data: undefined,
      })
    })

    test('Failure to create pricebookentry in Salesforce', async () => {
      mockSalesforceOrderService = {
        getProductByExternalId: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({ records: [] })),
        createProduct: jest.fn().mockResolvedValue(Result.TaskOk({ id: 'id' })),
        createPricebookEntry: jest
          .fn()
          .mockResolvedValue(Result.TaskError('error')),
      }
      const response = await service.processOpporunity(
        opportunity,
        '',
        parameterList,
        '',
        ''
      )

      expect(response).toEqual({
        status: 500,
        message: 'error',
        data: undefined,
      })
    })

    test('Failure to associate opportunity and product in Salesforce', async () => {
      mockSalesforceOrderService = {
        getProductByExternalId: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({ records: [] })),
        createProduct: jest.fn().mockResolvedValue(Result.TaskOk({ id: 'id' })),
        createPricebookEntry: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({ id: 'id' })),
      }

      mockSalesforceOpportunityService = {
        associateOpportunityAndProduct: jest
          .fn()
          .mockResolvedValue(Result.TaskError('error')),
      }

      mockMasterDataService = {
        saveUpdatePriceBookEntry: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({})),
      }
      const response = await service.processOpporunity(
        opportunity,
        '',
        parameterList,
        '',
        ''
      )

      expect(response).toEqual({
        status: 500,
        message: 'error',
        data: undefined,
      })
    })

    test('Flow when a product exists in Salesforce', async () => {
      mockSalesforceOrderService = {
        getProductByExternalId: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({ records: [{ Id: 'id' }] })),
        updateUnitPricePricebookEntry: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({ id: 'id' })),
      }
      mockMasterDataService = {
        getPriceBookEntry: jest
          .fn()
          .mockResolvedValue(
            Result.TaskOk([{ priceBookEntryId: 'priceBookEntryId' }])
          ),
        updateUnitPricePricebookEntry: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({ id: 'id' })),
      }
      const response = await service.processOpporunity(
        opportunity,
        '',
        parameterList,
        '',
        ''
      )

      expect(response).toEqual({
        status: 500,
        message: 'error',
        data: undefined,
      })
    })

    test('Failure to get pricebookentry in MTDT', async () => {
      mockSalesforceOrderService = {
        getProductByExternalId: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({ records: [{ Id: 'id' }] })),
        updateUnitPricePricebookEntry: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({ id: 'id' })),
        createPricebookEntry: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({ id: 'id' })),
      }

      mockMasterDataService = {
        getPriceBookEntry: jest
          .fn()
          .mockResolvedValue(Result.TaskError('error')),
        saveUpdatePriceBookEntry: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({})),
      }
      const response = await service.processOpporunity(
        opportunity,
        '',
        parameterList,
        '',
        ''
      )

      expect(response).toEqual({
        status: 500,
        message: 'error',
        data: undefined,
      })
    })

    test('Failure to create pricebookentry in Salesforce', async () => {
      mockSalesforceOrderService = {
        getProductByExternalId: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({ records: [{ Id: 'id' }] })),
        updateUnitPricePricebookEntry: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({ id: 'id' })),
        createPricebookEntry: jest
          .fn()
          .mockResolvedValue(Result.TaskError('error')),
      }

      mockMasterDataService = {
        getPriceBookEntry: jest
          .fn()
          .mockResolvedValue(Result.TaskError('error')),
        saveUpdatePriceBookEntry: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({})),
      }
      const response = await service.processOpporunity(
        opportunity,
        '',
        parameterList,
        '',
        ''
      )

      expect(response).toEqual({
        status: 500,
        message: 'error',
        data: undefined,
      })
    })

    test('Error to create opportunity in Salesforce', async () => {
      mockSalesforceOrderService = {
        getProductByExternalId: jest
          .fn()
          .mockRejectedValue(Result.TaskError('error')),
      }
      const response = await service.processOpporunity(
        opportunity,
        '',
        parameterList,
        '',
        ''
      )

      expect(response).toEqual({
        status: 500,
        message: 'an error occurred while processing the completed order',
        data: Result.TaskResult(500, 'error', undefined),
      })
    })
  })
})

```


[System] You are an expert VTEX IO developer. You specialize in building VTEX Store Framework apps, React components, GraphQL APIs, and Node.js services for e-commerce platforms.

[User] Show me the implementation of salesforce-connector/node/__tests__/service/OrderServiceTest.ts from the salesforce-connector VTEX app.

[Assistant]
Here's the implementation:

```typescript
import type { OrderVtexResponse } from '../../schemas/orderVtexResponse'
import type { Parameter } from '../../schemas/Parameter'
import { ParameterList } from '../../schemas/Parameter'
import { Result } from '../../schemas/Result'
import OrderService from '../../service/OrderService'
import { ACCOUNT_ID, LIST_PRICE_ID } from '../../utils/constans'

let mockSalesforceOrderService: any
let mockMasterDataService: any
let mockSalesforceClientService: any

jest.mock('../../service/SalesforceOrderService', () =>
  jest.fn().mockImplementation(() => mockSalesforceOrderService)
)
jest.mock('../../service/MasterDataService', () =>
  jest.fn().mockImplementation(() => mockMasterDataService)
)
jest.mock('../../service/SalesforceClientService', () =>
  jest.fn().mockImplementation(() => mockSalesforceClientService)
)

describe('OrderService', () => {
  let service: OrderService
  let order: OrderVtexResponse
  let parameterList: ParameterList

  beforeEach(() => {
    service = new OrderService()
    order = {
      orderId: 'orderId',
      sequence: '0',
      status: 'status',
      value: 0,
      discounts: 0,
      ratesAndBenefitsData: [
        {
          name: 'name',
        },
      ],
      creationDate: 'creationDate',
      paymentSystemName: 'paymentSystemName',
      items: [
        {
          id: 'id',
          productId: 'productId',
          uniqueId: 'uniqueId',
          name: 'name',
          quantity: 0,
          measurementUnit: 'measurementUnit',
          price: 0,
          imageUrl: 'imageUrl',
          refId: 'refId',
          sellingPrice: 0,
        },
      ],
      clientProfileData: {
        id: 'id',
        firtsName: 'firtsName',
        lastName: 'lastName',
        document: 'document',
        phone: 'phone',
        userProfileId: 'userProfileId',
      },
      address: {
        street: 'street',
        city: 'city',
        state: 'state',
        country: 'country',
        postalCode: 'postalCode',
      },
    }
    const paremeterAccount = {
      id: ACCOUNT_ID,
      parameterValue: 'ACCOUNT_ID',
    }

    const parameterListPrice = {
      id: LIST_PRICE_ID,
      parameterValue: 'LIST_PRICE_ID',
    }

    const parameters: Parameter[] = []

    parameters.push(paremeterAccount)
    parameters.push(parameterListPrice)
    parameterList = new ParameterList(parameters)
  })
  describe('processOrder', () => {
    test('create order in Salesforce', async () => {
      mockSalesforceOrderService = {
        createOrder: jest.fn().mockResolvedValue(Result.TaskOk({ id: 'id' })),
        getProductByExternalId: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({ records: [] })),
        createProduct: jest.fn().mockResolvedValue(Result.TaskOk({ id: 'id' })),
        createPricebookEntry: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({ id: 'id' })),
        associateOrderAndProduct: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({})),
      }
      mockMasterDataService = {
        saveUpdateOrder: jest.fn().mockResolvedValue(Result.TaskOk({})),
        saveUpdatePriceBookEntry: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({})),
      }
      mockSalesforceClientService = {
        login: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({ access_token: 'token' })),
      }
      const response = await service.processOrder(
        order,
        'clientSalesforceId',
        parameterList,
        'authToken',
        'accountVtex'
      )

      expect(response).toEqual({
        status: 200,
        message: 'OK',
        data: '',
      })
    })

    test('Failure to list price id in MTDT', async () => {
      parameterList.remove(LIST_PRICE_ID)
      const response = await service.processOrder(
        order,
        'clientSalesforceId',
        parameterList,
        'authToken',
        'accountVtex'
      )

      expect(response).toEqual({
        status: 500,
        message: 'Parameter not found: STANDARD_PRICEBOOK_ID',
        data: undefined,
      })
    })

    test('Failure to create order in Salesforce', async () => {
      mockSalesforceOrderService = {
        createOrder: jest.fn().mockResolvedValue(Result.TaskError('error')),
      }
      const response = await service.processOrder(
        order,
        'clientSalesforceId',
        parameterList,
        'authToken',
        'accountVtex'
      )

      expect(response).toEqual({
        status: 500,
        message: 'error',
        data: undefined,
      })
    })

    test('Failure to save or update order in MTDT', async () => {
      mockSalesforceOrderService = {
        createOrder: jest.fn().mockResolvedValue(Result.TaskOk({ id: 'id' })),
      }
      mockMasterDataService = {
        saveUpdateOrder: jest.fn().mockResolvedValue(Result.TaskError('error')),
      }
      const response = await service.processOrder(
        order,
        'clientSalesforceId',
        parameterList,
        'authToken',
        'accountVtex'
      )

      expect(response).toEqual({
        status: 500,
        message: 'error',
        data: undefined,
      })
    })

    test('Failure to get product by external id in Salesforce', async () => {
      mockSalesforceOrderService = {
        createOrder: jest.fn().mockResolvedValue(Result.TaskOk({ id: 'id' })),
        getProductByExternalId: jest
          .fn()
          .mockResolvedValue(Result.TaskError('error')),
      }
      mockMasterDataService = {
        saveUpdateOrder: jest.fn().mockResolvedValue(Result.TaskOk({})),
      }
      const response = await service.processOrder(
        order,
        'clientSalesforceId',
        parameterList,
        'authToken',
        'accountVtex'
      )

      expect(response).toEqual({
        status: 500,
        message: 'error',
        data: undefined,
      })
    })

    test('Failure to create product in Salesforce', async () => {
      mockSalesforceOrderService = {
        createOrder: jest.fn().mockResolvedValue(Result.TaskOk({ id: 'id' })),
        getProductByExternalId: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({ records: [] })),
        createProduct: jest.fn().mockResolvedValue(Result.TaskError('error')),
      }
      mockMasterDataService = {
        saveUpdateOrder: jest.fn().mockResolvedValue(Result.TaskOk({})),
      }
      const response = await service.processOrder(
        order,
        'clientSalesforceId',
        parameterList,
        'authToken',
        'accountVtex'
      )

      expect(response).toEqual({
        status: 500,
        message: 'error',
        data: undefined,
      })
    })

    test('Failure to create pricebookentry in Salesforce', async () => {
      mockSalesforceOrderService = {
        createOrder: jest.fn().mockResolvedValue(Result.TaskOk({ id: 'id' })),
        getProductByExternalId: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({ records: [] })),
        createProduct: jest.fn().mockResolvedValue(Result.TaskOk({ id: 'id' })),
        createPricebookEntry: jest
          .fn()
          .mockResolvedValue(Result.TaskError('error')),
      }
      mockMasterDataService = {
        saveUpdateOrder: jest.fn().mockResolvedValue(Result.TaskOk({})),
      }
      const response = await service.processOrder(
        order,
        'clientSalesforceId',
        parameterList,
        'authToken',
        'accountVtex'
      )

      expect(response).toEqual({
        status: 500,
        message: 'error',
        data: undefined,
      })
    })

    test('Failure to associate order and product in Salesforce', async () => {
      mockSalesforceOrderService = {
        createOrder: jest.fn().mockResolvedValue(Result.TaskOk({ id: 'id' })),
        getProductByExternalId: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({ records: [] })),
        createProduct: jest.fn().mockResolvedValue(Result.TaskOk({ id: 'id' })),
        createPricebookEntry: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({ id: 'id' })),
        associateOrderAndProduct: jest
          .fn()
          .mockResolvedValue(Result.TaskError('error')),
      }
      mockMasterDataService = {
        saveUpdateOrder: jest.fn().mockResolvedValue(Result.TaskOk({})),
        saveUpdatePriceBookEntry: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({})),
      }
      const response = await service.processOrder(
        order,
        'clientSalesforceId',
        parameterList,
        'authToken',
        'accountVtex'
      )

      expect(response).toEqual({
        status: 500,
        message: 'error',
        data: undefined,
      })
    })

    test('Flow when a product exists in Salesforce', async () => {
      mockSalesforceOrderService = {
        createOrder: jest.fn().mockResolvedValue(Result.TaskOk({ id: 'id' })),
        getProductByExternalId: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({ records: [{ Id: 'id' }] })),
        updateUnitPricePricebookEntry: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({ id: 'id' })),
        associateOrderAndProduct: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({})),
      }
      mockMasterDataService = {
        saveUpdateOrder: jest.fn().mockResolvedValue(Result.TaskOk({})),
        getPriceBookEntry: jest
          .fn()
          .mockResolvedValue(
            Result.TaskOk([{ id: 'id', priceBookEntryId: 'priceBookEntryId' }])
          ),
      }
      const response = await service.processOrder(
        order,
        'clientSalesforceId',
        parameterList,
        'authToken',
        'accountVtex'
      )

      expect(response).toEqual({
        status: 200,
        message: 'OK',
        data: '',
      })
    })

    test('Flow when a pricebookentry not exists in MTDT', async () => {
      mockSalesforceOrderService = {
        createOrder: jest.fn().mockResolvedValue(Result.TaskOk({ id: 'id' })),
        getProductByExternalId: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({ records: [{ Id: 'id' }] })),
        updateUnitPricePricebookEntry: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({ id: 'id' })),
        createPricebookEntry: jest
          .fn()
          .mockResolvedValue(Result.TaskError('error')),
        associateOrderAndProduct: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({})),
      }
      mockMasterDataService = {
        saveUpdateOrder: jest.fn().mockResolvedValue(Result.TaskOk({})),
        getPriceBookEntry: jest
          .fn()
          .mockResolvedValue(Result.TaskError('error')),
        saveUpdatePriceBookEntry: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({})),
      }
      const response = await service.processOrder(
        order,
        'clientSalesforceId',
        parameterList,
        'authToken',
        'accountVtex'
      )

      expect(response).toEqual({
        status: 500,
        message: 'error',
        data: undefined,
      })
    })

    test('Failure to associate order and product in Salesforce', async () => {
      mockSalesforceOrderService = {
        createOrder: jest.fn().mockResolvedValue(Result.TaskOk({ id: 'id' })),
        getProductByExternalId: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({ records: [{ Id: 'id' }] })),
        updateUnitPricePricebookEntry: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({ id: 'id' })),
        createPricebookEntry: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({ id: 'id' })),
        associateOrderAndProduct: jest
          .fn()
          .mockResolvedValue(Result.TaskError('error')),
      }
      mockMasterDataService = {
        saveUpdateOrder: jest.fn().mockResolvedValue(Result.TaskOk({})),
        getPriceBookEntry: jest
          .fn()
          .mockResolvedValue(Result.TaskError('error')),
        saveUpdatePriceBookEntry: jest
          .fn()
          .mockResolvedValue(Result.TaskOk({})),
      }
      const response = await service.processOrder(
        order,
        'clientSalesforceId',
        parameterList,
        'authToken',
        'accountVtex'
      )

      expect(response).toEqual({
        status: 500,
        message: 'error',
        data: undefined,
      })
    })

    test('Error to create order in Salesforce', async () => {
      mockSalesforceOrderService = {
        createOrder: jest.fn().mockRejectedValue(Result.TaskError('error')),
      }
      const response = await service.processOrder(
        order,
        'clientSalesforceId',
        parameterList,
        'authToken',
        'accountVtex'
      )

      expect(response).toEqual({
        status: 500,
        message: 'an error occurred while processing the completed order',
        data: Result.TaskResult(500, 'error', undefined),
      })
    })
  })
})

```