Digitale bierlijst

cli.py 2.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. import click
  2. from piket_client.model import ServerStatus, NetworkError, Consumption, Settlement
  3. from prettytable import PrettyTable
  4. @click.group()
  5. def cli():
  6. """Poke coco from the command line."""
  7. pass
  8. @cli.command()
  9. def status():
  10. """Show the current status of the server."""
  11. status = ServerStatus.is_server_running()
  12. if isinstance(status, NetworkError):
  13. print_error(f"Failed to get data from server, error {status.value}")
  14. return
  15. print_ok("Server is available.")
  16. open_consumptions = ServerStatus.unsettled_consumptions()
  17. if isinstance(open_consumptions, NetworkError):
  18. print_error(
  19. f"Failed to get unsettled consumptions, error {open_consumptions.value}"
  20. )
  21. return
  22. click.echo(f"There are {open_consumptions.amount} unsettled consumptions.")
  23. if open_consumptions.amount > 0:
  24. click.echo(f"First at: {open_consumptions.first_timestamp.strftime('%c')}")
  25. click.echo(f"Most recent at: {open_consumptions.last_timestamp.strftime('%c')}")
  26. @cli.group()
  27. def people():
  28. pass
  29. @cli.group()
  30. def settlements():
  31. pass
  32. @settlements.command("show")
  33. @click.argument("settlement_id", type=click.INT)
  34. def show_settlement(settlement_id: int) -> None:
  35. """Get and view the contents of a Settlement."""
  36. s = Settlement.get(settlement_id)
  37. if isinstance(s, NetworkError):
  38. print_error(f"Could not get Settlement: {s.value}")
  39. return
  40. output_settlement_info(s)
  41. @settlements.command("create")
  42. @click.argument("name")
  43. def create_settlement(name: str) -> None:
  44. """Create a new Settlement."""
  45. s = Settlement.create(name)
  46. if isinstance(s, NetworkError):
  47. print_error(f"Could not create Settlement: {s.value}")
  48. return
  49. output_settlement_info(s)
  50. def output_settlement_info(s: Settlement) -> None:
  51. click.echo(f'Settlement {s.settlement_id}, "{s.name}"')
  52. click.echo(f"Summary:")
  53. for key, value in s.consumption_summary.items():
  54. click.echo(f" - {value['count']} {value['name']} ({key})")
  55. ct_name_by_id = {key: value["name"] for key, value in s.consumption_summary.items()}
  56. table = PrettyTable()
  57. table.field_names = ["Name", *ct_name_by_id.values()]
  58. table.sortby = "Name"
  59. table.align = "r"
  60. table.align["Name"] = "l" # type: ignore
  61. zero_fields = {k: "" for k in ct_name_by_id.values()}
  62. for item in s.per_person_counts.values():
  63. r = {"Name": item["full_name"], **zero_fields}
  64. for key, value in item["counts"].items():
  65. r[ct_name_by_id[key]] = value
  66. table.add_row(r.values())
  67. print(table)
  68. def print_ok(msg: str) -> None:
  69. click.echo(click.style(msg, fg="green"))
  70. def print_error(msg: str) -> None:
  71. click.echo(click.style(msg, fg="red", bold=True), err=True)
  72. if __name__ == "__main__":
  73. cli()