• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

pulibrary / pdc_describe / 03d8a05a-af84-47dc-84f0-6a23483b4931

19 Sep 2024 03:48PM UTC coverage: 96.167% (-0.02%) from 96.19%
03d8a05a-af84-47dc-84f0-6a23483b4931

Pull #1936

circleci

jrgriffiniii
Ensures that empty files and nil user IDs for WorkActivity objects raise ArgumentErrors
Pull Request #1936: Ensures that empty files and nil user IDs for WorkActivity objects raise ArgumentErrors

6 of 7 new or added lines in 3 files covered. (85.71%)

1 existing line in 1 file now uncovered.

3312 of 3444 relevant lines covered (96.17%)

204.69 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

95.27
/app/models/work_activity.rb
1
# frozen_string_literal: true
2

3
require_relative "../lib/diff_tools"
1✔
4

5
# rubocop:disable Metrics/ClassLength
6
class WorkActivity < ApplicationRecord
1✔
7
  MESSAGE = "COMMENT" # TODO: Migrate existing records to "MESSAGE"; then close #825.
1✔
8
  NOTIFICATION = "NOTIFICATION"
1✔
9
  MESSAGE_ACTIVITY_TYPES = [MESSAGE, NOTIFICATION].freeze
1✔
10

11
  CHANGES = "CHANGES"
1✔
12
  DATACITE_ERROR = "DATACITE-ERROR"
1✔
13
  FILE_CHANGES = "FILE-CHANGES"
1✔
14
  MIGRATION_START = "MIGRATION_START"
1✔
15
  MIGRATION_COMPLETE = "MIGRATION_COMPLETE"
1✔
16
  PROVENANCE_NOTES = "PROVENANCE-NOTES"
1✔
17
  SYSTEM = "SYSTEM"
1✔
18
  CHANGE_LOG_ACTIVITY_TYPES = [CHANGES, FILE_CHANGES, PROVENANCE_NOTES, SYSTEM, DATACITE_ERROR, MIGRATION_COMPLETE].freeze
1✔
19

20
  USER_REFERENCE = /@[\w]*/ # e.g. @xy123
1✔
21

22
  include Rails.application.routes.url_helpers
1✔
23

24
  belongs_to :work
1✔
25
  has_many :work_activity_notifications, dependent: :destroy
1✔
26

27
  def self.add_work_activity(work_id, message, user_id, activity_type:, created_at: nil)
1✔
28
    activity = WorkActivity.new(
448✔
29
      work_id:,
30
      activity_type:,
31
      message:,
32
      created_by_user_id: user_id,
33
      created_at: # If nil, will be set by activerecord at save.
34
    )
35
    activity.save!
448✔
36
    activity.notify_users
448✔
37
    activity
448✔
38
  end
39

40
  def self.activities_for_work(work_id, activity_types)
1✔
41
    where(work_id:, activity_type: activity_types)
671✔
42
  end
43

44
  def self.messages_for_work(work_id)
1✔
45
    activities_for_work(work_id, MESSAGE_ACTIVITY_TYPES)
274✔
46
  end
47

48
  def self.changes_for_work(work_id)
1✔
49
    activities_for_work(work_id, CHANGE_LOG_ACTIVITY_TYPES)
276✔
50
  end
51

52
  # Log notifications for each of the users references on the activity
53
  def notify_users
1✔
54
    users_referenced.each do |uid|
454✔
55
      user_id = User.where(uid:).first&.id
234✔
56
      if user_id.nil?
234✔
57
        notify_group(uid)
101✔
58
      else
59
        WorkActivityNotification.create(work_activity_id: id, user_id:)
133✔
60
      end
61
    end
62
  end
63

64
  def notify_group(groupid)
1✔
65
    group = Group.where(code: groupid).first
101✔
66
    if group.nil?
101✔
67
      Rails.logger.info("Message #{id} for work #{work_id} referenced an non-existing user: #{groupid}")
3✔
68
    else
69
      group.administrators.each do |admin|
98✔
70
        WorkActivityNotification.create(work_activity_id: id, user_id: admin.id)
59✔
71
      end
72
    end
73
  end
74

75
  # Returns the `uid` of the users referenced on the activity (without the `@` symbol)
76
  def users_referenced
1✔
77
    message.scan(USER_REFERENCE).map { |at_uid| at_uid[1..-1] }
688✔
78
  end
79

80
  def created_by_user
1✔
81
    return nil unless created_by_user_id
326✔
82

83
    User.find(created_by_user_id)
321✔
84
  end
85

86
  def message_event_type?
1✔
87
    MESSAGE_ACTIVITY_TYPES.include? activity_type
×
88
  end
89

90
  def log_event_type?
1✔
91
    CHANGE_LOG_ACTIVITY_TYPES.include? activity_type
×
92
  end
93

94
  def renderer
1✔
95
    @renderer ||= begin
120✔
96
                    klass = if activity_type == CHANGES
119✔
97
                              MetadataChanges
32✔
98
                            elsif activity_type == FILE_CHANGES
87✔
99
                              FileChanges
10✔
100
                            elsif activity_type == MIGRATION_COMPLETE
77✔
101
                              Migration
1✔
102
                            elsif activity_type == PROVENANCE_NOTES
76✔
103
                              ProvenanceNote
5✔
104
                            elsif CHANGE_LOG_ACTIVITY_TYPES.include?(activity_type)
71✔
105
                              OtherLogEvent
33✔
106
                            else
107
                              Message
38✔
108
                            end
109
                    klass.new(self)
119✔
110

111
                  end
112
  end
113

114
  delegate :to_html, to: :renderer
1✔
115

116
  class Renderer
1✔
117
    def initialize(work_activity)
1✔
118
      @work_activity = work_activity
119✔
119
    end
120

121
    UNKNOWN_USER = "Unknown user outside the system"
1✔
122
    DATE_TIME_FORMAT = "%B %d, %Y %H:%M"
1✔
123
    DATE_FORMAT = "%B %d, %Y"
1✔
124
    SORTABLE_DATE_TIME_FORMAT = "%Y-%m-%d %H:%M"
1✔
125

126
    def to_html
1✔
127
      title_html + "<span class='message-html'>#{body_html.chomp}</span>"
115✔
128
    end
129

130
    def created_by_user_html
1✔
131
      return UNKNOWN_USER unless @work_activity.created_by_user
81✔
132

133
      "#{@work_activity.created_by_user.given_name_safe} (@#{@work_activity.created_by_user.uid})"
77✔
134
    end
135

136
    def created_sortable_html
1✔
137
      @work_activity.created_at.time.strftime(SORTABLE_DATE_TIME_FORMAT)
5✔
138
    end
139

140
    def created_updated_html
1✔
141
      created = @work_activity.created_at.time.strftime(DATE_TIME_FORMAT)
115✔
142
      updated = @work_activity.updated_at.time.strftime(DATE_TIME_FORMAT)
115✔
143
      created_date = @work_activity.created_at.time.strftime(DATE_FORMAT)
115✔
144
      updated_date = @work_activity.updated_at.time.strftime(DATE_FORMAT)
115✔
145
      if created_date == updated_date
115✔
146
        created
103✔
147
      else
148
        "#{created} (backdated event created #{updated})"
12✔
149
      end
150
    end
151

152
    def title_html
1✔
153
      "<span class='activity-history-title'>#{created_updated_html} by #{created_by_user_html}</span>"
76✔
154
    end
155
  end
156

157
  class MetadataChanges < Renderer
1✔
158
    # Returns the message formatted to display _metadata_ changes that were logged as an activity
159
    def body_html
1✔
160
      message_json = JSON.parse(@work_activity.message)
32✔
161

162
      # Messages should consistently be Arrays of Hashes, but this might require a migration from legacy field records
163
      messages = if message_json.is_a?(Array)
32✔
164
                   message_json
×
165
                 else
166
                   Array.wrap(message_json)
32✔
167
                 end
168

169
      elements = messages.map do |message|
32✔
170
        markup = if message.is_a?(Hash)
32✔
171
                   message.keys.map do |field|
32✔
172
                     mapped = message[field].map { |value| change_value_html(value) }
176✔
173
                     "<details class='message-html'><summary class='show-changes'>#{field&.titleize}</summary>#{mapped.join}</details>"
88✔
174
                   end
175
                 else
176
                   # For handling cases where WorkActivity#message only contains Strings, or Arrays of Strings
177
                   [
178
                     "<details class='message-html'><summary class='show-changes'></summary>#{message}</details>"
×
179
                   ]
180
                 end
181
        markup.join
32✔
182
      end
183

184
      elements.flatten.join
32✔
185
    end
186

187
    def change_value_html(value)
1✔
188
      if value["action"] == "changed"
88✔
189
        DiffTools::SimpleDiff.new(value["from"], value["to"]).to_html
88✔
190
      else
191
        "old change"
×
192
      end
193
    end
194
  end
195

196
  class FileChanges < Renderer
1✔
197
    # Returns the message formatted to display _file_ changes that were logged as an activity
198
    def body_html
1✔
199
      changes = JSON.parse(@work_activity.message)
10✔
200
      if changes.is_a?(Hash)
10✔
201
        changes = [changes]
1✔
202
      end
203

204
      files_added = changes.select { |v| v["action"] == "added" }
30✔
205
      files_deleted = changes.select { |v| v["action"] == "removed" }
30✔
206
      files_replaced = changes.select { |v| v["action"] == "replaced" }
30✔
207

208
      changes_html = []
10✔
209
      unless files_added.empty?
10✔
210
        label = "Files Added: "
9✔
211
        label += files_added.length.to_s
9✔
212
        changes_html << "<tr><td>#{label}</td></tr>"
9✔
213
      end
214

215
      unless files_deleted.empty?
10✔
216
        label = "Files Deleted: "
2✔
217
        label += files_deleted.length.to_s
2✔
218
        changes_html << "<tr><td>#{label}</td></tr>"
2✔
219
      end
220

221
      unless files_replaced.empty?
10✔
222
        label = "Files Replaced: "
1✔
223
        label += files_replaced.length.to_s
1✔
224
        changes_html << "<tr><td>#{label}</td></tr>"
1✔
225
      end
226

227
      "<table>#{changes_html.join}</table>"
10✔
228
    end
229
  end
230

231
  class Migration < Renderer
1✔
232
    # Returns the message formatted to display _file_ changes that were logged as an activity
233
    def body_html
1✔
234
      changes = JSON.parse(@work_activity.message)
1✔
235
      "<p>#{changes['message']}</p>"
1✔
236
    end
237
  end
238

239
  class BaseMessage < Renderer
1✔
240
    def body_html
1✔
241
      text = user_refernces(@work_activity.message)
72✔
242
      mark_down_to_html(text)
72✔
243
    end
244

245
    def mark_down_to_html(text_in)
1✔
246
      # allow ``` for code blocks (Kramdown only supports ~~~)
247
      text = text_in.gsub("```", "~~~")
77✔
248
      Kramdown::Document.new(text).to_html
77✔
249
    end
250

251
    def user_refernces(text_in)
1✔
252
      # convert user references to user links
253
      text_in.gsub(USER_REFERENCE) do |at_uid|
77✔
254
        uid = at_uid[1..-1]
50✔
255

256
        if uid
50✔
257
          group = Group.find_by(code: uid)
50✔
258
          if group
50✔
259
            "<a class='message-user-link' title='#{group.title}' href='#{@work_activity.group_path(group)}'>#{group.title}</a>"
22✔
260
          else
261
            user = User.find_by(uid:)
28✔
262
            user_info = if user
28✔
263
                          user.given_name_safe
28✔
264
                        else
265
                          uid
×
266
                        end
267
            "<a class='message-user-link' title='#{user_info}' href='#{@work_activity.users_path}/#{uid}'>#{at_uid}</a>"
28✔
268
          end
269
        else
NEW
270
          Rails.logger.warn("Failed to extract the user ID from #{uid}")
×
UNCOV
271
          UNKNOWN_USER
×
272
        end
273
      end
274
    end
275
  end
276

277
  class OtherLogEvent < BaseMessage
1✔
278
  end
279

280
  class Message < BaseMessage
1✔
281
    # Override the default:
282
    def created_by_user_html
1✔
283
      return UNKNOWN_USER unless @work_activity.created_by_user
39✔
284

285
      user = @work_activity.created_by_user
38✔
286
      "#{user.given_name_safe} (@#{user.uid})"
38✔
287
    end
288

289
    def title_html
1✔
290
      "<span class='activity-history-title'>#{created_by_user_html} at #{created_updated_html}</span>"
39✔
291
    end
292
  end
293

294
  class ProvenanceNote < BaseMessage
1✔
295
    def body_html
1✔
296
      message_hash = JSON.parse(@work_activity.message)
5✔
297
      text = user_refernces(message_hash["note"])
5✔
298
      message = mark_down_to_html(text)
5✔
299
      change_label = message_hash["change_label"]&.titleize
5✔
300
      change_label ||= "Change"
5✔
301
      # TODO: Make this show the change label with the note under see changes
302
      "<details class='message-html'><summary class='show-changes'>#{change_label}</summary>#{message}</details>"
5✔
303
    end
304
  end
305
end
306
# rubocop:enable Metrics/ClassLength
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc