mv-shipping-line-assignment-strategy.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import {
  2. ChannelService,
  3. EntityHydrator,
  4. idsAreEqual,
  5. Injector,
  6. Order,
  7. OrderSellerStrategy,
  8. RequestContext,
  9. ShippingLine,
  10. ShippingLineAssignmentStrategy,
  11. } from '@vendure/core';
  12. export class MultivendorShippingLineAssignmentStrategy implements ShippingLineAssignmentStrategy {
  13. private entityHydrator: EntityHydrator;
  14. private channelService: ChannelService;
  15. init(injector: Injector) {
  16. this.entityHydrator = injector.get(EntityHydrator);
  17. this.channelService = injector.get(ChannelService);
  18. }
  19. async assignShippingLineToOrderLines(ctx: RequestContext, shippingLine: ShippingLine, order: Order) {
  20. // First we need to ensure the required relations are available
  21. // to work with.
  22. const defaultChannel = await this.channelService.getDefaultChannel();
  23. await this.entityHydrator.hydrate(ctx, shippingLine, { relations: ['shippingMethod.channels'] });
  24. const { channels } = shippingLine.shippingMethod;
  25. // We assume that, if a ShippingMethod is assigned to exactly 2 Channels,
  26. // then one is the default Channel and the other is the seller's Channel.
  27. if (channels.length === 2) {
  28. const sellerChannel = channels.find(c => !idsAreEqual(c.id, defaultChannel.id));
  29. if (sellerChannel) {
  30. // Once we have established the seller's Channel, we can filter the OrderLines
  31. // that belong to that Channel. The `sellerChannelId` was previously established
  32. // in the `OrderSellerStrategy.setOrderLineSellerChannel()` method.
  33. return order.lines.filter(line => idsAreEqual(line.sellerChannelId, sellerChannel.id));
  34. }
  35. }
  36. return order.lines;
  37. }
  38. }