Program to Automatically Generate a Simple Invoice in Text Format

Python program to automatically generate simple text invoices with customer data, products, quantities, subtotal, VAT, and total saved as a formatted text file.

Brief Introduction

Program to Automatically Generate a Simple Invoice in Text Format (python)
DESCRIPTION:
This Python program allows you to create a simple invoice in text format starting from customer data, products, and quantities. It generates a .txt file with the details of items, prices, subtotal, VAT, and final total.

ADDITIONAL NOTES:
The program is simple and does not use databases or graphical interfaces. It is designed to generate textual invoices automatically and is easily extendable. The invoice number management is static but can be implemented with an increment system or reading from an external file.

EXPLANATIONS:
- The Product class represents an item with description and unit price.
- The Invoice class contains the invoice data, calculates subtotal, VAT, and total, and generates the formatted text.
- The generate_invoice_text method creates a string with the invoice formatted in a readable way.
- The save_invoice method writes the text to a .txt file named based on the invoice number.
- In main, example data are defined and an invoice is created, saved, and notified to the user.

Example Code: python

import datetime

class Prodotto:
    def __init__(self, descrizione, prezzo_unitario):
        self.descrizione = descrizione
        self.prezzo_unitario = prezzo_unitario

class Fattura:
    def __init__(self, numero, cliente, indirizzo, partita_iva, prodotti_quantita, iva_percentuale=22):
        self.numero = numero
        self.cliente = cliente
        self.indirizzo = indirizzo
        self.partita_iva = partita_iva
        self.prodotti_quantita = prodotti_quantita  # dict {Prodotto: quantita}
        self.iva_percentuale = iva_percentuale
        self.data = datetime.date.today()

    def calcola_subtotale(self):
        subtotale = 0
        for prodotto, quantita in self.prodotti_quantita.items():
            subtotale += prodotto.prezzo_unitario * quantita
        return subtotale

    def calcola_iva(self):
        return self.calcola_subtotale() * self.iva_percentuale / 100

    def calcola_totale(self):
        return self.calcola_subtotale() + self.calcola_iva()

    def genera_testo_fattura(self):
        righe = []
        righe.append(f"Invoice no. {self.numero}")
        righe.append(f"Date: {self.data.strftime('%d/%m/%Y')}")
        righe.append("")
        righe.append(f"Customer: {self.cliente}")
        righe.append(f"Address: {self.indirizzo}")
        righe.append(f"VAT Number: {self.partita_iva}")
        righe.append("")
        righe.append("Description           Quantity    Unit Price    Total")
        righe.append("------------------------------------------------------------")

        for prodotto, quantita in self.prodotti_quantita.items():
            totale_prodotto = prodotto.prezzo_unitario * quantita
            # Aligned formatting with spaces
            righe.append(f"{prodotto.descrizione:<20} {quantita:>8}    {prodotto.prezzo_unitario:>14.2f}    {totale_prodotto:>10.2f}")

        righe.append("------------------------------------------------------------")
        subtotale = self.calcola_subtotale()
        iva = self.calcola_iva()
        totale = self.calcola_totale()

        righe.append(f"Subtotal: {subtotale:.2f} EUR")
        righe.append(f"VAT ({self.iva_percentuale}%): {iva:.2f} EUR")
        righe.append(f"Total: {totale:.2f} EUR")

        return "\n".join(righe)

    def salva_fattura(self):
        nome_file = f"fattura_{self.numero}.txt"
        testo = self.genera_testo_fattura()
        with open(nome_file, "w", encoding="utf-8") as f:
            f.write(testo)
        return nome_file


def main():
    # Customer data
    cliente = "Mario Rossi"
    indirizzo = "Via Roma 10, 00100 Roma"
    partita_iva = "IT12345678901"

    # Available products
    prodotto1 = Prodotto("Blue Pen", 1.20)
    prodotto2 = Prodotto("A4 Notebook", 2.50)
    prodotto3 = Prodotto("30cm Ruler", 1.00)

    # Quantities purchased
    prodotti_quantita = {
        prodotto1: 10,
        prodotto2: 5,
        prodotto3: 2
    }

    # Invoice number (could be incremental)
    numero_fattura = 1

    fattura = Fattura(numero_fattura, cliente, indirizzo, partita_iva, prodotti_quantita)

    nome_file = fattura.salva_fattura()
    print(f"Invoice saved in file: {nome_file}")


if __name__ == "__main__":
    main()
×
×
×
Do you want to regenerate the answer?
×
Export chat
Choose export format
Generazione PDF in corso…
Allegati
×
You are about to close the chat and switch to the image generator. If you are not logged in, you will lose our chat. Do you confirm?
You are viewing a shared chat in temporary mode. It will not be saved.
×
Saved prompts
×
Private note
×
Label
×
Search all chats
×
Your insights
Analyzing…
×
AI Preferences
Assistant name 30
Answer length
AI model
Structured answers
Include examples
Use emojis
Guide me, don't solve Hints and questions instead of a ready answer
More settings →
×
Share this chat
Anyone opening this link can view the chat or add it to their profile as their own chat.
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
Shared chat
Someone shared a chat with you. Do you want to just view it or add it to your chats?
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
×

Saved messages

Loading...

×

Chat History

example-programs · CHAT HISTORY

Loading...

AI Preferences

×
  • BasicQuick and essential answers for study
  • MediumHigher quality for study and programming
  • AdvancedComplex reasoning and detailed analysis
Explain Steps

What do you need?

Python 3.x

DEPENDENCIES: no external libraries, only standard libraries (datetime)

CONFIG: the program saves the invoice file named 'fattura_<number>.txt' in the execution folder

INPUT: customer data (name, address, VAT number), list of products (description, unit price), quantities purchased

OUTPUT: text file with formatted invoice

Similar Topics

Program that asks for name and age and prints them formatted
Simple Python program that asks for user name and age, then prints a formatted message. Ideal for beginners learning input output and basic validation.
Program that asks for three numbers and prints the largest
Python program that prompts for three integers and prints the largest number using max function and input conversion for easy comparison.
Program that counts how many years are left until retirement
Simple Python program that calculates years left until retirement at 67, handling invalid inputs and suitable for beginners running in terminal.
Program that prints a simple numbered text menu
This Python program displays a simple numbered text menu, handles user input with validation, and prints messages based on choices in the console.
Program that repeats a message N times
Python program that repeats a user message N times with input validation for positive integers, demonstrating loops and basic input output in Python 3.
Program that asks for a sentence and counts the number of characters
Simple Python program that prompts for a sentence and counts the total number of characters including spaces and punctuation marks.
Program that asks for three grades and calculates the weighted average
Python program that prompts for three grades and weights, calculates the weighted average, validates inputs, and displays the result on the console.
Program that prints a countdown from 1 to
Simple Python program that prints a countdown from 1 to with one-second intervals using loops and time.sleep for beginners.