import fetch from "node-fetch"; import fetchEbayUserToken from "../utils/fetchEbayUserToken.js"; export const createAndListItem = async (req, res) => { const { sku, marketplaceId, format, listingDuration, availableQuantity, categoryId, condition, listingDescription, pricingSummary, mpn, 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 // only need these if payloads is there? 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, quantity: availableQuantity, product: { title: product.title.substring(0, 80), // Utilizing product title brand: product.brand, // Using brand from the product object mpn: mpn, description: product.description, // Using product description imageUrls: product.imageUrls, // Using all imageUrls from product }, availability: { shipToLocationAvailability: { quantity: availableQuantity, availabilityDistributions: [ // Adding availability distributions { availabilityType: "IN_STOCK", // Assuming items are in stock for pickup fulfillmentTime: { // Fulfillment time for shipping unit: "DAY", value: 1 // Adjust based on your shipping fulfillment time }, merchantLocationKey: merchantLocationKey, // Specify the location for shipping availability quantity: availableQuantity // Quantity available for shipping from the specified location } ] }, }, 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; // 2. Create the offer for the inventory item const offerPayload = { sku, marketplaceId, format, // This is equivalent to format: format, categoryId, // Moved to top-level, outside of the 'listing' object listingDescription, // Moved to top-level, outside of the 'listing' object merchantLocationKey, // Moved to top-level, outside of the 'listing' object pricingSummary: { price: pricingSummary.price, }, availableQuantity, listingDuration, listingPolicies: { // Include the listing policies with their respective IDs fulfillmentPolicyId: "246576176016", returnPolicyId: "246576188016", paymentPolicyId: "246576154016", }, // Additional fields from the sample payload can be included here as needed }; 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; console.log(offerId) // 3. Publish the offer to convert it into a live listing const publishOfferResponse = await fetch( `https://api.ebay.com/sell/inventory/v1/offer/${offerId}/publish/`, // Ensure the offerId is correctly inserted { method: "POST", headers: { Authorization: `Bearer ${token}`, // Ensure your token is valid "Content-Type": "application/json", }, } ); const responseBody = await publishOfferResponse.json(); // Assuming the response will be in JSON format console.log(responseBody); 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, }); } }; export const getOffers = async (req, res) => { const sku = "LEMUG2022212234120245"; // Assuming this is your SKU const offerId = 418806088016 try { const token = await fetchEbayUserToken(req, res); // Assuming fetchEbayUserToken handles token retrieval internally const response = await fetch('https://api.ebay.com/commerce/taxonomy/v1/get_default_category_tree_id?marketplace_id=EBAY_US', { method: 'GET', headers: { "Content-Type": "application/json", "Content-Language": "en-US", "Authorization": `Bearer ${token}`, }, }); console.log(response) const offers = await response.json(); // Parsing the JSON body of the response res.json(offers); // Sending the offers back to the client } catch (error) { console.error('Error fetching offers:', error); res.status(500).json({ error: 'Internal Server Error', message: error.message, }); } }; // fulfill policy = 246576176016 // return policy = 246576188016 // payment policy = 246576154016