This commit is contained in:
joseph le 2023-10-20 09:53:53 +07:00
commit 8e051c269a
14 changed files with 2242 additions and 594 deletions

View File

@ -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 = "";

View File

@ -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);
}
};

View File

@ -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;

View File

@ -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");
}
}
}

View File

@ -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")
})();

View File

@ -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);

Binary file not shown.

Before

Width:  |  Height:  |  Size: 304 KiB

View File

@ -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 += `<tr><td>${PID}</td>
<td>${VID}</td>
<td>${SN}</td>
<td></td>
<td></td>
<td>yes</td></tr>`;
}
} 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("<br>")
.match(regexMemory) !== null
? (
parseInt(
showVersion
.filter(
(line) =>
line.includes("bytes of memory") ||
line.includes("bytes of physical memory")
)
.join("<br>")
.match(regexMemory)[0]
) /
1024 /
1024
).toFixed(2) +
"G (D: " +
memDefaultForPID.split(":")[1] +
")"
: "";
let flash = showVersion
.filter((line) =>
line.toLocaleLowerCase().includes("compactflash")
)
.join("<br>");
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("<br>")
.match(regexMemory) !== null
? (
parseInt(flash.match(regexMemory)[0]) /
parseInt(
showVersion
.filter(
(line) =>
line.includes("bytes of memory") ||
line.includes(
"bytes of physical memory"
)
)
.join("<br>")
.match(regexMemory)[0]
) /
1024 /
1024
).toFixed(2) +
"G (D: " +
memDefaultForPID.split(":")[2] +
memDefaultForPID.split(":")[1] +
")"
: "",
extra_item: "no",
});
: "";
html += `<tr style='background-color:${backgroundColor}'><td>${PID}</td>
<td>${VID}</td>
<td>${SN}</td>
<td>${RAM}</td>
<td>${
flash.match(regexMemory) !== null
? (
parseInt(flash.match(regexMemory)[0]) /
1024 /
1024
).toFixed(2) +
"G (D: " +
memDefaultForPID.split(":")[2] +
")"
: ""
}</td>
<td>no</td></tr>`;
let flash = showVersion
.filter((line) =>
line.toLocaleLowerCase().includes("compactflash")
)
.join("<br>");
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 += `<tr><td>${PID}</td>
<td>${VID}</td>
<td>${SN}</td>
<td></td>
<td></td>
<td>yes</td></tr>`;
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 += `<tr style='background-color:${backgroundColor}'><td>${PID}</td>
<td>${VID}</td>
<td>${SN}</td>
<td></td>
<td></td>
<td>no</td></tr>`;
}
}
});
}
});
});
}
});
}
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:
"<table border='1'>\
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 += `<tr><td>${inf.PID}</td>
<td>${inf.VID}</td>
<td>${inf.SN}</td>
<td>${inf.RAM}</td>
<td>${inf.flash}</td>
<td>${inf.extra_item}</td></tr>`;
});
const options = {
from: "admin@apactech.io",
// to: "joseph@apactech.io, ips@ipsupply.com.au",
to: "joseph@apactech.io",
subject: "(AUTO-REPORT) SERIAL NUMBER",
html:
"<table border='1'>\
<thead>\
<tr>\
<th>PID</th>\
@ -343,15 +328,26 @@ export const sendDeviceInfora = async () => {
</tr>\
</thead>\
<tbody>" +
html +
"</tbody>\
html +
"</tbody>\
</table>",
};
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);
}

File diff suppressed because it is too large Load Diff

109
package-lock.json generated
View File

@ -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"
}

View File

@ -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",

View File

@ -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]

Binary file not shown.

Before

Width:  |  Height:  |  Size: 102 KiB

299
start/routes.ts Normal file
View File

@ -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"
);