@DELETE
@Path("/{code}/")
@Transactional
public Response removeOrderElement(@PathParam("code") String code) {
try {
OrderElement orderElement = orderElementDAO.findByCode(code);
String errorMessage = checkRemovalValidation(orderElement);
if (errorMessage != null) {
return Response.status(Status.FORBIDDEN)
.entity(new ErrorDTO(errorMessage)).build();
}
if (orderElement.isOrder()) {
orderModel.remove((Order) orderElement);
} else {
Order order = orderDAO.loadOrderAvoidingProxyFor(orderElement);
orderModel.initEdit(order, null);
order = orderModel.getOrder();
orderElement = findOrderElement(order, orderElement.getId());
OrderLineGroup parent = orderElement.getParent();
parent.remove(orderElement);
orderElement.detachFromParent();
if (!parent.isOrder() && parent.getChildren().isEmpty()) {
OrderElement newElement = parent.toLeaf();
if (!order.isCodeAutogenerated()) {
newElement.setCode(UUID.randomUUID().toString());
}
parent.getParent().replace(parent, newElement);
parent.detachFromParent();
}