Class: FreshBooks::CLI::Commands

Inherits:
Thor
  • Object
show all
Defined in:
lib/freshbooks/cli.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.dispatch(command, given_args, given_opts, config) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/freshbooks/cli.rb', line 16

def self.dispatch(command, given_args, given_opts, config)
  requested_command = command || given_args.first

  super
rescue Thor::UnknownArgumentError => e
  if requested_command.to_s == "log"
    unknown_option = e.unknown.first
    raise Thor::InvocationError, log_parse_error_message(unknown_option, e.message)
  end

  raise
end

.exit_on_failure? ⇒ Boolean

Returns:

  • (Boolean)


12
13
14
# File 'lib/freshbooks/cli.rb', line 12

def self.exit_on_failure?
  true
end

.handle_argument_error(command, error, args, arity) ⇒ Object



29
30
31
32
33
34
35
36
# File 'lib/freshbooks/cli.rb', line 29

def self.handle_argument_error(command, error, args, arity)
  unknown_option = args.find { |arg| arg.to_s.start_with?("--") }
  if command.name == "log" && unknown_option
    raise Thor::InvocationError, log_parse_error_message(unknown_option, error.message)
  end

  super
end

.log_parse_error_message(option, fallback) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/freshbooks/cli.rb', line 38

def self.log_parse_error_message(option, fallback)
  suggestion = { "--hours" => "--duration", "--notes" => "--note" }[option]
  lines = ["Unknown option: #{option || fallback}"]
  lines << "Did you mean: #{suggestion}" if suggestion
  lines.concat([
    "",
    "fb log requires:",
    "  --duration HOURS",
    "  --note TEXT",
    "",
    "Example:",
    '  fb log --project "Sample Project" --service "Development" --duration 0.5 --note "Reviewed pull requests" --yes'
  ])
  lines.join("\n")
end

Instance Method Details

#auth(subcommand = nil, *args) ⇒ Object



103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/freshbooks/cli.rb', line 103

def auth(subcommand = nil, *args)
  case subcommand
  when "setup"
    config = Auth.setup_config_from_args
    if options[:format] == "json"
      puts JSON.pretty_generate({ "config_path" => Auth.config_path, "status" => "saved" })
    else
      puts "Config saved to #{Auth.config_path}"
    end

  when "url"
    config = Auth.load_config
    abort("No config found. Run: fb auth setup (set FRESHBOOKS_CLIENT_ID and FRESHBOOKS_CLIENT_SECRET first)") unless config
    url = Auth.authorize_url(config)
    if options[:format] == "json"
      puts JSON.pretty_generate({ "url" => url })
    else
      puts url
    end

  when "callback"
    config = Auth.load_config
    abort("No config found. Run: fb auth setup (set FRESHBOOKS_CLIENT_ID and FRESHBOOKS_CLIENT_SECRET first)") unless config
    redirect_url = args.first
    abort("Usage: fb auth callback REDIRECT_URL") unless redirect_url
    code = Auth.extract_code_from_url(redirect_url)
    abort("Could not find 'code' parameter in the URL.") unless code
    tokens = Auth.exchange_code(config, code)

    # Auto-discover businesses
    businesses = Auth.fetch_businesses(tokens["access_token"])
    if businesses.length == 1
      Auth.select_business(config, businesses.first.dig("business", "id"), businesses)
      biz = businesses.first["business"]
      if options[:format] == "json"
        puts JSON.pretty_generate({ "status" => "authenticated", "business" => biz })
      else
        puts "Business auto-selected: #{biz["name"]} (#{biz["id"]})"
      end
    else
      if options[:format] == "json"
        biz_list = businesses.map { |m| m["business"] }
        puts JSON.pretty_generate({ "status" => "authenticated", "businesses" => biz_list, "business_selected" => false })
      else
        puts "Authenticated! Multiple businesses found — select one with: fb business --select ID"
        businesses.each do |m|
          biz = m["business"]
          puts "  #{biz["name"]} (ID: #{biz["id"]})"
        end
      end
    end

  when "status"
    status_data = Auth.auth_status
    if options[:format] == "json"
      puts JSON.pretty_generate(status_data)
    else
      puts "Config: #{status_data["config_exists"] ? "found" : "missing"} (#{status_data["config_path"]})"
      puts "Tokens: #{status_data["tokens_exist"] ? "found" : "missing"}"
      if status_data["tokens_exist"]
        puts "Expired: #{status_data["tokens_expired"] ? "yes" : "no"}"
      end
      puts "Requires re-auth: #{status_data["requires_reauth"] ? "yes" : "no"}"
      puts "Business ID: #{status_data["business_id"] || "not set"}"
      puts "Account ID: #{status_data["account_id"] || "not set"}"
    end

  else
    unless interactive?
      abort("Use auth subcommands for non-interactive auth: fb auth setup, fb auth url, fb auth callback, fb auth status")
    end
    config = Auth.require_config
    tokens = Auth.authorize(config)
    Auth.discover_business(tokens["access_token"], config)
    puts "\nReady to go! Try: fb entries"
  end
end

#business ⇒ Object



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/freshbooks/cli.rb', line 185

def business
  Auth.valid_access_token
  config = Auth.load_config
  tokens = Auth.load_tokens
  businesses = Auth.fetch_businesses(tokens["access_token"])

  if businesses.empty?
    abort("No business memberships found on your FreshBooks account.")
  end

  if options[:select]
    Auth.select_business(config, options[:select], businesses)
    selected = businesses.find { |m| m.dig("business", "id").to_s == options[:select].to_s }
    biz = selected["business"]
    if options[:format] == "json"
      puts JSON.pretty_generate(biz)
    else
      puts "Active business: #{biz["name"]} (#{biz["id"]})"
    end
    return
  end

  if options.key?("select") && options[:select].nil?
    # --select with no value: interactive picker
    unless interactive?
      abort("Non-interactive: use --select ID. Available businesses:\n" +
        businesses.map { |m| "  #{m.dig("business", "name")} (ID: #{m.dig("business", "id")})" }.join("\n"))
    end

    puts "\nBusinesses:\n\n"
    businesses.each_with_index do |m, i|
      biz = m["business"]
      active = biz["id"].to_s == config["business_id"].to_s ? " [active]" : ""
      puts "  #{i + 1}. #{biz["name"]} (#{biz["id"]})#{active}"
    end

    print "\nSelect business (1-#{businesses.length}): "
    input = $stdin.gets&.strip
    abort("Cancelled.") if input.nil? || input.empty?

    idx = input.to_i - 1
    abort("Invalid selection.") if idx < 0 || idx >= businesses.length

    selected_biz = businesses[idx]
    Auth.select_business(config, selected_biz.dig("business", "id"), businesses)
    puts "Active business: #{selected_biz.dig("business", "name")} (#{selected_biz.dig("business", "id")})"
    return
  end

  # Default: list businesses
  if options[:format] == "json"
    biz_list = businesses.map do |m|
      biz = m["business"]
      biz.merge("active" => biz["id"].to_s == config["business_id"].to_s)
    end
    puts JSON.pretty_generate(biz_list)
  else
    businesses.each do |m|
      biz = m["business"]
      active = biz["id"].to_s == config["business_id"].to_s ? " [active]" : ""
      puts "#{biz["name"]} (ID: #{biz["id"]})#{active}"
    end
  end
end

#cache(subcommand = "status") ⇒ Object



642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
# File 'lib/freshbooks/cli.rb', line 642

def cache(subcommand = "status")
  case subcommand
  when "refresh"
    Auth.valid_access_token
    Spinner.spin("Refreshing cache") do
      Api.fetch_clients(force: true)
      Api.fetch_projects(force: true)
      Api.fetch_services(force: true)
      Api.build_name_maps
    end
    puts "Cache refreshed."
  when "clear"
    if File.exist?(Auth.cache_path)
      File.delete(Auth.cache_path)
      puts "Cache cleared."
    else
      puts "No cache file found."
    end
  when "status"
    cache = Auth.load_cache
    if options[:format] == "json"
      if cache["updated_at"]
        age = Time.now.to_i - cache["updated_at"]
        puts JSON.pretty_generate({
          "updated_at" => cache["updated_at"],
          "age_seconds" => age,
          "fresh" => age < 600,
          "clients" => (cache["clients_data"] || []).length,
          "projects" => (cache["projects_data"] || []).length,
          "services" => (cache["services"] || cache["services_data"] || {}).length
        })
      else
        puts JSON.pretty_generate({ "fresh" => false, "clients" => 0, "projects" => 0, "services" => 0 })
      end
      return
    end

    if cache["updated_at"]
      age = Time.now.to_i - cache["updated_at"]
      updated = Time.at(cache["updated_at"]).strftime("%Y-%m-%d %H:%M:%S")
      fresh = age < 600
      puts "Cache updated: #{updated}"
      puts "Age: #{age}s (#{fresh ? "fresh" : "stale"})"
      puts "Clients: #{(cache["clients_data"] || []).length}"
      puts "Projects: #{(cache["projects_data"] || []).length}"
      puts "Services: #{(cache["services"] || cache["services_data"] || {}).length}"
    else
      puts "No cache data."
    end
  else
    abort("Unknown cache subcommand: #{subcommand}. Use: refresh, clear, status")
  end
end

#clients ⇒ Object



425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
# File 'lib/freshbooks/cli.rb', line 425

def clients
  Auth.valid_access_token
  clients = Spinner.spin("Fetching clients") { Api.fetch_clients }

  if clients.empty?
    puts "No clients found."
    return
  end

  if options[:format] == "json"
    puts JSON.pretty_generate(clients)
    return
  end

  rows = clients.map do |c|
    name = c["organization"]
    name = "#{c["fname"]} #{c["lname"]}" if name.nil? || name.empty?
    email = c["email"] || "-"
    org = c["organization"] || "-"
    [name, email, org]
  end

  print_table(["Name", "Email", "Organization"], rows)
end

#delete ⇒ Object



546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
# File 'lib/freshbooks/cli.rb', line 546

def delete
  Auth.valid_access_token

  if options[:id]
    entry_id = options[:id]
  else
    abort("Missing required flag: --id") unless interactive?
    entry_id = pick_entry_interactive("delete")
  end

  unless options[:yes]
    print "Delete entry #{entry_id}? (y/N): "
    answer = $stdin.gets&.strip&.downcase
    abort("Cancelled.") unless answer == "y"
  end

  Spinner.spin("Deleting time entry") { Api.delete_time_entry(entry_id) }

  if options[:format] == "json"
    puts JSON.pretty_generate({ "id" => entry_id, "deleted" => true })
  else
    puts "Time entry #{entry_id} deleted."
  end
end

#edit ⇒ Object



583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
# File 'lib/freshbooks/cli.rb', line 583

def edit
  Auth.valid_access_token

  if options[:id]
    entry_id = options[:id]
  else
    abort("Missing required flag: --id") unless interactive?
    entry_id = pick_entry_interactive("edit")
  end

  entry = Spinner.spin("Fetching time entry") { Api.fetch_time_entry(entry_id) }
  abort("Time entry not found.") unless entry

  maps = Spinner.spin("Resolving names") { Api.build_name_maps }
  has_edit_flags = options[:duration] || options[:note] || options[:date] || options[:client] || options[:project] || options[:service] || options[:internal]
  scripted = has_edit_flags || !interactive?

  fields = build_edit_fields(entry, maps, scripted)

  current_client = maps[:clients][entry["client_id"].to_s] || entry["client_id"].to_s
  current_project = maps[:projects][entry["project_id"].to_s] || "-"
  current_hours = (entry["duration"].to_i / 3600.0).round(2)
  new_hours = fields["duration"] ? (fields["duration"].to_i / 3600.0).round(2) : current_hours
  summary_client = if fields.key?("client_id")
    fields["client_id"] ? maps[:clients][fields["client_id"].to_s] : "Internal"
  elsif fields["project_id"] != entry["project_id"]
    "Internal"
  else
    current_client
  end

  unless options[:format] == "json"
    puts "\n--- Edit Summary ---"
    puts "  Date:     #{fields["started_at"] || entry["started_at"]}"
    puts "  Client:   #{summary_client}"
    puts "  Project:  #{fields["project_id"] ? maps[:projects][fields["project_id"].to_s] : current_project}"
    puts "  Duration: #{new_hours}h"
    puts "  Note:     #{fields["note"] || entry["note"]}"
    puts "--------------------\n\n"
  end

  unless options[:yes]
    print "Save changes? (Y/n): "
    answer = $stdin.gets&.strip&.downcase
    abort("Cancelled.") if answer == "n"
  end

  result = Spinner.spin("Updating time entry") { Api.update_time_entry(entry_id, fields) }

  if options[:format] == "json"
    puts JSON.pretty_generate(result)
  else
    puts "Time entry #{entry_id} updated."
  end
end

#entries ⇒ Object



340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# File 'lib/freshbooks/cli.rb', line 340

def entries
  Auth.valid_access_token

  today = Date.today

  if options[:from] || options[:to]
    first_day = options[:from] ? Date.parse(options[:from]) : nil
    last_day = options[:to] ? Date.parse(options[:to]) : nil
  else
    month = options[:month] || today.month
    year = options[:year] || today.year
    first_day = Date.new(year, month, 1)
    last_day = Date.new(year, month, -1)
  end

  label = if first_day && last_day
    "#{first_day} to #{last_day}"
  elsif first_day
    "from #{first_day} onwards"
  elsif last_day
    "up to #{last_day}"
  end

  entries = Spinner.spin("Fetching time entries#{label ? " (#{label})" : ""}") do
    Api.fetch_time_entries(
      started_from: first_day&.to_s,
      started_to: last_day&.to_s
    )
  end

  if entries.empty?
    if options[:format] == "json"
      puts "[]"
    else
      puts "No time entries#{label ? " #{label}" : ""}."
    end
    return
  end

  if options[:format] == "json"
    puts JSON.pretty_generate(entries)
    return
  end

  maps = Spinner.spin("Resolving names") { Api.build_name_maps }
  entries.sort_by! { |e| e["started_at"] || "" }

  rows = entries.map do |e|
    date = (e["local_started_at"] || e["started_at"] || "?").slice(0, 10)
    client = display_client_name(e["client_id"], maps)
    project = maps[:projects][e["project_id"].to_s] || "-"
    service = maps[:services][e["service_id"].to_s] || "-"
    note = e["note"] || ""
    hours = (e["duration"].to_i / 3600.0).round(2)
    [e["id"].to_s, date, client, project, service, note, "#{hours}h"]
  end

  print_table(["ID", "Date", "Client", "Project", "Service", "Note", "Duration"], rows, wrap_col: 5)

  total = entries.sum { |e| e["duration"].to_i } / 3600.0

  # Per-client breakdown
  by_client = entries.group_by { |e| display_client_name(e["client_id"], maps) }
  if by_client.length > 1
    puts "\nBy client:"
    by_client.sort_by { |_, es| -es.sum { |e| e["duration"].to_i } }.each do |name, es|
      puts "  #{name}: #{(es.sum { |e| e["duration"].to_i } / 3600.0).round(2)}h"
    end
  end

  # Per-service breakdown
  by_service = entries.group_by { |e| maps[:services][e["service_id"].to_s] || "-" }
  if by_service.length > 1
    puts "\nBy service:"
    by_service.sort_by { |_, es| -es.sum { |e| e["duration"].to_i } }.each do |name, es|
      puts "  #{name}: #{(es.sum { |e| e["duration"].to_i } / 3600.0).round(2)}h"
    end
  end

  puts "\nTotal: #{total.round(2)}h"
end

#help(command = nil) ⇒ Object



699
700
701
702
703
704
705
# File 'lib/freshbooks/cli.rb', line 699

def help(command = nil)
  if options[:format] == "json"
    puts JSON.pretty_generate(help_json)
    return
  end
  super
end

#log ⇒ Object



272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
# File 'lib/freshbooks/cli.rb', line 272

def log
  if options[:help]
    self.class.command_help(shell, "log")
    return
  end

  Auth.valid_access_token
  defaults = Auth.load_defaults

  context = resolve_log_context(defaults)
  client = context[:client]
  project = context[:project]
  service = select_service(defaults, project)
  date = pick_date
  duration_hours = pick_duration
  note = pick_note

  client_name = client ? display_name(client) : "Internal"

  unless options[:format] == "json"
    puts "\n--- Time Entry Summary ---"
    puts "  Client:   #{client_name}"
    puts "  Project:  #{project ? project["title"] : "(none)"}"
    puts "  Service:  #{service ? service["name"] : "(none)"}"
    puts "  Date:     #{date}"
    puts "  Duration: #{duration_hours}h"
    puts "  Note:     #{note}"
    puts "--------------------------\n\n"
  end

  unless options[:yes]
    print "Submit? (Y/n): "
    answer = $stdin.gets&.strip&.downcase
    abort("Cancelled.") if answer == "n"
  end

  entry = {
    "is_logged" => true,
    "duration" => (duration_hours * 3600).to_i,
    "note" => note,
    "started_at" => normalize_datetime(date)
  }
  entry["client_id"] = client["id"] if client
  entry["project_id"] = project["id"] if project
  entry["service_id"] = service["id"] if service

  result = Api.create_time_entry(entry)

  if options[:format] == "json"
    puts JSON.pretty_generate(result)
  else
    puts "Time entry created!"
  end

  new_defaults = {}
  new_defaults["client_id"] = client["id"] if client
  new_defaults["project_id"] = project["id"] if project
  new_defaults["service_id"] = service["id"] if service
  Auth.save_defaults(new_defaults)
end

#projects ⇒ Object



454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
# File 'lib/freshbooks/cli.rb', line 454

def projects
  Auth.valid_access_token
  maps = Spinner.spin("Resolving names") { Api.build_name_maps }

  projects = if options[:client]
    client_id = maps[:clients].find { |_id, name| name.downcase == options[:client].downcase }&.first
    abort("Client not found: #{options[:client]}") unless client_id
    Spinner.spin("Fetching projects") { Api.fetch_projects_for_client(client_id) }
  else
    Spinner.spin("Fetching projects") { Api.fetch_projects }
  end

  if projects.empty?
    puts "No projects found."
    return
  end

  if options[:format] == "json"
    puts JSON.pretty_generate(projects)
    return
  end

  rows = projects.map do |p|
    client_name = display_project_client_name(p, maps)
    [p["title"], client_name, p["active"] ? "active" : "inactive"]
  end

  print_table(["Title", "Client", "Status"], rows)
end

#services ⇒ Object



487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
# File 'lib/freshbooks/cli.rb', line 487

def services
  Auth.valid_access_token
  services = Spinner.spin("Fetching services") { Api.fetch_services }

  if services.empty?
    puts "No services found."
    return
  end

  if options[:format] == "json"
    puts JSON.pretty_generate(services)
    return
  end

  rows = services.map do |s|
    billable = s["billable"] ? "yes" : "no"
    [s["name"], billable]
  end

  print_table(["Name", "Billable"], rows)
end

#status ⇒ Object



512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
# File 'lib/freshbooks/cli.rb', line 512

def status
  Auth.valid_access_token
  today = Date.today
  week_start = today - ((today.wday - 1) % 7)
  month_start = Date.new(today.year, today.month, 1)

  entries = Spinner.spin("Fetching time entries") do
    Api.fetch_time_entries(started_from: month_start.to_s, started_to: today.to_s)
  end
  maps = Spinner.spin("Resolving names") { Api.build_name_maps }

  today_entries = entries.select { |e| e["started_at"] == today.to_s }
  week_entries = entries.select { |e| d = e["started_at"]; d && d >= week_start.to_s && d <= today.to_s }
  month_entries = entries

  if options[:format] == "json"
    puts JSON.pretty_generate({
      "today" => build_status_data(today.to_s, today.to_s, today_entries, maps),
      "this_week" => build_status_data(week_start.to_s, today.to_s, week_entries, maps),
      "this_month" => build_status_data(month_start.to_s, today.to_s, month_entries, maps)
    })
    return
  end

  print_status_section("Today (#{today})", today_entries, maps)
  print_status_section("This Week (#{week_start} to #{today})", week_entries, maps)
  print_status_section("This Month (#{month_start} to #{today})", month_entries, maps)
end

#version ⇒ Object



96
97
98
# File 'lib/freshbooks/cli.rb', line 96

def version
  puts "freshbooks-cli #{VERSION}"
end