Digitale bierlijst

cli.py 5.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. import click
  2. from piket_client.model import (
  3. ServerStatus,
  4. NetworkError,
  5. Consumption,
  6. Person,
  7. Settlement,
  8. ConsumptionType,
  9. )
  10. from prettytable import PrettyTable
  11. @click.group()
  12. def cli():
  13. """Poke coco from the command line."""
  14. pass
  15. @cli.command()
  16. def status():
  17. """Show the current status of the server."""
  18. status = ServerStatus.is_server_running()
  19. if isinstance(status, NetworkError):
  20. print_error(f"Failed to get data from server, error {status.value}")
  21. return
  22. print_ok("Server is available.")
  23. open_consumptions = ServerStatus.unsettled_consumptions()
  24. if isinstance(open_consumptions, NetworkError):
  25. print_error(
  26. f"Failed to get unsettled consumptions, error {open_consumptions.value}"
  27. )
  28. return
  29. click.echo(f"There are {open_consumptions.amount} unsettled consumptions.")
  30. if open_consumptions.amount > 0:
  31. click.echo(f"First at: {open_consumptions.first_timestamp.strftime('%c')}")
  32. click.echo(f"Most recent at: {open_consumptions.last_timestamp.strftime('%c')}")
  33. @cli.group()
  34. def people():
  35. pass
  36. @people.command("list")
  37. @click.option("--active/--inactive", default=None)
  38. def list_people(active: bool) -> None:
  39. people = Person.get_all(active=active)
  40. if isinstance(people, NetworkError):
  41. print_error(f"Could not get people: {people.value}")
  42. return
  43. table = PrettyTable()
  44. table.field_names = ["ID", "Full name", "Display name", "Active"]
  45. table.align["ID"] = "r"
  46. table.align["Full name"] = "l"
  47. table.align["Display name"] = "l"
  48. table.sortby = "Full name"
  49. for p in people:
  50. table.add_row([p.person_id, p.full_name, p.display_name, p.active])
  51. print(table)
  52. @people.command("create")
  53. @click.option("--display-name", type=click.STRING)
  54. @click.argument("name", type=click.STRING)
  55. def create_person(name: str, display_name: str) -> None:
  56. """Create a person."""
  57. person = Person(full_name=name, display_name=display_name).create()
  58. if isinstance(person, NetworkError):
  59. print_error(f"Could not create Person: {person.value}")
  60. return
  61. print_ok(f'Created person "{name}" with ID {person.person_id}.')
  62. @cli.group()
  63. def settlements():
  64. pass
  65. @settlements.command("show")
  66. @click.argument("settlement_id", type=click.INT)
  67. def show_settlement(settlement_id: int) -> None:
  68. """Get and view the contents of a Settlement."""
  69. s = Settlement.get(settlement_id)
  70. if isinstance(s, NetworkError):
  71. print_error(f"Could not get Settlement: {s.value}")
  72. return
  73. output_settlement_info(s)
  74. @settlements.command("create")
  75. @click.argument("name")
  76. def create_settlement(name: str) -> None:
  77. """Create a new Settlement."""
  78. s = Settlement.create(name)
  79. if isinstance(s, NetworkError):
  80. print_error(f"Could not create Settlement: {s.value}")
  81. return
  82. output_settlement_info(s)
  83. def output_settlement_info(s: Settlement) -> None:
  84. click.echo(f'Settlement {s.settlement_id}, "{s.name}"')
  85. click.echo(f"Summary:")
  86. for key, value in s.consumption_summary.items():
  87. click.echo(f" - {value['count']} {value['name']} ({key})")
  88. ct_name_by_id = {key: value["name"] for key, value in s.consumption_summary.items()}
  89. table = PrettyTable()
  90. table.field_names = ["Name", *ct_name_by_id.values()]
  91. table.sortby = "Name"
  92. table.align = "r"
  93. table.align["Name"] = "l" # type: ignore
  94. zero_fields = {k: "" for k in ct_name_by_id.values()}
  95. for item in s.per_person_counts.values():
  96. r = {"Name": item["full_name"], **zero_fields}
  97. for key, value in item["counts"].items():
  98. r[ct_name_by_id[key]] = value
  99. table.add_row(r.values())
  100. print(table)
  101. @cli.group()
  102. def consumption_types():
  103. pass
  104. @consumption_types.command("list")
  105. def list_consumption_types() -> None:
  106. active = ConsumptionType.get_all(active=True)
  107. inactive = ConsumptionType.get_all(active=False)
  108. if isinstance(active, NetworkError) or isinstance(inactive, NetworkError):
  109. print_error("Could not get consumption types!")
  110. return
  111. table = PrettyTable()
  112. table.field_names = ["ID", "Name", "Active"]
  113. table.sortby = "ID"
  114. for ct in active + inactive:
  115. table.add_row([ct.consumption_type_id, ct.name, ct.active])
  116. print(table)
  117. @consumption_types.command("create")
  118. @click.argument("name")
  119. def create_consumption_type(name: str) -> None:
  120. ct = ConsumptionType(name=name).create()
  121. if not isinstance(ct, NetworkError):
  122. print_ok(f'Created consumption type "{name}" with ID {ct.consumption_type_id}.')
  123. @consumption_types.command("activate")
  124. @click.argument("consumption_type_id", type=click.INT)
  125. def activate_consumption_type(consumption_type_id: int) -> None:
  126. ct = ConsumptionType.get(consumption_type_id)
  127. if isinstance(ct, NetworkError):
  128. print_error(f"Could not get ConsumptionType: {ct.value}")
  129. return
  130. result = ct.set_active(True)
  131. if not isinstance(result, NetworkError):
  132. print_ok(
  133. f"Consumption type {ct.consumption_type_id} ({ct.name}) is now active."
  134. )
  135. @consumption_types.command("deactivate")
  136. @click.argument("consumption_type_id", type=click.INT)
  137. def deactivate_consumption_type(consumption_type_id: int) -> None:
  138. ct = ConsumptionType.get(consumption_type_id)
  139. if isinstance(ct, NetworkError):
  140. print_error(f"Could not get ConsumptionType: {ct.value}")
  141. return
  142. result = ct.set_active(False)
  143. if not isinstance(result, NetworkError):
  144. print_ok(
  145. f"Consumption type {ct.consumption_type_id} ({ct.name}) is now inactive."
  146. )
  147. def print_ok(msg: str) -> None:
  148. click.echo(click.style(msg, fg="green"))
  149. def print_error(msg: str) -> None:
  150. click.echo(click.style(msg, fg="red", bold=True), err=True)
  151. if __name__ == "__main__":
  152. cli()