Skip to content
This repository has been archived by the owner on Nov 16, 2024. It is now read-only.

Cli #41

Merged
merged 3 commits into from
May 31, 2022
Merged

Cli #41

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 17 additions & 21 deletions npbc_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,19 +161,15 @@ def define_and_read_args(arguments: list[str]) -> ArgNamespace:
return main_parser.parse_args(arguments)


def status_print(status: bool, message: str) -> None:
def status_print(success: bool, message: str) -> None:
"""
print out a coloured status message using Colorama
- if the status is True, print in green (success)
- if the status is False, print in red (failure)
"""

if status:
print(f"{Fore.GREEN}", end="")
else:
print(f"{Fore.RED}", end="")

print(f"{Style.BRIGHT}{message}{Style.RESET_ALL}\n")
colour = Fore.GREEN if success else Fore.RED
print(f"{colour}{Style.BRIGHT}{message}{Style.RESET_ALL}\n")


def calculate(parsed_arguments: ArgNamespace, connection: Connection) -> None:
Expand Down Expand Up @@ -209,17 +205,17 @@ def calculate(parsed_arguments: ArgNamespace, connection: Connection) -> None:

# prepare a dictionary for undelivered strings
undelivered_strings = {
int(paper_id): []
for paper_id, _, _, _, _ in npbc_core.get_papers(connection)
int(paper_data.paper_id): []
for paper_data in npbc_core.get_papers(connection)
}

# get the undelivered strings from the database
try:
raw_undelivered_strings = npbc_core.get_undelivered_strings(connection, month=month, year=year)

# add them to the dictionary
for _, paper_id, _, _, string in raw_undelivered_strings:
undelivered_strings[paper_id].append(string)
for raw_undelivered_string in raw_undelivered_strings:
undelivered_strings[raw_undelivered_string.paper_id].append(raw_undelivered_string.string)

# ignore if none exist
except npbc_exceptions.StringNotExists:
Expand Down Expand Up @@ -440,12 +436,12 @@ def extract_costs_from_user_input(connection: Connection, paper_id: int | None,
status_print(False, f"Database error: {e}\nPlease report this to the developer.")
return

raw_data.sort(key=lambda paper: paper[2])
raw_data.sort(key=lambda paper: paper_id)

# extract the data from the database
delivered = [
bool(delivered)
for _, _, _, delivered, _ in raw_data
bool(paper_data.delivered)
for paper_data in raw_data
]

# if the number of days the paper is delivered is not equal to the number of costs, raise an error
Expand Down Expand Up @@ -582,8 +578,8 @@ def getpapers(parsed_arguments: ArgNamespace, connection: Connection) -> None:
headers.append('name')

names = list(set(
(paper_id, name)
for paper_id, name, _, _, _ in raw_data
(paper_data.paper_id, paper_data.name)
for paper_data in raw_data
))

# sort the names by paper ID and extract the names only
Expand All @@ -600,13 +596,13 @@ def getpapers(parsed_arguments: ArgNamespace, connection: Connection) -> None:
}

# for each paper, add the days to the dictionary
for paper_id, _, day_id, _, _ in raw_data:
days[paper_id][day_id] = {}
for paper_data in raw_data:
days[paper_data.paper_id][paper_data.day_id] = {}

# for each paper, add the costs and delivery data to the dictionary
for paper_id, _, day_id, day_delivery, day_cost in raw_data:
days[paper_id][day_id]['delivery'] = day_delivery
days[paper_id][day_id]['cost'] = day_cost
for paper_data in raw_data:
days[paper_data.paper_id][paper_data.day_id]['delivery'] = paper_data.delivered
days[paper_data.paper_id][paper_data.day_id]['cost'] = paper_data.cost

# if the user wants the delivery data, add it to the headers and the data to the list
if parsed_arguments.delivered:
Expand Down
20 changes: 16 additions & 4 deletions npbc_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

from calendar import day_name as weekday_names_iterable
from calendar import monthcalendar, monthrange
from collections import namedtuple
from collections.abc import Generator
from datetime import date, datetime, timedelta
from os import environ
Expand All @@ -34,6 +35,11 @@
## constant for names of weekdays
WEEKDAY_NAMES = tuple(weekday_names_iterable)

# create tuple classes for return data
Papers = namedtuple("Papers", ["paper_id", "name", "day_id", "delivered", "cost"])
UndeliveredStrings = namedtuple("UndeliveredStrings", ["string_id", "paper_id", "year", "month", "string"])


def create_and_setup_DB() -> Path:
"""ensure DB exists and it's set up with the schema"""

Expand Down Expand Up @@ -567,7 +573,7 @@ def delete_undelivered_string(
connection.execute(f"{delete_query} WHERE {conditions};", values)


def get_papers(connection: Connection) -> list[tuple[int, str, int, int, float]]:
def get_papers(connection: Connection) -> tuple[Papers]:
"""get all papers
- returns a list of tuples containing the following fields:
paper_id, paper_name, day_id, paper_delivered, paper_cost"""
Expand All @@ -583,7 +589,10 @@ def get_papers(connection: Connection) -> list[tuple[int, str, int, int, float]]

raw_data = connection.execute(query).fetchall()

return raw_data
return tuple(map(
lambda row: Papers(*row),
raw_data
))


def get_undelivered_strings(
Expand All @@ -593,7 +602,7 @@ def get_undelivered_strings(
year: int | None = None,
paper_id: int | None = None,
string: str | None = None
) -> list[tuple[int, int, int, int, str]]:
) -> tuple[UndeliveredStrings]:
"""get undelivered strings
- the user may specify as many as they want parameters
- available parameters: string_id, month, year, paper_id, string
Expand Down Expand Up @@ -647,7 +656,10 @@ def get_undelivered_strings(
if not data:
raise npbc_exceptions.StringNotExists("String with given parameters does not exist.")

return data
return tuple(map(
lambda row: UndeliveredStrings(*row),
data
))


def get_logged_data(
Expand Down
5 changes: 1 addition & 4 deletions test_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,9 @@ def test_db_creation():
DATABASE_PATH.unlink(missing_ok=True)
assert not DATABASE_PATH.exists()

try:
with raises(SystemExit):
npbc_cli.main([])

except SystemExit:
pass

assert DATABASE_PATH.exists()


Expand Down