This commit is contained in:
AdisakKanthawilang 2024-07-25 17:06:42 +07:00
parent 4b34fc20b8
commit 1c9cb7ea78
11 changed files with 741 additions and 122 deletions

View file

@ -52,6 +52,8 @@ import CallAPI from "../interfaces/call-api";
import { UseInterceptors } from "@nestjs/common"; import { UseInterceptors } from "@nestjs/common";
import { FileInterceptor } from "@nestjs/platform-express"; import { FileInterceptor } from "@nestjs/platform-express";
import * as xlsx from "xlsx"; import * as xlsx from "xlsx";
import { addLogSequence, setLogDataDiff } from "../interfaces/utils";
import { RequestWithUser } from "../middlewares/user";
@Route("api/v1/development/main") @Route("api/v1/development/main")
@Tags("Development") @Tags("Development")
@ -91,7 +93,7 @@ export class DevelopmentController extends Controller {
@Post() @Post()
async CreateDevelopment( async CreateDevelopment(
@Body() requestBody: CreateDevelopment, @Body() requestBody: CreateDevelopment,
@Request() request: { user: Record<string, any> }, @Request() request: RequestWithUser,
) { ) {
const chk_name = await this.developmentRepository.find({ const chk_name = await this.developmentRepository.find({
where: { where: {
@ -141,8 +143,12 @@ export class DevelopmentController extends Controller {
development.createdFullName = request.user.name; development.createdFullName = request.user.name;
development.lastUpdateUserId = request.user.sub; development.lastUpdateUserId = request.user.sub;
development.lastUpdateFullName = request.user.name; development.lastUpdateFullName = request.user.name;
addLogSequence(request, {
await this.developmentRepository.save(development); action: "database",
status: "success",
description: "Store Development.",
});
await this.developmentRepository.save(development, { data: request });
return new HttpSuccess(development.id); return new HttpSuccess(development.id);
} }
@ -157,8 +163,13 @@ export class DevelopmentController extends Controller {
async UpdateDevelopmentTab1( async UpdateDevelopmentTab1(
@Path() id: string, @Path() id: string,
@Body() requestBody: UpdateDevelopment1, @Body() requestBody: UpdateDevelopment1,
@Request() request: { user: Record<string, any> }, @Request() request: RequestWithUser,
) { ) {
// addLogSequence(request, {
// action: "database",
// status: "success",
// description: "Get Development.",
// });
const development = await this.developmentRepository.findOne({ const development = await this.developmentRepository.findOne({
where: { id }, where: { id },
}); });
@ -182,6 +193,7 @@ export class DevelopmentController extends Controller {
" มีอยู่ในระบบแล้ว", " มีอยู่ในระบบแล้ว",
); );
} }
const before = structuredClone(development);
Object.assign(development, requestBody); Object.assign(development, requestBody);
await new CallAPI() await new CallAPI()
.PostData(request, "/org/find/all", { .PostData(request, "/org/find/all", {
@ -255,7 +267,13 @@ export class DevelopmentController extends Controller {
default: default:
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลโครงการ/หลักสูตรการฝึกอบรม"); throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลโครงการ/หลักสูตรการฝึกอบรม");
} }
await this.developmentRepository.save(development); addLogSequence(request, {
action: "database",
status: "success",
description: "Store Development.",
});
await this.developmentRepository.save(development, { data: request });
setLogDataDiff(request, { before, after: development });
return new HttpSuccess(development.id); return new HttpSuccess(development.id);
} }
@ -270,8 +288,13 @@ export class DevelopmentController extends Controller {
async CreateDevelopmenttab2_1( async CreateDevelopmenttab2_1(
@Path() id: string, @Path() id: string,
@Body() requestBody: CreatePlannedGoal, @Body() requestBody: CreatePlannedGoal,
@Request() request: { user: Record<string, any> }, @Request() request: RequestWithUser,
) { ) {
// addLogSequence(request, {
// action: "database",
// status: "success",
// description: "Get Development.",
// });
const development = await this.developmentRepository.findOne({ const development = await this.developmentRepository.findOne({
where: { id }, where: { id },
}); });
@ -284,7 +307,12 @@ export class DevelopmentController extends Controller {
data.lastUpdateUserId = request.user.sub; data.lastUpdateUserId = request.user.sub;
data.lastUpdateFullName = request.user.name; data.lastUpdateFullName = request.user.name;
data.developmentPlannedGoalId = development.id; data.developmentPlannedGoalId = development.id;
await this.plannedGoalRepository.save(data); addLogSequence(request, {
action: "database",
status: "success",
description: "Store Development.",
});
await this.plannedGoalRepository.save(data, { data: request });
await Promise.all( await Promise.all(
requestBody.positions.map(async (x) => { requestBody.positions.map(async (x) => {
@ -305,12 +333,19 @@ export class DevelopmentController extends Controller {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลระดับตำแหน่ง"); throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลระดับตำแหน่ง");
} }
} }
const before = structuredClone(development);
_data.createdUserId = request.user.sub; _data.createdUserId = request.user.sub;
_data.createdFullName = request.user.name; _data.createdFullName = request.user.name;
_data.lastUpdateUserId = request.user.sub; _data.lastUpdateUserId = request.user.sub;
_data.lastUpdateFullName = request.user.name; _data.lastUpdateFullName = request.user.name;
_data.plannedGoalId = data.id; _data.plannedGoalId = data.id;
await this.plannedGoalPositionRepository.save(_data); addLogSequence(request, {
action: "database",
status: "success",
description: "Store Development.",
});
await this.plannedGoalPositionRepository.save(_data, { data: request });
setLogDataDiff(request, { before, after: development });
}), }),
); );
return new HttpSuccess(data.id); return new HttpSuccess(data.id);
@ -327,21 +362,33 @@ export class DevelopmentController extends Controller {
async CreateDevelopmenttab2_2( async CreateDevelopmenttab2_2(
@Path() id: string, @Path() id: string,
@Body() requestBody: CreatePlannedPeople, @Body() requestBody: CreatePlannedPeople,
@Request() request: { user: Record<string, any> }, @Request() request: RequestWithUser,
) { ) {
// addLogSequence(request, {
// action: "database",
// status: "success",
// description: "Get Development.",
// });
const development = await this.developmentRepository.findOne({ const development = await this.developmentRepository.findOne({
where: { id }, where: { id },
}); });
if (!development) { if (!development) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลโครงการ/หลักสูตรการฝึกอบรมนี้"); throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลโครงการ/หลักสูตรการฝึกอบรมนี้");
} }
const before = structuredClone(development);
const data = Object.assign(new PlannedPeople(), requestBody); const data = Object.assign(new PlannedPeople(), requestBody);
data.createdUserId = request.user.sub; data.createdUserId = request.user.sub;
data.createdFullName = request.user.name; data.createdFullName = request.user.name;
data.lastUpdateUserId = request.user.sub; data.lastUpdateUserId = request.user.sub;
data.lastUpdateFullName = request.user.name; data.lastUpdateFullName = request.user.name;
data.developmentPlannedPeopleId = development.id; data.developmentPlannedPeopleId = development.id;
await this.plannedPeopleRepository.save(data); addLogSequence(request, {
action: "database",
status: "success",
description: "Store Development.",
});
await this.plannedPeopleRepository.save(data, { data: request });
setLogDataDiff(request, { before, after: development });
return new HttpSuccess(data.id); return new HttpSuccess(data.id);
} }
@ -356,8 +403,13 @@ export class DevelopmentController extends Controller {
async CreateDevelopmenttab2_3( async CreateDevelopmenttab2_3(
@Path() id: string, @Path() id: string,
@Body() requestBody: CreateActualGoal, @Body() requestBody: CreateActualGoal,
@Request() request: { user: Record<string, any> }, @Request() request: RequestWithUser,
) { ) {
// addLogSequence(request, {
// action: "database",
// status: "success",
// description: "Get Development.",
// });
const development = await this.developmentRepository.findOne({ const development = await this.developmentRepository.findOne({
where: { id }, where: { id },
}); });
@ -365,6 +417,11 @@ export class DevelopmentController extends Controller {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลโครงการ/หลักสูตรการฝึกอบรมนี้"); throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลโครงการ/หลักสูตรการฝึกอบรมนี้");
} }
if (requestBody.posTypeActualId != null) { if (requestBody.posTypeActualId != null) {
// addLogSequence(request, {
// action: "database",
// status: "success",
// description: "Get Position Type.",
// });
const checkId = await this.posTypeRepository.findOne({ const checkId = await this.posTypeRepository.findOne({
where: { id: requestBody.posTypeActualId }, where: { id: requestBody.posTypeActualId },
}); });
@ -373,6 +430,11 @@ export class DevelopmentController extends Controller {
} }
} }
if (requestBody.posLevelActualId != null) { if (requestBody.posLevelActualId != null) {
// addLogSequence(request, {
// action: "database",
// status: "success",
// description: "Get Position Level.",
// });
const checkId = await this.posLevelRepository.findOne({ const checkId = await this.posLevelRepository.findOne({
where: { id: requestBody.posLevelActualId }, where: { id: requestBody.posLevelActualId },
}); });
@ -380,13 +442,20 @@ export class DevelopmentController extends Controller {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลระดับตำแหน่ง"); throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลระดับตำแหน่ง");
} }
} }
const before = structuredClone(development);
const data = Object.assign(new ActualGoal(), requestBody); const data = Object.assign(new ActualGoal(), requestBody);
data.createdUserId = request.user.sub; data.createdUserId = request.user.sub;
data.createdFullName = request.user.name; data.createdFullName = request.user.name;
data.lastUpdateUserId = request.user.sub; data.lastUpdateUserId = request.user.sub;
data.lastUpdateFullName = request.user.name; data.lastUpdateFullName = request.user.name;
data.developmentActualGoalId = development.id; data.developmentActualGoalId = development.id;
await this.actualGoalRepository.save(data); addLogSequence(request, {
action: "database",
status: "success",
description: "Store ActualGoal.",
});
await this.actualGoalRepository.save(data, { data: request });
setLogDataDiff(request, { before, after: development });
return new HttpSuccess(data.id); return new HttpSuccess(data.id);
} }
@ -401,21 +470,33 @@ export class DevelopmentController extends Controller {
async CreateDevelopmenttab2_4( async CreateDevelopmenttab2_4(
@Path() id: string, @Path() id: string,
@Body() requestBody: CreateActualPeople, @Body() requestBody: CreateActualPeople,
@Request() request: { user: Record<string, any> }, @Request() request: RequestWithUser,
) { ) {
// addLogSequence(request, {
// action: "database",
// status: "success",
// description: "Get Development.",
// });
const development = await this.developmentRepository.findOne({ const development = await this.developmentRepository.findOne({
where: { id }, where: { id },
}); });
if (!development) { if (!development) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลโครงการ/หลักสูตรการฝึกอบรมนี้"); throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลโครงการ/หลักสูตรการฝึกอบรมนี้");
} }
const before = structuredClone(development);
const data = Object.assign(new ActualPeople(), requestBody); const data = Object.assign(new ActualPeople(), requestBody);
data.createdUserId = request.user.sub; data.createdUserId = request.user.sub;
data.createdFullName = request.user.name; data.createdFullName = request.user.name;
data.lastUpdateUserId = request.user.sub; data.lastUpdateUserId = request.user.sub;
data.lastUpdateFullName = request.user.name; data.lastUpdateFullName = request.user.name;
data.developmentActualPeopleId = development.id; data.developmentActualPeopleId = development.id;
await this.actualPeopleRepository.save(data); addLogSequence(request, {
action: "database",
status: "success",
description: "Store ActualPeople.",
});
await this.actualPeopleRepository.save(data, { data: request });
setLogDataDiff(request, { before, after: development });
return new HttpSuccess(data.id); return new HttpSuccess(data.id);
} }
@ -430,8 +511,13 @@ export class DevelopmentController extends Controller {
async UpdateDevelopmenttab2_1( async UpdateDevelopmenttab2_1(
@Path() id: string, @Path() id: string,
@Body() requestBody: CreatePlannedGoal, @Body() requestBody: CreatePlannedGoal,
@Request() request: { user: Record<string, any> }, @Request() request: RequestWithUser,
) { ) {
// addLogSequence(request, {
// action: "database",
// status: "success",
// description: "Get Development.",
// });
const development = await this.plannedGoalRepository.findOne({ const development = await this.plannedGoalRepository.findOne({
where: { id }, where: { id },
relations: { relations: {
@ -441,13 +527,25 @@ export class DevelopmentController extends Controller {
if (!development) { if (!development) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลโครงการ/หลักสูตรการฝึกอบรมนี้"); throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลโครงการ/หลักสูตรการฝึกอบรมนี้");
} }
const before = structuredClone(development);
await this.plannedGoalPositionRepository.remove(development.plannedGoalPositions); addLogSequence(request, {
action: "remove",
status: "success",
description: "Remove data in the field on the PlannedGoalPosition.",
});
await this.plannedGoalPositionRepository.remove(development.plannedGoalPositions, {
data: request,
});
Object.assign(development, { ...requestBody, positions: [] }); Object.assign(development, { ...requestBody, positions: [] });
development.lastUpdateUserId = request.user.sub; development.lastUpdateUserId = request.user.sub;
development.lastUpdateFullName = request.user.name; development.lastUpdateFullName = request.user.name;
await this.plannedGoalRepository.save(development); addLogSequence(request, {
action: "database",
status: "success",
description: "Store PlannedGoal.",
});
await this.plannedGoalRepository.save(development, { data: request });
setLogDataDiff(request, { before, after: development });
if (requestBody.positions != null) { if (requestBody.positions != null) {
await Promise.all( await Promise.all(
requestBody.positions.map(async (x) => { requestBody.positions.map(async (x) => {
@ -473,7 +571,16 @@ export class DevelopmentController extends Controller {
_data.lastUpdateUserId = request.user.sub; _data.lastUpdateUserId = request.user.sub;
_data.lastUpdateFullName = request.user.name; _data.lastUpdateFullName = request.user.name;
_data.plannedGoalId = development.id; _data.plannedGoalId = development.id;
await this.plannedGoalPositionRepository.save(_data); addLogSequence(request, {
action: "database",
status: "success",
description: "Store Planned Goal Position.",
});
await this.plannedGoalPositionRepository.save(_data, {
data: {
request: request,
},
});
}), }),
); );
} }
@ -491,18 +598,30 @@ export class DevelopmentController extends Controller {
async UpdateDevelopmenttab2_2( async UpdateDevelopmenttab2_2(
@Path() id: string, @Path() id: string,
@Body() requestBody: CreatePlannedPeople, @Body() requestBody: CreatePlannedPeople,
@Request() request: { user: Record<string, any> }, @Request() request: RequestWithUser,
) { ) {
// addLogSequence(request, {
// action: "database",
// status: "success",
// description: "Get Development.",
// });
const development = await this.plannedPeopleRepository.findOne({ const development = await this.plannedPeopleRepository.findOne({
where: { id }, where: { id },
}); });
if (!development) { if (!development) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลโครงการ/หลักสูตรการฝึกอบรมนี้"); throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลโครงการ/หลักสูตรการฝึกอบรมนี้");
} }
const before = structuredClone(development);
Object.assign(development, requestBody); Object.assign(development, requestBody);
development.lastUpdateUserId = request.user.sub; development.lastUpdateUserId = request.user.sub;
development.lastUpdateFullName = request.user.name; development.lastUpdateFullName = request.user.name;
await this.plannedPeopleRepository.save(development); addLogSequence(request, {
action: "database",
status: "success",
description: "Store PlannedPeople.",
});
await this.plannedPeopleRepository.save(development, { data: request });
setLogDataDiff(request, { before, after: development });
return new HttpSuccess(development.id); return new HttpSuccess(development.id);
} }
@ -517,8 +636,13 @@ export class DevelopmentController extends Controller {
async UpdateDevelopmenttab2_3( async UpdateDevelopmenttab2_3(
@Path() id: string, @Path() id: string,
@Body() requestBody: CreateActualGoal, @Body() requestBody: CreateActualGoal,
@Request() request: { user: Record<string, any> }, @Request() request: RequestWithUser,
) { ) {
// addLogSequence(request, {
// action: "database",
// status: "success",
// description: "Get Development.",
// });
const development = await this.actualGoalRepository.findOne({ const development = await this.actualGoalRepository.findOne({
where: { id }, where: { id },
}); });
@ -526,6 +650,11 @@ export class DevelopmentController extends Controller {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลโครงการ/หลักสูตรการฝึกอบรมนี้"); throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลโครงการ/หลักสูตรการฝึกอบรมนี้");
} }
if (requestBody.posTypeActualId != null) { if (requestBody.posTypeActualId != null) {
// addLogSequence(request, {
// action: "database",
// status: "success",
// description: "Get Position Type.",
// });
const checkId = await this.posTypeRepository.findOne({ const checkId = await this.posTypeRepository.findOne({
where: { id: requestBody.posTypeActualId }, where: { id: requestBody.posTypeActualId },
}); });
@ -534,6 +663,11 @@ export class DevelopmentController extends Controller {
} }
} }
if (requestBody.posLevelActualId != null) { if (requestBody.posLevelActualId != null) {
// addLogSequence(request, {
// action: "database",
// status: "success",
// description: "Get Position Level.",
// });
const checkId = await this.posLevelRepository.findOne({ const checkId = await this.posLevelRepository.findOne({
where: { id: requestBody.posLevelActualId }, where: { id: requestBody.posLevelActualId },
}); });
@ -541,10 +675,17 @@ export class DevelopmentController extends Controller {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลระดับตำแหน่ง"); throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลระดับตำแหน่ง");
} }
} }
const before = structuredClone(development);
Object.assign(development, requestBody); Object.assign(development, requestBody);
development.lastUpdateUserId = request.user.sub; development.lastUpdateUserId = request.user.sub;
development.lastUpdateFullName = request.user.name; development.lastUpdateFullName = request.user.name;
await this.actualGoalRepository.save(development); addLogSequence(request, {
action: "database",
status: "success",
description: "Store ActualGoal.",
});
await this.actualGoalRepository.save(development, { data: request });
setLogDataDiff(request, { before, after: development });
return new HttpSuccess(development.id); return new HttpSuccess(development.id);
} }
@ -559,18 +700,30 @@ export class DevelopmentController extends Controller {
async UpdateDevelopmenttab2_4( async UpdateDevelopmenttab2_4(
@Path() id: string, @Path() id: string,
@Body() requestBody: CreateActualPeople, @Body() requestBody: CreateActualPeople,
@Request() request: { user: Record<string, any> }, @Request() request: RequestWithUser,
) { ) {
// addLogSequence(request, {
// action: "database",
// status: "success",
// description: "Get Development.",
// });
const development = await this.actualPeopleRepository.findOne({ const development = await this.actualPeopleRepository.findOne({
where: { id }, where: { id },
}); });
if (!development) { if (!development) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลโครงการ/หลักสูตรการฝึกอบรมนี้"); throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลโครงการ/หลักสูตรการฝึกอบรมนี้");
} }
const before = structuredClone(development);
Object.assign(development, requestBody); Object.assign(development, requestBody);
development.lastUpdateUserId = request.user.sub; development.lastUpdateUserId = request.user.sub;
development.lastUpdateFullName = request.user.name; development.lastUpdateFullName = request.user.name;
await this.actualPeopleRepository.save(development); addLogSequence(request, {
action: "database",
status: "success",
description: "Store ActualPeople.",
});
await this.actualPeopleRepository.save(development, { data: request });
setLogDataDiff(request, { before, after: development });
return new HttpSuccess(development.id); return new HttpSuccess(development.id);
} }
@ -582,7 +735,12 @@ export class DevelopmentController extends Controller {
* @param {string} id Id * @param {string} id Id
*/ */
@Delete("tab2_1/{id}") @Delete("tab2_1/{id}")
async DeleteDevelopmenttab2_1(@Path() id: string) { async DeleteDevelopmenttab2_1(@Path() id: string, @Request() request: RequestWithUser) {
// addLogSequence(request, {
// action: "database",
// status: "success",
// description: "Get Development.",
// });
const development = await this.plannedGoalRepository.findOne({ const development = await this.plannedGoalRepository.findOne({
where: { id }, where: { id },
}); });
@ -592,8 +750,18 @@ export class DevelopmentController extends Controller {
const _development = await this.plannedGoalPositionRepository.find({ const _development = await this.plannedGoalPositionRepository.find({
where: { plannedGoalId: id }, where: { plannedGoalId: id },
}); });
await this.plannedGoalPositionRepository.remove(_development); addLogSequence(request, {
await this.plannedGoalRepository.remove(development); action: "remove",
status: "success",
description: "Remove data in PlannedGoalPosition.",
});
await this.plannedGoalPositionRepository.remove(_development, { data: request });
addLogSequence(request, {
action: "remove",
status: "success",
description: "Remove data in PlannedGoal.",
});
await this.plannedGoalRepository.remove(development, { data: request });
return new HttpSuccess(development.id); return new HttpSuccess(development.id);
} }
@ -605,14 +773,24 @@ export class DevelopmentController extends Controller {
* @param {string} id Id * @param {string} id Id
*/ */
@Delete("tab2_2/{id}") @Delete("tab2_2/{id}")
async DeleteDevelopmenttab2_2(@Path() id: string) { async DeleteDevelopmenttab2_2(@Path() id: string, @Request() request: RequestWithUser) {
// addLogSequence(request, {
// action: "database",
// status: "success",
// description: "Get Development.",
// });
const development = await this.plannedPeopleRepository.findOne({ const development = await this.plannedPeopleRepository.findOne({
where: { id }, where: { id },
}); });
if (!development) { if (!development) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้เกี่ยวข้องเป้าหมายตามแผน"); throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้เกี่ยวข้องเป้าหมายตามแผน");
} }
await this.plannedPeopleRepository.remove(development); addLogSequence(request, {
action: "remove",
status: "success",
description: "Remove data in PlannedPeople.",
});
await this.plannedPeopleRepository.remove(development, { data: request });
return new HttpSuccess(development.id); return new HttpSuccess(development.id);
} }
@ -624,14 +802,24 @@ export class DevelopmentController extends Controller {
* @param {string} id Id * @param {string} id Id
*/ */
@Delete("tab2_3/{id}") @Delete("tab2_3/{id}")
async DeleteDevelopmenttab2_3(@Path() id: string) { async DeleteDevelopmenttab2_3(@Path() id: string, @Request() request: RequestWithUser) {
// addLogSequence(request, {
// action: "database",
// status: "success",
// description: "Get Development.",
// });
const development = await this.actualGoalRepository.findOne({ const development = await this.actualGoalRepository.findOne({
where: { id }, where: { id },
}); });
if (!development) { if (!development) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลกลุ่มเป้าหมายตามจริง"); throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลกลุ่มเป้าหมายตามจริง");
} }
await this.actualGoalRepository.remove(development); addLogSequence(request, {
action: "remove",
status: "success",
description: "Remove data in ActualGoal.",
});
await this.actualGoalRepository.remove(development, { data: request });
return new HttpSuccess(development.id); return new HttpSuccess(development.id);
} }
@ -643,14 +831,24 @@ export class DevelopmentController extends Controller {
* @param {string} id Id * @param {string} id Id
*/ */
@Delete("tab2_4/{id}") @Delete("tab2_4/{id}")
async DeleteDevelopmenttab2_4(@Path() id: string) { async DeleteDevelopmenttab2_4(@Path() id: string, @Request() request: RequestWithUser) {
// addLogSequence(request, {
// action: "database",
// status: "success",
// description: "Get Development.",
// });
const development = await this.actualPeopleRepository.findOne({ const development = await this.actualPeopleRepository.findOne({
where: { id }, where: { id },
}); });
if (!development) { if (!development) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้เกี่ยวข้องเป้าหมายตามจริง"); throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้เกี่ยวข้องเป้าหมายตามจริง");
} }
await this.actualPeopleRepository.remove(development); addLogSequence(request, {
action: "remove",
status: "success",
description: "Remove data in ActualPeople.",
});
await this.actualPeopleRepository.remove(development, { data: request });
return new HttpSuccess(development.id); return new HttpSuccess(development.id);
} }
@ -665,8 +863,13 @@ export class DevelopmentController extends Controller {
async UpdateDevelopmentTab3( async UpdateDevelopmentTab3(
@Path() id: string, @Path() id: string,
@Body() requestBody: UpdateDevelopment3, @Body() requestBody: UpdateDevelopment3,
@Request() request: { user: Record<string, any> }, @Request() request: RequestWithUser,
) { ) {
// addLogSequence(request, {
// action: "database",
// status: "success",
// description: "Get Development.",
// });
const development = await this.developmentRepository.findOne({ const development = await this.developmentRepository.findOne({
where: { id }, where: { id },
relations: { relations: {
@ -686,13 +889,35 @@ export class DevelopmentController extends Controller {
}); });
development.lastUpdateUserId = request.user.sub; development.lastUpdateUserId = request.user.sub;
development.lastUpdateFullName = request.user.name; development.lastUpdateFullName = request.user.name;
addLogSequence(request, {
await this.developmentProjectTypeRepository.remove(development.developmentProjectTypes); action: "remove",
status: "success",
description: "Remove data in DevelopmentProjectType.",
});
await this.developmentProjectTypeRepository.remove(development.developmentProjectTypes, {
data: request,
});
addLogSequence(request, {
action: "remove",
status: "success",
description: "Remove data in DevelopmentProjectTechniquePlanned.",
});
await this.developmentProjectTechniquePlannedRepository.remove( await this.developmentProjectTechniquePlannedRepository.remove(
development.developmentProjectTechniquePlanneds, development.developmentProjectTechniquePlanneds,
{
data: request,
}
); );
addLogSequence(request, {
action: "remove",
status: "success",
description: "Remove data in DevelopmentProjectTechniqueActual.",
});
await this.developmentProjectTechniqueActualRepository.remove( await this.developmentProjectTechniqueActualRepository.remove(
development.developmentProjectTechniqueActuals, development.developmentProjectTechniqueActuals,
{
data: request,
}
); );
const _null: any = null; const _null: any = null;
if ( if (
@ -905,7 +1130,12 @@ export class DevelopmentController extends Controller {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลยุทธศาสตร์เป้าหมายตามจริง"); throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลยุทธศาสตร์เป้าหมายตามจริง");
} }
} }
await this.developmentRepository.save(development); addLogSequence(request, {
action: "database",
status: "success",
description: "Store Development.",
});
await this.developmentRepository.save(development, { data: request });
if (requestBody.developmentProjectTypes != null) { if (requestBody.developmentProjectTypes != null) {
await Promise.all( await Promise.all(
requestBody.developmentProjectTypes.map(async (x) => { requestBody.developmentProjectTypes.map(async (x) => {
@ -916,7 +1146,12 @@ export class DevelopmentController extends Controller {
data.lastUpdateUserId = request.user.sub; data.lastUpdateUserId = request.user.sub;
data.lastUpdateFullName = request.user.name; data.lastUpdateFullName = request.user.name;
data.developmentId = development.id; data.developmentId = development.id;
await this.developmentProjectTypeRepository.save(data); addLogSequence(request, {
action: "database",
status: "success",
description: "Store DevelopmentProjectType.",
});
await this.developmentProjectTypeRepository.save(data, { data: request });
}), }),
); );
} }
@ -930,7 +1165,12 @@ export class DevelopmentController extends Controller {
data.lastUpdateUserId = request.user.sub; data.lastUpdateUserId = request.user.sub;
data.lastUpdateFullName = request.user.name; data.lastUpdateFullName = request.user.name;
data.developmentId = development.id; data.developmentId = development.id;
await this.developmentProjectTechniquePlannedRepository.save(data); addLogSequence(request, {
action: "database",
status: "success",
description: "Store DevelopmentProjectTechniquePlanned.",
});
await this.developmentProjectTechniquePlannedRepository.save(data, { data: request });
}), }),
); );
} }
@ -944,7 +1184,12 @@ export class DevelopmentController extends Controller {
data.lastUpdateUserId = request.user.sub; data.lastUpdateUserId = request.user.sub;
data.lastUpdateFullName = request.user.name; data.lastUpdateFullName = request.user.name;
data.developmentId = development.id; data.developmentId = development.id;
await this.developmentProjectTechniqueActualRepository.save(data); addLogSequence(request, {
action: "database",
status: "success",
description: "Store DevelopmentProjectTechniqueActual.",
});
await this.developmentProjectTechniqueActualRepository.save(data, { data: request });
}), }),
); );
} }
@ -962,18 +1207,30 @@ export class DevelopmentController extends Controller {
async UpdateDevelopmentTab4( async UpdateDevelopmentTab4(
@Path() id: string, @Path() id: string,
@Body() requestBody: UpdateDevelopment4, @Body() requestBody: UpdateDevelopment4,
@Request() request: { user: Record<string, any> }, @Request() request: RequestWithUser,
) { ) {
// addLogSequence(request, {
// action: "database",
// status: "success",
// description: "Get Development.",
// });
const development = await this.developmentRepository.findOne({ const development = await this.developmentRepository.findOne({
where: { id }, where: { id },
}); });
if (!development) { if (!development) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลโครงการ/หลักสูตรการฝึกอบรมนี้"); throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลโครงการ/หลักสูตรการฝึกอบรมนี้");
} }
const before = structuredClone(development);
Object.assign(development, requestBody); Object.assign(development, requestBody);
development.lastUpdateUserId = request.user.sub; development.lastUpdateUserId = request.user.sub;
development.lastUpdateFullName = request.user.name; development.lastUpdateFullName = request.user.name;
await this.developmentRepository.save(development); addLogSequence(request, {
action: "database",
status: "success",
description: "Store Development.",
});
await this.developmentRepository.save(development, { data: request });
setLogDataDiff(request, { before, after: development });
return new HttpSuccess(development.id); return new HttpSuccess(development.id);
} }
@ -988,21 +1245,33 @@ export class DevelopmentController extends Controller {
async CreateDevelopmenttab4_1( async CreateDevelopmenttab4_1(
@Path() id: string, @Path() id: string,
@Body() requestBody: CreateDevelopmentEvaluation, @Body() requestBody: CreateDevelopmentEvaluation,
@Request() request: { user: Record<string, any> }, @Request() request: RequestWithUser,
) { ) {
// addLogSequence(request, {
// action: "database",
// status: "success",
// description: "Get Development.",
// });
const development = await this.developmentRepository.findOne({ const development = await this.developmentRepository.findOne({
where: { id }, where: { id },
}); });
if (!development) { if (!development) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลโครงการ/หลักสูตรการฝึกอบรมนี้"); throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลโครงการ/หลักสูตรการฝึกอบรมนี้");
} }
const before = structuredClone(development);
const data = Object.assign(new DevelopmentEvaluation(), requestBody); const data = Object.assign(new DevelopmentEvaluation(), requestBody);
data.createdUserId = request.user.sub; data.createdUserId = request.user.sub;
data.createdFullName = request.user.name; data.createdFullName = request.user.name;
data.lastUpdateUserId = request.user.sub; data.lastUpdateUserId = request.user.sub;
data.lastUpdateFullName = request.user.name; data.lastUpdateFullName = request.user.name;
data.developmentId = development.id; data.developmentId = development.id;
await this.developmentEvaluationRepository.save(data); addLogSequence(request, {
action: "database",
status: "success",
description: "Store DevelopmentEvaluation.",
});
await this.developmentEvaluationRepository.save(data, { data: request });
setLogDataDiff(request, { before, after: development });
return new HttpSuccess(data.id); return new HttpSuccess(data.id);
} }
@ -1014,14 +1283,24 @@ export class DevelopmentController extends Controller {
* @param {string} id Id * @param {string} id Id
*/ */
@Delete("tab4_1/{id}") @Delete("tab4_1/{id}")
async DeleteDevelopmenttab4_1(@Path() id: string) { async DeleteDevelopmenttab4_1(@Path() id: string, @Request() request: RequestWithUser) {
// addLogSequence(request, {
// action: "database",
// status: "success",
// description: "Get Development Evaluation By ID.",
// });
const development = await this.developmentEvaluationRepository.findOne({ const development = await this.developmentEvaluationRepository.findOne({
where: { id }, where: { id },
}); });
if (!development) { if (!development) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้เกี่ยวข้องเป้าหมายตามแผน"); throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผู้เกี่ยวข้องเป้าหมายตามแผน");
} }
await this.developmentEvaluationRepository.remove(development); addLogSequence(request, {
action: "remove",
status: "success",
description: "Remove Development Evaluation By ID.",
});
await this.developmentEvaluationRepository.remove(development, { data: request });
return new HttpSuccess(development.id); return new HttpSuccess(development.id);
} }
@ -1036,7 +1315,7 @@ export class DevelopmentController extends Controller {
async UpdateDevelopmenttab4_1( async UpdateDevelopmenttab4_1(
@Path() id: string, @Path() id: string,
@Body() requestBody: CreateDevelopmentEvaluation, @Body() requestBody: CreateDevelopmentEvaluation,
@Request() request: { user: Record<string, any> }, @Request() request: RequestWithUser,
) { ) {
const development = await this.developmentEvaluationRepository.findOne({ const development = await this.developmentEvaluationRepository.findOne({
where: { id }, where: { id },
@ -1047,7 +1326,7 @@ export class DevelopmentController extends Controller {
Object.assign(development, requestBody); Object.assign(development, requestBody);
development.lastUpdateUserId = request.user.sub; development.lastUpdateUserId = request.user.sub;
development.lastUpdateFullName = request.user.name; development.lastUpdateFullName = request.user.name;
await this.developmentEvaluationRepository.save(development); await this.developmentEvaluationRepository.save(development, { data: request });
return new HttpSuccess(development.id); return new HttpSuccess(development.id);
} }
@ -1062,7 +1341,7 @@ export class DevelopmentController extends Controller {
async UpdateDevelopmentTab5( async UpdateDevelopmentTab5(
@Path() id: string, @Path() id: string,
@Body() requestBody: UpdateDevelopment5, @Body() requestBody: UpdateDevelopment5,
@Request() request: { user: Record<string, any> }, @Request() request: RequestWithUser,
) { ) {
const development = await this.developmentRepository.findOne({ const development = await this.developmentRepository.findOne({
where: { id }, where: { id },
@ -1083,9 +1362,20 @@ export class DevelopmentController extends Controller {
Object.assign(development, { ...requestBody, developmentAddresss: [] }); Object.assign(development, { ...requestBody, developmentAddresss: [] });
development.lastUpdateUserId = request.user.sub; development.lastUpdateUserId = request.user.sub;
development.lastUpdateFullName = request.user.name; development.lastUpdateFullName = request.user.name;
await this.developmentRepository.save(development); addLogSequence(request, {
action: "database",
await this.developmentAddresssRepository.remove(development.developmentAddresss); status: "success",
description: "Store Development.",
});
await this.developmentRepository.save(development, { data: request });
addLogSequence(request, {
action: "remove",
status: "success",
description: "Remove DevelopmentAddresss.",
});
await this.developmentAddresssRepository.remove(development.developmentAddresss, {
data: request,
});
await Promise.all( await Promise.all(
requestBody.developmentAddresss.map(async (x) => { requestBody.developmentAddresss.map(async (x) => {
const data = Object.assign(new DevelopmentAddress(), x); const data = Object.assign(new DevelopmentAddress(), x);
@ -1100,7 +1390,12 @@ export class DevelopmentController extends Controller {
data.createdFullName = request.user.name; data.createdFullName = request.user.name;
data.lastUpdateUserId = request.user.sub; data.lastUpdateUserId = request.user.sub;
data.lastUpdateFullName = request.user.name; data.lastUpdateFullName = request.user.name;
await this.developmentAddresssRepository.save(data); addLogSequence(request, {
action: "database",
status: "success",
description: "Store DevelopmentAddresss.",
});
await this.developmentAddresssRepository.save(data, { data: request });
}), }),
); );
@ -1163,7 +1458,7 @@ export class DevelopmentController extends Controller {
* @param {string} id Id * @param {string} id Id
*/ */
@Delete("{id}") @Delete("{id}")
async DeleteDevelopment(@Path() id: string) { async DeleteDevelopment(@Path() id: string , @Request () request: RequestWithUser) {
const development = await this.developmentRepository.findOne({ const development = await this.developmentRepository.findOne({
where: { id }, where: { id },
relations: { relations: {
@ -1189,22 +1484,93 @@ export class DevelopmentController extends Controller {
const plannedGoalPosition = await this.plannedGoalPositionRepository.find({ const plannedGoalPosition = await this.plannedGoalPositionRepository.find({
where: { plannedGoalId: In(development.developmentPlannedGoals.map((x) => x.id)) }, where: { plannedGoalId: In(development.developmentPlannedGoals.map((x) => x.id)) },
}); });
await this.plannedGoalPositionRepository.remove(plannedGoalPosition); addLogSequence(request, {
action: "remove",
status: "success",
description: "Remove PlannedGoalPosition.",
});
await this.plannedGoalPositionRepository.remove(plannedGoalPosition, { data: request });
} }
await this.actualPeopleRepository.remove(development.developmentActualPeoples); addLogSequence(request, {
await this.plannedPeopleRepository.remove(development.developmentPlannedPeoples); action: "remove",
await this.actualGoalRepository.remove(development.developmentActualGoals); status: "success",
await this.plannedGoalRepository.remove(development.developmentPlannedGoals); description: "Remove ActualPeople.",
await this.developmentProjectTypeRepository.remove(development.developmentProjectTypes); });
await this.actualPeopleRepository.remove(development.developmentActualPeoples, {
data: request,
});
addLogSequence(request, {
action: "remove",
status: "success",
description: "Remove PlannedPeople.",
});
await this.plannedPeopleRepository.remove(development.developmentPlannedPeoples, {
data: request,
});
addLogSequence(request, {
action: "remove",
status: "success",
description: "Remove ActualGoal.",
});
await this.actualGoalRepository.remove(development.developmentActualGoals, { data: request });
addLogSequence(request, {
action: "remove",
status: "success",
description: "Remove PlannedGoal.",
});
await this.plannedGoalRepository.remove(development.developmentPlannedGoals, { data: request });
addLogSequence(request, {
action: "remove",
status: "success",
description: "Remove DevelopmentProjectType.",
});
await this.developmentProjectTypeRepository.remove(development.developmentProjectTypes, {
data: request,
});
addLogSequence(request, {
action: "remove",
status: "success",
description: "Remove DevelopmentProjectTechniquePlanned.",
});
await this.developmentProjectTechniquePlannedRepository.remove( await this.developmentProjectTechniquePlannedRepository.remove(
development.developmentProjectTechniquePlanneds, development.developmentProjectTechniquePlanneds,
{
data: request,
},
); );
addLogSequence(request, {
action: "remove",
status: "success",
description: "Remove DevelopmentProjectTechniqueActuals.",
});
await this.developmentProjectTechniqueActualRepository.remove( await this.developmentProjectTechniqueActualRepository.remove(
development.developmentProjectTechniqueActuals, development.developmentProjectTechniqueActuals,
{
data: request,
},
); );
await this.developmentEvaluationRepository.remove(development.developmentEvaluations); addLogSequence(request, {
await this.developmentAddresssRepository.remove(development.developmentAddresss); action: "remove",
await this.developmentRepository.remove(development); status: "success",
description: "Remove DevelopmentEvaluation.",
});
await this.developmentEvaluationRepository.remove(development.developmentEvaluations, {
data: request,
});
addLogSequence(request, {
action: "remove",
status: "success",
description: "Remove DevelopmentAddresss.",
});
await this.developmentAddresssRepository.remove(development.developmentAddresss, {
data: request,
});
addLogSequence(request, {
action: "remove",
status: "success",
description: "Remove Development.",
});
await this.developmentRepository.remove(development, { data: request });
return new HttpSuccess(); return new HttpSuccess();
} }
@ -1278,10 +1644,7 @@ export class DevelopmentController extends Controller {
* @param {string} id Id * @param {string} id Id
*/ */
@Get("finish/{id}") @Get("finish/{id}")
async FinishDevelopemtById( async FinishDevelopemtById(@Path() id: string, @Request() request: RequestWithUser) {
@Path() id: string,
@Request() request: { user: Record<string, any> },
) {
const getDevelopment = await this.developmentRepository.findOne({ const getDevelopment = await this.developmentRepository.findOne({
where: { id: id }, where: { id: id },
}); });
@ -1291,7 +1654,12 @@ export class DevelopmentController extends Controller {
getDevelopment.status = "FINISH"; getDevelopment.status = "FINISH";
getDevelopment.lastUpdateUserId = request.user.sub; getDevelopment.lastUpdateUserId = request.user.sub;
getDevelopment.lastUpdateFullName = request.user.name; getDevelopment.lastUpdateFullName = request.user.name;
await this.developmentRepository.save(getDevelopment); addLogSequence(request, {
action: "database",
status: "success",
description: "Store Development.",
});
await this.developmentRepository.save(getDevelopment, { data: request });
return new HttpSuccess(getDevelopment); return new HttpSuccess(getDevelopment);
} }
@ -1662,10 +2030,7 @@ export class DevelopmentController extends Controller {
* @param {string} id Id * @param {string} id Id
*/ */
@Get("tab6/done/{id}") @Get("tab6/done/{id}")
async GetDevelopemtTab6DoneById( async GetDevelopemtTab6DoneById(@Path() id: string, @Request() request: RequestWithUser) {
@Path() id: string,
@Request() request: { user: Record<string, any> },
) {
const getDevelopment = await this.developmentHistoryRepository.find({ const getDevelopment = await this.developmentHistoryRepository.find({
where: { developmentId: id, isDone: false }, where: { developmentId: id, isDone: false },
relations: ["development"], relations: ["development"],
@ -1721,7 +2086,12 @@ export class DevelopmentController extends Controller {
_data.lastUpdateUserId = request.user.sub; _data.lastUpdateUserId = request.user.sub;
_data.lastUpdateFullName = request.user.name; _data.lastUpdateFullName = request.user.name;
await this.developmentHistoryRepository.save(_data); addLogSequence(request, {
action: "database",
status: "success",
description: "Store DevelopmentHistory.",
});
await this.developmentHistoryRepository.save(_data, { data: request });
}), }),
); );
return new HttpSuccess(getDevelopment); return new HttpSuccess(getDevelopment);
@ -1734,7 +2104,7 @@ export class DevelopmentController extends Controller {
* *
*/ */
@Get("org/root") @Get("org/root")
async GetOrgDevelopemt(@Request() request: { user: Record<string, any> }) { async GetOrgDevelopemt() {
const getOrg = await this.developmentRepository const getOrg = await this.developmentRepository
.createQueryBuilder("development") .createQueryBuilder("development")
.select("development.root") .select("development.root")
@ -1759,7 +2129,7 @@ export class DevelopmentController extends Controller {
async UploadUserDevelopemtById( async UploadUserDevelopemtById(
@Path() id: string, @Path() id: string,
@UploadedFile() file: Express.Multer.File, @UploadedFile() file: Express.Multer.File,
@Request() request: { user: Record<string, any> }, @Request() request: RequestWithUser,
) { ) {
const getDevelopment = await this.developmentRepository.findOne({ const getDevelopment = await this.developmentRepository.findOne({
where: { id: id }, where: { id: id },
@ -1801,7 +2171,12 @@ export class DevelopmentController extends Controller {
oldProfile.createdFullName = request.user.name; oldProfile.createdFullName = request.user.name;
oldProfile.lastUpdateUserId = request.user.sub; oldProfile.lastUpdateUserId = request.user.sub;
oldProfile.lastUpdateFullName = request.user.name; oldProfile.lastUpdateFullName = request.user.name;
await this.developmentHistoryRepository.save(oldProfile); addLogSequence(request, {
action: "database",
status: "success",
description: "Store DevelopmentHistory.",
});
await this.developmentHistoryRepository.save(oldProfile, { data: request });
return; return;
} }
if (item["ประเภท"] == undefined) return; if (item["ประเภท"] == undefined) return;
@ -1833,7 +2208,12 @@ export class DevelopmentController extends Controller {
development.createdFullName = request.user.name; development.createdFullName = request.user.name;
development.lastUpdateUserId = request.user.sub; development.lastUpdateUserId = request.user.sub;
development.lastUpdateFullName = request.user.name; development.lastUpdateFullName = request.user.name;
await this.developmentHistoryRepository.save(development); addLogSequence(request, {
action: "database",
status: "success",
description: "Store DevelopmentHistory.",
});
await this.developmentHistoryRepository.save(development, { data: request });
}) })
.catch((x) => { .catch((x) => {
return; return;
@ -1866,7 +2246,12 @@ export class DevelopmentController extends Controller {
development.createdFullName = request.user.name; development.createdFullName = request.user.name;
development.lastUpdateUserId = request.user.sub; development.lastUpdateUserId = request.user.sub;
development.lastUpdateFullName = request.user.name; development.lastUpdateFullName = request.user.name;
await this.developmentHistoryRepository.save(development); addLogSequence(request, {
action: "database",
status: "success",
description: "Store DevelopmentHistory.",
});
await this.developmentHistoryRepository.save(development, { data: request });
}) })
.catch((x) => { .catch((x) => {
return; return;

View file

@ -25,6 +25,8 @@ import {
} from "../entities/DevelopmentHistory"; } from "../entities/DevelopmentHistory";
import { EmployeePosType } from "../entities/EmployeePosType"; import { EmployeePosType } from "../entities/EmployeePosType";
import { EmployeePosLevel } from "../entities/EmployeePosLevel"; import { EmployeePosLevel } from "../entities/EmployeePosLevel";
import { RequestWithUser } from "../middlewares/user";
import { addLogSequence } from "../interfaces/utils";
@Route("api/v1/development/history/employee") @Route("api/v1/development/history/employee")
@Tags("DevelopmentEmployeeHistory") @Tags("DevelopmentEmployeeHistory")
@ -72,7 +74,7 @@ export class DevelopmentEmployeeHistoryController extends Controller {
@Post() @Post()
async CreateDevelopmentHistory( async CreateDevelopmentHistory(
@Body() requestBody: CreateDevelopmentHistory, @Body() requestBody: CreateDevelopmentHistory,
@Request() request: { user: Record<string, any> }, @Request() request: RequestWithUser,
) { ) {
const type = "EMPLOYEE"; const type = "EMPLOYEE";
const chk_name = await this.developmentHistoryRepository.find({ const chk_name = await this.developmentHistoryRepository.find({
@ -119,7 +121,12 @@ export class DevelopmentEmployeeHistoryController extends Controller {
development.createdFullName = request.user.name; development.createdFullName = request.user.name;
development.lastUpdateUserId = request.user.sub; development.lastUpdateUserId = request.user.sub;
development.lastUpdateFullName = request.user.name; development.lastUpdateFullName = request.user.name;
await this.developmentHistoryRepository.save(development); addLogSequence(request, {
action: "database",
status: "success",
description: "Store DevelopmentHistory.",
});
await this.developmentHistoryRepository.save(development, { data: request });
return new HttpSuccess(development.id); return new HttpSuccess(development.id);
} }
@ -134,7 +141,7 @@ export class DevelopmentEmployeeHistoryController extends Controller {
async UpdateDevelopmentHistory( async UpdateDevelopmentHistory(
@Path() id: string, @Path() id: string,
@Body() requestBody: UpdateDevelopmentHistory, @Body() requestBody: UpdateDevelopmentHistory,
@Request() request: { user: Record<string, any> }, @Request() request: RequestWithUser,
) { ) {
const type = "EMPLOYEE"; const type = "EMPLOYEE";
const development = await this.developmentHistoryRepository.findOne({ const development = await this.developmentHistoryRepository.findOne({
@ -184,7 +191,12 @@ export class DevelopmentEmployeeHistoryController extends Controller {
development.posLevelId = null; development.posLevelId = null;
development.lastUpdateUserId = request.user.sub; development.lastUpdateUserId = request.user.sub;
development.lastUpdateFullName = request.user.name; development.lastUpdateFullName = request.user.name;
await this.developmentHistoryRepository.save(development); addLogSequence(request, {
action: "database",
status: "success",
description: "Store DevelopmentHistory.",
});
await this.developmentHistoryRepository.save(development, { data: request });
return new HttpSuccess(development.id); return new HttpSuccess(development.id);
} }
@ -196,7 +208,7 @@ export class DevelopmentEmployeeHistoryController extends Controller {
* @param {string} id Id * @param {string} id Id
*/ */
@Delete("{id}") @Delete("{id}")
async DeleteDevelopmentHistory(@Path() id: string) { async DeleteDevelopmentHistory(@Path() id: string,@Request () request: RequestWithUser) {
const type = "EMPLOYEE"; const type = "EMPLOYEE";
const development = await this.developmentHistoryRepository.findOne({ const development = await this.developmentHistoryRepository.findOne({
where: { id: id, type: type }, where: { id: id, type: type },
@ -204,8 +216,12 @@ export class DevelopmentEmployeeHistoryController extends Controller {
if (!development) { if (!development) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลประวัติการฝึกอบรม/ดูงานนี้"); throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลประวัติการฝึกอบรม/ดูงานนี้");
} }
addLogSequence(request, {
await this.developmentHistoryRepository.remove(development); action: "remove",
status: "success",
description: "Remove DevelopmentHistory.",
});
await this.developmentHistoryRepository.remove(development, { data: request });
return new HttpSuccess(); return new HttpSuccess();
} }

View file

@ -25,6 +25,8 @@ import {
} from "../entities/DevelopmentHistory"; } from "../entities/DevelopmentHistory";
import { PosType } from "../entities/PosType"; import { PosType } from "../entities/PosType";
import { PosLevel } from "../entities/PosLevel"; import { PosLevel } from "../entities/PosLevel";
import { RequestWithUser } from "../middlewares/user";
import { addLogSequence } from "../interfaces/utils";
@Route("api/v1/development/history/officer") @Route("api/v1/development/history/officer")
@Tags("DevelopmentOfficerHistory") @Tags("DevelopmentOfficerHistory")
@ -72,7 +74,7 @@ export class DevelopmentOfficerHistoryController extends Controller {
@Post() @Post()
async CreateDevelopmentHistory( async CreateDevelopmentHistory(
@Body() requestBody: CreateDevelopmentHistory, @Body() requestBody: CreateDevelopmentHistory,
@Request() request: { user: Record<string, any> }, @Request() request: RequestWithUser,
) { ) {
const type = "OFFICER"; const type = "OFFICER";
const chk_name = await this.developmentHistoryRepository.find({ const chk_name = await this.developmentHistoryRepository.find({
@ -115,7 +117,12 @@ export class DevelopmentOfficerHistoryController extends Controller {
development.createdFullName = request.user.name; development.createdFullName = request.user.name;
development.lastUpdateUserId = request.user.sub; development.lastUpdateUserId = request.user.sub;
development.lastUpdateFullName = request.user.name; development.lastUpdateFullName = request.user.name;
await this.developmentHistoryRepository.save(development); addLogSequence(request, {
action: "database",
status: "success",
description: "Store DevelopmentHistory.",
});
await this.developmentHistoryRepository.save(development, { data: request });
return new HttpSuccess(development.id); return new HttpSuccess(development.id);
} }
@ -130,7 +137,7 @@ export class DevelopmentOfficerHistoryController extends Controller {
async UpdateDevelopmentHistory( async UpdateDevelopmentHistory(
@Path() id: string, @Path() id: string,
@Body() requestBody: UpdateDevelopmentHistory, @Body() requestBody: UpdateDevelopmentHistory,
@Request() request: { user: Record<string, any> }, @Request() request: RequestWithUser,
) { ) {
const type = "OFFICER"; const type = "OFFICER";
const development = await this.developmentHistoryRepository.findOne({ const development = await this.developmentHistoryRepository.findOne({
@ -176,7 +183,12 @@ export class DevelopmentOfficerHistoryController extends Controller {
development.type = type; development.type = type;
development.lastUpdateUserId = request.user.sub; development.lastUpdateUserId = request.user.sub;
development.lastUpdateFullName = request.user.name; development.lastUpdateFullName = request.user.name;
await this.developmentHistoryRepository.save(development); addLogSequence(request, {
action: "database",
status: "success",
description: "Store DevelopmentHistory.",
});
await this.developmentHistoryRepository.save(development, { data: request });
return new HttpSuccess(development.id); return new HttpSuccess(development.id);
} }
@ -188,7 +200,7 @@ export class DevelopmentOfficerHistoryController extends Controller {
* @param {string} id Id * @param {string} id Id
*/ */
@Delete("{id}") @Delete("{id}")
async DeleteDevelopmentHistory(@Path() id: string) { async DeleteDevelopmentHistory(@Path() id: string, @Request() request: RequestWithUser) {
const type = "OFFICER"; const type = "OFFICER";
const development = await this.developmentHistoryRepository.findOne({ const development = await this.developmentHistoryRepository.findOne({
where: { id: id, type: type }, where: { id: id, type: type },
@ -196,8 +208,12 @@ export class DevelopmentOfficerHistoryController extends Controller {
if (!development) { if (!development) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลประวัติการฝึกอบรม/ดูงานนี้"); throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลประวัติการฝึกอบรม/ดูงานนี้");
} }
addLogSequence(request, {
await this.developmentHistoryRepository.remove(development); action: "database",
status: "success",
description: "Store DevelopmentHistory.",
});
await this.developmentHistoryRepository.remove(development, { data: request });
return new HttpSuccess(); return new HttpSuccess();
} }

View file

@ -26,6 +26,9 @@ import {
import { PosType } from "../entities/PosType"; import { PosType } from "../entities/PosType";
import { PosLevel } from "../entities/PosLevel"; import { PosLevel } from "../entities/PosLevel";
import CallAPI from "../interfaces/call-api"; import CallAPI from "../interfaces/call-api";
import { RequestWithUser } from "../middlewares/user";
import { addLogSequence, setLogDataDiff } from "../interfaces/utils";
import { request } from "axios";
@Route("api/v1/development/scholarship") @Route("api/v1/development/scholarship")
@Tags("DevelopmentScholarship") @Tags("DevelopmentScholarship")
@ -44,9 +47,14 @@ export class DevelopmentScholarshipController extends Controller {
@Post() @Post()
async CreateDevelopmentScholarship( async CreateDevelopmentScholarship(
@Body() requestBody: CreateDevelopmentScholarship, @Body() requestBody: CreateDevelopmentScholarship,
@Request() request: { user: Record<string, any> }, @Request() request: RequestWithUser,
) { ) {
if (requestBody.posTypeId != null) { if (requestBody.posTypeId != null) {
// addLogSequence(request, {
// action: "database",
// status: "success",
// description: "Get Position Type.",
// });
const checkId = await this.posTypeRepository.findOne({ const checkId = await this.posTypeRepository.findOne({
where: { id: requestBody.posTypeId }, where: { id: requestBody.posTypeId },
}); });
@ -55,6 +63,11 @@ export class DevelopmentScholarshipController extends Controller {
} }
} }
if (requestBody.posLevelId != null) { if (requestBody.posLevelId != null) {
// addLogSequence(request, {
// action: "database",
// status: "success",
// description: "Get Position Level.",
// });
const checkId = await this.posLevelRepository.findOne({ const checkId = await this.posLevelRepository.findOne({
where: { id: requestBody.posLevelId }, where: { id: requestBody.posLevelId },
}); });
@ -68,7 +81,12 @@ export class DevelopmentScholarshipController extends Controller {
development.createdFullName = request.user.name; development.createdFullName = request.user.name;
development.lastUpdateUserId = request.user.sub; development.lastUpdateUserId = request.user.sub;
development.lastUpdateFullName = request.user.name; development.lastUpdateFullName = request.user.name;
await this.developmentScholarshipRepository.save(development); addLogSequence(request, {
action: "database",
status: "success",
description: "Store Development Scholarship.",
});
await this.developmentScholarshipRepository.save(development, { data: request });
return new HttpSuccess(development.id); return new HttpSuccess(development.id);
} }
@ -83,8 +101,13 @@ export class DevelopmentScholarshipController extends Controller {
async UpdateDevelopmentScholarship( async UpdateDevelopmentScholarship(
@Path() id: string, @Path() id: string,
@Body() requestBody: UpdateDevelopmentScholarship, @Body() requestBody: UpdateDevelopmentScholarship,
@Request() request: { user: Record<string, any> }, @Request() request: RequestWithUser,
) { ) {
// addLogSequence(request, {
// action: "database",
// status: "success",
// description: "Get Development Scholarship.",
// });
const development = await this.developmentScholarshipRepository.findOne({ const development = await this.developmentScholarshipRepository.findOne({
where: { id: id }, where: { id: id },
}); });
@ -92,6 +115,11 @@ export class DevelopmentScholarshipController extends Controller {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลทุนการศึกษา/ฝึกอบรมนี้"); throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลทุนการศึกษา/ฝึกอบรมนี้");
} }
if (requestBody.posTypeId != null) { if (requestBody.posTypeId != null) {
// addLogSequence(request, {
// action: "database",
// status: "success",
// description: "Get Position Type.",
// });
const checkId = await this.posTypeRepository.findOne({ const checkId = await this.posTypeRepository.findOne({
where: { id: requestBody.posTypeId }, where: { id: requestBody.posTypeId },
}); });
@ -100,6 +128,11 @@ export class DevelopmentScholarshipController extends Controller {
} }
} }
if (requestBody.posLevelId != null) { if (requestBody.posLevelId != null) {
// addLogSequence(request, {
// action: "database",
// status: "success",
// description: "Get Position Level.",
// });
const checkId = await this.posLevelRepository.findOne({ const checkId = await this.posLevelRepository.findOne({
where: { id: requestBody.posLevelId }, where: { id: requestBody.posLevelId },
}); });
@ -107,10 +140,17 @@ export class DevelopmentScholarshipController extends Controller {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลระดับตำแหน่ง"); throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลระดับตำแหน่ง");
} }
} }
const before = structuredClone(development);
Object.assign(development, requestBody); Object.assign(development, requestBody);
development.lastUpdateUserId = request.user.sub; development.lastUpdateUserId = request.user.sub;
development.lastUpdateFullName = request.user.name; development.lastUpdateFullName = request.user.name;
await this.developmentScholarshipRepository.save(development); addLogSequence(request, {
action: "database",
status: "success",
description: "Store DevelopmentScholarship.",
});
await this.developmentScholarshipRepository.save(development, { data: request });
setLogDataDiff(request, { before, after: development });
return new HttpSuccess(development.id); return new HttpSuccess(development.id);
} }
@ -122,15 +162,24 @@ export class DevelopmentScholarshipController extends Controller {
* @param {string} id Id * @param {string} id Id
*/ */
@Delete("{id}") @Delete("{id}")
async DeleteDevelopmentScholarship(@Path() id: string) { async DeleteDevelopmentScholarship(@Path() id: string, @Request() request: RequestWithUser) {
// addLogSequence(request, {
// action: "database",
// status: "success",
// description: "Get Development Scholarship",
// });
const development = await this.developmentScholarshipRepository.findOne({ const development = await this.developmentScholarshipRepository.findOne({
where: { id: id }, where: { id: id },
}); });
if (!development) { if (!development) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลทุนการศึกษา/ฝึกอบรมนี้"); throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลทุนการศึกษา/ฝึกอบรมนี้");
} }
addLogSequence(request, {
await this.developmentScholarshipRepository.remove(development); action: "remove",
status: "success",
description: "Remove Development Scholarship By ID.",
});
await this.developmentScholarshipRepository.remove(development, { data: request });
return new HttpSuccess(); return new HttpSuccess();
} }
@ -422,19 +471,30 @@ export class DevelopmentScholarshipController extends Controller {
async UpdateDevelopemtScholarshipUserById( async UpdateDevelopemtScholarshipUserById(
@Path() id: string, @Path() id: string,
@Body() requestBody: UpdateDevelopmentScholarshipUser, @Body() requestBody: UpdateDevelopmentScholarshipUser,
@Request() request: { user: Record<string, any> }, @Request() request: RequestWithUser,
) { ) {
// addLogSequence(request, {
// action: "database",
// status: "success",
// description: "Get Development Scholarship.",
// });
const getDevelopment = await this.developmentScholarshipRepository.findOne({ const getDevelopment = await this.developmentScholarshipRepository.findOne({
where: { id: id }, where: { id: id },
}); });
if (!getDevelopment) { if (!getDevelopment) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลทุนการศึกษา/ฝึกอบรมนี้"); throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลทุนการศึกษา/ฝึกอบรมนี้");
} }
const before = structuredClone(getDevelopment);
Object.assign(getDevelopment, requestBody); Object.assign(getDevelopment, requestBody);
getDevelopment.lastUpdateUserId = request.user.sub; getDevelopment.lastUpdateUserId = request.user.sub;
getDevelopment.lastUpdateFullName = request.user.name; getDevelopment.lastUpdateFullName = request.user.name;
await this.developmentScholarshipRepository.save(getDevelopment); addLogSequence(request, {
action: "database",
status: "success",
description: "Store DevelopmentScholarship.",
});
await this.developmentScholarshipRepository.save(getDevelopment, { data: request });
setLogDataDiff(request, { before, after: getDevelopment });
return new HttpSuccess(getDevelopment.id); return new HttpSuccess(getDevelopment.id);
} }
@ -450,8 +510,13 @@ export class DevelopmentScholarshipController extends Controller {
async ChangeStatusDevelopemtScholarshipById( async ChangeStatusDevelopemtScholarshipById(
@Path() id: string, @Path() id: string,
@Path() status: string, @Path() status: string,
@Request() request: { user: Record<string, any> }, @Request() request: RequestWithUser,
) { ) {
// addLogSequence(request, {
// action: "database",
// status: "success",
// description: "Get Development Scholarship.",
// });
const getDevelopment = await this.developmentScholarshipRepository.findOne({ const getDevelopment = await this.developmentScholarshipRepository.findOne({
where: { id: id }, where: { id: id },
}); });
@ -465,6 +530,11 @@ export class DevelopmentScholarshipController extends Controller {
let scholarshipType = ""; let scholarshipType = "";
if (_status == "GRADUATE") { if (_status == "GRADUATE") {
if (getDevelopment.scholarshipType != null) { if (getDevelopment.scholarshipType != null) {
// addLogSequence(request, {
// action: "database",
// status: "success",
// description: "Change Status Development Scholarship.",
// });
switch (getDevelopment.scholarshipType.trim().toUpperCase()) { switch (getDevelopment.scholarshipType.trim().toUpperCase()) {
case "DOMESTICE": case "DOMESTICE":
scholarshipType = "การศึกษาในประเทศ"; scholarshipType = "การศึกษาในประเทศ";
@ -509,14 +579,19 @@ export class DevelopmentScholarshipController extends Controller {
positionPathId: null, positionPathId: null,
}) })
.then(async (x) => { .then(async (x) => {
await this.developmentScholarshipRepository.save(getDevelopment); await this.developmentScholarshipRepository.save(getDevelopment, { data: request });
}) })
.catch((error) => { .catch((error) => {
console.error("ไม่สามารถบันทึกลงทะเบียนประวัติได้"); console.error("ไม่สามารถบันทึกลงทะเบียนประวัติได้");
}); });
} else if (_status == "NOTGRADUATE") { } else if (_status == "NOTGRADUATE") {
getDevelopment.status = _status; getDevelopment.status = _status;
await this.developmentScholarshipRepository.save(getDevelopment); addLogSequence(request, {
action: "database",
status: "success",
description: "Change Status Development Scholarship.",
});
await this.developmentScholarshipRepository.save(getDevelopment, { data: request });
} else { } else {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบสถานะนี้ในระบบ"); throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบสถานะนี้ในระบบ");
} }

View file

@ -20,6 +20,7 @@ import HttpError from "../interfaces/http-error";
import { Not } from "typeorm"; import { Not } from "typeorm";
import { CreatePortfolio, Portfolio } from "../entities/Portfolio"; import { CreatePortfolio, Portfolio } from "../entities/Portfolio";
import { RequestWithUser } from "../middlewares/user"; import { RequestWithUser } from "../middlewares/user";
import { addLogSequence } from "../interfaces/utils";
@Route("api/v1/development/portfolio") @Route("api/v1/development/portfolio")
@Tags("Portfolio") @Tags("Portfolio")
@ -105,7 +106,12 @@ export class PortfolioController extends Controller {
_portfolio.createdFullName = request.user.name; _portfolio.createdFullName = request.user.name;
_portfolio.lastUpdateUserId = request.user.sub; _portfolio.lastUpdateUserId = request.user.sub;
_portfolio.lastUpdateFullName = request.user.name; _portfolio.lastUpdateFullName = request.user.name;
await this.portfolioRepository.save(_portfolio); addLogSequence(request, {
action: "database",
status: "success",
description: "Store Portfolio.",
});
await this.portfolioRepository.save(_portfolio, { data: request });
return new HttpSuccess(_portfolio.id); return new HttpSuccess(_portfolio.id);
} }
@ -137,7 +143,12 @@ export class PortfolioController extends Controller {
_portfolio.lastUpdateUserId = request.user.sub; _portfolio.lastUpdateUserId = request.user.sub;
_portfolio.lastUpdateFullName = request.user.name; _portfolio.lastUpdateFullName = request.user.name;
Object.assign(_portfolio, requestBody); Object.assign(_portfolio, requestBody);
await this.portfolioRepository.save(_portfolio); addLogSequence(request, {
action: "database",
status: "success",
description: "Store Portfolio.",
});
await this.portfolioRepository.save(_portfolio, { data: request });
return new HttpSuccess(_portfolio.id); return new HttpSuccess(_portfolio.id);
} }
@ -156,7 +167,12 @@ export class PortfolioController extends Controller {
if (!_delPortfolio) { if (!_delPortfolio) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผลงานนี้"); throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบข้อมูลผลงานนี้");
} }
await this.portfolioRepository.delete(_delPortfolio.id); addLogSequence(request, {
action: "database",
status: "success",
description: "Store Portfolio.",
});
await this.portfolioRepository.delete(_delPortfolio.id), { data: request };
return new HttpSuccess(); return new HttpSuccess();
} }
} }

View file

@ -42,6 +42,8 @@ import HttpError from "../interfaces/http-error";
import HttpStatus from "../interfaces/http-status"; import HttpStatus from "../interfaces/http-status";
import HttpSuccess from "../interfaces/http-success"; import HttpSuccess from "../interfaces/http-success";
import { Check } from "typeorm"; import { Check } from "typeorm";
import { addLogSequence } from "../interfaces/utils";
import { RequestWithUser } from "../middlewares/user";
@Route("api/v1/development/strategy") @Route("api/v1/development/strategy")
@Tags("Strategy") @Tags("Strategy")
@ -105,7 +107,7 @@ export class StrategyController extends Controller {
@Post() @Post()
public async newStrategyChild( public async newStrategyChild(
@Request() request: { user: Record<string, any> }, @Request() request: RequestWithUser,
@Body() @Body()
body: { body: {
name: string; name: string;
@ -202,15 +204,19 @@ export class StrategyController extends Controller {
strategyChild.createdFullName = request.user.name; strategyChild.createdFullName = request.user.name;
strategyChild.lastUpdateUserId = request.user.sub; strategyChild.lastUpdateUserId = request.user.sub;
strategyChild.lastUpdateFullName = request.user.name; strategyChild.lastUpdateFullName = request.user.name;
addLogSequence(request, {
await repoSave.save(strategyChild); action: "database",
status: "success",
description: "Store Strategy.",
});
await repoSave.save(strategyChild, { data: request });
return new HttpSuccess(strategyChild.id); return new HttpSuccess(strategyChild.id);
} }
@Patch() @Patch()
public async editStrategyChild1( public async editStrategyChild1(
@Request() request: { user: Record<string, any> }, @Request() request: RequestWithUser,
@Body() @Body()
body: { body: {
name: string; name: string;
@ -278,14 +284,19 @@ export class StrategyController extends Controller {
strategyChild.lastUpdateUserId = request.user.sub; strategyChild.lastUpdateUserId = request.user.sub;
strategyChild.lastUpdateFullName = request.user.name; strategyChild.lastUpdateFullName = request.user.name;
await strategyRepo.save(strategyChild); addLogSequence(request, {
action: "remove",
status: "success",
description: "Edit Strategy by ID.",
});
await strategyRepo.save(strategyChild, { data: request });
return new HttpSuccess(); return new HttpSuccess();
} }
@Delete() @Delete()
public async deleteStrategyChild( public async deleteStrategyChild(
@Request() request: { user: Record<string, any> }, @Request() request: RequestWithUser,
@Body() @Body()
body: { body: {
levelnode: number; levelnode: number;

View file

@ -1,6 +1,28 @@
import "dotenv/config"; import "dotenv/config";
import "reflect-metadata"; import "reflect-metadata";
import { DataSource } from "typeorm"; import { DataSource, LogLevel, LogMessage } from "typeorm";
import { Logger } from "typeorm";
import { QueryRunner } from "typeorm/browser";
import { RequestWithUser } from "../middlewares/user";
export class MyCustomLogger implements Logger {
log(level: "log" | "info" | "warn", message: any, queryRunner?: QueryRunner) {}
logQuery(query: string, parameters?: any[], queryRunner?: QueryRunner): void {
const req = queryRunner?.data as RequestWithUser | undefined;
const logData = req?.app?.locals.logData?.sequence.at(-1);
if (logData && !logData.query) logData.query = [];
if (logData) logData.query.push(
"Query: " + query + (parameters ? (" - Parameters:" + JSON.stringify(parameters)) : '')
);
}
logMigration(message: string, queryRunner?: QueryRunner) {}
logQueryError(error: string | Error, query: string, parameters?: any[], queryRunner?: QueryRunner) {}
logQuerySlow(time: number, query: string, parameters?: any[], queryRunner?: QueryRunner) {}
logSchemaBuild(message: string, queryRunner?: QueryRunner) {}
}
export const AppDataSource = new DataSource({ export const AppDataSource = new DataSource({
type: "mysql", type: "mysql",
@ -11,7 +33,7 @@ export const AppDataSource = new DataSource({
password: process.env.DB_PASSWORD, password: process.env.DB_PASSWORD,
connectorPackage: "mysql2", connectorPackage: "mysql2",
synchronize: false, synchronize: false,
logging: true, logging: ["query", "error"],
entities: entities:
process.env.NODE_ENV !== "production" process.env.NODE_ENV !== "production"
? ["src/entities/**/*.ts"] ? ["src/entities/**/*.ts"]
@ -21,7 +43,6 @@ export const AppDataSource = new DataSource({
? ["src/migration/**/*.ts"] ? ["src/migration/**/*.ts"]
: ["dist/migration/**/*{.ts,.js}"], : ["dist/migration/**/*{.ts,.js}"],
subscribers: [], subscribers: [],
logger: new MyCustomLogger(),
}); });
// console.log(AppDataSource);
// export default database;

View file

@ -12,6 +12,7 @@ import {
Path, Path,
} from "tsoa"; } from "tsoa";
import axios from "axios"; import axios from "axios";
import { addLogSequence } from "./utils";
class CallAPI { class CallAPI {
//Get //Get
@ -25,8 +26,26 @@ class CallAPI {
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
}); });
addLogSequence(request, {
action: "request",
status: "success",
description: JSON.stringify(response.data.result),
request: {
method: "GET",
url: url,
},
});
return response.data.result; return response.data.result;
} catch (error) { } catch (error) {
addLogSequence(request, {
action: "request",
status: "error",
description: JSON.stringify(error),
request: {
method: "GET",
url: url,
},
});
throw error; throw error;
} }
} }
@ -41,8 +60,26 @@ class CallAPI {
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
}); });
addLogSequence(request, {
action: "request",
status: "success",
description: JSON.stringify(response.data.result),
request: {
method: "POST",
url: url,
},
});
return response.data.result; return response.data.result;
} catch (error) { } catch (error) {
addLogSequence(request, {
action: "request",
status: "error",
description: JSON.stringify(error),
request: {
method: "POST",
url: url,
},
});
throw error; throw error;
} }
} }

35
src/interfaces/utils.ts Normal file
View file

@ -0,0 +1,35 @@
import { RequestWithUser } from "../middlewares/user";
export type DataDiff = {
before: any;
after: any;
};
export type LogSequence = {
action: string;
status: "success" | "error";
description: string;
query?: string;
request?: {
method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
url: string;
};
};
export function setLogDataDiff(req: RequestWithUser, data: DataDiff) {
req.app.locals.logData.dataDiff = {
before: JSON.stringify(data.before),
after: JSON.stringify(data.after),
};
}
export function addLogSequence(req: RequestWithUser, data: LogSequence) {
if (!req.app.locals.logData.sequence) {
req.app.locals.logData.sequence = [];
}
req.app.locals.logData.sequence = req.app.locals.logData.sequence.concat(data);
}
export function editLogSequence(req: RequestWithUser, index: number, data: LogSequence) {
req.app.locals.logData.sequence[index] = data;
}

View file

@ -4,6 +4,12 @@ import HttpStatus from "../interfaces/http-status";
import { ValidateError } from "tsoa"; import { ValidateError } from "tsoa";
function error(error: Error, _req: Request, res: Response, _next: NextFunction) { function error(error: Error, _req: Request, res: Response, _next: NextFunction) {
const logData = _req.app.locals.logData.sequence?.at(-1);
if (logData) {
logData.status = "error";
logData.description = error.message;
}
if (error instanceof HttpError) { if (error instanceof HttpError) {
return res.status(error.status).json({ return res.status(error.status).json({
status: error.status, status: error.status,

View file

@ -39,7 +39,7 @@ async function logMiddleware(req: Request, res: Response, next: NextFunction) {
res.on("finish", () => { res.on("finish", () => {
if (!req.url.startsWith("/api/")) return; if (!req.url.startsWith("/api/")) return;
const level = LOG_LEVEL_MAP[process.env.LOG_LEVEL ?? "info"] || 1; const level = LOG_LEVEL_MAP[process.env.LOG_LEVEL ?? "debug"] || 4;
if (level === 1 && res.statusCode < 500) return; if (level === 1 && res.statusCode < 500) return;
if (level === 2 && res.statusCode < 400) return; if (level === 2 && res.statusCode < 400) return;
@ -47,6 +47,7 @@ async function logMiddleware(req: Request, res: Response, next: NextFunction) {
const obj = { const obj = {
logType: res.statusCode >= 500 ? "error" : res.statusCode >= 400 ? "warning" : "info", logType: res.statusCode >= 500 ? "error" : res.statusCode >= 400 ? "warning" : "info",
ip: req.ip,
systemName: "development", systemName: "development",
startTimeStamp: timestamp, startTimeStamp: timestamp,
endTimeStamp: new Date().toISOString(), endTimeStamp: new Date().toISOString(),
@ -55,7 +56,7 @@ async function logMiddleware(req: Request, res: Response, next: NextFunction) {
method: req.method, method: req.method,
endpoint: req.url, endpoint: req.url,
responseCode: String(res.statusCode === 304 ? 200 : res.statusCode), responseCode: String(res.statusCode === 304 ? 200 : res.statusCode),
responseDescription: data?.code, responseDescription: data?.message,
input: (level === 4 && JSON.stringify(req.body, null, 2)) || undefined, input: (level === 4 && JSON.stringify(req.body, null, 2)) || undefined,
output: (level === 4 && JSON.stringify(data, null, 2)) || undefined, output: (level === 4 && JSON.stringify(data, null, 2)) || undefined,
...req.app.locals.logData, ...req.app.locals.logData,