@Transactional
  @Override
  public CommandProcessingResult activationProcess(final JsonCommand command) {

    try {
      context.authenticatedUser();
      CommandProcessingResult resultClient = null;
      CommandProcessingResult resultSale = null;
      ///  CommandProcessingResult resultAllocate=null;
      CommandProcessingResult resultOrder = null;
      final JsonElement element = fromJsonHelper.parse(command.json());
      JsonArray clientData = fromJsonHelper.extractJsonArrayNamed("client", element);
      JsonArray saleData = fromJsonHelper.extractJsonArrayNamed("sale", element);
      JsonArray owndevices = fromJsonHelper.extractJsonArrayNamed("owndevice", element);
      // JsonArray allocateData = fromJsonHelper.extractJsonArrayNamed("allocate", element);
      JsonArray bookOrder = fromJsonHelper.extractJsonArrayNamed("bookorder", element);

      for (JsonElement j : clientData) {

        JsonCommand comm =
            new JsonCommand(
                null,
                j.toString(),
                j,
                fromJsonHelper,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null);
        resultClient = this.clientWritePlatformService.createClient(comm);
      }

      //  Configuration
      // configuration=configurationRepository.findOneByName(ConfigurationConstants.CONFIG_PROPERTY_DEVICE_AGREMENT_TYPE);
      // if(configuration.getValue().equalsIgnoreCase(ConfigurationConstants.CONFIR_PROPERTY_SALE)){
      if (saleData.size() != 0) {
        for (JsonElement sale : saleData) {
          JsonCommand comm =
              new JsonCommand(
                  null,
                  sale.toString(),
                  sale,
                  fromJsonHelper,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null);
          resultSale =
              this.oneTimeSaleWritePlatformService.createOneTimeSale(
                  comm, resultClient.getClientId());
        }
      } // else
      // if(configuration.getValue().equalsIgnoreCase(ConfigurationConstants.CONFIR_PROPERTY_OWN)){
      else if (owndevices.size() != 0) {
        for (JsonElement ownDevice : owndevices) {

          JsonCommand comm =
              new JsonCommand(
                  null,
                  ownDevice.toString(),
                  ownDevice,
                  fromJsonHelper,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null);
          resultSale =
              this.ownedHardwareWritePlatformService.createOwnedHardware(
                  comm, resultClient.getClientId());
        }
      }

      for (JsonElement order : bookOrder) {

        JsonCommand comm =
            new JsonCommand(
                null,
                order.toString(),
                order,
                fromJsonHelper,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null);
        resultOrder = this.orderWritePlatformService.createOrder(resultClient.getClientId(), comm);
      }
      return resultClient;

    } catch (DataIntegrityViolationException dve) {

      handleDataIntegrityIssues(command, dve);
      return new CommandProcessingResult(Long.valueOf(-1));
    }
  }
  // @SuppressWarnings("unused")
  @Override
  public CommandProcessingResult selfRegistrationProcess(JsonCommand command) {

    try {

      context.authenticatedUser();
      Configuration deviceStatusConfiguration =
          configurationRepository.findOneByName(
              ConfigurationConstants.CONFIR_PROPERTY_REGISTRATION_DEVICE);

      commandFromApiJsonDeserializer.validateForCreate(
          command.json(), deviceStatusConfiguration.isEnabled());
      Long id = new Long(1);
      CommandProcessingResult resultClient = null;
      CommandProcessingResult resultSale = null;
      CommandProcessingResult resultOrder = null;
      String device = null;
      String dateFormat = "dd MMMM yyyy";
      String activationDate = new SimpleDateFormat(dateFormat).format(DateUtils.getDateOfTenant());

      String fullname = command.stringValueOfParameterNamed("fullname");
      String firstName = command.stringValueOfParameterNamed("firstname");
      String city = command.stringValueOfParameterNamed("city");
      String address = command.stringValueOfParameterNamed("address");
      Long phone = command.longValueOfParameterNamed("phone");
      Long homePhoneNumber = command.longValueOfParameterNamed("homePhoneNumber");
      String email = command.stringValueOfParameterNamed("email");
      String nationalId = command.stringValueOfParameterNamed("nationalId");
      String deviceId = command.stringValueOfParameterNamed("device");
      String deviceAgreementType = command.stringValueOfParameterNamed("deviceAgreementType");
      String password = command.stringValueOfParameterNamed("password");
      String isMailCheck = command.stringValueOfParameterNamed("isMailCheck");
      String passport = command.stringValueOfParameterNamed("passport");
      SelfCareTemporary temporary = null;

      if (isMailCheck == null || isMailCheck.isEmpty()) {
        temporary = selfCareTemporaryRepository.findOneByEmailId(email);

        if (temporary == null) {
          throw new SelfCareTemporaryEmailIdNotFoundException(email);

        } else if (temporary.getStatus().equalsIgnoreCase("ACTIVE")) {
          throw new ClientAlreadyCreatedException();

        } else if (temporary.getStatus().equalsIgnoreCase("INACTIVE")) {
          throw new SelfCareNotVerifiedException(email);
        }
      }

      //	if (temporary.getStatus().equalsIgnoreCase("PENDING")){

      String zipCode = command.stringValueOfParameterNamed("zipCode");
      // client creation
      AddressData addressData = this.addressReadPlatformService.retrieveAdressBy(city);
      CodeValue codeValue = this.codeValueRepository.findOneByCodeValue("Normal");
      JSONObject clientcreation = new JSONObject();
      clientcreation.put("officeId", new Long(1));
      clientcreation.put("clientCategory", codeValue.getId());
      clientcreation.put("firstname", firstName);
      clientcreation.put("lastname", fullname);
      clientcreation.put("phone", phone);
      clientcreation.put("homePhoneNumber", homePhoneNumber);
      clientcreation.put("entryType", "IND"); // new Long(1));
      clientcreation.put("addressNo", address);
      clientcreation.put("city", addressData.getCity());
      clientcreation.put("state", addressData.getState());
      clientcreation.put("country", addressData.getCountry());
      clientcreation.put("email", email);
      clientcreation.put("locale", "en");
      clientcreation.put("active", true);
      clientcreation.put("dateFormat", dateFormat);
      clientcreation.put("activationDate", activationDate);
      clientcreation.put("flag", false);
      clientcreation.put("zipCode", zipCode);
      clientcreation.put("device", deviceId);
      clientcreation.put("password", password);

      if (nationalId != null && !nationalId.equalsIgnoreCase("")) {
        clientcreation.put("externalId", nationalId);
      }

      final JsonElement element = fromJsonHelper.parse(clientcreation.toString());
      JsonCommand clientCommand =
          new JsonCommand(
              null,
              clientcreation.toString(),
              element,
              fromJsonHelper,
              null,
              null,
              null,
              null,
              null,
              null,
              null,
              null,
              null,
              null,
              null,
              null);
      resultClient = this.clientWritePlatformService.createClient(clientCommand);

      if (resultClient == null) {
        throw new PlatformDataIntegrityException(
            "error.msg.client.creation.failed", "Client Creation Failed", "Client Creation Failed");
      }

      if (passport != null && !passport.equalsIgnoreCase("")) {
        CodeValue passportcodeValue = this.codeValueRepository.findOneByCodeValue("Passport");
        JSONObject clientIdentifierJson = new JSONObject();
        clientIdentifierJson.put("documentTypeId", passportcodeValue.getId());
        clientIdentifierJson.put("documentKey", passport);
        final JsonElement idenfierJsonEement =
            fromJsonHelper.parse(clientIdentifierJson.toString());
        JsonCommand idenfierJsonCommand =
            new JsonCommand(
                null,
                clientIdentifierJson.toString(),
                idenfierJsonEement,
                fromJsonHelper,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null);
        this.clientIdentifierWritePlatformService.addClientIdentifier(
            resultClient.getClientId(), idenfierJsonCommand);
      }

      if (temporary != null) {
        temporary.setStatus("ACTIVE");
        this.selfCareTemporaryRepository.saveAndFlush(temporary);
      }

      // book device
      if (deviceStatusConfiguration != null) {

        if (deviceStatusConfiguration.isEnabled()) {

          JSONObject bookDevice = new JSONObject();
          /*deviceStatusConfiguration = configurationRepository
          .findOneByName(ConfigurationConstants.CONFIG_PROPERTY_DEVICE_AGREMENT_TYPE);*/

          /*if (deviceStatusConfiguration != null&& deviceStatusConfiguration.isEnabled()
          && deviceStatusConfiguration.getValue().equalsIgnoreCase(ConfigurationConstants.CONFIR_PROPERTY_SALE)) {*/
          if (deviceAgreementType.equalsIgnoreCase(ConfigurationConstants.CONFIR_PROPERTY_SALE)) {

            device = command.stringValueOfParameterNamed("device");
            ItemDetails detail = itemDetailsRepository.getInventoryItemDetailBySerialNum(device);

            if (detail == null) {
              throw new SerialNumberNotFoundException(device);
            }

            ItemMaster itemMaster = this.itemRepository.findOne(detail.getItemMasterId());

            if (itemMaster == null) {
              throw new ItemNotFoundException(deviceId);
            }

            if (detail != null && detail.getStatus().equalsIgnoreCase("Used")) {
              throw new SerialNumberAlreadyExistException(device);
            }

            JSONObject serialNumberObject = new JSONObject();
            serialNumberObject.put("serialNumber", device);
            serialNumberObject.put("clientId", resultClient.getClientId());
            serialNumberObject.put("status", "allocated");
            serialNumberObject.put("itemMasterId", detail.getItemMasterId());
            serialNumberObject.put("isNewHw", "Y");
            JSONArray serialNumber = new JSONArray();
            serialNumber.put(0, serialNumberObject);

            bookDevice.put("chargeCode", itemMaster.getChargeCode());
            bookDevice.put("unitPrice", itemMaster.getUnitPrice());
            bookDevice.put("itemId", itemMaster.getId());
            bookDevice.put("discountId", id);
            bookDevice.put("officeId", detail.getOfficeId());
            bookDevice.put("totalPrice", itemMaster.getUnitPrice());

            bookDevice.put("quantity", id);
            bookDevice.put("locale", "en");
            bookDevice.put("dateFormat", dateFormat);
            bookDevice.put("saleType", "NEWSALE");
            bookDevice.put("saleDate", activationDate);
            bookDevice.put("serialNumber", serialNumber);

            final JsonElement deviceElement = fromJsonHelper.parse(bookDevice.toString());
            JsonCommand comm =
                new JsonCommand(
                    null,
                    bookDevice.toString(),
                    deviceElement,
                    fromJsonHelper,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null);

            resultSale =
                this.oneTimeSaleWritePlatformService.createOneTimeSale(
                    comm, resultClient.getClientId());

            if (resultSale == null) {
              throw new PlatformDataIntegrityException(
                  "error.msg.client.device.assign.failed",
                  "Device Assign Failed for ClientId :" + resultClient.getClientId(),
                  "Device Assign Failed");
            }

          } else if (deviceAgreementType.equalsIgnoreCase(
              ConfigurationConstants.CONFIR_PROPERTY_OWN)) {

            List<ItemMaster> itemMaster = this.itemRepository.findAll();
            bookDevice.put("locale", "en");
            bookDevice.put("dateFormat", dateFormat);
            bookDevice.put("allocationDate", activationDate);
            bookDevice.put("provisioningSerialNumber", deviceId);
            bookDevice.put("itemType", itemMaster.get(0).getId());
            bookDevice.put("serialNumber", deviceId);
            bookDevice.put("status", "ACTIVE");
            CommandWrapper commandWrapper =
                new CommandWrapperBuilder()
                    .createOwnedHardware(resultClient.getClientId())
                    .withJson(bookDevice.toString())
                    .build();
            final CommandProcessingResult result =
                portfolioCommandSourceWritePlatformService.logCommandSource(commandWrapper);

            if (result == null) {
              throw new PlatformDataIntegrityException(
                  "error.msg.client.device.assign.failed",
                  "Device Assign Failed for ClientId :" + resultClient.getClientId(),
                  "Device Assign Failed");
            }
          } else {

          }
        }
      }

      // book order
      Configuration selfregistrationconfiguration =
          configurationRepository.findOneByName(
              ConfigurationConstants.CONFIR_PROPERTY_SELF_REGISTRATION);

      if (selfregistrationconfiguration != null && selfregistrationconfiguration.isEnabled()) {

        if (selfregistrationconfiguration.getValue() != null) {

          JSONObject ordeJson = new JSONObject(selfregistrationconfiguration.getValue());
          ordeJson.put("locale", "en");
          ordeJson.put("isNewplan", true);
          ordeJson.put("dateFormat", dateFormat);
          ordeJson.put("start_date", activationDate);

          CommandWrapper commandRequest =
              new CommandWrapperBuilder()
                  .createOrder(resultClient.getClientId())
                  .withJson(ordeJson.toString())
                  .build();
          resultOrder =
              this.portfolioCommandSourceWritePlatformService.logCommandSource(commandRequest);

          if (resultOrder == null) {
            throw new PlatformDataIntegrityException(
                "error.msg.client.order.creation",
                "Book Order Failed for ClientId:" + resultClient.getClientId(),
                "Book Order Failed");
          }

        } else {

          String paytermCode = command.stringValueOfParameterNamed("paytermCode");
          Long contractPeriod = command.longValueOfParameterNamed("contractPeriod");
          Long planCode = command.longValueOfParameterNamed("planCode");

          JSONObject ordeJson = new JSONObject();

          ordeJson.put("planCode", planCode);
          ordeJson.put("contractPeriod", contractPeriod);
          ordeJson.put("paytermCode", paytermCode);
          ordeJson.put("billAlign", false);
          ordeJson.put("locale", "en");
          ordeJson.put("isNewplan", true);
          ordeJson.put("dateFormat", dateFormat);
          ordeJson.put("start_date", activationDate);

          CommandWrapper commandRequest =
              new CommandWrapperBuilder()
                  .createOrder(resultClient.getClientId())
                  .withJson(ordeJson.toString())
                  .build();
          resultOrder =
              this.portfolioCommandSourceWritePlatformService.logCommandSource(commandRequest);

          if (resultOrder == null) {
            throw new PlatformDataIntegrityException(
                "error.msg.client.order.creation",
                "Book Order Failed for ClientId:" + resultClient.getClientId(),
                "Book Order Failed");
          }
        }
      }

      return resultClient;

      /*}  else {
      	return new CommandProcessingResult(Long.valueOf(-1));
      }*/

    } catch (DataIntegrityViolationException dve) {
      handleDataIntegrityIssues(command, dve);
      return new CommandProcessingResult(Long.valueOf(-1));
    } catch (JSONException e) {
      return new CommandProcessingResult(Long.valueOf(-1));
    }
  }
  @Override
  public CommandProcessingResult convertToClient(final Long entityId) {

    final AppUser currentUser = context.authenticatedUser();
    final ClientProspect clientProspect = retrieveCodeBy(entityId);

    Long clientId = null;

    final JSONObject newClientJsonObject = new JSONObject();

    try {
      SimpleDateFormat formatter = new SimpleDateFormat("dd MMMM yyyy");
      String activationDate = formatter.format(DateUtils.getDateOfTenant());

      final Long officeId = currentUser.getOffice().getId();
      newClientJsonObject.put("dateFormat", "dd MMMM yyyy");
      newClientJsonObject.put("locale", "en");
      newClientJsonObject.put("officeId", officeId);
      newClientJsonObject.put("firstname", clientProspect.getFirstName());
      newClientJsonObject.put("middlename", clientProspect.getMiddleName());
      newClientJsonObject.put("lastname", clientProspect.getLastName());
      newClientJsonObject.put("fullname", "");
      newClientJsonObject.put("externalId", "");
      newClientJsonObject.put("clientCategory", "20");
      // newClientJsonObject.put("active","300");
      newClientJsonObject.put("activationDate", activationDate);
      newClientJsonObject.put("active", "true");
      newClientJsonObject.put("email", clientProspect.getEmail());
      newClientJsonObject.put("phone", clientProspect.getMobileNumber());
      newClientJsonObject.put("flag", false);
      /*
       * newClientJsonObject.put("login","");
       * newClientJsonObject.put("password","");
       */

      newClientJsonObject.put("addressNo", clientProspect.getAddress());
      newClientJsonObject.put("street", clientProspect.getStreetArea());
      newClientJsonObject.put("city", clientProspect.getCityDistrict());
      newClientJsonObject.put("zipCode", clientProspect.getZipCode());
      newClientJsonObject.put("state", clientProspect.getState());
      newClientJsonObject.put("country", clientProspect.getCountry());
      newClientJsonObject.put("flag", "false");

      final CommandWrapper commandNewClient =
          new CommandWrapperBuilder()
              .createClient()
              .withJson(newClientJsonObject.toString().toString())
              .build(); //

      final CommandProcessingResult clientResult =
          this.commandsSourceWritePlatformService.logCommandSource(commandNewClient);
      /*
       * final CommandWrapper commandRequest = new
       * CommandWrapperBuilder().
       * createAddress(clientResult.getClientId()).
       * withJson(newClientAddressObject.toString().toString()).build();
       * final CommandProcessingResult addressResult =
       * this.commandsSourceWritePlatformService
       * .logCommandSource(commandRequest);
       */

      clientProspect.setStatusRemark(clientResult.getClientId().toString());
      clientId = clientResult.getClientId();

    } catch (JSONException e) {
      e.printStackTrace();
    }

    clientProspect.setStatus("Closed");
    // clientProspect.setIsDeleted('Y');

    // clientProspect.setStatusRemark(command.stringValueOfParameterNamed("statusRemark"));

    this.clientProspectJpaRepository.saveAndFlush(clientProspect);

    return new CommandProcessingResultBuilder().withEntityId(clientId).build();
  }