class AmazonOrderProcessor {
constructor(connector) {
this.connector = connector;
this.sp = connector.sp;
this.stateset = connector.stateset;
}
// Fetch and process new orders
async processNewOrders() {
const orders = await this.sp.callAPI({
operation: 'getOrders',
endpoint: 'orders',
query: {
MarketplaceIds: [this.connector.config.marketplace],
CreatedAfter: new Date(Date.now() - 3600000).toISOString(),
OrderStatuses: ['Unshipped', 'PartiallyShipped'],
},
});
for (const amazonOrder of orders.Orders) {
await this.createStatesetOrder(amazonOrder);
}
}
// Create order in Stateset
async createStatesetOrder(amazonOrder) {
// Get order items
const orderItems = await this.sp.callAPI({
operation: 'getOrderItems',
endpoint: 'orders',
path: {
orderId: amazonOrder.AmazonOrderId,
},
});
const statesetOrder = await this.stateset.orders.create({
external_id: amazonOrder.AmazonOrderId,
channel: 'amazon',
customer: {
email: amazonOrder.BuyerEmail || `amazon_${amazonOrder.BuyerInfo?.BuyerName}@marketplace.com`,
name: amazonOrder.BuyerInfo?.BuyerName || 'Amazon Customer',
},
shipping_address: {
line1: amazonOrder.ShippingAddress?.AddressLine1,
line2: amazonOrder.ShippingAddress?.AddressLine2,
city: amazonOrder.ShippingAddress?.City,
state: amazonOrder.ShippingAddress?.StateOrRegion,
postal_code: amazonOrder.ShippingAddress?.PostalCode,
country: amazonOrder.ShippingAddress?.CountryCode,
},
line_items: orderItems.OrderItems.map(item => ({
external_id: item.OrderItemId,
sku: item.SellerSKU,
asin: item.ASIN,
name: item.Title,
quantity: parseInt(item.QuantityOrdered),
price: parseFloat(item.ItemPrice?.Amount || 0),
tax: parseFloat(item.ItemTax?.Amount || 0),
})),
subtotal: parseFloat(amazonOrder.OrderTotal?.Amount) - parseFloat(amazonOrder.TaxTotal?.Amount || 0),
tax: parseFloat(amazonOrder.TaxTotal?.Amount || 0),
total: parseFloat(amazonOrder.OrderTotal?.Amount),
currency: amazonOrder.OrderTotal?.CurrencyCode,
fulfillment_channel: amazonOrder.FulfillmentChannel,
metadata: {
amazon_order_status: amazonOrder.OrderStatus,
is_prime: amazonOrder.IsPrime,
is_premium_order: amazonOrder.IsPremiumOrder,
shipment_service_level: amazonOrder.ShipmentServiceLevel,
},
});
return statesetOrder;
}
// Update shipment tracking
async updateShipmentTracking(orderId, trackingInfo) {
const feed = await this.sp.callAPI({
operation: 'createFeed',
endpoint: 'feeds',
body: {
feedType: 'POST_ORDER_FULFILLMENT_DATA',
marketplaceIds: [this.connector.config.marketplace],
content: this.createFulfillmentFeed(orderId, trackingInfo),
},
});
return this.monitorFeed(feed.feedId);
}
}