From f9e358f6c300bf95ac75868bf02ce2c666952d51 Mon Sep 17 00:00:00 2001 From: "gibbs.shih" Date: Fri, 6 Sep 2024 16:26:55 +0800 Subject: [PATCH 1/6] update loggerError --- package.json | 2 +- .../api/v1/company/[companyId]/account/index.ts | 13 ++++++++++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/package.json b/package.json index ace1c3ca..36b1439f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "iSunFA", - "version": "0.8.0+71", + "version": "0.8.0+72", "private": false, "scripts": { "dev": "next dev", diff --git a/src/pages/api/v1/company/[companyId]/account/index.ts b/src/pages/api/v1/company/[companyId]/account/index.ts index 1fdc1087..1c09c16c 100644 --- a/src/pages/api/v1/company/[companyId]/account/index.ts +++ b/src/pages/api/v1/company/[companyId]/account/index.ts @@ -22,6 +22,7 @@ import { getSession } from '@/lib/utils/session'; import AccountRetrieverFactory from '@/lib/utils/account/account_retriever_factory'; import { AuthFunctionsKeys } from '@/interfaces/auth'; import { SortOrder } from '@/constants/sort'; +import { loggerError } from '@/lib/utils/logger_back'; function formatCompanyIdAccountId(companyId: unknown, accountId: string | string[] | undefined) { const isCompanyIdValid = !Number.isNaN(Number(companyId)); @@ -251,9 +252,15 @@ export async function handlePostRequest( updatedAt: timeInSeconds, level: parentAccount.level + 1, }; - const savedNewOwnAccount = await prisma.account.create({ - data: newOwnAccount, - }); + let savedNewOwnAccount: IAccount | null = null; + try { + savedNewOwnAccount = await prisma.account.create({ + data: newOwnAccount, + }); + } catch (error) { + const logError = loggerError(userId, 'Failed to create new own account', error as Error); + logError.error('Prisma related error'); + } return savedNewOwnAccount; } From 715335fbd757dd945ccadf273217ec349ff274bd Mon Sep 17 00:00:00 2001 From: "gibbs.shih" Date: Tue, 10 Sep 2024 17:19:11 +0800 Subject: [PATCH 2/6] adjust logger error --- package.json | 2 +- prisma/seed.ts | 1 - scripts/update_version.ts | 9 +- src/instrumentation.ts | 6 +- src/lib/utils/file.ts | 6 +- src/lib/utils/google_image_upload.ts | 4 +- src/lib/utils/repo/account.repo.ts | 50 ++++++- src/lib/utils/repo/invoice.beta.repo.ts | 20 ++- src/lib/utils/repo/invoice.repo.ts | 120 ++++++++++++++--- src/lib/utils/repo/journal.repo.ts | 36 ++++- src/lib/utils/repo/line_item.beta.repo.ts | 19 ++- src/lib/utils/repo/ocr.repo.ts | 22 +++- src/lib/utils/repo/payment.beta.repo.ts | 7 +- src/lib/utils/repo/report.repo.ts | 34 ++++- src/lib/utils/repo/voucher.beta.repo.ts | 37 +++++- src/lib/utils/repo/voucher.repo.ts | 81 ++++++++++-- src/pages/api/auth/error.ts | 10 +- .../v1/company/[companyId]/account/index.ts | 11 +- .../employee/[employeeId]/index.ts | 11 +- .../v1/company/[companyId]/invoice/index.ts | 15 ++- .../[companyId]/labor_cost_chart/index.ts | 14 +- .../[companyId]/ocr/[resultId]/index.ts | 7 +- .../api/v1/company/[companyId]/ocr/index.ts | 123 +++++++++--------- .../v1/company/[companyId]/report/index.ts | 4 +- .../[companyId]/voucher/[voucherId]/index.ts | 20 ++- .../v1/company/[companyId]/voucher/index.ts | 9 +- 26 files changed, 514 insertions(+), 164 deletions(-) diff --git a/package.json b/package.json index 36b1439f..92d8db74 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "iSunFA", - "version": "0.8.0+72", + "version": "0.8.0+73", "private": false, "scripts": { "dev": "next dev", diff --git a/prisma/seed.ts b/prisma/seed.ts index fb21c40d..ef941bbd 100644 --- a/prisma/seed.ts +++ b/prisma/seed.ts @@ -318,7 +318,6 @@ main() }) .catch(async () => { // Info (20240316 - Murky) - disconnect prisma - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger await prisma.$disconnect(); process.exit(1); }); diff --git a/scripts/update_version.ts b/scripts/update_version.ts index 5c6aca5f..e4b6831f 100644 --- a/scripts/update_version.ts +++ b/scripts/update_version.ts @@ -1,6 +1,7 @@ import * as fs from 'fs'; import * as path from 'path'; import { execSync } from 'child_process'; +import { loggerError } from '@/lib/utils/logger_back'; // Info: (20240701 - Jacky) Function to get the last committed version of package.json function getLastCommittedVersion(): string | null { @@ -28,7 +29,8 @@ try { packageJsonContent = fs.readFileSync(packageJsonPath, 'utf8'); packageJson = JSON.parse(packageJsonContent); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError(0, 'Package.json parsed failed', error as Error); + logError.error('Retreive packageJson in update_version.ts failed'); process.exit(1); // Info: (20240701 - Jacky) Exit the process with an error code } @@ -62,8 +64,7 @@ try { // Info:(20240730 - Jacky) - Add last line to prevent EOF error fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2) + '\n'); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError(0, 'Package.json write failed', error as Error); + logError.error('Update(Write) packageJson into packageJsonPath in update_version.ts failed'); process.exit(1); // Info: (20240701 - Jacky) Exit the process with an error code } - -// Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger diff --git a/src/instrumentation.ts b/src/instrumentation.ts index 91bbb927..4cc58427 100644 --- a/src/instrumentation.ts +++ b/src/instrumentation.ts @@ -1,9 +1,10 @@ +import loggerBack from '@/lib/utils/logger_back'; + /** * Info: (20240812 - Murky) All code in register will be run when "Starting..." is printed in the console. */ export async function register() { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger - + loggerBack.info('Instrumentation register starting...'); // Info: (20240812 - Murky) Node module using in this file need to be dynamically imported, it must be inside "if" statement if (process.env.NEXT_RUNTIME === 'nodejs') { const { createFileFoldersIfNotExists } = await import('@/lib/utils/file'); @@ -11,4 +12,5 @@ export async function register() { await import('pino'); await import('next-logger'); } + loggerBack.info('Instrumentation register completed!'); } diff --git a/src/lib/utils/file.ts b/src/lib/utils/file.ts index 230b1fed..9fe91b29 100644 --- a/src/lib/utils/file.ts +++ b/src/lib/utils/file.ts @@ -16,16 +16,16 @@ import { decryptFile, getPrivateKeyByCompany, } from '@/lib/utils/crypto'; -import logger from '@/lib/utils/logger_back'; +import logger, { loggerError } from '@/lib/utils/logger_back'; import { STATUS_MESSAGE } from '@/constants/status_code'; export async function createFileFoldersIfNotExists(): Promise { UPLOAD_IMAGE_FOLDERS_TO_CREATE_WHEN_START_SERVER.map(async (folder) => { try { await fs.mkdir(folder, { recursive: true }); - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError(0, 'createFileFoldersIfNotExists failed', error as Error); + logError.error('Func. createFileFoldersIfNotExists in file.ts failed'); } }); CRYPTO_FOLDER_PATH.map(async (folder) => { diff --git a/src/lib/utils/google_image_upload.ts b/src/lib/utils/google_image_upload.ts index 2a70f9ce..460ceda2 100644 --- a/src/lib/utils/google_image_upload.ts +++ b/src/lib/utils/google_image_upload.ts @@ -11,6 +11,7 @@ import path from 'path'; import fs from 'fs/promises'; import { File } from 'formidable'; import { FileFolder, getFileFolder } from '@/constants/file'; +import { loggerError } from '@/lib/utils/logger_back'; // Info: (20240604 - Murky) if process.env is not set, the error will stop all process, error can't be caught export const googleStorage = new Storage({ @@ -63,7 +64,8 @@ export async function uploadFileToGoogleCloud( await file.makePublic(); url = `${GOOGLE_STORAGE_BUCKET_URL}${destFileName}`; } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError(0, 'uploadFileToGoogleCloud failed', error as Error); + logError.error('Func. uploadFileToGoogleCloud in google_image_upload.ts failed'); } return url; } diff --git a/src/lib/utils/repo/account.repo.ts b/src/lib/utils/repo/account.repo.ts index 78d343bf..0b5d1c27 100644 --- a/src/lib/utils/repo/account.repo.ts +++ b/src/lib/utils/repo/account.repo.ts @@ -7,6 +7,7 @@ import { Account, Prisma } from '@prisma/client'; import { DEFAULT_PAGE_NUMBER } from '@/constants/display'; import { ReportSheetAccountTypeMap, ReportSheetType } from '@/constants/report'; import { SortOrder } from '@/constants/sort'; +import { loggerError } from '@/lib/utils/logger_back'; export async function findManyAccountsInPrisma({ companyId, @@ -90,7 +91,12 @@ export async function findManyAccountsInPrisma({ try { totalCount = await prisma.account.count({ where }); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'Count tototal count of account in findManyAccountsInPrisma failed', + error as Error + ); + logError.error('Prisma count account in account.repo.ts failed'); } const totalPage = Math.ceil(totalCount / limit); @@ -109,7 +115,12 @@ export async function findManyAccountsInPrisma({ try { accounts = await prisma.account.findMany(findManyArgs); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'Find many accounts in findManyAccountsInPrisma failed', + error as Error + ); + logError.error('Prisma find many accounts in account.repo.ts failed'); } const hasNextPage = accounts.length > limit; @@ -151,7 +162,12 @@ export async function findFirstAccountInPrisma(accountId: number, companyId: num }, }); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'Find first account in findFirstAccountInPrisma failed', + error as Error + ); + logError.error('Prisma find first account in account.repo.ts failed'); } return account; @@ -174,7 +190,12 @@ export async function updateAccountInPrisma( }, }); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'Update account in updateAccountInPrisma failed', + error as Error + ); + logError.error('Prisma update account in account.repo.ts failed'); } return account; @@ -195,7 +216,12 @@ export async function softDeleteAccountInPrisma(accountIdNumber: number, company }, }); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'Soft delete account in softDeleteAccountInPrisma failed', + error as Error + ); + logError.error('Prisma soft delete account in account.repo.ts failed'); } return account; } @@ -212,7 +238,12 @@ export async function findLatestSubAccountInPrisma(parentAccount: Account) { }, }); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'Find latest sub account in findLatestSubAccountInPrisma failed', + error as Error + ); + logError.error('Prisma find latest sub account in account.repo.ts failed'); } return latestSubAccount; } @@ -249,7 +280,12 @@ export async function fuzzySearchAccountByName(name: string) { `; [account] = accounts; } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'Fuzzy search account by name in fuzzySearchAccountByName failed', + error as Error + ); + logError.error('Prisma fuzzy search account by name in account.repo.ts failed'); } return account; diff --git a/src/lib/utils/repo/invoice.beta.repo.ts b/src/lib/utils/repo/invoice.beta.repo.ts index 9aca515f..20ec4200 100644 --- a/src/lib/utils/repo/invoice.beta.repo.ts +++ b/src/lib/utils/repo/invoice.beta.repo.ts @@ -13,6 +13,8 @@ import { IPaginatedData } from '@/interfaces/pagination'; import { SortBy } from '@/constants/journal'; import { STATUS_MESSAGE } from '@/constants/status_code'; import { SortOrder } from '@/constants/sort'; +import loggerBack, { loggerError } from '@/lib/utils/logger_back'; + /** * This function can find Unique Invoice by invoiceId, companyId is optional * @param {number} invoiceId you want to find @@ -49,10 +51,15 @@ export async function findUniqueInvoiceById( }); if (!invoice) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + loggerBack.info('No invoice found in findUniqueInvoiceById'); } } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'Find unique in invoice in findUniqueInvoiceById failed', + error as Error + ); + logError.error('Prisma related func. findUniqueInvoiceById in invoice.beta.repo.ts failed'); } return invoice; } @@ -126,7 +133,8 @@ export async function createInvoice( try { invoiceBeCreated = await prisma.invoice.create(invoiceCreateArgs); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError(0, 'Create invoice in createInvoice failed', error as Error); + logError.error('Prisma related invoice creation in invoice.beta.repo.ts failed'); } return invoiceBeCreated; @@ -210,7 +218,8 @@ export async function updateInvoice( try { invoiceBeUpdated = await prisma.invoice.update(invoiceUpdateArgs); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError(0, 'Update invoice in updateInvoice failed', error as Error); + logError.error('Prisma related invoice update in invoice.beta.repo.ts failed'); } return invoiceBeUpdated; @@ -308,7 +317,8 @@ export async function listInvoice({ try { invoices = await prisma.invoice.findMany(findManyArgs); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError(0, 'Find many in invoice in listInvoice failed', error as Error); + logError.error('Prisma related func. findMany in listInvoice in invoice.beta.repo.ts failed'); } const hasNextPage = invoices.length > pageSize; diff --git a/src/lib/utils/repo/invoice.repo.ts b/src/lib/utils/repo/invoice.repo.ts index 288355e0..9620486b 100644 --- a/src/lib/utils/repo/invoice.repo.ts +++ b/src/lib/utils/repo/invoice.repo.ts @@ -8,6 +8,7 @@ import { IInvoice, IInvoiceBeta, IInvoiceIncludePaymentJournal } from '@/interfa import { IPayment, IPaymentBeta } from '@/interfaces/payment'; import { timestampInSeconds } from '@/lib/utils/common'; import { Ocr, Prisma } from '@prisma/client'; +import loggerBack, { loggerError } from '@/lib/utils/logger_back'; export async function findUniqueOcrInPrisma(ocrId: number | undefined): Promise<{ id: number; @@ -33,7 +34,14 @@ export async function findUniqueOcrInPrisma(ocrId: number | undefined): Promise< }, }); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'find unique ocr in findUniqueOcrInPrisma failed', + error as Error + ); + logError.error( + 'Prisma related find unique ocr in findUniqueOcrInPrisma in invoice.repo.ts failed' + ); throw new Error(STATUS_MESSAGE.DATABASE_READ_FAILED_ERROR); } @@ -57,7 +65,14 @@ export async function updateOcrStatusInPrisma(ocrId: number, status: ProgressSta }, }); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'update ocr status in updateOcrStatusInPrisma failed', + error as Error + ); + logError.error( + 'Prisma related update ocr status in updateOcrStatusInPrisma in invoice.repo.ts failed' + ); throw new Error(STATUS_MESSAGE.DATABASE_UPDATE_FAILED_ERROR); } @@ -75,7 +90,14 @@ export async function findUniqueCompanyInPrisma(companyId: number) { select: { id: true }, }); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'find unique company in findUniqueCompanyInPrisma failed', + error as Error + ); + logError.error( + 'Prisma related find unique company in findUniqueCompanyInPrisma in invoice.repo.ts failed' + ); throw new Error(STATUS_MESSAGE.DATABASE_READ_FAILED_ERROR); } @@ -109,7 +131,14 @@ export async function findUniqueJournalInPrisma(journalId: number, companyId?: n }, }); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'find unique journal in findUniqueJournalInPrisma failed', + error as Error + ); + logError.error( + 'Prisma related find unique journal in findUniqueJournalInPrisma in invoice.repo.ts failed' + ); throw new Error(STATUS_MESSAGE.DATABASE_READ_FAILED_ERROR); } return journal; @@ -134,7 +163,14 @@ export async function createPaymentInPrisma(paymentData: IPaymentBeta) { }, }); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'create payment in createPaymentInPrisma failed', + error as Error + ); + logError.error( + 'Prisma related create payment in createPaymentInPrisma in invoice.repo.ts failed' + ); throw new Error(STATUS_MESSAGE.DATABASE_CREATE_FAILED_ERROR); } return payment; @@ -185,10 +221,17 @@ export async function findUniqueInvoiceInPrisma(invoiceId: number, companyId?: n }); if (!invoice) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + loggerBack.error('Invoice not found'); } } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'find unique invoice in findUniqueInvoiceInPrisma failed', + error as Error + ); + logError.error( + 'Prisma related find unique invoice in findUniqueInvoiceInPrisma in invoice.repo.ts failed' + ); throw new Error(STATUS_MESSAGE.DATABASE_READ_FAILED_ERROR); } return invoice; @@ -230,7 +273,14 @@ export async function createInvoiceInPrisma( }, }); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'create invoice in createInvoiceInPrisma failed', + error as Error + ); + logError.error( + 'Prisma related create invoice in createInvoiceInPrisma in invoice.repo.ts failed' + ); throw new Error(STATUS_MESSAGE.DATABASE_CREATE_FAILED_ERROR); } @@ -255,7 +305,14 @@ export async function createInvoiceAndPaymentInPrisma( return invoice.id; }); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'create invoice and payment in createInvoiceAndPaymentInPrisma failed', + error as Error + ); + logError.error( + 'Prisma related create invoice or payment in createInvoiceAndPaymentInPrisma in invoice.repo.ts failed' + ); throw new Error(STATUS_MESSAGE.DATABASE_CREATE_FAILED_ERROR); } @@ -295,7 +352,14 @@ export async function updateInvoiceInPrisma( }, }); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'update invoice in updateInvoiceInPrisma failed', + error as Error + ); + logError.error( + 'Prisma related update invoice in updateInvoiceInPrisma in invoice.repo.ts failed' + ); throw new Error(STATUS_MESSAGE.DATABASE_UPDATE_FAILED_ERROR); } @@ -330,7 +394,14 @@ export async function updateInvoiceAndPaymentInPrisma( updatedInvoiceId = invoice.id; } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'update invoice and payment in updateInvoiceAndPaymentInPrisma failed', + error as Error + ); + logError.error( + 'Prisma related update invoice or payment in updateInvoiceAndPaymentInPrisma in invoice.repo.ts failed' + ); } return updatedInvoiceId; } @@ -384,7 +455,14 @@ export async function createJournalInPrisma( }, }); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'create journal in createJournalInPrisma failed', + error as Error + ); + logError.error( + 'Prisma related create journal in createJournalInPrisma in invoice.repo.ts failed' + ); throw new Error(STATUS_MESSAGE.DATABASE_CREATE_FAILED_ERROR); } @@ -431,7 +509,14 @@ export async function updateJournalInPrisma( }, }); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'update journal in updateJournalInPrisma failed', + error as Error + ); + logError.error( + 'Prisma related update journal in updateJournalInPrisma in invoice.repo.ts failed' + ); throw new Error(STATUS_MESSAGE.DATABASE_UPDATE_FAILED_ERROR); } @@ -473,12 +558,14 @@ export async function handlePrismaSavingLogic( await updateOcrStatusInPrisma(ocrIdInDB.id, ProgressStatus.HAS_BEEN_USED); } } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError(0, 'handlePrismaSavingLogic failed', error as Error); + logError.error('Prisma related func. in handlePrismaSavingLogic in invoice.repo.ts failed'); } return journalIdBeCreated; } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError(0, 'handlePrismaSavingLogic failed', error as Error); + logError.error('Prisma related func. in handlePrismaSavingLogic in invoice.repo.ts failed'); throw new Error(STATUS_MESSAGE.DATABASE_CREATE_FAILED_ERROR); } } @@ -524,7 +611,8 @@ export async function handlePrismaUpdateLogic( contractId ); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError(0, 'handlePrismaUpdateLogic failed', error as Error); + logError.error('Prisma related func. in handlePrismaUpdateLogic in invoice.repo.ts failed'); } return journalIdBeUpdated; diff --git a/src/lib/utils/repo/journal.repo.ts b/src/lib/utils/repo/journal.repo.ts index c60938aa..1d4c9270 100644 --- a/src/lib/utils/repo/journal.repo.ts +++ b/src/lib/utils/repo/journal.repo.ts @@ -10,6 +10,7 @@ import { Prisma } from '@prisma/client'; import { calculateTotalPages, getTimestampNow } from '@/lib/utils/common'; import { JOURNAL_EVENT, SortBy } from '@/constants/journal'; import { SortOrder } from '@/constants/sort'; +import { loggerError } from '@/lib/utils/logger_back'; export async function findManyJournalsInPrisma( companyId: number, @@ -89,7 +90,12 @@ export async function findManyJournalsInPrisma( }, }); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'Find many journals in findManyJournalsInPrisma failed', + error as Error + ); + logError.error('Prisma find many journals in journal.repo.ts failed'); throw new Error(STATUS_MESSAGE.DATABASE_READ_FAILED_ERROR); } return journals; @@ -193,7 +199,8 @@ export async function listJournal( return paginatedJournalList; } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError(0, 'List journal in listJournal failed', error as Error); + logError.error('Func. listJournal in journal.repo.ts failed'); throw new Error(STATUS_MESSAGE.DATABASE_READ_FAILED_ERROR); } } @@ -237,7 +244,14 @@ export async function findUniqueJournalInPrisma(journalId: number, companyId: nu journal = await prisma.journal.findUnique(findUniqueArgs); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'Find unique journal in findUniqueJournalInPrisma failed', + error as Error + ); + logError.error( + 'Prisma find unique journal in findUniqueJournalInPrisma in journal.repo.ts failed' + ); throw new Error(STATUS_MESSAGE.DATABASE_READ_FAILED_ERROR); } return journal; @@ -254,7 +268,12 @@ export async function deleteJournalInPrisma( try { journalExists = await findUniqueJournalInPrisma(journalId, companyId); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'Find unique journal in deleteJournalInPrisma failed', + error as Error + ); + logError.error('Prisma find unique journal in deleteJournalInPrisma in journal.repo.ts failed'); } if (journalExists) { @@ -344,7 +363,14 @@ export async function deleteJournalInPrisma( }); }); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'Soft delete journal in deleteJournalInPrisma failed', + error as Error + ); + logError.error( + 'Prisma soft delete journal in deleteJournalInPrisma in journal.repo.ts failed' + ); } } return journal; diff --git a/src/lib/utils/repo/line_item.beta.repo.ts b/src/lib/utils/repo/line_item.beta.repo.ts index eff04460..44de7ed2 100644 --- a/src/lib/utils/repo/line_item.beta.repo.ts +++ b/src/lib/utils/repo/line_item.beta.repo.ts @@ -14,6 +14,7 @@ import { DEFAULT_PAGE_NUMBER } from '@/constants/display'; import { ILineItem, ILineItemIncludeAccount } from '@/interfaces/line_item'; import { IPaginatedData } from '@/interfaces/pagination'; import { STATUS_MESSAGE } from '@/constants/status_code'; +import { loggerError } from '@/lib/utils/logger_back'; /** * list invoices, return paginated data @@ -121,7 +122,8 @@ export async function listLineItems({ try { lineItems = await prisma.lineItem.findMany(findManyArgs); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError(0, 'Find many line items in listLineItems failed', error as Error); + logError.error('Prisma find many line items in listLineItems in line_item.beta.repo.ts failed'); } const hasNextPage = lineItems.length > pageSize; @@ -199,7 +201,8 @@ export async function createLineItem({ try { result = await prisma.lineItem.create(lineItemCreateArgs); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError(0, 'Create line item in createLineItem failed', error as Error); + logError.error('Prisma create line item in createLineItem in line_item.beta.repo.ts failed'); } return result; @@ -262,7 +265,8 @@ export async function updateLineItem({ try { result = await prisma.lineItem.update(lineItemUpdateArgs); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError(0, 'Update line item in updateLineItem failed', error as Error); + logError.error('Prisma update line item in updateLineItem in line_item.beta.repo.ts failed'); } return result; @@ -294,7 +298,14 @@ export async function deleteLineItem(lineItemId: number): Promise { diff --git a/src/lib/utils/repo/voucher.beta.repo.ts b/src/lib/utils/repo/voucher.beta.repo.ts index 2c82c44a..0cdf7fe4 100644 --- a/src/lib/utils/repo/voucher.beta.repo.ts +++ b/src/lib/utils/repo/voucher.beta.repo.ts @@ -7,6 +7,7 @@ import { } from '@/interfaces/voucher'; import { getTimestampNow, timestampInSeconds } from '@/lib/utils/common'; import { Prisma, Voucher } from '@prisma/client'; +import { loggerError } from '@/lib/utils/logger_back'; /** * This function can get the latest voucher no @@ -42,7 +43,14 @@ export async function getLatestVoucherNo(companyId: number) { try { voucher = await prisma.voucher.findFirst(findFirstArgs); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'get latest voucher no in getLatestVoucherNo failed', + error as Error + ); + logError.error( + 'Prisma related findFirst voucher in getLatestVoucherNo in voucher.beta.repo.ts failed' + ); } const localToday = new Date(); @@ -91,7 +99,14 @@ export async function findUniqueVoucherById(voucherId: number) { try { voucherData = await prisma.voucher.findUnique(findUniqueArgs); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'find unique voucher in findUniqueVoucherById failed', + error as Error + ); + logError.error( + 'Prisma related find unique voucher in findUniqueVoucherById in voucher.beta.repo.ts failed' + ); } return voucherData; } @@ -127,7 +142,14 @@ export async function createVoucherInPrisma(newVoucherNo: string, journalId: num try { voucherData = await prisma.voucher.create(voucherCreateArgs); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'create voucher in createVoucherInPrisma failed', + error as Error + ); + logError.error( + 'Prisma related create voucher in createVoucherInPrisma in voucher.beta.repo.ts failed' + ); } return voucherData; @@ -184,7 +206,14 @@ export async function findManyVoucherWithCashInPrisma( try { vouchers = await prisma.voucher.findMany(findManyArgs); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'find many voucher in findManyVoucherWithCashInPrisma failed', + error as Error + ); + logError.error( + 'Prisma related find many voucher in findManyVoucherWithCashInPrisma in voucher.beta.repo.ts failed' + ); } return vouchers; diff --git a/src/lib/utils/repo/voucher.repo.ts b/src/lib/utils/repo/voucher.repo.ts index deb33329..a41f4725 100644 --- a/src/lib/utils/repo/voucher.repo.ts +++ b/src/lib/utils/repo/voucher.repo.ts @@ -10,6 +10,7 @@ import { IVoucherFromPrismaIncludeJournalLineItems, } from '@/interfaces/voucher'; import { SortOrder } from '@/constants/sort'; +import loggerBack, { loggerError } from '@/lib/utils/logger_back'; export async function findUniqueJournalInvolveInvoicePaymentInPrisma( journalId: number | undefined @@ -30,7 +31,14 @@ export async function findUniqueJournalInvolveInvoicePaymentInPrisma( return result; } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'find unique journal involve invoice payment in findUniqueJournalInvolveInvoicePaymentInPrisma failed', + error as Error + ); + logError.error( + 'Prisma related find unique journal involve invoice payment in findUniqueJournalInvolveInvoicePaymentInPrisma in voucher.repo.ts failed' + ); throw new Error(STATUS_MESSAGE.DATABASE_READ_FAILED_ERROR); } } @@ -48,7 +56,14 @@ export async function findFirstAccountByNameInPrisma(accountName: string) { return result?.id || null; } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'find first account by name in findFirstAccountByNameInPrisma failed', + error as Error + ); + logError.error( + 'Prisma related find first account by name in findFirstAccountByNameInPrisma in voucher.repo.ts failed' + ); throw new Error(STATUS_MESSAGE.DATABASE_READ_FAILED_ERROR); } } @@ -75,7 +90,14 @@ export async function findFirstAccountBelongsToCompanyInPrisma(id: string, compa return result; } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'find first account belongs to company in findFirstAccountBelongsToCompanyInPrisma failed', + error as Error + ); + logError.error( + 'Prisma related find first account belongs to company in findFirstAccountBelongsToCompanyInPrisma in voucher.repo.ts failed' + ); throw new Error(STATUS_MESSAGE.DATABASE_READ_FAILED_ERROR); } } @@ -97,7 +119,14 @@ export async function findUniqueVoucherInPrisma(voucherId: number) { }, }); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'find unique voucher in findUniqueVoucherInPrisma failed', + error as Error + ); + logError.error( + 'Prisma related find unique voucher in findUniqueVoucherInPrisma in voucher.repo.ts failed' + ); throw new Error(STATUS_MESSAGE.DATABASE_READ_FAILED_ERROR); } return voucherData; @@ -110,7 +139,9 @@ export async function createLineItemInPrisma( ) { try { if (!lineItem.accountId) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + loggerBack.error( + 'lineItem.accountId is not provided in createLineItemInPrisma in voucher.repo.ts' + ); throw new Error(STATUS_MESSAGE.INTERNAL_SERVICE_ERROR); } @@ -120,7 +151,9 @@ export async function createLineItemInPrisma( ); if (!accountBelongsToCompany) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + loggerBack.error( + 'Account does not belong to company in createLineItemInPrisma in voucher.repo.ts' + ); throw new Error(STATUS_MESSAGE.INTERNAL_SERVICE_ERROR); } @@ -151,7 +184,14 @@ export async function createLineItemInPrisma( return result.id; } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'create line item in createLineItemInPrisma failed', + error as Error + ); + logError.error( + 'Prisma related create line item in createLineItemInPrisma in voucher.repo.ts failed' + ); throw new Error(STATUS_MESSAGE.DATABASE_CREATE_FAILED_ERROR); } } @@ -187,7 +227,14 @@ export async function getLatestVoucherNoInPrisma(companyId: number) { return `${localTodayNo}${newVoucherNo}`; } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'get latest voucher no in getLatestVoucherNoInPrisma failed', + error as Error + ); + logError.error( + 'Prisma related get latest voucher no in getLatestVoucherNoInPrisma in voucher.repo.ts failed' + ); throw new Error(STATUS_MESSAGE.DATABASE_READ_FAILED_ERROR); } } @@ -215,7 +262,14 @@ export async function createVoucherInPrisma(newVoucherNo: string, journalId: num return voucherData; } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'create voucher in createVoucherInPrisma failed', + error as Error + ); + logError.error( + 'Prisma related create voucher in createVoucherInPrisma in voucher.repo.ts failed' + ); throw new Error(STATUS_MESSAGE.DATABASE_CREATE_FAILED_ERROR); } } @@ -260,7 +314,14 @@ export async function findManyVoucherWithCashInPrisma( return vouchers; } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'find many voucher with cash in findManyVoucherWithCashInPrisma failed', + error as Error + ); + logError.error( + 'Prisma related find many voucher with cash in findManyVoucherWithCashInPrisma in voucher.repo.ts failed' + ); throw new Error(STATUS_MESSAGE.DATABASE_READ_FAILED_ERROR); } } diff --git a/src/pages/api/auth/error.ts b/src/pages/api/auth/error.ts index b8e1e15d..fb99c088 100644 --- a/src/pages/api/auth/error.ts +++ b/src/pages/api/auth/error.ts @@ -1,12 +1,18 @@ import { NextApiRequest, NextApiResponse } from 'next'; +import loggerBack, { loggerError } from '@/lib/utils/logger_back'; export default async function handler(req: NextApiRequest, res: NextApiResponse) { try { const { error } = req.query; - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + loggerBack.error(`Authentication Error: ${error}`); return res.status(500).json({ message: `Authentication Error: ${error}` }); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'Internal Server Error, handler auth error failed', + error as Error + ); + logError.error('handle auth error failed in handler function in auth/error.ts'); return res.status(500).json({ message: 'Internal Server Error' }); } } diff --git a/src/pages/api/v1/company/[companyId]/account/index.ts b/src/pages/api/v1/company/[companyId]/account/index.ts index 1c09c16c..54d6493c 100644 --- a/src/pages/api/v1/company/[companyId]/account/index.ts +++ b/src/pages/api/v1/company/[companyId]/account/index.ts @@ -183,18 +183,16 @@ export async function handleGetRequest( req: NextApiRequest, res: NextApiResponse> ) { - const { companyId } = await getSession(req, res); + const { companyId, userId } = await getSession(req, res); const formattedQuery = formatGetQuery(companyId, req); - const accountRetriever = AccountRetrieverFactory.createRetriever(formattedQuery); let paginatedAccount: IPaginatedAccount | null = null; - try { paginatedAccount = await accountRetriever.getAccounts(); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError(userId, 'Failed to retrieve accounts', error as Error); + logError.error('Prisma related error'); } - return paginatedAccount; } @@ -285,7 +283,8 @@ export default async function handler( } } catch (_error) { const error = _error as Error; - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError(0, 'handle account request failed', error); + logError.error('handle account request failed in handler function in account/index.ts'); statusMessage = error.message; } const { httpCode, result } = formatApiResponse( diff --git a/src/pages/api/v1/company/[companyId]/employee/[employeeId]/index.ts b/src/pages/api/v1/company/[companyId]/employee/[employeeId]/index.ts index 1d47b407..740054df 100644 --- a/src/pages/api/v1/company/[companyId]/employee/[employeeId]/index.ts +++ b/src/pages/api/v1/company/[companyId]/employee/[employeeId]/index.ts @@ -13,6 +13,7 @@ import { updateEmployeeById, } from '@/lib/utils/repo/employee.repo'; import { AuthFunctionsKeys } from '@/interfaces/auth'; +import { loggerError } from '@/lib/utils/logger_back'; function getTargetTime(): number { const nowTime = new Date().getTime(); @@ -66,7 +67,10 @@ async function deleteEmployee(employeeIdNumber: number): Promise { try { await updateEndDateByEmployeeId(employeeIdNumber, targetTime); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError(0, 'delete employee in deleteEmployee failed', error as Error); + logError.error( + 'Prisma related updateEndDateByEmployeeId in deleteEmployee in employee/employeeId/index.ts failed' + ); } } @@ -92,7 +96,10 @@ async function updateEmployee( ); await updateEmployeeProject(employeeIdNumber, projectIdsNames, targetTime); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError(0, 'update employee in updateEmployee failed', error as Error); + logError.error( + 'Prisma related updateEmployeeById or updateEmployeeProject in updateEmployee in employee/employeeId/index.ts failed' + ); } const employee = await getEmployeeById(employeeIdNumber); const projects = await getProjectsByEmployeeId(employeeIdNumber); diff --git a/src/pages/api/v1/company/[companyId]/invoice/index.ts b/src/pages/api/v1/company/[companyId]/invoice/index.ts index 8e7e1372..f899891f 100644 --- a/src/pages/api/v1/company/[companyId]/invoice/index.ts +++ b/src/pages/api/v1/company/[companyId]/invoice/index.ts @@ -12,6 +12,7 @@ import { checkAuthorization } from '@/lib/utils/auth_check'; import { getSession } from '@/lib/utils/session'; import { AuthFunctionsKeys } from '@/interfaces/auth'; import { InvoiceType } from '@/constants/invoice'; +import { loggerError } from '@/lib/utils/logger_back'; export interface IPostApiResponseType { journalId: number; @@ -74,7 +75,10 @@ export async function uploadInvoiceToAICH(invoice: IInvoice) { body: JSON.stringify([invoiceData]), }); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError(0, 'upload invoice to AICH failed', error as Error); + logError.error( + 'upload invoice to AICH failed when fetch in uploadInvoiceToAICH in invoice/index.ts' + ); throw new Error(STATUS_MESSAGE.INTERNAL_SERVICE_ERROR_AICH_FAILED); } @@ -99,7 +103,10 @@ export async function getPayloadFromResponseJSON( try { json = await responseJSON; } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError(0, 'get payload from response JSON failed', error as Error); + logError.error( + 'get payload from response JSON failed when await responseJSON in getPayloadFromResponseJSON in invoice/index.ts' + ); throw new Error(STATUS_MESSAGE.PARSE_JSON_FAILED_ERROR); } @@ -182,8 +189,8 @@ export default async function handler( } } catch (_error) { const error = _error as Error; - - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError(0, 'handler request failed', error); + logError.error('handle invoice request failed in handler in invoice/index.ts'); handleErrorResponse(res, error.message); } } diff --git a/src/pages/api/v1/company/[companyId]/labor_cost_chart/index.ts b/src/pages/api/v1/company/[companyId]/labor_cost_chart/index.ts index 89a019d9..12a8cbe9 100644 --- a/src/pages/api/v1/company/[companyId]/labor_cost_chart/index.ts +++ b/src/pages/api/v1/company/[companyId]/labor_cost_chart/index.ts @@ -8,6 +8,7 @@ import { checkAuthorization } from '@/lib/utils/auth_check'; import { getSession } from '@/lib/utils/session'; import { AuthFunctionsKeys } from '@/interfaces/auth'; import { getWorkRatesByCompanyId, getSalaryRecords } from '@/lib/utils/repo/labor_cost_chart.repo'; +import { loggerError } from '@/lib/utils/logger_back'; async function calculateProjectCosts( workRates: { @@ -45,15 +46,12 @@ async function calculateProjectCosts( }, {} as Record ); - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger // Info: (20240618 - Gibbs) 遍歷每一組 workRates Object.values(groupedWorkRates).forEach((group) => { const { createdAt } = group[0]; const { employeeId } = group[0].employeeProject; - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger // Info: (20240618 - Gibbs) 計算該員工在該日期的總工作時數 const totalHours = group.reduce((sum, current) => sum + current.actualHours, 0); - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger // Info: (20240618 - Gibbs) 找到該員工在該日期的薪資記錄 const salaryRecordList = salaryRecords.filter( (sr) => sr.employee_id === employeeId && sr.created_at === createdAt @@ -66,11 +64,9 @@ async function calculateProjectCosts( }, { total_payment: 0 } ); - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger if (!salaryRecord) return; // Info: (20240618 - Gibbs) 如果沒有找到薪資記錄,則跳過 // Info: (20240618 - Gibbs) 計算每小時薪資 const hourlyWage = salaryRecord.total_payment / totalHours; - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger // Info: (20240618 - Gibbs) 根據每個專案的工作時數比例分配薪資 group.forEach((employeeWorkRate) => { const projectName = employeeWorkRate.employeeProject.project.name; @@ -80,7 +76,6 @@ async function calculateProjectCosts( projectCosts[projectName] += hourlyWage * employeeWorkRate.actualHours; }); }); - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger return projectCosts; } @@ -119,12 +114,9 @@ async function handleGetRequest( if (date) { try { const workRates = await getWorkRatesByCompanyId(companyId, date); - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger const salaryRecords = await getSalaryRecords(date); - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger const projectCosts = await calculateProjectCosts(workRates, salaryRecords); const isEmpty = await checkEmpty(projectCosts); - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger payload = { date, categories: Object.keys(projectCosts), @@ -133,6 +125,10 @@ async function handleGetRequest( }; statusMessage = STATUS_MESSAGE.SUCCESS_GET; } catch (error) { + const logError = loggerError(userId, 'handleGetRequest failed', error as Error); + logError.error( + 'Prisma related func. in handleGetRequest in labor_cost_chart/index.ts failed' + ); statusMessage = STATUS_MESSAGE.INTERNAL_SERVICE_ERROR; } } diff --git a/src/pages/api/v1/company/[companyId]/ocr/[resultId]/index.ts b/src/pages/api/v1/company/[companyId]/ocr/[resultId]/index.ts index 676d7e01..a6d278df 100644 --- a/src/pages/api/v1/company/[companyId]/ocr/[resultId]/index.ts +++ b/src/pages/api/v1/company/[companyId]/ocr/[resultId]/index.ts @@ -18,7 +18,7 @@ import { checkAuthorization } from '@/lib/utils/auth_check'; import { AuthFunctionsKeys } from '@/interfaces/auth'; import { getAichUrl } from '@/lib/utils/aich'; import { AICH_APIS_TYPES } from '@/constants/aich'; -// import logger from '@/lib/utils/logger'; +import loggerBack, { loggerError } from '@/lib/utils/logger_back'; // Info: (20240522 - Murky) This OCR now can only be used on Invoice @@ -118,7 +118,7 @@ export async function handleGetRequest(resultId: string, type: string = 'invoice newOcr = formatOCRResultDate(newOcr); if (!isIInvoice(newOcr)) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + loggerBack.info('ocr/[resultId]: OCR result(newOcr) is not an invoice type'); newOcr = null; } @@ -192,7 +192,8 @@ export default async function handler( } } } catch (_error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError(userId, 'handle OCR request failed', _error as Error); + logError.error('handle OCR request failed in handler function in ocr/[resultId]/index.ts'); status = STATUS_MESSAGE.INTERNAL_SERVICE_ERROR; } } diff --git a/src/pages/api/v1/company/[companyId]/ocr/index.ts b/src/pages/api/v1/company/[companyId]/ocr/index.ts index c5eccc5f..9b122ba6 100644 --- a/src/pages/api/v1/company/[companyId]/ocr/index.ts +++ b/src/pages/api/v1/company/[companyId]/ocr/index.ts @@ -25,7 +25,7 @@ import { FileFolder, getFileFolder } from '@/constants/file'; import { getAichUrl } from '@/lib/utils/aich'; import { AICH_APIS_TYPES } from '@/constants/aich'; import { AVERAGE_OCR_PROCESSING_TIME } from '@/constants/ocr'; -import logger from '@/lib/utils/logger_back'; +import loggerBack, { loggerError } from '@/lib/utils/logger_back'; import { bufferToBlob, findFileByName, readFile } from '@/lib/utils/parse_image_form'; import { findFileById } from '@/lib/utils/repo/file.repo'; import { decryptImageFile, parseFilePathWithBaseUrlPlaceholder } from '@/lib/utils/file'; @@ -38,7 +38,7 @@ export async function readImageFromFilePath( const filePath = await findFileByName(fileFolder, fileName); if (!filePath) { - logger.info( + loggerBack.info( { fileName, }, @@ -50,7 +50,7 @@ export async function readImageFromFilePath( const fileBuffer = await readFile(filePath); if (!fileBuffer) { - logger.info( + loggerBack.info( { fileName, }, @@ -84,17 +84,12 @@ export async function uploadImageToAICH(imageBlob: Blob, imageName: string) { body: formData, }); } catch (error) { - // logger.error(error, 'Ocr uploadImageToAICH error, happen when POST AICH API'); + const logError = loggerError(0, 'upload image to AICH failed', error as Error); + logError.error('Ocr uploadImageToAICH error, happen when POST AICH API'); } if (!response || !response.ok) { - logger.info( - { - aich_response: response, - }, - 'Ocr uploadImageToAICH response is not ok' - ); - logger.error( + loggerBack.info( { aich_response: response, }, @@ -110,12 +105,12 @@ export async function getPayloadFromResponseJSON( responseJSON: Promise<{ payload?: unknown } | null> ) { if (!responseJSON) { - // logger.info( - // { - // responseJSON, - // }, - // 'Ocr getPayloadFromResponseJSON responseJSON is null' - // ); + loggerBack.info( + { + responseJSON, + }, + 'Ocr getPayloadFromResponseJSON responseJSON is null' + ); throw new Error(STATUS_MESSAGE.INTERNAL_SERVICE_ERROR_AICH_FAILED); } @@ -126,20 +121,20 @@ export async function getPayloadFromResponseJSON( try { json = await responseJSON; } catch (error) { - // logger.error( - // error, - // 'Ocr getPayloadFromResponseJSON error, happen when parse responseJSON from AICH API' - // ); + const logError = loggerError(0, 'get payload from response JSON failed', error as Error); + logError.error( + 'Ocr getPayloadFromResponseJSON error, happen when await responseJSON from AICH API' + ); throw new Error(STATUS_MESSAGE.PARSE_JSON_FAILED_ERROR); } if (!json || !json.payload) { - // logger.info( - // { - // aich_response: json, - // }, - // 'Ocr getPayloadFromResponseJSON response is not json, or json do not have payload' - // ); + loggerBack.info( + { + aich_response: json, + }, + 'Ocr getPayloadFromResponseJSON response is not json, or json do not have payload' + ); throw new Error(STATUS_MESSAGE.AICH_SUCCESSFUL_RETURN_BUT_RESULT_IS_NULL); } @@ -151,7 +146,7 @@ async function readFileFromLocalUrl(url: string): Promise { const fileBuffer = await readFile(filePath); if (!fileBuffer) { - logger.info( + loggerBack.info( `Error in reading image file from local url in OCR (but image existed), Url : ${url}` ); throw new Error(STATUS_MESSAGE.INTERNAL_SERVICE_ERROR); @@ -208,10 +203,12 @@ export async function postImageToAICH( type: 'invoice', uploadIdentifier, }; - logger.info(result, `Ocr postImageToAICH result, field: ${fileId}`); + loggerBack.info(result, `Ocr postImageToAICH result, field: ${fileId}`); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger - logger.error(error, 'Ocr postImageToAICH error, happen when POST Image to AICH API'); + const logError = loggerError(0, 'postImageToAICH failed', error as Error); + logError.error( + 'Ocr postImageToAICH error, happen when POST Image to AICH API, in postImageToAICH in ocr/index.ts' + ); } resultJson.push(result); @@ -285,7 +282,7 @@ function formatFormBody(req: NextApiRequest) { iv = (body.iv as string).split(','); imageType = body.imageType as string; } else { - logger.info(body, 'ocr body is not valid'); + loggerBack.info(body, 'ocr body is not valid'); throw new Error(STATUS_MESSAGE.INVALID_INPUT_TYPE); /* eslint-enable no-console */ } @@ -311,7 +308,7 @@ export async function fetchStatus(aichResultId: string) { const result = await fetch(fetchUrl); if (!result.ok) { - logger.info( + loggerBack.info( { aich_response: result, }, @@ -322,8 +319,10 @@ export async function fetchStatus(aichResultId: string) { status = (await result.json()).payload; } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger - // logger.error(error, 'Ocr fetchStatus error, happen when fetch AICH API'); + const logError = loggerError(0, 'fetchStatus failed', error as Error); + logError.error( + 'Ocr fetchStatus error, happen when fetch AICH API in fetchStatus in ocr/index.ts' + ); throw new Error(STATUS_MESSAGE.INTERNAL_SERVICE_ERROR_AICH_FAILED); } } @@ -419,8 +418,10 @@ export async function createOcrFromAichResults( }) ); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger - // logger.error(error, 'Ocr createOcrFromAichResults error, happen when create Ocr in Prisma'); + const logError = loggerError(0, 'createOcrFromAichResults failed', error as Error); + logError.error( + 'Ocr createOcrFromAichResults error, happen when create Ocr in Prisma in ocr/index.ts' + ); throw new Error(STATUS_MESSAGE.DATABASE_CREATE_FAILED_ERROR); } @@ -436,7 +437,8 @@ export async function handlePostRequest(companyId: number, req: NextApiRequest) resultJson = await createOcrFromAichResults(companyId, aichResults); statusMessage = STATUS_MESSAGE.CREATED; } catch (error) { - logger.error(error, 'Ocr handlePostRequest error, happen when POST Image to AICH API'); + const logError = loggerError(0, 'handlePostRequest failed', error as Error); + logError.error('Ocr handlePostRequest error, happen when POST Image to AICH API'); } return { @@ -454,11 +456,14 @@ export async function handleGetRequest(companyId: number, req: NextApiRequest) { try { ocrData = await findManyOCRByCompanyIdWithoutUsedInPrisma(companyId, ocrType as string); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger - // logger.error( - // error, - // 'Ocr handleGetRequest error, happen when findManyOCRByCompanyIdWithoutUsedInPrisma' - // ); + const logError = loggerError( + 0, + 'findManyOCRByCompanyIdWithoutUsedInPrisma failed', + error as Error + ); + logError.error( + 'Ocr handleGetRequest error, happen when findManyOCRByCompanyIdWithoutUsedInPrisma in ocr/index.ts' + ); throw new Error(STATUS_MESSAGE.INTERNAL_SERVICE_ERROR); } @@ -496,29 +501,29 @@ export default async function handler( break; } default: { - // logger.info( - // { - // method: req.method, - // }, - // 'Ocr handler method is not allowed' - // ); + loggerBack.info( + { + method: req.method, + }, + 'Ocr handler method is not allowed' + ); throw new Error(STATUS_MESSAGE.METHOD_NOT_ALLOWED); } } } catch (_error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger - // logger.error(_error, 'Ocr handler error'); + const logError = loggerError(userId, 'handle OCR request failed', _error as Error); + logError.error('handle OCR request failed in handler function in ocr/index.ts'); } } else { statusMessage = STATUS_MESSAGE.UNAUTHORIZED_ACCESS; - // logger.info( - // { - // userId, - // companyId, - // isAuth, - // }, - // 'Ocr handler is not authorized' - // ); + loggerBack.info( + { + userId, + companyId, + isAuth, + }, + 'Ocr handler is not authorized' + ); } const { httpCode, result } = formatApiResponse(statusMessage, payload); diff --git a/src/pages/api/v1/company/[companyId]/report/index.ts b/src/pages/api/v1/company/[companyId]/report/index.ts index d30747b3..9d241095 100644 --- a/src/pages/api/v1/company/[companyId]/report/index.ts +++ b/src/pages/api/v1/company/[companyId]/report/index.ts @@ -34,6 +34,7 @@ import { } from '@/lib/utils/type_guard/report'; import ReportGeneratorFactory from '@/lib/utils/report/report_generator_factory'; import { SortOrder } from '@/constants/sort'; +import { loggerError } from '@/lib/utils/logger_back'; export function formatTargetPageFromQuery(targetPage: string | string[] | undefined) { let targetPageNumber = DEFAULT_PAGE_NUMBER; @@ -244,7 +245,8 @@ async function generateReport( reportContent = await financialReportGenerator.generateReport(); } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError(0, 'generateReport failed', error as Error); + logError.error('Func. generateReport in company/companyId/report/index.ts failed'); } return reportContent; } diff --git a/src/pages/api/v1/company/[companyId]/voucher/[voucherId]/index.ts b/src/pages/api/v1/company/[companyId]/voucher/[voucherId]/index.ts index 6bad364c..77c5c073 100644 --- a/src/pages/api/v1/company/[companyId]/voucher/[voucherId]/index.ts +++ b/src/pages/api/v1/company/[companyId]/voucher/[voucherId]/index.ts @@ -12,6 +12,7 @@ import { import { checkAuthorization } from '@/lib/utils/auth_check'; import { AuthFunctionsKeys } from '@/interfaces/auth'; import { isVoucherAmountGreaterOrEqualThenPaymentAmount } from '@/lib/utils/voucher'; +import { loggerError } from '@/lib/utils/logger_back'; type ApiResponseType = IVoucherDataForAPIResponse | null; @@ -73,7 +74,10 @@ async function handleVoucherUpdatePrismaLogic( statusMessage = STATUS_MESSAGE.SUCCESS_UPDATE; } catch (_error) { const error = _error as Error; - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError(0, 'handleVoucherUpdatePrismaLogic failed', error); + logError.error( + 'Prisma related func. in handleVoucherUpdatePrismaLogic in voucher/voucherId/index.ts failed' + ); switch (error.message) { case STATUS_MESSAGE.RESOURCE_NOT_FOUND: statusMessage = STATUS_MESSAGE.RESOURCE_NOT_FOUND; @@ -104,7 +108,14 @@ async function handlePutRequest(companyId: number, req: NextApiRequest) { voucherUpdated = voucherUpdatedData.voucherUpdated; statusMessage = voucherUpdatedData.statusMessage; } catch (error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError( + 0, + 'handleVoucherUpdatePrismaLogic in handlePutRequest failed', + error as Error + ); + logError.error( + 'Prisma related func. in handlePutRequest in voucher/voucherId/index.ts failed' + ); } } @@ -140,7 +151,10 @@ export default async function handler( } } catch (_error) { const error = _error as Error; - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError(userId, 'handle voucherId request failed', error); + logError.error( + 'handle voucher request failed in handler function in voucher/voucherId/index.ts' + ); statusMessage = error.message; } } diff --git a/src/pages/api/v1/company/[companyId]/voucher/index.ts b/src/pages/api/v1/company/[companyId]/voucher/index.ts index 9fdd1433..24b08cee 100644 --- a/src/pages/api/v1/company/[companyId]/voucher/index.ts +++ b/src/pages/api/v1/company/[companyId]/voucher/index.ts @@ -22,6 +22,7 @@ import { getSession } from '@/lib/utils/session'; import { AuthFunctionsKeys } from '@/interfaces/auth'; import { IJournalFromPrismaIncludeInvoicePayment } from '@/interfaces/journal'; import { isVoucherAmountGreaterOrEqualThenPaymentAmount } from '@/lib/utils/voucher'; +import { loggerError } from '@/lib/utils/logger_back'; type ApiResponseType = IVoucherDataForAPIResponse | null; @@ -57,7 +58,10 @@ async function handleVoucherCreatePrismaLogic( statusMessage = STATUS_MESSAGE.CREATED; } catch (_error) { const error = _error as Error; - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError(0, 'handleVoucherCreatePrismaLogic failed', error); + logError.error( + 'Prisma related func. in handleVoucherCreatePrismaLogic in voucher/index.ts failed' + ); switch (error.message) { case STATUS_MESSAGE.RESOURCE_NOT_FOUND: @@ -126,7 +130,8 @@ export default async function handler( throw new Error(STATUS_MESSAGE.METHOD_NOT_ALLOWED); } } catch (_error) { - // Todo: (20240822 - Anna): [Beta] feat. Murky - 使用 logger + const logError = loggerError(userId, 'handler request failed', _error as Error); + logError.error('handle voucher request failed in handler in voucher/index.ts'); } } const { httpCode, result } = formatApiResponse(statusMessage, payload); From 91500371dae2cab2bc81f8f7ee1070f685fa32ed Mon Sep 17 00:00:00 2001 From: "gibbs.shih" Date: Tue, 10 Sep 2024 17:36:37 +0800 Subject: [PATCH 3/6] adjust logger error --- log/others/app-undefined.log | 0 package.json | 2 +- src/lib/utils/file.ts | 4 ++-- src/lib/utils/generate_user_icon.ts | 4 ++-- src/lib/utils/parse_image_form.ts | 4 ++-- src/lib/utils/repo/file.repo.ts | 16 ++++++++-------- .../api/v1/company/[companyId]/file/index.ts | 8 ++++---- .../company/[companyId]/image/[imageId]/index.ts | 12 +++++++----- .../[companyId]/ocr/[resultId]/index.test.ts | 10 +++++----- .../company/[companyId]/profit_insight/index.ts | 9 +++++++-- .../v1/company/[companyId]/public_key/index.ts | 6 +++--- 11 files changed, 41 insertions(+), 34 deletions(-) create mode 100644 log/others/app-undefined.log diff --git a/log/others/app-undefined.log b/log/others/app-undefined.log new file mode 100644 index 00000000..e69de29b diff --git a/package.json b/package.json index 92d8db74..25e024d4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "iSunFA", - "version": "0.8.0+73", + "version": "0.8.0+74", "private": false, "scripts": { "dev": "next dev", diff --git a/src/lib/utils/file.ts b/src/lib/utils/file.ts index 9fe91b29..56b0648c 100644 --- a/src/lib/utils/file.ts +++ b/src/lib/utils/file.ts @@ -16,7 +16,7 @@ import { decryptFile, getPrivateKeyByCompany, } from '@/lib/utils/crypto'; -import logger, { loggerError } from '@/lib/utils/logger_back'; +import loggerBack, { loggerError } from '@/lib/utils/logger_back'; import { STATUS_MESSAGE } from '@/constants/status_code'; export async function createFileFoldersIfNotExists(): Promise { @@ -84,7 +84,7 @@ export async function decryptImageFile({ const privateKey = await getPrivateKeyByCompany(companyId); if (!privateKey) { - logger.error(`Private key not found in decryptImageFile in image/[imageId]: ${file.id}`); + loggerBack.error(`Private key not found in decryptImageFile in image/[imageId]: ${file.id}`); throw new Error(STATUS_MESSAGE.FORBIDDEN); } const ivUint8Array = bufferToUint8Array(iv); diff --git a/src/lib/utils/generate_user_icon.ts b/src/lib/utils/generate_user_icon.ts index 3b49b2ff..5da4f764 100644 --- a/src/lib/utils/generate_user_icon.ts +++ b/src/lib/utils/generate_user_icon.ts @@ -4,7 +4,7 @@ import { generateSavePath, uploadFileToGoogleCloud, } from '@/lib/utils/google_image_upload'; -import logger from '@/lib/utils/logger_back'; +import loggerBack from '@/lib/utils/logger_back'; function isChinese(name: string): boolean { return /[\u3400-\u9FBF]/.test(name); @@ -102,7 +102,7 @@ export async function generateIcon(name: string) { mimeType = mimeAndSize.mimeType; size = mimeAndSize.size; } catch (error) { - logger.error(error, 'Error happened in generateIcon in generate_user_icon.ts'); + loggerBack.error(error, 'Error happened in generateIcon in generate_user_icon.ts'); } return { iconUrl, diff --git a/src/lib/utils/parse_image_form.ts b/src/lib/utils/parse_image_form.ts index 27cdffc4..a4d50077 100644 --- a/src/lib/utils/parse_image_form.ts +++ b/src/lib/utils/parse_image_form.ts @@ -4,7 +4,7 @@ import path from 'path'; import { NextApiRequest } from 'next'; import { FORMIDABLE_OPTIONS } from '@/constants/config'; import { FileFolder, getFileFolder } from '@/constants/file'; -import logger from '@/lib/utils/logger_back'; +import loggerBack from '@/lib/utils/logger_back'; export const parseForm = async ( req: NextApiRequest, @@ -59,7 +59,7 @@ export async function readFile(baseFolder: string, fileName?: string): Promise { }, }); } catch (error) { - logger.error(error, 'Error happened in findFileById in file.repo.ts'); + loggerBack.error(error, 'Error happened in findFileById in file.repo.ts'); } return file; } @@ -127,7 +127,7 @@ export async function findFileInDBByName(name: string): Promise { }, }); } catch (error) { - logger.error(error, 'Error happened in findFileByName in file.repo.ts'); + loggerBack.error(error, 'Error happened in findFileByName in file.repo.ts'); } return file; } @@ -151,7 +151,7 @@ export async function deleteFileById(fileId: number) { data, }); } catch (error) { - logger.error(error, 'Error happened in deleteFileById in file.repo.ts'); + loggerBack.error(error, 'Error happened in deleteFileById in file.repo.ts'); } return file; @@ -177,7 +177,7 @@ export async function deleteFileByName(name: string) { data, }); } catch (error) { - logger.error(error, 'Error happened in deleteFileByName in file.repo.ts'); + loggerBack.error(error, 'Error happened in deleteFileByName in file.repo.ts'); } return file; @@ -194,7 +194,7 @@ export async function deleteFileByIdForTesting(fileId: number) { where, }); } catch (error) { - logger.error(error, 'Error happened in deleteFileByIdForTest in file.repo.ts'); + loggerBack.error(error, 'Error happened in deleteFileByIdForTest in file.repo.ts'); } return file; diff --git a/src/pages/api/v1/company/[companyId]/file/index.ts b/src/pages/api/v1/company/[companyId]/file/index.ts index 71478fde..43a73294 100644 --- a/src/pages/api/v1/company/[companyId]/file/index.ts +++ b/src/pages/api/v1/company/[companyId]/file/index.ts @@ -14,7 +14,7 @@ import { updateProjectById } from '@/lib/utils/repo/project.repo'; import { AuthFunctionsKeys } from '@/interfaces/auth'; import formidable from 'formidable'; import { isEnumValue } from '@/lib/utils/type_guard/common'; -import logger from '@/lib/utils/logger_back'; +import loggerBack from '@/lib/utils/logger_back'; import { uint8ArrayToBuffer } from '@/lib/utils/crypto'; import { createFile } from '@/lib/utils/repo/file.repo'; import { generateFilePathWithBaseUrlPlaceholder } from '@/lib/utils/file'; @@ -144,7 +144,7 @@ function formatPostQuery(req: NextApiRequest) { // Info: (20240829 - Murky) Check if type is upload type const isTypeValid = isEnumValue(UploadType, type); if (!isTypeValid) { - logger.info(`API POST File: Invalid type: ${type}`); + loggerBack.info(`API POST File: Invalid type: ${type}`); throw new Error(STATUS_MESSAGE.INVALID_INPUT_TYPE); } @@ -198,7 +198,7 @@ async function handlePostRequest( if (!file) { statusMessage = STATUS_MESSAGE.IMAGE_UPLOAD_FAILED_ERROR; - logger.info(`API POST File: No file uploaded`); + loggerBack.info(`API POST File: No file uploaded`); } else { const { fileId, fileName } = await handleFileUpload( type, @@ -213,7 +213,7 @@ async function handlePostRequest( } } catch (_error) { const error = _error as Error; - logger.error(error, `API POST File: ${error.message}`); + loggerBack.error(error, `API POST File: ${error.message}`); statusMessage = error.message; } } diff --git a/src/pages/api/v1/company/[companyId]/image/[imageId]/index.ts b/src/pages/api/v1/company/[companyId]/image/[imageId]/index.ts index c201e72d..1071456e 100644 --- a/src/pages/api/v1/company/[companyId]/image/[imageId]/index.ts +++ b/src/pages/api/v1/company/[companyId]/image/[imageId]/index.ts @@ -6,7 +6,7 @@ import { formatApiResponse, isStringNumber } from '@/lib/utils/common'; import { isEnumValue } from '@/lib/utils/type_guard/common'; import { checkAuthorization } from '@/lib/utils/auth_check'; import { AuthFunctionsKeys } from '@/interfaces/auth'; -import logger from '@/lib/utils/logger_back'; +import loggerBack from '@/lib/utils/logger_back'; import { FileFolder } from '@/constants/file'; import { File } from '@prisma/client'; import { findFileById, findFileInDBByName } from '@/lib/utils/repo/file.repo'; @@ -55,7 +55,7 @@ async function handleGetRequest(req: NextApiRequest, res: NextApiResponse) { const { userId, companyId } = session; const isAuth = await checkAuthorization([AuthFunctionsKeys.user], { userId }); if (!isAuth) { - logger.info(`Unauthorized access in image/[imageId] by user: ${userId}`); + loggerBack.info(`Unauthorized access in image/[imageId] by user: ${userId}`); throw new Error(STATUS_MESSAGE.FORBIDDEN); } @@ -64,7 +64,7 @@ async function handleGetRequest(req: NextApiRequest, res: NextApiResponse) { const file = await getFileFromDB(imageId); if (!file) { - logger.info(`Image file not found in DB in image/[imageId]: ${imageId}`); + loggerBack.info(`Image file not found in DB in image/[imageId]: ${imageId}`); throw new Error(STATUS_MESSAGE.RESOURCE_NOT_FOUND); } @@ -72,14 +72,16 @@ async function handleGetRequest(req: NextApiRequest, res: NextApiResponse) { const fileBuffer = await readFile(filePath); if (!fileBuffer) { - logger.info(`Error in reading image file in image/[imageId] (but image existed): ${imageId}`); + loggerBack.info( + `Error in reading image file in image/[imageId] (but image existed): ${imageId}` + ); throw new Error(STATUS_MESSAGE.INTERNAL_SERVICE_ERROR); } payload = await decryptImageFile({ imageBuffer: fileBuffer, file, companyId }); } catch (_error) { const error = _error as Error; - logger.error(error, `Error in GET image/[imageId]:`); + loggerBack.error(error, `Error in GET image/[imageId]:`); statusMessage = error.message; } diff --git a/src/pages/api/v1/company/[companyId]/ocr/[resultId]/index.test.ts b/src/pages/api/v1/company/[companyId]/ocr/[resultId]/index.test.ts index 399f72df..43ac4355 100644 --- a/src/pages/api/v1/company/[companyId]/ocr/[resultId]/index.test.ts +++ b/src/pages/api/v1/company/[companyId]/ocr/[resultId]/index.test.ts @@ -3,7 +3,7 @@ import { STATUS_MESSAGE } from '@/constants/status_code'; import { IInvoice } from '@/interfaces/invoice'; import { EventType, PaymentPeriodType, PaymentStatusType } from '@/constants/account'; import * as common from '@/lib/utils/common'; -import logger from '@/lib/utils/logger_back'; +import loggerBack from '@/lib/utils/logger_back'; // Info: (20240806 - Murky) Temporary not use // let res: jest.Mocked; @@ -17,10 +17,10 @@ jest.mock('../../../../../../../lib/utils/common', () => ({ beforeEach(() => { // Info: (20240902 - Murky) Logger mock so that it doesn't log during tests - jest.spyOn(logger, 'error').mockImplementation(jest.fn()); - jest.spyOn(logger, 'warn').mockImplementation(jest.fn()); - jest.spyOn(logger, 'info').mockImplementation(jest.fn()); - jest.spyOn(logger, 'debug').mockImplementation(jest.fn()); + jest.spyOn(loggerBack, 'error').mockImplementation(jest.fn()); + jest.spyOn(loggerBack, 'warn').mockImplementation(jest.fn()); + jest.spyOn(loggerBack, 'info').mockImplementation(jest.fn()); + jest.spyOn(loggerBack, 'debug').mockImplementation(jest.fn()); }); afterEach(() => { diff --git a/src/pages/api/v1/company/[companyId]/profit_insight/index.ts b/src/pages/api/v1/company/[companyId]/profit_insight/index.ts index 83112405..b7f3cb31 100644 --- a/src/pages/api/v1/company/[companyId]/profit_insight/index.ts +++ b/src/pages/api/v1/company/[companyId]/profit_insight/index.ts @@ -13,6 +13,7 @@ import { getProjectsIncomeExpense, getPreLaunchProjectCount, } from '@/lib/utils/repo/profit_insight.repo'; +import { loggerError } from '@/lib/utils/logger_back'; export async function getProfitChange(targetTime: number, companyId: number) { // Info: (20240607 - Gibbs) startDayTimestampOfTargetTime, endDayTimestampOfTargetTime, startPreviousDayTimestampOfTargetTime, endPreviousDayTimestampOfTargetTime @@ -110,8 +111,12 @@ export default async function handler( } } } catch (_error) { - // ToDo: (20240823 - Murky) please used logger to print error - // const error = _error as Error; + const logError = loggerError( + userId, + 'request handler in profit_insight/index.ts failed', + _error as Error + ); + logError.error('request handler in profit_insight/index.ts failed'); statusMessage = STATUS_MESSAGE.INTERNAL_SERVICE_ERROR; } } diff --git a/src/pages/api/v1/company/[companyId]/public_key/index.ts b/src/pages/api/v1/company/[companyId]/public_key/index.ts index d1106cd6..1ac379c8 100644 --- a/src/pages/api/v1/company/[companyId]/public_key/index.ts +++ b/src/pages/api/v1/company/[companyId]/public_key/index.ts @@ -6,7 +6,7 @@ import { getSession } from '@/lib/utils/session'; import { checkAuthorization } from '@/lib/utils/auth_check'; import { AuthFunctionsKeys } from '@/interfaces/auth'; import { exportPublicKey, getPublicKeyByCompany } from '@/lib/utils/crypto'; -import logger from '@/lib/utils/logger_back'; +import loggerBack from '@/lib/utils/logger_back'; async function handleGetRequest( req: NextApiRequest, @@ -34,7 +34,7 @@ async function handleGetRequest( statusMessage = STATUS_MESSAGE.RESOURCE_NOT_FOUND; } } catch (error) { - logger.error(error); + loggerBack.error(error); } } } @@ -68,7 +68,7 @@ export default async function handler( } catch (_error) { const error = _error as Error; statusMessage = error.message; - logger.error(error); + loggerBack.error(error); } finally { const { httpCode, result } = formatApiResponse(statusMessage, payload); res.status(httpCode).json(result); From fca970c69eec0885aef16a10fc09866b8db8aa79 Mon Sep 17 00:00:00 2001 From: "gibbs.shih" Date: Wed, 11 Sep 2024 10:39:40 +0800 Subject: [PATCH 4/6] update instrumentation --- .gitignore | 3 +++ log/others/app-undefined.log | 0 package.json | 2 +- src/instrumentation.ts | 4 ---- 4 files changed, 4 insertions(+), 5 deletions(-) delete mode 100644 log/others/app-undefined.log diff --git a/.gitignore b/.gitignore index e61d7067..b4f51065 100644 --- a/.gitignore +++ b/.gitignore @@ -48,3 +48,6 @@ next-env.d.ts # backup *.backup pnpm-lock.yaml + +# logs +/log diff --git a/log/others/app-undefined.log b/log/others/app-undefined.log deleted file mode 100644 index e69de29b..00000000 diff --git a/package.json b/package.json index a8f9b623..5a5103ec 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "iSunFA", - "version": "0.8.1", + "version": "0.8.1+1", "private": false, "scripts": { "dev": "next dev", diff --git a/src/instrumentation.ts b/src/instrumentation.ts index 4cc58427..745bc012 100644 --- a/src/instrumentation.ts +++ b/src/instrumentation.ts @@ -1,10 +1,7 @@ -import loggerBack from '@/lib/utils/logger_back'; - /** * Info: (20240812 - Murky) All code in register will be run when "Starting..." is printed in the console. */ export async function register() { - loggerBack.info('Instrumentation register starting...'); // Info: (20240812 - Murky) Node module using in this file need to be dynamically imported, it must be inside "if" statement if (process.env.NEXT_RUNTIME === 'nodejs') { const { createFileFoldersIfNotExists } = await import('@/lib/utils/file'); @@ -12,5 +9,4 @@ export async function register() { await import('pino'); await import('next-logger'); } - loggerBack.info('Instrumentation register completed!'); } From 3ce778ec71d60ef277ffcd233d2a92534cd078c5 Mon Sep 17 00:00:00 2001 From: "gibbs.shih" Date: Wed, 11 Sep 2024 10:47:19 +0800 Subject: [PATCH 5/6] update gitignore --- .gitignore | 2 +- package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index b4f51065..cf344454 100644 --- a/.gitignore +++ b/.gitignore @@ -50,4 +50,4 @@ next-env.d.ts pnpm-lock.yaml # logs -/log +/log/* diff --git a/package.json b/package.json index 67911bd8..902ff6c8 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "iSunFA", - "version": "0.8.1+8", + "version": "0.8.1+10", "private": false, "scripts": { "dev": "next dev", From d43160afbcb4969bd32adc794e05af9650cef623 Mon Sep 17 00:00:00 2001 From: Luphia Chang Date: Wed, 11 Sep 2024 19:11:59 +0800 Subject: [PATCH 6/6] Update package.json --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 902ff6c8..2acfc154 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "iSunFA", - "version": "0.8.1+10", + "version": "0.8.1+7", "private": false, "scripts": { "dev": "next dev",