// Main function to create returns feed
const createReturnsFeed = async (req, res) => {
async function getReturns(offset, token) {
const DOCUMENT_UPSERT_BATCH_SIZE = 3;
var token;
var limit = 1;
console.log(offset);
console.log(limit);
try {
const response = await axios.post(`https://api.stateset.com/api/get-returns`, { limit: limit, offset: offset, "order_direction": "desc" }, {
headers: {
'Content-Type': 'application/json',
'token': "Bearer " + token,
},
});
var returns = response.data;
if (returns) {
const documents = [];
for (const item of returns) {
try {
const returnId = item.id || null;
const orderId = item.order_id || null;
const actionNeeded = item.action_needed || null;
const description = item.description || null;
const status = item.status || null;
const customerEmail = item.customerEmail || null;
const customerEmailNormalized = item.customer_email_normalized || null;
const zendeskNumber = item.zendesk_number || null;
const serialNumber = item.serial_number || null;
const reportedCondition = item.reported_condition || null;
const trackingNumber = item.tracking_number || null;
const rma = item.rma || null;
const reasonCategory = item.reason_category || null;
const country = item.country || null;
const ssoId = item.sso_id || null;
const enteredBy = item.entered_by || null;
const scannedSerialNumber = item.scanned_serial_number || null;
const issue = item.issue || null;
const condition = item.condition || null;
const amount = item.amount || null;
const taxRefunded = item.tax_refunded || null;
const totalRefunded = item.total_refunded || null;
const createdDate = item.created_date || null;
const orderDate = item.order_date || null;
const shippedDate = item.shipped_date || null;
const requestedDate = item.requested_date || null;
const flatRateShipping = item.flat_rate_shipping || null;
const warehouseReceivedDate = item.warehouse_received_date || null;
const warehouseConditionDate = item.warehouse_condition_date || null;
let metadata = {
returnId,
orderId,
actionNeeded,
description,
status,
customerEmail,
customerEmailNormalized,
zendeskNumber,
serialNumber,
reportedCondition,
trackingNumber,
rma,
reasonCategory,
country,
ssoId,
enteredBy,
scannedSerialNumber,
issue,
condition,
amount,
taxRefunded,
totalRefunded,
createdDate,
orderDate,
shippedDate,
requestedDate,
flatRateShipping,
warehouseReceivedDate,
warehouseConditionDate,
};
const document = {
id: uuid(),
returnId,
metadata,
};
documents.push(document);
} catch (error) {
console.log(`Error processing item: ${JSON.stringify(item)}`);
console.log(error);
}
for (let i = 0; i < documents.length; i += DOCUMENT_UPSERT_BATCH_SIZE) {
// Split documents into batches
var batchDocuments = documents.slice(i, i + DOCUMENT_UPSERT_BATCH_SIZE);
console.log(batchDocuments);
// Convert batchDocuments to string
var batchDocumentString = JSON.stringify(batchDocuments)
// Remove commas from string
console.log(batchDocumentString);
// Create Embeddings
console.log('Looping through documents...');
const user_id = "domsteil";
// OpenAI Request Body
var raw = JSON.stringify({ "input": batchDocumentString, "model": "text-embedding-3-large", "user": user_id });
// OpenAI Request Options
var requestOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': process.env.OPEN_AI
},
body: raw,
redirect: 'follow'
};
// Make Callout to OpenAI to get Embeddings
console.log('Creating Embedding...');
// Make Callout to OpenAI
let embeddings_response = await fetch("https://api.openai.com/v1/embeddings", requestOptions)
// Create Pinecone Request Body
const vectors_embeddings = await embeddings_response.json();
console.log(vectors_embeddings);
// Create Pinecone Request Body
var vectors_object = { id: uuid(), values: vectors_embeddings.data[0].embedding, metadata: { "text": batchDocumentString, "user": user_id } };
console.log(vectors_object);
var raw = JSON.stringify({ "vectors": vectors_object, "namespace": `return_data` });
var pineconeRequestOptions = {
method: "POST",
headers: {
"Content-Type": "application/json",
"Host": pinecone_index,
"Content-Length": 60,
"Api-Key": pinecone_api_key,
},
body: raw,
redirect: "follow",
};
// Make Callout to Pinecone
// Pinecone Upsert
console.log('Upserting Pinecone...');
let pinecone_query_response = await fetch(`https://${pinecone_index}/vectors/upsert`, pineconeRequestOptions)
.then(response => response.text())
.then(json => {
console.log(json);
})
.catch(error => {
console.error(error);
});
}
}
await getReturns(offset + 3, token);
}
} catch (error) {
console.log(offset);
console.error(error);
}
}
// Start at offset 0 with limit of 100
await getReturns(0, access_token);
}