Skip to content

Commit

Permalink
Merge pull request #82 from mollie/feature/MOL-477/PICT-257
Browse files Browse the repository at this point in the history
MOL-448/PICT-258 Update processor logic
  • Loading branch information
NghiaDTr authored Oct 16, 2024
2 parents 18955cc + 26daba0 commit 41925ec
Show file tree
Hide file tree
Showing 4 changed files with 648 additions and 4 deletions.
25 changes: 25 additions & 0 deletions processor/src/commercetools/cart.commercetools.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { createApiRoot } from '../client/create.client';
import CustomError from '../errors/custom.error';
import { logger } from '../utils/logger.utils';

export const getCartFromPayment = async (paymentId: string) => {
const carts = await createApiRoot()
.carts()
.get({
queryArgs: {
where: `paymentInfo(payments(id= "${paymentId}"))`,
},
})
.execute();

const results = carts.body.results;
if (results.length !== 1) {
logger.error('There is no cart which attached this target payment');

throw new CustomError(400, 'There is no cart which attached this target payment');
}

logger.info(`Found cart with id ${results[0].id}`);

return results[0];
};
40 changes: 39 additions & 1 deletion processor/src/service/payment.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,24 @@ import { ApplePaySessionRequest, CustomPayment, SupportedPaymentMethods } from '
import { parseStringToJsonObject } from '../utils/app.utils';
import ApplePaySession from '@mollie/api-client/dist/types/src/data/applePaySession/ApplePaySession';
import { getMethodConfigObjects } from '../commercetools/customObjects.commercetools';
import { getCartFromPayment } from '../commercetools/cart.commercetools';

type CustomMethod = {
id: string;
name: Record<string, string>;
description: Record<string, string>;
image: string;
order: number;
pricingConstraints?: PricingConstraintItem[];
};

type PricingConstraintItem = {
id?: number;
countryCode: string;
currencyCode: string;
minAmount: number;
maxAmount: number;
surchargeCost?: string;
};

/**
Expand Down Expand Up @@ -146,17 +157,19 @@ export const handleListPaymentMethodsByPayment = async (ctPayment: Payment): Pro
const mollieOptions = await mapCommercetoolsPaymentCustomFieldsToMollieListParams(ctPayment);
const methods: List<Method> = await listPaymentMethods(mollieOptions);
const configObjects: CustomObject[] = await getMethodConfigObjects();

const cart = await getCartFromPayment(ctPayment.id);
const customMethods = methods.map((method) => ({
id: method.id,
name: { 'en-GB': method.description },
description: { 'en-GB': '' },
image: method.image.svg,
order: 0,
}));

const validatedMethods = validateAndSortMethods(customMethods, configObjects);

const enableCardComponent = shouldEnableCardComponent(validatedMethods);
const ctUpdateActions: UpdateAction[] = [];

if (enableCardComponent) {
validatedMethods.splice(
Expand All @@ -165,11 +178,36 @@ export const handleListPaymentMethodsByPayment = async (ctPayment: Payment): Pro
);
}

if (cart.country) {
const currencyCode = ctPayment.amountPlanned.currencyCode;

configObjects.forEach((item: CustomObject) => {
const pricingConstraint = item.value.pricingConstraints?.find((pricingConstraint: PricingConstraintItem) => {
return pricingConstraint.countryCode === cart.country && pricingConstraint.currencyCode === currencyCode;
}) as PricingConstraintItem;

if (pricingConstraint) {
const amount = ctPayment.amountPlanned.centAmount / Math.pow(10, ctPayment.amountPlanned.fractionDigits);

if (
(pricingConstraint.minAmount && amount < pricingConstraint.minAmount) ||
(pricingConstraint.maxAmount && amount > pricingConstraint.maxAmount)
) {
const index: number = validatedMethods.findIndex((method) => method.id === item.value.id);

validatedMethods.splice(index, 1);
}
}
});
}

const availableMethods = JSON.stringify({
count: validatedMethods.length,
methods: validatedMethods.length ? validatedMethods : [],
});

const ctUpdateActions: UpdateAction[] = [];

ctUpdateActions.push(
setCustomFields(CustomFields.payment.profileId, enableCardComponent ? readConfiguration().mollie.profileId : ''),
);
Expand Down
88 changes: 88 additions & 0 deletions processor/tests/commercetools/cart.commercetools.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { getCartFromPayment } from './../../src/commercetools/cart.commercetools';
import { afterEach, describe, expect, jest, it } from '@jest/globals';
import { Cart } from '@commercetools/platform-sdk';
import { createApiRoot } from '../../src/client/create.client';
import { logger } from '../../src/utils/logger.utils';
import CustomError from '../../src/errors/custom.error';

const cart: Cart = {
id: '5c8b0375-305a-4f19-ae8e-07806b101999',
country: 'DE',
} as Cart;

jest.mock('../../src/client/create.client', () => ({
createApiRoot: jest.fn(),
}));

describe('Test getCartFromPayment', () => {
afterEach(() => {
jest.clearAllMocks();
});

it('should return the correct cart', async () => {
const getCarts = jest.fn();

(createApiRoot as jest.Mock).mockReturnValue({
carts: jest.fn().mockReturnValue({
get: getCarts,
}),
});

getCarts.mockReturnValue({
execute: jest.fn().mockReturnValue({
body: {
results: [cart],
},
}),
});

const paymentId = 'test-payment-id';
const result = await getCartFromPayment(paymentId);

expect(getCarts).toHaveBeenCalledTimes(1);
expect(getCarts).toHaveBeenCalledWith({
queryArgs: {
where: `paymentInfo(payments(id= "${paymentId}"))`,
},
});
expect(result).toStrictEqual(cart);
expect(logger.info).toHaveBeenCalledTimes(1);
expect(logger.info).toHaveBeenCalledWith(`Found cart with id ${cart.id}`);
});

it('should throw exception', async () => {
const getCarts = jest.fn();

(createApiRoot as jest.Mock).mockReturnValue({
carts: jest.fn().mockReturnValue({
get: getCarts,
}),
});

getCarts.mockReturnValue({
execute: jest.fn().mockReturnValue({
body: {
results: [],
},
}),
});

const paymentId = 'test-payment-id';

try {
await getCartFromPayment(paymentId);
} catch (error: any) {
expect(getCarts).toHaveBeenCalledTimes(1);
expect(getCarts).toHaveBeenCalledWith({
queryArgs: {
where: `paymentInfo(payments(id= "${paymentId}"))`,
},
});
expect(error).toBeInstanceOf(CustomError);
expect(error.statusCode).toBe(400);
expect(error.message).toBe('There is no cart which attached this target payment');
expect(logger.error).toHaveBeenCalledTimes(1);
expect(logger.error).toHaveBeenCalledWith('There is no cart which attached this target payment');
}
});
});
Loading

0 comments on commit 41925ec

Please sign in to comment.