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

Feature/35439 integrate vat tax include in price config into service application #13

Open
wants to merge 6 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 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
55 changes: 55 additions & 0 deletions event/src/avalara/requests/postprocess/postprocess.order.commit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import {
OrderSetCustomTypeAction,
OrderSetLineItemCustomTypeAction,
} from '@commercetools/platform-sdk';
import { TransactionModel } from 'avatax/lib/models/TransactionModel';
import { performOrderUpdateActions } from '../../../client/data.client';
import { logger } from '../../../utils/logger.utils';

function buildCustomTypeAction(
action: string,
customTypeId: string,
fields: object
) {
return {
action,
type: {
id: customTypeId,
typeId: 'type',
},
fields,
};
}

export async function postProcessing(
orderId: string,
orderVersion: number,
transaction: TransactionModel | undefined
) {
if (!transaction) {
return;
}
const actions: Array<
OrderSetLineItemCustomTypeAction | OrderSetCustomTypeAction
> = [];

for (const item of transaction?.lines || []) {
actions.push({
...buildCustomTypeAction('setLineItemCustomType', 'vat-code', {
vatCode: item.vatCode,
}),
lineItemId: item.itemCode,
} as OrderSetLineItemCustomTypeAction);
}

if (transaction.invoiceMessages) {
actions.push({
630N marked this conversation as resolved.
Show resolved Hide resolved
...buildCustomTypeAction('setCustomType', 'invoices-messages', {
invoiceMessages: transaction.invoiceMessages,
}),
} as OrderSetCustomTypeAction);
}
await performOrderUpdateActions(orderId, orderVersion, actions).catch(
(error) => logger.error(error)
);
}
29 changes: 29 additions & 0 deletions event/src/avalara/requests/postprocess/postprocess.order.refund.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { OrderSetCustomTypeAction } from '@commercetools/platform-sdk';
import { TransactionModel } from 'avatax/lib/models/TransactionModel';
import { performOrderUpdateActions } from '../../../client/data.client';
import { logger } from '../../../utils/logger.utils';

export async function postProcessing(
orderId: string,
orderVersion: number,
transaction: TransactionModel | undefined
) {
if (!transaction) {
return;
}
const actions: Array<OrderSetCustomTypeAction> = [];

if (transaction.invoiceMessages) {
actions.push({
action: 'setCustomType',
type: {
id: 'invoices-messages',
typeId: 'type',
},
fields: { invoiceMessages: transaction.invoiceMessages },
} as OrderSetCustomTypeAction);
}
await performOrderUpdateActions(orderId, orderVersion, actions).catch(
(error) => logger.error(error)
);
}
18 changes: 7 additions & 11 deletions event/src/avalara/requests/preprocess/preprocess.order.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { LineItem, Order } from '@commercetools/platform-sdk';
import { getCustomerEntityUseCode } from '../../../client/data.client';
import {
getCustomerEntityUseCode,
getCustomerVatId,
} from '../../../client/data.client';
import { CreateTransactionModel } from 'avatax/lib/models/CreateTransactionModel';
import { lineItem } from '../../utils/line.items';
import { shippingAddress } from '../../utils/shipping.address';
Expand All @@ -9,15 +12,6 @@ import { getCategoryTaxCodes } from './get.categories';
import { DocumentType } from 'avatax/lib/enums/DocumentType';
import { TransactionParameterModel } from 'avatax/lib/models/TransactionParameterModel';

function extractVatId(order: Order) {
const paymentCustomerVatIds = order?.paymentInfo?.payments.map(
(payment) => payment.obj?.customer?.obj?.vatId
);
const vatId = paymentCustomerVatIds?.find((vatId) => vatId !== undefined);

return vatId || order?.customerId;
}

// initialize and specify the tax document model of Avalara
export async function processOrder(
type: string,
Expand Down Expand Up @@ -78,7 +72,9 @@ export async function processOrder(
taxDocument.entityUseCode = customerInfo?.exemptCode;
taxDocument.lines = lines;

taxDocument.businessIdentificationNo = extractVatId(order);
taxDocument.businessIdentificationNo = await getCustomerVatId(
order?.customerId
);
taxDocument.parameters = [
{
name: 'Transport',
Expand Down
25 changes: 25 additions & 0 deletions event/src/client/data.client.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { createApiRoot } from './create.client';
import { OrderUpdateAction } from '@commercetools/platform-sdk';

export const getData = async (container: string) => {
const data = (
Expand Down Expand Up @@ -83,3 +84,27 @@ export const getOrder = async (id: string) => {
return (await createApiRoot().orders().withId({ ID: id }).get().execute())
.body;
};

export const performOrderUpdateActions = async (
id: string,
version: number,
actions: Array<OrderUpdateAction>
) => {
return (
await createApiRoot()
.orders()
.withId({ ID: id })
.post({ body: { version, actions } })
.execute()
).body;
};

export const getCustomerVatId = async (id?: string) => {
if (!id) {
return '';
}
return (
(await createApiRoot().customers().withId({ ID: id }).get().execute())?.body
?.vatId || ''
);
};
73 changes: 24 additions & 49 deletions event/src/controllers/event.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,8 @@ import { setUpAvaTax } from '../utils/avatax.utils';
import { commitTransaction } from '../avalara/requests/actions/commit.transaction';
import { voidTransaction } from '../avalara/requests/actions/void.transaction';
import { refundTransaction } from '../avalara/requests/actions/refund.transaction';
import { TransactionModel } from 'avatax/lib/models/TransactionModel';
import { Order } from '@commercetools/platform-sdk';
import { TransactionLineModel } from 'avatax/lib/models/TransactionLineModel';
import { postProcessing as commitPostProcessing } from '../avalara/requests/postprocess/postprocess.order.commit';
import { postProcessing as refundPostProcessing } from '../avalara/requests/postprocess/postprocess.order.refund';

/**
* Exposed event POST endpoint.
Expand Down Expand Up @@ -45,47 +44,6 @@ function parseRequest(request: Request) {
throw new CustomError(400, 'Bad request: No payload in the Pub/Sub message');
}

function buildResponseModel(
orderMessage: OrderCreatedMessage,
transaction: any
) {
if (!(transaction || transaction instanceof TransactionModel)) {
return undefined;
}
const lineItems = orderMessage.order?.lineItems?.map((lineItem) => {
return {
...lineItem,
custom: {
type: {
id: 'vatCodeType',
key: 'vatCode',
typeId: 'type',
},
fields: {
vatCode: transaction.lines?.find(
(x: TransactionLineModel) => x.itemCode === lineItem.variant.sku
)?.vatCode,
},
},
};
});
const order = {
...orderMessage.order,
lineItems: lineItems,
custom: {
type: {
id: 'invoiceMessagesType',
key: 'invoiceMessages',
typeId: 'type',
},
fields: {
invoiceMessages: transaction.invoiceMessages,
},
},
};
return order as Order;
}

export const post = async (
request: Request,
response: Response,
Expand Down Expand Up @@ -119,15 +77,23 @@ export const post = async (
if (!messagePayload.order) {
throw new CustomError(400, `Order must be defined.`);
}
const transaction = await commitTransaction(
await commitTransaction(
messagePayload.order,
credentials,
originAddress,
avataxConfig,
settings.displayPricesWithTax
).catch((error) => logger.error(error));
const updatedOrder = buildResponseModel(messagePayload, transaction);
response.status(200).send(updatedOrder);
)
.then(
async (transaction) =>
await commitPostProcessing(
messagePayload.order.id,
messagePayload.order.version,
transaction
)
)
.catch((error) => logger.error(error));
response.status(200).send();
break;
case 'OrderStateChanged':
if (
Expand All @@ -147,7 +113,16 @@ export const post = async (
originAddress,
avataxConfig,
settings.displayPricesWithTax
).catch((error) => logger.error(error));
)
.then(
async (transaction) =>
await refundPostProcessing(
messagePayload.resource.id,
messagePayload.version,
transaction
)
)
.catch((error) => logger.error(error));
}
});
}
Expand Down
59 changes: 3 additions & 56 deletions event/tests/event.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,45 +90,6 @@ const refundRequestConfigTest = generateGoodRequest(
'US'
);

const expectedSuccessfulCreateOrderResponse = {
createdAt: '2021-06-01T00:00:00.000Z',
custom: {
fields: { invoiceMessages: undefined },
type: { id: 'invoiceMessagesType', key: 'invoiceMessages', typeId: 'type' },
},
customerId: '123',
id: '123',
lineItems: [
{
custom: {
fields: { vatCode: '' },
type: { id: 'vatCodeType', key: 'vatCode', typeId: 'type' },
},
name: { en: 'Test Product' },
quantity: 2,
taxRate: { includedInPrice: false },
totalPrice: { centAmount: 12300, currencyCode: 'USD' },
variant: { id: 1, sku: 'sku123' },
},
],
orderNumber: orderNumber,
shippingAddress: {
city: 'Irvine',
country: 'US',
postalCode: '92614',
streetName: 'Main Street',
streetNumber: '2000',
},
shippingInfo: {
price: { centAmount: 123, currencyCode: 'USD' },
shippingMethod: { id: '123' },
shippingMethodName: 'Standard',
taxRate: { includedInPrice: false },
},
totalPrice: { centAmount: 24600, currencyCode: 'USD' },
version: 1,
};

const commitRequest = (country: string) =>
generateGoodRequest('OrderCreated', orderNumber, country);
const voidRequest = (country: string) =>
Expand Down Expand Up @@ -156,20 +117,11 @@ const response = {
send: jest.fn(),
} as unknown as Response;

const expectSuccessfulCall = (
next: NextFunction,
res: Response,
times = 1,
responseBody: any = undefined
) => {
const expectSuccessfulCall = (next: NextFunction, res: Response, times = 1) => {
expect(next).toBeCalledTimes(0);
expect(res.status).toBeCalledWith(200);
expect(res.send).toBeCalledTimes(times);
if (responseBody) {
expect(res.send).toBeCalledWith(responseBody);
} else {
expect(res.send).toBeCalledWith();
}
expect(res.send).toBeCalledWith();
};

describe('test event controller', () => {
Expand Down Expand Up @@ -269,12 +221,7 @@ describe('test event controller', () => {

expect(spyCommit).toBeCalledTimes(1);
expectCommitReturn(orderNumber, await getCommitResult());
expectSuccessfulCall(
next,
response,
1,
expectedSuccessfulCreateOrderResponse
);
expectSuccessfulCall(next, response);
});

test('cancel order, no lock transaction error is thrown', async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,6 @@ function getLineItemTaxAmountAction(
taxRate: number,
pricesIncludesTax: boolean
) {
console.log(
'getLineItemTaxAmountAction',
pricesIncludesTax,
taxCentAmount,
taxRate,
item.totalPrice.centAmount
);
return {
action: 'setLineItemTaxAmount',
lineItemId: item.id,
Expand Down
18 changes: 7 additions & 11 deletions service/src/avalara/requests/preprocess/preprocess.get.tax.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { Cart, LineItem } from '@commercetools/platform-sdk';
import { getCustomerEntityUseCode } from '../../../client/data.client';
import {
getCustomerEntityUseCode,
getCustomerVatId,
} from '../../../client/data.client';
import { CreateTransactionModel } from 'avatax/lib/models/CreateTransactionModel';
import { lineItem } from '../../utils/line.items';
import { shippingAddress } from '../../utils/shipping.address';
Expand All @@ -9,15 +12,6 @@ import { getCategoryTaxCodes } from './get.categories';
import { TransactionParameterModel } from 'avatax/lib/models/TransactionParameterModel';
import { DocumentType } from 'avatax/lib/enums/DocumentType';

function extractVatId(cart: Cart) {
const paymentCustomerVatIds = cart?.paymentInfo?.payments.map(
(payment) => payment.obj?.customer?.obj?.vatId
);
const vatId = paymentCustomerVatIds?.find((vatId) => vatId !== undefined);

return vatId || cart?.customerId;
}

// initialize and specify the tax document model of Avalara
export async function processCart(
cart: Cart,
Expand Down Expand Up @@ -68,7 +62,9 @@ export async function processCart(
);
taxDocument.lines = lines;

taxDocument.businessIdentificationNo = extractVatId(cart);
taxDocument.businessIdentificationNo = await getCustomerVatId(
cart?.customerId
);
taxDocument.parameters = [
{
name: 'Transport',
Expand Down
Loading