hrms-api-org/src/controllers/ApiWebServiceController.ts

157 lines
4.9 KiB
TypeScript
Raw Normal View History

2025-08-07 13:05:58 +07:00
import {
Controller,
Post,
Route,
Security,
Tags,
Body,
Path,
Request,
Response,
Get,
Query,
} from "tsoa";
import { AppDataSource } from "../database/data-source";
import HttpSuccess from "../interfaces/http-success";
import HttpStatusCode from "../interfaces/http-status";
import HttpError from "../interfaces/http-error";
import { ApiName } from "../entities/ApiName";
import { Profile } from "../entities/Profile";
2025-08-08 09:26:48 +07:00
import { isPermissionRequest } from "../middlewares/authWebService";
import { RequestWithUserWebService } from "../middlewares/user";
2025-08-08 17:14:29 +07:00
import { OrgRevision } from "../entities/OrgRevision";
2025-08-07 13:05:58 +07:00
@Route("api/v2/org/api-service")
@Tags("ApiKey")
2025-08-08 09:26:48 +07:00
@Security("webServiceAuth")
2025-08-07 13:05:58 +07:00
@Response(
HttpStatusCode.INTERNAL_SERVER_ERROR,
"เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง",
)
export class ApiWebServiceController extends Controller {
private apiNameRepository = AppDataSource.getRepository(ApiName);
2025-08-08 17:14:29 +07:00
private orgRevisionRepository = AppDataSource.getRepository(OrgRevision);
2025-08-07 13:05:58 +07:00
/**
* list fields by systems
* @summary fields systems
*/
@Get("/:system/:code")
async listAttribute(
2025-08-08 09:26:48 +07:00
@Request() request: RequestWithUserWebService,
2025-08-07 13:05:58 +07:00
@Path("system") system: "registry" | "registry_emp" | "registry_temp" | "organization",
@Path("code") code: string,
@Query("page") page: number = 1,
@Query("pageSize") pageSize: number = 100,
): Promise<HttpSuccess | HttpError> {
2025-08-08 17:14:29 +07:00
const apiName = await this.apiNameRepository.findOne({
where: { code },
select: ["id", "code", "methodApi", "system", "isActive"],
relations: ["apiAttributes"],
order: {
apiAttributes: {
ordering: "ASC",
2025-08-07 13:05:58 +07:00
},
2025-08-08 17:14:29 +07:00
},
});
if (!apiName || apiName.system != system || !apiName.isActive || apiName.methodApi != "GET") {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบ API ที่ระบุ");
}
await isPermissionRequest(request, apiName.id);
const offset = (page - 1) * pageSize;
const propertyKey = apiName.apiAttributes.map((attr) => `${attr.tbName}.${attr.propertyKey}`);
2025-08-07 13:05:58 +07:00
2025-08-08 17:14:29 +07:00
let Main:string = ""
let condition: string = "1=1"
if (system == "registry") {
Main = "Profile"
}
else if (system == "registry_emp") {
Main = "ProfileEmployee"
condition = `ProfileEmployee.employeeClass = "PERM"`
}
else if (system == "registry_temp") {
Main = "ProfileEmployee"
condition = `ProfileEmployee.employeeClass = "TEMP"`
}
else {
Main = "OrgRoot"
const revision = await this.orgRevisionRepository.findOne({
select: ["id"],
where: { orgRevisionIsCurrent: true, orgRevisionIsDraft: false }
});
condition = `OrgRoot.orgRevisionId = '${revision?.id}'`
}
const repo = AppDataSource.getRepository(Main);
const metadata = repo.metadata;
const relationMap: Record<string, string> = {};
metadata.relations.forEach((rel) => {
relationMap[rel.inverseEntityMetadata.name] = rel.propertyName;
});
// ดึงเฉพาะตารางรอง (ถ้าเลือกไว้)
let propertyOtherKey:any[] = [];
propertyOtherKey = [
...new Set(
propertyKey
.map((x) => x.split(".")[0])
.filter((tb) => tb !== Main)
)
]
2025-08-07 13:05:58 +07:00
2025-08-08 17:14:29 +07:00
const queryBuilder = repo.createQueryBuilder(Main)
2025-08-07 13:05:58 +07:00
2025-08-08 17:14:29 +07:00
// join กับตารารอง
if (propertyOtherKey.length > 0) {
propertyOtherKey.forEach((tb) => {
const relationName = relationMap[tb];
if (relationName) {
queryBuilder.leftJoinAndSelect(`${Main}.${relationName}`, tb);
}
});
}
const [items, total] = await queryBuilder
.where(condition)
.orderBy(`${Main}.createdAt`, "DESC")
.skip(offset)
.take(pageSize)
.getManyAndCount();
const results = items.map(item => {
const result: any = {};
propertyKey.forEach(key => {
const [table, field] = key.split(".");
if (table === Main) {
result[field] = item[field];
}
else {
const relationName = relationMap[table];
if (!relationName) return;
if (!Array.isArray(result[relationName])) {
result[relationName] = item[relationName]
? item[relationName].map((relItem: any) => {
const filteredRel: any = {};
propertyKey
.filter(k => k.startsWith(`${table}.`))
.forEach(k => {
const [, relField] = k.split(".");
filteredRel[relField] = relItem[relField];
});
return filteredRel;
})
: [];
}
}
});
return result;
});
2025-08-07 13:05:58 +07:00
2025-08-08 17:14:29 +07:00
return new HttpSuccess({ items: results, total });
2025-08-07 13:05:58 +07:00
}
}