Class: FreshBooks::CLI::Commands
- Inherits:
-
Thor
- Object
- Thor
- FreshBooks::CLI::Commands
- Defined in:
- lib/freshbooks/cli.rb
Class Method Summary collapse
Instance Method Summary collapse
- #auth(subcommand = nil, *args) ⇒ Object
- #business ⇒ Object
- #cache(subcommand = "status") ⇒ Object
- #clients ⇒ Object
- #delete ⇒ Object
- #edit ⇒ Object
- #entries ⇒ Object
- #help(command = nil) ⇒ Object
- #log ⇒ Object
- #projects ⇒ Object
- #services ⇒ Object
- #status ⇒ Object
- #version ⇒ Object
Class Method Details
.exit_on_failure? ⇒ Boolean
12 13 14 |
# File 'lib/freshbooks/cli.rb', line 12 def self.exit_on_failure? true end |
Instance Method Details
#auth(subcommand = nil, *args) ⇒ Object
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 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 |
# File 'lib/freshbooks/cli.rb', line 65 def auth(subcommand = nil, *args) case subcommand when "setup" config = Auth.setup_config_from_args if [: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.(config) if [: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 [:format] == "json" puts JSON.pretty_generate({ "status" => "authenticated", "business" => biz }) else puts "Business auto-selected: #{biz["name"]} (#{biz["id"]})" end else if [: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 [: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 "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.(config) Auth.discover_business(tokens["access_token"], config) puts "\nReady to go! Try: fb entries" end end |
#business ⇒ Object
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 180 181 182 183 184 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 |
# File 'lib/freshbooks/cli.rb', line 146 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 [:select] Auth.select_business(config, [:select], businesses) selected = businesses.find { |m| m.dig("business", "id").to_s == [:select].to_s } biz = selected["business"] if [:format] == "json" puts JSON.pretty_generate(biz) else puts "Active business: #{biz["name"]} (#{biz["id"]})" end return end if .key?("select") && [: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 [: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
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 638 639 |
# File 'lib/freshbooks/cli.rb', line 587 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 [: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
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 |
# File 'lib/freshbooks/cli.rb', line 370 def clients Auth.valid_access_token clients = Spinner.spin("Fetching clients") { Api.fetch_clients } if clients.empty? puts "No clients found." return end if [: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
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 |
# File 'lib/freshbooks/cli.rb', line 491 def delete Auth.valid_access_token if [:id] entry_id = [:id] else abort("Missing required flag: --id") unless interactive? entry_id = pick_entry_interactive("delete") end unless [: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 [:format] == "json" puts JSON.pretty_generate({ "id" => entry_id, "deleted" => true }) else puts "Time entry #{entry_id} deleted." end end |
#edit ⇒ Object
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 |
# File 'lib/freshbooks/cli.rb', line 528 def edit Auth.valid_access_token if [:id] entry_id = [: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 = [:duration] || [:note] || [:date] || [:client] || [:project] || [:service] || [: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 [: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 [: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 [:format] == "json" puts JSON.pretty_generate(result) else puts "Time entry #{entry_id} updated." end end |
#entries ⇒ Object
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 332 333 334 335 336 337 338 339 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 |
# File 'lib/freshbooks/cli.rb', line 285 def entries Auth.valid_access_token today = Date.today if [:from] || [:to] first_day = [:from] ? Date.parse([:from]) : nil last_day = [:to] ? Date.parse([:to]) : nil else month = [:month] || today.month year = [: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 [:format] == "json" puts "[]" else puts "No time entries#{label ? " #{label}" : ""}." end return end if [: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
644 645 646 647 648 649 650 |
# File 'lib/freshbooks/cli.rb', line 644 def help(command = nil) if [:format] == "json" puts JSON.pretty_generate(help_json) return end super end |
#log ⇒ Object
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 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 |
# File 'lib/freshbooks/cli.rb', line 222 def log 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 [: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 [: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 [: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
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 |
# File 'lib/freshbooks/cli.rb', line 399 def projects Auth.valid_access_token maps = Spinner.spin("Resolving names") { Api.build_name_maps } projects = if [:client] client_id = maps[:clients].find { |_id, name| name.downcase == [:client].downcase }&.first abort("Client not found: #{[: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 [: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
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 |
# File 'lib/freshbooks/cli.rb', line 432 def services Auth.valid_access_token services = Spinner.spin("Fetching services") { Api.fetch_services } if services.empty? puts "No services found." return end if [: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
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 483 484 |
# File 'lib/freshbooks/cli.rb', line 457 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 [: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
58 59 60 |
# File 'lib/freshbooks/cli.rb', line 58 def version puts "freshbooks-cli #{VERSION}" end |