diff --git a/app/utils/Logger.ts b/app/utils/Logger.ts index cffb2f8..dd27dd7 100644 --- a/app/utils/Logger.ts +++ b/app/utils/Logger.ts @@ -2,31 +2,31 @@ import fs from 'fs'; import moment from "moment"; -const shortenStringsInObject = (obj, maxLength) => { - // Kiểm tra nếu obj không phải là một đối tượng hoặc maxLength không phải là một số - if (typeof obj !== 'object' || typeof maxLength !== 'number') { - return obj; - } +// const shortenStringsInObject = (obj, maxLength) => { +// // Kiểm tra nếu obj không phải là một đối tượng hoặc maxLength không phải là một số +// if (typeof obj !== 'object' || typeof maxLength !== 'number') { +// return obj; +// } - // Duyệt qua các thuộc tính của đối tượng - for (const key in obj) { - if (obj.hasOwnProperty(key)) { - // Kiểm tra nếu thuộc tính là một chuỗi và độ dài của chuỗi lớn hơn maxLength - if (typeof obj[key] === 'string' && obj[key].length > maxLength) { - // Rút ngắn chuỗi lại maxLength ký tự - obj[key] = obj[key].substring(0, maxLength); - } - } - } +// // Duyệt qua các thuộc tính của đối tượng +// for (const key in obj) { +// if (obj.hasOwnProperty(key)) { +// // Kiểm tra nếu thuộc tính là một chuỗi và độ dài của chuỗi lớn hơn maxLength +// if (typeof obj[key] === 'string' && obj[key].length > maxLength) { +// // Rút ngắn chuỗi lại maxLength ký tự +// obj[key] = obj[key].substring(0, maxLength); +// } +// } +// } - if (Array.isArray(obj) && obj.length > 10) { - // Rút ngắn chuỗi lại maxLength ký tự - obj = "[Array:"+obj.length+"]\n"+obj.slice(0,15) - } +// if (Array.isArray(obj) && obj.length > 10) { +// // Rút ngắn chuỗi lại maxLength ký tự +// obj = "[Array:"+obj.length+"]\n"+obj.slice(0,15) +// } - return obj; - } +// return obj; +// } export function loggerAPI(req, res, location) { let old_data = ""; diff --git a/app/utils/addLogFunction.ts b/app/utils/addLogFunction.ts new file mode 100644 index 0000000..83571bd --- /dev/null +++ b/app/utils/addLogFunction.ts @@ -0,0 +1,34 @@ +import fs from "fs"; +import moment from "moment"; + +export const addLogFunction = async (fileName, data, functionName) => { + try { + fs.exists(fileName, async (exists) => { + if (exists) { + let old_data = await fs.readFileSync(fileName, "utf8"); + fs.writeFileSync( + fileName, + old_data + + "\n\n[" + + moment(Date.now()).format("D/M/YY-HH:mm:ss") + + "] - " + + functionName + + "\n" + + data + + "\n\n======================================================================" + ); + } else { + fs.writeFileSync( + fileName, + "\n\n[" + + moment(Date.now()).format("D/M/YY-HH:mm:ss") + + "] - System Logs" + + data + + "\n\n======================================================================" + ); + } + }); + } catch (error) { + console.log(error); + } +}; diff --git a/app/utils/addLogFunctionJS.js b/app/utils/addLogFunctionJS.js new file mode 100644 index 0000000..c1519a7 --- /dev/null +++ b/app/utils/addLogFunctionJS.js @@ -0,0 +1,36 @@ +const fs = require("fs"); +const moment = require("moment"); + +const addLogFunction = async (fileName, data, functionName) => { + try { + fs.exists(fileName, async (exists) => { + if (exists) { + let old_data = await fs.readFileSync(fileName, "utf8"); + fs.writeFileSync( + fileName, + old_data + + "\n\n[" + + moment(Date.now()).format("D/M/YY-HH:mm:ss") + + "] - " + + functionName + + "\n" + + data + + "\n\n======================================================================" + ); + } else { + fs.writeFileSync( + fileName, + "\n\n[" + + moment(Date.now()).format("D/M/YY-HH:mm:ss") + + "] - System Logs" + + data + + "\n\n======================================================================" + ); + } + }); + } catch (error) { + console.log(error); + } +}; + +module.exports.addLogFunction = addLogFunction; \ No newline at end of file diff --git a/app/utils/checkIndexSN.ts b/app/utils/checkIndexSN.ts index af7ae73..8847230 100644 --- a/app/utils/checkIndexSN.ts +++ b/app/utils/checkIndexSN.ts @@ -3,6 +3,8 @@ import Env from "@ioc:Adonis/Core/Env"; // import fs from "fs"; import axios from "axios"; +import { addLogFunction } from "./addLogFunction"; +import moment from "moment"; export const checkIndexSN = async (content, beginLine, nameF) => { try { @@ -195,6 +197,11 @@ export const checkIndexSN = async (content, beginLine, nameF) => { ); console.log(nameF + " response\n", response_int.data); + const fileName = + "./app/store/logsAPI/" + + moment(Date.now()).format("DD_MM_YYYY").toString() + + ".log"; + addLogFunction(fileName, "URL: https://int.ipsupply.com.au/api/transferPostData\n"+ response_int.data, "Update SN index to int.ipsupply.com.au"); } } } diff --git a/app/utils/powerSchedule.js b/app/utils/powerSchedule.js index 17d9134..dd82cf9 100644 --- a/app/utils/powerSchedule.js +++ b/app/utils/powerSchedule.js @@ -1,5 +1,6 @@ const puppeteer = require("puppeteer"); const zulip = require("zulip-js"); +const { addLogFunction } = require("./addLogFunctionJS"); (async () => { // Launch a headless browser @@ -60,8 +61,8 @@ const zulip = require("zulip-js"); ) { let params = { type: "stream", - to: "Result test - auto.nswteam.net", - topic: "Lịch cúp điện", + to: "APAC Tech Bão", + topic: "Thông báo chung", content: ":warning: :date: :warning:\n\n" + tableData @@ -72,4 +73,9 @@ const zulip = require("zulip-js"); client.messages.send(params); } }, 5000); + const fileName = + "./app/store/logsAPI/" + + moment(Date.now()).format("DD_MM_YYYY").toString() + + ".log"; + addLogFunction(fileName, JSON.stringify(params, null, 2), "powerSchedule") })(); diff --git a/app/utils/runtimeCheckLogs.ts b/app/utils/runtimeCheckLogs.ts index 2b29ecd..a7e378d 100644 --- a/app/utils/runtimeCheckLogs.ts +++ b/app/utils/runtimeCheckLogs.ts @@ -73,8 +73,8 @@ export async function runtimeCheckLogs(folderPath) { if ( filePath?.split(".")[filePath.split(".").length - 1] === "log" && filePath.split("/")[filePath.split("/").length - 1]?.split("-")[0] === - //localhost - // filePath.split("\\")[filePath.split("\\").length - 1]?.split("-")[0] === + //localhost + // filePath.split("\\")[filePath.split("\\").length - 1]?.split("-")[0] === moment(Date.now()).format("YYYYMMDD").toString() ) { //add information file to database @@ -99,86 +99,163 @@ export async function runtimeCheckLogs(folderPath) { // Watch for changes in the files listed async function watchFilesInList() { - //only check new file ---> fileList - fileList_old = new file - let listFileWatch = fileList - ?.filter((i) => fileList_old.includes(i) === false) - .map((file) => folderPath + "/" + file); - const watcher = chokidar.watch(listFileWatch, { - persistent: true, - usePolling: true, - interval: 300000, - }); + try { + //only check new file ---> fileList - fileList_old = new file + let listFileWatch = fileList + ?.filter((i) => fileList_old.includes(i) === false && i.includes(".log")) + .map((file) => folderPath + "/" + file); + const watcher = chokidar.watch(listFileWatch, { + persistent: true, + usePolling: true, + interval: 300000, + }); - watcher.setMaxListeners(200); + watcher.setMaxListeners(200); - watcher.on("change", async (path) => { - // fs.watchFile(filePath,{ interval: 15000 }, - // async (eventType) => { - //check special item, extra RAM, error in log - const fileName = path.split("/")[path.split("/").length - 1]; - // const fileName = path.split("\\")[path.split("\\").length - 1]; - const filePath = path; - let lines = []; - const today = DateTime.now().toFormat("yyyy-MM-dd"); - let allFile = await LogDetectFile.query().whereRaw( - `DATE(created_at) = ?`, - [today] - ); - // let allReport = await LogReport.all(); - let allValue = await KeyValue.all(); - const allReport = await LogReport.query().whereRaw( - `DATE(created_at) = ?`, - [today] - ); + watcher.on("change", async (path) => { + // fs.watchFile(filePath,{ interval: 15000 }, + // async (eventType) => { + //check special item, extra RAM, error in log + const fileName = path.split("/")[path.split("/").length - 1]; + // const fileName = path.split("\\")[path.split("\\").length - 1]; + const filePath = path; + let lines = []; + const today = DateTime.now().toFormat("yyyy-MM-dd"); + let allFile = await LogDetectFile.query().whereRaw( + `DATE(created_at) = ?`, + [today] + ); + // let allReport = await LogReport.all(); + let allValue = await KeyValue.all(); + const allReport = await LogReport.query().whereRaw( + `DATE(created_at) = ?`, + [today] + ); - //get information file - let fileDetect = allFile?.filter( - (i) => i.$original.file_name === fileName - )[0]; + //get information file + let fileDetect = allFile?.filter( + (i) => i.$original.file_name === fileName + )[0]; - let logsDetect = allReport?.filter( - (i) => i.$original.id_file === fileDetect?.id_ldf - ); - //get the last line detected - let lastLine = Math.max(...logsDetect.map((obj) => obj.line)); + let logsDetect = allReport?.filter( + (i) => i.$original.id_file === fileDetect?.id_ldf + ); + //get the last line detected + let lastLine = Math.max(...logsDetect.map((obj) => obj.line)); - //get content file in local - let contentFile = await fs - .readFileSync(filePath) - .toString() - ?.split("\n"); + //get content file in local + let contentFile = await fs + .readFileSync(filePath) + .toString() + ?.split("\n"); - //get index SN and send to ERP + //get index SN and send to ERP - checkIndexSN(contentFile, lastLine, fileName); + checkIndexSN(contentFile, lastLine, fileName); - //get list item to check - let listKeyValues = allValue.filter( - (i) => - i.$original.key === "MODEL_SPECIAL" || - i.$original.key === "CATCH_FAULTY" - ); + //get list item to check + let listKeyValues = allValue.filter( + (i) => + i.$original.key === "MODEL_SPECIAL" || + i.$original.key === "CATCH_FAULTY" + ); - //get list exclude error - let listExcludeErr = allValue - .filter((i) => i.$original.key === "EXCLUDE_ERR") - .map((obj) => obj.$original.value); + //get list exclude error + let listExcludeErr = allValue + .filter((i) => i.$original.key === "EXCLUDE_ERR") + .map((obj) => obj.$original.value); - //get list item special - let listExtraItem = allValue - .filter((i) => i.$original.key === "MODEL_SPECIAL") - .map((obj) => obj.$original.value); + //get list item special + let listExtraItem = allValue + .filter((i) => i.$original.key === "MODEL_SPECIAL") + .map((obj) => obj.$original.value); - //Process file content - if (contentFile.length > 50000) { - for (let i = 0; i < contentFile.length; i += 1000) { - const chunk = contentFile.slice(i, i + 1000); + //Process file content + if (contentFile.length > 50000) { + for (let i = 0; i < contentFile.length; i += 1000) { + const chunk = contentFile.slice(i, i + 1000); - chunk.map(async (line, index) => { + chunk.map(async (line, index) => { + //check line the line with errors and exclude errors + listKeyValues + .map((obj) => obj.$original.value) + .map(async (value) => { + if ( + line.includes(value) && + listExcludeErr.filter((err) => line.includes(err)) + .length === 0 + ) { + let log = allFile?.filter( + (i) => i.$original.file_name === fileName + )[0]; + + let checkLog = allReport?.filter( + (report) => + report.$original.id_file === log?.id_ldf && + report.$original.line === index + 1 && + report.$original.detected_content === value + ); + + if ( + log?.id_ldf === "" || + log?.id_ldf === null || + log?.id_ldf === undefined + ) { + console.log("ERROR CHECK ", fileName) + } + if (checkLog?.length === 0) { + await LogReport.create({ + detected_content: value, + line: index + 1, + id_file: log?.id_ldf, + }); + lines.push(index + 1); + } + } + + }); + + if ( + checkSpecialVersion(line) !== "" && + listExcludeErr.filter((err) => line.includes(err)).length === + 0 + ) { + let checkVersion = checkSpecialVersion(line); + let log = allFile?.filter( + (i) => i.$original.file_name === fileName + )[0]; + if ( + log?.id_ldf === "" || + log?.id_ldf === null || + log?.id_ldf === undefined + ) { + console.log("ERROR CHECK ", fileName) + } + let checkLog = allReport?.filter( + (report) => + report.$original.id_file === log?.id_ldf && + report.$original.line === index + 1 && + report.$original.detected_content === checkVersion + ); + + if (checkLog?.length === 0) { + await LogReport.create({ + detected_content: checkVersion, + line: index + 1, + id_file: log?.id_ldf, + }); + lines.push(index + 1); + } + } + }); + } + } else { + contentFile.map(async (line, index) => { //check line the line with errors and exclude errors listKeyValues .map((obj) => obj.$original.value) .map(async (value) => { + if ( line.includes(value) && listExcludeErr.filter((err) => line.includes(err)) @@ -187,7 +264,13 @@ export async function runtimeCheckLogs(folderPath) { let log = allFile?.filter( (i) => i.$original.file_name === fileName )[0]; - + if ( + log?.id_ldf === "" || + log?.id_ldf === null || + log?.id_ldf === undefined + ) { + console.log("ERROR CHECK ", fileName) + } let checkLog = allReport?.filter( (report) => report.$original.id_file === log?.id_ldf && @@ -216,7 +299,13 @@ export async function runtimeCheckLogs(folderPath) { let log = allFile?.filter( (i) => i.$original.file_name === fileName )[0]; - + if ( + log?.id_ldf === "" || + log?.id_ldf === null || + log?.id_ldf === undefined + ) { + console.log("ERROR CHECK ", fileName) + } let checkLog = allReport?.filter( (report) => report.$original.id_file === log?.id_ldf && @@ -235,189 +324,117 @@ export async function runtimeCheckLogs(folderPath) { } }); } - } else { - contentFile.map(async (line, index) => { - //check line the line with errors and exclude errors - listKeyValues - .map((obj) => obj.$original.value) - .map(async (value) => { - // console.log({line:Array(line), value:Array(value)}) - if ( - line.includes(value) && - listExcludeErr.filter((err) => line.includes(err)).length === - 0 - ) { - let log = allFile?.filter( - (i) => i.$original.file_name === fileName - )[0]; - let checkLog = allReport?.filter( - (report) => - report.$original.id_file === log?.id_ldf && - report.$original.line === index + 1 && - report.$original.detected_content === value - ); + //true: import log to log_report table, send report to Zulip + setTimeout(async () => { + if (lines.length === 0) { + console.log( + fileName + "has changed(" + contentFile.length + ") ---Good" + ); + } else { + console.log( + fileName + + "has changed(" + + contentFile.length + + ") ---SOS---" + + lines.length + ); + let allReport_new = await LogReport.query().whereRaw( + `DATE(created_at) = ?`, + [today] + ); - if (checkLog?.length === 0) { - await LogReport.create({ - detected_content: value, - line: index + 1, - id_file: log?.id_ldf, - }); - lines.push(index + 1); - } - } - - // if(checkSpecialVersion()) - }); - - if ( - checkSpecialVersion(line) !== "" && - listExcludeErr.filter((err) => line.includes(err)).length === 0 - ) { - let checkVersion = checkSpecialVersion(line); - let log = allFile?.filter( + let fileDetect = allFile?.filter( (i) => i.$original.file_name === fileName )[0]; - let checkLog = allReport?.filter( - (report) => - report.$original.id_file === log?.id_ldf && - report.$original.line === index + 1 && - report.$original.detected_content === checkVersion + let logsDetect = allReport_new?.filter( + (i) => i.$original.id_file === fileDetect?.id_ldf + ); + + //Get all report newest + let listReport = await getListLineByItem( + logsDetect + .map((obj) => obj.$original) + .filter((l) => l.line > lastLine) ); - if (checkLog?.length === 0) { - await LogReport.create({ - detected_content: checkVersion, - line: index + 1, - id_file: log?.id_ldf, + let content = + "| |Last updated at | Item/error | Line | Report \n|---|:---:|:---|:---|:-----------:\n"; + let spoiler = ""; + let issueFound = ""; + let important = [ + "Vxx", + "V00", + "(CAT3K_CAA-UNIVERSALK9-M), Version", + ]; + listReport.map((log, index) => { + let item = listExtraItem.includes(log.detected_content) + ? ":medal: **" + log.detected_content + "**" + : ":small_orange_diamond: " + log.detected_content; + + log.line?.map((line) => { + issueFound = + issueFound + + "\n`" + + line + + "` " + + contentFile[line - 1]?.replace( + log.detected_content, + "[" + + log.detected_content + + "](https://logs.danielvu.com/logs/" + + fileName + + "#" + + line + + ")" + ); }); - lines.push(index + 1); - } - } - }); - } - - //true: import log to log_report table, send report to Zulip - setTimeout(async () => { - if (lines.length === 0) { - console.log( - fileName + "has changed(" + contentFile.length + ") ---Good" - ); - } else { - console.log( - fileName + - "has changed(" + - contentFile.length + - ") ---SOS---" + - lines.length - ); - let allReport_new = await LogReport.query().whereRaw( - `DATE(created_at) = ?`, - [today] - ); - - let fileDetect = allFile?.filter( - (i) => i.$original.file_name === fileName - )[0]; - - let logsDetect = allReport_new?.filter( - (i) => i.$original.id_file === fileDetect?.id_ldf - ); - // console.log(logsDetect) - // await Database.rawQuery( - // "select * from log_reports where id_file = " + - // fileDetect?.id_ldf - // ); - //Get all report newest - let listReport = await getListLineByItem( - logsDetect - .map((obj) => obj.$original) - .filter((l) => l.line > lastLine) - ); - - let content = - "| |Last updated at | Item/error | Line | Report \n|---|:---:|:---|:---|:-----------:\n"; - let spoiler = ""; - let issueFound = ""; - let important = [ - "Vxx", - "V00", - "(CAT3K_CAA-UNIVERSALK9-M), Version", - ]; - listReport.map((log, index) => { - let item = listExtraItem.includes(log.detected_content) - ? ":medal: **" + log.detected_content + "**" - : ":small_orange_diamond: " + log.detected_content; - - log.line?.map((line) => { - issueFound = - issueFound + - "\n`" + - line + - "` " + - contentFile[line - 1]?.replace( - log.detected_content, - "[" + - log.detected_content + - "](https://logs.danielvu.com/logs/" + - fileName + - "#" + - line + - ")" - ); - }); - content = - content + - "|" + - (index + 1) + - "|**" + - moment(Date.now()).format("HH:mm - DD/MM") + - "**|" + - item + - "|" + - log.line + - "|[View](https://logs.danielvu.com/logs/" + - fileName + - "#" + - log.line + - ")\n"; - }); - - let icon = - important.filter((i) => content.includes(i)).length > 0 - ? "------------\n\n:no_entry: :no_entry:**" + + content = + content + + "|" + + (index + 1) + + "|**" + + moment(Date.now()).format("HH:mm - DD/MM") + + "**|" + + item + + "|" + + log.line + + "|[View](https://logs.danielvu.com/logs/" + fileName + - "**:no_entry: :no_entry:" - : "------------\n\n:warning: :warning: **" + fileName + "**"; - sendMessToZulip( - "stream", - Env.get("ZULIP_STREAM_ALERT"), - Env.get("ZULIP_TOPIC_ALERT"), - icon + - "\n\n" + - content + - "\n\n" + - spoiler + - "\n\n***Issue found:***\n" + - issueFound - ); - } - }, 3000); - // console.log(path + " change") - }); + "#" + + log.line + + ")\n"; + }); - watcher.on("error", (error) => { - console.error(`Watcher error: ${error}`); - }); - // await fileList.slice(0,40) - // ?.filter((i) => fileList_old.includes(i) === false) - // ?.forEach((fileName) => { - // //path file - // const filePath = `${folderPath}/${fileName}`; + let icon = + important.filter((i) => content.includes(i)).length > 0 + ? "------------\n\n:no_entry: :no_entry:**" + + fileName + + "**:no_entry: :no_entry:" + : "------------\n\n:warning: :warning: **" + fileName + "**"; + sendMessToZulip( + "stream", + Env.get("ZULIP_STREAM_ALERT"), + Env.get("ZULIP_TOPIC_ALERT"), + icon + + "\n\n" + + content + + "\n\n" + + spoiler + + "\n\n***Issue found:***\n" + + issueFound + ); + } + }, 3000); + }); - // }); + watcher.on("error", (error) => { + console.error(`Watcher error: ${error}`); + }); + } catch (error) { + console.log(error); + } } } catch (error) { console.log(error); diff --git a/app/utils/screenshot.png b/app/utils/screenshot.png deleted file mode 100644 index e567c3a..0000000 Binary files a/app/utils/screenshot.png and /dev/null differ diff --git a/app/utils/sendDeviceInfor.ts b/app/utils/sendDeviceInfor.ts index c2f6074..e4a1959 100644 --- a/app/utils/sendDeviceInfor.ts +++ b/app/utils/sendDeviceInfor.ts @@ -5,6 +5,7 @@ import nodeMailer from "nodemailer"; import LogDetectFile from "App/Models/LogDetectFile"; import InfoDevice from "App/Models/InfoDevice"; import KeyValue from "App/Models/KeyValue"; +import { addLogFunction } from "./addLogFunction"; export const sendDeviceInfora = async () => { try { @@ -14,10 +15,11 @@ export const sendDeviceInfora = async () => { const regexVersion = /sh.*? ver.*/; const regexMemory = /(\d+)K/g; const date = moment(Date.now()).format("YYYYMMDD"); - const memDefault = (await KeyValue.all()) + const allKeyValue = await KeyValue.all(); + const memDefault = allKeyValue .filter((i) => i.$attributes.key === "MEMORY_DEFAULT") .map((obj) => obj.$attributes.value); - const listInformation = []; + let listInformation = []; let dataFile = await LogDetectFile.all(); let html = ""; @@ -38,300 +40,283 @@ export const sendDeviceInfora = async () => { }); //Read file in listFile - await listFile.map(async (file) => { - fs.readFile( - Env.get("FOLDER_LOGS") + "/" + file, - "utf8", - async (err, data) => { - if (err) { - console.log(`Error reading file: ${err}`); - } else { - //Array line - const lines = data?.split("\n"); - const linesInventory = []; - let DBFileCheck = dataFile.filter( - (i) => i.$attributes.file_name === file - )[0]; - if (DBFileCheck !== undefined) { - if (lines.length > DBFileCheck?.$extras.last_check_SN) { - const DBFile = await LogDetectFile.find( - DBFileCheck?.$attributes.id_ldf - ); - - // console.log(DBFile) - - DBFile.last_check_SN = lines.length; - await DBFile.save(); - } + const filePromises = listFile.map((file, index) => { + return new Promise((resolve, reject) => { + fs.readFile( + Env.get("FOLDER_LOGS") + "/" + file, + "utf8", + async (err, data) => { + if (err) { + console.log(`Error reading file: ${err}`); } else { - await LogDetectFile.firstOrCreate( - { file_name: file }, - { file_name: file } - ); - - dataFile = await LogDetectFile.all(); - DBFileCheck = dataFile.filter( + //Array line + const lines = data?.split("\n"); + const linesInventory = []; + let DBFileCheck = dataFile.filter( (i) => i.$attributes.file_name === file )[0]; - } - - //Get index of "lines" with show inv - lines - ?.slice(DBFileCheck?.$extras.last_check_SN, lines.length - 1) - .map((line, index) => { - if (line.match(regexInventory) !== null) { - linesInventory.push(index); - } - }); - - //cut content with content1 = [linesInventory[index],linesInventory[index+1]] ... - linesInventory?.map((line, index) => { - const deviceContent = lines?.slice( - linesInventory[index], - linesInventory[index + 1] - ); - - let backgroundColor = "rgb(200 200 200 / 30%)"; - const showInventory = []; - let check = true; - let begin = 0; - let end = 4; - - //get showInventory content - while (check === true) { - if ( - deviceContent - .slice(begin, end) - .filter( - (i) => - i.includes("PID:") && - i.includes("VID:") && - i.includes("SN:") - ).length > 0 - ) { - showInventory.push( - deviceContent.slice(begin, end).join("\n") + if (DBFileCheck !== undefined) { + if (lines.length > DBFileCheck?.$extras.last_check_SN) { + const DBFile = await LogDetectFile.find( + DBFileCheck?.$attributes.id_ldf ); - begin = end; - end = end + 4; - } else { - check = false; + + // console.log(DBFile) + + DBFile.last_check_SN = lines.length; + await DBFile.save(); } + } else { + await LogDetectFile.firstOrCreate( + { file_name: file }, + { file_name: file } + ); + + dataFile = await LogDetectFile.all(); + DBFileCheck = dataFile.filter( + (i) => i.$attributes.file_name === file + )[0]; } - const showInventoryContent = showInventory - .join("\n") - .split("\n") - .filter( - (i) => - i.includes("PID:") && - i.includes("VID:") && - i.includes("SN:") + //Get index of "lines" with show inv + lines + ?.slice(DBFileCheck?.$extras.last_check_SN, lines.length - 1) + .map((line, index) => { + if (line.match(regexInventory) !== null) { + linesInventory.push(index); + } + }); + + //cut content with content1 = [linesInventory[index],linesInventory[index+1]] ... + linesInventory?.map((line, index) => { + const deviceContent = lines?.slice( + linesInventory[index], + linesInventory[index + 1] ); - //show version exists - if ( - deviceContent.filter( - (line) => line.match(regexVersion) !== null - ).length > 0 - ) { - const lineShowver = deviceContent.indexOf( + let backgroundColor = "rgb(200 200 200 / 30%)"; + const showInventory = []; + let check = true; + let begin = 0; + let end = 4; + + //get showInventory content + while (check === true) { + if ( + deviceContent + .slice(begin, end) + .filter( + (i) => + i.includes("PID:") && + i.includes("VID:") && + i.includes("SN:") + ).length > 0 + ) { + showInventory.push( + deviceContent.slice(begin, end).join("\n") + ); + begin = end; + end = end + 4; + } else { + check = false; + } + } + + const showInventoryContent = showInventory + .join("\n") + .split("\n") + .filter( + (i) => + i.includes("PID:") && + i.includes("VID:") && + i.includes("SN:") + ); + + //show version exists + if ( deviceContent.filter( (line) => line.match(regexVersion) !== null - )[0] - ); - - const showVersion = deviceContent.slice( - lineShowver, - deviceContent.indexOf( + ).length > 0 + ) { + const lineShowver = deviceContent.indexOf( deviceContent.filter( - (line) => line.search("Configuration register") !== -1 + (line) => line.match(regexVersion) !== null )[0] - ) + 1 - ); + ); - showInventoryContent.map((u, index) => { - const PID = u - ?.split("VID:")[0] - ?.split("PID:")[1] - ?.replace(/,/g, "") - .trim(); - const VID = u - ?.split("VID:")[1] - ?.split("SN:")[0] - ?.replace(/,/g, "") - .trim(); - const SN = u?.split("SN:")[1]?.replace(/,/g, "").trim(); - // let memory = - if (index > 0) { - if (PID !== "" && SN !== "") { - listInformation.push({ - PID: PID, - VID: VID, - SN: SN, - RAM: "", - flash: "", - extra_item: "yes", - }); + const showVersion = deviceContent.slice( + lineShowver, + deviceContent.indexOf( + deviceContent.filter( + (line) => line.search("Configuration register") !== -1 + )[0] + ) + 1 + ); - html += `${PID} - ${VID} - ${SN} - - - yes`; - } - } else { - if (PID !== "" && SN !== "") { - const memDefaultForPID = - memDefault.filter((i) => - PID.includes(i.split(":")[0]) - )[0] !== undefined - ? memDefault.filter((i) => - PID.includes(i.split(":")[0]) - )[0] - : PID + ":N/A:N/A"; - let RAM = - showVersion - .filter( - (line) => - line.includes("bytes of memory") || - line.includes("bytes of physical memory") - ) - .join("
") - .match(regexMemory) !== null - ? ( - parseInt( - showVersion - .filter( - (line) => - line.includes("bytes of memory") || - line.includes("bytes of physical memory") - ) - .join("
") - .match(regexMemory)[0] - ) / - 1024 / - 1024 - ).toFixed(2) + - "G (D: " + - memDefaultForPID.split(":")[1] + - ")" - : ""; - - let flash = showVersion - .filter((line) => - line.toLocaleLowerCase().includes("compactflash") - ) - .join("
"); - listInformation.push({ - PID: PID, - VID: VID, - SN: SN, - RAM: RAM, - flash: - flash.match(regexMemory) !== null + showInventoryContent.map((u, index) => { + const PID = u + ?.split("VID:")[0] + ?.split("PID:")[1] + ?.replace(/,/g, "") + .trim(); + const VID = u + ?.split("VID:")[1] + ?.split("SN:")[0] + ?.replace(/,/g, "") + .trim(); + const SN = u?.split("SN:")[1]?.replace(/,/g, "").trim(); + if (index > 0) { + if (PID !== "" && SN !== "") { + listInformation.push({ + PID: PID, + VID: VID, + SN: SN, + RAM: "", + flash: "", + extra_item: "yes", + }); + } + } else { + if (PID !== "" && SN !== "") { + const memDefaultForPID = + memDefault.filter((i) => + PID.includes(i.split(":")[0]) + )[0] !== undefined + ? memDefault.filter((i) => + PID.includes(i.split(":")[0]) + )[0] + : PID + ":N/A:N/A"; + let RAM = + showVersion + .filter( + (line) => + line.includes("bytes of memory") || + line.includes("bytes of physical memory") + ) + .join("
") + .match(regexMemory) !== null ? ( - parseInt(flash.match(regexMemory)[0]) / + parseInt( + showVersion + .filter( + (line) => + line.includes("bytes of memory") || + line.includes( + "bytes of physical memory" + ) + ) + .join("
") + .match(regexMemory)[0] + ) / 1024 / 1024 ).toFixed(2) + "G (D: " + - memDefaultForPID.split(":")[2] + + memDefaultForPID.split(":")[1] + ")" - : "", - extra_item: "no", - }); + : ""; - html += `${PID} - ${VID} - ${SN} - ${RAM} - ${ - flash.match(regexMemory) !== null - ? ( - parseInt(flash.match(regexMemory)[0]) / - 1024 / - 1024 - ).toFixed(2) + - "G (D: " + - memDefaultForPID.split(":")[2] + - ")" - : "" - } - no`; + let flash = showVersion + .filter((line) => + line.toLocaleLowerCase().includes("compactflash") + ) + .join("
"); + listInformation.push({ + PID: PID, + VID: VID, + SN: SN, + RAM: RAM, + flash: + flash.match(regexMemory) !== null + ? ( + parseInt(flash.match(regexMemory)[0]) / + 1024 / + 1024 + ).toFixed(2) + + "G (D: " + + memDefaultForPID.split(":")[2] + + ")" + : "", + extra_item: "no", + }); + } } - } - }); - } else { - //show version not exists --> RAM = N/A, Flash = N/A - showInventoryContent.map((u, index) => { - const PID = u - ?.split("VID:")[0] - ?.split("PID:")[1] - ?.replace(/,/g, "") - .trim(); - const VID = u - ?.split("VID:")[1] - ?.split("SN:")[0] - ?.replace(/,/g, "") - .trim(); - const SN = u?.split("SN:")[1]?.replace(/,/g, "").trim(); + }); + } else { + //show version not exists --> RAM = N/A, Flash = N/A + showInventoryContent.map((u, index) => { + const PID = u + ?.split("VID:")[0] + ?.split("PID:")[1] + ?.replace(/,/g, "") + .trim(); + const VID = u + ?.split("VID:")[1] + ?.split("SN:")[0] + ?.replace(/,/g, "") + .trim(); + const SN = u?.split("SN:")[1]?.replace(/,/g, "").trim(); - if (index > 0) { - if (PID !== "" && SN !== "") { - listInformation.push({ - PID: PID, - VID: VID, - SN: SN, - RAM: "", - flash: "", - extra_item: "yes", - }); - - html += `${PID} - ${VID} - ${SN} - - - yes`; + if (index > 0) { + if (PID !== "" && SN !== "") { + listInformation.push({ + PID: PID, + VID: VID, + SN: SN, + RAM: "", + flash: "", + extra_item: "yes", + }); + } + } else { + if (PID !== "" && SN !== "") { + listInformation.push({ + PID: PID, + VID: VID, + SN: SN, + RAM: "", + flash: "", + extra_item: "no", + }); + } } - } else { - if (PID !== "" && SN !== "") { - listInformation.push({ - PID: PID, - VID: VID, - SN: SN, - RAM: "", - flash: "", - extra_item: "no", - }); - - html += `${PID} - ${VID} - ${SN} - - - no`; - } - } - }); - } - }); + }); + } + }); + } + resolve(0); } - } - ); + ); + }); }); - setTimeout(async () => { - if (listInformation.length > 0) { - console.log(listInformation); - const options = { - from: "admin@apactech.io", - to: "joseph@apactech.io, ips@ipsupply.com.au", - subject: "(AUTO-REPORT) SERIAL NUMBER", - html: - "\ + await Promise.all(filePromises); + let specialModel = allKeyValue + .filter((i) => i.key === "MODEL_SPECIAL") + .map((obj) => obj.$attributes.value); + listInformation = listInformation.filter( + (i) => + i.RAM !== "" || + i.flash !== "" || + specialModel.filter((m) => i.PID.includes(m)).length > 0 + ); + if (listInformation.length > 0) { + console.log(listInformation); + listInformation.map((inf) => { + html += ` + + + + + `; + }); + const options = { + from: "admin@apactech.io", + // to: "joseph@apactech.io, ips@ipsupply.com.au", + to: "joseph@apactech.io", + subject: "(AUTO-REPORT) SERIAL NUMBER", + html: + "
${inf.PID}${inf.VID}${inf.SN}${inf.RAM}${inf.flash}${inf.extra_item}
\ \ \ \ @@ -343,15 +328,26 @@ export const sendDeviceInfora = async () => { \ \ " + - html + - "\ + html + + "\
PID
", - }; - transporter.sendMail(options); + }; + transporter.sendMail(options); + await InfoDevice.createMany(listInformation); + const fileName = + "./app/store/logsAPI/" + + moment(Date.now()).format("DD_MM_YYYY").toString() + + ".log"; - await InfoDevice.createMany(listInformation); - } - }, 5000); + addLogFunction( + fileName, + JSON.stringify(listInformation[0], null, 2), + "Get-Send devices info" + ); + + } else { + console.log("listInformation", listInformation); + } } catch (error) { console.log(error); } diff --git a/app/utils/sendStatusOtherSystem.js b/app/utils/sendStatusOtherSystem.js new file mode 100644 index 0000000..361d7aa --- /dev/null +++ b/app/utils/sendStatusOtherSystem.js @@ -0,0 +1,1214 @@ +const axios = require("axios"); +const crypto = require("crypto"); +const moment = require("moment"); +const zulip = require("zulip-js"); +const { exec } = require("child_process"); +const fs = require("fs"); +const { addLogFunction } = require("./addLogFunctionJS"); + +const config = { + username: "networktool-bot@zulip.ipsupply.com.au", + apiKey: "0jMAmOuhfLvBqKJikv5oAkyNM4RIEoAM", + realm: "https://zulip.ipsupply.com.au", +}; + +const checkMultipleRequest = async () => { + try { + let report = []; + let time = moment(Date.now()).format("HH:mm - DD/MM"); + const client = await zulip(config); + + const code = Math.random().toString(36).substring(2, 12); + const secretString = + code + "24feca0508b52d34b51db4b40964e7fff12edf71208a4607126f75cb5d504f7f"; + const accessToken = crypto + .createHash("md5") + .update(secretString) + .digest("hex"); + const tokenInt = + "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2ludC5pcHN1cHBseS5jb20uYXUvYXBpL2xvZ2luIiwiaWF0IjoxNjg5ODYyNjAxLCJleHAiOjE3MjEzOTg2MDEsIm5iZiI6MTY4OTg2MjYwMSwianRpIjoiUElZVjNBM3ZPQVlMQ081SyIsInN1YiI6MSwicHJ2IjoiYzhlZTFmYzg5ZTc3NWVjNGM3Mzg2NjdlNWJlMTdhNTkwYjZkNDBmYyJ9.UcybIKMBjTAY9i0PfIDQMtqHyN72Ul0jC03ZDGLGpMI"; + let content = "||Server| System time| Status \n|---|:---|:---|:---:\n"; + // Tạo tiêu đề + + let allResponse = ""; + const requests = [ + //Ebay Systems + { + url: "https://disti.danielvu.com/api/eBayCustomerLog", + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json", + loginid: null, + Code: code, + AccessToken: accessToken, + }, + data: {}, + name: "Ebay customer", + group: "Ebay Systems", + }, + { + url: "https://disti.danielvu.com/api/eBayNewItemLog", + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json", + loginid: null, + Code: code, + AccessToken: accessToken, + }, + data: {}, + name: "New item", + group: "Ebay Systems", + }, + { + url: "https://disti.danielvu.com/api/eBayChatLog", + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json", + loginid: null, + Code: code, + AccessToken: accessToken, + }, + data: {}, + name: "Ebay message", + group: "Ebay Systems", + }, + { + url: "https://disti.danielvu.com/api/sendSellerOrderToERP", + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json", + loginid: null, + Code: code, + AccessToken: accessToken, + }, + data: {}, + name: "Erp Sync Order Ebay", + group: "Ebay Systems", + }, + { + url: "https://disti.danielvu.com/api/sendBuyerOrderToERP", + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json", + loginid: null, + Code: code, + AccessToken: accessToken, + }, + data: {}, + name: "Erp Sync PO Ebay", + group: "Ebay Systems", + }, + //ERP Systems + { + url: "https://int.ipsupply.com.au/api/transferGetData", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer " + tokenInt, + }, + data: { + urlAPI: "/api/test-log-serial-number/sync-data", + filter: {}, + }, + name: "Log SN to ERP", + group: "ERP Systems", + }, + { + url: "https://int.ipsupply.com.au/api/transferGetData", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer " + tokenInt, + }, + data: { + urlAPI: "/api/stock-model-serial/check-sn-cisco", + filter: {}, + }, + name: "SN Cisco to ERP", + group: "ERP Systems", + }, + { + url: "https://int.ipsupply.com.au/api/transferPostData", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer " + tokenInt, + }, + data: { + urlAPI: "/api/logistics/check-shipping-rates", + data: { + courierName: "Fedex", + packageInfo: { + from: { + streetLines: ["8/4A Bachell Ave"], + city: "Lidcombe", + stateOrProvinceCode: "", + postalCode: "2141", + countryCode: "AU", + }, + to: { + streetLines: ["600 Terminal Dr"], + city: "Louisville", + stateOrProvinceCode: "KY", + postalCode: "40209", + countryCode: "US", + }, + requestedPackageLineItems: [ + { + weight: { + value: 10, + units: "KG", + }, + dimensions: { + length: 2, + width: 3, + height: 4, + units: "CM", + }, + groupPackageCount: 1, + }, + ], + commodities: [ + { + description: "G6", + quantity: 2, + quantityUnits: "PCS", + unitPrice: { + amount: 10000, + currency: "USD", + }, + customsValue: { + amount: 10000, + currency: "USD", + }, + }, + ], + inforCreateFedex: { + pickupType: "CONTACT_FEDEX_TO_SCHEDULE", + }, + }, + }, + }, + name: "Shipping rate Fedex", + group: "Shipping System", + }, + { + url: "https://int.ipsupply.com.au/api/transferPostData", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer " + tokenInt, + }, + data: { + urlAPI: "/api/logistics/check-shipping-rates", + data: { + courierName: "DHL", + packageInfo: { + from: { + streetLines: ["8/4A Bachell Ave"], + city: "Lidcombe", + stateOrProvinceCode: "", + postalCode: "2141", + countryCode: "AU", + }, + to: { + streetLines: ["600 Terminal Dr"], + city: "Louisville", + stateOrProvinceCode: "KY", + postalCode: "40209", + countryCode: "US", + }, + requestedPackageLineItems: [ + { + weight: { + value: 10, + units: "KG", + }, + dimensions: { + length: 2, + width: 3, + height: 4, + units: "CM", + }, + groupPackageCount: 1, + }, + ], + commodities: [ + { + description: "G6", + quantity: 2, + quantityUnits: "PCS", + unitPrice: { + amount: 10000, + currency: "USD", + }, + customsValue: { + amount: 10000, + currency: "USD", + }, + }, + ], + inforCreateFedex: { + pickupType: "CONTACT_FEDEX_TO_SCHEDULE", + }, + }, + }, + }, + name: "Shipping rate DHL", + group: "Shipping System", + }, + { + url: "https://int.ipsupply.com.au/api/transferPostData", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer " + tokenInt, + }, + data: { + urlAPI: "/api/logistics/check-shipping-rates", + data: { + courierName: "Transdirect", + packageInfo: { + from: { + streetLines: ["8/4A Bachell Ave"], + city: "Lidcombe", + stateOrProvinceCode: "", + postalCode: "2141", + countryCode: "AU", + }, + to: { + streetLines: ["600 Terminal Dr"], + city: "Louisville", + stateOrProvinceCode: "KY", + postalCode: "40209", + countryCode: "US", + }, + requestedPackageLineItems: [ + { + weight: { + value: 10, + units: "KG", + }, + dimensions: { + length: 2, + width: 3, + height: 4, + units: "CM", + }, + groupPackageCount: 1, + }, + ], + commodities: [ + { + description: "G6", + quantity: 2, + quantityUnits: "PCS", + unitPrice: { + amount: 10000, + currency: "USD", + }, + customsValue: { + amount: 10000, + currency: "USD", + }, + }, + ], + inforCreateFedex: { + pickupType: "CONTACT_FEDEX_TO_SCHEDULE", + }, + }, + }, + }, + name: "Shipping rate Transdirect", + group: "Shipping System", + }, + { + url: "https://int.ipsupply.com.au/api/transferPostData", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer " + tokenInt, + }, + data: { + urlAPI: "/api/logistics/check-shipping-rates", + data: { + courierName: "CouriersPlease", + packageInfo: { + from: { + streetLines: ["8/4A Bachell Ave"], + city: "Lidcombe", + stateOrProvinceCode: "", + postalCode: "2141", + countryCode: "AU", + }, + to: { + streetLines: ["600 Terminal Dr"], + city: "Louisville", + stateOrProvinceCode: "KY", + postalCode: "40209", + countryCode: "US", + }, + requestedPackageLineItems: [ + { + weight: { + value: 10, + units: "KG", + }, + dimensions: { + length: 2, + width: 3, + height: 4, + units: "CM", + }, + groupPackageCount: 1, + }, + ], + commodities: [ + { + description: "G6", + quantity: 2, + quantityUnits: "PCS", + unitPrice: { + amount: 10000, + currency: "USD", + }, + customsValue: { + amount: 10000, + currency: "USD", + }, + }, + ], + inforCreateFedex: { + pickupType: "CONTACT_FEDEX_TO_SCHEDULE", + }, + }, + }, + }, + name: "Shipping rate Courier Please", + group: "Shipping System", + }, + { + url: "https://int.ipsupply.com.au/api/transferPostData", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer " + tokenInt, + }, + data: { + urlAPI: "/api/logistics/check-shipping-rates", + data: { + courierName: "Auspost", + packageInfo: { + from: { + streetLines: ["8/4A Bachell Ave"], + city: "Lidcombe", + stateOrProvinceCode: "", + postalCode: "2141", + countryCode: "AU", + }, + to: { + streetLines: ["600 Terminal Dr"], + city: "Louisville", + stateOrProvinceCode: "KY", + postalCode: "40209", + countryCode: "US", + }, + requestedPackageLineItems: [ + { + weight: { + value: 10, + units: "KG", + }, + dimensions: { + length: 2, + width: 3, + height: 4, + units: "CM", + }, + groupPackageCount: 1, + }, + ], + commodities: [ + { + description: "G6", + quantity: 2, + quantityUnits: "PCS", + unitPrice: { + amount: 10000, + currency: "USD", + }, + customsValue: { + amount: 10000, + currency: "USD", + }, + }, + ], + inforCreateFedex: { + pickupType: "CONTACT_FEDEX_TO_SCHEDULE", + }, + }, + }, + }, + name: "Shipping rate Auspost", + group: "Shipping System", + }, + { + url: "https://int.ipsupply.com.au/api/transferPostData", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer " + tokenInt, + }, + data: { + urlAPI: "/api/logistics/check-shipping-rates", + data: { + courierName: "FRF", + packageInfo: { + from: { + streetLines: ["8/4A Bachell Ave"], + city: "Lidcombe", + stateOrProvinceCode: "", + postalCode: "2141", + countryCode: "AU", + }, + to: { + streetLines: ["112 Munro St"], + city: "South Melbourne", + postalCode: "3205", + countryCode: "AU", + }, + requestedPackageLineItems: [ + { + weight: { + value: 10, + units: "KG", + }, + dimensions: { + length: 2, + width: 3, + height: 4, + units: "CM", + }, + groupPackageCount: 1, + }, + ], + commodities: [ + { + description: "G6", + quantity: 2, + quantityUnits: "PCS", + unitPrice: { + amount: 10000, + currency: "USD", + }, + customsValue: { + amount: 10000, + currency: "USD", + }, + }, + ], + inforCreateFedex: { + pickupType: "CONTACT_FEDEX_TO_SCHEDULE", + }, + }, + }, + }, + name: "Shipping rate FRF", + group: "Shipping System", + }, + { + url: "https://int.ipsupply.com.au/api/transferPostData", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer " + tokenInt, + }, + data: { + urlAPI: "/api/logistics/check-shipping-rates", + data: { + courierName: "Sendle", + packageInfo: { + from: { + streetLines: ["8/4A Bachell Ave"], + city: "Lidcombe", + stateOrProvinceCode: "", + postalCode: "2141", + countryCode: "AU", + }, + to: { + streetLines: ["112 Munro St"], + city: "South Melbourne", + postalCode: "3205", + countryCode: "AU", + }, + requestedPackageLineItems: [ + { + weight: { + value: 10, + units: "KG", + }, + dimensions: { + length: 2, + width: 3, + height: 4, + units: "CM", + }, + groupPackageCount: 1, + }, + ], + commodities: [ + { + description: "G6", + quantity: 2, + quantityUnits: "PCS", + unitPrice: { + amount: 10000, + currency: "USD", + }, + customsValue: { + amount: 10000, + currency: "USD", + }, + }, + ], + inforCreateFedex: { + pickupType: "CONTACT_FEDEX_TO_SCHEDULE", + }, + }, + }, + }, + name: "Shipping rate Sendle", + group: "Shipping System", + }, + { + url: "https://int.ipsupply.com.au/api/transferPostData", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer " + tokenInt, + }, + data: { + urlAPI: "/api/logistics/check-tracking", + data: { + trackingNumber: "782568904960", + type: "Fedex", + }, + }, + name: "Tracking Fedex", + group: "Shipping System", + }, + { + url: "https://int.ipsupply.com.au/api/transferPostData", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer " + tokenInt, + }, + data: { + urlAPI: "/api/logistics/check-tracking", + data: { + trackingNumber: "210865775", + type: "TNT", + }, + }, + name: "Tracking TNT", + group: "Shipping System", + }, + { + url: "https://int.ipsupply.com.au/api/transferPostData", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer " + tokenInt, + }, + data: { + urlAPI: "/api/logistics/check-tracking", + data: { + trackingNumber: "1Z94VTP30308384260", + type: "UPS", + }, + }, + name: "Tracking UPS", + group: "Shipping System", + }, + { + url: "https://int.ipsupply.com.au/api/transferPostData", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer " + tokenInt, + }, + data: { + urlAPI: "/api/logistics/check-tracking", + data: { + trackingNumber: "33FJV771376901000930306", + type: "Auspost", + }, + }, + name: "Tracking Auspost", + group: "Shipping System", + }, + { + url: "https://int.ipsupply.com.au/api/transferPostData", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer " + tokenInt, + }, + data: { + urlAPI: "/api/logistics/check-tracking", + data: { + trackingNumber: "9400111206203073428144", + type: "USPS", + }, + }, + name: "Tracking USPS", + group: "Shipping System", + }, + { + url: "https://int.ipsupply.com.au/api/transferPostData", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer " + tokenInt, + }, + data: { + urlAPI: "/api/logistics/check-tracking", + data: { + trackingNumber: "CVAZ00633255", + type: "StarTrack", + }, + }, + name: "Tracking StarTrack", + group: "Shipping System", + }, + { + url: "https://int.ipsupply.com.au/api/transferPostData", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer " + tokenInt, + }, + data: { + urlAPI: "/api/logistics/check-tracking", + data: { + trackingNumber: "S92C5DS", + type: "Sendle", + }, + }, + name: "Tracking Sendle", + group: "Shipping System", + }, + { + url: "https://int.ipsupply.com.au/api/transferPostData", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer " + tokenInt, + }, + data: { + urlAPI: "/api/logistics/check-tracking", + data: { + trackingNumber: "2334909695 ", + type: "DHL", + }, + }, + name: "Tracking DHL", + group: "Shipping System", + }, + { + url: "https://int.ipsupply.com.au/api/transferPostData", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer " + tokenInt, + }, + data: { + urlAPI: "/api/logistics/check-tracking", + data: { + trackingNumber: "60508912001", + type: "CouriersPlease", + }, + }, + name: "Tracking CouriersPlease", + group: "Shipping System", + }, + //Other system + { + url: "https://int.ipsupply.com.au/api/transferPostData", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer " + tokenInt, + }, + data: { + urlAPI: "/api/stock-model-serial/check-sn-list-cisco", + data: { + serialNumbers: ["FGL1716W349"], + }, + }, + name: "Check SN Cisco", + group: "Other Systems", + }, + { + url: "ssh danielvu-gold@172.16.6.2 cat /home/danielvu-gold/htdocs/gold.danielvu.com/check_file.json", + method: "EXEC", + headers: {}, + data: {}, + name: "Perthmint", + group: "Other Systems", + }, + { + url: "https://disti.danielvu.com/api/fileAutoImportLog", + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json", + loginid: null, + Code: code, + AccessToken: accessToken, + }, + data: {}, + name: "Auto import Disti", + group: "Other Systems", + }, + //Test Log System + { + url: "nc -zv 172.16.7.13 8002", + method: "EXEC", + headers: {}, + data: {}, + name: "ATC to ERP", + group: "Test Log System", + }, + { + url: "nc -zv 172.16.7.13 5000", + method: "EXEC", + headers: {}, + data: {}, + name: "ATC worked", + group: "Test Log System", + }, + { + url: "nc -zv 172.16.6.23 7777", + method: "EXEC", + headers: {}, + data: {}, + name: "Read Test Log", + group: "Test Log System", + }, + ]; + + const logicCheck = async (req, response) => { + try { + if (Array.isArray(response.data) === false) { + if ( + (response.data.data !== undefined && + response.data.data.length > 0) || + (response.data !== undefined && response.data?.success) + ) { + report.push({ + group: req.group, + name: req.name, + status: ":check:", + code: response.status, + lengthOrData: response.data?.data?.length | response.data, + }); + } else { + if (response.data?.data !== undefined) { + if (Array.isArray(response.data.data) === false) { + const data = JSON.stringify( + response.data?.data + )?.toLocaleLowerCase(); + if ( + data?.includes("error") || + data?.includes("invalid") || + response.data.data === undefined + ) { + report.push({ + group: req.group, + name: req.name, + status: ":red_circle:", + code: response.status, + lengthOrData: JSON.stringify(response.data?.data), + }); + } else { + report.push({ + group: req.group, + name: req.name, + status: ":check:", + code: response.status, + lengthOrData: response.data?.data?.length, + }); + } + } else { + if ( + response.data?.data !== undefined && + response.data?.data?.length > 0 + ) { + report.push({ + group: req.group, + name: req.name, + status: ":check:", + code: response.status, + lengthOrData: response.data?.data?.length, + }); + } else { + report.push({ + group: req.group, + name: req.name, + status: ":red_circle:", + code: response.status, + lengthOrData: JSON.stringify(response.data?.data), + }); + } + } + } else { + const data = JSON.stringify(response.data)?.toLocaleLowerCase(); + if ( + data?.includes("error") || + data?.includes("invalid") || + response.data === undefined + ) { + report.push({ + group: req.group, + name: req.name, + status: ":red_circle:", + code: response.status, + lengthOrData: JSON.stringify(response.data?.data), + }); + } else { + report.push({ + group: req.group, + name: req.name, + status: ":check:", + code: response.status, + lengthOrData: response.data?.data?.length, + }); + } + } + } + } else { + if (response.data.length > 0) { + report.push({ + group: req.group, + name: req.name, + status: ":check:", + code: response.status, + lengthOrData: response.data.length, + }); + } else { + report.push({ + group: req.group, + name: req.name, + status: ":red_circle:", + code: response.status, + lengthOrData: response.data, + }); + } + } + } catch (error) { + console.log("logic check: ", error); + } + }; + + const runExec = (command, name) => { + return new Promise((resolve, reject) => { + exec(command, (error, stdout, stderr) => { + if (error) { + reject(error); + } else { + if (name === "Test Log System") { + if (stdout !== "") { + resolve(stdout); + } else { + resolve(stderr); + } + } else { + resolve(stdout); + } + } + }); + }); + }; + + const sortArray = (data) => { + data.sort((a, b) => { + if (a.group === b.group) { + return a.name.localeCompare(b.name); + } + return a.group.localeCompare(b.group); + }); + + // Đưa group "Other Systems" xuống cuối + data.sort((a, b) => { + if (a.group === "Other Systems") return 1; + if (b.group === "Other Systems") return -1; + return 0; + }); + + return data; + }; + + const promises = requests.map(async (req, index) => { + try { + if (req.method === "POST") { + let response = await axios.post(req.url, req.data, { + headers: req.headers, + }); + + let responseDataString = JSON.stringify(response.data, null, 2); + allResponse += `${req.name}\n${responseDataString}\n\n`; + console.log(response.data); + // Xử lý response ở đây + // console.log("Response:", response.data.length); + // console.log("Status:", response.status); + + if (response.data !== "" && response.data !== undefined) { + if (req.name !== "Auto import Disti") { + logicCheck(req, response); + } else { + console.log(response.data?.data?.length); + if (response.data?.data?.length > 0) { + response.data?.data?.map((u) => { + let name = req.name + " from " + u.data_name; + if (u.status === true) { + report.push({ + group: req.group, + name: name, + status: ":check:", + code: "good", + lengthOrData: response.data?.data, + }); + } else { + report.push({ + group: req.group, + name: name, + status: ":red_circle:", + code: "fail", + lengthOrData: response.data?.data, + }); + } + }); + } else { + report.push({ + group: req.group, + name: req.name, + status: ":red_circle:", + code: "fail", + lengthOrData: response.data?.data, + }); + } + } + } else { + console.log("Error:", response); + report.push({ + group: req.group, + name: req.name, + status: ":red_circle:", + code: response.status, + lengthOrData: "Error: " + JSON.stringify(response, null, 2), + }); + } + // .then((response) => { + + // }) + // .catch((error) => { + // // Xử lý lỗi ở đây + // console.log("Error:", error); + // report.push({ + // group: req.group, + // name: req.name, + // status: ":red_circle:", + // code: response.status, + // lengthOrData: "Error: " + error, + // }); + // }); + } + + if (req.method === "GET") { + let response = await axios.get(req.url, req.data, { + headers: req.headers, + }); + + let responseDataString = JSON.stringify(response.data, null, 2); + allResponse += `${req.name}\n${responseDataString}\n\n`; + console.log(response.data); + // Xử lý response ở đây + // console.log("Response:", response.data.length); + // console.log("Status:", response.status); + + if (response.data !== "" && response.data !== undefined) { + if (req.name !== "Auto import Disti") { + logicCheck(req, response); + } else { + console.log(response.data?.data?.length); + if (response.data?.data?.length > 0) { + response.data?.data?.map((u) => { + let name = req.name + " from " + u.data_name; + if (u.status === true) { + report.push({ + group: req.group, + name: name, + status: ":check:", + code: "good", + lengthOrData: response.data?.data, + }); + } else { + report.push({ + group: req.group, + name: name, + status: ":red_circle:", + code: "fail", + lengthOrData: response.data?.data, + }); + } + }); + } else { + report.push({ + group: req.group, + name: req.name, + status: ":red_circle:", + code: "fail", + lengthOrData: response.data?.data, + }); + } + } + } else { + console.log("Error:", response); + report.push({ + group: req.group, + name: req.name, + status: ":red_circle:", + code: response.status, + lengthOrData: "Error: " + JSON.stringify(response, null, 2), + }); + } + } + + if (req.method === "EXEC") { + const stdout = await runExec(req.url, req.group); + if (stdout !== "") { + let responseDataString = JSON.stringify(stdout, null, 2); + allResponse += `${req.name}\n${responseDataString}\n\n`; + + if (req.name === "Perthmint") { + if (stdout.toString().split("true").length - 1 > 1) { + report.push({ + group: req.group, + name: req.name, + status: ":check:", + code: "good", + lengthOrData: stdout, + }); + } else { + report.push({ + group: req.group, + name: req.name, + status: ":red_circle:", + code: "fail", + lengthOrData: stdout, + }); + } + } + + if (req.group === "Test Log System") { + report.push({ + group: req.group, + name: req.name, + status: ":check:", + code: "good", + lengthOrData: stdout, + }); + } + } else { + console.log(stdout); + let responseDataString = JSON.stringify(stdout, null, 2); + allResponse += `${req.name}\n${responseDataString}\n\n`; + report.push({ + group: req.group, + name: req.name, + status: ":red_circle:", + code: "fail", + lengthOrData: stdout, + }); + } + } + } catch (error) { + console.log("Error:", error); + report.push({ + group: req.group, + name: req.name, + status: ":red_circle:", + code: "bad", + lengthOrData: "Error: " + JSON.stringify(error, null, 2), + }); + } + }); + + await Promise.all(promises); + + let groupName = sortArray(report)[0]?.group; + let no = 0; + content += "||:high_voltage:**" + groupName + "**|||\n"; + sortArray(report).map((u, index) => { + no += 1; + if (u.group === groupName) { + content += + "|" + no + "|" + u.name + "|**" + time + "**|" + u.status + "|\n"; + } else { + no = 1; + groupName = u.group; + content += "||:high_voltage:**" + groupName + "**|||\n"; + content += + "|" + no + "|" + u.name + "|**" + time + "**|" + u.status + "|\n"; + } + }); + + let params = { + type: "stream", + to: "Result test - auto.nswteam.net", + topic: "AU-dev", + content: content, + // content: JSON.stringify(report, null, 2), + }; + + let params1 = { + type: "stream", + to: "System Logs", + topic: "stream events", + content: content, + }; + + client.messages.send(params); + client.messages.send(params1); + report.map((r) => { + allResponse += JSON.stringify(r, null, 2); + }); + const fileName = + "./app/store/logsAPI/" + + moment(Date.now()).format("DD_MM_YYYY").toString() + + ".log"; + + addLogFunction(fileName, allResponse, "System Logs") + + // fs.writeFileSync("/home/logs/logSystems.txt", allResponse); + console.log(sortArray(report)); + } catch (error) { + console.log(error); + if ( + JSON.stringify(error).includes( + "https://zulip.ipsupply.com.au/api/v1/messages failed" + ) + ) { + checkMultipleRequest(); + } + } +}; + +checkMultipleRequest(); diff --git a/package-lock.json b/package-lock.json index e8d3ef2..5e53ac9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,6 +17,7 @@ "axios": "^1.4.0", "child_process": "^1.0.2", "chokidar": "^3.5.3", + "crypto": "^1.0.1", "dotenv": "^16.3.1", "fs": "^0.0.1-security", "helpers": "^0.0.6", @@ -1366,9 +1367,9 @@ "dev": true }, "node_modules/@types/node": { - "version": "20.7.1", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.7.1.tgz", - "integrity": "sha512-LT+OIXpp2kj4E2S/p91BMe+VgGX2+lfO+XTpfXhh+bCk2LkQtHZSub8ewFBMGP5ClysPjTDFa4sMI8Q3n4T0wg==" + "version": "20.8.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.8.2.tgz", + "integrity": "sha512-Vvycsc9FQdwhxE3y3DzeIxuEJbWGDsnrxvMADzTDF/lcdR9/K+AQIeAghTQsHtotg/q0j3WEOYS/jQgSdWue3w==" }, "node_modules/@types/pino": { "version": "6.3.12", @@ -2860,6 +2861,12 @@ "node": "*" } }, + "node_modules/crypto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/crypto/-/crypto-1.0.1.tgz", + "integrity": "sha512-VxBKmeNcqQdiUQUW2Tzq0t377b54N2bMtXO/qiLa+6eRRmmC4qT3D4OnTGoT/U6O9aklQ/jTwbOtRMTTY8G0Ig==", + "deprecated": "This package is no longer supported. It's now a built-in Node module. If you've depended on crypto, you should switch to the one that's built-in." + }, "node_modules/cuid": { "version": "2.1.8", "resolved": "https://registry.npmjs.org/cuid/-/cuid-2.1.8.tgz", @@ -2873,9 +2880,9 @@ "dev": true }, "node_modules/data-uri-to-buffer": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-5.0.1.tgz", - "integrity": "sha512-a9l6T1qqDogvvnw0nKlfZzqsyikEBZBClF39V3TFoKhDtGBqHu2HkuomJc02j5zft8zrUaXEuoicLeW54RkzPg==", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-6.0.1.tgz", + "integrity": "sha512-MZd3VlchQkp8rdend6vrx7MmVDJzSNTBvghvKjirLkD+WTChA3KUf0jkE68Q4UyctNqI11zZO9/x2Yx+ub5Cvg==", "engines": { "node": ">= 14" } @@ -4121,12 +4128,12 @@ } }, "node_modules/get-uri": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/get-uri/-/get-uri-6.0.1.tgz", - "integrity": "sha512-7ZqONUVqaabogsYNWlYj0t3YZaL6dhuEueZXGF+/YVmf6dHmaFg8/6psJKqhx9QykIDKzpGcy2cn4oV4YC7V/Q==", + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/get-uri/-/get-uri-6.0.2.tgz", + "integrity": "sha512-5KLucCJobh8vBY1K07EFV4+cPZH3mrV9YeAruUseCQKHB58SGjjT2l9/eA9LD082IiuMjSlFJEcdJ27TXvbZNw==", "dependencies": { "basic-ftp": "^5.0.2", - "data-uri-to-buffer": "^5.0.1", + "data-uri-to-buffer": "^6.0.0", "debug": "^4.3.4", "fs-extra": "^8.1.0" }, @@ -4427,12 +4434,9 @@ "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==" }, "node_modules/has": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", - "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", - "dependencies": { - "function-bind": "^1.1.1" - }, + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.4.tgz", + "integrity": "sha512-qdSAmqLF6209RFj4VVItywPMbm3vWylknmB3nvNiUIs72xAimcM8nVYxYr7ncvZq5qzk9MKIZR8ijqD/1QuYjQ==", "engines": { "node": ">= 0.4.0" } @@ -6370,9 +6374,12 @@ } }, "node_modules/on-exit-leak-free": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.0.tgz", - "integrity": "sha512-VuCaZZAjReZ3vUwgOB8LxAosIurDiAW0s13rI1YwmaP++jvcxP77AWoQvenZebpCA2m8WC1/EosPYPMjnRAp/w==" + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz", + "integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==", + "engines": { + "node": ">=14.0.0" + } }, "node_modules/on-finished": { "version": "2.4.1", @@ -6847,9 +6854,9 @@ } }, "node_modules/pino-pretty": { - "version": "10.2.0", - "resolved": "https://registry.npmjs.org/pino-pretty/-/pino-pretty-10.2.0.tgz", - "integrity": "sha512-tRvpyEmGtc2D+Lr3FulIZ+R1baggQ4S3xD2Ar93KixFEDx6SEAUP3W5aYuEw1C73d6ROrNcB2IXLteW8itlwhA==", + "version": "10.2.2", + "resolved": "https://registry.npmjs.org/pino-pretty/-/pino-pretty-10.2.2.tgz", + "integrity": "sha512-RvAdCQAU51MdVsJdvXX4Bipb52wwldXtOzlva1NT8q2d7tmgYWFIMLhoSnfx2Sr+Hi7BLGpR/n8wgrcq5G/ykA==", "dependencies": { "colorette": "^2.0.7", "dateformat": "^4.6.3", @@ -6871,9 +6878,9 @@ } }, "node_modules/pino-pretty/node_modules/sonic-boom": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-3.4.0.tgz", - "integrity": "sha512-zSe9QQW30nPzjkSJ0glFQO5T9lHsk39tz+2bAAwCj8CNgEG8ItZiX7Wb2ZgA8I04dwRGCcf1m3ABJa8AYm12Fw==", + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-3.5.0.tgz", + "integrity": "sha512-02A0wEmj4d3aEIW/Sp6LMP1dNcG5cYmQPjhgtytIXa9tNmFZx3ragUPFmyBdgdM0yJJVSWwlLLEVHgrYfA0wtQ==", "dependencies": { "atomic-sleep": "^1.0.0" } @@ -10369,9 +10376,9 @@ "dev": true }, "@types/node": { - "version": "20.7.1", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.7.1.tgz", - "integrity": "sha512-LT+OIXpp2kj4E2S/p91BMe+VgGX2+lfO+XTpfXhh+bCk2LkQtHZSub8ewFBMGP5ClysPjTDFa4sMI8Q3n4T0wg==" + "version": "20.8.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.8.2.tgz", + "integrity": "sha512-Vvycsc9FQdwhxE3y3DzeIxuEJbWGDsnrxvMADzTDF/lcdR9/K+AQIeAghTQsHtotg/q0j3WEOYS/jQgSdWue3w==" }, "@types/pino": { "version": "6.3.12", @@ -11520,6 +11527,11 @@ "integrity": "sha512-mCxBlsHFYh9C+HVpiEacem8FEBnMXgU9gy4zmNC+SXAZNB/1idgp/aulFJ4FgCi7GPEVbfyng092GqL2k2rmow==", "dev": true }, + "crypto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/crypto/-/crypto-1.0.1.tgz", + "integrity": "sha512-VxBKmeNcqQdiUQUW2Tzq0t377b54N2bMtXO/qiLa+6eRRmmC4qT3D4OnTGoT/U6O9aklQ/jTwbOtRMTTY8G0Ig==" + }, "cuid": { "version": "2.1.8", "resolved": "https://registry.npmjs.org/cuid/-/cuid-2.1.8.tgz", @@ -11532,9 +11544,9 @@ "dev": true }, "data-uri-to-buffer": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-5.0.1.tgz", - "integrity": "sha512-a9l6T1qqDogvvnw0nKlfZzqsyikEBZBClF39V3TFoKhDtGBqHu2HkuomJc02j5zft8zrUaXEuoicLeW54RkzPg==" + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-6.0.1.tgz", + "integrity": "sha512-MZd3VlchQkp8rdend6vrx7MmVDJzSNTBvghvKjirLkD+WTChA3KUf0jkE68Q4UyctNqI11zZO9/x2Yx+ub5Cvg==" }, "dateformat": { "version": "4.6.3", @@ -12487,12 +12499,12 @@ "dev": true }, "get-uri": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/get-uri/-/get-uri-6.0.1.tgz", - "integrity": "sha512-7ZqONUVqaabogsYNWlYj0t3YZaL6dhuEueZXGF+/YVmf6dHmaFg8/6psJKqhx9QykIDKzpGcy2cn4oV4YC7V/Q==", + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/get-uri/-/get-uri-6.0.2.tgz", + "integrity": "sha512-5KLucCJobh8vBY1K07EFV4+cPZH3mrV9YeAruUseCQKHB58SGjjT2l9/eA9LD082IiuMjSlFJEcdJ27TXvbZNw==", "requires": { "basic-ftp": "^5.0.2", - "data-uri-to-buffer": "^5.0.1", + "data-uri-to-buffer": "^6.0.0", "debug": "^4.3.4", "fs-extra": "^8.1.0" }, @@ -12742,12 +12754,9 @@ "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==" }, "has": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", - "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", - "requires": { - "function-bind": "^1.1.1" - } + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.4.tgz", + "integrity": "sha512-qdSAmqLF6209RFj4VVItywPMbm3vWylknmB3nvNiUIs72xAimcM8nVYxYr7ncvZq5qzk9MKIZR8ijqD/1QuYjQ==" }, "has-ansi": { "version": "2.0.0", @@ -14214,9 +14223,9 @@ } }, "on-exit-leak-free": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.0.tgz", - "integrity": "sha512-VuCaZZAjReZ3vUwgOB8LxAosIurDiAW0s13rI1YwmaP++jvcxP77AWoQvenZebpCA2m8WC1/EosPYPMjnRAp/w==" + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz", + "integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==" }, "on-finished": { "version": "2.4.1", @@ -14594,9 +14603,9 @@ } }, "pino-pretty": { - "version": "10.2.0", - "resolved": "https://registry.npmjs.org/pino-pretty/-/pino-pretty-10.2.0.tgz", - "integrity": "sha512-tRvpyEmGtc2D+Lr3FulIZ+R1baggQ4S3xD2Ar93KixFEDx6SEAUP3W5aYuEw1C73d6ROrNcB2IXLteW8itlwhA==", + "version": "10.2.2", + "resolved": "https://registry.npmjs.org/pino-pretty/-/pino-pretty-10.2.2.tgz", + "integrity": "sha512-RvAdCQAU51MdVsJdvXX4Bipb52wwldXtOzlva1NT8q2d7tmgYWFIMLhoSnfx2Sr+Hi7BLGpR/n8wgrcq5G/ykA==", "requires": { "colorette": "^2.0.7", "dateformat": "^4.6.3", @@ -14615,9 +14624,9 @@ }, "dependencies": { "sonic-boom": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-3.4.0.tgz", - "integrity": "sha512-zSe9QQW30nPzjkSJ0glFQO5T9lHsk39tz+2bAAwCj8CNgEG8ItZiX7Wb2ZgA8I04dwRGCcf1m3ABJa8AYm12Fw==", + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-3.5.0.tgz", + "integrity": "sha512-02A0wEmj4d3aEIW/Sp6LMP1dNcG5cYmQPjhgtytIXa9tNmFZx3ragUPFmyBdgdM0yJJVSWwlLLEVHgrYfA0wtQ==", "requires": { "atomic-sleep": "^1.0.0" } diff --git a/package.json b/package.json index 2a1b2db..f1ff2c8 100644 --- a/package.json +++ b/package.json @@ -30,6 +30,7 @@ "axios": "^1.4.0", "child_process": "^1.0.2", "chokidar": "^3.5.3", + "crypto": "^1.0.1", "dotenv": "^16.3.1", "fs": "^0.0.1-security", "helpers": "^0.0.6", diff --git a/screenshot.js b/screenshot.js index 10f0f01..817b50c 100644 --- a/screenshot.js +++ b/screenshot.js @@ -1,10 +1,39 @@ -const regex = /(\d+)K/g; +const axios = require('axios'); +const md5 = require('md5'); -console.log( - "1000944K bytes of ATA System CompactFlash 0 (Read/Write) " - .match(regex) - .map((obj) => (parseInt(obj.replace("K", ""))/1024/1024).toFixed(2)+"G") -); +// Tạo dữ liệu JSON bạn muốn gửi đi +const dataToSend = { + // Đặt dữ liệu của bạn ở đây +}; + +// Tạo tiêu đề +const headers = { + 'Content-Type': 'application/json', + 'Accept': 'application/json', + 'loginid': null, + 'Code': 'chuoi ngau nhiên', + 'AccessToken': md5(Code + '24feca0508b52d34b51db4b40964e7fff12edf71208a4607126f75cb5d504f7f') +}; + +// Gửi POST request bằng Axios +axios.post('https://disti.danielvu.com/api/sendBuyerOrderToERP', dataToSend, { headers }) + .then(response => { + // Xử lý response ở đây + console.log('Response:', response.data); + }) + .catch(error => { + // Xử lý lỗi ở đây + console.error('Error:', error); + }); + + +// const regex = /(\d+)K/g; + +// console.log( +// "1000944K bytes of ATA System CompactFlash 0 (Read/Write) " +// .match(regex) +// .map((obj) => (parseInt(obj.replace("K", ""))/1024/1024).toFixed(2)+"G") +// ); // let a = [1,2,3] diff --git a/screenshot.png b/screenshot.png deleted file mode 100644 index 4509877..0000000 Binary files a/screenshot.png and /dev/null differ diff --git a/start/routes.ts b/start/routes.ts new file mode 100644 index 0000000..daa7724 --- /dev/null +++ b/start/routes.ts @@ -0,0 +1,299 @@ +import axios from "axios"; +/* +|-------------------------------------------------------------------------- +| Routes +|-------------------------------------------------------------------------- +| +| This file is dedicated for defining HTTP routes. A single file is enough +| for majority of projects, however you can define routes in different +| files and just make sure to import them inside this file. For example +| +| Define routes in following two files +| ├── start/routes/cart.ts +| ├── start/routes/customer.ts +| +| and then import them inside `start/routes.ts` as follows +| +| import './routes/cart' +| import './routes/customer' +| +*/ + +import Route from "@ioc:Adonis/Core/Route"; +import { runtimeCheckLogs } from "App/utils/runtimeCheckLogs"; +import Env from "@ioc:Adonis/Core/Env"; +import { sendMessToZulip } from "App/utils/sendMessToZulip"; +import moment from "moment"; +import Product from "App/Models/Product"; +import { sendDeviceInfora } from "App/utils/sendDeviceInfor"; + +runtimeCheckLogs(Env.get("FOLDER_LOGS")); + +// setTimeout(async() => { +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// LogDetectFile.all() +// console.log("first") +// }, 2000); + +//ERP get index serial number + +Route.post("/api/getIndexSerialNumber", "ErpsController.getIndexSerialNumber") + .middleware("checkToken").middleware( + "writeLog" + ); + // .middleware("writeLog"); + +Route.post("/api/getParagraph", "ErpsController.getParagraph") +.middleware("checkToken") +.middleware("writeLog") + + +//Users +Route.post("/api/account/createUser", "UsersController.create").middleware( + "writeLog" +); + +Route.post("/api/account/checkLogin", "UsersController.checkLogin").middleware( + "writeLog" +); + +//Log +Route.get("/api/log/showLog/:name?", "LogsController.showLog").middleware( + "writeLog" +); + +Route.get("/api/getAllLogDetect", "LogsController.getAllLogDetect") + +//Key-Value +Route.post("/api/getKeyValue", "ValuesController.getKeyValue") + +Route.post("/api/deleteValue", "ValuesController.destroy").middleware( + "writeLog" +); + +Route.post("/api/editValue", "ValuesController.edit").middleware( + "writeLog" +); + +Route.post("/api/addValue", "ValuesController.create").middleware("writeLog"); + +Route.post("/api/backupProduct", async ({ request, response }) => { + try { + const date = moment(Date.now()).format("YYYYMMDD"); + const res = await axios.post( + "https://logs.danielvu.com/api/getIndexSerialNumber", + { from: date, to: date }, + { + headers: { + Authorization: request.headers().authorization?.replace(/"/g, ""), + }, + } + ); + + res.data.map((obj, index) => { + res.data[index] = { + PID: res.data[index].PID, + SN: res.data[index].SN, + VID: res.data[index].VID, + line: res.data[index].line.join(","), + file: res.data[index].fileName, + warehouse: res.data[index].warehouse, + }; + }); + const addProduct = await Product.createMany(res.data); + // console.log(addProduct) + response.status(200).send("Add " + res.data.length + " success!"); + await sendMessToZulip( + "stream", + "networkToolBot", + "Log service", + "Backup product " + + date + + " success with " + + res.data.length + + " products" + ); + } catch (error) { + response.status(500).send(error); + await sendMessToZulip( + "stream", + "networkToolBot", + "Log service", + "Backup product fail. Please check!" + ); + } +}).middleware("writeLog"); + +Route.post("/api/sendMailInforDevice", async () => { + try { + sendDeviceInfora() + } catch (error) { + console.log(error) + } +}).middleware("checkToken").middleware( + "writeLog" +); +