Skip to content

Commit

Permalink
Merge branch 'collection_experiment'
Browse files Browse the repository at this point in the history
  • Loading branch information
Kaya-Sem committed Jul 16, 2024
2 parents 9b1c2b5 + 7f324da commit 96b4f66
Show file tree
Hide file tree
Showing 6 changed files with 132 additions and 83 deletions.
Binary file modified src/backpack_cli.db
Binary file not shown.
23 changes: 21 additions & 2 deletions src/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,24 +128,43 @@ def create_item(name: str, weight: float, category: str, note: str):
print(f"\n[green]Item '{name}' added successfully![/green]\n")



def add_items_to_collection(collection_id: int, item_ids: List[int]):
conn = Connection(DATABASE)

added_count = 0
skipped_count = 0

for item_id in item_ids:
# Check if the item is already in the collection
conn.cursor.execute(
"INSERT INTO collection_items (collection_id, item_id) VALUES (?, ?)",
"SELECT COUNT(*) FROM collection_items WHERE collection_id = ? AND item_id = ?",
(collection_id, item_id),
)
exists = conn.cursor.fetchone()[0]

if exists:
skipped_count += 1
else:
conn.cursor.execute(
"INSERT INTO collection_items (collection_id, item_id) VALUES (?, ?)",
(collection_id, item_id),
)
added_count += 1

conn.commit()
conn.close()

print(f"\n[green]Items added to collection [italic]{collection_id}[/italic] successfully![/green]\n")
if added_count > 0:
print(f"\n[green]{added_count} item(s) added to collection [italic]{collection_id}[/italic] successfully![/green]")
if skipped_count > 0:
print(f"\n[yellow]{skipped_count} item(s) were already in the collection and were skipped.[/yellow]\n")


def delete_item(item_id: int):
conn = Connection(DATABASE)

# TODO: items should not be removed, rather 'archived'
# remove item from collections
conn.cursor.execute(
"DELETE FROM collection_items WHERE item_id = ?", (item_id,)
Expand Down
54 changes: 54 additions & 0 deletions src/export_commands.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import click

from database import get_collection


@click.command()
@click.argument('collection_id', type=int)
@click.argument('output_file', type=click.Path(writable=True))
@click.option('--pdf', is_flag=True, help='Creates a PDF checklist instead of a markdown')
def checklist(collection_id, output_file, pdf):
"""
Export a collection of items as a markdown checklist or PDF.
COLLECTION_ID: The ID of the collection to export.
OUTPUT_FILE: The file to write the checklist to.
--pdf: Creates a markdown file instead of PDF.
"""
try:
collection = get_collection(collection_id)
if not pdf:
markdown_content = generate_markdown_checklist(collection)
with open(output_file, 'w') as file:
file.write(markdown_content)
click.echo(f"Collection {collection_id} exported to {output_file} as markdown successfully.")
else:
# generate_pdf_checklist(collection, output_file)
click.echo(f"Collection {collection_id} exported to {output_file} as PDF successfully.")
except Exception as e:
click.echo(f"An error occurred: {e}")


def generate_markdown_checklist(collection):
"""
Generate a markdown checklist for a given collection.
"""
checklist = f"# {collection.name}\n"
checklist += f"{collection.description}\n\n"

for category, items_list in collection.items.items():
checklist += f"### {category}\n\n"
for item in items_list:
name = pad_string(item.name, 30)
checklist += f"- [ ] {name} ({item.note})\n"
checklist += f"\n"

return checklist


def pad_string(s, width):
return s + ' ' * (width - len(s))


if __name__ == "__main__":
pass
100 changes: 57 additions & 43 deletions src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
delete_collection,
)

# I am not totally sure what this rich console does or out it works.
from export_commands import checklist

console = Console()


Expand All @@ -27,18 +28,54 @@
def cli():
pass

# Register the checklist command
cli.add_command(checklist)


# NOTE: subcommands for 'add'
@cli.group()
def add():
"""Add items to collections"""
pass


@add.command()
@click.argument('item_ids', nargs=-1, type=int, required=False)
@click.option('--collection', 'collection_id', type=int, help='Collection ID to add items to')
@click.option('--interactive', is_flag=True, help='Interactive mode to select items and collections')
def item(item_ids, collection_id, interactive):
"""
Add items to a collection.
"""
if interactive:
handle_interactive_add()
else:
if not item_ids:
click.echo("You must provide at least one item ID.")
return

if not collection_id:
click.echo("You must provide a collection ID.")
return

try:
add_items_to_collection(collection_id, item_ids)
except Exception as e:
click.echo(f"An error occurred: {e}")



@cli.group()
def view():
"""View items, collections, etc."""
"""View items and collections."""
pass


# NOTE: subcommands for 'list'

@cli.group()
def list():
"""List items, collections, etc."""
"""List items and collections."""
pass


Expand Down Expand Up @@ -71,12 +108,12 @@ def collections():
# NOTE: subcommands for 'add'

@cli.group()
def add():
"""Add items, collections, etc."""
def create():
"""Create items and collections."""
pass


@add.command()
@create.command()
def item():
name = click.prompt("Enter the name of the item", type=str)
weight = click.prompt("Enter the weight of the item", type=float)
Expand All @@ -86,7 +123,7 @@ def item():
create_item(name, weight, category, note)


@add.command()
@create.command()
def collection():
name = click.prompt("Enter the name of the collection", type=str)
description = click.prompt("Enter the description of the collection", type=str)
Expand All @@ -98,8 +135,8 @@ def collection():

@view.command()
@click.argument("id", required=False, type=int)
def collection(col_id):
if col_id is None:
def collection(id):
if id is None:
collections = get_collections()
if collections:
print(f"\nAvailable collections [dim]({len(collections)})[/dim]:\n")
Expand All @@ -108,10 +145,10 @@ def collection(col_id):
else:
click.echo("No collections found in the database")

col_id = click.prompt("Enter the ID of the collection you want to view", type=int)
id = click.prompt("Enter the ID of the collection you want to view", type=int)

try:
collection = get_collection(col_id)
collection = get_collection(id)
view_collection(collection)
except ValueError as e:
click.echo(str(e))
Expand Down Expand Up @@ -144,8 +181,8 @@ def print_collection_items(items):

@view.command()
@click.argument("id", required=False, type=int)
def item(it_id):
if it_id is None:
def item(id):
if id is None:
items = get_items()
if items:
click.echo("Available items:")
Expand All @@ -155,10 +192,10 @@ def item(it_id):
click.echo("No items found in the database.")
sys.exit()

it_id = click.prompt("Enter the ID of the item you want to view", type=int)
id = click.prompt("Enter the ID of the item you want to view", type=int)

try:
item = get_item(it_id)
item = get_item(id)
print(
f"Item ID: {item.id}, Name: {item.name}, Weight: {item.weight}, Category: {item.category}"
)
Expand All @@ -170,14 +207,14 @@ def item(it_id):

@cli.group()
def delete():
"""Delete items, collections, etc."""
"""Delete items and collections."""
pass


@delete.command()
@click.argument("id", required=False, type=int)
def item(it_id):
if it_id is None:
def item(id):
if id is None:
items = get_items()
if items:
print(f"{len(items)} available items:")
Expand All @@ -187,10 +224,10 @@ def item(it_id):
print("No items found in the database.")
sys.exit()

it_id = click.prompt("Enter the ID of the item you want to delete", type=int)
id = click.prompt("Enter the ID of the item you want to delete", type=int)

try:
delete_item(it_id)
delete_item(id)
except ValueError as e:
click.echo(str(e))

Expand All @@ -216,28 +253,5 @@ def collection(collection_id):
click.echo(str(e))


# NOTE: subcommands for "collection"

@cli.group()
def collection():
"""Add and remove items to collections."""
pass


# TODO: implement improved "collection" logic
@collection.command("add-item")
@click.argument("collection_id", type=int)
@click.argument("item_ids", nargs=-1, type=int) # Accept multiple item_ids
def add_item_to_collection(collection_id, item_ids):
if not item_ids:
click.echo("You must provide at least one item ID.")
return

try:
add_items_to_collection(collection_id, item_ids)
except Exception as e:
click.echo(f"An error occurred: {e}")


if __name__ == "__main__":
cli()
38 changes: 0 additions & 38 deletions src/main.spec

This file was deleted.

Binary file added src/test2.pdf
Binary file not shown.

0 comments on commit 96b4f66

Please sign in to comment.