From b426f0ad83a016c22b258df29e759fda0244a40a Mon Sep 17 00:00:00 2001 From: wayanrivan Date: Thu, 12 Mar 2026 12:09:59 +0700 Subject: [PATCH] update: add new module inital stock --- src/controllers/pharmacy/initial_stock.ts | 138 ++++++++++++++++++++++ src/helpers/orm.ts | 5 +- src/model/initial_stock.ts | 23 ++++ src/routes/private.ts | 4 + src/swagger/builder.js | 7 ++ 5 files changed, 175 insertions(+), 2 deletions(-) create mode 100644 src/controllers/pharmacy/initial_stock.ts create mode 100644 src/model/initial_stock.ts diff --git a/src/controllers/pharmacy/initial_stock.ts b/src/controllers/pharmacy/initial_stock.ts new file mode 100644 index 0000000..bfcca11 --- /dev/null +++ b/src/controllers/pharmacy/initial_stock.ts @@ -0,0 +1,138 @@ +import { Response, NextFunction, Application } from "express"; +import { Request } from "express-jwt"; +import { ReturnHelper } from "../../helpers/express/return"; +import { OrmHelper } from "../../helpers/orm"; +import Joi from "joi"; +import { ILogObj, Logger } from "tslog"; +import { Language } from "../../langs/lang"; +import { InitialStock, ItemMaster, Room, ItemOrigin, Paging } from "entity"; +import CommonHelper from "../../helpers/common"; +import * as fastcsv from 'fast-csv'; +import dayjs from "dayjs"; +import { InitialStockModel } from "../../model/initial_stock"; + +const log: Logger = new Logger({ name: '[InitialStockController]', type: 'pretty' }); + +export class InitialStockController { + static async list(req: Request, res: Response, next: NextFunction): Promise { + /* + #swagger.tags = ['Pharmacy - InitialStock'] + #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: any = await schema.validateAsync(req.query); + + let filter = param.filter && param.filter !== "" ? JSON.parse(param.filter) : {}; + + var query = await InitialStockModel.list(filter); + + const offset = (param.page - 1) * param.limit; + let limit = param.limit; + + const res_count = query; + const res_list = query.select([ + 'InitialStock.id', + 'InitialStock.exp_date', + 'ItemMaster.item_name', + 'Room.room', + 'ItemOrigin.origin_name', + ]) + .leftJoin("InitialStock.itemmaster", "ItemMaster") + .leftJoin("InitialStock.room", "Room") + .leftJoin("InitialStock.itemorigin", "ItemOrigin") + .orderBy("InitialStock." + param.order_field, param.order_direction) + .offset(offset) + .limit(limit); + + if (param.with_deleted) { + res_count.withDeleted(); + res_list.withDeleted(); + } + + const current_page = param.page; + const total_count_data = await res_count.getCount(); + const list_data = await res_list.getMany(); + const count_data = CommonHelper.countObject(list_data); + + return ReturnHelper.successResponselist(res, 200, Language.lang.success_view, count_data, current_page, total_count_data, list_data); + } 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 create(req: Request, res: Response, next: NextFunction): Promise { + /* + #swagger.tags = ['Pharmacy - InitialStock'] + #swagger.security = [{ + "bearerAuth": [] + }] + + #swagger.requestBody = { + required: true, + content: { + "application/json": { + schema: { + $ref: "#/components/schemas/initial_stock" + } + } + } + } + */ + const queryRunner = OrmHelper.DB.createQueryRunner(); + await queryRunner.startTransaction(); + try { + const schema = Joi.object().keys({ + itemmaster: Joi.string().uuid().required().label("Item Master ID"), + room: Joi.string().uuid().required().label("Room ID"), + itemorigin: Joi.string().uuid().required().label("Item Origin ID"), + batch: Joi.string().required().label("Batch"), + exp_date: Joi.date().required().label("Exp Date"), + }); + + const param: any = await schema.validateAsync(req.body); + + const itemmaster = OrmHelper.DB.getRepository(ItemMaster).findOneBy({ id: param.itemmaster }); + const room = OrmHelper.DB.getRepository(Room).findOneBy({ id: param.room }) + const itemorigin = OrmHelper.DB.getRepository(ItemOrigin).findOneBy({ id: param.itemorigin }); + + if (!itemmaster) throw { message: "Item Master not found" }; + if (!room) throw { message: "Room not found" }; + if (!itemorigin) throw { message: "Item Origin not found" }; + + const initial_stock = new InitialStock(); + initial_stock.itemmaster = param.itemmaster; + initial_stock.room = param.room; + initial_stock.itemorigin = param.itemorigin; + initial_stock.batch = param.batch; + initial_stock.exp_date = param.exp_date; + + await queryRunner.manager.save(initial_stock); + await queryRunner.commitTransaction(); + + return ReturnHelper.successResponseAny(res, 200, Language.lang.success_insert, initial_stock); + + } catch (e: unknown) { + log.error(e); + const err = e as Error; + + return ReturnHelper.errorResponse(res, 500, 401, Language.lang.failed_insert, err.message); + } + } +} \ No newline at end of file diff --git a/src/helpers/orm.ts b/src/helpers/orm.ts index cc89ebb..8e304f4 100644 --- a/src/helpers/orm.ts +++ b/src/helpers/orm.ts @@ -1,7 +1,7 @@ import config from 'config'; import { DataSource } from "typeorm"; import { ILogObj, Logger } from 'tslog'; -import { Administrativu, Aldeia, District, Menu, Munisipo, Suco, Application, Nationality, Diagnosis, DiagnosticProcedure, Room, ServiceType, ServiceClass, Service, ServiceFare, ServicePackage, Department, DoctorSchedule, MeasurementUnit, ReferenceRange, QueueMonitoring, ExaminationDetail, ExaminationType, User, UserRole, HrmsEmployee, HrmsDepartment, HrmsPosition, HrmsShift,HospitalInformation, ItemOrigin, ItemType, ItemTypeDetail, Unit, ItemCategory, ItemStatus, UsageInstructions, UsageTime, ItemClass, ItemClassDetail, GenericName, Factory, Supplier, FactoryToSupplier, ItemMaster, ItemGroup, PharmacyInfo, ItemPrice, SellingPricePercentage, PatientGroup, PatientGuarantor } from 'entity' +import { Administrativu, Aldeia, District, Menu, Munisipo, Suco, Application, Nationality, Diagnosis, DiagnosticProcedure, Room, ServiceType, ServiceClass, Service, ServiceFare, ServicePackage, Department, DoctorSchedule, MeasurementUnit, ReferenceRange, QueueMonitoring, ExaminationDetail, ExaminationType, User, UserRole, HrmsEmployee, HrmsDepartment, HrmsPosition, HrmsShift,HospitalInformation, ItemOrigin, ItemType, ItemTypeDetail, Unit, ItemCategory, ItemStatus, UsageInstructions, UsageTime, ItemClass, ItemClassDetail, GenericName, Factory, Supplier, FactoryToSupplier, ItemMaster, ItemGroup, PharmacyInfo, ItemPrice, SellingPricePercentage, PatientGroup, PatientGuarantor,InitialStock } from 'entity' export class OrmHelper { static DB: DataSource = null @@ -40,7 +40,8 @@ export class OrmHelper { ItemPrice, SellingPricePercentage, PatientGroup, - PatientGuarantor + PatientGuarantor, + InitialStock ], subscribers: [], migrations: [], diff --git a/src/model/initial_stock.ts b/src/model/initial_stock.ts new file mode 100644 index 0000000..4ea9cdf --- /dev/null +++ b/src/model/initial_stock.ts @@ -0,0 +1,23 @@ +import { InitialStock } from "entity"; +import { SelectQueryBuilder } from "typeorm"; +import CommonHelper from "../helpers/common"; +import { OrmHelper } from "../helpers/orm"; + +export class InitialStockModel { + static async list(filter = {}): Promise> { + const repo = OrmHelper.DB.getRepository(InitialStock); + let whereAttr: string[] = []; + let whereVal: any = {}; + if (filter && Object.keys(filter).length > 0) { + whereAttr = [...whereAttr, ...CommonHelper.handleQueryFilter(filter, "InitialStock").whereAttr]; + whereVal = { ...whereVal, ...CommonHelper.handleQueryFilter(filter, "InitialStock").whereVal }; + } + + var query = repo.createQueryBuilder("InitialStock"); + if (whereAttr.length != 0) { + query = query.where(whereAttr.join(" and "), whereVal); + } + + return query; + } +} \ No newline at end of file diff --git a/src/routes/private.ts b/src/routes/private.ts index 1b11a1f..4db2044 100644 --- a/src/routes/private.ts +++ b/src/routes/private.ts @@ -51,6 +51,7 @@ import { PatientGuarantorController } from '../controllers/patient_guarantor'; import { GenericNameController } from '../controllers/pharmacy/generic_name'; import { RefferalHospital } from 'entity'; import { RefferalHospitalController } from '../controllers/refferal_hospital'; +import { InitialStockController } from '../controllers/pharmacy/initial_stock'; export class RoutePrivate { static setup(app: express.Application) { @@ -399,5 +400,8 @@ export class RoutePrivate { app.put('/api/refferal-hospital/update/:id', RefferalHospitalController.update) app.delete('/api/refferal-hospital/delete/:id/:hard', RefferalHospitalController.delete) app.put('/api/refferal-hospital/restore/:id', RefferalHospitalController.restore) + + app.get('/api/initial-stock/list', InitialStockController.list) + app.post('/api/initial-stock/create', InitialStockController.create) } } \ No newline at end of file diff --git a/src/swagger/builder.js b/src/swagger/builder.js index 52db881..6d4f397 100644 --- a/src/swagger/builder.js +++ b/src/swagger/builder.js @@ -298,6 +298,13 @@ const doc = { $selling_price: 'Selling Price (required, number, minimum 0)', $expired_date: 'Expired Date (required, date)' }, + initial_stock: { + $itemmaster: 'Item Master uuid', + $room: 'Room uuid', + $itemorigin: 'Item Origin uuid', + $batch: 'Batch', + $exp_date: 'Exp Date', + }, selling_price_percentage: { $item_master_id: 'Item Master ID (required, UUID)', $item_origin_id: 'Item Origin ID (required, UUID)',