Skip to content

Commit

Permalink
feat: add last update report
Browse files Browse the repository at this point in the history
  • Loading branch information
ilyaliao committed Oct 7, 2024
1 parent a84c5e5 commit 34866c9
Show file tree
Hide file tree
Showing 5 changed files with 63 additions and 14 deletions.
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const cli = cac()
cli
.command('report', 'generate report')
.option('--type <type>', 'Set report type', {
default: 'not-working',
default: 'last-update',
})
.action((options) => {
if (options.type === 'not-working') {
Expand Down
44 changes: 44 additions & 0 deletions src/modules/reportLastUpdate/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,49 @@
import process from 'node:process'
import { consola } from 'consola'
import type { Device } from '~/type'
import { formatDate, performanceUtils, readFileContent, writeFile } from '~/utils'

export async function generateReportLastUpdate(): Promise<void> {
consola.start('開始產生機具最後更新報表')
const cost = performanceUtils()

consola.info('讀取檔案中')
const nameDevicePrefix = process.env.Name_Device || 'airaConnect.devices'
const devices: Device[] = await readFileContent(`./data/${nameDevicePrefix}.json`)

consola.info(`讀取檔案完成,共花費 ${(cost() / 1000).toFixed(2)} 秒`)

const result = formatOutput(devices)

consola.info(`已處理完畢,正在寫入檔案,共花費 ${(cost() / 1000).toFixed(2)} 秒`)

await writeOutput(result)

consola.success('已寫入檔案,共花費')
}

/**
* 格式化輸出資料
*/
export function formatOutput(devices: Device[]): string {
const startDate = new Date(Math.min(...devices.map(d => d.updatedAt)))
const endDate = new Date(Math.max(...devices.map(d => d.updatedAt)))
const dateRange = `${startDate.getMonth() + 1}/${startDate.getDate()} - ${endDate.getMonth() + 1}/${endDate.getDate()}`

const header = `\t${dateRange}\n#\t名稱\t最後更新時間\n`

const deviceLines = devices.map((device, idx) => `${idx + 1}\t${device.name}\t${formatDate(device.updatedAt)}`).join('\n')

return header + deviceLines
}

/**
* 寫入結果到檔案
*/
async function writeOutput(resultString: string): Promise<void> {
const date = new Date()
const formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
const outputFileName = `./output/${formattedDate}-report-last-update.txt`

await writeFile(outputFileName, resultString)
}
23 changes: 10 additions & 13 deletions src/modules/reportNotWorking/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import fs from 'node:fs/promises'
import process from 'node:process'
import { pathToFileURL } from 'node:url'
import { consola } from 'consola'
import dotenv from 'dotenv'
import type { Device } from '~/type'
import { exit, formatDate, performanceUtils, prompt, readFileContent, readFolderNames } from '~/utils'
import { exit, formatDate, performanceUtils, prompt, readFileContent, readFolderNames, writeFile } from '~/utils'
import { preprocessData, type serializableData } from './prepare'
import type { Payload, ProcessedResult, ProcessedSignal } from './dtos'

Expand All @@ -14,7 +13,7 @@ export async function generateReportNotWorking(): Promise<void> {
consola.start('開始產生未正常運作機具報表')
const cost = performanceUtils()

consola.info('檢查檔案中')
consola.info('檢查檔案中...')

const nameMessagePrefix = process.env.Name_Message || 'airaConnect.machineryMessages.test'

Expand Down Expand Up @@ -61,11 +60,11 @@ export async function generateReportNotWorking(): Promise<void> {

const { areaMap, devicesMap } = preprocessedData

const resultString = formatOutput(areaMap, devicesMap, transformedPayloads, startTime, endTime)
const result = formatOutput(areaMap, devicesMap, transformedPayloads, startTime, endTime)

consola.info(`已處理完畢,正在寫入檔案,共花費 ${(cost() / 1000).toFixed(2)} 秒`)

await writeOutput(resultString)
await writeOutput(result)

consola.success('已寫入檔案,共花費')
}
Expand Down Expand Up @@ -133,31 +132,29 @@ function formatOutput(
): string {
const startDate = new Date(startTime)
const endDate = new Date(endTime)
const formattedDate = `${startDate.getMonth() + 1}/${startDate.getDate()} - ${endDate.getMonth() + 1}/${endDate.getDate()}`
const dateRange = `${startDate.getMonth() + 1}/${startDate.getDate()} - ${endDate.getMonth() + 1}/${endDate.getDate()}`

const header = `日期\t${formattedDate}\nGateway\t通訊設備\tDI\t區域\t名稱\t燈號\t最後更新時間\n`
const header = `\t${dateRange}\n#\tGateway\t通訊設備\tDI\t區域\t名稱\t燈號\t最後更新時間\n`
const lines: string[] = []

processedSignals.forEach((signal) => {
const [gateway, communicationEquipment] = signal.channel.split('/')
const deviceKey = `${signal.gatewayId}/${signal.communicationEquipmentId}`

const matchingDevices = Object.entries(devicesMap)
.filter(([key]) => {
return key.startsWith(deviceKey)
})
.filter(([key]) => key.startsWith(deviceKey))
.map(([_, device]) => device)

matchingDevices.forEach((device) => {
const areaName = areaMap[device.areaId] || '--'
const formattedLastUpdateTime = formatDate(signal.lastUpdateTime)

signal.diResults.forEach((diKey) => {
signal.diResults.forEach((diKey, idx) => {
const diNumber = diKey.replace('DI', '')
const matchingSignal = device.signal.find(s => s.pin.replace('R', '') === diNumber)

if (matchingSignal) {
lines.push(`${gateway}\t${communicationEquipment}\t${diKey}\t${areaName}\t${device.name}\t${matchingSignal.light}\t${formattedLastUpdateTime}`)
lines.push(`${idx + 1}\t${gateway}\t${communicationEquipment}\t${diKey}\t${areaName}\t${device.name}\t${matchingSignal.light}\t${formattedLastUpdateTime}`)
}
})
})
Expand All @@ -174,5 +171,5 @@ async function writeOutput(resultString: string): Promise<void> {
const formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
const outputFileName = `./output/${formattedDate}-report-not-working.txt`

await fs.writeFile(pathToFileURL(outputFileName), resultString, 'utf-8')
await writeFile(outputFileName, resultString)
}
1 change: 1 addition & 0 deletions src/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export interface Device {
model: string
name: string
signal: Signal[]
updatedAt: number
}

export interface Signal {
Expand Down
7 changes: 7 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,10 @@ export async function readFileContent<T>(filePath: PathLike = 'data'): Promise<T
return []
}
}

/**
* 寫入檔案
*/
export async function writeFile(filePath: string, content: string): Promise<void> {
await fs.writeFile(filePath, content, 'utf-8')
}

0 comments on commit 34866c9

Please sign in to comment.