diff --git a/openapi/oh.yaml b/openapi/oh.yaml index 40afbffe6..cac0d7d3e 100644 --- a/openapi/oh.yaml +++ b/openapi/oh.yaml @@ -59,8 +59,8 @@ paths: $ref: "#/components/schemas/WardDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -140,8 +140,8 @@ paths: $ref: "#/components/schemas/VaccineTypeDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -194,8 +194,8 @@ paths: $ref: "#/components/schemas/VaccineDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -955,8 +955,8 @@ paths: $ref: "#/components/schemas/OperationRowDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -1083,8 +1083,8 @@ paths: $ref: "#/components/schemas/MovementTypeDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -1137,8 +1137,8 @@ paths: $ref: "#/components/schemas/MedicalTypeDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -1215,8 +1215,8 @@ paths: $ref: "#/components/schemas/MedicalDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -1254,8 +1254,8 @@ paths: $ref: "#/components/schemas/MalnutritionDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -1555,7 +1555,7 @@ paths: content: application/json: schema: - type: boolean + $ref: "#/components/schemas/PatientExaminationDTO" security: - bearerAuth: [] /diseasetypes: @@ -1604,8 +1604,8 @@ paths: $ref: "#/components/schemas/DiseaseTypeDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -1643,8 +1643,8 @@ paths: $ref: "#/components/schemas/DiseaseDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -1670,7 +1670,7 @@ paths: put: tags: - DischargeType - operationId: updateDischargeTypet + operationId: updateDischargeType requestBody: content: application/json: @@ -1697,8 +1697,8 @@ paths: $ref: "#/components/schemas/DischargeTypeDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -1751,8 +1751,8 @@ paths: $ref: "#/components/schemas/DeliveryTypeDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -1805,8 +1805,8 @@ paths: $ref: "#/components/schemas/DeliveryResultTypeDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -1961,8 +1961,8 @@ paths: $ref: "#/components/schemas/AdmissionTypeDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -2047,8 +2047,8 @@ paths: responses: "400": description: Bad Request - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -2067,8 +2067,8 @@ paths: $ref: "#/components/schemas/VisitDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -2089,8 +2089,8 @@ paths: $ref: "#/components/schemas/VisitDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -2268,8 +2268,8 @@ paths: $ref: "#/components/schemas/TherapyRowDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -2290,12 +2290,12 @@ paths: $ref: "#/components/schemas/TherapyRowDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: - $ref: "#/components/schemas/TherapyRow" + $ref: "#/components/schemas/TherapyRowDTO" security: - bearerAuth: [] /therapies/meds-out-of-stock: @@ -2386,8 +2386,8 @@ paths: $ref: "#/components/schemas/MovementDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -2414,8 +2414,8 @@ paths: $ref: "#/components/schemas/MovementDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -2524,8 +2524,8 @@ paths: $ref: "#/components/schemas/PricesOthersDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -2559,8 +2559,8 @@ paths: $ref: "#/components/schemas/PriceListDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -2594,8 +2594,8 @@ paths: $ref: "#/components/schemas/PregnantTreatmentTypeDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -2614,8 +2614,8 @@ paths: $ref: "#/components/schemas/PatientVaccineDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -2662,8 +2662,8 @@ paths: $ref: "#/components/schemas/PatientDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -2697,8 +2697,8 @@ paths: $ref: "#/components/schemas/OperationTypeDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -2732,8 +2732,8 @@ paths: $ref: "#/components/schemas/OperationDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -2774,8 +2774,8 @@ paths: $ref: "#/components/schemas/OpdDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -2794,8 +2794,8 @@ paths: $ref: "#/components/schemas/OpdWithOperationRowDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -2814,8 +2814,8 @@ paths: $ref: "#/components/schemas/MovementWardDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -2842,8 +2842,8 @@ paths: $ref: "#/components/schemas/MovementDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -2870,8 +2870,8 @@ paths: $ref: "#/components/schemas/MovementDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -2921,8 +2921,8 @@ paths: $ref: "#/components/schemas/LabWithRowsDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -2943,8 +2943,8 @@ paths: $ref: "#/components/schemas/LabWithRowsDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -2978,8 +2978,8 @@ paths: $ref: "#/components/schemas/LaboratoryDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -3013,8 +3013,8 @@ paths: $ref: "#/components/schemas/ExamTypeDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -3083,8 +3083,8 @@ paths: $ref: "#/components/schemas/ExamRowDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -3103,12 +3103,12 @@ paths: $ref: "#/components/schemas/PatientExaminationDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: - type: boolean + $ref: "#/components/schemas/PatientExaminationDTO" security: - bearerAuth: [] /bills: @@ -3155,8 +3155,8 @@ paths: $ref: "#/components/schemas/FullBillDTO" required: true responses: - "200": - description: OK + "201": + description: Created content: application/json: schema: @@ -3235,7 +3235,7 @@ paths: "200": description: OK content: - '*/*': + application/json: schema: $ref: "#/components/schemas/LoginResponse" security: @@ -4439,7 +4439,7 @@ paths: get: tags: - Opds - operationId: getProgYear_1 + operationId: getProgressiveYear parameters: - name: year in: path @@ -5142,7 +5142,7 @@ paths: "200": description: OK content: - application/json: + text/plain: schema: type: string security: @@ -5411,9 +5411,7 @@ paths: content: application/json: schema: - type: object - additionalProperties: - type: boolean + type: boolean security: - bearerAuth: [] /diseases/opd: @@ -5798,7 +5796,7 @@ paths: get: tags: - Admissions - operationId: getNextYProg + operationId: getNextYearProgressiveId parameters: - name: wardcode in: query @@ -6079,9 +6077,7 @@ paths: content: application/json: schema: - type: object - additionalProperties: - type: boolean + type: boolean security: - bearerAuth: [] /dischargetypes/{code}: @@ -6235,14 +6231,14 @@ components: description: lock format: int32 example: 0 - opd: - type: boolean male: type: boolean female: type: boolean pharmacy: type: boolean + opd: + type: boolean PatientDTO: required: - age @@ -6953,11 +6949,11 @@ components: type: string description: "Flag record deleted, values are 'Y' OR 'N' " example: "N" + fhu: + type: string yprog: type: integer format: int32 - fhu: - type: string description: The admission AdmissionTypeDTO: required: @@ -7910,938 +7906,6 @@ components: description: "The sms flag: 1 if sms need to be sent to patient, 0 otherwise" format: int32 example: 0 - Patient: - required: - - age - - birthDate - - bloodType - - city - - deleted - - fatherName - - firstName - - motherName - - name - - secondName - - sex - type: object - properties: - createdBy: - type: string - createdDate: - type: string - format: date-time - lastModifiedBy: - type: string - lastModifiedDate: - type: string - format: date-time - active: - type: integer - format: int32 - code: - type: integer - format: int32 - firstName: - type: string - secondName: - type: string - name: - type: string - birthDate: - type: string - format: date - age: - type: integer - format: int32 - agetype: - type: string - sex: - type: string - address: - type: string - city: - type: string - nextKin: - type: string - telephone: - type: string - note: - type: string - motherName: - type: string - mother: - type: string - fatherName: - type: string - father: - type: string - bloodType: - type: string - hasInsurance: - type: string - parentTogether: - type: string - taxCode: - type: string - maritalStatus: - type: string - profession: - type: string - deleted: - type: string - anamnesis: - type: string - allergies: - type: string - lock: - type: integer - format: int32 - patientProfilePhoto: - $ref: "#/components/schemas/PatientProfilePhoto" - patientConsensus: - $ref: "#/components/schemas/PatientConsensus" - informations: - type: string - searchString: - type: string - PatientConsensus: - type: object - properties: - createdBy: - type: string - createdDate: - type: string - format: date-time - lastModifiedBy: - type: string - lastModifiedDate: - type: string - format: date-time - active: - type: integer - format: int32 - id: - type: integer - format: int32 - consensusFlag: - type: boolean - serviceFlag: - type: boolean - patient: - $ref: "#/components/schemas/Patient" - PatientProfilePhoto: - type: object - properties: - patient: - $ref: "#/components/schemas/Patient" - photo: - type: array - items: - type: string - format: byte - photoAsImage: - type: object - properties: - accelerationPriority: - type: number - format: float - source: - type: object - graphics: - type: object - properties: - color: - type: object - properties: - red: - type: integer - format: int32 - green: - type: integer - format: int32 - blue: - type: integer - format: int32 - alpha: - type: integer - format: int32 - colorSpace: - type: object - properties: - type: - type: integer - format: int32 - numComponents: - type: integer - format: int32 - cs_sRGB: - type: boolean - rgb: - type: integer - format: int32 - transparency: - type: integer - format: int32 - clipBounds: - type: object - properties: - x: - type: number - format: double - "y": - type: number - format: double - width: - type: number - format: double - height: - type: number - format: double - empty: - type: boolean - location: - type: object - properties: - x: - type: number - format: double - "y": - type: number - format: double - size: - type: object - properties: - width: - type: number - format: double - height: - type: number - format: double - bounds2D: - type: object - properties: - empty: - type: boolean - width: - type: number - format: double - height: - type: number - format: double - maxX: - type: number - format: double - maxY: - type: number - format: double - centerX: - type: number - format: double - centerY: - type: number - format: double - minX: - type: number - format: double - minY: - type: number - format: double - "y": - type: number - format: double - x: - type: number - format: double - rect: - type: object - properties: - empty: - type: boolean - width: - type: number - format: double - height: - type: number - format: double - maxX: - type: number - format: double - maxY: - type: number - format: double - centerX: - type: number - format: double - centerY: - type: number - format: double - minX: - type: number - format: double - minY: - type: number - format: double - "y": - type: number - format: double - x: - type: number - format: double - writeOnly: true - maxX: - type: number - format: double - maxY: - type: number - format: double - centerX: - type: number - format: double - centerY: - type: number - format: double - minX: - type: number - format: double - minY: - type: number - format: double - xormode: - type: object - properties: - red: - type: integer - format: int32 - green: - type: integer - format: int32 - blue: - type: integer - format: int32 - alpha: - type: integer - format: int32 - colorSpace: - type: object - properties: - type: - type: integer - format: int32 - numComponents: - type: integer - format: int32 - cs_sRGB: - type: boolean - rgb: - type: integer - format: int32 - transparency: - type: integer - format: int32 - writeOnly: true - font: - type: object - properties: - name: - type: string - style: - type: integer - format: int32 - size: - type: integer - format: int32 - attributes: - type: object - additionalProperties: - type: object - family: - type: string - plain: - type: boolean - transform: - type: object - properties: - scaleX: - type: number - format: double - shearY: - type: number - format: double - shearX: - type: number - format: double - scaleY: - type: number - format: double - translateX: - type: number - format: double - translateY: - type: number - format: double - type: - type: integer - format: int32 - identity: - type: boolean - toRotation: - type: number - format: double - writeOnly: true - toQuadrantRotation: - type: integer - format: int32 - writeOnly: true - determinant: - type: number - format: double - fontName: - type: string - bold: - type: boolean - italic: - type: boolean - numGlyphs: - type: integer - format: int32 - missingGlyphCode: - type: integer - format: int32 - italicAngle: - type: number - format: float - transformed: - type: boolean - psname: - type: string - size2D: - type: number - format: float - availableAttributes: - type: array - items: - type: object - clip: - type: object - properties: - bounds: - type: object - properties: - x: - type: number - format: double - "y": - type: number - format: double - width: - type: number - format: double - height: - type: number - format: double - empty: - type: boolean - location: - type: object - properties: - x: - type: number - format: double - "y": - type: number - format: double - size: - type: object - properties: - width: - type: number - format: double - height: - type: number - format: double - bounds2D: - type: object - properties: - empty: - type: boolean - width: - type: number - format: double - height: - type: number - format: double - maxX: - type: number - format: double - maxY: - type: number - format: double - centerX: - type: number - format: double - centerY: - type: number - format: double - minX: - type: number - format: double - minY: - type: number - format: double - "y": - type: number - format: double - x: - type: number - format: double - rect: - type: object - properties: - empty: - type: boolean - width: - type: number - format: double - height: - type: number - format: double - maxX: - type: number - format: double - maxY: - type: number - format: double - centerX: - type: number - format: double - centerY: - type: number - format: double - minX: - type: number - format: double - minY: - type: number - format: double - "y": - type: number - format: double - x: - type: number - format: double - writeOnly: true - maxX: - type: number - format: double - maxY: - type: number - format: double - centerX: - type: number - format: double - centerY: - type: number - format: double - minX: - type: number - format: double - minY: - type: number - format: double - bounds2D: - type: object - properties: - empty: - type: boolean - width: - type: number - format: double - height: - type: number - format: double - maxX: - type: number - format: double - maxY: - type: number - format: double - centerX: - type: number - format: double - centerY: - type: number - format: double - minX: - type: number - format: double - minY: - type: number - format: double - "y": - type: number - format: double - x: - type: number - format: double - clipRect: - type: object - properties: - x: - type: number - format: double - "y": - type: number - format: double - width: - type: number - format: double - height: - type: number - format: double - empty: - type: boolean - location: - type: object - properties: - x: - type: number - format: double - "y": - type: number - format: double - size: - type: object - properties: - width: - type: number - format: double - height: - type: number - format: double - bounds2D: - type: object - properties: - empty: - type: boolean - width: - type: number - format: double - height: - type: number - format: double - maxX: - type: number - format: double - maxY: - type: number - format: double - centerX: - type: number - format: double - centerY: - type: number - format: double - minX: - type: number - format: double - minY: - type: number - format: double - "y": - type: number - format: double - x: - type: number - format: double - rect: - type: object - properties: - empty: - type: boolean - width: - type: number - format: double - height: - type: number - format: double - maxX: - type: number - format: double - maxY: - type: number - format: double - centerX: - type: number - format: double - centerY: - type: number - format: double - minX: - type: number - format: double - minY: - type: number - format: double - "y": - type: number - format: double - x: - type: number - format: double - writeOnly: true - maxX: - type: number - format: double - maxY: - type: number - format: double - centerX: - type: number - format: double - centerY: - type: number - format: double - minX: - type: number - format: double - minY: - type: number - format: double - deprecated: true - fontMetrics: - type: object - properties: - font: - type: object - properties: - name: - type: string - style: - type: integer - format: int32 - size: - type: integer - format: int32 - attributes: - type: object - additionalProperties: - type: object - family: - type: string - plain: - type: boolean - transform: - type: object - properties: - scaleX: - type: number - format: double - shearY: - type: number - format: double - shearX: - type: number - format: double - scaleY: - type: number - format: double - translateX: - type: number - format: double - translateY: - type: number - format: double - type: - type: integer - format: int32 - identity: - type: boolean - toRotation: - type: number - format: double - writeOnly: true - toQuadrantRotation: - type: integer - format: int32 - writeOnly: true - determinant: - type: number - format: double - fontName: - type: string - bold: - type: boolean - italic: - type: boolean - numGlyphs: - type: integer - format: int32 - missingGlyphCode: - type: integer - format: int32 - italicAngle: - type: number - format: float - transformed: - type: boolean - psname: - type: string - size2D: - type: number - format: float - availableAttributes: - type: array - items: - type: object - height: - type: integer - format: int32 - ascent: - type: integer - format: int32 - descent: - type: integer - format: int32 - leading: - type: integer - format: int32 - maxDescent: - type: integer - format: int32 - widths: - type: array - items: - type: integer - format: int32 - fontRenderContext: - type: object - properties: - antiAliased: - type: boolean - transformType: - type: integer - format: int32 - transform: - type: object - properties: - scaleX: - type: number - format: double - shearY: - type: number - format: double - shearX: - type: number - format: double - scaleY: - type: number - format: double - translateX: - type: number - format: double - translateY: - type: number - format: double - type: - type: integer - format: int32 - identity: - type: boolean - toRotation: - type: number - format: double - writeOnly: true - toQuadrantRotation: - type: integer - format: int32 - writeOnly: true - determinant: - type: number - format: double - antiAliasingHint: - type: object - fractionalMetricsHint: - type: object - transformed: - type: boolean - maxAscent: - type: integer - format: int32 - maxDecent: - type: integer - format: int32 - deprecated: true - maxAdvance: - type: integer - format: int32 - TherapyRow: - required: - - endDate - - freqInDay - - freqInPeriod - - medicalId - - notifyInt - - patient - - qty - - smsInt - - startDate - - unitID - type: object - properties: - createdBy: - type: string - createdDate: - type: string - format: date-time - lastModifiedBy: - type: string - lastModifiedDate: - type: string - format: date-time - active: - type: integer - format: int32 - therapyID: - type: integer - format: int32 - patient: - $ref: "#/components/schemas/Patient" - startDate: - type: string - format: date-time - endDate: - type: string - format: date-time - medicalId: - type: integer - format: int32 - qty: - type: number - format: double - unitID: - type: integer - format: int32 - freqInDay: - type: integer - format: int32 - freqInPeriod: - type: integer - format: int32 - note: - type: string - notifyInt: - type: integer - format: int32 - smsInt: - type: integer - format: int32 - medical: - type: integer - format: int32 - notify: - type: boolean - sms: - type: boolean TherapyDTO: type: object properties: @@ -9125,7 +8189,7 @@ components: type: integer format: int32 list: - $ref: "#/components/schemas/PriceList" + $ref: "#/components/schemas/PriceListDTO" group: type: string description: The group @@ -9155,42 +8219,6 @@ components: format: int32 readOnly: true description: Class representing a prices - PriceList: - required: - - code - - currency - - description - - name - type: object - properties: - createdBy: - type: string - createdDate: - type: string - format: date-time - lastModifiedBy: - type: string - lastModifiedDate: - type: string - format: date-time - active: - type: integer - format: int32 - id: - type: integer - format: int32 - code: - type: string - name: - type: string - description: - type: string - currency: - type: string - lock: - type: integer - format: int32 - description: The price list PageInfoDTO: type: object properties: diff --git a/src/main/java/org/isf/accounting/rest/BillController.java b/src/main/java/org/isf/accounting/rest/BillController.java index 80ab7c8ef..2c4de3723 100644 --- a/src/main/java/org/isf/accounting/rest/BillController.java +++ b/src/main/java/org/isf/accounting/rest/BillController.java @@ -44,52 +44,52 @@ import org.isf.utils.exception.model.OHExceptionMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/bills") +@RestController @Tag(name = "Bills") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class BillController { private static final Logger LOGGER = LoggerFactory.getLogger(BillController.class); - @Autowired - protected BillBrowserManager billManager; + private final BillBrowserManager billManager; - @Autowired - protected PriceListManager priceListManager; + private final PriceListManager priceListManager; - @Autowired - protected PatientBrowserManager patientManager; + private final PatientBrowserManager patientManager; - @Autowired - protected BillMapper billMapper; + private final BillMapper billMapper; - @Autowired - protected BillItemsMapper billItemsMapper; + private final BillItemsMapper billItemsMapper; - @Autowired - protected BillPaymentsMapper billPaymentsMapper; + private final BillPaymentsMapper billPaymentsMapper; - public BillController(BillBrowserManager billManager, PriceListManager priceListManager, - PatientBrowserManager patientManager, BillMapper billMapper, BillItemsMapper billItemsMapper, - BillPaymentsMapper billPaymentsMapper) { + public BillController( + BillBrowserManager billManager, + PriceListManager priceListManager, + PatientBrowserManager patientManager, + BillMapper billMapper, + BillItemsMapper billItemsMapper, + BillPaymentsMapper billPaymentsMapper + ) { this.billManager = billManager; this.priceListManager = priceListManager; this.patientManager = patientManager; @@ -100,12 +100,13 @@ public BillController(BillBrowserManager billManager, PriceListManager priceList /** * Create new bill with the list of billItems and the list of billPayments - * @param newBillDto + * @param newBillDto Bill payload * @return {@link FullBillDTO} - * @throws OHServiceException + * @throws OHServiceException When failed to create bill */ - @PostMapping(value = "/bills", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity newBill(@RequestBody FullBillDTO newBillDto) throws OHServiceException { + @PostMapping("/bills") + @ResponseStatus(HttpStatus.CREATED) + public FullBillDTO newBill(@RequestBody FullBillDTO newBillDto) throws OHServiceException { if (newBillDto == null) { throw new OHAPIException(new OHExceptionMessage("Bill is null.")); @@ -118,7 +119,7 @@ public ResponseEntity newBill(@RequestBody FullBillDTO newBillDto) List list = priceListManager.getLists(); - PriceList plist = list.stream().filter(pricel -> pricel.getName().equals(bill.getListName())).findAny().orElse(null); + PriceList plist = list.stream().filter(priceList -> priceList.getName().equals(bill.getListName())).findAny().orElse(null); if (pat != null) { bill.setBillPatient(pat); @@ -141,18 +142,19 @@ public ResponseEntity newBill(@RequestBody FullBillDTO newBillDto) } catch (OHServiceException e) { throw new OHAPIException(new OHExceptionMessage("Bill is not created.")); } - return ResponseEntity.status(HttpStatus.CREATED).body(newBillDto); + + return newBillDto; } /** * Update bill with the list of billItems and the list of billPayments - * - * @param odBillDto + * + * @param odBillDto Bill payload * @return {@link FullBillDTO} - * @throws OHServiceException + * @throws OHServiceException When failed to update bill */ - @PutMapping(value = "/bills/{id}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity updateBill(@PathVariable Integer id, @RequestBody FullBillDTO odBillDto) throws OHServiceException { + @PutMapping("/bills/{id}") + public FullBillDTO updateBill(@PathVariable Integer id, @RequestBody FullBillDTO odBillDto) throws OHServiceException { LOGGER.info("updated Bill {}", odBillDto); Bill bill = billMapper.map2Model(odBillDto.getBill()); @@ -190,7 +192,8 @@ public ResponseEntity updateBill(@PathVariable Integer id, @Request } catch (OHServiceException e) { throw new OHAPIException(new OHExceptionMessage("Bill is not updated.")); } - return ResponseEntity.status(HttpStatus.CREATED).body(odBillDto); + + return odBillDto; } /** @@ -199,13 +202,13 @@ public ResponseEntity updateBill(@PathVariable Integer id, @Request * @param dateTo the high date range endpoint, inclusive. * @param code the patient code, which can be set or not. * @return a list of retrieved {@link Bill}s or {@code null} if an error occurred. - * @throws OHServiceException + * @throws OHServiceException When failed to get bills */ - @GetMapping(value = "/bills", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> searchBills( - @RequestParam(value = "datefrom") @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") @Schema(implementation = String.class) LocalDateTime dateFrom, - @RequestParam(value = "dateto") @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") @Schema(implementation = String.class) LocalDateTime dateTo, - @RequestParam(value = "patient_code", required = false, defaultValue = "") Integer code) throws OHServiceException { + @GetMapping("/bills") + public List searchBills( + @RequestParam(value = "datefrom") @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") @Schema(implementation = String.class) LocalDateTime dateFrom, + @RequestParam(value = "dateto") @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") @Schema(implementation = String.class) LocalDateTime dateTo, + @RequestParam(value = "patient_code", required = false, defaultValue = "") Integer code) throws OHServiceException { List bills; @@ -219,27 +222,22 @@ public ResponseEntity> searchBills( bills = billManager.getBills(dateFrom, dateTo, pat); } - List billDTOS = billMapper.map2DTOList(bills); - - if (billDTOS.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(billDTOS); - } - return ResponseEntity.ok(billDTOS); + return billMapper.map2DTOList(bills); } /** * Retrieves all the billPayments for a given parameters - * @param dateFrom - * @param dateTo + * @param dateFrom Start date + * @param dateTo End date * @param code the patient code, which can be set or not. * @return the list of payments - * @throws OHServiceException + * @throws OHServiceException When failed to get bill payments */ - @GetMapping(value = "/bills/payments", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> searchBillsPayments( - @RequestParam(value = "datefrom") @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") @Schema(implementation = String.class) LocalDateTime dateFrom, - @RequestParam(value = "dateto") @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") @Schema(implementation = String.class) LocalDateTime dateTo, - @RequestParam(value = "patient_code", required = false, defaultValue = "") Integer code) throws OHServiceException { + @GetMapping("/bills/payments") + public List searchBillsPayments( + @RequestParam(value = "datefrom") @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") @Schema(implementation = String.class) LocalDateTime dateFrom, + @RequestParam(value = "dateto") @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") @Schema(implementation = String.class) LocalDateTime dateTo, + @RequestParam(value = "patient_code", required = false, defaultValue = "") Integer code) throws OHServiceException { LOGGER.info("Get Payments datefrom: {} dateTo: {} patient: {}", dateFrom, dateTo, code); LOGGER.info("Get getPayments datefrom: {} dateTo: {}", dateFrom, dateTo); @@ -252,63 +250,43 @@ public ResponseEntity> searchBillsPayments( payments = billManager.getPayments(dateFrom, dateTo, pat); } - List paymentsDTOS = billPaymentsMapper.map2DTOList(payments); - - if (paymentsDTOS.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } - return ResponseEntity.ok(paymentsDTOS); + return billPaymentsMapper.map2DTOList(payments); } /** * Gets all the {@link BillPayments} for the specified {@link Bill}. * @param id the bill id. * @return a list of {@link BillPayments} or {@code null} if an error occurred. - * @throws OHServiceException + * @throws OHServiceException When failed to get bill payments */ - - @GetMapping(value = "/bills/payments/{bill_id}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getPaymentsByBillId(@PathVariable(value = "bill_id") Integer id) throws OHServiceException { + @GetMapping("/bills/payments/{bill_id}") + public List getPaymentsByBillId(@PathVariable(value = "bill_id") Integer id) throws OHServiceException { LOGGER.info("Get getPayments for bill with id: {}", id); - List billPayments = billManager.getPayments(id); - - List paymentsDTOS = billPaymentsMapper.map2DTOList(billPayments); - - if (paymentsDTOS.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } - return ResponseEntity.ok(paymentsDTOS); + return billPaymentsMapper.map2DTOList(billManager.getPayments(id)); } /** * Retrieves all the {@link BillItems} associated to the passed {@link Bill} id. * @param id the bill id. * @return a list of {@link BillItems} or {@code null} if an error occurred. - * @throws OHServiceException + * @throws OHServiceException When failed to get bill items */ - @GetMapping(value = "/bills/items/{bill_id}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getItems(@PathVariable(value = "bill_id") Integer id) throws OHServiceException { + @GetMapping("/bills/items/{bill_id}") + public List getItems(@PathVariable(value = "bill_id") Integer id) throws OHServiceException { LOGGER.info("Get Items for bill with id: {}", id); - List items = billManager.getItems(id); - - List itemsDTOS = billItemsMapper.map2DTOList(items); - - if (itemsDTOS.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } - return ResponseEntity.ok(itemsDTOS); + return billItemsMapper.map2DTOList(billManager.getItems(id)); } /** * Get the {@link Bill} with specified billID - * @param id the bill Id + * @param id the bill ID * @return the {@link Bill} or {@code null} if an error occurred. - * @throws OHServiceException + * @throws OHServiceException When failed to get the bill */ - @GetMapping(value = "/bills/{id}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getBill(@PathVariable Integer id) throws OHServiceException { + @GetMapping("/bills/{id}") + public BillDTO getBill(@PathVariable Integer id) throws OHServiceException { LOGGER.info("Get bill with id: {}", id); Bill bill = billManager.getBill(id); @@ -316,49 +294,36 @@ public ResponseEntity getBill(@PathVariable Integer id) throws OHServic BillDTO billDTO = billMapper.map2DTO(bill); if (billDTO == null) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); + throw new OHAPIException(new OHExceptionMessage("Bill not found with ID :" + id), HttpStatus.NOT_FOUND); } - return ResponseEntity.ok(billDTO); + + return billDTO; } /** * Retrieves all the {@link Bill}s associated to the specified {@link Patient}. * @param code - the Patient's code * @return the list of {@link Bill}s - * @throws OHServiceException + * @throws OHServiceException When failed to get associated bills */ - @GetMapping(value = "/bills/pending/affiliate", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getPendingBillsAffiliate(@RequestParam(value = "patient_code") Integer code) throws OHServiceException { + @GetMapping("/bills/pending/affiliate") + public List getPendingBillsAffiliate(@RequestParam(value = "patient_code") Integer code) throws OHServiceException { LOGGER.info("Get bill with id: {}", code); - List bills = billManager.getPendingBillsAffiliate(code); - - List billDTOS = billMapper.map2DTOList(bills); - - if (billDTOS.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } - return ResponseEntity.ok(billDTOS); + return billMapper.map2DTOList(billManager.getPendingBillsAffiliate(code)); } /** * Returns all the pending {@link Bill}s for the specified patient. * @param code the patient code. * @return the list of pending bills or {@code null} if an error occurred. - * @throws OHServiceException + * @throws OHServiceException When failed to get patient pending bills */ - @GetMapping(value = "/bills/pending", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getPendingBills(@RequestParam(value = "patient_code") Integer code) throws OHServiceException { + @GetMapping("/bills/pending") + public List getPendingBills(@RequestParam(value = "patient_code") Integer code) throws OHServiceException { LOGGER.info("Get bill with id: {}", code); - List bills = billManager.getPendingBills(code); - - List billDTOS = billMapper.map2DTOList(bills); - - if (billDTOS.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(billDTOS); - } - return ResponseEntity.ok(billDTOS); + return billMapper.map2DTOList(billManager.getPendingBills(code)); } /** @@ -367,83 +332,70 @@ public ResponseEntity> getPendingBills(@RequestParam(value = "pati * @param dateTo the high date range endpoint, inclusive. * @param billItemDTO the bill item object. * @return a list of retrieved {@link Bill}s or {@code null} if an error occurred. - * @throws OHServiceException + * @throws OHServiceException When error occurs */ - @PostMapping(value = "/bills/search/by/item", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> searchBills( - @RequestParam(value = "datefrom") @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") @Schema(implementation = String.class) LocalDateTime dateFrom, - @RequestParam(value = "dateto") @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") @Schema(implementation = String.class) LocalDateTime dateTo, - @RequestBody BillItemsDTO billItemDTO) throws OHServiceException { - + @PostMapping("/bills/search/by/item") + public List searchBills( + @RequestParam(value = "datefrom") @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") @Schema(implementation = String.class) LocalDateTime dateFrom, + @RequestParam(value = "dateto") @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") @Schema(implementation = String.class) LocalDateTime dateTo, + @RequestBody BillItemsDTO billItemDTO) throws OHServiceException { BillItems billItem = billItemsMapper.map2Model(billItemDTO); LOGGER.info("Get Bills dateFrom: {} dateTo: {} Bill ITEM ID: {}", dateFrom, dateTo, billItem.getId()); - List bills = billManager.getBills(dateFrom, dateTo, billItem); - - List billDTOS = billMapper.map2DTOList(bills); - - if (billDTOS.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } - return ResponseEntity.ok(billDTOS); + return billMapper.map2DTOList(billManager.getBills(dateFrom, dateTo, billItem)); } /** * Returns all the distinct stored {@link BillItems}. * - * @return a list of distinct {@link BillItems} or null if an error occurs. - * @throws OHServiceException + * @return a list of distinct {@link BillItems}. + * @throws OHServiceException When error occurs */ - @GetMapping(value = "/bills/items", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getDistinctItems() throws OHServiceException { - + @GetMapping("/bills/items") + public List getDistinctItems() throws OHServiceException { LOGGER.info("get all the distinct stored BillItems"); - List items = billManager.getDistinctItems(); // TODO: verify if it's correct - - List itemsDTOS = billItemsMapper.map2DTOList(items); - - if (itemsDTOS.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } - return ResponseEntity.ok(itemsDTOS); + return billItemsMapper.map2DTOList(billManager.getDistinctItems()); // TODO: verify if it's correct } - @DeleteMapping(value = "/bills/{id}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity deleteBill(@PathVariable Integer id) throws OHServiceException { + /** + * Delete a bill using ID + * @param id Bill ID + * @return true if the bill has been successfully deleted, + * throws exception otherwise + * @throws OHServiceException When failed to delete bill + */ + @DeleteMapping("/bills/{id}") + public Boolean deleteBill(@PathVariable Integer id) throws OHServiceException { LOGGER.info("Delete bill id: {}", id); Bill bill = billManager.getBill(id); + if (bill == null) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); + throw new OHAPIException(new OHExceptionMessage("Bill not found with ID :" + id), HttpStatus.NOT_FOUND); } + try { billManager.deleteBill(bill); } catch (OHServiceException e) { throw new OHAPIException(new OHExceptionMessage("Bill is not deleted.")); } - return ResponseEntity.ok(true); + + return true; } /** * Search all the {@link Bill}s associated to the passed {@link BillPayments}. * @param paymentsDTO the {@link BillPaymentsDTO} associated to the bill to retrieve. * @return a list of {@link Bill} associated to the passed {@link BillPayments} or {@code null} if an error occurred. - * @throws OHServiceException + * @throws OHServiceException When failed to get bills */ - @PostMapping(value = "/bills/search/by/payments", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> searchBillsByPayments(@RequestBody List paymentsDTO) throws OHServiceException { - + @PostMapping("/bills/search/by/payments") + public List searchBillsByPayments( + @RequestBody List paymentsDTO + ) throws OHServiceException { List billPayments = billPaymentsMapper.map2ModelList(paymentsDTO); - List bills = billManager.getBills(billPayments); - - List billDTOS = billMapper.map2DTOList(bills); - - if (billDTOS.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } - return ResponseEntity.ok(billDTOS); + return billMapper.map2DTOList(billManager.getBills(billPayments)); } - } diff --git a/src/main/java/org/isf/admission/rest/AdmissionController.java b/src/main/java/org/isf/admission/rest/AdmissionController.java index 4074973ac..57965c079 100644 --- a/src/main/java/org/isf/admission/rest/AdmissionController.java +++ b/src/main/java/org/isf/admission/rest/AdmissionController.java @@ -23,7 +23,6 @@ import java.time.LocalDateTime; import java.util.List; -import java.util.stream.Collectors; import jakarta.validation.Valid; @@ -33,10 +32,8 @@ import org.isf.admission.mapper.AdmissionMapper; import org.isf.admission.mapper.AdmittedPatientMapper; import org.isf.admission.model.Admission; -import org.isf.admission.model.AdmittedPatient; import org.isf.admtype.model.AdmissionType; import org.isf.disctype.manager.DischargeTypeBrowserManager; -import org.isf.disctype.mapper.DischargeTypeMapper; import org.isf.disctype.model.DischargeType; import org.isf.disease.manager.DiseaseBrowserManager; import org.isf.disease.model.Disease; @@ -44,7 +41,6 @@ import org.isf.dlvrrestype.model.DeliveryResultType; import org.isf.dlvrtype.manager.DeliveryTypeBrowserManager; import org.isf.dlvrtype.model.DeliveryType; -import org.isf.operation.manager.OperationBrowserManager; import org.isf.patient.manager.PatientBrowserManager; import org.isf.patient.model.Patient; import org.isf.pregtreattype.manager.PregnantTreatmentTypeBrowserManager; @@ -58,11 +54,9 @@ import org.isf.ward.model.Ward; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.DeleteMapping; @@ -72,6 +66,7 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; @@ -81,9 +76,10 @@ import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/admissions") +@RestController @Tag(name = "Admissions") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class AdmissionController { private static final Logger LOGGER = LoggerFactory.getLogger(AdmissionController.class); @@ -91,316 +87,300 @@ public class AdmissionController { // TODO: to centralize protected static final String DEFAULT_PAGE_SIZE = "80"; - @Autowired - private AdmissionBrowserManager admissionManager; + private final AdmissionBrowserManager admissionManager; - @Autowired - private PatientBrowserManager patientManager; + private final PatientBrowserManager patientManager; - @Autowired - private WardBrowserManager wardManager; + private final WardBrowserManager wardManager; - @Autowired - private DiseaseBrowserManager diseaseManager; + private final DiseaseBrowserManager diseaseManager; - @Autowired - private PregnantTreatmentTypeBrowserManager pregTraitTypeManager; + private final PregnantTreatmentTypeBrowserManager pregnantTreatmentTypeBrowserManager; - @Autowired - private DeliveryTypeBrowserManager dlvrTypeManager; + private final DeliveryTypeBrowserManager deliveryTypeBrowserManager; - @Autowired - private DeliveryResultTypeBrowserManager dlvrrestTypeManager; + private final DeliveryResultTypeBrowserManager deliveryResultTypeBrowserManager; - @Autowired - private AdmissionMapper admissionMapper; + private final AdmissionMapper admissionMapper; - @Autowired - private AdmittedPatientMapper admittedMapper; + private final AdmittedPatientMapper admittedMapper; - @Autowired - private DischargeTypeBrowserManager dischargeTypeManager; + private final DischargeTypeBrowserManager dischargeTypeManager; - @Autowired - private DischargeTypeMapper dischargeTypeMapper; // not used for now, maybe in future? - - public AdmissionController(AdmissionBrowserManager admissionManager, PatientBrowserManager patientManager, WardBrowserManager wardManager, - DiseaseBrowserManager diseaseManager, OperationBrowserManager operationManager, PregnantTreatmentTypeBrowserManager pregTraitTypeManager, - DeliveryTypeBrowserManager dlvrTypeManager, DeliveryResultTypeBrowserManager dlvrrestTypeManager, AdmissionMapper admissionMapper, - AdmittedPatientMapper admittedMapper, DischargeTypeBrowserManager dischargeTypeManager, DischargeTypeMapper dischargeTypeMapper) { + public AdmissionController( + AdmissionBrowserManager admissionManager, + PatientBrowserManager patientManager, + WardBrowserManager wardManager, + DiseaseBrowserManager diseaseManager, + PregnantTreatmentTypeBrowserManager pregnancyTraitTypeManager, + DeliveryTypeBrowserManager deliveryTypeBrowserManager, + DeliveryResultTypeBrowserManager deliveryResultTypeBrowserManager, + AdmissionMapper admissionMapper, + AdmittedPatientMapper admittedMapper, + DischargeTypeBrowserManager dischargeTypeManager + ) { this.admissionManager = admissionManager; this.patientManager = patientManager; this.wardManager = wardManager; this.diseaseManager = diseaseManager; - this.pregTraitTypeManager = pregTraitTypeManager; - this.dlvrTypeManager = dlvrTypeManager; - this.dlvrrestTypeManager = dlvrrestTypeManager; + this.pregnantTreatmentTypeBrowserManager = pregnancyTraitTypeManager; + this.deliveryTypeBrowserManager = deliveryTypeBrowserManager; + this.deliveryResultTypeBrowserManager = deliveryResultTypeBrowserManager; this.admissionMapper = admissionMapper; this.admittedMapper = admittedMapper; this.dischargeTypeManager = dischargeTypeManager; - this.dischargeTypeMapper = dischargeTypeMapper; } /** - * Get {@link Admission} for the specified id. - * - * @param patientCode + * Get {@link Admission} for the specified patient. + * + * @param patientCode Patient Code * @return the {@link Admission} found or NO_CONTENT otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to get patient admissions */ - @GetMapping(value = "/admissions/patient/{patientCode}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getAdmissions(@PathVariable("patientCode") int patientCode) throws OHServiceException { + @GetMapping("/admissions/patient/{patientCode}") + public List getAdmissions(@PathVariable("patientCode") int patientCode) throws OHServiceException { LOGGER.info("Get admission by patient id: {}", patientCode); Patient patient = patientManager.getPatientById(patientCode); if (patient == null) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); - } - List listAdmissions = admissionManager.getAdmissions(patient); - if (listAdmissions == null) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); + throw new OHAPIException(new OHExceptionMessage("Patient not found with ID :" + patientCode), HttpStatus.NOT_FOUND); } - List listAdmissionsDTO = listAdmissions.stream().map(admission -> { - - AdmissionDTO admissionDTO = new AdmissionDTO(); - if (admission != null) { - admissionDTO = admissionMapper.map2DTO(admission); - } - return admissionDTO; - }).collect(Collectors.toList()); - return ResponseEntity.ok(listAdmissionsDTO); + return admissionMapper.map2DTOList(admissionManager.getAdmissions(patient)); } /** - * Get the only one admission without Admission date for the specified patient. - * - * @param patientCode - * @return found {@link Admission}, N0_CONTENT if there is no {@link Admission} + * Get current admission for the specified patient. + * + * @param patientCode Patient Code + * @return found {@link Admission}, NO_CONTENT if there is no {@link Admission} * found or message error. - * @throws OHServiceException + * @throws OHServiceException When failed to get patient current admission */ - @GetMapping(value = "/admissions/current", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getCurrentAdmission(@RequestParam("patientCode") int patientCode) - throws OHServiceException { + @GetMapping("/admissions/current") + public AdmissionDTO getCurrentAdmission(@RequestParam("patientCode") int patientCode) throws OHServiceException { LOGGER.info("Get admission by patient code: {}", patientCode); + Patient patient = patientManager.getPatientById(patientCode); if (patient == null) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); + throw new OHAPIException(new OHExceptionMessage("Patient not found with ID :" + patientCode), HttpStatus.NOT_FOUND); } - Admission admission = admissionManager.getCurrentAdmission(patient); - if (admission == null) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } - AdmissionDTO admDTO = admissionMapper.map2DTO(admission); - return ResponseEntity.ok(admDTO); + + return admissionMapper.map2DTO(admissionManager.getCurrentAdmission(patient)); } /** * Get all admitted {@link Patient}s based on the applied filters. - * - * @param searchTerms - * @param admissionRange - * @param dischargeRange + * + * @param searchTerms Search keywords + * @param admissionRange Admission range + * @param dischargeRange Discharge range * @return the {@link List} of found {@link Patient} or NO_CONTENT otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to get admitted patient */ - @GetMapping(value = "/admissions/admittedPatients", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getAdmittedPatients( - @RequestParam(name = "searchterms", defaultValue = "", required = false) String searchTerms, - @RequestParam(name = "admissionrange", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) @ArraySchema(schema = @Schema(implementation = String.class)) LocalDateTime[] admissionRange, - @RequestParam(name = "dischargerange", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) @ArraySchema(schema = @Schema(implementation = String.class)) LocalDateTime[] dischargeRange) - throws OHServiceException { + @GetMapping("/admissions/admittedPatients") + public List getAdmittedPatients( + @RequestParam(name = "searchterms", defaultValue = "", required = false) String searchTerms, + @RequestParam(name = "admissionrange", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) @ArraySchema(schema = @Schema(implementation = String.class)) LocalDateTime[] admissionRange, + @RequestParam(name = "dischargerange", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) @ArraySchema(schema = @Schema(implementation = String.class)) LocalDateTime[] dischargeRange + ) throws OHServiceException { LOGGER.info("Get admitted patients search terms: {}", searchTerms); + if (admissionRange != null && admissionRange.length == 2) { LOGGER.debug("Get admissions started between {} and {}", admissionRange[0], admissionRange[1]); } + if (dischargeRange != null && dischargeRange.length == 2) { LOGGER.debug("Get admissions that end between {} and {}", dischargeRange[0], dischargeRange[1]); } - List admittedPatients = admissionManager.getAdmittedPatients(admissionRange, dischargeRange, searchTerms); - if (admittedPatients.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } - - return ResponseEntity.ok(admittedMapper.map2DTOList(admittedPatients)); + return admittedMapper.map2DTOList(admissionManager.getAdmittedPatients(admissionRange, dischargeRange, searchTerms)); } /** * Get all the {@link Admission}s that start in the specified range - * - * @param admissionRange + * + * @param admissionRange Admission range * @return the {@link List} of found {@link Admission} or NO_CONTENT otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to get admission */ - @GetMapping(value = "/admissions", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getAdmissions( - @RequestParam(name = "admissionrange") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) @ArraySchema(schema = @Schema(implementation = String.class)) LocalDateTime[] admissionRange, - @RequestParam(value = "page", required = false, defaultValue = "0") int page, - @RequestParam(value = "size", required = false, defaultValue = DEFAULT_PAGE_SIZE) int size, - @RequestParam(value = "paged", required = false, defaultValue = "false") boolean paged) - throws OHServiceException { + @GetMapping("/admissions") + public Page getAdmissions( + @RequestParam(name = "admissionrange") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) @ArraySchema(schema = @Schema(implementation = String.class)) LocalDateTime[] admissionRange, + @RequestParam(value = "page", required = false, defaultValue = "0") int page, + @RequestParam(value = "size", required = false, defaultValue = DEFAULT_PAGE_SIZE) int size, + @RequestParam(value = "paged", required = false, defaultValue = "false") boolean paged + ) throws OHServiceException { LOGGER.debug("Get admissions started between {} and {}", admissionRange[0], admissionRange[1]); Page admissionsPageableDTO = new Page<>(); List admissionsDTO; if (paged) { - PagedResponse admissions = admissionManager.getAdmissionsPageable(admissionRange[0], admissionRange[1], page, size); + PagedResponse admissions = admissionManager.getAdmissionsPageable( + admissionRange[0], admissionRange[1], page, size + ); admissionsDTO = admissionMapper.map2DTOList(admissions.getData()); admissionsPageableDTO.setPageInfo(admissionMapper.setParameterPageInfo(admissions.getPageInfo())); } else { - List adms = admissionManager.getAdmissionsByAdmissionDate(admissionRange[0], admissionRange[1]); - admissionsDTO = admissionMapper.map2DTOList(adms); - } - if (admissionsDTO.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); + List admissions = admissionManager.getAdmissionsByAdmissionDate( + admissionRange[0], admissionRange[1] + ); + admissionsDTO = admissionMapper.map2DTOList(admissions); } + admissionsPageableDTO.setData(admissionsDTO); - return ResponseEntity.ok(admissionsPageableDTO); + + return admissionsPageableDTO; } /** * Get all the {@link Admission}s that end in the specified range - * - * @param dischargeRange + * + * @param dischargeRange Discharge range * @return the {@link List} of found {@link Admission} or NO_CONTENT otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to get admissions */ - @GetMapping(value = "/admissions/discharges", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getDischarges( - @RequestParam(name = "dischargerange") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) @ArraySchema(schema = @Schema(implementation = String.class)) LocalDateTime[] dischargeRange, - @RequestParam(value = "page", required = false, defaultValue = "0") int page, - @RequestParam(value = "size", required = false, defaultValue = DEFAULT_PAGE_SIZE) int size) - throws OHServiceException { + @GetMapping("/admissions/discharges") + public Page getDischarges( + @RequestParam(name = "dischargerange") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) @ArraySchema(schema = @Schema(implementation = String.class)) LocalDateTime[] dischargeRange, + @RequestParam(value = "page", required = false, defaultValue = "0") int page, + @RequestParam(value = "size", required = false, defaultValue = DEFAULT_PAGE_SIZE) int size + ) throws OHServiceException { LOGGER.debug("Get admissions that end between {} and {}", dischargeRange[0], dischargeRange[1]); PagedResponse admissionsPageable = admissionManager.getDischargesPageable(dischargeRange[0], dischargeRange[1], page, size); - if (admissionsPageable.getData().isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } + Page admissionsPageableDTO = new Page<>(); List admissionsDTO = admissionMapper.map2DTOList(admissionsPageable.getData()); admissionsPageableDTO.setData(admissionsDTO); admissionsPageableDTO.setPageInfo(admissionMapper.setParameterPageInfo(admissionsPageable.getPageInfo())); - return ResponseEntity.ok(admissionsPageableDTO); + + return admissionsPageableDTO; } /** - * Get the next prog in the year for specified {@link Ward} code. - * - * @param wardCode - * @return the next prog. - * @throws OHServiceException + * Get the next progressive ID in the year for specified {@link Ward} code. + * + * @param wardCode Ward Code + * @return the next progressive ID. + * @throws OHServiceException When failed to get the next progressive ID */ - @GetMapping(value = "/admissions/getNextProgressiveIdInYear", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getNextYProg(@RequestParam("wardcode") String wardCode) throws OHServiceException { - LOGGER.info("get the next prog in the year for ward code: {}", wardCode); + @GetMapping("/admissions/getNextProgressiveIdInYear") + public Integer getNextYearProgressiveId(@RequestParam("wardcode") String wardCode) throws OHServiceException { + LOGGER.info("get the next progressive ID in the year for ward code: {}", wardCode); if (wardCode.trim().isEmpty() || !wardManager.isCodePresent(wardCode)) { throw new OHAPIException(new OHExceptionMessage("Ward not found for code:" + wardCode)); } - return ResponseEntity.ok(admissionManager.getNextYProg(wardCode)); + return admissionManager.getNextYProg(wardCode); } /** * Get the number of used beds for the specified {@link Ward} code. - * - * @param wardCode + * + * @param wardCode Ward Code * @return the number of used beds. - * @throws OHServiceException + * @throws OHServiceException When failed to the number of used beds */ - @GetMapping(value = "/admissions/getBedsOccupationInWard", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getUsedWardBed(@RequestParam("wardid") String wardCode) throws OHServiceException { + @GetMapping("/admissions/getBedsOccupationInWard") + public Integer getUsedWardBed(@RequestParam("wardid") String wardCode) throws OHServiceException { LOGGER.info("Counts the number of used bed for ward code: {}", wardCode); if (wardCode.trim().isEmpty() || !wardManager.isCodePresent(wardCode)) { throw new OHAPIException(new OHExceptionMessage("Ward not found for code:" + wardCode)); } - return ResponseEntity.ok(admissionManager.getUsedWardBed(wardCode)); + return admissionManager.getUsedWardBed(wardCode); } /** * Set an {@link Admission} record to be deleted. - * - * @param id + * + * @param id Admission ID * @return {@code true} if the record has been set to delete. - * @throws OHServiceException + * @throws OHServiceException When failed to delete admission */ - @DeleteMapping(value = "/admissions/{id}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity deleteAdmissionType(@PathVariable("id") int id) throws OHServiceException { + @DeleteMapping("/admissions/{id}") + public boolean deleteAdmissionType(@PathVariable("id") int id) throws OHServiceException { LOGGER.info("setting admission to deleted: {}", id); Admission admission = admissionManager.getAdmission(id); + if (admission == null) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); + throw new OHAPIException(new OHExceptionMessage("Admission not found for code:" + id)); } + admissionManager.setDeleted(id); - return ResponseEntity.ok(true); + return true; } /** * Discharge the {@link Admission}s for the specified {@link Patient} code. - * - * @param patientCode + * + * @param patientCode Patient code * @return {@code true} if the record has been set to discharge. - * @throws OHServiceException + * @throws OHServiceException When failed to discharge the patient */ - @PostMapping(value = "/admissions/discharge", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity dischargePatient(@RequestParam("patientCode") int patientCode, - @Valid @RequestBody AdmissionDTO currentAdmissionDTO) throws OHServiceException { + @PostMapping("/admissions/discharge") + public boolean dischargePatient( + @RequestParam("patientCode") int patientCode, + @Valid @RequestBody AdmissionDTO currentAdmissionDTO + ) throws OHServiceException { LOGGER.info("discharge the patient"); - Patient patient = patientManager.getPatientById(patientCode); + Patient patient = patientManager.getPatientById(patientCode); if (patient == null) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(false); + throw new OHAPIException(new OHExceptionMessage("Patient not found for code:" + patientCode)); } - Admission admission = admissionManager.getCurrentAdmission(patient); + Admission admission = admissionManager.getCurrentAdmission(patient); if (admission == null) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); + throw new OHAPIException(new OHExceptionMessage("Patient is not admitted")); } - Admission adm = admissionMapper.map2Model(currentAdmissionDTO); - if (adm == null || admission.getId() != adm.getId()) { - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); - } + // TODO: Use a appropriate DTO which includes validation and remove following lines + Admission adm = admissionMapper.map2Model(currentAdmissionDTO); if (adm.getDiseaseOut1() == null) { throw new OHAPIException(new OHExceptionMessage("at least one disease must be give.")); } + if (adm.getDisDate() == null) { throw new OHAPIException(new OHExceptionMessage("the exit date must be filled in.")); } + if (adm.getDisDate().isBefore(adm.getAdmDate())) { throw new OHAPIException(new OHExceptionMessage("the exit date must be after the entry date.")); } if (adm.getDisType() == null || !dischargeTypeManager.isCodePresent(adm.getDisType().getCode())) { throw new OHAPIException(new OHExceptionMessage("the type of output is mandatory or does not exist.")); } + adm.setAdmitted(0); Admission admissionUpdated = admissionManager.updateAdmission(adm); - return ResponseEntity.status(HttpStatus.OK).body(admissionUpdated != null); + return admissionUpdated != null; } /** * Create a new {@link Admission}. - * - * @param newAdmissionDTO + * + * @param newAdmissionDTO Admission payload * @return the generated id or {@code null} for the created {@link Admission}. - * @throws OHServiceException + * @throws OHServiceException When failed to create admission */ - @PostMapping(value = "/admissions", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity newAdmissions(@Valid @RequestBody AdmissionDTO newAdmissionDTO) - throws OHServiceException { - + @PostMapping("/admissions") + @ResponseStatus(HttpStatus.CREATED) + public AdmissionDTO newAdmissions( + @Valid @RequestBody AdmissionDTO newAdmissionDTO + ) throws OHServiceException { Admission newAdmission = admissionMapper.map2Model(newAdmissionDTO); + if (newAdmissionDTO.getWard() != null && newAdmissionDTO.getWard().getCode() != null - && !newAdmissionDTO.getWard().getCode().trim().isEmpty()) { + && !newAdmissionDTO.getWard().getCode().trim().isEmpty()) { List wards = wardManager.getWards().stream() - .filter(w -> w.getCode().equals(newAdmissionDTO.getWard().getCode())).collect(Collectors.toList()); + .filter(w -> w.getCode().equals(newAdmissionDTO.getWard().getCode())).toList(); if (wards.isEmpty()) { throw new OHAPIException(new OHExceptionMessage("Ward not found.")); } @@ -410,13 +390,16 @@ ResponseEntity newAdmissions(@Valid @RequestBody AdmissionDTO newA } if (newAdmissionDTO.getAdmType() != null && newAdmissionDTO.getAdmType().getCode() != null - && !newAdmissionDTO.getAdmType().getCode().trim().isEmpty()) { - List types = admissionManager.getAdmissionType().stream() - .filter(admt -> admt.getCode().equals(newAdmissionDTO.getAdmType().getCode())) - .collect(Collectors.toList()); + && !newAdmissionDTO.getAdmType().getCode().trim().isEmpty()) { + List types = admissionManager.getAdmissionType() + .stream() + .filter(admissionType -> admissionType.getCode().equals(newAdmissionDTO.getAdmType().getCode())) + .toList(); + if (types.isEmpty()) { throw new OHAPIException(new OHExceptionMessage("Admission type not found.")); } + newAdmission.setAdmType(types.get(0)); } else { throw new OHAPIException(new OHExceptionMessage("Admission type field is required.")); @@ -431,12 +414,12 @@ ResponseEntity newAdmissions(@Valid @RequestBody AdmissionDTO newA } else { throw new OHAPIException(new OHExceptionMessage("Patient field is required.")); } + List diseases = diseaseManager.getDiseaseAll(); if (newAdmissionDTO.getDiseaseIn() != null && newAdmissionDTO.getDiseaseIn().getCode() != null) { List dIns = diseases.stream() - .filter(d -> d.getCode().equals(newAdmissionDTO.getDiseaseIn().getCode())) - .collect(Collectors.toList()); + .filter(d -> d.getCode().equals(newAdmissionDTO.getDiseaseIn().getCode())).toList(); if (dIns.isEmpty()) { throw new OHAPIException(new OHExceptionMessage("Disease in not found.")); } @@ -445,8 +428,7 @@ ResponseEntity newAdmissions(@Valid @RequestBody AdmissionDTO newA if (newAdmissionDTO.getDiseaseOut1() != null && newAdmissionDTO.getDiseaseOut1().getCode() != null) { List dOut1 = diseases.stream() - .filter(d -> d.getCode().equals(newAdmissionDTO.getDiseaseOut1().getCode())) - .collect(Collectors.toList()); + .filter(d -> d.getCode().equals(newAdmissionDTO.getDiseaseOut1().getCode())).toList(); if (dOut1.isEmpty()) { throw new OHAPIException(new OHExceptionMessage("Disease out 1 not found.")); } @@ -455,8 +437,7 @@ ResponseEntity newAdmissions(@Valid @RequestBody AdmissionDTO newA if (newAdmissionDTO.getDiseaseOut2() != null && newAdmissionDTO.getDiseaseOut2().getCode() != null) { List dOut2 = diseases.stream() - .filter(d -> d.getCode().equals(newAdmissionDTO.getDiseaseOut2().getCode())) - .collect(Collectors.toList()); + .filter(d -> d.getCode().equals(newAdmissionDTO.getDiseaseOut2().getCode())).toList(); if (dOut2.isEmpty()) { throw new OHAPIException(new OHExceptionMessage("Disease out 2 not found.")); } @@ -465,8 +446,7 @@ ResponseEntity newAdmissions(@Valid @RequestBody AdmissionDTO newA if (newAdmissionDTO.getDiseaseOut3() != null && newAdmissionDTO.getDiseaseOut3().getCode() != null) { List dOut3 = diseases.stream() - .filter(d -> d.getCode().equals(newAdmissionDTO.getDiseaseOut3().getCode())) - .collect(Collectors.toList()); + .filter(d -> d.getCode().equals(newAdmissionDTO.getDiseaseOut3().getCode())).toList(); if (dOut3.isEmpty()) { throw new OHAPIException(new OHExceptionMessage("Disease out 3 not found.")); } @@ -474,11 +454,10 @@ ResponseEntity newAdmissions(@Valid @RequestBody AdmissionDTO newA } if (newAdmissionDTO.getDisType() != null && newAdmissionDTO.getDisType().getCode() != null - && !newAdmissionDTO.getDisType().getCode().trim().isEmpty()) { + && !newAdmissionDTO.getDisType().getCode().trim().isEmpty()) { List disTypes = admissionManager.getDischargeType(); List disTypesF = disTypes.stream() - .filter(dtp -> dtp.getCode().equals(newAdmissionDTO.getDisType().getCode())) - .collect(Collectors.toList()); + .filter(dtp -> dtp.getCode().equals(newAdmissionDTO.getDisType().getCode())).toList(); if (disTypesF.isEmpty()) { throw new OHAPIException(new OHExceptionMessage("Discharge type not found.")); } @@ -486,51 +465,60 @@ ResponseEntity newAdmissions(@Valid @RequestBody AdmissionDTO newA } if (newAdmissionDTO.getPregTreatmentType() != null && newAdmissionDTO.getPregTreatmentType().getCode() != null - && !newAdmissionDTO.getPregTreatmentType().getCode().trim().isEmpty()) { - List pregTTypes = pregTraitTypeManager.getPregnantTreatmentType(); - List pregTTypesF = pregTTypes.stream() - .filter(pregtt -> pregtt.getCode().equals(newAdmissionDTO.getPregTreatmentType().getCode())) - .collect(Collectors.toList()); - if (pregTTypesF.isEmpty()) { + && !newAdmissionDTO.getPregTreatmentType().getCode().trim().isEmpty()) { + List pregnantTreatmentTypes = pregnantTreatmentTypeBrowserManager.getPregnantTreatmentType(); + List pregnantTreatmentTypesFound = pregnantTreatmentTypes + .stream() + .filter(pregnantTreatmentType -> pregnantTreatmentType.getCode().equals(newAdmissionDTO.getPregTreatmentType().getCode())) + .toList(); + + if (pregnantTreatmentTypesFound.isEmpty()) { throw new OHAPIException(new OHExceptionMessage("Pregnant treatment type not found.")); } - newAdmission.setPregTreatmentType(pregTTypesF.get(0)); + + newAdmission.setPregTreatmentType(pregnantTreatmentTypesFound.get(0)); } if (newAdmissionDTO.getDeliveryType() != null && newAdmissionDTO.getDeliveryType().getCode() != null - && !newAdmissionDTO.getDeliveryType().getCode().trim().isEmpty()) { - List dlvrTypes = dlvrTypeManager.getDeliveryType(); - List dlvrTypesF = dlvrTypes.stream() - .filter(dlvrType -> dlvrType.getCode().equals(newAdmissionDTO.getDeliveryType().getCode())) - .collect(Collectors.toList()); - if (dlvrTypesF.isEmpty()) { + && !newAdmissionDTO.getDeliveryType().getCode().trim().isEmpty()) { + List deliveryTypes = deliveryTypeBrowserManager.getDeliveryType(); + List deliveryTypesFound = deliveryTypes + .stream() + .filter(deliveryType -> deliveryType.getCode().equals(newAdmissionDTO.getDeliveryType().getCode())) + .toList(); + + if (deliveryTypesFound.isEmpty()) { throw new OHAPIException(new OHExceptionMessage("Delivery type not found.")); } - newAdmission.setDeliveryType(dlvrTypesF.get(0)); + + newAdmission.setDeliveryType(deliveryTypesFound.get(0)); } if (newAdmissionDTO.getDeliveryResult() != null && newAdmissionDTO.getDeliveryResult().getCode() != null - && !newAdmissionDTO.getDeliveryResult().getCode().trim().isEmpty()) { - List dlvrrestTypes = dlvrrestTypeManager.getDeliveryResultType(); - List dlvrrestTypesF = dlvrrestTypes.stream().filter( - dlvrrestType -> dlvrrestType.getCode().equals(newAdmissionDTO.getDeliveryResult().getCode())) - .collect(Collectors.toList()); - if (dlvrrestTypesF.isEmpty()) { + && !newAdmissionDTO.getDeliveryResult().getCode().trim().isEmpty()) { + List deliveryResultTypes = deliveryResultTypeBrowserManager.getDeliveryResultType(); + List deliveryResultTypesFound = deliveryResultTypes + .stream() + .filter(deliveryResultType -> deliveryResultType.getCode().equals(newAdmissionDTO.getDeliveryResult().getCode())) + .toList(); + + if (deliveryResultTypesFound.isEmpty()) { throw new OHAPIException(new OHExceptionMessage("Delivery result type not found.")); } - newAdmission.setDeliveryResult(dlvrrestTypesF.get(0)); + + newAdmission.setDeliveryResult(deliveryResultTypesFound.get(0)); } String name = StringUtils.hasLength(newAdmission.getPatient().getName()) - ? newAdmission.getPatient().getFirstName() + ' ' + newAdmission.getPatient().getSecondName() - : newAdmission.getPatient().getName(); + ? newAdmission.getPatient().getFirstName() + ' ' + newAdmission.getPatient().getSecondName() + : newAdmission.getPatient().getName(); LOGGER.info("Create admission for patient {}", name); int aId = admissionManager.newAdmissionReturnKey(newAdmission); if (aId > 0) { newAdmission.setId(aId); } - AdmissionDTO admDTO = admissionMapper.map2DTO(newAdmission); - return ResponseEntity.status(HttpStatus.CREATED).body(admDTO); + + return admissionMapper.map2DTO(newAdmission); } @ExceptionHandler @@ -541,24 +529,26 @@ public void handle(HttpMessageNotReadableException e) { /** * Updates the specified {@link Admission} object. - * - * @param updateAdmissionDTO + * + * @param updateAdmissionDTO Admission payload * @return {@code true} if has been updated, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to update admission */ - @PutMapping(value = "/admissions", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity updateAdmissions(@RequestBody AdmissionDTO updateAdmissionDTO) throws OHServiceException { - + @PutMapping("/admissions") + public AdmissionDTO updateAdmissions( + @RequestBody AdmissionDTO updateAdmissionDTO + ) throws OHServiceException { Admission old = admissionManager.getAdmission(updateAdmissionDTO.getId()); if (old == null) { throw new OHAPIException(new OHExceptionMessage("Admission not found.")); } + Admission updateAdmission = admissionMapper.map2Model(updateAdmissionDTO); if (updateAdmissionDTO.getWard() != null && updateAdmissionDTO.getWard().getCode() != null - && !updateAdmissionDTO.getWard().getCode().trim().isEmpty()) { + && !updateAdmissionDTO.getWard().getCode().trim().isEmpty()) { List wards = wardManager.getWards().stream() - .filter(w -> w.getCode().equals(updateAdmissionDTO.getWard().getCode())).collect(Collectors.toList()); + .filter(w -> w.getCode().equals(updateAdmissionDTO.getWard().getCode())).toList(); if (wards.isEmpty()) { throw new OHAPIException(new OHExceptionMessage("Ward not found.")); } @@ -568,10 +558,9 @@ ResponseEntity updateAdmissions(@RequestBody AdmissionDTO updateAd } if (updateAdmissionDTO.getAdmType() != null && updateAdmissionDTO.getAdmType().getCode() != null - && !updateAdmissionDTO.getAdmType().getCode().trim().isEmpty()) { + && !updateAdmissionDTO.getAdmType().getCode().trim().isEmpty()) { List types = admissionManager.getAdmissionType().stream() - .filter(admt -> admt.getCode().equals(updateAdmissionDTO.getAdmType().getCode())) - .collect(Collectors.toList()); + .filter(admissionType -> admissionType.getCode().equals(updateAdmissionDTO.getAdmType().getCode())).toList(); if (types.isEmpty()) { throw new OHAPIException(new OHExceptionMessage("Admission type not found.")); } @@ -592,8 +581,7 @@ ResponseEntity updateAdmissions(@RequestBody AdmissionDTO updateAd List diseases = diseaseManager.getDiseaseAll(); if (updateAdmissionDTO.getDiseaseIn() != null && updateAdmissionDTO.getDiseaseIn().getCode() != null) { List dIns = diseases.stream() - .filter(d -> d.getCode().equals(updateAdmissionDTO.getDiseaseIn().getCode())) - .collect(Collectors.toList()); + .filter(d -> d.getCode().equals(updateAdmissionDTO.getDiseaseIn().getCode())).toList(); if (dIns.isEmpty()) { throw new OHAPIException(new OHExceptionMessage("Disease in not found.")); } @@ -602,8 +590,7 @@ ResponseEntity updateAdmissions(@RequestBody AdmissionDTO updateAd if (updateAdmissionDTO.getDiseaseOut1() != null && updateAdmissionDTO.getDiseaseOut1().getCode() != null) { List dOut1s = diseases.stream() - .filter(d -> d.getCode().equals(updateAdmissionDTO.getDiseaseOut1().getCode())) - .collect(Collectors.toList()); + .filter(d -> d.getCode().equals(updateAdmissionDTO.getDiseaseOut1().getCode())).toList(); if (dOut1s.isEmpty()) { throw new OHAPIException(new OHExceptionMessage("Disease out 1 not found.")); } @@ -612,8 +599,7 @@ ResponseEntity updateAdmissions(@RequestBody AdmissionDTO updateAd if (updateAdmissionDTO.getDiseaseOut2() != null && updateAdmissionDTO.getDiseaseOut2().getCode() != null) { List dOut2s = diseases.stream() - .filter(d -> d.getCode().equals(updateAdmissionDTO.getDiseaseOut2().getCode())) - .collect(Collectors.toList()); + .filter(d -> d.getCode().equals(updateAdmissionDTO.getDiseaseOut2().getCode())).toList(); if (dOut2s.isEmpty()) { throw new OHAPIException(new OHExceptionMessage("Disease out 2 not found.")); } @@ -622,8 +608,7 @@ ResponseEntity updateAdmissions(@RequestBody AdmissionDTO updateAd if (updateAdmissionDTO.getDiseaseOut3() != null && updateAdmissionDTO.getDiseaseOut3().getCode() != null) { List dOut3s = diseases.stream() - .filter(d -> d.getCode().equals(updateAdmissionDTO.getDiseaseOut3().getCode())) - .collect(Collectors.toList()); + .filter(d -> d.getCode().equals(updateAdmissionDTO.getDiseaseOut3().getCode())).toList(); if (dOut3s.isEmpty()) { throw new OHAPIException(new OHExceptionMessage("Disease out 3 not found.")); } @@ -631,11 +616,10 @@ ResponseEntity updateAdmissions(@RequestBody AdmissionDTO updateAd } if (updateAdmissionDTO.getDisType() != null && updateAdmissionDTO.getDisType().getCode() != null - && !updateAdmissionDTO.getDisType().getCode().trim().isEmpty()) { + && !updateAdmissionDTO.getDisType().getCode().trim().isEmpty()) { List disTypes = admissionManager.getDischargeType(); List disTypesF = disTypes.stream() - .filter(dtp -> dtp.getCode().equals(updateAdmissionDTO.getDisType().getCode())) - .collect(Collectors.toList()); + .filter(dtp -> dtp.getCode().equals(updateAdmissionDTO.getDisType().getCode())).toList(); if (disTypesF.isEmpty()) { throw new OHAPIException(new OHExceptionMessage("Discharge type not found.")); } @@ -643,52 +627,61 @@ ResponseEntity updateAdmissions(@RequestBody AdmissionDTO updateAd } if (updateAdmissionDTO.getPregTreatmentType() != null && updateAdmissionDTO.getPregTreatmentType().getCode() != null - && !updateAdmissionDTO.getPregTreatmentType().getCode().trim().isEmpty()) { - List pregTTypes = pregTraitTypeManager.getPregnantTreatmentType(); - List pregTTypesF = pregTTypes.stream() - .filter(pregtt -> pregtt.getCode().equals(updateAdmissionDTO.getPregTreatmentType().getCode())) - .collect(Collectors.toList()); - if (pregTTypesF.isEmpty()) { + && !updateAdmissionDTO.getPregTreatmentType().getCode().trim().isEmpty()) { + List pregnancyTreatmentTypes = pregnantTreatmentTypeBrowserManager.getPregnantTreatmentType(); + List pregnancyTreatmentTypesFound = pregnancyTreatmentTypes + .stream() + .filter(pregnantTreatmentType -> pregnantTreatmentType.getCode().equals(updateAdmissionDTO.getPregTreatmentType().getCode())) + .toList(); + + if (pregnancyTreatmentTypesFound.isEmpty()) { throw new OHAPIException(new OHExceptionMessage("Pregnant treatment type not found.")); } - updateAdmission.setPregTreatmentType(pregTTypesF.get(0)); + + updateAdmission.setPregTreatmentType(pregnancyTreatmentTypesFound.get(0)); } if (updateAdmissionDTO.getDeliveryType() != null && updateAdmissionDTO.getDeliveryType().getCode() != null - && !updateAdmissionDTO.getDeliveryType().getCode().trim().isEmpty()) { - List dlvrTypes = dlvrTypeManager.getDeliveryType(); - List dlvrTypesF = dlvrTypes.stream() - .filter(dlvrType -> dlvrType.getCode().equals(updateAdmissionDTO.getDeliveryType().getCode())) - .collect(Collectors.toList()); - if (dlvrTypesF.isEmpty()) { + && !updateAdmissionDTO.getDeliveryType().getCode().trim().isEmpty()) { + List deliveryTypes = deliveryTypeBrowserManager.getDeliveryType(); + List deliveryTypesFound = deliveryTypes + .stream() + .filter(deliveryType -> deliveryType.getCode().equals(updateAdmissionDTO.getDeliveryType().getCode())) + .toList(); + + if (deliveryTypesFound.isEmpty()) { throw new OHAPIException(new OHExceptionMessage("Delivery type not found.")); } - updateAdmission.setDeliveryType(dlvrTypesF.get(0)); + + updateAdmission.setDeliveryType(deliveryTypesFound.get(0)); } if (updateAdmissionDTO.getDeliveryResult() != null && updateAdmissionDTO.getDeliveryResult().getCode() != null - && !updateAdmissionDTO.getDeliveryResult().getCode().trim().isEmpty()) { - List dlvrrestTypes = dlvrrestTypeManager.getDeliveryResultType(); - List dlvrrestTypesF = dlvrrestTypes.stream().filter( - dlvrrestType -> dlvrrestType.getCode().equals(updateAdmissionDTO.getDeliveryResult().getCode())) - .collect(Collectors.toList()); - if (dlvrrestTypesF.isEmpty()) { + && !updateAdmissionDTO.getDeliveryResult().getCode().trim().isEmpty()) { + List deliveryResultTypes = deliveryResultTypeBrowserManager.getDeliveryResultType(); + List deliveryResultTypesFound = deliveryResultTypes + .stream() + .filter(deliveryResultType -> deliveryResultType.getCode().equals(updateAdmissionDTO.getDeliveryResult().getCode())) + .toList(); + + if (deliveryResultTypesFound.isEmpty()) { throw new OHAPIException(new OHExceptionMessage("Delivery result type not found.")); } - updateAdmission.setDeliveryResult(dlvrrestTypesF.get(0)); + + updateAdmission.setDeliveryResult(deliveryResultTypesFound.get(0)); } String name = StringUtils.hasLength(updateAdmission.getPatient().getName()) - ? updateAdmission.getPatient().getFirstName() + ' ' + updateAdmission.getPatient().getSecondName() - : updateAdmission.getPatient().getName(); + ? updateAdmission.getPatient().getFirstName() + ' ' + updateAdmission.getPatient().getSecondName() + : updateAdmission.getPatient().getName(); LOGGER.info("update admission for patient {}", name); + Admission isUpdatedAdmission = admissionManager.updateAdmission(updateAdmission); + if (isUpdatedAdmission == null) { throw new OHAPIException(new OHExceptionMessage("Admission not updated.")); } - AdmissionDTO admDTO = admissionMapper.map2DTO(isUpdatedAdmission); - return ResponseEntity.ok(admDTO); + return admissionMapper.map2DTO(isUpdatedAdmission); } - } diff --git a/src/main/java/org/isf/admtype/rest/AdmissionTypeController.java b/src/main/java/org/isf/admtype/rest/AdmissionTypeController.java index 7d4af9a8b..dd4fd0535 100644 --- a/src/main/java/org/isf/admtype/rest/AdmissionTypeController.java +++ b/src/main/java/org/isf/admtype/rest/AdmissionTypeController.java @@ -22,7 +22,6 @@ package org.isf.admtype.rest; import java.util.List; -import java.util.stream.Collectors; import org.isf.admtype.dto.AdmissionTypeDTO; import org.isf.admtype.manager.AdmissionTypeBrowserManager; @@ -33,120 +32,123 @@ import org.isf.utils.exception.model.OHExceptionMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/admissiontypes") +@RestController() @Tag(name = "AdmissionTypes") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class AdmissionTypeController { private static final Logger LOGGER = LoggerFactory.getLogger(AdmissionTypeController.class); - @Autowired - protected AdmissionTypeBrowserManager admtManager; + private final AdmissionTypeBrowserManager admissionTypeManager; - @Autowired - protected AdmissionTypeMapper mapper; + private final AdmissionTypeMapper mapper; - public AdmissionTypeController(AdmissionTypeBrowserManager admtManager, AdmissionTypeMapper admissionTypemapper) { - this.admtManager = admtManager; + public AdmissionTypeController( + AdmissionTypeBrowserManager admissionTypeBrowserManager, AdmissionTypeMapper admissionTypemapper + ) { + this.admissionTypeManager = admissionTypeBrowserManager; this.mapper = admissionTypemapper; } /** * Create a new {@link AdmissionType} - * - * @param admissionTypeDTO + * + * @param admissionTypeDTO Admission Type payload * @return {@code true} if the admission type has been stored, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to create admission type */ - @PostMapping(value = "/admissiontypes", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity newAdmissionType(@RequestBody AdmissionTypeDTO admissionTypeDTO) throws OHServiceException { + @PostMapping(value = "/admissiontypes") + @ResponseStatus(HttpStatus.CREATED) + public AdmissionTypeDTO newAdmissionType(@RequestBody AdmissionTypeDTO admissionTypeDTO) throws OHServiceException { String code = admissionTypeDTO.getCode(); + LOGGER.info("Create Admission Type {}", code); - AdmissionType newAdmissionType = admtManager.newAdmissionType(mapper.map2Model(admissionTypeDTO)); - if (!admtManager.isCodePresent(code)) { + + AdmissionType newAdmissionType = admissionTypeManager.newAdmissionType(mapper.map2Model(admissionTypeDTO)); + if (!admissionTypeManager.isCodePresent(code)) { throw new OHAPIException(new OHExceptionMessage("Admission Type is not created."), HttpStatus.INTERNAL_SERVER_ERROR); } - return ResponseEntity.status(HttpStatus.CREATED).body(mapper.map2DTO(newAdmissionType)); + + return mapper.map2DTO(newAdmissionType); } /** * Updates the specified {@link AdmissionType}. - * - * @param admissionTypeDTO + * + * @param admissionTypeDTO Admission Type payload * @return {@code true} if the admission type has been updated, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to update the admission type */ - @PutMapping(value = "/admissiontypes", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity updateAdmissionTypes(@RequestBody AdmissionTypeDTO admissionTypeDTO) - throws OHServiceException { - LOGGER.info("Update admissiontypes code: {}", admissionTypeDTO.getCode()); - AdmissionType admt = mapper.map2Model(admissionTypeDTO); - if (!admtManager.isCodePresent(admt.getCode())) { + @PutMapping(value = "/admissiontypes") + public AdmissionTypeDTO updateAdmissionTypes( + @RequestBody AdmissionTypeDTO admissionTypeDTO + ) throws OHServiceException { + LOGGER.info("Update admission types code: {}", admissionTypeDTO.getCode()); + + AdmissionType admissionType = mapper.map2Model(admissionTypeDTO); + if (!admissionTypeManager.isCodePresent(admissionType.getCode())) { throw new OHAPIException(new OHExceptionMessage("Admission Type not found.")); } - AdmissionType updatedAdmissionType = admtManager.updateAdmissionType(admt); - return ResponseEntity.ok(mapper.map2DTO(updatedAdmissionType)); + + return mapper.map2DTO(admissionTypeManager.updateAdmissionType(admissionType)); } /** * Get all the available {@link AdmissionType}s. - * + * * @return a {@link List} of {@link AdmissionType} or NO_CONTENT if there is no data found. - * @throws OHServiceException + * @throws OHServiceException When failed to get admission types */ - @GetMapping(value = "/admissiontypes", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getAdmissionTypes() throws OHServiceException { + @GetMapping(value = "/admissiontypes") + public List getAdmissionTypes() throws OHServiceException { LOGGER.info("Get all Admission Types "); - List admissionTypes = admtManager.getAdmissionType(); - List admissionTypeDTOs = mapper.map2DTOList(admissionTypes); - if (admissionTypeDTOs.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(admissionTypeDTOs); - } else { - return ResponseEntity.ok(admissionTypeDTOs); - } + + return mapper.map2DTOList(admissionTypeManager.getAdmissionType()); } /** * Delete {@link AdmissionType} for specified code. - * - * @param code + * + * @param code Admission Type Code * @return {@code true} if the {@link AdmissionType} has been deleted, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to delete admission type */ @DeleteMapping(value = "/admissiontypes/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity deleteAdmissionType(@PathVariable("code") String code) throws OHServiceException { + public boolean deleteAdmissionType(@PathVariable("code") String code) throws OHServiceException { LOGGER.info("Delete Admission Type code: {}", code); - if (admtManager.isCodePresent(code)) { - List admissionTypes = admtManager.getAdmissionType(); - List admtFounds = admissionTypes.stream().filter(ad -> ad.getCode().equals(code)) - .collect(Collectors.toList()); - if (!admtFounds.isEmpty()) { - try { - admtManager.deleteAdmissionType(admtFounds.get(0)); - } catch (OHServiceException serviceException) { - LOGGER.error("Delete Admission: {} failed.", code); - throw new OHAPIException(new OHExceptionMessage("Admission not deleted.")); - } + + if (!admissionTypeManager.isCodePresent(code)) { + throw new OHAPIException(new OHExceptionMessage("Admission type not found with ID :" + code), HttpStatus.NOT_FOUND); + } + + List admissionTypes = admissionTypeManager.getAdmissionType(); + List admissionTypesFound = admissionTypes.stream().filter(ad -> ad.getCode().equals(code)).toList(); + + if (!admissionTypesFound.isEmpty()) { + try { + admissionTypeManager.deleteAdmissionType(admissionTypesFound.get(0)); + } catch (OHServiceException serviceException) { + LOGGER.error("Delete Admission: {} failed.", code); + throw new OHAPIException(new OHExceptionMessage("Admission not deleted.")); } - } else { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); } - return ResponseEntity.ok(true); - } + return true; + } } diff --git a/src/main/java/org/isf/agetype/rest/AgeTypeController.java b/src/main/java/org/isf/agetype/rest/AgeTypeController.java index 9d0f96d15..c5fc70da7 100644 --- a/src/main/java/org/isf/agetype/rest/AgeTypeController.java +++ b/src/main/java/org/isf/agetype/rest/AgeTypeController.java @@ -37,115 +37,113 @@ import org.isf.utils.exception.model.OHExceptionMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/agetypes") +@RestController @Tag(name = "AgeTypes") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class AgeTypeController { private static final Logger LOGGER = LoggerFactory.getLogger(AgeTypeController.class); - @Autowired - private AgeTypeBrowserManager ageTypeManager; - - @Autowired - private AgeTypeMapper mapper; - + private final AgeTypeBrowserManager ageTypeManager; + + private final AgeTypeMapper mapper; + public AgeTypeController(AgeTypeBrowserManager ageTypeManager, AgeTypeMapper ageTypeMapper) { this.ageTypeManager = ageTypeManager; this.mapper = ageTypeMapper; } - + /** * Get all the age types stored + * * @return the list of age types found - * @throws OHServiceException + * @throws OHServiceException When failed to get age types */ - @GetMapping(value = "/agetypes", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getAllAgeTypes() throws OHServiceException { + @GetMapping(value = "/agetypes") + public List getAllAgeTypes() throws OHServiceException { LOGGER.info("Get age types"); - List results = ageTypeManager.getAgeType(); - List parsedResults = mapper.map2DTOList(results); - if (!parsedResults.isEmpty()) { - return ResponseEntity.ok(parsedResults); - } else { - LOGGER.info("Empty age types list"); - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(parsedResults); - } + + return mapper.map2DTOList(ageTypeManager.getAgeType()); } - + /** * Update an age type * @param ageTypeDTO - the age type to be updated * @return {@link AgeTypeDTO} the updated age type - * @throws OHServiceException + * @throws OHServiceException When failed to update age type */ - @PutMapping(value = "/agetypes", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity updateAgeType(@Valid @RequestBody AgeTypeDTO ageTypeDTO) throws OHServiceException { + @PutMapping(value = "/agetypes") + public AgeTypeDTO updateAgeType(@Valid @RequestBody AgeTypeDTO ageTypeDTO) throws OHServiceException { if (ageTypeDTO.getCode() == null || ageTypeDTO.getCode().trim().isEmpty()) { throw new OHAPIException(new OHExceptionMessage("The age type is not valid.")); } + LOGGER.info("Update age type"); + AgeType ageType = mapper.map2Model(ageTypeDTO); List ageTypes = new ArrayList<>(); ageTypes.add(ageType); + try { ageTypeManager.updateAgeType(ageTypes); - return ResponseEntity.ok(ageTypeDTO); + return ageTypeDTO; } catch (OHServiceException ex) { throw new OHAPIException(new OHExceptionMessage("The age type is not updated."), HttpStatus.INTERNAL_SERVER_ERROR); } } - + /** * Get the code of an age type whose ages range includes a given age * @param age - the given age * @return the code of the age type matching the given age - * @throws OHServiceException + * @throws OHServiceException When failed to get age type */ - @GetMapping(value = "/agetypes/code", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getAgeTypeCodeByAge(@RequestParam("age") int age) throws OHServiceException { + @GetMapping(value = "/agetypes/code") + public Map getAgeTypeCodeByAge(@RequestParam("age") int age) throws OHServiceException { LOGGER.info("Get age type by age: {}", age); + String result = ageTypeManager.getTypeByAge(age); Map responseBody = new HashMap<>(); + if (result != null){ responseBody.put("code", result); - return ResponseEntity.ok(responseBody); - } else { - LOGGER.info("No corresponding age code for the given age"); - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(responseBody); - } + } else { + LOGGER.info("No corresponding age code for the given age"); + } + + return responseBody; } - + /** * Gets the {@link AgeType} from the code index. * @param index the code index. * @return the retrieved element. - * @throws OHServiceException + * @throws OHServiceException When failed to get age type */ - @GetMapping(value = "/agetypes/{index}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getAgeTypeByIndex(@PathVariable int index) throws OHServiceException { + @GetMapping(value = "/agetypes/{index}") + public AgeTypeDTO getAgeTypeByIndex(@PathVariable int index) throws OHServiceException { LOGGER.info("Get age type by index: {}", index); AgeType result = ageTypeManager.getTypeByCode(index); - if (result != null){ - return ResponseEntity.ok(mapper.map2DTO(result)); - } else { - LOGGER.info("No corresponding age code for the given index"); - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } + + if (result == null){ + LOGGER.info("No corresponding age code for the given index"); + throw new OHAPIException(new OHExceptionMessage("Age type not found with index :" + index), HttpStatus.NOT_FOUND); + } + + return mapper.map2DTO(result); } - } diff --git a/src/main/java/org/isf/disctype/rest/DischargeTypeController.java b/src/main/java/org/isf/disctype/rest/DischargeTypeController.java index 3283ccbae..a21101444 100644 --- a/src/main/java/org/isf/disctype/rest/DischargeTypeController.java +++ b/src/main/java/org/isf/disctype/rest/DischargeTypeController.java @@ -22,7 +22,6 @@ package org.isf.disctype.rest; import java.util.List; -import java.util.stream.Collectors; import org.isf.disctype.dto.DischargeTypeDTO; import org.isf.disctype.manager.DischargeTypeBrowserManager; @@ -33,33 +32,32 @@ import org.isf.utils.exception.model.OHExceptionMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/dischargetype") +@RestController @Tag(name = "DischargeType") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class DischargeTypeController { private static final Logger LOGGER = LoggerFactory.getLogger(DischargeTypeController.class); - @Autowired - protected DischargeTypeBrowserManager discTypeManager; + private final DischargeTypeBrowserManager discTypeManager; - @Autowired - protected DischargeTypeMapper mapper; + private final DischargeTypeMapper mapper; public DischargeTypeController(DischargeTypeBrowserManager discTypeManager, DischargeTypeMapper dischargeTypemapper) { this.discTypeManager = discTypeManager; @@ -68,87 +66,91 @@ public DischargeTypeController(DischargeTypeBrowserManager discTypeManager, Disc /** * Create a new {@link DischargeType} - * - * @param dischTypeDTO + * + * @param dischargeTypeDTO Discharge Type payload * @return {@code true} if the {@link DischargeType} has been stored, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to create discharge type */ - @PostMapping(value = "/dischargetypes", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity newDischargeType(@RequestBody DischargeTypeDTO dischTypeDTO) throws OHServiceException { - String code = dischTypeDTO.getCode(); + @PostMapping(value = "/dischargetypes") + @ResponseStatus(HttpStatus.CREATED) + public DischargeTypeDTO newDischargeType(@RequestBody DischargeTypeDTO dischargeTypeDTO) throws OHServiceException { + String code = dischargeTypeDTO.getCode(); LOGGER.info("Create discharge type {}", code); - DischargeType newDischargeType = discTypeManager.newDischargeType(mapper.map2Model(dischTypeDTO)); + + DischargeType newDischargeType = discTypeManager.newDischargeType(mapper.map2Model(dischargeTypeDTO)); if (!discTypeManager.isCodePresent(code)) { throw new OHAPIException(new OHExceptionMessage("Discharge Type is not created."), HttpStatus.INTERNAL_SERVER_ERROR); } - return ResponseEntity.status(HttpStatus.CREATED).body(mapper.map2DTO(newDischargeType)); + + return mapper.map2DTO(newDischargeType); } /** * Update the specified {@link DischargeType} - * - * @param dischTypeDTO + * + * @param dischargeTypeDTO Discharge type payload * @return {@code true} if the {@link DischargeType} has been updated, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to update discharge type */ @PutMapping(value = "/dischargetypes", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity updateDischargeTypet(@RequestBody DischargeTypeDTO dischTypeDTO) throws OHServiceException { - LOGGER.info("Update discharge type with code: {}", dischTypeDTO.getCode()); - DischargeType dischType = mapper.map2Model(dischTypeDTO); - if (!discTypeManager.isCodePresent(dischTypeDTO.getCode())) { + public DischargeTypeDTO updateDischargeType( + @RequestBody DischargeTypeDTO dischargeTypeDTO + ) throws OHServiceException { + LOGGER.info("Update discharge type with code: {}", dischargeTypeDTO.getCode()); + + DischargeType dischargeType = mapper.map2Model(dischargeTypeDTO); + if (!discTypeManager.isCodePresent(dischargeTypeDTO.getCode())) { throw new OHAPIException(new OHExceptionMessage("Discharge Type not found.")); } - DischargeType updatedDischargeType = discTypeManager.updateDischargeType(dischType); + + DischargeType updatedDischargeType = discTypeManager.updateDischargeType(dischargeType); if (!discTypeManager.isCodePresent(updatedDischargeType.getCode())) { throw new OHAPIException(new OHExceptionMessage("Discharge Type is not updated."), HttpStatus.INTERNAL_SERVER_ERROR); } - return ResponseEntity.ok(mapper.map2DTO(dischType)); + + return mapper.map2DTO(dischargeType); } /** * Get all the available {@link DischargeType}s - * + * * @return a {@link List} of {@link DischargeType} or NO_CONTENT if there is no data found. - * @throws OHServiceException + * @throws OHServiceException When failed to get discharge types */ - @GetMapping(value = "/dischargetypes", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getDischargeTypes() throws OHServiceException { + @GetMapping(value = "/dischargetypes") + public List getDischargeTypes() throws OHServiceException { LOGGER.info("Get all discharge types "); - List dischTypes = discTypeManager.getDischargeType(); - List dischTypeDTOs = mapper.map2DTOList(dischTypes); - if (dischTypeDTOs.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(dischTypeDTOs); - } else { - return ResponseEntity.ok(dischTypeDTOs); - } + + return mapper.map2DTOList(discTypeManager.getDischargeType()); } /** * Delete {@link DischargeType} for the specified code. - * - * @param code + * + * @param code Discharge type code * @return {@code true} if the {@link DischargeType} has been deleted, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to delete discharge type */ - @DeleteMapping(value = "/dischargetypes/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity deleteDischargeType(@PathVariable("code") String code) throws OHServiceException { + @DeleteMapping(value = "/dischargetypes/{code}") + public boolean deleteDischargeType(@PathVariable("code") String code) throws OHServiceException { LOGGER.info("Delete discharge type code: {}", code); - if (discTypeManager.isCodePresent(code)) { - List dischTypes = discTypeManager.getDischargeType(); - List dischTypeFounds = dischTypes.stream().filter(ad -> ad.getCode().equals(code)) - .collect(Collectors.toList()); - if (!dischTypeFounds.isEmpty()) { - try { - discTypeManager.deleteDischargeType(dischTypeFounds.get(0)); - } catch (OHServiceException serviceException) { - LOGGER.error("Delete discharge type: {} failed.", code); - throw new OHAPIException(new OHExceptionMessage("Discharge type not deleted.")); - } + + if (!discTypeManager.isCodePresent(code)) { + throw new OHAPIException(new OHExceptionMessage("Discharge type not found with code :" + code), HttpStatus.NOT_FOUND); + } + + List dischargeTypes = discTypeManager.getDischargeType(); + List dischargeTypeFounds = dischargeTypes.stream().filter(ad -> ad.getCode().equals(code)).toList(); + + if (!dischargeTypeFounds.isEmpty()) { + try { + discTypeManager.deleteDischargeType(dischargeTypeFounds.get(0)); + } catch (OHServiceException serviceException) { + LOGGER.error("Delete discharge type: {} failed.", code); + throw new OHAPIException(new OHExceptionMessage("Discharge type not deleted.")); } - } else { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); } - return ResponseEntity.ok(true); - } + return true; + } } diff --git a/src/main/java/org/isf/disease/rest/DiseaseController.java b/src/main/java/org/isf/disease/rest/DiseaseController.java index c4ae29b52..164397cf0 100644 --- a/src/main/java/org/isf/disease/rest/DiseaseController.java +++ b/src/main/java/org/isf/disease/rest/DiseaseController.java @@ -21,9 +21,7 @@ */ package org.isf.disease.rest; -import java.util.HashMap; import java.util.List; -import java.util.Map; import jakarta.validation.Valid; @@ -36,282 +34,289 @@ import org.isf.utils.exception.model.OHExceptionMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/diseases") +@RestController @Tag(name = "Diseases") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class DiseaseController { private static final Logger LOGGER = LoggerFactory.getLogger(DiseaseController.class); - @Autowired - protected DiseaseBrowserManager diseaseManager; - - @Autowired - protected DiseaseMapper mapper; + private final DiseaseBrowserManager diseaseManager; + + private final DiseaseMapper mapper; public DiseaseController(DiseaseBrowserManager diseaseManager, DiseaseMapper diseaseMapper) { this.diseaseManager = diseaseManager; this.mapper = diseaseMapper; } - + /** * Gets all the stored {@link Disease} with ODP flag {@code true}. * @return the stored diseases with ODP flag true. - * @throws OHServiceException + * @throws OHServiceException When failed to get opd diseases */ - @GetMapping(value = "/diseases/opd", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getDiseasesOpd() throws OHServiceException { - LOGGER.info("Get opd diseases"); - List diseases = diseaseManager.getDiseaseOpd(); - if (diseases != null) { - return computeResponse(diseases); - } else { - throw new OHAPIException(new OHExceptionMessage("Error getting OPO diseases."), HttpStatus.INTERNAL_SERVER_ERROR); - } + @GetMapping(value = "/diseases/opd") + public List getDiseasesOpd() throws OHServiceException { + LOGGER.info("Get opd diseases"); + List diseases = diseaseManager.getDiseaseOpd(); + if (diseases == null) { + throw new OHAPIException(new OHExceptionMessage("Error getting OPD diseases."), HttpStatus.INTERNAL_SERVER_ERROR); + } + + return mapper.map2DTOList(diseases); } - + /** - * Gets all the stored {@link Disease} with the specified typecode and flag ODP true. - * @param typeCode - the filter typecode. + * Gets all the stored {@link Disease} with the specified type code and flag ODP true. + * @param typeCode - the filter type code. * @return the retrieved diseases. - * @throws OHServiceException + * @throws OHServiceException When failed to get diseases */ - @GetMapping(value = "/diseases/opd/{typecode}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getDiseasesOpdByCode(@PathVariable("typecode") String typeCode) throws OHServiceException { - LOGGER.info("Get opd diseases by type code"); - List diseases = diseaseManager.getDiseaseOpd(typeCode); - if (diseases != null) { - return computeResponse(diseases); - } else { - throw new OHAPIException(new OHExceptionMessage("Error getting OPD diseases."), HttpStatus.INTERNAL_SERVER_ERROR); - } + @GetMapping(value = "/diseases/opd/{typecode}") + public List getDiseasesOpdByCode( + @PathVariable("typecode") String typeCode + ) throws OHServiceException { + LOGGER.info("Get opd diseases by type code"); + + List diseases = diseaseManager.getDiseaseOpd(typeCode); + if (diseases == null) { + throw new OHAPIException(new OHExceptionMessage("Error getting OPD diseases."), HttpStatus.INTERNAL_SERVER_ERROR); + } + + return mapper.map2DTOList(diseases); } - + /** * Gets all the stored {@link Disease} with IPD_OUT flag {@code true}. * @return the stored disease with IPD flag {@code true}. - * @throws OHServiceException + * @throws OHServiceException When failed to IPD diseases */ - @GetMapping(value = "/diseases/ipd/out", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getDiseasesIpdOut() throws OHServiceException { - LOGGER.info("Get ipd out diseases"); - List diseases = diseaseManager.getDiseaseIpdOut(); - if (diseases != null) { - return computeResponse(diseases); - } else { - throw new OHAPIException(new OHExceptionMessage("Error getting IPD out diseases."), HttpStatus.INTERNAL_SERVER_ERROR); - } + @GetMapping(value = "/diseases/ipd/out") + public List getDiseasesIpdOut() throws OHServiceException { + LOGGER.info("Get ipd out diseases"); + + List diseases = diseaseManager.getDiseaseIpdOut(); + if (diseases == null) { + throw new OHAPIException(new OHExceptionMessage("Error getting IPD out diseases."), HttpStatus.INTERNAL_SERVER_ERROR); + } + + return mapper.map2DTOList(diseases); } - + /** * Gets all the stored {@link Disease} with the specified typecode and the flag IPD_OUT {@code true}. * @param typeCode - the filter typecode. * @return the retrieved diseases. - * @throws OHServiceException + * @throws OHServiceException When failed to get IPD diseases */ - @GetMapping(value = "/diseases/ipd/out/{typecode}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getDiseasesIpdOutByCode(@PathVariable("typecode") String typeCode) throws OHServiceException { - LOGGER.info("Get ipd out diseases by type code"); - List diseases = diseaseManager.getDiseaseIpdOut(typeCode); - if (diseases != null) { - return computeResponse(diseases); - } else { - throw new OHAPIException(new OHExceptionMessage("Error getting IPD out diseases."), HttpStatus.INTERNAL_SERVER_ERROR); - } + @GetMapping(value = "/diseases/ipd/out/{typecode}") + public List getDiseasesIpdOutByCode( + @PathVariable("typecode") String typeCode + ) throws OHServiceException { + LOGGER.info("Get ipd out diseases by type code"); + + List diseases = diseaseManager.getDiseaseIpdOut(typeCode); + if (diseases == null) { + throw new OHAPIException(new OHExceptionMessage("Error getting IPD out diseases."), HttpStatus.INTERNAL_SERVER_ERROR); + } + + return mapper.map2DTOList(diseases); } - + /** * Gets all the stored {@link Disease} with IPD_IN flag {@code true}. * @return the stored disease with IPD flag {@code true}. - * @throws OHServiceException + * @throws OHServiceException When failed to get IPD diseases */ - @GetMapping(value = "/diseases/ipd/in", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getDiseasesIpdIn() throws OHServiceException { - LOGGER.info("Get ipd-in diseases"); - List diseases = diseaseManager.getDiseaseIpdIn(); - if (diseases != null) { - return computeResponse(diseases); - } else { - throw new OHAPIException(new OHExceptionMessage("Error getting IPD-in diseases."), HttpStatus.INTERNAL_SERVER_ERROR); - } + @GetMapping(value = "/diseases/ipd/in") + public List getDiseasesIpdIn() throws OHServiceException { + LOGGER.info("Get ipd-in diseases"); + List diseases = diseaseManager.getDiseaseIpdIn(); + if (diseases == null) { + throw new OHAPIException(new OHExceptionMessage("Error getting IPD-in diseases."), HttpStatus.INTERNAL_SERVER_ERROR); + } + + return mapper.map2DTOList(diseases); } - + /** * Gets all the stored {@link Disease} with the specified typecode and the flag IPD_IN {@code true}. * @param typeCode - the filter typecode. * @return the retrieved diseases. - * @throws OHServiceException + * @throws OHServiceException When failed to get IPD diseases */ - @GetMapping(value = "/diseases/ipd/in/{typecode}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getDiseasesIpdInByCode(@PathVariable("typecode") String typeCode) throws OHServiceException { - LOGGER.info("Get ipd-in diseases by type code"); - List diseases = diseaseManager.getDiseaseIpdIn(typeCode); - if (diseases != null) { - return computeResponse(diseases); - } else { - throw new OHAPIException(new OHExceptionMessage("Error getting IPD-in diseases."), HttpStatus.INTERNAL_SERVER_ERROR); - } + @GetMapping(value = "/diseases/ipd/in/{typecode}") + public List getDiseasesIpdInByCode( + @PathVariable("typecode") String typeCode + ) throws OHServiceException { + LOGGER.info("Get ipd-in diseases by type code"); + + List diseases = diseaseManager.getDiseaseIpdIn(typeCode); + if (diseases == null) { + throw new OHAPIException(new OHExceptionMessage("Error getting IPD-in diseases."), HttpStatus.INTERNAL_SERVER_ERROR); + } + + return mapper.map2DTOList(diseases); } - + /** * Gets both OPD and IPDs diseases. * @return the stored diseases. - * @throws OHServiceException + * @throws OHServiceException When failed to get diseases */ - @GetMapping(value = "/diseases/both", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getDiseases() throws OHServiceException { - LOGGER.info("Get both ipd and opd diseases"); - List diseases = diseaseManager.getDisease(); - if (diseases != null) { - return computeResponse(diseases); - } else { - throw new OHAPIException(new OHExceptionMessage("Error getting diseases."), HttpStatus.INTERNAL_SERVER_ERROR); - } + @GetMapping(value = "/diseases/both") + public List getDiseases() throws OHServiceException { + LOGGER.info("Get both ipd and opd diseases"); + + List diseases = diseaseManager.getDisease(); + if (diseases == null) { + throw new OHAPIException(new OHExceptionMessage("Error getting diseases."), HttpStatus.INTERNAL_SERVER_ERROR); + } + + return mapper.map2DTOList(diseases); } - + /** * Retrieves all OPD and IPDs {@link Disease} with the specified typecode. * @param typeCode - the filter typecode. * @return all the diseases with the specified typecode. - * @throws OHServiceException + * @throws OHServiceException When failed to get diseases */ - @GetMapping(value = "/diseases/both/{typecode}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getDiseases(@PathVariable("typecode") String typeCode) throws OHServiceException { - LOGGER.info("Get both ipd and opd diseases by type code"); - List diseases = diseaseManager.getDisease(typeCode); - if (diseases != null) { - return computeResponse(diseases); - } else { - throw new OHAPIException(new OHExceptionMessage("Error getting diseases by type code."), HttpStatus.INTERNAL_SERVER_ERROR); - } + @GetMapping(value = "/diseases/both/{typecode}") + public List getDiseases(@PathVariable("typecode") String typeCode) throws OHServiceException { + LOGGER.info("Get both ipd and opd diseases by type code"); + List diseases = diseaseManager.getDisease(typeCode); + + if (diseases == null) { + throw new OHAPIException( + new OHExceptionMessage("Error getting diseases by type code."), HttpStatus.INTERNAL_SERVER_ERROR + ); + } + + return mapper.map2DTOList(diseases); } - + /** * Returns all diseases, deleted ones also * @return the stored diseases. - * @throws OHServiceException + * @throws OHServiceException When failed to get diseases */ - @GetMapping(value = "/diseases/all", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getAllDiseases() throws OHServiceException { - LOGGER.info("Get all diseases, deleted ones too"); - List diseases = diseaseManager.getDiseaseAll(); - if (diseases != null) { - return computeResponse(diseases); - } else { - throw new OHAPIException(new OHExceptionMessage("Error getting all diseases."), HttpStatus.INTERNAL_SERVER_ERROR); - } + @GetMapping(value = "/diseases/all") + public List getAllDiseases() throws OHServiceException { + LOGGER.info("Get all diseases, deleted ones too"); + + List diseases = diseaseManager.getDiseaseAll(); + if (diseases == null) { + throw new OHAPIException( + new OHExceptionMessage("Error getting all diseases."), HttpStatus.INTERNAL_SERVER_ERROR + ); + } + + return mapper.map2DTOList(diseases); } - + /** * Gets a {@link Disease} with the specified code. * @param code - the disease code. * @return the found disease. - * @throws OHServiceException + * @throws OHServiceException When failed to get the disease */ - @GetMapping(value = "/diseases/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getDiseaseByCode(@PathVariable("code") String code) throws OHServiceException { - LOGGER.info("Get disease by code"); - - Disease disease = diseaseManager.getDiseaseByCode(code); - if (disease != null) { - return ResponseEntity.ok(mapper.map2DTO(disease)); - } else { - throw new OHAPIException(new OHExceptionMessage("No disease found with the specified code."), HttpStatus.INTERNAL_SERVER_ERROR); - } + @GetMapping(value = "/diseases/{code}") + public DiseaseDTO getDiseaseByCode(@PathVariable("code") String code) throws OHServiceException { + LOGGER.info("Get disease by code"); + + Disease disease = diseaseManager.getDiseaseByCode(code); + if (disease == null) { + throw new OHAPIException( + new OHExceptionMessage("No disease found with the specified code."), HttpStatus.NOT_FOUND + ); + } + + return mapper.map2DTO(disease); } - + /** * Stores the specified {@link Disease}. * @param diseaseDTO - the disease to store. * @return the stored disease - * @throws OHServiceException + * @throws OHServiceException When failed to create the disease */ - @PostMapping(value = "/diseases", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity newDisease(@Valid @RequestBody DiseaseDTO diseaseDTO) throws OHServiceException { + @PostMapping(value = "/diseases") + @ResponseStatus(HttpStatus.CREATED) + public DiseaseDTO newDisease(@Valid @RequestBody DiseaseDTO diseaseDTO) throws OHServiceException { Disease disease = mapper.map2Model(diseaseDTO); + if (diseaseManager.isCodePresent(disease.getCode())) { - throw new OHAPIException(new OHExceptionMessage("Duplicated disease code."), HttpStatus.INTERNAL_SERVER_ERROR); + throw new OHAPIException(new OHExceptionMessage("Duplicated disease code.")); } + if (diseaseManager.descriptionControl(disease.getDescription(), disease.getType().getCode())) { - throw new OHAPIException(new OHExceptionMessage("Duplicated disease description for the same disease type."), - HttpStatus.INTERNAL_SERVER_ERROR); + throw new OHAPIException(new OHExceptionMessage("Duplicated disease description for the same disease type.")); } + try { - diseaseManager.newDisease(disease); - return ResponseEntity.status(HttpStatus.CREATED).body(diseaseDTO); + return mapper.map2DTO(diseaseManager.newDisease(disease)); } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Disease not created."), HttpStatus.INTERNAL_SERVER_ERROR); } } - + /** * Updates the specified {@link Disease}. * @param diseaseDTO - the disease to update. * @return the updated disease - * @throws OHServiceException + * @throws OHServiceException When failed to update the disease */ - @PutMapping(value="/diseases", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity updateDisease(@Valid @RequestBody DiseaseDTO diseaseDTO) throws OHServiceException { + @PutMapping(value="/diseases") + public DiseaseDTO updateDisease(@Valid @RequestBody DiseaseDTO diseaseDTO) throws OHServiceException { Disease disease = mapper.map2Model(diseaseDTO); if (!diseaseManager.isCodePresent(disease.getCode())) { - throw new OHAPIException(new OHExceptionMessage("Disease not found."), HttpStatus.INTERNAL_SERVER_ERROR); + throw new OHAPIException(new OHExceptionMessage("Disease not found."), HttpStatus.NOT_FOUND); } + disease.setLock(diseaseDTO.getLock()); try { - diseaseManager.updateDisease(disease); - return ResponseEntity.ok(diseaseDTO); + return mapper.map2DTO(diseaseManager.updateDisease(disease)); } catch (OHServiceException serviceException) { - throw new OHAPIException(new OHExceptionMessage("Disease not updated."), HttpStatus.INTERNAL_SERVER_ERROR); - } + throw new OHAPIException(new OHExceptionMessage("Disease not updated."), HttpStatus.INTERNAL_SERVER_ERROR); + } } - + /** * Mark as deleted the specified {@link Disease}. * @param code - the code of the disease to mark delete. * @return {@code true} if the disease has been marked, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to delete a disease */ - @DeleteMapping(value = "/diseases/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> deleteDisease(@PathVariable("code") String code) throws OHServiceException { + @DeleteMapping(value = "/diseases/{code}") + public boolean deleteDisease(@PathVariable("code") String code) throws OHServiceException { Disease disease = diseaseManager.getDiseaseByCode(code); - if (disease != null) { - Map result = new HashMap<>(); - boolean isDeleted; - try { - diseaseManager.deleteDisease(disease); - isDeleted = true; - } catch (OHServiceException serviceException) { - isDeleted = false; - } - result.put("deleted", isDeleted); - return ResponseEntity.ok(result); - } else { - throw new OHAPIException(new OHExceptionMessage("No disease found with the specified code."), HttpStatus.INTERNAL_SERVER_ERROR); + + if (disease == null) { + throw new OHAPIException(new OHExceptionMessage("No disease found with the specified code."), HttpStatus.NOT_FOUND); } - } - - private ResponseEntity> computeResponse(List diseases) { - List diseasesDTO = mapper.map2DTOList(diseases); - if (diseasesDTO.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(diseasesDTO); - } else { - return ResponseEntity.ok(diseasesDTO); - } - } + try { + diseaseManager.deleteDisease(disease); + return true; + } catch (OHServiceException serviceException) { + return false; + } + } } diff --git a/src/main/java/org/isf/distype/rest/DiseaseTypeController.java b/src/main/java/org/isf/distype/rest/DiseaseTypeController.java index 399d2241b..863bc5cf0 100644 --- a/src/main/java/org/isf/distype/rest/DiseaseTypeController.java +++ b/src/main/java/org/isf/distype/rest/DiseaseTypeController.java @@ -21,10 +21,7 @@ */ package org.isf.distype.rest; -import java.util.HashMap; import java.util.List; -import java.util.Map; -import java.util.Optional; import jakarta.validation.Valid; @@ -35,117 +32,107 @@ import org.isf.shared.exceptions.OHAPIException; import org.isf.utils.exception.OHServiceException; import org.isf.utils.exception.model.OHExceptionMessage; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/diseasetypes") +@RestController @Tag(name = "Disease Types") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class DiseaseTypeController { - @Autowired - private DiseaseTypeBrowserManager diseaseTypeManager; - - @Autowired - protected DiseaseTypeMapper mapper; + private final DiseaseTypeBrowserManager diseaseTypeManager; + + private final DiseaseTypeMapper mapper; public DiseaseTypeController(DiseaseTypeBrowserManager diseaseTypeManager, DiseaseTypeMapper diseaseTypeMapper) { this.diseaseTypeManager = diseaseTypeManager; this.mapper = diseaseTypeMapper; } - + /** * Returns all the stored {@link DiseaseType}s. * @return a list of disease type. - * @throws OHServiceException + * @throws OHServiceException When failed to get disease type */ - @GetMapping(value = "/diseasetypes", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getAllDiseaseTypes() throws OHServiceException { - List results = diseaseTypeManager.getDiseaseType(); - List parsedResults=mapper.map2DTOList(results); - if (!parsedResults.isEmpty()) { - return ResponseEntity.ok(parsedResults); - } else { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(parsedResults); - } - } - + @GetMapping(value = "/diseasetypes") + public List getAllDiseaseTypes() throws OHServiceException { + return mapper.map2DTOList(diseaseTypeManager.getDiseaseType()); + } + /** * Create a new {@link DiseaseType}. - * @param diseaseTypeDTO + * @param diseaseTypeDTO Disease type payload * @return the disease type created * @throws OHServiceException - in case of duplicated code or in case of error */ - @PostMapping(value = "/diseasetypes", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity newDiseaseType(@Valid @RequestBody DiseaseTypeDTO diseaseTypeDTO) throws OHServiceException { - DiseaseType diseaseType = mapper.map2Model(diseaseTypeDTO); - if (diseaseTypeManager.isCodePresent(diseaseType.getCode())) { - throw new OHAPIException(new OHExceptionMessage("Specified Disease Type code is already used."), HttpStatus.INTERNAL_SERVER_ERROR); - } - try { - diseaseTypeManager.newDiseaseType(diseaseType); - } catch (OHServiceException serviceException) { - throw new OHAPIException(new OHExceptionMessage("Disease Type is not created."), HttpStatus.INTERNAL_SERVER_ERROR); - } - return ResponseEntity.status(HttpStatus.CREATED).body(diseaseTypeDTO); + @PostMapping(value = "/diseasetypes") + @ResponseStatus(HttpStatus.CREATED) + public DiseaseTypeDTO newDiseaseType( + @Valid @RequestBody DiseaseTypeDTO diseaseTypeDTO + ) throws OHServiceException { + DiseaseType diseaseType = mapper.map2Model(diseaseTypeDTO); + if (diseaseTypeManager.isCodePresent(diseaseType.getCode())) { + throw new OHAPIException(new OHExceptionMessage("Specified Disease Type code is already used.")); + } + + try { + return mapper.map2DTO(diseaseTypeManager.newDiseaseType(diseaseType)); + } catch (OHServiceException serviceException) { + throw new OHAPIException(new OHExceptionMessage("Failed to create disease type."), HttpStatus.INTERNAL_SERVER_ERROR); + } } - + /** * Updates the specified {@link DiseaseType}. * @param diseaseTypeDTO - the disease type to update. * @return the updated disease type - * @throws OHServiceException + * @throws OHServiceException When failed to update disease type */ - @PutMapping(value = "/diseasetypes", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity updateDiseaseType(@Valid @RequestBody DiseaseTypeDTO diseaseTypeDTO) throws OHServiceException { + @PutMapping(value = "/diseasetypes") + public DiseaseTypeDTO updateDiseaseType(@Valid @RequestBody DiseaseTypeDTO diseaseTypeDTO) throws OHServiceException { DiseaseType diseaseType = mapper.map2Model(diseaseTypeDTO); if (!diseaseTypeManager.isCodePresent(diseaseType.getCode())) { - throw new OHAPIException(new OHExceptionMessage("Disease Type not found."), HttpStatus.INTERNAL_SERVER_ERROR); + throw new OHAPIException(new OHExceptionMessage("Disease Type not found."), HttpStatus.NOT_FOUND); } + try { - diseaseTypeManager.updateDiseaseType(diseaseType); - return ResponseEntity.ok(diseaseTypeDTO); + return mapper.map2DTO(diseaseTypeManager.updateDiseaseType(diseaseType)); } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Disease Type not updated."), HttpStatus.INTERNAL_SERVER_ERROR); } } - + /** * Deletes the specified {@link DiseaseType}. * @param code - the code of the disease type to remove. * @return {@code true} if the disease has been removed, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to delete disease type */ - @DeleteMapping(value = "/diseasetypes/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> deleteDiseaseType(@PathVariable String code) throws OHServiceException { - Optional optDiseaseType = diseaseTypeManager.getDiseaseType() - .stream() - .filter(item -> item.getCode().equals(code)) - .findFirst(); - if (optDiseaseType.isPresent()) { - try { - diseaseTypeManager.deleteDiseaseType(optDiseaseType.get()); - Map result = new HashMap<>(1); - result.put("deleted", true); - return ResponseEntity.ok(result); - } catch (OHServiceException serviceException) { - throw new OHAPIException(new OHExceptionMessage("Disease Type not deleted."), HttpStatus.INTERNAL_SERVER_ERROR); - } - } else { - throw new OHAPIException(new OHExceptionMessage("No Disease Type found with the given code."), HttpStatus.INTERNAL_SERVER_ERROR); + @DeleteMapping(value = "/diseasetypes/{code}") + public boolean deleteDiseaseType(@PathVariable String code) throws OHServiceException { + DiseaseType diseaseType = diseaseTypeManager.getDiseaseType(code); + if (diseaseType == null) { + throw new OHAPIException(new OHExceptionMessage("No Disease Type found with the given code."), HttpStatus.NOT_FOUND); } - } + try { + diseaseTypeManager.deleteDiseaseType(diseaseType); + return true; + } catch (OHServiceException e) { + return false; + } + } } diff --git a/src/main/java/org/isf/dlvrrestype/rest/DeliveryResultTypeController.java b/src/main/java/org/isf/dlvrrestype/rest/DeliveryResultTypeController.java index 4d72815f0..d214c1373 100644 --- a/src/main/java/org/isf/dlvrrestype/rest/DeliveryResultTypeController.java +++ b/src/main/java/org/isf/dlvrrestype/rest/DeliveryResultTypeController.java @@ -22,7 +22,6 @@ package org.isf.dlvrrestype.rest; import java.util.List; -import java.util.stream.Collectors; import org.isf.dlvrrestype.dto.DeliveryResultTypeDTO; import org.isf.dlvrrestype.manager.DeliveryResultTypeBrowserManager; @@ -33,127 +32,121 @@ import org.isf.utils.exception.model.OHExceptionMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/deliveryresulttypes") +@RestController @Tag(name = "Delivery Result Type") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class DeliveryResultTypeController { private static final Logger LOGGER = LoggerFactory.getLogger(DeliveryResultTypeController.class); - @Autowired - protected DeliveryResultTypeBrowserManager dlvrrestManager; + private final DeliveryResultTypeBrowserManager deliveryResultTypeManager; - @Autowired - protected DeliveryResultTypeMapper mapper; + private final DeliveryResultTypeMapper mapper; - public DeliveryResultTypeController(DeliveryResultTypeBrowserManager dlvrrestManager, DeliveryResultTypeMapper deliveryResultTypeMapper) { - this.dlvrrestManager = dlvrrestManager; + public DeliveryResultTypeController( + DeliveryResultTypeBrowserManager deliveryResultTypeBrowserManager, DeliveryResultTypeMapper deliveryResultTypeMapper + ) { + this.deliveryResultTypeManager = deliveryResultTypeBrowserManager; this.mapper = deliveryResultTypeMapper; } /** * Create a new {@link DeliveryResultType}. - * @param dlvrrestTypeDTO + * @param deliveryResultTypeDTO Delivery result type payload * @return {@code true} if the {@link DeliveryResultType} has been stored, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to create delivery result type */ - @PostMapping(value = "/deliveryresulttypes", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity newDeliveryResultType(@RequestBody DeliveryResultTypeDTO dlvrrestTypeDTO) - throws OHServiceException { - String code = dlvrrestTypeDTO.getCode(); - LOGGER.info("Create Delivery Result Type {}", code); - dlvrrestManager.newDeliveryResultType(mapper.map2Model(dlvrrestTypeDTO)); - DeliveryResultType dlvrrestTypeCreated = null; - List dlvrrestTypeFounds = dlvrrestManager.getDeliveryResultType().stream() - .filter(ad -> ad.getCode().equals(code)).collect(Collectors.toList()); - if (!dlvrrestTypeFounds.isEmpty()) { - dlvrrestTypeCreated = dlvrrestTypeFounds.get(0); - } - if (dlvrrestTypeCreated == null) { - throw new OHAPIException(new OHExceptionMessage("Delivery result type is not created."), HttpStatus.INTERNAL_SERVER_ERROR); - } - return ResponseEntity.status(HttpStatus.CREATED).body(mapper.map2DTO(dlvrrestTypeCreated)); + @PostMapping(value = "/deliveryresulttypes") + @ResponseStatus(HttpStatus.CREATED) + DeliveryResultTypeDTO newDeliveryResultType( + @RequestBody DeliveryResultTypeDTO deliveryResultTypeDTO + ) throws OHServiceException { + LOGGER.info("Create Delivery Result Type {}", deliveryResultTypeDTO.getCode()); + + return mapper.map2DTO(deliveryResultTypeManager.newDeliveryResultType(mapper.map2Model(deliveryResultTypeDTO))); } /** * Update the specified {@link DeliveryResultType}. - * @param dlvrrestTypeDTO + * @param deliveryResultTypeDTO Delivery result type payload * @return {@code true} if the {@link DeliveryResultType} has been updated, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to update delivery result type */ - @PutMapping(value = "/deliveryresulttypes", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity updateDeliveryResultTypes(@RequestBody DeliveryResultTypeDTO dlvrrestTypeDTO) - throws OHServiceException { - LOGGER.info("Update Delivery Result Type code: {}", dlvrrestTypeDTO.getCode()); - DeliveryResultType dlvrrestType = mapper.map2Model(dlvrrestTypeDTO); - if (!dlvrrestManager.isCodePresent(dlvrrestType.getCode())) { - throw new OHAPIException(new OHExceptionMessage("Delivery Result Type not found.")); + @PutMapping(value = "/deliveryresulttypes") + public DeliveryResultTypeDTO updateDeliveryResultTypes( + @RequestBody DeliveryResultTypeDTO deliveryResultTypeDTO + ) throws OHServiceException { + LOGGER.info("Update Delivery Result Type code: {}", deliveryResultTypeDTO.getCode()); + if (!deliveryResultTypeManager.isCodePresent(deliveryResultTypeDTO.getCode())) { + throw new OHAPIException(new OHExceptionMessage("Delivery Result Type not found."), HttpStatus.NOT_FOUND); } + + DeliveryResultType deliveryResultType = mapper.map2Model(deliveryResultTypeDTO); try { - dlvrrestManager.updateDeliveryResultType(dlvrrestType); + return mapper.map2DTO(deliveryResultTypeManager.updateDeliveryResultType(deliveryResultType)); } catch (OHServiceException serviceException) { - throw new OHAPIException(new OHExceptionMessage("Delivery Result Type is not updated."), HttpStatus.INTERNAL_SERVER_ERROR); + throw new OHAPIException( + new OHExceptionMessage("Delivery Result Type is not updated."), HttpStatus.INTERNAL_SERVER_ERROR + ); } - return ResponseEntity.ok(mapper.map2DTO(dlvrrestType)); } /** * Get all the available {@link DeliveryResultType}s. * @return a {@link List} of {@link DeliveryResultType} or NO_CONTENT if there is no data found. - * @throws OHServiceException + * @throws OHServiceException When failed to get delivery result types */ - @GetMapping(value = "/deliveryresulttypes", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getDeliveryResultTypes() throws OHServiceException { + @GetMapping(value = "/deliveryresulttypes") + public List getDeliveryResultTypes() throws OHServiceException { LOGGER.info("Get all Delivery Result Types."); - List dlvrrestissionTypes = dlvrrestManager.getDeliveryResultType(); - List dlvrrestTypeDTOs = mapper.map2DTOList(dlvrrestissionTypes); - if (dlvrrestTypeDTOs.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(dlvrrestTypeDTOs); - } else { - return ResponseEntity.ok(dlvrrestTypeDTOs); - } + return mapper.map2DTOList(deliveryResultTypeManager.getDeliveryResultType()); } /** * Delete {@link DeliveryResultType} for the specified code. - * @param code + * @param code Delivery result type code * @return {@code true} if the {@link DeliveryResultType} has been deleted, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to delete delivery result type */ - @DeleteMapping(value = "/deliveryresulttypes/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity deleteDeliveryResultType(@PathVariable("code") String code) - throws OHServiceException { + @DeleteMapping(value = "/deliveryresulttypes/{code}") + public boolean deleteDeliveryResultType( + @PathVariable("code") String code + ) throws OHServiceException { LOGGER.info("Delete Delivery Result Type code: {}", code); - if (dlvrrestManager.isCodePresent(code)) { - List dlvrrestTypes = dlvrrestManager.getDeliveryResultType(); - List dlvrrestTypeFounds = dlvrrestTypes.stream().filter(ad -> ad.getCode().equals(code)) - .collect(Collectors.toList()); - if (!dlvrrestTypeFounds.isEmpty()) { - try { - dlvrrestManager.deleteDeliveryResultType(dlvrrestTypeFounds.get(0)); - } catch (OHServiceException serviceException) { - throw new OHAPIException(new OHExceptionMessage("Delivery Result Type is not deleted."), HttpStatus.INTERNAL_SERVER_ERROR); - } - } - } else { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); + + List deliveryResultTypes = deliveryResultTypeManager.getDeliveryResultType(); + List deliveryResultTypeFounds = deliveryResultTypes + .stream() + .filter(ad -> ad.getCode().equals(code)) + .toList(); + + if (deliveryResultTypeFounds.isEmpty()) { + throw new OHAPIException(new OHExceptionMessage("Delivery Result Type not found."), HttpStatus.NOT_FOUND); } - return ResponseEntity.ok(true); - } + try { + deliveryResultTypeManager.deleteDeliveryResultType(deliveryResultTypeFounds.get(0)); + return true; + } catch (OHServiceException serviceException) { + throw new OHAPIException( + new OHExceptionMessage("Delivery Result Type is not deleted."), HttpStatus.INTERNAL_SERVER_ERROR + ); + } + } } diff --git a/src/main/java/org/isf/dlvrtype/rest/DeliveryTypeController.java b/src/main/java/org/isf/dlvrtype/rest/DeliveryTypeController.java index 567d6e463..c871ebd6b 100644 --- a/src/main/java/org/isf/dlvrtype/rest/DeliveryTypeController.java +++ b/src/main/java/org/isf/dlvrtype/rest/DeliveryTypeController.java @@ -22,7 +22,6 @@ package org.isf.dlvrtype.rest; import java.util.List; -import java.util.stream.Collectors; import org.isf.dlvrtype.dto.DeliveryTypeDTO; import org.isf.dlvrtype.manager.DeliveryTypeBrowserManager; @@ -33,129 +32,120 @@ import org.isf.utils.exception.model.OHExceptionMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/deliverytype") +@RestController @Tag(name = "Delivery Type") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class DeliveryTypeController { private static final Logger LOGGER = LoggerFactory.getLogger(DeliveryTypeController.class); - @Autowired - protected DeliveryTypeBrowserManager dlvrtypeManager; + private final DeliveryTypeBrowserManager deliveryTypeManager; - @Autowired - protected DeliveryTypeMapper deliveryTypeMapper; + private final DeliveryTypeMapper deliveryTypeMapper; - public DeliveryTypeController(DeliveryTypeBrowserManager dlvrtypeManager, DeliveryTypeMapper deliveryTypeMapper) { - this.dlvrtypeManager = dlvrtypeManager; + public DeliveryTypeController(DeliveryTypeBrowserManager deliveryTypeManager, DeliveryTypeMapper deliveryTypeMapper) { + this.deliveryTypeManager = deliveryTypeManager; this.deliveryTypeMapper = deliveryTypeMapper; } /** * Create a new {@link DeliveryType}. - * - * @param dlvrTypeDTO + * + * @param deliveryTypeDTO Delivery Type payload * @return {@code true} if the {@link DeliveryType} has been stored, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to create delivery type */ - @PostMapping(value = "/deliverytypes", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity newDeliveryType(@RequestBody DeliveryTypeDTO dlvrTypeDTO) throws OHServiceException { - String code = dlvrTypeDTO.getCode(); - LOGGER.info("Create Delivery Type {}", code); - dlvrtypeManager.newDeliveryType(deliveryTypeMapper.map2Model(dlvrTypeDTO)); - DeliveryType dlvrTypeCreated = null; - List dlvrTypeFounds = dlvrtypeManager.getDeliveryType().stream().filter(ad -> ad.getCode().equals(code)) - .collect(Collectors.toList()); - if (!dlvrTypeFounds.isEmpty()) { - dlvrTypeCreated = dlvrTypeFounds.get(0); - } - if (dlvrTypeCreated == null) { - throw new OHAPIException(new OHExceptionMessage("Delivery Type not created.")); + @PostMapping(value = "/deliverytypes") + @ResponseStatus(HttpStatus.CREATED) + public DeliveryTypeDTO newDeliveryType(@RequestBody DeliveryTypeDTO deliveryTypeDTO) throws OHServiceException { + LOGGER.info("Create Delivery Type {}", deliveryTypeDTO.getCode()); + + DeliveryType deliveryType = deliveryTypeManager.newDeliveryType(deliveryTypeMapper.map2Model(deliveryTypeDTO)); + + if (deliveryType == null) { + throw new OHAPIException(new OHExceptionMessage("Failed to create delivery type")); } - return ResponseEntity.status(HttpStatus.CREATED).body(deliveryTypeMapper.map2DTO(dlvrTypeCreated)); + + return deliveryTypeMapper.map2DTO(deliveryType); } /** * Update the specified {@link DeliveryType}. - * - * @param dlvrTypeDTO + * + * @param deliveryTypeDTO Delivery type payload * @return {@code true} if the {@link DeliveryType} has been updated, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to update delivery type */ - @PutMapping(value = "/deliverytypes", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity updateDeliveryTypes(@RequestBody DeliveryTypeDTO dlvrTypeDTO) throws OHServiceException { - LOGGER.info("Update Delivery Type code: {}", dlvrTypeDTO.getCode()); - DeliveryType dlvrType = deliveryTypeMapper.map2Model(dlvrTypeDTO); - if (!dlvrtypeManager.isCodePresent(dlvrType.getCode())) { - throw new OHAPIException(new OHExceptionMessage("Delivery Type not found.")); + @PutMapping(value = "/deliverytypes") + public DeliveryTypeDTO updateDeliveryTypes( + @RequestBody DeliveryTypeDTO deliveryTypeDTO + ) throws OHServiceException { + LOGGER.info("Update Delivery Type code: {}", deliveryTypeDTO.getCode()); + if (!deliveryTypeManager.isCodePresent(deliveryTypeDTO.getCode())) { + throw new OHAPIException(new OHExceptionMessage("Delivery Type not found."), HttpStatus.NOT_FOUND); } + try { - dlvrtypeManager.updateDeliveryType(dlvrType); + return deliveryTypeMapper.map2DTO( + deliveryTypeManager.updateDeliveryType(deliveryTypeMapper.map2Model(deliveryTypeDTO)) + ); } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Delivery Type is not updated.")); } - return ResponseEntity.ok(deliveryTypeMapper.map2DTO(dlvrType)); } /** * Get all the available {@link DeliveryType}. - * + * * @return a {@link List} of {@link DeliveryType} or NO_CONTENT if there is no data found. - * @throws OHServiceException + * @throws OHServiceException When failed to get delivery results */ - @GetMapping(value = "/deliverytypes", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getDeliveryTypes() throws OHServiceException { + @GetMapping(value = "/deliverytypes") + public List getDeliveryTypes() throws OHServiceException { LOGGER.info("Get all Delivery Types"); - List dlvrTypes = dlvrtypeManager.getDeliveryType(); - List dlvrTypeDTOs = deliveryTypeMapper.map2DTOList(dlvrTypes); - if (dlvrTypeDTOs.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(dlvrTypeDTOs); - } else { - return ResponseEntity.ok(dlvrTypeDTOs); - } + return deliveryTypeMapper.map2DTOList(deliveryTypeManager.getDeliveryType()); } /** * Delete {@link DeliveryType} for specified code. - * - * @param code + * + * @param code Delivery result code * @return {@code true} if the {@link DeliveryType} has been deleted, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to delete delivery type */ - @DeleteMapping(value = "/deliverytypes/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity deleteDeliveryType(@PathVariable("code") String code) throws OHServiceException { + @DeleteMapping(value = "/deliverytypes/{code}") + public boolean deleteDeliveryType(@PathVariable("code") String code) throws OHServiceException { LOGGER.info("Delete Delivery Type code: {}", code); - if (dlvrtypeManager.isCodePresent(code)) { - List dlvrTypes = dlvrtypeManager.getDeliveryType(); - List dlvrTypeFounds = dlvrTypes.stream().filter(ad -> ad.getCode().equals(code)) - .collect(Collectors.toList()); - if (!dlvrTypeFounds.isEmpty()) { - try { - dlvrtypeManager.deleteDeliveryType(dlvrTypeFounds.get(0)); - } catch (OHServiceException serviceException) { - LOGGER.error("Delete Delivery Type: {} failed.", code); - throw new OHAPIException(new OHExceptionMessage("Delivery Type not deleted.")); - } - } - } else { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); + + List deliveryTypes = deliveryTypeManager.getDeliveryType(); + List deliveryTypeFounds = deliveryTypes.stream().filter(ad -> ad.getCode().equals(code)).toList(); + + if (deliveryTypeFounds.isEmpty()) { + throw new OHAPIException(new OHExceptionMessage("Delivery Type not found."), HttpStatus.NOT_FOUND); } - return ResponseEntity.ok(true); - } + try { + deliveryTypeManager.deleteDeliveryType(deliveryTypeFounds.get(0)); + return true; + } catch (OHServiceException serviceException) { + LOGGER.error("Delete Delivery Type: {} failed.", code); + throw new OHAPIException(new OHExceptionMessage("Delivery Type not deleted.")); + } + } } diff --git a/src/main/java/org/isf/exam/rest/ExamController.java b/src/main/java/org/isf/exam/rest/ExamController.java index 8db5568bf..181a276a0 100644 --- a/src/main/java/org/isf/exam/rest/ExamController.java +++ b/src/main/java/org/isf/exam/rest/ExamController.java @@ -37,38 +37,45 @@ import org.isf.shared.exceptions.OHAPIException; import org.isf.utils.exception.OHServiceException; import org.isf.utils.exception.model.OHExceptionMessage; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@Tag(name = "Exams") @RestController +@Tag(name = "Exams") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class ExamController { - @Autowired - protected ExamBrowsingManager examManager; + private final ExamBrowsingManager examManager; - @Autowired - protected ExamTypeBrowserManager examTypeBrowserManager; + private final ExamTypeBrowserManager examTypeBrowserManager; - @Autowired - private ExamMapper examMapper; + private final ExamMapper examMapper; + + public ExamController( + ExamBrowsingManager examManager, + ExamTypeBrowserManager examTypeBrowserManager, + ExamMapper examMapper + ) { + this.examManager = examManager; + this.examTypeBrowserManager = examTypeBrowserManager; + this.examMapper = examMapper; + } + @PostMapping(value = "/exams") @ResponseStatus(HttpStatus.CREATED) - @PostMapping(value = "/exams", produces = MediaType.APPLICATION_JSON_VALUE) public ExamDTO newExam(@Valid @RequestBody ExamWithRowsDTO examWithRowsDTO) throws OHServiceException { ExamDTO examDTO = examWithRowsDTO.exam(); List examRows = examWithRowsDTO.rows(); @@ -80,7 +87,8 @@ public ExamDTO newExam(@Valid @RequestBody ExamWithRowsDTO examWithRowsDTO) thro } if (examDTO.getProcedure() == 1 && examDTO.getDefaultResult() != null) { - if ((examRows == null ? Collections.emptyList() : examRows).stream().noneMatch(row -> examDTO.getDefaultResult().equals(row))) { + if ((examRows == null ? Collections.emptyList() : examRows).stream() + .noneMatch(row -> examDTO.getDefaultResult().equals(row))) { throw new OHAPIException(new OHExceptionMessage("Exam default result doesn't match any exam rows.")); } } @@ -95,8 +103,10 @@ public ExamDTO newExam(@Valid @RequestBody ExamWithRowsDTO examWithRowsDTO) thro return examMapper.map2DTO(exam); } - @PutMapping(value = "/exams/{code:.+}", produces = MediaType.APPLICATION_JSON_VALUE) - public ExamDTO updateExam(@PathVariable String code, @Valid @RequestBody ExamWithRowsDTO examWithRowsDTO) throws OHServiceException { + @PutMapping(value = "/exams/{code:.+}") + public ExamDTO updateExam( + @PathVariable String code, @Valid @RequestBody ExamWithRowsDTO examWithRowsDTO + ) throws OHServiceException { ExamDTO examDTO = examWithRowsDTO.exam(); List examRows = examWithRowsDTO.rows(); @@ -113,7 +123,8 @@ public ExamDTO updateExam(@PathVariable String code, @Valid @RequestBody ExamWit } if (examDTO.getProcedure() == 1 && examDTO.getDefaultResult() != null) { - if ((examRows == null ? Collections.emptyList() : examRows).stream().noneMatch(row -> examDTO.getDefaultResult().equals(row))) { + if ((examRows == null ? Collections.emptyList() : examRows).stream() + .noneMatch(row -> examDTO.getDefaultResult().equals(row))) { throw new OHAPIException(new OHExceptionMessage("Exam default result doesn't match any exam rows.")); } } @@ -128,39 +139,27 @@ public ExamDTO updateExam(@PathVariable String code, @Valid @RequestBody ExamWit return examMapper.map2DTO(examUpdated); } - @GetMapping(value = "/exams/description/{description:.+}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getExams(@PathVariable String description) throws OHServiceException { - List exams = examMapper.map2DTOList(examManager.getExams(description)); - - if (exams == null || exams.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } else { - return ResponseEntity.ok(exams); - } + @GetMapping(value = "/exams/description/{description:.+}") + public List getExams(@PathVariable String description) throws OHServiceException { + return examMapper.map2DTOList(examManager.getExams(description)); } - @GetMapping(value = "/exams", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getExams() throws OHServiceException { - List exams = examMapper.map2DTOList(examManager.getExams()); - - if (exams == null || exams.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } else { - return ResponseEntity.ok(exams); - } + @GetMapping(value = "/exams") + public List getExams() throws OHServiceException { + return examMapper.map2DTOList(examManager.getExams()); } - @DeleteMapping(value = "/exams/{code:.+}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity deleteExam(@PathVariable String code) throws OHServiceException { + @DeleteMapping(value = "/exams/{code:.+}") + public boolean deleteExam(@PathVariable String code) throws OHServiceException { Optional exam = examManager.getExams().stream().filter(e -> e.getCode().equals(code)).findFirst(); - if (!exam.isPresent()) { + if (exam.isEmpty()) { throw new OHAPIException(new OHExceptionMessage("Exam not found.")); } try { examManager.deleteExam(exam.get()); + return true; } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Exam not deleted.")); } - return ResponseEntity.ok(true); } -} +} \ No newline at end of file diff --git a/src/main/java/org/isf/exam/rest/ExamRowController.java b/src/main/java/org/isf/exam/rest/ExamRowController.java index 2d723b633..6b8cf34ad 100644 --- a/src/main/java/org/isf/exam/rest/ExamRowController.java +++ b/src/main/java/org/isf/exam/rest/ExamRowController.java @@ -32,15 +32,14 @@ import org.isf.shared.exceptions.OHAPIException; import org.isf.utils.exception.OHServiceException; import org.isf.utils.exception.model.OHExceptionMessage; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; @@ -48,32 +47,38 @@ import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/examrows") +@RestController @Tag(name = "Exam Rows") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class ExamRowController { - @Autowired - protected ExamBrowsingManager examManager; + private final ExamBrowsingManager examManager; - @Autowired - protected ExamRowBrowsingManager examRowBrowsingManager; + private final ExamRowBrowsingManager examRowBrowsingManager; - @Autowired - private ExamRowMapper examRowMapper; + private final ExamRowMapper examRowMapper; - public ExamRowController(ExamBrowsingManager examManager, ExamRowBrowsingManager examRowBrowsingManager, ExamRowMapper examRowMapper) { + public ExamRowController( + ExamBrowsingManager examManager, + ExamRowBrowsingManager examRowBrowsingManager, + ExamRowMapper examRowMapper + ) { this.examManager = examManager; this.examRowBrowsingManager = examRowBrowsingManager; this.examRowMapper = examRowMapper; } - @PostMapping(value = "/examrows", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity newExamRow(@RequestBody ExamRowDTO examRowDTO) throws OHServiceException { - Exam exam = examManager.getExams().stream().filter(e -> examRowDTO.getExam().getCode().equals(e.getCode())).findFirst().orElse(null); + @PostMapping("/examrows") + @ResponseStatus(HttpStatus.CREATED) + public ExamRowDTO newExamRow(@RequestBody ExamRowDTO examRowDTO) throws OHServiceException { + Exam exam = examManager.getExams() + .stream() + .filter(e -> examRowDTO.getExam().getCode().equals(e.getCode())) + .findFirst().orElse(null); if (exam == null) { - throw new OHAPIException(new OHExceptionMessage("Exam not found.")); + throw new OHAPIException(new OHExceptionMessage("Exam not found."), HttpStatus.NOT_FOUND); } ExamRow examRow = examRowMapper.map2Model(examRowDTO); @@ -83,72 +88,48 @@ public ResponseEntity newExamRow(@RequestBody ExamRowDTO examRowDTO) if (isCreatedExamRow == null) { throw new OHAPIException(new OHExceptionMessage("ExamRow not created.")); } - return ResponseEntity.status(HttpStatus.CREATED).body(examRowMapper.map2DTO(isCreatedExamRow)); - } - - @GetMapping(value = "/examrows", produces = MediaType.APPLICATION_JSON_VALUE) - @ResponseStatus(HttpStatus.OK) - public ResponseEntity> getExamRows() throws OHServiceException { - List examRows = examRowBrowsingManager.getExamRow(); - if (examRows == null || examRows.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } else { - return ResponseEntity.ok(examRowMapper.map2DTOList(examRows)); - } + return examRowMapper.map2DTO(isCreatedExamRow); } - @GetMapping(value = "/examrows/{code:.+}", produces = MediaType.APPLICATION_JSON_VALUE) - @ResponseStatus(HttpStatus.OK) - public ResponseEntity> getExamRowsByCode(@PathVariable Integer code) throws OHServiceException { - List examRows = examRowBrowsingManager.getExamRow(code); - - if (examRows == null || examRows.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } else { - return ResponseEntity.ok(examRowMapper.map2DTOList(examRows)); - } + @GetMapping("/examrows") + public List getExamRows() throws OHServiceException { + return examRowMapper.map2DTOList(examRowBrowsingManager.getExamRow()); } - @GetMapping(value = "/examrows/search", produces = MediaType.APPLICATION_JSON_VALUE) - @ResponseStatus(HttpStatus.OK) - public ResponseEntity> getExamRowsByCodeAndDescription(@RequestParam Integer code, @RequestParam String description) throws OHServiceException { - List examRows = examRowBrowsingManager.getExamRow(code, description); + @GetMapping("/examrows/{code:.+}") + public List getExamRowsByCode(@PathVariable Integer code) throws OHServiceException { + return examRowMapper.map2DTOList(examRowBrowsingManager.getExamRow(code)); + } - if (examRows == null || examRows.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } else { - return ResponseEntity.ok(examRowMapper.map2DTOList(examRows)); - } + @GetMapping("/examrows/search") + public List getExamRowsByCodeAndDescription( + @RequestParam Integer code, @RequestParam String description + ) throws OHServiceException { + return examRowMapper.map2DTOList(examRowBrowsingManager.getExamRow(code, description)); } - @DeleteMapping(value = "/examrows/{code:.+}", produces = MediaType.APPLICATION_JSON_VALUE) - @ResponseStatus(HttpStatus.OK) - public ResponseEntity deleteExam(@PathVariable Integer code) throws OHServiceException { + @DeleteMapping("/examrows/{code:.+}") + public boolean deleteExam(@PathVariable Integer code) throws OHServiceException { List examRows = examRowBrowsingManager.getExamRow(code); if (examRows == null || examRows.isEmpty()) { - throw new OHAPIException(new OHExceptionMessage("ExamRows not found.")); + throw new OHAPIException(new OHExceptionMessage("ExamRows not found."), HttpStatus.NOT_FOUND); } + if (examRows.size() > 1) { throw new OHAPIException(new OHExceptionMessage("Found multiple ExamRows.")); } + try { examRowBrowsingManager.deleteExamRow(examRows.get(0)); + return true; } catch (OHServiceException serviceException) { - throw new OHAPIException(new OHExceptionMessage("ExamRow not deleted.")); + throw new OHAPIException(new OHExceptionMessage("ExamRow not deleted."),HttpStatus.INTERNAL_SERVER_ERROR); } - return ResponseEntity.ok(true); } - @GetMapping(value = "/examrows/byExamCode/{examCode:.+}", produces = MediaType.APPLICATION_JSON_VALUE) - @ResponseStatus(HttpStatus.OK) - public ResponseEntity> getExamRowsByExamCode(@PathVariable String examCode) throws OHServiceException { - List examRows = examRowBrowsingManager.getExamRowByExamCode(examCode); - - if (examRows == null || examRows.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } else { - return ResponseEntity.ok(examRowMapper.map2DTOList(examRows)); - } + @GetMapping("/examrows/byExamCode/{examCode:.+}") + public List getExamRowsByExamCode(@PathVariable String examCode) throws OHServiceException { + return examRowMapper.map2DTOList(examRowBrowsingManager.getExamRowByExamCode(examCode)); } } diff --git a/src/main/java/org/isf/examination/rest/ExaminationController.java b/src/main/java/org/isf/examination/rest/ExaminationController.java index 055b2560f..d12e003b3 100644 --- a/src/main/java/org/isf/examination/rest/ExaminationController.java +++ b/src/main/java/org/isf/examination/rest/ExaminationController.java @@ -22,7 +22,6 @@ package org.isf.examination.rest; import java.util.List; -import java.util.stream.Collectors; import org.isf.examination.dto.PatientExaminationDTO; import org.isf.examination.manager.ExaminationBrowserManager; @@ -41,15 +40,14 @@ import org.isf.utils.pagination.PagedResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; @@ -57,152 +55,152 @@ import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/examinations") +@RestController @Tag(name = "Examinations") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class ExaminationController { private static final Logger LOGGER = LoggerFactory.getLogger(ExaminationController.class); - @Autowired - protected ExaminationBrowserManager examinationBrowserManager; + private final ExaminationBrowserManager examinationBrowserManager; - @Autowired - private PatientExaminationMapper patientExaminationMapper; + private final PatientExaminationMapper patientExaminationMapper; - @Autowired - private PatientBrowserManager patientBrowserManager; + private final PatientBrowserManager patientBrowserManager; - public ExaminationController(ExaminationBrowserManager examinationBrowserManager, PatientExaminationMapper patientExaminationMapper, - PatientBrowserManager patientBrowserManager) { + public ExaminationController( + ExaminationBrowserManager examinationBrowserManager, + PatientExaminationMapper patientExaminationMapper, + PatientBrowserManager patientBrowserManager + ) { this.examinationBrowserManager = examinationBrowserManager; this.patientExaminationMapper = patientExaminationMapper; this.patientBrowserManager = patientBrowserManager; } - @PostMapping(value = "/examinations", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity newPatientExamination(@RequestBody PatientExaminationDTO newPatientExamination) throws OHServiceException { + @PostMapping("/examinations") + @ResponseStatus(HttpStatus.CREATED) + public PatientExaminationDTO newPatientExamination( + @RequestBody PatientExaminationDTO newPatientExamination + ) throws OHServiceException { Patient patient = patientBrowserManager.getPatientById(newPatientExamination.getPatientCode()); if (patient == null) { - throw new OHAPIException(new OHExceptionMessage("Patient does not exist.")); + throw new OHAPIException(new OHExceptionMessage("Patient does not exist."), HttpStatus.NOT_FOUND); } + validateExamination(newPatientExamination); PatientExamination patientExamination = patientExaminationMapper.map2Model(newPatientExamination); patientExamination.setPatient(patient); patientExamination.setPex_date(newPatientExamination.getPex_date()); - examinationBrowserManager.saveOrUpdate(patientExamination); - return ResponseEntity.status(HttpStatus.CREATED).body(true); + return patientExaminationMapper.map2DTO(examinationBrowserManager.saveOrUpdate(patientExamination)); } - @PutMapping(value = "/examinations/{id}", produces = MediaType.APPLICATION_JSON_VALUE) - @ResponseStatus(HttpStatus.OK) - public ResponseEntity updateExamination(@PathVariable Integer id, @RequestBody PatientExaminationDTO dto) throws OHServiceException { + @PutMapping("/examinations/{id}") + public PatientExaminationDTO updateExamination( + @PathVariable Integer id, @RequestBody PatientExaminationDTO dto + ) throws OHServiceException { if (dto.getPex_ID() != id) { throw new OHAPIException(new OHExceptionMessage("Patient examination id mismatch.")); } if (examinationBrowserManager.getByID(id) == null) { - throw new OHAPIException(new OHExceptionMessage("Patient examination not found.")); + throw new OHAPIException(new OHExceptionMessage("Patient examination not found."), HttpStatus.NOT_FOUND); } Patient patient = patientBrowserManager.getPatientById(dto.getPatientCode()); if (patient == null) { - throw new OHAPIException(new OHExceptionMessage("Patient does not exist.")); + throw new OHAPIException(new OHExceptionMessage("Patient does not exist."), HttpStatus.NOT_FOUND); } + validateExamination(dto); PatientExamination patientExamination = patientExaminationMapper.map2Model(dto); patientExamination.setPatient(patient); patientExamination.setPex_date(dto.getPex_date()); - examinationBrowserManager.saveOrUpdate(patientExamination); - return ResponseEntity.ok(true); + return patientExaminationMapper.map2DTO(examinationBrowserManager.saveOrUpdate(patientExamination)); } - @GetMapping(value = "/examinations/defaultPatientExamination", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getDefaultPatientExamination(@RequestParam Integer patId) throws OHServiceException { - + @GetMapping("/examinations/defaultPatientExamination") + public PatientExaminationDTO getDefaultPatientExamination(@RequestParam Integer patId) throws OHServiceException { Patient patient = patientBrowserManager.getPatientById(patId); if (patient == null) { - throw new OHAPIException(new OHExceptionMessage("Patient does not exist.")); + throw new OHAPIException(new OHExceptionMessage("Patient does not exist."), HttpStatus.NOT_FOUND); } + PatientExamination patientExamination = examinationBrowserManager.getDefaultPatientExamination(patient); - PatientExaminationDTO patientExaminationDTO = patientExaminationMapper.map2DTO(patientExamination); - if (patientExaminationDTO == null) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } else { - return ResponseEntity.ok(patientExaminationDTO); + + if (patientExamination == null) { + throw new OHAPIException(new OHExceptionMessage("Patient examination not found."), HttpStatus.NOT_FOUND); } - } - @GetMapping(value = "/examinations/fromLastPatientExamination/{id}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getFromLastPatientExamination(@PathVariable Integer id) throws OHServiceException { + return patientExaminationMapper.map2DTO(patientExamination); + } + @GetMapping("/examinations/fromLastPatientExamination/{id}") + public PatientExaminationDTO getFromLastPatientExamination( + @PathVariable Integer id + ) throws OHServiceException { PatientExamination lastPatientExamination = examinationBrowserManager.getByID(id); - PatientExaminationDTO patientExaminationDTO = patientExaminationMapper - .map2DTO(examinationBrowserManager.getFromLastPatientExamination(lastPatientExamination)); - if (patientExaminationDTO == null) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } else { - return ResponseEntity.ok(patientExaminationDTO); + + if (lastPatientExamination == null) { + throw new OHAPIException(new OHExceptionMessage("Patient examination not found."), HttpStatus.NOT_FOUND); } - } - @GetMapping(value = "/examinations/{id}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getByID(@PathVariable Integer id) throws OHServiceException { + PatientExamination patientExamination = examinationBrowserManager.getFromLastPatientExamination(lastPatientExamination); + return patientExaminationMapper.map2DTO(patientExamination); + } + + @GetMapping("/examinations/{id}") + public PatientExaminationDTO getByID(@PathVariable Integer id) throws OHServiceException { PatientExamination patientExamination = examinationBrowserManager.getByID(id); if (patientExamination == null) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } else { - PatientExaminationDTO patientExaminationDTO = patientExaminationMapper.map2DTO(patientExamination); - return ResponseEntity.ok(patientExaminationDTO); - + throw new OHAPIException(new OHExceptionMessage("Patient examination not found."), HttpStatus.NOT_FOUND); } - } - @GetMapping(value = "/examinations/lastByPatientId/{patId}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getLastByPatientId(@PathVariable Integer patId) throws OHServiceException { + return patientExaminationMapper.map2DTO(patientExamination); + } + @GetMapping("/examinations/lastByPatientId/{patId}") + public PatientExaminationDTO getLastByPatientId( + @PathVariable Integer patId + ) throws OHServiceException { PatientExamination patientExamination = examinationBrowserManager.getLastByPatID(patId); if (patientExamination == null) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } else { - PatientExaminationDTO patientExaminationDTO = patientExaminationMapper.map2DTO(patientExamination); - return ResponseEntity.ok(patientExaminationDTO); + throw new OHAPIException(new OHExceptionMessage("Patient examination not found."), HttpStatus.NOT_FOUND); } + + return patientExaminationMapper.map2DTO(patientExamination); } - @GetMapping(value = "/examinations/lastNByPatId", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getLastNByPatID(@RequestParam Integer limit, @RequestParam Integer patId) throws OHServiceException { + @GetMapping("/examinations/lastNByPatId") + public Page getLastNByPatID( + @RequestParam Integer limit, @RequestParam Integer patId + ) throws OHServiceException { LOGGER.info("Get examinations limit: {}", limit); - PagedResponse patientExaminationListPageable = examinationBrowserManager.getLastNByPatIDPageable(patId, limit); - - if (patientExaminationListPageable == null || patientExaminationListPageable.getData().isEmpty()) { - LOGGER.info("The patient list is empty."); - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } else { - Page patientExaminationPageableDTO = new Page<>(); - List patientExaminationDTO = patientExaminationMapper.map2DTOList(patientExaminationListPageable.getData()); - patientExaminationPageableDTO.setData(patientExaminationDTO); - patientExaminationPageableDTO.setPageInfo(patientExaminationMapper.setParameterPageInfo(patientExaminationListPageable.getPageInfo())); - return ResponseEntity.ok(patientExaminationPageableDTO); - } + PagedResponse patientExaminationListPageable = examinationBrowserManager + .getLastNByPatIDPageable(patId, limit); + + Page patientExaminationPageableDTO = new Page<>(); + List patientExaminationDTO = patientExaminationMapper.map2DTOList( + patientExaminationListPageable.getData() + ); + patientExaminationPageableDTO.setData(patientExaminationDTO); + patientExaminationPageableDTO.setPageInfo(patientExaminationMapper.setParameterPageInfo( + patientExaminationListPageable.getPageInfo()) + ); + + return patientExaminationPageableDTO; } - @GetMapping(value = "/examinations/byPatientId/{patId}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getByPatientId(@PathVariable Integer patId) throws OHServiceException { - - List patientExamination = examinationBrowserManager.getByPatID(patId); - if (patientExamination == null || patientExamination.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } else { - List listPatientExaminationDTO = patientExamination.stream().map(pat -> { - return patientExaminationMapper.map2DTO(pat); - }).collect(Collectors.toList()); - return ResponseEntity.ok(listPatientExaminationDTO); - } + @GetMapping("/examinations/byPatientId/{patId}") + public List getByPatientId( + @PathVariable Integer patId + ) throws OHServiceException { + return patientExaminationMapper.map2DTOList(examinationBrowserManager.getByPatID(patId)); } public void validateExamination(PatientExaminationDTO newPatientExamination) throws OHServiceException { @@ -214,13 +212,13 @@ public void validateExamination(PatientExaminationDTO newPatientExamination) thr throw new OHAPIException(new OHExceptionMessage("The height and weight are compulsory")); } if (pex_height < ExaminationParameters.HEIGHT_MIN - || pex_height > ExaminationParameters.HEIGHT_MAX) { + || pex_height > ExaminationParameters.HEIGHT_MAX) { throw new OHAPIException(new OHExceptionMessage( - "The height should be between " + ExaminationParameters.HEIGHT_MIN + " and " + ExaminationParameters.HEIGHT_MAX)); + "The height should be between " + ExaminationParameters.HEIGHT_MIN + " and " + ExaminationParameters.HEIGHT_MAX)); } if (pex_weight < ExaminationParameters.WEIGHT_MIN || pex_weight > ExaminationParameters.WEIGHT_MAX) { throw new OHAPIException(new OHExceptionMessage( - "The weight should be between" + ExaminationParameters.WEIGHT_MIN + " and " + ExaminationParameters.WEIGHT_MAX)); + "The weight should be between" + ExaminationParameters.WEIGHT_MIN + " and " + ExaminationParameters.WEIGHT_MAX)); } Integer pex_ap_min = newPatientExamination.getPex_ap_min(); Integer pex_ap_max = newPatientExamination.getPex_ap_max(); @@ -230,50 +228,50 @@ public void validateExamination(PatientExaminationDTO newPatientExamination) thr if (pex_ap_min != null && pex_ap_max == null) { throw new OHAPIException(new OHExceptionMessage("Malformed minimum/maximum blood pressure: maximum missing")); } - if (pex_ap_min != null && pex_ap_max != null && pex_ap_min > pex_ap_max) { + if (pex_ap_min != null && pex_ap_min > pex_ap_max) { throw new OHAPIException(new OHExceptionMessage("The minimum blood pressure must be lower than the maximum blood pressure")); } Integer pex_hr = newPatientExamination.getPex_hr(); if (pex_hr != null && (pex_hr < ExaminationParameters.HR_MIN || pex_hr > ExaminationParameters.HR_MAX)) { throw new OHAPIException( - new OHExceptionMessage("Heart rate should be between " + ExaminationParameters.HR_MIN + " and " + ExaminationParameters.HR_MAX)); + new OHExceptionMessage("Heart rate should be between " + ExaminationParameters.HR_MIN + " and " + ExaminationParameters.HR_MAX)); } Double pex_temp = newPatientExamination.getPex_temp(); if (pex_temp != null && (pex_temp < ExaminationParameters.TEMP_MIN || pex_temp > ExaminationParameters.TEMP_MAX)) { throw new OHAPIException(new OHExceptionMessage( - "The temperature should be between " + ExaminationParameters.TEMP_MIN + " and " + ExaminationParameters.TEMP_MAX)); + "The temperature should be between " + ExaminationParameters.TEMP_MIN + " and " + ExaminationParameters.TEMP_MAX)); } Double pex_sat = newPatientExamination.getPex_sat(); if (pex_sat != null && (pex_sat < ExaminationParameters.SAT_MIN || pex_sat > ExaminationParameters.SAT_MAX)) { throw new OHAPIException(new OHExceptionMessage( - "The saturation should be between " + ExaminationParameters.SAT_MIN + " and " + ExaminationParameters.SAT_MAX)); + "The saturation should be between " + ExaminationParameters.SAT_MIN + " and " + ExaminationParameters.SAT_MAX)); } Integer pex_hgt = newPatientExamination.getPex_hgt(); if (pex_hgt != null && (pex_hgt < ExaminationParameters.HGT_MIN || pex_hgt > ExaminationParameters.HGT_MAX)) { throw new OHAPIException( - new OHExceptionMessage("HGT should be between " + ExaminationParameters.HGT_MIN + " and " + ExaminationParameters.HGT_MAX)); + new OHExceptionMessage("HGT should be between " + ExaminationParameters.HGT_MIN + " and " + ExaminationParameters.HGT_MAX)); } Integer pex_rr = newPatientExamination.getPex_rr(); if (pex_rr != null && (pex_rr < ExaminationParameters.RR_MIN || pex_rr > ExaminationParameters.RR_MAX)) { throw new OHAPIException(new OHExceptionMessage( - "Respiratory rate should be between " + ExaminationParameters.RR_MIN + " and " + ExaminationParameters.RR_MAX)); + "Respiratory rate should be between " + ExaminationParameters.RR_MIN + " and " + ExaminationParameters.RR_MAX)); } Integer pex_diuresis = newPatientExamination.getPex_diuresis(); if (pex_diuresis != null && (pex_diuresis < ExaminationParameters.DIURESIS_MIN || pex_diuresis > ExaminationParameters.DIURESIS_MAX)) { throw new OHAPIException(new OHExceptionMessage( - "Diuresis should be between " + ExaminationParameters.DIURESIS_MIN + " and " + ExaminationParameters.DIURESIS_MAX)); + "Diuresis should be between " + ExaminationParameters.DIURESIS_MIN + " and " + ExaminationParameters.DIURESIS_MAX)); } Diurese pex_diuresis_desc = newPatientExamination.getPex_diuresis_desc(); - if (pex_diuresis_desc != null && Diurese.valueOf(pex_diuresis_desc.toString()) == null) { - throw new OHAPIException(new OHExceptionMessage("Diuresis description is not found")); + if (pex_diuresis_desc != null) { + Diurese.valueOf(pex_diuresis_desc.toString()); } Bowel pex_bowel_desc = newPatientExamination.getPex_bowel_desc(); - if (pex_bowel_desc != null && Bowel.valueOf(pex_bowel_desc.toString()) == null) { - throw new OHAPIException(new OHExceptionMessage("Bowel description is not found")); + if (pex_bowel_desc != null) { + Bowel.valueOf(pex_bowel_desc.toString()); } Ausculation pex_auscultation = newPatientExamination.getPex_auscultation(); - if (pex_auscultation != null && Ausculation.valueOf(pex_auscultation.toString()) == null) { - throw new OHAPIException(new OHExceptionMessage("Auscultation is not found")); + if (pex_auscultation != null) { + Ausculation.valueOf(pex_auscultation.toString()); } } } diff --git a/src/main/java/org/isf/exatype/rest/ExamTypeController.java b/src/main/java/org/isf/exatype/rest/ExamTypeController.java index 1648570eb..ab49f8a70 100644 --- a/src/main/java/org/isf/exatype/rest/ExamTypeController.java +++ b/src/main/java/org/isf/exatype/rest/ExamTypeController.java @@ -22,7 +22,6 @@ package org.isf.exatype.rest; import java.util.List; -import java.util.stream.Collectors; import org.isf.exatype.dto.ExamTypeDTO; import org.isf.exatype.manager.ExamTypeBrowserManager; @@ -33,91 +32,79 @@ import org.isf.utils.exception.model.OHExceptionMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/examtypes") +@RestController @Tag(name = "Exam Types") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class ExamTypeController { private static final Logger LOGGER = LoggerFactory.getLogger(ExamTypeController.class); - @Autowired - protected ExamTypeBrowserManager examTypeBrowserManager; + private final ExamTypeBrowserManager examTypeBrowserManager; - @Autowired - private ExamTypeMapper examTypeMapper; + private final ExamTypeMapper examTypeMapper; public ExamTypeController(ExamTypeBrowserManager examTypeBrowserManager, ExamTypeMapper examTypeMapper) { this.examTypeBrowserManager = examTypeBrowserManager; this.examTypeMapper = examTypeMapper; } - @PostMapping(value = "/examtypes", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity newExamType(@RequestBody ExamTypeDTO newExamType) throws OHServiceException { - - ExamType examType = examTypeMapper.map2Model(newExamType); - ExamType createdExamType = examTypeBrowserManager.newExamType(examType); - return ResponseEntity.status(HttpStatus.CREATED).body(examTypeMapper.map2DTO(createdExamType)); + @PostMapping("/examtypes") + @ResponseStatus(HttpStatus.CREATED) + public ExamTypeDTO newExamType(@RequestBody ExamTypeDTO newExamType) throws OHServiceException { + return examTypeMapper.map2DTO(examTypeBrowserManager.newExamType(examTypeMapper.map2Model(newExamType))); } - @PutMapping(value = "/examtypes/{code:.+}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity updateExamType(@PathVariable String code, @RequestBody ExamTypeDTO updateExamType) throws OHServiceException { - + @PutMapping("/examtypes/{code:.+}") + public ExamTypeDTO updateExamType( + @PathVariable String code, @RequestBody ExamTypeDTO updateExamType + ) throws OHServiceException { if (!updateExamType.getCode().equals(code)) { throw new OHAPIException(new OHExceptionMessage("Exam Type code mismatch.")); } if (!examTypeBrowserManager.isCodePresent(code)) { - throw new OHAPIException(new OHExceptionMessage("Exam Type not found.")); + throw new OHAPIException(new OHExceptionMessage("Exam Type not found."), HttpStatus.NOT_FOUND); } - ExamType examType = examTypeMapper.map2Model(updateExamType); - ExamType updatedExamType = examTypeBrowserManager.updateExamType(examType); - return ResponseEntity.ok(examTypeMapper.map2DTO(updatedExamType)); + return examTypeMapper.map2DTO(examTypeBrowserManager.updateExamType(examTypeMapper.map2Model(updateExamType))); } - @GetMapping(value = "/examtypes", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getExamTypes() throws OHServiceException { - List examTypeDTOS = examTypeMapper.map2DTOList(examTypeBrowserManager.getExamType()); - - if (examTypeDTOS == null || examTypeDTOS.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } - return ResponseEntity.ok(examTypeDTOS); + @GetMapping("/examtypes") + public List getExamTypes() throws OHServiceException { + return examTypeMapper.map2DTOList(examTypeBrowserManager.getExamType()); } - @DeleteMapping(value = "/examtypes/{code:.+}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity deleteExamType(@PathVariable String code) throws OHServiceException { + @DeleteMapping("/examtypes/{code:.+}") + public boolean deleteExamType(@PathVariable String code) throws OHServiceException { LOGGER.info("Delete Exam Type Type code: {}", code); - if (examTypeBrowserManager.isCodePresent(code)) { - List examTypes = examTypeBrowserManager.getExamType(); - List examFounds = examTypes.stream().filter(ad -> ad.getCode().equals(code)) - .collect(Collectors.toList()); - if (!examFounds.isEmpty()) { - try { - examTypeBrowserManager.deleteExamType(examFounds.get(0)); - } catch (OHServiceException serviceException) { - LOGGER.error("Delete Exam Type: {} failed.", code); - throw new OHAPIException(new OHExceptionMessage("Exam Type not deleted.")); - } - } - } else { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); + + List examTypes = examTypeBrowserManager.getExamType(); + List examFounds = examTypes.stream().filter(ad -> ad.getCode().equals(code)).toList(); + if (examFounds.isEmpty()) { + throw new OHAPIException(new OHExceptionMessage("Exam Type not found."), HttpStatus.NOT_FOUND); } - return ResponseEntity.ok(true); - } + try { + examTypeBrowserManager.deleteExamType(examFounds.get(0)); + return true; + } catch (OHServiceException serviceException) { + LOGGER.error("Delete Exam Type: {} failed.", code); + throw new OHAPIException(new OHExceptionMessage("Exam Type not deleted.")); + } + } } diff --git a/src/main/java/org/isf/hospital/rest/HospitalController.java b/src/main/java/org/isf/hospital/rest/HospitalController.java index c78ddccb2..7b8b3afa3 100644 --- a/src/main/java/org/isf/hospital/rest/HospitalController.java +++ b/src/main/java/org/isf/hospital/rest/HospitalController.java @@ -28,72 +28,70 @@ import org.isf.shared.exceptions.OHAPIException; import org.isf.utils.exception.OHServiceException; import org.isf.utils.exception.model.OHExceptionMessage; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/hospitals") +@RestController @Tag(name = "Hospitals") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class HospitalController { - @Autowired - private HospitalBrowsingManager hospitalBrowsingManager; + private final HospitalBrowsingManager hospitalBrowsingManager; - @Autowired - private HospitalMapper hospitalMapper; + private final HospitalMapper hospitalMapper; public HospitalController(HospitalBrowsingManager hospitalBrowsingManager, HospitalMapper hospitalMapper) { this.hospitalBrowsingManager = hospitalBrowsingManager; this.hospitalMapper = hospitalMapper; } - @PutMapping(value = "/hospitals/{code:.+}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity updateHospital(@PathVariable String code, @RequestBody HospitalDTO hospitalDTO) throws OHServiceException { - + @PutMapping("/hospitals/{code:.+}") + public HospitalDTO updateHospital( + @PathVariable String code, @RequestBody HospitalDTO hospitalDTO + ) throws OHServiceException { if (!hospitalDTO.getCode().equals(code)) { throw new OHAPIException(new OHExceptionMessage("Hospital code mismatch.")); } + if (hospitalBrowsingManager.getHospital().getCode() == null) { - throw new OHAPIException(new OHExceptionMessage("Hospital not found.")); + throw new OHAPIException(new OHExceptionMessage("Hospital not found."), HttpStatus.NOT_FOUND); } Hospital hospital = hospitalMapper.map2Model(hospitalDTO); hospital.setLock(hospitalDTO.getLock()); - Hospital hospi = hospitalBrowsingManager.updateHospital(hospital); - return ResponseEntity.ok(hospitalMapper.map2DTO(hospi)); + return hospitalMapper.map2DTO(hospitalBrowsingManager.updateHospital(hospital)); } - @GetMapping(value = "/hospitals", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getHospital() throws OHServiceException { + @GetMapping("/hospitals") + public HospitalDTO getHospital() throws OHServiceException { Hospital hospital = hospitalBrowsingManager.getHospital(); if (hospital == null) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } else { - return ResponseEntity.ok(hospitalMapper.map2DTO(hospital)); + throw new OHAPIException(new OHExceptionMessage("Hospital not found."), HttpStatus.NOT_FOUND); } + + return hospitalMapper.map2DTO(hospital); } - @GetMapping(value = "/hospitals/currencyCode", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getHospitalCurrencyCode() throws OHServiceException { + @GetMapping(value = "/hospitals/currencyCode", produces = MediaType.TEXT_PLAIN_VALUE) + public String getHospitalCurrencyCode() throws OHServiceException { String hospitalCurrencyCod = hospitalBrowsingManager.getHospitalCurrencyCod(); if (hospitalCurrencyCod == null || hospitalCurrencyCod.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } else { - return ResponseEntity.ok(hospitalCurrencyCod); + throw new OHAPIException(new OHExceptionMessage("Hospital not found."), HttpStatus.NOT_FOUND); } - } + return hospitalCurrencyCod; + } } diff --git a/src/main/java/org/isf/lab/rest/LaboratoryController.java b/src/main/java/org/isf/lab/rest/LaboratoryController.java index cd2ee9a0e..1be838beb 100644 --- a/src/main/java/org/isf/lab/rest/LaboratoryController.java +++ b/src/main/java/org/isf/lab/rest/LaboratoryController.java @@ -34,7 +34,6 @@ import org.isf.lab.dto.LaboratoryDTO; import org.isf.lab.dto.LaboratoryRowDTO; import org.isf.lab.manager.LabManager; -import org.isf.lab.mapper.LaboratoryForPrintMapper; import org.isf.lab.mapper.LaboratoryMapper; import org.isf.lab.mapper.LaboratoryRowMapper; import org.isf.lab.model.Laboratory; @@ -50,25 +49,26 @@ import org.isf.utils.pagination.PagedResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/laboratories") +@RestController @Tag(name = "Laboratories") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class LaboratoryController { private static final Logger LOGGER = LoggerFactory.getLogger(LaboratoryController.class); @@ -86,44 +86,40 @@ public class LaboratoryController { private static final String DONE = LaboratoryStatus.done.toString(); - @Autowired - protected LabManager laboratoryManager; + private final LabManager laboratoryManager; - @Autowired - protected ExamBrowsingManager examManager; + private final ExamBrowsingManager examManager; - @Autowired - private PatientBrowserManager patientBrowserManager; + private final PatientBrowserManager patientBrowserManager; - @Autowired - private LaboratoryMapper laboratoryMapper; + private final LaboratoryMapper laboratoryMapper; - @Autowired - private LaboratoryRowMapper laboratoryRowMapper; + private final LaboratoryRowMapper laboratoryRowMapper; - @Autowired - private LaboratoryForPrintMapper laboratoryForPrintMapper; - - public LaboratoryController(LabManager laboratoryManager, PatientBrowserManager patientBrowserManager, - ExamBrowsingManager examManager, LaboratoryMapper laboratoryMapper, LaboratoryRowMapper laboratoryRowMapper, - LaboratoryForPrintMapper laboratoryForPrintMapper) { + public LaboratoryController( + LabManager laboratoryManager, + PatientBrowserManager patientBrowserManager, + ExamBrowsingManager examManager, + LaboratoryMapper laboratoryMapper, + LaboratoryRowMapper laboratoryRowMapper + ) { this.laboratoryManager = laboratoryManager; this.patientBrowserManager = patientBrowserManager; this.examManager = examManager; this.laboratoryMapper = laboratoryMapper; this.laboratoryRowMapper = laboratoryRowMapper; - this.laboratoryForPrintMapper = laboratoryForPrintMapper; } /** * Create a new {@link LaboratoryRowDTO}. - * - * @param labWithRowsDTO + * + * @param labWithRowsDTO Lab with rows payload * @return {@code true} if the record has been created, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to create lab with rows */ - @PostMapping(value = "/laboratories", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity newLaboratory(@RequestBody LabWithRowsDTO labWithRowsDTO) throws OHServiceException { + @PostMapping("/laboratories") + @ResponseStatus(HttpStatus.CREATED) + public boolean newLaboratory(@RequestBody LabWithRowsDTO labWithRowsDTO) throws OHServiceException { LOGGER.info("store exam with result"); LaboratoryDTO laboratoryDTO = labWithRowsDTO.getLaboratoryDTO(); List labRow = labWithRowsDTO.getLaboratoryRowList(); @@ -134,7 +130,7 @@ public ResponseEntity newLaboratory(@RequestBody LabWithRowsDTO labWith } Exam exam = examManager.getExams().stream().filter(e -> e.getCode().equals(laboratoryDTO.getExam().getCode())) - .findFirst().orElse(null); + .findFirst().orElse(null); if (exam == null) { throw new OHAPIException(new OHExceptionMessage("Exam not found.")); } @@ -153,19 +149,21 @@ public ResponseEntity newLaboratory(@RequestBody LabWithRowsDTO labWith } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Laboratory not created.")); } - return ResponseEntity.status(HttpStatus.CREATED).body(true); + + return true; } /** * Create a new {@link LaboratoryDTO}. - * - * @param laboratoryDTO + * + * @param laboratoryDTO Lab exam payload * @return {@code true} if the record has been created, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to create lab exam * @author Arnaud */ - @PostMapping(value = "/laboratories/examRequest", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity newExamRequest(@RequestBody LaboratoryDTO laboratoryDTO) throws OHServiceException { + @PostMapping("/laboratories/examRequest") + @ResponseStatus(HttpStatus.CREATED) + public boolean newExamRequest(@RequestBody LaboratoryDTO laboratoryDTO) throws OHServiceException { LOGGER.info("store exam request"); Patient patient = patientBrowserManager.getPatientById(laboratoryDTO.getPatientCode()); @@ -174,7 +172,7 @@ public ResponseEntity newExamRequest(@RequestBody LaboratoryDTO laborat } Exam exam = examManager.getExams().stream().filter(e -> e.getCode().equals(laboratoryDTO.getExam().getCode())) - .findFirst().orElse(null); + .findFirst().orElse(null); if (exam == null) { throw new OHAPIException(new OHExceptionMessage("Exam not found.")); } @@ -186,10 +184,11 @@ public ResponseEntity newExamRequest(@RequestBody LaboratoryDTO laborat labToInsert.setStatus(DRAFT); labToInsert.setResult(""); labToInsert.setInOutPatient(laboratoryDTO.getInOutPatient().toString()); - List labList = laboratoryManager.getLaboratory(patient).stream() - .filter(e -> e.getStatus().equals(DRAFT)).collect(Collectors.toList()); + List labList = laboratoryManager.getLaboratory(patient) + .stream() + .filter(e -> e.getStatus().equals(DRAFT)).toList(); - if (!(labList == null || labList.isEmpty())) { + if (!labList.isEmpty()) { for (Laboratory lab : labList) { if (lab.getExam().equals(exam)) { throw new OHAPIException(new OHExceptionMessage("Exam Request already exists.")); @@ -202,19 +201,20 @@ public ResponseEntity newExamRequest(@RequestBody LaboratoryDTO laborat } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Laboratory not created.")); } - return ResponseEntity.status(HttpStatus.CREATED).body(true); + + return true; } /** * Create a {@link List} of {@link LaboratoryRowDTO}. - * - * @param labsWithRows + * + * @param labsWithRows List of lab exam with rows * @return {@code true} if the record has been created, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to create lab exams */ - @PostMapping(value = "/laboratories/insertList", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity newLaboratory2(@RequestBody List labsWithRows) - throws OHServiceException { + @PostMapping("/laboratories/insertList") + @ResponseStatus(HttpStatus.CREATED) + public boolean newLaboratory2(@RequestBody List labsWithRows) throws OHServiceException { LOGGER.info("store List of Exam with result"); List labsToInsert = new ArrayList<>(); List> labsRowsToInsert = new ArrayList<>(); @@ -227,7 +227,7 @@ public ResponseEntity newLaboratory2(@RequestBody List } Exam exam = examManager.getExams().stream() - .filter(e -> e.getCode().equals(laboratoryDTO.getExam().getCode())).findFirst().orElse(null); + .filter(e -> e.getCode().equals(laboratoryDTO.getExam().getCode())).findFirst().orElse(null); if (exam == null) { throw new OHAPIException(new OHExceptionMessage("Exam not found.")); } @@ -242,7 +242,7 @@ public ResponseEntity newLaboratory2(@RequestBody List List labRowToInsert = new ArrayList<>(); for (String rowDescription : labWithRowsDTO.getLaboratoryRowList()) { labRowToInsert - .add(laboratoryRowMapper.map2Model(new LaboratoryRowDTO(rowDescription, laboratoryDTO))); + .add(laboratoryRowMapper.map2Model(new LaboratoryRowDTO(rowDescription, laboratoryDTO))); } if (!labRowToInsert.isEmpty()) { labsRowsToInsert.add(labRowToInsert); @@ -255,20 +255,23 @@ public ResponseEntity newLaboratory2(@RequestBody List } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Laboratory not created.")); } - return ResponseEntity.status(HttpStatus.CREATED).body(true); + + return true; } /** * Updates the specified {@link LaboratoryRowDTO} object. - * - * @param code - * @param labWithRowsDTO + * + * @param code Lab exam code + * @param labWithRowsDTO Lab exam payload * @return {@code true} if has been updated, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to update lab exam */ - @PutMapping(value = "/laboratories/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity updateLaboratory(@PathVariable Integer code, - @RequestBody LabWithRowsDTO labWithRowsDTO) throws OHServiceException { + @PutMapping("/laboratories/{code}") + public boolean updateLaboratory( + @PathVariable Integer code, + @RequestBody LabWithRowsDTO labWithRowsDTO + ) throws OHServiceException { LOGGER.info("Update labWithRows code: {}", code); LaboratoryDTO laboratoryDTO = labWithRowsDTO.getLaboratoryDTO(); List labRow = labWithRowsDTO.getLaboratoryRowList(); @@ -278,20 +281,22 @@ public ResponseEntity updateLaboratory(@PathVariable Integer code, } Optional labo = laboratoryManager.getLaboratory(code); - if (!labo.isPresent()) { - throw new OHAPIException(new OHExceptionMessage("Laboratory not found.")); + if (labo.isEmpty()) { + throw new OHAPIException(new OHExceptionMessage("Laboratory not found."), HttpStatus.NOT_FOUND); } + Laboratory lab = labo.get(); if (lab.getStatus().equalsIgnoreCase(DELETED) || lab.getStatus().equalsIgnoreCase(INVALID)) { throw new OHAPIException(new OHExceptionMessage("This exam can not be update because its status is " + lab.getStatus())); } + Patient patient = patientBrowserManager.getPatientById(laboratoryDTO.getPatientCode()); if (patient == null) { throw new OHAPIException(new OHExceptionMessage("Patient not found.")); } Exam exam = examManager.getExams().stream().filter(e -> e.getCode().equals(laboratoryDTO.getExam().getCode())) - .findFirst().orElse(null); + .findFirst().orElse(null); if (exam == null) { throw new OHAPIException(new OHExceptionMessage("Exam not found.")); } @@ -304,9 +309,11 @@ public ResponseEntity updateLaboratory(@PathVariable Integer code, if (labRow != null) { labRows = new ArrayList<>(labRow); } + if (!laboratoryDTO.getResult().isEmpty()) { labToInsert.setStatus(DONE); } + try { laboratoryManager.updateLaboratory(labToInsert, labRows); } catch (OHServiceException e) { @@ -316,45 +323,43 @@ public ResponseEntity updateLaboratory(@PathVariable Integer code, } throw new OHAPIException(e.getMessages().get(0)); } - return ResponseEntity.ok(true); + + return true; } /** * Updates the specified {@link LaboratoryDTO} object. - * - * @param code - * @param status + * + * @param code Lab exam code + * @param status Lab exam status * @return {@code true} if has been updated, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to change lab exam status * @author Arnaud */ - @PutMapping(value = "/laboratories/examRequest/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity updateExamRequest(@PathVariable Integer code, @RequestParam String status) - throws OHServiceException { + @PutMapping("/laboratories/examRequest/{code}") + public boolean updateExamRequest( + @PathVariable Integer code, @RequestParam String status + ) throws OHServiceException { LOGGER.info("Update exam request code: {}", code); - LaboratoryStatus stat = LaboratoryStatus.valueOf(status); - if (stat != null) { - try { - laboratoryManager.updateExamRequest(code, status); - } catch (OHServiceException serviceException) { - throw new OHAPIException(new OHExceptionMessage("Laboratory not updated.")); - } - return ResponseEntity.ok(true); - } else { - throw new OHAPIException(new OHExceptionMessage("This status doesn't exist.")); + + try { + laboratoryManager.updateExamRequest(code, status); + } catch (OHServiceException serviceException) { + throw new OHAPIException(new OHExceptionMessage("Laboratory not updated.")); } + return true; } /** * Set an {@link LaboratoryDTO} record to be deleted. - * - * @param code + * + * @param code Lab exam code * @return {@code true} if the record has been set to delete, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to delete lab exam */ - @DeleteMapping(value = "/laboratories/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity deleteExam(@PathVariable Integer code) throws OHServiceException { + @DeleteMapping("/laboratories/{code}") + public boolean deleteExam(@PathVariable Integer code) throws OHServiceException { LOGGER.info("Delete Exam code: {}", code); Optional lab = laboratoryManager.getLaboratory(code); if (lab.isPresent()) { @@ -363,33 +368,33 @@ public ResponseEntity deleteExam(@PathVariable Integer code) throws OHS throw new OHAPIException(new OHExceptionMessage("This exam can not be deleted because its status is " + labToDelete.getStatus())); } } else { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); + throw new OHAPIException(new OHExceptionMessage("Lab exam not found."), HttpStatus.NOT_FOUND); } + try { laboratoryManager.updateExamRequest(code, DELETED); + return true; } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Exam is not deleted.")); } - return ResponseEntity.ok(true); } /** * Get the list of exams {@link LaboratoryRowDTO}s divided by pages. - * - * @param oneWeek - * @param page - * @param size + * + * @param oneWeek Get for the previous week? + * @param page The page number + * @param size The page size * @return the {@link List} of found {@link LaboratoryRowDTO} or NO_CONTENT otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to get lab exams */ - @GetMapping(value = "/laboratories", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getLaboratory(@RequestParam boolean oneWeek, @RequestParam int page, @RequestParam int size) - throws OHServiceException { + @GetMapping("/laboratories") + public Page getLaboratory( + @RequestParam boolean oneWeek, @RequestParam int page, @RequestParam int size + ) throws OHServiceException { LOGGER.info("Get all LabWithRows"); PagedResponse labListPageable = laboratoryManager.getLaboratoryPageable(oneWeek, page, size); - if (labListPageable == null || labListPageable.getData().isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } + List labWithRowsDto = labListPageable.getData().stream().map(lab -> { LabWithRowsDTO labDTO = new LabWithRowsDTO(); List labDescription = new ArrayList<>(); @@ -407,8 +412,8 @@ public ResponseEntity> getLaboratory(@RequestParam boolean labDescription.add(laboratoryRow.getDescription()); } } - } + laboratoryDTO.setRegistrationDate(lab.getCreatedDate()); laboratoryDTO.setInOutPatient(PatientSTATUS.valueOf(lab.getInOutPatient())); laboratoryDTO.setStatus(LaboratoryStatus.valueOf(lab.getStatus())); @@ -416,33 +421,34 @@ public ResponseEntity> getLaboratory(@RequestParam boolean labDTO.setLaboratoryRowList(labDescription); return labDTO; }).collect(Collectors.toList()); + Page labWithRowsDtoPageable = new Page<>(); labWithRowsDtoPageable.setPageInfo(laboratoryMapper.setParameterPageInfo(labListPageable.getPageInfo())); labWithRowsDtoPageable.setData(labWithRowsDto); - return ResponseEntity.ok(labWithRowsDtoPageable); + + return labWithRowsDtoPageable; } /** * Get all {@link LaboratoryRowDTO}s for the specified id. - * - * @param patId + * + * @param patId Patient ID * @return the {@link List} of found {@link LaboratoryRowDTO} or NO_CONTENT otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to get patient's lab exams */ - @GetMapping(value = "/laboratories/byPatientId/{patId}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getLaboratory(@PathVariable Integer patId) throws OHServiceException { + @GetMapping("/laboratories/byPatientId/{patId}") + public List getLaboratory(@PathVariable Integer patId) throws OHServiceException { LOGGER.info("Get LabWithRows for patient Id: {}", patId); + Patient patient = patientBrowserManager.getPatientById(patId); if (patient == null) { throw new OHAPIException(new OHExceptionMessage("Patient not found.")); } List labList = laboratoryManager.getLaboratory(patient).stream() - .filter(e -> !e.getStatus().equalsIgnoreCase(DRAFT) && !e.getStatus().equalsIgnoreCase(OPEN)).collect(Collectors.toList()); - if (labList == null || labList.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } - return ResponseEntity.ok(labList.stream().map(lab -> { + .filter(e -> !e.getStatus().equalsIgnoreCase(DRAFT) && !e.getStatus().equalsIgnoreCase(OPEN)).toList(); + + return labList.stream().map(lab -> { LabWithRowsDTO labDTO = new LabWithRowsDTO(); List labDescription = new ArrayList<>(); LaboratoryDTO laboratoryDTO = laboratoryMapper.map2DTO(lab); @@ -467,104 +473,93 @@ public ResponseEntity> getLaboratory(@PathVariable Integer labDTO.setLaboratoryDTO(laboratoryDTO); labDTO.setLaboratoryRowList(labDescription); return labDTO; - }).collect(Collectors.toList())); + }).collect(Collectors.toList()); } /** * Get all {@link LaboratoryDTO}s for the specified id. - * - * @param patId + * + * @param patId Patient ID * @return the {@link List} of found {@link LaboratoryDTO} or NO_CONTENT otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to get patient exam request * @author Arnaud */ - @GetMapping(value = "/laboratories/examRequest/patient/{patId}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getLaboratoryExamRequest(@PathVariable Integer patId) - throws OHServiceException { + @GetMapping("/laboratories/examRequest/patient/{patId}") + public List getLaboratoryExamRequest( + @PathVariable Integer patId + ) throws OHServiceException { LOGGER.info("Get Exam requested by patient Id: {}", patId); + Patient patient = patientBrowserManager.getPatientById(patId); if (patient == null) { throw new OHAPIException(new OHExceptionMessage("Patient not found.")); } List labList = laboratoryManager.getLaboratory(patient).stream() - .filter(e -> e.getStatus().equalsIgnoreCase(DRAFT) || e.getStatus().equalsIgnoreCase(OPEN)).collect(Collectors.toList()); - if (labList == null || labList.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } + .filter(e -> e.getStatus().equalsIgnoreCase(DRAFT) || e.getStatus().equalsIgnoreCase(OPEN)).toList(); - return ResponseEntity.ok(labList.stream().map(lab -> { + return labList.stream().map(lab -> { LaboratoryDTO laboratoryDTO = laboratoryMapper.map2DTO(lab); laboratoryDTO.setRegistrationDate(lab.getCreatedDate()); laboratoryDTO.setInOutPatient(PatientSTATUS.valueOf(lab.getInOutPatient())); laboratoryDTO.setStatus(LaboratoryStatus.valueOf(lab.getStatus())); return laboratoryDTO; - }).collect(Collectors.toList())); + }).collect(Collectors.toList()); } /** * Get all {@link LaboratoryDTO}s. - * + * * @return the {@link List} of found {@link LaboratoryDTO} or NO_CONTENT otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to get exam requests * @author Arnaud */ - @GetMapping(value = "/laboratories/examRequest", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getLaboratoryExamRequest() throws OHServiceException { + @GetMapping("/laboratories/examRequest") + public List getLaboratoryExamRequest() throws OHServiceException { LOGGER.info("Get all Exam Requested"); List labList = laboratoryManager.getLaboratory().stream() - .filter(e -> e.getStatus().equalsIgnoreCase(DRAFT) || e.getStatus().equalsIgnoreCase(OPEN)).collect(Collectors.toList()); - if (labList == null || labList.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } + .filter(e -> e.getStatus().equalsIgnoreCase(DRAFT) || e.getStatus().equalsIgnoreCase(OPEN)).toList(); - return ResponseEntity.ok(labList.stream().map(lab -> { + return labList.stream().map(lab -> { LaboratoryDTO laboratoryDTO = laboratoryMapper.map2DTO(lab); laboratoryDTO.setRegistrationDate(lab.getCreatedDate()); laboratoryDTO.setInOutPatient(PatientSTATUS.valueOf(lab.getInOutPatient())); laboratoryDTO.setStatus(LaboratoryStatus.valueOf(lab.getStatus())); return laboratoryDTO; - }).collect(Collectors.toList())); + }).collect(Collectors.toList()); } /** * Get all {@link String}s. - * + * * @return the {@link List} of all material or NO_CONTENT otherwise. - * @throws OHServiceException */ - @GetMapping(value = "/laboratories/materials", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getMaterials() throws OHServiceException { + @GetMapping("/laboratories/materials") + public List getMaterials() { LOGGER.info("Get all Material"); - List materialList = laboratoryManager.getMaterialList(); - if (materialList == null || materialList.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } else { - return ResponseEntity.ok(materialList); - } + return laboratoryManager.getMaterialList(); } /** * Get all the {@link LaboratoryRowDTO}s based on the applied filters. - * - * @param examName - * @param dateFrom - * @param dateTo - * @param patientCode + * + * @param examName Exam name + * @param dateFrom Start date + * @param dateTo End date + * @param patientCode Patient Code * @return the {@link List} of found {@link LabWithRowsDTO} or NO_CONTENT otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to get lab exams */ - - @GetMapping(value = "/laboratories/exams", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getLaboratoryForPrint( - @RequestParam(required = false, defaultValue = "") String examName, - @RequestParam(value = "dateFrom") String dateFrom, @RequestParam(value = "dateTo") String dateTo, - @RequestParam(value = "patientCode", required = false, defaultValue = "0") int patientCode, - @RequestParam(value = "status", required = false, defaultValue = "") String status, - @RequestParam(value = "page", required = false, defaultValue = "0") int page, - @RequestParam(value = "size", required = false, defaultValue = DEFAULT_PAGE_SIZE) int size, - @RequestParam(value = "paged", required = false, defaultValue = "false") boolean paged) - throws OHServiceException { + @GetMapping("/laboratories/exams") + public Page getLaboratoryForPrint( + @RequestParam(required = false, defaultValue = "") String examName, + @RequestParam(value = "dateFrom") String dateFrom, @RequestParam(value = "dateTo") String dateTo, + @RequestParam(value = "patientCode", required = false, defaultValue = "0") int patientCode, + @RequestParam(value = "status", required = false, defaultValue = "") String status, + @RequestParam(value = "page", required = false, defaultValue = "0") int page, + @RequestParam(value = "size", required = false, defaultValue = DEFAULT_PAGE_SIZE) int size, + @RequestParam(value = "paged", required = false, defaultValue = "false") boolean paged + ) throws OHServiceException { LOGGER.info("Get labWithRow within specified date"); LOGGER.debug("examName: {}", examName); LOGGER.debug("dateFrom: {}", dateFrom); @@ -584,7 +579,7 @@ public ResponseEntity> getLaboratoryForPrint( patient = patientBrowserManager.getPatientById(patientCode); if (patient == null || laboratoryManager.getLaboratory(patient) == null) { throw new OHAPIException(new OHExceptionMessage("Patient not found."), - HttpStatus.INTERNAL_SERVER_ERROR); + HttpStatus.INTERNAL_SERVER_ERROR); } } PagedResponse laboratoryPageable; @@ -598,7 +593,7 @@ public ResponseEntity> getLaboratoryForPrint( laboratoryPageable = laboratoryManager.getLaboratoryPageable(null, dateF, dateT, patient, page, size); } labList = laboratoryPageable.getData() - .stream().filter(lab -> lab.getStatus().equalsIgnoreCase(status)).collect(Collectors.toList()); + .stream().filter(lab -> lab.getStatus().equalsIgnoreCase(status)).collect(Collectors.toList()); } else { if (!examName.isEmpty()) { Exam exam = examManager.getExams(examName).get(0); @@ -613,7 +608,7 @@ public ResponseEntity> getLaboratoryForPrint( } else { if (!status.isEmpty()) { labList = laboratoryManager.getLaboratory(examName, dateF, dateT, patient) - .stream().filter(lab -> lab.getStatus().equalsIgnoreCase(status)).collect(Collectors.toList()); + .stream().filter(lab -> lab.getStatus().equalsIgnoreCase(status)).collect(Collectors.toList()); } else { labList = laboratoryManager.getLaboratory(examName, dateF, dateT, patient); @@ -621,81 +616,76 @@ public ResponseEntity> getLaboratoryForPrint( } } - if (labList == null || labList.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } else { - List labWithRowList = labList.stream().map(lab -> { - LabWithRowsDTO labDTO = new LabWithRowsDTO(); - List labDescription = new ArrayList<>(); - LaboratoryDTO laboratoryDTO = laboratoryMapper.map2DTO(lab); - if (lab.getExam().getProcedure() == 2) { - List labDes = new ArrayList<>(); - try { - labDes = laboratoryManager.getLaboratoryRowList(lab.getCode()); - } catch (OHServiceException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - if (!labDes.isEmpty()) { - for (LaboratoryRow laboratoryRow : labDes) { - labDescription.add(laboratoryRow.getDescription()); - } + List labWithRowList = labList.stream().map(lab -> { + LabWithRowsDTO labDTO = new LabWithRowsDTO(); + List labDescription = new ArrayList<>(); + LaboratoryDTO laboratoryDTO = laboratoryMapper.map2DTO(lab); + if (lab.getExam().getProcedure() == 2) { + List labDes = new ArrayList<>(); + try { + labDes = laboratoryManager.getLaboratoryRowList(lab.getCode()); + } catch (OHServiceException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + if (!labDes.isEmpty()) { + for (LaboratoryRow laboratoryRow : labDes) { + labDescription.add(laboratoryRow.getDescription()); } } - laboratoryDTO.setRegistrationDate(lab.getCreatedDate()); - laboratoryDTO.setInOutPatient(PatientSTATUS.valueOf(lab.getInOutPatient())); - laboratoryDTO.setStatus(LaboratoryStatus.valueOf(lab.getStatus())); - labDTO.setLaboratoryDTO(laboratoryDTO); - labDTO.setLaboratoryRowList(labDescription); - return labDTO; - }).collect(Collectors.toList()); - result.setData(labWithRowList); - return ResponseEntity.ok(result); - } + } + laboratoryDTO.setRegistrationDate(lab.getCreatedDate()); + laboratoryDTO.setInOutPatient(PatientSTATUS.valueOf(lab.getInOutPatient())); + laboratoryDTO.setStatus(LaboratoryStatus.valueOf(lab.getStatus())); + labDTO.setLaboratoryDTO(laboratoryDTO); + labDTO.setLaboratoryRowList(labDescription); + return labDTO; + }).collect(Collectors.toList()); + result.setData(labWithRowList); + + return result; } /** * Get all the {@link LaboratoryDTO}s for the specified id. - * - * @param code + * + * @param code Lab exam code * @return the {@link List} of found {@link LaboratoryDTO} or NO_CONTENT otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to get lab exam */ - @GetMapping(value = "/laboratories/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getExamById(@PathVariable Integer code) throws OHServiceException { + @GetMapping("/laboratories/{code}") + public LaboratoryDTO getExamById(@PathVariable Integer code) throws OHServiceException { LOGGER.info("Get Laboratory associated to specified CODE: {}", code); - Optional labo = laboratoryManager.getLaboratory(code); - Laboratory lab; - if (labo.isPresent()) { - lab = labo.get(); - } else { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); + Laboratory lab = laboratoryManager.getLaboratory(code).orElse(null); + if (lab == null) { + throw new OHAPIException(new OHExceptionMessage("Lab exam not found"), HttpStatus.NOT_FOUND); } + LaboratoryDTO laboratoryDTO = laboratoryMapper.map2DTO(lab); laboratoryDTO.setRegistrationDate(lab.getCreatedDate()); laboratoryDTO.setInOutPatient(PatientSTATUS.valueOf(lab.getInOutPatient())); laboratoryDTO.setStatus(LaboratoryStatus.valueOf(lab.getStatus())); - return ResponseEntity.ok(laboratoryDTO); + + return laboratoryDTO; } /** * Get all the {@link LaboratoryRowDTO}s for the specified id. - * - * @param code + * + * @param code Lab exam code * @return the {@link List} of found {@link LaboratoryRowDTO} or NO_CONTENT otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to get lab exam with row */ - @GetMapping(value = "/laboratories/exams/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getExamWithRowsById(@PathVariable Integer code) throws OHServiceException { + @GetMapping("/laboratories/exams/{code}") + public LabWithRowsDTO getExamWithRowsById(@PathVariable Integer code) throws OHServiceException { LOGGER.info("Get labWithRows associated to specified CODE: {}", code); LabWithRowsDTO lab = new LabWithRowsDTO(); - Optional labo = laboratoryManager.getLaboratory(code); - Laboratory laboratory; - if (labo.isPresent()) { - laboratory = labo.get(); - } else { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); + + Laboratory laboratory = laboratoryManager.getLaboratory(code).orElse(null); + if (laboratory == null) { + throw new OHAPIException(new OHExceptionMessage("Lab exam not found"), HttpStatus.NOT_FOUND); } + LaboratoryDTO labDTO = laboratoryMapper.map2DTO(laboratory); labDTO.setRegistrationDate(laboratory.getCreatedDate()); labDTO.setInOutPatient(PatientSTATUS.valueOf(laboratory.getInOutPatient())); @@ -713,19 +703,20 @@ public ResponseEntity getExamWithRowsById(@PathVariable Integer } lab.setLaboratoryRowList(labDescription); - return ResponseEntity.ok(lab); + + return lab; } /** * Set an {@link Laboratory} record to be deleted. - * - * @param code + * + * @param code Lab exam code * @return {@code true} if the record has been set to invalid, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to delete lab exam * @author Arnaud */ - @DeleteMapping(value = "/laboratories/examRequest/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity deleteExamRequest(@PathVariable Integer code) throws OHServiceException { + @DeleteMapping("/laboratories/examRequest/{code}") + public boolean deleteExamRequest(@PathVariable Integer code) throws OHServiceException { LOGGER.info("Get Laboratory associated to specified CODE: {}", code); Optional labo = laboratoryManager.getLaboratory(code); if (labo.isPresent()) { @@ -734,13 +725,14 @@ public ResponseEntity deleteExamRequest(@PathVariable Integer code) thr throw new OHAPIException(new OHExceptionMessage("This exam can not be deleted because its status is " + lab.getStatus())); } } else { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); + throw new OHAPIException(new OHExceptionMessage("Lab exam not found"), HttpStatus.NOT_FOUND); } + try { laboratoryManager.updateExamRequest(code, INVALID); + return true; } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Exam request is not deleted.")); } - return ResponseEntity.ok(true); } } diff --git a/src/main/java/org/isf/login/rest/LoginController.java b/src/main/java/org/isf/login/rest/LoginController.java index e253e9175..0d0c2ebc2 100644 --- a/src/main/java/org/isf/login/rest/LoginController.java +++ b/src/main/java/org/isf/login/rest/LoginController.java @@ -43,12 +43,12 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import io.jsonwebtoken.JwtException; @@ -58,25 +58,28 @@ @RestController @Tag(name = "Login") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class LoginController { - private HttpSession httpSession; + private final HttpSession httpSession; - private SessionAuditManager sessionAuditManager; + private final SessionAuditManager sessionAuditManager; - private TokenProvider tokenProvider; + private final TokenProvider tokenProvider; - private CustomAuthenticationManager authenticationManager; + private final CustomAuthenticationManager authenticationManager; - private UserBrowsingManager userManager; + private final UserBrowsingManager userManager; private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class); - public LoginController(HttpSession httpSession, - SessionAuditManager sessionAuditManager, - TokenProvider tokenProvider, - CustomAuthenticationManager authenticationManager, - UserBrowsingManager userManager) { + public LoginController( + HttpSession httpSession, + SessionAuditManager sessionAuditManager, + TokenProvider tokenProvider, + CustomAuthenticationManager authenticationManager, + UserBrowsingManager userManager + ) { this.httpSession = httpSession; this.sessionAuditManager = sessionAuditManager; this.tokenProvider = tokenProvider; @@ -84,10 +87,12 @@ public LoginController(HttpSession httpSession, this.userManager = userManager; } - @PostMapping(value = "/auth/login", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity authenticateUser(@Valid @RequestBody LoginRequest loginRequest) throws OHAPIException { + @PostMapping(value = "/auth/login") + public LoginResponse authenticateUser( + @Valid @RequestBody LoginRequest loginRequest + ) { Authentication authentication = authenticationManager.authenticate( - new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())); + new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())); SecurityContextHolder.getContext().setAuthentication(authentication); String jwt = tokenProvider.generateJwtToken(authentication, false); // use the shorter validity String refreshToken = tokenProvider.generateRefreshToken(authentication); @@ -103,16 +108,16 @@ public ResponseEntity authenticateUser(@Valid @RequestBody LoginR try { this.httpSession.setAttribute("sessionAuditId", - sessionAuditManager.newSessionAudit(new SessionAudit(userDetails, LocalDateTime.now(), null))); + sessionAuditManager.newSessionAudit(new SessionAudit(userDetails, LocalDateTime.now(), null))); } catch (OHServiceException e1) { LOGGER.error("Unable to log user login in the session_audit table"); } - return ResponseEntity.ok(new LoginResponse(jwt, refreshToken, userDetails)); + return new LoginResponse(jwt, refreshToken, userDetails); } @PostMapping("/auth/refresh-token") - public ResponseEntity refreshToken(@RequestBody TokenRefreshRequest request) throws OHAPIException { + public LoginResponse refreshToken(@RequestBody TokenRefreshRequest request) throws OHAPIException { String refreshToken = request.getRefreshToken(); try { @@ -122,7 +127,7 @@ public ResponseEntity refreshToken(@RequestBody TokenRefreshReque String newAccessToken = tokenProvider.generateJwtToken(authentication, false); String newRefreshToken = tokenProvider.generateRefreshToken(authentication); - return ResponseEntity.ok(new LoginResponse(newAccessToken, newRefreshToken, username)); + return new LoginResponse(newAccessToken, newRefreshToken, username); } else { throw new OHAPIException(new OHExceptionMessage("Invalid Refresh Token")); } @@ -130,5 +135,4 @@ public ResponseEntity refreshToken(@RequestBody TokenRefreshReque throw new OHAPIException(new OHExceptionMessage("Refresh token expired or invalid")); } } - } diff --git a/src/main/java/org/isf/malnutrition/rest/MalnutritionController.java b/src/main/java/org/isf/malnutrition/rest/MalnutritionController.java index 7160466c1..3a900b189 100644 --- a/src/main/java/org/isf/malnutrition/rest/MalnutritionController.java +++ b/src/main/java/org/isf/malnutrition/rest/MalnutritionController.java @@ -36,129 +36,139 @@ import org.isf.utils.exception.model.OHExceptionMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/malnutritions") +@RestController @Tag(name = "Malnutritions") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class MalnutritionController { private static final Logger LOGGER = LoggerFactory.getLogger(MalnutritionController.class); - @Autowired - private MalnutritionMapper mapper; - - @Autowired - private MalnutritionManager manager; - + private final MalnutritionMapper mapper; + + private final MalnutritionManager manager; + + public MalnutritionController(MalnutritionMapper mapper, MalnutritionManager manager) { + this.mapper = mapper; + this.manager = manager; + } + /** * Stores a new {@link Malnutrition}. The malnutrition object is updated with the generated id. * @param malnutritionDTO the malnutrition to store. - * @return {@link ResponseEntity} with status {@code HttpStatus.CREATED} if the malnutrition has been stored - * @throws OHServiceException + * @return the malnutrition that has been stored + * @throws OHServiceException When failed to store the malnutrition */ - @PostMapping(value = "/malnutritions", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity newMalnutrition(@RequestBody @Valid MalnutritionDTO malnutritionDTO) throws OHServiceException{ + @PostMapping(value = "/malnutritions") + @ResponseStatus(HttpStatus.CREATED) + public MalnutritionDTO newMalnutrition( + @RequestBody @Valid MalnutritionDTO malnutritionDTO + ) throws OHServiceException{ LOGGER.info("Creating a new malnutrition ..."); Malnutrition isCreatedMalnutrition = manager.newMalnutrition(mapper.map2Model(malnutritionDTO)); if (isCreatedMalnutrition == null) { LOGGER.info("Malnutrition is not created!"); - throw new OHAPIException(new OHExceptionMessage("Malnutrition not created.")); - } + throw new OHAPIException(new OHExceptionMessage("Malnutrition not created.")); + } LOGGER.info("Malnutrition successfully created!"); - return ResponseEntity.status(HttpStatus.CREATED).body(mapper.map2DTO(isCreatedMalnutrition)); + + return mapper.map2DTO(isCreatedMalnutrition); } - + /** * Retrieves all the {@link Malnutrition} associated to the given admission id. * @param admissionID the admission id to use as filter. * @return all the retrieved malnutrition. - * @throws OHServiceException + * @throws OHServiceException When failed to get malnutrition */ - @GetMapping(value = "/malnutritions/{id_admission}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getMalnutrition(@PathVariable("id_admission") String admissionID) throws OHServiceException{ + @GetMapping(value = "/malnutritions/{id_admission}") + public List getMalnutrition( + @PathVariable("id_admission") String admissionID + ) throws OHServiceException{ LOGGER.info("Looking for malnutrition controls. Admission ID is {}", admissionID); + List malnutritions = manager.getMalnutrition(admissionID); if (malnutritions == null) { throw new OHAPIException(new OHExceptionMessage("Error while retrieving malnutrition controls.")); } - List mappedMalnutritions = mapper.map2DTOList(malnutritions); - if (mappedMalnutritions.isEmpty()) { - LOGGER.info("No malnutrition control found"); - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(mappedMalnutritions); - } else { - LOGGER.info("Found {} malnutrition controls", mappedMalnutritions.size()); - return ResponseEntity.ok(mappedMalnutritions); - } + + return mapper.map2DTOList(malnutritions); } - + /** * Returns the last {@link Malnutrition} entry for specified patient ID. * @param patientID - the patient ID * @return the last {@link Malnutrition} for specified patient ID. - * @throws OHServiceException + * @throws OHServiceException When failed to get last malnutrition */ - @GetMapping(value = "/malnutritions/last/{id_patient}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getLastMalnutrition(@PathVariable("id_patient") int patientID) throws OHServiceException { + @GetMapping(value = "/malnutritions/last/{id_patient}") + public MalnutritionDTO getLastMalnutrition( + @PathVariable("id_patient") int patientID + ) throws OHServiceException { Malnutrition foundMalnutrition = manager.getLastMalnutrition(patientID); if (foundMalnutrition == null) { - throw new OHAPIException(new OHExceptionMessage("No malnutrition found.")); - } else { - return ResponseEntity.ok(mapper.map2DTO(foundMalnutrition)); + throw new OHAPIException(new OHExceptionMessage("No malnutrition found.")); } + + return mapper.map2DTO(foundMalnutrition); } - + /** * Updates the specified {@link Malnutrition}. * @param malnutritionDTO the {@link Malnutrition} to update * @return the updated {@link Malnutrition} - * @throws OHServiceException + * @throws OHServiceException When failed to update malnutrition */ - @PutMapping(value = "/malnutritions", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity updateMalnutrition(@RequestBody @Valid MalnutritionDTO malnutritionDTO) throws OHServiceException { - Malnutrition updatedMalnutrition = manager.updateMalnutrition(mapper.map2Model(malnutritionDTO)); - return ResponseEntity.ok(mapper.map2DTO(updatedMalnutrition)); + @PutMapping(value = "/malnutritions") + public MalnutritionDTO updateMalnutrition( + @RequestBody @Valid MalnutritionDTO malnutritionDTO + ) throws OHServiceException { + return mapper.map2DTO(manager.updateMalnutrition(mapper.map2Model(malnutritionDTO))); } - + /** * Deletes a given {@link Malnutrition}. * @param code - the code of malnutrition to delete. * @return {@code true} if the malnutrition has been deleted, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to delete malnutrition */ - @DeleteMapping(value = "/malnutritions", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity deleteMalnutrition(@RequestParam int code) throws OHServiceException{ - Malnutrition malNutri = manager.getMalnutrition(code); - List malnutritions = manager.getMalnutrition(String.valueOf(malNutri.getAdmission().getId())); + @DeleteMapping(value = "/malnutritions") + public boolean deleteMalnutrition(@RequestParam int code) throws OHServiceException{ + Malnutrition malnutrition = manager.getMalnutrition(code); + List malnutritions = manager.getMalnutrition(String.valueOf(malnutrition.getAdmission().getId())); List matchedMalnutritions = new ArrayList<>(); if (malnutritions != null) { matchedMalnutritions = malnutritions - .stream() - .filter(malnutrition -> malnutrition.getCode() == code) - .collect(Collectors.toList()); + .stream() + .filter(item -> item.getCode() == code) + .collect(Collectors.toList()); } + if (matchedMalnutritions.isEmpty()) { throw new OHAPIException(new OHExceptionMessage("Malnutrition control not found.")); } + try { manager.deleteMalnutrition(matchedMalnutritions.get(0)); + return true; } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Malnutrition not deleted.")); } - return ResponseEntity.ok(true); } } diff --git a/src/main/java/org/isf/medical/rest/MedicalController.java b/src/main/java/org/isf/medical/rest/MedicalController.java index 2c376a130..ab09d2c69 100644 --- a/src/main/java/org/isf/medical/rest/MedicalController.java +++ b/src/main/java/org/isf/medical/rest/MedicalController.java @@ -35,191 +35,185 @@ import org.isf.utils.exception.model.OHExceptionMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/medicals") +@RestController @Tag(name = "Medicals") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class MedicalController { private static final Logger LOGGER = LoggerFactory.getLogger(MedicalController.class); - @Autowired - private MedicalBrowsingManager medicalManager; - - @Autowired - private MedicalMapper mapper; - + private final MedicalBrowsingManager medicalManager; + + private final MedicalMapper mapper; + + public MedicalController(MedicalBrowsingManager medicalManager, MedicalMapper mapper) { + this.medicalManager = medicalManager; + this.mapper = mapper; + } /** * Returns the requested medical. * @param code the medical code. * @return the retrieved medical. - * @throws OHServiceException + * @throws OHServiceException When failed to get medical */ - @GetMapping(value = "/medicals/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getMedical(@PathVariable int code) throws OHServiceException { + @GetMapping(value = "/medicals/{code}") + public MedicalDTO getMedical(@PathVariable int code) throws OHServiceException { LOGGER.info("Retrieving medical with code {} ...", code); Medical medical = medicalManager.getMedical(code); if (medical == null) { LOGGER.info("Medical not found."); throw new OHAPIException(new OHExceptionMessage("Medical not found.")); - } else { - LOGGER.info("Medical retrieved successfully."); - return ResponseEntity.ok(mapper.map2DTO(medical)); } + + LOGGER.info("Medical {} retrieved successfully.", medical.getDescription()); + + return mapper.map2DTO(medical); } - + /** * Returns all the medicals. * @param sortBy - specifies by which property the medicals should be sorted * @return all the medicals. - * @throws OHServiceException + * @throws OHServiceException When failed to get medicals */ - @GetMapping(value = "/medicals", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getMedicals(@RequestParam(name="sort_by", required=false) MedicalSortBy sortBy) - throws OHServiceException { + @GetMapping(value = "/medicals") + public List getMedicals( + @RequestParam(name="sort_by", required=false) MedicalSortBy sortBy + ) throws OHServiceException { LOGGER.info("Retrieving all the medicals..."); + List medicals; if (sortBy == null || sortBy == MedicalSortBy.NONE) { medicals = medicalManager.getMedicals(); - } - else if (sortBy == MedicalSortBy.CODE) { + } else if (sortBy == MedicalSortBy.CODE) { medicals = medicalManager.getMedicalsSortedByCode(); } else { //sortBy == MedicalSortBy.NAME medicals = medicalManager.getMedicalsSortedByName(); } + if (medicals == null) { - throw new OHAPIException(new OHExceptionMessage("Error while retrieving medicals.")); - } - List mappedMedicals = mapper.map2DTOList(medicals); - if (mappedMedicals.isEmpty()) { - LOGGER.info("No medical found."); - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(mappedMedicals); - } else { - LOGGER.info("Found {} medicals.", mappedMedicals.size()); - return ResponseEntity.ok(mappedMedicals); + throw new OHAPIException(new OHExceptionMessage("Error while retrieving medicals."), HttpStatus.INTERNAL_SERVER_ERROR); } + + return mapper.map2DTOList(medicals); } - + /** * Returns all the medicals with the specified criteria. * @param description - the medical description * @param type - the medical type * @param critical - {@code true} to include only medicals under critical level * @param nameSorted - if {@code true} return the list in alphabetical order - * @return - * @throws OHServiceException + * @return The filtered list of medicals + * @throws OHServiceException When failed to get medicals */ - @GetMapping(value = "/medicals/filter", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> filterMedicals( - @RequestParam(name="desc", required=false) String description, - @RequestParam(name="type", required=false) String type, - @RequestParam(name="critical", defaultValue="false") boolean critical, - @RequestParam(name="name_sorted", defaultValue="false") boolean nameSorted) throws OHServiceException { + @GetMapping(value = "/medicals/filter") + public List filterMedicals( + @RequestParam(name="desc", required=false) String description, + @RequestParam(name="type", required=false) String type, + @RequestParam(name="critical", defaultValue="false") boolean critical, + @RequestParam(name="name_sorted", defaultValue="false") boolean nameSorted + ) throws OHServiceException { LOGGER.info("Filtering the medicals..."); List medicals; if (description != null && type != null) { medicals = medicalManager.getMedicals(description, type, critical); - } else if (description != null && type == null) { + } else if (description != null) { medicals = medicalManager.getMedicals(description); - } else if (description == null && type != null) { + } else if (type != null) { medicals = medicalManager.getMedicals(type, nameSorted); } else if (nameSorted){ - medicals = medicalManager.getMedicals(null, nameSorted); + medicals = medicalManager.getMedicals(null, true); } else { medicals = medicalManager.getMedicals(); } - + if (medicals == null) { throw new OHAPIException(new OHExceptionMessage("Error while retrieving medicals.")); } - List mappedMedicals = mapper.map2DTOList(medicals); - if (mappedMedicals.isEmpty()) { - LOGGER.info("No medical found."); - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(mappedMedicals); - } else { - LOGGER.info("Found {} medicals.", mappedMedicals.size()); - return ResponseEntity.ok(mappedMedicals); - } + + return mapper.map2DTOList(medicals); } - + /** * Saves the specified {@link Medical}. * @param medicalDTO - the medical to save * @param ignoreSimilar - if {@code true}, it ignore the warning "similarsFoundWarning" - * @return {@link ResponseEntity} with status {@code HttpStatus.CREATED} if the medical was created - * @throws OHServiceException + * @return The created medical + * @throws OHServiceException When failed to save the medical */ - @PostMapping(value = "/medicals", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity newMedical( - @RequestBody MedicalDTO medicalDTO, - @RequestParam(name="ignore_similar", defaultValue="false") boolean ignoreSimilar) throws OHServiceException { + @PostMapping(value = "/medicals") + @ResponseStatus(HttpStatus.CREATED) + public MedicalDTO newMedical( + @RequestBody MedicalDTO medicalDTO, + @RequestParam(name="ignore_similar", defaultValue="false") boolean ignoreSimilar + ) throws OHServiceException { LOGGER.info("Creating a new medical ..."); - Medical createdMedical; try { - createdMedical = medicalManager.newMedical(mapper.map2Model(medicalDTO), ignoreSimilar); + LOGGER.info("Medical successfully created."); + return mapper.map2DTO(medicalManager.newMedical(mapper.map2Model(medicalDTO), ignoreSimilar)); } catch (OHServiceException serviceException) { LOGGER.info("Medical is not created."); - throw new OHAPIException(new OHExceptionMessage("Medical not created.")); - } - LOGGER.info("Medical successfully created."); - return ResponseEntity.status(HttpStatus.CREATED).body(mapper.map2DTO(createdMedical)); + throw new OHAPIException(new OHExceptionMessage("Medical not created.")); + } } - + /** * Updates the specified {@link Medical}. * @param medicalDTO - the medical to update * @param ignoreSimilar - if {@code true}, it ignore the warning "similarsFoundWarning" - * @return {@link ResponseEntity} with status {@code HttpStatus.OK} if the medical was updated - * @throws OHServiceException + * @return The updated medical + * @throws OHServiceException When failed to update medical */ - @PutMapping(value = "/medicals", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity updateMedical( - @RequestBody @Valid MedicalDTO medicalDTO, - @RequestParam(name="ignore_similar", defaultValue="false") boolean ignoreSimilar) throws OHServiceException { + @PutMapping(value = "/medicals") + public MedicalDTO updateMedical( + @RequestBody @Valid MedicalDTO medicalDTO, + @RequestParam(name="ignore_similar", defaultValue="false") boolean ignoreSimilar + ) throws OHServiceException { LOGGER.info("Updating a medical ..."); - Medical updatedMedical; try { - updatedMedical = medicalManager.updateMedical(mapper.map2Model(medicalDTO), ignoreSimilar); + LOGGER.info("Medical successfully updated."); + return mapper.map2DTO(medicalManager.updateMedical(mapper.map2Model(medicalDTO), ignoreSimilar)); } catch (OHServiceException serviceException) { LOGGER.info("Medical is not updated."); - throw new OHAPIException(new OHExceptionMessage("Medical not updated.")); - } - LOGGER.info("Medical successfully updated."); - return ResponseEntity.status(HttpStatus.OK).body(mapper.map2DTO(updatedMedical)); + throw new OHAPIException(new OHExceptionMessage("Medical not updated.")); + } } - + /** * Deletes the specified {@link Medical}. * @param code the medical to delete. * @return {@code true} if the medical has been deleted. - * @throws OHServiceException + * @throws OHServiceException When failed to delete medical */ - @DeleteMapping(value = "/medicals/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity deleteMedical(@PathVariable Integer code) throws OHServiceException { + @DeleteMapping(value = "/medicals/{code}") + public boolean deleteMedical(@PathVariable Integer code) throws OHServiceException { Medical medical = medicalManager.getMedical(code); if (medical == null) { - throw new OHAPIException(new OHExceptionMessage("Medical not found.")); + throw new OHAPIException(new OHExceptionMessage("Medical not found."), HttpStatus.NOT_FOUND); } try { medicalManager.deleteMedical(medical); + return true; } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Medical not deleted")); } - return ResponseEntity.ok(true); } } diff --git a/src/main/java/org/isf/medicalstock/rest/MedicalStockMovementController.java b/src/main/java/org/isf/medicalstock/rest/MedicalStockMovementController.java index 11c3e7ed0..f652ad701 100644 --- a/src/main/java/org/isf/medicalstock/rest/MedicalStockMovementController.java +++ b/src/main/java/org/isf/medicalstock/rest/MedicalStockMovementController.java @@ -39,192 +39,199 @@ import org.isf.utils.exception.OHServiceException; import org.isf.utils.exception.model.OHExceptionMessage; import org.isf.ward.model.Ward; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/medicalstockmovements") +@RestController @Tag(name = "Stock Movements") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class MedicalStockMovementController { - @Autowired - private MovementMapper movMapper; + private final MovementMapper movMapper; - @Autowired - private LotMapper lotMapper; + private final LotMapper lotMapper; - @Autowired - private MovBrowserManager movManager; + private final MovBrowserManager movManager; - @Autowired - private MovStockInsertingManager movInsertingManager; + private final MovStockInsertingManager movInsertingManager; - @Autowired - private MedicalBrowsingManager medicalManager; + private final MedicalBrowsingManager medicalManager; + + public MedicalStockMovementController( + MovementMapper movMapper, + LotMapper lotMapper, + MovBrowserManager movManager, + MovStockInsertingManager movInsertingManager, + MedicalBrowsingManager medicalManager + ) { + this.movMapper = movMapper; + this.lotMapper = lotMapper; + this.movManager = movManager; + this.movInsertingManager = movInsertingManager; + this.medicalManager = medicalManager; + } /** * Insert a list of charging {@link Movement}s and related {@link Lot}s. - * + * * @param movementDTOs - the list of {@link Movement}s * @param referenceNumber - the reference number to be set for all movements * if {@link null}, each movement must have a different referenceNumber - * @return - * @throws OHServiceException + * @return true if movements have been created, false or throw exception + * otherwise + * @throws OHServiceException when failed to create movements */ - @PostMapping(value = "/medicalstockmovements/charge", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity newMultipleChargingMovements(@RequestBody List movementDTOs, - @RequestParam(name = "ref", required = true) String referenceNumber) throws OHServiceException { + @PostMapping("/medicalstockmovements/charge") + @ResponseStatus(HttpStatus.CREATED) + public boolean newMultipleChargingMovements( + @RequestBody List movementDTOs, + @RequestParam(name = "ref") String referenceNumber + ) throws OHServiceException { List movements = new ArrayList<>(movMapper.map2ModelList(movementDTOs)); movInsertingManager.newMultipleChargingMovements(movements, referenceNumber); - return ResponseEntity.status(HttpStatus.CREATED).body(true); + return true; } /** * Insert a list of discharging {@link Movement}s. - * + * * @param movementDTOs - the list of {@link Movement}s * @param referenceNumber - the reference number to be set for all movements * if {@link null}, each movement must have a different referenceNumber - * @return - * @throws OHServiceException + * @return true if movements have been created, false or throw exception + * otherwise + * @throws OHServiceException When failed to create discharge movements */ - @PostMapping(value = "/medicalstockmovements/discharge", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity newMultipleDischargingMovements(@RequestBody List movementDTOs, - @RequestParam(name = "ref", required = true) String referenceNumber) throws OHServiceException { + @PostMapping("/medicalstockmovements/discharge") + @ResponseStatus(HttpStatus.CREATED) + public boolean newMultipleDischargingMovements( + @RequestBody List movementDTOs, + @RequestParam(name = "ref") String referenceNumber + ) throws OHServiceException { List movements = new ArrayList<>(movMapper.map2ModelList(movementDTOs)); movInsertingManager.newMultipleDischargingMovements(movements, referenceNumber); - return ResponseEntity.status(HttpStatus.CREATED).body(true); + + return true; } /** * Retrieves all the {@link Movement}s. * @return the retrieved movements. - * @throws OHServiceException + * @throws OHServiceException When failed to get movements */ - @GetMapping(value = "/medicalstockmovements", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getMovements() throws OHServiceException { - List movements = movManager.getMovements(); - return collectResults(movements); + @GetMapping("/medicalstockmovements") + public List getMovements() throws OHServiceException { + return movMapper.map2DTOList(movManager.getMovements()); } /** * Retrieves all the movement associated to the specified {@link Ward}. - * @param wardId - * @param dateFrom - * @param dateTo + * + * @param wardId Ward Code + * @param dateFrom Start date + * @param dateTo End date * @return the retrieved movements. - * @throws OHServiceException + * @throws OHServiceException When failed to get ward movements */ - @GetMapping(value = "/medicalstockmovements/filter/v1", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getMovements( - @RequestParam("ward_id") String wardId, - @RequestParam("from") LocalDateTime dateFrom, - @RequestParam("to") LocalDateTime dateTo) throws OHServiceException { - List movements = movManager.getMovements(wardId, dateFrom, dateTo); - return collectResults(movements); + @GetMapping("/medicalstockmovements/filter/v1") + public List getMovements( + @RequestParam("ward_id") String wardId, + @RequestParam("from") LocalDateTime dateFrom, + @RequestParam("to") LocalDateTime dateTo + ) throws OHServiceException { + return movMapper.map2DTOList(movManager.getMovements(wardId, dateFrom, dateTo)); } /** * Retrieves all the movement associated to the specified reference number. - * @param refNo + * @param refNo Reference ID * @return the retrieved movements - * @throws OHServiceException + * @throws OHServiceException When failed to get movements */ - @GetMapping(value = "/medicalstockmovements/{ref}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getMovements(@PathVariable("ref") String refNo) throws OHServiceException { - List movements = movManager.getMovementsByReference(refNo); - return collectResults(movements); + @GetMapping("/medicalstockmovements/{ref}") + public List getMovements(@PathVariable("ref") String refNo) throws OHServiceException { + return movMapper.map2DTOList(movManager.getMovementsByReference(refNo)); } /** * Retrieves all the {@link Movement}s with the specified criteria. - * @param medicalCode - * @param medicalType - * @param wardId - * @param movType - * @param movFrom - * @param movTo - * @param lotPrepFrom - * @param lotPrepTo - * @param lotDueFrom - * @param lotDueTo + * @param medicalCode Medical code + * @param medicalType Medical type + * @param wardId Ward code + * @param movType Movement type + * @param movFrom Movement start date + * @param movTo Movement end date + * @param lotPrepFrom Lot preparation start date + * @param lotPrepTo Lot preparation end date + * @param lotDueFrom Lot expiration start date + * @param lotDueTo Lot expiration end date * @return the retrieved movements. - * @throws OHServiceException + * @throws OHServiceException When failed to get movements */ - @GetMapping(value = "/medicalstockmovements/filter/v2", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getMovements( - @RequestParam(name = "med_code", required = false) Integer medicalCode, - @RequestParam(name = "med_type", required = false) String medicalType, - @RequestParam(name = "ward_id", required = false) String wardId, - @RequestParam(name = "mov_type", required = false) String movType, - @RequestParam(name = "mov_from", required = false) LocalDateTime movFrom, - @RequestParam(name = "mov_to", required = false) LocalDateTime movTo, - @RequestParam(name = "lot_prep_from", required = false) LocalDateTime lotPrepFrom, - @RequestParam(name = "lot_prep_to", required = false) LocalDateTime lotPrepTo, - @RequestParam(name = "lot_due_from", required = false) LocalDateTime lotDueFrom, - @RequestParam(name = "lot_due_to", required = false) LocalDateTime lotDueTo) throws OHServiceException { - - List movements = movManager.getMovements(medicalCode, medicalType, wardId, movType, movFrom, movTo, lotPrepFrom, lotPrepTo, lotDueFrom, - lotDueTo); - return collectResults(movements); + @GetMapping("/medicalstockmovements/filter/v2") + public List getMovements( + @RequestParam(name = "med_code", required = false) Integer medicalCode, + @RequestParam(name = "med_type", required = false) String medicalType, + @RequestParam(name = "ward_id", required = false) String wardId, + @RequestParam(name = "mov_type", required = false) String movType, + @RequestParam(name = "mov_from", required = false) LocalDateTime movFrom, + @RequestParam(name = "mov_to", required = false) LocalDateTime movTo, + @RequestParam(name = "lot_prep_from", required = false) LocalDateTime lotPrepFrom, + @RequestParam(name = "lot_prep_to", required = false) LocalDateTime lotPrepTo, + @RequestParam(name = "lot_due_from", required = false) LocalDateTime lotDueFrom, + @RequestParam(name = "lot_due_to", required = false) LocalDateTime lotDueTo + ) throws OHServiceException { + return movMapper.map2DTOList( + movManager.getMovements( + medicalCode, medicalType, wardId, movType, movFrom, movTo, lotPrepFrom, lotPrepTo, lotDueFrom, lotDueTo + ) + ); } /** * Retrieves all the {@link Lot} associated to the specified {@link Medical}, expiring first on top - * @param medCode + * @param medCode Medical code * @return the retrieved lots. - * @throws OHServiceException + * @throws OHServiceException When failed to */ - @GetMapping(value = "/medicalstockmovements/lot/{med_code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getLotByMedical(@PathVariable("med_code") int medCode) throws OHServiceException { + @GetMapping("/medicalstockmovements/lot/{med_code}") + public List getLotByMedical(@PathVariable("med_code") int medCode) throws OHServiceException { Medical med = medicalManager.getMedical(medCode); if (med == null) { - throw new OHAPIException(new OHExceptionMessage("Medical not found.")); - } - List lots = movInsertingManager.getLotByMedical(med); - List mappedLots = lotMapper.map2DTOList(lots); - if (mappedLots.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(mappedLots); - } else { - return ResponseEntity.ok(mappedLots); + throw new OHAPIException(new OHExceptionMessage("Medical not found."), HttpStatus.NOT_FOUND); } + return lotMapper.map2DTOList(movInsertingManager.getLotByMedical(med)); } /** * Checks if the provided quantity is under the medical limits. - * @param medCode - * @param specifiedQuantity + * @param medCode Medical code + * @param specifiedQuantity Quantity to check * @return {@code true} if is under the limit, false otherwise - * @throws OHServiceException + * @throws OHServiceException When failed to check quantity */ - @GetMapping(value = "/medicalstockmovements/critical/check", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity alertCriticalQuantity( - @RequestParam("med_code") int medCode, - @RequestParam("qty") int specifiedQuantity) throws OHServiceException { + @GetMapping("/medicalstockmovements/critical/check") + public boolean alertCriticalQuantity( + @RequestParam("med_code") int medCode, + @RequestParam("qty") int specifiedQuantity + ) throws OHServiceException { Medical med = medicalManager.getMedical(medCode); if (med == null) { - throw new OHAPIException(new OHExceptionMessage("Medical not found.")); + throw new OHAPIException(new OHExceptionMessage("Medical not found."), HttpStatus.NOT_FOUND); } - return ResponseEntity.ok(movInsertingManager.alertCriticalQuantity(med, specifiedQuantity)); - } - private ResponseEntity> collectResults(List movements) { - List mappedMovements = movMapper.map2DTOList(movements); - if (mappedMovements.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(mappedMovements); - } else { - return ResponseEntity.ok(mappedMovements); - } + return movInsertingManager.alertCriticalQuantity(med, specifiedQuantity); } } diff --git a/src/main/java/org/isf/medicalstock/rest/StockMovementController.java b/src/main/java/org/isf/medicalstock/rest/StockMovementController.java index 56e77a732..eb45537a3 100644 --- a/src/main/java/org/isf/medicalstock/rest/StockMovementController.java +++ b/src/main/java/org/isf/medicalstock/rest/StockMovementController.java @@ -39,191 +39,200 @@ import org.isf.utils.exception.OHServiceException; import org.isf.utils.exception.model.OHExceptionMessage; import org.isf.ward.model.Ward; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "stockmovements") +@RestController @Tag(name = "Stock Movements") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class StockMovementController { - @Autowired - private MovementMapper movMapper; - - @Autowired - private LotMapper lotMapper; - - @Autowired - private MovBrowserManager movManager; - - @Autowired - private MovStockInsertingManager movInsertingManager; - - @Autowired - private MedicalBrowsingManager medicalManager; - + private final MovementMapper movMapper; + + private final LotMapper lotMapper; + + private final MovBrowserManager movManager; + + private final MovStockInsertingManager movInsertingManager; + + private final MedicalBrowsingManager medicalManager; + + public StockMovementController( + MovementMapper movMapper, + LotMapper lotMapper, + MovBrowserManager movManager, + MovStockInsertingManager movInsertingManager, + MedicalBrowsingManager medicalManager + ) { + this.movMapper = movMapper; + this.lotMapper = lotMapper; + this.movManager = movManager; + this.movInsertingManager = movInsertingManager; + this.medicalManager = medicalManager; + } + /** * Insert a list of charging {@link Movement}s and related {@link Lot}s. - * + * * @param movementDTOs - the list of {@link Movement}s * @param referenceNumber - the reference number to be set for all movements * if {@link null}, each movement must have a different referenceNumber - * @return - * @throws OHServiceException + * @return true if the movements have been created, false or + * throw exception otherwise + * @throws OHServiceException When failed to create movements */ - @PostMapping(value = "/stockmovements/charge", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity newMultipleChargingMovements(@RequestBody List movementDTOs, - @RequestParam(name="ref", required=true) String referenceNumber) throws OHServiceException { + @PostMapping("/stockmovements/charge") + @ResponseStatus(HttpStatus.CREATED) + public boolean newMultipleChargingMovements( + @RequestBody List movementDTOs, + @RequestParam(name="ref", required=true) String referenceNumber + ) throws OHServiceException { List movements = new ArrayList<>(movMapper.map2ModelList(movementDTOs)); movInsertingManager.newMultipleChargingMovements(movements, referenceNumber); - return ResponseEntity.status(HttpStatus.CREATED).body(true); + + return true; } - + /** * Insert a list of discharging {@link Movement}s. - * + * * @param movementDTOs - the list of {@link Movement}s * @param referenceNumber - the reference number to be set for all movements * if {@link null}, each movement must have a different referenceNumber - * @return - * @throws OHServiceException + * @return true if the movements have been created, false or + * throw exception otherwise + * @throws OHServiceException When failed to create movements */ - @PostMapping(value = "/stockmovements/discharge", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity newMultipleDischargingMovements(@RequestBody List movementDTOs, - @RequestParam(name="ref", required=true) String referenceNumber) throws OHServiceException { + @PostMapping("/stockmovements/discharge") + @ResponseStatus(HttpStatus.CREATED) + public boolean newMultipleDischargingMovements( + @RequestBody List movementDTOs, + @RequestParam(name="ref", required=true) String referenceNumber + ) throws OHServiceException { List movements = new ArrayList<>(movMapper.map2ModelList(movementDTOs)); movInsertingManager.newMultipleDischargingMovements(movements, referenceNumber); - return ResponseEntity.status(HttpStatus.CREATED).body(true); + + return true; } - + /** * Retrieves all the {@link Movement}s. * @return the retrieved movements. - * @throws OHServiceException + * @throws OHServiceException When failed to get movements */ - @GetMapping(value = "/stockmovements", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getMovements() throws OHServiceException { - List movements = movManager.getMovements(); - return collectResults(movements); + @GetMapping("/stockmovements") + public List getMovements() throws OHServiceException { + return movMapper.map2DTOList(movManager.getMovements()); } - + /** * Retrieves all the movement associated to the specified {@link Ward}. - * @param wardId - * @param dateFrom - * @param dateTo + * + * @param wardId Ward code + * @param dateFrom Start date + * @param dateTo End date * @return the retrieved movements. - * @throws OHServiceException + * @throws OHServiceException When failed to get movements */ - @GetMapping(value = "/stockmovements/filter/v1", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getMovements( - @RequestParam("ward_id") String wardId, - @RequestParam("from") LocalDateTime dateFrom, - @RequestParam("to") LocalDateTime dateTo) throws OHServiceException { - List movements = movManager.getMovements(wardId, dateFrom, dateTo); - return collectResults(movements); + @GetMapping("/stockmovements/filter/v1") + public List getMovements( + @RequestParam("ward_id") String wardId, + @RequestParam("from") LocalDateTime dateFrom, + @RequestParam("to") LocalDateTime dateTo + ) throws OHServiceException { + return movMapper.map2DTOList(movManager.getMovements(wardId, dateFrom, dateTo)); } - + /** * Retrieves all the movement associated to the specified reference number. - * @param refNo + * @param refNo Reference number * @return the retrieved movements - * @throws OHServiceException + * @throws OHServiceException When failed to get movements */ - @GetMapping(value = "/stockmovements/{ref}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getMovements(@PathVariable("ref") String refNo) throws OHServiceException { - List movements = movManager.getMovementsByReference(refNo); - return collectResults(movements); + @GetMapping("/stockmovements/{ref}") + public List getMovements(@PathVariable("ref") String refNo) throws OHServiceException { + return movMapper.map2DTOList(movManager.getMovementsByReference(refNo)); } - + /** * Retrieves all the {@link Movement}s with the specified criteria. - * @param medicalCode - * @param medicalType - * @param wardId - * @param movType - * @param movFrom - * @param movTo - * @param lotPrepFrom - * @param lotPrepTo - * @param lotDueFrom - * @param lotDueTo + * @param medicalCode Medical code + * @param medicalType Medical type + * @param wardId Ward code + * @param movType Movement type + * @param movFrom Movement start date + * @param movTo Movement end date + * @param lotPrepFrom Lot preparation start date + * @param lotPrepTo Lot preparation end date + * @param lotDueFrom Lot expiration start date + * @param lotDueTo Lot expiration end date * @return the retrieved movements. - * @throws OHServiceException + * @throws OHServiceException When failed to get movement */ - @GetMapping(value = "/stockmovements/filter/v2", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getMovements( - @RequestParam(name="med_code", required=false) Integer medicalCode, - @RequestParam(name="med_type", required=false) String medicalType, - @RequestParam(name="ward_id", required=false) String wardId, - @RequestParam(name="mov_type", required=false) String movType, - @RequestParam(name="mov_from", required=false) LocalDateTime movFrom, - @RequestParam(name="mov_to", required=false) LocalDateTime movTo, - @RequestParam(name="lot_prep_from", required=false) LocalDateTime lotPrepFrom, - @RequestParam(name="lot_prep_to", required=false) LocalDateTime lotPrepTo, - @RequestParam(name="lot_due_from", required=false) LocalDateTime lotDueFrom, - @RequestParam(name="lot_due_to", required=false) LocalDateTime lotDueTo) throws OHServiceException { - - List movements = movManager.getMovements(medicalCode, medicalType, wardId, movType, movFrom, movTo, lotPrepFrom, lotPrepTo, lotDueFrom, - lotDueTo); - return collectResults(movements); + @GetMapping("/stockmovements/filter/v2") + public List getMovements( + @RequestParam(name="med_code", required=false) Integer medicalCode, + @RequestParam(name="med_type", required=false) String medicalType, + @RequestParam(name="ward_id", required=false) String wardId, + @RequestParam(name="mov_type", required=false) String movType, + @RequestParam(name="mov_from", required=false) LocalDateTime movFrom, + @RequestParam(name="mov_to", required=false) LocalDateTime movTo, + @RequestParam(name="lot_prep_from", required=false) LocalDateTime lotPrepFrom, + @RequestParam(name="lot_prep_to", required=false) LocalDateTime lotPrepTo, + @RequestParam(name="lot_due_from", required=false) LocalDateTime lotDueFrom, + @RequestParam(name="lot_due_to", required=false) LocalDateTime lotDueTo + ) throws OHServiceException { + return movMapper.map2DTOList( + movManager.getMovements( + medicalCode, medicalType, wardId, movType, movFrom, movTo, lotPrepFrom, lotPrepTo, lotDueFrom, lotDueTo + ) + ); } - + /** * Retrieves all the {@link Lot} associated to the specified {@link Medical}, expiring first on top - * @param medCode + * @param medCode Medical code * @return the retrieved lots. - * @throws OHServiceException + * @throws OHServiceException When failed to get lot movements */ - @GetMapping(value = "/stockmovements/lot/{med_code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getLotByMedical(@PathVariable("med_code") int medCode) throws OHServiceException { + @GetMapping("/stockmovements/lot/{med_code}") + public List getLotByMedical(@PathVariable("med_code") int medCode) throws OHServiceException { Medical med = medicalManager.getMedical(medCode); if (med == null) { throw new OHAPIException(new OHExceptionMessage("Medical not found.")); } - List lots = movInsertingManager.getLotByMedical(med); - List mappedLots = lotMapper.map2DTOList(lots); - if (mappedLots.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(mappedLots); - } else { - return ResponseEntity.ok(mappedLots); - } + + return lotMapper.map2DTOList(movInsertingManager.getLotByMedical(med)); } - + /** * Checks if the provided quantity is under the medical limits. - * @param medCode - * @param specifiedQuantity + * @param medCode Medical code + * @param specifiedQuantity Quantity to check * @return {@code true} if is under the limit, false otherwise - * @throws OHServiceException + * @throws OHServiceException When failed to check medical quantity */ - @GetMapping(value = "/stockmovements/critical/check", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity alertCriticalQuantity( - @RequestParam("med_code") int medCode, - @RequestParam("qty") int specifiedQuantity) throws OHServiceException { + @GetMapping("/stockmovements/critical/check") + public boolean alertCriticalQuantity( + @RequestParam("med_code") int medCode, + @RequestParam("qty") int specifiedQuantity + ) throws OHServiceException { Medical med = medicalManager.getMedical(medCode); if (med == null) { throw new OHAPIException(new OHExceptionMessage("Medical not found.")); } - return ResponseEntity.ok(movInsertingManager.alertCriticalQuantity(med, specifiedQuantity)); - } - - private ResponseEntity> collectResults(List movements) { - List mappedMovements = movMapper.map2DTOList(movements); - if (mappedMovements.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(mappedMovements); - } else { - return ResponseEntity.ok(mappedMovements); - } + + return movInsertingManager.alertCriticalQuantity(med, specifiedQuantity); } } diff --git a/src/main/java/org/isf/medicalstockward/rest/MedicalStockWardController.java b/src/main/java/org/isf/medicalstockward/rest/MedicalStockWardController.java index 189c35064..897334a4d 100644 --- a/src/main/java/org/isf/medicalstockward/rest/MedicalStockWardController.java +++ b/src/main/java/org/isf/medicalstockward/rest/MedicalStockWardController.java @@ -24,7 +24,6 @@ import java.time.LocalDate; import java.time.LocalDateTime; import java.util.List; -import java.util.stream.Collectors; import jakarta.validation.Valid; @@ -42,62 +41,63 @@ import org.isf.utils.exception.model.OHExceptionMessage; import org.isf.ward.manager.WardBrowserManager; import org.isf.ward.model.Ward; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/medicalstockward") +@RestController @Tag(name = "Medical Stock Ward") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class MedicalStockWardController { - private static final Logger LOGGER = LoggerFactory.getLogger(MedicalStockWardController.class); + private final MedicalWardMapper medicalWardMapper; - @Autowired - private MedicalWardMapper medicalWardMapper; + private final MovementWardMapper movementWardMapper; - @Autowired - private MovementWardMapper movementWardMapper; + private final MovWardBrowserManager movWardBrowserManager; - @Autowired - private MovWardBrowserManager movWardBrowserManager; + private final MedicalBrowsingManager medicalManager; - @Autowired - private MedicalBrowsingManager medicalManager; + private final WardBrowserManager wardManager; - @Autowired - private WardBrowserManager wardManager; + public MedicalStockWardController( + MedicalWardMapper medicalWardMapper, + MovementWardMapper movementWardMapper, + MovWardBrowserManager movWardBrowserManager, + MedicalBrowsingManager medicalManager, + WardBrowserManager wardManager + ) { + this.medicalWardMapper = medicalWardMapper; + this.movementWardMapper = movementWardMapper; + this.movWardBrowserManager = movWardBrowserManager; + this.medicalManager = medicalManager; + this.wardManager = wardManager; + } /** * Gets all the {@link MedicalWard}s associated to the specified ward. * * @param wardId the ward id. * @return the retrieved {@link MedicalWard}s. - * @throws OHServiceException + * @throws OHServiceException When failed to get ward medicals */ - @GetMapping(value = "/medicalstockward/{ward_code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getMedicalsWard(@PathVariable("ward_code") char wardId) throws OHServiceException { - List medWards = movWardBrowserManager.getMedicalsWard(wardId, true); //FIXME: provide provision for boolean ,false? - List mappedMedWards = medicalWardMapper.map2DTOList(medWards); - if (mappedMedWards.isEmpty()) { - LOGGER.info("No medical found"); - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(mappedMedWards); - } else { - LOGGER.info("Found {} medicals", mappedMedWards.size()); - return ResponseEntity.ok(mappedMedWards); - } + @GetMapping(value = "/medicalstockward/{ward_code}") + public List getMedicalsWard(@PathVariable("ward_code") char wardId) throws OHServiceException { + // FIXME: provide provision for boolean ,false? + List medWards = movWardBrowserManager.getMedicalsWard(wardId, true); + + return medicalWardMapper.map2DTOList(medWards); } /** @@ -108,37 +108,23 @@ public ResponseEntity> getMedicalsWard(@PathVariable("ward_ * @return the total quantity. * @throws OHServiceException if an error occurs retrieving the quantity. */ - @GetMapping(value = "/medicalstockward/current/{ward_code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getCurrentQuantityInWard( - @PathVariable("ward_code") String wardId, - @RequestParam("med_id") int medicalId) throws OHServiceException { + @GetMapping(value = "/medicalstockward/current/{ward_code}") + public Integer getCurrentQuantityInWard( + @PathVariable("ward_code") String wardId, + @RequestParam("med_id") int medicalId + ) throws OHServiceException { Medical medical = medicalManager.getMedical(medicalId); if (medical == null) { - throw new OHAPIException(new OHExceptionMessage("Medical not found.")); + throw new OHAPIException(new OHExceptionMessage("Medical not found."), HttpStatus.NOT_FOUND); } - List wards = wardManager.getWards().stream().filter(w -> w.getCode().equals(wardId)).collect(Collectors.toList()); - if (wards == null || wards.isEmpty()) { - throw new OHAPIException(new OHExceptionMessage("Ward not found.")); + + List wards = wardManager.getWards().stream().filter(w -> w.getCode().equals(wardId)).toList(); + if (wards.isEmpty()) { + throw new OHAPIException(new OHExceptionMessage("Ward not found."), HttpStatus.NOT_FOUND); } - return ResponseEntity.ok(movWardBrowserManager.getCurrentQuantityInWard(wards.get(0), medical)); - } -// TODO: needs update when UI supports movements wards -// /** -// * Gets all the {@link MovementWard}s. -// * -// * @return all the retrieved movements ward. -// * @throws OHServiceException -// */ -// @GetMapping(value = "/medicalstockward/movements", produces = MediaType.APPLICATION_JSON_VALUE) -// public ResponseEntity> getMovementWard() throws OHServiceException { -// List mappedMovs = movementWardMapper.map2DTOList(movWardBrowserManager.getMovementWard()); -// if (mappedMovs.isEmpty()) { -// return ResponseEntity.status(HttpStatus.NO_CONTENT).body(mappedMovs); -// } else { -// return ResponseEntity.ok(mappedMovs); -// } -// } + return movWardBrowserManager.getCurrentQuantityInWard(wards.get(0), medical); + } /** * Gets all the movement ward with the specified criteria. @@ -147,14 +133,14 @@ public ResponseEntity getCurrentQuantityInWard( * @param dateFrom the lower bound for the movement date range. * @param dateTo the upper bound for the movement date range. * @return all the retrieved movements. - * @throws OHServiceException + * @throws OHServiceException When failed to get ward movements */ - @GetMapping(value = "/medicalstockward/movements/{ward_code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getMovementWard( - @PathVariable("ward_code") String wardId, - @RequestParam("from") LocalDate dateFrom, - @RequestParam("to") LocalDate dateTo) throws OHServiceException { - + @GetMapping("/medicalstockward/movements/{ward_code}") + public List getMovementWard( + @PathVariable("ward_code") String wardId, + @RequestParam("from") LocalDate dateFrom, + @RequestParam("to") LocalDate dateTo + ) throws OHServiceException { LocalDateTime dateFromTime = null; if (dateFrom != null) { dateFromTime = dateFrom.atStartOfDay(); @@ -165,36 +151,25 @@ public ResponseEntity> getMovementWard( dateToTime = dateTo.atStartOfDay(); } - List movs = movWardBrowserManager.getMovementWard(wardId, dateFromTime, dateToTime); - List mappedMovs = movementWardMapper.map2DTOList(movs); - if (mappedMovs.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(mappedMovs); - } else { - return ResponseEntity.ok(mappedMovs); - } + return movementWardMapper.map2DTOList(movWardBrowserManager.getMovementWard(wardId, dateFromTime, dateToTime)); } /** * Gets all the movement wards with the specified criteria. * - * @param idwardTo the target ward id. + * @param idWardTo the target ward id. * @param dateFrom the lower bound for the movement date range. * @param dateTo the upper bound for the movement date range. * @return all the retrieved movements. - * @throws OHServiceException + * @throws OHServiceException When failed to get ward movements */ - @GetMapping(value = "/medicalstockward/movements/to/{target_ward_code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getWardMovementsToWard( - @PathVariable("target_ward_code") String idwardTo, - @RequestParam("from") LocalDateTime dateFrom, - @RequestParam("to") LocalDateTime dateTo) throws OHServiceException { - - List movs = movWardBrowserManager.getWardMovementsToWard(idwardTo, dateFrom, dateTo); - List mappedMovs = movementWardMapper.map2DTOList(movs); - if (mappedMovs.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(mappedMovs); - } - return ResponseEntity.ok(mappedMovs); + @GetMapping(value = "/medicalstockward/movements/to/{target_ward_code}") + public List getWardMovementsToWard( + @PathVariable("target_ward_code") String idWardTo, + @RequestParam("from") LocalDateTime dateFrom, + @RequestParam("to") LocalDateTime dateTo + ) throws OHServiceException { + return movementWardMapper.map2DTOList(movWardBrowserManager.getWardMovementsToWard(idWardTo, dateFrom, dateTo)); } /** @@ -202,52 +177,16 @@ public ResponseEntity> getWardMovementsToWard( * * @param newMovementDTO the movement to persist. * @return {@code true} if the movement has been persisted, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to create ward stock movement */ - @PostMapping(value = "/medicalstockward/movements", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity newMovementWard(@Valid @RequestBody MovementWardDTO newMovementDTO) throws OHServiceException { + @PostMapping(value = "/medicalstockward/movements") + @ResponseStatus(HttpStatus.CREATED) + public boolean newMovementWard( + @Valid @RequestBody MovementWardDTO newMovementDTO + ) throws OHServiceException { MovementWard newMovement = movementWardMapper.map2Model(newMovementDTO); movWardBrowserManager.newMovementWard(newMovement); - return ResponseEntity.status(HttpStatus.CREATED).body(null); - } - -// TODO: needs update when UI supports movements wards -// /** -// * Persists the specified movements. -// * -// * @param newMovementDTOs the movements to persist. -// * @return {@code true} if the movements have been persisted, {@code false} otherwise. -// * @throws OHServiceException -// */ -// @PostMapping(value = "/medicalstockward/movements/all", produces = MediaType.APPLICATION_JSON_VALUE) -// public ResponseEntity newMovementWard(@Valid @RequestBody List newMovementDTOs) throws OHServiceException { -// List newMovements = new ArrayList<>(); -// newMovements.addAll(movementWardMapper.map2ModelList(newMovementDTOs)); -// movWardBrowserManager.newMovementWard(newMovements); -// return ResponseEntity.status(HttpStatus.CREATED).body(null); -// } -// -// TODO: needs update when UI supports movements wards -// /** -// * Updates the specified {@link MovementWard}. -// * -// * @param movementWardDTO the movement ward to update. -// * @return {@code true} if the movement has been updated, {@code false} otherwise. -// * @throws OHServiceException -// */ -// @PutMapping(value = "/medicalstockward/movements", produces = MediaType.APPLICATION_JSON_VALUE) -// public ResponseEntity updateMovementWard(@Valid @RequestBody MovementWardDTO movementWardDTO) throws OHServiceException { -// MovementWard movementWard = movementWardMapper.map2Model(movementWardDTO); -// boolean isPresent = movWardBrowserManager.getMovementWard().stream().anyMatch(mov -> mov.getCode() == movementWard.getCode()); -// if (!isPresent) { -// throw new OHAPIException(new OHExceptionMessage("Movement ward not found.")); -// } -// -// boolean isUpdated = movWardBrowserManager.updateMovementWard(movementWard); -// if (!isUpdated) { -// throw new OHAPIException(new OHExceptionMessage("Movement ward not updated.")); -// } -// return ResponseEntity.ok(isUpdated); -// } + return true; + } } diff --git a/src/main/java/org/isf/medstockmovtype/rest/MedStockMovementTypeController.java b/src/main/java/org/isf/medstockmovtype/rest/MedStockMovementTypeController.java index 916da0dc4..829bed7bb 100644 --- a/src/main/java/org/isf/medstockmovtype/rest/MedStockMovementTypeController.java +++ b/src/main/java/org/isf/medstockmovtype/rest/MedStockMovementTypeController.java @@ -22,7 +22,6 @@ package org.isf.medstockmovtype.rest; import java.util.List; -import java.util.stream.Collectors; import jakarta.validation.Valid; @@ -35,51 +34,48 @@ import org.isf.utils.exception.model.OHExceptionMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/medstockmovementtypes") +@RestController @Tag(name = "Medical Stock Movement Type") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class MedStockMovementTypeController { private static final Logger LOGGER = LoggerFactory.getLogger(MedStockMovementTypeController.class); - @Autowired - private MovementTypeMapper mapper; + private final MovementTypeMapper mapper; - @Autowired - private MedicalDsrStockMovementTypeBrowserManager manager; + private final MedicalDsrStockMovementTypeBrowserManager manager; + + public MedStockMovementTypeController(MovementTypeMapper mapper, MedicalDsrStockMovementTypeBrowserManager manager) { + this.mapper = mapper; + this.manager = manager; + } /** * Returns all the medical stock movement types. + * * @return all the medical stock movement types. - * @throws OHServiceException + * @throws OHServiceException When failed to get movement types */ - @GetMapping(value = "/medstockmovementtypes", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getMedicalDsrStockMovementType() throws OHServiceException { + @GetMapping(value = "/medstockmovementtypes") + public List getMedicalDsrStockMovementType() throws OHServiceException { LOGGER.info("Retrieving all the movement types ..."); - List movementTypes = manager.getMedicalDsrStockMovementType(); - List mappedMovements = mapper.map2DTOList(movementTypes); - if (mappedMovements.isEmpty()) { - LOGGER.info("No movement type found"); - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(mappedMovements); - } else { - LOGGER.info("Found {} movement types", mappedMovements.size()); - return ResponseEntity.ok(mappedMovements); - } + return mapper.map2DTOList(manager.getMedicalDsrStockMovementType()); } /** @@ -87,27 +83,31 @@ public ResponseEntity> getMedicalDsrStockMovementType() th * @param code - the code of the movement type. * @return {@link MovementType}. */ - @GetMapping(value = "/medstockmovementtypes/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getMovementType(@PathVariable("code") String code) throws OHServiceException { - MovementType foundMvmntType = manager.getMovementType(code); - if (foundMvmntType == null) { - throw new OHAPIException(new OHExceptionMessage("Movement type not found.")); + @GetMapping(value = "/medstockmovementtypes/{code}") + public MovementTypeDTO getMovementType(@PathVariable("code") String code) throws OHServiceException { + MovementType movementType = manager.getMovementType(code); + if (movementType == null) { + throw new OHAPIException(new OHExceptionMessage("Movement type not found."), HttpStatus.NOT_FOUND); } - return ResponseEntity.ok(mapper.map2DTO(foundMvmntType)); + + return mapper.map2DTO(movementType); } /** * Save the specified {@link MovementType}. + * * @param medicalDsrStockMovementType the medical stock movement type to save. - * @return {@link ResponseEntity} with status {@code HttpStatus.CREATED} if the medical stock movement type has been saved. - * @throws OHServiceException + * @return the created movement type + * @throws OHServiceException When failed to create movement type */ - @PostMapping(value = "/medstockmovementtypes", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity newMedicalDsrStockMovementType(@RequestBody @Valid MovementTypeDTO medicalDsrStockMovementType) - throws OHServiceException { + @PostMapping(value = "/medstockmovementtypes") + @ResponseStatus(HttpStatus.CREATED) + public MovementTypeDTO newMedicalDsrStockMovementType( + @RequestBody @Valid MovementTypeDTO medicalDsrStockMovementType + ) throws OHServiceException { try { MovementType isCreatedMovementType = manager.newMedicalDsrStockMovementType(mapper.map2Model(medicalDsrStockMovementType)); - return ResponseEntity.status(HttpStatus.CREATED).body(mapper.map2DTO(isCreatedMovementType)); + return mapper.map2DTO(isCreatedMovementType); } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Movement type not created.")); } @@ -115,20 +115,22 @@ public ResponseEntity newMedicalDsrStockMovementType(@RequestBo /** * Updates the specified {@link MovementType}. + * * @param medicalDsrStockMovementTypeDTO the medical stock movement type to update. - * @return {@link ResponseEntity} with status {@code HttpStatus.OK} if the medical stock movement type has been updated. - * @throws OHServiceException + * @return the updated movement type + * @throws OHServiceException When failed to update movement type */ - @PutMapping(value = "/medstockmovementtypes", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity updateMedicalDsrStockMovementType(@RequestBody @Valid MovementTypeDTO medicalDsrStockMovementTypeDTO) - throws OHServiceException { + @PutMapping(value = "/medstockmovementtypes") + public MovementTypeDTO updateMedicalDsrStockMovementType( + @RequestBody @Valid MovementTypeDTO medicalDsrStockMovementTypeDTO + ) throws OHServiceException { MovementType medicalDsrStockMovementType = mapper.map2Model(medicalDsrStockMovementTypeDTO); if (!manager.isCodePresent(medicalDsrStockMovementType.getCode())) { - throw new OHAPIException(new OHExceptionMessage("Movement type not found.")); + throw new OHAPIException(new OHExceptionMessage("Movement type not found."), HttpStatus.NOT_FOUND); } + try { - MovementType isUpdatedMovementType = manager.updateMedicalDsrStockMovementType(medicalDsrStockMovementType); - return ResponseEntity.ok(mapper.map2DTO(isUpdatedMovementType)); + return mapper.map2DTO(manager.updateMedicalDsrStockMovementType(medicalDsrStockMovementType)); } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Movement type not updated.")); } @@ -136,36 +138,38 @@ public ResponseEntity updateMedicalDsrStockMovementType(@Reques /** * Checks if the specified movement type's code is already used. + * * @param code the code to check. * @return {@code true} if the code is used, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to check movement type code */ - @GetMapping(value = "/medstockmovementtypes/check/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity isCodeUsed(@PathVariable String code) throws OHServiceException { - return ResponseEntity.ok(manager.isCodePresent(code)); + @GetMapping(value = "/medstockmovementtypes/check/{code}") + public boolean isCodeUsed(@PathVariable String code) throws OHServiceException { + return manager.isCodePresent(code); } /** * Deletes the specified movement type. + * * @param code - the code of the medical stock movement type to delete. * @return {@code true} if the medical stock movement type has been deleted, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to delete movement type */ - @DeleteMapping(value = "/medstockmovementtypes/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity deleteMedicalDsrStockMovementType(@PathVariable("code") String code) throws OHServiceException { - List matchedMvmntTypes = manager.getMedicalDsrStockMovementType() - .stream() - .filter(item -> item.getCode().equals(code)) - .collect(Collectors.toList()); - if (matchedMvmntTypes.isEmpty()) { - throw new OHAPIException(new OHExceptionMessage("Movement type not found.")); + @DeleteMapping(value = "/medstockmovementtypes/{code}") + public boolean deleteMedicalDsrStockMovementType( + @PathVariable("code") String code + ) throws OHServiceException { + List matchedMovementTypes = manager.getMedicalDsrStockMovementType() + .stream() + .filter(item -> item.getCode().equals(code)).toList(); + if (matchedMovementTypes.isEmpty()) { + throw new OHAPIException(new OHExceptionMessage("Movement type not found."), HttpStatus.NOT_FOUND); } try { - manager.deleteMedicalDsrStockMovementType(matchedMvmntTypes.get(0)); - return ResponseEntity.ok(true); + manager.deleteMedicalDsrStockMovementType(matchedMovementTypes.get(0)); + return true; } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Movement type not deleted.")); } } - } diff --git a/src/main/java/org/isf/medtype/rest/MedicalTypeController.java b/src/main/java/org/isf/medtype/rest/MedicalTypeController.java index 83a5c977a..be214faba 100644 --- a/src/main/java/org/isf/medtype/rest/MedicalTypeController.java +++ b/src/main/java/org/isf/medtype/rest/MedicalTypeController.java @@ -22,7 +22,6 @@ package org.isf.medtype.rest; import java.util.List; -import java.util.stream.Collectors; import jakarta.validation.Valid; @@ -35,119 +34,125 @@ import org.isf.utils.exception.model.OHExceptionMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/medicaltypes") +@RestController @Tag(name = "Medical Types") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class MedicalTypeController { private static final Logger LOGGER = LoggerFactory.getLogger(MedicalTypeController.class); - @Autowired - private MedicalTypeBrowserManager medicalTypeBrowserManager; + private final MedicalTypeBrowserManager medicalTypeBrowserManager; + + private final MedicalTypeMapper medicalTypeMapper; + + public MedicalTypeController( + MedicalTypeBrowserManager medicalTypeBrowserManager, MedicalTypeMapper medicalTypeMapper + ) { + this.medicalTypeBrowserManager = medicalTypeBrowserManager; + this.medicalTypeMapper = medicalTypeMapper; + } - @Autowired - private MedicalTypeMapper medicalTypeMapper; - /** * Retrieves all the medical types. * @return the found medical types. - * @throws OHServiceException + * @throws OHServiceException When failed to get medical types */ - @GetMapping(value = "/medicaltypes", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getMedicalTypes() throws OHServiceException { + @GetMapping(value = "/medicaltypes") + public List getMedicalTypes() throws OHServiceException { LOGGER.info("Retrieving all the medical types ..."); - List medicalTypes = medicalTypeBrowserManager.getMedicalType(); - List mappedMedicalTypes = medicalTypeMapper.map2DTOList(medicalTypes); - if (mappedMedicalTypes.isEmpty()) { - LOGGER.info("No medical type found"); - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(mappedMedicalTypes); - } else { - LOGGER.info("Found {} medical types", mappedMedicalTypes.size()); - return ResponseEntity.ok(mappedMedicalTypes); - } + return medicalTypeMapper.map2DTOList(medicalTypeBrowserManager.getMedicalType()); } - + /** * Saves the specified medical type. * @param medicalTypeDTO the medical type to save. - * @return {@link ResponseEntity} with status {@code HttpStatus.CREATED} if the medical type has been saved. - * @throws OHServiceException + * @return The created medical type + * @throws OHServiceException When failed to create medical type */ - @PostMapping(value = "/medicaltypes", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity createMedicalType(@RequestBody @Valid MedicalTypeDTO medicalTypeDTO) throws OHServiceException { - MedicalType isCreatedMedicalType = medicalTypeBrowserManager.newMedicalType(medicalTypeMapper.map2Model(medicalTypeDTO)); + @PostMapping(value = "/medicaltypes") + @ResponseStatus(HttpStatus.CREATED) + public MedicalTypeDTO createMedicalType(@RequestBody @Valid MedicalTypeDTO medicalTypeDTO) throws OHServiceException { + MedicalType isCreatedMedicalType = medicalTypeBrowserManager.newMedicalType( + medicalTypeMapper.map2Model(medicalTypeDTO) + ); + if (isCreatedMedicalType == null) { - throw new OHAPIException(new OHExceptionMessage("Medical type not created.")); - } - return ResponseEntity.status(HttpStatus.CREATED).body(medicalTypeMapper.map2DTO(isCreatedMedicalType)); + throw new OHAPIException(new OHExceptionMessage("Medical type not created.")); + } + + return medicalTypeMapper.map2DTO(isCreatedMedicalType); } - + /** * Updates the specified medical type. * @param medicalTypeDTO the medical type to update. - * @return {@link ResponseEntity} with status {@code HttpStatus.OK} if the medical type has been updated. - * @throws OHServiceException + * @return The updated medical type + * @throws OHServiceException When failed to update medical type */ - @PutMapping(value = "/medicaltypes", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity updateMedicalType(@RequestBody @Valid MedicalTypeDTO medicalTypeDTO) throws OHServiceException { + @PutMapping(value = "/medicaltypes") + public MedicalTypeDTO updateMedicalType(@RequestBody @Valid MedicalTypeDTO medicalTypeDTO) throws OHServiceException { MedicalType medicalType = medicalTypeMapper.map2Model(medicalTypeDTO); if (!medicalTypeBrowserManager.isCodePresent(medicalType.getCode())) { - throw new OHAPIException(new OHExceptionMessage("Medical type not found.")); + throw new OHAPIException(new OHExceptionMessage("Medical type not found."), HttpStatus.NOT_FOUND); } + MedicalType isUpdatedMedicalType = medicalTypeBrowserManager.updateMedicalType(medicalType); + if (isUpdatedMedicalType == null) { - throw new OHAPIException(new OHExceptionMessage("Medical type not updated.")); - } - return ResponseEntity.ok(medicalTypeMapper.map2DTO(isUpdatedMedicalType)); + throw new OHAPIException(new OHExceptionMessage("Medical type not updated.")); + } + + return medicalTypeMapper.map2DTO(isUpdatedMedicalType); } - + /** * Checks if the specified medical type code is already used. * @param code - the code to check. * @return {@code true} if the code is used, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to check if medical type code is used */ - @GetMapping(value = "/medicaltypes/check/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity isCodeUsed(@PathVariable String code) throws OHServiceException { - return ResponseEntity.ok(medicalTypeBrowserManager.isCodePresent(code)); + @GetMapping(value = "/medicaltypes/check/{code}") + public boolean isCodeUsed(@PathVariable String code) throws OHServiceException { + return medicalTypeBrowserManager.isCodePresent(code); } /** * Deletes the specified medical type. * @param code - the code of the medical type to delete. * @return {@code true} if the medical type has been deleted. - * @throws OHServiceException + * @throws OHServiceException When failed to delete medical type */ - @DeleteMapping(value = "/medicaltypes/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity deleteMedicalType(@PathVariable("code") String code) throws OHServiceException { + @DeleteMapping(value = "/medicaltypes/{code}") + public boolean deleteMedicalType(@PathVariable("code") String code) throws OHServiceException { List matchedMedicalTypes = medicalTypeBrowserManager.getMedicalType() - .stream() - .filter(item -> item.getCode().equals(code)) - .collect(Collectors.toList()); - if (!matchedMedicalTypes.isEmpty()) { - try { - medicalTypeBrowserManager.deleteMedicalType(matchedMedicalTypes.get(0)); - } catch (OHServiceException serviceException) { - throw new OHAPIException(new OHExceptionMessage("Medical type not deleted.")); - } - return ResponseEntity.ok(true); - } else { - throw new OHAPIException(new OHExceptionMessage("Medical type not found.")); + .stream() + .filter(item -> item.getCode().equals(code)).toList(); + + if (matchedMedicalTypes.isEmpty()) { + throw new OHAPIException(new OHExceptionMessage("Medical type not found."), HttpStatus.NOT_FOUND); + } + + try { + medicalTypeBrowserManager.deleteMedicalType(matchedMedicalTypes.get(0)); + return true; + } catch (OHServiceException serviceException) { + throw new OHAPIException(new OHExceptionMessage("Medical type not deleted.")); } } } diff --git a/src/main/java/org/isf/opd/rest/OpdController.java b/src/main/java/org/isf/opd/rest/OpdController.java index b49266a97..18113025d 100644 --- a/src/main/java/org/isf/opd/rest/OpdController.java +++ b/src/main/java/org/isf/opd/rest/OpdController.java @@ -26,7 +26,6 @@ import java.util.List; import java.util.stream.Collectors; -import org.isf.distype.manager.DiseaseTypeBrowserManager; import org.isf.generaldata.MessageBundle; import org.isf.opd.dto.OpdDTO; import org.isf.opd.dto.OpdWithOperationRowDTO; @@ -48,110 +47,119 @@ import org.isf.ward.model.Ward; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/opds") +@RestController @Tag(name = "Opds") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class OpdController { private static final Logger LOGGER = LoggerFactory.getLogger(OpdController.class); - + // TODO: to centralize protected static final String DEFAULT_PAGE_SIZE = "80"; - @Autowired - protected OpdBrowserManager opdManager; - - @Autowired - protected OpdMapper mapper; - - @Autowired - protected PatientBrowserManager patientManager; - - @Autowired - protected OperationRowBrowserManager operationRowManager; - - @Autowired - protected OperationRowMapper opRowMapper; - - @Autowired - protected WardBrowserManager wardManager; - - @Autowired - protected DiseaseTypeBrowserManager diseaseTypeManager; - - public OpdController(OpdBrowserManager opdManager, OpdMapper opdmapper, PatientBrowserManager patientManager, OperationRowBrowserManager - operationRowManager, OperationRowMapper opRowMapper, WardBrowserManager wardManager, DiseaseTypeBrowserManager diseaseTypeManager) { + private final OpdBrowserManager opdManager; + + private final OpdMapper mapper; + + private final PatientBrowserManager patientManager; + + private final OperationRowBrowserManager operationRowManager; + + private final OperationRowMapper opRowMapper; + + private final WardBrowserManager wardManager; + + public OpdController( + OpdBrowserManager opdManager, + OpdMapper opdmapper, + PatientBrowserManager patientManager, + OperationRowBrowserManager + operationRowManager, + OperationRowMapper opRowMapper, + WardBrowserManager wardManager + ) { this.opdManager = opdManager; this.mapper = opdmapper; this.patientManager = patientManager; this.operationRowManager = operationRowManager; this.opRowMapper = opRowMapper; this.wardManager = wardManager; - this.diseaseTypeManager = diseaseTypeManager; } /** * Create a new {@link Opd}. - * @param opdDTO + * @param opdDTO OPD payload * @return the code of {@link Opd} stored - * @throws OHServiceException + * @throws OHServiceException When failed to create OPD */ - @PostMapping(value = "/opds", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity newOpd(@RequestBody OpdDTO opdDTO) throws OHServiceException { - int code = opdDTO.getCode(); - LOGGER.info("store Out patient {}", code); + @PostMapping("/opds") + @ResponseStatus(HttpStatus.CREATED) + public OpdDTO newOpd(@RequestBody OpdDTO opdDTO) throws OHServiceException { + LOGGER.info("store Out patient {}", opdDTO.getCode()); Patient patient = patientManager.getPatientById(opdDTO.getPatientCode()); + if (patient == null) { - throw new OHAPIException(new OHExceptionMessage("Patient not found.")); + throw new OHAPIException(new OHExceptionMessage("Patient not found."), HttpStatus.NOT_FOUND); } + if (" ".equals(opdDTO.getNote())) { throw new OHAPIException(new OHExceptionMessage("Note field mandatory.")); } + Opd opdToInsert = mapper.map2Model(opdDTO); opdToInsert.setPatient(patient); Opd isCreatedOpd = opdManager.newOpd(opdToInsert); + if (isCreatedOpd == null) { throw new OHAPIException(new OHExceptionMessage("Opd not created.")); } - return ResponseEntity.status(HttpStatus.CREATED).body(mapper.map2DTO(isCreatedOpd)); + + return mapper.map2DTO(isCreatedOpd); } /** * Create a new {@link OpdWithOperationRowDTO}. - * @param opdWithOperationRowDTO + * @param opdWithOperationRowDTO OPD with Operation row payload * @return the OpdWithOperationRowDTO stored - * @throws OHServiceException + * @throws OHServiceException When failed to create OPD */ - @PostMapping(value = "/opds/rows", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity newOpdWithOperationRow(@RequestBody OpdWithOperationRowDTO opdWithOperationRowDTO) throws OHServiceException { + @PostMapping("/opds/rows") + @ResponseStatus(HttpStatus.CREATED) + public OpdWithOperationRowDTO newOpdWithOperationRow( + @RequestBody OpdWithOperationRowDTO opdWithOperationRowDTO + ) throws OHServiceException { int code = opdWithOperationRowDTO.getOpdDTO().getCode(); LOGGER.info("store Out patient {}", code); - OpdWithOperationRowDTO opdWithOperatioRow = new OpdWithOperationRowDTO(); + OpdWithOperationRowDTO opdWithOperationRow = new OpdWithOperationRowDTO(); + Patient patient = patientManager.getPatientById(opdWithOperationRowDTO.getOpdDTO().getPatientCode()); if (patient == null) { - throw new OHAPIException(new OHExceptionMessage("Patient not found.")); + throw new OHAPIException(new OHExceptionMessage("Patient not found."), HttpStatus.NOT_FOUND); } + if (" ".equals(opdWithOperationRowDTO.getOpdDTO().getNote())) { throw new OHAPIException(new OHExceptionMessage("Note field mandatory.")); } + Opd opdToInsert = mapper.map2Model(opdWithOperationRowDTO.getOpdDTO()); opdToInsert.setPatient(patient); Opd isCreatedOpd = opdManager.newOpd(opdToInsert); @@ -159,7 +167,7 @@ ResponseEntity newOpdWithOperationRow(@RequestBody OpdWi throw new OHAPIException(new OHExceptionMessage("Opd not created.")); } OpdDTO opdDTO = mapper.map2DTO(isCreatedOpd); - opdWithOperatioRow.setOpdDTO(opdDTO); + opdWithOperationRow.setOpdDTO(opdDTO); List listOp = new ArrayList<>(); if (!opdWithOperationRowDTO.getOperationRows().isEmpty()) { for (OperationRowDTO operationRow : opdWithOperationRowDTO.getOperationRows()) { @@ -168,31 +176,31 @@ ResponseEntity newOpdWithOperationRow(@RequestBody OpdWi listOp.add(opRowMapper.map2DTO(createOpeRow)); } } - opdWithOperatioRow.setOperationRows(listOp); - return ResponseEntity.status(HttpStatus.CREATED).body(opdWithOperatioRow); + opdWithOperationRow.setOperationRows(listOp); + + return opdWithOperationRow; } - + /** * Updates the specified {@link Opd}. - * @param opdDTO + * @param opdDTO OPD payload * @return the code of updated {@link Opd} - * @throws OHServiceException + * @throws OHServiceException When failed to update OPD */ - @PutMapping(value = "/opds/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity updateOpd(@PathVariable("code") int code, @RequestBody OpdDTO opdDTO) - throws OHServiceException { + @PutMapping("/opds/{code}") + public OpdDTO updateOpd(@PathVariable("code") int code, @RequestBody OpdDTO opdDTO) throws OHServiceException { LOGGER.info("Update opds code: {}", opdDTO.getCode()); if (opdManager.getOpdById(code).isEmpty()) { - throw new OHAPIException(new OHExceptionMessage("Opd not found.")); + throw new OHAPIException(new OHExceptionMessage("Opd not found."), HttpStatus.NOT_FOUND); } - if (opdDTO.getCode() != 0 && opdDTO.getCode() != code) { - throw new OHAPIException(new OHExceptionMessage("Opd not found.")); + if (opdDTO.getCode() != 0 && opdDTO.getCode() != code) { + throw new OHAPIException(new OHExceptionMessage("Opd not found."), HttpStatus.NOT_FOUND); } - + Patient patient = patientManager.getPatientById(opdDTO.getPatientCode()); if (patient == null) { - throw new OHAPIException(new OHExceptionMessage("Patient not found.")); + throw new OHAPIException(new OHExceptionMessage("Patient not found."), HttpStatus.NOT_FOUND); } Opd opdToUpdate = mapper.map2Model(opdDTO); @@ -201,32 +209,34 @@ ResponseEntity updateOpd(@PathVariable("code") int code, @RequestBody Op if (updatedOpd == null) { throw new OHAPIException(new OHExceptionMessage("Opd not updated.")); } - return ResponseEntity.status(HttpStatus.OK).body(mapper.map2DTO(updatedOpd)); + + return mapper.map2DTO(updatedOpd); } /** * Updates the specified {@link OpdWithOperationRowDTO}. - * @param code - * @param opdWithOperationRowDTO + * @param code OPD code + * @param opdWithOperationRowDTO OPD with Operation row payload * @return the OpdWithOperationRowDTO updated - * @throws OHServiceException + * @throws OHServiceException When failed to update OPD */ - @PutMapping(value = "/opds/rows/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity updateOpdWithOperationRow(@PathVariable("code") int code, @RequestBody OpdWithOperationRowDTO opdWithOperationRowDTO) - throws OHServiceException { + @PutMapping("/opds/rows/{code}") + public OpdWithOperationRowDTO updateOpdWithOperationRow( + @PathVariable("code") int code, @RequestBody OpdWithOperationRowDTO opdWithOperationRowDTO + ) throws OHServiceException { LOGGER.info("Update opds code: {}", code); OpdWithOperationRowDTO opdWithOperatioRow = new OpdWithOperationRowDTO(); if (opdManager.getOpdById(code).isEmpty()) { - throw new OHAPIException(new OHExceptionMessage("Opd not found.")); + throw new OHAPIException(new OHExceptionMessage("Opd not found."), HttpStatus.NOT_FOUND); } - if (opdWithOperationRowDTO.getOpdDTO().getCode() != 0 && opdWithOperationRowDTO.getOpdDTO().getCode() != code) { - throw new OHAPIException(new OHExceptionMessage("Opd not found.")); + if (opdWithOperationRowDTO.getOpdDTO().getCode() != 0 && opdWithOperationRowDTO.getOpdDTO().getCode() != code) { + throw new OHAPIException(new OHExceptionMessage("Opd not found."), HttpStatus.NOT_FOUND); } - + Patient patient = patientManager.getPatientById(opdWithOperationRowDTO.getOpdDTO().getPatientCode()); if (patient == null) { - throw new OHAPIException(new OHExceptionMessage("Patient not found.")); + throw new OHAPIException(new OHExceptionMessage("Patient not found."), HttpStatus.NOT_FOUND); } Opd opdToUpdate = mapper.map2Model(opdWithOperationRowDTO.getOpdDTO()); @@ -247,54 +257,53 @@ ResponseEntity updateOpdWithOperationRow(@PathVariable(" } else { updateOpeRow = operationRowManager.updateOperationRow(opRowMapper.map2Model(operationRow)); } - + listOpeRow.add(opRowMapper.map2DTO(updateOpeRow)); } } opdWithOperatioRow.setOperationRows(listOpeRow); - return ResponseEntity.status(HttpStatus.OK).body(opdWithOperatioRow); + + return opdWithOperatioRow; } - + /** * Get all {@link Opd}s for today or for the last week. * @return a {@link List} of {@link Opd} or NO_CONTENT if there is no data found. - * @throws OHServiceException + * @throws OHServiceException When failed to get OPD */ - @GetMapping(value = "/opds/weekly", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getOpdToDayOrWeek(@RequestParam(name="oneWeek", required=false) Boolean oneWeek) throws OHServiceException { + @GetMapping("/opds/weekly") + public List getOpdToDayOrWeek( + @RequestParam(name="oneWeek", required=false) Boolean oneWeek + ) throws OHServiceException { LOGGER.info("Get all today or since one week opd"); if (oneWeek == null) { oneWeek = false; - } - List opds = opdManager.getOpd(oneWeek); - List opdDTOs = mapper.map2DTOList(opds); - if (opdDTOs.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(opdDTOs); - } else { - return ResponseEntity.ok(opdDTOs); } + + return mapper.map2DTOList(opdManager.getOpd(oneWeek)); } - + /** * Get all {@link Opd}s within specified date range. * @return a {@link List} of {@link Opd} or NO_CONTENT if there is no data found. - * @throws OHServiceException + * @throws OHServiceException When failed to get OPDs */ - @GetMapping(value = "/opds/search", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getOpdByDates( - @RequestParam(value = "dateFrom") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) @Schema(implementation = String.class) LocalDate dateFrom, - @RequestParam(value = "dateTo") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) @Schema(implementation = String.class) LocalDate dateTo, - @RequestParam(value = "diseaseTypeCode", required = false) String diseaseTypeCode, - @RequestParam(value = "diseaseCode", required = false) String diseaseCode, - @RequestParam(value = "ageFrom", required = false, defaultValue = "0") Integer ageFrom, - @RequestParam(value = "ageTo", required = false, defaultValue = "200") Integer ageTo, - @RequestParam(value = "sex", required = false, defaultValue = "A") char sex, - @RequestParam(value = "newPatient", required = false, defaultValue = "A") char newPatient, - @RequestParam(value = "patientCode", required = false, defaultValue = "0") Integer patientCode, - @RequestParam(value = "page", required = false, defaultValue = "0") int page, - @RequestParam(value = "size", required = false, defaultValue = DEFAULT_PAGE_SIZE) int size, - @RequestParam(value = "paged", required = false, defaultValue = "false") boolean paged, - @RequestParam(value = "wardCode", required = false) String wardCode) throws OHServiceException { + @GetMapping("/opds/search") + public Page getOpdByDates( + @RequestParam(value = "dateFrom") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) @Schema(implementation = String.class) LocalDate dateFrom, + @RequestParam(value = "dateTo") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) @Schema(implementation = String.class) LocalDate dateTo, + @RequestParam(value = "diseaseTypeCode", required = false) String diseaseTypeCode, + @RequestParam(value = "diseaseCode", required = false) String diseaseCode, + @RequestParam(value = "ageFrom", required = false, defaultValue = "0") Integer ageFrom, + @RequestParam(value = "ageTo", required = false, defaultValue = "200") Integer ageTo, + @RequestParam(value = "sex", required = false, defaultValue = "A") char sex, + @RequestParam(value = "newPatient", required = false, defaultValue = "A") char newPatient, + @RequestParam(value = "patientCode", required = false, defaultValue = "0") Integer patientCode, + @RequestParam(value = "page", required = false, defaultValue = "0") int page, + @RequestParam(value = "size", required = false, defaultValue = DEFAULT_PAGE_SIZE) int size, + @RequestParam(value = "paged", required = false, defaultValue = "false") boolean paged, + @RequestParam(value = "wardCode", required = false) String wardCode + ) throws OHServiceException { LOGGER.info("Get opd within specified dates"); LOGGER.debug("dateFrom: {}", dateFrom); LOGGER.debug("dateTo: {}", dateTo); @@ -317,9 +326,10 @@ public ResponseEntity> getOpdByDates( if (wardCode != null) { ward = wardManager.findWard(wardCode); } + if (paged) { PagedResponse opdsPaged = opdManager.getOpdPageable(ward, diseaseTypeCode, MessageBundle.getMessage(diseaseTypeCode), dateFrom, dateTo, ageFrom, ageTo, sex, newPatient, page,size); - opdDTOs = opdsPaged.getData().stream().map(opd -> mapper.map2DTO(opd)).collect(Collectors.toList()); + opdDTOs = opdsPaged.getData().stream().map(mapper::map2DTO).collect(Collectors.toList()); opdPageable.setPageInfo(mapper.setParameterPageInfo(opdsPaged.getPageInfo())); } else { if (patientCode != 0) { @@ -327,23 +337,21 @@ public ResponseEntity> getOpdByDates( } else { opds = opdManager.getOpd(ward, diseaseTypeCode, diseaseCode, dateFrom, dateTo, ageFrom, ageTo, sex, newPatient, null); } - opdDTOs = opds.stream().map(opd -> mapper.map2DTO(opd)).collect(Collectors.toList()); + opdDTOs = opds.stream().map(mapper::map2DTO).collect(Collectors.toList()); } + opdPageable.setData(opdDTOs); - if (opdDTOs.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(opdPageable); - } else { - return ResponseEntity.ok(opdPageable); - } + + return opdPageable; } - + /** * Get all {@link OpdWithOperationRowDTO}s associated to specified patient CODE. * @return a {@link List} of {@link OpdWithOperationRowDTO} or NO_CONTENT if there is no data found. - * @throws OHServiceException + * @throws OHServiceException When failed to get OPDs */ - @GetMapping(value = "/opds/patient/{pcode}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getOpdByPatient(@PathVariable("pcode") int pcode) throws OHServiceException { + @GetMapping("/opds/patient/{pcode}") + public List getOpdByPatient(@PathVariable("pcode") int pcode) throws OHServiceException { LOGGER.info("Get opd associated to specified patient CODE: {}", pcode); List opds = opdManager.getOpdList(pcode); @@ -364,76 +372,72 @@ public ResponseEntity> getOpdByPatient(@PathVariabl } else { opRows.setOperationRows(new ArrayList<>()); } - + return opRows; }).collect(Collectors.toList()); - return ResponseEntity.ok(opdWithOperations); - - } else { - - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(opdWithOperations); } + return opdWithOperations; } /** * Delete {@link Opd} for specified code. - * @param code + * @param code OPD code * @return {@code true} if the {@link Opd} has been deleted, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to delete OPD */ - @DeleteMapping(value = "/opds/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity deleteOpd(@PathVariable("code") int code) throws OHServiceException { + @DeleteMapping("/opds/{code}") + public boolean deleteOpd(@PathVariable("code") int code) throws OHServiceException { LOGGER.info("Delete Opd code: {}", code); + Opd toDelete = new Opd(); toDelete.setCode(code); + try { opdManager.deleteOpd(toDelete); + return true; } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Opd not deleted.")); } - return ResponseEntity.ok(true); } - + /** * Get the maximum progressive number within specified year or within current year if {@code 0}. * @return the max progressive number - * @throws OHServiceException + * @throws OHServiceException When failed to get year progressive number */ - @GetMapping(value = "/opds/ProgYear/{year}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getProgYear(@PathVariable("year") int year) throws OHServiceException { + @GetMapping("/opds/ProgYear/{year}") + public Integer getProgressiveYear(@PathVariable("year") int year) throws OHServiceException { LOGGER.info("Get progressive number within specified year"); - int yProg = opdManager.getProgYear(year); - return ResponseEntity.ok(yProg); + + return opdManager.getProgYear(year); } - + /** * Get the last {@link Opd} in time associated with specified patient ID. * @return last Opd associated with specified patient ID or {@code null} - * @throws OHServiceException + * @throws OHServiceException When failed to get last OPD */ - @GetMapping(value = "/opds/last/{patientCode}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getLastOpd(@PathVariable("patientCode") int patientCode) throws OHServiceException { + @GetMapping("/opds/last/{patientCode}") + public OpdDTO getLastOpd(@PathVariable("patientCode") int patientCode) throws OHServiceException { LOGGER.info("Get the last opp for patient code: {}", patientCode); Opd lastOpd = opdManager.getLastOpd(patientCode); + if (lastOpd == null) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } else { - return ResponseEntity.ok(mapper.map2DTO(lastOpd)); + throw new OHAPIException(new OHExceptionMessage("Opd not found."), HttpStatus.NOT_FOUND); } - + + return mapper.map2DTO(lastOpd); } - + /** * Check if the given {@code opdNum} does already exist for the given {@code year}. * @return {@code true} if the given number exists in year, {@code false} otherwise - * @throws OHServiceException + * @throws OHServiceException When failed to check the OPD number */ - @GetMapping(value = "/opds/check/progyear", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity isExistOpdNum(@RequestParam("opdNum") int opdNum, @RequestParam("year") int year) throws OHServiceException { + @GetMapping("/opds/check/progyear") + public boolean isExistOpdNum(@RequestParam("opdNum") int opdNum, @RequestParam("year") int year) throws OHServiceException { LOGGER.info("check if progYear: {} already exist for year : {}", opdNum, year); - Boolean isExist = opdManager.isExistOpdNum(opdNum, year); - return ResponseEntity.ok(isExist); + return opdManager.isExistOpdNum(opdNum, year); } - } diff --git a/src/main/java/org/isf/operation/rest/OperationController.java b/src/main/java/org/isf/operation/rest/OperationController.java index 1638bb0c9..9f51b9a86 100644 --- a/src/main/java/org/isf/operation/rest/OperationController.java +++ b/src/main/java/org/isf/operation/rest/OperationController.java @@ -22,7 +22,6 @@ package org.isf.operation.rest; import java.util.List; -import java.util.stream.Collectors; import org.isf.admission.manager.AdmissionBrowserManager; import org.isf.admission.model.Admission; @@ -44,86 +43,97 @@ import org.isf.utils.exception.model.OHExceptionMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/operations") +@RestController @Tag(name = "Operations") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class OperationController { private static final Logger LOGGER = LoggerFactory.getLogger(OperationController.class); - @Autowired - protected OperationBrowserManager operationManager; + private final OperationBrowserManager operationManager; - @Autowired - protected AdmissionBrowserManager admissionManager; + private final AdmissionBrowserManager admissionManager; - @Autowired - protected OperationRowBrowserManager operationRowManager; + private final OperationRowBrowserManager operationRowManager; - @Autowired - protected PatientBrowserManager patientBrowserManager; + private final PatientBrowserManager patientBrowserManager; - @Autowired - protected OperationMapper mapper; + private final OperationMapper mapper; - @Autowired - protected OpdMapper opdMapper; + private final OpdMapper opdMapper; - @Autowired - protected OperationRowMapper opRowMapper; + private final OperationRowMapper opRowMapper; - public OperationController(OperationBrowserManager operationManager, OperationMapper operationmapper) { + public OperationController( + OperationBrowserManager operationManager, + AdmissionBrowserManager admissionManager, + OperationRowBrowserManager operationRowManager, + PatientBrowserManager patientBrowserManager, + OperationMapper mapper, OpdMapper opdMapper, + OperationRowMapper opRowMapper + ) { this.operationManager = operationManager; - this.mapper = operationmapper; + this.admissionManager = admissionManager; + this.operationRowManager = operationRowManager; + this.patientBrowserManager = patientBrowserManager; + this.mapper = mapper; + this.opdMapper = opdMapper; + this.opRowMapper = opRowMapper; } - /** * Create a new {@link Operation}. - * - * @param operationDTO + * + * @param operationDTO Operation payload * @return {@code true} if the operation has been stored, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to create operation */ - @PostMapping(value = "/operations", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity newOperation(@RequestBody OperationDTO operationDTO) throws OHServiceException { + @PostMapping("/operations") + @ResponseStatus(HttpStatus.CREATED) + public OperationDTO newOperation(@RequestBody OperationDTO operationDTO) throws OHServiceException { String code = operationDTO.getCode(); LOGGER.info("Create operation {}.", code); if (operationManager.descriptionControl(operationDTO.getDescription(), operationDTO.getType().getCode())) { - throw new OHAPIException(new OHExceptionMessage("Another operation already created with provided description and types.")); + throw new OHAPIException(new OHExceptionMessage( + "Another operation already created with provided description and types." + )); } + Operation isCreatedOperation = operationManager.newOperation(mapper.map2Model(operationDTO)); if (isCreatedOperation == null) { throw new OHAPIException(new OHExceptionMessage("Operation not created.")); } - return ResponseEntity.status(HttpStatus.CREATED).body(mapper.map2DTO(isCreatedOperation)); + + return mapper.map2DTO(isCreatedOperation); } /** * Updates the specified {@link Operation}. - * - * @param operationDTO + * + * @param operationDTO Operation payload * @return {@code true} if the operation has been updated, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to update operation */ - @PutMapping(value = "/operations/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity updateOperation(@PathVariable String code, @RequestBody OperationDTO operationDTO) - throws OHServiceException { + @PutMapping("/operations/{code}") + public OperationDTO updateOperation( + @PathVariable String code, @RequestBody OperationDTO operationDTO + ) throws OHServiceException { LOGGER.info("Update operations code: {}.", operationDTO.getCode()); Operation operation = mapper.map2Model(operationDTO); if (!operationManager.isCodePresent(code)) { @@ -134,217 +144,205 @@ ResponseEntity updateOperation(@PathVariable String code, @Request if (isUpdatedOperation == null) { throw new OHAPIException(new OHExceptionMessage("Operation not updated.")); } - return ResponseEntity.ok(mapper.map2DTO(isUpdatedOperation)); + + return mapper.map2DTO(isUpdatedOperation); } /** * Get all the available {@link Operation}s. - * + * * @return a {@link List} of {@link Operation} or NO_CONTENT if there is no data found. - * @throws OHServiceException + * @throws OHServiceException When failed to get operations */ - @GetMapping(value = "/operations", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getOperations() throws OHServiceException { + @GetMapping("/operations") + public List getOperations() throws OHServiceException { LOGGER.info("Get all operations."); - List operations = operationManager.getOperation(); - List operationDTOs = mapper.map2DTOList(operations); - if (operationDTOs.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(operationDTOs); - } else { - return ResponseEntity.ok(operationDTOs); - } + + return mapper.map2DTOList(operationManager.getOperation()); } /** * Get the {@link Operation} with the specified code. - * + * * @return found operation - * @throws OHServiceException + * @throws OHServiceException When failed get the operation */ - @GetMapping(value = "/operations/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getOperationByCode(@PathVariable String code) throws OHServiceException { + @GetMapping("/operations/{code}") + public OperationDTO getOperationByCode(@PathVariable String code) throws OHServiceException { LOGGER.info("Get operation for provided code: {}.", code); Operation operation = operationManager.getOperationByCode(code); - if (operation != null) { - return ResponseEntity.ok(mapper.map2DTO(operation)); - } else { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); + + if (operation == null) { + throw new OHAPIException(new OHExceptionMessage("Operation not found."), HttpStatus.NOT_FOUND); } + + return mapper.map2DTO(operation); } /** * Get all {@link Operation}s whose {@link OperationType}'s description matches specified string. - * + * * @return {@link List} of {@link Operation} or NO_CONTENT if there is no data found. - * @throws OHServiceException + * @throws OHServiceException When failed get operations */ - @GetMapping(value = "/operations/search/type", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getOperationByTypeDescription(@RequestParam String typeDescription) throws OHServiceException { + @GetMapping("/operations/search/type") + public List getOperationByTypeDescription( + @RequestParam String typeDescription + ) throws OHServiceException { LOGGER.info("Get operations for provided type description: {}.", typeDescription); - List operations = operationManager.getOperationByTypeDescription(typeDescription); - List operationDTOs = mapper.map2DTOList(operations); - if (operationDTOs.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(operationDTOs); - } else { - return ResponseEntity.ok(operationDTOs); - } + + return mapper.map2DTOList(operationManager.getOperationByTypeDescription(typeDescription)); } /** * Delete {@link Operation} for specified code. - * - * @param code + * + * @param code Operation code * @return {@code true} if the {@link Operation} has been deleted, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to delete operation */ - @DeleteMapping(value = "/operations/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity deleteOperation(@PathVariable("code") String code) throws OHServiceException { + @DeleteMapping("/operations/{code}") + public boolean deleteOperation(@PathVariable("code") String code) throws OHServiceException { LOGGER.info("Delete operation code: {}.", code); Operation operation = operationManager.getOperationByCode(code); + if (operation == null) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); + throw new OHAPIException(new OHExceptionMessage("Operation not deleted."), HttpStatus.NOT_FOUND); } + try { operationManager.deleteOperation(operation); + return true; } catch (OHServiceException serviceException) { LOGGER.error("Delete Operation: {} failed.", code); throw new OHAPIException(new OHExceptionMessage("Operation not deleted.")); } - return ResponseEntity.ok(true); } /** * Create a new {@link OperationRow}. - * - * @param operationRowDTO + * + * @param operationRowDTO Operation Row payload * @return {@code true} if the operation has been stored, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to save operation row */ - @PostMapping(value = "/operations/rows", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity newOperationRow(@RequestBody OperationRowDTO operationRowDTO) throws OHServiceException { + @PostMapping("/operations/rows") + @ResponseStatus(HttpStatus.CREATED) + public OperationRowDTO newOperationRow(@RequestBody OperationRowDTO operationRowDTO) throws OHServiceException { int code = operationRowDTO.getAdmission().getId(); LOGGER.info("Create operation: {}.", code); + if (operationRowDTO.getAdmission() == null && operationRowDTO.getOpd() == null) { throw new OHAPIException(new OHExceptionMessage("At least one field between admission and Opd is required.")); } OperationRow opRow = opRowMapper.map2Model(operationRowDTO); OperationRow createOpeRow = operationRowManager.newOperationRow(opRow); - List opRowFounds = operationRowManager.getOperationRowByAdmission(opRow.getAdmission()).stream() - .filter(op -> op.getAdmission().getId() == code) - .collect(Collectors.toList()); + List opRowFounds = operationRowManager.getOperationRowByAdmission(opRow.getAdmission()) + .stream() + .filter(op -> op.getAdmission().getId() == code) + .toList(); + OperationRow opCreated = null; if (!opRowFounds.isEmpty()) { opCreated = opRowFounds.get(0); } + if (createOpeRow == null || opCreated == null) { throw new OHAPIException(new OHExceptionMessage("Operation row not created.")); } - OperationRowDTO opR = opRowMapper.map2DTO(opCreated); - return ResponseEntity.status(HttpStatus.CREATED).body(opR); + + return opRowMapper.map2DTO(opCreated); } /** * Updates the specified {@link OperationRow}. - * - * @param operationRowDTO + * + * @param operationRowDTO Operation Row payload * @return {@code true} if the operation row has been updated, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to update operation row */ - @PutMapping(value = "/operations/rows", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity updateOperationRow(@RequestBody OperationRowDTO operationRowDTO) throws OHServiceException { + @PutMapping("/operations/rows") + public Integer updateOperationRow(@RequestBody OperationRowDTO operationRowDTO) throws OHServiceException { LOGGER.info("Update operations row code: {}.", operationRowDTO.getId()); if (operationRowDTO.getAdmission() == null && operationRowDTO.getOpd() == null) { throw new OHAPIException(new OHExceptionMessage("At least one field between admission and Opd is required.")); } OperationRow opRow = opRowMapper.map2Model(operationRowDTO); - List opRowFounds = operationRowManager.getOperationRowByAdmission(opRow.getAdmission()).stream().filter(op -> op.getId() == opRow.getId()) - .collect(Collectors.toList()); + List opRowFounds = operationRowManager.getOperationRowByAdmission(opRow.getAdmission()) + .stream() + .filter(op -> op.getId() == opRow.getId()) + .toList(); + if (opRowFounds.isEmpty()) { - throw new OHAPIException(new OHExceptionMessage("Operation row not found.")); + throw new OHAPIException(new OHExceptionMessage("Operation row not found."), HttpStatus.NOT_FOUND); } OperationRow updateOpeRow = operationRowManager.updateOperationRow(opRow); if (updateOpeRow == null) { throw new OHAPIException(new OHExceptionMessage("Operation not updated.")); } - return ResponseEntity.ok(opRow.getId()); + + return opRow.getId(); } /** * Get {@link OperationRow}s for specified admission. - * + * * @return {@link List} of {@link OperationRow} or NO_CONTENT if there is no data found. - * @throws OHServiceException + * @throws OHServiceException When failed to get operations */ - @GetMapping(value = "/operations/rows/search/admission", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getOperationRowsByAdmt(@RequestParam("admissionId") int id) throws OHServiceException { + @GetMapping("/operations/rows/search/admission") + public List getOperationRowsByAdmt(@RequestParam("admissionId") int id) throws OHServiceException { LOGGER.info("Get operations row for provided admission."); Admission adm = admissionManager.getAdmission(id); - List operationRows = operationRowManager.getOperationRowByAdmission(adm); - List operationRowDTOs = operationRows.stream().map(operation -> { - return opRowMapper.map2DTO(operation); - }).collect(Collectors.toList()); - if (operationRowDTOs.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(operationRowDTOs); - } else { - return ResponseEntity.ok(operationRowDTOs); - } + + return opRowMapper.map2DTOList(operationRowManager.getOperationRowByAdmission(adm)); } /** * Get {@link OperationRow}s for specified patient. - * + * * @return {@link List} of {@link OperationRow} or NO_CONTENT if there is no data found. - * @throws OHServiceException + * @throws OHServiceException When failed to get operations */ - @GetMapping(value = "/operations/rows/search/patient", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getOperationRowsByPatient(@RequestParam int patientCode) throws OHServiceException { + @GetMapping("/operations/rows/search/patient") + public List getOperationRowsByPatient(@RequestParam int patientCode) throws OHServiceException { LOGGER.info("Get operations row for provided patient."); Patient patient = patientBrowserManager.getPatientById(patientCode); - List operationRows = operationRowManager.getOperationRowByPatientCode(patient); - List operationRowDTOs = operationRows.stream().map(operation -> opRowMapper.map2DTO(operation)).collect(Collectors.toList()); - if (operationRowDTOs.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(operationRowDTOs); - } else { - return ResponseEntity.ok(operationRowDTOs); - } + + return opRowMapper.map2DTOList(operationRowManager.getOperationRowByPatientCode(patient)); } /** * Get {@link OperationRow}s for specified {@link OpdDTO}. - * + * * @return {@link List} of {@link OperationRow} or NO_CONTENT if there is no data found. - * @throws OHServiceException + * @throws OHServiceException When failed to get operation rows */ - @PostMapping(value = "/operations/rows/search/opd", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getOperationRowsByOpd(@RequestBody OpdDTO opdDTO) throws OHServiceException { + @PostMapping("/operations/rows/search/opd") + public List getOperationRowsByOpd(@RequestBody OpdDTO opdDTO) throws OHServiceException { LOGGER.info("Get operations row for provided opd."); - List operationRows = operationRowManager.getOperationRowByOpd(opdMapper.map2Model(opdDTO)); - List operationRowDTOs = operationRows.stream().map(operation -> opRowMapper.map2DTO(operation)).collect(Collectors.toList()); - if (operationRowDTOs.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(operationRowDTOs); - } else { - return ResponseEntity.ok(operationRowDTOs); - } + return opRowMapper.map2DTOList(operationRowManager.getOperationRowByOpd(opdMapper.map2Model(opdDTO))); } /** * Delete the {@link OperationRow} with the specified code. - * - * @param code + * + * @param code Operation Row code * @return {@code true} if the {@link OperationRow} has been deleted, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to delete operation row */ - @DeleteMapping(value = "/operations/rows/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity deleteOperationRow(@PathVariable int code) throws OHServiceException { + @DeleteMapping("/operations/rows/{code}") + public boolean deleteOperationRow(@PathVariable int code) throws OHServiceException { LOGGER.info("Delete operation row code: {}.", code); OperationRow opRow = new OperationRow(); opRow.setId(code); + try { operationRowManager.deleteOperationRow(opRow); - return ResponseEntity.ok(true); + return true; } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Operation row not deleted.")); } diff --git a/src/main/java/org/isf/opetype/rest/OperationTypeController.java b/src/main/java/org/isf/opetype/rest/OperationTypeController.java index 0c479bc18..8d4e063cf 100644 --- a/src/main/java/org/isf/opetype/rest/OperationTypeController.java +++ b/src/main/java/org/isf/opetype/rest/OperationTypeController.java @@ -22,7 +22,6 @@ package org.isf.opetype.rest; import java.util.List; -import java.util.stream.Collectors; import org.isf.opetype.dto.OperationTypeDTO; import org.isf.opetype.manager.OperationTypeBrowserManager; @@ -33,33 +32,32 @@ import org.isf.utils.exception.model.OHExceptionMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/operationtypes") +@RestController @Tag(name = "Operations Types") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class OperationTypeController { private static final Logger LOGGER = LoggerFactory.getLogger(OperationTypeController.class); - @Autowired - protected OperationTypeBrowserManager opeTypeManager; + private final OperationTypeBrowserManager opeTypeManager; - @Autowired - protected OperationTypeMapper mapper; + private final OperationTypeMapper mapper; public OperationTypeController(OperationTypeBrowserManager opeTypeManager, OperationTypeMapper operationTypemapper) { this.opeTypeManager = opeTypeManager; @@ -68,92 +66,84 @@ public OperationTypeController(OperationTypeBrowserManager opeTypeManager, Opera /** * Create a new {@link OperationType}. - * - * @param operationTypeDTO + * + * @param operationTypeDTO Operation Type payload * @return the newly stored {@link OperationType} object. - * @throws OHServiceException + * @throws OHServiceException When failed to create operation type */ - @PostMapping(value = "/operationtypes", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity newOperationType(@RequestBody OperationTypeDTO operationTypeDTO) throws OHServiceException { + @PostMapping("/operationtypes") + @ResponseStatus(HttpStatus.CREATED) + public OperationTypeDTO newOperationType(@RequestBody OperationTypeDTO operationTypeDTO) throws OHServiceException { String code = operationTypeDTO.getCode(); LOGGER.info("Create Operation Type {}", code); - OperationType newOperationType; + try { - newOperationType = opeTypeManager.newOperationType(mapper.map2Model(operationTypeDTO)); + return mapper.map2DTO(opeTypeManager.newOperationType(mapper.map2Model(operationTypeDTO))); } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Operation Type not created.")); } - return ResponseEntity.status(HttpStatus.CREATED).body(mapper.map2DTO(newOperationType)); } /** * Updates the specified {@link OperationType}. - * - * @param operationTypeDTO + * + * @param operationTypeDTO Operation Type payload * @return the newly updated {@link OperationType} object. - * @throws OHServiceException + * @throws OHServiceException When failed to update operation type */ - @PutMapping(value = "/operationtypes/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity updateOperationTypes(@PathVariable String code, @RequestBody OperationTypeDTO operationTypeDTO) - throws OHServiceException { + @PutMapping("/operationtypes/{code}") + public OperationTypeDTO updateOperationTypes( + @PathVariable String code, @RequestBody OperationTypeDTO operationTypeDTO + ) throws OHServiceException { LOGGER.info("Update operationtypes code: {}", operationTypeDTO.getCode()); + OperationType opeType = mapper.map2Model(operationTypeDTO); if (!opeTypeManager.isCodePresent(code)) { - throw new OHAPIException(new OHExceptionMessage("Operation Type not found.")); + throw new OHAPIException(new OHExceptionMessage("Operation Type not found."), HttpStatus.NOT_FOUND); } - OperationType updatedOperationType; + try { - updatedOperationType = opeTypeManager.updateOperationType(opeType); + return mapper.map2DTO(opeTypeManager.updateOperationType(opeType)); } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Operation Type not updated.")); } - return ResponseEntity.ok(mapper.map2DTO(updatedOperationType)); } /** * Get all the available {@link OperationType}s. - * + * * @return a {@link List} of {@link OperationType} or NO_CONTENT if there is no data found. - * @throws OHServiceException + * @throws OHServiceException When failed to get operation types */ - @GetMapping(value = "/operationtypes", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getOperationTypes() throws OHServiceException { + @GetMapping("/operationtypes") + public List getOperationTypes() throws OHServiceException { LOGGER.info("Get all operation Types "); - List operationTypes = opeTypeManager.getOperationType(); - List operationTypeDTOs = mapper.map2DTOList(operationTypes); - if (operationTypeDTOs.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(operationTypeDTOs); - } else { - return ResponseEntity.ok(operationTypeDTOs); - } + + return mapper.map2DTOList(opeTypeManager.getOperationType()); } /** * Delete {@link OperationType} with the specified code. - * - * @param code + * + * @param code Operation Type code * @return {@code true} if the {@link OperationType} has been deleted, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to delete operation type */ - @DeleteMapping(value = "/operationtypes/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity deleteOperationType(@PathVariable("code") String code) throws OHServiceException { + @DeleteMapping("/operationtypes/{code}") + public boolean deleteOperationType(@PathVariable("code") String code) throws OHServiceException { LOGGER.info("Delete Operation Type code: {}", code); - if (opeTypeManager.isCodePresent(code)) { - List opeTypes = opeTypeManager.getOperationType(); - List opeTypeFounds = opeTypes.stream().filter(ad -> ad.getCode().equals(code)) - .collect(Collectors.toList()); - if (!opeTypeFounds.isEmpty()) { - try { - opeTypeManager.deleteOperationType(opeTypeFounds.get(0)); - } catch (OHServiceException serviceException) { - LOGGER.error("Delete Operation Type code: {} failed.", code); - throw new OHAPIException(new OHExceptionMessage("Operation Type not deleted.")); - } - } - } else { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); + List opeTypes = opeTypeManager.getOperationType(); + List opeTypeFounds = opeTypes.stream().filter(ad -> ad.getCode().equals(code)).toList(); + if (opeTypeFounds.isEmpty()) { + throw new OHAPIException(new OHExceptionMessage("Operation Type not found."), HttpStatus.NOT_FOUND); } - return ResponseEntity.ok(true); - } + try { + opeTypeManager.deleteOperationType(opeTypeFounds.get(0)); + return true; + } catch (OHServiceException serviceException) { + LOGGER.error("Delete Operation Type code: {} failed.", code); + throw new OHAPIException(new OHExceptionMessage("Operation Type not deleted.")); + } + } } diff --git a/src/main/java/org/isf/patconsensus/rest/PatientConsensusController.java b/src/main/java/org/isf/patconsensus/rest/PatientConsensusController.java index 6ca7fbe18..7477abff1 100644 --- a/src/main/java/org/isf/patconsensus/rest/PatientConsensusController.java +++ b/src/main/java/org/isf/patconsensus/rest/PatientConsensusController.java @@ -32,63 +32,67 @@ import org.isf.utils.exception.model.OHExceptionMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/patientconsensus") +@RestController @Tag(name = "Patient Consensus") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class PatientConsensusController { private static final Logger LOGGER = LoggerFactory.getLogger(PatientConsensusController.class); - @Autowired - protected PatientConsensusBrowserManager manager; + private final PatientConsensusBrowserManager manager; - @Autowired - protected PatientConsensusMapper mapper; + private final PatientConsensusMapper mapper; - @GetMapping(value = "/patientconsensus/{patientId}", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity getPatientConsensus(@PathVariable Integer patientId) throws OHServiceException { + public PatientConsensusController(PatientConsensusBrowserManager manager, PatientConsensusMapper mapper) { + this.manager = manager; + this.mapper = mapper; + } + + @GetMapping(value = "/patientconsensus/{patientId}") + public PatientConsensusDTO getPatientConsensus(@PathVariable Integer patientId) throws OHServiceException { LOGGER.info("Retrieving patient consensus: {}", patientId); - Optional patientConsensus = manager.getPatientConsensusByUserId(patientId); - if (patientConsensus.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); + PatientConsensus patientConsensus = manager.getPatientConsensusByUserId(patientId).orElse(null); + + if (patientConsensus == null) { + throw new OHAPIException(new OHExceptionMessage("Patient consensus not found."), HttpStatus.NOT_FOUND); } - PatientConsensusDTO patientDTO = mapper.map2DTO(patientConsensus.get()); - return ResponseEntity.ok(patientDTO); + + return mapper.map2DTO(patientConsensus); } - @PutMapping(value = "/patientconsensus/{patientId}", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity updatePatientConsensus(@PathVariable Integer patientId, @RequestBody PatientConsensusDTO patientConsensus) - throws OHServiceException { + @PutMapping(value = "/patientconsensus/{patientId}") + public PatientConsensusDTO updatePatientConsensus( + @PathVariable Integer patientId, @RequestBody PatientConsensusDTO patientConsensus + ) throws OHServiceException { LOGGER.info("Update patient consensus by id: {}", patientId); if (!patientId.equals(patientConsensus.getPatientId())) { throw new OHAPIException(new OHExceptionMessage("Patient code mismatch.")); } Optional patConsensusOpt = this.manager.getPatientConsensusByUserId(patientId); if (patConsensusOpt.isEmpty()) { - throw new OHAPIException(new OHExceptionMessage("PatientConsensus not found.")); + throw new OHAPIException(new OHExceptionMessage("PatientConsensus not found."), HttpStatus.NOT_FOUND); } + PatientConsensus updatedPatienConsensusModel = mapper.map2Model(patientConsensus); updatedPatienConsensusModel.setId(patConsensusOpt.get().getId()); try { PatientConsensus patientConsensusUpdated = manager.updatePatientConsensus(updatedPatienConsensusModel); - PatientConsensusDTO patientConsensusDTO = mapper.map2DTO(patientConsensusUpdated); - return ResponseEntity.ok(patientConsensusDTO); + return mapper.map2DTO(patientConsensusUpdated); } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("PatientConsensus is not updated.")); } } - } diff --git a/src/main/java/org/isf/patient/rest/PatientController.java b/src/main/java/org/isf/patient/rest/PatientController.java index 1906b2c7d..70b411ddc 100644 --- a/src/main/java/org/isf/patient/rest/PatientController.java +++ b/src/main/java/org/isf/patient/rest/PatientController.java @@ -22,11 +22,11 @@ package org.isf.patient.rest; import java.time.LocalDateTime; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.stream.Collectors; import org.isf.admission.manager.AdmissionBrowserManager; import org.isf.admission.model.Admission; @@ -43,10 +43,8 @@ import org.isf.utils.pagination.PagedResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; @@ -54,15 +52,18 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/patients") +@RestController @Tag(name = "Patients") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class PatientController { private static final Logger LOGGER = LoggerFactory.getLogger(PatientController.class); @@ -70,20 +71,20 @@ public class PatientController { // TODO: to centralize protected static final String DEFAULT_PAGE_SIZE = "80"; - @Autowired - protected PatientBrowserManager patientManager; + private final PatientBrowserManager patientManager; - @Autowired - protected AdmissionBrowserManager admissionManager; + private final AdmissionBrowserManager admissionManager; - @Autowired - private PatientConsensusBrowserManager patientConsensusManager; + private final PatientConsensusBrowserManager patientConsensusManager; - @Autowired - protected PatientMapper patientMapper; + private final PatientMapper patientMapper; - public PatientController(PatientBrowserManager patientManager, AdmissionBrowserManager admissionManager, PatientMapper patientMapper, - PatientConsensusBrowserManager patientConsensusManager) { + public PatientController( + PatientBrowserManager patientManager, + AdmissionBrowserManager admissionManager, + PatientMapper patientMapper, + PatientConsensusBrowserManager patientConsensusManager + ) { this.patientManager = patientManager; this.admissionManager = admissionManager; this.patientMapper = patientMapper; @@ -93,12 +94,13 @@ public PatientController(PatientBrowserManager patientManager, AdmissionBrowserM /** * Create new {@link Patient}. * - * @param newPatient - * @return - * @throws OHServiceException + * @param newPatient Patient payload + * @return The created patient + * @throws OHServiceException When failed to create patient */ - @PostMapping(value = "/patients", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity newPatient(@RequestBody PatientDTO newPatient) throws OHServiceException { + @PostMapping(value = "/patients") + @ResponseStatus(HttpStatus.CREATED) + public PatientDTO newPatient(@RequestBody PatientDTO newPatient) throws OHServiceException { String name = StringUtils.hasLength(newPatient.getName()) ? newPatient.getFirstName() + ' ' + newPatient.getSecondName() : newPatient.getName(); LOGGER.info("Create patient '{}'.", name); @@ -113,19 +115,21 @@ ResponseEntity newPatient(@RequestBody PatientDTO newPatient) throws if (patient == null) { throw new OHAPIException(new OHExceptionMessage("Patient not created.")); } - return ResponseEntity.status(HttpStatus.CREATED).body(patientMapper.map2DTO(patient)); + + return patientMapper.map2DTO(patient); } - @PutMapping(value = "/patients/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity updatePatient(@PathVariable int code, @RequestBody PatientDTO updatePatient) throws OHServiceException { + @PutMapping(value = "/patients/{code}") + public PatientDTO updatePatient(@PathVariable int code, @RequestBody PatientDTO updatePatient) throws OHServiceException { LOGGER.info("Update patient code: '{}'.", code); if (!updatePatient.getCode().equals(code)) { throw new OHAPIException(new OHExceptionMessage("Patient code mismatch.")); } Patient patientRead = patientManager.getPatientById(code); if (patientRead == null) { - throw new OHAPIException(new OHExceptionMessage("Patient not found.")); + throw new OHAPIException(new OHExceptionMessage("Patient not found."), HttpStatus.NOT_FOUND); } + Optional patientConsensus = patientConsensusManager.getPatientConsensusByUserId(patientRead.getCode()); if (patientConsensus.isEmpty()) { throw new OHAPIException(new OHExceptionMessage("PatientConsensus not found.")); @@ -141,48 +145,50 @@ ResponseEntity updatePatient(@PathVariable int code, @RequestBody Pa if (patient == null) { throw new OHAPIException(new OHExceptionMessage("Patient not updated.")); } - PatientDTO patientDTO = patientMapper.map2DTO(patient); - return ResponseEntity.ok(patientDTO); + + return patientMapper.map2DTO(patient); } - @GetMapping(value = "/patients", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getPatients(@RequestParam(value = "page", required = false, defaultValue = "0") int page, - @RequestParam(value = "size", required = false, defaultValue = DEFAULT_PAGE_SIZE) int size) throws OHServiceException { + @GetMapping(value = "/patients") + public Page getPatients( + @RequestParam(value = "page", required = false, defaultValue = "0") int page, + @RequestParam(value = "size", required = false, defaultValue = DEFAULT_PAGE_SIZE) int size + ) throws OHServiceException { LOGGER.info("Get patients page: {} size: {}.", page, size); PagedResponse patients = patientManager.getPatientsPageable(page, size); - if (patients.getData().isEmpty()) { - LOGGER.info("The patient list is empty."); - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } + Page patientPageableDTO = new Page<>(); List patientsDTO = patientMapper.map2DTOList(patients.getData()); patientPageableDTO.setData(patientsDTO); patientPageableDTO.setPageInfo(patientMapper.setParameterPageInfo(patients.getPageInfo())); - return ResponseEntity.ok(patientPageableDTO); + + return patientPageableDTO; } - @GetMapping(value = "/patients/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getPatient(@PathVariable("code") int code) throws OHServiceException { + @GetMapping(value = "/patients/{code}") + public PatientDTO getPatient(@PathVariable("code") int code) throws OHServiceException { LOGGER.info("Get patient code: '{}'.", code); Patient patient = patientManager.getPatientById(code); LOGGER.info("Patient retrieved: {}.", patient); if (patient == null) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); + throw new OHAPIException(new OHExceptionMessage("Patient not found."), HttpStatus.NOT_FOUND); } + LOGGER.debug("AdmissionBrowserManager injected: {}.", admissionManager); Admission admission = admissionManager.getCurrentAdmission(patient); LOGGER.debug("Admission retrieved: {}.", admission); Boolean status = admission != null; - PatientDTO patientDTO = patientMapper.map2DTOWS(patient, status); - return ResponseEntity.ok(patientDTO); - } - @GetMapping(value = "/patients/search", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> searchPatient(@RequestParam(value = "firstName", defaultValue = "", required = false) String firstName, - @RequestParam(value = "secondName", defaultValue = "", required = false) String secondName, - @RequestParam(value = "birthDate", defaultValue = "", required = false) LocalDateTime birthDate, - @RequestParam(value = "address", defaultValue = "", required = false) String address) throws OHServiceException { + return patientMapper.map2DTOWS(patient, status); + } + @GetMapping(value = "/patients/search") + public List searchPatient( + @RequestParam(value = "firstName", defaultValue = "", required = false) String firstName, + @RequestParam(value = "secondName", defaultValue = "", required = false) String secondName, + @RequestParam(value = "birthDate", defaultValue = "", required = false) LocalDateTime birthDate, + @RequestParam(value = "address", defaultValue = "", required = false) String address + ) throws OHServiceException { Map params = new HashMap<>(); if (firstName != null && !firstName.isEmpty()) { @@ -201,76 +207,73 @@ public ResponseEntity> searchPatient(@RequestParam(value = "fir params.put("address", address); } - List patientList = null; + List patientList = new ArrayList<>(); if (!params.entrySet().isEmpty()) { patientList = patientManager.getPatients(params); } - if (patientList == null) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } - - List patientListDTO = patientList.stream().map(patient -> { + return patientList.stream().map(patient -> { Admission admission = admissionManager.getCurrentAdmission(patient); Boolean status = admission != null; return patientMapper.map2DTOWS(patient, status); - }).collect(Collectors.toList()); - return ResponseEntity.ok(patientListDTO); + }).toList(); } - @GetMapping(value = "/patients/all", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getPatientAll(@RequestParam int code) throws OHServiceException { + @GetMapping(value = "/patients/all") + public PatientDTO getPatientAll(@RequestParam int code) throws OHServiceException { LOGGER.info("Get patient for provided code even if logically deleted: '{}'.", code); Patient patient = patientManager.getPatientAll(code); if (patient == null) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); + throw new OHAPIException(new OHExceptionMessage("Patient not found."), HttpStatus.NOT_FOUND); } - PatientDTO patientDTO = patientMapper.map2DTO(patient); - return ResponseEntity.ok(patientDTO); + + return patientMapper.map2DTO(patient); } - @GetMapping(value = "/patients/nextcode", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getPatientNextCode() throws OHServiceException { + @GetMapping(value = "/patients/nextcode") + public Integer getPatientNextCode() throws OHServiceException { LOGGER.info("Get patient next code."); - int nextCode = patientManager.getNextPatientCode(); - return ResponseEntity.ok(nextCode); + return patientManager.getNextPatientCode(); } - @DeleteMapping(value = "/patients/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity deletePatient(@PathVariable int code) throws OHServiceException { + @DeleteMapping(value = "/patients/{code}") + public boolean deletePatient(@PathVariable int code) throws OHServiceException { LOGGER.info("Delete patient code: '{}'.", code); Patient patient = patientManager.getPatientById(code); if (patient == null) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); + throw new OHAPIException(new OHExceptionMessage("Patient not found."), HttpStatus.NOT_FOUND); } + try { patientManager.deletePatient(patient); + return true; } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Patient not deleted.")); } - return ResponseEntity.ok(true); } - @GetMapping(value = "/patients/merge", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity mergePatients(@RequestParam int mergedcode, @RequestParam int code2) throws OHServiceException { + @GetMapping(value = "/patients/merge") + public boolean mergePatients(@RequestParam int mergedcode, @RequestParam int code2) throws OHServiceException { LOGGER.info("Merge patient for code '{}' in patient for code '{}'.", code2, mergedcode); Patient mergedPatient = patientManager.getPatientById(mergedcode); Patient patient2 = patientManager.getPatientById(code2); if (mergedPatient == null || patient2 == null) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); + throw new OHAPIException(new OHExceptionMessage("Patient not found."), HttpStatus.NOT_FOUND); } + try { patientManager.mergePatient(mergedPatient, patient2); + return true; } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Patients not merged.")); } - return ResponseEntity.ok(true); } - @GetMapping(value = "/patients/cities", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getPatientCities() throws OHServiceException { + @GetMapping(value = "/patients/cities") + public List getPatientCities() throws OHServiceException { LOGGER.info("Get all cities of the patients."); - return ResponseEntity.ok(patientManager.getCities()); + + return patientManager.getCities(); } } diff --git a/src/main/java/org/isf/patvac/rest/PatVacController.java b/src/main/java/org/isf/patvac/rest/PatVacController.java index ae6115a21..3622b80a7 100644 --- a/src/main/java/org/isf/patvac/rest/PatVacController.java +++ b/src/main/java/org/isf/patvac/rest/PatVacController.java @@ -33,54 +33,52 @@ import org.isf.utils.exception.model.OHExceptionMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/patientvaccines") +@RestController @Tag(name = "Patient Vaccines") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class PatVacController { private static final Logger LOGGER = LoggerFactory.getLogger(PatVacController.class); - @Autowired - protected PatVacManager patVacManager; - - @Autowired - protected PatVacMapper mapper; + private final PatVacManager patVacManager; - public PatVacController(PatVacManager patVacManager, PatVacMapper patientVaccinemapper) { + private final PatVacMapper mapper; + + public PatVacController(PatVacManager patVacManager, PatVacMapper patientVaccineMapper) { this.patVacManager = patVacManager; - this.mapper = patientVaccinemapper; + this.mapper = patientVaccineMapper; } /** * Create a new {@link PatientVaccine}. - * @param patientVaccineDTO + * @param patientVaccineDTO Patient Vaccine DTO * @return {@code true} if the operation type has been stored, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to create patient vaccine */ - @PostMapping(value = "/patientvaccines", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity newPatientVaccine(@RequestBody PatientVaccineDTO patientVaccineDTO) throws OHServiceException { - int code = patientVaccineDTO.getCode(); - LOGGER.info("Create patient vaccine {}", code); - PatientVaccine newPatientVaccine; + @PostMapping("/patientvaccines") + @ResponseStatus(HttpStatus.CREATED) + public PatientVaccineDTO newPatientVaccine(@RequestBody PatientVaccineDTO patientVaccineDTO) throws OHServiceException { + LOGGER.info("Create patient vaccine {}", patientVaccineDTO.getCode()); + try { - newPatientVaccine = patVacManager.newPatientVaccine(mapper.map2Model(patientVaccineDTO)); - return ResponseEntity.status(HttpStatus.CREATED).body(mapper.map2DTO(newPatientVaccine)); + return mapper.map2DTO(patVacManager.newPatientVaccine(mapper.map2Model(patientVaccineDTO))); } catch (OHServiceException serviceException) { LOGGER.error("Patient vaccine not created."); throw new OHAPIException(new OHExceptionMessage("Patient vaccine not created.")); @@ -89,20 +87,19 @@ ResponseEntity newPatientVaccine(@RequestBody PatientVaccineD /** * Updates the specified {@link PatientVaccine}. - * @param patientVaccineDTO + * @param patientVaccineDTO Patient Vaccine payload * @return {@code true} if the operation type has been updated, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to update patient vaccine */ - @PutMapping(value = "/patientvaccines/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity updatePatientVaccinet(@PathVariable Integer code, @RequestBody PatientVaccineDTO patientVaccineDTO) - throws OHServiceException { + @PutMapping("/patientvaccines/{code}") + public PatientVaccineDTO updatePatientVaccinet( + @PathVariable Integer code, @RequestBody PatientVaccineDTO patientVaccineDTO + ) throws OHServiceException { LOGGER.info("Update patientvaccines code: {}", patientVaccineDTO.getCode()); PatientVaccine patvac = mapper.map2Model(patientVaccineDTO); patvac.setLock(patientVaccineDTO.getLock()); - PatientVaccine updatedPatientVaccine; try { - updatedPatientVaccine = patVacManager.updatePatientVaccine(mapper.map2Model(patientVaccineDTO)); - return ResponseEntity.ok(mapper.map2DTO(updatedPatientVaccine)); + return mapper.map2DTO(patVacManager.updatePatientVaccine(mapper.map2Model(patientVaccineDTO))); } catch (OHServiceException serviceException) { LOGGER.error("Patient vaccine not updated."); throw new OHAPIException(new OHExceptionMessage("Patient vaccine not updated.")); @@ -112,71 +109,70 @@ ResponseEntity updatePatientVaccinet(@PathVariable Integer co /** * Get all the {@link PatientVaccine}s for today or in the last week. * @return the list of {@link PatientVaccine}s - * @throws OHServiceException + * @throws OHServiceException When failed to get patient vaccines */ - @GetMapping(value = "/patientvaccines/week", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getPatientVaccines(@RequestParam(required=false) Boolean oneWeek) throws OHServiceException { + @GetMapping("/patientvaccines/week") + public List getPatientVaccines( + @RequestParam(required=false) Boolean oneWeek + ) throws OHServiceException { LOGGER.info("Get the all patient vaccine of to day or one week"); if (oneWeek == null) { oneWeek = false; } - List patientVaccines = patVacManager.getPatientVaccine(oneWeek); - List patientVaccineDTOs = mapper.map2DTOList(patientVaccines); - if (patientVaccineDTOs.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(patientVaccineDTOs); - } else { - return ResponseEntity.ok(patientVaccineDTOs); - } + + return mapper.map2DTOList(patVacManager.getPatientVaccine(oneWeek)); } - + /** * Get all {@link PatientVaccine}s within {@code dateFrom} and {@code dateTo}. * @return the list of {@link PatientVaccine}s - * @throws OHServiceException + * @throws OHServiceException When failed to get patient vaccines */ - @GetMapping(value = "/patientvaccines/filter", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getPatientVaccinesByDatesRanges(@RequestParam String vaccineTypeCode, @RequestParam String vaccineCode, - @RequestParam LocalDate dateFrom, @RequestParam LocalDate dateTo, @RequestParam char sex, @RequestParam int ageFrom, @RequestParam int ageTo) throws OHServiceException { + @GetMapping("/patientvaccines/filter") + public List getPatientVaccinesByDatesRanges( + @RequestParam String vaccineTypeCode, + @RequestParam String vaccineCode, + @RequestParam LocalDate dateFrom, + @RequestParam LocalDate dateTo, + @RequestParam char sex, + @RequestParam int ageFrom, + @RequestParam int ageTo + ) throws OHServiceException { LOGGER.info("filter patient vaccine by dates ranges"); - List patientVaccines = patVacManager.getPatientVaccine(vaccineTypeCode, vaccineCode, dateFrom.atStartOfDay(), dateTo.atStartOfDay(), sex, ageFrom, ageTo); - List patientVaccineDTOs = mapper.map2DTOList(patientVaccines); - if (patientVaccineDTOs.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(patientVaccineDTOs); - } else { - return ResponseEntity.ok(patientVaccineDTOs); - } + return mapper.map2DTOList(patVacManager.getPatientVaccine( + vaccineTypeCode, vaccineCode, dateFrom.atStartOfDay(), dateTo.atStartOfDay(), sex, ageFrom, ageTo + )); } - + /** * Get the maximum progressive number within specified year or within current year if {@code 0}. * @return {@code int} - the progressive number in the year - * @throws OHServiceException + * @throws OHServiceException When failed to get the progressive number */ - @GetMapping(value = "/patientvaccines/progyear/{year}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getProgYear(@PathVariable int year) throws OHServiceException { + @GetMapping("/patientvaccines/progyear/{year}") + public Integer getProgYear(@PathVariable int year) throws OHServiceException { LOGGER.info("Get progressive number within specified year"); - int yProg = patVacManager.getProgYear(year); - return ResponseEntity.ok(yProg); + + return patVacManager.getProgYear(year); } /** * Delete {@link PatientVaccine} for specified code. - * @param code + * @param code Patient vaccine code * @return {@code true} if the {@link PatientVaccine} has been deleted, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to delete patient vaccine */ - @DeleteMapping(value = "/patientvaccines/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity deletePatientVaccine(@PathVariable int code) throws OHServiceException { + @DeleteMapping("/patientvaccines/{code}") + public boolean deletePatientVaccine(@PathVariable int code) throws OHServiceException { LOGGER.info("Delete patient vaccine code: {}", code); PatientVaccine patVac = new PatientVaccine(); patVac.setCode(code); try { patVacManager.deletePatientVaccine(patVac); - return ResponseEntity.ok(true); + return true; } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Patient vaccine not deleted.")); } } - } diff --git a/src/main/java/org/isf/permissions/rest/PermissionController.java b/src/main/java/org/isf/permissions/rest/PermissionController.java index 33338547d..edbeab3b0 100644 --- a/src/main/java/org/isf/permissions/rest/PermissionController.java +++ b/src/main/java/org/isf/permissions/rest/PermissionController.java @@ -22,80 +22,80 @@ package org.isf.permissions.rest; import java.util.List; + import org.isf.permissions.dto.PermissionDTO; import org.isf.permissions.manager.PermissionManager; import org.isf.permissions.mapper.PermissionMapper; import org.isf.permissions.model.Permission; +import org.isf.shared.exceptions.OHAPIException; import org.isf.utils.exception.OHServiceException; +import org.isf.utils.exception.model.OHExceptionMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/permissions") +@RestController @Tag(name = "Permissions") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class PermissionController { private static final Logger LOGGER = LoggerFactory.getLogger(PermissionController.class); - @Autowired - protected PermissionManager permissionManager; + private final PermissionManager permissionManager; + + private final PermissionMapper permissionMapper; - @Autowired - protected PermissionMapper permissionMapper; + public PermissionController(PermissionManager permissionManager, PermissionMapper permissionMapper) { + this.permissionManager = permissionManager; + this.permissionMapper = permissionMapper; + } - @GetMapping(value = "/permissions/userGroupCode/{userGroupCode}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> retrievePermissionsByUserGroupCode(@PathVariable("userGroupCode") String userGroupCode) - throws OHServiceException { + @GetMapping(value = "/permissions/userGroupCode/{userGroupCode}") + public List retrievePermissionsByUserGroupCode( + @PathVariable("userGroupCode") String userGroupCode + ) throws OHServiceException { LOGGER.info("Retrieving permissions: retrievePermissionsByUserGroupCode({}).", userGroupCode); - List domains = permissionManager.retrievePermissionsByGroupCode(userGroupCode); - List dtos = permissionMapper.map2DTOList(domains); - if (dtos.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(dtos); - } else { - return ResponseEntity.status(HttpStatus.CREATED).body(dtos); - } + + return permissionMapper.map2DTOList(permissionManager.retrievePermissionsByGroupCode(userGroupCode)); } - @GetMapping(value = "/permissions", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> retrieveAllPermissions() throws OHServiceException { + @GetMapping(value = "/permissions") + public List retrieveAllPermissions() throws OHServiceException { LOGGER.info("Retrieving permissions: retrieveAllPermissions()."); - List permissions = permissionManager.retrieveAllPermissions(); - if (permissions == null) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } - List dtos = permissionMapper.map2DTOList(permissions); - return ResponseEntity.status(HttpStatus.CREATED).body(dtos); + + return permissionMapper.map2DTOList(permissionManager.retrieveAllPermissions()); } - @GetMapping(value = "/permissions/{id}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity retrievePermissionById(@PathVariable("id") Integer id) throws OHServiceException { + @GetMapping(value = "/permissions/{id}") + public PermissionDTO retrievePermissionById(@PathVariable("id") Integer id) throws OHServiceException { LOGGER.info("Retrieving permissions: retrievePermissionById({}).", id); Permission permission = permissionManager.retrievePermissionById(id); + if (permission == null) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); + throw new OHAPIException(new OHExceptionMessage("Permission not created."), HttpStatus.NOT_FOUND); } - PermissionDTO dtos = permissionMapper.map2DTO(permission); - return ResponseEntity.status(HttpStatus.CREATED).body(dtos); + + return permissionMapper.map2DTO(permission); } - @GetMapping(value = "/permissions/name/{name:.+}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity retrievePermissionByName(@PathVariable("name") String name) throws OHServiceException { + @GetMapping(value = "/permissions/name/{name:.+}") + public PermissionDTO retrievePermissionByName(@PathVariable("name") String name) throws OHServiceException { LOGGER.info("Retrieving permissions: retrievePermissionByName({}).", name); Permission permission = permissionManager.retrievePermissionByName(name); + if (permission == null) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); + throw new OHAPIException(new OHExceptionMessage("Permission not created."), HttpStatus.NOT_FOUND); } - PermissionDTO dtos = permissionMapper.map2DTO(permission); - return ResponseEntity.status(HttpStatus.CREATED).body(dtos); + + return permissionMapper.map2DTO(permission); } } diff --git a/src/main/java/org/isf/pregtreattype/rest/PregnantTreatmentTypeController.java b/src/main/java/org/isf/pregtreattype/rest/PregnantTreatmentTypeController.java index 3d79d1479..8db09d864 100644 --- a/src/main/java/org/isf/pregtreattype/rest/PregnantTreatmentTypeController.java +++ b/src/main/java/org/isf/pregtreattype/rest/PregnantTreatmentTypeController.java @@ -22,7 +22,6 @@ package org.isf.pregtreattype.rest; import java.util.List; -import java.util.stream.Collectors; import org.isf.pregtreattype.dto.PregnantTreatmentTypeDTO; import org.isf.pregtreattype.manager.PregnantTreatmentTypeBrowserManager; @@ -33,125 +32,132 @@ import org.isf.utils.exception.model.OHExceptionMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/pregnanttreatmenttypes") +@RestController @Tag(name = "Pregnant Treatment Types") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class PregnantTreatmentTypeController { private static final Logger LOGGER = LoggerFactory.getLogger(PregnantTreatmentTypeController.class); - @Autowired - protected PregnantTreatmentTypeBrowserManager pregTreatTypeManager; + private final PregnantTreatmentTypeBrowserManager pregnantTreatmentTypeManager; - @Autowired - protected PregnantTreatmentTypeMapper mapper; + private final PregnantTreatmentTypeMapper mapper; - public PregnantTreatmentTypeController(PregnantTreatmentTypeBrowserManager pregTreatTypeManager, PregnantTreatmentTypeMapper pregnantTreatmentTypemapper) { - this.pregTreatTypeManager = pregTreatTypeManager; + public PregnantTreatmentTypeController( + PregnantTreatmentTypeBrowserManager pregnantTreatmentTypeManager, + PregnantTreatmentTypeMapper pregnantTreatmentTypemapper + ) { + this.pregnantTreatmentTypeManager = pregnantTreatmentTypeManager; this.mapper = pregnantTreatmentTypemapper; } /** * Create a new {@link PregnantTreatmentType}. - * - * @param pregnantTreatmentTypeDTO + * + * @param pregnantTreatmentTypeDTO Pregnant Treatment Type payload * @return the newly stored {@link PregnantTreatmentType} object. - * @throws OHServiceException + * @throws OHServiceException When failed to create Pregnant Treatment Type */ - @PostMapping(value = "/pregnanttreatmenttypes", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity newPregnantTreatmentType(@RequestBody PregnantTreatmentTypeDTO pregnantTreatmentTypeDTO) - throws OHServiceException { - String code = pregnantTreatmentTypeDTO.getCode(); - LOGGER.info("Create PregnantTreatmentType {}", code); - PregnantTreatmentType isCreatedPregnantTreatmentType = pregTreatTypeManager.newPregnantTreatmentType(mapper.map2Model(pregnantTreatmentTypeDTO)); + @PostMapping(value = "/pregnanttreatmenttypes") + @ResponseStatus(HttpStatus.CREATED) + public PregnantTreatmentTypeDTO newPregnantTreatmentType( + @RequestBody PregnantTreatmentTypeDTO pregnantTreatmentTypeDTO + ) throws OHServiceException { + LOGGER.info("Create PregnantTreatmentType {}", pregnantTreatmentTypeDTO.getCode()); + + PregnantTreatmentType isCreatedPregnantTreatmentType = pregnantTreatmentTypeManager.newPregnantTreatmentType( + mapper.map2Model(pregnantTreatmentTypeDTO) + ); + if (isCreatedPregnantTreatmentType == null) { throw new OHAPIException(new OHExceptionMessage("Pregnant Treatment Type not created.")); } - return ResponseEntity.status(HttpStatus.CREATED).body(mapper.map2DTO(isCreatedPregnantTreatmentType)); + + return mapper.map2DTO(isCreatedPregnantTreatmentType); } /** * Updates the specified {@link PregnantTreatmentType}. - * - * @param pregnantTreatmentTypeDTO + * + * @param pregnantTreatmentTypeDTO Pregnant Treatment Type payload * @return the updated {@link PregnantTreatmentType} object. - * @throws OHServiceException + * @throws OHServiceException When failed to update Pregnant Treatment Type */ - @PutMapping(value = "/pregnanttreatmenttypes/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity updatePregnantTreatmentTypes(@PathVariable String code, - @RequestBody PregnantTreatmentTypeDTO pregnantTreatmentTypeDTO) - throws OHServiceException { + @PutMapping(value = "/pregnanttreatmenttypes/{code}") + public PregnantTreatmentTypeDTO updatePregnantTreatmentTypes( + @PathVariable String code, + @RequestBody PregnantTreatmentTypeDTO pregnantTreatmentTypeDTO + ) throws OHServiceException { LOGGER.info("Update PregnantTreatmentType code: {}", pregnantTreatmentTypeDTO.getCode()); PregnantTreatmentType pregTreatType = mapper.map2Model(pregnantTreatmentTypeDTO); - if (!pregTreatTypeManager.isCodePresent(code)) { - throw new OHAPIException(new OHExceptionMessage("Pregnant Treatment Type not found.")); + if (!pregnantTreatmentTypeManager.isCodePresent(code)) { + throw new OHAPIException(new OHExceptionMessage("Pregnant Treatment Type not found."), HttpStatus.NOT_FOUND); } - PregnantTreatmentType isUpdatedPregnantTreatmentType = pregTreatTypeManager.updatePregnantTreatmentType(pregTreatType); + PregnantTreatmentType isUpdatedPregnantTreatmentType = pregnantTreatmentTypeManager.updatePregnantTreatmentType(pregTreatType); if (isUpdatedPregnantTreatmentType == null) { throw new OHAPIException(new OHExceptionMessage("Pregnant Treatment Type not updated.")); } - return ResponseEntity.ok(mapper.map2DTO(isUpdatedPregnantTreatmentType)); + + return mapper.map2DTO(isUpdatedPregnantTreatmentType); } /** * Get all the available {@link PregnantTreatmentType}s. - * + * * @return a {@link List} of {@link PregnantTreatmentType} or NO_CONTENT if there is no data found. - * @throws OHServiceException + * @throws OHServiceException When failed to get Pregnant Treatment Types */ - @GetMapping(value = "/pregnanttreatmenttypes", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getPregnantTreatmentTypes() throws OHServiceException { + @GetMapping(value = "/pregnanttreatmenttypes") + public List getPregnantTreatmentTypes() throws OHServiceException { LOGGER.info("Get all pregnantTreatment Types "); - List pregnantTreatmentTypes = pregTreatTypeManager.getPregnantTreatmentType(); - List pregnantTreatmentTypeDTOs = mapper.map2DTOList(pregnantTreatmentTypes); - if (pregnantTreatmentTypeDTOs.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(pregnantTreatmentTypeDTOs); - } else { - return ResponseEntity.ok(pregnantTreatmentTypeDTOs); - } + + List pregnantTreatmentTypes = pregnantTreatmentTypeManager.getPregnantTreatmentType(); + + return mapper.map2DTOList(pregnantTreatmentTypes); } /** * Delete the {@link PregnantTreatmentType} for the specified code. - * - * @param code + * + * @param code Pregnant Treatment Type code * @return {@code true} if the {@link PregnantTreatmentType} has been deleted, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to delete Pregnant Treatment Type */ - @DeleteMapping(value = "/pregnanttreatmenttypes/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity deletePregnantTreatmentType(@PathVariable("code") String code) throws OHServiceException { + @DeleteMapping(value = "/pregnanttreatmenttypes/{code}") + public boolean deletePregnantTreatmentType(@PathVariable("code") String code) throws OHServiceException { LOGGER.info("Delete PregnantTreatment Type code: {}", code); - if (pregTreatTypeManager.isCodePresent(code)) { - List pregTreatTypes = pregTreatTypeManager.getPregnantTreatmentType(); - List pregTreatTypeFounds = pregTreatTypes.stream().filter(ad -> ad.getCode().equals(code)) - .collect(Collectors.toList()); - if (!pregTreatTypeFounds.isEmpty()) { - try { - pregTreatTypeManager.deletePregnantTreatmentType(pregTreatTypeFounds.get(0)); - } catch (OHServiceException serviceException) { - LOGGER.error("Delete PregnantTreatment Type: {} failed.", code); - throw new OHAPIException(new OHExceptionMessage("PregnantTreatment Type not deleted.")); - } - } - } else { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); + List pregTreatTypes = pregnantTreatmentTypeManager.getPregnantTreatmentType(); + List pregTreatTypeFounds = pregTreatTypes + .stream() + .filter(ad -> ad.getCode().equals(code)) + .toList(); + + if (pregTreatTypeFounds.isEmpty()) { + throw new OHAPIException(new OHExceptionMessage("Pregnant Treatment Type not found."), HttpStatus.NOT_FOUND); } - return ResponseEntity.ok(true); - } + try { + pregnantTreatmentTypeManager.deletePregnantTreatmentType(pregTreatTypeFounds.get(0)); + return true; + } catch (OHServiceException serviceException) { + LOGGER.error("Delete PregnantTreatment Type: {} failed.", code); + throw new OHAPIException(new OHExceptionMessage("PregnantTreatment Type not deleted.")); + } + } } diff --git a/src/main/java/org/isf/priceslist/dto/PriceDTO.java b/src/main/java/org/isf/priceslist/dto/PriceDTO.java index c1c0a1f49..e386653a4 100644 --- a/src/main/java/org/isf/priceslist/dto/PriceDTO.java +++ b/src/main/java/org/isf/priceslist/dto/PriceDTO.java @@ -23,8 +23,6 @@ import jakarta.validation.constraints.NotNull; -import org.isf.priceslist.model.PriceList; - import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema.AccessMode; @@ -35,7 +33,7 @@ public class PriceDTO { @NotNull @Schema(description = "The price list") - private PriceList list; + private PriceListDTO list; @NotNull @Schema(description = "The group") @@ -79,7 +77,7 @@ public int getId() { return this.id; } - public PriceList getList() { + public PriceListDTO getList() { return this.list; } @@ -103,7 +101,7 @@ public void setId(int id) { this.id = id; } - public void setList(PriceList list) { + public void setList(PriceListDTO list) { this.list = list; } diff --git a/src/main/java/org/isf/priceslist/rest/PriceListController.java b/src/main/java/org/isf/priceslist/rest/PriceListController.java index 578d1c3e6..a332c2b29 100644 --- a/src/main/java/org/isf/priceslist/rest/PriceListController.java +++ b/src/main/java/org/isf/priceslist/rest/PriceListController.java @@ -22,7 +22,6 @@ package org.isf.priceslist.rest; import java.util.List; -import java.util.stream.Collectors; import org.isf.priceslist.dto.PriceDTO; import org.isf.priceslist.dto.PriceListDTO; @@ -36,55 +35,54 @@ import org.isf.utils.exception.model.OHExceptionMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/pricelists") +@RestController @Tag(name = "Price Lists") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class PriceListController { private static final Logger LOGGER = LoggerFactory.getLogger(PriceListController.class); - @Autowired - protected PriceListManager priceListManager; - - @Autowired - protected PriceListMapper mapper; - - @Autowired - protected PriceMapper priceMapper; + private final PriceListManager priceListManager; - public PriceListController(PriceListManager priceListManager, PriceListMapper priceListmapper) { + private final PriceListMapper mapper; + + private final PriceMapper priceMapper; + + public PriceListController(PriceListManager priceListManager, PriceListMapper priceListmapper, PriceMapper priceMapper) { this.priceListManager = priceListManager; this.mapper = priceListmapper; + this.priceMapper = priceMapper; } /** * Create a new {@link PriceList}. - * @param priceListDTO + * @param priceListDTO PriceList payload * @return the new {@link PriceList}. - * @throws OHServiceException + * @throws OHServiceException When failed to create price list */ - @PostMapping(value = "/pricelists", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity newPriceList(@RequestBody PriceListDTO priceListDTO) throws OHServiceException { + @PostMapping("/pricelists") + @ResponseStatus(HttpStatus.CREATED) + public PriceListDTO newPriceList(@RequestBody PriceListDTO priceListDTO) throws OHServiceException { LOGGER.info("Create price list {}.", priceListDTO.getCode()); try { - PriceList createdPriceList = priceListManager.newList(mapper.map2Model(priceListDTO)); - return ResponseEntity.status(HttpStatus.CREATED).body(mapper.map2DTO(createdPriceList)); + return mapper.map2DTO(priceListManager.newList(mapper.map2Model(priceListDTO))); } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Price list not created.")); } @@ -92,18 +90,18 @@ ResponseEntity newPriceList(@RequestBody PriceListDTO priceListDTO /** * Updates the specified {@link PriceList}. - * @param priceListDTO + * @param priceListDTO Price List payload * @return the updated {@link PriceList}. - * @throws OHServiceException + * @throws OHServiceException When failed to update the price list */ - @PutMapping(value = "/pricelists/{id}", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity updatePriceLists(@PathVariable Integer id, @RequestBody PriceListDTO priceListDTO) - throws OHServiceException { - LOGGER.info("Update pricelists code: {}.", priceListDTO.getCode()); + @PutMapping("/pricelists/{id}") + public PriceListDTO updatePriceLists( + @PathVariable Integer id, @RequestBody PriceListDTO priceListDTO + ) throws OHServiceException { + LOGGER.info("Update price list code: {}.", priceListDTO.getCode()); PriceList priceList = mapper.map2Model(priceListDTO); try { - PriceList updatedPriceList = priceListManager.updateList(priceList); - return ResponseEntity.ok(mapper.map2DTO(updatedPriceList)); + return mapper.map2DTO(priceListManager.updateList(priceList)); } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Price list not updated.")); } @@ -112,99 +110,92 @@ ResponseEntity updatePriceLists(@PathVariable Integer id, @Request /** * Get all the available {@link PriceList}s. * @return a {@link List} of {@link PriceList} or NO_CONTENT if there is no data found. - * @throws OHServiceException + * @throws OHServiceException WHen failed to price lists */ - @GetMapping(value = "/pricelists", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getPriceLists() throws OHServiceException { + @GetMapping("/pricelists") + public List getPriceLists() throws OHServiceException { LOGGER.info("Get all price lists."); - List priceLists = priceListManager.getLists(); - List priceListDTOs = mapper.map2DTOList(priceLists); - if (priceListDTOs.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(priceListDTOs); - } else { - return ResponseEntity.ok(priceListDTOs); - } + + return mapper.map2DTOList(priceListManager.getLists()); } - + /** * Get all the available {@link Price}s. * @return a {@link List} of {@link PriceList} or NO_CONTENT if there is no data found. - * @throws OHServiceException + * @throws OHServiceException When failed to get prices */ - @GetMapping(value = "/pricelists/prices", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getPrices() throws OHServiceException { + @GetMapping("/pricelists/prices") + public List getPrices() throws OHServiceException { LOGGER.info("Get all prices."); - List prices = priceListManager.getPrices(); - List priceListDTOs = priceMapper.map2DTOList(prices); - if (priceListDTOs.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(priceListDTOs); - } else { - return ResponseEntity.ok(priceListDTOs); - } + + return priceMapper.map2DTOList(priceListManager.getPrices()); } /** * Delete {@link PriceList} for specified code. - * @param id + * @param id Price list ID * @return {@code true} if the {@link PriceList} has been deleted. - * @throws OHServiceException + * @throws OHServiceException When failed to delete price list */ - @DeleteMapping(value = "/pricelists/{id}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity deletePriceList(@PathVariable int id) throws OHServiceException { + @DeleteMapping("/pricelists/{id}") + public boolean deletePriceList(@PathVariable int id) throws OHServiceException { LOGGER.info("Delete price list id: {}.", id); List priceLists = priceListManager.getLists(); - List priceListFounds = priceLists.stream().filter(pl -> pl.getId() == id).collect(Collectors.toList()); + List priceListFounds = priceLists.stream().filter(pl -> pl.getId() == id).toList(); if (priceListFounds.isEmpty()) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); + throw new OHAPIException(new OHExceptionMessage("Price list not found."), HttpStatus.NOT_FOUND); } try { priceListManager.deleteList(priceListFounds.get(0)); - return ResponseEntity.ok(true); + return true; } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Price list not deleted.")); } } - + /** * Duplicate specified {@link PriceList}. * @return {@code true} if the list has been duplicated. - * @throws OHServiceException + * @throws OHServiceException When failed to duplicate the price list */ - @GetMapping(value = "/pricelists/duplicate/{id}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity copyList(@PathVariable Long id) throws OHServiceException { + @GetMapping("/pricelists/duplicate/{id}") + public boolean copyList(@PathVariable Long id) throws OHServiceException { LOGGER.info("Duplicate list for price list id: {}.", id); List priceLists = priceListManager.getLists(); - List priceListFounds = priceLists.stream().filter(pl -> pl.getId() == id).collect(Collectors.toList()); + List priceListFounds = priceLists.stream().filter(pl -> pl.getId() == id).toList(); if (priceListFounds.isEmpty()) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); + throw new OHAPIException(new OHExceptionMessage("Price list not found."), HttpStatus.NOT_FOUND); } + try { priceListManager.copyList(priceListFounds.get(0)); - return ResponseEntity.ok(true); + return true; } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Price list not duplicated.")); } } - + /** * Duplicate {@link PriceList} multiplying by {@code factor} and rounding by {@code step}. * @return {@code true} if the list has been duplicated. - * @throws OHServiceException + * @throws OHServiceException When failed to duplicate the price list */ - @GetMapping(value = "/pricelists/duplicate/byfactor/{id}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity copyByFactorAndStep(@PathVariable Long id, @RequestParam double factor, @RequestParam double step) throws OHServiceException { + @GetMapping("/pricelists/duplicate/byfactor/{id}") + public boolean copyByFactorAndStep( + @PathVariable Long id, @RequestParam double factor, @RequestParam double step + ) throws OHServiceException { LOGGER.info("Duplicate list for price list id: {}.", id); List priceLists = priceListManager.getLists(); - List priceListFounds = priceLists.stream().filter(pl -> pl.getId() == id).collect(Collectors.toList()); + List priceListFounds = priceLists.stream().filter(pl -> pl.getId() == id).toList(); if (priceListFounds.isEmpty()) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); + throw new OHAPIException(new OHExceptionMessage("Price list not found."), HttpStatus.NOT_FOUND); } + try { priceListManager.copyList(priceListFounds.get(0), factor, step); - return ResponseEntity.ok(true); + return true; } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Price list not duplicated.")); } } - } diff --git a/src/main/java/org/isf/pricesothers/rest/PricesOthersController.java b/src/main/java/org/isf/pricesothers/rest/PricesOthersController.java index 97bcd335e..66a5ddb0d 100644 --- a/src/main/java/org/isf/pricesothers/rest/PricesOthersController.java +++ b/src/main/java/org/isf/pricesothers/rest/PricesOthersController.java @@ -22,7 +22,6 @@ package org.isf.pricesothers.rest; import java.util.List; -import java.util.stream.Collectors; import org.isf.pricesothers.dto.PricesOthersDTO; import org.isf.pricesothers.manager.PricesOthersManager; @@ -33,33 +32,32 @@ import org.isf.utils.exception.model.OHExceptionMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/pricesothers") +@RestController @Tag(name = "Others Price") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class PricesOthersController { private static final Logger LOGGER = LoggerFactory.getLogger(PricesOthersController.class); - @Autowired - protected PricesOthersManager pricesOthersManager; + private final PricesOthersManager pricesOthersManager; - @Autowired - protected PricesOthersMapper mapper; + private final PricesOthersMapper mapper; public PricesOthersController(PricesOthersManager pricesOthersManager, PricesOthersMapper pricesOthersmapper) { this.pricesOthersManager = pricesOthersManager; @@ -68,17 +66,16 @@ public PricesOthersController(PricesOthersManager pricesOthersManager, PricesOth /** * Create a new {@link PricesOthers}. - * @param pricesOthersDTO + * @param pricesOthersDTO PriceOther payload * @return {@code true} if the prices others has been stored, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to create price other */ - @PostMapping(value = "/pricesothers", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity newPricesOthers(@RequestBody PricesOthersDTO pricesOthersDTO) throws OHServiceException { + @PostMapping("/pricesothers") + @ResponseStatus(HttpStatus.CREATED) + public PricesOthersDTO newPricesOthers(@RequestBody PricesOthersDTO pricesOthersDTO) throws OHServiceException { LOGGER.info("Create prices others {}", pricesOthersDTO.getCode()); - PricesOthers newPricesOthers; try { - newPricesOthers = pricesOthersManager.newOther(mapper.map2Model(pricesOthersDTO)); - return ResponseEntity.status(HttpStatus.CREATED).body(mapper.map2DTO(newPricesOthers)); + return mapper.map2DTO(pricesOthersManager.newOther(mapper.map2Model(pricesOthersDTO))); } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Prices Others not created.")); } @@ -86,24 +83,28 @@ ResponseEntity newPricesOthers(@RequestBody PricesOthersDTO pri /** * Updates the specified {@link PricesOthers}. - * @param pricesOthersDTO + * @param pricesOthersDTO PriceOther payload * @return {@code true} if the prices others has been updated, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to update price other */ - @PutMapping(value = "/pricesothers/{id}", produces = MediaType.APPLICATION_JSON_VALUE) - ResponseEntity updatePricesOthers(@PathVariable Integer id, @RequestBody PricesOthersDTO pricesOthersDTO) - throws OHServiceException { - LOGGER.info("Update pricesothers code: {}", pricesOthersDTO.getCode()); + @PutMapping("/pricesothers/{id}") + public PricesOthersDTO updatePricesOthers( + @PathVariable Integer id, @RequestBody PricesOthersDTO pricesOthersDTO + ) throws OHServiceException { + LOGGER.info("Update prices other code: {}", pricesOthersDTO.getCode()); + PricesOthers pricesOthers = mapper.map2Model(pricesOthersDTO); - List pricesOthersFounds = pricesOthersManager.getOthers().stream().filter(po -> po.getId() == pricesOthersDTO.getId()) - .collect(Collectors.toList()); + List pricesOthersFounds = pricesOthersManager.getOthers() + .stream() + .filter(po -> po.getId() == pricesOthersDTO.getId()) + .toList(); + if (pricesOthersFounds.isEmpty()) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); + throw new OHAPIException(new OHExceptionMessage("Other price not found."), HttpStatus.NOT_FOUND); } - PricesOthers isUpdatedPricesOthers; + try { - isUpdatedPricesOthers = pricesOthersManager.updateOther(pricesOthers); - return ResponseEntity.ok(mapper.map2DTO(isUpdatedPricesOthers)); + return mapper.map2DTO(pricesOthersManager.updateOther(pricesOthers)); } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Prices Others not updated.")); } @@ -112,40 +113,37 @@ ResponseEntity updatePricesOthers(@PathVariable Integer id, @Re /** * Get all the available {@link PricesOthers}s. * @return a {@link List} of {@link PricesOthers} or NO_CONTENT if there is no data found. - * @throws OHServiceException + * @throws OHServiceException When failed to get other prices */ - @GetMapping(value = "/pricesothers", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getPricesOthers() throws OHServiceException { + @GetMapping("/pricesothers") + public List getPricesOthers() throws OHServiceException { LOGGER.info("Get all prices others "); - List pricesOthers = pricesOthersManager.getOthers(); - List pricesOthersDTOs = mapper.map2DTOList(pricesOthers); - if (pricesOthersDTOs.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(pricesOthersDTOs); - } else { - return ResponseEntity.ok(pricesOthersDTOs); - } + + return mapper.map2DTOList(pricesOthersManager.getOthers()); } /** * Delete {@link PricesOthers} for specified code. - * @param id + * @param id Other price ID * @return {@code true} if the {@link PricesOthers} has been deleted, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to delete the other price */ - @DeleteMapping(value = "/pricesothers/{id}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity deletePricesOthers(@PathVariable int id) throws OHServiceException { + @DeleteMapping("/pricesothers/{id}") + public boolean deletePricesOthers(@PathVariable int id) throws OHServiceException { LOGGER.info("Delete prices others id: {}", id); + List pricesOthers = pricesOthersManager.getOthers(); - List pricesOthersFounds = pricesOthers.stream().filter(po -> po.getId() == id).collect(Collectors.toList()); + List pricesOthersFounds = pricesOthers.stream().filter(po -> po.getId() == id).toList(); + if (pricesOthersFounds.isEmpty()) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); + throw new OHAPIException(new OHExceptionMessage("Other price not deleted."), HttpStatus.NOT_FOUND); } + try { pricesOthersManager.deleteOther(pricesOthersFounds.get(0)); - return ResponseEntity.ok(true); + return true; } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Prices Others not deleted.")); } } - } diff --git a/src/main/java/org/isf/sms/rest/SmsController.java b/src/main/java/org/isf/sms/rest/SmsController.java index e8ebb27ae..cdf07581d 100644 --- a/src/main/java/org/isf/sms/rest/SmsController.java +++ b/src/main/java/org/isf/sms/rest/SmsController.java @@ -22,7 +22,6 @@ package org.isf.sms.rest; import java.time.LocalDate; -import java.time.LocalDateTime; import java.util.List; import jakarta.validation.Valid; @@ -36,84 +35,84 @@ import org.isf.utils.exception.model.OHExceptionMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/sms") +@RestController @Tag(name = "SMS") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class SmsController { private static final Logger LOGGER = LoggerFactory.getLogger(SmsController.class); - @Autowired - private SmsManager smsManager; + private final SmsManager smsManager; + + private final SmsMapper smsMapper; + + public SmsController(SmsManager smsManager, SmsMapper smsMapper) { + this.smsManager = smsManager; + this.smsMapper = smsMapper; + } - @Autowired - private SmsMapper smsMapper; - /** * Fetch the list of {@link Sms}s. - * @param dateFrom - * @param dateTo + * @param dateFrom Start date + * @param dateTo End date * @return the found list - * @throws OHServiceException + * @throws OHServiceException When failed to get sms */ - @GetMapping(value = "/sms", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getAll( - @RequestParam(required = true) String dateFrom, - @RequestParam(required = true) String dateTo) throws OHServiceException { + @GetMapping(value = "/sms") + public List getAll( + @RequestParam() String dateFrom, + @RequestParam() String dateTo + ) throws OHServiceException { LOGGER.info("Fetching the list of sms"); - LocalDateTime from = LocalDate.parse(dateFrom).atStartOfDay(); - LocalDateTime to = LocalDate.parse(dateTo).atStartOfDay(); - List smsList = smsManager.getAll(from, to); - List mappedSmsList = smsMapper.map2DTOList(smsList); - if (mappedSmsList.isEmpty()) { - LOGGER.info("No sms found"); - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(mappedSmsList); - } else { - LOGGER.info("Found {} sms", mappedSmsList.size()); - return ResponseEntity.ok(mappedSmsList); - } + + return smsMapper.map2DTOList(smsManager.getAll( + LocalDate.parse(dateFrom).atStartOfDay(), + LocalDate.parse(dateTo).atStartOfDay() + )); } - + /** * Save the specified {@link Sms}. - * @param smsDTO + * @param smsDTO SMS payload * @return {@code true} if the sms is saved - * @throws OHServiceException + * @throws OHServiceException When failed to save the SMS */ - @PostMapping(value = "/sms", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity saveSms( - @RequestBody @Valid SmsDTO smsDTO, - @RequestParam(defaultValue="false") boolean split) throws OHServiceException { + @PostMapping(value = "/sms") + public boolean saveSms( + @RequestBody @Valid SmsDTO smsDTO, + @RequestParam(defaultValue="false") boolean split + ) throws OHServiceException { smsManager.saveOrUpdate(smsMapper.map2Model(smsDTO), split); - return ResponseEntity.ok(true); + return true; } - + /** * Deletes the specified {@link Sms}. - * @param smsDTOList + * @param smsDTOList SMS * @return {@code true} if the sms is deleted - * @throws OHServiceException + * @throws OHServiceException When failed to delete SMS */ - @PostMapping(value = "/sms/delete", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity deleteSms(@RequestBody @Valid List smsDTOList) throws OHServiceException { + @PostMapping(value = "/sms/delete") + public Boolean deleteSms(@RequestBody @Valid List smsDTOList) throws OHServiceException { List smsList = smsMapper.map2ModelList(smsDTOList); if (smsList.stream().anyMatch(sms -> sms.getSmsId() <= 0)) { - throw new OHAPIException(new OHExceptionMessage("Some Sms are not found.")); + throw new OHAPIException(new OHExceptionMessage("Some Sms are not found."), HttpStatus.NOT_FOUND); } smsManager.delete(smsList); - return ResponseEntity.ok(true); + + return true; } } diff --git a/src/main/java/org/isf/stats/rest/ReportsController.java b/src/main/java/org/isf/stats/rest/ReportsController.java index e12b9ee2a..28b022e1f 100644 --- a/src/main/java/org/isf/stats/rest/ReportsController.java +++ b/src/main/java/org/isf/stats/rest/ReportsController.java @@ -34,36 +34,43 @@ import org.isf.stat.manager.JasperReportsManager; import org.isf.utils.exception.OHServiceException; import org.isf.utils.exception.model.OHExceptionMessage; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/reports") +@RestController @Tag(name = "Reports") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class ReportsController { - @Autowired - private JasperReportsManager reportsManager; - @GetMapping(value = "/reports/exams-list", produces = MediaType.APPLICATION_JSON_VALUE) + private final JasperReportsManager reportsManager; + + public ReportsController(JasperReportsManager reportsManager) { + this.reportsManager = reportsManager; + } + + @GetMapping("/reports/exams-list") public ResponseEntity printExamsListPdf(HttpServletRequest request) throws OHServiceException, IOException { return getReport(reportsManager.getExamsListPdf(), request); } - @GetMapping(value = "/reports/diseases-list", produces = MediaType.APPLICATION_JSON_VALUE) + @GetMapping("/reports/diseases-list") public ResponseEntity printDiseasesListPdf(HttpServletRequest request) throws OHServiceException, IOException { return getReport(reportsManager.getDiseasesListPdf(), request); } - private ResponseEntity getReport(JasperReportResultDto resultDto, HttpServletRequest request) throws OHServiceException, IOException { + private ResponseEntity getReport( + JasperReportResultDto resultDto, HttpServletRequest request + ) throws OHServiceException, IOException { Path report = Paths.get(resultDto.getFilename()).normalize(); Resource resource; try { @@ -90,9 +97,9 @@ private ResponseEntity getReport(JasperReportResultDto resultDto, HttpSe byte[] out = IOUtils.toByteArray(resource.getInputStream()); return ResponseEntity.ok() - .contentType(MediaType.parseMediaType(contentType)) - .header(HttpHeaders.CONTENT_DISPOSITION, - "attachment; filename=\"" + resource.getFilename() + '"') - .body(out); + .contentType(MediaType.parseMediaType(contentType)) + .header(HttpHeaders.CONTENT_DISPOSITION, + "attachment; filename=\"" + resource.getFilename() + '"') + .body(out); } } diff --git a/src/main/java/org/isf/supplier/rest/SupplierController.java b/src/main/java/org/isf/supplier/rest/SupplierController.java index 9de00c26f..a07eb80cc 100644 --- a/src/main/java/org/isf/supplier/rest/SupplierController.java +++ b/src/main/java/org/isf/supplier/rest/SupplierController.java @@ -34,10 +34,8 @@ import org.isf.utils.exception.model.OHExceptionMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @@ -52,18 +50,22 @@ import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/suppliers") +@RestController @Tag(name = "Suppliers") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class SupplierController { private static final Logger LOGGER = LoggerFactory.getLogger(SupplierController.class); - @Autowired - private SupplierBrowserManager manager; + private final SupplierBrowserManager manager; - @Autowired - private SupplierMapper mapper; + private final SupplierMapper mapper; + + public SupplierController(SupplierBrowserManager manager, SupplierMapper mapper) { + this.manager = manager; + this.mapper = mapper; + } /** * Saves the specified {@link SupplierDTO}. @@ -71,7 +73,7 @@ public class SupplierController { * @return {@code true} if the supplier was saved * @throws OHServiceException When failed to save the supplier */ - @PostMapping(value = "/suppliers", produces = MediaType.APPLICATION_JSON_VALUE) + @PostMapping("/suppliers") @ResponseStatus(HttpStatus.CREATED) public SupplierDTO saveSupplier(@RequestBody @Valid SupplierDTO supplierDTO) throws OHServiceException { LOGGER.info("Saving a new supplier..."); @@ -91,7 +93,7 @@ public SupplierDTO saveSupplier(@RequestBody @Valid SupplierDTO supplierDTO) thr * @return {@code true} if the supplier was updated * @throws OHServiceException When failed to update the supplier */ - @PutMapping(value = "/suppliers", produces = MediaType.APPLICATION_JSON_VALUE) + @PutMapping("/suppliers") public SupplierDTO updateSupplier(@RequestBody @Valid SupplierDTO supplierDTO) throws OHServiceException { if (supplierDTO.getSupId() == null || manager.getByID(supplierDTO.getSupId()) == null) { throw new OHAPIException(new OHExceptionMessage("Supplier not found."), HttpStatus.NOT_FOUND); @@ -113,21 +115,15 @@ public SupplierDTO updateSupplier(@RequestBody @Valid SupplierDTO supplierDTO) t * @return the list of suppliers found * @throws OHServiceException When failed to retrieve suppliers */ - @GetMapping(value = "/suppliers", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getSuppliers( - @RequestParam(name="exclude_deleted", defaultValue="true") boolean excludeDeleted + @GetMapping("/suppliers") + public List getSuppliers( + @RequestParam(name="exclude_deleted", defaultValue="true") boolean excludeDeleted ) throws OHServiceException { LOGGER.info("Loading suppliers..."); List suppliers = excludeDeleted? manager.getList() : manager.getAll(); - List mappedSuppliers = mapper.map2DTOList(suppliers); - - if (mappedSuppliers.isEmpty()) { - LOGGER.info("No supplier found."); - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(mappedSuppliers); - } + LOGGER.info("Found {} suppliers.", suppliers.size()); - LOGGER.info("Found {} suppliers.", mappedSuppliers.size()); - return ResponseEntity.ok(mappedSuppliers); + return mapper.map2DTOList(suppliers); } /** @@ -136,7 +132,7 @@ public ResponseEntity> getSuppliers( * @return the found supplier * @throws OHServiceException When failed to retrieve the supplier */ - @GetMapping(value = "/suppliers/{id}", produces = MediaType.APPLICATION_JSON_VALUE) + @GetMapping("/suppliers/{id}") public SupplierDTO getSuppliers(@PathVariable Integer id) throws OHServiceException { LOGGER.info("Loading supplier with ID {}", id); Supplier supplier = manager.getByID(id); @@ -155,7 +151,7 @@ public SupplierDTO getSuppliers(@PathVariable Integer id) throws OHServiceExcept * @param id Supplier ID * @throws OHServiceException When failed to delete the supplier */ - @DeleteMapping(value = "/suppliers/{id}", produces = MediaType.APPLICATION_JSON_VALUE) + @DeleteMapping("/suppliers/{id}") @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteSupplier(@PathVariable Integer id) throws OHServiceException { LOGGER.info("Loading supplier with ID {}", id); diff --git a/src/main/java/org/isf/therapy/rest/TherapyController.java b/src/main/java/org/isf/therapy/rest/TherapyController.java index 09ad134f5..1ce0f66c6 100644 --- a/src/main/java/org/isf/therapy/rest/TherapyController.java +++ b/src/main/java/org/isf/therapy/rest/TherapyController.java @@ -28,168 +28,152 @@ import org.isf.medical.dto.MedicalDTO; import org.isf.medical.mapper.MedicalMapper; -import org.isf.medicals.model.Medical; import org.isf.shared.exceptions.OHAPIException; import org.isf.therapy.dto.TherapyDTO; import org.isf.therapy.dto.TherapyRowDTO; import org.isf.therapy.manager.TherapyManager; import org.isf.therapy.mapper.TherapyMapper; import org.isf.therapy.mapper.TherapyRowMapper; -import org.isf.therapy.model.Therapy; import org.isf.therapy.model.TherapyRow; import org.isf.utils.exception.OHServiceException; import org.isf.utils.exception.model.OHExceptionMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/therapies") +@RestController @Tag(name = "Therapies") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class TherapyController { - private static final Logger LOGGER = LoggerFactory.getLogger(TherapyController.class); + private final TherapyManager manager; - @Autowired - private TherapyManager manager; + private final TherapyMapper therapyMapper; - @Autowired - private TherapyMapper therapyMapper; + private final TherapyRowMapper therapyRowMapper; - @Autowired - private TherapyRowMapper therapyRowMapper; + private final MedicalMapper medicalMapper; + + public TherapyController( + TherapyManager manager, + TherapyMapper therapyMapper, + TherapyRowMapper therapyRowMapper, + MedicalMapper medicalMapper + ) { + this.manager = manager; + this.therapyMapper = therapyMapper; + this.therapyRowMapper = therapyRowMapper; + this.medicalMapper = medicalMapper; + } - @Autowired - private MedicalMapper medicalMapper; - - /** * Creates a new therapy for related Patient. * @param thRowDTO - the therapy * @return the created therapy - * @throws OHServiceException + * @throws OHServiceException When failed to create therapy */ - @PostMapping(value = "/therapies", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity newTherapy(@RequestBody TherapyRowDTO thRowDTO) throws OHServiceException { + @PostMapping("/therapies") + @ResponseStatus(HttpStatus.CREATED) + public TherapyRowDTO newTherapy(@RequestBody TherapyRowDTO thRowDTO) throws OHServiceException { if (thRowDTO.getPatID() == null) { - throw new OHAPIException(new OHExceptionMessage("Patient not found.")); + throw new OHAPIException(new OHExceptionMessage("Patient not found."), HttpStatus.NOT_FOUND); } - TherapyRow thRow = therapyRowMapper.map2Model(thRowDTO); - thRow = manager.newTherapy(thRow); - return ResponseEntity.status(HttpStatus.CREATED).body(therapyRowMapper.map2DTO(thRow)); + + return therapyRowMapper.map2DTO(manager.newTherapy(therapyRowMapper.map2Model(thRowDTO))); } - + /** * Replaces all therapies for related Patient. * @param thRowDTOs - the list of therapies * @return {@code true} if the rows has been inserted, {@code false} otherwise - * @throws OHServiceException + * @throws OHServiceException When failed to replace patient therapies */ - @PostMapping(value = "/therapies/replace", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity replaceTherapies(@RequestBody @Valid List thRowDTOs) throws OHServiceException { + @PostMapping("/therapies/replace") + @ResponseStatus(HttpStatus.CREATED) + public TherapyRowDTO replaceTherapies( + @RequestBody @Valid List thRowDTOs + ) throws OHServiceException { ArrayList therapies = (ArrayList)therapyRowMapper.map2ModelList(thRowDTOs); - TherapyRow done = manager.newTherapy(therapies.get(0)); - if (done != null) { - return ResponseEntity.status(HttpStatus.CREATED).body(done); - } else { - throw new OHAPIException(new OHExceptionMessage("Therapies not replaced.")); - } + + return therapyRowMapper.map2DTO(manager.newTherapy(therapies.get(0))); } - + /** * Deletes all therapies for specified Patient Code. * @param code - the Patient Code * @return {@code true} if the therapies have been deleted, throws an exception otherwise - * @throws OHServiceException + * @throws OHServiceException When failed to delete patient therapies */ - @DeleteMapping(value = "/therapies/{code_patient}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity deleteAllTherapies(@PathVariable("code_patient") Integer code) throws OHServiceException { + @DeleteMapping("/therapies/{code_patient}") + public boolean deleteAllTherapies(@PathVariable("code_patient") Integer code) throws OHServiceException { try { manager.deleteAllTherapies(code); + return true; } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Therapies not deleted.")); } - return ResponseEntity.ok(true); } - + /** * Gets the medicals that are not available for the specified list of therapies. * @param therapyDTOs - the list of therapies * @return the list of medicals out of stock - * @throws OHServiceException + * @throws OHServiceException When failed to get not available medicals */ - @PostMapping(value = "/therapies/meds-out-of-stock", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getMedicalsOutOfStock(@RequestBody List therapyDTOs) throws OHServiceException { - List therapyRows = therapyMapper.map2ModelList(therapyDTOs); - List meds = manager.getMedicalsOutOfStock(therapyRows); - List mappedMeds = medicalMapper.map2DTOList(meds); - if (mappedMeds.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(mappedMeds); - } else { - LOGGER.info("Found {} medicals", mappedMeds.size()); - return ResponseEntity.ok(mappedMeds); - } + @PostMapping("/therapies/meds-out-of-stock") + public List getMedicalsOutOfStock( + @RequestBody List therapyDTOs + ) throws OHServiceException { + return medicalMapper.map2DTOList(manager.getMedicalsOutOfStock(therapyMapper.map2ModelList(therapyDTOs))); } - + /** * Gets the list of therapies for specified Patient ID. * @param patientID - the Patient ID * @return the list of therapies of the patient or all the therapies if {@code 0} is passed - * @throws OHServiceException + * @throws OHServiceException When failed to get patient therapies */ - @GetMapping(value = "/therapies/{code_patient}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getTherapyRows(@PathVariable("code_patient") Integer patientID) throws OHServiceException { - List thRows = manager.getTherapyRows(patientID); - List mappedThRows = therapyRowMapper.map2DTOList(thRows); - if (mappedThRows.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(mappedThRows); - } else { - LOGGER.info("Found {} therapies", mappedThRows.size()); - return ResponseEntity.ok(mappedThRows); - } + @GetMapping("/therapies/{code_patient}") + public List getTherapyRows + (@PathVariable("code_patient") Integer patientID + ) throws OHServiceException { + return therapyRowMapper.map2DTOList(manager.getTherapyRows(patientID)); } - + /** * Gets a list of therapies from a list of therapyRows (DB records). * @param thRowDTOs - the list of therapyRows * @return the list of therapies - * @throws OHServiceException + * @throws OHServiceException When failed to get therapies */ - @PostMapping(value = "/therapies/from-rows", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getTherapies(@RequestBody @Valid List thRowDTOs) throws OHServiceException { - List thRows = therapyRowMapper.map2ModelList(thRowDTOs); - List therapies = manager.getTherapies(thRows); - List mappedTherapies = therapies != null? therapyMapper.map2DTOList(therapies) : null; - if (mappedTherapies == null || mappedTherapies.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(mappedTherapies); - } else { - LOGGER.info("Found {} therapies", mappedTherapies.size()); - return ResponseEntity.ok(mappedTherapies); - } + @PostMapping("/therapies/from-rows") + public List getTherapies( + @RequestBody @Valid List thRowDTOs + ) throws OHServiceException { + return therapyMapper.map2DTOList(manager.getTherapies(therapyRowMapper.map2ModelList(thRowDTOs))); } - + /** * Gets therapy from a therapyRow (DB record). * @param thRowDTO - the therapyRow * @return the therapy - * @throws OHServiceException + * @throws OHServiceException When failed to get therapy */ - @PostMapping(value = "/therapies/from-row", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getTherapy(@RequestBody @Valid TherapyRowDTO thRowDTO) throws OHServiceException { - TherapyRow thRow = therapyRowMapper.map2Model(thRowDTO); - TherapyDTO mappedTherapy = therapyMapper.map2DTO(manager.createTherapy(thRow)); - return ResponseEntity.ok(mappedTherapy); + @PostMapping("/therapies/from-row") + public TherapyDTO getTherapy(@RequestBody @Valid TherapyRowDTO thRowDTO) throws OHServiceException { + return therapyMapper.map2DTO(manager.createTherapy(therapyRowMapper.map2Model(thRowDTO))); } } diff --git a/src/main/java/org/isf/usergroups/rest/UserGroupController.java b/src/main/java/org/isf/usergroups/rest/UserGroupController.java index f318ea57d..4683dcc31 100644 --- a/src/main/java/org/isf/usergroups/rest/UserGroupController.java +++ b/src/main/java/org/isf/usergroups/rest/UserGroupController.java @@ -24,7 +24,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Objects; -import java.util.stream.Collectors; import jakarta.validation.Valid; @@ -45,7 +44,6 @@ import org.isf.utils.exception.model.OHExceptionMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.DeleteMapping; @@ -55,34 +53,50 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/usergroups") +@RestController @Tag(name = "User Groups") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class UserGroupController { private static final Logger LOGGER = LoggerFactory.getLogger(UserGroupController.class); - @Autowired - protected PermissionManager permissionManager; - @Autowired - protected GroupPermissionManager groupPermissionManager; - @Autowired - private UserGroupMapper userGroupMapper; - @Autowired - private PermissionMapper permissionMapper; - @Autowired - private UserBrowsingManager userManager; + + private final PermissionManager permissionManager; + + private final GroupPermissionManager groupPermissionManager; + + private final UserGroupMapper userGroupMapper; + + private final PermissionMapper permissionMapper; + + private final UserBrowsingManager userManager; + + public UserGroupController( + PermissionManager permissionManager, + GroupPermissionManager groupPermissionManager, + UserGroupMapper userGroupMapper, + PermissionMapper permissionMapper, + UserBrowsingManager userManager + ) { + this.permissionManager = permissionManager; + this.groupPermissionManager = groupPermissionManager; + this.userGroupMapper = userGroupMapper; + this.permissionMapper = permissionMapper; + this.userManager = userManager; + } /** * Returns the list of {@link UserGroup}s. * @return the list of {@link UserGroup}s */ - @GetMapping(value = "/usergroups", produces = MediaType.APPLICATION_JSON_VALUE) + @GetMapping(value = "/usergroups") public List getUserGroups() throws OHServiceException { LOGGER.info("Attempting to fetch the list of user groups."); List groups = userManager.getUserGroup(); @@ -96,7 +110,7 @@ public List getUserGroups() throws OHServiceException { * @param code - the code of the {@link UserGroup} to delete */ @ResponseStatus(HttpStatus.NO_CONTENT) - @DeleteMapping(value = "/usergroups/{group_code}", produces = MediaType.APPLICATION_JSON_VALUE) + @DeleteMapping(value = "/usergroups/{group_code}") public void deleteGroup(@PathVariable("group_code") String code) throws OHServiceException { try { UserGroup group = loadUserGroup(code); @@ -113,14 +127,14 @@ public void deleteGroup(@PathVariable("group_code") String code) throws OHServic * @throws OHServiceException When failed to create the user group */ @ResponseStatus(HttpStatus.CREATED) - @PostMapping(value = "/usergroups", produces = MediaType.APPLICATION_JSON_VALUE) + @PostMapping(value = "/usergroups") public UserGroupDTO newUserGroup(@Valid @RequestBody UserGroupDTO userGroupDTO) throws OHServiceException { UserGroup userGroup = userGroupMapper.map2Model(userGroupDTO); List permissions = new ArrayList<>(); if (userGroupDTO.getPermissions() != null && !userGroupDTO.getPermissions().isEmpty()) { permissions = userGroupDTO.getPermissions() - .stream().map(permissionDTO -> permissionMapper.map2Model(permissionDTO)) + .stream().map(permissionMapper::map2Model) .toList(); } @@ -138,8 +152,10 @@ public UserGroupDTO newUserGroup(@Valid @RequestBody UserGroupDTO userGroupDTO) * @return {@link UserGroupDTO} for the updated group. * @throws OHServiceException When failed to update the user group */ - @PutMapping(value = "/usergroups/{group_code}", produces = MediaType.APPLICATION_JSON_VALUE) - public UserGroupDTO updateUserGroup(@PathVariable("group_code") String code, @Valid @RequestBody UserGroupDTO userGroupDTO) throws OHServiceException { + @PutMapping(value = "/usergroups/{group_code}") + public UserGroupDTO updateUserGroup( + @PathVariable("group_code") String code, @Valid @RequestBody UserGroupDTO userGroupDTO + ) throws OHServiceException { if (!Objects.equals(userGroupDTO.getCode(), code)) { throw new OHAPIException(new OHExceptionMessage("Invalid request payload")); } @@ -152,7 +168,7 @@ public UserGroupDTO updateUserGroup(@PathVariable("group_code") String code, @Va List permissions = new ArrayList<>(); if (userGroupDTO.getPermissions() != null && !userGroupDTO.getPermissions().isEmpty()) { permissions = userGroupDTO.getPermissions() - .stream().map(permissionDTO -> permissionMapper.map2Model(permissionDTO)) + .stream().map(permissionMapper::map2Model) .toList(); } @@ -170,7 +186,7 @@ public UserGroupDTO updateUserGroup(@PathVariable("group_code") String code, @Va * @return Returns the {@link UserGroup} found using the given code * @throws OHServiceException When failed to retrieve the user group */ - @GetMapping(value = "/usergroups/{group_code}", produces = MediaType.APPLICATION_JSON_VALUE) + @GetMapping(value = "/usergroups/{group_code}") public UserGroupDTO getUserGroup(@PathVariable("group_code") String code) throws OHServiceException { UserGroup userGroup = userManager.findUserGroupByCode(code); if (userGroup == null) { @@ -196,7 +212,7 @@ public UserGroupDTO getUserGroup(@PathVariable("group_code") String code) throws * @throws OHServiceException When failed to assign the permission to the user group */ @ResponseStatus(HttpStatus.CREATED) - @PostMapping(value = "/usergroups/{group_code}/permissions/{id}", produces = MediaType.APPLICATION_JSON_VALUE) + @PostMapping(value = "/usergroups/{group_code}/permissions/{id}") public int assignPermission( @PathVariable("group_code") String userGroupCode, @PathVariable("id") int permissionId @@ -226,7 +242,7 @@ public int assignPermission( * @return List of {@link PermissionDTO} corresponding to the list of permissions assigned to the group * @throws OHServiceException If the update operation fails */ - @PutMapping(value = "/usergroups/{group_code}/permissions", produces = MediaType.APPLICATION_JSON_VALUE) + @PutMapping(value = "/usergroups/{group_code}/permissions") public List updateGroupPermissions( @PathVariable("group_code") String userGroupCode, @RequestBody GroupPermissionsDTO payload @@ -239,7 +255,9 @@ public List updateGroupPermissions( } try { - return permissionMapper.map2DTOList(groupPermissionManager.update(userGroup, payload.permissionIds(), false)); + return permissionMapper.map2DTOList( + groupPermissionManager.update(userGroup, payload.permissionIds(), false) + ); } catch (OHDataValidationException e) { LOGGER.info("Fail to update user groups permissions, reason: {}", e.getMessage()); throw new OHAPIException(new OHExceptionMessage("Failed to update permissions")); @@ -259,12 +277,16 @@ public List updateGroupPermissions( * @return List of {@link PermissionDTO} corresponding to the list of permissions assigned to the group * @throws OHServiceException If the update operation fails */ - @PatchMapping(value = "/usergroups/{group_code}/permissions", produces = MediaType.APPLICATION_JSON_VALUE) + @PatchMapping(value = "/usergroups/{group_code}/permissions") public List replaceGroupPermissions( @PathVariable("group_code") String userGroupCode, @RequestBody GroupPermissionsDTO payload ) throws OHServiceException { - LOGGER.info("Attempting to replace user group({}) permissions, with permissions ids, {}", userGroupCode, payload.permissionIds()); + LOGGER.info( + "Attempting to replace user group({}) permissions, with permissions ids, {}", + userGroupCode, payload.permissionIds() + ); + UserGroup userGroup = userManager.findUserGroupByCode(userGroupCode); if (userGroup == null) { LOGGER.info("Could not find user group corresponding to the group code {}", userGroupCode); @@ -272,7 +294,9 @@ public List replaceGroupPermissions( } try { - return permissionMapper.map2DTOList(groupPermissionManager.update(userGroup, payload.permissionIds(), true)); + return permissionMapper.map2DTOList( + groupPermissionManager.update(userGroup, payload.permissionIds(), true) + ); } catch (OHDataValidationException e) { LOGGER.info("Fail to replace user groups permissions, reason: {}", e.getMessage()); throw new OHAPIException(new OHExceptionMessage("Failed to update permissions")); @@ -286,7 +310,7 @@ public List replaceGroupPermissions( * @throws OHServiceException When failed to revoke the permission to the user group */ @ResponseStatus(HttpStatus.NO_CONTENT) - @DeleteMapping(value = "/usergroups/{group_code}/permissions/{id}", produces = MediaType.APPLICATION_JSON_VALUE) + @DeleteMapping(value = "/usergroups/{group_code}/permissions/{id}") public void revokePermission( @PathVariable("group_code") String userGroupCode, @PathVariable("id") int permissionId @@ -310,9 +334,9 @@ public void revokePermission( } private UserGroup loadUserGroup(String code) throws OHServiceException { - List group = userManager.getUserGroup().stream().filter(g -> g.getCode().equals(code)).collect(Collectors.toList()); + List group = userManager.getUserGroup().stream().filter(g -> g.getCode().equals(code)).toList(); if (group.isEmpty()) { - throw new OHAPIException(new OHExceptionMessage("User group not found.")); + throw new OHAPIException(new OHExceptionMessage("User group not found."), HttpStatus.NOT_FOUND); } return group.get(0); } diff --git a/src/main/java/org/isf/users/rest/UserController.java b/src/main/java/org/isf/users/rest/UserController.java index 8d781b6ec..fccaf6b88 100644 --- a/src/main/java/org/isf/users/rest/UserController.java +++ b/src/main/java/org/isf/users/rest/UserController.java @@ -21,9 +21,11 @@ */ package org.isf.users.rest; -import io.swagger.v3.oas.annotations.security.SecurityRequirement; -import io.swagger.v3.oas.annotations.tags.Tag; +import java.util.List; +import java.util.stream.Collectors; + import jakarta.validation.Valid; + import org.isf.menu.manager.UserBrowsingManager; import org.isf.menu.model.User; import org.isf.permissions.dto.PermissionDTO; @@ -39,39 +41,64 @@ import org.isf.utils.exception.model.OHExceptionMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; -import java.util.List; -import java.util.stream.Collectors; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/users") +@RestController @Tag(name = "Users") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class UserController { private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class); - @Autowired - protected PermissionManager permissionManager; - @Autowired - protected PermissionMapper permissionMapper; - @Autowired - private UserMapper userMapper; - @Autowired - private UserGroupMapper userGroupMapper; - @Autowired - private UserBrowsingManager userManager; + + private final PermissionManager permissionManager; + + private final PermissionMapper permissionMapper; + + private final UserMapper userMapper; + + private final UserGroupMapper userGroupMapper; + + private final UserBrowsingManager userManager; + + public UserController( + PermissionManager permissionManager, + PermissionMapper permissionMapper, + UserMapper userMapper, + UserGroupMapper userGroupMapper, + UserBrowsingManager userManager + ) { + this.permissionManager = permissionManager; + this.permissionMapper = permissionMapper; + this.userMapper = userMapper; + this.userGroupMapper = userGroupMapper; + this.userManager = userManager; + } /** * Returns the list of {@link User}s. * * @return the list of {@link User}s. */ - @GetMapping(value = "/users", produces = MediaType.APPLICATION_JSON_VALUE) - public List getUser(@RequestParam(name = "group_id", required = false) String groupID) throws OHServiceException { + @GetMapping("/users") + public List getUser( + @RequestParam(name = "group_id", required = false) String groupID + ) throws OHServiceException { LOGGER.info("Fetching the list of users."); List users; if (groupID != null) { @@ -80,7 +107,7 @@ public List getUser(@RequestParam(name = "group_id", required = false) users = userManager.getUser(); } List mappedUsers = userMapper.map2DTOList( - users.stream().peek(user -> user.setPasswd(null)).toList() + users.stream().peek(user -> user.setPasswd(null)).toList() ); LOGGER.info("Found {} user(s).", mappedUsers.size()); return mappedUsers; @@ -89,10 +116,10 @@ public List getUser(@RequestParam(name = "group_id", required = false) /** * Returns a {@link User}. * - * @param userName - user name + * @param userName - username * @return {@link User} */ - @GetMapping(value = "/users/{username}", produces = MediaType.APPLICATION_JSON_VALUE) + @GetMapping("/users/{username}") public UserDTO getUserByName(@PathVariable("username") String userName) throws OHServiceException { User user = userManager.getUserByName(userName); if (user == null) { @@ -103,17 +130,18 @@ public UserDTO getUserByName(@PathVariable("username") String userName) throws O } /** - * Updates an existing {@link User}. When the password in the payload is not empty, other fields are ignored and only the password is updated, otherwise + * Updates an existing {@link User}. When the password in the payload is not empty, + * other fields are ignored and only the password is updated, otherwise * other fields are updated except the password(whether empty or not). * * @param userDTO - the {@link User} to update * @return the updated {@link UserDTO} if the user has been updated. * @throws OHServiceException throws if the update fails */ - @PutMapping(value = "/users/{username}", produces = MediaType.APPLICATION_JSON_VALUE) + @PutMapping("/users/{username}") public UserDTO updateUser( - @PathVariable("username") String userName, - @Valid @RequestBody UserDTO userDTO) throws OHServiceException { + @PathVariable("username") String userName, + @Valid @RequestBody UserDTO userDTO) throws OHServiceException { LOGGER.info("Updating the user {}.", userName); String requestUserName = userDTO.getUserName(); if (requestUserName != null && !userName.equals(requestUserName)) { @@ -148,7 +176,7 @@ public UserDTO updateUser( * @throws OHServiceException When failed to create user */ @ResponseStatus(HttpStatus.CREATED) - @PostMapping(value = "/users", produces = MediaType.APPLICATION_JSON_VALUE) + @PostMapping("/users") public UserDTO newUser(@Valid @RequestBody UserDTO userDTO) throws OHServiceException { LOGGER.info("Attempting to create user {}.", userDTO.getUserName()); User user = userMapper.map2Model(userDTO); @@ -167,7 +195,7 @@ public UserDTO newUser(@Valid @RequestBody UserDTO userDTO) throws OHServiceExce * @param username - the name of the {@link User} to delete */ @ResponseStatus(HttpStatus.NO_CONTENT) - @DeleteMapping(value = "/users/{username}", produces = MediaType.APPLICATION_JSON_VALUE) + @DeleteMapping("/users/{username}") public void deleteUser(@PathVariable String username) throws OHServiceException { User foundUser = userManager.getUserByName(username); if (foundUser == null) { @@ -181,12 +209,13 @@ public void deleteUser(@PathVariable String username) throws OHServiceException } /** - * Retrieves profile of the current logged in user. If user not found, an empty list of permissions is returned + * Retrieves profile of the current logged in user. + * If user not found, an empty list of permissions is returned * * @return list of permissions {@link Permission} - * @throws OHServiceException + * @throws OHServiceException When failed to get logged in user */ - @GetMapping(value = "/users/me", produces = MediaType.APPLICATION_JSON_VALUE) + @GetMapping("/users/me") public UserProfileDTO retrieveProfileByCurrentLoggedInUser() throws OHServiceException { String currentUser = SecurityContextHolder.getContext().getAuthentication().getName(); LOGGER.info("Retrieving profile: retrieveProfileByCurrentLoggedInUser({}).", currentUser); @@ -194,23 +223,24 @@ public UserProfileDTO retrieveProfileByCurrentLoggedInUser() throws OHServiceExc } /** - * Updates the current {@link User} profile. When the password in the payload is not empty, other fields are ignored and only the password is updated, + * Updates the current {@link User} profile. When the password + * in the payload is not empty, other fields are ignored and only the password is updated, * otherwise other fields are updated except the password(whether empty or not). * * @param userDTO - the {@link User} to update * @return the current {@link UserProfileDTO} if the user has been updated. * @throws OHServiceException throws if the update fails */ - @PutMapping(value = "/users/me", produces = MediaType.APPLICATION_JSON_VALUE) - public UserProfileDTO updateProfile( - @RequestBody UserDTO userDTO) throws OHServiceException { + @PutMapping("/users/me") + public UserProfileDTO updateProfile(@RequestBody UserDTO userDTO) throws OHServiceException { String requestUserName = userDTO.getUserName(); String currentUser = SecurityContextHolder.getContext().getAuthentication().getName(); User entity = userManager.getUserByName(requestUserName); LOGGER.info("Updating the user {}.", currentUser); if (!requestUserName.equals(currentUser)) { - throw new OHAPIException(new OHExceptionMessage(String.format("You're not allowed to update %s's profile.", requestUserName)), - HttpStatus.FORBIDDEN); + throw new OHAPIException(new OHExceptionMessage(String.format("" + + "You're not allowed to update %s's profile.", requestUserName) + ),HttpStatus.FORBIDDEN); } if (entity == null) { throw new OHAPIException(new OHExceptionMessage("The specified user does not exist.")); @@ -232,13 +262,16 @@ public UserProfileDTO updateProfile( } /** - * Retrieves all permissions of the username passed as path variable. If user not found, an empty list of permissions is returned. + * Retrieves all permissions of the username passed as path variable. + * If user not found, an empty list of permissions is returned. * * @return list of permissions {@link Permission} * @throws OHServiceException When failed to load user's permissions */ - @GetMapping(value = "/users/{username}/permissions", produces = MediaType.APPLICATION_JSON_VALUE) - public List retrievePermissionsByUsername(@PathVariable("username") String username) throws OHServiceException { + @GetMapping("/users/{username}/permissions") + public List retrievePermissionsByUsername( + @PathVariable("username") String username + ) throws OHServiceException { LOGGER.info("Retrieving permissions: retrievePermissionsByUsername({}).", username); List domains = this.permissionManager.retrievePermissionsByUsername(username); return this.permissionMapper.map2DTOList(domains); diff --git a/src/main/java/org/isf/usersettings/rest/UserSettingController.java b/src/main/java/org/isf/usersettings/rest/UserSettingController.java index 5bc8a3dd3..652a5d714 100644 --- a/src/main/java/org/isf/usersettings/rest/UserSettingController.java +++ b/src/main/java/org/isf/usersettings/rest/UserSettingController.java @@ -37,7 +37,6 @@ import org.isf.utils.exception.model.OHExceptionMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.security.core.context.SecurityContextHolder; @@ -47,33 +46,43 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/usersettings") +@RestController @Tag(name = "User Settings") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class UserSettingController { private static final Logger LOGGER = LoggerFactory.getLogger(UserSettingController.class); - @Autowired - private UserBrowsingManager userManager; - @Autowired - private UserSettingManager userSettingManager; + private final UserBrowsingManager userManager; - @Autowired - private UserSettingMapper userSettingMapper; + private final UserSettingManager userSettingManager; + + private final UserSettingMapper userSettingMapper; + + public UserSettingController( + UserBrowsingManager userManager, + UserSettingManager userSettingManager, + UserSettingMapper userSettingMapper + ) { + this.userManager = userManager; + this.userSettingManager = userSettingManager; + this.userSettingMapper = userSettingMapper; + } /** * Retrieves all userSettings of the current user. * @return list of userSetting {@link UserSettingDTO}. * @throws OHServiceException When fail to retrieve userSettings */ - @GetMapping(value = "/usersettings", produces = MediaType.APPLICATION_JSON_VALUE) + @GetMapping(value = "/usersettings") public List getUserSettings() throws OHServiceException { LOGGER.info("Retrieve all userSettings of the current user."); String currentUser = SecurityContextHolder.getContext().getAuthentication().getName(); @@ -91,10 +100,10 @@ public List getUserSettings() throws OHServiceException { * Returns a {@link UserSettingDTO} of userSetting created. * @param userSettingDTO - the {@link UserSettingDTO} to insert. * @return {@link UserSettingDTO} if the userSetting has been created, null otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to create user setting */ @ResponseStatus(HttpStatus.CREATED) - @PostMapping(value = "/usersettings", produces = MediaType.APPLICATION_JSON_VALUE) + @PostMapping(value = "/usersettings") public UserSettingDTO newUserSettings(@Valid @RequestBody UserSettingDTO userSettingDTO) throws OHServiceException { LOGGER.info("Create a UserSetting."); String requestUserName = userSettingDTO.getUser(); @@ -126,9 +135,10 @@ public UserSettingDTO newUserSettings(@Valid @RequestBody UserSettingDTO userSet * @return {@link UserSettingDTO} if the UserSetting has been updated. * @throws OHServiceException If the update operation fails */ - @PutMapping(value = "/usersettings/{id}", produces = MediaType.APPLICATION_JSON_VALUE) - public UserSettingDTO updateUserSettings(@PathVariable(name = "id") int id, @Valid @RequestBody UserSettingDTO userSettingDTO) - throws OHServiceException { + @PutMapping(value = "/usersettings/{id}") + public UserSettingDTO updateUserSettings( + @PathVariable(name = "id") int id, @Valid @RequestBody UserSettingDTO userSettingDTO + ) throws OHServiceException { LOGGER.info("Update a UserSetting."); String requestUserName = userSettingDTO.getUser(); String currentUser = SecurityContextHolder.getContext().getAuthentication().getName(); @@ -161,10 +171,12 @@ public UserSettingDTO updateUserSettings(@PathVariable(name = "id") int id, @Val * Retrieves an existing {@link UserSettingDTO} by user. * @param configName - the name of the userSetting {@link UserSetting} . * @return {@link UserSettingDTO} if the UserSetting exists, null otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to get user setting */ - @GetMapping(value = "/usersettings/{configName}", produces = MediaType.APPLICATION_JSON_VALUE) - public UserSettingDTO getUserSettingByUser(@PathVariable(name = "configName") String configName) throws OHServiceException { + @GetMapping(value = "/usersettings/{configName}") + public UserSettingDTO getUserSettingByUser( + @PathVariable(name = "configName") String configName + ) throws OHServiceException { String currentUser = SecurityContextHolder.getContext().getAuthentication().getName(); LOGGER.info("Retrieve the userSetting By user {} and configName {}.", currentUser, configName); UserSetting userSetting = userSettingManager.getUserSettingByUserNameConfigName(currentUser, configName); @@ -181,7 +193,7 @@ public UserSettingDTO getUserSettingByUser(@PathVariable(name = "configName") St * @throws OHServiceException If the deletion fails */ @ResponseStatus(HttpStatus.NO_CONTENT) - @DeleteMapping(value = "/usersettings/{id}", produces = MediaType.APPLICATION_JSON_VALUE) + @DeleteMapping(value = "/usersettings/{id}") public void deleteUserSetting(@PathVariable(name = "id") int id) throws OHServiceException { Optional userSetting = userSettingManager.getUserSettingById(id); final String ADMIN = "admin"; diff --git a/src/main/java/org/isf/vaccine/rest/VaccineController.java b/src/main/java/org/isf/vaccine/rest/VaccineController.java index 35a35ae8c..cf5c279db 100644 --- a/src/main/java/org/isf/vaccine/rest/VaccineController.java +++ b/src/main/java/org/isf/vaccine/rest/VaccineController.java @@ -33,33 +33,32 @@ import org.isf.vaccine.model.Vaccine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/vaccines") +@RestController @Tag(name = "Vaccines") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class VaccineController { private static final Logger LOGGER = LoggerFactory.getLogger(VaccineController.class); - @Autowired - protected VaccineBrowserManager vaccineManager; - - @Autowired - protected VaccineMapper mapper; + private final VaccineBrowserManager vaccineManager; + + private final VaccineMapper mapper; public VaccineController(VaccineBrowserManager vaccineManager, VaccineMapper vaccineMapper) { this.vaccineManager = vaccineManager; @@ -69,78 +68,66 @@ public VaccineController(VaccineBrowserManager vaccineManager, VaccineMapper vac /** * Get all the vaccines. * - * @return NO_CONTENT if there aren't any vaccines, {@code List} otherwise. - * @throws OHServiceException + * @return List of vaccines. + * @throws OHServiceException When failed to get vaccine */ - @GetMapping(value = "/vaccines", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getVaccines() throws OHServiceException { + @GetMapping("/vaccines") + public List getVaccines() throws OHServiceException { LOGGER.info("Get vaccines"); - List vaccines = vaccineManager.getVaccine(); - List listVaccines = mapper.map2DTOList(vaccines); - if (listVaccines.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(listVaccines); - } else { - return ResponseEntity.ok(listVaccines); - } + + return mapper.map2DTOList(vaccineManager.getVaccine()); } /** * Get all the vaccines related to a vaccineType code. * * @param vaccineTypeCode of the vaccine - * @return NO_CONTENT if there aren't vaccines related to the code, {@code List} otherwise. - * @throws OHServiceException + * @return The list of vaccines related to the supplied vaccine type code + * @throws OHServiceException When failed to get vaccines */ - @GetMapping(value = "/vaccines/type-code/{vaccineTypeCode}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getVaccinesByVaccineTypeCode(@PathVariable String vaccineTypeCode) throws OHServiceException { + @GetMapping("/vaccines/type-code/{vaccineTypeCode}") + public List getVaccinesByVaccineTypeCode(@PathVariable String vaccineTypeCode) throws OHServiceException { LOGGER.info("Get vaccine by code: {}", vaccineTypeCode); - List vaccines = vaccineManager.getVaccine(vaccineTypeCode); - List listVaccines = mapper.map2DTOList(vaccines); - if (listVaccines.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(listVaccines); - } else { - return ResponseEntity.ok(listVaccines); - } + + return mapper.map2DTOList(vaccineManager.getVaccine(vaccineTypeCode)); } /** * Create a new vaccine. * - * @param newVaccine + * @param newVaccine Vaccine payload * @return an error message if there is a problem, ok otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to create the vaccine */ - @PostMapping(value = "/vaccines", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity newVaccine(@RequestBody VaccineDTO newVaccine) throws OHServiceException { + @PostMapping("/vaccines") + @ResponseStatus(HttpStatus.CREATED) + public VaccineDTO newVaccine(@RequestBody VaccineDTO newVaccine) throws OHServiceException { LOGGER.info("Create vaccine: {}", newVaccine); - Vaccine isCreatedVaccine; try { - isCreatedVaccine = vaccineManager.newVaccine(mapper.map2Model(newVaccine)); + return mapper.map2DTO(vaccineManager.newVaccine(mapper.map2Model(newVaccine))); } catch (OHDataIntegrityViolationException e) { throw new OHAPIException(new OHExceptionMessage("Vaccine type already present.")); } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Vaccine not created.")); } - return ResponseEntity.status(HttpStatus.CREATED).body(mapper.map2DTO(isCreatedVaccine)); } /** * Update a vaccine. * - * @param updateVaccine + * @param updateVaccine Vaccine payload * @return an error message if there are some problems, ok otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to update vaccine */ - @PutMapping(value = "/vaccines", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity updateVaccine(@RequestBody VaccineDTO updateVaccine) throws OHServiceException { + @PutMapping("/vaccines") + public VaccineDTO updateVaccine(@RequestBody VaccineDTO updateVaccine) throws OHServiceException { LOGGER.info("Update vaccine: {}", updateVaccine); - Vaccine updatedVaccine; + try { - updatedVaccine = vaccineManager.updateVaccine(mapper.map2Model(updateVaccine)); + return mapper.map2DTO(vaccineManager.updateVaccine(mapper.map2Model(updateVaccine))); } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Vaccine not updated.")); } - return ResponseEntity.ok(mapper.map2DTO(updatedVaccine)); } /** @@ -148,34 +135,35 @@ public ResponseEntity updateVaccine(@RequestBody VaccineDTO updateVa * * @param code of the vaccine to delete * @return an error message if there are some problems, ok otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to delete vaccine */ - @DeleteMapping(value = "/vaccines/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity deleteVaccine(@PathVariable("code") String code) throws OHServiceException { + @DeleteMapping("/vaccines/{code}") + public boolean deleteVaccine(@PathVariable("code") String code) throws OHServiceException { LOGGER.info("Delete vaccine code: {}", code); Vaccine vaccine = vaccineManager.findVaccine(code); - if (vaccine != null) { - try { - vaccineManager.deleteVaccine(vaccine); - } catch (OHServiceException serviceException) { - throw new OHAPIException(new OHExceptionMessage("Vaccine not deleted.")); - } - return ResponseEntity.ok(true); + if (vaccine == null) { + throw new OHAPIException(new OHExceptionMessage("Vaccine not found."), HttpStatus.NOT_FOUND); + } + + try { + vaccineManager.deleteVaccine(vaccine); + return true; + } catch (OHServiceException serviceException) { + throw new OHAPIException(new OHExceptionMessage("Vaccine not deleted.")); } - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); } - + /** * Check if the code is already used by other vaccine. * - * @param code + * @param code Vaccine code * @return {@code true} if it is already used, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to check vaccine code */ - @GetMapping(value = "/vaccines/check/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity checkVaccineCode(@PathVariable String code) throws OHServiceException { - LOGGER.info("Check vaccine code: {}", code); - boolean check = vaccineManager.isCodePresent(code); - return ResponseEntity.ok(check); + @GetMapping("/vaccines/check/{code}") + public boolean checkVaccineCode(@PathVariable String code) throws OHServiceException { + LOGGER.info("Check vaccine code: {}", code); + + return vaccineManager.isCodePresent(code); } } diff --git a/src/main/java/org/isf/vactype/rest/VaccineTypeController.java b/src/main/java/org/isf/vactype/rest/VaccineTypeController.java index eb41edb58..1523e20ed 100644 --- a/src/main/java/org/isf/vactype/rest/VaccineTypeController.java +++ b/src/main/java/org/isf/vactype/rest/VaccineTypeController.java @@ -33,35 +33,37 @@ import org.isf.vactype.model.VaccineType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/vaccinetypes") +@RestController @Tag(name = "Vaccine Type") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class VaccineTypeController { private static final Logger LOGGER = LoggerFactory.getLogger(VaccineTypeController.class); - @Autowired - protected VaccineTypeBrowserManager vaccineTypeManager; + private final VaccineTypeBrowserManager vaccineTypeManager; - @Autowired - protected VaccineTypeMapper mapper; + private final VaccineTypeMapper mapper; - public VaccineTypeController(VaccineTypeBrowserManager vaccineTypeManager, VaccineTypeMapper vaccineTypeMapper) { + public VaccineTypeController( + VaccineTypeBrowserManager vaccineTypeManager, + VaccineTypeMapper vaccineTypeMapper + ) { this.vaccineTypeManager = vaccineTypeManager; this.mapper = vaccineTypeMapper; } @@ -69,61 +71,51 @@ public VaccineTypeController(VaccineTypeBrowserManager vaccineTypeManager, Vacci /** * Get all the vaccine types. * - * @return - * @throws OHServiceException + * @return The list of vaccine types + * @throws OHServiceException When failed to get vaccine types */ - @GetMapping(value = "/vaccinetypes", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getVaccineType() throws OHServiceException { + @GetMapping("/vaccinetypes") + public List getVaccineType() throws OHServiceException { LOGGER.info("Get vaccine types."); - List vaccinesTypes = vaccineTypeManager.getVaccineType(); - List listVaccines = mapper.map2DTOList(vaccinesTypes); - if (listVaccines.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(listVaccines); - } else { - return ResponseEntity.ok(listVaccines); - } + return mapper.map2DTOList(vaccineTypeManager.getVaccineType()); } /** * Create a new vaccine type. * - * @param newVaccineType + * @param newVaccineType VaccineType payload * @return an error message if there are some problem, ok otherwise - * @throws OHServiceException + * @throws OHServiceException When failed to create vaccine type */ - @PostMapping(value = "/vaccinetypes", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity newVaccineType(@RequestBody VaccineTypeDTO newVaccineType) throws OHServiceException { + @PostMapping("/vaccinetypes") + @ResponseStatus(HttpStatus.CREATED) + public VaccineTypeDTO newVaccineType(@RequestBody VaccineTypeDTO newVaccineType) throws OHServiceException { LOGGER.info("Create vaccine type: {}", newVaccineType); - VaccineType newVaccineTYpe; try { - newVaccineTYpe = vaccineTypeManager.newVaccineType(mapper.map2Model(newVaccineType)); + return mapper.map2DTO(vaccineTypeManager.newVaccineType(mapper.map2Model(newVaccineType))); } catch (OHDataIntegrityViolationException e) { throw new OHAPIException(new OHExceptionMessage("Vaccine Type already present.")); - } - if (newVaccineTYpe == null) { + } catch (OHServiceException e) { throw new OHAPIException(new OHExceptionMessage("Vaccine Type not created.")); } - return ResponseEntity.status(HttpStatus.CREATED).body(mapper.map2DTO(newVaccineTYpe)); } /** * Update a vaccine type. * - * @param updateVaccineType + * @param updateVaccineType VaccineType payload * @return an error message if there are some problem, ok otherwise - * @throws OHServiceException + * @throws OHServiceException When failed to update vaccine type */ - @PutMapping(value = "/vaccinetypes", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity updateVaccineType(@RequestBody VaccineTypeDTO updateVaccineType) throws OHServiceException { + @PutMapping("/vaccinetypes") + public VaccineTypeDTO updateVaccineType(@RequestBody VaccineTypeDTO updateVaccineType) throws OHServiceException { LOGGER.info("Update vaccine type: {}", updateVaccineType); - VaccineType updatedVaccineType; + try { - updatedVaccineType = vaccineTypeManager.updateVaccineType(mapper.map2Model(updateVaccineType)); + return mapper.map2DTO(vaccineTypeManager.updateVaccineType(mapper.map2Model(updateVaccineType))); } catch (OHServiceException serviceException) { throw new OHAPIException(new OHExceptionMessage("Vaccine Type not updated.")); } - return ResponseEntity.ok(mapper.map2DTO(updatedVaccineType)); - } /** @@ -131,34 +123,34 @@ public ResponseEntity updateVaccineType(@RequestBody VaccineType * * @param code the vaccineType to delete * @return an error message if there are some problem, ok otherwise - * @throws OHServiceException + * @throws OHServiceException When failed to delete vaccine type */ - @DeleteMapping(value = "/vaccinetypes/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity deleteVaccineType(@PathVariable String code) throws OHServiceException { + @DeleteMapping("/vaccinetypes/{code}") + public boolean deleteVaccineType(@PathVariable String code) throws OHServiceException { LOGGER.info("Delete vaccine type code: {}", code); + VaccineType vaccineType = vaccineTypeManager.findVaccineType(code); - if (vaccineType != null) { - try { - vaccineTypeManager.deleteVaccineType(vaccineType); - } catch (OHServiceException serviceException) { - throw new OHAPIException(new OHExceptionMessage("Vaccine Type not deleted.")); - } - return ResponseEntity.ok(true); + if (vaccineType == null) { + throw new OHAPIException(new OHExceptionMessage("Vaccine Type not found."), HttpStatus.NOT_FOUND); + } + try { + vaccineTypeManager.deleteVaccineType(vaccineType); + return true; + } catch (OHServiceException serviceException) { + throw new OHAPIException(new OHExceptionMessage("Vaccine Type not deleted.")); } - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); } /** * Check if the code is already used by other vaccine type. * - * @param code + * @param code Vaccine type code * @return {@code true} if it is already used, {@code false} otherwise - * @throws OHServiceException + * @throws OHServiceException When failed to check the vaccine type code */ - @GetMapping(value = "/vaccinetypes/check/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity checkVaccineTypeCode(@PathVariable String code) throws OHServiceException { + @GetMapping("/vaccinetypes/check/{code}") + public boolean checkVaccineTypeCode(@PathVariable String code) throws OHServiceException { LOGGER.info("Check vaccine type code: {}", code); - boolean check = vaccineTypeManager.isCodePresent(code); - return ResponseEntity.ok(check); + return vaccineTypeManager.isCodePresent(code); } } diff --git a/src/main/java/org/isf/visits/rest/VisitsController.java b/src/main/java/org/isf/visits/rest/VisitsController.java index dd24346af..b28b749bf 100644 --- a/src/main/java/org/isf/visits/rest/VisitsController.java +++ b/src/main/java/org/isf/visits/rest/VisitsController.java @@ -21,7 +21,6 @@ */ package org.isf.visits.rest; -import java.util.ArrayList; import java.util.List; import org.isf.shared.exceptions.OHAPIException; @@ -33,33 +32,32 @@ import org.isf.visits.model.Visit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/visits") +@RestController @Tag(name = "Visit") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class VisitsController { private static final Logger LOGGER = LoggerFactory.getLogger(VisitsController.class); - @Autowired - protected VisitManager visitManager; + private final VisitManager visitManager; - @Autowired - protected VisitMapper mapper; + private final VisitMapper mapper; public VisitsController(VisitManager visitManager, VisitMapper visitMapper) { this.visitManager = visitManager; @@ -71,55 +69,41 @@ public VisitsController(VisitManager visitManager, VisitMapper visitMapper) { * * @param patID the id of the patient * @return NO_CONTENT if there aren't visitors, {@code List} otherwise - * @throws OHServiceException + * @throws OHServiceException When failed to get patient visits */ - @GetMapping(value = "/visits/patient/{patID}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getVisit(@PathVariable("patID") int patID) throws OHServiceException { + @GetMapping("/visits/patient/{patID}") + public List getVisit(@PathVariable("patID") int patID) throws OHServiceException { LOGGER.info("Get visit related to patId: {}", patID); - List visit = visitManager.getVisits(patID); - List listVisit = new ArrayList<>(); - for (Visit visitP : visit) { - VisitDTO visitDTO = mapper.map2DTO(visitP); - listVisit.add(visitDTO); - } - if (listVisit.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } else { - return ResponseEntity.ok(listVisit); - } + + return mapper.map2DTOList(visitManager.getVisits(patID)); } /** * Create a new visitor. * - * @param newVisit + * @param newVisit Visit payload * @return an error if there are some problem, the visitor id (Integer) otherwise - * @throws OHServiceException + * @throws OHServiceException When failed to create visit */ - @PostMapping(value = "/visits", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity newVisit(@RequestBody VisitDTO newVisit) throws OHServiceException { + @PostMapping("/visits") + @ResponseStatus(HttpStatus.CREATED) + public VisitDTO newVisit(@RequestBody VisitDTO newVisit) throws OHServiceException { LOGGER.info("Create Visit: {}", newVisit); - Visit visitD = mapper.map2Model(newVisit); - Visit visit = visitManager.newVisit(visitD); - return ResponseEntity.status(HttpStatus.CREATED).body(mapper.map2DTO(visit)); // TODO: verify if it's correct + return mapper.map2DTO(visitManager.newVisit(mapper.map2Model(newVisit))); } /** - * Create new visitors. - * + * Create new visits. + * * @param newVisits a list with all the visitors * @return an error message if there are some problem, ok otherwise - * @throws OHServiceException + * @throws OHServiceException When failed to create visits */ - @PostMapping(value = "/visits/insertList", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity newVisits(@RequestBody List newVisits) throws OHServiceException { + @PostMapping("/visits/insertList") + @ResponseStatus(HttpStatus.CREATED) + public boolean newVisits(@RequestBody List newVisits) throws OHServiceException { LOGGER.info("Create Visits"); - List listVisits = mapper.map2ModelList(newVisits); - boolean areCreated = visitManager.newVisits(listVisits); - if (!areCreated) { - throw new OHAPIException(new OHExceptionMessage("Visits not created.")); - } - return ResponseEntity.status(HttpStatus.CREATED).body(areCreated); + return visitManager.newVisits(mapper.map2ModelList(newVisits)); } /** @@ -127,35 +111,34 @@ public ResponseEntity newVisits(@RequestBody List newVisits) * * @param patID the id of the patient * @return an error message if there are some problem, ok otherwise - * @throws OHServiceException + * @throws OHServiceException When failed to delete patient visit */ - @DeleteMapping(value = "/visits/delete/{patID}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity deleteVisitsRelatedToPatient(@PathVariable("patID") int patID) throws OHServiceException { + @DeleteMapping("/visits/delete/{patID}") + public boolean deleteVisitsRelatedToPatient( + @PathVariable("patID") int patID + ) throws OHServiceException { LOGGER.info("Delete Visit related to patId: {}", patID); - boolean areDeleted = visitManager.deleteAllVisits(patID); - if (!areDeleted) { - throw new OHAPIException(new OHExceptionMessage("Visits not deleted.")); - } - return ResponseEntity.ok(true); + + return visitManager.deleteAllVisits(patID); } /** - * Create new visitors. + * Update visit * * @param visitID the id of the visit + * @param updateVisit Visit payload * @return an error message if there are some problem, ok otherwise - * @throws OHServiceException + * @throws OHServiceException When failed to update the visit */ - @PutMapping(value = "/visits/{visitID}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity updateVisit(@PathVariable("visitID") int visitID, @RequestBody VisitDTO updateVisit) throws OHServiceException { + @PutMapping("/visits/{visitID}") + public VisitDTO updateVisit( + @PathVariable("visitID") int visitID, @RequestBody VisitDTO updateVisit + ) throws OHServiceException { LOGGER.info("Create Visits"); - Visit visit = visitManager.findVisit(visitID); - if (visit == null) { - throw new OHAPIException(new OHExceptionMessage("Visit not found.")); - } - if (visit.getVisitID() != updateVisit.getVisitID()) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); + Visit visit = visitManager.findVisit(visitID); + if (visit == null || visit.getVisitID() != updateVisit.getVisitID()) { + throw new OHAPIException(new OHExceptionMessage("Visit not found."), HttpStatus.NOT_FOUND); } Visit visitUp = mapper.map2Model(updateVisit); @@ -163,7 +146,7 @@ public ResponseEntity updateVisit(@PathVariable("visitID") int visitID if (visitUpdate == null) { throw new OHAPIException(new OHExceptionMessage("Visit not updated.")); } - return ResponseEntity.status(HttpStatus.OK).body(mapper.map2DTO(visitUpdate)); - } + return mapper.map2DTO(visitUpdate); + } } diff --git a/src/main/java/org/isf/ward/rest/WardController.java b/src/main/java/org/isf/ward/rest/WardController.java index 9098f4763..c57c72646 100644 --- a/src/main/java/org/isf/ward/rest/WardController.java +++ b/src/main/java/org/isf/ward/rest/WardController.java @@ -32,33 +32,32 @@ import org.isf.ward.model.Ward; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -@RestController(value = "/wards") +@RestController @Tag(name = "Wards") @SecurityRequirement(name = "bearerAuth") +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) public class WardController { private static final Logger LOGGER = LoggerFactory.getLogger(WardController.class); - @Autowired - protected WardBrowserManager wardManager; - - @Autowired - protected WardMapper mapper; + private final WardBrowserManager wardManager; + + private final WardMapper mapper; public WardController(WardBrowserManager wardManager, WardMapper wardMapper) { this.wardManager = wardManager; @@ -69,91 +68,80 @@ public WardController(WardBrowserManager wardManager, WardMapper wardMapper) { * Get all the {@link Ward}s. * * @return NO_CONTENT if there aren't wards, {@code List} otherwise - * @throws OHServiceException + * @throws OHServiceException When failed to get wards */ - @GetMapping(value = "/wards", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getWards() throws OHServiceException { + @GetMapping(value = "/wards") + public List getWards() throws OHServiceException { LOGGER.info("Get wards"); - List wards = wardManager.getWards(); - List listWard = mapper.map2DTOList(wards); - if (listWard.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } else { - return ResponseEntity.ok(listWard); - } + + return mapper.map2DTOList(wardManager.getWards()); } /** * Get all the {@link Ward}s with maternity flag {@code false}. * * @return NO_CONTENT if there aren't wards, {@code List} otherwise - * @throws OHServiceException + * @throws OHServiceException When failed to get wards */ - @GetMapping(value = "/wardsNoMaternity", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getWardsNoMaternity() throws OHServiceException { + @GetMapping(value = "/wardsNoMaternity") + public List getWardsNoMaternity() throws OHServiceException { LOGGER.info("Get wards no maternity"); - List wards = wardManager.getWardsNoMaternity(); - List listWard = mapper.map2DTOList(wards); - if (listWard.isEmpty()) { - return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null); - } else { - return ResponseEntity.ok(listWard); - } + + return mapper.map2DTOList(wardManager.getWardsNoMaternity()); } /** * Get current number of patients inside a {@link Ward}. * - * @param code + * @param code Ward code * @return BAD_REQUEST if there are some problem, integer otherwise - * @throws OHServiceException + * @throws OHServiceException When failed to get the number of occupants */ - @GetMapping(value = "/wards/occupation/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getCurrentOccupation(@PathVariable String code) throws OHServiceException { - LOGGER.info("Get current occupation ward code: {}", code); + @GetMapping(value = "/wards/occupation/{code}") + public Integer getCurrentOccupation(@PathVariable String code) throws OHServiceException { + LOGGER.info("Get current occupation ward code: {}", code); Ward ward = wardManager.findWard(code); - int numberOfPatients = wardManager.getCurrentOccupation(ward); - if (numberOfPatients == -1) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); - } else { - return ResponseEntity.ok(numberOfPatients); - } + + return wardManager.getCurrentOccupation(ward); } /** * Create a new {@link Ward}. * - * @param newWard + * @param newWard Ward payload * @return an error message if there are some problem, ok otherwise - * @throws OHServiceException + * @throws OHServiceException When failed to create ward */ - @PostMapping(value = "/wards", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity newWard(@RequestBody WardDTO newWard) throws OHServiceException { - LOGGER.info("Create Ward: {}", newWard); + @PostMapping(value = "/wards") + @ResponseStatus(HttpStatus.CREATED) + public WardDTO newWard(@RequestBody WardDTO newWard) throws OHServiceException { + LOGGER.info("Create Ward: {}", newWard); Ward wardCreated = wardManager.newWard(mapper.map2Model(newWard)); if (wardCreated == null) { throw new OHAPIException(new OHExceptionMessage("Ward not created.")); } - return ResponseEntity.status(HttpStatus.CREATED).body(mapper.map2DTO(wardCreated)); + + return mapper.map2DTO(wardCreated); } /** * Update a specified {@link Ward}. * - * @param updateWard + * @param updateWard Ward payload * @return an error message if there are some problem, ok otherwise - * @throws OHServiceException + * @throws OHServiceException When */ - @PutMapping(value = "/wards", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity updateWard(@RequestBody WardDTO updateWard) throws OHServiceException { - LOGGER.info("Update ward with code: {}", updateWard.getCode()); - Ward ward = mapper.map2Model(updateWard); - ward.setLock(updateWard.getLock()); + @PutMapping(value = "/wards") + public WardDTO updateWard(@RequestBody WardDTO updateWard) throws OHServiceException { + LOGGER.info("Update ward with code: {}", updateWard.getCode()); + Ward ward = mapper.map2Model(updateWard); + ward.setLock(updateWard.getLock()); Ward wardUpdated = wardManager.updateWard(ward); if (wardUpdated == null) { throw new OHAPIException(new OHExceptionMessage("Ward not updated.")); } - return ResponseEntity.ok(mapper.map2DTO(wardUpdated)); + + return mapper.map2DTO(wardUpdated); } @@ -162,35 +150,37 @@ public ResponseEntity updateWard(@RequestBody WardDTO updateWard) throw * * @param code the ward to delete * @return an error message if there are some problem, ok otherwise - * @throws OHServiceException + * @throws OHServiceException When failed to delete ward */ - @DeleteMapping(value = "/wards/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity deleteWard(@PathVariable String code) throws OHServiceException { + @DeleteMapping(value = "/wards/{code}") + public boolean deleteWard(@PathVariable String code) throws OHServiceException { LOGGER.info("Delete Ward with code: {}", code); Ward ward = wardManager.findWard(code); - if (ward != null) { - try { - wardManager.deleteWard(ward); - } catch (OHServiceException serviceException) { - throw new OHAPIException(new OHExceptionMessage("Ward not deleted.")); - } - return ResponseEntity.ok(true); + if (ward == null) { + throw new OHAPIException(new OHExceptionMessage("Ward not found."), HttpStatus.NOT_FOUND); + } + + try { + wardManager.deleteWard(ward); + return true; + } catch (OHServiceException serviceException) { + throw new OHAPIException(new OHExceptionMessage("Ward not deleted.")); } - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); } /** * Check if the code is already used by other {@link Ward}. * - * @param code + * @param code Ward code * @return {@code true} if it is already used, false otherwise - * @throws OHServiceException + * @throws OHServiceException When failed to check the ward code */ - @GetMapping(value = "/wards/check/{code}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity checkWardCode(@PathVariable(value = "code") String code) throws OHServiceException { - LOGGER.info("Check ward code: {}", code); - boolean check = wardManager.isCodePresent(code); - return ResponseEntity.ok(check); + @GetMapping(value = "/wards/check/{code}") + public boolean checkWardCode( + @PathVariable(value = "code") String code + ) throws OHServiceException { + LOGGER.info("Check ward code: {}", code); + return wardManager.isCodePresent(code); } /** @@ -199,13 +189,13 @@ public ResponseEntity checkWardCode(@PathVariable(value = "code") Strin * @param createIfNotExist if {@code true} it will create the missing {@link Ward} (with default values) * and will return {@link true} * @return {@code true} if the Maternity {@link Ward} exists, {@code false} otherwise. - * @throws OHServiceException + * @throws OHServiceException When failed to check the ward */ - @GetMapping(value = "/wards/check/maternity/{createIfNotExist}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity checkWardMaternityCode(@PathVariable Boolean createIfNotExist) throws OHServiceException { + @GetMapping(value = "/wards/check/maternity/{createIfNotExist}") + public boolean checkWardMaternityCode( + @PathVariable Boolean createIfNotExist + ) throws OHServiceException { LOGGER.info("Check ward maternity code"); - boolean check = wardManager.maternityControl(createIfNotExist); - return ResponseEntity.ok(check); + return wardManager.maternityControl(createIfNotExist); } - } diff --git a/src/test/java/org/isf/accounting/rest/BillControllerTest.java b/src/test/java/org/isf/accounting/rest/BillControllerTest.java index 006eba9ad..f9ebd272d 100644 --- a/src/test/java/org/isf/accounting/rest/BillControllerTest.java +++ b/src/test/java/org/isf/accounting/rest/BillControllerTest.java @@ -42,6 +42,7 @@ import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; @@ -108,13 +109,13 @@ public class BillControllerTest extends ControllerBaseTest { @Mock private PatientBrowserManager patientManagerMock; - private BillMapper billMapper = new BillMapper(); + private final BillMapper billMapper = new BillMapper(); - private BillItemsMapper billItemsMapper = new BillItemsMapper(); + private final BillItemsMapper billItemsMapper = new BillItemsMapper(); - private BillPaymentsMapper billPaymentsMapper = new BillPaymentsMapper(); + private final BillPaymentsMapper billPaymentsMapper = new BillPaymentsMapper(); - private PatientMapper patientMapper = new PatientMapper(); + private final PatientMapper patientMapper = new PatientMapper(); private MockMvc mockMvc; @@ -124,9 +125,9 @@ public class BillControllerTest extends ControllerBaseTest { public void setup() { closeable = MockitoAnnotations.openMocks(this); this.mockMvc = MockMvcBuilders - .standaloneSetup(new BillController(billManagerMock, priceListManagerMock, patientManagerMock, billMapper, billItemsMapper, billPaymentsMapper)) - .setControllerAdvice(new OHResponseEntityExceptionHandler()) - .build(); + .standaloneSetup(new BillController(billManagerMock, priceListManagerMock, patientManagerMock, billMapper, billItemsMapper, billPaymentsMapper)) + .setControllerAdvice(new OHResponseEntityExceptionHandler()) + .build(); ModelMapper modelMapper = new ModelMapper(); modelMapper.addConverter(new BlobToByteArrayConverter()); @@ -150,13 +151,13 @@ public void when_post_bills_is_call_without_contentType_header_then_HttpMediaTyp String request = "/bills"; MvcResult result = this.mockMvc - .perform(post(request).content(new byte[] { 'a', 'b', 'c' })) - .andDo(log()) - .andExpect(status().is4xxClientError()) - .andExpect(status().isUnsupportedMediaType()) - // TODO .andExpect(content().string(anyOf(nullValue(), equalTo("")))) - .andExpect(content().string(containsString("Unsupported Media Type"))) - .andReturn(); + .perform(post(request).content(new byte[] { 'a', 'b', 'c' })) + .andDo(log()) + .andExpect(status().is4xxClientError()) + .andExpect(status().isUnsupportedMediaType()) + // TODO .andExpect(content().string(anyOf(nullValue(), equalTo("")))) + .andExpect(content().string(containsString("Unsupported Media Type"))) + .andReturn(); Optional exception = Optional.ofNullable((HttpMediaTypeNotSupportedException) result.getResolvedException()); LOGGER.debug("exception: {}", exception); @@ -171,17 +172,17 @@ public void when_post_bills_is_call_with_empty_body_then_BadRequest_HttpMessageN String empty_body = ""; MvcResult result = this.mockMvc - .perform( - post(request) - .content(empty_body.getBytes()) - .contentType(MediaType.APPLICATION_JSON) - ) - .andDo(log()) - .andExpect(status().is4xxClientError()) - .andExpect(status().isBadRequest()) - // TODO .andExpect(content().string(anyOf(nullValue(), equalTo("")))) - .andExpect(content().string(containsString("Failed to read request"))) - .andReturn(); + .perform( + post(request) + .content(empty_body.getBytes()) + .contentType(MediaType.APPLICATION_JSON) + ) + .andDo(log()) + .andExpect(status().is4xxClientError()) + .andExpect(status().isBadRequest()) + // TODO .andExpect(content().string(anyOf(nullValue(), equalTo("")))) + .andExpect(content().string(containsString("Failed to read request"))) + .andReturn(); Optional exception = Optional.ofNullable((HttpMessageNotReadableException) result.getResolvedException()); LOGGER.debug("exception: {}", exception); @@ -203,16 +204,16 @@ public void when_post_patients_PatientBrowserManager_getPatient_returns_null_the when(patientManagerMock.getPatientById(anyInt())).thenReturn(null); MvcResult result = this.mockMvc - .perform( - post(request) - .contentType(MediaType.APPLICATION_JSON) - .content(FullBillDTOHelper.asJsonString(newFullBillDTO)) - ) - .andDo(log()) - .andExpect(status().is4xxClientError()) - .andExpect(status().isBadRequest()) //TODO Create OHCreateAPIException - .andExpect(content().string(containsString("Patient not found."))) - .andReturn(); + .perform( + post(request) + .contentType(MediaType.APPLICATION_JSON) + .content(Objects.requireNonNull(FullBillDTOHelper.asJsonString(newFullBillDTO))) + ) + .andDo(log()) + .andExpect(status().is4xxClientError()) + .andExpect(status().isBadRequest()) //TODO Create OHCreateAPIException + .andExpect(content().string(containsString("Patient not found."))) + .andReturn(); //TODO Create OHCreateAPIException Optional oHAPIException = Optional.ofNullable((OHAPIException) result.getResolvedException()); @@ -236,16 +237,16 @@ public void when_put_bills_PatientBrowserManager_getPatient_returns_null_then_OH when(billManagerMock.getBill(id)).thenReturn(bill); MvcResult result = this.mockMvc - .perform( - put(request, id) - .contentType(MediaType.APPLICATION_JSON) - .content(FullBillDTOHelper.asJsonString(newFullBillDTO)) - ) - .andDo(log()) - .andExpect(status().is4xxClientError()) - .andExpect(status().isBadRequest()) //TODO Create OHCreateAPIException - .andExpect(content().string(containsString("Patient not found."))) - .andReturn(); + .perform( + put(request, id) + .contentType(MediaType.APPLICATION_JSON) + .content(Objects.requireNonNull(FullBillDTOHelper.asJsonString(newFullBillDTO))) + ) + .andDo(log()) + .andExpect(status().is4xxClientError()) + .andExpect(status().isBadRequest()) //TODO Create OHCreateAPIException + .andExpect(content().string(containsString("Patient not found."))) + .andReturn(); //TODO Create OHCreateAPIException Optional oHAPIException = Optional.ofNullable((OHAPIException) result.getResolvedException()); @@ -293,18 +294,18 @@ public void when_put_bills_PatientBrowserManager_getPatient_returns_null_then_OK //TODO check eq(bill) case //when(billManagerMock.updateBill(bill, billItemsArrayList, billPaymentsList)) when(billManagerMock.updateBill(any(Bill.class), eq(billItemsList), eq(billPaymentsList))) - .thenReturn(bill); + .thenReturn(bill); this.mockMvc - .perform( - put(request, id) - .contentType(MediaType.APPLICATION_JSON) - .content(FullBillDTOHelper.asJsonString(newFullBillDTO)) - ) - .andDo(log()) - .andExpect(status().isCreated()) - .andExpect(content().string(containsString(FullBillDTOHelper.asJsonString(newFullBillDTO)))) - .andReturn(); + .perform( + put(request, id) + .contentType(MediaType.APPLICATION_JSON) + .content(Objects.requireNonNull(FullBillDTOHelper.asJsonString(newFullBillDTO))) + ) + .andDo(log()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(FullBillDTOHelper.asJsonString(newFullBillDTO)))) + .andReturn(); } @Test @@ -315,20 +316,19 @@ public void when_get_items_with_existent_id_then_getItems_returns_items_and_OK() FullBillDTO newFullBillDTO = FullBillDTOHelper.setup(patientMapper, billItemsMapper, billPaymentsMapper); newFullBillDTO.getBill().setId(id); - List itemsDTOSExpected = new ArrayList<>( - newFullBillDTO.getBillItems().stream().map(it -> billItemsMapper.map2Model(it)).collect(Collectors.toList())); + List itemsDTOSExpected = newFullBillDTO.getBillItems().stream().map(billItemsMapper::map2Model).collect(Collectors.toList()); when(billManagerMock.getItems(id)).thenReturn(itemsDTOSExpected); this.mockMvc - .perform( - get(request, id) - .contentType(MediaType.APPLICATION_JSON) - ) - .andDo(log()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(BillHelper.getObjectMapper().writeValueAsString(newFullBillDTO.getBillItems())))) - .andReturn(); + .perform( + get(request, id) + .contentType(MediaType.APPLICATION_JSON) + ) + .andDo(log()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(BillHelper.getObjectMapper().writeValueAsString(newFullBillDTO.getBillItems())))) + .andReturn(); } @Test @@ -337,12 +337,12 @@ public void when_get_items_with_existent_id_then_getItems_is_empty_and_isNoConte String request = "/bills/items/{bill_id}"; this.mockMvc - .perform( - get(request, id) - .contentType(MediaType.APPLICATION_JSON) - ) - .andDo(log()) - .andExpect(status().isNoContent()); + .perform( + get(request, id) + .contentType(MediaType.APPLICATION_JSON) + ) + .andDo(log()) + .andExpect(status().isOk()); } @Test @@ -356,14 +356,14 @@ public void when_get_bill_with_existent_id_then_response_BillDTO_and_OK() throws when(billManagerMock.getBill(id)).thenReturn(bill); this.mockMvc - .perform( - get(request, id) - .contentType(MediaType.APPLICATION_JSON) - ) - .andDo(log()) - .andExpect(status().isOk()) - // TODO 1 .andExpect(content().string(containsString(BillDTOHelper.asJsonString(BillDTOHelper.setup(id))))) - .andReturn(); + .perform( + get(request, id) + .contentType(MediaType.APPLICATION_JSON) + ) + .andDo(log()) + .andExpect(status().isOk()) + // TODO 1 .andExpect(content().string(containsString(BillDTOHelper.asJsonString(BillDTOHelper.setup(id))))) + .andReturn(); } @Test @@ -376,13 +376,13 @@ public void when_delete_bill_with_existent_id_then_response_true_and_OK() throws when(billManagerMock.getBill(id)).thenReturn(bill); this.mockMvc - .perform( - delete(request, id) - .contentType(MediaType.APPLICATION_JSON) - ) - .andDo(log()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString("true"))); + .perform( + delete(request, id) + .contentType(MediaType.APPLICATION_JSON) + ) + .andDo(log()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("true"))); } @Test @@ -397,15 +397,15 @@ public void when_get_bill_pending_affiliate_with_existent_patient_code_then_resp when(billManagerMock.getPendingBillsAffiliate(code)).thenReturn(billList); this.mockMvc - .perform( - get(request, code) - .contentType(MediaType.APPLICATION_JSON) - ) - .andDo(log()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(BillDTOHelper.asJsonString(expectedBillDTO1)))) - .andExpect(content().string(containsString(BillDTOHelper.asJsonString(expectedBillDTO2)))) - .andReturn(); + .perform( + get(request, code) + .contentType(MediaType.APPLICATION_JSON) + ) + .andDo(log()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(BillDTOHelper.asJsonString(expectedBillDTO1)))) + .andExpect(content().string(containsString(BillDTOHelper.asJsonString(expectedBillDTO2)))) + .andReturn(); } @Test @@ -422,16 +422,16 @@ public void when_post_searchBillsByPayments_with_a_list_of_existent_billsPayment when(billManagerMock.getBills(billsPaymentsList)).thenReturn(billList); this.mockMvc - .perform( - post(request) - .contentType(MediaType.APPLICATION_JSON) - .content(BillPaymentsDTOHelper.asJsonString(billsPaymentsDTOList)) - ) - .andDo(log()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(BillDTOHelper.asJsonString(expectedBillDTO1)))) - .andExpect(content().string(containsString(BillDTOHelper.asJsonString(expectedBillDTO2)))) - .andReturn(); + .perform( + post(request) + .contentType(MediaType.APPLICATION_JSON) + .content(Objects.requireNonNull(BillPaymentsDTOHelper.asJsonString(billsPaymentsDTOList))) + ) + .andDo(log()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(BillDTOHelper.asJsonString(expectedBillDTO1)))) + .andExpect(content().string(containsString(BillDTOHelper.asJsonString(expectedBillDTO2)))) + .andReturn(); } @Test @@ -443,26 +443,26 @@ public void when_get_pendingBills_with_existent_patient_code_then_response_List_ BillDTO expectedBillDTO1 = billMapper.map2DTO(billList.get(0)); BillDTO expectedBillDTO2 = billMapper.map2DTO(billList.get(1)); - List billDTOS = billList.stream().map(b -> billMapper.map2DTO(b)).collect(Collectors.toList()); + List billDTOS = billList.stream().map(billMapper::map2DTO).collect(Collectors.toList()); when(billManagerMock.getPendingBills(code)).thenReturn(billList); this.mockMvc - .perform( - get(request, code) - .contentType(MediaType.APPLICATION_JSON) - ) - .andDo(log()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(BillDTOHelper.asJsonString(expectedBillDTO1)))) - .andExpect(content().string(containsString(BillDTOHelper.asJsonString(expectedBillDTO2)))) - .andExpect(content().string(containsString(BillDTOHelper.asJsonString(billDTOS)))) - .andReturn(); + .perform( + get(request, code) + .contentType(MediaType.APPLICATION_JSON) + ) + .andDo(log()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(BillDTOHelper.asJsonString(expectedBillDTO1)))) + .andExpect(content().string(containsString(BillDTOHelper.asJsonString(expectedBillDTO2)))) + .andExpect(content().string(containsString(BillDTOHelper.asJsonString(billDTOS)))) + .andReturn(); } @Test public void when_post_searchBillsByItem_with_valid_dates_and_billItemsDTO_content_and_PatientBrowserManager_getBills_returns_billList_then_OK() - throws Exception { + throws Exception { String request = "/bills/search/by/item?datefrom={dateFrom}&dateto={dateTo}"; String dateFrom = LocalDateTime.now().format(DateTimeFormatter.ofPattern(Constants.DATE_FORMAT_YYYY_MM_DD_T_HH_MM_SS_SSS_Z)); String dateTo = LocalDateTime.now().format(DateTimeFormatter.ofPattern(Constants.DATE_FORMAT_YYYY_MM_DD_T_HH_MM_SS_SSS_Z)); @@ -481,16 +481,16 @@ public void when_post_searchBillsByItem_with_valid_dates_and_billItemsDTO_conten when(billManagerMock.getBills(any(LocalDateTime.class), any(LocalDateTime.class), eq(billItem))).thenReturn(billList); this.mockMvc - .perform( - post(request, dateFrom, dateTo) - .contentType(MediaType.APPLICATION_JSON) - .content(BillItemsDTOHelper.asJsonString(billItemsDTO)) - ) - .andDo(log()) - .andDo(print()) - .andExpect(status().isOk()) - // TODO 1 .andExpect(content().string(containsString(BillDTOHelper.asJsonString(BillDTOHelper.setup(id))))) - .andReturn(); + .perform( + post(request, dateFrom, dateTo) + .contentType(MediaType.APPLICATION_JSON) + .content(Objects.requireNonNull(BillItemsDTOHelper.asJsonString(billItemsDTO))) + ) + .andDo(log()) + .andDo(print()) + .andExpect(status().isOk()) + // TODO 1 .andExpect(content().string(containsString(BillDTOHelper.asJsonString(BillDTOHelper.setup(id))))) + .andReturn(); } @Test @@ -512,15 +512,15 @@ public void when_get_searchBills_with_valid_dates_and_valid_patient_code_and_Pat when(billManagerMock.getBills(any(LocalDateTime.class), any(LocalDateTime.class), eq(patient))).thenReturn(billList); this.mockMvc - .perform( - get(request, dateFrom, dateTo, patientCode) - .contentType(MediaType.APPLICATION_JSON) - ) - .andDo(log()) - .andDo(print()) - .andExpect(status().isOk()) - // TODO 1 .andExpect(content().string(containsString(BillDTOHelper.asJsonString(BillDTOHelper.setup(id))))) - .andReturn(); + .perform( + get(request, dateFrom, dateTo, patientCode) + .contentType(MediaType.APPLICATION_JSON) + ) + .andDo(log()) + .andDo(print()) + .andExpect(status().isOk()) + // TODO 1 .andExpect(content().string(containsString(BillDTOHelper.asJsonString(BillDTOHelper.setup(id))))) + .andReturn(); } @Test @@ -536,20 +536,20 @@ public void when_get_getDistinctItems_BillBrowserManager_getDistinctItems_return billItemsList.add(billItems1); billItemsList.add(billItems2); - List expectedBillItemsDTOList = billItemsList.stream().map(it -> billItemsMapper.map2DTO(it)).collect(Collectors.toList()); + List expectedBillItemsDTOList = billItemsList.stream().map(billItemsMapper::map2DTO).collect(Collectors.toList()); //TODO emulate distinct behavior since both billItems in List are equal when(billManagerMock.getDistinctItems()).thenReturn(billItemsList); this.mockMvc - .perform( - get(request) - .contentType(MediaType.APPLICATION_JSON) - ) - .andDo(log()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(BillItemsDTOHelper.asJsonString(expectedBillItemsDTOList)))) - .andReturn(); + .perform( + get(request) + .contentType(MediaType.APPLICATION_JSON) + ) + .andDo(log()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(BillItemsDTOHelper.asJsonString(expectedBillItemsDTOList)))) + .andReturn(); } @Test @@ -563,14 +563,14 @@ public void when_get_getPaymentsByBillId_with_valid_bill_id_and_BillBrowserManag when(billManagerMock.getPayments(billId)).thenReturn(BillPaymentsDTOHelper.toModelList(billPaymentsDTOList, billPaymentsMapper)); this.mockMvc - .perform( - get(request, billId) - .contentType(MediaType.APPLICATION_JSON) - ) - .andDo(log()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(BillPaymentsDTOHelper.asJsonString(billPaymentsDTOList)))) - .andReturn(); + .perform( + get(request, billId) + .contentType(MediaType.APPLICATION_JSON) + ) + .andDo(log()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(BillPaymentsDTOHelper.asJsonString(billPaymentsDTOList)))) + .andReturn(); } } diff --git a/src/test/java/org/isf/admission/rest/AdmissionControllerTest.java b/src/test/java/org/isf/admission/rest/AdmissionControllerTest.java index e24c1fc74..7ec9377e3 100644 --- a/src/test/java/org/isf/admission/rest/AdmissionControllerTest.java +++ b/src/test/java/org/isf/admission/rest/AdmissionControllerTest.java @@ -34,6 +34,7 @@ import java.time.LocalDateTime; import java.util.List; +import java.util.Objects; import org.isf.admission.data.AdmissionHelper; import org.isf.admission.dto.AdmissionDTO; @@ -46,7 +47,6 @@ import org.isf.admtype.model.AdmissionType; import org.isf.disctype.data.DischargeTypeHelper; import org.isf.disctype.manager.DischargeTypeBrowserManager; -import org.isf.disctype.mapper.DischargeTypeMapper; import org.isf.disctype.model.DischargeType; import org.isf.disease.data.DiseaseHelper; import org.isf.disease.manager.DiseaseBrowserManager; @@ -103,22 +103,20 @@ public class AdmissionControllerTest { private OperationBrowserManager operationManagerMock; @Mock - private PregnantTreatmentTypeBrowserManager pregTraitTypeManagerMock; + private PregnantTreatmentTypeBrowserManager pregnancyTreatmentTypeManagerMock; @Mock - private DeliveryTypeBrowserManager dlvrTypeManagerMock; + private DeliveryTypeBrowserManager deliveryTypeManager; @Mock - private DeliveryResultTypeBrowserManager dlvrrestTypeManagerMock; + private DeliveryResultTypeBrowserManager deliveryResultTypeManagerMock; @Mock private DischargeTypeBrowserManager dischargeTypeManagerMock; - private AdmissionMapper admissionMapper; + private final AdmissionMapper admissionMapper; - private AdmittedPatientMapper admittedMapper; - - private DischargeTypeMapper dischargeMapper; + private final AdmittedPatientMapper admittedMapper; private MockMvc mockMvc; @@ -127,19 +125,20 @@ public class AdmissionControllerTest { public AdmissionControllerTest() { admittedMapper = new AdmittedPatientMapper(); admissionMapper = new AdmissionMapper(); - dischargeMapper = new DischargeTypeMapper(); } @BeforeEach public void setup() { closeable = MockitoAnnotations.openMocks(this); this.mockMvc = MockMvcBuilders - .standaloneSetup(new AdmissionController(admissionManagerMock, patientManagerMock, wardManagerMock, - diseaseManagerMock, operationManagerMock, pregTraitTypeManagerMock, - dlvrTypeManagerMock, dlvrrestTypeManagerMock, admissionMapper, - admittedMapper, dischargeTypeManagerMock, dischargeMapper)) - .setControllerAdvice(new OHResponseEntityExceptionHandler()) - .build(); + .standaloneSetup(new AdmissionController(admissionManagerMock, patientManagerMock, wardManagerMock, + diseaseManagerMock, pregnancyTreatmentTypeManagerMock, + deliveryTypeManager, deliveryResultTypeManagerMock, admissionMapper, + admittedMapper, dischargeTypeManagerMock) + ) + .setControllerAdvice(new OHResponseEntityExceptionHandler()) + .build(); + ModelMapper modelMapper = new ModelMapper(); modelMapper.addConverter(new BlobToByteArrayConverter()); modelMapper.addConverter(new ByteArrayToBlobConverter()); @@ -153,29 +152,6 @@ void closeService() throws Exception { closeable.close(); } -// @Test -// public void testGetAdmissions_200() throws Exception { -// String request = "/admissions/{id}"; -// int id = 1; -// -// Admission admission = AdmissionHelper.setup(); -// when(admissionManagerMock.getAdmission(id)) -// .thenReturn(admission); -// -// MvcResult result = this.mockMvc -// .perform( -// get(request, id) -// .contentType(MediaType.APPLICATION_JSON) -// ) -// .andDo(log()) -// .andExpect(status().is2xxSuccessful()) -// .andExpect(status().isOk()) -// .andExpect(content().string(containsString(AdmissionHelper.asJsonString(admissionMapper.map2DTO(admission))))) -// .andReturn(); -// -// LOGGER.debug("result: {}", result); -// } - @Test public void testGetCurrentAdmission_200() throws Exception { String request = "/admissions/current"; @@ -183,21 +159,21 @@ public void testGetCurrentAdmission_200() throws Exception { Patient patient = PatientHelper.setup(); when(patientManagerMock.getPatientById(patientCode)) - .thenReturn(patient); + .thenReturn(patient); Admission admission = AdmissionHelper.setup(); when(admissionManagerMock.getCurrentAdmission(patient)) - .thenReturn(admission); + .thenReturn(admission); MvcResult result = this.mockMvc - .perform(get(request) - .param("patientCode", patientCode.toString()) - .contentType(MediaType.APPLICATION_JSON)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(AdmissionHelper.asJsonString(admissionMapper.map2DTO(admission))))) - .andReturn(); + .perform(get(request) + .param("patientCode", patientCode.toString()) + .contentType(MediaType.APPLICATION_JSON)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(AdmissionHelper.asJsonString(admissionMapper.map2DTO(admission))))) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -208,16 +184,16 @@ public void testGetAllAdmittedPatients_200() throws Exception { List admittedPatients = PatientHelper.setupAdmittedPatientList(2); when(admissionManagerMock.getAdmittedPatients(any(), any(), any(String.class))) - .thenReturn(admittedPatients); + .thenReturn(admittedPatients); MvcResult result = this.mockMvc - .perform(get(request) - .contentType(MediaType.APPLICATION_JSON)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(PatientHelper.asJsonString(admittedMapper.map2DTOList(admittedPatients))))) - .andReturn(); + .perform(get(request) + .contentType(MediaType.APPLICATION_JSON)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(PatientHelper.asJsonString(admittedMapper.map2DTOList(admittedPatients))))) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -229,15 +205,15 @@ public void testGetAdmittedPatientsSearch_200() throws Exception { String searchTerms = ""; when(admissionManagerMock.getAdmittedPatients(any(), any(), any(String.class))) - .thenReturn(admittedPatients); + .thenReturn(admittedPatients); MvcResult result = this.mockMvc - .perform(get(request, searchTerms) - .contentType(MediaType.APPLICATION_JSON)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(PatientHelper.asJsonString(admittedMapper.map2DTOList(admittedPatients))))) - .andReturn(); + .perform(get(request, searchTerms) + .contentType(MediaType.APPLICATION_JSON)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(PatientHelper.asJsonString(admittedMapper.map2DTOList(admittedPatients))))) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -249,16 +225,16 @@ public void testGetAdmittedPatients_200() throws Exception { String searchTerms = ""; when(admissionManagerMock.getAdmittedPatients(any(), any(), any(String.class))) - .thenReturn(admittedPatients); + .thenReturn(admittedPatients); MvcResult result = this.mockMvc - .perform(get(request, searchTerms, null, null) - .contentType(MediaType.APPLICATION_JSON)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(PatientHelper.asJsonString(admittedMapper.map2DTOList(admittedPatients))))) - .andReturn(); + .perform(get(request, searchTerms, null, null) + .contentType(MediaType.APPLICATION_JSON)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(PatientHelper.asJsonString(admittedMapper.map2DTOList(admittedPatients))))) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -270,46 +246,46 @@ public void testGetPatientAdmissions_200() throws Exception { Patient patient = PatientHelper.setup(); when(patientManagerMock.getPatientById(patientCode)) - .thenReturn(patient); + .thenReturn(patient); List listAdmissions = AdmissionHelper.setupAdmissionList(2); when(admissionManagerMock.getAdmissions(patient)) - .thenReturn(listAdmissions); + .thenReturn(listAdmissions); MvcResult result = this.mockMvc - .perform(get(request, patientCode) - .contentType(MediaType.APPLICATION_JSON)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(AdmissionHelper.asJsonString(admissionMapper.map2DTOList(listAdmissions))))) - .andReturn(); + .perform(get(request, patientCode) + .contentType(MediaType.APPLICATION_JSON)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(AdmissionHelper.asJsonString(admissionMapper.map2DTOList(listAdmissions))))) + .andReturn(); LOGGER.debug("result: {}", result); } @Test - public void testGetNextYProg_200() throws Exception { + public void testGetNextYProgressiveId_200() throws Exception { String request = "/admissions/getNextProgressiveIdInYear"; String wardCode = "1"; when(wardManagerMock.isCodePresent(wardCode)) - .thenReturn(true); + .thenReturn(true); - Integer nextYProg = 1; + Integer nextYProgressiveId = 1; when(admissionManagerMock.getNextYProg(wardCode)) - .thenReturn(nextYProg); + .thenReturn(nextYProgressiveId); MvcResult result = this.mockMvc - .perform( - get(request) - .param("wardcode", wardCode) - .contentType(MediaType.APPLICATION_JSON)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(nextYProg.toString()))) - .andReturn(); + .perform( + get(request) + .param("wardcode", wardCode) + .contentType(MediaType.APPLICATION_JSON)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(nextYProgressiveId.toString()))) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -320,20 +296,20 @@ public void testGetUsedWardBed_200() throws Exception { String wardCode = "1"; when(wardManagerMock.isCodePresent(wardCode)) - .thenReturn(true); + .thenReturn(true); Integer bed = 1012; when(admissionManagerMock.getUsedWardBed(wardCode)) - .thenReturn(bed); + .thenReturn(bed); MvcResult result = this.mockMvc - .perform(get(request, wardCode) - .contentType(MediaType.APPLICATION_JSON)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(bed.toString()))) - .andReturn(); + .perform(get(request, wardCode) + .contentType(MediaType.APPLICATION_JSON)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(bed.toString()))) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -345,16 +321,16 @@ public void testDeleteAdmission_200() throws Exception { Admission admission = AdmissionHelper.setup(); when(admissionManagerMock.getAdmission(id)) - .thenReturn(admission); + .thenReturn(admission); this.mockMvc - .perform( - delete(request, id) - .contentType(MediaType.APPLICATION_JSON)) - .andDo(log()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString("true"))) - .andReturn(); + .perform( + delete(request, id) + .contentType(MediaType.APPLICATION_JSON)) + .andDo(log()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("true"))) + .andReturn(); } @Test @@ -386,14 +362,14 @@ public void testDischargeAdmission_200() throws Exception { AdmissionDTO admissionDTO = admissionMapper.map2DTO(admission); this.mockMvc - .perform( - post(request) - .param("patientCode", patientCode.toString()) - .contentType(MediaType.APPLICATION_JSON) - .content(AdmissionHelper.asJsonString(admissionDTO))) - .andDo(log()) - .andExpect(status().isOk()) - .andReturn(); + .perform( + post(request) + .param("patientCode", patientCode.toString()) + .contentType(MediaType.APPLICATION_JSON) + .content(Objects.requireNonNull(AdmissionHelper.asJsonString(admissionDTO)))) + .andDo(log()) + .andExpect(status().isOk()) + .andReturn(); } @Test @@ -408,41 +384,41 @@ public void testNewAdmissions_201() throws Exception { Admission newAdmission = admissionMapper.map2Model(body); when(admissionManagerMock.newAdmissionReturnKey(newAdmission)) - .thenReturn(id); + .thenReturn(id); List wardList = WardHelper.setupWardList(2); when(wardManagerMock.getWards()) - .thenReturn(wardList); + .thenReturn(wardList); List admissionTypeList = AdmissionTypeDTOHelper.setupAdmissionTypeList(3); when(admissionManagerMock.getAdmissionType()) - .thenReturn(admissionTypeList); + .thenReturn(admissionTypeList); Patient patient = PatientHelper.setup(); patient.setCode(code); when(patientManagerMock.getPatientById(body.getPatient().getCode())) - .thenReturn(patient); + .thenReturn(patient); List diseaseList = DiseaseHelper.setupDiseaseList(3); when(diseaseManagerMock.getDiseaseAll()) - .thenReturn(diseaseList); + .thenReturn(diseaseList); List operationsList = OperationHelper.setupOperationList(3); when(operationManagerMock.getOperation()) - .thenReturn(operationsList); + .thenReturn(operationsList); List disTypes = DischargeTypeHelper.setupDischargeTypeList(3); when(admissionManagerMock.getDischargeType()) - .thenReturn(disTypes); + .thenReturn(disTypes); MvcResult result = this.mockMvc - .perform(post(request) - .contentType(MediaType.APPLICATION_JSON) - .content(AdmissionHelper.asJsonString(body))) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isCreated()) - .andReturn(); + .perform(post(request) + .contentType(MediaType.APPLICATION_JSON) + .content(Objects.requireNonNull(AdmissionHelper.asJsonString(body)))) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isCreated()) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -459,51 +435,51 @@ public void testUpdateAdmissions() throws Exception { Admission update = admissionMapper.map2Model(body); when(admissionManagerMock.getAdmission(body.getId())) - .thenReturn(old); + .thenReturn(old); List wardList = WardHelper.setupWardList(2); when(wardManagerMock.getWards()) - .thenReturn(wardList); + .thenReturn(wardList); List admissionTypeList = AdmissionTypeDTOHelper.setupAdmissionTypeList(3); when(admissionManagerMock.getAdmissionType()) - .thenReturn(admissionTypeList); + .thenReturn(admissionTypeList); Patient patient = PatientHelper.setup(); patient.setCode(code); when(patientManagerMock.getPatientById(body.getPatient().getCode())) - .thenReturn(patient); + .thenReturn(patient); when(patientManagerMock.getPatientById(body.getPatient().getCode())) - .thenReturn(patient); + .thenReturn(patient); List diseaseList = DiseaseHelper.setupDiseaseList(3); when(diseaseManagerMock.getDiseaseAll()) - .thenReturn(diseaseList); + .thenReturn(diseaseList); List operationsList = OperationHelper.setupOperationList(3); when(operationManagerMock.getOperation()) - .thenReturn(operationsList); + .thenReturn(operationsList); List disTypes = DischargeTypeHelper.setupDischargeTypeList(3); when(admissionManagerMock.getDischargeType()) - .thenReturn(disTypes); + .thenReturn(disTypes); - List pregTTypes = PregnantTreatmentTypeHelper.setupPregnantTreatmentTypeList(3); - when(pregTraitTypeManagerMock.getPregnantTreatmentType()) - .thenReturn(pregTTypes); + List pregnancyTreatmentTypes = PregnantTreatmentTypeHelper.setupPregnantTreatmentTypeList(3); + when(pregnancyTreatmentTypeManagerMock.getPregnantTreatmentType()) + .thenReturn(pregnancyTreatmentTypes); when(admissionManagerMock.updateAdmission(update)) - .thenReturn(update); + .thenReturn(update); MvcResult result = this.mockMvc - .perform(put(request) - .contentType(MediaType.APPLICATION_JSON) - .content(AdmissionHelper.asJsonString(body))) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andReturn(); + .perform(put(request) + .contentType(MediaType.APPLICATION_JSON) + .content(Objects.requireNonNull(AdmissionHelper.asJsonString(body)))) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andReturn(); LOGGER.debug("result: {}", result); } diff --git a/src/test/java/org/isf/admtype/rest/AdmissionTypeControllerTest.java b/src/test/java/org/isf/admtype/rest/AdmissionTypeControllerTest.java index ecff577df..88d4f9f28 100644 --- a/src/test/java/org/isf/admtype/rest/AdmissionTypeControllerTest.java +++ b/src/test/java/org/isf/admtype/rest/AdmissionTypeControllerTest.java @@ -31,6 +31,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.Objects; import org.isf.admtype.data.AdmissionTypeDTOHelper; import org.isf.admtype.dto.AdmissionTypeDTO; @@ -59,7 +60,7 @@ public class AdmissionTypeControllerTest { private static final Logger LOGGER = LoggerFactory.getLogger(AdmissionTypeControllerTest.class); @Mock - protected AdmissionTypeBrowserManager admtManagerMock; + protected AdmissionTypeBrowserManager admissionTypeManagerMock; protected AdmissionTypeMapper admissionTypemapper = new AdmissionTypeMapper(); @@ -71,9 +72,9 @@ public class AdmissionTypeControllerTest { public void setup() { closeable = MockitoAnnotations.openMocks(this); this.mockMvc = MockMvcBuilders - .standaloneSetup(new AdmissionTypeController(admtManagerMock, admissionTypemapper)) - .setControllerAdvice(new OHResponseEntityExceptionHandler()) - .build(); + .standaloneSetup(new AdmissionTypeController(admissionTypeManagerMock, admissionTypemapper)) + .setControllerAdvice(new OHResponseEntityExceptionHandler()) + .build(); ModelMapper modelMapper = new ModelMapper(); modelMapper.addConverter(new BlobToByteArrayConverter()); modelMapper.addConverter(new ByteArrayToBlobConverter()); @@ -90,25 +91,23 @@ public void testNewAdmissionType_201() throws Exception { String request = "/admissiontypes"; AdmissionTypeDTO body = AdmissionTypeDTOHelper.setup(admissionTypemapper); - boolean isCreated = true; - AdmissionType admissionType = new AdmissionType("ZZ", "aDescription"); - when(admtManagerMock.newAdmissionType(admissionType)) - .thenReturn(admissionType); + when(admissionTypeManagerMock.newAdmissionType(admissionType)) + .thenReturn(admissionType); - when(admtManagerMock.isCodePresent(body.getCode())) - .thenReturn(true); + when(admissionTypeManagerMock.isCodePresent(body.getCode())) + .thenReturn(true); MvcResult result = this.mockMvc - .perform(post(request) - .contentType(MediaType.APPLICATION_JSON) - .content(AdmissionTypeDTOHelper.asJsonString(body)) - ) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isCreated()) - .andReturn(); + .perform(post(request) + .contentType(MediaType.APPLICATION_JSON) + .content(Objects.requireNonNull(AdmissionTypeDTOHelper.asJsonString(body))) + ) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isCreated()) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -119,21 +118,21 @@ public void testUpdateAdmissionType_200() throws Exception { AdmissionTypeDTO body = AdmissionTypeDTOHelper.setup(admissionTypemapper); AdmissionType admissionType = new AdmissionType("ZZ", "aDescription"); - when(admtManagerMock.isCodePresent(admissionType.getCode())) - .thenReturn(true); + when(admissionTypeManagerMock.isCodePresent(admissionType.getCode())) + .thenReturn(true); - when(admtManagerMock.updateAdmissionType(admissionType)) - .thenReturn(admissionType); + when(admissionTypeManagerMock.updateAdmissionType(admissionType)) + .thenReturn(admissionType); MvcResult result = this.mockMvc - .perform(put(request) - .contentType(MediaType.APPLICATION_JSON) - .content(AdmissionTypeDTOHelper.asJsonString(body)) - ) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andReturn(); + .perform(put(request) + .contentType(MediaType.APPLICATION_JSON) + .content(Objects.requireNonNull(AdmissionTypeDTOHelper.asJsonString(body))) + ) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -143,17 +142,17 @@ public void testGetAdmissionTypes_200() throws Exception { String request = "/admissiontypes"; AdmissionType admissionType = new AdmissionType("ZZ", "aDescription"); - List admtFounds = new ArrayList<>(); - admtFounds.add(admissionType); - when(admtManagerMock.getAdmissionType()) - .thenReturn(admtFounds); + List admissionTypesFound = new ArrayList<>(); + admissionTypesFound.add(admissionType); + when(admissionTypeManagerMock.getAdmissionType()) + .thenReturn(admissionTypesFound); MvcResult result = this.mockMvc - .perform(get(request)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andReturn(); + .perform(get(request)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -164,21 +163,21 @@ public void testDeleteAdmissionType_200() throws Exception { AdmissionTypeDTO body = AdmissionTypeDTOHelper.setup(admissionTypemapper); String code = body.getCode(); - when(admtManagerMock.isCodePresent(code)) - .thenReturn(true); + when(admissionTypeManagerMock.isCodePresent(code)) + .thenReturn(true); AdmissionType admissionType = new AdmissionType("ZZ", "aDescription"); - ArrayList admtFounds = new ArrayList<>(); - admtFounds.add(admissionType); - when(admtManagerMock.getAdmissionType()) - .thenReturn(admtFounds); + ArrayList admissionTypesFound = new ArrayList<>(); + admissionTypesFound.add(admissionType); + when(admissionTypeManagerMock.getAdmissionType()) + .thenReturn(admissionTypesFound); MvcResult result = this.mockMvc - .perform(delete(request, code)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andReturn(); + .perform(delete(request, code)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andReturn(); LOGGER.debug("result: {}", result); } diff --git a/src/test/java/org/isf/agetype/rest/AgeTypeControllerTest.java b/src/test/java/org/isf/agetype/rest/AgeTypeControllerTest.java index 448ed7d9e..d2c428933 100644 --- a/src/test/java/org/isf/agetype/rest/AgeTypeControllerTest.java +++ b/src/test/java/org/isf/agetype/rest/AgeTypeControllerTest.java @@ -72,9 +72,9 @@ public class AgeTypeControllerTest { public void setup() { closeable = MockitoAnnotations.openMocks(this); this.mockMvc = MockMvcBuilders - .standaloneSetup(new AgeTypeController(ageTypeManagerMock, ageTypeMapper)) - .setControllerAdvice(new OHResponseEntityExceptionHandler()) - .build(); + .standaloneSetup(new AgeTypeController(ageTypeManagerMock, ageTypeMapper)) + .setControllerAdvice(new OHResponseEntityExceptionHandler()) + .build(); ModelMapper modelMapper = new ModelMapper(); modelMapper.addConverter(new BlobToByteArrayConverter()); modelMapper.addConverter(new ByteArrayToBlobConverter()); @@ -94,15 +94,15 @@ public void testGetAllAgeTypes_200() throws Exception { List parsedResults = ageTypeMapper.map2DTOList(results); when(ageTypeManagerMock.getAgeType()) - .thenReturn(results); + .thenReturn(results); MvcResult result = this.mockMvc - .perform(get(request)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(AgeTypeHelper.getObjectMapper().writeValueAsString(parsedResults)))) - .andReturn(); + .perform(get(request)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(AgeTypeHelper.getObjectMapper().writeValueAsString(parsedResults)))) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -116,17 +116,17 @@ public void testUpdateAgeType_200() throws Exception { ageTypes.add(AgeTypeHelper.setup()); when(ageTypeManagerMock.updateAgeType(ageTypes)) - .thenReturn(ageTypes); + .thenReturn(ageTypes); MvcResult result = this.mockMvc - .perform(put(request) - .contentType(MediaType.APPLICATION_JSON) - .content(Objects.requireNonNull(AgeTypeHelper.asJsonString(body))) - ) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andReturn(); + .perform(put(request) + .contentType(MediaType.APPLICATION_JSON) + .content(Objects.requireNonNull(AgeTypeHelper.asJsonString(body))) + ) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -139,16 +139,16 @@ public void testGetAgeTypeCodeByAge_200() throws Exception { String responseString = "resultString"; when(ageTypeManagerMock.getTypeByAge(age)) - .thenReturn(responseString); + .thenReturn(responseString); MvcResult result = this.mockMvc - .perform(get(request, age)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(responseString))) - .andExpect(content().string(containsString("code"))) - .andReturn(); + .perform(get(request, age)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(responseString))) + .andExpect(content().string(containsString("code"))) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -161,15 +161,15 @@ public void testGetAgeTypeByIndex_200() throws Exception { AgeTypeDTO ageTypeDTO = ageTypeMapper.map2DTO(ageType); when(ageTypeManagerMock.getTypeByCode(index)) - .thenReturn(ageType); + .thenReturn(ageType); MvcResult result = this.mockMvc - .perform(get(request, index)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(AgeTypeHelper.getObjectMapper().writeValueAsString(ageTypeDTO)))) - .andReturn(); + .perform(get(request, index)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(AgeTypeHelper.getObjectMapper().writeValueAsString(ageTypeDTO)))) + .andReturn(); LOGGER.debug("result: {}", result); } diff --git a/src/test/java/org/isf/disctype/rest/DischargeTypeControllerTest.java b/src/test/java/org/isf/disctype/rest/DischargeTypeControllerTest.java index 5416e5724..10f7666f1 100644 --- a/src/test/java/org/isf/disctype/rest/DischargeTypeControllerTest.java +++ b/src/test/java/org/isf/disctype/rest/DischargeTypeControllerTest.java @@ -33,6 +33,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.Objects; import org.isf.disctype.data.DischargeTypeHelper; import org.isf.disctype.dto.DischargeTypeDTO; @@ -73,9 +74,9 @@ public class DischargeTypeControllerTest { public void setup() { closeable = MockitoAnnotations.openMocks(this); this.mockMvc = MockMvcBuilders - .standaloneSetup(new DischargeTypeController(discTypeManagerMock, dischargeTypeMapper)) - .setControllerAdvice(new OHResponseEntityExceptionHandler()) - .build(); + .standaloneSetup(new DischargeTypeController(discTypeManagerMock, dischargeTypeMapper)) + .setControllerAdvice(new OHResponseEntityExceptionHandler()) + .build(); ModelMapper modelMapper = new ModelMapper(); modelMapper.addConverter(new BlobToByteArrayConverter()); modelMapper.addConverter(new ByteArrayToBlobConverter()); @@ -95,46 +96,46 @@ public void testNewDischargeType_201() throws Exception { DischargeTypeDTO body = dischargeTypeMapper.map2DTO(dischargeType); when(discTypeManagerMock.newDischargeType(dischargeTypeMapper.map2Model(body))) - .thenReturn(dischargeType); + .thenReturn(dischargeType); when(discTypeManagerMock.isCodePresent(dischargeType.getCode())) - .thenReturn(true); + .thenReturn(true); MvcResult result = this.mockMvc - .perform(post(request) - .contentType(MediaType.APPLICATION_JSON) - .content(DischargeTypeHelper.asJsonString(body)) - ) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isCreated()) - .andReturn(); + .perform(post(request) + .contentType(MediaType.APPLICATION_JSON) + .content(Objects.requireNonNull(DischargeTypeHelper.asJsonString(body))) + ) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isCreated()) + .andReturn(); LOGGER.debug("result: {}", result); } @Test - public void testUpdateDischargeTypet_200() throws Exception { + public void testUpdateDischargeType_200() throws Exception { String request = "/dischargetypes"; String code = "ZZ"; DischargeType dischargeType = DischargeTypeHelper.setup(code); DischargeTypeDTO body = dischargeTypeMapper.map2DTO(dischargeType); when(discTypeManagerMock.isCodePresent(body.getCode())) - .thenReturn(true); + .thenReturn(true); when(discTypeManagerMock.updateDischargeType(dischargeTypeMapper.map2Model(body))) - .thenReturn(dischargeType); + .thenReturn(dischargeType); MvcResult result = this.mockMvc - .perform(put(request) - .contentType(MediaType.APPLICATION_JSON) - .content(DischargeTypeHelper.asJsonString(body)) - ) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andReturn(); + .perform(put(request) + .contentType(MediaType.APPLICATION_JSON) + .content(Objects.requireNonNull(DischargeTypeHelper.asJsonString(body))) + ) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -144,20 +145,20 @@ public void testGetDischargeTypes_200() throws Exception { String request = "/dischargetypes"; DischargeType dischargeType = new DischargeType("ZZ", "aDescription"); - List dischTypes = new ArrayList<>(); - dischTypes.add(dischargeType); + List dischargeTypes = new ArrayList<>(); + dischargeTypes.add(dischargeType); when(discTypeManagerMock.getDischargeType()) - .thenReturn(dischTypes); + .thenReturn(dischargeTypes); - List expectedDischTypeDTOs = dischargeTypeMapper.map2DTOList(dischTypes); + List expectedDischargeTypeDTOs = dischargeTypeMapper.map2DTOList(dischargeTypes); MvcResult result = this.mockMvc - .perform(get(request)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(DischargeTypeHelper.getObjectMapper().writeValueAsString(expectedDischTypeDTOs)))) - .andReturn(); + .perform(get(request)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(DischargeTypeHelper.getObjectMapper().writeValueAsString(expectedDischargeTypeDTOs)))) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -169,22 +170,22 @@ public void testDeleteDischargeType_200() throws Exception { DischargeTypeDTO body = dischargeTypeMapper.map2DTO(DischargeTypeHelper.setup(code)); when(discTypeManagerMock.isCodePresent(body.getCode())) - .thenReturn(true); + .thenReturn(true); DischargeType dischargeType = new DischargeType("ZZ", "aDescription"); - List dischTypeFounds = new ArrayList<>(); - dischTypeFounds.add(dischargeType); + List dischargeTypeFounds = new ArrayList<>(); + dischargeTypeFounds.add(dischargeType); when(discTypeManagerMock.getDischargeType()) - .thenReturn(dischTypeFounds); + .thenReturn(dischargeTypeFounds); String isDeleted = "true"; MvcResult result = this.mockMvc - .perform(delete(request, code)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(isDeleted))) - .andReturn(); + .perform(delete(request, code)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(isDeleted))) + .andReturn(); LOGGER.debug("result: {}", result); } diff --git a/src/test/java/org/isf/disease/rest/DiseaseControllerTest.java b/src/test/java/org/isf/disease/rest/DiseaseControllerTest.java index 278d7e30b..7a223436f 100644 --- a/src/test/java/org/isf/disease/rest/DiseaseControllerTest.java +++ b/src/test/java/org/isf/disease/rest/DiseaseControllerTest.java @@ -32,6 +32,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.List; +import java.util.Objects; import org.isf.disease.data.DiseaseHelper; import org.isf.disease.dto.DiseaseDTO; @@ -62,7 +63,7 @@ public class DiseaseControllerTest { @Mock private DiseaseBrowserManager diseaseBrowserManagerMock; - private DiseaseMapper diseaseMapper = new DiseaseMapper(); + private final DiseaseMapper diseaseMapper = new DiseaseMapper(); private MockMvc mockMvc; @@ -72,9 +73,9 @@ public class DiseaseControllerTest { public void setup() { closeable = MockitoAnnotations.openMocks(this); this.mockMvc = MockMvcBuilders - .standaloneSetup(new DiseaseController(diseaseBrowserManagerMock, diseaseMapper)) - .setControllerAdvice(new OHResponseEntityExceptionHandler()) - .build(); + .standaloneSetup(new DiseaseController(diseaseBrowserManagerMock, diseaseMapper)) + .setControllerAdvice(new OHResponseEntityExceptionHandler()) + .build(); ModelMapper modelMapper = new ModelMapper(); modelMapper.addConverter(new BlobToByteArrayConverter()); modelMapper.addConverter(new ByteArrayToBlobConverter()); @@ -92,14 +93,14 @@ public void testGetDiseasesOpd_200() throws Exception { List diseases = DiseaseHelper.setupDiseaseList(3); when(diseaseBrowserManagerMock.getDiseaseOpd()) - .thenReturn(diseases); + .thenReturn(diseases); MvcResult result = this.mockMvc - .perform(get(request)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andReturn(); + .perform(get(request)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -112,15 +113,15 @@ public void testGetDiseasesOpdByCode_200() throws Exception { List diseases = DiseaseHelper.setupDiseaseList(3); when(diseaseBrowserManagerMock.getDiseaseOpd(typeCode)) - .thenReturn(diseases); + .thenReturn(diseases); MvcResult result = this.mockMvc - .perform(get(request, typeCode)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(DiseaseHelper.getObjectMapper().writeValueAsString(diseaseMapper.map2DTOList(diseases))))) - .andReturn(); + .perform(get(request, typeCode)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(DiseaseHelper.getObjectMapper().writeValueAsString(diseaseMapper.map2DTOList(diseases))))) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -131,15 +132,15 @@ public void testGetDiseasesIpdOut_200() throws Exception { List diseases = DiseaseHelper.setupDiseaseList(3); when(diseaseBrowserManagerMock.getDiseaseIpdOut()) - .thenReturn(diseases); + .thenReturn(diseases); MvcResult result = this.mockMvc - .perform(get(request)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(DiseaseHelper.getObjectMapper().writeValueAsString(diseaseMapper.map2DTOList(diseases))))) - .andReturn(); + .perform(get(request)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(DiseaseHelper.getObjectMapper().writeValueAsString(diseaseMapper.map2DTOList(diseases))))) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -152,15 +153,15 @@ public void testGetDiseasesIpdOutByCode_200() throws Exception { List diseases = DiseaseHelper.setupDiseaseList(3); when(diseaseBrowserManagerMock.getDiseaseIpdOut(typeCode)) - .thenReturn(diseases); + .thenReturn(diseases); MvcResult result = this.mockMvc - .perform(get(request, typeCode)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(DiseaseHelper.getObjectMapper().writeValueAsString(diseaseMapper.map2DTOList(diseases))))) - .andReturn(); + .perform(get(request, typeCode)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(DiseaseHelper.getObjectMapper().writeValueAsString(diseaseMapper.map2DTOList(diseases))))) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -172,15 +173,15 @@ public void testGetDiseasesIpdIn_200() throws Exception { List diseases = DiseaseHelper.setupDiseaseList(3); when(diseaseBrowserManagerMock.getDiseaseIpdIn()) - .thenReturn(diseases); + .thenReturn(diseases); MvcResult result = this.mockMvc - .perform(get(request)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(DiseaseHelper.getObjectMapper().writeValueAsString(diseaseMapper.map2DTOList(diseases))))) - .andReturn(); + .perform(get(request)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(DiseaseHelper.getObjectMapper().writeValueAsString(diseaseMapper.map2DTOList(diseases))))) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -193,15 +194,15 @@ public void testGetDiseasesIpdInByCode_200() throws Exception { List diseases = DiseaseHelper.setupDiseaseList(3); when(diseaseBrowserManagerMock.getDiseaseIpdOut(typeCode)) - .thenReturn(diseases); + .thenReturn(diseases); MvcResult result = this.mockMvc - .perform(get(request, typeCode)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(DiseaseHelper.getObjectMapper().writeValueAsString(diseaseMapper.map2DTOList(diseases))))) - .andReturn(); + .perform(get(request, typeCode)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(DiseaseHelper.getObjectMapper().writeValueAsString(diseaseMapper.map2DTOList(diseases))))) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -212,15 +213,15 @@ public void testGetDiseases_200() throws Exception { List diseases = DiseaseHelper.setupDiseaseList(3); when(diseaseBrowserManagerMock.getDisease()) - .thenReturn(diseases); + .thenReturn(diseases); MvcResult result = this.mockMvc - .perform(get(request)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(DiseaseHelper.getObjectMapper().writeValueAsString(diseaseMapper.map2DTOList(diseases))))) - .andReturn(); + .perform(get(request)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(DiseaseHelper.getObjectMapper().writeValueAsString(diseaseMapper.map2DTOList(diseases))))) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -233,15 +234,15 @@ public void testGetDiseasesString_200() throws Exception { List diseases = DiseaseHelper.setupDiseaseList(3); when(diseaseBrowserManagerMock.getDisease(typeCode)) - .thenReturn(diseases); + .thenReturn(diseases); MvcResult result = this.mockMvc - .perform(get(request, typeCode)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(DiseaseHelper.getObjectMapper().writeValueAsString(diseaseMapper.map2DTOList(diseases))))) - .andReturn(); + .perform(get(request, typeCode)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(DiseaseHelper.getObjectMapper().writeValueAsString(diseaseMapper.map2DTOList(diseases))))) + .andReturn(); LOGGER.debug("result: {}", result); @@ -253,15 +254,15 @@ public void testGetAllDiseases_200() throws Exception { List diseases = DiseaseHelper.setupDiseaseList(3); when(diseaseBrowserManagerMock.getDiseaseAll()) - .thenReturn(diseases); + .thenReturn(diseases); MvcResult result = this.mockMvc - .perform(get(request)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(DiseaseHelper.getObjectMapper().writeValueAsString(diseaseMapper.map2DTOList(diseases))))) - .andReturn(); + .perform(get(request)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(DiseaseHelper.getObjectMapper().writeValueAsString(diseaseMapper.map2DTOList(diseases))))) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -274,15 +275,15 @@ public void testGetDiseaseByCode() throws Exception { Disease disease = DiseaseHelper.setup(); when(diseaseBrowserManagerMock.getDiseaseByCode(code)) - .thenReturn(disease); + .thenReturn(disease); MvcResult result = this.mockMvc - .perform(get(request, code)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(DiseaseHelper.getObjectMapper().writeValueAsString(diseaseMapper.map2DTO(disease))))) - .andReturn(); + .perform(get(request, code)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(DiseaseHelper.getObjectMapper().writeValueAsString(diseaseMapper.map2DTO(disease))))) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -295,23 +296,23 @@ public void testNewDisease_200() throws Exception { DiseaseDTO body = diseaseMapper.map2DTO(disease); when(diseaseBrowserManagerMock.isCodePresent(disease.getCode())) - .thenReturn(false); + .thenReturn(false); when(diseaseBrowserManagerMock.descriptionControl(disease.getDescription(), disease.getType().getCode())) - .thenReturn(false); + .thenReturn(false); when(diseaseBrowserManagerMock.newDisease(disease)) - .thenReturn(disease); + .thenReturn(disease); MvcResult result = this.mockMvc - .perform(post(request) - .contentType(MediaType.APPLICATION_JSON) - .content(DiseaseHelper.asJsonString(body)) - ) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isCreated()) - .andReturn(); + .perform(post(request) + .contentType(MediaType.APPLICATION_JSON) + .content(Objects.requireNonNull(DiseaseHelper.asJsonString(body))) + ) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isCreated()) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -324,20 +325,20 @@ public void testUpdateDisease_201() throws Exception { DiseaseDTO body = diseaseMapper.map2DTO(disease); when(diseaseBrowserManagerMock.isCodePresent(disease.getCode())) - .thenReturn(true); + .thenReturn(true); when(diseaseBrowserManagerMock.updateDisease(disease)) - .thenReturn(disease); + .thenReturn(disease); MvcResult result = this.mockMvc - .perform(put(request) - .contentType(MediaType.APPLICATION_JSON) - .content(DiseaseHelper.asJsonString(body)) - ) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andReturn(); + .perform(put(request) + .contentType(MediaType.APPLICATION_JSON) + .content(Objects.requireNonNull(DiseaseHelper.asJsonString(body))) + ) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -352,19 +353,19 @@ public void testDeleteDisease() throws Exception { DiseaseDTO body = diseaseMapper.map2DTO(disease); when(diseaseBrowserManagerMock.getDiseaseByCode(code)) - .thenReturn(disease); + .thenReturn(disease); MvcResult result = this.mockMvc - .perform(delete(request, code) - .contentType(MediaType.APPLICATION_JSON) - .content(DiseaseHelper.asJsonString(body)) - ) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString("true"))) - - .andReturn(); + .perform(delete(request, code) + .contentType(MediaType.APPLICATION_JSON) + .content(Objects.requireNonNull(DiseaseHelper.asJsonString(body))) + ) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("true"))) + + .andReturn(); LOGGER.debug("result: {}", result); } diff --git a/src/test/java/org/isf/distype/rest/DiseaseTypeControllerTest.java b/src/test/java/org/isf/distype/rest/DiseaseTypeControllerTest.java index 286a22f18..ed9894f75 100644 --- a/src/test/java/org/isf/distype/rest/DiseaseTypeControllerTest.java +++ b/src/test/java/org/isf/distype/rest/DiseaseTypeControllerTest.java @@ -22,6 +22,7 @@ package org.isf.distype.rest; import static org.hamcrest.Matchers.containsString; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -32,6 +33,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.List; +import java.util.Objects; import org.isf.distype.data.DiseaseTypeHelper; import org.isf.distype.dto.DiseaseTypeDTO; @@ -72,9 +74,9 @@ public class DiseaseTypeControllerTest { public void setup() { closeable = MockitoAnnotations.openMocks(this); this.mockMvc = MockMvcBuilders - .standaloneSetup(new DiseaseTypeController(diseaseTypeBrowserManager, diseaseTypeMapper)) - .setControllerAdvice(new OHResponseEntityExceptionHandler()) - .build(); + .standaloneSetup(new DiseaseTypeController(diseaseTypeBrowserManager, diseaseTypeMapper)) + .setControllerAdvice(new OHResponseEntityExceptionHandler()) + .build(); ModelMapper modelMapper = new ModelMapper(); modelMapper.addConverter(new BlobToByteArrayConverter()); modelMapper.addConverter(new ByteArrayToBlobConverter()); @@ -95,15 +97,15 @@ public void testGetAllDiseaseTypes_200() throws Exception { List parsedResults = diseaseTypeMapper.map2DTOList(results); when(diseaseTypeBrowserManager.getDiseaseType()) - .thenReturn(results); + .thenReturn(results); MvcResult result = this.mockMvc - .perform(get(request)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(DiseaseTypeHelper.getObjectMapper().writeValueAsString(parsedResults)))) - .andReturn(); + .perform(get(request)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(DiseaseTypeHelper.getObjectMapper().writeValueAsString(parsedResults)))) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -116,20 +118,20 @@ public void testNewDiseaseType_201() throws Exception { DiseaseTypeDTO body = diseaseTypeMapper.map2DTO(diseaseType); when(diseaseTypeBrowserManager.isCodePresent(body.getCode())) - .thenReturn(false); + .thenReturn(false); when(diseaseTypeBrowserManager.newDiseaseType(diseaseTypeMapper.map2Model(body))) - .thenReturn(diseaseType); + .thenReturn(diseaseType); MvcResult result = this.mockMvc - .perform(post(request) - .contentType(MediaType.APPLICATION_JSON) - .content(DiseaseTypeHelper.asJsonString(body)) - ) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isCreated()) - .andReturn(); + .perform(post(request) + .contentType(MediaType.APPLICATION_JSON) + .content(Objects.requireNonNull(DiseaseTypeHelper.asJsonString(body))) + ) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isCreated()) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -143,20 +145,20 @@ public void testUpdateDiseaseType_200() throws Exception { DiseaseTypeDTO body = diseaseTypeMapper.map2DTO(diseaseType); when(diseaseTypeBrowserManager.isCodePresent(body.getCode())) - .thenReturn(true); + .thenReturn(true); when(diseaseTypeBrowserManager.updateDiseaseType(diseaseTypeMapper.map2Model(body))) - .thenReturn(diseaseType); + .thenReturn(diseaseType); MvcResult result = this.mockMvc - .perform(put(request) - .contentType(MediaType.APPLICATION_JSON) - .content(DiseaseTypeHelper.asJsonString(body)) - ) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andReturn(); + .perform(put(request) + .contentType(MediaType.APPLICATION_JSON) + .content(Objects.requireNonNull(DiseaseTypeHelper.asJsonString(body))) + ) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -168,17 +170,17 @@ public void testDeleteDiseaseType_200() throws Exception { DiseaseTypeDTO body = diseaseTypeMapper.map2DTO(DiseaseTypeHelper.setup(0)); String code = body.getCode(); - when(diseaseTypeBrowserManager.getDiseaseType()) - .thenReturn(DiseaseTypeHelper.setupDiseaseTypeList(1)); + when(diseaseTypeBrowserManager.getDiseaseType(anyString())) + .thenReturn(DiseaseTypeHelper.setupDiseaseTypeList(1).get(0)); String isDeleted = "true"; MvcResult result = this.mockMvc - .perform(delete(request, code)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(isDeleted))) - .andReturn(); + .perform(delete(request, code)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(isDeleted))) + .andReturn(); LOGGER.debug("result: {}", result); } diff --git a/src/test/java/org/isf/dlvrrestype/rest/DeliveryResultTypeControllerTest.java b/src/test/java/org/isf/dlvrrestype/rest/DeliveryResultTypeControllerTest.java index b934eccad..5aedc533b 100644 --- a/src/test/java/org/isf/dlvrrestype/rest/DeliveryResultTypeControllerTest.java +++ b/src/test/java/org/isf/dlvrrestype/rest/DeliveryResultTypeControllerTest.java @@ -33,6 +33,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.Objects; import org.isf.dlvrrestype.data.DeliveryResultTypeHelper; import org.isf.dlvrrestype.dto.DeliveryResultTypeDTO; @@ -73,9 +74,9 @@ public class DeliveryResultTypeControllerTest { public void setup() { closeable = MockitoAnnotations.openMocks(this); this.mockMvc = MockMvcBuilders - .standaloneSetup(new DeliveryResultTypeController(deliveryResultTypeBrowserManagerMock, deliveryResultTypeMapper)) - .setControllerAdvice(new OHResponseEntityExceptionHandler()) - .build(); + .standaloneSetup(new DeliveryResultTypeController(deliveryResultTypeBrowserManagerMock, deliveryResultTypeMapper)) + .setControllerAdvice(new OHResponseEntityExceptionHandler()) + .build(); ModelMapper modelMapper = new ModelMapper(); modelMapper.addConverter(new BlobToByteArrayConverter()); modelMapper.addConverter(new ByteArrayToBlobConverter()); @@ -98,20 +99,20 @@ public void testNewDeliveryResultType_201() throws Exception { results.add(deliveryResultType); when(deliveryResultTypeBrowserManagerMock.getDeliveryResultType()) - .thenReturn(results); + .thenReturn(results); when(deliveryResultTypeBrowserManagerMock.newDeliveryResultType(deliveryResultTypeMapper.map2Model(body))) - .thenReturn(deliveryResultType); + .thenReturn(deliveryResultType); MvcResult result = this.mockMvc - .perform(post(request) - .contentType(MediaType.APPLICATION_JSON) - .content(DeliveryResultTypeHelper.asJsonString(body)) - ) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isCreated()) - .andReturn(); + .perform(post(request) + .contentType(MediaType.APPLICATION_JSON) + .content(Objects.requireNonNull(DeliveryResultTypeHelper.asJsonString(body))) + ) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isCreated()) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -125,20 +126,20 @@ public void testUpdateDeliveryResultTypet_200() throws Exception { DeliveryResultTypeDTO body = deliveryResultTypeMapper.map2DTO(deliveryResultType); when(deliveryResultTypeBrowserManagerMock.isCodePresent(body.getCode())) - .thenReturn(true); + .thenReturn(true); when(deliveryResultTypeBrowserManagerMock.updateDeliveryResultType(deliveryResultTypeMapper.map2Model(body))) - .thenReturn(deliveryResultType); + .thenReturn(deliveryResultType); MvcResult result = this.mockMvc - .perform(put(request) - .contentType(MediaType.APPLICATION_JSON) - .content(DeliveryResultTypeHelper.asJsonString(body)) - ) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andReturn(); + .perform(put(request) + .contentType(MediaType.APPLICATION_JSON) + .content(Objects.requireNonNull(DeliveryResultTypeHelper.asJsonString(body))) + ) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -152,15 +153,15 @@ public void testGetDeliveryResultTypes_200() throws Exception { List dlvrrestTypeDTOs = deliveryResultTypeMapper.map2DTOList(results); when(deliveryResultTypeBrowserManagerMock.getDeliveryResultType()) - .thenReturn(results); + .thenReturn(results); MvcResult result = this.mockMvc - .perform(get(request)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(DeliveryResultTypeHelper.getObjectMapper().writeValueAsString(dlvrrestTypeDTOs)))) - .andReturn(); + .perform(get(request)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(DeliveryResultTypeHelper.getObjectMapper().writeValueAsString(dlvrrestTypeDTOs)))) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -173,19 +174,19 @@ public void testDeleteDeliveryResultType() throws Exception { String code = body.getCode(); when(deliveryResultTypeBrowserManagerMock.isCodePresent(code)) - .thenReturn(true); + .thenReturn(true); when(deliveryResultTypeBrowserManagerMock.getDeliveryResultType()) - .thenReturn(DeliveryResultTypeHelper.setupDeliveryResultTypeList(1)); + .thenReturn(DeliveryResultTypeHelper.setupDeliveryResultTypeList(1)); String isDeleted = "true"; MvcResult result = this.mockMvc - .perform(delete(request, code)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(isDeleted))) - .andReturn(); + .perform(delete(request, code)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(isDeleted))) + .andReturn(); LOGGER.debug("result: {}", result); } diff --git a/src/test/java/org/isf/dlvrtype/rest/DeliveryTypeControllerTest.java b/src/test/java/org/isf/dlvrtype/rest/DeliveryTypeControllerTest.java index 14575dd68..bc0bf5512 100644 --- a/src/test/java/org/isf/dlvrtype/rest/DeliveryTypeControllerTest.java +++ b/src/test/java/org/isf/dlvrtype/rest/DeliveryTypeControllerTest.java @@ -33,6 +33,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.Objects; import org.isf.dlvrtype.data.DeliveryTypeHelper; import org.isf.dlvrtype.dto.DeliveryTypeDTO; @@ -73,9 +74,9 @@ public class DeliveryTypeControllerTest { public void setup() { closeable = MockitoAnnotations.openMocks(this); this.mockMvc = MockMvcBuilders - .standaloneSetup(new DeliveryTypeController(deliveryTypeBrowserManagerMock, deliveryTypeMapper)) - .setControllerAdvice(new OHResponseEntityExceptionHandler()) - .build(); + .standaloneSetup(new DeliveryTypeController(deliveryTypeBrowserManagerMock, deliveryTypeMapper)) + .setControllerAdvice(new OHResponseEntityExceptionHandler()) + .build(); ModelMapper modelMapper = new ModelMapper(); modelMapper.addConverter(new BlobToByteArrayConverter()); modelMapper.addConverter(new ByteArrayToBlobConverter()); @@ -98,21 +99,20 @@ public void testNewDeliveryType_201() throws Exception { results.add(deliveryType); when(deliveryTypeBrowserManagerMock.getDeliveryType()) - .thenReturn(results); + .thenReturn(results); - boolean isCreated = true; when(deliveryTypeBrowserManagerMock.newDeliveryType(deliveryTypeMapper.map2Model(body))) - .thenReturn(deliveryType); + .thenReturn(deliveryType); MvcResult result = this.mockMvc - .perform(post(request) - .contentType(MediaType.APPLICATION_JSON) - .content(DeliveryTypeHelper.asJsonString(body)) - ) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isCreated()) - .andReturn(); + .perform(post(request) + .contentType(MediaType.APPLICATION_JSON) + .content(Objects.requireNonNull(DeliveryTypeHelper.asJsonString(body))) + ) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isCreated()) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -126,21 +126,20 @@ public void testUpdateDeliveryTypet_200() throws Exception { DeliveryTypeDTO body = deliveryTypeMapper.map2DTO(deliveryType); when(deliveryTypeBrowserManagerMock.isCodePresent(body.getCode())) - .thenReturn(true); + .thenReturn(true); - boolean isUpdated = true; when(deliveryTypeBrowserManagerMock.updateDeliveryType(deliveryTypeMapper.map2Model(body))) - .thenReturn(deliveryType); + .thenReturn(deliveryType); MvcResult result = this.mockMvc - .perform(put(request, "ZZ" + code) - .contentType(MediaType.APPLICATION_JSON) - .content(DeliveryTypeHelper.asJsonString(body)) - ) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andReturn(); + .perform(put(request, "ZZ" + code) + .contentType(MediaType.APPLICATION_JSON) + .content(Objects.requireNonNull(DeliveryTypeHelper.asJsonString(body))) + ) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -154,15 +153,15 @@ public void testGetDeliveryTypes_200() throws Exception { List dlvrrestTypeDTOs = deliveryTypeMapper.map2DTOList(results); when(deliveryTypeBrowserManagerMock.getDeliveryType()) - .thenReturn(results); + .thenReturn(results); MvcResult result = this.mockMvc - .perform(get(request)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(DeliveryTypeHelper.getObjectMapper().writeValueAsString(dlvrrestTypeDTOs)))) - .andReturn(); + .perform(get(request)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(DeliveryTypeHelper.getObjectMapper().writeValueAsString(dlvrrestTypeDTOs)))) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -175,19 +174,19 @@ public void testDeleteDeliveryType_200() throws Exception { String code = body.getCode(); when(deliveryTypeBrowserManagerMock.isCodePresent(code)) - .thenReturn(true); + .thenReturn(true); when(deliveryTypeBrowserManagerMock.getDeliveryType()) - .thenReturn(DeliveryTypeHelper.setupDeliveryTypeList(1)); + .thenReturn(DeliveryTypeHelper.setupDeliveryTypeList(1)); String isDeleted = "true"; MvcResult result = this.mockMvc - .perform(delete(request, code)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(isDeleted))) - .andReturn(); + .perform(delete(request, code)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(isDeleted))) + .andReturn(); LOGGER.debug("result: {}", result); } diff --git a/src/test/java/org/isf/lab/rest/LaboratoryControllerTest.java b/src/test/java/org/isf/lab/rest/LaboratoryControllerTest.java index 0ab85ad2b..8cec619aa 100644 --- a/src/test/java/org/isf/lab/rest/LaboratoryControllerTest.java +++ b/src/test/java/org/isf/lab/rest/LaboratoryControllerTest.java @@ -35,6 +35,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.Objects; import java.util.Optional; import org.isf.exa.manager.ExamBrowsingManager; @@ -42,7 +43,6 @@ import org.isf.lab.dto.LabWithRowsDTO; import org.isf.lab.dto.LaboratoryDTO; import org.isf.lab.manager.LabManager; -import org.isf.lab.mapper.LaboratoryForPrintMapper; import org.isf.lab.mapper.LaboratoryMapper; import org.isf.lab.mapper.LaboratoryRowMapper; import org.isf.lab.model.Laboratory; @@ -53,6 +53,7 @@ import org.isf.shared.exceptions.OHResponseEntityExceptionHandler; import org.isf.shared.mapper.converter.BlobToByteArrayConverter; import org.isf.shared.mapper.converter.ByteArrayToBlobConverter; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; @@ -83,24 +84,28 @@ public class LaboratoryControllerTest { protected LaboratoryRowMapper laboratoryRowMapper = new LaboratoryRowMapper(); - protected LaboratoryForPrintMapper laboratoryForPrintMapper = new LaboratoryForPrintMapper(); - private MockMvc mockMvc; + private AutoCloseable closeable; + @BeforeEach public void setup() { - MockitoAnnotations.initMocks(this); + closeable = MockitoAnnotations.openMocks(this); this.mockMvc = MockMvcBuilders - .standaloneSetup(new LaboratoryController(laboratoryManager, patientBrowserManager, examManager, laboratoryMapper, laboratoryRowMapper, - laboratoryForPrintMapper)) - .setControllerAdvice(new OHResponseEntityExceptionHandler()) - .build(); + .standaloneSetup(new LaboratoryController(laboratoryManager, patientBrowserManager, examManager, laboratoryMapper, laboratoryRowMapper)) + .setControllerAdvice(new OHResponseEntityExceptionHandler()) + .build(); ModelMapper modelMapper = new ModelMapper(); modelMapper.addConverter(new BlobToByteArrayConverter()); modelMapper.addConverter(new ByteArrayToBlobConverter()); ReflectionTestUtils.setField(laboratoryMapper, "modelMapper", modelMapper); } + @AfterEach + void closeService() throws Exception { + closeable.close(); + } + @Test public void testNewLaboratory_201() throws Exception { String request = "/laboratories"; @@ -125,13 +130,13 @@ public void testNewLaboratory_201() throws Exception { when(examManager.getExams()).thenReturn(Collections.singletonList(lab.getExam())); MvcResult result = this.mockMvc - .perform(post(request) - .content(LaboratoryHelper.asJsonString(labWithRowsDTO)) - .contentType(MediaType.APPLICATION_JSON)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isCreated()) - .andReturn(); + .perform(post(request) + .content(Objects.requireNonNull(LaboratoryHelper.asJsonString(labWithRowsDTO))) + .contentType(MediaType.APPLICATION_JSON)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isCreated()) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -163,13 +168,13 @@ public void testUpdateLaboratory_200() throws Exception { when(examManager.getExams()).thenReturn(Collections.singletonList(lab.getExam())); MvcResult result = this.mockMvc - .perform(put(request, lab.getCode()) - .content(LaboratoryHelper.asJsonString(labWithRowsDTO)) - .contentType(MediaType.APPLICATION_JSON)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andReturn(); + .perform(put(request, lab.getCode()) + .content(Objects.requireNonNull(LaboratoryHelper.asJsonString(labWithRowsDTO))) + .contentType(MediaType.APPLICATION_JSON)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -202,13 +207,13 @@ public void testGetLaboratory_200() throws Exception { when(patientBrowserManager.getPatientById(anyInt())).thenReturn(patient); when(examManager.getExams()).thenReturn(Collections.singletonList(lab.getExam())); MvcResult result = this.mockMvc - .perform(get(request, patient.getCode()) - .contentType(MediaType.APPLICATION_JSON)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andExpect(jsonPath("$[0].laboratoryDTO.exam.code").value(lab.getExam().getCode())) - .andReturn(); + .perform(get(request, patient.getCode()) + .contentType(MediaType.APPLICATION_JSON)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andExpect(jsonPath("$[0].laboratoryDTO.exam.code").value(lab.getExam().getCode())) + .andReturn(); LOGGER.debug("result: {}", result); } diff --git a/src/test/java/org/isf/login/rest/LoginControllerTest.java b/src/test/java/org/isf/login/rest/LoginControllerTest.java index 19f8eb84e..e08cf4f9e 100644 --- a/src/test/java/org/isf/login/rest/LoginControllerTest.java +++ b/src/test/java/org/isf/login/rest/LoginControllerTest.java @@ -31,6 +31,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.List; +import java.util.Objects; import jakarta.servlet.http.HttpSession; @@ -46,6 +47,7 @@ import org.isf.sessionaudit.manager.SessionAuditManager; import org.isf.shared.exceptions.OHResponseEntityExceptionHandler; import org.isf.users.data.UserHelper; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; @@ -81,16 +83,25 @@ public class LoginControllerTest { @Mock private UserBrowsingManager userManager; + private AutoCloseable closeable; + @BeforeEach public void setUp() { - MockitoAnnotations.openMocks(this); + closeable = MockitoAnnotations.openMocks(this); - LoginController loginController = new LoginController(httpSession, sessionAuditManager, tokenProvider, authenticationManager, userManager); + LoginController loginController = new LoginController( + httpSession, sessionAuditManager, tokenProvider, authenticationManager, userManager + ); this.mvc = MockMvcBuilders - .standaloneSetup(loginController) - .setControllerAdvice(new OHResponseEntityExceptionHandler()) - .build(); + .standaloneSetup(loginController) + .setControllerAdvice(new OHResponseEntityExceptionHandler()) + .build(); + } + + @AfterEach + void closeService() throws Exception { + closeable.close(); } @Test @@ -122,11 +133,11 @@ void testAuthenticateUser_Success() throws Exception { // Perform the login request mvc.perform(post("/auth/login") - .contentType(MediaType.APPLICATION_JSON) - .content(UserHelper.asJsonString(loginRequest))) - .andExpect(status().isOk()) - .andExpect(content().string(expectedJson)) - .andReturn(); + .contentType(MediaType.APPLICATION_JSON) + .content(Objects.requireNonNull(UserHelper.asJsonString(loginRequest)))) + .andExpect(status().isOk()) + .andExpect(content().string(Objects.requireNonNull(expectedJson))) + .andReturn(); } // TODO testAuthenticateUser_Failure @@ -153,12 +164,12 @@ void testRefreshToken_Success() throws Exception { // Perform POST request to refresh-token endpoint mvc.perform(post("/auth/refresh-token") - .accept(MediaType.APPLICATION_JSON) - .contentType(MediaType.APPLICATION_JSON) - .content(UserHelper.asJsonString(request))) - .andExpect(status().isOk()) - .andExpect(content().string(expectedJson)) - .andReturn(); + .accept(MediaType.APPLICATION_JSON) + .contentType(MediaType.APPLICATION_JSON) + .content(Objects.requireNonNull(UserHelper.asJsonString(request)))) + .andExpect(status().isOk()) + .andExpect(content().string(Objects.requireNonNull(expectedJson))) + .andReturn(); } @Test @@ -172,12 +183,12 @@ void testRefreshToken_Invalid() throws Exception { // Perform POST request to refresh-token endpoint mvc.perform( - post("/auth/refresh-token") - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON) - .content(UserHelper.asJsonString(request))) - .andExpect(status().isBadRequest()) - .andExpect(content().string(containsString("Invalid Refresh Token"))); + post("/auth/refresh-token") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(Objects.requireNonNull(UserHelper.asJsonString(request)))) + .andExpect(status().isBadRequest()) + .andExpect(content().string(containsString("Invalid Refresh Token"))); } @Test @@ -191,11 +202,11 @@ void testRefreshToken_JwtException() throws Exception { // Perform POST request to refresh-token endpoint mvc.perform( - post("/auth/refresh-token") - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON) - .content(UserHelper.asJsonString(request))) - .andExpect(content().string(containsString("Refresh token expired or invalid"))); + post("/auth/refresh-token") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(Objects.requireNonNull(UserHelper.asJsonString(request)))) + .andExpect(content().string(containsString("Refresh token expired or invalid"))); } } diff --git a/src/test/java/org/isf/opd/rest/OpdControllerTest.java b/src/test/java/org/isf/opd/rest/OpdControllerTest.java index 2120062b3..0c745f4dc 100644 --- a/src/test/java/org/isf/opd/rest/OpdControllerTest.java +++ b/src/test/java/org/isf/opd/rest/OpdControllerTest.java @@ -26,7 +26,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.log; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import org.isf.distype.manager.DiseaseTypeBrowserManager; +import java.util.Objects; + import org.isf.opd.data.OpdHelper; import org.isf.opd.dto.OpdDTO; import org.isf.opd.manager.OpdBrowserManager; @@ -75,9 +76,6 @@ public class OpdControllerTest { @Mock protected WardBrowserManager wardBrowserManager; - @Mock - protected DiseaseTypeBrowserManager diseaseTypeBrowserManagerMock; - private MockMvc mockMvc; private AutoCloseable closeable; @@ -86,10 +84,10 @@ public class OpdControllerTest { public void setup() { closeable = MockitoAnnotations.openMocks(this); this.mockMvc = MockMvcBuilders - .standaloneSetup(new OpdController(opdBrowserManagerMock, opdMapper, patientBrowserManagerMock, operationRowBrowserManagerMock, - opRowMapper, wardBrowserManager, diseaseTypeBrowserManagerMock)) - .setControllerAdvice(new OHResponseEntityExceptionHandler()) - .build(); + .standaloneSetup(new OpdController(opdBrowserManagerMock, opdMapper, patientBrowserManagerMock, operationRowBrowserManagerMock, + opRowMapper, wardBrowserManager)) + .setControllerAdvice(new OHResponseEntityExceptionHandler()) + .build(); ModelMapper modelMapper = new ModelMapper(); modelMapper.addConverter(new BlobToByteArrayConverter()); modelMapper.addConverter(new ByteArrayToBlobConverter()); @@ -118,13 +116,13 @@ public void testNewOpd_201() throws Exception { when(opdBrowserManagerMock.newOpd(opdMapper.map2Model(body))).thenReturn(opd); MvcResult result = this.mockMvc - .perform(post(request) - .contentType(MediaType.APPLICATION_JSON) - .content(OpdHelper.asJsonString(body))) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isCreated()) - .andReturn(); + .perform(post(request) + .contentType(MediaType.APPLICATION_JSON) + .content(Objects.requireNonNull(OpdHelper.asJsonString(body)))) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isCreated()) + .andReturn(); LOGGER.debug("result: {}", result); } diff --git a/src/test/java/org/isf/operation/rest/OperationControllerTest.java b/src/test/java/org/isf/operation/rest/OperationControllerTest.java index bf7d59e20..a825a77f6 100644 --- a/src/test/java/org/isf/operation/rest/OperationControllerTest.java +++ b/src/test/java/org/isf/operation/rest/OperationControllerTest.java @@ -32,12 +32,18 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.List; +import java.util.Objects; +import org.isf.admission.manager.AdmissionBrowserManager; +import org.isf.opd.mapper.OpdMapper; import org.isf.operation.data.OperationHelper; import org.isf.operation.dto.OperationDTO; import org.isf.operation.manager.OperationBrowserManager; +import org.isf.operation.manager.OperationRowBrowserManager; import org.isf.operation.mapper.OperationMapper; +import org.isf.operation.mapper.OperationRowMapper; import org.isf.operation.model.Operation; +import org.isf.patient.manager.PatientBrowserManager; import org.isf.shared.exceptions.OHResponseEntityExceptionHandler; import org.isf.shared.mapper.converter.BlobToByteArrayConverter; import org.isf.shared.mapper.converter.ByteArrayToBlobConverter; @@ -58,12 +64,27 @@ import com.fasterxml.jackson.databind.ObjectMapper; public class OperationControllerTest { - + private static final Logger LOGGER = LoggerFactory.getLogger(OperationControllerTest.class); @Mock protected OperationBrowserManager operationBrowserManagerMock; + @Mock + protected AdmissionBrowserManager admissionBrowserManager; + + @Mock + protected OperationRowBrowserManager operationRowBrowserManager; + + @Mock + protected PatientBrowserManager patientBrowserManager; + + @Mock + protected OpdMapper opdMapper; + + @Mock + protected OperationRowMapper operationRowMapper; + protected OperationMapper operationMapper = new OperationMapper(); private MockMvc mockMvc; @@ -74,9 +95,17 @@ public class OperationControllerTest { public void setup() { closeable = MockitoAnnotations.openMocks(this); this.mockMvc = MockMvcBuilders - .standaloneSetup(new OperationController(operationBrowserManagerMock, operationMapper)) - .setControllerAdvice(new OHResponseEntityExceptionHandler()) - .build(); + .standaloneSetup(new OperationController( + operationBrowserManagerMock, + admissionBrowserManager, + operationRowBrowserManager, + patientBrowserManager, + operationMapper, + opdMapper, + operationRowMapper + )) + .setControllerAdvice(new OHResponseEntityExceptionHandler()) + .build(); ModelMapper modelMapper = new ModelMapper(); modelMapper.addConverter(new BlobToByteArrayConverter()); modelMapper.addConverter(new ByteArrayToBlobConverter()); @@ -91,29 +120,29 @@ void closeService() throws Exception { @Test public void testNewOperation_201() throws Exception { String request = "/operations"; - + Operation operation = OperationHelper.setup(); OperationDTO body = operationMapper.map2DTO(operation); - String code = body.getCode(); + String code = body.getCode(); when(operationBrowserManagerMock.descriptionControl(body.getDescription(), body.getType().getCode())) - .thenReturn(false); + .thenReturn(false); when(operationBrowserManagerMock.newOperation(operationMapper.map2Model(body))) - .thenReturn(operation); + .thenReturn(operation); when(operationBrowserManagerMock.getOperationByCode(code)) - .thenReturn(operation); - + .thenReturn(operation); + MvcResult result = this.mockMvc - .perform(post(request) - .contentType(MediaType.APPLICATION_JSON) - .content(OperationHelper.asJsonString(body)) - ) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isCreated()) - .andReturn(); + .perform(post(request) + .contentType(MediaType.APPLICATION_JSON) + .content(Objects.requireNonNull(OperationHelper.asJsonString(body))) + ) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isCreated()) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -125,22 +154,22 @@ public void testUpdateOperation_200() throws Exception { Operation operation = OperationHelper.setup(); OperationDTO body = operationMapper.map2DTO(operation); - + when(operationBrowserManagerMock.isCodePresent(code)) - .thenReturn(true); + .thenReturn(true); when(operationBrowserManagerMock.updateOperation(operation)) - .thenReturn(operation); + .thenReturn(operation); MvcResult result = this.mockMvc - .perform(put(request, code) - .contentType(MediaType.APPLICATION_JSON) - .content(OperationHelper.asJsonString(body)) - ) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andReturn(); + .perform(put(request, code) + .contentType(MediaType.APPLICATION_JSON) + .content(Objects.requireNonNull(OperationHelper.asJsonString(body))) + ) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -154,15 +183,15 @@ public void testGetOperation_200() throws Exception { List operationDTOs = operationMapper.map2DTOList(results); when(operationBrowserManagerMock.getOperation()) - .thenReturn(results); + .thenReturn(results); MvcResult result = this.mockMvc - .perform(get(request)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(new ObjectMapper().writeValueAsString(operationDTOs)))) - .andReturn(); + .perform(get(request)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(new ObjectMapper().writeValueAsString(operationDTOs)))) + .andReturn(); LOGGER.debug("result: {}", result); } @@ -173,18 +202,18 @@ public void testDeleteOperation_200() throws Exception { Operation deleteOperation = OperationHelper.setup(); OperationDTO body = operationMapper.map2DTO(deleteOperation); String code = body.getCode(); - + when(operationBrowserManagerMock.getOperationByCode(code)) - .thenReturn(OperationHelper.setup()); + .thenReturn(OperationHelper.setup()); String isDeleted = "true"; MvcResult result = this.mockMvc - .perform(delete(request, code)) - .andDo(log()) - .andExpect(status().is2xxSuccessful()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(isDeleted))) - .andReturn(); + .perform(delete(request, code)) + .andDo(log()) + .andExpect(status().is2xxSuccessful()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(isDeleted))) + .andReturn(); LOGGER.debug("result: {}", result); } diff --git a/src/test/java/org/isf/patient/rest/PatientControllerTest.java b/src/test/java/org/isf/patient/rest/PatientControllerTest.java index 768d903ba..512f1b86b 100644 --- a/src/test/java/org/isf/patient/rest/PatientControllerTest.java +++ b/src/test/java/org/isf/patient/rest/PatientControllerTest.java @@ -39,6 +39,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.List; +import java.util.Objects; import java.util.Optional; import org.isf.admission.data.AdmissionHelper; @@ -93,7 +94,7 @@ public class PatientControllerTest { @Mock private PatientConsensusBrowserManager patientConsensusManagerMock; - private PatientMapper patientMapper = new PatientMapper(); + private final PatientMapper patientMapper = new PatientMapper(); private MockMvc mockMvc; @@ -103,10 +104,10 @@ public class PatientControllerTest { public void setup() { closeable = MockitoAnnotations.openMocks(this); this.mockMvc = MockMvcBuilders - .standaloneSetup(new PatientController(patientBrowserManagerMock, admissionBrowserManagerMock, patientMapper, - patientConsensusManagerMock)) - .setControllerAdvice(new OHResponseEntityExceptionHandler()) - .build(); + .standaloneSetup(new PatientController(patientBrowserManagerMock, admissionBrowserManagerMock, patientMapper, + patientConsensusManagerMock)) + .setControllerAdvice(new OHResponseEntityExceptionHandler()) + .build(); ModelMapper modelMapper = new ModelMapper(); PatientMapping.addMapping(modelMapper); modelMapper.addConverter(new BlobToByteArrayConverter()); @@ -122,20 +123,20 @@ void closeService() throws Exception { /** * Test method for {@link PatientController#newPatient(PatientDTO)}. * - * @throws Exception + * @throws Exception When error occurs */ @Test public void when_post_patients_is_call_without_contentType_header_then_HttpMediaTypeNotSupportedException() throws Exception { String request = "/patients"; MvcResult result = this.mockMvc - .perform(post(request).content(new byte[] { 'a', 'b', 'c' })) - .andDo(log()) - .andExpect(status().is4xxClientError()) - .andExpect(status().isUnsupportedMediaType()) - // TODO .andExpect(content().string(anyOf(nullValue(), equalTo("")))) - .andExpect(content().string(containsString("Unsupported Media Type"))) - .andReturn(); + .perform(post(request).content(new byte[] { 'a', 'b', 'c' })) + .andDo(log()) + .andExpect(status().is4xxClientError()) + .andExpect(status().isUnsupportedMediaType()) + // TODO .andExpect(content().string(anyOf(nullValue(), equalTo("")))) + .andExpect(content().string(containsString("Unsupported Media Type"))) + .andReturn(); Optional exception = Optional.ofNullable((HttpMediaTypeNotSupportedException) result.getResolvedException()); LOGGER.debug("exception: {}", exception); @@ -154,16 +155,16 @@ public void when_post_patients_is_call_with_empty_body_then_BadRequest_HttpMessa String empty_body = ""; MvcResult result = this.mockMvc - .perform( - post(request) - .content(empty_body.getBytes()) - .contentType(MediaType.APPLICATION_JSON)) - .andDo(log()) - .andExpect(status().is4xxClientError()) - .andExpect(status().isBadRequest()) - // TODO .andExpect(content().string(anyOf(nullValue(), equalTo("")))) - .andExpect(content().string(containsString("Failed to read request"))) - .andReturn(); + .perform( + post(request) + .content(empty_body.getBytes()) + .contentType(MediaType.APPLICATION_JSON)) + .andDo(log()) + .andExpect(status().is4xxClientError()) + .andExpect(status().isBadRequest()) + // TODO .andExpect(content().string(anyOf(nullValue(), equalTo("")))) + .andExpect(content().string(containsString("Failed to read request"))) + .andReturn(); Optional exception = Optional.ofNullable((HttpMessageNotReadableException) result.getResolvedException()); LOGGER.debug("exception: {}", exception); @@ -184,15 +185,15 @@ public void when_post_patients_PatientBrowserManager_getPatient_returns_null_the when(patientBrowserManagerMock.getPatientById(anyInt())).thenReturn(null); MvcResult result = this.mockMvc - .perform( - post(request) - .contentType(MediaType.APPLICATION_JSON) - .content(PatientHelper.asJsonString(newPatientDTO))) - .andDo(log()) - .andExpect(status().is4xxClientError()) - .andExpect(status().isBadRequest()) // TODO Create OHCreateAPIException - .andExpect(content().string(containsString("Patient not created."))) - .andReturn(); + .perform( + post(request) + .contentType(MediaType.APPLICATION_JSON) + .content(PatientHelper.asJsonString(newPatientDTO))) + .andDo(log()) + .andExpect(status().is4xxClientError()) + .andExpect(status().isBadRequest()) // TODO Create OHCreateAPIException + .andExpect(content().string(containsString("Patient not created."))) + .andReturn(); // TODO Create OHCreateAPIException Optional oHAPIException = Optional.ofNullable((OHAPIException) result.getResolvedException()); @@ -216,13 +217,13 @@ public void when_post_patients_PatientBrowserManager_newPatient_returns_false_th when(patientBrowserManagerMock.savePatient(any(Patient.class))).thenReturn(patientMapper.map2Model(newPatientDTO)); // TODO: verify if it's correct MvcResult result = this.mockMvc - .perform(post(request) - .contentType(MediaType.APPLICATION_JSON) - .content(PatientHelper.asJsonString(newPatientDTO))) - .andDo(log()) - .andExpect(status().isCreated()) - .andExpect(content().string(containsString(code.toString()))) - .andReturn(); + .perform(post(request) + .contentType(MediaType.APPLICATION_JSON) + .content(PatientHelper.asJsonString(newPatientDTO))) + .andDo(log()) + .andExpect(status().isCreated()) + .andExpect(content().string(containsString(code.toString()))) + .andReturn(); // TODO Create OHCreateAPIException Optional oHAPIException = Optional.ofNullable((OHAPIException) result.getResolvedException()); @@ -249,13 +250,13 @@ public void when_post_patients_and_both_calls_to_PatientBrowserManager_success_t when(patientBrowserManagerMock.getPatientById(anyInt())).thenReturn(newPatient); this.mockMvc - .perform( - post(request) - .contentType(MediaType.APPLICATION_JSON) - .content(PatientHelper.asJsonString(newPatientDTO))) - .andDo(log()) - .andExpect(status().isCreated()) - .andExpect(content().string(containsString(code.toString()))); + .perform( + post(request) + .contentType(MediaType.APPLICATION_JSON) + .content(PatientHelper.asJsonString(newPatientDTO))) + .andDo(log()) + .andExpect(status().isCreated()) + .andExpect(content().string(containsString(code.toString()))); } /** @@ -286,15 +287,15 @@ public void when_put_update_patient_with_valid_body_and_existent_code_then_BadRe when(patientBrowserManagerMock.savePatient(any(Patient.class))).thenReturn(null); this.mockMvc - .perform( - put(request, code) - .contentType(MediaType.APPLICATION_JSON) - .content(PatientHelper.asJsonString(newPatientDTO))) - .andDo(log()) - .andDo(print()) - .andExpect(status().is4xxClientError()) - .andExpect(status().isBadRequest()) - .andExpect(content().string(containsString("Patient not updated."))); + .perform( + put(request, code) + .contentType(MediaType.APPLICATION_JSON) + .content(PatientHelper.asJsonString(newPatientDTO))) + .andDo(log()) + .andDo(print()) + .andExpect(status().is4xxClientError()) + .andExpect(status().isBadRequest()) + .andExpect(content().string(containsString("Patient not updated."))); } @@ -309,14 +310,14 @@ public void when_put_update_patient_with_invalid_body_and_existent_code_then_Htt String request = "/patients/{code}"; MvcResult result = this.mockMvc - .perform( - put(request, code) - .contentType(MediaType.APPLICATION_JSON) - .content(new byte[3])) - .andDo(log()) - .andExpect(status().is4xxClientError()) - .andExpect(status().isBadRequest()) - .andReturn(); + .perform( + put(request, code) + .contentType(MediaType.APPLICATION_JSON) + .content(new byte[3])) + .andDo(log()) + .andExpect(status().is4xxClientError()) + .andExpect(status().isBadRequest()) + .andReturn(); Optional exception = Optional.ofNullable((HttpMessageNotReadableException) result.getResolvedException()); LOGGER.debug("oHAPIException: {}", exception); @@ -340,12 +341,12 @@ public void when_put_update_patient_with_valid_body_and_unexistent_code_then_OHA when(patientBrowserManagerMock.getPatientById(code)).thenReturn(null); MvcResult result = this.mockMvc - .perform(put(request, code).contentType(MediaType.APPLICATION_JSON) - .content(PatientHelper.asJsonString(newPatientDTO))) - .andDo(log()) - .andExpect(status().is4xxClientError()) - .andExpect(status().isBadRequest()) // TODO Create OHUpdateAPIException - .andExpect(content().string(containsString("Patient not found."))).andReturn(); + .perform(put(request, code).contentType(MediaType.APPLICATION_JSON) + .content(Objects.requireNonNull(PatientHelper.asJsonString(newPatientDTO)))) + .andDo(log()) + .andExpect(status().is4xxClientError()) + .andExpect(status().isNotFound()) // TODO Create OHUpdateAPIException + .andExpect(content().string(containsString("Patient not found."))).andReturn(); // TODO Create OHUpdateAPIException Optional oHAPIException = Optional.ofNullable((OHAPIException) result.getResolvedException()); @@ -366,23 +367,23 @@ public void when_get_patients_non_parameters_then_return_list_of_PatientDTO_page int expectedPageSize = Integer.parseInt(PatientController.DEFAULT_PAGE_SIZE); List patientList = PatientHelper.setupPatientList(expectedPageSize); - + PagedResponse patientPageable = new PagedResponse<>(); patientPageable.setData(patientList); patientPageable.setPageInfo(PatientHelper.setParameterPage()); Page expectedPatientDTOList = new Page<>(); - expectedPatientDTOList.setData(patientMapper.map2DTOList(patientList)); + expectedPatientDTOList.setData(patientMapper.map2DTOList(patientList)); expectedPatientDTOList.setPageInfo(patientMapper.setParameterPageInfo(patientPageable.getPageInfo())); - when(patientBrowserManagerMock.getPatientsPageable(anyInt(), anyInt())) - .thenReturn(patientPageable); + when(patientBrowserManagerMock.getPatientsPageable(anyInt(), anyInt())) + .thenReturn(patientPageable); this.mockMvc - .perform(get(request) - .contentType(MediaType.APPLICATION_JSON)) - .andDo(log()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(PatientHelper.asJsonString(expectedPatientDTOList.getData())))) - .andReturn(); + .perform(get(request) + .contentType(MediaType.APPLICATION_JSON)) + .andDo(log()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(PatientHelper.asJsonString(expectedPatientDTOList.getData())))) + .andReturn(); } @@ -406,13 +407,13 @@ public void when_get_patients_with_existent_code_and_not_admitted_then_response_ when(admissionBrowserManagerMock.getCurrentAdmission(patient)).thenReturn(null); this.mockMvc - .perform( - get(request, code) - .contentType(MediaType.APPLICATION_JSON)) - .andDo(log()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(PatientHelper.asJsonString(expectedPatientDTO)))) - .andReturn(); + .perform( + get(request, code) + .contentType(MediaType.APPLICATION_JSON)) + .andDo(log()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(PatientHelper.asJsonString(expectedPatientDTO)))) + .andReturn(); } @@ -438,13 +439,13 @@ public void when_get_patients_with_existent_code_and_admitted_then_response_Pati when(admissionBrowserManagerMock.getCurrentAdmission(patient)).thenReturn(admission); this.mockMvc - .perform( - get(request, code) - .contentType(MediaType.APPLICATION_JSON)) - .andDo(log()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString(PatientHelper.asJsonString(expectedPatientDTO)))) - .andReturn(); + .perform( + get(request, code) + .contentType(MediaType.APPLICATION_JSON)) + .andDo(log()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString(PatientHelper.asJsonString(expectedPatientDTO)))) + .andReturn(); } @@ -462,12 +463,12 @@ public void when_get_patients_search_without_name_and_unexistent_code_then_respo when(patientBrowserManagerMock.getPatientById(code)).thenReturn(null); this.mockMvc - .perform( - get(request) - .param("code", code.toString()) - .contentType(MediaType.APPLICATION_JSON)) - .andDo(log()) - .andExpect(status().isNoContent()); + .perform( + get(request) + .param("code", code.toString()) + .contentType(MediaType.APPLICATION_JSON)) + .andDo(log()) + .andExpect(status().isOk()); } /** @@ -481,11 +482,11 @@ public void when_get_patients_search_without_name_and_without_code_then_response String request = "/patients/search"; this.mockMvc - .perform( - get(request) - .contentType(MediaType.APPLICATION_JSON)) - .andDo(log()) - .andExpect(status().isNoContent()); + .perform( + get(request) + .contentType(MediaType.APPLICATION_JSON)) + .andDo(log()) + .andExpect(status().isOk()); } /** @@ -502,12 +503,12 @@ public void when_get_patients_search_with_unexistent_name_and_without_code_then_ when(patientBrowserManagerMock.getPatientById(null)).thenReturn(null); this.mockMvc - .perform( - get(request) - .param("name", name) - .contentType(MediaType.APPLICATION_JSON)) - .andDo(log()) - .andExpect(status().isNoContent()); + .perform( + get(request) + .param("name", name) + .contentType(MediaType.APPLICATION_JSON)) + .andDo(log()) + .andExpect(status().isOk()); } /** @@ -525,12 +526,12 @@ public void when_delete_patients_with_existent_code_then_response_true_and_OK() when(patientBrowserManagerMock.getPatientById(code)).thenReturn(patient); this.mockMvc - .perform( - delete(request, code) - .contentType(MediaType.APPLICATION_JSON)) - .andDo(log()) - .andExpect(status().isOk()) - .andExpect(content().string(containsString("true"))); + .perform( + delete(request, code) + .contentType(MediaType.APPLICATION_JSON)) + .andDo(log()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("true"))); } /** @@ -546,11 +547,11 @@ public void when_delete_patients_with_unexistent_code_then_response_Not_Found() when(patientBrowserManagerMock.getPatientById(code)).thenReturn(null); this.mockMvc - .perform( - delete(request, code) - .contentType(MediaType.APPLICATION_JSON)) - .andDo(log()) - .andExpect(status().isNotFound()); + .perform( + delete(request, code) + .contentType(MediaType.APPLICATION_JSON)) + .andDo(log()) + .andExpect(status().isNotFound()); } /** @@ -570,14 +571,14 @@ public void when_delete_patients_with_existent_code_but_fail_deletion_then_OHAPI doThrow(new OHServiceException(new OHExceptionMessage("Failure"))).when(patientBrowserManagerMock).deletePatient(patient); MvcResult result = this.mockMvc - .perform( - delete(request, code) - .contentType(MediaType.APPLICATION_JSON)) - .andDo(log()) - .andExpect(status().is4xxClientError()) - .andExpect(status().isBadRequest()) // TODO Create OHDeleteAPIException - .andExpect(content().string(containsString("Patient not deleted."))) - .andReturn(); + .perform( + delete(request, code) + .contentType(MediaType.APPLICATION_JSON)) + .andDo(log()) + .andExpect(status().is4xxClientError()) + .andExpect(status().isBadRequest()) // TODO Create OHDeleteAPIException + .andExpect(content().string(containsString("Patient not deleted."))) + .andReturn(); // TODO Create OHDeleteAPIException Optional oHAPIException = Optional.ofNullable((OHAPIException) result.getResolvedException()); diff --git a/src/test/java/org/isf/usergroups/rest/UserGroupControllerTest.java b/src/test/java/org/isf/usergroups/rest/UserGroupControllerTest.java index 6941cf0ff..9cad4f860 100644 --- a/src/test/java/org/isf/usergroups/rest/UserGroupControllerTest.java +++ b/src/test/java/org/isf/usergroups/rest/UserGroupControllerTest.java @@ -176,7 +176,6 @@ void getUserGroup() throws Exception { @DisplayName("Delete user groups") void deleteUserGroup() throws Exception { UserGroup userGroup = UserGroupHelper.generateUserGroup(); - UserGroupDTO userGroupDTO = userGroupMapper.map2DTO(userGroup); when(userManager.getUserGroup()).thenReturn(List.of(userGroup)); doNothing().when(userManager).deleteGroup(any()); diff --git a/src/test/java/org/isf/vaccine/rest/VaccineControllerTest.java b/src/test/java/org/isf/vaccine/rest/VaccineControllerTest.java index 17a3181ec..d6e00cd66 100644 --- a/src/test/java/org/isf/vaccine/rest/VaccineControllerTest.java +++ b/src/test/java/org/isf/vaccine/rest/VaccineControllerTest.java @@ -32,6 +32,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.List; +import java.util.Objects; import org.isf.shared.exceptions.OHResponseEntityExceptionHandler; import org.isf.shared.mapper.converter.BlobToByteArrayConverter; @@ -142,7 +143,7 @@ public void testNewVaccine_201() throws Exception { MvcResult result = this.mockMvc .perform(post(request) .contentType(MediaType.APPLICATION_JSON) - .content(VaccineHelper.asJsonString(body)) + .content(Objects.requireNonNull(VaccineHelper.asJsonString(body))) ) .andDo(log()) //.andDo(print()) @@ -165,7 +166,7 @@ public void testUpdateVaccine_200() throws Exception { MvcResult result = this.mockMvc .perform(put(request) .contentType(MediaType.APPLICATION_JSON) - .content(VaccineHelper.asJsonString(body)) + .content(Objects.requireNonNull(VaccineHelper.asJsonString(body))) ) .andDo(log()) .andExpect(status().is2xxSuccessful()) diff --git a/src/test/java/org/isf/vactype/rest/VaccineTypeControllerTest.java b/src/test/java/org/isf/vactype/rest/VaccineTypeControllerTest.java index 4fb4958ae..e12162f7c 100644 --- a/src/test/java/org/isf/vactype/rest/VaccineTypeControllerTest.java +++ b/src/test/java/org/isf/vactype/rest/VaccineTypeControllerTest.java @@ -32,6 +32,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.List; +import java.util.Objects; import org.isf.shared.exceptions.OHResponseEntityExceptionHandler; import org.isf.shared.mapper.converter.BlobToByteArrayConverter; @@ -121,7 +122,7 @@ public void testNewVaccineType_200() throws Exception { MvcResult result = this.mockMvc .perform(post(request) .contentType(MediaType.APPLICATION_JSON) - .content(VaccineTypeHelper.asJsonString(body)) + .content(Objects.requireNonNull(VaccineTypeHelper.asJsonString(body))) ) .andDo(log()) .andExpect(status().is2xxSuccessful()) @@ -144,7 +145,7 @@ public void testUpdateVaccineType_200() throws Exception { MvcResult result = this.mockMvc .perform(put(request) .contentType(MediaType.APPLICATION_JSON) - .content(VaccineTypeHelper.asJsonString(body)) + .content(Objects.requireNonNull(VaccineTypeHelper.asJsonString(body))) ) .andDo(log()) .andExpect(status().is2xxSuccessful()) diff --git a/src/test/java/org/isf/visits/rest/VisitsControllerTest.java b/src/test/java/org/isf/visits/rest/VisitsControllerTest.java index 9fc69b48a..f31d0b153 100644 --- a/src/test/java/org/isf/visits/rest/VisitsControllerTest.java +++ b/src/test/java/org/isf/visits/rest/VisitsControllerTest.java @@ -31,6 +31,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.List; +import java.util.Objects; import org.isf.shared.exceptions.OHResponseEntityExceptionHandler; import org.isf.shared.mapper.converter.BlobToByteArrayConverter; @@ -122,7 +123,7 @@ public void testNewVisit_201() throws Exception { MvcResult result = this.mockMvc .perform(post(request) .contentType(MediaType.APPLICATION_JSON) - .content(VisitHelper.asJsonString(body)) + .content(Objects.requireNonNull(VisitHelper.asJsonString(body))) ) .andDo(log()) .andExpect(status().is2xxSuccessful()) @@ -147,7 +148,7 @@ public void testNewVisits_201() throws Exception { MvcResult result = this.mockMvc .perform(post(request) .contentType(MediaType.APPLICATION_JSON) - .content(VisitHelper.asJsonString(body)) + .content(Objects.requireNonNull(VisitHelper.asJsonString(body))) ) .andDo(log()) .andExpect(status().is2xxSuccessful()) diff --git a/src/test/java/org/isf/ward/rest/WardControllerTest.java b/src/test/java/org/isf/ward/rest/WardControllerTest.java index e34172e68..f45c3b229 100644 --- a/src/test/java/org/isf/ward/rest/WardControllerTest.java +++ b/src/test/java/org/isf/ward/rest/WardControllerTest.java @@ -32,6 +32,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.List; +import java.util.Objects; import org.isf.shared.exceptions.OHResponseEntityExceptionHandler; import org.isf.shared.mapper.converter.BlobToByteArrayConverter; @@ -171,7 +172,7 @@ public void testNewWard_200() throws Exception { MvcResult result = this.mockMvc .perform(post(request) .contentType(MediaType.APPLICATION_JSON) - .content(WardHelper.asJsonString(body)) + .content(Objects.requireNonNull(WardHelper.asJsonString(body))) ) .andDo(log()) .andExpect(status().is2xxSuccessful()) @@ -194,7 +195,7 @@ public void testUpdateWard_200() throws Exception { MvcResult result = this.mockMvc .perform(put(request) .contentType(MediaType.APPLICATION_JSON) - .content(WardHelper.asJsonString(body)) + .content(Objects.requireNonNull(WardHelper.asJsonString(body))) ) .andDo(log()) .andExpect(status().is2xxSuccessful())