Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/ocr change interface #2084

Merged
merged 21 commits into from
Aug 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "iSunFA",
"version": "0.8.0+12",
"version": "0.8.0+13",
"private": false,
"scripts": {
"dev": "next dev",
Expand Down
4 changes: 4 additions & 0 deletions src/constants/aich.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
export enum AICH_APIS_TYPES {
UPLOAD_OCR = 'upload_ocr',
GET_OCR_RESULT_ID = 'get_ocr_result_id',
GET_OCR_RESULT = 'get_ocr_result',
UPLOAD_INVOICE = 'upload_invoice',
GET_INVOICE_RESULT_ID = 'get_invoice_result_id',
GET_INVOICE_RESULT = 'get_invoice_result',
}
17 changes: 17 additions & 0 deletions src/lib/utils/aich.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,23 @@ export function getAichUrl(endPoint: AICH_APIS_TYPES, aichResultId?: string): st
throw new Error('AICH Result ID is required');
}
return `${AICH_URI}/api/v1/ocr/${aichResultId}/process_status`;
case AICH_APIS_TYPES.GET_OCR_RESULT:
if (!aichResultId) {
throw new Error('AICH Result ID is required');
}
return `${AICH_URI}/api/v1/ocr/${aichResultId}/result`;
case AICH_APIS_TYPES.UPLOAD_INVOICE:
return `${AICH_URI}/api/v1/invoices/upload`;
case AICH_APIS_TYPES.GET_INVOICE_RESULT_ID:
if (!aichResultId) {
throw new Error('AICH Result ID is required');
}
return `${AICH_URI}/api/v1/invoices/${aichResultId}/process_status`;
case AICH_APIS_TYPES.GET_INVOICE_RESULT:
if (!aichResultId) {
throw new Error('AICH Result ID is required');
}
return `${AICH_URI}/api/v1/invoices/${aichResultId}/result`;
default:
throw new Error('Invalid AICH API Type');
}
Expand Down
27 changes: 26 additions & 1 deletion src/lib/utils/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,30 @@ export function transformBytesToFileSizeString(bytes: number): string {
return `${size} ${sizes[i]}`;
}

/**
* Info: (20240816 Murky): Transform file size string to bytes, file size string format should be like '1.00 MB'
* @param sizeString
* @returns
*/
export function transformFileSizeStringToBytes(sizeString: string): number {
const regex = /^\d+(\.\d+)? (Bytes|KB|MB|GB|TB|PB|EB|ZB|YB)$/;

let bytes = 0;
if (regex.test(sizeString)) {
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const [size, unit] = sizeString.split(' ');

const sizeIndex = sizes.indexOf(unit);
if (sizeIndex === -1) {
throw new Error('Invalid file size unit');
}

bytes = parseFloat(size) * 1024 ** sizeIndex;
}

return Math.round(bytes);
}

// page, limit to offset
export function pageToOffset(
page: number = DEFAULT_PAGE_START_AT,
Expand Down Expand Up @@ -635,5 +659,6 @@ export function throttle<F extends (...args: unknown[]) => unknown>(
}

export function generateUUID(): string {
return Math.random().toString(36).substring(2, 12);
const randomUUID = Math.random().toString(36).substring(2, 12);
return randomUUID;
}
8 changes: 4 additions & 4 deletions src/lib/utils/repo/ocr.repo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,9 @@ export async function createOcrInPrisma(
const now = Date.now();
const nowTimestamp = timestampInSeconds(now);

let ocrData: Ocr | null = null;
try {
const ocrData = await prisma.ocr.create({
ocrData = await prisma.ocr.create({
data: {
companyId,
aichResultId: aichResult.resultStatus.resultId,
Expand All @@ -112,14 +113,13 @@ export async function createOcrInPrisma(
updatedAt: nowTimestamp,
},
});

return ocrData;
} catch (error) {
// Deprecated (20240611 - Murky) Debugging purpose
// eslint-disable-next-line no-console
console.log(error);
throw new Error(STATUS_MESSAGE.DATABASE_CREATE_FAILED_ERROR);
}

return ocrData;
}

export async function deleteOcrByResultId(aichResultId: string): Promise<Ocr> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ describe('fetchOCRResult', () => {
const result = await module.fetchOCRResult(resultId);

expect(global.fetch).toHaveBeenCalledWith(
expect.stringContaining(`/api/v1/ocr/${resultId}/result`)
expect.stringContaining(`/api/v1/invoices/${resultId}/result`)
);

expect(result).toEqual({ payload: 'testPayload' });
Expand Down
6 changes: 4 additions & 2 deletions src/pages/api/v1/company/[companyId]/ocr/[resultId]/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
// Info Murky (20240416): this is mock api need to migrate to microservice
import type { NextApiRequest, NextApiResponse } from 'next';
import { AICH_URI } from '@/constants/config';
import { IResponseData } from '@/interfaces/response_data';
import { IInvoice } from '@/interfaces/invoice';
import {
Expand All @@ -17,6 +16,8 @@ import { ProgressStatus } from '@/constants/account';
import { getSession } from '@/lib/utils/session';
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';

// Info (20240522 - Murky): This OCR now can only be used on Invoice

Expand All @@ -31,7 +32,8 @@ export async function fetchOCRResult(resultId: string) {
let response: Response;

try {
response = await fetch(`${AICH_URI}/api/v1/ocr/${resultId}/result`);
const fetchURL = getAichUrl(AICH_APIS_TYPES.GET_INVOICE_RESULT, resultId);
response = await fetch(fetchURL);
} catch (error) {
throw new Error(STATUS_MESSAGE.INTERNAL_SERVICE_ERROR_AICH_FAILED);
}
Expand Down
60 changes: 47 additions & 13 deletions src/pages/api/v1/company/[companyId]/ocr/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import * as repository from '@/lib/utils/repo/ocr.repo';
import { Ocr } from '@prisma/client';
import { IAccountResultStatus } from '@/interfaces/accounting_account';
import * as authCheck from '@/lib/utils/auth_check';
import { IOCR } from '@/interfaces/ocr';

global.fetch = jest.fn();

Expand All @@ -24,6 +25,7 @@ jest.mock('../../../../../../lib/utils/common', () => ({
timestampInSeconds: jest.fn(),
timestampInMilliSeconds: jest.fn(),
transformBytesToFileSizeString: jest.fn(),
generateUUID: jest.fn(),
}));

jest.mock('../../../../../../lib/utils/repo/ocr.repo', () => {
Expand Down Expand Up @@ -123,7 +125,7 @@ describe('POST OCR', () => {
expect(promiseJson).toBeInstanceOf(Promise);

expect(global.fetch).toHaveBeenCalledWith(
expect.stringContaining('/ocr/upload'),
expect.stringContaining('/invoices/upload'),
expect.objectContaining({ method: 'POST', body: expect.any(FormData) })
);
});
Expand Down Expand Up @@ -175,13 +177,19 @@ describe('POST OCR', () => {
describe('postImageToAICH', () => {
let mockImages: MockProxy<formidable.Files<'image'>>;
let mockImage: MockProxy<formidable.File>;
let mockImageFields: {
imageSize: number;
imageName: string;
uploadIdentifier: string;
}[];
const mockPath = '/test';
const mockMimetype = 'image/png';
const mockFileContent = Buffer.from('mock image content');
beforeEach(() => {
mockImage = mock<formidable.File>();
mockImage.filepath = mockPath;
mockImage.mimetype = mockMimetype;
mockImageFields = [];
mockImage.size = 1000;
jest.spyOn(fs.promises, 'readFile').mockResolvedValue(mockFileContent);
jest.spyOn(common, 'transformOCRImageIDToURL').mockReturnValue('testImageUrl');
Expand All @@ -201,7 +209,8 @@ describe('POST OCR', () => {
mockImages = mock<formidable.Files<'image'>>({
image: [],
});
const result = await module.postImageToAICH(mockImages);
mockImageFields = [];
const result = await module.postImageToAICH(mockImages, mockImageFields);
expect(result).toEqual([]);
});

Expand All @@ -213,7 +222,7 @@ describe('POST OCR', () => {

(global.fetch as jest.Mock).mockResolvedValue(mockResponse);

const resultJson = await module.postImageToAICH(mockImages);
const resultJson = await module.postImageToAICH(mockImages, mockImageFields);

const resultJsonExpect = expect.objectContaining({
resultStatus: expect.any(String),
Expand All @@ -227,7 +236,7 @@ describe('POST OCR', () => {
expect(resultJson).toEqual(resultJsonArrayExpect);

expect(global.fetch).toHaveBeenCalledWith(
expect.stringContaining('/ocr/upload'),
expect.stringContaining('/invoices/upload'),
expect.objectContaining({ method: 'POST', body: expect.any(FormData) })
);
});
Expand Down Expand Up @@ -271,7 +280,11 @@ describe('POST OCR', () => {
},
],
};
mockFields = mock<formidable.Fields>();
mockFields = {
imageSize: ["1 MB"],
imageName: ['test.png'],
uploadIdentifier: ['test'],
};
});

it('should return image file', async () => {
Expand All @@ -281,19 +294,28 @@ describe('POST OCR', () => {
};

jest.spyOn(parseImageForm, 'parseForm').mockResolvedValue(mockReturn);
const imageFile = await module.getImageFileFromFormData(req);
expect(imageFile).toEqual(mockFiles);
const imageFile = await module.getImageFileAndFormFromFormData(req);

expect(imageFile).toEqual(mockReturn);
});

it('should return empty object when parseForm failed', async () => {
jest.spyOn(parseImageForm, 'parseForm').mockRejectedValue(new Error('parseForm failed'));
const result = await module.getImageFileFromFormData(req);
expect(result).toEqual({});
const result = await module.getImageFileAndFormFromFormData(req);

const expectReturn = {
fields: {},
files: {},
};

expect(result).toEqual(expectReturn);
});
});

describe('createOcrFromAichResults', () => {
it('should return resultJson', async () => {
jest.spyOn(common, 'timestampInSeconds').mockReturnValue(0);
jest.spyOn(common, 'transformBytesToFileSizeString').mockReturnValue('1 MB');
const resultId = 'testResultId';
const companyId = 1;
const mockAichReturn = [
Expand All @@ -306,6 +328,8 @@ describe('POST OCR', () => {
imageName: 'testImageName',
imageSize: 1024,
type: 'invoice',
uploadIdentifier: 'test',
createAt: 0,
},
];

Expand All @@ -323,11 +347,18 @@ describe('POST OCR', () => {
deletedAt: null,
};

const expectResult: IAccountResultStatus[] = [
const expectResult: IOCR[] = [
{
resultId,
status: ProgressStatus.SUCCESS,
},
aichResultId: "testResultId",
createdAt: 0,
id: 1,
imageName: "testImageName",
imageSize: "1 MB",
imageUrl: "testImageUrl",
progress: 0,
status: ProgressStatus.IN_PROGRESS,
uploadIdentifier: "test",
}
];

jest.spyOn(repository, 'createOcrInPrisma').mockResolvedValue(mockOcrDbResult);
Expand Down Expand Up @@ -433,13 +464,16 @@ describe('GET OCR', () => {
describe('fetchStatus', () => {
it('should return resultJson', async () => {
const aichResultId = 'testAichResultId';

const mockResponse = {
ok: true,
json: jest.fn().mockResolvedValue({ payload: ProgressStatus.SUCCESS }),
};

(global.fetch as jest.Mock).mockResolvedValue(mockResponse);

jest.spyOn(common, 'generateUUID').mockReturnValue(aichResultId);

const resultJson = await module.fetchStatus(aichResultId);
expect(resultJson).toEqual(ProgressStatus.SUCCESS);
});
Expand Down
Loading