Files @ 8c86d58fda4b
Branch filter:

Location: ChaosStuff/stockcli/stockcli/cli.py

Dennis Fink
Remove uneeded type annotations
import json
import logging
import logging.config
from operator import itemgetter

import click
import requests
from rich.panel import Panel
from rich.table import Table

from .console import DEFAULT_PADDING, console, int_prompt, prompt
from .stock import (
    add_by_barcode,
    get_info_by_barcode,
    transfer_by_barcode,
    update_by_barcode,
)
from .utils import prepare_barcode

TASK_MAP = {
    "1": ("Transfer stock", transfer_by_barcode),
    "2": ("Add stock", add_by_barcode),
    "3": ("Update stock", update_by_barcode),
    "4": ("Get product info", get_info_by_barcode),
}


@click.command(context_settings={"help_option_names": ("-h", "--help", "-?")})
@click.option(
    "-c",
    "--config",
    "configfile",
    default="/etc/stockcli.json",
    type=click.File("r"),
    help="Config file to load",
)
@click.pass_context
def stockcli(ctx: click.Context, configfile: click.File) -> None:

    config = json.load(configfile)  # type: ignore
    logging.config.dictConfig(config["logging"])

    ctx.ensure_object(dict)
    ctx.obj["request_session"] = requests.Session()
    ctx.obj["request_session"].headers.update(
        {
            "accept": "application/json",
            "GROCY-API-KEY": config["grocy"]["apikey"],
        }
    )
    ctx.obj["base_url"] = f"{config['grocy']['url']}/api/"

    menu = Table.grid(padding=DEFAULT_PADDING)
    menu.add_column(justify="left", style="green", no_wrap=True)
    menu.add_column(justify="left", style="cyan", no_wrap=True)

    for task_id, task in sorted(TASK_MAP.items(), key=itemgetter(0)):
        menu.add_row(task_id, task[0])

    while True:
        click.clear()
        console.print(Panel(menu, title="[green bold]Menu[/green bold]"))
        choice = prompt.ask(
            "Enter a number to select a task", choices=list(TASK_MAP.keys())
        )
        logging.debug(f"User selected task: {choice}")
        selected_task = TASK_MAP[choice][1]

        rerun = True
        while rerun:
            barcode = prompt.ask("Please scan the barcode")
            barcode = prepare_barcode(barcode)

            try:
                selected_task(barcode)
            except (
                requests.Timeout,
                requests.ConnectionError,
                requests.HTTPError,
                requests.TooManyRedirects,
            ):
                rerun = False
                console.input("Continue")
            else:
                rerun = bool(
                    int_prompt.ask(
                        "Do the same with another product",
                        choices=["0", "1"],
                        default=0,
                    )
                )


if __name__ == "__main__":
    stockcli()