typescript Copy code
import { SQS } from "aws-sdk";
import { queryFrApi } from "../../utils/frApi";
import { sendToMasterData } from "../../utils/masterApi";
import * as type from "../../utils/types";
const sqs = new SQS();
export const handler = async (event: any) => {
console.log("Starting handler function...");
const params = {
QueueUrl: "https://sqs.eu-west-2.amazonaws.com/806798940075/product-headers-qeue-jm",
VisibilityTimeout: 10,
WaitTimeSeconds: 10,
};
try {
const data = await sqs.receiveMessage(params).promise();
if (!data.Messages || data.Messages.length === 0) {
console.log("No messages in the queue");
return { message: "No messages in the queue" };
}
const message = data.Messages[0];
const receiptHandle = message.ReceiptHandle;
const product: type.Product = JSON.parse(message.Body);
console.log("Received message:", product);
const detailsAPI = await queryFrApi(
`https://x3.etcfr.f12cloud.pt:444/api1/x3/erp/X3V12_ETCFR/YCCPRODUCT('${product["ITMREF"]}')?representation=YCCPRODUCT.$details`,
);
// fetch stocks
const stockAPICall = await queryFrApi(
`https://x3.etcfr.f12cloud.pt:444/api1/x3/erp/X3V12_ETCFR/ITMMVT?representation=YCCSTOCK.$query&orderBy=ITMREF&where=(ITMREF) eq '${product["ITMREF"]}'&count=100`,
);
const stockAPI: type.stockResource[] = stockAPICall["$resources"];
// fetch sells
const sellsAPICall = await queryFrApi(
`https://x3.etcfr.f12cloud.pt:444/api1/x3/erp/X3V12_ETCFR/YCCPPRICLIST?representation=YCCPPRICLIST.$query&where=(PLICRI2) eq '${product["ITMREF"]}'`,
);
const sellsAPI: type.sellResource[] = sellsAPICall["$resources"];
// add the image to the products that have {}
if (product.IMG != null) {
typeof product.IMG === "object" && Object.keys(product.IMG).length === 0
? (product.IMG = await queryFrApi(
`https://x3.etcfr.f12cloud.pt:444/api1/x3/erp/X3V12_ETCFR/BDOC('C_YCCPRODUCT~%C2%A8~IMG~%C2%A8~ITM~%C2%A8~${product["ITMREF"]}~%C2%A8~')`,
))
: null;
}
const branchName = detailsAPI.$actxFolder;
const masterBranch = {
branchName: branchName,
language: detailsAPI.$actxLan,
};
const masterProduct = {
productName: product.ITMREF,
imageUrl: product.IMG,
description: product.ITMDES1,
branchName: branchName,
manufacturerPartNumber: product.$uuid,
categories: {
main: detailsAPI.ITMCZTSICOD?.[0]?.ZTSICOD,
sub: detailsAPI.ITMCZTSICOD?.[1]?.ZTSICOD,
leaf: detailsAPI.ITMCZTSICOD?.[2]?.ZTSICOD,
},
};
const masterManufacturer = {
name: "anonymous",
};
const masterSells = [];
for (const sell of sellsAPI) {
const filterSell: type.ObjectSell = {
price: sell.PRI,
partNumber: sell.PLICRI2,
productName: product.ITMREF,
manufacturerName: "anonymous",
branchName: branchName,
};
masterSells.push(filterSell);
}
const masterStocks = [];
const masterWarehouse = [];
for (const stock of stockAPI) {
const filterStock: type.ObjectStock = {
address: stock.STOFCY,
quantity: stock.SALSTO,
productName: product.ITMREF,
branchName: branchName,
};
masterStocks.push(filterStock);
const filterWarehouse = {
address: stock.STOFCY,
branchName: branchName,
};
masterWarehouse.push(filterWarehouse);
}
try {
const result = await sendToMasterData(masterBranch, "/addBranch");
if (result === 200) {
const results1 = await Promise.all([
sendToMasterData(masterProduct, "/addProduct"),
sendToMasterData(masterManufacturer, "/addManufacturer"),
Promise.all(masterWarehouse.map((warehouse) => sendToMasterData(warehouse, "/addWarehouse"))),
]);
if (results1.every((value) => value === 200)) {
const results2 = await Promise.all([
Promise.all(masterStocks.map((stock) => sendToMasterData(stock, "/addStock"))),
Promise.all(masterSells.map((sell) => sendToMasterData(sell, "/addSell"))),
]);
} else {
if (results1[0] !== 200) {
return {
statusCode: 200,
body: "An error occurred while adding product",
};
} else if (results1[1] !== 200) {
return {
statusCode: 200,
body: "An error occurred while adding manufacturer",
};
} else {
return {
statusCode: 200,
body: "An error occurred while adding warehouse",
};
}
}
} else {
return {
statusCode: 200,
body: "An error occurred while adding a branch",
};
}
} catch (error) {
console.error("An error occurred:", error);
return {
statusCode: 200,
body: "An error occurred",
};
}
const paramsDelete = {
QueueUrl: "https://sqs.eu-west-2.amazonaws.com/806798940075/product-headers-qeue-jm",
ReceiptHandle: receiptHandle,
};
await sqs.deleteMessage(paramsDelete).promise();
return { message: "ok" };
} catch (error) {
console.error("An error occurred:", error);
return {
statusCode: 200,
body: "An error occurred",
};
}
};
I hope this helps! Let me know if you have any questions or need further clarification.