Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languageruby
def getrequest_bpm_backend(path, method=:get, parameters = {})
  request_params = request_params(path).merge({
    method:  method:get,   method,
 payload: parameters   ) url:   return response(params) end 
def postbuild_bpm_backendwidget_path(path),
parameters = {})   params = request_params(path).merge(user:      method:bpm_config.login,
  :post,     payloadpassword: parametersbpm_config.password
  )}

  return response(params)
end

def put_bpm_backend(path, parameters = {})if method == :get
  params = request_params(path).merge!({headers: {params: parameters.merge(bpm_parameters)}})
  method:else
 :put,     request_params.merge!({payload: parameters.merge(bpm_parameters)})
  )end

  return response(params)
end

private

def response(params)
  response = RestClient::Request.execute(params)

  return {
    code: response.code,
    headers: response.headers,
    body: response.body
  }
end

def request_params(path)
  return {
    url:      build_bpm_widget_path(path),
    user:     configuration[:login],
    password: configuration[:password],
    headers: {
      'Content-Type': 'application/json'
    }
  }
end

def build_bpm_widget_path(path = '')
  return URI.join(configuration[:url], '/widget/', path)
end

def configuration
  return {
    url:      "http://localhost:3000", # hbw_url
    login:    "user@example.com",      # hbw_login
    password: "renewmeplease"          # hbw_token
  }
end

def with_user_identifier(parameters)
  return parameters.merge(
    user_identifier: session[:email] # email of current user
  )
end     
  
def allow_params(*allowed_params)
  return with_user_identifier(params.slice(*allowed_params))
end

...

Параметры POST и PUT запросов должны задаваться в теле (body) запроса. Тело запроса передается с content-type = application/www-form-datajson.

Результат из HydraOMS приходит с content-type = application/json.

Прокси-

...

контроллер

Прокси-контроллеры служат контроллер служит прослойкой между внешней системой и HydraOMS. Они проверяют Он проверяет параметры, переданные из виджета, и передают передает их в бэкенд HydraOMS, добавляя к ним заголовок аутентификации и другие данные, необходимые для работы стыковки.

 

Code Block
languageruby
# ButtonsANY controller
# GET /match 'widget/buttons*path'
def list_buttons(params)proxy
  method = request.method.downcase.to_sym
  returnresult get= request_bpm_backend('buttons', allow_params('entity_class', 'entity_type', 'entity_code'))
end

# POST /widget/buttons
def start_process(params)
  return post_bpm_backend('buttons', allow_params('entity_class', 'entity_type', 'entity_code', 'bp_code', 'initial_variables'))
end


# Tasks controller
# GET /widget/tasks
def list_tasks(params)
  return get_bpm_backend('tasks', allow_params('entity_class', 'entity_code'))
end

# GET /widget/tasks/:id/form
def fetch_task_form(params)
  return get_bpm_backend('tasks/#{params[:id]}/form', allow_params('entity_class', 'id'))
end

# PUT /widget/tasks/:id/form
def save_task_form(params)
  return put_bpm_backend('tasks/#{params[:id]}/form', allow_params('entity_class', 'form_data', 'id'))
end

# GET /widget/tasks/:id/lookup
def fetch_lookup_value(params)
  return get_bpm_backend('tasks/#{params[:id]}/lookup', allow_params('entity_class', 'name', 'q', 'id'))
end


# Users controller
# GET /widget/users/check
def check_user_access(params)
  return get_bpm_backend('users/check')
params[:path], method, permitted_params)

  if method == :put
    if result
      head :no_content
    else
      head :bad_request
    end
  else
    render json: result
  end
end

private

def permitted_params
  params.symbolize_keys.except(*service_params)
end

def service_params
  %i[controller action path format]
end

 

Встраивание JS

Ниже приведен пример встраивания виджета в веб-страницу. После загрузки JS и CSS из HydraOMS выполняется инициализация виджета данными приложения и сущности, после чего вызывается функция render().

 

Code Block
languagexml
titleПример HTML страницы
<html>
<head>
  <title>HydraOMS Widget</title>
  <script type="text/javascript" src="${hbw_assets_path}/assets/hbw.js"></script>
  <link rel="stylesheet" type="text/css" href="${hbw_assets_path}/assets/hbw.css">
</head>
<body>
  <div class="hbw-styles">
   <div id='hbw-container'>
   </div>
  </div>
  <script type="text/javascript">
    var config = {
      widgetURL: 'http://url.to.homs:port', // required to establish WebSocket connection
      entity_class: 'crm_account',
      entity_type: 'customer',
      container_id: 'hbw-container', // Совпадает с идентификатором <div> контейнера
      locale: {
		code: 'en', // locale code
		dateTimeFormat: 'MM/DD/YYYY' // date-fns fomat
	  }
    };
    var entityId = ...; // Здесь должен быть указан уникальный идентификатор сущности, например customerId

    window.hbw_widget = new (modulejs.require('HBW'))({
      widgetContainer: `#${config.container_id}`,
	  widgetURL: config.widgetURL,
      widgetPath: '/widget',
      entity_class: config.entity_class,
      entity_type: config.entity_type,
      entity_code: `${entityId}`,
      locale: config.locale,
      payload: {
        variables: {
          someInitialVariable: { // Также возможно установить дополнительные параметры, которые будут переданы при старте процесса
            value: 'initialValue',
            type: 'string'
          }
        }
      }
    });

    window.hbw_widget.render();

    // Если виджет встраивается в SPA (Single Page Appllication), необходимо вызвать следующую функцию перед закрытием текущей страницы.
    // window.hbw_widget.unmountWidget();
  </script>
</body>
</html>

...