From 3d41d03f79519ff0fb4a1df7b9c8ad193b5807fa Mon Sep 17 00:00:00 2001 From: Joseph Le Date: Thu, 26 Feb 2026 17:52:00 +1100 Subject: [PATCH] Update folder get logs --- .gitconfig | 2 + app/Controllers/Http/ErpsController.ts | 71 +++++++++++++++- app/Controllers/Http/LogsController.ts | 109 ++++++++++++++++++++++++- start/routes.ts | 2 +- 4 files changed, 180 insertions(+), 4 deletions(-) diff --git a/.gitconfig b/.gitconfig index 09c08d4..f49e2c1 100644 --- a/.gitconfig +++ b/.gitconfig @@ -14,3 +14,5 @@ directory = /home/Log_service/ directory = /home/Log_service/ directory = /home/Log_service/ + directory = /home/Log_service/ + directory = /home/Log_service/ diff --git a/app/Controllers/Http/ErpsController.ts b/app/Controllers/Http/ErpsController.ts index a6816ea..5bdf4a6 100644 --- a/app/Controllers/Http/ErpsController.ts +++ b/app/Controllers/Http/ErpsController.ts @@ -7,6 +7,7 @@ const path = require("path"); const BASE_URL = Env.get("BASE_URL_LOG"); const BASE_URL_AUTO = `${BASE_URL}/`; +const LOG_DIR = "home/logs"; export default class ErpsController { /** * Controller do tim cac serial number trong cac log trong khoang thoi gian xac dinh @@ -18,7 +19,7 @@ export default class ErpsController { response, }: HttpContextContract) { const { from, to } = request.all(); - const getListLog = async (from, to) => { + const getListLogOld = async (from, to) => { try { const listLog: string[] = []; const response = await axios.get(BASE_URL); @@ -58,6 +59,44 @@ export default class ErpsController { } }; + const getListLog = async (from: string, to: string) => { + try { + const listLog: string[] = []; + + // đọc danh sách file trong thư mục + const files = await fs.readdirSync(LOG_DIR); + + // lọc file .log + const logFiles = files.filter((file) => file.endsWith(".log")); + + // dùng Promise.all để xử lý async đúng cách + await Promise.all( + logFiles.map(async (fileName) => { + const prefixNumber = parseInt(fileName.split("-")[0]); + + if ( + prefixNumber >= parseInt(from) && + prefixNumber <= parseInt(to) + ) { + listLog.push(path.join(LOG_DIR, fileName)); + + const record = await LogDetectFile.firstOrCreate( + { file_name: fileName }, + { file_name: fileName } + ); + + console.log(record.toJSON()); + } + }) + ); + + return listLog; + } catch (error) { + console.log(error); + return []; + } +}; + const fetchWithRetry = async (url) => { let retries = 0; const MAX_RETRIES = 10; @@ -279,7 +318,7 @@ export default class ErpsController { * @param {Integer} range khoang dong truoc/sau line * @author {Token} req.headers.authorization //token xac thuc */ - public async getParagraph({ request, response }: HttpContextContract) { + public async getParagraphOld({ request, response }: HttpContextContract) { const { fileName, line, range } = request.all(); try { @@ -302,6 +341,34 @@ export default class ErpsController { } } + public async getParagraph({ request, response }: HttpContextContract) { + const { fileName, line, range } = request.all(); + + try { + let fName = fileName; + // const res = await axios.get(BASE_URL + "/" + fName); + + const LOG_DIR = "/home/logs"; + const filePath = path.join(LOG_DIR, fileName); + const res = await fs.readFileSync(filePath, "utf-8"); + + const arrayLine = res?.split("\n"); + + if (Number(range) >= Number(line)) { + response.status(200).json({ + content: arrayLine?.slice(0, line + range)?.join("\n"), + }); + } else { + response.status(200).json({ + content: arrayLine?.slice(line - range - 1, line + range)?.join("\n"), + }); + } + } catch (error) { + console.log(error); + response.status(202).send({ mess: "FILE NOT FOUND", error: error }); + } + } + public async store({ request, response }: HttpContextContract) { } public async show({ }: HttpContextContract) { } diff --git a/app/Controllers/Http/LogsController.ts b/app/Controllers/Http/LogsController.ts index a1bc39c..e661bdc 100644 --- a/app/Controllers/Http/LogsController.ts +++ b/app/Controllers/Http/LogsController.ts @@ -5,11 +5,13 @@ import LogDetectFile from "App/Models/LogDetectFile"; import axios from "axios"; import Env from "@ioc:Adonis/Core/Env"; import { checkSpecialVersion } from "App/utils/helper"; +import path from "path"; +import fs from "fs"; const BASE_URL = Env.get("BASE_URL_LOG"); export default class LogsController { - public async showLog({ request, response }: HttpContextContract) { + public async showLogOld({ request, response }: HttpContextContract) { try { const fileName = decodeURIComponent(request.params().name); console.log(fileName); @@ -108,6 +110,111 @@ export default class LogsController { } } + public async showLog({ request, response }: HttpContextContract) { + try { + const fileName = decodeURIComponent(request.params().name); + console.log(fileName); + const fileDetect = await LogDetectFile.findBy("file_name", fileName); + + if (!fileDetect) { + return response.status(203).send("FILE NOT FOUND"); + } + + const logsDetect = await Database.rawQuery( + "SELECT * FROM log_reports WHERE id_file = ?", + [fileDetect.id_ldf] + ); + + const lines = [...new Set(logsDetect[0].map((obj) => obj.line))].sort( + (a: number, b: number) => a - b + ); + + const logUrl = `${BASE_URL}/${fileName}`; + + // const content = await axios.get(logUrl); + + // Get log from home/logs + const LOG_DIR = "/home/logs"; + const filePath = path.join(LOG_DIR, fileName); + const content = await fs.readFileSync(filePath, "utf-8"); + + const allKeyValues = await KeyValue.all(); + + const keyValueMap = allKeyValues.reduce((acc, { $original }) => { + acc[$original.key] = acc[$original.key] || []; + acc[$original.key].push($original.value); + return acc; + }, {} as Record); + + const MODEL_SPECIAL = keyValueMap["MODEL_SPECIAL"] || []; + const CATCH_FAULTY = keyValueMap["CATCH_FAULTY"] || []; + const EXCLUDE_ERR = keyValueMap["EXCLUDE_ERR"] || []; + + const rawData = content.split("\n"); + const processedData: string[] = []; + const modelSpecialDetected: string[] = []; + const issueSpecialDetected: string[] = []; + + for (let i = 0; i < rawData.length; i++) { + let line = rawData[i]; + let numberedLine = `${i + 1}|-|${line}`; + const specialVersion = checkSpecialVersion(line); + + if (specialVersion) { + const index = numberedLine.indexOf(specialVersion); + numberedLine = + numberedLine.slice(0, index) + + "|-|" + + specialVersion + + "|-|" + + numberedLine.slice(index + specialVersion.length); + } + + for (const value of [...MODEL_SPECIAL, ...CATCH_FAULTY]) { + if ( + line.includes(value) && + !EXCLUDE_ERR.some((err) => line.includes(err)) + ) { + const index = numberedLine.indexOf(value); + numberedLine = + numberedLine.slice(0, index) + + "|-|" + + value + + "|-|" + + numberedLine.slice(index + value.length); + break; + } + } + + processedData.push(numberedLine); + } + + for (const lineIndex of lines) { + const line = processedData[Number(lineIndex) - 1]; + if (!line) continue; + if (EXCLUDE_ERR.some((err) => line.includes(err))) continue; + + if ( + MODEL_SPECIAL.some((model) => line.includes(model)) || + checkSpecialVersion(line) + ) { + modelSpecialDetected.push(line); + } else { + issueSpecialDetected.push(line); + } + } + + response.status(200).send({ + modelSpecial: modelSpecialDetected.join("\n"), + issueItem: issueSpecialDetected.join("\n"), + contentFile: processedData.join("\n"), + }); + } catch (error) { + console.error("Error fetching log:", error); + response.status(203).send("FILE NOT FOUND"); + } + } + public async getAllLogDetect({ response }: HttpContextContract) { try { const files = await LogDetectFile.all(); diff --git a/start/routes.ts b/start/routes.ts index 2e0ae5b..1208264 100644 --- a/start/routes.ts +++ b/start/routes.ts @@ -95,7 +95,7 @@ Route.post("/api/backupProduct", async ({ request, response }) => { PID: res.data[index].PID, SN: res.data[index].SN, VID: res.data[index].VID, - brand: res.data[index].brand, + // brand: res.data[index].brand, line: res.data[index].line.join(","), file: res.data[index].fileName, warehouse: res.data[index].warehouse,