import fetch from "node-fetch"; import fetchEbayUserToken from "../utils/fetchEbayUserToken.js"; export const createAndListItem = async (req, res) => { const { sku, marketplaceId, format, availableQuantity, categoryId, condition, listingDescription, pricingSummary, merchantLocationKey, quantityLimitPerBuyer, product, // Extract the entire product object packageWeightAndSize, // Adjusted to packageWeightAndSize from the refined payload imageUrls, } = req.body; const token = await fetchEbayUserToken(req, res); // Get the eBay user token let dynamicAspects = {}; for (const [key, value] of Object.entries(product.aspects)) { dynamicAspects[key] = Array.isArray(value) ? value : [value]; } try { // Create the inventory item const inventoryItemPayload = { sku, condition, product: { title: product.title.substring(0, 80), // Utilizing product title brand: product.brand, // Using brand from the product object description: product.description, // Using product description imageUrls: product.imageUrls, // Using all imageUrls from product aspects: dynamicAspects }, availability: { shipToLocationAvailability: { quantity: availableQuantity, }, }, // Package weight and dimensions, adjusted to the new structure packageWeightAndSize: { weight: { value: parseFloat(packageWeightAndSize.weight.value), unit: packageWeightAndSize.weight.unit, }, dimensions: { length: parseFloat(packageWeightAndSize.dimensions.length), width: parseFloat(packageWeightAndSize.dimensions.width), height: parseFloat(packageWeightAndSize.dimensions.height), unit: packageWeightAndSize.dimensions.unit, }, }, }; const createItemResponse = await fetch( `https://api.ebay.com/sell/inventory/v1/inventory_item/${sku}`, { method: "PUT", headers: { "Content-Type": "application/json", "Content-Language": "en-US", "Authorization": `Bearer ${token}`, "Accept": "application/json", }, body: JSON.stringify(inventoryItemPayload), } ); // Optionally, you can parse the response body if eBay's API returns useful information in it const itemResponseData = await createItemResponse; console.log(itemResponseData); // 2. Create the offer for the inventory item const offerPayload = { sku, marketplaceId, format, listing: { categoryId, listingDescription, merchantLocationKey, }, pricingSummary, quantityLimitPerBuyer, }; const offerResponse = await fetch( `https://api.ebay.com/sell/inventory/v1/offer`, { method: "POST", headers: { "Content-Type": "application/json", "Content-Language": "en-US", Authorization: `Bearer ${token}`, }, body: JSON.stringify(offerPayload), } ); if (!offerResponse.ok) { // Handle error in creating the offer const errorBody = await offerResponse.text(); throw new Error( `Failed to create offer: ${offerResponse.status} - ${errorBody}` ); } const offerData = await offerResponse.json(); const offerId = offerData.offerId; // 3. Publish the offer to convert it into a live listing await fetch( `https://api.ebay.com/sell/inventory/v1/offer/${offerId}/publish/`, { method: "POST", headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", }, } ); res.json({ success: true, message: "Item listed successfully" }); } catch (error) { console.error("Error in createAndListItem endpoint:", error); res.status(500).json({ success: false, message: "Failed to create and list item on eBay", error: error.message, }); } }; export const deleteItemBySku = async (req, res) => { const { sku } = req.params; // Assuming SKU is provided as a URL parameter try { const token = await fetchEbayUserToken(req, res); // Get the eBay user token // Perform the deletion of the inventory item const deleteResponse = await fetch(`https://api.ebay.com/sell/inventory/v1/inventory_item/${sku}`, { method: "DELETE", headers: { "Authorization": `Bearer ${token}`, "Content-Type": "application/json", "Accept": "application/json", }, }); if (!deleteResponse.ok) { // Handle unsuccessful deletion const errorBody = await deleteResponse.text(); throw new Error(`Failed to delete inventory item: ${deleteResponse.status} - ${errorBody}`); } // Successfully deleted the item res.json({ success: true, message: `Item with SKU: ${sku} deleted successfully.` }); } catch (error) { console.error("Error in deleteItemBySku endpoint:", error); res.status(500).json({ success: false, message: `Failed to delete item with SKU: ${sku} from eBay`, error: error.message, }); } }; export const getAllInventory = async (req, res) => { const limit = req.query.limit || '100'; // Set default limit const offset = req.query.offset || '0'; // Set default offset try { const token = await fetchEbayUserToken(req, res); // Assuming fetchEbayUserToken doesn't need req, res passed and handles token internally const response = await fetch(`https://api.ebay.com/sell/inventory/v1/inventory_item?limit=${limit}&offset=${offset}`, { method: 'GET', headers: { "Content-Type": "application/json", "Authorization": `Bearer ${token}`, "Accept-Language": "en-US", }, }); if (!response.ok) { // If the response is not okay, throw an error with status and statusText throw new Error(`Failed to retrieve inventory items: ${response.status} ${response.statusText}`); } const inventoryItems = await response.json(); // Parsing the JSON body of the response res.json(inventoryItems); // Sending the inventory items back to the client } catch (error) { console.error('Error fetching inventory:', error); res.status(500).json({ error: 'Internal Server Error', message: error.message, }); } };