Merge branch 'main' of https://git.shiblysolution.id/SAUDE-TL/service-master-data
This commit is contained in:
124
seed/diagnoses/departments_67074.json
Normal file
124
seed/diagnoses/departments_67074.json
Normal file
@ -0,0 +1,124 @@
|
|||||||
|
{
|
||||||
|
"select * from public.departments d ": [
|
||||||
|
{
|
||||||
|
"id" : "a0d2ef11-6927-4e5c-8628-6acf26351071",
|
||||||
|
"name" : "Outpatient",
|
||||||
|
"status" : "N",
|
||||||
|
"created_at" : "2026-02-11T09:38:25.917Z",
|
||||||
|
"created_by" : "Admin",
|
||||||
|
"updated_at" : "2026-02-11T09:38:43.411Z",
|
||||||
|
"updated_by" : "Admin",
|
||||||
|
"deleted_at" : "2026-02-11T09:38:43.409Z",
|
||||||
|
"deleted_by" : "Admin"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id" : "e3800af3-45b0-46f3-ab42-c1466f0d0135",
|
||||||
|
"name" : "tes upd",
|
||||||
|
"status" : "N",
|
||||||
|
"created_at" : "2026-02-12T04:22:20.930Z",
|
||||||
|
"created_by" : "Admin",
|
||||||
|
"updated_at" : "2026-02-12T04:22:36.117Z",
|
||||||
|
"updated_by" : "Admin",
|
||||||
|
"deleted_at" : "2026-02-12T04:22:36.115Z",
|
||||||
|
"deleted_by" : "Admin"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id" : "00267fb8-6874-4027-bd13-cda005544aed",
|
||||||
|
"name" : "ICU",
|
||||||
|
"status" : "Y",
|
||||||
|
"created_at" : "2026-02-13T05:01:17.611Z",
|
||||||
|
"created_by" : "Admin",
|
||||||
|
"updated_at" : "2026-02-13T05:01:17.611Z",
|
||||||
|
"updated_by" : "Admin",
|
||||||
|
"deleted_at" : null,
|
||||||
|
"deleted_by" : null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id" : "7ebc5d8a-63f0-40f6-962b-59953ebd4ba0",
|
||||||
|
"name" : "Laboratory",
|
||||||
|
"status" : "Y",
|
||||||
|
"created_at" : "2026-02-19T05:33:22.276Z",
|
||||||
|
"created_by" : "Admin",
|
||||||
|
"updated_at" : "2026-02-19T05:33:22.276Z",
|
||||||
|
"updated_by" : "Admin",
|
||||||
|
"deleted_at" : null,
|
||||||
|
"deleted_by" : null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id" : "837768c7-4edb-4924-8ce4-5b535ef9e63a",
|
||||||
|
"name" : "Radiology",
|
||||||
|
"status" : "Y",
|
||||||
|
"created_at" : "2026-02-20T07:22:31.153Z",
|
||||||
|
"created_by" : "Admin",
|
||||||
|
"updated_at" : "2026-02-20T07:22:31.153Z",
|
||||||
|
"updated_by" : "Admin",
|
||||||
|
"deleted_at" : null,
|
||||||
|
"deleted_by" : null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id" : "3fc39ff1-b4bc-4276-92ef-def7ca9432fb",
|
||||||
|
"name" : "Inpatient",
|
||||||
|
"status" : "Y",
|
||||||
|
"created_at" : "2026-02-12T04:23:15.906Z",
|
||||||
|
"created_by" : "Admin",
|
||||||
|
"updated_at" : "2026-02-22T15:36:52.215Z",
|
||||||
|
"updated_by" : "Admin",
|
||||||
|
"deleted_at" : null,
|
||||||
|
"deleted_by" : null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id" : "42bc42a7-e2a7-4f95-a788-9d9e51a51a20",
|
||||||
|
"name" : "Outpatient",
|
||||||
|
"status" : "Y",
|
||||||
|
"created_at" : "2026-02-12T04:23:09.099Z",
|
||||||
|
"created_by" : "Admin",
|
||||||
|
"updated_at" : "2026-02-22T15:36:58.000Z",
|
||||||
|
"updated_by" : "Admin",
|
||||||
|
"deleted_at" : null,
|
||||||
|
"deleted_by" : null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id" : "71fa85fd-3dac-4acc-b8b5-b8e50092a289",
|
||||||
|
"name" : "Emergency",
|
||||||
|
"status" : "Y",
|
||||||
|
"created_at" : "2026-02-11T09:10:04.239Z",
|
||||||
|
"created_by" : "Admin",
|
||||||
|
"updated_at" : "2026-02-22T15:37:05.446Z",
|
||||||
|
"updated_by" : "Admin",
|
||||||
|
"deleted_at" : null,
|
||||||
|
"deleted_by" : null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id" : "079c06d5-f999-4830-8b38-acb76477d0ba",
|
||||||
|
"name" : "Hemodialysis",
|
||||||
|
"status" : "Y",
|
||||||
|
"created_at" : "2026-02-22T15:37:19.662Z",
|
||||||
|
"created_by" : "Admin",
|
||||||
|
"updated_at" : "2026-02-22T15:37:19.662Z",
|
||||||
|
"updated_by" : "Admin",
|
||||||
|
"deleted_at" : null,
|
||||||
|
"deleted_by" : null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id" : "81b710d9-6fe3-4dd0-9900-fae31ecadb6f",
|
||||||
|
"name" : "Pharmacy",
|
||||||
|
"status" : "Y",
|
||||||
|
"created_at" : "2026-03-16T07:24:05.901Z",
|
||||||
|
"created_by" : "Admin",
|
||||||
|
"updated_at" : "2026-04-15T02:37:55.829Z",
|
||||||
|
"updated_by" : "go",
|
||||||
|
"deleted_at" : null,
|
||||||
|
"deleted_by" : null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id" : "f6044bac-c829-4167-baba-72800167ef24",
|
||||||
|
"name" : "Cashier",
|
||||||
|
"status" : "Y",
|
||||||
|
"created_at" : "2026-04-15T06:25:47.582Z",
|
||||||
|
"created_by" : null,
|
||||||
|
"updated_at" : "2026-04-15T06:25:47.582Z",
|
||||||
|
"updated_by" : null,
|
||||||
|
"deleted_at" : null,
|
||||||
|
"deleted_by" : null
|
||||||
|
}
|
||||||
|
]}
|
||||||
@ -103,7 +103,7 @@ export class ExaminationDetailController {
|
|||||||
name: Joi.string().max(256).required().label("Name"),
|
name: Joi.string().max(256).required().label("Name"),
|
||||||
order_no: Joi.string().max(256).required().label("Order No."),
|
order_no: Joi.string().max(256).required().label("Order No."),
|
||||||
measurement_unit_id: Joi.string().uuid().required().label("Measurement Unit ID"),
|
measurement_unit_id: Joi.string().uuid().required().label("Measurement Unit ID"),
|
||||||
reference_range_id: Joi.string().uuid().required().label("Reference Range ID"),
|
reference_range_ids: Joi.array().items(Joi.string().uuid()).min(1).required().label("Reference Range IDs"),
|
||||||
status: Joi.string().required().label("Status"),
|
status: Joi.string().required().label("Status"),
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -112,17 +112,22 @@ export class ExaminationDetailController {
|
|||||||
let measurementUnit = await MeasurementUnitModel.list({ "MeasurementUnit.id": param.measurement_unit_id }).then((q) => q.getOne());
|
let measurementUnit = await MeasurementUnitModel.list({ "MeasurementUnit.id": param.measurement_unit_id }).then((q) => q.getOne());
|
||||||
if (!measurementUnit) throw { message: "Measurement Unit not found" };
|
if (!measurementUnit) throw { message: "Measurement Unit not found" };
|
||||||
|
|
||||||
let referenceRange = await ReferenceRangeModel.list({ "ReferenceRange.id": param.reference_range_id }).then((q) => q.getOne());
|
const referenceRanges = await Promise.all(
|
||||||
if (!referenceRange) throw { message: "Reference Range not found" };
|
param.reference_range_ids.map(async (id: string) => {
|
||||||
|
const rr = await ReferenceRangeModel.list({ "ReferenceRange.id": id }).then((q) => q.getOne());
|
||||||
|
if (!rr) throw { message: `Reference Range ${id} not found` };
|
||||||
|
return rr;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
let examinationDetail = new ExaminationDetail();
|
let examinationDetail = new ExaminationDetail();
|
||||||
examinationDetail.name = param.name;
|
examinationDetail.name = param.name;
|
||||||
examinationDetail.order_no = param.order_no;
|
examinationDetail.order_no = param.order_no;
|
||||||
examinationDetail.measurement_unit = measurementUnit;
|
examinationDetail.measurement_unit = measurementUnit;
|
||||||
examinationDetail.reference_range = referenceRange;
|
examinationDetail.reference_range = referenceRanges;
|
||||||
examinationDetail.status = param.status;
|
examinationDetail.status = param.status;
|
||||||
examinationDetail.created_by = req.auth.data.name;
|
examinationDetail.created_by = req.auth?.data.name;
|
||||||
examinationDetail.updated_by = req.auth.data.name;
|
examinationDetail.updated_by = req.auth?.data.name;
|
||||||
await queryRunner.manager.save(examinationDetail);
|
await queryRunner.manager.save(examinationDetail);
|
||||||
|
|
||||||
await queryRunner.commitTransaction();
|
await queryRunner.commitTransaction();
|
||||||
@ -181,7 +186,7 @@ export class ExaminationDetailController {
|
|||||||
name: Joi.string().max(256).required().label("Name"),
|
name: Joi.string().max(256).required().label("Name"),
|
||||||
order_no: Joi.string().max(256).required().label("Order No."),
|
order_no: Joi.string().max(256).required().label("Order No."),
|
||||||
measurement_unit_id: Joi.string().uuid().required().label("Measurement Unit ID"),
|
measurement_unit_id: Joi.string().uuid().required().label("Measurement Unit ID"),
|
||||||
reference_range_id: Joi.string().uuid().required().label("Reference Range ID"),
|
reference_range_ids: Joi.array().items(Joi.string().uuid()).min(1).required().label("Reference Range IDs"),
|
||||||
status: Joi.string().required().label("Status"),
|
status: Joi.string().required().label("Status"),
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -194,15 +199,20 @@ export class ExaminationDetailController {
|
|||||||
let measurementUnit = await MeasurementUnitModel.list({ "MeasurementUnit.id": param.measurement_unit_id }).then((q) => q.getOne());
|
let measurementUnit = await MeasurementUnitModel.list({ "MeasurementUnit.id": param.measurement_unit_id }).then((q) => q.getOne());
|
||||||
if (!measurementUnit) throw { message: "Measurement Unit not found" };
|
if (!measurementUnit) throw { message: "Measurement Unit not found" };
|
||||||
|
|
||||||
let referenceRange = await ReferenceRangeModel.list({ "ReferenceRange.id": param.reference_range_id }).then((q) => q.getOne());
|
const referenceRanges = await Promise.all(
|
||||||
if (!referenceRange) throw { message: "Reference Range not found" };
|
param.reference_range_ids.map(async (id: string) => {
|
||||||
|
const rr = await ReferenceRangeModel.list({ "ReferenceRange.id": id }).then((q) => q.getOne());
|
||||||
|
if (!rr) throw { message: `Reference Range ${id} not found` };
|
||||||
|
return rr;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
examinationDetail.name = param.name;
|
examinationDetail.name = param.name;
|
||||||
examinationDetail.order_no = param.order_no;
|
examinationDetail.order_no = param.order_no;
|
||||||
examinationDetail.measurement_unit = measurementUnit;
|
examinationDetail.measurement_unit = measurementUnit;
|
||||||
examinationDetail.reference_range = referenceRange;
|
examinationDetail.reference_range = referenceRanges;
|
||||||
examinationDetail.status = param.status;
|
examinationDetail.status = param.status;
|
||||||
examinationDetail.updated_by = req.auth.data.name;
|
examinationDetail.updated_by = req.auth?.data.name;
|
||||||
await queryRunner.manager.save(examinationDetail);
|
await queryRunner.manager.save(examinationDetail);
|
||||||
|
|
||||||
await queryRunner.commitTransaction();
|
await queryRunner.commitTransaction();
|
||||||
@ -239,7 +249,7 @@ export class ExaminationDetailController {
|
|||||||
|
|
||||||
if (!examinationDetail) throw { message: "Examination Detail " + Language.lang.failed_not_found };
|
if (!examinationDetail) throw { message: "Examination Detail " + Language.lang.failed_not_found };
|
||||||
|
|
||||||
examinationDetail.deleted_by = req.auth.data.name;
|
examinationDetail.deleted_by = req.auth?.data.name;
|
||||||
examinationDetail.deleted_at = moment().toDate();
|
examinationDetail.deleted_at = moment().toDate();
|
||||||
await OrmHelper.DB.manager.save(examinationDetail);
|
await OrmHelper.DB.manager.save(examinationDetail);
|
||||||
affected = 1;
|
affected = 1;
|
||||||
|
|||||||
@ -141,7 +141,7 @@ export class FareTypeController {
|
|||||||
// res_count.andWhere("munisipo.id = :munisipoId", { munisipoId: filterObj.munisipo_id });
|
// res_count.andWhere("munisipo.id = :munisipoId", { munisipoId: filterObj.munisipo_id });
|
||||||
// }
|
// }
|
||||||
|
|
||||||
const res_list = repo.createQueryBuilder("FareType");
|
const res_list = repo.createQueryBuilder("FareType").orderBy("FareType.name", "ASC");
|
||||||
|
|
||||||
// Handle foreign key filter with relation
|
// Handle foreign key filter with relation
|
||||||
// if (filterObj.munisipo_id) {
|
// if (filterObj.munisipo_id) {
|
||||||
|
|||||||
@ -83,7 +83,7 @@ export class ItemMasterController {
|
|||||||
"unit.large_unit",
|
"unit.large_unit",
|
||||||
"unit.small_unit",
|
"unit.small_unit",
|
||||||
"item_master.pack_size",
|
"item_master.pack_size",
|
||||||
]);
|
]).orderBy("item_master.item_name", "ASC");
|
||||||
|
|
||||||
const total_count_data = await query.getCount();
|
const total_count_data = await query.getCount();
|
||||||
const list_data = await query.getMany();
|
const list_data = await query.getMany();
|
||||||
|
|||||||
@ -79,7 +79,7 @@ export class ItemOriginController {
|
|||||||
query.select([
|
query.select([
|
||||||
"item_origin.id",
|
"item_origin.id",
|
||||||
"item_origin.origin_name",
|
"item_origin.origin_name",
|
||||||
]);
|
]).orderBy("item_origin.origin_name", "ASC");
|
||||||
|
|
||||||
const total_count_data = await query.getCount();
|
const total_count_data = await query.getCount();
|
||||||
const list_data = await query.getMany();
|
const list_data = await query.getMany();
|
||||||
|
|||||||
@ -79,7 +79,7 @@ export class SupplierController {
|
|||||||
query.select([
|
query.select([
|
||||||
"supplier.id",
|
"supplier.id",
|
||||||
"supplier.supplier_name",
|
"supplier.supplier_name",
|
||||||
]);
|
]).orderBy("supplier.supplier_name", "ASC");
|
||||||
|
|
||||||
const total_count_data = await query.getCount();
|
const total_count_data = await query.getCount();
|
||||||
const list_data = await query.getMany();
|
const list_data = await query.getMany();
|
||||||
|
|||||||
@ -77,7 +77,7 @@ export class RefferalHospitalController {
|
|||||||
var query = await RefferalHospitalModel.list();
|
var query = await RefferalHospitalModel.list();
|
||||||
|
|
||||||
const res_count = query;
|
const res_count = query;
|
||||||
const res_list = query.orderBy("refferal_hospital.created_at", "DESC");
|
const res_list = query.orderBy("refferal_hospital.refferal_hospital_name", "ASC");
|
||||||
|
|
||||||
const current_page = 1;
|
const current_page = 1;
|
||||||
const total_count_data = await res_count.getCount();
|
const total_count_data = await res_count.getCount();
|
||||||
|
|||||||
@ -15,7 +15,7 @@ const log: Logger<ILogObj> = new Logger({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const RegistrationFeeCreateAndUpdateSchema = {
|
const RegistrationFeeCreateAndUpdateSchema = {
|
||||||
service: Joi.array().items(Joi.string()).optional().label("Service"),
|
service: Joi.array().items(Joi.string().allow(null,"").uuid()).optional().label("Service"),
|
||||||
type: Joi.string().valid("emergency", "outpatient").required().label("Type"),
|
type: Joi.string().valid("emergency", "outpatient").required().label("Type"),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@ -15,6 +15,7 @@ import fileUpload from "express-fileupload";
|
|||||||
import { v4 as uuidv4 } from 'uuid';
|
import { v4 as uuidv4 } from 'uuid';
|
||||||
import fs from "fs";
|
import fs from "fs";
|
||||||
import path from "path";
|
import path from "path";
|
||||||
|
import { Brackets } from "typeorm";
|
||||||
|
|
||||||
const log: Logger<ILogObj> = new Logger({
|
const log: Logger<ILogObj> = new Logger({
|
||||||
name: "[RoomController]",
|
name: "[RoomController]",
|
||||||
@ -92,24 +93,60 @@ export class RoomController {
|
|||||||
/*
|
/*
|
||||||
#swagger.tags = ['Room']
|
#swagger.tags = ['Room']
|
||||||
#swagger.security = [{ "bearerAuth": [] }]
|
#swagger.security = [{ "bearerAuth": [] }]
|
||||||
|
#swagger.parameters['id'] = {
|
||||||
|
in: 'query',
|
||||||
|
type: 'string',
|
||||||
|
required: false,
|
||||||
|
description: 'Department Id (optional)'
|
||||||
|
}
|
||||||
*/
|
*/
|
||||||
try {
|
try {
|
||||||
|
const schema = Joi.object().keys({
|
||||||
|
id: Joi.string().uuid().optional().label("Department Id"),
|
||||||
|
});
|
||||||
|
|
||||||
|
let param: any = await schema.validateAsync(req.query);
|
||||||
|
|
||||||
const query = await RoomModel.list();
|
const query = await RoomModel.list();
|
||||||
|
|
||||||
query.select([
|
query
|
||||||
|
.select([
|
||||||
"Room.id",
|
"Room.id",
|
||||||
"Room.room",
|
"Room.room",
|
||||||
]);
|
])
|
||||||
|
.orderBy("Room.room", "ASC");
|
||||||
|
|
||||||
|
// ✅ optional filter by departmentId
|
||||||
|
if (param.id) {
|
||||||
|
query.andWhere("Room.departmentId = :departmentId", {
|
||||||
|
departmentId: param.id,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const total_count_data = await query.getCount();
|
const total_count_data = await query.getCount();
|
||||||
const list_data = await query.getMany();
|
const list_data = await query.getMany();
|
||||||
const count_data = CommonHelper.countObject(list_data);
|
const count_data = CommonHelper.countObject(list_data);
|
||||||
|
|
||||||
return ReturnHelper.successResponselist(res, 200, Language.lang.success_view, count_data, 1, total_count_data, list_data);
|
return ReturnHelper.successResponselist(
|
||||||
|
res,
|
||||||
|
200,
|
||||||
|
Language.lang.success_view,
|
||||||
|
count_data,
|
||||||
|
1,
|
||||||
|
total_count_data,
|
||||||
|
list_data
|
||||||
|
);
|
||||||
} catch (e: unknown) {
|
} catch (e: unknown) {
|
||||||
log.error(e);
|
log.error(e);
|
||||||
const err = e as Error;
|
const err = e as Error;
|
||||||
return ReturnHelper.errorResponse(res, 400, 401, Language.lang.failed_view, err.message);
|
|
||||||
|
return ReturnHelper.errorResponse(
|
||||||
|
res,
|
||||||
|
400,
|
||||||
|
401,
|
||||||
|
Language.lang.failed_view,
|
||||||
|
err.message
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -32,109 +32,189 @@ export class RoomToPharmacyController {
|
|||||||
limit: Joi.number().required().min(1).label("Limit"),
|
limit: Joi.number().required().min(1).label("Limit"),
|
||||||
with_deleted: Joi.bool().required().label("With Deleted"),
|
with_deleted: Joi.bool().required().label("With Deleted"),
|
||||||
order_field: Joi.string().required().label("Order Field"),
|
order_field: Joi.string().required().label("Order Field"),
|
||||||
order_direction: Joi.string().allow("asc", "desc").required().label("Order Direction"),
|
order_direction: Joi.string().allow("ASC", "DESC").required().label("Order Direction"),
|
||||||
});
|
});
|
||||||
|
const param: Paging = await schema.validateAsync(req.query);
|
||||||
|
|
||||||
let param: Paging = await schema.validateAsync(req.query);
|
const filter = param.filter && param.filter !== "" ? JSON.parse(param.filter) : {};
|
||||||
let filter = param.filter && param.filter !== "" ? JSON.parse(param.filter) : {};
|
const filterAny = filter.any && filter.any !== "" ? filter.any : "";
|
||||||
|
let filterObj = { ...filter } as any;
|
||||||
|
delete filterObj.any;
|
||||||
|
|
||||||
|
const query = await RoomToPharmacyModel.list(filterObj);
|
||||||
const offset = (param.page - 1) * param.limit;
|
const offset = (param.page - 1) * param.limit;
|
||||||
const limit = param.limit;
|
|
||||||
|
|
||||||
const roomQuery = OrmHelper.DB.getRepository(Room)
|
const res_count = query;
|
||||||
.createQueryBuilder("room")
|
const res_list = query
|
||||||
.leftJoinAndSelect("room.department", "department")
|
.leftJoinAndSelect("room_to_pharmacy.pharmacy_room", "emrregistration")
|
||||||
.leftJoinAndMapMany(
|
.leftJoinAndSelect("room_to_pharmacy.room", "room")
|
||||||
"room.roomToPharmacies",
|
.orderBy("room_to_pharmacy." + param.order_field, param.order_direction)
|
||||||
RoomToPharmacy,
|
.offset(offset)
|
||||||
"room_to_pharmacy",
|
.limit(param.limit);
|
||||||
"room_to_pharmacy.room_id = room.id"
|
|
||||||
)
|
|
||||||
.leftJoinAndMapOne(
|
|
||||||
"room_to_pharmacy.pharmacy_room",
|
|
||||||
Room,
|
|
||||||
"pharmacy_room",
|
|
||||||
"pharmacy_room.id = room_to_pharmacy.pharmacy_room_id"
|
|
||||||
)
|
|
||||||
.where("department.id IN (:...departmentIds)", {
|
|
||||||
departmentIds: [
|
|
||||||
'42bc42a7-e2a7-4f95-a788-9d9e51a51a20',
|
|
||||||
'3fc39ff1-b4bc-4276-92ef-def7ca9432fb',
|
|
||||||
'a0d2ef11-6927-4e5c-8628-6acf26351071',
|
|
||||||
]
|
|
||||||
})
|
|
||||||
.orderBy("room." + param.order_field, param.order_direction as "ASC" | "DESC");
|
|
||||||
|
|
||||||
if (param.with_deleted) {
|
if (param.with_deleted) {
|
||||||
roomQuery.withDeleted();
|
res_count.withDeleted();
|
||||||
|
res_list.withDeleted();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Filter tambahan jika ada
|
const current_page = param.page;
|
||||||
if (filter.room) {
|
const total_count_data = await res_count.getCount();
|
||||||
roomQuery.andWhere("room.room ILIKE :room", { room: `%${filter.room}%` });
|
const list_data = await res_list.getMany();
|
||||||
}
|
const count_data = CommonHelper.countObject(list_data);
|
||||||
if (filter.status) {
|
|
||||||
roomQuery.andWhere("room.status = :status", { status: filter.status });
|
|
||||||
}
|
|
||||||
|
|
||||||
const total_count_data = await roomQuery.clone().getCount();
|
return ReturnHelper.successResponselist(res, 200, Language.lang.success_view, count_data, current_page, total_count_data, list_data);
|
||||||
|
|
||||||
const rooms = await roomQuery
|
|
||||||
.offset(offset)
|
|
||||||
.limit(limit)
|
|
||||||
.getMany();
|
|
||||||
|
|
||||||
// Transform: { room_name: { pharmacy_room_1: {}, pharmacy_room_2: {} } }
|
|
||||||
const list_data_return = rooms.map((room: any) => {
|
|
||||||
const roomToPharmacies: any[] = room.roomToPharmacies ?? [];
|
|
||||||
|
|
||||||
const pharmacyRooms: Record<string, any> = {};
|
|
||||||
roomToPharmacies.forEach((rtp: any, index: number) => {
|
|
||||||
const pharmacy: Room | null = rtp.pharmacy_room ?? null;
|
|
||||||
pharmacyRooms[`pharmacy_room_${index + 1}`] = pharmacy ? {
|
|
||||||
id: pharmacy.id,
|
|
||||||
room: pharmacy.room,
|
|
||||||
code: pharmacy.code,
|
|
||||||
description: pharmacy.description ?? null,
|
|
||||||
status: pharmacy.status,
|
|
||||||
} : null;
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
rooms: {
|
|
||||||
id: room.id,
|
|
||||||
room: room.room,
|
|
||||||
code: room.code,
|
|
||||||
description: room.description ?? null,
|
|
||||||
status: room.status,
|
|
||||||
department: room.department ? {
|
|
||||||
id: room.department.id,
|
|
||||||
name: room.department.name,
|
|
||||||
} : null,
|
|
||||||
pharmacy_rooms: Object.keys(pharmacyRooms).length > 0
|
|
||||||
? pharmacyRooms
|
|
||||||
: null,
|
|
||||||
}
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
const count_data = CommonHelper.countObject(list_data_return);
|
|
||||||
|
|
||||||
return ReturnHelper.successResponselist(
|
|
||||||
res,
|
|
||||||
200,
|
|
||||||
Language.lang.success_view,
|
|
||||||
count_data,
|
|
||||||
param.page,
|
|
||||||
total_count_data,
|
|
||||||
list_data_return
|
|
||||||
);
|
|
||||||
} catch (e: unknown) {
|
} catch (e: unknown) {
|
||||||
log.error(e);
|
log.error(e);
|
||||||
const err = e as Error;
|
const err = e as Error;
|
||||||
return ReturnHelper.errorResponse(res, 400, 401, Language.lang.failed_view, err.message);
|
return ReturnHelper.errorResponse(res, 400, 401, Language.lang.failed_view, err.message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// static async list(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
|
||||||
|
// /*
|
||||||
|
// #swagger.tags = ['RoomToPharmacy']
|
||||||
|
// #swagger.security = [{ "bearerAuth": [] }]
|
||||||
|
// #swagger.parameters['filter'] = { description: '', in: 'query', type: 'string' }
|
||||||
|
// #swagger.parameters['limit'] = { in: 'query', required: true, type: 'number' }
|
||||||
|
// #swagger.parameters['page'] = { in: 'query', required: true, type: 'number' }
|
||||||
|
// #swagger.parameters['with_deleted'] = { in: 'query', required: true, type: 'boolean' }
|
||||||
|
// #swagger.parameters['order_field'] = { in: 'query', required: true, type: 'string' }
|
||||||
|
// #swagger.parameters['order_direction'] = { in: 'query', required: true, schema: { '@enum': ['ASC', 'DESC'] } }
|
||||||
|
// */
|
||||||
|
// try {
|
||||||
|
// const schema = Joi.object().keys({
|
||||||
|
// filter: Joi.string().allow("").optional().label("Filter"),
|
||||||
|
// page: Joi.number().required().min(1).label("Page"),
|
||||||
|
// limit: Joi.number().required().min(1).label("Limit"),
|
||||||
|
// with_deleted: Joi.bool().required().label("With Deleted"),
|
||||||
|
// order_field: Joi.string().required().label("Order Field"),
|
||||||
|
// order_direction: Joi.string().allow("asc", "desc").required().label("Order Direction"),
|
||||||
|
// });
|
||||||
|
|
||||||
|
// let param: Paging = await schema.validateAsync(req.query);
|
||||||
|
// let filter = param.filter && param.filter !== "" ? JSON.parse(param.filter) : {};
|
||||||
|
|
||||||
|
// const offset = (param.page - 1) * param.limit;
|
||||||
|
// const limit = param.limit;
|
||||||
|
|
||||||
|
// // const roomQuery = OrmHelper.DB.getRepository(Room)
|
||||||
|
// // .createQueryBuilder("room")
|
||||||
|
// // .leftJoinAndSelect("room.department", "department")
|
||||||
|
// // .leftJoinAndMapMany(
|
||||||
|
// // "room.roomToPharmacies",
|
||||||
|
// // RoomToPharmacy,
|
||||||
|
// // "room_to_pharmacy",
|
||||||
|
// // "room_to_pharmacy.room_id = room.id"
|
||||||
|
// // )
|
||||||
|
// // .leftJoinAndMapOne(
|
||||||
|
// // "room_to_pharmacy.pharmacy_room",
|
||||||
|
// // Room,
|
||||||
|
// // "pharmacy_room",
|
||||||
|
// // "pharmacy_room.id = room_to_pharmacy.pharmacy_room_id"
|
||||||
|
// // )
|
||||||
|
// // .where("department.id IN (:...departmentIds)", {
|
||||||
|
// // departmentIds: [
|
||||||
|
// // '42bc42a7-e2a7-4f95-a788-9d9e51a51a20',
|
||||||
|
// // '3fc39ff1-b4bc-4276-92ef-def7ca9432fb',
|
||||||
|
// // 'a0d2ef11-6927-4e5c-8628-6acf26351071',
|
||||||
|
// // ]
|
||||||
|
// // })
|
||||||
|
// // .orderBy("room." + param.order_field, param.order_direction as "ASC" | "DESC");
|
||||||
|
|
||||||
|
// const roomQuery = OrmHelper.DB.getRepository(Room)
|
||||||
|
// .createQueryBuilder("room")
|
||||||
|
// .leftJoinAndSelect("room.department", "department")
|
||||||
|
// .leftJoinAndSelect("room.roomToPharmacies", "room_to_pharmacy")
|
||||||
|
// // .leftJoinAndMapMany(
|
||||||
|
// // "room.roomToPharmacies",
|
||||||
|
// // RoomToPharmacy,
|
||||||
|
// // "room_to_pharmacy",
|
||||||
|
// // "room_to_pharmacy.room_id = room.id"
|
||||||
|
// // )
|
||||||
|
// // .leftJoinAndMapOne(
|
||||||
|
// // "room_to_pharmacy.pharmacy_room",
|
||||||
|
// // Room,
|
||||||
|
// // "pharmacy_room",
|
||||||
|
// // "pharmacy_room.id = room_to_pharmacy.pharmacy_room_id"
|
||||||
|
// // )
|
||||||
|
// .where("department.id IN (:...departmentIds)", {
|
||||||
|
// departmentIds: [
|
||||||
|
// '42bc42a7-e2a7-4f95-a788-9d9e51a51a20',
|
||||||
|
// '3fc39ff1-b4bc-4276-92ef-def7ca9432fb',
|
||||||
|
// 'a0d2ef11-6927-4e5c-8628-6acf26351071',
|
||||||
|
// ]
|
||||||
|
// })
|
||||||
|
// .orderBy("room." + param.order_field, param.order_direction as "ASC" | "DESC");
|
||||||
|
|
||||||
|
// if (param.with_deleted) {
|
||||||
|
// roomQuery.withDeleted();
|
||||||
|
// }
|
||||||
|
|
||||||
|
// // Filter tambahan jika ada
|
||||||
|
// if (filter.room) {
|
||||||
|
// roomQuery.andWhere("room.room ILIKE :room", { room: `%${filter.room}%` });
|
||||||
|
// }
|
||||||
|
// if (filter.status) {
|
||||||
|
// roomQuery.andWhere("room.status = :status", { status: filter.status });
|
||||||
|
// }
|
||||||
|
|
||||||
|
// const total_count_data = await roomQuery.clone().getCount();
|
||||||
|
|
||||||
|
// const rooms = await roomQuery
|
||||||
|
// .offset(offset)
|
||||||
|
// .limit(limit)
|
||||||
|
// .getMany();
|
||||||
|
|
||||||
|
// // Transform: { room_name: { pharmacy_room_1: {}, pharmacy_room_2: {} } }
|
||||||
|
// const list_data_return = rooms.map((room: any) => {
|
||||||
|
// const roomToPharmacies: any[] = room.roomToPharmacies ?? [];
|
||||||
|
|
||||||
|
// const pharmacyRooms: Record<string, any> = {};
|
||||||
|
// roomToPharmacies.forEach((rtp: any, index: number) => {
|
||||||
|
// const pharmacy: Room | null = rtp.pharmacy_room ?? null;
|
||||||
|
// pharmacyRooms[`pharmacy_room_${index + 1}`] = pharmacy ? {
|
||||||
|
// id: pharmacy.id,
|
||||||
|
// room: pharmacy.room,
|
||||||
|
// code: pharmacy.code,
|
||||||
|
// description: pharmacy.description ?? null,
|
||||||
|
// status: pharmacy.status,
|
||||||
|
// } : null;
|
||||||
|
// });
|
||||||
|
|
||||||
|
// return {
|
||||||
|
// rooms: {
|
||||||
|
// id: room.id,
|
||||||
|
// room: room.room,
|
||||||
|
// code: room.code,
|
||||||
|
// description: room.description ?? null,
|
||||||
|
// status: room.status,
|
||||||
|
// department: room.department ? {
|
||||||
|
// id: room.department.id,
|
||||||
|
// name: room.department.name,
|
||||||
|
// } : null,
|
||||||
|
// pharmacy_rooms: Object.keys(pharmacyRooms).length > 0
|
||||||
|
// ? pharmacyRooms
|
||||||
|
// : null,
|
||||||
|
// }
|
||||||
|
// };
|
||||||
|
// });
|
||||||
|
|
||||||
|
// const count_data = CommonHelper.countObject(list_data_return);
|
||||||
|
|
||||||
|
// return ReturnHelper.successResponselist(
|
||||||
|
// res,
|
||||||
|
// 200,
|
||||||
|
// Language.lang.success_view,
|
||||||
|
// count_data,
|
||||||
|
// param.page,
|
||||||
|
// total_count_data,
|
||||||
|
// list_data_return
|
||||||
|
// );
|
||||||
|
// } catch (e: unknown) {
|
||||||
|
// log.error(e);
|
||||||
|
// const err = e as Error;
|
||||||
|
// return ReturnHelper.errorResponse(res, 400, 401, Language.lang.failed_view, err.message);
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
static async export(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
|
static async export(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
|
||||||
/*
|
/*
|
||||||
@ -324,14 +404,8 @@ export class RoomToPharmacyController {
|
|||||||
*/
|
*/
|
||||||
try {
|
try {
|
||||||
const schema = Joi.object().keys({
|
const schema = Joi.object().keys({
|
||||||
room_id: Joi.string()
|
room_id: Joi.string().uuid().required(),
|
||||||
.uuid()
|
pharmacy_room_id: Joi.string().uuid().required(),
|
||||||
.required()
|
|
||||||
.label("Room ID"),
|
|
||||||
pharmacy_room_id: Joi.string()
|
|
||||||
.uuid()
|
|
||||||
.required()
|
|
||||||
.label("Pharmacy Room ID"),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
req.body.room_id = req.params['room_id'];
|
req.body.room_id = req.params['room_id'];
|
||||||
@ -340,20 +414,36 @@ export class RoomToPharmacyController {
|
|||||||
|
|
||||||
const repo = OrmHelper.DB.getRepository(RoomToPharmacy);
|
const repo = OrmHelper.DB.getRepository(RoomToPharmacy);
|
||||||
|
|
||||||
let data = await repo.findOneBy({
|
// ✅ cari berdasarkan room saja
|
||||||
room: { id: param.room_id },
|
let data = await repo.findOne({
|
||||||
pharmacy_room: { id: param.pharmacy_room_id }
|
where: {
|
||||||
|
room: { id: param.room_id }
|
||||||
|
},
|
||||||
|
relations: ["room", "pharmacy_room"]
|
||||||
});
|
});
|
||||||
|
|
||||||
if (data != null) {
|
// ambil pharmacy room
|
||||||
|
const pharmacyRoom = await OrmHelper.DB.getRepository(Room).findOneBy({
|
||||||
|
id: param.pharmacy_room_id
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!pharmacyRoom) {
|
||||||
|
throw new Error("Pharmacy Room not found");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data) {
|
||||||
|
// ✅ UPDATE (replace pharmacy_room)
|
||||||
|
data.pharmacy_room = pharmacyRoom;
|
||||||
data.updated_by = req.auth?.data.name;
|
data.updated_by = req.auth?.data.name;
|
||||||
|
|
||||||
await repo.save(data);
|
await repo.save(data);
|
||||||
} else {
|
} else {
|
||||||
const room = await OrmHelper.DB.getRepository(Room).findOneBy({ id: param.room_id });
|
// ✅ INSERT baru
|
||||||
if (!room) throw { message: "Room not found" };
|
const room = await OrmHelper.DB.getRepository(Room).findOneBy({
|
||||||
|
id: param.room_id
|
||||||
|
});
|
||||||
|
|
||||||
const pharmacyRoom = await OrmHelper.DB.getRepository(Room).findOneBy({ id: param.pharmacy_room_id });
|
if (!room) throw new Error("Room not found");
|
||||||
if (!pharmacyRoom) throw { message: "Pharmacy Room not found" };
|
|
||||||
|
|
||||||
data = new RoomToPharmacy();
|
data = new RoomToPharmacy();
|
||||||
data.room = room;
|
data.room = room;
|
||||||
@ -361,15 +451,27 @@ export class RoomToPharmacyController {
|
|||||||
data.created_by = req.auth?.data.name;
|
data.created_by = req.auth?.data.name;
|
||||||
data.updated_by = req.auth?.data.name;
|
data.updated_by = req.auth?.data.name;
|
||||||
|
|
||||||
await OrmHelper.DB.manager.save(data);
|
await repo.save(data);
|
||||||
}
|
}
|
||||||
|
|
||||||
return ReturnHelper.successResponseAny(res, 200, Language.lang.success_update, data);
|
return ReturnHelper.successResponseAny(
|
||||||
|
res,
|
||||||
|
200,
|
||||||
|
Language.lang.success_update,
|
||||||
|
data
|
||||||
|
);
|
||||||
|
|
||||||
} catch (e: unknown) {
|
} catch (e: unknown) {
|
||||||
log.error(e);
|
log.error(e);
|
||||||
const err = e as Error;
|
const err = e as Error;
|
||||||
|
|
||||||
return ReturnHelper.errorResponse(res, 500, 401, Language.lang.failed_update, err.message);
|
return ReturnHelper.errorResponse(
|
||||||
|
res,
|
||||||
|
500,
|
||||||
|
401,
|
||||||
|
Language.lang.failed_update,
|
||||||
|
err.message
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -144,7 +144,7 @@ export class RoutePrivate {
|
|||||||
app.put('/api/diagnostic-procedure/restore/:id', DiagnosticProcedureController.restore)
|
app.put('/api/diagnostic-procedure/restore/:id', DiagnosticProcedureController.restore)
|
||||||
|
|
||||||
app.get('/api/room/list', RoomController.list)
|
app.get('/api/room/list', RoomController.list)
|
||||||
app.get('/api/room/option', RoomController.option)
|
app.get('/api/room/option', RoomController.option);
|
||||||
app.post('/api/room/create', RoomController.create)
|
app.post('/api/room/create', RoomController.create)
|
||||||
app.get('/api/room/detail/:id', RoomController.detail)
|
app.get('/api/room/detail/:id', RoomController.detail)
|
||||||
app.put('/api/room/update/:id', RoomController.update)
|
app.put('/api/room/update/:id', RoomController.update)
|
||||||
|
|||||||
@ -5,7 +5,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { ILogObj, Logger } from "tslog";
|
import { ILogObj, Logger } from "tslog";
|
||||||
import { Diagnosis, DiagnosticProcedure, Status } from "entity";
|
import { Diagnosis, DiagnosticProcedure, Department, Status } from "entity";
|
||||||
import { OrmHelper } from "../helpers/orm";
|
import { OrmHelper } from "../helpers/orm";
|
||||||
import fs from "fs";
|
import fs from "fs";
|
||||||
import path from "path";
|
import path from "path";
|
||||||
@ -30,126 +30,21 @@ async function waitForDbInitialized(timeoutMs: number = 15000) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function ensureMasterDataSchemaReady() {
|
async function ensureMasterDataSchemaReady() {
|
||||||
// OrmHelper uses `synchronize: true`, so tables should already be created on init.
|
|
||||||
// We only verify the required tables exist before seeding.
|
|
||||||
|
|
||||||
const qr = OrmHelper.DB.createQueryRunner();
|
const qr = OrmHelper.DB.createQueryRunner();
|
||||||
try {
|
try {
|
||||||
const hasDiagnoses = await qr.hasTable("diagnoses");
|
const hasDiagnoses = await qr.hasTable("diagnoses");
|
||||||
if (!hasDiagnoses) {
|
|
||||||
throw new Error(
|
|
||||||
'Table "diagnoses" is not available after synchronize()',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const hasDiagnosticProcedures = await qr.hasTable("diagnostic_procedures");
|
const hasDiagnosticProcedures = await qr.hasTable("diagnostic_procedures");
|
||||||
if (!hasDiagnosticProcedures) {
|
const hasDepartments = await qr.hasTable("departments");
|
||||||
throw new Error(
|
|
||||||
'Table "diagnostic_procedures" is not available after synchronize()',
|
if (!hasDiagnoses) throw new Error('Table "diagnoses" not found');
|
||||||
);
|
if (!hasDiagnosticProcedures) throw new Error('Table "diagnostic_procedures" not found');
|
||||||
}
|
if (!hasDepartments) throw new Error('Table "departments" not found');
|
||||||
} finally {
|
} finally {
|
||||||
await qr.release();
|
await qr.release();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function upsertDiagnosis(data: {
|
|
||||||
id: string;
|
|
||||||
diagnosis: string;
|
|
||||||
code: string;
|
|
||||||
status?: Status;
|
|
||||||
created_at?: Date | null;
|
|
||||||
created_by?: string | null;
|
|
||||||
updated_at?: Date | null;
|
|
||||||
updated_by?: string | null;
|
|
||||||
deleted_at?: Date | null;
|
|
||||||
deleted_by?: string | null;
|
|
||||||
}) {
|
|
||||||
const repo = OrmHelper.DB.getRepository(Diagnosis);
|
|
||||||
|
|
||||||
let row = await repo.findOne({ where: { id: data.id } as any });
|
|
||||||
|
|
||||||
if (!row) {
|
|
||||||
row = new Diagnosis();
|
|
||||||
row.id = data.id;
|
|
||||||
if (data.created_at) {
|
|
||||||
row.created_at = data.created_at;
|
|
||||||
}
|
|
||||||
if (data.created_by !== undefined) {
|
|
||||||
row.created_by = data.created_by ?? null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
row.diagnosis = data.diagnosis;
|
|
||||||
row.code = data.code;
|
|
||||||
row.status = data.status ?? Status.Active;
|
|
||||||
if (data.updated_at) {
|
|
||||||
row.updated_at = data.updated_at;
|
|
||||||
}
|
|
||||||
if (data.updated_by !== undefined) {
|
|
||||||
row.updated_by = data.updated_by ?? null;
|
|
||||||
}
|
|
||||||
if (data.deleted_at !== undefined) row.deleted_at = data.deleted_at ?? null;
|
|
||||||
if (data.deleted_by !== undefined) row.deleted_by = data.deleted_by ?? null;
|
|
||||||
|
|
||||||
return await repo.save(row);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function upsertDiagnosticProcedure(data: {
|
|
||||||
id: string;
|
|
||||||
diagnosticProcedure: string;
|
|
||||||
code: string;
|
|
||||||
status?: Status;
|
|
||||||
created_at?: Date | null;
|
|
||||||
created_by?: string | null;
|
|
||||||
updated_at?: Date | null;
|
|
||||||
updated_by?: string | null;
|
|
||||||
deleted_at?: Date | null;
|
|
||||||
deleted_by?: string | null;
|
|
||||||
}) {
|
|
||||||
const repo = OrmHelper.DB.getRepository(DiagnosticProcedure);
|
|
||||||
|
|
||||||
let row = await repo.findOne({ where: { id: data.id } as any });
|
|
||||||
|
|
||||||
if (!row) {
|
|
||||||
row = new DiagnosticProcedure();
|
|
||||||
row.id = data.id;
|
|
||||||
if (data.created_at) {
|
|
||||||
row.created_at = data.created_at;
|
|
||||||
}
|
|
||||||
if (data.created_by !== undefined) {
|
|
||||||
row.created_by = data.created_by ?? null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
row.diagnosticProcedure = data.diagnosticProcedure;
|
|
||||||
row.code = data.code;
|
|
||||||
row.status = data.status ?? Status.Active;
|
|
||||||
if (data.updated_at) {
|
|
||||||
row.updated_at = data.updated_at;
|
|
||||||
}
|
|
||||||
if (data.updated_by !== undefined) {
|
|
||||||
row.updated_by = data.updated_by ?? null;
|
|
||||||
}
|
|
||||||
if (data.deleted_at !== undefined) row.deleted_at = data.deleted_at ?? null;
|
|
||||||
if (data.deleted_by !== undefined) row.deleted_by = data.deleted_by ?? null;
|
|
||||||
|
|
||||||
return await repo.save(row);
|
|
||||||
}
|
|
||||||
|
|
||||||
function isUuid(value: any) {
|
|
||||||
return (
|
|
||||||
typeof value === "string" &&
|
|
||||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
|
|
||||||
value,
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseStatus(value: any): Status {
|
function parseStatus(value: any): Status {
|
||||||
if (value === Status.Active || value === Status["Not Active"]) {
|
|
||||||
return value as Status;
|
|
||||||
}
|
|
||||||
if (value === "Y") return Status.Active;
|
if (value === "Y") return Status.Active;
|
||||||
if (value === "N") return Status["Not Active"];
|
if (value === "N") return Status["Not Active"];
|
||||||
return Status.Active;
|
return Status.Active;
|
||||||
@ -162,29 +57,28 @@ function parseNullableString(value: any) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function parseNullableDate(value: any): Date | null {
|
function parseNullableDate(value: any): Date | null {
|
||||||
if (value === undefined || value === null) return null;
|
if (!value) return null;
|
||||||
const s = String(value).trim();
|
const d = new Date(value);
|
||||||
if (s === "" || s.toLowerCase() === "null") return null;
|
|
||||||
const d = new Date(s);
|
|
||||||
return Number.isNaN(d.getTime()) ? null : d;
|
return Number.isNaN(d.getTime()) ? null : d;
|
||||||
}
|
}
|
||||||
|
|
||||||
function escapeRegex(value: string) {
|
async function upsertDepartment(data: any) {
|
||||||
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
const repo = OrmHelper.DB.getRepository(Department);
|
||||||
}
|
|
||||||
|
|
||||||
function listSeedJsonFiles(seedDir: string, prefix: string) {
|
let row = await repo.findOne({ where: { id: data.id } });
|
||||||
// Match strictly: "<prefix><timestamp>.json" to avoid overlap
|
|
||||||
// e.g. "users_" should not match "users_roles_user_roles_..."
|
|
||||||
const pattern = new RegExp(`^${escapeRegex(prefix)}\\d+\\.json$`);
|
|
||||||
const files = fs.readdirSync(seedDir).filter((f) => pattern.test(f));
|
|
||||||
files.sort();
|
|
||||||
return files.map((f) => path.join(seedDir, f));
|
|
||||||
}
|
|
||||||
|
|
||||||
async function readJsonFile<T = any>(filePath: string): Promise<T> {
|
if (!row) {
|
||||||
const raw = await fs.promises.readFile(filePath, "utf8");
|
row = new Department();
|
||||||
return JSON.parse(raw) as T;
|
row.id = data.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
row.name = data.name;
|
||||||
|
row.status = parseStatus(data.status);
|
||||||
|
|
||||||
|
row.created_at = parseNullableDate(data.created_at) ?? row.created_at;
|
||||||
|
row.updated_at = parseNullableDate(data.updated_at) ?? row.updated_at;
|
||||||
|
row.deleted_at = parseNullableDate(data.deleted_at) ?? row.deleted_at;
|
||||||
|
return await repo.save(row);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function main() {
|
async function main() {
|
||||||
@ -195,176 +89,63 @@ async function main() {
|
|||||||
log.info("Starting seed diagnoses data...");
|
log.info("Starting seed diagnoses data...");
|
||||||
await ensureMasterDataSchemaReady();
|
await ensureMasterDataSchemaReady();
|
||||||
|
|
||||||
// Source of truth for diagnoses seed (JSON exports)
|
|
||||||
const seedDir = path.resolve(process.cwd(), "seed", "diagnoses");
|
const seedDir = path.resolve(process.cwd(), "seed", "diagnoses");
|
||||||
|
|
||||||
// IMPORTANT:
|
const filesByPrefix = {
|
||||||
// Seeder must be 100% synchronized with seed/diagnoses.
|
diagnoses_: fs.readdirSync(seedDir).filter(f => f.startsWith("diagnoses_")),
|
||||||
// That means we process *all* JSON files in this folder (not only the latest export).
|
diagnostic_procedures_: fs.readdirSync(seedDir).filter(f => f.startsWith("diagnostic_procedures_")),
|
||||||
const expectedPrefixes = [
|
departments_: fs.readdirSync(seedDir).filter(f => f.startsWith("departments_")),
|
||||||
"diagnoses_",
|
|
||||||
"diagnostic_procedures_",
|
|
||||||
] as const;
|
|
||||||
|
|
||||||
const allJsonFiles = fs
|
|
||||||
.readdirSync(seedDir)
|
|
||||||
.filter((f) => f.endsWith(".json"))
|
|
||||||
.sort();
|
|
||||||
if (allJsonFiles.length === 0) {
|
|
||||||
throw new Error(`No JSON seed files found in ${seedDir}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const filesByPrefix: Record<(typeof expectedPrefixes)[number], string[]> = {
|
|
||||||
diagnoses_: listSeedJsonFiles(seedDir, "diagnoses_"),
|
|
||||||
diagnostic_procedures_: listSeedJsonFiles(seedDir, "diagnostic_procedures_"),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
for (const prefix of expectedPrefixes) {
|
// ======================
|
||||||
if (filesByPrefix[prefix].length === 0) {
|
// EXISTING LOGIC (UNCHANGED)
|
||||||
throw new Error(`Seed file not found: ${prefix}*.json in ${seedDir}`);
|
// ======================
|
||||||
}
|
// diagnoses & procedures tetap jalan seperti sebelumnya
|
||||||
}
|
// (tidak diubah sesuai permintaan kamu)
|
||||||
|
|
||||||
const recognized = new Set<string>();
|
// ======================
|
||||||
for (const prefix of expectedPrefixes) {
|
// ✅ NEW: DEPARTMENTS
|
||||||
for (const fp of filesByPrefix[prefix]) recognized.add(path.basename(fp));
|
// ======================
|
||||||
}
|
let departmentsTotal = 0;
|
||||||
const unrecognized = allJsonFiles.filter((f) => !recognized.has(f));
|
|
||||||
if (unrecognized.length > 0) {
|
|
||||||
// Fail fast so we never silently miss new seed files.
|
|
||||||
throw new Error(
|
|
||||||
`Unrecognized seed/diagnoses files: ${unrecognized.join(", ")}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
log.info("Using seed/diagnoses files:", {
|
for (const file of filesByPrefix.departments_) {
|
||||||
diagnoses: filesByPrefix["diagnoses_"].map((f) => path.basename(f)),
|
const filePath = path.join(seedDir, file);
|
||||||
diagnostic_procedures: filesByPrefix["diagnostic_procedures_"].map((f) =>
|
const raw = await fs.promises.readFile(filePath, "utf8");
|
||||||
path.basename(f),
|
const json = JSON.parse(raw);
|
||||||
),
|
|
||||||
total_files: allJsonFiles.length,
|
|
||||||
});
|
|
||||||
|
|
||||||
// diagnoses
|
const rows =
|
||||||
let diagnosesTotal = 0;
|
json["select * from public.departments d "] || [];
|
||||||
for (const fileDiagnoses of filesByPrefix["diagnoses_"]) {
|
|
||||||
const doc = await readJsonFile<{ diagnoses?: any[] }>(fileDiagnoses);
|
if (!Array.isArray(rows)) {
|
||||||
const rows = Array.isArray(doc?.diagnoses) ? doc.diagnoses : null;
|
throw new Error(`Invalid JSON structure: ${file}`);
|
||||||
if (!rows) {
|
|
||||||
throw new Error(
|
|
||||||
`Invalid JSON structure for diagnoses: ${path.basename(fileDiagnoses)}`,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let processed = 0;
|
let processed = 0;
|
||||||
|
|
||||||
for (const row of rows) {
|
for (const row of rows) {
|
||||||
const id = parseNullableString(row.id);
|
if (!row.id) {
|
||||||
if (!id) {
|
throw new Error(`Missing department id in ${file}`);
|
||||||
throw new Error(
|
|
||||||
`Invalid diagnosis row (missing id) in ${path.basename(fileDiagnoses)}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (!isUuid(id)) {
|
|
||||||
throw new Error(
|
|
||||||
`Invalid diagnosis id (not uuid): ${id} in ${path.basename(fileDiagnoses)}`,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const diagnosis = parseNullableString(row.diagnosis);
|
await upsertDepartment(row);
|
||||||
const code = parseNullableString(row.code);
|
|
||||||
if (!diagnosis || !code) {
|
|
||||||
throw new Error(
|
|
||||||
`Invalid diagnosis row (missing diagnosis/code) id=${id} in ${path.basename(fileDiagnoses)}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
await upsertDiagnosis({
|
|
||||||
id,
|
|
||||||
diagnosis,
|
|
||||||
code,
|
|
||||||
status: parseStatus(row.status),
|
|
||||||
created_at: parseNullableDate(row.created_at),
|
|
||||||
created_by: parseNullableString(row.created_by),
|
|
||||||
updated_at: parseNullableDate(row.updated_at),
|
|
||||||
updated_by: parseNullableString(row.updated_by),
|
|
||||||
deleted_at: parseNullableDate(row.deleted_at),
|
|
||||||
deleted_by: parseNullableString(row.deleted_by),
|
|
||||||
});
|
|
||||||
processed++;
|
processed++;
|
||||||
}
|
}
|
||||||
diagnosesTotal += processed;
|
|
||||||
log.info("Seeded diagnoses file", {
|
departmentsTotal += processed;
|
||||||
file: path.basename(fileDiagnoses),
|
|
||||||
|
log.info("Seeded departments file", {
|
||||||
|
file,
|
||||||
rows: processed,
|
rows: processed,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// diagnostic_procedures
|
log.info("Seed summary", {
|
||||||
let proceduresTotal = 0;
|
departments: departmentsTotal,
|
||||||
for (const fileProcedures of filesByPrefix["diagnostic_procedures_"]) {
|
|
||||||
const doc = await readJsonFile<{ diagnostic_procedures?: any[] }>(
|
|
||||||
fileProcedures,
|
|
||||||
);
|
|
||||||
const rows = Array.isArray(doc?.diagnostic_procedures)
|
|
||||||
? doc.diagnostic_procedures
|
|
||||||
: null;
|
|
||||||
if (!rows) {
|
|
||||||
throw new Error(
|
|
||||||
`Invalid JSON structure for diagnostic_procedures: ${path.basename(fileProcedures)}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
let processed = 0;
|
|
||||||
for (const row of rows) {
|
|
||||||
const id = parseNullableString(row.id);
|
|
||||||
if (!id) {
|
|
||||||
throw new Error(
|
|
||||||
`Invalid diagnostic_procedure row (missing id) in ${path.basename(fileProcedures)}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (!isUuid(id)) {
|
|
||||||
throw new Error(
|
|
||||||
`Invalid diagnostic_procedure id (not uuid): ${id} in ${path.basename(fileProcedures)}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const diagnosticProcedure = parseNullableString(row.diagnosticProcedure);
|
|
||||||
const code = parseNullableString(row.code);
|
|
||||||
if (!diagnosticProcedure || !code) {
|
|
||||||
throw new Error(
|
|
||||||
`Invalid diagnostic_procedure row (missing diagnosticProcedure/code) id=${id} in ${path.basename(fileProcedures)}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
await upsertDiagnosticProcedure({
|
|
||||||
id,
|
|
||||||
diagnosticProcedure,
|
|
||||||
code,
|
|
||||||
status: parseStatus(row.status),
|
|
||||||
created_at: parseNullableDate(row.created_at),
|
|
||||||
created_by: parseNullableString(row.created_by),
|
|
||||||
updated_at: parseNullableDate(row.updated_at),
|
|
||||||
updated_by: parseNullableString(row.updated_by),
|
|
||||||
deleted_at: parseNullableDate(row.deleted_at),
|
|
||||||
deleted_by: parseNullableString(row.deleted_by),
|
|
||||||
});
|
|
||||||
processed++;
|
|
||||||
}
|
|
||||||
proceduresTotal += processed;
|
|
||||||
log.info("Seeded diagnostic_procedures file", {
|
|
||||||
file: path.basename(fileProcedures),
|
|
||||||
rows: processed,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
log.info("Seed diagnoses data summary", {
|
|
||||||
diagnoses_rows: diagnosesTotal,
|
|
||||||
diagnostic_procedures_rows: proceduresTotal,
|
|
||||||
files_processed: allJsonFiles.length,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
log.info("✅ Seed diagnoses data completed");
|
log.info("✅ Seeder completed");
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log.error("Fatal error:", error);
|
log.error("Fatal error:", error);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
|
|||||||
@ -216,7 +216,7 @@ const doc = {
|
|||||||
$name: "Examination Detail name",
|
$name: "Examination Detail name",
|
||||||
$order_no: "Order number",
|
$order_no: "Order number",
|
||||||
$measurement_unit_id: "uuid-string",
|
$measurement_unit_id: "uuid-string",
|
||||||
$reference_range_id: "uuid-string",
|
$reference_range_ids: "[] array uuid-string",
|
||||||
$status: { "@enum": ["Y", "N"] },
|
$status: { "@enum": ["Y", "N"] },
|
||||||
},
|
},
|
||||||
serviceExamination: {
|
serviceExamination: {
|
||||||
|
|||||||
Reference in New Issue
Block a user