Skip to content

Commit 1fef7ca

Browse files
committed
Basic gem for controlling timesleeps on Freeagent.
0 parents  commit 1fef7ca

File tree

8 files changed

+346
-0
lines changed

8 files changed

+346
-0
lines changed

.github/workflows/main.yml

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
name: Ruby
2+
3+
on:
4+
push:
5+
branches:
6+
- main
7+
8+
pull_request:
9+
10+
jobs:
11+
build:
12+
runs-on: ubuntu-latest
13+
name: Ruby ${{ matrix.ruby }}
14+
strategy:
15+
matrix:
16+
ruby:
17+
- '3.2.0'
18+
19+
steps:
20+
- uses: actions/checkout@v4
21+
- name: Set up Ruby
22+
uses: ruby/setup-ruby@v1
23+
with:
24+
ruby-version: ${{ matrix.ruby }}
25+
bundler-cache: true
26+
- name: Run the default task
27+
run: bundle exec rake

.gitignore

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
.env
2+
.token.yml
3+
*.gem

LICENSE

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
The MIT License (MIT)
2+
3+
Copyright © 2025 Register Dynamics Limited.
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6+
7+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8+
9+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

README.txt

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
freeagent-cli: Access and control Freeagent data from the command line.
2+
3+
This gem supplies a `fa` executable which can create, read, update and delete
4+
data using the Freeagent API.
5+
6+
You need to specify valid Freeagent app credentials. Generate a Freeagent app at
7+
https://dev.freeagent.com/apps. Ensure you set 'http://localhost:*/' as a valid
8+
OAuth redirect URI. Then export your ID and secret as environment variables
9+
FREEAGENT_APP_ID and FREEAGENT_APP_SECRET. On first run, `fa` will authenticate
10+
you via OAuth so watch out for an authentication URI printed to the console.

Rakefile

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# frozen_string_literal: true
2+
3+
require "bundler/gem_tasks"
4+
task default: %i[]

exe/fa

+80
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
#!/usr/bin/env ruby
2+
3+
require 'thor'
4+
require_relative '../lib/freeagent'
5+
6+
def match type, collection, needle, *values
7+
found = collection.select do |item|
8+
values.map(&:to_proc).any? {|v| v.call(item) == needle }
9+
end
10+
if found.none?
11+
possibles = collection.product(values).map {|item, value| value.to_proc.call(item).to_s }
12+
raise ArgumentError, "No #{type} matching '#{needle}' found, expecting one from #{possibles}"
13+
end
14+
unless found.one?
15+
raise ArgumentError, "Ambiguous #{type}: could be #{found.map(&:url).join(', ')}"
16+
end
17+
found.first
18+
end
19+
20+
module Freeagent
21+
class Timeslips < Thor
22+
no_commands do
23+
def api
24+
@api ||= API.new
25+
end
26+
end
27+
28+
desc 'list USER PROJECT TASK FROM TO', "List timeslips"
29+
def list user, project, task, from, to
30+
from = Date::parse from
31+
to = Date::parse to
32+
user = match :user, api.users, user, :first_name, :last_name, :email
33+
project = match :project, api.projects, project, :name
34+
task = match :task, api.tasks(project), task, :name
35+
36+
api.timeslips(user, project, task, from, to).each do |timeslip|
37+
puts [Date::parse(timeslip.dated_on).strftime('%a %d %b %Y'), user.email, project.name, task.name, timeslip.hours].join("\t")
38+
end
39+
end
40+
41+
desc 'create USER PROJECT TASK FROM TO', "Create timeslips"
42+
method_option :hours, aliases: '-h', type: :numeric, default: 8, desc: "Number of hours per day"
43+
method_option :weekends, aliases: '-w', type: :boolean, default: false, desc: "Create timeslips on Saturdays and Sundays"
44+
def create user, project, task, from, to
45+
from = Date::parse from
46+
to = Date::parse to
47+
user = match :user, api.users, user, :first_name, :last_name, :email
48+
project = match :project, api.projects, project, :name
49+
task = match :task, api.tasks(project), task, :name
50+
51+
puts "Creating timeslips for #{user.first_name} #{user.last_name} for task '#{task.name}' in project '#{project.name}' between #{from} and #{to} inclusive"
52+
timeslips = from.step(to).map do |date|
53+
next if (date.saturday? || date.sunday?) && !options[:weekends]
54+
{'task' => task.url, 'project' => project.url, 'user' => user.url, 'dated_on' => date.to_s, 'hours' => options[:hours]}
55+
end.reject(&:nil?)
56+
api.batch_create_timeslips timeslips
57+
end
58+
59+
desc 'delete USER PROJECT TASK FROM TO', 'Delete timeslips'
60+
def delete user, project, task, from, to
61+
from = Date::parse from
62+
to = Date::parse to
63+
user = match :user, api.users, user, :first_name, :last_name, :email
64+
project = match :project, api.projects, project, :name
65+
task = match :task, api.tasks(project), task, :name
66+
67+
puts "Deleting timeslips for #{user.first_name} #{user.last_name} for task '#{task.name}' in project '#{project.name}' between #{from} and #{to} inclusive"
68+
api.timeslips(user, project, task, from, to).each do |timeslip|
69+
api.delete_timeslip(timeslip)
70+
end
71+
end
72+
end
73+
74+
class Command < Thor
75+
desc "timeslips", "Create, read, update and delete timeslips"
76+
subcommand "timeslips", Timeslips
77+
end
78+
end
79+
80+
Freeagent::Command.start

freeagent-cli.gemspec

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# frozen_string_literal: true
2+
3+
Gem::Specification.new do |spec|
4+
spec.name = 'freeagent-cli'
5+
spec.version = '0.1'
6+
spec.authors = ['Simon Worthington']
7+
spec.email = ['simon@register-dynamics.co.uk']
8+
9+
readme = File.read('README.txt').split("\n")
10+
spec.summary = readme.first
11+
spec.description = readme[1..].join("\n").strip
12+
spec.homepage = 'https://www.github.com/register-dynamics/freeagent-cli'
13+
spec.required_ruby_version = '>= 3.0.0'
14+
15+
spec.metadata['homepage_uri'] = spec.homepage
16+
spec.metadata['source_code_uri'] = spec.homepage
17+
spec.license = 'MIT'
18+
19+
# Specify which files should be added to the gem when it is released.
20+
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
21+
gemspec = File.basename(__FILE__)
22+
spec.files = IO.popen(%w[git ls-files -z], chdir: __dir__, err: IO::NULL) do |ls|
23+
ls.readlines("\x0", chomp: true).reject do |f|
24+
(f == gemspec) ||
25+
f.start_with?(*%w[bin/ test/ spec/ features/ .git .github appveyor Gemfile])
26+
end
27+
end
28+
spec.bindir = 'exe'
29+
spec.executables = spec.files.grep(%r{\A#{spec.bindir}/}) { |f| File.basename(f) }
30+
spec.require_paths = ['lib']
31+
32+
# Uncomment to register a new dependency of your gem
33+
spec.add_dependency 'oauth2', '~> 2'
34+
spec.add_dependency 'webrick', '~> 1.9'
35+
spec.add_dependency 'thor', '~> 1.3'
36+
37+
spec.add_development_dependency 'rake', '~> 13'
38+
39+
# For more information and examples about making a new gem, check out our
40+
# guide at: https://bundler.io/guides/creating_gem.html
41+
end

lib/freeagent.rb

+172
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
require 'oauth2'
2+
require 'webrick'
3+
4+
FREEAGENT_APP_ID = ENV['FREEAGENT_APP_ID']
5+
FREEAGENT_APP_SECRET = ENV['FREEAGENT_APP_SECRET']
6+
7+
TOKEN_FILE = './.token.yml'
8+
9+
module Freeagent
10+
class API
11+
def initialize
12+
if FREEAGENT_APP_ID.nil? || FREEAGENT_APP_ID.empty?
13+
raise ArgumentError, 'FREEAGENT_APP_ID is unset'
14+
end
15+
if FREEAGENT_APP_SECRET.nil? || FREEAGENT_APP_SECRET.empty?
16+
raise ArgumentError, 'FREEAGENT_APP_SECRET is unset'
17+
end
18+
19+
@token = reload || authorize
20+
File.write TOKEN_FILE, @token.to_hash.to_hash.to_yaml
21+
end
22+
23+
private
24+
def reload
25+
if File.exist? TOKEN_FILE
26+
OAuth2::AccessToken.from_hash(client, YAML.unsafe_load_file(TOKEN_FILE)).refresh
27+
end
28+
rescue OAuth2::Error
29+
nil
30+
end
31+
32+
def client
33+
@client ||= OAuth2::Client.new(FREEAGENT_APP_ID, FREEAGENT_APP_SECRET,
34+
site: 'https://api.freeagent.com/v2/',
35+
authorize_url: 'approve_app',
36+
token_url: 'token_endpoint'
37+
)
38+
end
39+
40+
def authorize
41+
receiver = WEBrick::HTTPServer.new(Port: 0)
42+
receiver_url = "http://localhost:#{receiver.config[:Port]}/"
43+
url = client.auth_code.authorize_url(redirect_uri: receiver_url)
44+
puts "Go and authorize at #{url}, I'm waiting..."
45+
46+
access_code = nil
47+
receiver.mount_proc '/' do |req, res|
48+
# TODO: parse redirect response...
49+
access_code = req.query['code']
50+
receiver.shutdown
51+
end
52+
53+
Signal.trap('INT') do
54+
receiver.shutdown
55+
end
56+
57+
receiver.start
58+
raise if access_code.nil?
59+
60+
client.auth_code.get_token(access_code, redirect_uri: receiver_url)
61+
end
62+
63+
def get *parts, **params
64+
relatives = parts.map(&:to_s).join('/')
65+
uri = URI.parse(relatives)
66+
puts "GET #{uri}"
67+
res = @token.get(uri, params: params, headers: {'Accept': 'application/json'})
68+
data = res.parsed
69+
if res.headers.include? 'Link'
70+
data._links = res.headers['Link'].split(", ").map do |link|
71+
url, rel = link.split('; rel=')
72+
[rel.gsub(/^'|'$/, ''), URI::parse(url.gsub(/^<|>$/, ''))]
73+
end.to_h
74+
end
75+
data
76+
rescue => err
77+
if err.response.status == 429
78+
retry_after = err.response.headers['retry-after'].to_i
79+
STDERR.puts "Rate limited; sleeping for #{retry_after}"
80+
sleep retry_after
81+
retry
82+
end
83+
end
84+
85+
def get_pages *path, **params
86+
Enumerator.new do |yielder|
87+
loop do
88+
res = get(*path, **{per_page: 100}.update(params))
89+
yielder << res
90+
break if res._links.nil? || res._links.next.nil?
91+
params = URI::decode_www_form(res._links.next.query).to_h
92+
end
93+
end
94+
end
95+
96+
def post *parts, **params
97+
data = parts.pop
98+
relatives = parts.map(&:to_s).join('/')
99+
uri = URI.parse(relatives)
100+
puts "POST #{uri}"
101+
body = data.to_json
102+
@token.post(uri, body: body, params: params, headers: {'Content-Type': 'application/json', 'Accept': 'application/json'}).parsed
103+
end
104+
105+
def delete *parts, **params
106+
relatives = parts.map(&:to_s).join('/')
107+
uri = URI.parse(relatives)
108+
puts "DELETE #{uri}"
109+
@token.delete(uri, params: params, headers: {'Accept': 'application/json'})
110+
end
111+
112+
public
113+
def first_accounting_year_end
114+
Date.parse get('company').company.first_accounting_year_end
115+
end
116+
117+
def periods year
118+
get('payroll', year).periods
119+
end
120+
121+
def payslips year, period
122+
get('payroll', year, period).period.payslips
123+
end
124+
125+
def profiles year
126+
get('payroll_profiles', year).profiles
127+
end
128+
129+
def projects
130+
get_pages('projects').flat_map(&:projects)
131+
end
132+
133+
def tasks project
134+
get_pages('tasks', project: project.url).flat_map(&:tasks)
135+
end
136+
137+
def timeslips user, project, task, from, to
138+
get_pages('timeslips', user: user.url, project: project.url, task: task.url, from_date: from.to_s, to_date: to.to_s).flat_map(&:timeslips)
139+
end
140+
141+
def create_timeslip user, project, task, dated, hours
142+
post('timeslips', {
143+
'task' => task.url,
144+
'project' => project.url,
145+
'user' => user.url,
146+
'dated_on' => dated.to_s,
147+
'hours' => hours,
148+
})
149+
end
150+
151+
def batch_create_timeslips timeslips
152+
post('timeslips', {'timeslips' => timeslips})
153+
end
154+
155+
def delete_timeslip timeslip
156+
id = timeslip.url.split('/').last
157+
delete('timeslips', id)
158+
end
159+
160+
def users
161+
get_pages('users').flat_map(&:users)
162+
end
163+
164+
def user id
165+
get('users', id).user
166+
end
167+
168+
def profile year, user
169+
get('payroll_profiles', year, user: user)
170+
end
171+
end
172+
end

0 commit comments

Comments
 (0)