students_lab4_s0195941 0.1.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: 98d9755635837a41233209956b536c3b7c4697c3da369d0533462255e0f61baa
4
+ data.tar.gz: 0650577a2363c75d54296ba17d2ef4cc74f16f5f82b47351ef8ca2d0b45fa064
5
+ SHA512:
6
+ metadata.gz: 84ec7b37b7c7deb70a67a039b2ffd0677943e794ada1dec85289e1d5075ee137c94bb73d6d2426032876e197caef25badb23c8bcda18d617e900961ea0bc7994
7
+ data.tar.gz: c585038ba12535870e2915087c01582fb76c8b85fd04ce88a7d477efbbb1b26dbdf992b3209662e3f29090d42876c3a79089049279ee6bd8091144aac364e95a
data/README.md ADDED
@@ -0,0 +1,15 @@
1
+ Загляни в issues, в Лабораторную работу 0(L0).
2
+
3
+ ## Лабораторная работа 4 — каталог студентов
4
+
5
+ Для запуска нужны Ruby 3.3 или новее, графическая среда для FXRuby и PostgreSQL.
6
+ В новой базе выполните `db/create_student_table.sql` и `db/add_unique_student_contacts.sql`.
7
+ Для демонстрационных данных выполните `db/seed_students.sql` один раз. Если таблица уже создана, примените только миграцию уникальности.
8
+ SQL-файлы также доступны в каталоге `db` установленного гема (`gem contents students_lab4_s0195941`).
9
+
10
+ По умолчанию приложение подключается к базе `students_lab4` на `127.0.0.1:5432` под пользователем `postgres`.
11
+ Настройки можно переопределить через `PGHOST`, `PGPORT`, `PGDATABASE` и `PGUSER`.
12
+ Для пароля используйте локальный файл PostgreSQL `pgpass.conf` на Windows или `.pgpass` на Linux.
13
+
14
+ Из рабочего каталога проект запускается командой `ruby src/student_list_app.rb`.
15
+ После установки гема запускайте `students-lab4-s0195941`.
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'students_lab4_s0195941'
4
+
5
+ StudentsLab4.run
@@ -0,0 +1,12 @@
1
+ BEGIN;
2
+
3
+ CREATE UNIQUE INDEX IF NOT EXISTS student_unique_git
4
+ ON student (lower(regexp_replace(git, '^https://(www\.)?', 'https://')));
5
+ CREATE UNIQUE INDEX IF NOT EXISTS student_unique_phone
6
+ ON student (regexp_replace(regexp_replace(phone, '[^0-9]', '', 'g'), '^8([0-9]{10})$', '7\1'));
7
+ CREATE UNIQUE INDEX IF NOT EXISTS student_unique_telegram
8
+ ON student (lower(telegram));
9
+ CREATE UNIQUE INDEX IF NOT EXISTS student_unique_email
10
+ ON student (lower(email));
11
+
12
+ COMMIT;
@@ -0,0 +1,10 @@
1
+ CREATE TABLE student (
2
+ id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
3
+ last_name text NOT NULL,
4
+ first_name text NOT NULL,
5
+ patronymic text,
6
+ phone text,
7
+ telegram text,
8
+ email text,
9
+ git text
10
+ );
@@ -0,0 +1,5 @@
1
+ INSERT INTO student (last_name, first_name, phone, telegram, email, git)
2
+ VALUES
3
+ ('Иванов', 'Иван', '+79161234567', NULL, NULL, 'https://github.com/lab4-ivanov'),
4
+ ('Петрова', 'Анна', NULL, '@lab4_anna', 'anna@example.com', NULL),
5
+ ('Сидоров', 'Павел', NULL, NULL, NULL, NULL);
@@ -0,0 +1 @@
1
+ require_relative '../src/student_list_app'
@@ -0,0 +1,9 @@
1
+ require_relative 'student_form_controller'
2
+
3
+ class CreateStudentController < StudentFormController
4
+ private
5
+
6
+ def persist(student)
7
+ @students.add(student)
8
+ end
9
+ end
data/src/data_list.rb ADDED
@@ -0,0 +1,57 @@
1
+ require_relative 'data_table'
2
+
3
+ class Data_list
4
+ def initialize(list)
5
+ @selected = []
6
+ @names = get_names.map { |name| name.dup.freeze }.freeze
7
+ self.list = list
8
+ end
9
+
10
+ def list=(list)
11
+ @list = list.map { |element| element.dup.freeze }.freeze
12
+ clear_selected
13
+ nil
14
+ end
15
+
16
+ def select(number)
17
+ unless number.is_a?(Integer) && number >= 0 && number < @list.length
18
+ raise IndexError, 'Номер элемента находится за пределами списка'
19
+ end
20
+
21
+ @selected << number unless @selected.include?(number)
22
+ nil
23
+ end
24
+
25
+ def get_selected
26
+ @selected.map { |number| @list[number].id }
27
+ end
28
+
29
+ def get_names
30
+ return @names.dup unless @names.nil?
31
+
32
+ ['№ по порядку'] + get_attribute_names
33
+ end
34
+
35
+ def get_data
36
+ rows = @list.each_with_index.map do |element, index|
37
+ [index + 1] + get_object_data(element)
38
+ end
39
+
40
+ Data_table.new(rows)
41
+ end
42
+
43
+ def clear_selected
44
+ @selected.clear
45
+ nil
46
+ end
47
+
48
+ private
49
+
50
+ def get_attribute_names
51
+ raise NotImplementedError, 'Наследник должен реализовать get_attribute_names'
52
+ end
53
+
54
+ def get_object_data(element)
55
+ raise NotImplementedError, 'Наследник должен реализовать get_object_data'
56
+ end
57
+ end
@@ -0,0 +1,41 @@
1
+ require_relative 'data_list'
2
+
3
+ class Data_list_student_short < Data_list
4
+ attr_reader :whole_entities_count
5
+
6
+ def initialize(list)
7
+ super
8
+ @whole_entities_count = list.length
9
+ @observers = []
10
+ end
11
+
12
+ def add_observer(observer)
13
+ @observers << observer unless @observers.include?(observer)
14
+ end
15
+
16
+ def notify
17
+ column_names = get_names
18
+ table = get_data
19
+ @observers.dup.each do |observer|
20
+ observer.set_table_params(column_names, @whole_entities_count)
21
+ observer.set_table_data(table)
22
+ end
23
+ nil
24
+ end
25
+
26
+ def replace_page(students, count)
27
+ self.list = students
28
+ @whole_entities_count = count
29
+ nil
30
+ end
31
+
32
+ private
33
+
34
+ def get_attribute_names
35
+ ['Фамилия и инициалы', 'Контакт', 'Git']
36
+ end
37
+
38
+ def get_object_data(student)
39
+ [student.last_name_initials, student.contact, student.git]
40
+ end
41
+ end
data/src/data_table.rb ADDED
@@ -0,0 +1,30 @@
1
+ class Data_table
2
+ def initialize(table)
3
+ unless table.is_a?(Array) && table.all? { |row| row.is_a?(Array) }
4
+ raise ArgumentError, 'Таблица должна быть двумерным массивом'
5
+ end
6
+
7
+ columns = table.empty? ? 0 : table.first.length
8
+
9
+ unless table.all? { |row| row.length == columns }
10
+ raise ArgumentError, 'Строки таблицы должны иметь одинаковую длину'
11
+ end
12
+
13
+ @table = table.map do |row|
14
+ row.map { |element| element.dup.freeze }.freeze
15
+ end.freeze
16
+ end
17
+
18
+ def get_element(row, column)
19
+ @table.fetch(row).fetch(column)
20
+ end
21
+
22
+ def get_columns
23
+ @table.empty? ? 0 : @table.first.length
24
+ end
25
+
26
+ def get_rows
27
+ @table.length
28
+ end
29
+
30
+ end
data/src/db.rb ADDED
@@ -0,0 +1,14 @@
1
+ require 'pg'
2
+
3
+ module DB
4
+ def self.connect(&block)
5
+ PG.connect(
6
+ host: ENV.fetch('PGHOST', '127.0.0.1'),
7
+ port: ENV.fetch('PGPORT', '5432'),
8
+ dbname: ENV.fetch('PGDATABASE', 'students_lab4'),
9
+ user: ENV.fetch('PGUSER', 'postgres'),
10
+ connect_timeout: 5,
11
+ &block
12
+ )
13
+ end
14
+ end
data/src/student.rb ADDED
@@ -0,0 +1,126 @@
1
+ require_relative 'student_base'
2
+ require_relative 'validated_attr_writer'
3
+
4
+ class Student < StudentBase
5
+ include Comparable
6
+ singleton_class.prepend(ValidatedAttrWriter)
7
+
8
+ attr_accessor :last_name, :first_name, :patronymic
9
+ attr_reader :phone, :telegram, :email
10
+ attr_writer :git, :phone, :telegram, :email
11
+ private :phone=, :telegram=, :email=
12
+
13
+ def <=>(other)
14
+ return nil unless other.is_a?(Student)
15
+
16
+ [last_name, first_name, patronymic.to_s] <=>
17
+ [other.last_name, other.first_name, other.patronymic.to_s]
18
+ end
19
+
20
+ def initialize(last_name:, first_name:, id: nil, patronymic: nil,
21
+ phone: nil, telegram: nil, email: nil, git: nil)
22
+ raise ArgumentError, "Невалидный ID: #{id}" unless valid_id?(id)
23
+
24
+ super(id: id)
25
+ self.contact = { phone: phone, telegram: telegram, email: email }
26
+
27
+ self.last_name = last_name
28
+ self.first_name = first_name
29
+ self.patronymic = patronymic
30
+ self.git = git
31
+ end
32
+
33
+ def self.from_hash(attributes)
34
+ new(
35
+ id: attributes['id'],
36
+ last_name: attributes['last_name'],
37
+ first_name: attributes['first_name'],
38
+ patronymic: attributes['patronymic'],
39
+ phone: attributes['phone'],
40
+ telegram: attributes['telegram'],
41
+ email: attributes['email'],
42
+ git: attributes['git']
43
+ )
44
+ end
45
+
46
+ def self.valid_name?(name)
47
+ valid_format?(name, /\A[А-ЯЁA-Z][а-яёa-z]+\z/, required: true)
48
+ end
49
+
50
+ def self.valid_phone?(phone)
51
+ valid_format?(
52
+ phone,
53
+ /\A(?:\+7\d{10}|8\d{10}|8\(\d{3}\)\d{3}-\d{2}-\d{2})\z/
54
+ )
55
+ end
56
+
57
+ def self.valid_telegram?(telegram)
58
+ valid_format?(telegram, /\A@[a-zA-Z0-9_]{5,32}\z/)
59
+ end
60
+
61
+ def self.valid_email?(email)
62
+ valid_format?(email, /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i)
63
+ end
64
+
65
+ def self.valid_git?(git)
66
+ valid_format?(git, /\Ahttps:\/\/(www\.)?(github|gitlab)\.com\/[\w\-]+\z/)
67
+ end
68
+
69
+ def self.valid_format?(value, pattern, required: false)
70
+ return !required if value.nil?
71
+
72
+ value.is_a?(String) && value.match?(pattern)
73
+ end
74
+
75
+ def self.valid_last_name?(value)
76
+ valid_name?(value)
77
+ end
78
+
79
+ def self.valid_first_name?(value)
80
+ valid_name?(value)
81
+ end
82
+
83
+ def self.valid_patronymic?(value)
84
+ value.nil? || valid_name?(value)
85
+ end
86
+
87
+ private_class_method :valid_format?, :valid_last_name?, :valid_first_name?, :valid_patronymic?
88
+
89
+ def contact
90
+ return "telegram - #{@telegram}" if @telegram
91
+ return "email - #{@email}" if @email
92
+ return "phone - #{@phone}" if @phone
93
+
94
+ nil
95
+ end
96
+
97
+ def contact=(contacts)
98
+ self.phone = contacts[:phone]
99
+ self.telegram = contacts[:telegram]
100
+ self.email = contacts[:email]
101
+ end
102
+
103
+ def last_name_initials
104
+ initials = "#{last_name} #{first_name[0]}."
105
+ initials += " #{patronymic[0]}." if patronymic
106
+ initials
107
+ end
108
+
109
+ def to_s
110
+ fio = "#{last_name} #{first_name}"
111
+ fio += " #{patronymic}" if patronymic
112
+ parts = [fio]
113
+ parts << "ID: #{id}" if id
114
+ parts << "git: #{git}" if git
115
+ parts << "phone: #{@phone}" if @phone
116
+ parts << "telegram: #{@telegram}" if @telegram
117
+ parts << "email: #{@email}" if @email
118
+ parts.join(", ")
119
+ end
120
+
121
+ private
122
+
123
+ def valid_id?(value)
124
+ value.nil? || value.to_s.match?(/\A\d+\z/)
125
+ end
126
+ end
@@ -0,0 +1,33 @@
1
+ class StudentBase
2
+ attr_reader :id, :git
3
+
4
+ def initialize(id:, git: nil)
5
+ @id = id
6
+ @git = git
7
+ end
8
+
9
+ def has_git?
10
+ !git.nil?
11
+ end
12
+
13
+ def has_contact?
14
+ !contact.nil?
15
+ end
16
+
17
+ def last_name_initials
18
+ raise NotImplementedError, 'Наследник должен реализовать last_name_initials'
19
+ end
20
+
21
+ def contact
22
+ raise NotImplementedError, 'Наследник должен реализовать contact'
23
+ end
24
+
25
+ def short_info
26
+ parts = [last_name_initials]
27
+ parts << "ID: #{id}" if id
28
+ selected_contact = contact
29
+ parts << selected_contact if selected_contact
30
+ parts << "git: #{git}" if git
31
+ parts.join(", ")
32
+ end
33
+ end
@@ -0,0 +1,48 @@
1
+ require_relative 'student'
2
+ require_relative 'students_list'
3
+
4
+ class StudentFormController
5
+ def initialize(view, students)
6
+ @view = view
7
+ @students = students
8
+ end
9
+
10
+ def open
11
+ @view.open(self, initial_attributes)
12
+ end
13
+
14
+ def changed(attributes)
15
+ @view.set_submit_enabled(!build_student(attributes).nil?)
16
+ end
17
+
18
+ def submit(attributes)
19
+ student = build_student(attributes)
20
+ return unless student
21
+
22
+ @view.accept if persist(student)
23
+ rescue Students_list::DuplicateContact => error
24
+ @view.show_duplicate_contact(error.field)
25
+ rescue Students_list::ConnectionLost
26
+ @view.show_connection_error
27
+ end
28
+
29
+ private
30
+
31
+ def initial_attributes
32
+ {}
33
+ end
34
+
35
+ def persist(student)
36
+ raise NotImplementedError
37
+ end
38
+
39
+ def build_student(attributes)
40
+ normalized = attributes.transform_values do |value|
41
+ text = value.strip
42
+ text.empty? ? nil : text
43
+ end
44
+ Student.new(**normalized)
45
+ rescue ArgumentError
46
+ nil
47
+ end
48
+ end
@@ -0,0 +1,71 @@
1
+ require 'fox16'
2
+
3
+ class StudentFormView < Fox::FXDialogBox
4
+ FIELD_LABELS = {
5
+ last_name: 'Фамилия',
6
+ first_name: 'Имя',
7
+ patronymic: 'Отчество',
8
+ phone: 'Телефон',
9
+ telegram: 'Telegram',
10
+ email: 'Email',
11
+ git: 'Git'
12
+ }.freeze
13
+
14
+ def initialize(owner, title)
15
+ super(owner, title, Fox::DECOR_TITLE | Fox::DECOR_BORDER | Fox::DECOR_CLOSE)
16
+
17
+ content = Fox::FXVerticalFrame.new(self, Fox::LAYOUT_FILL_X | Fox::LAYOUT_FILL_Y)
18
+ fields = Fox::FXMatrix.new(content, 2, Fox::MATRIX_BY_COLUMNS | Fox::LAYOUT_FILL_X)
19
+ @inputs = FIELD_LABELS.to_h do |attribute, label|
20
+ Fox::FXLabel.new(fields, label)
21
+ [attribute, Fox::FXTextField.new(fields, 32, opts: Fox::TEXTFIELD_NORMAL | Fox::LAYOUT_FILL_X)]
22
+ end
23
+
24
+ buttons = Fox::FXHorizontalFrame.new(content, Fox::LAYOUT_FILL_X)
25
+ @ok_button = Fox::FXButton.new(buttons, 'ОК')
26
+ @ok_button.disable
27
+ Fox::FXButton.new(buttons, 'Отмена', nil, self, Fox::FXDialogBox::ID_CANCEL)
28
+
29
+ @inputs.each_value do |input|
30
+ input.connect(Fox::SEL_CHANGED) { @controller.changed(attributes) }
31
+ end
32
+ @ok_button.connect(Fox::SEL_COMMAND) { @controller.submit(attributes) }
33
+ end
34
+
35
+ def open(controller, initial_attributes)
36
+ @inputs.each do |attribute, input|
37
+ input.text = initial_attributes[attribute].to_s
38
+ end
39
+ @controller = controller
40
+ @controller.changed(attributes)
41
+ execute(Fox::PLACEMENT_OWNER)
42
+ ensure
43
+ @controller = nil
44
+ end
45
+
46
+ def set_submit_enabled(enabled)
47
+ enabled ? @ok_button.enable : @ok_button.disable
48
+ end
49
+
50
+ def accept
51
+ handle(self, Fox.MKUINT(Fox::FXDialogBox::ID_ACCEPT, Fox::SEL_COMMAND), nil)
52
+ end
53
+
54
+ def show_duplicate_contact(field)
55
+ label = FIELD_LABELS.fetch(field)
56
+ message = "Значение поля «#{label}» уже указано у другого студента."
57
+ Fox::FXMessageBox.error(self, Fox::MBOX_OK, 'Контакт уже занят', message)
58
+ @inputs.fetch(field).setFocus
59
+ end
60
+
61
+ def show_connection_error
62
+ message = 'Связь прервалась при сохранении. Закройте форму и обновите список, чтобы проверить результат.'
63
+ Fox::FXMessageBox.error(self, Fox::MBOX_OK, 'База данных недоступна', message)
64
+ end
65
+
66
+ private
67
+
68
+ def attributes
69
+ @inputs.transform_values(&:text)
70
+ end
71
+ end
@@ -0,0 +1,18 @@
1
+ require_relative 'db'
2
+ require_relative 'student_list_view'
3
+
4
+ module StudentsLab4
5
+ def self.run
6
+ DB.connect do |connection|
7
+ app = Fox::FXApp.new
8
+ view = StudentListView.new(app, connection)
9
+
10
+ app.create
11
+ view.refresh_data
12
+ view.show(Fox::PLACEMENT_SCREEN)
13
+ app.run
14
+ end
15
+ end
16
+ end
17
+
18
+ StudentsLab4.run if $PROGRAM_NAME == __FILE__
@@ -0,0 +1,89 @@
1
+ require_relative 'students_list'
2
+ require_relative 'create_student_controller'
3
+ require_relative 'update_student_controller'
4
+
5
+ class StudentListController
6
+ PAGE_SIZE = 2
7
+ attr_reader :page
8
+
9
+ def initialize(view, connection)
10
+ @view = view
11
+ @students = Students_list.new(connection)
12
+ @page = 1
13
+ @incomplete_only = false
14
+ @data_list = Data_list_student_short.new([])
15
+ @data_list.add_observer(@view)
16
+ end
17
+
18
+ def refresh_data
19
+ load_page
20
+ last_page = [total_pages, 1].max
21
+ if @page > last_page
22
+ @page = last_page
23
+ load_page
24
+ end
25
+ @data_list.notify
26
+ rescue Students_list::ConnectionLost
27
+ @view.show_connection_error('Не удалось загрузить список. Когда база заработает, нажмите «Обновить».')
28
+ end
29
+
30
+ def show_incomplete_students(incomplete_only)
31
+ @incomplete_only = incomplete_only
32
+ @page = 1
33
+ refresh_data
34
+ end
35
+
36
+ def delete_selected(row_numbers)
37
+ ids = selected_student_ids(row_numbers)
38
+ return if ids.empty?
39
+
40
+ @students.delete_many(ids)
41
+ refresh_data
42
+ rescue Students_list::ConnectionLost
43
+ @view.show_connection_error('Связь прервалась при удалении. Обновите список, чтобы проверить результат.')
44
+ end
45
+
46
+ def open_create_form
47
+ form = @view.build_student_form
48
+ CreateStudentController.new(form, @students).open
49
+ refresh_data
50
+ end
51
+
52
+ def open_update_form(row_numbers)
53
+ ids = selected_student_ids(row_numbers)
54
+ return unless ids.one?
55
+
56
+ student = @students.get_by_id(ids.first)
57
+ if student
58
+ form = @view.build_student_form('Изменить студента')
59
+ UpdateStudentController.new(form, @students, student).open
60
+ end
61
+ refresh_data
62
+ rescue Students_list::ConnectionLost
63
+ @view.show_connection_error('Не удалось загрузить студента. Когда база заработает, нажмите «Обновить».')
64
+ end
65
+
66
+ def total_pages
67
+ (@data_list.whole_entities_count + PAGE_SIZE - 1) / PAGE_SIZE
68
+ end
69
+
70
+ def change_page(step)
71
+ next_page = @page + step
72
+ return unless next_page.between?(1, total_pages)
73
+
74
+ @page = next_page
75
+ refresh_data
76
+ end
77
+
78
+ private
79
+
80
+ def load_page
81
+ @students.get_k_n_student_short_list(@page, PAGE_SIZE, @data_list, incomplete_only: @incomplete_only)
82
+ end
83
+
84
+ def selected_student_ids(row_numbers)
85
+ @data_list.clear_selected
86
+ row_numbers.each { |row| @data_list.select(row) }
87
+ @data_list.get_selected
88
+ end
89
+ end
@@ -0,0 +1,100 @@
1
+ require 'fox16'
2
+ require_relative 'student_list_controller'
3
+ require_relative 'student_form_view'
4
+
5
+ class StudentListView < Fox::FXMainWindow
6
+ def initialize(app, connection)
7
+ super(app, 'Список студентов', width: 850, height: 420)
8
+
9
+ content = Fox::FXVerticalFrame.new(self, Fox::LAYOUT_FILL_X | Fox::LAYOUT_FILL_Y)
10
+ table_area = Fox::FXGroupBox.new(content, 'Студенты', Fox::FRAME_GROOVE | Fox::LAYOUT_FILL_X | Fox::LAYOUT_FILL_Y)
11
+ table_content = Fox::FXVerticalFrame.new(table_area, Fox::LAYOUT_FILL_X | Fox::LAYOUT_FILL_Y)
12
+ navigation = Fox::FXHorizontalFrame.new(table_content, Fox::LAYOUT_FILL_X)
13
+ @previous_page = Fox::FXButton.new(navigation, 'Назад')
14
+ @page_label = Fox::FXLabel.new(navigation, '')
15
+ @next_page = Fox::FXButton.new(navigation, 'Далее')
16
+ incomplete_filter = Fox::FXCheckButton.new(navigation, 'Только без Git или контакта')
17
+ incomplete_filter.setCheck(0)
18
+ @table = Fox::FXTable.new(table_content, opts: Fox::LAYOUT_FILL_X | Fox::LAYOUT_FILL_Y | Fox::TABLE_READONLY)
19
+ @table.rowHeaderMode = Fox::LAYOUT_FIX_WIDTH
20
+ @table.rowHeaderWidth = 0
21
+ controls = Fox::FXGroupBox.new(content, 'Управление', Fox::FRAME_GROOVE | Fox::LAYOUT_FILL_X)
22
+ buttons = Fox::FXHorizontalFrame.new(controls, Fox::LAYOUT_FILL_X)
23
+ add_button = Fox::FXButton.new(buttons, 'Добавить')
24
+ @edit_button = Fox::FXButton.new(buttons, 'Изменить')
25
+ @delete_button = Fox::FXButton.new(buttons, 'Удалить')
26
+ @refresh_button = Fox::FXButton.new(buttons, 'Обновить')
27
+
28
+ @controller = StudentListController.new(self, connection)
29
+ add_button.connect(Fox::SEL_COMMAND) { @controller.open_create_form }
30
+ @previous_page.connect(Fox::SEL_COMMAND) { @controller.change_page(-1) }
31
+ @next_page.connect(Fox::SEL_COMMAND) { @controller.change_page(1) }
32
+ incomplete_filter.connect(Fox::SEL_COMMAND) do |button|
33
+ @controller.show_incomplete_students(button.checkState == 1)
34
+ end
35
+ @refresh_button.connect(Fox::SEL_COMMAND) { refresh_data }
36
+ @edit_button.connect(Fox::SEL_COMMAND) { @controller.open_update_form(selected_rows) }
37
+ @delete_button.connect(Fox::SEL_COMMAND) { @controller.delete_selected(selected_rows) }
38
+
39
+ @table.connect(Fox::SEL_SELECTED) { update_action_buttons; 0 }
40
+ @table.connect(Fox::SEL_DESELECTED) { update_action_buttons; 0 }
41
+ update_action_buttons
42
+ end
43
+
44
+ def refresh_data
45
+ @controller.refresh_data
46
+ end
47
+
48
+ def build_student_form(title = 'Добавить студента')
49
+ StudentFormView.new(self, title)
50
+ end
51
+
52
+ def show_connection_error(message)
53
+ @table.setTableSize(0, @table.numColumns)
54
+ @previous_page.disable
55
+ @next_page.disable
56
+ update_action_buttons
57
+ @page_label.text = 'База данных недоступна'
58
+ Fox::FXMessageBox.error(self, Fox::MBOX_OK, 'База данных недоступна', message)
59
+ end
60
+
61
+ def set_table_params(column_names, whole_entities_count)
62
+ @column_names = column_names
63
+ total_pages = @controller.total_pages
64
+ page = total_pages.zero? ? 0 : @controller.page
65
+ @page_label.text = "Страница #{page} из #{total_pages} | Всего записей: #{whole_entities_count}"
66
+ page > 1 ? @previous_page.enable : @previous_page.disable
67
+ page < total_pages ? @next_page.enable : @next_page.disable
68
+ end
69
+
70
+ def set_table_data(data_table)
71
+ @table.killSelection
72
+ @table.setTableSize(data_table.get_rows, @column_names.length)
73
+
74
+ @column_names.each_with_index do |name, column|
75
+ @table.setColumnText(column, name)
76
+ @table.setColumnWidth(column, column.zero? ? 100 : 225)
77
+ end
78
+
79
+ data_table.get_rows.times do |row|
80
+ @column_names.length.times do |column|
81
+ @table.setItemText(row, column, data_table.get_element(row, column).to_s)
82
+ end
83
+ end
84
+ update_action_buttons
85
+ end
86
+
87
+ private
88
+
89
+ def selected_rows
90
+ @table.numRows.times.select do |row|
91
+ @table.numColumns.times.any? { |column| @table.itemSelected?(row, column) }
92
+ end
93
+ end
94
+
95
+ def update_action_buttons
96
+ selected_count = selected_rows.length
97
+ selected_count == 1 ? @edit_button.enable : @edit_button.disable
98
+ selected_count.positive? ? @delete_button.enable : @delete_button.disable
99
+ end
100
+ end
@@ -0,0 +1,29 @@
1
+ require_relative 'student_base'
2
+
3
+ class StudentShort < StudentBase
4
+ attr_reader :last_name_initials, :contact
5
+
6
+ def initialize(id:, last_name_initials:, contact: nil, git: nil)
7
+ raise ArgumentError, 'ID обязателен' if id.nil?
8
+ raise ArgumentError, 'Фамилия и инициалы обязательны' if last_name_initials.nil?
9
+
10
+ super(id: id, git: git)
11
+
12
+ @last_name_initials = last_name_initials
13
+ @contact = contact
14
+ end
15
+
16
+ def self.from_student(student)
17
+ new(
18
+ id: student.id,
19
+ last_name_initials: student.last_name_initials,
20
+ contact: student.contact,
21
+ git: student.git
22
+ )
23
+ end
24
+
25
+ def to_s
26
+ short_info
27
+ end
28
+
29
+ end
@@ -0,0 +1,172 @@
1
+ require 'logger'
2
+ require 'pg'
3
+ require_relative 'student'
4
+ require_relative 'student_short'
5
+ require_relative 'data_list_student_short'
6
+
7
+ class Students_list
8
+ class ConnectionLost < StandardError; end
9
+
10
+ class DuplicateContact < StandardError
11
+ attr_reader :field
12
+
13
+ def initialize(field)
14
+ @field = field
15
+ super("Контакт #{field} уже занят")
16
+ end
17
+ end
18
+
19
+ CONTACT_FIELDS_BY_INDEX = {
20
+ 'student_unique_git' => :git,
21
+ 'student_unique_phone' => :phone,
22
+ 'student_unique_telegram' => :telegram,
23
+ 'student_unique_email' => :email
24
+ }.freeze
25
+
26
+ def initialize(connection, logger: Logger.new($stderr))
27
+ @connection = connection
28
+ @logger = logger
29
+ end
30
+
31
+ def get_by_id(id)
32
+ query(:get_by_id, 'SELECT * FROM student WHERE id = $1', [id]) do |result|
33
+ row = result.first
34
+ Student.from_hash(row) if row
35
+ end
36
+ end
37
+
38
+ def get_k_n_student_short_list(k, n, target = nil, incomplete_only: false)
39
+ unless k.is_a?(Integer) && k.positive? && n.is_a?(Integer) && n.positive?
40
+ raise ArgumentError, 'Номер страницы и её размер должны быть положительными целыми числами'
41
+ end
42
+
43
+ sql = <<~SQL
44
+ WITH matching_students AS (
45
+ SELECT * FROM student
46
+ WHERE NOT $3::boolean OR git IS NULL
47
+ OR (phone IS NULL AND telegram IS NULL AND email IS NULL)
48
+ )
49
+ SELECT page.*, totals.whole_entities_count
50
+ FROM (SELECT COUNT(*) AS whole_entities_count FROM matching_students) AS totals
51
+ LEFT JOIN (
52
+ SELECT * FROM matching_students ORDER BY id LIMIT $1 OFFSET $2
53
+ ) AS page ON TRUE
54
+ ORDER BY page.id
55
+ SQL
56
+
57
+ query(:load_page, sql, [n, (k - 1) * n, incomplete_only]) do |result|
58
+ count = result.first.fetch('whole_entities_count').to_i
59
+ students = result.filter_map do |row|
60
+ StudentShort.from_student(Student.from_hash(row)) if row['id']
61
+ end
62
+
63
+ target ||= Data_list_student_short.new([])
64
+ target.replace_page(students, count)
65
+ target
66
+ end
67
+ end
68
+
69
+ def add(student)
70
+ sql = <<~SQL
71
+ INSERT INTO student (last_name, first_name, patronymic, phone, telegram, email, git)
72
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
73
+ RETURNING id
74
+ SQL
75
+
76
+ id = query(:add, sql, student_values(student)) do |result|
77
+ result.first.fetch('id').to_i
78
+ end
79
+ @logger.info("student.add id=#{id}")
80
+ id
81
+ rescue PG::UniqueViolation => error
82
+ raise_contact_conflict(error)
83
+ end
84
+
85
+ def replace(id, student)
86
+ sql = <<~SQL
87
+ UPDATE student
88
+ SET last_name = $1, first_name = $2, patronymic = $3,
89
+ phone = $4, telegram = $5, email = $6, git = $7
90
+ WHERE id = $8
91
+ RETURNING id
92
+ SQL
93
+
94
+ saved_id = query(:replace, sql, student_values(student) + [id]) do |result|
95
+ row = result.first
96
+ row.fetch('id').to_i if row
97
+ end
98
+ @logger.info("student.replace id=#{saved_id}") if saved_id
99
+ saved_id
100
+ rescue PG::UniqueViolation => error
101
+ raise_contact_conflict(error)
102
+ end
103
+
104
+ def delete(id)
105
+ deleted_id = with_database(:delete) { delete_record(id) }
106
+ @logger.info("student.delete id=#{deleted_id}") if deleted_id
107
+ deleted_id
108
+ end
109
+
110
+ def delete_many(ids)
111
+ deleted_ids = with_database(:delete_many) do
112
+ @connection.transaction do
113
+ ids.filter_map { |id| delete_record(id) }
114
+ end
115
+ end
116
+ deleted_ids.each { |id| @logger.info("student.delete id=#{id}") }
117
+ ids
118
+ end
119
+
120
+ def count
121
+ query(:count, 'SELECT COUNT(*) AS whole_entities_count FROM student', []) do |result|
122
+ result.first.fetch('whole_entities_count').to_i
123
+ end
124
+ end
125
+
126
+ private
127
+
128
+ def delete_record(id)
129
+ @connection.exec_params('DELETE FROM student WHERE id = $1 RETURNING id', [id]) do |result|
130
+ row = result.first
131
+ row.fetch('id').to_i if row
132
+ end
133
+ end
134
+
135
+ def query(operation, sql, params, &block)
136
+ with_database(operation) { @connection.exec_params(sql, params, &block) }
137
+ end
138
+
139
+ def with_database(operation)
140
+ if @connection_lost
141
+ @connection.reset
142
+ @connection_lost = false
143
+ end
144
+ yield
145
+ rescue PG::Error => error
146
+ sqlstate = error.result&.error_field(PG::Result::PG_DIAG_SQLSTATE)
147
+ @logger.error("student.#{operation} failed (#{error.class}, SQLSTATE=#{sqlstate || 'unknown'})")
148
+ unless error.is_a?(PG::ConnectionBad) || @connection.status == PG::CONNECTION_BAD ||
149
+ sqlstate&.start_with?('08') || %w[57P01 57P02 57P03].include?(sqlstate)
150
+ raise
151
+ end
152
+
153
+ @connection_lost = true
154
+ raise ConnectionLost, 'Соединение с PostgreSQL недоступно'
155
+ rescue StandardError => error
156
+ @logger.error("student.#{operation} failed (#{error.class})")
157
+ raise
158
+ end
159
+
160
+ def raise_contact_conflict(error)
161
+ index = error.result&.error_field(PG::Result::PG_DIAG_CONSTRAINT_NAME)
162
+ field = CONTACT_FIELDS_BY_INDEX[index]
163
+ raise error unless field
164
+
165
+ raise DuplicateContact.new(field)
166
+ end
167
+
168
+ def student_values(student)
169
+ [student.last_name, student.first_name, student.patronymic,
170
+ student.phone, student.telegram, student.email, student.git]
171
+ end
172
+ end
@@ -0,0 +1,26 @@
1
+ require_relative 'student_form_controller'
2
+
3
+ class UpdateStudentController < StudentFormController
4
+ def initialize(view, students, original_student)
5
+ super(view, students)
6
+ @original_student = original_student
7
+ end
8
+
9
+ private
10
+
11
+ def initial_attributes
12
+ {
13
+ last_name: @original_student.last_name,
14
+ first_name: @original_student.first_name,
15
+ patronymic: @original_student.patronymic,
16
+ phone: @original_student.phone,
17
+ telegram: @original_student.telegram,
18
+ email: @original_student.email,
19
+ git: @original_student.git
20
+ }
21
+ end
22
+
23
+ def persist(student)
24
+ @students.replace(@original_student.id, student)
25
+ end
26
+ end
@@ -0,0 +1,24 @@
1
+ module ValidatedAttrWriter
2
+ def attr_writer(*attributes)
3
+ attributes.map do |attribute|
4
+ validator = :"valid_#{attribute}?"
5
+
6
+ define_method("#{attribute}=") do |value|
7
+ unless self.class.respond_to?(validator, true)
8
+ raise NotImplementedError, "#{self.class} должен реализовать #{validator}"
9
+ end
10
+
11
+ unless self.class.send(validator, value)
12
+ raise ArgumentError, "Невалидное значение #{attribute}: #{value.inspect}"
13
+ end
14
+
15
+ instance_variable_set("@#{attribute}", value)
16
+ end
17
+ end
18
+ end
19
+
20
+ def attr_accessor(*attributes)
21
+ attr_reader(*attributes)
22
+ attr_writer(*attributes)
23
+ end
24
+ end
metadata ADDED
@@ -0,0 +1,108 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: students_lab4_s0195941
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - s0195941
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: fxruby
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '1.6'
19
+ - - ">="
20
+ - !ruby/object:Gem::Version
21
+ version: 1.6.51
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ requirements:
26
+ - - "~>"
27
+ - !ruby/object:Gem::Version
28
+ version: '1.6'
29
+ - - ">="
30
+ - !ruby/object:Gem::Version
31
+ version: 1.6.51
32
+ - !ruby/object:Gem::Dependency
33
+ name: logger
34
+ requirement: !ruby/object:Gem::Requirement
35
+ requirements:
36
+ - - "~>"
37
+ - !ruby/object:Gem::Version
38
+ version: '1.6'
39
+ type: :runtime
40
+ prerelease: false
41
+ version_requirements: !ruby/object:Gem::Requirement
42
+ requirements:
43
+ - - "~>"
44
+ - !ruby/object:Gem::Version
45
+ version: '1.6'
46
+ - !ruby/object:Gem::Dependency
47
+ name: pg
48
+ requirement: !ruby/object:Gem::Requirement
49
+ requirements:
50
+ - - "~>"
51
+ - !ruby/object:Gem::Version
52
+ version: '1.7'
53
+ type: :runtime
54
+ prerelease: false
55
+ version_requirements: !ruby/object:Gem::Requirement
56
+ requirements:
57
+ - - "~>"
58
+ - !ruby/object:Gem::Version
59
+ version: '1.7'
60
+ description: FXRuby application for listing, creating, editing and deleting students
61
+ in PostgreSQL.
62
+ executables:
63
+ - students-lab4-s0195941
64
+ extensions: []
65
+ extra_rdoc_files: []
66
+ files:
67
+ - README.md
68
+ - bin/students-lab4-s0195941
69
+ - db/add_unique_student_contacts.sql
70
+ - db/create_student_table.sql
71
+ - db/seed_students.sql
72
+ - lib/students_lab4_s0195941.rb
73
+ - src/create_student_controller.rb
74
+ - src/data_list.rb
75
+ - src/data_list_student_short.rb
76
+ - src/data_table.rb
77
+ - src/db.rb
78
+ - src/student.rb
79
+ - src/student_base.rb
80
+ - src/student_form_controller.rb
81
+ - src/student_form_view.rb
82
+ - src/student_list_app.rb
83
+ - src/student_list_controller.rb
84
+ - src/student_list_view.rb
85
+ - src/student_short.rb
86
+ - src/students_list.rb
87
+ - src/update_student_controller.rb
88
+ - src/validated_attr_writer.rb
89
+ licenses: []
90
+ metadata: {}
91
+ rdoc_options: []
92
+ require_paths:
93
+ - lib
94
+ required_ruby_version: !ruby/object:Gem::Requirement
95
+ requirements:
96
+ - - ">="
97
+ - !ruby/object:Gem::Version
98
+ version: '3.3'
99
+ required_rubygems_version: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - ">="
102
+ - !ruby/object:Gem::Version
103
+ version: '0'
104
+ requirements: []
105
+ rubygems_version: 4.0.16
106
+ specification_version: 4
107
+ summary: Desktop student directory for the MVC design patterns lab
108
+ test_files: []