Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Weekly Release dev-main-13-02-24 #990

Merged
merged 2 commits into from
Feb 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1139,6 +1139,7 @@ Object {
"getOrderItemAvailableActivities": [Function],
"getOrderReturnOptions": [Function],
"getOrderShippingAddressChangeRequests": [Function],
"getPackagingOptions": [Function],
"getPaymentIntent": [Function],
"getPaymentIntentCharge": [Function],
"getPaymentIntentInstrument": [Function],
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { rest, type RestHandler } from 'msw';
import type { PackagingOption } from '../types/index.js';

const path = '/api/checkout/v1/packagingOptions';

const fixtures = {
success: (response: PackagingOption[]): RestHandler =>
rest.get(path, (_req, res, ctx) =>
res(ctx.status(200), ctx.json(response)),
),
failure: (): RestHandler =>
rest.get(path, (_req, res, ctx) =>
res(ctx.status(404), ctx.json({ message: 'stub error' })),
),
};

export default fixtures;
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`checkout client getPackagingOptions should receive a client request error 1`] = `
Object {
"code": "-1",
"message": "stub error",
"name": "AxiosError",
"status": 404,
"transportLayerErrorCode": "ERR_BAD_REQUEST",
}
`;
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,7 @@ describe('checkout client', () => {
hadUnavailableItems: true,
isGuestUser: true,
shippingMode: ShippingMode.ByMerchant,
customerId: 123,
},
shippingOptions: [
{
Expand Down
38 changes: 38 additions & 0 deletions packages/client/src/checkout/__tests__/getPackagingOptions.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import * as checkoutClient from '../index.js';
import { mockPackagingOptionsResponse } from 'tests/__fixtures__/checkout/packagingOptions.fixtures.mjs';
import { type PackagingOption } from '../types/index.js';
import client from '../../helpers/client/index.js';
import fixtures from '../__fixtures__/getPackagingOptions.fixtures.js';
import mswServer from '../../../tests/mswServer.js';

describe('checkout client', () => {
const expectedConfig = undefined;

beforeEach(() => jest.clearAllMocks());

describe('getPackagingOptions', () => {
const spy = jest.spyOn(client, 'get');
const query = { channelCode: 'code' };
const urlToBeCalled = `/checkout/v1/packagingOptions?channelCode=${query.channelCode}`;

it('should handle a client request successfully', async () => {
const response: PackagingOption[] = mockPackagingOptionsResponse;

mswServer.use(fixtures.success(response));

await expect(
checkoutClient.getPackagingOptions(query),
).resolves.toStrictEqual(response);
expect(spy).toHaveBeenCalledWith(urlToBeCalled, expectedConfig);
});

it('should receive a client request error', async () => {
mswServer.use(fixtures.failure());

await expect(
checkoutClient.getPackagingOptions(query),
).rejects.toMatchSnapshot();
expect(spy).toHaveBeenCalledWith(urlToBeCalled, expectedConfig);
});
});
});
22 changes: 22 additions & 0 deletions packages/client/src/checkout/getPackagingOptions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { adaptError } from '../helpers/client/formatError.js';
import client from '../helpers/client/index.js';
import join from 'proper-url-join';
import type { GetPackagingOptions } from './types/index.js';

/**
* Method responsible for loading the packaging options.
*
* @param query - Query params.
* @param config - Custom configurations to send to the client instance (axios).
*
* @returns Promise that will resolve when the call to the endpoint finishes.
*/
const getPackagingOptions: GetPackagingOptions = (query, config) =>
client
.get(join('/checkout/v1/packagingOptions', { query }), config)
.then(response => response.data)
.catch(error => {
throw adaptError(error);
});

export default getPackagingOptions;
1 change: 1 addition & 0 deletions packages/client/src/checkout/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export { default as getCheckoutSession } from './getCheckoutSession.js';
export { default as getCheckoutSessionCharge } from './getCheckoutSessionCharge.js';
export { default as getCheckoutSessionTags } from './getCheckoutSessionTags.js';
export { default as getCollectPoints } from './getCollectPoints.js';
export { default as getPackagingOptions } from './getPackagingOptions.js';
export { default as patchCheckoutOrder } from './patchCheckoutOrder.js';
export { default as patchCheckoutOrderDeliveryBundles } from './patchCheckoutOrderDeliveryBundles.js';
export { default as patchCheckoutOrderDeliveryBundleUpgrades } from './patchCheckoutOrderDeliveryBundleUpgrades.js';
Expand Down
3 changes: 3 additions & 0 deletions packages/client/src/checkout/types/checkoutOrder.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type {
import type { CheckoutOrderItem, CheckoutOrderMerchant } from './index.js';
import type { CustomerTypeLegacy } from '../../orders/types/order.types.js';
import type { MerchantLocation } from '../../merchantsLocations/types/merchantLocation.types.js';
import type { Metadata } from '../../types/index.js';
import type { PaymentIntent } from '../../payments/index.js';
import type { PromotionEvaluationId } from '../../promotionEvaluations/index.js';

Expand Down Expand Up @@ -78,4 +79,6 @@ export type CheckoutOrder = {
shippingMode: ShippingMode;
paymentIntentId?: PaymentIntent['id'];
promotionEvaluationId?: PromotionEvaluationId;
customerId: number;
metadata?: Metadata;
};
2 changes: 2 additions & 0 deletions packages/client/src/checkout/types/checkoutOrderItem.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type {
Brand,
CheckoutOrderItemStatus,
Color,
Metadata,
OrderItemCreationChannelLegacy,
Price,
Product,
Expand Down Expand Up @@ -77,4 +78,5 @@ export type CheckoutOrderItem = {
subTotalOriginalAmount: number;
};
selectedSaleIntent?: SaleIntent & string;
metadata?: Metadata;
};
11 changes: 11 additions & 0 deletions packages/client/src/checkout/types/getPackagingOptions.types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import type { Config } from '../../types/index.js';
import type { PackagingOption } from './index.js';

export type GetPackagingOptionsQuery = {
channelCode: string;
};

export type GetPackagingOptions = (
query?: GetPackagingOptionsQuery,
config?: Config,
) => Promise<PackagingOption[]>;
2 changes: 2 additions & 0 deletions packages/client/src/checkout/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ export * from './getCheckoutSession.types.js';
export * from './getCheckoutSessionCharge.types.js';
export * from './getCheckoutSessionTags.types.js';
export * from './getCollectPoints.types.js';
export * from './getPackagingOptions.types.js';
export * from './itemDeliveryProvisioning.types.js';
export * from './packagingOption.types.js';
export * from './patchCheckoutOrder.types.js';
export * from './patchCheckoutOrderDeliveryBundles.types.js';
export * from './patchCheckoutOrderDeliveryBundleUpgrades.types.js';
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export type PackagingOption = string;
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { CheckoutAddress, Config } from '../../types/index.js';
import type { CheckoutAddress, Config, Metadata } from '../../types/index.js';
import type {
CheckoutOrder,
CheckoutOrderShippingOption,
Expand All @@ -18,6 +18,7 @@ export type PatchCheckoutOrderData = {
shippingOption?: CheckoutOrderShippingOption;
deliveryBundleUpdate?: CheckoutOrderDeliveryBundleUpdate;
email?: string;
metadata?: Metadata;
};

export type PatchCheckoutOrder = (
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Bag } from '../../bags/index.js';
import type { Config } from '../../types/index.js';
import type { Config, Metadata } from '../../types/index.js';
import type { GetCheckoutOrderResponse, ShippingMode } from './index.js';
import type { Product } from '../../products/types/index.js';

Expand All @@ -22,11 +22,13 @@ export type PostCheckoutOrderItem = {

export type PostCheckoutOrderDataWithItems = PostCheckoutOrderData & {
items: PostCheckoutOrderItem[];
metadata?: Metadata;
};

export type PostCheckoutOrderDataWithBag = PostCheckoutOrderData & {
bagId: Bag['id'];
removePurchasedItemsFromBag?: boolean;
metadata?: Metadata;
};

export type PostCheckoutOrderDataWithDraftOrder = {
Expand Down
19 changes: 19 additions & 0 deletions packages/react/src/analytics/integrations/GA4/GA4.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,25 @@ class GA4 extends integrations.Integration<GA4IntegrationOptions> {
return this;
}

/**
* Method to check if the integration is ready to be loaded.
*
* @param consent - User consent data.
* @param options - Options passed for the GA4 integration.
*
* @returns If the integration is ready to be loaded.
*/
static override shouldLoad(
consent: ConsentData,
options: GA4IntegrationOptions,
) {
if (get(options, `${OPTION_GOOGLE_CONSENT_CONFIG}.mode`) === 'Advanced') {
return true;
}

return super.shouldLoad(consent, options);
}

/**
* Send page events to GA4.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,10 @@ function getWindowGa4Spy() {
}

describe('GA4 Integration', () => {
const validOptions = {
measurementId: 'GA-123456-12',
};

beforeEach(() => {
jest.clearAllMocks();
});
Expand All @@ -99,21 +103,39 @@ describe('GA4 Integration', () => {
});

it('`shouldLoad` should return false if there is no user consent', () => {
expect(GA4.shouldLoad({ statistics: false }, {})).toBe(false);
expect(GA4.shouldLoad({}, {})).toBe(false);
expect(GA4.shouldLoad({ statistics: false }, { ...validOptions })).toBe(
false,
);
expect(GA4.shouldLoad({}, { ...validOptions })).toBe(false);
});

it('`shouldLoad` should return true if there is user consent', () => {
expect(GA4.shouldLoad({ statistics: true }, {})).toBe(true);
expect(GA4.shouldLoad({ statistics: true }, { ...validOptions })).toBe(
true,
);
});

it('`shouldLoad` should return true if google consent mode option was passed as `Advanced`', () => {
expect(
GA4.shouldLoad(
{},
{
...validOptions,
googleConsentConfig: {
ad_personalization: {},
ad_storage: {},
ad_user_data: {},
analytics_storage: {},
mode: 'Advanced',
},
},
),
).toBe(true);
});

describe('GA4 instance', () => {
let ga4Instance;

const validOptions = {
measurementId: 'GA-123456-12',
};

const loadData: LoadIntegrationEventData = {
...loadIntegrationData,
user: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { isEqual, omit } from 'lodash-es';
export class GoogleConsentMode {
private dataLayer!: string; // Stores different data layer names
private config?: GoogleConsentModeConfig; // Stores default or customized consent category mappings
private configExcludingRegionsAndWaitForUpdate!: Record<
private configExcludingModeRegionsAndWaitForUpdate!: Record<
string,
GoogleConsentCategoryConfig
>; // exclude not consent properties from config
Expand All @@ -30,9 +30,10 @@ export class GoogleConsentMode {
this.config = config;

// select only the Google Consent Elements
this.configExcludingRegionsAndWaitForUpdate = omit(this.config || {}, [
this.configExcludingModeRegionsAndWaitForUpdate = omit(this.config || {}, [
'waitForUpdate',
'regions',
'mode',
]);

this.loadDefaults(initConsent);
Expand All @@ -52,13 +53,13 @@ export class GoogleConsentMode {

// Obtain default google consent registry
const consentRegistry = Object.keys(
this.configExcludingRegionsAndWaitForUpdate,
this.configExcludingModeRegionsAndWaitForUpdate,
).reduce(
(result, consentKey) => ({
...result,
[consentKey]:
this.configExcludingRegionsAndWaitForUpdate[consentKey]?.default ||
GoogleConsentType.Denied,
this.configExcludingModeRegionsAndWaitForUpdate[consentKey]
?.default || GoogleConsentType.Denied,
}),
initialValue,
);
Expand Down Expand Up @@ -87,10 +88,11 @@ export class GoogleConsentMode {

// Fill consent value into consent element, using analytics consent categories
const consentRegistry = Object.keys(
this.configExcludingRegionsAndWaitForUpdate,
this.configExcludingModeRegionsAndWaitForUpdate,
).reduce((result, consentKey) => {
let consentValue = GoogleConsentType.Denied;
const consent = this.configExcludingRegionsAndWaitForUpdate[consentKey];
const consent =
this.configExcludingModeRegionsAndWaitForUpdate[consentKey];

if (consent) {
// has consent config key
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,5 @@ export type GoogleConsentModeConfig =
GoogleConsentMappingsBase<GoogleConsentCategoryConfig> & {
regions?: Array<GoogleConsentRegionConfig>;
waitForUpdate?: number;
mode?: 'Basic' | 'Advanced';
};
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,7 @@ Object {
},
],
"currency": "EUR",
"customerId": 123,
"customerType": 0,
"formattedGrandTotal": "102 €",
"formattedSubTotalAmount": "100 €",
Expand All @@ -310,6 +311,7 @@ Object {
30380051,
],
"locale": "en-US",
"metadata": Object {},
"orderId": "D7XM6Y",
"paymentIntentId": "123",
"shippingAddress": Object {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,7 @@ Object {
},
],
"currency": "EUR",
"customerId": 123,
"customerType": 0,
"formattedGrandTotal": "102 €",
"formattedSubTotalAmount": "100 €",
Expand All @@ -310,6 +311,7 @@ Object {
30380051,
],
"locale": "en-US",
"metadata": Object {},
"orderId": "D7XM6Y",
"paymentIntentId": "123",
"shippingAddress": Object {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,7 @@ Object {
},
],
"currency": "EUR",
"customerId": 123,
"customerType": 0,
"formattedGrandTotal": "102 €",
"formattedSubTotalAmount": "100 €",
Expand All @@ -310,6 +311,7 @@ Object {
30380051,
],
"locale": "en-US",
"metadata": Object {},
"orderId": "D7XM6Y",
"paymentIntentId": "123",
"shippingAddress": Object {
Expand Down
Loading
Loading