|
| 1 | +require 'register_sources_bods/enums/statement_types' |
| 2 | + |
| 3 | +class BodsStatementSorter |
| 4 | + # accepts array of statements |
| 5 | + # returns sorted by publication date, with any statements referred to by relationships |
| 6 | + def sort_statements(statements) |
| 7 | + statements = statements.sort_by { |statement| statement.publicationDetails&.publicationDate } |
| 8 | + |
| 9 | + statements_by_id = statements.map { |statement| [statement.statementID, statement] }.to_h |
| 10 | + |
| 11 | + used_ids = Set.new |
| 12 | + new_statements = [] |
| 13 | + |
| 14 | + while new_statements.length < statements.length |
| 15 | + current_new_statement_count = new_statements.length |
| 16 | + |
| 17 | + statements.each do |statement| |
| 18 | + next if used_ids.include?(statement.statementID) |
| 19 | + |
| 20 | + replaced_ids = statement.replacesStatements || [] |
| 21 | + |
| 22 | + dependent_ids = |
| 23 | + case statement.statementType |
| 24 | + when RegisterSourcesBods::StatementTypes['personStatement'], RegisterSourcesBods::StatementTypes['entityStatement'] |
| 25 | + [] |
| 26 | + when RegisterSourcesBods::StatementTypes['ownershipOrControlStatement'] |
| 27 | + [ |
| 28 | + statement.subject&.describedByEntityStatement, |
| 29 | + statement.interestedParty&.describedByEntityStatement, |
| 30 | + statement.interestedParty&.describedByPersonStatement |
| 31 | + ].compact |
| 32 | + end |
| 33 | + |
| 34 | + all_dependent = (replaced_ids + dependent_ids).compact.uniq |
| 35 | + |
| 36 | + all_dependencies_satisfied = all_dependent.all? { |dependency_id| used_ids.include? dependency_id } |
| 37 | + |
| 38 | + next unless all_dependencies_satisfied |
| 39 | + |
| 40 | + new_statements << statement |
| 41 | + used_ids << statement.statementID |
| 42 | + end |
| 43 | + |
| 44 | + if current_new_statement_count == new_statements.count |
| 45 | + # This only happens when the level limiting means that there are relationship statements |
| 46 | + # without the entity dependency being in this statement list |
| 47 | + # In this scenario, these relationship statements should be skipped, so just stop here |
| 48 | + break |
| 49 | + end |
| 50 | + end |
| 51 | + |
| 52 | + new_statements |
| 53 | + end |
| 54 | +end |
0 commit comments