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 8 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+10",
"version": "0.8.0+11",
"private": false,
"scripts": {
"dev": "next dev",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ const LoginConfirmModal: React.FC<ILoginConfirmProps> = ({
</button>
</div>
<hr className="absolute left-0 top-60px w-full max-w-xl border-lightGray6" />
<div className="h-50vh m-4 overflow-y-auto rounded-xs border border-navyBlue bg-lightGray7 lg:p-4">
<div className="m-4 h-50vh overflow-y-auto rounded-xs border border-navyBlue bg-lightGray7 lg:p-4">
{modalData.content === 'info_collection_statement' && <InformationStatement />}
{modalData.content === 'term_n_privacy' && <TermsOfServiceAndPrivacyPolicy />}
</div>
Expand Down
2 changes: 1 addition & 1 deletion src/components/login_page_body/login_page_body.beta.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ const LoginPageBody = () => {

return (
<div className="relative flex h-screen flex-col items-center justify-center text-center">
<div className="bg-login_bg absolute inset-0 z-0 h-full w-full bg-cover bg-center bg-no-repeat blur-md"></div>
<div className="absolute inset-0 z-0 h-full w-full bg-login_bg bg-cover bg-center bg-no-repeat blur-md"></div>
{isLoading ? (
<Loader />
) : (
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_GEMINI = 'upload_gemini',
GET_GEMINI_RESULT_ID = 'get_gemini_result_id',
GET_GEMINI_RESULT = 'get_gemini_result',
}
2 changes: 1 addition & 1 deletion src/contexts/global_context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -420,7 +420,7 @@ export const GlobalProvider = ({ children }: IGlobalProvider) => {
const position = toastPosition ?? ToastPosition.TOP_CENTER; // Info:(20240513 - Julian) default position 'top-center'

// Info:(20240513 - Julian) 如果 closeable 為 false,則 autoClose、closeOnClick、draggable 都會被設為 false
const autoClose = closeable ? isAutoClose ?? 5000 : false; // Info:(20240513 - Julian) default autoClose 5000ms
const autoClose = closeable ? (isAutoClose ?? 5000) : false; // Info:(20240513 - Julian) default autoClose 5000ms

const closeOnClick = closeable; // Info:(20240513 - Julian) default closeOnClick true
const draggable = closeable; // Info:(20240513 - Julian) default draggable true
Expand Down
2 changes: 1 addition & 1 deletion src/lib/hooks/use_api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ const useAPI = <Data>(
apiConfig: IAPIConfig,
options: IAPIInput,
triggerImmediately: boolean = false,
cancel?: boolean,
cancel?: boolean
): IAPIResponse<Data> => {
const [success, setSuccess] = useState<boolean | undefined>(undefined);
const [code, setCode] = useState<string | undefined>(undefined);
Expand Down
2 changes: 1 addition & 1 deletion src/lib/hooks/use_api_worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const useAPIWorker = <Data>(
apiConfig: IAPIConfig,
options: IAPIInput,
triggerImmediately: boolean = false,
cancel?: boolean,
cancel?: boolean
): IAPIResponse<Data> => {
const [success, setSuccess] = useState<boolean | undefined>(undefined);
const [code, setCode] = useState<string | undefined>(undefined);
Expand Down
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_GEMINI:
return `${AICH_URI}/api/v1/gemini/upload`;
case AICH_APIS_TYPES.GET_GEMINI_RESULT_ID:
if (!aichResultId) {
throw new Error('AICH Result ID is required');
}
return `${AICH_URI}/api/v1/gemini/${aichResultId}/process_status`;
case AICH_APIS_TYPES.GET_GEMINI_RESULT:
if (!aichResultId) {
throw new Error('AICH Result ID is required');
}
return `${AICH_URI}/api/v1/gemini/${aichResultId}/result`;
default:
throw new Error('Invalid AICH API Type');
}
Expand Down
24 changes: 24 additions & 0 deletions 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
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/gemini/${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_GEMINI_RESULT, resultId);
response = await fetch(fetchURL);
} catch (error) {
throw new Error(STATUS_MESSAGE.INTERNAL_SERVICE_ERROR_AICH_FAILED);
}
Expand Down
56 changes: 43 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 Down Expand Up @@ -123,7 +124,7 @@ describe('POST OCR', () => {
expect(promiseJson).toBeInstanceOf(Promise);

expect(global.fetch).toHaveBeenCalledWith(
expect.stringContaining('/ocr/upload'),
expect.stringContaining('/gemini/upload'),
expect.objectContaining({ method: 'POST', body: expect.any(FormData) })
);
});
Expand Down Expand Up @@ -175,13 +176,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 +208,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 +221,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 +235,7 @@ describe('POST OCR', () => {
expect(resultJson).toEqual(resultJsonArrayExpect);

expect(global.fetch).toHaveBeenCalledWith(
expect.stringContaining('/ocr/upload'),
expect.stringContaining('/gemini/upload'),
expect.objectContaining({ method: 'POST', body: expect.any(FormData) })
);
});
Expand Down Expand Up @@ -271,7 +279,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 +293,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 +327,8 @@ describe('POST OCR', () => {
imageName: 'testImageName',
imageSize: 1024,
type: 'invoice',
uploadIdentifier: 'test',
createAt: 0,
},
];

Expand All @@ -323,11 +346,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
Loading