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

Added shouldSendOrder to ShipmatePluginConfig #500

Merged
merged 8 commits into from
Sep 26, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
4 changes: 4 additions & 0 deletions packages/vendure-plugin-shipmate/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# 1.3.0 (2024-08-27)

- Add `ShipmatePluginConfig.shouldSendOrder` (#498)

# 1.2.3 (2024-08-20)

- Log warning when failed to cancel a shipment in Shipmate
Expand Down
3 changes: 3 additions & 0 deletions packages/vendure-plugin-shipmate/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ import { ShipmatePlugin } from '@pinelab/vendure-plugin-shipmate';
plugins: [
ShipmatePlugin.init({
apiUrl: 'https://api.shipmate.co.uk/v1.2', // Or https://api-staging.shipmate.co.uk/v1.2 for the testing environment
shouldSendOrder: function ( ctx: RequestContext, order: Order): Promise<boolean> | boolean {
return order.totalQuantity < 5;
martijnvdbrug marked this conversation as resolved.
Show resolved Hide resolved
}
}),
AdminUiPlugin.init({
port: 3002,
Expand Down
2 changes: 1 addition & 1 deletion packages/vendure-plugin-shipmate/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@pinelab/vendure-plugin-shipmate",
"version": "1.2.3",
"version": "1.3.0",
"description": "Vendure plugin for integration with Shipmate",
"icon": "truck",
"author": "Martijn van de Brug <martijn@pinelab.studio>",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,14 @@ export class ShipmateService implements OnApplicationBootstrap {
}

/**
* Created a job in the job queue to send the order to Shipmate
* Creates a job in the job queue to send the order to Shipmate
martijnvdbrug marked this conversation as resolved.
Show resolved Hide resolved
*/
async addJob(
event: OrderStateTransitionEvent | OrderPlacedEvent
): Promise<void> {
if (!this.config.shouldSendOrder(event.ctx, event.order)) {
return;
martijnvdbrug marked this conversation as resolved.
Show resolved Hide resolved
}
const { ctx, order, fromState, toState } = event;
if (event instanceof OrderPlacedEvent) {
await this.jobQueue.add(
Expand Down
11 changes: 10 additions & 1 deletion packages/vendure-plugin-shipmate/src/shipmate.plugin.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { PluginCommonModule, VendurePlugin } from '@vendure/core';
import {
Order,
PluginCommonModule,
RequestContext,
VendurePlugin,
} from '@vendure/core';
import { ShipmateService } from './api/shipmate.service';
import { HttpModule } from '@nestjs/axios';
import { ShipmateConfigEntity } from './api/shipmate-config.entity';
Expand All @@ -18,6 +23,10 @@ export interface ShipmatePluginConfig {
apiUrl:
| 'https://api.shipmate.co.uk/v1.2'
| 'https://api-staging.shipmate.co.uk/v1.2';
shouldSendOrder(
ctx: RequestContext,
order: Order
): Promise<boolean> | boolean;
}

@VendurePlugin({
Expand Down
7 changes: 7 additions & 0 deletions packages/vendure-plugin-shipmate/test/dev-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
DefaultSearchPlugin,
LogLevel,
mergeConfig,
Order,
RequestContext,
} from '@vendure/core';
import { initialData } from '../../test/src/initial-data';
Expand All @@ -28,6 +29,12 @@ import { createSettledOrder } from '../../test/src/shop-utils';
plugins: [
ShipmatePlugin.init({
apiUrl: process.env.SHIPMATE_BASE_URL as any,
shouldSendOrder: function (
ctx: RequestContext,
order: Order
): Promise<boolean> | boolean {
return true;
},
}),
DefaultSearchPlugin,
AdminUiPlugin.init({
Expand Down
54 changes: 44 additions & 10 deletions packages/vendure-plugin-shipmate/test/shipmate.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
RequestContext,
isGraphQlErrorResult,
Order,
DefaultOrderCodeStrategy,
} from '@vendure/core';
import {
createTestEnvironment,
Expand Down Expand Up @@ -39,7 +40,7 @@ import {
} from '@vendure/common/lib/generated-types';

class MockOrderCodeStrategy implements OrderCodeStrategy {
generate(ctx: RequestContext): string | Promise<string> {
generate(ctx: RequestContext): string {
// Mock order code as 'FBJYSHC7WTRQEA14', as defined in the mock object
return mockShipment.shipment_reference;
}
Expand All @@ -62,14 +63,18 @@ describe('Shipmate plugin', async () => {
plugins: [
ShipmatePlugin.init({
apiUrl: nockBaseUrl,
//only send order if the total quantity is less than 5
shouldSendOrder: function (
ctx: RequestContext,
order: Order
): Promise<boolean> | boolean {
return order.totalQuantity < 5;
},
}),
],
paymentOptions: {
paymentMethodHandlers: [testPaymentMethod],
},
orderOptions: {
orderCodeStrategy: new MockOrderCodeStrategy(),
},
});

({ server, shopClient, adminClient } = createTestEnvironment(config));
Expand Down Expand Up @@ -104,7 +109,33 @@ describe('Shipmate plugin', async () => {

let order: Order | undefined;

it('Should not create a Shipment when an Order.totalQuantity is >= 5', async () => {
nock(nockBaseUrl)
.post('/tokens', (reqBody) => {
return true;
})
.reply(200, {
message: 'Login Successful',
data: {
token: '749a75e3c1048965c498017efae8051f',
},
})
.persist(true);
let shipmentRequest: any;
Copy link
Member

@martijnvdbrug martijnvdbrug Sep 19, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This shipmentRequest is never assigned in the Nock request, so this test will always pass. The test below is doing it correctly: shipmentRequest = reqBody;

Maybe it makes sense to make a global shipmentRequests and a global Nock that catches all shipmetn request. So, not per testcase. here we would store all shipment requests in this test suite. We can then do this:

  1. First test if an order with quantity < 5 is being sent to Shipmate, by testing if we have shipmateRequests[0]. This way we are sure the logic of sending works
  2. We then do the test if an order with quantity > 5 is NOT being sent, by creating another order, and testing if shipmateRequests still only has 1 request.

What do you think?

await createSettledOrder(shopClient, 'T_1', true, [
{ id: 'T_1', quantity: 2 },
{ id: 'T_2', quantity: 3 },
]);
await new Promise((resolve) => setTimeout(resolve, 1000));
const orderService = server.app.get(OrderService);
order = await orderService.findOne(ctx, 1);
expect(shipmentRequest?.shipment_reference).toBeUndefined();
});

it('Should create a Shipment when an Order is placed', async () => {
vi.spyOn(DefaultOrderCodeStrategy.prototype, 'generate').mockImplementation(
() => mockShipment.shipment_reference
);
nock(nockBaseUrl)
.post('/tokens', (reqBody) => {
return true;
Expand All @@ -123,10 +154,11 @@ describe('Shipmate plugin', async () => {
return true;
})
.reply(200, { data: [mockShipment], message: 'Shipment Created' });
await shopClient.asAnonymousUser();
await createSettledOrder(shopClient, 'T_1');
await new Promise((resolve) => setTimeout(resolve, 1000));
const orderService = server.app.get(OrderService);
order = await orderService.findOne(ctx, 1);
order = await orderService.findOne(ctx, 2);
expect(shipmentRequest?.shipment_reference).toBe(order?.code);
});

Expand All @@ -150,7 +182,7 @@ describe('Shipmate plugin', async () => {
try {
const modifyOrderInput: ModifyOrderInput = {
dryRun: true,
orderId: 1,
orderId: 2,
addItems: [
{
productVariantId: 3,
Expand All @@ -160,7 +192,7 @@ describe('Shipmate plugin', async () => {
};
const transitionToModifyingResult = await orderService.transitionToState(
ctx,
1,
2,
'Modifying'
);
if (isGraphQlErrorResult(transitionToModifyingResult)) {
Expand All @@ -173,7 +205,7 @@ describe('Shipmate plugin', async () => {
const transitionArrangingAdditionalPaymentResult =
await orderService.transitionToState(
ctx,
1,
2,
'ArrangingAdditionalPayment'
);
if (isGraphQlErrorResult(transitionArrangingAdditionalPaymentResult)) {
Expand All @@ -196,13 +228,14 @@ describe('Shipmate plugin', async () => {
>{
auth_token: authToken,
event: 'TRACKING_COLLECTED',
order_reference: mockShipment.shipment_reference,
shipment_reference: mockShipment.shipment_reference,
});
//shipmate's api expects a status of 201
expect(result.status).toBe(201);
// await new Promise((resolve) => setTimeout(resolve, 4000));
const orderService = server.app.get(OrderService);
const detailedOrder = await orderService.findOne(ctx, 1, ['fulfillments']);
const detailedOrder = await orderService.findOne(ctx, 2, ['fulfillments']);
expect(detailedOrder?.state).toBe('Shipped');
expect(detailedOrder?.fulfillments?.length).toBeGreaterThan(0);
});
Expand All @@ -213,13 +246,14 @@ describe('Shipmate plugin', async () => {
>{
auth_token: authToken,
event: 'TRACKING_DELIVERED',
order_reference: mockShipment.shipment_reference,
shipment_reference: mockShipment.shipment_reference,
});
//shipmate's api expects a status of 201
expect(result.status).toBe(201);
// await new Promise((resolve) => setTimeout(resolve, 4000));
const orderService = server.app.get(OrderService);
const detailedOrder = await orderService.findOne(ctx, 1, ['fulfillments']);
const detailedOrder = await orderService.findOne(ctx, 2, ['fulfillments']);
expect(detailedOrder?.state).toBe('Delivered');
expect(detailedOrder?.fulfillments?.length).toBeGreaterThan(0);
});
Expand Down
Loading