public void closeOrder(final StateChangeContext stateChangeContext) {
    final Entity productionTracking = stateChangeContext.getOwner();
    final Entity order = productionTracking.getBelongsToField(ORDER);

    if (!orderClosingHelper.orderShouldBeClosed(productionTracking)) {
      return;
    }
    if (order.getStringField(STATE).equals(COMPLETED.getStringValue())) {
      stateChangeContext.addMessage(
          "productionCounting.order.orderIsAlreadyClosed", StateMessageType.INFO, false);
      return;
    }
    final StateChangeContext orderStateChangeContext =
        stateChangeContextBuilder.build(
            orderStateChangeAspect.getChangeEntityDescriber(),
            order,
            OrderState.COMPLETED.getStringValue());
    orderStateChangeAspect.changeState(orderStateChangeContext);
    Entity orderFromDB = order.getDataDefinition().get(orderStateChangeContext.getOwner().getId());
    if (orderFromDB.getStringField(STATE).equals(COMPLETED.getStringValue())) {
      stateChangeContext.addMessage(
          "productionCounting.order.orderClosed", StateMessageType.INFO, false);
    } else if (StateChangeStatus.PAUSED.equals(orderStateChangeContext.getStatus())) {
      stateChangeContext.addMessage(
          "productionCounting.order.orderWillBeClosedAfterExtSync", StateMessageType.INFO, false);
    } else {
      stateChangeContext.addMessage(
          "productionCounting.order.orderCannotBeClosed", StateMessageType.FAILURE, false);

      List<ErrorMessage> errors = Lists.newArrayList();

      if (!orderFromDB.getErrors().isEmpty()) {
        errors.addAll(order.getErrors().values());
      }
      if (!orderFromDB.getGlobalErrors().isEmpty()) {
        errors.addAll(order.getGlobalErrors());
      }

      if (!errors.isEmpty()) {
        StringBuilder errorMessages = new StringBuilder();

        for (ErrorMessage errorMessage : errors) {
          String translatedErrorMessage =
              translationService.translate(
                  errorMessage.getMessage(), Locale.getDefault(), errorMessage.getVars());
          errorMessages.append(translatedErrorMessage);
          errorMessages.append(", ");
        }

        stateChangeContext.addValidationError(
            "orders.order.orderStates.error", errorMessages.toString());
      }
    }
  }
  public void checkIfExistsFinalRecord(final StateChangeContext stateChangeContext) {
    final Entity productionTracking = stateChangeContext.getOwner();
    final Entity order = productionTracking.getBelongsToField(ProductionTrackingFields.ORDER);
    final String typeOfProductionRecording =
        order.getStringField(OrderFieldsPC.TYPE_OF_PRODUCTION_RECORDING);

    final SearchCriteriaBuilder searchBuilder = productionTracking.getDataDefinition().find();
    searchBuilder.add(
        SearchRestrictions.eq(
            ProductionTrackingFields.STATE, ProductionTrackingStateStringValues.ACCEPTED));
    searchBuilder.add(SearchRestrictions.belongsTo(ProductionTrackingFields.ORDER, order));
    searchBuilder.add(SearchRestrictions.eq(ProductionTrackingFields.LAST_TRACKING, true));

    if (productionCountingService.isTypeOfProductionRecordingForEach(typeOfProductionRecording)) {
      searchBuilder.add(
          SearchRestrictions.belongsTo(
              ProductionTrackingFields.TECHNOLOGY_OPERATION_COMPONENT,
              productionTracking.getBelongsToField(
                  ProductionTrackingFields.TECHNOLOGY_OPERATION_COMPONENT)));
    }

    if (searchBuilder.list().getTotalNumberOfEntities() != 0) {
      stateChangeContext.addValidationError(
          "productionCounting.productionTracking.messages.error.finalExists");
    }
  }
 public void showReasonForm(
     final StateChangeContext stateChangeContext, final ViewContextHolder viewContext) {
   final Entity order = stateChangeContext.getOwner();
   final Entity parameter = parameterService.getParameter();
   Long differenceForDateFrom = getEffectiveDateFromDifference(parameter, order);
   Long differenceForDateTo = getEffectiveDateToDifference(parameter, order);
   final Entity stateChangeEntity = stateChangeContext.getStateChangeEntity();
   String additionalInfoKey = null;
   String additionalInfo = null;
   // EFFECTIVE_DATE_FROM
   if (parameter.getBooleanField(ParameterFieldsO.REASON_NEEDED_WHEN_DELAYED_EFFECTIVE_DATE_FROM)
       && differenceForDateFrom > 0L) {
     final String differenceAsString =
         TimeConverterService.convertTimeToString(String.valueOf(Math.abs(differenceForDateFrom)));
     additionalInfoKey = "orders.order.stateChange.additionalInfo.startTooLate";
     additionalInfo =
         translationService.translate(
             additionalInfoKey, LocaleContextHolder.getLocale(), differenceAsString);
   }
   if (parameter.getBooleanField(ParameterFieldsO.REASON_NEEDED_WHEN_EARLIER_EFFECTIVE_DATE_FROM)
       && differenceForDateFrom < 0L) {
     final String differenceAsString =
         TimeConverterService.convertTimeToString(String.valueOf(Math.abs(differenceForDateFrom)));
     additionalInfoKey = "orders.order.stateChange.additionalInfo.startTooEarly";
     additionalInfo =
         translationService.translate(
             additionalInfoKey, LocaleContextHolder.getLocale(), differenceAsString);
   }
   // EFFECTIVE_DATE_TO
   if (parameter.getBooleanField(ParameterFieldsO.REASON_NEEDED_WHEN_DELAYED_EFFECTIVE_DATE_TO)
       && differenceForDateTo > 0L) {
     final String differenceAsString =
         TimeConverterService.convertTimeToString(String.valueOf(Math.abs(differenceForDateTo)));
     additionalInfoKey = "orders.order.stateChange.additionalInfo.endTooLate";
     additionalInfo =
         translationService.translate(
             additionalInfoKey, LocaleContextHolder.getLocale(), differenceAsString);
   }
   if (parameter.getBooleanField(ParameterFieldsO.REASON_NEEDED_WHEN_EARLIER_EFFECTIVE_DATE_TO)
       && differenceForDateTo < 0L) {
     final String differenceAsString =
         TimeConverterService.convertTimeToString(String.valueOf(Math.abs(differenceForDateTo)));
     additionalInfoKey = "orders.order.stateChange.additionalInfo.endTooEarly";
     additionalInfo =
         translationService.translate(
             additionalInfoKey, LocaleContextHolder.getLocale(), differenceAsString);
   }
   if (additionalInfo != null) {
     stateChangeEntity.setField(OrderStateChangeFields.ADDITIONAL_INFO, additionalInfo);
     stateChangeContext.save();
   }
   stateChangeContext.setStatus(StateChangeStatus.PAUSED);
   stateChangeContext.save();
   viewContext
       .getViewDefinitionState()
       .openModal(
           "../page/orders/orderStateChangeReasonDialog.html?context={\"form.id\": "
               + stateChangeContext.getStateChangeEntity().getId()
               + "}");
 }
  private void checkIfRecordOperationProductComponentsWereFilled(
      final StateChangeContext stateChangeContext) {
    final Entity productionTracking = stateChangeContext.getOwner();

    if (!checkIfUsedQuantitiesWereFilled(
            productionTracking, ProductionTrackingFields.TRACKING_OPERATION_PRODUCT_IN_COMPONENTS)
        && !checkIfUsedQuantitiesWereFilled(
            productionTracking,
            ProductionTrackingFields.TRACKING_OPERATION_PRODUCT_OUT_COMPONENTS)) {
      stateChangeContext.addValidationError(
          "productionCounting.productionTracking.messages.error.recordOperationProductComponentsNotFilled");
    }
  }
 public void onComplete(
     final StateChangeContext stateChangeContext, final ViewContextHolder viewContext) {
   final Entity order = stateChangeContext.getOwner();
   if (neededWhenCorrectingDateTo() && !hasRequiredCorrectionDateToReasonField(order)) {
     stateChangeContext.addFieldValidationError(
         REASON_TYPE_CORRECTION_DATE_TO, "orders.order.stateChange.missingEndCorrectionReason");
     stateChangeContext.setStatus(StateChangeStatus.FAILURE);
     stateChangeContext.save();
     return;
   }
   final long difference = getEffectiveDateToDifference(order);
   if (difference == 0L) {
     return;
   }
   setAdditionalInfo(stateChangeContext, difference);
   showReasonForm(stateChangeContext, viewContext);
 }
 public void checkIfTimesIsSet(final StateChangeContext stateChangeContext) {
   final Entity productionRecord = stateChangeContext.getOwner();
   Entity orderEntity = productionRecord.getBelongsToField(ProductionTrackingFields.ORDER);
   Entity parameter = parameterService.getParameter();
   if (parameter.getBooleanField(ParameterFieldsPC.VALIDATE_PRODUCTION_RECORD_TIMES)
       && orderEntity.getBooleanField(OrderFieldsPC.REGISTER_PRODUCTION_TIME)) {
     Integer machineTimie =
         productionRecord.getIntegerField(ProductionTrackingFields.MACHINE_TIME);
     if (machineTimie == null || machineTimie == 0) {
       stateChangeContext.addFieldValidationError(
           ProductionTrackingFields.MACHINE_TIME, "qcadooView.validate.field.error.missing");
     }
     Integer laborTime = productionRecord.getIntegerField(ProductionTrackingFields.LABOR_TIME);
     if (laborTime == null || laborTime == 0) {
       stateChangeContext.addFieldValidationError(
           ProductionTrackingFields.LABOR_TIME, "qcadooView.validate.field.error.missing");
     }
   }
 }
 public void onLeavingDraft(final StateChangeContext stateChangeContext) {
   Entity productionTracking = stateChangeContext.getOwner();
   productionTracking.setField(ProductionTrackingFields.LAST_STATE_CHANGE_FAILS, false);
   productionTracking.setField(ProductionTrackingFields.LAST_STATE_CHANGE_FAIL_CAUSE, null);
   stateChangeContext.setOwner(productionTracking);
 }
 public void onChangeFromAcceptedToDeclined(final StateChangeContext stateChangeContext) {
   final Entity productionTracking = stateChangeContext.getOwner();
   updateBasicProductionCounting(productionTracking, new Substraction());
   setOrderDoneQuantity(productionTracking);
 }
 public void onAccept(final StateChangeContext stateChangeContext) {
   final Entity productionTracking = stateChangeContext.getOwner();
   updateBasicProductionCounting(productionTracking, new Addition());
   setOrderDoneQuantity(productionTracking);
   closeOrder(stateChangeContext);
 }