Skip to content

Commit

Permalink
voucher unify input check
Browse files Browse the repository at this point in the history
  • Loading branch information
TinyMurky committed Sep 11, 2024
1 parent ee8a01c commit ae82064
Show file tree
Hide file tree
Showing 6 changed files with 91 additions and 119 deletions.
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.1+13",
"version": "0.8.1+14",
"private": false,
"scripts": {
"dev": "next dev",
Expand Down
3 changes: 3 additions & 0 deletions src/constants/zod_schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
ocrResultGetByIdValidator,
ocrUploadValidator,
} from '@/lib/utils/zod_schema/ocr';
import { voucherCreateValidator, voucherUpdateValidator } from '@/lib/utils/zod_schema/voucher';
import { zodExampleValidator } from '@/lib/utils/zod_schema/zod_example';

/*
Expand All @@ -32,4 +33,6 @@ export const API_ZOD_SCHEMA = {
[APIName.INVOICE_CREATE]: invoiceCreateValidator,
[APIName.INVOICE_UPDATE]: invoiceUpdateValidator,
[APIName.INVOICE_GET_BY_ID]: invoiceGetByIdValidator,
[APIName.VOUCHER_CREATE]: voucherCreateValidator,
[APIName.VOUCHER_UPDATE]: voucherUpdateValidator,
};
41 changes: 41 additions & 0 deletions src/lib/utils/zod_schema/voucher.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { IZodValidator } from '@/interfaces/zod_validator';
import { z } from 'zod';

const lineItemZod = z.object({
lineItemIndex: z.string(),
account: z.string(),
description: z.string(),
debit: z.boolean(),
amount: z.number(),
accountId: z.number(),
});

const voucherZod = z.object({
journalId: z.number(),
lineItems: z.array(lineItemZod),
});

const voucherCreateQueryValidator = z.object({});
const voucherCreateBodyValidator = z.object({
voucher: voucherZod,
});

export const voucherCreateValidator: IZodValidator<
(typeof voucherCreateQueryValidator)['shape'],
(typeof voucherCreateBodyValidator)['shape']
> = {
query: voucherCreateQueryValidator,
body: voucherCreateBodyValidator,
};

const voucherUpdateQueryValidator = z.object({
voucherId: z.string().regex(/^\d+$/).transform(Number),
});

export const voucherUpdateValidator: IZodValidator<
(typeof voucherUpdateQueryValidator)['shape'],
(typeof voucherCreateBodyValidator)['shape']
> = {
query: voucherUpdateQueryValidator,
body: voucherCreateBodyValidator,
};
85 changes: 27 additions & 58 deletions src/pages/api/v1/company/[companyId]/voucher/[voucherId]/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { IVoucherDataForAPIResponse, IVoucherDataForSavingToDB } from '@/interfa
import { NextApiRequest, NextApiResponse } from 'next';
import { STATUS_MESSAGE } from '@/constants/status_code';
import { formatApiResponse } from '@/lib/utils/common';
import { isIVoucherDataForSavingToDB } from '@/lib/utils/type_guard/voucher';
import { getSession } from '@/lib/utils/session';
import {
updateVoucherByJournalIdInPrisma,
Expand All @@ -13,46 +12,11 @@ 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';
import { validateRequest } from '@/lib/utils/request_validator';
import { APIName } from '@/constants/api_connection';

type ApiResponseType = IVoucherDataForAPIResponse | null;

function isVoucherValid(
voucher: IVoucherDataForSavingToDB
): voucher is IVoucherDataForSavingToDB & { journalId: number } {
if (
!voucher ||
!isIVoucherDataForSavingToDB(voucher) ||
!voucher.journalId ||
typeof voucher.journalId !== 'number'
) {
return false;
}
return true;
}

// Info: (20240613 - Murky) Temporary not use
// function formatVoucherId(voucherId: unknown): number {
// let voucherIdInNumber = -1;
// if (typeof voucherId === 'string') {
// voucherIdInNumber = parseInt(voucherId, 10);
// }
// return voucherIdInNumber;
// }

function formatVoucherBody(voucher: IVoucherDataForSavingToDB) {
let voucherData: IVoucherDataForSavingToDB | null = null;
if (isVoucherValid(voucher)) {
voucherData = voucher;
}
return voucherData;
}

function formatPutBody(req: NextApiRequest) {
const { voucher } = req.body;
const voucherData = formatVoucherBody(voucher as IVoucherDataForSavingToDB);
return { voucherData };
}

async function handleVoucherUpdatePrismaLogic(
voucher: IVoucherDataForSavingToDB,
companyId: number
Expand Down Expand Up @@ -96,27 +60,25 @@ async function handleVoucherUpdatePrismaLogic(
};
}

async function handlePutRequest(companyId: number, req: NextApiRequest) {
async function handlePutRequest(
companyId: number,
voucher: IVoucherDataForSavingToDB & { journalId: number }
) {
// Info: (20240613 - Murky) Temporary not use
// const { voucherIdInNumber } = formatGetQuery(req);
const { voucherData } = formatPutBody(req);
let voucherUpdated: ApiResponseType = null;
let statusMessage: string = STATUS_MESSAGE.INTERNAL_SERVICE_ERROR;
if (voucherData) {
try {
const voucherUpdatedData = await handleVoucherUpdatePrismaLogic(voucherData, companyId);
voucherUpdated = voucherUpdatedData.voucherUpdated;
statusMessage = voucherUpdatedData.statusMessage;
} catch (error) {
const logError = loggerError(
0,
'handleVoucherUpdatePrismaLogic in handlePutRequest failed',
error as Error
);
logError.error(
'Prisma related func. in handlePutRequest in voucher/voucherId/index.ts failed'
);
}
try {
const voucherUpdatedData = await handleVoucherUpdatePrismaLogic(voucher, companyId);
voucherUpdated = voucherUpdatedData.voucherUpdated;
statusMessage = voucherUpdatedData.statusMessage;
} catch (error) {
const logError = loggerError(
0,
'handleVoucherUpdatePrismaLogic in handlePutRequest failed',
error as Error
);
logError.error('Prisma related func. in handlePutRequest in voucher/voucherId/index.ts failed');
}

return {
Expand All @@ -140,9 +102,16 @@ export default async function handler(
try {
switch (req.method) {
case 'PUT': {
const { voucherUpdated, statusMessage: message } = await handlePutRequest(companyId, req);
payload = voucherUpdated;
statusMessage = message;
const { body } = validateRequest(APIName.VOUCHER_UPDATE, req, userId);
if (body) {
const { voucher } = body;
const { voucherUpdated, statusMessage: message } = await handlePutRequest(
companyId,
voucher
);
payload = voucherUpdated;
statusMessage = message;
}
break;
}
default: {
Expand Down
54 changes: 0 additions & 54 deletions src/pages/api/v1/company/[companyId]/voucher/[voucherId]/status.ts

This file was deleted.

25 changes: 19 additions & 6 deletions src/pages/api/v1/company/[companyId]/voucher/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import { AuthFunctionsKeys } from '@/interfaces/auth';
import { IJournalFromPrismaIncludeInvoicePayment } from '@/interfaces/journal';
import { isVoucherAmountGreaterOrEqualThenPaymentAmount } from '@/lib/utils/voucher';
import { loggerError } from '@/lib/utils/logger_back';
import { validateRequest } from '@/lib/utils/request_validator';
import { APIName } from '@/constants/api_connection';

type ApiResponseType = IVoucherDataForAPIResponse | null;

Expand Down Expand Up @@ -96,9 +98,12 @@ function isVoucherValid(
return true;
}

export async function handlePostRequest(req: NextApiRequest, companyId: number) {
const { voucher } = req.body;

export async function handlePostRequest(
companyId: number,
voucher: IVoucherDataForSavingToDB & {
journalId: number;
}
) {
// Info: ( 20240522 - Murky)body need to provide LineItems and journalId
if (!isVoucherValid(voucher)) {
throw new Error(STATUS_MESSAGE.INVALID_INPUT_PARAMETER);
Expand All @@ -123,9 +128,17 @@ export default async function handler(
if (isAuth) {
try {
if (req.method === 'POST') {
const { updatedVoucher, statusMessage: message } = await handlePostRequest(req, companyId);
payload = updatedVoucher;
statusMessage = message;
const { body } = validateRequest(APIName.VOUCHER_CREATE, req, userId);

if (body) {
const { voucher } = body;
const { updatedVoucher, statusMessage: message } = await handlePostRequest(
companyId,
voucher
);
payload = updatedVoucher;
statusMessage = message;
}
} else {
throw new Error(STATUS_MESSAGE.METHOD_NOT_ALLOWED);
}
Expand Down

0 comments on commit ae82064

Please sign in to comment.