docgen-adapter 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 5843bd2a380e11e802a39d91839e5daa56ed848ebf3f9c1ec8d4c02a5fe96331
4
+ data.tar.gz: a1d2955903f75f3b1a5d64cc03cd16b879c7346aab5e5259bdd6a7c376557609
5
+ SHA512:
6
+ metadata.gz: 62f713cb8e3a6047295e8dabf3a2f11d20498e53448dcb2ffa75d5fe1e1b02fd4295b6871aa0a3a28d5910930c5d2202725df36bf3eba77da8d4ab740819e148
7
+ data.tar.gz: 23d0dd3ac4e4686756df2f0237997b45db796a4c80e0e665d20a6ad1d019156370da7e207c8b0f5f5bca7c7dd7e9e1f837e37342628197e955aa9967539f49ab
data/README.md ADDED
@@ -0,0 +1,64 @@
1
+ # DocGen Adapter
2
+ [![Gem Version](https://badge.fury.io/rb/docgen-adapter.svg)](https://badge.fury.io/rb/docgen-adapter)
3
+
4
+ Гем для адаптации собственного сервиса генерации документов и упрощения работы с ним.
5
+
6
+ ## Установка
7
+
8
+ Добавить в Gemfile
9
+
10
+ ```ruby
11
+ gem 'docgen-adapter'
12
+ ```
13
+
14
+ И выполнить:
15
+
16
+ ```bash
17
+ bundle
18
+ ```
19
+
20
+ ## Конфигурация
21
+
22
+ Добавьте файл конфигурации `config/initializers/docgen_adapter.rb` и задайте необходимые настройки:
23
+
24
+ ```ruby
25
+ DocgenAdapter.configure do |config|
26
+
27
+ config.redis_host = ''
28
+ config.redis_port = ''
29
+ config.redis_password = ''
30
+
31
+ end
32
+ ```
33
+
34
+ ## Использование
35
+
36
+ Использование с помощью вызова метода `generate` класса `DocgenAdapter`. Например:
37
+
38
+ ```ruby
39
+ params = {
40
+ DocumentNumber: 12345678,
41
+ Houses: [
42
+ {
43
+ HouseAddress: 'г. Калуга',
44
+ PersonFIO: 'Иванов ИИ',
45
+ PersonState: 'электромонтер',
46
+ PersonPhone: '89171234567',
47
+ OrganizationName: 'Россети',
48
+ OrganizationAddress: 'г. Обнинск',
49
+ OrganizationPhone: '1234567',
50
+ OrganizationCite: 'https://www.rosseti.ru'
51
+ }
52
+ ]
53
+ }
54
+
55
+ DocgenAdapter.new(type: 'docx', doc_id: 1, debug: true).generate(params)
56
+ ```
57
+
58
+ Опции:
59
+
60
+ - `type` - тип документа, возможные значения: `docx`, `xlsx`
61
+
62
+ - `doc_id` - ID документа
63
+
64
+ - `debug` - необязательная опция для дебага, при передаче `debug: true` при вызове отображаются формируемые параметры
@@ -0,0 +1 @@
1
+ require 'docgen_adapter'
@@ -0,0 +1,17 @@
1
+ class DocgenAdapter
2
+ class Configuration
3
+
4
+ attr_accessor :redis_host,
5
+ :redis_port,
6
+ :redis_password
7
+ end
8
+
9
+ def self.configure
10
+ yield(config)
11
+ config
12
+ end
13
+
14
+ def self.config
15
+ @config ||= Configuration.new
16
+ end
17
+ end
@@ -0,0 +1,125 @@
1
+ require 'docgen_adapter/configuration'
2
+ require 'redis'
3
+
4
+ class DocgenAdapter
5
+
6
+ def initialize(type:, doc_id:, debug: false)
7
+ # аргументы сервиса
8
+ @type = type
9
+ @doc_id = doc_id
10
+ @debug = Rails.env.development? && debug
11
+ @task_id = SecureRandom.uuid
12
+
13
+ # формирование названия генерируемого файла
14
+ dir = Dir.mktmpdir
15
+ @filename = "#{dir}/#{@task_id}_#{@doc_id}.#{@type}"
16
+ end
17
+
18
+ # выполнение генерации документа
19
+ def generate(params = {})
20
+ @service_params = build_params(params)
21
+
22
+ # отображение параметров для проверки
23
+ puts JSON.pretty_generate(JSON.parse(@service_params)) if @debug
24
+
25
+ # подписка ка канал и ожидание сообщений в другом потоке
26
+ Thread.new { subscribe_and_listen }
27
+
28
+ # ожидание
29
+ sleep(0.5)
30
+
31
+ # отправка сообщения с заданием
32
+ redis.publish('TASKS', @service_params)
33
+
34
+ # путь до сгенерированного файла в ответе
35
+ @filename
36
+ end
37
+
38
+ private
39
+
40
+ # соединение с микросервисом через Redis
41
+ def redis
42
+ @redis ||= Redis.new(
43
+ host: DocgenAdapter.config.redis_host,
44
+ port: DocgenAdapter.config.redis_port,
45
+ password: DocgenAdapter.config.redis_password
46
+ )
47
+ end
48
+
49
+ # подписаться на канал задания и ожидать сообщения
50
+ def subscribe_and_listen
51
+ redis.subscribe(@task_id) do |on|
52
+ on.subscribe do |channel|
53
+ puts "Подписка на канал задания #{channel}"
54
+ end
55
+
56
+ # обработка сообщений
57
+ on.message do |_channel, message|
58
+ handle_redis_message(message)
59
+ end
60
+
61
+ on.unsubscribe do |channel|
62
+ puts "Отписка от канала задания #{channel}"
63
+ end
64
+ end
65
+ end
66
+
67
+ # формирование объекта с параметрами
68
+ def build_params(params)
69
+ {
70
+ ИдентификаторЗадачи: @task_id,
71
+ ИдентификаторДокумента: @doc_id,
72
+ ТипДокумента: @type,
73
+ Md5ДополнительныхФайлов: [],
74
+ ПараметрыДокумента: params
75
+ }.to_json
76
+ end
77
+
78
+ # обработка сообщения пришедшего в канал Redis
79
+ def handle_redis_message(message)
80
+ # игнорируем сообщение с ID задания
81
+ return if message == @task_id
82
+
83
+ case message.encoding.to_s
84
+ when 'UTF-8'
85
+ handle_doc_info(message)
86
+ when 'ASCII-8BIT'
87
+ handle_doc_file(message)
88
+ end
89
+ end
90
+
91
+ # обработка JSON с информацией о документе
92
+ def handle_doc_info(message)
93
+ object = JSON.parse(message)
94
+
95
+ case object['Результат']
96
+ when 0
97
+ # успех
98
+ # TODO: добавить обработку
99
+ when 1
100
+ # ошибка
101
+ exception_msg = handle_exception(object)
102
+ raise StandardError.new(exception_msg)
103
+ end
104
+ end
105
+
106
+ # обработка бинарных данных файла документа
107
+ def handle_doc_file(message)
108
+ # запись бинарных данных в файл
109
+ File.write @filename, message.force_encoding('utf-8')
110
+
111
+ # сообщение с файлом приходит последним - отписка от канала Redis
112
+ redis.unsubscribe
113
+ end
114
+
115
+ def handle_exception(object)
116
+ text = "Генерация документа #{@doc_type}: #{object['ИдентификаторЗадачи']}\n" + object['ОписаниеОшибки']['Сообщение'] + object['ОписаниеОшибки']['СтекВызовов']
117
+
118
+ if Rails.env.development?
119
+ puts text
120
+ else
121
+ Rollbar.error(text, params: @service_params)
122
+ end
123
+ end
124
+
125
+ end
metadata ADDED
@@ -0,0 +1,67 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: docgen-adapter
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Павел Бабин
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2024-10-16 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: redis
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '5.3'
20
+ - - ">="
21
+ - !ruby/object:Gem::Version
22
+ version: 5.3.0
23
+ type: :runtime
24
+ prerelease: false
25
+ version_requirements: !ruby/object:Gem::Requirement
26
+ requirements:
27
+ - - "~>"
28
+ - !ruby/object:Gem::Version
29
+ version: '5.3'
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: 5.3.0
33
+ description: Адаптер собственного сервиса генерации документов
34
+ email: babin359@gmail.com
35
+ executables: []
36
+ extensions: []
37
+ extra_rdoc_files: []
38
+ files:
39
+ - README.md
40
+ - lib/docgen-adapter.rb
41
+ - lib/docgen_adapter.rb
42
+ - lib/docgen_adapter/configuration.rb
43
+ homepage:
44
+ licenses:
45
+ - MIT
46
+ metadata:
47
+ rubygems_mfa_required: 'true'
48
+ post_install_message:
49
+ rdoc_options: []
50
+ require_paths:
51
+ - lib
52
+ required_ruby_version: !ruby/object:Gem::Requirement
53
+ requirements:
54
+ - - ">="
55
+ - !ruby/object:Gem::Version
56
+ version: 3.1.0
57
+ required_rubygems_version: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ requirements: []
63
+ rubygems_version: 3.4.10
64
+ signing_key:
65
+ specification_version: 4
66
+ summary: Адаптер собственного сервиса генерации документов
67
+ test_files: []