Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ptime mapper script #737

Draft
wants to merge 80 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 36 commits
Commits
Show all changes
80 commits
Select commit Hold shift + click to select a range
a77a77d
Create migration to add ptime id to person model
RandomTannenbaum Jun 21, 2024
665bf0b
Start writing mapper script
RandomTannenbaum Jun 21, 2024
2f1660f
Implement basic PTime client class and install webmock gem
ManuelMoeri Jun 24, 2024
0555ec7
Create new migration to fix naming of ptime_emplyoee_id attribute
ManuelMoeri Jun 24, 2024
83fa511
Add first test to see how webmock works
ManuelMoeri Jun 24, 2024
fbc8987
Fix first client spec
RandomTannenbaum Jun 24, 2024
6a75e33
Write json body to test employee endpoint
RandomTannenbaum Jun 25, 2024
6a9a89a
Fix tests by allowing localhost connection and write negative test fo…
RandomTannenbaum Jun 25, 2024
9ddd723
Make ptime client specs not read values from env variables
RandomTannenbaum Jun 25, 2024
7ab6727
Set error messages on errors in client and change test data urls to e…
RandomTannenbaum Jun 25, 2024
8f85e91
Fix params of ptime client and implement basic mapper script
RandomTannenbaum Jun 25, 2024
f945378
Add new tests and remove unnecessary
RandomTannenbaum Jun 25, 2024
933c2fc
Add test for ambiguous matched people
ManuelMoeri Jun 26, 2024
ff37bcc
Add email to filter before matching as well
ManuelMoeri Jun 26, 2024
244369f
Possibly make rubocop happy
ManuelMoeri Jun 26, 2024
7e58084
Try to make rubocop happy again
ManuelMoeri Jun 26, 2024
132424a
Add evaluate task for mapping script
RandomTannenbaum Jun 27, 2024
2070ffb
Outsource mapper script code to methods and fix tests
RandomTannenbaum Jun 27, 2024
b89c933
Add test for dry run
RandomTannenbaum Jun 27, 2024
b44a2d0
Make rubocop happy :)
RandomTannenbaum Jun 27, 2024
f9be66c
Remove unnecessary requires
RandomTannenbaum Jun 27, 2024
104185e
Replace .count == 1 with .one?
RandomTannenbaum Jun 27, 2024
aa4c5f5
Start writing script that updates the data of the people in skills
RandomTannenbaum Jun 27, 2024
7d775c3
Write script that maps the data from a ptime employee to the correspo…
RandomTannenbaum Jun 28, 2024
82d03f0
Disable rubocop metrics all together instead of one by one in assign …
RandomTannenbaum Jun 28, 2024
96913d2
Fix file naming of spec files
RandomTannenbaum Jun 28, 2024
907da90
Move class into module and fix mapping of person to employee data, wr…
RandomTannenbaum Jun 28, 2024
35f4b0d
Fix updating of people data and test it and fix faulty key in json us…
RandomTannenbaum Jun 28, 2024
1190569
Fix update people data specs by assigning the ptime base url env var …
RandomTannenbaum Jun 28, 2024
5ac5585
Only update ptime employee id if its not already set
RandomTannenbaum Jun 28, 2024
8c8e0e4
Test if marital status can be changed in specs
RandomTannenbaum Jun 28, 2024
dd0bacd
Write rake task that runs the people update
RandomTannenbaum Jun 28, 2024
b2d5d0b
Show message in assign employee ids script conditionally
RandomTannenbaum Jun 28, 2024
dbe7132
Add delayed jobs and daemon gems and start writing delayed jobs
RandomTannenbaum Jul 1, 2024
6fb4df1
Fix specs to work with delayed job
RandomTannenbaum Jul 2, 2024
480e328
Remove delayed job functionality
RandomTannenbaum Jul 3, 2024
138fab7
Add first approach for fetching people from ptime API
ManuelMoeri Jul 4, 2024
7f6abdd
Add helper and write test for fetching employee data
ManuelMoeri Jul 4, 2024
ea3d4e5
Finish test and fix logic in displaying people
ManuelMoeri Jul 5, 2024
3a6b7c0
Implement correct routing of person and fix a problem in the docker s…
ManuelMoeri Jul 5, 2024
c25e18c
Possibly fix docker compose file
ManuelMoeri Jul 8, 2024
4385c4a
Fix tests and implement logic for sorting people
ManuelMoeri Jul 8, 2024
202006a
Implement logic for fallback and cleanup helper method
ManuelMoeri Jul 9, 2024
1dc3065
Improve fallback logic by making it more readable and shorter
ManuelMoeri Jul 9, 2024
1267736
Implement first approach on calling the ptime api after 5 minutes
ManuelMoeri Jul 10, 2024
512593b
Improve logic of 5 minutes request and change client.rb
ManuelMoeri Jul 11, 2024
c9e9825
Add logic to load site correctly and remove unnecessary code
ManuelMoeri Jul 12, 2024
39acf6e
Fix logic of rendering people and cleanup code
ManuelMoeri Jul 15, 2024
d967660
Add tests for person_helper
ManuelMoeri Jul 17, 2024
c657e8f
Add ptime_helpers to cleanup code
ManuelMoeri Jul 17, 2024
bcb3ebe
Fix tests
ManuelMoeri Jul 17, 2024
456f27b
Fix last test and remove pry
ManuelMoeri Jul 17, 2024
4718e92
Fix test and add comment
ManuelMoeri Jul 18, 2024
bf771aa
Generalize window resizing of capybara
ManuelMoeri Jul 18, 2024
189ab80
Cleanup code and add comments
ManuelMoeri Jul 19, 2024
2e2ae6b
Add one more test for client.rb
ManuelMoeri Jul 19, 2024
766e942
Reverse test from last commit
ManuelMoeri Jul 19, 2024
aa36e82
change location of helper
kcinay055679 Jul 25, 2024
4153a5b
set ptime stubing global
kcinay055679 Jul 25, 2024
87d84d8
clean up ptime client specs
kcinay055679 Jul 25, 2024
96391b2
create json file for fixtures
kcinay055679 Jul 25, 2024
cce291b
use hashes instead of strings for json keys create global ptime stub …
kcinay055679 Jul 25, 2024
d3bb9c3
use custom ptime stubbing method everywhere
kcinay055679 Jul 25, 2024
dd96900
fix tests after always using [:data]
kcinay055679 Jul 25, 2024
0d1c4ff
clean up ptime client
kcinay055679 Jul 25, 2024
7550234
improve structure of people search
kcinay055679 Jul 25, 2024
552cf7d
Client isn't longer controlled by random env vars
kcinay055679 Jul 25, 2024
d9c02be
simplify ptime_helpers
kcinay055679 Jul 25, 2024
44d76bd
clean up PR
kcinay055679 Jul 26, 2024
71db98a
Clean up Skills db fallback logic
kcinay055679 Jul 26, 2024
3a7997a
improve readability by using more helper
kcinay055679 Jul 26, 2024
d19bd8e
clean up
kcinay055679 Jul 26, 2024
57ad58a
add client test
kcinay055679 Jul 29, 2024
5411381
Merge pull request #748 from puzzle/feature/745-fetch-people-search-e…
kcinay055679 Jul 29, 2024
af3def7
ds muäs so
kcinay055679 Jul 29, 2024
2763d61
so its aber
kcinay055679 Jul 29, 2024
d272a03
Resolve conversations
RandomTannenbaum Jul 29, 2024
48fb6be
Remove unneeded spec and fix spec that tests the not found case when …
RandomTannenbaum Jul 30, 2024
a52ceaa
Fix order of name interpolation in id mapper script
RandomTannenbaum Jul 30, 2024
65fb684
Update json fixtures and use full_name instead of interpolating it
RandomTannenbaum Jul 30, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -99,3 +99,5 @@ config/docker/development/home/rails/.bash_history

/app/assets/builds/*
!/app/assets/builds/.keep

.sec
1 change: 1 addition & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ group :test do
gem 'capybara'
gem 'selenium-webdriver', '>= 4.11.8'
gem 'simplecov'
gem 'webmock'
# Use fixed version of webdrivers to avoid compatibility issues with chrome and chromedriver
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
Expand Down
18 changes: 18 additions & 0 deletions Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ GEM
ast (2.4.2)
base64 (0.2.0)
bcrypt (3.1.20)
bigdecimal (3.1.8)
bindata (2.5.0)
bleib (0.0.8)
bootsnap (1.18.3)
Expand Down Expand Up @@ -118,9 +119,13 @@ GEM
deep_merge (~> 1.2, >= 1.2.1)
countries (6.0.0)
unaccent (~> 0.3)
crack (1.0.0)
RandomTannenbaum marked this conversation as resolved.
Show resolved Hide resolved
bigdecimal
rexml
crass (1.0.6)
cssbundling-rails (1.4.0)
railties (>= 6.0.0)
daemons (1.4.1)
database_cleaner (2.0.2)
database_cleaner-active_record (>= 2, < 3)
database_cleaner-active_record (2.1.0)
Expand All @@ -129,6 +134,11 @@ GEM
database_cleaner-core (2.0.1)
date (3.3.4)
deep_merge (1.2.2)
delayed_job (4.1.11)
activesupport (>= 3.0, < 8.0)
delayed_job_active_record (4.1.8)
activerecord (>= 3.0, < 8.0)
delayed_job (>= 3.0, < 5)
devise (4.9.4)
bcrypt (~> 3.0)
orm_adapter (~> 0.1)
Expand Down Expand Up @@ -166,6 +176,7 @@ GEM
rainbow
rubocop (>= 1.0)
sysexits (~> 1.1)
hashdiff (1.1.0)
hashie (5.0.0)
http-accept (1.7.0)
http-cookie (1.0.5)
Expand Down Expand Up @@ -444,6 +455,10 @@ GEM
version_gem (1.1.4)
warden (1.2.9)
rack (>= 2.0.9)
webmock (3.23.1)
addressable (>= 2.8.0)
crack (>= 0.3.2)
hashdiff (>= 0.4.0, < 2.0.0)
websocket (1.2.10)
websocket-driver (0.7.6)
websocket-extensions (>= 0.1.0)
Expand All @@ -469,7 +484,9 @@ DEPENDENCIES
config
countries
cssbundling-rails
daemons
database_cleaner
delayed_job_active_record
devise
dotenv
faker
Expand Down Expand Up @@ -517,6 +534,7 @@ DEPENDENCIES
stimulus-rails
turbo-rails
tzinfo-data
webmock

BUNDLED WITH
2.4.10
69 changes: 69 additions & 0 deletions app/domain/ptime/assign_employee_ids.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# This script will assign each person the corresponding employee ID from PuzzleTime
module Ptime
class AssignEmployeeIds

# rubocop:disable Rails/Output
def run(should_map: false)
puts 'Notice this is a dry run and mapping will not happen!' unless should_map
fetch_data

puts "Currently there are:
- #{@ptime_employees.length} employees in PuzzleTime
- #{@skills_people.count} people in PuzzleSkills
This is a difference of #{(@skills_people.count - @ptime_employees.length).abs} entries"
map_employees(should_map)
end

private

# rubocop:disable Metrics
def map_employees(should_map)
puts 'Assigning employee IDs now...' if should_map

ambiguous_entries = []
unmatched_entries = []
mapped_people_count = 0

@ptime_employees.each do |ptime_employee|
ptime_employee_firstname = ptime_employee['attributes']['firstname']
ptime_employee_lastname = ptime_employee['attributes']['lastname']
ptime_employee_name = "#{ptime_employee_firstname} #{ptime_employee_lastname}"
RandomTannenbaum marked this conversation as resolved.
Show resolved Hide resolved
ptime_employee_email = ptime_employee['attributes']['email']
matched_skills_people = Person.where(ptime_employee_id: nil)
.where(name: ptime_employee_name)
.where(email: ptime_employee_email)
RandomTannenbaum marked this conversation as resolved.
Show resolved Hide resolved

if matched_skills_people.empty?
RandomTannenbaum marked this conversation as resolved.
Show resolved Hide resolved
unmatched_entries << { name: ptime_employee_name, id: ptime_employee['id'] }
elsif matched_skills_people.one?
RandomTannenbaum marked this conversation as resolved.
Show resolved Hide resolved
if should_map
matched_skills_person = matched_skills_people.first
RandomTannenbaum marked this conversation as resolved.
Show resolved Hide resolved
matched_skills_person.ptime_employee_id = ptime_employee['id']
matched_skills_person.save!
end
mapped_people_count += 1
else
ambiguous_entries << { name: ptime_employee_name, id: ptime_employee['id'] }
end
end

puts '--------------------------'
puts "#{mapped_people_count} people were matched successfully"
puts '--------------------------'
puts "#{unmatched_entries.size} people didn't match"
unmatched_entries.each { |entry| puts "- #{entry[:name]} with id #{entry[:id]}" }
puts '--------------------------'
puts "#{ambiguous_entries.size} people ambiguous matched"
ambiguous_entries.each { |entry| puts "- #{entry[:name]} with id #{entry[:id]}" }
end
# rubocop:enable Metrics

def fetch_data
puts 'Fetching required data...'
@ptime_employees = Ptime::Client.new.get('employees', { per_page: 1000 })['data']
RandomTannenbaum marked this conversation as resolved.
Show resolved Hide resolved
@skills_people = Person.all
puts 'Successfully fetched data'
end
# rubocop:enable Rails/Output
end
end
46 changes: 46 additions & 0 deletions app/domain/ptime/client.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# frozen_string_literal: true

require 'rest_client'
require 'base64'

module Ptime
class Client
def initialize
@base_url = "#{ENV.fetch('PTIME_BASE_URL')}/api/v1/"
end

def get(endpoint, params = {})
request(:get, @base_url + endpoint, params)
end

private

def request(method, path, params = nil)
path = "#{path}?#{URI.encode_www_form(params)}"
RandomTannenbaum marked this conversation as resolved.
Show resolved Hide resolved
response = RestClient.send(method, path, headers)
JSON.parse(response.body)
rescue RestClient::BadRequest => e
msg = response_error_message(e)
e.message = msg if msg.present?
raise e
end

def response_error_message(exception)
JSON.parse(exception.response.body).dig('error', 'message')
rescue JSON::ParserError # rescue only JSON parsing errors
RandomTannenbaum marked this conversation as resolved.
Show resolved Hide resolved
nil
end

def headers
{
authorization: "Basic #{basic_token}",
content_type: :json,
accept: :json
}
end

def basic_token
Base64.encode64("#{ENV.fetch('PTIME_API_USERNAME')}:#{ENV.fetch('PTIME_API_PASSWORD')}")
end
end
end
35 changes: 35 additions & 0 deletions app/domain/ptime/update_people_data.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# frozen_string_literal: true

module Ptime
class UpdatePeopleData
ATTRIBUTE_MAPPING = { shortname: :shortname, email: :email, marital_status: :marital_status,
graduation: :title }.freeze

# rubocop:disable Metrics
def run
ptime_employees = Ptime::Client.new.get('employees', { per_page: 1000 })['data']
ptime_employees.each do |ptime_employee|
ptime_employee_firstname = ptime_employee['attributes']['firstname']
ptime_employee_lastname = ptime_employee['attributes']['lastname']
ptime_employee_name = "#{ptime_employee_firstname} #{ptime_employee_lastname}"

skills_person = Person.find_by(ptime_employee_id: ptime_employee['id'])
skills_person ||= Person.new

skills_person.name = ptime_employee_name
skills_person.ptime_employee_id ||= ptime_employee['id']
ptime_employee['attributes'].each do |key, value|
if key.to_sym.in?(ATTRIBUTE_MAPPING.keys)
skills_person[ATTRIBUTE_MAPPING[key.to_sym]] = value
end
end
skills_person.company = Company.first
skills_person.birthdate = '1.1.2000'
skills_person.location = 'Bern'
skills_person.nationality = 'CH'
skills_person.save!
end
end
# rubocop:enable Metrics
end
end
5 changes: 5 additions & 0 deletions bin/delayed_job
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#!/usr/bin/env ruby

require File.expand_path(File.join(File.dirname(__FILE__), '..', 'config', 'environment'))
require 'delayed/command'
Delayed::Command.new(ARGV).daemonize
2 changes: 2 additions & 0 deletions config/application.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,5 +37,7 @@ class Application < Rails::Application

config.assets.enabled = true
config.assets.paths << Rails.root.join("uploads")

config.active_job.queue_adapter = :delayed_job
RandomTannenbaum marked this conversation as resolved.
Show resolved Hide resolved
end
end
5 changes: 5 additions & 0 deletions db/migrate/20240624122411_add_ptime_employee_id_to_people.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
class AddPtimeEmployeeIdToPeople < ActiveRecord::Migration[7.0]
def change
add_column :people, :ptime_employee_id, :integer
end
end
22 changes: 22 additions & 0 deletions db/migrate/20240701085558_create_delayed_jobs.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
class CreateDelayedJobs < ActiveRecord::Migration[7.0]
def self.up
create_table :delayed_jobs do |table|
table.integer :priority, default: 0, null: false # Allows some jobs to jump to the front of the queue
table.integer :attempts, default: 0, null: false # Provides for retries, but still fail eventually.
table.text :handler, null: false # YAML-encoded string of the object that will do work
table.text :last_error # reason for last failure (See Note below)
table.datetime :run_at # When to run. Could be Time.zone.now for immediately, or sometime in the future.
table.datetime :locked_at # Set when a client is working on this object
table.datetime :failed_at # Set when all retries have failed (actually, by default, the record is deleted instead)
table.string :locked_by # Who is working on this object (if locked)
table.string :queue # The name of the queue this job is in
table.timestamps null: true
end

add_index :delayed_jobs, [:priority, :run_at], name: "delayed_jobs_priority"
end

def self.down
drop_table :delayed_jobs
end
end
18 changes: 17 additions & 1 deletion db/schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.

ActiveRecord::Schema[7.0].define(version: 2024_06_03_085509) do
ActiveRecord::Schema[7.0].define(version: 2024_07_01_085558) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"

Expand Down Expand Up @@ -77,6 +77,21 @@
t.datetime "updated_at", precision: nil, null: false
end

create_table "delayed_jobs", force: :cascade do |t|
t.integer "priority", default: 0, null: false
t.integer "attempts", default: 0, null: false
t.text "handler", null: false
t.text "last_error"
t.datetime "run_at"
t.datetime "locked_at"
t.datetime "failed_at"
t.string "locked_by"
t.string "queue"
t.datetime "created_at"
t.datetime "updated_at"
t.index ["priority", "run_at"], name: "delayed_jobs_priority"
end

create_table "departments", force: :cascade do |t|
t.string "name", null: false
t.datetime "created_at", null: false
Expand Down Expand Up @@ -148,6 +163,7 @@
t.string "email"
t.integer "department_id"
t.string "shortname"
t.integer "ptime_employee_id"
t.index ["company_id"], name: "index_people_on_company_id"
end

Expand Down
4 changes: 3 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ services:
stdin_open: true
environment:
- RAILS_DB_HOST=postgres
env_file: .env
env_file:
- .env
- .sec
build:
context: ./config/docker/development
dockerfile: Rails.dockerfile
Expand Down
16 changes: 16 additions & 0 deletions lib/tasks/ptime.rake
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
namespace :ptime do
desc 'assign puzzletime employee ids to people'
task :assign => :environment do
Ptime::AssignEmployeeIds.new.run(should_map: true)
end

desc 'evaluate assignment of employee ids to people'
task :evaluate_assign => :environment do
Ptime::AssignEmployeeIds.new.run
end

desc 'update person data with the data from ptime'
task :update_people => :environment do
Ptime::UpdatePeopleData.new.run
end
end
Loading
Loading