Digitale bierlijst

cli.py 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. click.echo(f"Settlement {settlement_id}, \"{s.name}\"")
  41. click.echo(f"Summary:")
  42. for key, value in s.consumption_summary.items():
  43. click.echo(f" - {value['count']} {value['name']} ({key})")
  44. ct_name_by_id = {key: value["name"] for key, value in s.consumption_summary.items()}
  45. table = PrettyTable()
  46. table.field_names = ["Name", *ct_name_by_id.values()]
  47. table.sortby = "Name"
  48. table.align = "r"
  49. table.align["Name"] = "l" # type: ignore
  50. zero_fields = {k: "" for k in ct_name_by_id.values()}
  51. for item in s.per_person_counts.values():
  52. r = {"Name": item["full_name"], **zero_fields}
  53. for key, value in item["counts"].items():
  54. r[ct_name_by_id[key]] = value
  55. table.add_row(r.values())
  56. print(table)
  57. def print_ok(msg: str) -> None:
  58. click.echo(click.style(msg, fg="green"))
  59. def print_error(msg: str) -> None:
  60. click.echo(click.style(msg, fg="red", bold=True), err=True)
  61. if __name__ == "__main__":
  62. cli()