|
| 1 | +import click |
| 2 | +import requests |
| 3 | + |
| 4 | +""" |
| 5 | +SCRIPT REQUIRES expense_api.py to run with univorn. |
| 6 | +Notes: |
| 7 | +expose_value=False --> option will not show up as an actual option when the user invokes the command. |
| 8 | +""" |
| 9 | + |
| 10 | +# base url for your fastapi server |
| 11 | +BASE_URL = "http://127.0.0.1:8000" |
| 12 | + |
| 13 | +@click.group(help="A group of commands for the expense tracker app.") |
| 14 | +@click.option("--warning", is_eager=True, help="WARNING: fastapi/expense_api.py needs to run on uvicorn server before running this script.", expose_value=False) |
| 15 | +def expense(): |
| 16 | + """ |
| 17 | + command group for managing expenses. |
| 18 | + """ |
| 19 | + pass |
| 20 | + |
| 21 | +# ========== |
| 22 | + |
| 23 | +@click.command() |
| 24 | +@click.option("-a", "--amount", type=float, required=True, help="Amount of the expense.") |
| 25 | +@click.option("-c", "--category", type=str, required=True, help="Category of the expense.") |
| 26 | +@click.option("-d", "--date", type=click.DateTime(formats=["%d-%m-%y"]), required=True, help="Date of the expense (format: DD-MM-YY).") |
| 27 | +@click.option("-n", "--note", type=str, help="Optional notes for the expense.") |
| 28 | +def add_expense(amount, category, date, note): |
| 29 | + """ |
| 30 | + add a new expense. |
| 31 | + """ |
| 32 | + # send a POST request to the server to add a new expense |
| 33 | + response = requests.post(f"{BASE_URL}/expenses/", json={ |
| 34 | + "amount": amount, |
| 35 | + "category": category, |
| 36 | + "date": date.date().isoformat(), |
| 37 | + "note": note or "" |
| 38 | + }) |
| 39 | + |
| 40 | + # check if the response status code indicates success (201 Created) |
| 41 | + if response.status_code == 201: |
| 42 | + result = response.json() |
| 43 | + # output the added expense details in a formatted manner |
| 44 | + click.echo("\nExpense Added Successfully:") |
| 45 | + click.echo("=" * 30) |
| 46 | + click.echo(f"ID : {result['id']}") |
| 47 | + click.echo(f"Amount : ${amount:.2f}") |
| 48 | + click.echo(f"Category: {category}") |
| 49 | + click.echo(f"Date : {date.date()}") |
| 50 | + click.echo(f"Note : {note or 'No notes provided'}") |
| 51 | + click.echo("=" * 30) |
| 52 | + # handle bad request errors (400 Bad Request) |
| 53 | + elif response.status_code == 400: |
| 54 | + click.echo(f"Bad request: {response.json().get('detail', 'Invalid data provided')}") |
| 55 | + else: |
| 56 | + # handle other errors |
| 57 | + click.echo(f"Error adding expense: {response.status_code} - {response.text}") |
| 58 | + |
| 59 | +# ========== |
| 60 | + |
| 61 | +@click.command() |
| 62 | +@click.option("-s", "--start-date", type=click.DateTime(formats=["%d-%m-%y"]), help="Start date for viewing expenses (format: DD-MM-YY).") |
| 63 | +@click.option("-e", "--end-date", type=click.DateTime(formats=["%d-%m-%y"]), help="End date for viewing expenses (format: DD-MM-YY).") |
| 64 | +def view_expenses(start_date, end_date): |
| 65 | + """ |
| 66 | + view expenses within a date range. |
| 67 | + """ |
| 68 | + # prepare query parameters for the GET request |
| 69 | + params = { |
| 70 | + "start_date": start_date.date().isoformat() if start_date else None, |
| 71 | + "end_date": end_date.date().isoformat() if end_date else None |
| 72 | + } |
| 73 | + |
| 74 | + # remove any parameters that are None to avoid sending unnecessary parameters |
| 75 | + params = {k: v for k, v in params.items() if v is not None} |
| 76 | + |
| 77 | + # send a GET request to the server to retrieve expenses |
| 78 | + response = requests.get(f"{BASE_URL}/expenses/", params=params) |
| 79 | + |
| 80 | + # check if the response status code indicates success (200 OK) |
| 81 | + if response.status_code == 200: |
| 82 | + expenses = response.json() |
| 83 | + if not expenses: |
| 84 | + click.echo("No expenses found for the given dates.") |
| 85 | + else: |
| 86 | + # output the retrieved expenses in a formatted manner |
| 87 | + click.echo("\nExpenses Found:") |
| 88 | + click.echo("=" * 30) |
| 89 | + for exp in expenses: |
| 90 | + click.echo(f"ID : {exp['id']}") |
| 91 | + click.echo(f"Amount : ${exp['amount']:.2f}") |
| 92 | + click.echo(f"Category: {exp['category']}") |
| 93 | + click.echo(f"Date : {exp['date']}") |
| 94 | + click.echo(f"Note : {exp['note'] or 'No notes provided'}") |
| 95 | + click.echo("-" * 30) |
| 96 | + |
| 97 | + # handle bad request errors (400 Bad Request) |
| 98 | + elif response.status_code == 400: |
| 99 | + click.echo(f"Bad request: {response.json().get('detail', 'Invalid date format')}") |
| 100 | + else: |
| 101 | + # handle other errors |
| 102 | + click.echo(f"Error retrieving expenses: {response.status_code} - {response.text}") |
| 103 | + |
| 104 | +# ========== |
| 105 | + |
| 106 | +@click.command() |
| 107 | +@click.option("--id", type=int, required=True, help="ID of the expense to delete.") |
| 108 | +def delete_expense(id): |
| 109 | + """ |
| 110 | + delete an expense by its id. |
| 111 | + """ |
| 112 | + # send a DELETE request to the server to remove the expense with the given ID |
| 113 | + response = requests.delete(f"{BASE_URL}/expenses/{id}") |
| 114 | + |
| 115 | + # check if the response status code indicates success (204 No Content) |
| 116 | + if response.status_code == 204: |
| 117 | + click.echo(f"Deleted expense with ID: {id}") |
| 118 | + |
| 119 | + # handle not found errors (404 Not Found) |
| 120 | + elif response.status_code == 404: |
| 121 | + click.echo(f"Expense with ID {id} not found.") |
| 122 | + else: |
| 123 | + # handle other errors |
| 124 | + click.echo(f"Error deleting expense: {response.status_code} - {response.text}") |
| 125 | + |
| 126 | +# ========== |
| 127 | + |
| 128 | +@click.command() |
| 129 | +@click.option("-s", "--start-date", type=click.DateTime(formats=["%d-%m-%y"]), help="Start date for the expense report (format: DD-MM-YY).") |
| 130 | +@click.option("-e", "--end-date", type=click.DateTime(formats=["%d-%m-%y"]), help="End date for the expense report (format: DD-MM-YY).") |
| 131 | +def generate_report(start_date, end_date): |
| 132 | + """ |
| 133 | + generate an expense report within a date range. |
| 134 | + """ |
| 135 | + # prepare query parameters for the GET request |
| 136 | + params = { |
| 137 | + "start_date": start_date.date().isoformat() if start_date else None, |
| 138 | + "end_date": end_date.date().isoformat() if end_date else None |
| 139 | + } |
| 140 | + |
| 141 | + # remove any parameters that are None to avoid sending unnecessary parameters |
| 142 | + params = {k: v for k, v in params.items() if v is not None} |
| 143 | + |
| 144 | + # send a GET request to the server to generate the expense report |
| 145 | + response = requests.get(f"{BASE_URL}/report/", params=params) |
| 146 | + |
| 147 | + # check if the response status code indicates success (200 OK) |
| 148 | + if response.status_code == 200: |
| 149 | + report = response.json() |
| 150 | + total_amount = report.get("total_amount", 0) |
| 151 | + click.echo(f"Total expenses from {start_date.date() if start_date else 'start'} to {end_date.date() if end_date else 'end'}: ${total_amount:.2f}") |
| 152 | + |
| 153 | + # handle bad request errors (400 Bad Request) |
| 154 | + elif response.status_code == 400: |
| 155 | + click.echo(f"Bad request: {response.json().get('detail', 'Invalid date format')}") |
| 156 | + else: |
| 157 | + # handle other errors |
| 158 | + click.echo(f"Error generating report: {response.status_code} - {response.text}") |
| 159 | + |
| 160 | +# ========== |
| 161 | + |
| 162 | +# add the sub-commands to the "expense" group |
| 163 | +expense.add_command(add_expense) |
| 164 | +expense.add_command(view_expenses) |
| 165 | +expense.add_command(delete_expense) |
| 166 | +expense.add_command(generate_report) |
| 167 | + |
| 168 | +# if this script runs directly, invoke the "expense" group |
| 169 | +if __name__ == "__main__": |
| 170 | + expense() |
0 commit comments